from pathlib import Path import re, json, hashlib, xml.etree.ElementTree as ET, subprocess root=Path.cwd(); key='진정명의회복을등기원인으로하는소유권이전등기청구' work=root/f'tmp/규칙문서재작성_{key}_20260913_batch5' snap=json.loads((work/'snapshot.json').read_text()) source=Path(snap['source']).read_text(); draft=(work/'draft.md').read_text() sl=source.splitlines(); dl=draft.splitlines(); fmt=root/'1. 베타 0.5 다듬기/output_format_v1.txt'; xml=ET.fromstring(fmt.read_text()) assert not (work/'audit_once.json').exists(), 'Single audit already run' def add(path,text): patch='*** Begin Patch\n*** Add File: '+str(path.relative_to(root))+'\n'+''.join('+'+l+'\n' for l in text.splitlines())+'*** End Patch\n' subprocess.run(['apply_patch',patch],check=True,capture_output=True) def plain(s): return re.sub(r'[`*]','',s).strip() def norm(s): return re.sub(r'\s+','',plain(s)) heads=[] for i,l in enumerate(dl,1): if l.startswith('##'): heads.append((i,l)) def loc(lineno): return next((h for n,h in reversed(heads) if n<=lineno),'제목')+f' / L{lineno}' units=[]; formatting=[]; oldsec=0; oldid=''; incode=False for no,l in enumerate(sl,1): if re.match(r'^## \d+\.',l): oldsec=int(re.match(r'^## (\d+)',l).group(1)) ids=re.match(r'^### ((?:Q|RULE|FORM|CHECK)-T\d+)',l) if ids: oldid=ids.group(1) if l.startswith('```'): incode=not incode; formatting.append(no);continue if not l.strip() or l=='---' or l.startswith('#') or re.fullmatch(r'[|: -]+',l):formatting.append(no);continue if l.startswith('|'): cells=[c.strip() for c in l.strip('|').split('|')] if cells[0] in ['항목','판정','입력 ID','경로','원고/등기권리자','상황','Leaf ID','Code','Evidence ID']: formatting.append(no);continue chunks=cells else: text=re.sub(r'^(?:- \[ \] |- |\d+\. )','',l).strip() chunks=re.split(r'(?<=[다요음임])\.\s+',text) if not incode else [text] for ci,c in enumerate(chunks,1): if not c:continue currentid=next(iter(re.findall(r'(?:IN|STOP|E|LEAF)-T\d+',l)),oldid) target=[] for n,d in enumerate(dl,1): if norm(c) and norm(c) in norm(d):target.append((n,d)) # prefer the corresponding definition or body, not history summaries desired={0:'0',1:'1',2:'2',3:'2',4:'3',5:'3',6:'4',7:'4',8:'B',9:'5',10:'7',11:'A',12:'7'}[oldsec] def score(t): h=loc(t[0]);return (0 if currentid and currentid in h else 1,0 if re.search(r'## (?:부록 )?'+desired+r'[. ]',h) else 1,t[0]) target.sort(key=score) units.append({'id':f'U{len(units)+1:04}','source_line':no,'cell':ci,'old_section':oldsec,'old_id':currentid,'text':c,'destination':loc(target[0][0]) if target else None,'method':'직접 원문·문맥 대조' if target else '변환 문맥 대조 필요'}) checks=[] def check(label,val,detail=''): checks.append({'name':label,'pass':bool(val),'detail':detail}) check('UTF-8',draft.encode().decode()==draft) check('top headings',re.findall(r'^## (.*)$',draft,re.M)==['0. 메타데이터와 사용법','1. 청구권·사실정보 연결과 보완','2. 유형 선택과 작성 경로','3. 당사자·대상·범위의 작성 규칙','4. 금액·기간·조건·부수청구','5. 표준 문형과 조립','6. 청구원인 작성 단계에 전달할 사항','7. 진행·보완·전환·중단 기준','부록 A. 근거와 적용 제한','부록 B. 문서 관리·제작 검증']) check('title',dl[0]=='# '+snap['identity']+' — 청구취지 작성 규칙') check('metadata four',len(re.findall(r'^\| (사건종류|사건키|적용범위|적용제외) \|',draft,re.M))==4) check('fences',sum(l.startswith('```') for l in dl)%2==0) check('template residue',not re.search(r'CASE_KEY|CASE_DISPLAY_NAME|RUN_ID|\$\{',draft)) for family in ['IN','Q','RULE','LEAF','FORM','STOP','E','CHECK']: a=set(re.findall(r'\b'+family+r'-T\d+',source));b=set(re.findall(r'\b'+family+r'-T\d+',draft)) check(family+' IDs',a==b,f'{len(a)} / {len(b)}') urls=lambda t:set(re.findall(r'https?://[^\s|)<>]+',t)) check('URLs',urls(source)<=urls(draft),str(len(urls(source)))) check('dates',set(re.findall(r'\d{4}-\d{2}-\d{2}',source))<=set(re.findall(r'\d{4}-\d{2}-\d{2}',draft))) for p,v in snap['hashes'].items(): check('input hash '+p,hashlib.sha256((root/p).read_bytes()).hexdigest()==v['sha256']) fields=['선택 기준','작성 전에 연결할 정보','법적 전제','미확인 처리','주문 문장','조립','사용 금지 조건','근거','검토'] for i in range(1,10): id_=f'FORM-T{i:02}' body=re.search(r'^### '+id_+r'.*?\n(.*?)(?=^### |^## |\Z)',draft,re.M|re.S).group(1) check(id_+' 9 fields',all('- '+f+':' in body for f in fields)) old=re.search(r'^### '+id_+r'.*?```text\n(.*?)\n```',source,re.M|re.S).group(1) new=re.search(r'```text\n(.*?)\n```',body,re.S).group(1) check(id_+' order',old==new) check('five states',all(s in draft for s in ['작성 진행','재검토를 붙여 진행','해당 부분 보완 대기','다른 구성·절차로 전환','해당 구성 중단'])) check('URL ban','우회 원문 수집도 금지' in draft) check('status split','작성 상태는' in draft and '검토 상태는' in draft) check('table pipes',all(l.count('|')>=3 for l in dl if l.startswith('|'))) format_units=[] def walk(el,path): children=list(el) if el.attrib:format_units.append({'id':f'F{len(format_units)+1:03}','xpath':path,'text':str(el.attrib),'kind':'구조·속성'}) if not children:format_units.append({'id':f'F{len(format_units)+1:03}','xpath':path,'text':el.text.strip(),'kind':'요구본문'}) counts={} for child in children: counts[child.tag]=counts.get(child.tag,0)+1 walk(child,path+'/'+child.tag+f'[{counts[child.tag]}]') walk(xml,'/output_format') add(work/'audit_once.json',json.dumps({'units':units,'formatting_lines':formatting,'format':format_units,'checks':checks},ensure_ascii=False,indent=2)) print('units',len(units),'formatting lines',len(formatting),'format requirements',len(format_units),'checks',len(checks),'failed',[c for c in checks if not c['pass']]) print('MANUAL TRANSFORM UNITS') for u in units: if not u['destination']:print(u['id'],u['source_line'],u['text'])