-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpackage_manager.py
More file actions
2490 lines (2055 loc) · 92.1 KB
/
package_manager.py
File metadata and controls
2490 lines (2055 loc) · 92.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
FedRAMP Package Manager
A unified tool for managing FedRAMP package documentation updates.
Workflow:
1. Place original documents in 'originals/' directory
2. Run 'analyze' to discover terms
3. Run 'preview' to review changes
4. Run 'apply' to create drafts with changes (originals preserved)
5. Run 'verify' to validate drafts and check completeness
Commands:
status - Show current configuration status
analyze - Scan documents and discover terms
preview - Preview replacements across all documents
apply - Apply replacements (originals -> drafts workflow)
verify - Re-analyze drafts to verify completeness
export - Export analysis to Excel/CSV
Usage:
python package_manager.py status
python package_manager.py analyze
python package_manager.py preview
python package_manager.py apply
python package_manager.py verify
python package_manager.py export --format excel
"""
import re
import json
import argparse
import shutil
from datetime import datetime
from pathlib import Path
from collections import defaultdict
from copy import deepcopy
from docx import Document
from docx.table import Table
from docx.text.paragraph import Paragraph
# Optional imports for export
try:
import pandas as pd
PANDAS_AVAILABLE = True
except ImportError:
PANDAS_AVAILABLE = False
try:
import openpyxl
EXCEL_AVAILABLE = True
except ImportError:
EXCEL_AVAILABLE = False
# =============================================================================
# CONFIGURATION
# =============================================================================
class Config:
"""Central configuration for the package manager."""
def __init__(self, base_dir: str = "."):
self.base_dir = Path(base_dir)
self.terms_dict_path = self.base_dir / "terms_dictionary.json"
self.replacements_path = self.base_dir / "replacements.json"
# Directory structure for workflow
self.originals_dir = self.base_dir / "originals" # Source documents (never modified)
self.drafts_dir = self.base_dir / "drafts" # Working copies with changes
self.output_dir = self.base_dir / "output" # Reports and exports
self.backup_dir = self.base_dir / "backups" # Historical backups
# Processing options
self.whole_word_matching = True
self.case_sensitive = True
# File patterns to process
self.include_patterns = ["*.docx"]
self.exclude_patterns = ["~$*", "*_BACKUP_*", "*_UPDATED_*"]
def get_originals(self) -> list:
"""Get all original documents to process."""
if not self.originals_dir.exists():
return []
docs = []
for pattern in self.include_patterns:
docs.extend(self.originals_dir.glob(pattern))
return self._filter_docs(docs)
def get_drafts(self) -> list:
"""Get all draft documents."""
if not self.drafts_dir.exists():
return []
docs = []
for pattern in self.include_patterns:
docs.extend(self.drafts_dir.glob(pattern))
return self._filter_docs(docs)
def get_documents(self) -> list:
"""Get all documents to process (checks originals first, then base dir)."""
# First check originals directory
if self.originals_dir.exists():
docs = self.get_originals()
if docs:
return docs
# Fall back to base directory for backward compatibility
docs = []
for pattern in self.include_patterns:
docs.extend(self.base_dir.glob(pattern))
return self._filter_docs(docs)
def _filter_docs(self, docs: list) -> list:
"""Filter documents based on exclusion patterns."""
filtered = []
for doc in docs:
excluded = False
for exc_pattern in self.exclude_patterns:
if doc.match(exc_pattern):
excluded = True
break
if not excluded:
filtered.append(doc)
return sorted(filtered)
def ensure_dirs(self):
"""Create output directories if needed."""
self.originals_dir.mkdir(exist_ok=True)
self.drafts_dir.mkdir(exist_ok=True)
self.output_dir.mkdir(exist_ok=True)
self.backup_dir.mkdir(exist_ok=True)
# =============================================================================
# TERMS DICTIONARY
# =============================================================================
class TermsDictionary:
"""Manages the master terms dictionary."""
def __init__(self, dict_path: Path):
self.dict_path = dict_path
self.data = self._load()
def _load(self) -> dict:
if not self.dict_path.exists():
return self._default_dict()
with open(self.dict_path, 'r') as f:
return json.load(f)
def _default_dict(self) -> dict:
return {
"known_technologies": {"terms": {}},
"known_teams": {"terms": {}},
"known_positions": {"terms": {}},
"discovery_patterns": {},
"exclusions": {"terms": []}
}
def get_all_known_terms(self) -> dict:
terms = {}
for term, info in self.data.get("known_technologies", {}).get("terms", {}).items():
terms[term] = {"type": "technology", "category": info.get("category", "unknown")}
for term, info in self.data.get("known_teams", {}).get("terms", {}).items():
terms[term] = {"type": "team"}
for term, info in self.data.get("known_positions", {}).get("terms", {}).items():
terms[term] = {"type": "position", "acronym": info.get("acronym")}
return terms
def get_exclusions(self) -> list:
return self.data.get("exclusions", {}).get("terms", [])
# =============================================================================
# REPLACEMENTS
# =============================================================================
class ReplacementsConfig:
"""Manages replacements configuration."""
def __init__(self, replacements_path: Path):
self.path = replacements_path
self.replacements = self._load()
def _load(self) -> dict:
if not self.path.exists():
return {}
with open(self.path, 'r') as f:
data = json.load(f)
replacements = data.get("replacements", {})
# Filter and process
filtered = {}
for k, v in replacements.items():
if k.startswith("=====") or v == "DELETE_THIS_LINE" or k.startswith("_"):
continue
if v in ("DELETE", "REMOVE"):
filtered[k] = ""
else:
filtered[k] = v
return filtered
def get_ordered(self) -> list:
"""Get replacements ordered by length (longest first)."""
return sorted(self.replacements.items(), key=lambda x: len(x[0]), reverse=True)
# =============================================================================
# TEXT QUALITY CHECKS
# =============================================================================
def find_repeated_words(text: str, min_word_length: int = 2) -> list:
"""
Find adjacent repeated words in text (e.g., 'Knox Knox').
Returns list of dicts with:
- word: the repeated word
- count: how many times it repeats consecutively
- context: surrounding text for reference
- position: character position in text
"""
if not text:
return []
# Pattern to find repeated words (case-insensitive)
# Matches: word followed by whitespace and the same word
pattern = re.compile(
r'\b(\w{' + str(min_word_length) + r',})\s+\1\b',
re.IGNORECASE
)
results = []
for match in pattern.finditer(text):
word = match.group(1)
position = match.start()
# Get context (50 chars before and after)
context_start = max(0, position - 30)
context_end = min(len(text), match.end() + 30)
context = text[context_start:context_end]
# Check for more than 2 repetitions (e.g., "Knox Knox Knox")
full_match = match.group(0)
extended_pattern = re.compile(
rf'\b({re.escape(word)}(?:\s+{re.escape(word)})+)\b',
re.IGNORECASE
)
extended_match = extended_pattern.search(text[position:position + 200])
if extended_match:
full_match = extended_match.group(1)
repetition_count = len(re.findall(rf'\b{re.escape(word)}\b', full_match, re.IGNORECASE))
else:
repetition_count = 2
results.append({
"word": word,
"count": repetition_count,
"context": context.strip(),
"position": position,
"full_match": full_match
})
return results
def fix_repeated_words(text: str, min_word_length: int = 2) -> tuple:
"""
Fix adjacent repeated words in text (e.g., 'Knox Knox' -> 'Knox').
Returns tuple of (fixed_text, list of fixes made).
Each fix is a dict with: word, original, position
"""
if not text:
return text, []
fixes = []
# Pattern to find repeated words (case-insensitive)
# This handles 2+ repetitions: "Knox Knox" or "Knox Knox Knox"
def replace_repeated(match):
word = match.group(1)
full_match = match.group(0)
fixes.append({
"word": word,
"original": full_match,
"position": match.start()
})
return word # Keep just one instance
# Pattern matches: word followed by one or more repetitions of whitespace + same word
pattern = re.compile(
r'\b(\w{' + str(min_word_length) + r',})(\s+\1)+\b',
re.IGNORECASE
)
fixed_text = pattern.sub(replace_repeated, text)
return fixed_text, fixes
def check_document_for_repeated_words(doc_path: Path, min_word_length: int = 2) -> dict:
"""
Check a document for repeated adjacent words.
Returns dict with:
- document: filename
- issues: list of repeated word findings with location info
- total_issues: count of issues found
"""
from docx import Document
doc = Document(str(doc_path))
issues = []
def check_paragraph(para_text: str, location: str):
repeated = find_repeated_words(para_text, min_word_length)
for r in repeated:
issues.append({
"location": location,
"word": r["word"],
"count": r["count"],
"context": r["context"],
"full_match": r["full_match"]
})
# Check body paragraphs
for para_idx, para in enumerate(doc.paragraphs):
if para.text.strip():
check_paragraph(para.text, f"Body, Paragraph {para_idx + 1}")
# Check tables
for table_idx, table in enumerate(doc.tables):
for row_idx, row in enumerate(table.rows):
for col_idx, cell in enumerate(row.cells):
for para in cell.paragraphs:
if para.text.strip():
location = f"Table {table_idx + 1}, Row {row_idx + 1}, Col {col_idx + 1}"
check_paragraph(para.text, location)
# Check headers/footers
for section_idx, section in enumerate(doc.sections):
for header in [section.header, section.first_page_header, section.even_page_header]:
if header:
for para in header.paragraphs:
if para.text.strip():
check_paragraph(para.text, f"Header (Section {section_idx + 1})")
for footer in [section.footer, section.first_page_footer, section.even_page_footer]:
if footer:
for para in footer.paragraphs:
if para.text.strip():
check_paragraph(para.text, f"Footer (Section {section_idx + 1})")
return {
"document": doc_path.name,
"issues": issues,
"total_issues": len(issues)
}
# =============================================================================
# DOCUMENT PROCESSOR
# =============================================================================
class DocumentProcessor:
"""Processes a single document for replacements."""
def __init__(self, doc_path: Path, config: Config):
self.doc_path = doc_path
self.config = config
self.changes = []
self.summary = defaultdict(int)
def extract_text(self, doc: Document) -> str:
"""Extract all text from document."""
all_text = []
for para in doc.paragraphs:
all_text.append(para.text)
for table in doc.tables:
for row in table.rows:
for cell in row.cells:
for para in cell.paragraphs:
all_text.append(para.text)
for section in doc.sections:
for header in [section.header, section.first_page_header, section.even_page_header]:
if header:
for para in header.paragraphs:
all_text.append(para.text)
for footer in [section.footer, section.first_page_footer, section.even_page_footer]:
if footer:
for para in footer.paragraphs:
all_text.append(para.text)
return "\n".join(all_text)
def create_pattern(self, text: str) -> re.Pattern:
"""Create regex pattern for matching."""
escaped = re.escape(text)
if self.config.whole_word_matching:
pattern = rf'\b{escaped}\b'
else:
pattern = escaped
flags = 0 if self.config.case_sensitive else re.IGNORECASE
return re.compile(pattern, flags)
def process_paragraph(self, paragraph: Paragraph, replacements: list,
location: str, preview_only: bool) -> bool:
"""Process a single paragraph."""
full_text = paragraph.text
if not full_text.strip():
return False
changes_made = False
# Calculate new text
new_full_text = full_text
for old_text, new_text in replacements:
pattern = self.create_pattern(old_text)
new_full_text = pattern.sub(new_text, new_full_text)
# Log changes
for old_text, new_text in replacements:
pattern = self.create_pattern(old_text)
if pattern.search(full_text):
for match in pattern.finditer(full_text):
context_start = max(0, match.start() - 50)
context_end = min(len(full_text), match.end() + 50)
context_before = full_text[context_start:context_end]
self.changes.append({
"document": self.doc_path.name,
"location": location,
"old_text": old_text,
"new_text": new_text if new_text else "[DELETED]",
"context_before": context_before,
"is_deletion": new_text == ""
})
key = f"{old_text} -> {new_text if new_text else '[DELETED]'}"
self.summary[key] += 1
changes_made = True
# Apply changes
if changes_made and not preview_only:
if paragraph.runs:
for i, run in enumerate(paragraph.runs):
run_text = run.text
for old_text, new_text in replacements:
pattern = self.create_pattern(old_text)
run_text = pattern.sub(new_text, run_text)
# Fix any repeated words created by replacements (e.g., "Knox Knox" -> "Knox")
run_text, _ = fix_repeated_words(run_text)
run.text = run_text
else:
# Fix repeated words in full text too
new_full_text, _ = fix_repeated_words(new_full_text)
paragraph.text = new_full_text
return changes_made
def process(self, replacements: list, preview_only: bool = True) -> dict:
"""Process the document with the given replacements."""
doc = Document(str(self.doc_path))
changes_made = False
# Body paragraphs
for para_idx, paragraph in enumerate(doc.paragraphs):
location = f"Body, Paragraph {para_idx + 1}"
if self.process_paragraph(paragraph, replacements, location, preview_only):
changes_made = True
# Tables
for table_idx, table in enumerate(doc.tables):
for row_idx, row in enumerate(table.rows):
for col_idx, cell in enumerate(row.cells):
for para_idx, paragraph in enumerate(cell.paragraphs):
location = f"Table {table_idx + 1}, Row {row_idx + 1}, Col {col_idx + 1}"
if self.process_paragraph(paragraph, replacements, location, preview_only):
changes_made = True
# Headers and footers
for section_idx, section in enumerate(doc.sections):
for header in [section.header, section.first_page_header, section.even_page_header]:
if header:
for para_idx, paragraph in enumerate(header.paragraphs):
location = f"Header (Section {section_idx + 1})"
if self.process_paragraph(paragraph, replacements, location, preview_only):
changes_made = True
for footer in [section.footer, section.first_page_footer, section.even_page_footer]:
if footer:
for para_idx, paragraph in enumerate(footer.paragraphs):
location = f"Footer (Section {section_idx + 1})"
if self.process_paragraph(paragraph, replacements, location, preview_only):
changes_made = True
return {
"document": self.doc_path.name,
"changes_made": changes_made,
"change_count": len(self.changes),
"changes": self.changes,
"summary": dict(self.summary),
"doc_object": doc if not preview_only else None
}
# =============================================================================
# BATCH PROCESSOR
# =============================================================================
class BatchProcessor:
"""Processes multiple documents in batch."""
def __init__(self, config: Config):
self.config = config
self.terms_dict = TermsDictionary(config.terms_dict_path)
self.replacements_config = ReplacementsConfig(config.replacements_path)
self.results = {}
self.timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
def process_all(self, preview_only: bool = True) -> dict:
"""Process all documents."""
documents = self.config.get_documents()
replacements = self.replacements_config.get_ordered()
if not documents:
print("No documents found to process.")
return {}
if not replacements:
print("No replacements defined in replacements.json")
return {}
print(f"\n{'PREVIEW MODE' if preview_only else 'APPLYING CHANGES'}")
print(f"Documents to process: {len(documents)}")
print(f"Replacements defined: {len(replacements)}")
print("-" * 50)
all_results = {
"timestamp": self.timestamp,
"mode": "preview" if preview_only else "apply",
"documents": {},
"total_changes": 0,
"summary": defaultdict(int)
}
for doc_path in documents:
print(f"\nProcessing: {doc_path.name}...")
processor = DocumentProcessor(doc_path, self.config)
result = processor.process(replacements, preview_only)
all_results["documents"][doc_path.name] = {
"change_count": result["change_count"],
"changes": result["changes"],
"summary": result["summary"]
}
all_results["total_changes"] += result["change_count"]
for key, count in result["summary"].items():
all_results["summary"][key] += count
# Save document if not preview
if not preview_only and result["doc_object"]:
self.config.ensure_dirs()
# Backup original
backup_path = self.config.backup_dir / f"{doc_path.stem}_BACKUP_{self.timestamp}{doc_path.suffix}"
shutil.copy2(doc_path, backup_path)
print(f" Backed up to: {backup_path.name}")
# Save updated
output_path = self.config.output_dir / f"{doc_path.stem}_UPDATED_{self.timestamp}{doc_path.suffix}"
result["doc_object"].save(str(output_path))
print(f" Saved to: {output_path.name}")
print(f" Changes: {result['change_count']}")
all_results["summary"] = dict(all_results["summary"])
self.results = all_results
return all_results
def generate_report(self, output_path: Path = None) -> str:
"""Generate a text report of the results."""
lines = []
lines.append("=" * 80)
lines.append(f"FEDRAMP PACKAGE {'PREVIEW' if self.results.get('mode') == 'preview' else 'UPDATE'} REPORT")
lines.append(f"Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
lines.append("=" * 80)
lines.append(f"\nTotal documents processed: {len(self.results.get('documents', {}))}")
lines.append(f"Total changes: {self.results.get('total_changes', 0)}")
# Summary by replacement
lines.append("\n" + "-" * 40)
lines.append("CHANGES BY REPLACEMENT")
lines.append("-" * 40)
for change, count in sorted(self.results.get("summary", {}).items(), key=lambda x: -x[1]):
lines.append(f" [{count:4d}x] {change}")
# Per-document details
lines.append("\n" + "-" * 40)
lines.append("PER-DOCUMENT DETAILS")
lines.append("-" * 40)
for doc_name, doc_data in self.results.get("documents", {}).items():
lines.append(f"\n{doc_name}:")
lines.append(f" Total changes: {doc_data['change_count']}")
if doc_data.get("summary"):
for change, count in sorted(doc_data["summary"].items(), key=lambda x: -x[1]):
lines.append(f" [{count:3d}x] {change}")
lines.append("\n" + "=" * 80)
lines.append("END OF REPORT")
lines.append("=" * 80)
report = "\n".join(lines)
if output_path:
with open(output_path, 'w') as f:
f.write(report)
return report
def generate_detailed_report(self, output_path: Path = None) -> str:
"""Generate a detailed text report showing each change with context."""
lines = []
lines.append("=" * 80)
lines.append(f"FEDRAMP PACKAGE DETAILED {'PREVIEW' if self.results.get('mode') == 'preview' else 'CHANGES'} REPORT")
lines.append(f"Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
lines.append("=" * 80)
lines.append(f"\nTotal documents processed: {len(self.results.get('documents', {}))}")
lines.append(f"Total changes: {self.results.get('total_changes', 0)}")
# Group changes by replacement type for easier review
for doc_name, doc_data in self.results.get("documents", {}).items():
lines.append("\n" + "=" * 80)
lines.append(f"DOCUMENT: {doc_name}")
lines.append(f"Total changes: {doc_data['change_count']}")
lines.append("=" * 80)
# Group changes by old_text -> new_text
changes_by_type = defaultdict(list)
for change in doc_data.get("changes", []):
key = f"{change['old_text']} -> {change['new_text']}"
changes_by_type[key].append(change)
# Sort by count (most frequent first)
sorted_types = sorted(changes_by_type.items(), key=lambda x: -len(x[1]))
for change_type, changes in sorted_types:
lines.append("\n" + "-" * 60)
lines.append(f"[{len(changes)}x] {change_type}")
lines.append("-" * 60)
# Show up to 5 examples with context
for i, change in enumerate(changes[:5]):
lines.append(f"\n Location: {change['location']}")
context = change.get('context_before', '')
if context:
# Highlight the term in context
lines.append(f" Context: \"{context}\"")
if change.get('is_deletion'):
lines.append(f" Action: DELETE")
if len(changes) > 5:
lines.append(f"\n ... and {len(changes) - 5} more instances")
lines.append("\n" + "=" * 80)
lines.append("END OF DETAILED REPORT")
lines.append("=" * 80)
report = "\n".join(lines)
if output_path:
with open(output_path, 'w') as f:
f.write(report)
return report
def export_to_excel(self, output_path: Path) -> bool:
"""Export results to Excel spreadsheet."""
if not PANDAS_AVAILABLE or not EXCEL_AVAILABLE:
print("Error: pandas and openpyxl required for Excel export")
print("Install with: pip install pandas openpyxl")
return False
# Create DataFrames
# 1. Summary sheet
summary_data = []
for change, count in self.results.get("summary", {}).items():
parts = change.split(" -> ")
summary_data.append({
"Original Term": parts[0] if len(parts) > 0 else "",
"Replacement": parts[1] if len(parts) > 1 else "",
"Total Count": count
})
summary_df = pd.DataFrame(summary_data)
# 2. Document summary sheet
doc_summary_data = []
for doc_name, doc_data in self.results.get("documents", {}).items():
doc_summary_data.append({
"Document": doc_name,
"Total Changes": doc_data["change_count"]
})
doc_summary_df = pd.DataFrame(doc_summary_data)
# 3. Detailed changes sheet
changes_data = []
for doc_name, doc_data in self.results.get("documents", {}).items():
for change in doc_data.get("changes", []):
changes_data.append({
"Document": doc_name,
"Location": change["location"],
"Original Term": change["old_text"],
"Replacement": change["new_text"],
"Is Deletion": change.get("is_deletion", False),
"Context": change.get("context_before", "")[:100]
})
changes_df = pd.DataFrame(changes_data)
# Write to Excel
with pd.ExcelWriter(str(output_path), engine='openpyxl') as writer:
summary_df.to_excel(writer, sheet_name='Summary', index=False)
doc_summary_df.to_excel(writer, sheet_name='Documents', index=False)
changes_df.to_excel(writer, sheet_name='All Changes', index=False)
return True
def export_to_csv(self, output_dir: Path) -> bool:
"""Export results to CSV files."""
if not PANDAS_AVAILABLE:
print("Error: pandas required for CSV export")
return False
output_dir.mkdir(exist_ok=True)
# Summary
summary_data = []
for change, count in self.results.get("summary", {}).items():
parts = change.split(" -> ")
summary_data.append({
"Original Term": parts[0] if len(parts) > 0 else "",
"Replacement": parts[1] if len(parts) > 1 else "",
"Total Count": count
})
pd.DataFrame(summary_data).to_csv(output_dir / "summary.csv", index=False)
# All changes
changes_data = []
for doc_name, doc_data in self.results.get("documents", {}).items():
for change in doc_data.get("changes", []):
changes_data.append({
"Document": doc_name,
"Location": change["location"],
"Original Term": change["old_text"],
"Replacement": change["new_text"],
"Is Deletion": change.get("is_deletion", False),
"Context": change.get("context_before", "")
})
pd.DataFrame(changes_data).to_csv(output_dir / "all_changes.csv", index=False)
return True
# =============================================================================
# ANALYZER (for discovery)
# =============================================================================
class PackageAnalyzer:
"""Analyzes documents for term discovery."""
def __init__(self, config: Config):
self.config = config
self.terms_dict = TermsDictionary(config.terms_dict_path)
self.results = {}
def analyze(self) -> dict:
"""Analyze all documents."""
documents = self.config.get_documents()
known_terms = self.terms_dict.get_all_known_terms()
print(f"\nAnalyzing {len(documents)} documents...")
results = {
"timestamp": datetime.now().isoformat(),
"documents_analyzed": len(documents),
"known_terms": defaultdict(lambda: {"documents": [], "total_count": 0}),
"per_document": {}
}
for doc_path in documents:
print(f" {doc_path.name}...")
try:
doc = Document(str(doc_path))
processor = DocumentProcessor(doc_path, self.config)
full_text = processor.extract_text(doc)
doc_terms = {}
for term, info in known_terms.items():
pattern = re.compile(rf'\b{re.escape(term)}\b')
matches = pattern.findall(full_text)
if matches:
doc_terms[term] = len(matches)
results["known_terms"][term]["documents"].append({
"file": doc_path.name,
"count": len(matches)
})
results["known_terms"][term]["total_count"] += len(matches)
results["known_terms"][term]["type"] = info.get("type")
results["per_document"][doc_path.name] = {
"terms_found": len(doc_terms),
"terms": doc_terms
}
except Exception as e:
print(f" Error: {e}")
results["per_document"][doc_path.name] = {"error": str(e)}
results["known_terms"] = dict(results["known_terms"])
self.results = results
return results
def export_to_excel(self, output_path: Path) -> bool:
"""Export analysis to Excel."""
if not PANDAS_AVAILABLE or not EXCEL_AVAILABLE:
return False
# Terms summary
terms_data = []
for term, data in self.results.get("known_terms", {}).items():
terms_data.append({
"Term": term,
"Type": data.get("type", "unknown"),
"Total Count": data["total_count"],
"Documents": len(data["documents"]),
"Document List": ", ".join([d["file"] for d in data["documents"]])
})
terms_df = pd.DataFrame(terms_data)
# Cross-document matrix
all_terms = list(self.results.get("known_terms", {}).keys())
all_docs = list(self.results.get("per_document", {}).keys())
matrix_data = []
for doc in all_docs:
row = {"Document": doc}
doc_terms = self.results["per_document"].get(doc, {}).get("terms", {})
for term in all_terms:
row[term] = doc_terms.get(term, 0)
matrix_data.append(row)
matrix_df = pd.DataFrame(matrix_data)
with pd.ExcelWriter(str(output_path), engine='openpyxl') as writer:
terms_df.to_excel(writer, sheet_name='Terms Summary', index=False)
matrix_df.to_excel(writer, sheet_name='Cross-Document Matrix', index=False)
return True
# =============================================================================
# FONT ANALYSIS AND STANDARDIZATION
# =============================================================================
def get_theme_fonts(document):
"""
Extract theme fonts (major/minor) from document's theme part.
Returns (major_font, minor_font) or (None, None) if not found.
"""
try:
from lxml import etree
pkg = document.part.package
for rel in pkg.main_document_part.rels.values():
if 'theme' in rel.reltype.lower():
theme_part = rel.target_part
theme_xml = theme_part.blob
root = etree.fromstring(theme_xml)
nsmap = {'a': 'http://schemas.openxmlformats.org/drawingml/2006/main'}
font_scheme = root.find('.//a:fontScheme', nsmap)
if font_scheme is not None:
major = font_scheme.find('.//a:majorFont/a:latin', nsmap)
minor = font_scheme.find('.//a:minorFont/a:latin', nsmap)
major_font = major.get('typeface') if major is not None else None
minor_font = minor.get('typeface') if minor is not None else None
return major_font, minor_font
except Exception:
pass
return None, None
# Cache for theme fonts per document (avoid re-parsing XML)
_theme_font_cache = {}
def get_effective_font(run, paragraph, document=None):
"""
Resolve the effective font name and size for a run by tracing the style hierarchy.
Returns (font_name, font_size_pt, is_name_inherited, is_size_inherited)
"""
# Start with run's direct font settings
font_name = run.font.name
font_size = run.font.size.pt if run.font.size else None
is_name_inherited = font_name is None
is_size_inherited = font_size is None
# If not set on run, try paragraph style
if font_name is None or font_size is None:
try:
para_style = paragraph.style
if para_style and para_style.font:
if font_name is None and para_style.font.name:
font_name = para_style.font.name
if font_size is None and para_style.font.size:
font_size = para_style.font.size.pt
# Try base style if still not found
if (font_name is None or font_size is None) and para_style:
base = para_style.base_style
while base and (font_name is None or font_size is None):
if base.font:
if font_name is None and base.font.name:
font_name = base.font.name
if font_size is None and base.font.size:
font_size = base.font.size.pt
base = base.base_style
except Exception:
pass # Style access can fail in some documents
# Try document's default style if still not found
if (font_name is None or font_size is None) and document:
try:
# Try the Normal style which is the default paragraph style
normal_style = document.styles.get_by_id('Normal', None)
if normal_style is None:
normal_style = document.styles['Normal']
if normal_style and normal_style.font:
if font_name is None and normal_style.font.name:
font_name = normal_style.font.name
if font_size is None and normal_style.font.size:
font_size = normal_style.font.size.pt
except Exception:
pass
# Try theme fonts if still not found
if font_name is None and document:
try:
doc_id = id(document)
if doc_id not in _theme_font_cache:
_theme_font_cache[doc_id] = get_theme_fonts(document)
major_font, minor_font = _theme_font_cache[doc_id]
# Use minor (body) font as default for most text
if minor_font:
font_name = minor_font
except Exception:
pass
# Default fallbacks if still not resolved
if font_name is None:
font_name = "Unknown"
if font_size is None:
font_size = None # Keep as None if truly unknown
return font_name, font_size, is_name_inherited, is_size_inherited
def format_font_combo(font_name, size, bold, italic, effective_name=None, effective_size=None) -> str:
"""Format a font combination for display."""
parts = []
# Font name - show effective name with (inherited) marker if applicable
if font_name:
parts.append(font_name)
elif effective_name:
parts.append(f"{effective_name} (inherited)")
else:
parts.append("[unknown]")
# Font size - show effective size with (inherited) marker if applicable
if size:
parts.append(f"{size}pt")
elif effective_size:
parts.append(f"{effective_size}pt (inherited)")
else:
parts.append("[unknown size]")