#!/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())