import json,re from pathlib import Path base=Path(r"C:\Apache24\htdocs\.codex_tmp") main=json.loads((base/'ocr_candidates.json').read_text(encoding='utf-8')) retry=json.loads((base/'ocr_retry_results.json').read_text(encoding='utf-8-sig')) trans=str.maketrans('٠١٢٣٤٥٦٧٨٩۰۱۲۳۴۵۶۷۸۹','01234567890123456789') retry_by_id={} for r in retry: sid=int(r['file'].split('_')[1]); text=(r.get('text') or '').translate(trans) candidates=[] for idx,line in enumerate(text.split('|')): digits=re.sub(r'\D','',line) if 6<=len(digits)<=9: candidates.append({'value':digits,'line':idx}) retry_by_id[sid]={'text':text,'candidates':candidates} for r in main: if not r['chosen']: rr=retry_by_id.get(r['id'],{}) c=rr.get('candidates',[]) # The document number is printed at the top and normally appears in the first OCR lines. early=[x for x in c if x['line']<=2] if early: r['chosen']=early[0]['value']; r['source']='full-early' else: r['source']='unresolved' r['retry_candidates']=c else: r['source']='top-crop' (base/'ocr_merged.json').write_text(json.dumps(main,ensure_ascii=False,indent=2),encoding='utf-8') print(json.dumps({'resolved':sum(bool(r['chosen']) for r in main),'unresolved':sum(not r['chosen'] for r in main),'retry_any_candidates':sum(bool(retry_by_id.get(r['id'],{}).get('candidates')) for r in main if r['source']=='unresolved')},ensure_ascii=False))