-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathreplace_docx.py
More file actions
1148 lines (945 loc) · 36.1 KB
/
Copy pathreplace_docx.py
File metadata and controls
1148 lines (945 loc) · 36.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
# -*- coding: utf-8 -*-
import argparse
import csv
import json
import re
import shutil
import sys
from datetime import datetime
from pathlib import Path
from docx import Document
PLACEHOLDER_LITERALS = [
"XXX",
"XX公司",
"某某公司",
"某地区某公司",
"待补充",
"待填写",
"待完善",
"填写",
"【】",
"[]",
"[ ]",
"__",
"____",
"202X年",
"20XX年",
"xxxx",
"xxxxx",
"TBD",
"TODO",
]
PLACEHOLDER_REGEXES = [
(re.compile(r"\{\{[^{}]*\}\}"), "{{...}}"),
(re.compile(r"\$\{[^{}]*\}"), "${...}"),
]
UNSUPPORTED_RISKS = [
"脚注、尾注、批注、文本框、文档属性未自动处理,需人工复核。",
"复杂域代码、目录、水印、SmartArt、图片内文字未自动处理,需人工复核。",
]
CONTEXT_WINDOW = 18
MAX_SCAN_HITS_PER_TERM = 5
def build_char_map(paragraph):
chars = []
for run_idx, run in enumerate(paragraph.runs):
for char_idx, ch in enumerate(run.text):
chars.append({
"char": ch,
"run_idx": run_idx,
"char_idx": char_idx,
})
return chars
def normalize_spaces(text):
return text.replace("\r", " ").replace("\n", " ").strip()
def extract_context(text, start, end, window=CONTEXT_WINDOW):
prefix_start = max(0, start - window)
suffix_end = min(len(text), end + window)
snippet = text[prefix_start:suffix_end]
snippet = normalize_spaces(snippet)
if prefix_start > 0:
snippet = f"…{snippet}"
if suffix_end < len(text):
snippet = f"{snippet}…"
return snippet
def build_preview(full_text, match):
before = extract_context(full_text, match["start"], match["end"])
after_text = (
full_text[:match["start"]]
+ match["new"]
+ full_text[match["end"]:]
)
after = extract_context(
after_text,
match["start"],
match["start"] + len(match["new"]),
)
return {
"field": match["old"],
"before": before,
"after": after,
"location": match["location"],
}
def find_matches(full_text, replacements):
matches = []
index = 0
while index < len(full_text):
matched = None
for order, (old, new) in enumerate(replacements):
if full_text.startswith(old, index):
matched = {
"start": index,
"end": index + len(old),
"old": old,
"new": new,
"order": order,
}
break
if matched is None:
index += 1
continue
matches.append(matched)
index = matched["end"]
return matches
def apply_single_match(paragraph, chars, match):
affected = chars[match["start"]:match["end"]]
first_run_idx = affected[0]["run_idx"]
delete_map = {}
for item in affected:
delete_map.setdefault(item["run_idx"], set()).add(item["char_idx"])
for run_idx, run in enumerate(paragraph.runs):
if run_idx not in delete_map:
continue
new_text_parts = []
inserted = False
for char_idx, ch in enumerate(run.text):
if char_idx in delete_map[run_idx]:
if run_idx == first_run_idx and not inserted:
new_text_parts.append(match["new"])
inserted = True
else:
new_text_parts.append(ch)
run.text = "".join(new_text_parts)
def replace_text_in_paragraph(paragraph, replacements, stats, previews, location):
if not paragraph.runs:
return
chars = build_char_map(paragraph)
if not chars:
return
full_text = "".join(item["char"] for item in chars)
matches = find_matches(full_text, replacements)
if not matches:
return
for match in matches:
stats[match["old"]] = stats.get(match["old"], 0) + 1
if len(previews) < 2:
match["location"] = location
previews.append(build_preview(full_text, match))
for match in sorted(matches, key=lambda item: item["start"], reverse=True):
apply_single_match(paragraph, chars, match)
def replace_in_table(table, replacements, stats, previews, scope):
for row_idx, row in enumerate(table.rows, 1):
for col_idx, cell in enumerate(row.cells, 1):
for para_idx, paragraph in enumerate(cell.paragraphs, 1):
location = f"{scope} / 行 {row_idx} / 列 {col_idx} / 段落 {para_idx}"
replace_text_in_paragraph(
paragraph,
replacements,
stats,
previews,
location,
)
for nested_idx, nested_table in enumerate(cell.tables, 1):
nested_scope = (
f"{scope} / 行 {row_idx} / 列 {col_idx} / 嵌套表格 {nested_idx}"
)
replace_in_table(
nested_table,
replacements,
stats,
previews,
nested_scope,
)
def replace_in_container(container, replacements, stats, previews, scope):
for para_idx, paragraph in enumerate(container.paragraphs, 1):
location = f"{scope}段落 {para_idx}"
replace_text_in_paragraph(paragraph, replacements, stats, previews, location)
for table_idx, table in enumerate(container.tables, 1):
replace_in_table(table, replacements, stats, previews, f"{scope}表格 {table_idx}")
def collect_container_records(container, scope, records):
for para_idx, paragraph in enumerate(container.paragraphs, 1):
text = normalize_spaces(paragraph.text)
if text:
records.append({
"location": f"{scope}段落 {para_idx}",
"text": text,
})
for table_idx, table in enumerate(container.tables, 1):
collect_table_records(table, f"{scope}表格 {table_idx}", records)
def collect_table_records(table, scope, records):
for row_idx, row in enumerate(table.rows, 1):
for col_idx, cell in enumerate(row.cells, 1):
for para_idx, paragraph in enumerate(cell.paragraphs, 1):
text = normalize_spaces(paragraph.text)
if text:
records.append({
"location": f"{scope} / 行 {row_idx} / 列 {col_idx} / 段落 {para_idx}",
"text": text,
})
for nested_idx, nested_table in enumerate(cell.tables, 1):
collect_table_records(
nested_table,
f"{scope} / 行 {row_idx} / 列 {col_idx} / 嵌套表格 {nested_idx}",
records,
)
def collect_scan_records(doc):
records = []
collect_container_records(doc, "正文", records)
for section_idx, section in enumerate(doc.sections, 1):
collect_container_records(section.header, f"第 {section_idx} 节页眉", records)
collect_container_records(section.footer, f"第 {section_idx} 节页脚", records)
collect_container_records(
section.first_page_header,
f"第 {section_idx} 节首页页眉",
records,
)
collect_container_records(
section.first_page_footer,
f"第 {section_idx} 节首页页脚",
records,
)
collect_container_records(
section.even_page_header,
f"第 {section_idx} 节偶数页页眉",
records,
)
collect_container_records(
section.even_page_footer,
f"第 {section_idx} 节偶数页页脚",
records,
)
return records
def scan_records_for_terms(records, terms):
findings = []
seen = set()
for term in terms:
hit_count = 0
for record in records:
start = record["text"].find(term)
while start != -1:
if hit_count >= MAX_SCAN_HITS_PER_TERM:
break
end = start + len(term)
context = extract_context(record["text"], start, end)
key = (term, record["location"], context)
if key not in seen:
findings.append({
"term": term,
"location": record["location"],
"context": context,
})
seen.add(key)
hit_count += 1
start = record["text"].find(term, start + len(term))
return findings
def scan_records_for_placeholders(records):
findings = []
seen = set()
for record in records:
candidates = []
for literal in PLACEHOLDER_LITERALS:
start = record["text"].find(literal)
hit_count = 0
while start != -1:
if hit_count >= MAX_SCAN_HITS_PER_TERM:
break
candidates.append({
"term": literal,
"start": start,
"end": start + len(literal),
})
hit_count += 1
start = record["text"].find(literal, start + len(literal))
for pattern, label in PLACEHOLDER_REGEXES:
hit_count = 0
for match in pattern.finditer(record["text"]):
if hit_count >= MAX_SCAN_HITS_PER_TERM:
break
candidates.append({
"term": label,
"start": match.start(),
"end": match.end(),
})
hit_count += 1
accepted_ranges = []
for candidate in sorted(
candidates,
key=lambda item: (item["start"], -(item["end"] - item["start"])),
):
overlapped = False
for accepted in accepted_ranges:
if not (
candidate["end"] <= accepted["start"]
or candidate["start"] >= accepted["end"]
):
overlapped = True
break
if overlapped:
continue
accepted_ranges.append(candidate)
context = extract_context(
record["text"],
candidate["start"],
candidate["end"],
)
key = (candidate["term"], record["location"], context)
if key in seen:
continue
findings.append({
"term": candidate["term"],
"location": record["location"],
"context": context,
})
seen.add(key)
return findings
def make_backup(input_path, backup_dir=None):
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
backup_root = Path(backup_dir) if backup_dir else input_path.parent
backup_root.mkdir(parents=True, exist_ok=True)
backup_path = backup_root / f"{input_path.stem}.backup_{timestamp}{input_path.suffix}"
shutil.copy2(input_path, backup_path)
return backup_path
def replace_in_docx(input_path, output_path, replacements, create_backup=False, backup_dir=None):
input_path = Path(input_path)
output_path = Path(output_path)
if not input_path.exists():
raise FileNotFoundError(f"输入文件不存在:{input_path}")
if input_path.suffix.lower() != ".docx":
raise ValueError("仅支持 .docx 文件,不支持 .doc/.docm 或其他格式。")
if not replacements:
raise ValueError("替换规则为空。")
output_path.parent.mkdir(parents=True, exist_ok=True)
backup_path = None
if create_backup:
backup_path = make_backup(input_path, backup_dir=backup_dir)
doc = Document(str(input_path))
stats = {}
previews = []
replace_in_container(doc, replacements, stats, previews, "正文")
for section_idx, section in enumerate(doc.sections, 1):
replace_in_container(
section.header,
replacements,
stats,
previews,
f"第 {section_idx} 节页眉",
)
replace_in_container(
section.footer,
replacements,
stats,
previews,
f"第 {section_idx} 节页脚",
)
replace_in_container(
section.first_page_header,
replacements,
stats,
previews,
f"第 {section_idx} 节首页页眉",
)
replace_in_container(
section.first_page_footer,
replacements,
stats,
previews,
f"第 {section_idx} 节首页页脚",
)
replace_in_container(
section.even_page_header,
replacements,
stats,
previews,
f"第 {section_idx} 节偶数页页眉",
)
replace_in_container(
section.even_page_footer,
replacements,
stats,
previews,
f"第 {section_idx} 节偶数页页脚",
)
doc.save(str(output_path))
records = collect_scan_records(doc)
return {
"input_path": input_path,
"output_path": output_path,
"backup_path": backup_path,
"stats": stats,
"previews": previews,
"records": records,
}
def parse_replacements(args):
items = []
for item in args:
if "=" not in item:
raise ValueError(f"参数格式错误:{item},应为 旧词=新词")
old, new = item.split("=", 1)
items.append({
"old": old,
"new": new,
})
cleaned, warnings, errors = validate_replacements(items)
if warnings:
for warning in warnings:
print(f"警告:{warning}", file=sys.stderr)
if errors:
raise ValueError(";".join(errors))
return cleaned
def split_list_value(raw):
if raw is None:
return []
text = str(raw).strip()
if not text:
return []
parts = re.split(r"[,,;;、|]", text)
return [item.strip() for item in parts if item.strip()]
def normalize_replacements(raw):
if isinstance(raw, dict):
return [{"old": key, "new": value} for key, value in raw.items()]
if isinstance(raw, list):
items = []
for entry in raw:
if isinstance(entry, dict) and "old" in entry and "new" in entry:
items.append({"old": entry["old"], "new": entry["new"]})
elif isinstance(entry, (list, tuple)) and len(entry) == 2:
items.append({"old": entry[0], "new": entry[1]})
else:
raise ValueError(f"无法识别的 replacements 项:{entry}")
return items
raise ValueError("replacements 仅支持对象或数组格式。")
def validate_replacements(items):
cleaned = []
warnings = []
errors = []
seen = {}
for index, item in enumerate(items, 1):
old = "" if item.get("old") is None else str(item.get("old")).strip()
new = "" if item.get("new") is None else str(item.get("new"))
if not old:
errors.append(f"第 {index} 个替换项的旧值为空。")
continue
if old in seen:
if seen[old] != new:
errors.append(f"字段 {old} 存在冲突替换:{seen[old]} / {new}")
else:
warnings.append(f"字段 {old} 存在重复映射,已按同值去重。")
continue
seen[old] = new
cleaned.append((old, new))
if new == "":
warnings.append(f"字段 {old} 的新值为空,需人工确认是否允许删除。")
old_values = [old for old, _ in cleaned]
old_set = set(old_values)
for old, new in cleaned:
if new and new in old_set:
warnings.append(f"检测到链式替换风险:{old} -> {new}")
ordered_olds = sorted(old_values, key=len, reverse=True)
for index, old in enumerate(ordered_olds):
for other in ordered_olds[index + 1:]:
if other in old:
warnings.append(f"检测到包含关系:{old} / {other}")
cleaned.sort(key=lambda item: len(item[0]), reverse=True)
return cleaned, dedupe_messages(warnings), dedupe_messages(errors)
def dedupe_messages(messages):
seen = set()
unique = []
for message in messages:
if message in seen:
continue
seen.add(message)
unique.append(message)
return unique
def parse_arrow_line(line):
for separator in ("→", "->", "=>"):
if separator in line:
old, new = line.split(separator, 1)
return old.strip(), new.strip()
raise ValueError(f"无法识别的替换行:{line}")
def parse_text_manifest(text):
manifest = {"files": []}
current = None
for raw_line in text.splitlines():
line = raw_line.strip()
if not line:
continue
if line.startswith("原始文件:") or line.startswith("原始文件:"):
manifest["template"] = line.split(":", 1)[-1].split(":", 1)[-1].strip()
continue
if line.startswith("输出目录:") or line.startswith("输出目录:"):
manifest["output_dir"] = line.split(":", 1)[-1].split(":", 1)[-1].strip()
continue
if line.startswith("检查字段:") or line.startswith("检查字段:"):
manifest["check_fields"] = split_list_value(
line.split(":", 1)[-1].split(":", 1)[-1].strip()
)
continue
if line.startswith("文件:") or line.startswith("文件:"):
if current:
manifest["files"].append(current)
current = {
"output_filename": line.split(":", 1)[-1].split(":", 1)[-1].strip(),
"replacements": [],
}
continue
if line.startswith("重点检查:") or line.startswith("重点检查:"):
if current is None:
raise ValueError("重点检查字段必须写在某个“文件:”块内。")
current["check_fields"] = split_list_value(
line.split(":", 1)[-1].split(":", 1)[-1].strip()
)
continue
old, new = parse_arrow_line(line)
if current is None:
raise ValueError("替换映射必须写在某个“文件:”块内。")
current["replacements"].append({"old": old, "new": new})
if current:
manifest["files"].append(current)
return manifest
def parse_table_rows(rows):
files = []
for row in rows:
output_filename = (row.get("output_filename") or "").strip()
if not output_filename:
continue
item = {
"output_filename": output_filename,
"replacements": [],
}
for key, value in row.items():
if key in {"output_filename", "check_fields", "focus_fields"}:
continue
if key.startswith("old_"):
suffix = key[4:]
new_key = f"new_{suffix}"
old_value = (value or "").strip()
new_value = (row.get(new_key) or "").strip()
if old_value or new_value:
item["replacements"].append({
"old": old_value,
"new": new_value,
})
focus_value = row.get("check_fields") or row.get("focus_fields")
if focus_value:
item["check_fields"] = split_list_value(focus_value)
files.append(item)
return {"files": files}
def parse_markdown_table(text):
table_lines = []
for line in text.splitlines():
stripped = line.strip()
if stripped.startswith("|") and stripped.endswith("|"):
table_lines.append(stripped)
if len(table_lines) < 2:
raise ValueError("Markdown 表格格式不足。")
header = [cell.strip() for cell in table_lines[0].strip("|").split("|")]
rows = []
for line in table_lines[2:]:
values = [cell.strip() for cell in line.strip("|").split("|")]
row = {}
for index, key in enumerate(header):
row[key] = values[index] if index < len(values) else ""
rows.append(row)
return parse_table_rows(rows)
def parse_csv_manifest(manifest_path, delimiter=","):
with manifest_path.open("r", encoding="utf-8-sig", newline="") as handle:
reader = csv.DictReader(handle, delimiter=delimiter)
rows = list(reader)
return parse_table_rows(rows)
def load_manifest(manifest_path):
suffix = manifest_path.suffix.lower()
if suffix == ".json":
data = json.loads(manifest_path.read_text(encoding="utf-8"))
if isinstance(data, list):
return {"files": data}
if isinstance(data, dict):
return data
raise ValueError("JSON 清单必须是对象或数组。")
if suffix == ".csv":
return parse_csv_manifest(manifest_path, delimiter=",")
if suffix == ".tsv":
return parse_csv_manifest(manifest_path, delimiter="\t")
text = manifest_path.read_text(encoding="utf-8")
if suffix == ".md" and "|" in text and "output_filename" in text:
return parse_markdown_table(text)
return parse_text_manifest(text)
def resolve_path(base_dir, raw_value):
path = Path(raw_value)
if path.is_absolute():
return path
return (base_dir / path).resolve()
def pick_value(manifest, *keys):
for key in keys:
value = manifest.get(key)
if value:
return value
return None
def escape_cell(value):
text = "" if value is None else str(value)
text = text.replace("\r", " ").replace("\n", "<br>")
return text.replace("|", r"\|")
def markdown_table(headers, rows):
output = []
output.append("| " + " | ".join(headers) + " |")
output.append("|" + "|".join(["---"] * len(headers)) + "|")
if not rows:
empty = ["-" for _ in headers]
output.append("| " + " | ".join(empty) + " |")
return "\n".join(output)
for row in rows:
output.append(
"| " + " | ".join(escape_cell(row.get(header, "")) for header in headers) + " |"
)
return "\n".join(output)
def build_report(report_data):
lines = [
"# 批量 Word 替换检查报告",
"",
"## 一、输入信息",
"",
f"- 原始文件:{report_data['template_path']}",
f"- 输出目录:{report_data['output_dir']}",
f"- 输出文件数量:{report_data['file_count']}",
f"- 替换映射来源:{report_data['mapping_source']}",
f"- 执行时间:{report_data['executed_at']}",
"",
"## 二、文件生成结果",
"",
markdown_table(
["序号", "输出文件名", "是否生成", "备注"],
report_data["generation_rows"],
),
"",
"## 三、替换统计",
"",
markdown_table(
["输出文件名", "替换前", "替换后", "替换次数", "备注"],
report_data["replacement_rows"],
),
"",
"## 四、旧信息残留检查",
"",
markdown_table(
["输出文件名", "残留字段", "出现位置", "说明"],
report_data["residual_rows"],
),
"",
"## 五、通用占位符检查",
"",
markdown_table(
["输出文件名", "疑似占位符", "出现位置", "说明"],
report_data["placeholder_rows"],
),
"",
"## 六、替换实例预览",
"",
markdown_table(
["输出文件名", "字段", "替换前上下文", "替换后上下文"],
report_data["preview_rows"],
),
"",
"## 七、高风险文档提示",
"",
markdown_table(
["输出文件名", "风险项", "说明"],
report_data["risk_rows"],
),
"",
"## 八、异常与待确认项",
"",
markdown_table(
["输出文件名", "问题", "建议处理"],
report_data["issue_rows"],
),
"",
]
return "\n".join(lines)
def prepare_batch_item(item, global_check_fields):
output_filename = (item.get("output_filename") or item.get("filename") or "").strip()
if not output_filename:
raise ValueError("缺少 output_filename。")
replacements = normalize_replacements(item.get("replacements") or item.get("mapping") or {})
cleaned, warnings, errors = validate_replacements(replacements)
check_fields = split_list_value(item.get("check_fields") or item.get("focus_fields"))
if not check_fields:
check_fields = list(global_check_fields)
return {
"output_filename": output_filename,
"replacements": cleaned,
"check_fields": check_fields,
"warnings": warnings,
"errors": errors,
}
def run_batch(args):
manifest_path = Path(args.batch).resolve()
manifest = load_manifest(manifest_path)
template_value = args.template or pick_value(manifest, "template", "input_file", "source_file")
output_dir_value = args.output_dir or pick_value(
manifest,
"output_dir",
"output_directory",
)
if not template_value:
raise ValueError("批量模式缺少原始文件,请通过 manifest 或 --template 提供。")
if not output_dir_value:
raise ValueError("批量模式缺少输出目录,请通过 manifest 或 --output-dir 提供。")
template_path = resolve_path(manifest_path.parent, template_value)
output_dir = resolve_path(manifest_path.parent, output_dir_value)
output_dir.mkdir(parents=True, exist_ok=True)
files = manifest.get("files") or manifest.get("items") or []
if not files:
raise ValueError("批量模式未读取到任何文件任务。")
global_check_fields = split_list_value(manifest.get("check_fields"))
report_data = {
"template_path": template_path,
"output_dir": output_dir,
"file_count": len(files),
"mapping_source": manifest_path,
"executed_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"generation_rows": [],
"replacement_rows": [],
"residual_rows": [],
"placeholder_rows": [],
"preview_rows": [],
"risk_rows": [],
"issue_rows": [],
}
seen_outputs = set()
for index, raw_item in enumerate(files, 1):
output_filename = raw_item.get("output_filename") or raw_item.get("filename") or ""
try:
item = prepare_batch_item(raw_item, global_check_fields)
except Exception as exc:
report_data["generation_rows"].append({
"序号": index,
"输出文件名": output_filename or "-",
"是否生成": "否",
"备注": str(exc),
})
report_data["issue_rows"].append({
"输出文件名": output_filename or "-",
"问题": str(exc),
"建议处理": "检查替换清单格式后重试。",
})
continue
if item["output_filename"] in seen_outputs:
report_data["generation_rows"].append({
"序号": index,
"输出文件名": item["output_filename"],
"是否生成": "否",
"备注": "输出文件名重复。",
})
report_data["issue_rows"].append({
"输出文件名": item["output_filename"],
"问题": "输出文件名重复。",
"建议处理": "修改清单,确保每个输出文件名唯一。",
})
continue
seen_outputs.add(item["output_filename"])
for error in item["errors"]:
report_data["issue_rows"].append({
"输出文件名": item["output_filename"],
"问题": error,
"建议处理": "修正冲突后重新执行。",
})
if item["errors"]:
report_data["generation_rows"].append({
"序号": index,
"输出文件名": item["output_filename"],
"是否生成": "否",
"备注": "存在冲突替换,已停止处理。",
})
continue
output_path = output_dir / item["output_filename"]
if output_path.resolve() == template_path.resolve():
report_data["generation_rows"].append({
"序号": index,
"输出文件名": item["output_filename"],
"是否生成": "否",
"备注": "输出文件不能覆盖原始模板。",
})
report_data["issue_rows"].append({
"输出文件名": item["output_filename"],
"问题": "输出文件路径与原始模板相同。",
"建议处理": "修改输出目录或输出文件名。",
})
continue
overwrite_note = "覆盖已有文件。" if output_path.exists() else ""
try:
result = replace_in_docx(
template_path,
output_path,
item["replacements"],
create_backup=args.backup,
backup_dir=args.backup_dir,
)
except Exception as exc:
report_data["generation_rows"].append({
"序号": index,
"输出文件名": item["output_filename"],
"是否生成": "否",
"备注": str(exc),
})
report_data["issue_rows"].append({
"输出文件名": item["output_filename"],
"问题": str(exc),
"建议处理": "检查模板文件、输出目录和替换清单。",
})
continue
report_data["generation_rows"].append({
"序号": index,
"输出文件名": item["output_filename"],
"是否生成": "是",
"备注": overwrite_note or "生成成功。",
})
terms_to_check = []
for old, _ in item["replacements"]:
if old not in terms_to_check:
terms_to_check.append(old)
for field in item["check_fields"]:
if field not in terms_to_check:
terms_to_check.append(field)
residuals = scan_records_for_terms(result["records"], terms_to_check)
placeholders = scan_records_for_placeholders(result["records"])
for old, new in item["replacements"]:
count = result["stats"].get(old, 0)
note_parts = []
if count == 0:
note_parts.append("未命中")
report_data["replacement_rows"].append({
"输出文件名": item["output_filename"],
"替换前": old,
"替换后": new,