GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — python-hwpx/scripts/generate_openrate_corpus.py at main · VerifiedIdiot/python-hwpx

Expand file tree

/

generate_openrate_corpus.py

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
1674 lines (1525 loc) · 70 KB
/

generate_openrate_corpus.py

Copy path

File metadata and controls

1674 lines (1525 loc) · 70 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
# SPDX-License-Identifier: Apache-2.0
"""007-open-rate P2 / 010-corpus-publication P1 — FROZEN stratified corpora of
GENERATED .hwpx outputs + provenance manifests, for real-Hancom open-rate runs.
v1 (default mode, specs/007 P2): the published N=100 baseline. It is FROZEN —
this script now REFUSES to regenerate it while ``work/openrate-corpus/
manifest.json`` exists (builder buckets are not bit-stable, so a rerun would
silently invalidate the published sha256 freeze). ``--force-v1`` overrides.
v2 (``--v2``, specs/010 FR-002): ADDITIVE ONLY. Writes a NEW tree
``work/openrate-corpus-v2/`` + fresh manifest (``hwpx.openrate.frozen-
manifest.v2``) that references v1 by relative path + sha256 and NEVER touches
v1 bytes. New strata: form-fit-wide (full 25-input x 3-length sweep minus the
combos already frozen in v1), redline-wide (all v1 authored docs x tracked
insert/delete/replace round-robin, minus v1-covered combos), pii-merge
(synthetic machine-PII roster, masking DEFAULT-ON, raw probe values recorded
per record for the P3 0-leak sweep), authored-toc (native TABLEOFCONTENTS
field docs), reading-runformat (named run formatting + footnote docs,
footnotes preclassified expected-degrade), and shipped-artifacts (read-only
inventory of real demo/ + hwpx-skill outputs — referenced, never copied).
A combined v1+v2 manifest (``combined_manifest.json``) is emitted for the box
filelist step. ``--dry-run`` prints planned per-stratum counts, writes nothing.
Generation ONLY. No Hancom oracle, no commit, no scorecard. The composer
WITHHOLDS bytes when its static open-safety gate fails (server
``_save_generated_document`` raises on ``openSafety.ok == False``), so produced
may be < requested. We record, per bucket: requested / produced / the list of
REQUESTED-BUT-WITHHELD items (end-to-end FAILURES, not absent rows), and compute
``emit_rate = produced / requested``. Every produced file ALSO gets a STATIC
pre-filter result via ``validate_editor_open_safety`` — a structural pre-filter,
NOT the Hancom verdict (that comes later, on Windows).
Determinism: fixed seeds, sorted iteration, stable IDs, no wall-clock in IDs and
``generatedAt`` is left ``null`` (root stamps it).
v1 runs from the automation env (installed surface + editable python-hwpx):
cd python-hwpx-automation
uv run --with-editable ../python-hwpx python \\
../python-hwpx/scripts/generate_openrate_corpus.py
v2 needs only python-hwpx (no MCP surface):
cd python-hwpx
.venv/bin/python scripts/generate_openrate_corpus.py --v2 [--dry-run]
"""
from __future__ import annotations
import argparse
import hashlib
import json
import re
import sys
import traceback
import zipfile
from pathlib import Path
from typing import Any, Sequence
# --- repo geometry --------------------------------------------------------------
PYTHON_HWPX = Path(__file__).resolve().parent.parent # .../python-hwpx
HWPX_ROOT = PYTHON_HWPX.parent # .../hwpx
AUTOMATION_REPO = HWPX_ROOT / "python-hwpx-automation"
OUT_DIR = PYTHON_HWPX / "work" / "openrate-corpus"
OUT_DIR_V2 = PYTHON_HWPX / "work" / "openrate-corpus-v2"
SPEC_EVIDENCE = HWPX_ROOT / "specs" / "007-open-rate" / "evidence"
SPEC_EVIDENCE_V2 = HWPX_ROOT / "specs" / "010-corpus-publication" / "evidence"
M2_CORPUS = PYTHON_HWPX / "tests" / "fixtures" / "m2_corpus"
EXAM_FIXTURES = PYTHON_HWPX / "tests" / "fixtures" / "exam"
PUBLIC_CORPUS = PYTHON_HWPX / "work" / "public-document-corpus"
# shipped real artifacts (read-only inventory roots — NEVER written to)
SHIPPED_ROOTS: list[tuple[str, Path]] = [
("demo", HWPX_ROOT / "demo"),
("skill-examples", HWPX_ROOT / "hwpx-skill" / "examples" / "out"),
]
# --- imports (editable python-hwpx; the MCP surface is imported lazily in
# gen_authored so v2 mode / unit tests do not require hwpx_automation) -----------
from hwpx.document import HwpxDocument # noqa: E402
from hwpx.form_fit import FitPolicy # noqa: E402
from hwpx.form_fit.apply import fit_cell_text # noqa: E402
from hwpx.tools import toc_author # noqa: E402
from hwpx.tools.mail_merge import merge_template_rows # noqa: E402
from hwpx.tools.package_validator import validate_editor_open_safety # noqa: E402
# ================================================================================
# helpers
# ================================================================================
def sha256_file(path: Path) -> str:
h = hashlib.sha256()
with path.open("rb") as fh:
for chunk in iter(lambda: fh.read(1 << 16), b""):
h.update(chunk)
return h.hexdigest()
def static_open_safety_ok(path: Path) -> bool:
"""Structural pre-filter (necessary-not-sufficient). NOT the Hancom verdict."""
try:
return bool(validate_editor_open_safety(path).ok)
except Exception:
return False
def record(
*,
rec_id: str,
bucket: str,
seed: str,
output_path: Path | None,
produced: bool,
withheld_reason: str | None = None,
input_path: Path | None = None,
) -> dict[str, Any]:
out: dict[str, Any] = {
"id": rec_id,
"bucket": bucket,
"seed": seed,
"requested": True,
"produced": produced,
"output_path": str(output_path) if output_path else None,
"output_sha256": None,
"input_path": str(input_path) if input_path else None,
"input_sha256": (sha256_file(input_path) if input_path and input_path.exists() else None),
"withheld_reason": withheld_reason,
"static_open_safety_ok": None,
}
if produced and output_path and output_path.exists():
out["output_sha256"] = sha256_file(output_path)
out["static_open_safety_ok"] = static_open_safety_ok(output_path)
return out
# ================================================================================
# deterministic Korean banks (NO real persons / NO real orgs)
# ================================================================================
ORG_BANK = ["○○교육지원청", "△△군청", "□□시청", "◇◇구청", "☆☆교육청"]
ISSUER_BANK = ["○○교육지원청교육장", "△△군수", "□□시장", "◇◇구청장", "☆☆교육감"]
SUBJECT_BANK = [
"교육협력 사업 추진 협조 요청",
"안전점검 결과 통보",
"예산 집행 실적 제출 안내",
"행사 개최 협조 요청",
"시설 보수 계획 알림",
]
DATE_BANK = ["2026. 6. 27.", "2026. 7. 3.", "2026. 7. 10.", "2026. 7. 18.", "2026. 8. 4."]
DEPT_BANK = ["기획부", "운영부", "지원부", "총무부", "관리부", "협력부", "교육부", "안전부"]
# synthetic mail-merge roster (30 rows) — NO real persons
SURNAMES = ["김", "이", "박", "최", "정", "강", "조", "윤", "장", "임"]
GIVEN = ["민준", "서연", "도윤", "지우", "예준", "하은", "주원", "지민", "현우", "수아"]
def cycle(bank: list[str], idx: int) -> str:
return bank[idx % len(bank)]
# ================================================================================
# bucket 1 — authored (40) : 공문 15 / 보고서 15 / 가정통신문 10
# ================================================================================
def _table_block(rows_n: int) -> dict[str, Any]:
cols = [
{"key": "dept", "label": "부서"},
{"key": "goal", "label": "목표"},
{"key": "done", "label": "실적"},
{"key": "rate", "label": "달성률"},
]
rows = []
for r in range(rows_n):
goal = 10 + r * 2
done = goal - (r % 3)
rate = f"{round(done / goal * 100)}%"
rows.append({"dept": cycle(DEPT_BANK, r), "goal": str(goal), "done": str(done), "rate": rate})
return {"type": "table", "columns": cols, "rows": rows}
def authored_plans() -> list[tuple[str, str, dict[str, Any]]]:
"""Return (rec_id, seed, plan) parameter-sweep, deterministic & sorted."""
plans: list[tuple[str, str, dict[str, Any]]] = []
table_rows_cycle = [3, 5, 8]
# 공문 15 : vary org/subject/date + gyeolmun present/absent
for i in range(15):
seed = f"authored:gongmun:{i:02d}"
org = cycle(ORG_BANK, i)
subject = cycle(SUBJECT_BANK, i)
date = cycle(DATE_BANK, i)
has_gyeolmun = (i % 2 == 0)
plan: dict[str, Any] = {
"schemaVersion": "hwpx.document_plan.v1",
"title": f"2026학년도 {subject}",
"metadata": {"document_type": "공문"},
"blocks": [
{"type": "paragraph", "text": "수신 각급기관장"},
{"type": "heading", "level": 1, "text": "1. 관련"},
{"type": "paragraph", "text": f"가. {org} {subject} 계획({date})"},
{"type": "heading", "level": 1, "text": "2. 협조 요청 사항"},
{"type": "paragraph", "text": "가. 붙임 서식을 작성하여 회신하여 주시기 바랍니다."},
{"type": "paragraph", "text": "나. 원활한 추진을 위하여 적극 협조하여 주시기 바랍니다."},
{"type": "paragraph", "text": "붙임 관련 서식 1부. 끝."},
],
}
if has_gyeolmun:
plan["gyeolmun"] = {
"issuer": cycle(ISSUER_BANK, i),
"productionNumber": f"행정과-{1000 + i}",
"enforcementDate": date,
"disclosure": "공개" if i % 3 else "부분공개",
}
plans.append((f"authored-gongmun-{i:02d}", seed, plan))
# 보고서 15 : vary title/dept + table present/absent + row counts 3/5/8
for i in range(15):
seed = f"authored:bogoseo:{i:02d}"
org = cycle(ORG_BANK, i)
has_table = (i % 3 != 0) # ~2/3 with a table
rows_n = table_rows_cycle[i % 3]
blocks: list[dict[str, Any]] = [
{"type": "heading", "level": 1, "text": "1. 추진 개요"},
{"type": "paragraph", "text": f"가. {org} 2026년 상반기 추진 실적을 다음과 같이 보고합니다."},
{"type": "heading", "level": 2, "text": "가. 부서별 실적 요약"},
]
if has_table:
blocks.append(_table_block(rows_n))
else:
blocks.append({"type": "paragraph", "text": "가. 전 부서 목표 대비 95% 이상을 달성하였습니다."})
blocks += [
{"type": "heading", "level": 1, "text": "2. 향후 계획"},
{"type": "paragraph", "text": "가. 미달 부서에 대한 보완 계획을 수립하여 하반기에 반영한다."},
]
plan = {
"schemaVersion": "hwpx.document_plan.v1",
"title": f"부서별 추진실적 보고서 ({i + 1}호)",
"metadata": {"document_type": "보고서"},
"blocks": blocks,
}
plans.append((f"authored-bogoseo-{i:02d}", seed, plan))
# 가정통신문 10 : vary title/date
for i in range(10):
seed = f"authored:gajeong:{i:02d}"
date = cycle(DATE_BANK, i)
plan = {
"schemaVersion": "hwpx.document_plan.v1",
"title": f"생활 안내 가정통신문 ({i + 1}차)",
"metadata": {"document_type": "가정통신문"},
"blocks": [
{"type": "paragraph", "text": "학부모님, 안녕하십니까? 학교 교육활동에 보내주신 관심에 감사드립니다."},
{"type": "heading", "level": 1, "text": "1. 안내 기간"},
{"type": "paragraph", "text": f"가. {date}부터 적용됩니다."},
{"type": "heading", "level": 1, "text": "2. 생활 안내"},
{"type": "paragraph", "text": "가. 규칙적인 생활과 안전 수칙 준수에 유의하여 주시기 바랍니다."},
{"type": "paragraph", "text": "나. 가정에서 자녀의 독서와 휴식이 균형을 이루도록 지도 부탁드립니다."},
{"type": "paragraph", "text": date},
{"type": "paragraph", "text": "○○중학교장"},
],
}
plans.append((f"authored-gajeong-{i:02d}", seed, plan))
plans.sort(key=lambda t: t[0])
return plans
def gen_authored(out_dir: Path) -> tuple[list[dict[str, Any]], list[Path]]:
from hwpx_automation import server # lazy: v1-only dependency (installed MCP surface)
records: list[dict[str, Any]] = []
produced_paths: list[Path] = []
bucket_dir = out_dir / "authored"
bucket_dir.mkdir(parents=True, exist_ok=True)
for rec_id, seed, plan in authored_plans():
out_path = bucket_dir / f"{rec_id}.hwpx"
if out_path.exists():
out_path.unlink()
produced = False
withheld_reason: str | None = None
try:
res = server.create_document_from_plan(
str(out_path), plan, verify_render=False, verbosity="compact"
)
if res.get("created") and out_path.exists():
produced = True
else:
withheld_reason = (
res.get("error")
or res.get("handoff_status")
or "create_document_from_plan returned created=False"
)
except Exception as exc: # composer withheld bytes on open-safety gate fail
withheld_reason = f"{type(exc).__name__}: {exc}".strip()[:400]
rec = record(
rec_id=rec_id, bucket="authored", seed=seed,
output_path=out_path if produced else None,
produced=produced, withheld_reason=withheld_reason,
)
records.append(rec)
if produced:
produced_paths.append(out_path)
print(f"[authored] {rec_id} produced={produced} "
f"static_ok={rec['static_open_safety_ok']} {withheld_reason or ''}")
return records, produced_paths
# ================================================================================
# bucket 2 — mail-merge (30) : one 30-row synthetic roster over 1-2 templates
# ================================================================================
def build_merge_template(path: Path, kind: str) -> None:
"""A small placeholder template ({{name}} in a narrow table cell + body text)."""
doc = HwpxDocument.new()
if kind == "award":
doc.add_paragraph("상 장")
doc.add_paragraph("위 사람은 {{org}} 행사에서 우수한 성적을 거두었기에")
doc.add_paragraph("이 상장을 수여합니다. ({{date}})")
table = doc.add_paragraph("").add_table(1, 2)
table.cell(0, 0).set_text("성명")
table.cell(0, 1).set_size(width=5000)
table.cell(0, 1).set_text("{{name}}")
else: # notice
doc.add_paragraph("가정통신문 — {{org}}")
doc.add_paragraph("{{name}} 학부모님께 안내드립니다. ({{date}})")
table = doc.add_paragraph("").add_table(1, 2)
table.cell(0, 0).set_text("수신")
table.cell(0, 1).set_size(width=5000)
table.cell(0, 1).set_text("{{name}}")
doc.save_to_path(path)
def synthetic_roster() -> list[dict[str, str]]:
rows: list[dict[str, str]] = []
for r in range(30):
name = cycle(SURNAMES, r) + cycle(GIVEN, (r * 7) % len(GIVEN))
rows.append({
"name": name,
"org": cycle(ORG_BANK, r),
"date": cycle(DATE_BANK, r),
})
return rows
def gen_merge_template_rows(out_dir: Path) -> tuple[list[dict[str, Any]], list[Path]]:
records: list[dict[str, Any]] = []
produced_paths: list[Path] = []
bucket_dir = out_dir / "mail-merge"
bucket_dir.mkdir(parents=True, exist_ok=True)
tmpl_dir = bucket_dir / "_templates"
tmpl_dir.mkdir(parents=True, exist_ok=True)
roster = synthetic_roster()
# 2 templates; split the 30 rows 15/15 deterministically so each produced
# file is 1 .hwpx per row (effective-N caveat: clones share a template).
templates = [("award", roster[:15], 0), ("notice", roster[15:], 15)]
for kind, rows, base in templates:
tmpl_path = tmpl_dir / f"template_{kind}.hwpx"
build_merge_template(tmpl_path, kind)
tmpl_sha = sha256_file(tmpl_path)
report = merge_template_rows(
tmpl_path,
rows,
output_dir=bucket_dir / kind,
filename_pattern=f"mm-{kind}-{{index:02d}}.hwpx",
fit_policy=FitPolicy.keep(),
strict=False,
)
row_reports = {r["rowIndex"]: r for r in report["rows"]}
for local_idx in range(1, len(rows) + 1):
global_idx = base + local_idx
rec_id = f"mailmerge-{kind}-{global_idx:02d}"
seed = f"mailmerge:{kind}:row{global_idx:02d}"
rr = row_reports.get(local_idx, {})
produced = bool(rr.get("created"))
out_path = Path(rr["filename"]) if rr.get("filename") else None
withheld_reason = None
if not produced:
reasons = rr.get("reasons") or []
withheld_reason = (
",".join(reasons) if reasons
else "mail_merge did not create this row"
)
rec = record(
rec_id=rec_id, bucket="mail-merge", seed=seed,
output_path=out_path if produced else None,
produced=produced, withheld_reason=withheld_reason,
)
rec["input_path"] = str(tmpl_path)
rec["input_sha256"] = tmpl_sha
# surface fit/needs-review without dropping the produced file
if rr.get("reasons"):
rec["needs_review_reasons"] = rr["reasons"]
records.append(rec)
if produced and out_path:
produced_paths.append(out_path)
print(f"[mail-merge] {rec_id} produced={produced} "
f"static_ok={rec['static_open_safety_ok']} {withheld_reason or ''}")
return records, produced_paths
# ================================================================================
# bucket 3 — form-fit over REAL forms (20) : sweep value-length {short,med,overflow}
# ================================================================================
LENGTH_SWEEP = {
"short": "김민준",
"medium": "행정안전부 정책기획관실 협력담당",
"overflow": "아주아주아주아주아주아주아주아주아주아주아주긴값입니다정말로굉장히길어서칸을넘칩니다" * 2,
}
def _first_fillable_cell(doc: HwpxDocument):
"""Deterministic target: the first empty table cell (sorted document order)."""
for p in doc.sections[0].paragraphs:
for t in p.tables:
for row in t.rows:
for c in row.cells:
txt = "".join(
getattr(pp, "text", "") or "" for pp in getattr(c, "paragraphs", [])
)
if txt.strip() == "":
return c
return None
def form_fit_inputs() -> list[tuple[str, Path]]:
"""Sorted, deterministic input list: 3 m2 forms + open-safety-ok corpus."""
inputs: list[tuple[str, Path]] = []
for name in sorted(p.name for p in M2_CORPUS.glob("*.hwpx")):
inputs.append((f"m2:{Path(name).stem}", M2_CORPUS / name))
manifest = json.loads((PUBLIC_CORPUS / "manifest.json").read_text(encoding="utf-8"))
corpus_ok = [
e for e in manifest["entries"] if e.get("open_safety_ok")
]
corpus_ok.sort(key=lambda e: e["local_path"])
for e in corpus_ok:
lp = Path(e["local_path"])
inputs.append((f"corpus:{lp.stem}", lp))
return inputs
def gen_form_fit(out_dir: Path, target_n: int = 20) -> tuple[list[dict[str, Any]], list[Path]]:
records: list[dict[str, Any]] = []
produced_paths: list[Path] = []
bucket_dir = out_dir / "form-fit"
bucket_dir.mkdir(parents=True, exist_ok=True)
inputs = form_fit_inputs()
sweep_order = ["short", "medium", "overflow"]
emitted = 0
for tag, in_path in inputs:
if emitted >= target_n:
break
if not in_path.exists():
continue
for length in sweep_order:
if emitted >= target_n:
break
rec_id = f"formfit-{tag.replace(':', '_')}-{length}"
seed = f"formfit:{tag}:{length}"
out_path = bucket_dir / f"{rec_id}.hwpx"
if out_path.exists():
out_path.unlink()
value = LENGTH_SWEEP[length]
produced = False
withheld_reason: str | None = None
try:
doc = HwpxDocument.open(in_path)
cell = _first_fillable_cell(doc)
if cell is None:
withheld_reason = "no empty table cell found for programmatic fill"
doc.close()
else:
fit_cell_text(cell, value, FitPolicy.keep(), document=doc)
doc.save_to_path(out_path)
doc.close()
if out_path.exists() and static_open_safety_ok(out_path):
produced = True
elif out_path.exists():
# produced bytes but static pre-filter flags it: keep the
# file (Hancom is the real judge) — still counts produced.
produced = True
except Exception as exc:
withheld_reason = f"{type(exc).__name__}: {exc}".strip()[:400]
rec = record(
rec_id=rec_id, bucket="form-fit", seed=seed,
output_path=out_path if produced else None,
produced=produced, withheld_reason=withheld_reason,
input_path=in_path,
)
rec["value_length_class"] = length
records.append(rec)
if produced:
produced_paths.append(out_path)
emitted += 1
print(f"[form-fit] {rec_id} produced={produced} "
f"static_ok={rec['static_open_safety_ok']} {withheld_reason or ''}")
return records, produced_paths
# ================================================================================
# bucket 4 — exam (5) : A_form x exam md of {5,10,15} questions
# ================================================================================
def _slice_exam_md(src_md: str, n_questions: int) -> str:
"""Take the first N top-level (## ) questions from the sample exam markdown."""
lines = src_md.splitlines()
header_lines: list[str] = []
body_lines: list[str] = []
q_count = 0
in_body = False
for ln in lines:
is_q_head = bool(re.match(r"^##\s+\d", ln)) or bool(re.match(r"^##\s+\d+[∼~]", ln))
if is_q_head:
in_body = True
q_count += 1
if q_count > n_questions:
break
if not in_body:
header_lines.append(ln)
else:
body_lines.append(ln)
return "\n".join(header_lines + body_lines).strip() + "\n"
def gen_exam(out_dir: Path) -> tuple[list[dict[str, Any]], list[Path]]:
records: list[dict[str, Any]] = []
produced_paths: list[Path] = []
bucket_dir = out_dir / "exam"
bucket_dir.mkdir(parents=True, exist_ok=True)
a_form = EXAM_FIXTURES / "A_form.hwpx"
sample_md = (EXAM_FIXTURES / "sample_exam.md").read_text(encoding="utf-8")
# Exam composition and the render transport belong to the MCP owner now, and
# are imported here rather than at module scope so importing this script —
# which the unit tests do — never requires hwpx_automation. Same reason the
# authored-generation path already defers its MCP import.
from hwpx_automation.office.exam.compose import compose_exam_into_form
from hwpx_automation.office.rendering.oracle import NullOracle
null_oracle = NullOracle() # generation only — never render
# 5 outputs = {5,10,15} questions, then 5 and 10 again to reach 5 files
variants = [5, 10, 15, 5, 10]
for vi, n_q in enumerate(variants):
rec_id = f"exam-{vi:02d}-q{n_q:02d}"
seed = f"exam:Aform:q{n_q}:v{vi}"
out_path = bucket_dir / f"{rec_id}.hwpx"
if out_path.exists():
out_path.unlink()
exam_md = _slice_exam_md(sample_md, n_q)
produced = False
withheld_reason: str | None = None
try:
res = compose_exam_into_form(
str(a_form), exam_md, str(out_path), oracle=null_oracle
)
if out_path.exists():
produced = True
else:
withheld_reason = "compose produced no output file"
_ = res # render_checked False / needs_review True by design (no oracle)
except Exception as exc:
withheld_reason = f"{type(exc).__name__}: {exc}".strip()[:400]
rec = record(
rec_id=rec_id, bucket="exam", seed=seed,
output_path=out_path if produced else None,
produced=produced, withheld_reason=withheld_reason,
input_path=a_form,
)
rec["n_questions"] = n_q
records.append(rec)
if produced:
produced_paths.append(out_path)
print(f"[exam] {rec_id} produced={produced} "
f"static_ok={rec['static_open_safety_ok']} {withheld_reason or ''}")
return records, produced_paths
# ================================================================================
# bucket 5 — redline (5) : take 5 authored outputs, apply tracked changes
# ================================================================================
def gen_redline(out_dir: Path, authored_paths: list[Path]) -> tuple[list[dict[str, Any]], list[Path]]:
records: list[dict[str, Any]] = []
produced_paths: list[Path] = []
bucket_dir = out_dir / "redline"
bucket_dir.mkdir(parents=True, exist_ok=True)
sources = sorted(authored_paths, key=lambda p: p.name)[:5]
for i, src in enumerate(sources):
rec_id = f"redline-{i:02d}-{src.stem}"
seed = f"redline:{src.stem}"
out_path = bucket_dir / f"{rec_id}.hwpx"
if out_path.exists():
out_path.unlink()
produced = False
withheld_reason: str | None = None
try:
doc = HwpxDocument.open(src)
paras = [p for p in doc.sections[0].paragraphs
if (getattr(p, "text", "") or "").strip()]
applied = 0
# tracked insert on the 1st text para
if paras:
doc.add_tracked_insert(paras[0], " [검토필]", author="검토자",
date="2026-07-01T00:00:00")
applied += 1
# tracked replace on a para containing a known token, else delete-clip
for p in paras[1:]:
txt = getattr(p, "text", "") or ""
if "가." in txt:
try:
doc.add_tracked_replace(p, "가.", "가.(수정)",
author="검토자",
date="2026-07-01T00:00:00")
applied += 1
break
except Exception:
continue
if applied == 0:
withheld_reason = "no eligible paragraph for a tracked change"
doc.close()
else:
doc.save_to_path(out_path)
doc.close()
if out_path.exists():
produced = True
except Exception as exc:
withheld_reason = f"{type(exc).__name__}: {exc}".strip()[:400]
rec = record(
rec_id=rec_id, bucket="redline", seed=seed,
output_path=out_path if produced else None,
produced=produced, withheld_reason=withheld_reason,
input_path=src,
)
records.append(rec)
if produced:
produced_paths.append(out_path)
print(f"[redline] {rec_id} produced={produced} "
f"static_ok={rec['static_open_safety_ok']} {withheld_reason or ''}")
return records, produced_paths
# ================================================================================
# ================================================================================
# corpus v2 (specs/010-corpus-publication FR-002) — ADDITIVE strata only.
# v1 is FROZEN: v2 READS v1 outputs/manifest but never writes into OUT_DIR.
# ================================================================================
# ================================================================================
V2_SCHEMA = "hwpx.openrate.frozen-manifest.v2"
COMBINED_SCHEMA = "hwpx.openrate.combined-manifest.v1"
V2_TRACK_AUTHOR = "검토자"
V2_TRACK_DATE = "2026-07-02T00:00:00" # fixed timestamp — deterministic, not wall-clock
REDLINE_OPS = ("insert", "delete", "replace")
PII_MERGE_N = 35
AUTHORED_TOC_N = 15
READING_RUNFORMAT_N = 10
READING_FOOTNOTE_N = 3
TOC_HEADING_BANK = ["추진 배경", "추진 계획", "세부 과제", "기대 효과", "향후 일정"]
COLOR_BANK = ["#C00000", "#0070C0", "#00B050", "#7030A0"]
FONT_BANK = ["함초롬돋움", "함초롬바탕"]
def record_v2(
*,
rec_id: str,
stratum: str,
seed: str,
output_path: Path | None,
produced: bool,
withheld_reason: str | None = None,
input_path: Path | None = None,
**extra: Any,
) -> dict[str, Any]:
"""A v1 record + v2 fields: stratum, hostile_input (tagging hook — future
hwpxlib-derived inputs set True so input-attributed failures separate), extras."""
rec = record(
rec_id=rec_id, bucket=stratum, seed=seed,
output_path=output_path, produced=produced,
withheld_reason=withheld_reason, input_path=input_path,
)
rec["stratum"] = stratum
rec["hostile_input"] = False
rec.update(extra)
return rec
# --------------------------------------------------------------------------------
# pure planners (unit-tested; no filesystem writes)
# --------------------------------------------------------------------------------
def v1_formfit_combos(v1_manifest: dict[str, Any]) -> set[tuple[str, str]]:
"""(input-tag, length) combos already frozen in v1 — v2 must SKIP these.
v1 form-fit seeds are ``formfit:{tag}:{length}`` where tag itself contains a
colon (``m2:form_002`` / ``corpus:aikorea-…``).
"""
combos: set[tuple[str, str]] = set()
for rec in v1_manifest.get("records", []):
if rec.get("bucket") != "form-fit":
continue
parts = str(rec.get("seed", "")).split(":")
if len(parts) >= 3 and parts[0] == "formfit":
combos.add((":".join(parts[1:-1]), parts[-1]))
return combos
def plan_form_fit_wide(
inputs: Sequence[tuple[str, Path]],
v1_combos: set[tuple[str, str]],
sweep_order: Sequence[str] = ("short", "medium", "overflow"),
) -> list[tuple[str, Path, str]]:
"""Full input x length sweep minus v1-frozen combos. Deterministic order."""
planned: list[tuple[str, Path, str]] = []
for tag, in_path in inputs:
for length in sweep_order:
if (tag, length) in v1_combos:
continue
planned.append((tag, in_path, length))
return planned
def v1_authored_sources(v1_manifest: dict[str, Any]) -> list[tuple[str, Path]]:
"""(stem, path) of every produced v1 authored doc, sorted by stem (pure)."""
out: list[tuple[str, Path]] = []
for rec in v1_manifest.get("records", []):
if rec.get("bucket") == "authored" and rec.get("produced") and rec.get("output_path"):
p = Path(rec["output_path"])
out.append((p.stem, p))
out.sort(key=lambda t: t[0])
return out
def v1_redline_covered(
v1_manifest: dict[str, Any],
v1_ops: Sequence[str] = ("insert", "replace"),
) -> set[tuple[str, str]]:
"""(source-stem, op) combos v1 already exercises. The frozen v1 generator
applied a tracked INSERT always and a tracked REPLACE conditionally on each
of its 5 sources, so both ops count as covered for those stems."""
covered: set[tuple[str, str]] = set()
for rec in v1_manifest.get("records", []):
if rec.get("bucket") != "redline":
continue
seed = str(rec.get("seed", ""))
stem = seed.split(":", 1)[1] if ":" in seed else seed
for op in v1_ops:
covered.add((stem, op))
return covered
def plan_redline_wide(
source_stems: Sequence[str],
covered: set[tuple[str, str]],
) -> list[tuple[str, str]]:
"""One tracked op per source, round-robin insert/delete/replace by index,
skipping (source, op) combos v1 already covers. Deterministic."""
planned: list[tuple[str, str]] = []
for i, stem in enumerate(source_stems):
op = REDLINE_OPS[i % len(REDLINE_OPS)]
if (stem, op) in covered:
continue
planned.append((stem, op))
return planned
def luhn_check_digit(payload: str) -> str:
"""Check digit that makes ``payload + digit`` Luhn-valid."""
total = 0
for pos, ch in enumerate(reversed(payload)):
d = int(ch)
if pos % 2 == 0: # doubling starts at the digit adjacent to the check digit
d *= 2
if d > 9:
d -= 9
total += d
return str((10 - total % 10) % 10)
def luhn_ok(number: str) -> bool:
digits = re.sub(r"\D", "", number)
if not digits:
return False
total = 0
for pos, ch in enumerate(reversed(digits)):
d = int(ch)
if pos % 2 == 1:
d *= 2
if d > 9:
d -= 9
total += d
return total % 10 == 0
def synthetic_pii_roster(n: int = PII_MERGE_N) -> list[dict[str, str]]:
"""Deterministic SYNTHETIC machine-PII roster (NO real persons, NO random).
Every value derives from the row index: rrn is pattern-valid (YYMMDD-GNNNNNN,
plausible date, gender 1-4) but a range-safe fake; phone is 010-xxxx-xxxx;
email is under example.com; card is 16-digit Luhn-valid (so the shipped
masking engine detects and masks it — the corpus property under test).
"""
rows: list[dict[str, str]] = []
for i in range(n):
name = cycle(SURNAMES, i) + cycle(GIVEN, (i * 7) % len(GIVEN))
yy = 70 + (i % 30)
mm = (i % 12) + 1
dd = (i % 28) + 1
gender = 1 + (i % 4)
rrn = f"{yy:02d}{mm:02d}{dd:02d}-{gender}{234500 + i:06d}"
phone = f"010-{1000 + i:04d}-{5600 + i:04d}"
email = f"user{i:02d}@example.com"
card_payload = f"4111{2200 + i:04d}{3300 + i:04d}{100 + (i % 900):03d}"
card_digits = card_payload + luhn_check_digit(card_payload)
card = "-".join(card_digits[j:j + 4] for j in range(0, 16, 4))
rows.append({
"name": name,
"org": cycle(ORG_BANK, i),
"date": cycle(DATE_BANK, i),
"rrn": rrn,
"phone": phone,
"email": email,
"card": card,
})
return rows
def merge_manifests(
v1_manifest: dict[str, Any],
v2_manifest: dict[str, Any],
*,
v1_root: Path,
v2_root: Path,
shipped_root: Path,
) -> dict[str, Any]:
"""Combined v1+v2 manifest for the box filelist step (pure; inputs unmodified).
v1 records are merged BY REFERENCE (copied dicts, untouched files). Every
produced record gains ``box_rel`` — its path under the box mirror layout
``{v1/**, v2/**, shipped/**}`` — so openrate_box_filelist --combined can emit
exact box paths without guessing roots.
"""
def _box_rel(path_str: str, root: Path, prefix: str) -> str:
p = Path(path_str)
try:
rel = p.resolve().relative_to(root.resolve()).as_posix()
except ValueError: # not under the expected root — basename fallback
rel = p.name
return f"{prefix}/{rel}"
records: list[dict[str, Any]] = []
for rec in v1_manifest.get("records", []):
rr = dict(rec)
rr["corpus"] = "v1"
rr.setdefault("stratum", rr.get("bucket"))
rr["box_rel"] = (
_box_rel(str(rr["output_path"]), v1_root, "v1") if rr.get("output_path") else None
)
records.append(rr)
for rec in v2_manifest.get("records", []):
rr = dict(rec)
rr["corpus"] = "v2"
rr.setdefault("stratum", rr.get("bucket"))
if rr.get("output_path"):
if rr.get("stratum") == "shipped-artifacts":
rr["box_rel"] = _box_rel(str(rr["output_path"]), shipped_root, "shipped")
else:
rr["box_rel"] = _box_rel(str(rr["output_path"]), v2_root, "v2")
else:
rr["box_rel"] = None
records.append(rr)
requested_total = len(records)
produced_total = sum(1 for r in records if r.get("produced"))
counts: dict[str, dict[str, int]] = {}
for r in records:
key = f"{r['corpus']}:{r.get('stratum') or r.get('bucket')}"
slot = counts.setdefault(key, {"requested": 0, "produced": 0})
slot["requested"] += 1
if r.get("produced"):
slot["produced"] += 1
return {
"schemaVersion": COMBINED_SCHEMA,
"generatedAt": None, # root stamps it — DO NOT call datetime.now
"note": (
"Combined v1+v2 population for the box run. v1 records merged BY "
"REFERENCE (frozen bytes untouched); box_rel is the path under the "
"box mirror layout {v1/**, v2/**, shipped/**}."
),
"v1_schema": v1_manifest.get("schemaVersion"),
"v2_schema": v2_manifest.get("schemaVersion"),
"counts_per_stratum": counts,
"requested_total": requested_total,
"produced_total": produced_total,
"records": records,
}
# --------------------------------------------------------------------------------
# stratum 1 — form-fit-wide: FULL input x length sweep minus v1 combos (~+55)
# --------------------------------------------------------------------------------
def gen_form_fit_wide(
out_dir: Path, v1_manifest: dict[str, Any]
) -> tuple[list[dict[str, Any]], list[Path]]:
records: list[dict[str, Any]] = []
produced_paths: list[Path] = []
bucket_dir = out_dir / "form-fit-wide"
bucket_dir.mkdir(parents=True, exist_ok=True)
inputs = [(tag, p) for tag, p in form_fit_inputs() if p.exists()]
planned = plan_form_fit_wide(inputs, v1_formfit_combos(v1_manifest))
for tag, in_path, length in planned:
rec_id = f"formfit-wide-{tag.replace(':', '_')}-{length}"
seed = f"formfit-wide:{tag}:{length}"
out_path = bucket_dir / f"{rec_id}.hwpx"
if out_path.exists():
out_path.unlink()
value = LENGTH_SWEEP[length]
produced = False
withheld_reason: str | None = None
try:
doc = HwpxDocument.open(in_path)
cell = _first_fillable_cell(doc)
if cell is None:
withheld_reason = "no empty table cell found for programmatic fill"
doc.close()
else:
fit_cell_text(cell, value, FitPolicy.keep(), document=doc)
doc.save_to_path(out_path)
doc.close()
if out_path.exists():
# static pre-filter recorded either way (Hancom is the judge)
produced = True
except Exception as exc:
withheld_reason = f"{type(exc).__name__}: {exc}".strip()[:400]
rec = record_v2(
rec_id=rec_id, stratum="form-fit-wide", seed=seed,
output_path=out_path if produced else None,
produced=produced, withheld_reason=withheld_reason,
input_path=in_path,
value_length_class=length,
)
records.append(rec)
if produced:
produced_paths.append(out_path)
print(f"[form-fit-wide] {rec_id} produced={produced} "
f"static_ok={rec['static_open_safety_ok']} {withheld_reason or ''}")
return records, produced_paths
# --------------------------------------------------------------------------------
# stratum 2 — redline-wide: all v1 authored sources x insert/delete/replace (~+37)
# --------------------------------------------------------------------------------
def _apply_tracked_op(doc: HwpxDocument, op: str) -> str | None:
"""Apply one tracked op deterministically. Returns a withheld reason or None."""
paras = [p for p in doc.sections[0].paragraphs
if (getattr(p, "text", "") or "").strip()]
if not paras:
return "no text paragraph in source"
if op == "insert":
doc.add_tracked_insert(paras[0], " [검토필]",
author=V2_TRACK_AUTHOR, date=V2_TRACK_DATE)
return None
if op == "delete":
target = paras[1] if len(paras) > 1 else paras[0]
doc.add_tracked_delete(target, author=V2_TRACK_AUTHOR, date=V2_TRACK_DATE)
return None
if op == "replace":
for p in paras:
if "가." in (getattr(p, "text", "") or ""):
doc.add_tracked_replace(p, "가.", "가.(수정)",
author=V2_TRACK_AUTHOR, date=V2_TRACK_DATE)
return None
return "no eligible paragraph for tracked replace"
return f"unknown tracked op: {op}"
def gen_redline_wide(
out_dir: Path, v1_manifest: dict[str, Any]
) -> tuple[list[dict[str, Any]], list[Path]]:
records: list[dict[str, Any]] = []
produced_paths: list[Path] = []
bucket_dir = out_dir / "redline-wide"
bucket_dir.mkdir(parents=True, exist_ok=True)
sources = v1_authored_sources(v1_manifest) # READ-ONLY v1 inputs
path_by_stem = dict(sources)
planned = plan_redline_wide([s for s, _ in sources],
v1_redline_covered(v1_manifest))
for stem, op in planned:
src = path_by_stem[stem]
rec_id = f"redlinewide-{op}-{stem}"
seed = f"redline-wide:{stem}:{op}"
out_path = bucket_dir / f"{rec_id}.hwpx"
if out_path.exists():
out_path.unlink()
produced = False
withheld_reason: str | None = None
if not src.exists():
withheld_reason = "v1 source file missing on disk"
else:
try:
View remainder of file in raw view
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.