"""부록 정리 프롬프트(최적색인방식전_청구취지규칙문서_정리_프롬프트_Opus.md)의 결정적 단계.
python3 appx_clean.py inv ROOT KEY WORK -> WORK/KEY.inv.json (목록·기본 판정·참조·ID)
python3 appx_clean.py build ROOT KEY WORK DEC.json [OUTDIR] -> 출력 파일·기록 json·검사 결과(C1~C12)
OUTDIR(ROOT 아래 폴더 이름)을 주면 출력은 그 폴더에, 기록 json은 그 아래 _기록에 쓴다. 이름이 _로 시작하는 항목은 C1이 보지 않는다.
DEC.json (LLM 판단):
{
"sections": {"<머리글 줄 그대로>": {"action": "KEEP_SECTION|KEEP_ITEMS|KEEP_UNSURE|DISCARD", "why": "...",
"items": ["항목 첫머리의 고유 부분 문자열", ...]}},
"pre_b": "KEEP|DISCARD",
"refs": [{"match": "참조 text+context 안의 부분 문자열", "from": "body|A|B|*",
"kind": "APPLY|RECORD|RAW_DANGLING|NOT_REF", "target": "<머리글 줄>|## 부록 B|null"}],
"patches": [{"old": "조립본에 정확히 한 번 나오는 문구", "new": "바꿀 문구", "why": "근거(해결책 파일·항목)", "count": 기대 횟수(선택, 기본 1)}] (선택)
"record_ids": {"X-2": "정의 행이 옛 지시 문구를 인용하는 이력 행이라 남기지 않음"} (선택)
}
patches는 미결 쟁점 해결책처럼 사람이 확정한 내용 수정과, 프롬프트 §4.7의 기준일 덧붙임(버린 절에만 있던 실행·법률 검토 기준일을 부록 A에 되살림)만 담는다. C2·C7은 교체 전 조립본으로, 나머지 검사는 교체 후 출력으로 본다.
적지 않은 절은 기본 판정을 따른다(①·② 기준 KEEP_SECTION, 나머지 DISCARD). DISCARD 절은 가리켜졌으면 OMIT, 아니면 DROP.
번호 참조(B.n)는 머리글이 '### B.n '으로 시작하는 절이 하나뿐이면 자동으로 그 절에 닿고, 종류는 refs 규칙이 없으면 RECORD로 둔다.
KEEP_ITEMS 절은 items와 별도로, 머리글 칸이 '잔여'로 시작하는 표에서 그 칸이 '없음'·'—'·'-'·빈칸이 아닌 행을 자동으로 모두 남긴다(C11이 확인).
머리글을 남긴 KEEP_ITEMS 절은 OMIT_LINE 대신 ITEMS_LINES 가운데 하나를 쓴다: 잔여 행만 남으면 "res", items로 고른 항목만 남으면 "ref", 둘 다면 "mix".
ID 정의는 줄머리 외에 줄 중간의 정의 표지도 인정한다: "(IMP-04, 원문 217행)", "LC-05:", "효과: RULE-09 (피고)", 머리글 끝 "(`RULE-G-06`)",
절 번호가 앞에 붙은 머리글 "### 4.2 RULE-RES-03 — …".
record_ids의 ID는 C5가 정의를 요구하지 않는다. 대신 C12가 출력에서 그 ID가 나오는 모든 자리 바로 앞(40자 안)에 부록 B 참조가 있는지 본다.
items로 남긴 표 행의 표 머리글에 '원문 … 문구' 칸이 있으면 OLD_WORDING_ROW 플래그로 알린다(옛 지시 문구 인용 가능성; 사람이 확인).
"""
import hashlib, json, os, re, sys, unicodedata
OMIT_LINE = "(제작 관리 기록 — 이 판에서 생략)"
ITEMS_LINES = {"res": "(본문이 연결한 미결 쟁점 행만 남겼다 — 나머지 제작 기록은 이 판에서 생략)",
"ref": "(본문이 가리킨 항목만 남겼다 — 나머지 제작 기록은 이 판에서 생략)",
"mix": "(본문이 가리킨 항목과 미결 쟁점 행만 남겼다 — 나머지 제작 기록은 이 판에서 생략)"}
FIXED_LINES = {OMIT_LINE, *ITEMS_LINES.values()}
NO_RESIDUE = ("", "없음", "—", "-", "–")
R_NUM = re.compile(r"(?:부록\s*|§)?(? ?', "", ln)
new = re.sub(r"\[([^\]\n]*)\]\(#[^)\n]*\)", r"\1", new)
new = re.sub(r"\[([^\]\n]*)\]\(https?://[^)\n]*\)", r"\1", new)
new = re.sub(r"(?:
|[ \t])*https?://[^\s|<)]+", "", new)
if new.startswith("|") and "http" in ln:
oc, nc = ln.split("|"), new.split("|")
if len(oc) == len(nc):
new = "|".join(" URL 삭제 " if (not c.strip() and "http" in oc[k]) else c for k, c in enumerate(nc))
return new
def clean(seg):
res = []
for ln in seg.split("\n"):
new = clean_line(ln)
if ln.strip() and not new.strip():
continue
res.append(new)
return re.sub(r"\n{3,}", "\n\n", "\n".join(res)).strip("\n")
def defs(s):
d = set()
for line in s.split("\n"):
line = re.sub(r'\s*', "", line).strip()
m = R_DEF.match(line)
if m:
d.add(m.group(1))
d.update(g for m in R_DEF_MID.finditer(line) for g in m.groups() if g)
for R in (R_DEF_HEAD, R_DEF_NUM):
m = R.match(line)
if m:
d.add(m.group(1))
return d
def ids(s):
return {m.group() for m in R_ID.finditer(s) if re.search(r"\d", m.group())}
def load(root, key):
rp, rn = find_raw(root, key)
t = open(rp, encoding="utf-8").read()
ref = open(os.path.join(root, "청구취지규칙문서_사건종류별", "청구취지작성규칙_%s.md" % key), encoding="utf-8").read()
ia, ib = t.find("\n## 부록 A") + 1, t.find("\n## 부록 B") + 1
assert 0 < ia < ib, "appendix boundary"
assert re.sub(r'', "", t[:ia]) == ref, "body != designated set"
B = t[ib:]
hs = [(m.start(), len(m.group(1)), m.group()) for m in R_HEAD.finditer(B)]
chunks = [] # 머리글부터 다음 머리글(단계 무관) 앞까지
for k, (s, lv, h) in enumerate(hs):
e = hs[k + 1][0] if k + 1 < len(hs) else len(B)
end_sub = next((s2 for s2, lv2, _ in hs[k + 1:] if lv2 <= lv), len(B))
parent = next((hs[q][2] for q in range(k - 1, -1, -1) if hs[q][1] < lv), None)
chunks.append({"heading": h, "level": lv, "start": ib + s, "end": ib + e, "sub_end": ib + end_sub, "parent": parent})
for c in chunks:
txt = t[c["start"]:c["sub_end"]]
ls = txt.split("\n")
hdrs = [re.sub(r'', "", ls[i]) for i in range(len(ls) - 1)
if ls[i].lstrip().startswith("|") and re.match(r"\s*\|[\s:|-]+\|\s*$", ls[i + 1]) and "-" in ls[i + 1]]
has_tbl = any(any(re.search(r"LEAF|Leaf|말단", x) for x in h.split("|")) and any(re.search(r"FORM|Form|문형", x) for x in h.split("|")) for h in hdrs)
c["default"] = "KEEP_SECTION" if (re.search(r"경로.{0,10}문형", c["heading"]) or has_tbl) else "DISCARD"
pre_b = t[ib:ib + hs[0][0]] if hs else B
return t, rn, ref, ia, ib, chunks, pre_b
def find_refs(t, spans):
out = []
for name, s0, e0 in spans:
seg = t[s0:e0] if isinstance(t, str) else t[name][s0:e0]
for R, kind in ((R_NUM, "num"), (R_NAME_B, "nameB"), (R_NAME_A, "nameA")):
for m in R.finditer(seg):
if kind != "num" and re.match(r"부록\s*[AB]\. ", seg[m.start():m.start() + 6]) and seg[max(0, m.start() - 3):m.start()].endswith("## "):
continue # 부록 머리글 자체
ctx = seg[max(0, m.start() - 80):m.end() + 40].replace("\n", " ")
out.append({"text": m.group(), "from": name, "at": s0 + m.start(), "context": ctx, "kind_re": kind,
"num": m.group(1) if kind == "num" else None})
return out
def heading_for_num(chunks, num):
hits = [c["heading"] for c in chunks if re.match(r"#{3,6} (?:부록\s*)?B\.?%s(?![\d.]*\d)(?:[ .]|$)" % re.escape(num), c["heading"])]
return hits[0] if len(hits) == 1 else None
def resolve(refs, chunks, rules):
res = []
for r in refs:
rule = next((x for x in rules if x["match"] in (r["text"] + " " + r["context"]) and x.get("from", "*") in ("*", r["from"])), None)
if r["kind_re"] == "nameA":
res.append(dict(r, kind="APPLY", target="## 부록 A")); continue
if rule:
res.append(dict(r, kind=rule["kind"], target=rule.get("target"))); continue
if r["kind_re"] == "num":
h = heading_for_num(chunks, r["num"])
res.append(dict(r, kind="RECORD" if h else "UNRESOLVED", target=h)); continue
res.append(dict(r, kind="UNRESOLVED", target=None))
return res
def cmd_inv(root, key, work):
t, rn, ref, ia, ib, chunks, pre_b = load(root, key)
keep = [c for c in chunks if c["default"] == "KEEP_SECTION"]
spans = [("body", 0, ia), ("A", ia, ib)] + [("B", c["start"], c["sub_end"]) for c in keep]
refs = resolve(find_refs(t, spans), chunks, [])
kept_txt = t[:ib] + "".join(t[c["start"]:c["sub_end"]] for c in keep)
kd = defs(kept_txt)
disc = [c for c in chunks if not any(k["start"] <= c["start"] < k["sub_end"] for k in keep)]
only = []
for x in sorted(ids(kept_txt) - kd):
for c in disc:
seg = t[c["start"]:c["end"]]
for line in seg.split("\n"):
m = R_DEF.match(re.sub(r'\s*', "", line).strip())
if m and m.group(1) == x:
only.append({"id": x, "section": c["heading"], "line": line[:400]}); break
else:
continue
break
body = t[:ia]
sel = "\n".join(l for l in body.split("\n") if "선택 기준" in l)
kb = "".join(t[c["start"]:c["sub_end"]] for c in keep)
lwf = sorted({m.group() for m in re.finditer(r"LEAF-[A-Za-z0-9-]*\d[A-Za-z0-9-]*", body)} - set(re.findall(r"LEAF-[A-Za-z0-9-]+", kb + sel)))
inv = {"key": key, "raw": rn, "chars": len(t), "body_end": ia, "appendix_a": [ia, ib],
"pre_b": {"chars": len(pre_b), "text": pre_b[:600]},
"b_sections": [dict({k: c[k] for k in ("heading", "level", "parent", "start", "end", "sub_end", "default")},
chars=c["end"] - c["start"], head300=t[c["start"]:c["start"] + 300]) for c in chunks],
"refs": [{k: r[k] for k in ("text", "from", "at", "context", "kind", "target")} for r in refs],
"ids_only_in_discarded": only, "leaf_without_form_default": lwf}
json.dump(inv, open(os.path.join(work, key + ".inv.json"), "w", encoding="utf-8"), ensure_ascii=False, indent=1)
print(json.dumps({"key": key, "sections": len(chunks), "default_keep": [c["heading"] for c in keep],
"refs": len(refs), "unresolved": sum(r["kind"] == "UNRESOLVED" for r in refs),
"ids_only_in_discarded": [o["id"] for o in only], "lwf": lwf}, ensure_ascii=False))
def item_block(seg, start_sub):
lines = seg.split("\n")
p = seg.index(start_sub)
li = seg[:p].count("\n")
ln = lines[li]
if ln.lstrip().startswith("|"):
a = li
while a > 0 and lines[a - 1].lstrip().startswith("|"):
a -= 1
return ("row", (a, a + 1), li)
if re.match(r"\s*(?:[-*]|\d+\.)\s", ln):
b = li + 1
while b < len(lines) and lines[b].startswith((" ", "\t")) and lines[b].strip():
b += 1
return ("list", li, b)
a = li
while a > 0 and lines[a - 1].strip():
a -= 1
b = li
while b < len(lines) and lines[b].strip():
b += 1
return ("para", a, b)
def residue_rows(seg):
"""'잔여' 칸이 있는 표에서 잔여가 남은 행의 줄 번호와 그 표의 머리글·구분 줄 번호."""
lines, picks, rows = seg.split("\n"), [], []
for i in range(len(lines) - 1):
if not (lines[i].lstrip().startswith("|") and re.match(r"\s*\|[\s:|-]+\|\s*$", lines[i + 1])):
continue
cells = [x.strip() for x in lines[i].strip().strip("|").split("|")]
col = next((n for n, x in enumerate(cells) if x.startswith("잔여")), None)
if col is None:
continue
j = i + 2
while j < len(lines) and lines[j].lstrip().startswith("|"):
cs = [x.strip() for x in lines[j].strip().strip("|").split("|")]
if col < len(cs) and cs[col] not in NO_RESIDUE:
rows.append(j)
j += 1
if any(i + 2 <= r < j for r in rows):
picks += [i, i + 1]
return picks, rows
def assemble(t, ref, ia, ib, chunks, pre_b, dec, referenced):
secs = dec.get("sections", {})
act = {}
for c in chunks:
d = secs.get(c["heading"], {})
act[c["heading"]] = d.get("action", c["default"])
# KEEP_SECTION/KEEP_UNSURE은 하위 절까지 포함
inside = set()
for c in chunks:
if act[c["heading"]] in ("KEEP_SECTION", "KEEP_UNSURE"):
for c2 in chunks:
if c["start"] < c2["start"] < c["sub_end"]:
inside.add(c2["heading"])
kept_any = {c["heading"] for c in chunks if act[c["heading"]] in ("KEEP_SECTION", "KEEP_UNSURE", "KEEP_ITEMS") or c["heading"] in inside}
need_head = set(referenced)
for c in chunks: # 남긴 하위 절의 상위 머리글은 남긴다
if c["heading"] in kept_any or c["heading"] in referenced:
p = c["parent"]
while p:
need_head.add(p)
p = next(x["parent"] for x in chunks if x["heading"] == p)
parts = [ref, clean(t[ia:ib]) + "\n\n"]
bh = t[ib:t.find("\n", ib)]
pre_body = t[t.find("\n", ib) + 1:ib + len(pre_b)]
parts.append(bh + "\n\n" + ((clean(pre_body) + "\n\n") if dec.get("pre_b") == "KEEP" and pre_body.strip() else ""))
decisions = []
for c in chunks:
h, a = c["heading"], act[c["heading"]]
d = secs.get(h, {})
if h in inside:
decisions.append({"heading": h, "action": "IN_KEPT_PARENT"})
parts.append(clean(t[c["start"]:c["end"]]) + "\n\n"); continue
if a in ("KEEP_SECTION", "KEEP_UNSURE"):
decisions.append({"heading": h, "action": a, "why": d.get("why", "기본 판정 ①·②")})
parts.append(clean(t[c["start"]:c["end"]]) + "\n\n"); continue
if a == "KEEP_ITEMS":
seg = t[c["start"]:c["end"]]
lines = seg.split("\n")
picks, rows = residue_rows(seg)
picks, items, n_res = picks + rows, [], len(set(rows))
for st in d.get("items", []):
kind, x, y = item_block(seg, st)
it = {"match": st[:60], "kind": kind}
if kind == "row":
a0, a1 = x
picks += [a0, a1, y]
it["quotes_raw"] = any(R_OLD_COL.match(c.strip()) for c in lines[a0].split("|"))
else:
picks += list(range(x, y))
items.append(it)
sel = sorted(set(picks))
txt, prev = [], None
for i in sel:
if prev is not None and i != prev + 1 and not (lines[i].startswith("|") and lines[prev].startswith("|")):
txt.append("")
txt.append(lines[i]); prev = i
body_txt = clean("\n".join(txt))
hk = h in need_head
ref_rows = {y if k == "row" else -1 for k, _, y in (item_block(seg, st) for st in d.get("items", []))} - set(rows)
kind = "mix" if n_res and ref_rows else ("res" if n_res else "ref")
decisions.append({"heading": h, "action": "KEEP_ITEMS", "heading_kept": hk, "items": items, "residue_rows": n_res, "line": kind, "why": d.get("why", "")})
parts.append(("%s\n\n%s\n\n%s\n\n" % (h, ITEMS_LINES[kind], body_txt)) if hk else body_txt + "\n\n"); continue
if h in need_head:
decisions.append({"heading": h, "action": "OMIT", "why": d.get("why", "가리켜진 제작 관리 기록 절")})
parts.append("%s\n\n%s\n\n" % (h, OMIT_LINE))
else:
decisions.append({"heading": h, "action": "DROP", "why": d.get("why", "제작 관리 기록; 가리키는 참조 없음")})
out = "".join(parts).rstrip("\n") + "\n"
return out, decisions, need_head, act, inside
def apply_patches(out, patches, regions=None):
for p in patches:
n, want = out.count(p["old"]), p.get("count", 1)
assert n == want, "patch old found %d times (want %d): %s" % (n, want, p["old"][:80])
if regions is not None:
regions.append("body" if out.find(p["old"]) < out.find("\n## 부록 A") else "appendix")
out = out.replace(p["old"], p["new"])
return out
def cmd_build(root, key, work, decp, outdir=None):
t, rn, ref, ia, ib, chunks, pre_b = load(root, key)
dec = json.load(open(decp, encoding="utf-8"))
rules = dec.get("refs", [])
referenced, seen = set(), None
for _ in range(10): # 닫힘
out, decisions, need_head, act, inside = assemble(t, ref, ia, ib, chunks, pre_b, dec, referenced)
# 본문·부록 A는 raw 위치로, 부록 B는 조립된 출력 안에서 찾는다(남긴 글만 대상, 고정 문구·머리글 줄 제외)
ob = out.find("\n## 부록 B") + 1
btxt = "\n".join("" if (l in FIXED_LINES or R_HEAD.match(l) or l.startswith("## 부록 B")) else l for l in out[ob:].split("\n"))
res = resolve(find_refs(t, [("body", 0, ia), ("A", ia, ib)]) + find_refs({"B": btxt}, [("B", 0, len(btxt))]), chunks, rules)
new_ref = {r["target"] for r in res if r["target"] and r["target"].startswith("###")}
if new_ref == seen:
break
seen, referenced = new_ref, new_ref
patches = dec.get("patches", [])
regions = []
out0, out = out, apply_patches(out, patches, regions)
# ---- 검사 ----
C, fail = {}, {}
if outdir:
od = os.path.join(root, outdir); ld = os.path.join(od, "_기록")
else:
od, ld = os.path.join(root, "청구취지규칙문서_사건종류별_부록정리"), os.path.join(root, "청구취지규칙문서_사건종류별_부록정리_기록")
os.makedirs(od, exist_ok=True); os.makedirs(ld, exist_ok=True)
op = os.path.join(od, "청구취지작성규칙_%s.md" % key)
open(op, "w", encoding="utf-8").write(out)
names = [unicodedata.normalize("NFC", n) for n in os.listdir(od)]
stray = [n for n in names if not re.match(r"청구취지작성규칙_.+\.md$", n) and not n.startswith("_")]
C["C1"] = os.path.exists(op) and not stray; fail["C1"] = stray
C["C2"] = out0[:out0.find("\n## 부록 A") + 1] == ref
want = [d["heading"] for d in decisions if d["action"] in ("KEEP_SECTION", "KEEP_UNSURE", "OMIT", "IN_KEPT_PARENT") or d.get("heading_kept")]
got = [m.group() for m in R_HEAD.finditer(out[out.find("\n## 부록 B"):])]
C["C3"] = want == got and "\n## 부록 B" in out and all(h in got for h in referenced); fail["C3"] = [want, got] if not C["C3"] else []
heads_out = set(m.group().strip() for m in re.finditer(r"(?m)^#{2,6} .*$", out))
bad = [r for r in res if r["kind"] == "UNRESOLVED" or (r["kind"] in ("APPLY", "RECORD") and r["target"] not in ("## 부록 A", "## 부록 B") and r["target"] not in heads_out)]
C["C4"] = not bad; fail["C4"] = [{k: r[k] for k in ("text", "from", "at", "context", "kind", "target")} for r in bad][:40]
rec = dec.get("record_ids", {})
lost0 = (ids(out) & defs(t)) - defs(out)
lost = sorted(lost0 - set(rec))
C["C5"] = not lost; fail["C5"] = lost
bad12 = ["unneeded:" + x for x in rec if x not in lost0]
for x in sorted(set(rec) & lost0): # 부록 B 기록 위치 표지로만 쓰였는지
for m in re.finditer(r"(?