from pathlib import Path import csv,json,platform,datetime,sys HERE=Path(__file__).resolve().parent def clean(value):return str(value or '').strip() def read_csv(root,name): with (root/'input'/f'{name}.csv').open(encoding='utf-8-sig',newline='') as f:return list(csv.DictReader(f)) def hashfile(path): import hashlib return hashlib.sha256(path.read_bytes()).hexdigest() def known(value):return clean(value).lower() not in {"","미확인","unknown"} REPORT_HEADERS=['원본 참조', '판정', '누락키'] def compute(root=HERE): a,b=read_csv(root,'A'),read_csv(root,'B');kept=[];exact=[];conflicts=[];seen={};rows=[] for source,table in [('A',a),('B',b)]: for i,r in enumerate(table,1): key=(clean(r.get('request')),clean(r.get('time')));ref=f'{source}:{i}';missing=[field for field,value in zip(['request','time'],key) if not value] if missing:conflicts.append({'row':ref,'key':'|'.join(key),'different_fields':[],'missing_fields':missing});rows.append([ref,'검토',' / '.join(missing)]);continue comparable=dict(r);comparable['request'],comparable['time']=key if key not in seen:seen[key]=comparable;kept.append(ref);rows.append([ref,'유지','']) elif seen[key]==comparable:exact.append(ref);rows.append([ref,'완전 사본','']) else:conflicts.append({'row':ref,'key':'|'.join(key),'different_fields':[k for k in comparable if comparable[k]!=seen[key][k]]});rows.append([ref,'충돌 검토','']) actual={'input_rows':len(a)+len(b),'kept_rows':kept,'exact_copies':exact,'review_conflicts':conflicts,'R014_history_rows':sum(r['request']=='R014' for r in seen.values())} return actual,rows,{'policy':'Request/time must be known before automatic duplicate comparison. Only judgment keys are trimmed;location and note text are preserved.'} def run(root=HERE): try:actual,rows,details=compute(root) except ValueError as exc: report={'lab_id':root.name,'status':'INPUT_ERROR','actual':None,'input_error':str(exc),'assertion_count':0} (root/'results.json').write_text(json.dumps(report,ensure_ascii=False,indent=2),encoding='utf-8') (root/'actual.json').write_text('null',encoding='utf-8') with (root/'results.csv').open('w',encoding='utf-8-sig',newline='') as f:csv.writer(f).writerows([['입력 검토 필요'],[str(exc)]]) print(json.dumps(report,ensure_ascii=False));return report expected=json.loads((root/'expected/report.json').read_text(encoding='utf-8')) checks=[{'field':k,'pass':actual.get(k)==v,'actual':actual.get(k),'expected':v} for k,v in expected.items()] passed=all(c['pass'] for c in checks) and set(actual)==set(expected) report={'lab_id':root.name,'synthetic_fixture':True,'environment':{'python':platform.python_version(),'platform':platform.system(),'processor':'Python standard library'},'run_utc':datetime.datetime.now(datetime.timezone.utc).isoformat(),'status':'PASS' if passed else 'FAIL','assertion_count':len(checks),'actual':actual,'assertions':checks,'details':details,'limits':'Synthetic record checks only;not a real building inspection,safety/legal verdict,Excel app test,physical receipt or authenticity verification.'} (root/'results.json').write_text(json.dumps(report,ensure_ascii=False,indent=2),encoding='utf-8') (root/'actual.json').write_text(json.dumps(actual,ensure_ascii=False,indent=2),encoding='utf-8') with (root/'results.csv').open('w',encoding='utf-8-sig',newline='') as f: w=csv.writer(f);w.writerow(REPORT_HEADERS);w.writerows(rows) print(json.dumps(report,ensure_ascii=False,indent=2)) return report if __name__=='__main__': report=run() if report['status']!='PASS':raise SystemExit(1)