Run this model with HF Jobs

Run dllwa/gemma4-form-report-lora on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.

Paste one of these prompts into your coding agent:

Fine-tune on my dataset

Use HF Jobs to fine-tune https://huggingface.co/dllwa/gemma4-form-report-lora. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.

Run batch inference

Use HF Jobs to run batch inference with https://huggingface.co/dllwa/gemma4-form-report-lora on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
File size: 35,199 Bytes
3ca95cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""λͺ©ν‘œ 1 6μ°¨ 짝 쑰립 β€” [빈 μ„œμ‹]+[μ‚¬μš©μž ν…μŠ€νŠΈ] β†’ μ±„μ›Œμ§„ μ„œμ‹ (NP-014, DECISIONS 9/15).

## 계약 (μ‚¬μš©μž ν™•μ • 9/14~15)
    μž…λ ₯  [μ„œμ‹]  빈 ν…œν”Œλ¦Ώ(μΉΈ 라벨 λ‚˜μ—΄ β€” μ‹œμŠ€ν…œ μ£Όμž…, μ§λ§ˆλ‹€ 닀름 = μΌλ°˜ν™” μ‹ ν˜Έ)
          [μš”μ²­]  λͺ¨λ“œ A: μžμ—°μ–΄ λ°œν™”(μ—­ν•©μ„±) Β· λͺ¨λ“œ B: κ°œμ‘°μ‹ λ‚˜μ—΄ 덀프(결정적)
    μ •λ‹΅  μ„œμ‹ ꡬ쑰 κ·ΈλŒ€λ‘œ + μš”μ²­μ— μžˆλŠ” κ°’λ§Œ 칸에(데이터 ν‘œκΈ°λ‘œ) + λ‚˜λ¨Έμ§€ 칸은 빈칸

## μ›μ²œκ³Ό μ •λ‹΅ (λ Œλ”λ§ μ˜ˆμ™Έ β€” DECISIONS 9/15 등둝)
data/probe_datago/raw/*.csv (54μ„œμ‹ 73kν–‰, μ΄μš©ν—ˆλ½ 'μ œν•œ μ—†μŒ' λͺ…μ‹œλΆ„λ§Œ β€”
runs/datago_collect_log.tsv). μ •λ‹΅ = μ„œμ‹μ— CSV ν–‰ 값을 **μ½”λ“œλ‘œ 결정적 쑰립**.
κ°’ μ „λΆ€ μ‹€μ‘΄Β·LLM μ°½μž‘ μ—†μŒΒ·CSV κ²°μΈ‘ = μžμ—° 빈칸.

## λΆ„ν•  β€” 파일(=μ„œμ‹) λ‹¨μœ„
val 은 **ν†΅μ§Έλ‘œ λΊ€ μ„œμ‹λ“€**이닀: ν•™μŠ΅μ΄ λͺ» λ³Έ μ„œμ‹μ„ λ”°λ₯΄λŠ”κ°€κ°€ λͺ©ν‘œ 1 의 μ£Όμž₯이라
ν–‰ λ‹¨μœ„ λΆ„ν• λ‘œλŠ” κ·Έκ±Έ λͺ» μž°λ‹€. ν‚€μ›Œλ“œλ³„λ‘œ 고루 8개 νŒŒμΌμ„ val 둜 λΊ€λ‹€(seed 42).

## 두 단계
  --phase prep  : CSV 정리·뢄할 β†’ λͺ¨λ“œ A λ°œν™” μ—­ν•©μ„± μž…λ ₯(utter_in.jsonl) + meta.json
  --phase build : ν•©μ„± λ°œν™”(--utter) 게이트 ν†΅κ³ΌλΆ„μœΌλ‘œ A 짝 + B 짝(덀프) 쑰립
게이트: κ³ λ₯Έ κ°’λ§ˆλ‹€ β€” 사싀 토큰 있으면 μ •κ·œν˜•μ΄ λ°œν™”μ— μ „λΆ€ 쑴재(factnorm),
μ—†μœΌλ©΄ μ–΄μ ˆ κ²ΉμΉ¨ β‰₯0.6. 미달 짝 폐기(수 기둝).

μ‚¬μš©:
  python3 src/data/make_form_pairs.py --phase prep  --out data/form6
  (μ„œλ²„μ—μ„œ λ°œν™” 생성)  β†’ python3 ... --phase build --utter data/form6/utter_out.jsonl
"""
import argparse
import collections
import csv
import io
import json
import os
import random
import re
import statistics as st
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from common.factnorm import facts_norm  # noqa: E402

INSTRUCTION = (
    "μ£Όμ–΄μ§„ μ„œμ‹μ„ κ·ΈλŒ€λ‘œ 따라 λ¬Έμ„œ μ΄ˆμ•ˆμ„ μž‘μ„±ν•˜λΌ. μš”μ²­μ— μžˆλŠ” κ°’λ§Œ ν•΄λ‹Ή 칸에 μ±„μš°κ³ , "
    "μš”μ²­μ— μ—†λŠ” 칸은 빈칸으둜 남겨라. μš”μ²­μ— μžˆμ–΄λ„ μ„œμ‹μ— 칸이 μ—†λŠ” λ‚΄μš©μ€ 버렀라.")
SYNTH_INSTRUCTION = (
    "μ•„λž˜ ν•­λͺ©λ“€μ„ λ‹΄μ•„, λ‹΄λ‹Ήμžμ—κ²Œ λ¬Έμ„œ μž‘μ„±μ„ μš”μ²­ν•˜λŠ” μžμ—°μŠ€λŸ¬μš΄ 말을 써라.\n"
    "- 좜λ ₯은 **μš”μ²­ν•˜λŠ” 말 ν•œ μ€„λ§Œ** μ“΄λ‹€. μ„œλ‘Β·μ„€λͺ…Β·μ„ νƒμ§€Β·λ”°μ˜΄ν‘œλ₯Ό 뢙이지 마라.\n"
    "- λͺ¨λ“  ν•­λͺ© 값을 빠짐없이 말에 담아라. κ°’μ˜ ν‘œκΈ°λŠ” λ§νˆ¬μ— 맞게 바꿔도 λœλ‹€"
    "(예: 2025-04-08 β†’ 25λ…„ 4μ›” 8일).\n- ν•­λͺ©μ— μ—†λŠ” 사싀을 μΆ”κ°€ν•˜μ§€ 마라.\n"
    "- λ¬Έμ„œ 이름을 μ–ΈκΈ‰ν•˜λ©° μž‘μ„±ν•΄ 달라고 ν•˜λΌ.")
DROP_COL = re.compile(r"순번|μ—°λ²ˆ|^번호$|번호$|μ½”λ“œ|μœ„λ„|경도|데이터기쀀|κΈ°μ€€μΌμž|등둝일|μˆ˜μ •μΌ|^λΉ„κ³ $")
BULLETS = ["β—‹", "❍", "-"]
# μ„œμ‹ μƒκΉ€μƒˆ(7μ°¨) β€” 배울 것은 νŠΉμ • μƒκΉ€μƒˆκ°€ μ•„λ‹ˆλΌ "μ£Όμ–΄μ§„ μƒκΉ€μƒˆ λ”°λ₯΄κΈ°"λ‹€.
# ꡬ획 λΆ„λ₯˜: μ‹€λ¬Ό μ„œμ‹μ˜ 톡상 μœ„κ³„(κ°œμš”/일정·μž₯μ†Œ/문의)λ₯Ό 컬럼 μ΄λ¦„μœΌλ‘œ λ‚˜λˆˆλ‹€.
import re as _re
SEC_RULES = [("일정·μž₯μ†Œ", _re.compile(r"μΌμ‹œ|일자|μ‹œκ°|κΈ°κ°„|μš”μΌ|년도|μž₯μ†Œ|μ£Όμ†Œ|μœ„μΉ˜|μ§€μ—­")),
             ("λ¬Έμ˜Β·λ‹΄λ‹Ή", _re.compile(r"μ „ν™”|연락|λ‹΄λ‹Ή|문의|κΈ°κ΄€|주졜|μ£Όκ΄€|후원|운영"))]


def sec_of(col):
    for name, rx in SEC_RULES:
        if rx.search(col):
            return name
    return "κ°œμš”"


def pad_label(c):
    """λΆ€μ‚° μžκ°„ν˜•: 4κΈ€μž μ΄ν•˜ 라벨은 '일    μ‹œ' 처럼 λ²Œλ¦°λ‹€."""
    return ("    ".join(c) if len(c) <= 2 else "  ".join(c)) if len(c) <= 4 else c


STYLES = ("bracket", "colon", "number", "section", "pad")

# ── λͺ©λ‘ μΉΈ (10μ°¨) β€” 값이 μ—¬λŸ¬ ν•­λͺ©μ΄λ©΄ ν•˜μœ„ "   - " μ€„λ‘œ μ „κ°œν•œλ‹€ ─────────────
# μ‚¬μš©μž 규격(9/14 μ˜ˆμ‹œ)의 ν•˜μœ„ λŒ€μ‹œ ꡬ쑰. μ„œμ‹μ˜ "   - " ν•œ 쀄은 반볡 κ°€λŠ₯ν•œ
# νŒ¨ν„΄ ν‘œμ‹œμ΄λ©°, μ •λ‹΅μ—μ„œ ν•­λͺ© 수만큼 λŠ˜μ–΄λ‚œλ‹€. ν•œ 쀄 뭉침을 λ§‰λŠ” ν•™μŠ΅ μ‹ ν˜Έ.
SEP_ITEMS = _re.compile(r"\s*[Β·β€§;|]\s*|\n|\s*/\s*(?=[^0-9])|\s*,\s*(?=[κ°€-힣A-Za-z(]{2})")


def split_items(v):
    parts = [p.strip(" -β€’\t") for p in SEP_ITEMS.split(v or "") if p and len(p.strip()) >= 4]
    if len(parts) >= 2 and all(len(p) <= 60 for p in parts):
        return parts
    return None


def render_styled(form, cols, style, filled=None, listy=None):
    """listy = λͺ©λ‘ μΉΈ μ§‘ν•©. λͺ©λ‘ 칸은 라벨 쀄 + ν•˜μœ„ '   - ' 쀄(λ“€)둜 λ Œλ”λ§:
    μ„œμ‹(빈)  β†’ 라벨 쀄 + '   - ' ν•œ 쀄(νŒ¨ν„΄ ν‘œμ‹œ)
    μ •λ‹΅(채움)β†’ 라벨 쀄 + ν•­λͺ©λ‹Ή '   - ν•­λͺ©' 쀄 Β· 빈칸이면 '   - ' κ·ΈλŒ€λ‘œ"""
    filled = filled or {}
    listy = listy or set()

    def emit(L, head, c):
        v = filled.get(c, "")
        if c in listy:
            L.append(head.rstrip())
            items = split_items(v) or ([v] if v else [])
            if items:
                L.extend(f"   - {it}" for it in items)
            else:
                L.append("   - ")
        else:
            L.append(f"{head} {v}".rstrip())

    L = [form]
    if style == "section":
        groups = {}
        for c in cols:
            groups.setdefault(sec_of(c), []).append(c)
        for sec in ("κ°œμš”", "일정·μž₯μ†Œ", "λ¬Έμ˜Β·λ‹΄λ‹Ή"):
            if sec not in groups:
                continue
            L.append(f"β–‘ {sec}")
            for c in groups[sec]:
                emit(L, f"  β—‹ ({c})", c)
    elif style == "colon":
        for c in cols:
            emit(L, f"- {c}:", c)
    elif style == "number":
        for i, c in enumerate(cols, 1):
            emit(L, f"{i}. {c} :", c)
    elif style == "pad":
        for c in cols:
            emit(L, f" β—‹ ({pad_label(c)})", c)
    else:
        for c in cols:
            emit(L, f" β—‹ ({c})", c)
    return "\n".join(L)
WORD = re.compile(r"[κ°€-힣A-Za-z0-9]{2,}")
TAILS = ("라고 함", "인 λ“―", "이라고 ν–ˆμŒ", "ν•˜κΈ°λ‘œ ν–ˆλ‹€λ˜λ°")


def read_table(path):
    b = open(path, "rb").read()
    for enc in ("utf-8-sig", "utf-8", "cp949"):
        try:
            text = b.decode(enc)
            break
        except UnicodeDecodeError:
            continue
    else:
        text = b.decode("cp949", errors="replace")
    rows = list(csv.reader(io.StringIO(text)))
    if len(rows) < 5:
        return None
    # μΉΈ μ΄λ¦„μ˜ κ΄„ν˜ΈλŠ” "(라벨)" 틀을 κΉ¨λœ¨λ¦°λ‹€ β€” 곡백으둜 정리 [μžκΈ°κ²€μ¦ μ‹€μΈ‘ 9/15]
    hdr = [re.sub(r"\s+", " ", re.sub(r"[()οΌˆοΌ‰]", " ", h)).strip() for h in rows[0]]
    keep = [i for i, h in enumerate(hdr) if h and len(h) <= 40 and not DROP_COL.search(h)]
    if len(keep) < 3:
        return None
    data = []
    for r in rows[1:]:
        vals = {hdr[i]: r[i].strip() for i in keep if i < len(r) and r[i].strip()
                and len(r[i].strip()) <= 120 and "οΏ½" not in r[i]}
        if len(vals) >= 2:
            data.append(vals)
    return [hdr[i] for i in keep], data


def form_name(title):
    """데이터셋 제λͺ© β†’ μ„œμ‹ 이름. '좩청남도_곡연행사정보_20240726' β†’ '곡연행사정보'."""
    t = re.sub(r"_\d{6,8}$", "", title)
    parts = t.split("_")
    return parts[-1] if len(parts) > 1 else t


def render(form, cols, bullet, filled=None):
    """μ„œμ‹(빈) λ˜λŠ” μ •λ‹΅(채움) λ Œλ”λ§ β€” μ •λ‹΅ ν‘œκΈ°λŠ” CSV κ°’ κ·ΈλŒ€λ‘œ."""
    lines = [form]
    for c in cols:
        v = (filled or {}).get(c, "")
        lines.append(f" {bullet} ({c}) {v}".rstrip())
    return "\n".join(lines)


def load_forms(raw_dir, log_path):
    kw_of = {}
    for ln in open(log_path, encoding="utf-8"):
        f = ln.rstrip("\n").split("\t")
        if len(f) >= 3:
            kw_of[f[1]] = (f[0], f[2])
    forms = {}
    for fn in sorted(os.listdir(raw_dir)):
        pk = fn.split(".")[0]
        t = read_table(os.path.join(raw_dir, fn))
        if not t:
            continue
        cols, data = t
        kw, title = kw_of.get(pk, ("?", pk))
        forms[pk] = {"kw": kw, "form": form_name(title), "cols": cols, "rows": data}
    return forms


def split_val(forms, rng, n_val=8):
    by_kw = collections.defaultdict(list)
    for pk, f in forms.items():
        by_kw[f["kw"]].append(pk)
    val = []
    kws = sorted(by_kw)
    rng.shuffle(kws)
    while len(val) < n_val and kws:
        for kw in list(kws):
            cand = [p for p in by_kw[kw] if p not in val]
            if cand:
                val.append(rng.choice(cand))
            else:
                kws.remove(kw)
            if len(val) >= n_val:
                break
    return set(val)


def value_in(v, utter):
    fv = facts_norm(v)
    if fv:
        return fv <= facts_norm(utter)
    wv = set(WORD.findall(v))
    if not wv:
        return True
    wu = set(WORD.findall(utter))
    # ν™œμš©ν˜• κ΄€μš©: "운영"은 "μš΄μ˜ν•œ"에 λ“€μ–΄ μžˆλ‹€ [게이트 μ‹€μΈ‘ 9/15]
    hit = sum(1 for w in wv if any(u.startswith(w) or w in u for u in wu))
    return hit / len(wv) >= 0.6



def pick_utter(pred, chosen):
    """ν•©μ„± μ‚°μΆœμ—μ„œ λ°œν™” 쀄 κ³ λ₯΄κΈ° β€” base κ°€ λΉ„μ„œ μ„œλ‘λ₯Ό λΆ™μ΄λŠ” 일이 μž¦λ‹€ [μ‹€μΈ‘ 9/15].
    κ°’ 컀버리지가 κ°€μž₯ 높은 쀄(λ˜λŠ” 이웃 두 쀄)을 κ³ λ₯Έλ‹€. μ΅œμ’… νŒμ •μ€ κ²Œμ΄νŠΈκ°€ ν•œλ‹€."""
    # 쀄머리 μ •λ¦¬λŠ” λͺ©λ‘ 번호("1. ")와 λ”°μ˜΄ν‘œλ§Œ β€” 숫자λ₯Ό ν†΅μ§Έλ‘œ μ§€μš°λ©΄ 연도가 λ‚ μ•„κ°„λ‹€ [μ‹€μΈ‘ 9/15]
    lines = [re.sub(r"^(?:\d{1,2}[.)]\s+|[\-*\s\"β€œβ€']+)*", "", l).strip()
             for l in (pred or "").splitlines() if l.strip()]
    best, score = "", -1
    for i, l in enumerate(lines):
        for c in ([l] + ([l + " " + lines[i + 1]] if i + 1 < len(lines) else [])):
            if c.startswith("μš”μ²­ν•˜μ‹ ") or len(c) < 8:
                continue
            s = sum(1 for v in chosen.values() if value_in(v, c))
            if s > score:
                best, score = c, s
    return best


def _bat(w):
    """λ§ˆμ§€λ§‰ κΈ€μžμ— 받침이 μžˆλŠ”κ°€ (ν•œκΈ€ μ•„λ‹ˆλ©΄ False β€” 쑰사 κΈ°λ³Έν˜•)."""
    ch = (w or " ")[-1]
    return 0xAC00 <= ord(ch) <= 0xD7A3 and (ord(ch) - 0xAC00) % 28 > 0


def josa(w, a, b):
    """λ°›μΉ¨ 있으면 a, μ—†μœΌλ©΄ b β€” josa('마련','은','λŠ”') β†’ '은'."""
    return a if _bat(w) else b


def enum_sentence(label, items, rng):
    """10μ°¨ Eλͺ¨λ“œ: λͺ©λ‘ 값을 'ν•œ λ¬Έμž₯ μ•ˆ ꡬ어 λ‚˜μ—΄'둜 β€” κ΄€μΈ‘λœ λ­‰μΉ¨ 꼴을 ν•™μŠ΅ 뢄포에 λ„£λŠ”λ‹€.
    (μ‹€λ¬Ό κ΄€μΈ‘ 9/16: 'μ œλ„κΈ°λ°˜ λ§ˆλ ¨ν•˜κ³  AI μ„œλΉ„μŠ€ λ„μž…ν•˜κ³  … μ„Έ κ°ˆλž˜μ•Ό' 꼴만 λ­‰μ³€λ‹€)"""
    conn = rng.choice(("ν•˜κ³ ", "λž‘", ", 그리고", "μ΄λž‘μ™€"))
    if conn == "ν•˜κ³ ":
        joined = "ν•˜κ³  ".join(items)
    elif conn == "λž‘":
        joined = " ".join(f"{it}{josa(it,'μ΄λž‘','λž‘')}" for it in items[:-1]) + " " + items[-1]
    elif conn == "μ΄λž‘μ™€":
        joined = " ".join(f"{it}{josa(it,'κ³Ό','와')}" for it in items[:-1]) + " " + items[-1]
    else:
        joined = ", ".join(items[:-1]) + " 그리고 " + items[-1]
    eun = josa(label, "은", "λŠ”")
    frame = rng.choice((
        f"{label}{eun} {joined}{josa(items[-1],'이야','μ•Ό')}.",
        f"{label}{eun} {joined}{josa(items[-1],'으둜','둜')} μž‘μ•˜μ–΄.",
        f"{label} μͺ½μ€ {joined}, μ΄λ ‡κ²Œ {len(items)}κ°œμ•Ό.",
        f"{label}{eun} {joined} μ •λ„λ‘œ μƒκ°ν•˜κ³  μžˆμ–΄.",
    ))
    return frame


def speak_slot(label, v, rng):
    """Eλͺ¨λ“œμ˜ λΉ„λͺ©λ‘ μΉΈ β€” ꡬ어 λ¬Έμž₯ 틀에 값을 μ–ΉλŠ”λ‹€(κ°’ λ¬Έμžμ—΄μ€ 보쑴, ν‹€λ§Œ ꡬ어)."""
    eun = josa(label, "은", "λŠ”")
    return rng.choice((
        f"{label}{eun} {v}{josa(v,'이야','μ•Ό')}.",
        f"{label}{eun} {v}{josa(v,'으둜','둜')} ν•΄μ€˜.",
        f"{label}{eun} {v}.",
    ))


def parse_alias(path, forms):
    """λ™μ˜μ–΄ ν•©μ„± μ‚°μΆœ β†’ {pk: {μΉΈ: [별칭…]}}. ν˜•μ‹ μ–΄κΈ‹λ‚œ 쀄은 버린닀(λˆˆν™•μΈ 별도)."""
    import re as _r
    out = {}
    for ln in open(path, encoding="utf-8"):
        r = json.loads(ln)
        pk = r["source"]
        cols = {c: c for c in forms.get(pk, {}).get("cols", [])}
        m = {}
        for line in (r.get("prediction") or "").splitlines():
            mm = _r.match(r"\s*[-*]?\s*(.{1,40}?)\s*=>\s*(.+)$", line)
            if not mm:
                continue
            col = mm.group(1).strip()
            if col not in cols:
                continue
            als = [x.strip() for x in mm.group(2).split("|")
                   if 1 < len(x.strip()) <= 14 and x.strip() != col]
            if als:
                m[col] = als
        if m:
            out[pk] = m
    return out


def decoy_ok(dc, dv, target_cols, target_alias):
    """9μ°¨ μž‰μ—¬ κ·œμΉ™ β€” μž‰μ—¬λŠ” '식별 κ°€λŠ₯ν•œ 무관 정보'μ—¬μ•Ό ν•œλ‹€ [침투 μ‹€λ¬Ό 뢄석 9/15].

    8차의 μž‰μ—¬λŠ” λ‹€λ₯Έ μ„œμ‹μ˜ ν–‰μ—μ„œ λ½‘μ•˜λŠ”λ° μ„œμ‹λ“€μ΄ 곡톡 μΉΈ(μˆ˜κ°•λ£ŒΒ·μ‹œμž‘μΌβ€¦)을 κ³΅μœ ν•΄
    `μˆ˜κ°•λ£Œ: 10000` 같은 **μ§„μ§œ μ§€μ‹œμ™€ ꡬ별 λΆˆκ°€λŠ₯ν•œ 함정**이 μ„žμ˜€λ‹€. 맀핑을 배운 λͺ¨λΈμ΄
    μ •ν™•νžˆ κ·Έ 함정에 κ±Έλ € νšŒκ·€(βˆ’3.4)둜 λ‚˜νƒ€λ‚¬λ‹€ β€” λͺ¨λΈ 결함이 μ•„λ‹ˆλΌ μ‹œν—˜ 섀계 결함.
    κ·œμΉ™: λŒ€μƒ μ„œμ‹μ˜ μΉΈκ³Ό 라벨이 κ°™κ±°λ‚˜Β·λ³„μΉ­μ΄κ±°λ‚˜Β·μ–΄μ ˆμ΄ 겹치면 μž‰μ—¬λ‘œ μ“°μ§€ μ•ŠλŠ”λ‹€.
    라벨 μ—†λŠ” μž‰μ—¬λ„ κΈˆμ§€(맨 값은 좜처λ₯Ό μ•Œ 수 μ—†μ–΄ μ±„μš°λŠ” 게 계약상 μ˜³μ„ 수 μžˆλ‹€).
    """
    wl = set(WORD.findall(dc))
    for c in target_cols:
        wc = set(WORD.findall(c))
        if dc == c or (wl and wc and len(wl & wc) / min(len(wl), len(wc)) >= 0.5):
            return False
        for al in (target_alias or {}).get(c, []):
            wa = set(WORD.findall(al))
            if dc == al or (wl and wa and len(wl & wa) / min(len(wl), len(wa)) >= 0.5):
                return False
    return True


def dump_line(c, v, rng4, alias):
    """8μ°¨ 덀프 쀄 β€” 라벨 λ™μ˜μ–΄Β·λΌλ²¨ 은닉·싀물 λ©”λͺ¨ν˜• μž₯식 (μž…λ ₯ μͺ½ λ³€ν˜•λ§Œ)."""
    roll = rng4.random()
    if roll < 0.40 and alias.get(c):
        c2 = rng4.choice(alias[c])
        return f"{c2}: {v}"
    if roll < 0.60:
        return v                                   # 라벨 은닉 β€” κ°’λ§Œ
    if roll < 0.75:
        return f"β—‹ {pad_label(c)} : {v}"           # μ‹€λ¬Ό λ©”λͺ¨ν˜•(μžκ°„Β·κΈ°ν˜Έ)
    return f"{c}: {v}"


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--phase", choices=("prep", "build"), required=True)
    ap.add_argument("--raw", default="data/probe_datago/raw")
    ap.add_argument("--log", default="runs/datago_collect_log.tsv")
    ap.add_argument("--out", default="data/form6")
    ap.add_argument("--utter", nargs="+", default=[], help="build: λ°œν™” jsonl (볡수 κ°€λŠ₯ β€” 쀄 선택은 pick_utter)")
    ap.add_argument("--seed", type=int, default=42)
    ap.add_argument("--train-rows", type=int, default=60, help="νŒŒμΌλ‹Ή ν‘œλ³Έ ν–‰ μƒν•œ")
    ap.add_argument("--val-rows", type=int, default=20)
    ap.add_argument("--preview", type=int, default=0)
    ap.add_argument("--alias", default="", help="8μ°¨: 라벨 λ™μ˜μ–΄ jsonl β€” B2(뢈일치) 짝 μΆ”κ°€ 생성")
    ap.add_argument("--utter-long", default="", help="10μ°¨: κΈ΄ 쀄글 ν•©μ„± μ‚°μΆœ jsonl β€” AL 짝 μΆ”κ°€")
    ap.add_argument("--utter-long-in", default="", help="10μ°¨: κΈ΄ 쀄글 ν•©μ„± μž…λ ₯ jsonl (μΉΈ 선택 λ³΅μ›μš©)")
    ap.add_argument("--modes-tm", action="store_true", help="10μ°¨: ν‘œ(T)Β·ν˜Όν•©(M) 짝 μΆ”κ°€")
    ap.add_argument("--mode-enum", action="store_true", help="10μ°¨: λ¬Έμž₯ 속 λ‚˜μ—΄(E) 짝 μΆ”κ°€")
    ap.add_argument("--prefix", default="pairs6", help="μ‚°μΆœ 파일 접두(pairs6/pairs10)")
    a = ap.parse_args()
    rng = random.Random(a.seed)
    os.makedirs(a.out, exist_ok=True)
    forms = load_forms(a.raw, a.log)
    val_pks = split_val(forms, random.Random(a.seed))
    print(f"μ„œμ‹ {len(forms)}개 λ‘œλ“œ Β· val μ„œμ‹ {len(val_pks)}개(톡째 ν™€λ“œμ•„μ›ƒ): "
          + ", ".join(f"{forms[p]['form']}({forms[p]['kw']})" for p in sorted(val_pks)))

    # ν–‰ ν‘œλ³Έ μΆ”μΆœ (결정적) β€” prepΒ·build κ°€ 같은 ν‘œλ³Έμ„ 봐야 ν•œλ‹€
    sample = {}
    for pk, f in forms.items():
        cap = a.val_rows if pk in val_pks else a.train_rows
        idx = list(range(len(f["rows"])))
        rng2 = random.Random(f"{a.seed}:{pk}")
        rng2.shuffle(idx)
        sample[pk] = idx[:cap]

    utt_long = {}
    if a.utter_long:
        for ln in open(a.utter_long, encoding="utf-8"):
            r = json.loads(ln)
            utt_long[r["source"]] = (r.get("prediction") or "").strip()

    if a.phase == "prep":
        n = 0
        with open(os.path.join(a.out, "utter_in.jsonl"), "w", encoding="utf-8") as w:
            for pk, f in forms.items():
                for ri in sample[pk]:
                    row = f["rows"][ri]
                    rng3 = random.Random(f"{a.seed}:{pk}:{ri}")
                    # λ°œν™” λͺ¨λ“œλŠ” 말둜 μ „ν•  짧은 κ°’λ§Œ β€” κΈ΄ λ‚΄μš©μ€ 덀프 λͺ¨λ“œ λͺ« [게이트 μ‹€μΈ‘ 9/15]
                    short = {c: v for c, v in row.items() if len(v) <= 40} or row
                    k = rng3.randint(1, min(6, len(short)))
                    chosen = dict(rng3.sample(sorted(short.items()), k))
                    w.write(json.dumps({
                        "source": f"{pk}#r{ri}",
                        "instruction": SYNTH_INSTRUCTION,
                        "input": f"[λ¬Έμ„œ 이름] {f['form']}\n[ν•­λͺ©]\n"
                                 + "\n".join(f"- {c}: {v}" for c, v in chosen.items()),
                        "output": ""}, ensure_ascii=False) + "\n")
                    n += 1
        meta = {"val_pks": sorted(val_pks), "seed": a.seed}
        json.dump(meta, open(os.path.join(a.out, "meta.json"), "w"))
        print(f"[μ €μž₯] utter_in.jsonl β€” λ°œν™” μ—­ν•©μ„± μž…λ ₯ {n:,}건")
        return

    # ── build ───────────────────────────────────────────────────────────
    utt = collections.defaultdict(str)
    for path in a.utter:
        for ln in open(path, encoding="utf-8"):
            r = json.loads(ln)
            utt[r["source"]] += "\n" + (r.get("prediction", "") or "")

    out_rows = {"train": [], "val": []}
    out_rows_b2 = {"train": [], "val": []}
    aliases = parse_alias(a.alias, forms) if a.alias else None
    if aliases is not None:
        print(f"λ™μ˜μ–΄: μ„œμ‹ {len(aliases)}개 Β· μΉΈ {sum(len(v) for v in aliases.values())}개")
    drop = collections.Counter()
    pks = sorted(forms)
    for pk, f in forms.items():
        split = "val" if pk in val_pks else "train"
        style = random.Random(f"{a.seed}:s:{pk}").choice(STYLES)
        for ri in sample[pk]:
            row = f["rows"][ri]
            rng3 = random.Random(f"{a.seed}:{pk}:{ri}")
            short = {c: v for c, v in row.items() if len(v) <= 40} or row
            k = rng3.randint(1, min(6, len(short)))
            chosen = dict(rng3.sample(sorted(short.items()), k))
            listy = {c for c, v in row.items() if split_items(v)}
            skel = render_styled(f["form"], f["cols"], style, listy=listy)

            # ── λͺ¨λ“œ A: λ°œν™” ──
            u = pick_utter(utt.get(f"{pk}#r{ri}", ""), chosen)
            if not u:
                drop["A: λ°œν™” μ—†μŒ"] += 1
            elif not all(value_in(v, u) for v in chosen.values()):
                drop["A: 게이트(κ°’ 미포함)"] += 1
            elif facts_norm(u) - set().union(*[facts_norm(v) for v in chosen.values()], facts_norm(f["form"])):
                drop["A: 게이트(μž‰μ—¬ 사싀)"] += 1
            else:
                gold = render_styled(f["form"], f["cols"], style, chosen, listy=listy)
                out_rows[split].append({
                    "mode": "A", "form_pk": pk, "form": f["form"], "kw": f["kw"],
                    "source": f"{pk}#r{ri}#A", "instruction": INSTRUCTION,
                    "slots_filled": chosen, "slots_list": sorted(listy), "n_slot": len(f["cols"]),
                    "n_blank": len(f["cols"]) - len(chosen), "decoy_lines": [],
                    "input": f"[μ„œμ‹]\n{skel}\n[μš”μ²­]\n{u}", "output": gold})

            # ── λͺ¨λ“œ B: 덀프 (결정적 β€” ν•©μ„± λΆˆν•„μš”) ──
            m = max(2, round(len(row) * rng3.uniform(0.5, 1.0)))
            given = dict(rng3.sample(sorted(row.items()), min(m, len(row))))
            others = [p for p in pks if p != pk and forms[p]["kw"] != f["kw"]] or \
                     [p for p in pks if p != pk]
            other = forms[rng3.choice(others)]
            orow = other["rows"][rng3.randrange(len(other["rows"]))]
            cand = [(c, v) for c, v in sorted(orow.items())
                    if decoy_ok(c, v, f["cols"], (aliases or {}).get(pk))]
            rng3.shuffle(cand)
            deco = [f"{c}: {v}" for c, v in cand[:rng3.randint(3, 5)]]
            # μž‰μ—¬κ°€ μ •λ‹΅ 어디와도(제λͺ©Β·λΌλ²¨μ˜ 숫자 포함) μ•ˆ 겹치게 β€” κ°’λ§Œ 보면 μƒŒλ‹€ [μ‹€μΈ‘]
            gold_facts = facts_norm(render_styled(f["form"], f["cols"], style, row, listy=listy))
            deco = [d for d in deco if not (facts_norm(d) & gold_facts)]
            dump = [f"{c}: {v}" for c, v in given.items()] + deco
            for i in range(len(dump)):
                if rng3.random() < 0.1:
                    dump[i] += " " + rng3.choice(TAILS)
            rng3.shuffle(dump)
            gold = render_styled(f["form"], f["cols"], style, given, listy=listy)
            if aliases is not None and pk in aliases:
                rng4 = random.Random(f"{a.seed}:{pk}:{ri}:b2")
                m2 = max(2, round(len(row) * rng4.uniform(0.4, 0.9)))
                given2 = dict(rng4.sample(sorted(row.items()), min(m2, len(row))))
                o2 = forms[rng4.choice(others)]
                orow2 = o2["rows"][rng4.randrange(len(orow2_pool := o2["rows"]))] if False else \
                        o2["rows"][rng4.randrange(len(o2["rows"]))]
                cand2 = [(c, v) for c, v in sorted(orow2.items())
                         if decoy_ok(c, v, f["cols"], (aliases or {}).get(pk))]
                rng4.shuffle(cand2)
                deco2 = [f"{c}: {v}" for c, v in cand2[:rng4.randint(3, 5)]]
                gold2 = render_styled(f["form"], f["cols"], style, given2, listy=listy)
                gf2 = facts_norm(render_styled(f["form"], f["cols"], style, row, listy=listy))
                deco2 = [d for d in deco2 if not (facts_norm(d) & gf2)]
                dump2 = [dump_line(c, v, rng4, aliases[pk]) for c, v in given2.items()] + deco2
                rng4.shuffle(dump2)
                if not (facts_norm(gold2) - facts_norm("\n".join(dump2) + skel + f["form"])):
                    out_rows_b2[split].append({
                        "mode": "B2", "form_pk": pk, "form": f["form"], "kw": f["kw"],
                        "source": f"{pk}#r{ri}#B2", "instruction": INSTRUCTION,
                        "slots_filled": given2, "slots_list": sorted(listy), "n_slot": len(f["cols"]),
                        "n_blank": len(f["cols"]) - len(given2), "decoy_lines": deco2,
                        "input": f"[μ„œμ‹]\n{skel}\n[μš”μ²­]\n" + "\n".join(f"- {d}" for d in dump2),
                        "output": gold2})
                else:
                    drop["B2 사싀 λˆ„μΆœ 폐기"] += 1
            out_rows[split].append({
                "mode": "B", "form_pk": pk, "form": f["form"], "kw": f["kw"],
                "source": f"{pk}#r{ri}#B", "instruction": INSTRUCTION,
                "slots_filled": given, "slots_list": sorted(listy), "n_slot": len(f["cols"]),
                "n_blank": len(f["cols"]) - len(given), "decoy_lines": deco,
                "input": f"[μ„œμ‹]\n{skel}\n[μš”μ²­]\n" + "\n".join(f"- {d}" for d in dump),
                "output": gold})
            # ── λͺ¨λ“œ T: ν‘œ λΆ™μ—¬λ„£κΈ° (결정적) ──
            if a.modes_tm and rng3.random() < 0.5:
                gT = dict(rng3.sample(sorted(row.items()), max(2, round(len(row) * rng3.uniform(0.4, 0.9)))))
                trows = [f"{c}\t{v}" for c, v in gT.items()]
                oT = forms[rng3.choice(others)]
                candT = [(c, v) for c, v in sorted(oT["rows"][0].items())
                         if decoy_ok(c, v, f["cols"], (aliases or {}).get(pk))
                         and not (facts_norm(f"{c}: {v}") & gold_facts)][:2]
                trows += [f"{c}\t{v}" for c, v in candT]
                rng3.shuffle(trows)
                goldT = render_styled(f["form"], f["cols"], style, gT, listy=listy)
                if not (facts_norm(goldT) - facts_norm("\n".join(trows) + skel + f["form"])):
                    out_rows[split].append({
                        "mode": "T", "form_pk": pk, "form": f["form"], "kw": f["kw"],
                        "source": f"{pk}#r{ri}#T", "instruction": INSTRUCTION,
                        "slots_filled": gT, "slots_list": sorted(listy), "n_slot": len(f["cols"]),
                        "n_blank": len(f["cols"]) - len(gT),
                        "decoy_lines": [f"{c}: {v}" for c, v in candT],
                        "input": f"[μ„œμ‹]\n{skel}\n[μš”μ²­]\n" + "\n".join(trows), "output": goldT})
            # ── λͺ¨λ“œ M: ν˜Όν•© (μ§€μ‹œλ¬Έ + λΆ™μž„ λ©”λͺ¨, 결정적) ──
            if a.modes_tm and rng3.random() < 0.5:
                gM = dict(rng3.sample(sorted(row.items()), max(2, round(len(row) * rng3.uniform(0.3, 0.8)))))
                lead = rng3.choice([
                    f"μ•„λž˜ λ‚΄μš© μ°Έκ³ ν•΄μ„œ {f['form']} μ΄ˆμ•ˆ μž‘μ„±ν•΄μ€˜.",
                    f"λ©”λͺ¨ 뢙인닀. {f['form']} μ–‘μ‹μœΌλ‘œ 정리 뢀탁해.",
                    f"{f['form']} ν•˜λ‚˜ λ§Œλ“€μ–΄ μ£Όμ„Έμš”. μžλ£ŒλŠ” μ•„λž˜μ— μžˆμŠ΅λ‹ˆλ‹€."])
                mlines = [f"- {c}: {v}" for c, v in gM.items()]
                oM = forms[rng3.choice(others)]
                candM = [(c, v) for c, v in sorted(oM["rows"][0].items())
                         if decoy_ok(c, v, f["cols"], (aliases or {}).get(pk))
                         and not (facts_norm(f"{c}: {v}") & gold_facts)][:2]
                mlines += [f"- {c}: {v}" for c, v in candM]
                rng3.shuffle(mlines)
                goldM = render_styled(f["form"], f["cols"], style, gM, listy=listy)
                if not (facts_norm(goldM) - facts_norm("\n".join(mlines) + skel + f["form"])):
                    out_rows[split].append({
                        "mode": "M", "form_pk": pk, "form": f["form"], "kw": f["kw"],
                        "source": f"{pk}#r{ri}#M", "instruction": INSTRUCTION,
                        "slots_filled": gM, "slots_list": sorted(listy), "n_slot": len(f["cols"]),
                        "n_blank": len(f["cols"]) - len(gM),
                        "decoy_lines": [f"{c}: {v}" for c, v in candM],
                        "input": f"[μ„œμ‹]\n{skel}\n[μš”μ²­]\n{lead}\n---\n" + "\n".join(mlines),
                        "output": goldM})
            # ── λͺ¨λ“œ E: λ¬Έμž₯ 속 ꡬ어 λ‚˜μ—΄ (결정적) β€” 10μ°¨ 겨λƒ₯ β‘  [μ‹€λ¬Ό κ΄€μΈ‘ 9/16] ──
            if a.mode_enum:
                rng5 = random.Random(f"{a.seed}:{pk}:{ri}:e")
                lcand = [(c, split_items(row[c])) for c in sorted(listy)
                         if row.get(c) and split_items(row[c]) and len(split_items(row[c])) <= 5
                         and all(len(it) <= 40 for it in split_items(row[c]))]
                if lcand and rng5.random() < 0.7:
                    cL, items = rng5.choice(lcand)
                    extras = dict(rng5.sample(
                        sorted((c, v) for c, v in short.items() if c != cL),
                        min(rng5.randint(0, 2), max(0, len(short) - 1))))
                    gE = {cL: row[cL], **extras}
                    sents = [enum_sentence(cL, items, rng5)] + \
                            [speak_slot(c, v, rng5) for c, v in extras.items()]
                    rng5.shuffle(sents)
                    lead = rng5.choice((f"{f['form']} λ§Œλ“€μ–΄μ€˜. ", f"{f['form']} ν•˜λ‚˜ μž‘μ•„μ€˜. ", ""))
                    uE = lead + " ".join(sents)
                    goldE = render_styled(f["form"], f["cols"], style, gE, listy=listy)
                    # 게이트: ν™˜κ° λ°©ν–₯(μ •λ‹΅ 사싀 βŠ† μž…λ ₯ 사싀) β€” ν”„λ ˆμž„μ˜ 'N개' 같은 μž‰μ—¬ μˆ«μžλŠ” ν—ˆμš©
                    if not (facts_norm(goldE) - facts_norm(uE + skel + f["form"])):
                        out_rows[split].append({
                            "mode": "E", "form_pk": pk, "form": f["form"], "kw": f["kw"],
                            "source": f"{pk}#r{ri}#E", "instruction": INSTRUCTION,
                            "slots_filled": gE, "slots_list": sorted(listy), "n_slot": len(f["cols"]),
                            "n_blank": len(f["cols"]) - len(gE), "decoy_lines": [],
                            "input": f"[μ„œμ‹]\n{skel}\n[μš”μ²­]\n{uE}", "output": goldE})
                    else:
                        drop["E 사싀 λˆ„μΆœ 폐기"] += 1

    # ── λͺ¨λ“œ AL: κΈ΄ 쀄글 λ°œν™” (μ—­ν•©μ„± μ‚°μΆœ 쑰립) β€” 10μ°¨ 겨λƒ₯ β‘‘ 의 μžμ—° ꡬ어 μΆ• ──
    if utt_long:
        if not a.utter_long_in:
            raise SystemExit("--utter-long 은 --utter-long-in(μΉΈ 선택 λ³΅μ›μš©)κ³Ό ν•¨κ»˜ 써야 ν•œλ‹€")
        ins_long = {}
        for ln in open(a.utter_long_in, encoding="utf-8"):
            r = json.loads(ln)
            ch = {}
            for m in re.finditer(r"^- ([^:]+): (.+)$", r["input"], re.M):
                ch[m.group(1).strip()] = m.group(2).strip()
            ins_long[r["source"]] = ch
        for src, u in utt_long.items():
            pk = src.split("#")[0]
            if pk not in forms or not u:
                drop["AL: μ„œμ‹/μ‚°μΆœ μ—†μŒ"] += 1
                continue
            f = forms[pk]
            chosen = ins_long.get(src, {})
            chosen = {c: v for c, v in chosen.items() if c in f["cols"]}
            if not chosen:
                drop["AL: μΉΈ 볡원 μ‹€νŒ¨"] += 1
                continue
            if not all(value_in(v, u) for v in chosen.values()):
                drop["AL: 게이트(κ°’ 미포함)"] += 1
                continue
            if facts_norm(u) - set().union(*[facts_norm(v) for v in chosen.values()],
                                           facts_norm(f["form"])):
                drop["AL: 게이트(μž‰μ—¬ 사싀)"] += 1
                continue
            split = "val" if pk in val_pks else "train"
            style = random.Random(f"{a.seed}:s:{pk}").choice(STYLES)
            row_listy = {c for c, v in chosen.items() if split_items(v)}
            skel = render_styled(f["form"], f["cols"], style, listy=row_listy)
            gold = render_styled(f["form"], f["cols"], style, chosen, listy=row_listy)
            out_rows[split].append({
                "mode": "AL", "form_pk": pk, "form": f["form"], "kw": f["kw"],
                "source": f"{src}#AL", "instruction": INSTRUCTION,
                "slots_filled": chosen, "slots_list": sorted(row_listy),
                "n_slot": len(f["cols"]), "n_blank": len(f["cols"]) - len(chosen),
                "decoy_lines": [], "input": f"[μ„œμ‹]\n{skel}\n[μš”μ²­]\n{u}", "output": gold})

    if aliases is not None:
        out_rows["train"] += out_rows_b2["train"]
        vm = out_rows_b2["val"]
        random.Random(a.seed).shuffle(vm)
        pv = os.path.join(a.out, f"{a.prefix}_val_mismatch.jsonl")
        with open(pv, "w", encoding="utf-8") as w:
            for r in vm:
                w.write(json.dumps(r, ensure_ascii=False) + "\n")
        print(f"[μ €μž₯] {pv} β€” 라벨 뢈일치 val {len(vm):,}건 (μ‹ κ·œ λŠ₯λ ₯ νŠΈλž™)")

    # val λΌμš°νŒ…: νšŒκ·€ νŠΈλž™(AΒ·B β€” 9μ°¨ κΈ°μ€€κ³Ό 비ꡐ κ°€λŠ₯)κ³Ό μ‹ κ·œ 문체 νŠΈλž™(val_long)을 뢄리
    val_long = [r for r in out_rows["val"] if r["mode"] not in ("A", "B")]
    out_rows["val"] = [r for r in out_rows["val"] if r["mode"] in ("A", "B")]
    if val_long:
        random.Random(a.seed).shuffle(val_long)
        pl = os.path.join(a.out, f"{a.prefix}_val_long.jsonl")
        with open(pl, "w", encoding="utf-8") as w:
            for r in val_long:
                w.write(json.dumps(r, ensure_ascii=False) + "\n")
        print(f"[μ €μž₯] {pl} β€” μ‹ κ·œ 문체 val {len(val_long):,}건 "
              f"({collections.Counter(r['mode'] for r in val_long)})")
    for split in ("train", "val"):
        rows = out_rows[split]
        rng.shuffle(rows)
        p = os.path.join(a.out, f"{a.prefix}_{split}.jsonl")
        with open(p, "w", encoding="utf-8") as w:
            for r in rows:
                w.write(json.dumps(r, ensure_ascii=False) + "\n")
        mc = collections.Counter(r["mode"] for r in rows)
        print(f"[μ €μž₯] {p} β€” {len(rows):,}건 ({dict(mc)}) Β· μ„œμ‹ "
              f"{len({r['form_pk'] for r in rows})}μ’…")
        if rows:
            print(f"  빈칸/μ„œμ‹μΉΈ 쀑앙 {st.median(r['n_blank'] for r in rows):.0f}/"
                  f"{st.median(r['n_slot'] for r in rows):.0f} Β· μ •λ‹΅ κΈ€μž 쀑앙 "
                  f"{st.median(len(r['output']) for r in rows):,.0f}")
    print(f"폐기 {dict(drop) or 'μ—†μŒ'}")

    # ── 뢄포 감사 (DECISIONS 9/16 등둝 절차) β€” μž…λ ₯ 곡간 차원별 뢄포, 빈 μΉΈ κ²½κ³  ──
    allr = out_rows["train"] + out_rows["val"] + val_long
    if allr:
        def req_len(r):
            return len(r["input"].split("[μš”μ²­]\n", 1)[-1])
        print("\n── 뢄포 감사 (계약 차원 Γ— 짝 수) ──")
        mc = collections.Counter(r["mode"] for r in allr)
        print(f"  문체: λ°œν™” A {mc['A']:,} Β· 긴쀄글 AL {mc['AL']:,} Β· λ‚˜μ—΄λ¬Έμž₯ E {mc['E']:,}"
              f" Β· 덀프 B {mc['B']:,} Β· 뢈일치 B2 {mc['B2']:,} Β· ν‘œ T {mc['T']:,} Β· ν˜Όν•© M {mc['M']:,}")
        bins = collections.Counter(("~80" if n <= 80 else "81~200" if n <= 200
                                    else "201~400" if n <= 400 else "400+")
                                   for n in map(req_len, allr))
        print(f"  μš”μ²­λΆ€ 길이: {dict(sorted(bins.items()))}")
        lab = collections.Counter(("뢈일치" if r["mode"] == "B2" else
                                   "λΌλ²¨μ—†μŒ" if r["mode"] in ("A", "AL", "E") else "일치") for r in allr)
        print(f"  라벨성: {dict(lab)}")
        nlist = sum(1 for r in allr if any(c in r["slots_filled"] for c in r["slots_list"]))
        ndec = sum(1 for r in allr if r["decoy_lines"])
        print(f"  κ°’ ν˜•νƒœ: λͺ©λ‘ μΉΈ 채움 포함 {nlist:,} (그쀑 λ‚˜μ—΄ λ¬Έμž₯ μž…λ ₯ E {mc['E']:,}) Β· μž‰μ—¬ 포함 {ndec:,}")
        empty = [k for k in ("A", "AL", "E", "B", "B2", "T", "M") if mc[k] == 0]
        if empty:
            print(f"  ⚠️ 빈 μΉΈ(계약이 μš”κ΅¬ν•˜λ‚˜ 짝 0건): {empty} β€” κ΅¬ν˜„μ΄ 계약보닀 쒁닀")
        else:
            print("  βœ… 계약 차원 μ „ 칸에 짝 쑴재")
    for r in out_rows["val"][:a.preview]:
        print(f"\n{'=' * 60}\n[{r['mode']} Β· {r['form']}]")
        print("--- μž…λ ₯ ---")
        print(r["input"][:600])
        print("--- μ •λ‹΅ ---")
        print(r["output"][:400])


if __name__ == "__main__":
    raise SystemExit(main())