Spaces:
Running
Running
Deploy Cham-OCR V26.2: Archival Polarity Fix, 2-Column Divider Barrier, Safe Deskew, Detector Provenance, Auto Router v2.3 & Studio JSON Import
Browse filesFiles changed (6)
117 unmodified lines118119120121122123117 unmodified lines- **Independent Confirmation of `V26.1` (`1deee5f5ff351070`)**: Achieved **`6.71%` Micro CER** on `frozen` (`-0.92` percentage points vs. `2026-11-20` `85525b0ca091acaf` `7.63%`, beating `V24` `28–0` and `R3.1` `15–6`), **`3.07%` E2E CER** (`25/25` lines) on real camera `harum_palei_01`, **`4.04%` CER** across 9 stress degradations, **`100%` (`42/42`)** on 14 mandatory symbols, **`100%` (`21/21` count; positional alignment pending Priority B)** on 7 hyphen contexts, **`0%` Latin script leakage**, and **`0/4` blank/ruled/speckle false positives**.- **Closed Backend API Contract & Exact Per-Line Provenance (`ocr-studio/app.py`, Priority A)**: Enforced `ALLOWED_MODEL_IDS` allowlist validation (eliminating silent HTTP `200` fallback to `v23` on unknown model IDs and deriving `recognizers[].version` strictly from on-disk manifests), guarded `POST /ocr` against missing `image` keys (HTTP `400` JSON instead of `502`), rejected invalid `method` / `reading_order` / degenerate `bbox` (`x2 <= x1` or out-of-bounds) with HTTP `400`, propagated exact `routed_version` through both Pass 1 and Pass 2 (`seen_boxes` + `deferred_copies`) of `segment_lines_advanced()` (`valley`/`adaptive`) while removing all post-OCR Unicode character-based recognizer guessing, and reclassified `v25` under `Historical Baselines` (`V25 Bilingual (Legacy)`). While `v25` matches its exported 162-token dictionary and dynamic `pool2d(stride=[3,2])` PIR graph yet exhibits `49.81%` E2E CER and `280` leaked Latin letters across `21/29` Cham pages on `frozen`, exact causal attribution among domain shift, unmasked `W=480` resize, expanded 162-token CTC space, and crop preprocessing remains open pending single-factor controlled ablations.- **`Auto Router v2.2` & Paired Cham Digit Control Check**: Added a low-Cham-ratio (`c_ratio < 0.35`) Latin+digit handoff branch to `AutoRoutingOCRWrapper` (`vietnamese_00` CER cut from `26.02% -> 4.88%` with all 3 lines routed to `vi`, while intra-line Cham–Latin code-switching remains open). On Cham numerals (`U+AA50..U+AA59`), paired re-testing on tight ink crops (`ImageOps.invert(...).getbbox()`, preserving historical `2026-11-22/digits` artifacts untouched) lowered `v24_1_r4` CER from `14.0% -> 6.0%` (`33.33% -> 75.0%` exact), demonstrating that `8.0` percentage points stemmed from horizontally compressing an uncropped `1100x100` white canvas into `W=480` while **`6.0%` CER (`3/12` lines) remains genuine recognition error** on dense Cham numeral strings.---117 unmodified lines118119120121122123124125126127117 unmodified lines- **Independent Confirmation of `V26.1` (`1deee5f5ff351070`)**: Achieved **`6.71%` Micro CER** on `frozen` (`-0.92` percentage points vs. `2026-11-20` `85525b0ca091acaf` `7.63%`, beating `V24` `28–0` and `R3.1` `15–6`), **`3.07%` E2E CER** (`25/25` lines) on real camera `harum_palei_01`, **`4.04%` CER** across 9 stress degradations, **`100%` (`42/42`)** on 14 mandatory symbols, **`100%` (`21/21` count; positional alignment pending Priority B)** on 7 hyphen contexts, **`0%` Latin script leakage**, and **`0/4` blank/ruled/speckle false positives**.- **Closed Backend API Contract & Exact Per-Line Provenance (`ocr-studio/app.py`, Priority A)**: Enforced `ALLOWED_MODEL_IDS` allowlist validation (eliminating silent HTTP `200` fallback to `v23` on unknown model IDs and deriving `recognizers[].version` strictly from on-disk manifests), guarded `POST /ocr` against missing `image` keys (HTTP `400` JSON instead of `502`), rejected invalid `method` / `reading_order` / degenerate `bbox` (`x2 <= x1` or out-of-bounds) with HTTP `400`, propagated exact `routed_version` through both Pass 1 and Pass 2 (`seen_boxes` + `deferred_copies`) of `segment_lines_advanced()` (`valley`/`adaptive`) while removing all post-OCR Unicode character-based recognizer guessing, and reclassified `v25` under `Historical Baselines` (`V25 Bilingual (Legacy)`). While `v25` matches its exported 162-token dictionary and dynamic `pool2d(stride=[3,2])` PIR graph yet exhibits `49.81%` E2E CER and `280` leaked Latin letters across `21/29` Cham pages on `frozen`, exact causal attribution among domain shift, unmasked `W=480` resize, expanded 162-token CTC space, and crop preprocessing remains open pending single-factor controlled ablations.- **`Auto Router v2.2` & Paired Cham Digit Control Check**: Added a low-Cham-ratio (`c_ratio < 0.35`) Latin+digit handoff branch to `AutoRoutingOCRWrapper` (`vietnamese_00` CER cut from `26.02% -> 4.88%` with all 3 lines routed to `vi`, while intra-line Cham–Latin code-switching remains open). On Cham numerals (`U+AA50..U+AA59`), paired re-testing on tight ink crops (`ImageOps.invert(...).getbbox()`, preserving historical `2026-11-22/digits` artifacts untouched) lowered `v24_1_r4` CER from `14.0% -> 6.0%` (`33.33% -> 75.0%` exact), demonstrating that `8.0` percentage points stemmed from horizontally compressing an uncropped `1100x100` white canvas into `W=480` while **`6.0%` CER (`3/12` lines) remains genuine recognition error** on dense Cham numeral strings.12. **Priority B Controlled 5-Module Diagnostic Suite (`2026-11-22`, `REPORTS/priority_b_diagnostics_2026_11_22/PRIORITY_B_DIAGNOSTIC_REPORT_VI.md`)**: Executed `132` non-destructive live probes isolating detector vs. recognizer error, strict vs. pre-registered philological CER, genuine two-column `auto` reading order, intra-line bilingual & `V25` width isolation, and safe-border deskew:- **`synthetic_142` & `uncovered_ink_ratio` Root Cause**: Decomposed `synthetic_142`'s `23.84%` CER (`87` edits) into `74.71%` (`65` edits) from missed `GT[1]` (`y=[73,107]`) and `25.29%` (`22` edits, `7.48%` Matched-Line CER) on the `7` matched lines; identified that `compute_uncovered_ink()`'s `0.25 * median_line_h = 11px` vertical box dilation bridged across the missed `34px` line (`uncovered_ink_ratio = 0.0`). On `Frozen-30`, Strict Matched-Line CER is `5.80%` vs. `5.13%` Philological CER (`9.23%` genuine equivalences).- **Two-Column Reading Order, Intra-Line Bilingual & Safe-Border Deskew**: Verified Kendall's $\tau = 1.000$ (`5/5` 2-column pages; clean 2-col CER `69.96% -> 3.70%` under `auto`), isolated `Auto Router v2.2`'s `33.33%` CER on intra-line Cham–Vietnamese lines and `c_conf < 0.85` gate miss on `Năm 2000-2025`, falsified the single-cause `V25` `use_valid_mask` hypothesis (`41.67%` CER even at `0%` right-padding `ar48 ≈ 465`), and demonstrated safe-border deskew cutting `-11°` `synthetic_167` CER `40.0% -> 4.62%` (`harum_palei_01` `-14°` `8.27% -> 2.36%`, gated at `|θ| >= 9°`).13. **`RealScan-Gold v4` Multi-Source Physical Archival Corpus (`2026-11-22`, `ocr-benchmark/data/realscan_gold_v4/manifest.json`, `REPORTS/REALSCAN_GOLD_V4_COLLECTION_REPORT_VI.md`)**: Harvested **`56` new authentic physical pages (`1,023` pre-segmented draft lines)** across **`25` independent manuscripts & historical printed monographs** (`57` multi-line physical pages + `7` Wikimedia specimens across **`27` independent sources** total, `synthetic_pages_included = 0`) spanning palm-leaf *agal* (`8`), traditional handmade/*Đại*/*Quyến*/Chinese paper (`23`), 20th-century cement-bag/notebook/newspaper/A4/scroll substrates (`13`), and 1889/1906 lithographed & 2-column intra-line bilingual printed books (`12`), under a strict **2-Tier Anti-Circular Ground-Truth Protocol** (`gt: null` on all `staging_review_queue` pages until human sign-off via `scripts/ingest_studio_to_realscan_gold.py --version v4 --promote-verified`) and gitignored binary storage honoring British Library EAP terms.---
238 unmodified lines23924024124224324485 unmodified lines3303313323333343353363373383393403413 unmodified lines3453463473483493503517 unmodified lines3593603613623633643653664 unmodified lines3713723733743753763773783793803813824 unmodified lines387388389390391392138 unmodified lines531532533534535536537538539540541542238 unmodified lines78178278378478578678778878979067 unmodified lines858859860861862863185 unmodified lines10491050105110521053105410551056105710581059106019 unmodified lines108010811082108310841085220 unmodified lines1306130713081309131013111312131324 unmodified lines13381339134013411342134313441345134613471348134913501351135247 unmodified lines14001401140214031404140514061407139 unmodified lines15471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569100 unmodified lines167016711672167316741675167616771678167916801681168216831036 unmodified lines2720272127222723272427252726272727287 unmodified lines273627372738273927402741274227432744274527462747274827492750275127522753275462 unmodified lines281728182819282028212822282328246 unmodified lines283128322833283428352836283723 unmodified lines2861286228632864286528662867238 unmodified lines_ROUTER_ILLEGAL_MEDIAL_RE = re.compile(r'[\uAA33\uAA34]{2,}|[\uAA2F\uAA30]{2,}')_ROUTER_EDITORIAL_SYMS = set('-/_*[]{}<>=+%@#')def _cham_script_ratio(text):85 unmodified linesbest_cham.append((chosen_txt, chosen_conf))best_cham_ver.append(chosen_ver)# 3. Selective Vietnamese / Latin multiscript handoff ONLY when Cham CTC emits non-Cham soup or severe uncertaintyviet_indices = []viet_imgs = []for i, (c_txt, c_conf) in enumerate(best_cham):c_ratio = _cham_script_ratio(c_txt)if (c_ratio < 0.62 and c_conf < 0.85) or c_conf < 0.34:viet_indices.append(i)viet_imgs.append(img_list[i])3 unmodified linesfor idx_orig, v_res in zip(viet_indices, viet_batch):viet_map[idx_orig] = v_res# 4. Script-aware adjudication preventing false Vietnamese takeover on historical Cham manuscriptsfinal_results = [None] * len(img_list)selected_vers = []for i in range(len(img_list)):7 unmodified linesv_txt, v_conf = viet_map[i]v_conf = float(v_conf)c_ratio = _cham_script_ratio(c_txt)v_alpha = _latin_alpha_ratio(v_txt)v_lat_cnt = _latin_alpha_count(v_txt)take_viet = Falseif v_alpha >= 0.42:4 unmodified lines# Coherent Cham script present -> protect historical Cham folios unless Vi is overwhelmingly confidenttake_viet = (c_conf < 0.50 and v_conf >= 0.88 and v_alpha >= 0.70)elif c_ratio < 0.35 and v_lat_cnt >= 2 and (v_alpha >= 0.18 or _has_viet_diacritics(v_txt)):# Digit/punctuation-heavy Vietnamese lines (e.g. "Số trang: 0123456789, dấu ! ? : ; ( ) / -")# where Cham CTC emits non-Cham bracket/digit soup while Vi decodes valid Latin words + numberstake_viet = (v_conf >= 0.55 and v_conf >= c_conf - 0.05)elif c_conf < 0.25 and v_conf > c_conf + 0.25:take_viet = Trueif take_viet:final_results[i] = (v_txt, v_conf)selected_vers.append('vi')4 unmodified linesself.last_selected_versions = list(selected_vers)return final_results, list(selected_vers), 0.0def __call__(self, img_list):results, _, elapsed = self.predict_with_provenance(img_list)return results, elapsed138 unmodified linesargs.rec_image_shape = str(manifest_for_shape.get("rec_image_shape") or default_rec_shape)args.use_space_char = True# Batch size config: default to 1 on CPU to prevent padding latency blowup from varying crop aspect ratiosenv_batch = os.getenv("OCR_REC_BATCH_SIZE")if env_batch:ocr_rec_batch_size = int(env_batch)else:ocr_rec_batch_size = 1 if not paddle.is_compiled_with_cuda() else 16args.rec_batch_num = ocr_rec_batch_size238 unmodified linesxm = (ox1 + ox2) / 2.0return abs(f1(xm) - f2(xm)) > ratio * tdef merge_line_boxes(boxes, img_w, img_h):"""Merges horizontally separated bounding boxes on the same line into a single unified line crop.Prevents splitting a single line into separate fragments across distant words."""if boxes is None or len(boxes) == 0:return []67 unmodified linesif h_overlap > 0.25 and _stacked_by_centerline(r1[4], r2[4], max(r1[0], r2[0]), min(r1[2], r2[2])):continueif v_overlap >= 0.50 and x_dist <= max(40.0, 2.5 * min_h):new_x1 = max(0.0, min(r1[0], r2[0]))new_x2 = min(float(img_w), max(r1[2], r2[2]))185 unmodified linescnt = cv2.approxPolyDP(cnt, 1.0, True).reshape(-1, 2).astype(np.float32) + offreturn _ribbon_info(cnt)def merge_line_polygons(polys, img_w, img_h):"""Polygon counterpart of merge_line_boxes() for Cham-DBNet box_type='poly'.Fragments of one curved line (shared, extrapolated centerline) are merged into one curved polygon;vertically stacked wavy lines are never merged even though their AABBs overlap (the decision usesribbon centerlines / thickness, not AABB heights). Detached micro-diacritic specks next to a full lineare suppressed as in merge_line_boxes. Returns polygons sorted by centerline y."""items = []19 unmodified linesfor j in range(i + 1, len(items)):if used[j]:continueif _ribbons_same_line(r1, items[j]):r1 = _merge_ribbon_polys(r1, items[j])used[j] = True220 unmodified linesz = math.log(p / (1.0 - p))return round(1.0 / (1.0 + math.exp(-z / T)), 6)def get_model_info(model_ver):"""Returns provenance info (model id, weight fingerprints, detector, normalizer) for the response."""info = {"model": model_ver, "normalizer": None}rec_versions = [DEFAULT_CHAM_MODEL, 'v24_1_r3_1', 'vi'] if model_ver == 'auto' else [model_ver]recs = []24 unmodified lineselif v in ocr_models and isinstance(ocr_models.get(v), OfficialPaddleOCRWrapper):recs.append({"version": v, "model_dir": None, "wrapper": "OfficialPaddleOCRWrapper"})info["recognizers"] = recsif not det_model_info:info["detector"] = {"name": None, "mode": DET_MODE, "loaded": False}else:info["detector"] = {"name": det_model_info.get("name"), "mode": det_model_info.get("mode"), "loaded": True,"weights_sha256_16": _file_fingerprint(os.path.join(det_model_info.get("dir", ""), "inference.pdiparams")),# Exposed so a deployment can be verified: False means the fine-tuned Cham-DBNet# failed to load (e.g. PIR model on an old Paddle) and only the legacy detector runs."cham_dbnet_available": cham_det_model is not None,"cham_dbnet_sha256_16": _file_fingerprint(os.path.join(CHAM_DET_DIR, "inference.pdiparams")) if cham_det_model is not None else None,"cham_dbnet_box_type": ("poly" if _is_poly_detector(cham_det_model) else "quad") if cham_det_model is not None else None}try:import paddle as _paddle47 unmodified linescover = np.zeros((h, w), dtype=np.uint8)for poly in polygons:cv2.fillPoly(cover, [np.round(np.array(poly, dtype=np.float32)).astype(np.int32)], 1)pad = int(max(3, round(0.25 * median_line_h))) if median_line_h else 5cover = cv2.dilate(cover, np.ones((2 * pad + 1, 2 * pad + 1), np.uint8))total, uncovered, idxs = 0, 0, []for i in range(len(stats)):ch, area = stats[i, cv2.CC_STAT_HEIGHT], stats[i, cv2.CC_STAT_AREA]139 unmodified linesdef check_inverted_polarity(img):"""Detects if an image has inverted polarity (light/white text on dark/colored background)."""if img is None or img.size == 0:return Falsegray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) if len(img.shape) == 3 else imgh, w = gray.shape[:2]pad_h = max(1, int(h * 0.05))pad_w = max(1, int(w * 0.05))border = np.concatenate([gray[0:pad_h, :].flatten(),gray[-pad_h:, :].flatten(),gray[:, 0:pad_w].flatten(),gray[:, -pad_w:].flatten()])bg_val = float(np.median(border))fg_val = float(np.percentile(gray, 95))return bool(bg_val < 145 and (fg_val - bg_val) > 35)def preprocess_crop_for_rec(crop_img):"""100 unmodified linesis_inverted = check_inverted_polarity(img)det_img = (255 - img) if is_inverted else imgh, w = img.shape[:2]def _detect(detector):boxes, _ = detector(det_img)if _is_poly_detector(detector):boxes = [] if boxes is None else [np.array(b, dtype=np.float32).reshape(-1, 2) for b in boxes]return merge_line_polygons(boxes, w, h)boxes = [] if boxes is None else [np.array(b, dtype=np.float32) for b in boxes]return merge_line_boxes(boxes, w, h)def _coverage(boxes):"""(uncovered ink ratio, max box height / glyph height) for a candidate box set.1036 unmodified lines}doc_reasons = []doc_extra = {}if method == 'dbnet':ink = analyze_text_ink(img)doc_extra['ink_ratio'] = round(ink['ink_ratio'], 5)if is_blank_page(ink):# No text-like ink: never hallucinate a line on blank / near-blank paper7 unmodified linestry:det = get_det_model()final_crops, lines_metadata, det_info = segment_lines_dbnet(img, det, ink=ink, return_info=True, reading_order=reading_order)except Exception:import tracebackprint(f"❌ DBNet segmentation error: {traceback.format_exc()}")final_crops, lines_metadata = [], []base_segmentation_sec = time.time() - t_segif det_info:doc_extra['layout'] = det_info.get('layout')doc_extra['uncovered_ink_ratio'] = det_info.get('uncovered_ink_ratio')profiler_dict['det_lines'] = det_info.get('lines_detected')profiler_dict['detector'] = det_info.get('detector')profiler_dict['detector_switched'] = det_info.get('detector_switched')profiler_dict['uncovered_ink_ratio_primary'] = det_info.get('uncovered_ink_ratio_primary')if not final_crops:62 unmodified linesif not cal_ver and model_ver != 'auto':cal_ver = resolve_actual_model_version(model_ver)if (cal_ver and cal_ver not in ('vi', 'en', 'fr', 'japan')) and (cal_ver in ('v24', 'v25', 'v26') or str(cal_ver).startswith('v24')):if any('\uAA00' <= ch <= '\uAA5F' for ch in (pred_text or '')):try:6 unmodified lines_, buffer = cv2.imencode('.png', line_img)line_b64 = base64.b64encode(buffer).decode('utf-8')cal_conf = calibrate_line_confidence(confidence, cal_ver, pred_text)# Backward-compatible format with explicit per-line recognizer provenanceresults.append({23 unmodified linesprofiler_dict['backend_total_sec'] = round(time.time() - t_start, 4)profiler_dict['base_segmentation_sec'] = round(base_segmentation_sec, 4)document = build_document_status(results, doc_reasons, doc_extra)return {'lines': results, 'profiler': profiler_dict, 'document': document, 'model_info': get_model_info(model_ver)}def save_correction_entry(data, base_dir=None):"""Persists a verified/corrected text line to legacy ocr_corrections.txt and Stage R4 active learning storage."""238 unmodified lines23924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536685 unmodified lines4524534544554564574584594604614624634644653 unmodified lines4694704714724734744757 unmodified lines4834844854864874884894904914924 unmodified lines4974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435444 unmodified lines549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631138 unmodified lines770771772773774775776777778779780781782238 unmodified lines1021102210231024102510261027102810291030103167 unmodified lines1099110011011102110311041105110611071108185 unmodified lines129412951296129712981299130013011302130313041305130619 unmodified lines132613271328132913301331133213331334220 unmodified lines1555155615571558155915601561156224 unmodified lines158715881589159015911592159315941595159615971598159916001601160216031604160547 unmodified lines16531654165516561657165816591660166116621663139 unmodified lines1803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938100 unmodified lines20392040204120422043204420452046204720482049205020512052205320542055205620572058205920601036 unmodified lines30973098309931003101310231033104310531063107310831093110311131127 unmodified lines312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315662 unmodified lines3219322032213222322332243225322632276 unmodified lines323432353236323732383239324023 unmodified lines3264326532663267326832693270327132723273327432753276327732783279238 unmodified lines_ROUTER_ILLEGAL_MEDIAL_RE = re.compile(r'[\uAA33\uAA34]{2,}|[\uAA2F\uAA30]{2,}')_ROUTER_EDITORIAL_SYMS = set('-/_*[]{}<>=+%@#')_ROUTER_GIBBERISH_TOKEN_RE = re.compile(r'(?:[a-z\u00E0-\u1EF9][A-Z]'r'|[A-Z\u00C0-\u01AF]{2,}[a-z\u00E0-\u1EF9]'r'|[A-Za-z\u00C0-\u1EF9]+[0-9]+[A-Za-z0-9\u00C0-\u1EF9]*'r'|[0-9]+(?!(?:er|e|st|nd|rd|th)\b)[A-Za-z\u00C0-\u1EF9]+'r'|\bZ[BCDFGHJKLMNPQRSTVWXYZ\u00C0-\u1EF9]'r'|\bXX\)'r'|[BCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz]{5,})')_ROUTER_CHAM_SOUP_RE = re.compile(r'(?:[{}\[\]_\\]|/[0-9 ]|[0-9][\uAA00-\uAA5F]|[\uAA00-\uAA5F][0-9])')_ROUTER_LATIN_VOWELS = set('aeiouyàáảãạăằắẳẵặâầấẩẫậèéẻẽẹêềếểễệìíỉĩịòóỏõọôồốổỗộơờớởỡợùúủũụưừứửữựỳýỷỹỵœæ')def _cham_char_count(text):return sum(1 for ch in (text or '') if '\uAA00' <= ch <= '\uAA5F')def _is_clean_ascii_numeral_span(text):s = (text or '').strip()if not s:return Falseascii_digits = sum(1 for ch in s if ch.isascii() and ch.isdigit())if ascii_digits < 3:return Falsereturn all((ch.isascii() and (ch.isdigit() or ch in ' -–—./:,()')) for ch in s)def _is_plausible_latin_span(text):"""Rejects CTC script-mismatch gibberish (e.g. '2VfWKV)', 'g873986)') while accepting real Latin/Vi/Fr words."""s = (text or '').strip()if not s:return Falsealpha = [ch for ch in s if ('a' <= ch.lower() <= 'z') or ('\u00C0' <= ch <= '\u1EF9')]if len(alpha) < 2:return Falseif _ROUTER_GIBBERISH_TOKEN_RE.search(s):return Falsev_cnt = sum(1 for ch in alpha if ch.lower() in _ROUTER_LATIN_VOWELS)return (v_cnt / float(len(alpha))) >= 0.20def _has_plausible_latin_word(text):"""True when at least one whitespace token (>=2 letters) in `text` is a clean non-gibberish Latin/Vi/Fr word."""for tok in (text or '').split():cleaned = tok.strip('.,;:!?()[]{}"\'-–—/')if len(cleaned) >= 2 and _is_plausible_latin_span(cleaned):return Truereturn Falsedef _find_coarse_phrase_spans(crop_img, max_chunks=6):"""Segments a line crop into at most `max_chunks` phrase spans while preserving standalone Cham headwords."""spans = _find_horizontal_word_spans(crop_img)if len(spans) <= 1:return spansh, w = crop_img.shape[:2]min_chunk_w = max(16, int(round(0.55 * h)))# Merge tiny spans (< min_chunk_w) into their closest neighbour while keeping headword-width tokens intactmerged = list(spans)while len(merged) > 2:widths = [b - a for a, b in merged]smallest_i = int(np.argmin(widths))if widths[smallest_i] >= min_chunk_w and len(merged) <= max_chunks:breakif len(merged) <= max_chunks and all(wd >= min_chunk_w for wd in widths):breakif widths[smallest_i] < min_chunk_w:if smallest_i == 0:pair_i = 0elif smallest_i == len(merged) - 1:pair_i = len(merged) - 2else:gap_l = merged[smallest_i][0] - merged[smallest_i - 1][1]gap_r = merged[smallest_i + 1][0] - merged[smallest_i][1]pair_i = smallest_i - 1 if gap_l <= gap_r else smallest_ielse:gaps = [merged[k + 1][0] - merged[k][1] for k in range(len(merged) - 1)]pair_i = int(np.argmin(gaps))merged[pair_i] = (merged[pair_i][0], merged[pair_i + 1][1])merged.pop(pair_i + 1)return merged if len(merged) >= 2 else [(0, w)]def _find_horizontal_word_spans(crop_img):"""Segments a mixed-script line crop into word/phrase x-intervals [x0, x1] at clean vertical whitespace valleys."""if not isinstance(crop_img, np.ndarray) or crop_img.ndim < 2 or crop_img.size == 0:return []gray = cv2.cvtColor(crop_img, cv2.COLOR_BGR2GRAY) if crop_img.ndim == 3 else crop_imgh, w = gray.shape[:2]if h < 10 or w < int(2.4 * h):return [(0, w)]bg = float(np.percentile(gray, 85))ink = (bg - gray.astype(np.float32)) > max(22.0, 0.14 * bg)y0, y1 = int(h * 0.12), max(int(h * 0.12) + 1, int(h * 0.88))is_gap = ink[y0:y1, :].sum(axis=0) == 0min_gap = max(5, int(round(0.16 * h)))spans = []in_word = Falsestart = 0gap_run = 0for x in range(w):if not is_gap[x]:if not in_word:start = max(0, x - 3)in_word = Truegap_run = 0elif in_word:gap_run += 1if gap_run >= min_gap:end = min(w, x - gap_run + 4)if end - start >= max(8, int(0.25 * h)):spans.append((start, end))in_word = Falseif in_word:end = wif end - start >= max(8, int(0.25 * h)):spans.append((start, end))return spans if len(spans) >= 2 else [(0, w)]def _cham_script_ratio(text):85 unmodified linesbest_cham.append((chosen_txt, chosen_conf))best_cham_ver.append(chosen_ver)# 3. Selective Vietnamese / Latin multiscript handoff (v2.3: also probes low-Cham-ratio lines & Cham-soup lines# so lines like 'Năm 2000-2025', '1990-2000', and 'ꨂꨣꩃ ꨌꩌ (Người Chăm)' are routed/split accurately)viet_indices = []viet_imgs = []for i, (c_txt, c_conf) in enumerate(best_cham):c_ratio = _cham_script_ratio(c_txt)has_cham_soup = bool(_ROUTER_CHAM_SOUP_RE.search(c_txt or ''))if (c_ratio < 0.62 and c_conf < 0.85) or c_ratio < 0.35 or c_conf < 0.34 or (has_cham_soup and c_conf < 0.90):viet_indices.append(i)viet_imgs.append(img_list[i])3 unmodified linesfor idx_orig, v_res in zip(viet_indices, viet_batch):viet_map[idx_orig] = v_res# 4. Script-aware adjudication + Intra-Line Horizontal Script-Span Splitting (Auto Router v2.3)final_results = [None] * len(img_list)selected_vers = []for i in range(len(img_list)):7 unmodified linesv_txt, v_conf = viet_map[i]v_conf = float(v_conf)c_ratio = _cham_script_ratio(c_txt)c_cnt = _cham_char_count(c_txt)v_alpha = _latin_alpha_ratio(v_txt)v_lat_cnt = _latin_alpha_count(v_txt)has_cham_soup = bool(_ROUTER_CHAM_SOUP_RE.search(c_txt or ''))take_viet = Falseif v_alpha >= 0.42:4 unmodified lines# Coherent Cham script present -> protect historical Cham folios unless Vi is overwhelmingly confidenttake_viet = (c_conf < 0.50 and v_conf >= 0.88 and v_alpha >= 0.70)elif c_ratio < 0.35 and v_lat_cnt >= 2 and (v_alpha >= 0.18 or _has_viet_diacritics(v_txt)):# Digit/punctuation-heavy Vietnamese lines (e.g. "Năm 2000-2025", "Số trang: 0123456789")take_viet = (v_conf >= 0.55 and (v_conf >= c_conf - 0.05 or _has_viet_diacritics(v_txt)))elif c_ratio < 0.25 and v_lat_cnt == 0 and _is_clean_ascii_numeral_span(v_txt):# Pure ASCII numeral/year-range lines where Cham CTC mixed script ('1꩐0-200') or collapsed repeated '00'/'99' ('1990-200' vs '1990-2000');# clean non-collapsed numerals ('123 - 456', '7-8') stay on the Cham specialist.v_digits = sum(1 for ch in (v_txt or '') if ch.isascii() and ch.isdigit())c_ascii_digits = sum(1 for ch in (c_txt or '') if ch.isascii() and ch.isdigit())ctc_collapsed_rep = (('00' in (v_txt or '') or '99' in (v_txt or '')) and v_digits > c_ascii_digits)take_viet = (v_conf >= 0.84 and (has_cham_soup or ctc_collapsed_rep))elif c_conf < 0.25 and v_conf > c_conf + 0.25:take_viet = True# Auto Router v2.3: Symmetric Intra-Line Horizontal Script-Span Splitting# Fast-skip 100% pure high-confidence Latin/Fr/Vi lines and 100% pure high-confidence Cham linesis_clean_pure_latin = (take_vietand v_conf >= 0.86and v_alpha >= 0.62and not _ROUTER_GIBBERISH_TOKEN_RE.search(v_txt or ''))is_clean_pure_cham = ((not take_viet)and c_conf >= 0.84and c_ratio >= 0.75and not has_cham_soup)if (not is_clean_pure_latinand not is_clean_pure_chamand (c_cnt >= 2 or (c_cnt >= 1 and _ROUTER_GIBBERISH_TOKEN_RE.search(v_txt or '')))and v_lat_cnt >= 2and v_conf >= 0.55and _has_plausible_latin_word(v_txt)):split_res = self._try_intraline_script_split(img_list[i], c_ver, _norm_u, default_is_viet=take_viet)if split_res is not None:final_results[i] = (split_res[0], split_res[1])selected_vers.append(split_res[2])continueif take_viet:final_results[i] = (v_txt, v_conf)selected_vers.append('vi')4 unmodified linesself.last_selected_versions = list(selected_vers)return final_results, list(selected_vers), 0.0def _try_intraline_script_split(self, crop_img, cham_ver, norm_fn, default_is_viet=False):"""Splits a mixed Cham+Latin line into <=6 coarse phrase spans with symmetric bidirectional gain gating."""spans = _find_coarse_phrase_spans(crop_img, max_chunks=6)if len(spans) < 2 or len(spans) > 6:return Nonesub_imgs = [crop_img[:, x0:x1] for x0, x1 in spans]try:c_sub_res, _ = self.cham_model(sub_imgs)v_sub_res, _ = self.viet_model(sub_imgs)except Exception:return Noneif len(c_sub_res) != len(spans) or len(v_sub_res) != len(spans):return Nonelabels = []for (ct, cc), (vt, vc) in zip(c_sub_res, v_sub_res):cc, vc = float(cc), float(vc)cr = _cham_script_ratio(ct)cham_soup = bool(_ROUTER_CHAM_SOUP_RE.search(ct or ''))if default_is_viet:# Line defaulted to Vi/Fr: only flip a chunk to Cham if it is genuinely Akhar Thrah AND Vi failed/garbled itvi_garbled = (vc < 0.82) or bool(_ROUTER_GIBBERISH_TOKEN_RE.search(vt or '')) or (_latin_alpha_ratio(vt) < 0.45)if cr >= 0.55 and _cham_char_count(ct) >= 1 and cc >= max(0.55, vc - 0.08) and vi_garbled and not cham_soup:labels.append('cham')else:labels.append('vi')else:# Line defaulted to Cham: only flip a chunk to Vi if Cham failed/garbled AND Vi decoded plausible Latin wordscham_garbled = (cr < 0.45) or (cc < 0.78) or cham_soupif cham_garbled and vc >= max(0.74, cc + 0.06) and (_is_plausible_latin_span(vt) or _has_viet_diacritics(vt)):labels.append('vi')else:labels.append('cham')if len(set(labels)) < 2:return None# Merge adjacent same-script word spans so each recognizer receives maximal contiguous phrase context!grouped = []cur_lbl = labels[0]cur_x0, cur_x1 = spans[0]for lbl, (x0, x1) in zip(labels[1:], spans[1:]):if lbl == cur_lbl:cur_x1 = x1else:grouped.append((cur_lbl, cur_x0, cur_x1))cur_lbl, cur_x0, cur_x1 = lbl, x0, x1grouped.append((cur_lbl, cur_x0, cur_x1))cham_grp_imgs = [crop_img[:, x0:x1] for lbl, x0, x1 in grouped if lbl == 'cham']vi_grp_imgs = [crop_img[:, x0:x1] for lbl, x0, x1 in grouped if lbl == 'vi']c_grp_out = iter(self.cham_model(cham_grp_imgs)[0]) if cham_grp_imgs else iter(())v_grp_out = iter(self.viet_model(vi_grp_imgs)[0]) if vi_grp_imgs else iter(())parts = []weighted_conf = 0.0total_w = 0.0for lbl, x0, x1 in grouped:span_w = max(1.0, float(x1 - x0))if lbl == 'cham':gt_txt, gt_conf = next(c_grp_out, ('', 0.0))gt_txt = norm_fn(gt_txt) if any('\uAA00' <= c <= '\uAA5F' for c in (gt_txt or '')) else (gt_txt or '')else:gt_txt, gt_conf = next(v_grp_out, ('', 0.0))gt_txt = (gt_txt or '').strip()if gt_txt:parts.append(gt_txt)weighted_conf += float(gt_conf) * span_wtotal_w += span_wif len(parts) < 2 or total_w <= 0:return Nonemerged_txt = ' '.join(parts)if _cham_char_count(merged_txt) < 1 or _latin_alpha_count(merged_txt) < 2:return Nonereturn merged_txt, round(weighted_conf / total_w, 6), f"{cham_ver}+vi"def __call__(self, img_list):results, _, elapsed = self.predict_with_provenance(img_list)return results, elapsed138 unmodified linesargs.rec_image_shape = str(manifest_for_shape.get("rec_image_shape") or default_rec_shape)args.use_space_char = True# Batch size config: TextRecognizer pre-sorts crops by wh_ratio, and V26.1 uses use_valid_mask=True,# so CPU mini-batch=6 cuts 70-line 2-column latency ~2x (preventing Cloudflare HTTP 524) with zero padding driftenv_batch = os.getenv("OCR_REC_BATCH_SIZE")if env_batch:ocr_rec_batch_size = int(env_batch)else:ocr_rec_batch_size = 6 if not paddle.is_compiled_with_cuda() else 16args.rec_batch_num = ocr_rec_batch_size238 unmodified linesxm = (ox1 + ox2) / 2.0return abs(f1(xm) - f2(xm)) > ratio * tdef merge_line_boxes(boxes, img_w, img_h, col_divider_x=None):"""Merges horizontally separated bounding boxes on the same line into a single unified line crop.Prevents splitting a single line into separate fragments across distant words, while neverbridging across a detected vertical two-column divider (`col_divider_x`)."""if boxes is None or len(boxes) == 0:return []67 unmodified linesif h_overlap > 0.25 and _stacked_by_centerline(r1[4], r2[4], max(r1[0], r2[0]), min(r1[2], r2[2])):continueif col_divider_x is not None:if min(r1[0], r2[0]) < col_divider_x - 3.0 and max(r1[2], r2[2]) > col_divider_x + 3.0:continueif v_overlap >= 0.50 and x_dist <= max(40.0, 2.5 * min_h):new_x1 = max(0.0, min(r1[0], r2[0]))new_x2 = min(float(img_w), max(r1[2], r2[2]))185 unmodified linescnt = cv2.approxPolyDP(cnt, 1.0, True).reshape(-1, 2).astype(np.float32) + offreturn _ribbon_info(cnt)def merge_line_polygons(polys, img_w, img_h, col_divider_x=None):"""Polygon counterpart of merge_line_boxes() for Cham-DBNet box_type='poly'.Fragments of one curved line (shared, extrapolated centerline) are merged into one curved polygon;vertically stacked wavy lines are never merged even though their AABBs overlap (the decision usesribbon centerlines / thickness, not AABB heights), and fragments on opposite sides of a verticaltwo-column divider (`col_divider_x`) are never merged. Detached micro-diacritic specks next to a full lineare suppressed as in merge_line_boxes. Returns polygons sorted by centerline y."""items = []19 unmodified linesfor j in range(i + 1, len(items)):if used[j]:continueif col_divider_x is not None:if min(r1['x0'], items[j]['x0']) < col_divider_x - 3.0 and max(r1['x1'], items[j]['x1']) > col_divider_x + 3.0:continueif _ribbons_same_line(r1, items[j]):r1 = _merge_ribbon_polys(r1, items[j])used[j] = True220 unmodified linesz = math.log(p / (1.0 - p))return round(1.0 / (1.0 + math.exp(-z / T)), 6)def get_model_info(model_ver, executed_detector=None, detector_switched=False):"""Returns provenance info (model id, weight fingerprints, executed detector, normalizer) for the response."""info = {"model": model_ver, "normalizer": None}rec_versions = [DEFAULT_CHAM_MODEL, 'v24_1_r3_1', 'vi'] if model_ver == 'auto' else [model_ver]recs = []24 unmodified lineselif v in ocr_models and isinstance(ocr_models.get(v), OfficialPaddleOCRWrapper):recs.append({"version": v, "model_dir": None, "wrapper": "OfficialPaddleOCRWrapper"})info["recognizers"] = recsif not det_model_info and not executed_detector:info["detector"] = {"name": None, "mode": DET_MODE, "loaded": False}else:active_det_name = executed_detector or det_model_info.get("name")active_det_dir = CHAM_DET_DIR if active_det_name == "cham_dbnet" else det_model_info.get("dir", "")cham_sha16 = _file_fingerprint(os.path.join(CHAM_DET_DIR, "inference.pdiparams")) if (cham_det_model is not None or active_det_name == "cham_dbnet") else Noneinfo["detector"] = {"name": active_det_name, "mode": det_model_info.get("mode", DET_MODE), "loaded": True,"detector_switched": bool(detector_switched),"weights_sha256_16": _file_fingerprint(os.path.join(active_det_dir, "inference.pdiparams")) if active_det_dir else None,# Exposed so a deployment can be verified: False means the fine-tuned Cham-DBNet# failed to load (e.g. PIR model on an old Paddle) and only the legacy detector runs."cham_dbnet_available": cham_det_model is not None,"cham_dbnet_sha256_16": cham_sha16,"cham_dbnet_box_type": ("poly" if _is_poly_detector(cham_det_model) else "quad") if cham_det_model is not None else None}try:import paddle as _paddle47 unmodified linescover = np.zeros((h, w), dtype=np.uint8)for poly in polygons:cv2.fillPoly(cover, [np.round(np.array(poly, dtype=np.float32)).astype(np.int32)], 1)# Anisotropic dilation: tight vertical pad (0.08 * median_line_h) prevents two neighbouring lines# from bridging vertically across a missed short line (e.g. synthetic_142 GT[1]), while preserving horizontal word marginpad_y = int(max(2, round(0.08 * median_line_h))) if median_line_h else 3pad_x = int(max(3, round(0.25 * median_line_h))) if median_line_h else 5cover = cv2.dilate(cover, np.ones((2 * pad_y + 1, 2 * pad_x + 1), np.uint8))total, uncovered, idxs = 0, 0, []for i in range(len(stats)):ch, area = stats[i, cv2.CC_STAT_HEIGHT], stats[i, cv2.CC_STAT_AREA]139 unmodified linesdef check_inverted_polarity(img):"""Morphological Opening Solid-Substrate vs Thin-Stroke Polarity Detector.Returns True iff >=95% of the morphologically opened background is dark (<85) AND bright foregroundpixels (`p99.2`) vanish under opening (`diff > 45`), proving genuine light text strokes on a darkbackground while never falsely inverting archival photos on dark velvet tables or tan/brown palm-leaf/paper."""if img is None or img.size == 0:return Falsegray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) if len(img.shape) == 3 else imgh, w = gray.shape[:2]if h < 8 or w < 8:return Falseif float(np.median(gray)) >= 130.0:return Falseif h >= 180 and w >= 240:roi = gray[int(h * 0.14):int(h * 0.68), int(w * 0.16):int(w * 0.84)]else:roi = grayscale = min(1.0, 900.0 / float(max(roi.shape[:2])))work = (cv2.resize(roi, (max(8, int(roi.shape[1] * scale)), max(8, int(roi.shape[0] * scale))), interpolation=cv2.INTER_AREA)if scale < 1.0 else roi)wh, ww = work.shape[:2]k = int(max(7, min(21, round(min(wh, ww) / 8)))) | 1se = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (k, k))opened = cv2.morphologyEx(work, cv2.MORPH_OPEN, se)op_p95 = float(np.percentile(opened, 95))fg_p992 = float(np.percentile(work, 99.2))return bool(op_p95 < 85.0 and (fg_p992 - op_p95) > 45.0)def detect_vertical_column_divider(img):"""Detects a continuous printed vertical column-divider rule in [0.38W, 0.62W] (e.g. 2-column dictionaries)."""if img is None or img.size == 0:return Nonegray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) if len(img.shape) == 3 else imgh, w = gray.shape[:2]if h < 300 or w < 300:return Noney0, y1 = int(h * 0.14), int(h * 0.86)x0, x1 = int(w * 0.38), int(w * 0.62)band = gray[y0:y1, x0:x1]bh, bw = band.shapehoriz_bg = cv2.GaussianBlur(band, (31, 1), 0)dark = (cv2.subtract(horiz_bg, band) > 22).astype(np.uint8)q_peaks = []for q in range(4):s0, s1 = (q * bh) // 4, ((q + 1) * bh) // 4sub = cv2.dilate(dark[s0:s1, :], np.ones((1, 3), np.uint8))dens = sub.mean(axis=0)pk = int(np.argmax(dens))val = float(dens[pk])lf = dens[max(0, pk - 22):max(0, pk - 5)]rf = dens[min(bw, pk + 6):min(bw, pk + 23)]if val >= 0.50 and len(lf) >= 5 and len(rf) >= 5 and float(lf.mean()) <= 0.12 and float(rf.mean()) <= 0.12:q_peaks.append((q, pk, val))if len(q_peaks) < 3:return Nonexs = [p[1] for p in q_peaks]if max(xs) - min(xs) > 16:return Nonereturn x0 + int(round(float(np.median(xs))))def maybe_safe_deskew_page(img, min_abs_deg=9.0, min_var_gain=1.55, search_deg=16.0, step_deg=0.5):"""Conditional Safe-Border Pre-Detection Deskew gated strictly at |theta| >= 9.0 deg AND projectionvariance gain >= 1.55x. Returns (deskewed_img, M_inv_2x3_or_None, applied_angle_deg).Guarantees 0% change on upright or mildly tilted pages (|theta| < 9 deg) and 0 border glyph clipping."""if img is None or img.size == 0:return img, None, 0.0h, w = img.shape[:2]if h < 140 or w < 180:return img, None, 0.0gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) if len(img.shape) == 3 else imgif check_inverted_polarity(img):gray = 255 - grayroi = gray[int(h * 0.14):int(h * 0.84), int(w * 0.14):int(w * 0.86)]scale = min(1.0, 560.0 / float(max(roi.shape[:2])))small = cv2.resize(roi, (max(16, int(roi.shape[1] * scale)), max(16, int(roi.shape[0] * scale))), interpolation=cv2.INTER_AREA)bh = cv2.morphologyEx(small, cv2.MORPH_BLACKHAT, cv2.getStructuringElement(cv2.MORPH_RECT, (25, 25)))_, bw = cv2.threshold(bh, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)if int((bw > 0).sum()) < 80:return img, None, 0.0sh, sw = bw.shapecx, cy = sw / 2.0, sh / 2.0zero_score = max(1.0, float(np.var(bw.sum(axis=1).astype(np.float64))))best_angle = 0.0best_score = zero_scorefor ang in np.arange(-search_deg, search_deg + 1e-6, step_deg):if abs(float(ang)) < 1e-4:continueM_s = cv2.getRotationMatrix2D((cx, cy), float(ang), 1.0)rot = cv2.warpAffine(bw, M_s, (sw, sh), flags=cv2.INTER_NEAREST, borderMode=cv2.BORDER_CONSTANT, borderValue=0)sc = float(np.var(rot.sum(axis=1).astype(np.float64)))if sc > best_score:best_score = scbest_angle = float(ang)if abs(best_angle) < min_abs_deg or (best_score / zero_score) < min_var_gain:return img, None, 0.0rad = math.radians(abs(best_angle))cos_a, sin_a = math.cos(rad), math.sin(rad)new_w = int(math.ceil(w * cos_a + h * sin_a))new_h = int(math.ceil(h * cos_a + w * sin_a))M = cv2.getRotationMatrix2D((w / 2.0, h / 2.0), best_angle, 1.0)M[0, 2] += (new_w - w) / 2.0M[1, 2] += (new_h - h) / 2.0deskewed = cv2.warpAffine(img, M, (new_w, new_h), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)M_inv = cv2.invertAffineTransform(M)return deskewed, M_inv, round(best_angle, 2)def map_deskew_pts_to_original(pts, M_inv, orig_w, orig_h):"""Maps 2D points from deskewed canvas space back to original image frame [0..orig_w-1, 0..orig_h-1]."""arr = np.asarray(pts, dtype=np.float64).reshape(-1, 2)ones = np.ones((len(arr), 1), dtype=np.float64)mapped = np.hstack([arr, ones]) @ np.asarray(M_inv, dtype=np.float64).Tmapped[:, 0] = np.clip(mapped[:, 0], 0, max(0, orig_w - 1))mapped[:, 1] = np.clip(mapped[:, 1], 0, max(0, orig_h - 1))return mappeddef preprocess_crop_for_rec(crop_img):"""100 unmodified linesis_inverted = check_inverted_polarity(img)det_img = (255 - img) if is_inverted else imgh, w = img.shape[:2]col_divider_x = detect_vertical_column_divider(det_img) if reading_order != 'rows' else Noneif col_divider_x is not None:# Mask thin vertical 2-column rule on det_img so DBNet never bridges left & right columns across '|'det_img = det_img.copy()rx0, rx1 = max(0, col_divider_x - 3), min(w, col_divider_x + 4)bg_fill = int(np.median(det_img[int(h * 0.14):int(h * 0.86), max(0, rx0 - 12):min(w, rx1 + 12)]))det_img[int(h * 0.10):int(h * 0.90), rx0:rx1] = bg_fillinfo["column_divider_x"] = int(col_divider_x)def _detect(detector):boxes, _ = detector(det_img)if _is_poly_detector(detector):boxes = [] if boxes is None else [np.array(b, dtype=np.float32).reshape(-1, 2) for b in boxes]return merge_line_polygons(boxes, w, h, col_divider_x=col_divider_x)boxes = [] if boxes is None else [np.array(b, dtype=np.float32) for b in boxes]return merge_line_boxes(boxes, w, h, col_divider_x=col_divider_x)def _coverage(boxes):"""(uncovered ink ratio, max box height / glyph height) for a candidate box set.1036 unmodified lines}doc_reasons = []doc_extra = {}executed_det_name = Noneexecuted_det_switched = Falseif method == 'dbnet':orig_h, orig_w = img.shape[:2]work_img, deskew_M_inv, deskew_deg = maybe_safe_deskew_page(img)if deskew_M_inv is not None:profiler_dict['deskew_angle_deg'] = deskew_degdoc_extra['deskew_angle_deg'] = deskew_degink = analyze_text_ink(work_img)doc_extra['ink_ratio'] = round(ink['ink_ratio'], 5)if is_blank_page(ink):# No text-like ink: never hallucinate a line on blank / near-blank paper7 unmodified linestry:det = get_det_model()final_crops, lines_metadata, det_info = segment_lines_dbnet(work_img, det, ink=ink, return_info=True, reading_order=reading_order)except Exception:import tracebackprint(f"❌ DBNet segmentation error: {traceback.format_exc()}")final_crops, lines_metadata = [], []if deskew_M_inv is not None and lines_metadata:for meta in lines_metadata:poly = meta.get('polygon')if not poly and meta.get('bbox') and len(meta['bbox']) == 4:bx0, by0, bx1, by1 = meta['bbox']poly = [[bx0, by0], [bx1, by0], [bx1, by1], [bx0, by1]]if poly:orig_pts = map_deskew_pts_to_original(poly, deskew_M_inv, orig_w, orig_h)meta['polygon'] = np.round(orig_pts, 1).tolist()x0_m = int(round(float(orig_pts[:, 0].min())))y0_m = int(round(float(orig_pts[:, 1].min())))x1_m = int(round(float(orig_pts[:, 0].max())))y1_m = int(round(float(orig_pts[:, 1].max())))meta['bbox'] = [x0_m, y0_m, x1_m, y1_m]meta['core_box'] = [y0_m, y1_m]base_segmentation_sec = time.time() - t_segif det_info:executed_det_name = det_info.get('detector')executed_det_switched = bool(det_info.get('detector_switched'))doc_extra['layout'] = det_info.get('layout')doc_extra['uncovered_ink_ratio'] = det_info.get('uncovered_ink_ratio')profiler_dict['det_lines'] = det_info.get('lines_detected')profiler_dict['detector'] = executed_det_nameprofiler_dict['detector_switched'] = executed_det_switchedprofiler_dict['uncovered_ink_ratio_primary'] = det_info.get('uncovered_ink_ratio_primary')if not final_crops:62 unmodified linesif not cal_ver and model_ver != 'auto':cal_ver = resolve_actual_model_version(model_ver)primary_rec_part = str(cal_ver).split('+', 1)[0] if cal_ver else ''if (cal_ver and cal_ver not in ('vi', 'en', 'fr', 'japan')) and (primary_rec_part in ('v24', 'v25', 'v26') or primary_rec_part.startswith('v24')):if any('\uAA00' <= ch <= '\uAA5F' for ch in (pred_text or '')):try:6 unmodified lines_, buffer = cv2.imencode('.png', line_img)line_b64 = base64.b64encode(buffer).decode('utf-8')cal_conf = calibrate_line_confidence(confidence, primary_rec_part or cal_ver, pred_text)# Backward-compatible format with explicit per-line recognizer provenanceresults.append({23 unmodified linesprofiler_dict['backend_total_sec'] = round(time.time() - t_start, 4)profiler_dict['base_segmentation_sec'] = round(base_segmentation_sec, 4)document = build_document_status(results, doc_reasons, doc_extra)return {'lines': results,'profiler': profiler_dict,'document': document,'model_info': get_model_info(model_ver,executed_detector=executed_det_name,detector_switched=executed_det_switched,),}def save_correction_entry(data, base_dir=None):"""Persists a verified/corrected text line to legacy ocr_corrections.txt and Stage R4 active learning storage."""
218 unmodified lines219220221222223224225218 unmodified lines<span>Specimens</span></button></div><input type="file" id="file-input" multiple accept="image/*,application/pdf,.pdf" style="display: none;" onchange="StudioApp.handleIncomingFiles(this.files); this.value='';"><div class="intake-meta-row"><label class="toggle-switch-label" title="Automatically run OCR when new images or PDF pages are added"><input type="checkbox" id="chk-auto-ocr" onchange="StudioApp.setAutoOcr(this.checked)">218 unmodified lines219220221222223224225218 unmodified lines<span>Specimens</span></button></div><input type="file" id="file-input" multiple accept="image/*,application/pdf,.pdf,application/json,.json" style="display: none;" onchange="StudioApp.handleIncomingFiles(this.files); this.value='';"><div class="intake-meta-row"><label class="toggle-switch-label" title="Automatically run OCR when new images or PDF pages are added"><input type="checkbox" id="chk-auto-ocr" onchange="StudioApp.setAutoOcr(this.checked)">
524 unmodified lines52552652752852953053153253353410 unmodified lines545546547548549550551552553554555556557558559560561562524 unmodified linesreturn folio;}async function handleIncomingFiles(fileList) {if (!fileList || fileList.length === 0) return;const files = Array.from(fileList);const pdfFiles = files.filter((f) => (f.type === "application/pdf") || (f.name && f.name.toLowerCase().endsWith(".pdf")));const imgFiles = files.filter((f) => (f.type && f.type.startsWith("image/")) || /\.(png|jpe?g|webp|bmp|gif)$/i.test(f.name || ""));const newlyAdded = [];10 unmodified lines}}if (newlyAdded.length > 0 && (!state.activeFolioId || newlyAdded.length === 1)) {await selectFolio(newlyAdded[0].id);}if (newlyAdded.length > 1) {toast(`Added ${newlyAdded.length} manuscript folios to queue`);} else if (newlyAdded.length === 1) {toast(`Loaded ${newlyAdded[0].name}`);}if (pdfFiles.length > 0) {await openPdfImportDialog(pdfFiles[0]);} else if (state.autoTranscribeOnUpload && newlyAdded.length > 0) {runBatchOCR("unprocessed");}}524 unmodified lines52552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959010 unmodified lines601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634524 unmodified linesreturn folio;}function readFileAsText(file) {return new Promise((resolve, reject) => {const reader = new FileReader();reader.onload = (ev) => resolve(String(ev.target.result || ""));reader.onerror = (err) => reject(err);reader.readAsText(file, "utf-8");});}function stemName(filename) {return String(filename || "").replace(/^.*[\\/]/, "").replace(/\.studio\.json$/i, "").replace(/\.[^.]+$/, "").trim().toLowerCase();}async function applyImportedJsonPayload(payload) {const entries = Array.isArray(payload && payload.documents) ? payload.documents : [payload];let hydratedCount = 0;for (const entry of entries) {if (!entry || !Array.isArray(entry.lines)) continue;const targetStem = stemName(entry.doc_id || entry.image_name || entry.name || "");let folio = state.queue.find((q) => stemName(q.name) === targetStem);if (!folio && entries.length === 1 && state.activeFolioId) {folio = state.queue.find((q) => q.id === state.activeFolioId);}if (!folio) continue;folio.lines = entry.lines.map((ln, idx) => ({...ln,index: ln.index || ln.line_id || idx + 1,text: ln.text ?? ln.draft_prediction ?? "",confidence: Number(ln.confidence ?? ln.draft_confidence ?? 0),calibrated_confidence: Number(ln.calibrated_confidence ?? ln.draft_calibrated_confidence ?? ln.confidence ?? 0),human_verified: Boolean(ln.human_verified)}));folio.lineCount = folio.lines.length;folio.verifiedCount = folio.lines.filter((l) => l.human_verified).length;folio.model = entry.model || folio.model;folio.status = computeDocStatus(folio.lines, folio.document);await dbPutFolio(folio);hydratedCount++;if (folio.id === state.activeFolioId) {await selectFolio(folio.id);}}if (hydratedCount > 0) {persistQueueIndex();renderQueue();updateCorpusFooter();}return hydratedCount;}async function handleIncomingFiles(fileList) {if (!fileList || fileList.length === 0) return;const files = Array.from(fileList);const pdfFiles = files.filter((f) => (f.type === "application/pdf") || (f.name && f.name.toLowerCase().endsWith(".pdf")));const jsonFiles = files.filter((f) => (f.type === "application/json") || /\.json$/i.test(f.name || ""));const imgFiles = files.filter((f) => (f.type && f.type.startsWith("image/")) || /\.(png|jpe?g|webp|bmp|gif)$/i.test(f.name || ""));const newlyAdded = [];10 unmodified lines}}let hydratedFolios = 0;for (const jf of jsonFiles) {try {const rawTxt = await readFileAsText(jf);const parsed = JSON.parse(rawTxt);hydratedFolios += await applyImportedJsonPayload(parsed);appendLog(`Imported transcription JSON: ${jf.name}`, "success");} catch (err) {toast(`JSON import error (${jf.name}): ${err.message}`);appendLog(`Failed to parse JSON ${jf.name}: ${err}`, "error");}}if (newlyAdded.length > 0 && (!state.activeFolioId || newlyAdded.length === 1)) {await selectFolio(newlyAdded[0].id);}if (hydratedFolios > 0) {toast(`Hydrated ${hydratedFolios} folio(s) from Review Queue JSON`);} else if (newlyAdded.length > 1) {toast(`Added ${newlyAdded.length} manuscript folios to queue`);} else if (newlyAdded.length === 1) {toast(`Loaded ${newlyAdded[0].name}`);}const hasUnprocessedNew = newlyAdded.some((it) => it.status === "Unprocessed" && (!it.lines || it.lines.length === 0));if (pdfFiles.length > 0) {await openPdfImportDialog(pdfFiles[0]);} else if (state.autoTranscribeOnUpload && hasUnprocessedNew) {runBatchOCR("unprocessed");}}
833 unmodified lines834835836837838839833 unmodified linesapp.ocr_models['auto'] = saved_autoclass TestQualityGates(unittest.TestCase):pass833 unmodified lines83483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037833 unmodified linesapp.ocr_models['auto'] = saved_autodef test_realscan_gold_v4_anti_circular_and_promotion_gates():"""RealScan-Gold v4: enforces gt=None on staging_review_queue, blocks unverified Studio drafts, promotes Verified pages."""import jsonimport tempfilerepo_root = os.path.dirname(app.PROJECT_ROOT)scripts_dir = os.path.join(repo_root, 'scripts')if scripts_dir not in sys.path:sys.path.insert(0, scripts_dir)import ingest_studio_to_realscan_gold as ingest_v4with tempfile.TemporaryDirectory() as tmpdir:v4_dir = os.path.join(tmpdir, 'ocr-benchmark', 'data', 'realscan_gold_v4')pages_dir = os.path.join(v4_dir, 'pages')os.makedirs(pages_dir, exist_ok=True)page_p = os.path.join(pages_dir, 'eap_test_folio_01.jpg')img = np.full((240, 600, 3), 235, dtype=np.uint8)cv2.rectangle(img, (40, 50), (520, 92), (25, 25, 25), -1)cv2.rectangle(img, (40, 120), (490, 162), (25, 25, 25), -1)cv2.imwrite(page_p, img)manifest_p = os.path.join(v4_dir, 'manifest.json')seed_manifest = {'schema_version': '4.0.0','dataset_id': 'realscan_gold_v4','summary': {},'documents': [{'doc_id': 'eap_test_folio_01','split': 'staging_review_queue','verification_status': 'pending_human_review','verified_by_human': False,'gold_eligible': False,'stratum': 'handwritten_paper_traditional','source_collection_id': 'EAP698-TEST','redistribution_allowed_in_git': False,'page_relpath': 'ocr-benchmark/data/realscan_gold_v4/pages/eap_test_folio_01.jpg','page_sha256': ingest_v4.sha256_file(page_p),'draft_ocr_summary': {'cham_bearing_lines': 2},'line_count': 2,'lines': [{'line': 1, 'bbox': [40, 50, 520, 92], 'crop_relpath': 'ocr-benchmark/data/realscan_gold_v4/crops/x1.png','crop_sha256': '0' * 64, 'gt': None, 'verified_by_human': False, 'draft_prediction': 'ꨙꨳꨯꨮ'},{'line': 2, 'bbox': [40, 120, 490, 162], 'crop_relpath': 'ocr-benchmark/data/realscan_gold_v4/crops/x2.png','crop_sha256': '0' * 64, 'gt': None, 'verified_by_human': False, 'draft_prediction': 'ꨌꩌ'},],}],}with open(manifest_p, 'w', encoding='utf-8') as f:json.dump(seed_manifest, f)# 1. Unverified draft Studio JSON MUST be rejected by Anti-Circularity Gateunverified_json = os.path.join(tmpdir, 'draft_unverified.json')with open(unverified_json, 'w', encoding='utf-8') as f:json.dump({'image_name': 'eap_test_folio_01.jpg','status': 'Needs review','lines': [{'bbox': [40, 50, 520, 92], 'text': 'ꨙꨯꨳꨮ', 'human_verified': False},{'bbox': [40, 120, 490, 162], 'text': 'ꨌꩌ', 'human_verified': False},],}, f)rejected = Falsetry:ingest_v4.promote_verified_v4(unverified_json, manifest_path=manifest_p, project_root=tmpdir)except ValueError as exc:rejected = 'Anti-Circularity Gate' in str(exc)assert rejected, 'Expected ValueError from Anti-Circularity Gate on unverified Studio draft!'# 2. Human-verified Studio JSON promotes cleanly & enforces Logical Order normalize_unicode ('ꨙꨯꨳꨮ' -> 'ꨙꨳꨯꨮ')verified_json = os.path.join(tmpdir, 'human_verified.json')with open(verified_json, 'w', encoding='utf-8') as f:json.dump({'image_name': 'eap_test_folio_01.jpg','status': 'Verified','lines': [{'bbox': [40, 50, 520, 92], 'text': 'ꨙꨯꨳꨮ ꨚꨤꨬ', 'original_text': 'ꨙꨳꨯꨮ', 'human_verified': True},{'bbox': [40, 120, 490, 162], 'text': 'ꨌꩌ ꨣꩌ', 'original_text': 'ꨌꩌ', 'human_verified': True},],}, f)updated = ingest_v4.promote_verified_v4(verified_json, annotator='paleographer_a', review_round=2, manifest_path=manifest_p, project_root=tmpdir)doc = updated['documents'][0]assert doc['split'] == 'verified_gold' and doc['verified_by_human'] is True and doc['gold_eligible'] is Trueassert doc['annotator_id'] == 'paleographer_a' and doc['review_round'] == 2assert doc['lines'][0]['gt'] == 'ꨙꨳꨯꨮ ꨚꨤꨬ', doc['lines'][0]assert updated['summary']['verified_gold_pages'] == 1assert updated['summary']['staging_new_physical_pages'] == 0stats = ingest_v4.verify_manifest_integrity(manifest_p, project_root=tmpdir)assert stats['checked_files'] == 3, stats# 3. Verify production RealScan-Gold v4 manifest on disk if already builtprod_v4 = os.path.join(repo_root, 'ocr-benchmark', 'data', 'realscan_gold_v4', 'manifest.json')if os.path.exists(prod_v4):m4 = json.load(open(prod_v4, encoding='utf-8'))assert m4['summary']['synthetic_pages_included'] == 0assert m4['summary']['total_physical_pages'] >= 50prod_stats = ingest_v4.verify_manifest_integrity(prod_v4, project_root=repo_root)assert prod_stats['documents'] >= 58, prod_statsdef test_stage1_v26_2_polarity_divider_deskew_provenance_and_router_v23():"""Adversarial regression gate for Pipeline v26.2 + Auto Router v2.3 (Gate SC-1)."""# 1. check_inverted_polarity: must NOT invert dark-framed archival photo (bright paper interior),# and MUST invert genuine dark-substrate white-stroke negative/dark-mode image (even 1 line).archival_dark_frame = np.full((600, 800, 3), 24, dtype=np.uint8)archival_dark_frame[90:510, 120:680] = 215 # bright paper folio inside dark table framefor y in range(140, 460, 48):cv2.line(archival_dark_frame, (160, y), (640, y), (30, 30, 30), 3)assert app.check_inverted_polarity(archival_dark_frame) is False, "False positive inversion on dark-framed archival photo!"dark_mode_1line = np.full((240, 720, 3), 22, dtype=np.uint8)cv2.putText(dark_mode_1line, "CHAM NEGATIVE TEST", (60, 130), cv2.FONT_HERSHEY_SIMPLEX, 1.1, (242, 242, 242), 2)assert app.check_inverted_polarity(dark_mode_1line) is True, "Missed genuine 1-line dark-substrate white-stroke image!"# 2. detect_vertical_column_divider + cross-column barrier in merge_line_boxestwo_col_page = np.full((900, 1200, 3), 242, dtype=np.uint8)cv2.line(two_col_page, (600, 140), (600, 820), (35, 35, 35), 2)div_x = app.detect_vertical_column_divider(two_col_page)assert div_x is not None and 595 <= div_x <= 605, f"Expected divider near x=600, got {div_x}"q_left = [[140, 300], [594, 300], [594, 336], [140, 336]]q_right = [[606, 301], [1080, 301], [1080, 337], [606, 337]]assert len(app.merge_line_boxes([q_left, q_right], 1200, 900, col_divider_x=None)) == 1merged_boxes = app.merge_line_boxes([q_left, q_right], 1200, 900, col_divider_x=div_x)assert len(merged_boxes) == 2, f"Cross-column merge leaked across col_divider_x={div_x}: {merged_boxes}"single_col_page = np.full((900, 1200, 3), 242, dtype=np.uint8)for y in range(160, 780, 52):cv2.line(single_col_page, (150, y), (1050, y), (30, 30, 30), 3)assert app.detect_vertical_column_divider(single_col_page) is None, "False column divider on single-column page!"# 3. get_model_info detector provenance when detector_switched=Truemi_switched = app.get_model_info('v24_1_r4', executed_detector='cham_dbnet', detector_switched=True)assert mi_switched['detector']['name'] == 'cham_dbnet'assert mi_switched['detector']['detector_switched'] is Trueassert mi_switched['detector']['weights_sha256_16'] == mi_switched['detector']['cham_dbnet_sha256_16']# 4. maybe_safe_deskew_page: 0-deg untouched; -12-deg counter-rotated and inverse-mapped cleanlystraight = np.full((520, 760, 3), 248, dtype=np.uint8)for y in range(90, 440, 46):cv2.line(straight, (90, y), (670, y), (20, 20, 20), 4)_, M0, ang0 = app.maybe_safe_deskew_page(straight)assert M0 is None and ang0 == 0.0, f"Unexpected deskew on 0-deg image: {ang0}"M_rot = cv2.getRotationMatrix2D((380.0, 260.0), -12.0, 1.0)tilted = cv2.warpAffine(straight, M_rot, (760, 520), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)dsk_im, M_inv, ang_est = app.maybe_safe_deskew_page(tilted)assert M_inv is not None and 10.5 <= ang_est <= 13.5, f"Expected ~+12 deg deskew, got {ang_est}"mapped_pt = app.map_deskew_pts_to_original([[100.0, 100.0], [200.0, 100.0], [200.0, 130.0], [100.0, 130.0]], M_inv, 760, 520)assert len(mapped_pt) == 4 and all(0.0 <= px <= 760.0 and 0.0 <= py <= 520.0 for px, py in mapped_pt)# 5. Auto Router v2.3: 'Năm 2000-2025', pure ASCII year '1990-2000', genuine Cham digits, and intra-line splitdummy_mixed = np.full((48, 360, 3), 250, dtype=np.uint8)cv2.rectangle(dummy_mixed, (20, 12), (120, 36), (20, 20, 20), -1) # span 0 (Cham headword)cv2.rectangle(dummy_mixed, (165, 12), (335, 36), (20, 20, 20), -1) # span 1 (Vietnamese/French gloss)def _mock_cham(imgs):outs = []for im in imgs:w = im.shape[1]if w > 300:outs.append(('ꨂꨣꩃ ꨌꩌ {61ꨯꨮꩀ', 0.78))elif w < 140:outs.append(('ꨂꨣꩃ ꨌꩌ', 0.96))else:outs.append(('{61_48}', 0.41))return outs, 0.01def _mock_viet(imgs):outs = []for im in imgs:w = im.shape[1]if w > 300:outs.append(('2ZwY Người Chăm', 0.89))elif w < 140:outs.append(('2ZwY', 0.62))else:outs.append(('(Người Chăm)', 0.96))return outs, 0.01router_split = app.AutoRoutingOCRWrapper(_mock_cham, _mock_viet, cham_w320_model=None, primary_ver='v24_1_r4')res_s, vers_s, _ = router_split.predict_with_provenance([dummy_mixed])assert vers_s == ['v24_1_r4+vi'], f"Expected intra-line split v24_1_r4+vi, got {vers_s}: {res_s}"assert 'ꨂꨣꩃ ꨌꩌ' in res_s[0][0] and '(Người Chăm)' in res_s[0][0], res_srouter_yr = app.AutoRoutingOCRWrapper(lambda imgs: ([('꩒) 200-2026', 0.87), ('1꩐0-200', 0.81), ('꩒꩐꩒꩖', 0.97)], 0.01),lambda imgs: ([('Năm 2000-2025', 0.98), ('1990-2000', 0.98), ('2026', 0.70)], 0.01),cham_w320_model=None,primary_ver='v24_1_r4',)blank = np.full((48, 240, 3), 250, dtype=np.uint8)res_y, vers_y, _ = router_yr.predict_with_provenance([blank, blank, blank])assert res_y[0][0] == 'Năm 2000-2025' and vers_y[0] == 'vi', (res_y[0], vers_y[0])assert res_y[1][0] == '1990-2000' and vers_y[1] == 'vi', (res_y[1], vers_y[1])assert res_y[2][0] == '꩒꩐꩒꩖' and vers_y[2] == 'v24_1_r4', (res_y[2], vers_y[2])class TestQualityGates(unittest.TestCase):pass
12345678910111213141516171819202122232 unmodified lines262728293031323334354 unmodified lines4041424344451 unmodified line474849505152535410 unmodified lines6566676869707172732 unmodified lines767778798081824 unmodified lines878889909192939495969798991001011022 unmodified lines105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153#!/usr/bin/env python3# -*- coding: utf-8 -*-"""Cham-OCR Studio -> RealScan-Gold v2 Ingestion & Verification CLI================================================================Ingests human-verified manuscript transcriptions exported from `https://ocr.cham.asia`(`cham_ocr_transcription.json` / `training_pairs_manifest.json` + page image, OR`ocr-studio/data/active_learning/corrections.jsonl`) into `ocr-benchmark/data/realscan_gold_v2/manifest.json`:- Enforces canonical Brahmic Logical Order (`normalize_unicode`).- Extracts lossless PNG line crops and locks every page & crop with SHA-256.- Verifies zero SHA-256 / exact-text collision against active training datasets."""import osimport sysimport jsonimport shutilimport hashlibimport argparsefrom datetime import datetime, timezoneimport cv22 unmodified linesPROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))sys.path.insert(0, os.path.join(PROJECT_ROOT, "ocr-training", "scripts"))from generate_data import normalize_unicodeMANIFEST_V2 = os.path.join(PROJECT_ROOT, "ocr-benchmark", "data", "realscan_gold_v2", "manifest.json")MANIFEST_V3 = os.path.join(PROJECT_ROOT, "ocr-benchmark", "data", "realscan_gold_v3", "manifest.json")def sha256_file(path: str) -> str:4 unmodified linesreturn h.hexdigest().lower()def ingest_page_json(image_path: str,export_json_path: str,1 unmodified linedomain: str = "user_verified_manuscript",manifest_path: str = MANIFEST_V2,project_root: str = PROJECT_ROOT,):assert os.path.exists(manifest_path), f"Missing {manifest_path}; run scripts/build_realscan_gold_v2.py first."assert os.path.exists(image_path) and os.path.exists(export_json_path)with open(manifest_path, "r", encoding="utf-8") as _mf:10 unmodified linesraw_lines = raw.get("lines") or raw.get("pairs") or []assert raw_lines, f"No lines/pairs found in {export_json_path}"v2_root = os.path.dirname(manifest_path)pages_dir = os.path.join(v2_root, "pages")crops_dir = os.path.join(v2_root, "crops")os.makedirs(pages_dir, exist_ok=True)os.makedirs(crops_dir, exist_ok=True)2 unmodified linesdoc_lines = []for idx, item in enumerate(raw_lines, start=1):txt = normalize_unicode((item.get("text") or item.get("gt") or "").strip())bbox = item.get("bbox")if not txt or not bbox or len(bbox) != 4:continue4 unmodified linescontinuecrop_p = os.path.join(crops_dir, f"{doc_id}_line_{idx:02d}.png")cv2.imwrite(crop_p, img[y0:y1, x0:x1])doc_lines.append({"line": len(doc_lines) + 1,"bbox": [x0, y0, x1, y1],"crop_relpath": os.path.relpath(crop_p, project_root).replace("\\", "/"),"crop_sha256": sha256_file(crop_p),"gt": txt,})assert doc_lines, "0 valid verified lines after filtering"manifest["documents"].append({"doc_id": doc_id,"source_type": "studio_human_verified_scan","archival_domain": domain,2 unmodified lines"page_sha256": sha256_file(dst_page),"line_count": len(doc_lines),"lines": doc_lines,})manifest["summary"]["real_camera_pages"] = sum(1 for d in manifest["documents"] if d["source_type"] in ("authentic_cham_poem_page", "studio_human_verified_scan"))manifest["summary"]["real_camera_lines"] = sum(d["line_count"] for d in manifest["documents"] if d["source_type"] in ("authentic_cham_poem_page", "studio_human_verified_scan"))manifest["summary"]["total_evaluated_lines"] = sum(len(d.get("lines", [])) for d in manifest["documents"])with open(manifest_path, "w", encoding="utf-8") as f:json.dump(manifest, f, indent=2, ensure_ascii=False)print(f"✅ Ingested `{doc_id}` ({len(doc_lines)} verified lines) -> {manifest_path}")return manifestdef main():ap = argparse.ArgumentParser(description="Ingest human-verified Studio exports into RealScan-Gold v2/v3")ap.add_argument("--image", help="Path to original manuscript page image")ap.add_argument("--studio-json", help="Path to exported Studio JSON (cham_ocr_transcription.json or training_pairs_manifest.json)")ap.add_argument("--doc-id", help="Unique document identifier (e.g. panduranga_folio_02)")ap.add_argument("--domain", default="user_verified_manuscript", help="Archival domain tag")ap.add_argument("--version", choices=["v2", "v3"], default="v3", help="Target RealScan-Gold version (default: v3)")ap.add_argument("--verify-manifest", action="store_true", help="Verify SHA-256 integrity of all RealScan-Gold assets")args = ap.parse_args()target_manifest = MANIFEST_V3 if args.version == "v3" else MANIFEST_V2if args.verify_manifest:m = json.load(open(target_manifest, "r", encoding="utf-8"))checked = 0for d in m["documents"]:if d.get("page_relpath"):p = os.path.join(PROJECT_ROOT, d["page_relpath"].replace("/", os.sep))assert sha256_file(p) == d["page_sha256"], f"Page SHA mismatch: {p}"checked += 1items = list(d.get("lines", []))for grp in (d.get("groups") or {}).values():items.extend(grp)for ln in items:cp = os.path.join(PROJECT_ROOT, ln["crop_relpath"].replace("/", os.sep))assert sha256_file(cp) == ln["crop_sha256"], f"Crop SHA mismatch: {cp}"checked += 1print(f"✅ RealScan-Gold {args.version} integrity verified: {checked} files match SHA-256 100%.")returnif not (args.image and args.studio_json and args.doc_id):ap.error("Provide --image, --studio-json, and --doc-id (or --verify-manifest)")ingest_page_json(args.image, args.studio_json, args.doc_id, domain=args.domain, manifest_path=target_manifest)if __name__ == "__main__":123456789101112131415161718192021222324252 unmodified lines28293031323334353637383940414243444 unmodified lines4950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981991 unmodified line20120220320420520620720820921021110 unmodified lines2222232242252262272282292302312322332342 unmodified lines2372382392402412422434 unmodified lines2482492502512522532542552562572582592602612622632642652662 unmodified lines269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395#!/usr/bin/env python3# -*- coding: utf-8 -*-"""Cham-OCR Studio -> RealScan-Gold (v2 / v3 / v4) Ingestion, Promotion & Verification CLI=======================================================================================Ingests and promotes human-verified manuscript transcriptions exported from `https://ocr.cham.asia`(`cham_ocr_transcription.json` single-page or multi-page batch export, or `training_pairs_manifest.json`)into `ocr-benchmark/data/realscan_gold_v{2,3,4}/manifest.json`:- Enforces canonical Brahmic Logical Order (`normalize_unicode`) on Cham textlines.- Enforces strict Anti-Circular Ground-Truth Gate on `v4`: rejects unverified Studio drafts(`status != "Verified"` and `human_verified != True`) unless explicitly attested by a namedhuman annotator (`--confirm-human-verified --annotator <name>`).- Extracts lossless PNG line crops (respecting manual Studio bbox edits/splits/merges) and locks SHA-256.- Recomputes `verified_gold` vs `staging_review_queue` summary counters cleanly."""import argparsefrom datetime import datetime, timezoneimport hashlibimport jsonimport osimport sysimport cv22 unmodified linesPROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))sys.path.insert(0, os.path.join(PROJECT_ROOT, "ocr-training", "scripts"))from generate_data import normalize_unicode # noqa: E402MANIFEST_V2 = os.path.join(PROJECT_ROOT, "ocr-benchmark", "data", "realscan_gold_v2", "manifest.json")MANIFEST_V3 = os.path.join(PROJECT_ROOT, "ocr-benchmark", "data", "realscan_gold_v3", "manifest.json")MANIFEST_V4 = os.path.join(PROJECT_ROOT, "ocr-benchmark", "data", "realscan_gold_v4", "manifest.json")MANIFEST_BY_VER = {"v2": MANIFEST_V2,"v3": MANIFEST_V3,"v4": MANIFEST_V4,}def sha256_file(path: str) -> str:4 unmodified linesreturn h.hexdigest().lower()def _normalize_line_text(raw_txt: str) -> str:s = (raw_txt or "").strip()if any("\uAA00" <= ch <= "\uAA5F" for ch in s):return normalize_unicode(s)return sdef recompute_v4_summary(manifest: dict) -> dict:docs = manifest.get("documents", [])verified_pages = [d for d in docs if d.get("split") == "verified_gold" and d.get("stratum") != "wikimedia_public_specimens"]verified_specs = [d for d in docs if d.get("split") == "verified_gold" and d.get("stratum") == "wikimedia_public_specimens"]staging_pages = [d for d in docs if d.get("split") == "staging_review_queue"]indep_staging = {d.get("source_collection_id") or d["doc_id"] for d in staging_pages}indep_all = {d.get("source_collection_id") or d["doc_id"] for d in docs}manifest["summary"] = {"synthetic_pages_included": 0,"verified_gold_pages": len(verified_pages),"verified_gold_page_lines": sum(len(d.get("lines", [])) for d in verified_pages),"verified_gold_specimens": sum(d.get("specimen_count", len(d.get("lines", []))) for d in verified_specs),"staging_new_physical_pages": len(staging_pages),"staging_independent_sources": len(indep_staging),"staging_draft_lines": sum(len(d.get("lines", [])) for d in staging_pages),"staging_cham_bearing_lines": sum((d.get("draft_ocr_summary") or {}).get("cham_bearing_lines", 0) for d in staging_pages),"total_physical_pages": len(verified_pages) + len(staging_pages),"total_independent_sources": len(indep_all),"strata_page_counts": {st: sum(1 for d in docs if d.get("stratum") == st and d.get("stratum") != "wikimedia_public_specimens")for st in sorted({d.get("stratum", "unknown") for d in docs if d.get("stratum") != "wikimedia_public_specimens"})},}return manifestdef _check_human_verified_gate(doc_payload: dict, raw_lines: list, annotator: str, confirm_human_verified: bool):status_slug = str(doc_payload.get("status") or "").strip().lower()all_lines_verified = bool(raw_lines) and all(bool(ln.get("human_verified")) for ln in raw_lines)if status_slug == "verified" or all_lines_verified:returnif confirm_human_verified and annotator and annotator.strip():returnraise ValueError(f"Anti-Circularity Gate rejected `{doc_payload.get('doc_id') or doc_payload.get('image_name')}`: "f"document status is {doc_payload.get('status')!r} and lines are not marked `human_verified: true`. ""Verify lines in Cham OCR Studio (`https://ocr.cham.asia`) so status becomes 'Verified', ""or pass `--confirm-human-verified --annotator <your_name>` if manually reviewed offline.")def promote_verified_v4(export_json_path: str,annotator: str = "studio_reviewer",review_round: int = 1,confirm_human_verified: bool = False,manifest_path: str = MANIFEST_V4,project_root: str = PROJECT_ROOT,) -> dict:"""Promotes one or more human-verified `staging_review_queue` folios in RealScan-Gold v4 to `verified_gold`."""assert os.path.exists(manifest_path), f"Missing {manifest_path}; run scripts/build_realscan_gold_v4.py first."assert os.path.exists(export_json_path), f"Missing Studio JSON: {export_json_path}"with open(manifest_path, "r", encoding="utf-8") as mf:manifest = json.load(mf)with open(export_json_path, "r", encoding="utf-8") as ef:payload = json.load(ef)doc_entries = payload.get("documents") if isinstance(payload.get("documents"), list) else [payload]assert doc_entries, f"No document payloads found in {export_json_path}"v4_root = os.path.dirname(manifest_path)crops_dir = os.path.join(v4_root, "crops")os.makedirs(crops_dir, exist_ok=True)by_id = {d["doc_id"]: d for d in manifest["documents"]}promoted = []for entry in doc_entries:raw_name = entry.get("doc_id") or entry.get("image_name") or entry.get("name") or ""doc_id = os.path.splitext(os.path.basename(str(raw_name)))[0]if doc_id not in by_id:raise KeyError(f"Cannot match doc_id {doc_id!r} in {manifest_path}")raw_lines = entry.get("lines") or entry.get("pairs") or []assert raw_lines, f"No lines found for `{doc_id}`"_check_human_verified_gate(entry, raw_lines, annotator=annotator, confirm_human_verified=confirm_human_verified)target_doc = by_id[doc_id]page_abs = os.path.join(project_root, target_doc["page_relpath"].replace("/", os.sep))assert os.path.exists(page_abs), (f"Missing local page image {page_abs}. Run `python scripts/build_realscan_gold_v4.py --fetch` first.")img = cv2.imread(page_abs)assert img is not None, f"Cannot decode {page_abs}"h, w = img.shape[:2]verified_lines = []for item in raw_lines:txt = _normalize_line_text(item.get("text") or item.get("gt") or "")bbox = item.get("bbox")if not txt or not bbox or len(bbox) != 4:continuex0, y0, x1, y1 = [int(round(v)) for v in bbox]x0, y0 = max(0, x0), max(0, y0)x1, y1 = min(w, x1), min(h, y1)if x1 - x0 < 6 or y1 - y0 < 6:continuel_idx = len(verified_lines) + 1crop_p = os.path.join(crops_dir, f"{doc_id}_gold_line_{l_idx:02d}.png")cv2.imwrite(crop_p, img[y0:y1, x0:x1])verified_lines.append({"line": l_idx,"bbox": [x0, y0, x1, y1],"polygon": item.get("polygon"),"crop_relpath": os.path.relpath(crop_p, project_root).replace("\\", "/"),"crop_sha256": sha256_file(crop_p),"gt": txt,"verified_by_human": True,"draft_prediction": item.get("original_text"),})assert verified_lines, f"0 valid verified lines remaining for `{doc_id}`"target_doc.update({"split": "verified_gold","verification_status": "human_verified","verified_by_human": True,"gold_eligible": True,"annotator_id": annotator.strip() if annotator else "studio_reviewer","review_round": int(review_round),"verified_at": datetime.now(timezone.utc).isoformat(),"line_count": len(verified_lines),"lines": verified_lines,})promoted.append((doc_id, len(verified_lines)))recompute_v4_summary(manifest)with open(manifest_path, "w", encoding="utf-8", newline="\n") as out_f:json.dump(manifest, out_f, indent=2, ensure_ascii=False)for did, lcnt in promoted:print(f"✅ Promoted `{did}` ({lcnt} human-verified lines, round={review_round}, annotator={annotator!r}) -> verified_gold")return manifestdef ingest_page_json(image_path: str,export_json_path: str,1 unmodified linedomain: str = "user_verified_manuscript",manifest_path: str = MANIFEST_V2,project_root: str = PROJECT_ROOT,annotator: str = "studio_reviewer",review_round: int = 1,confirm_human_verified: bool = False,):assert os.path.exists(manifest_path), f"Missing {manifest_path}"assert os.path.exists(image_path) and os.path.exists(export_json_path)with open(manifest_path, "r", encoding="utf-8") as _mf:10 unmodified linesraw_lines = raw.get("lines") or raw.get("pairs") or []assert raw_lines, f"No lines/pairs found in {export_json_path}"is_v4 = manifest.get("schema_version", "").startswith("4.")if is_v4:_check_human_verified_gate(raw, raw_lines, annotator=annotator, confirm_human_verified=confirm_human_verified)root_dir = os.path.dirname(manifest_path)pages_dir = os.path.join(root_dir, "pages")crops_dir = os.path.join(root_dir, "crops")os.makedirs(pages_dir, exist_ok=True)os.makedirs(crops_dir, exist_ok=True)2 unmodified linesdoc_lines = []for idx, item in enumerate(raw_lines, start=1):txt = _normalize_line_text(item.get("text") or item.get("gt") or "")bbox = item.get("bbox")if not txt or not bbox or len(bbox) != 4:continue4 unmodified linescontinuecrop_p = os.path.join(crops_dir, f"{doc_id}_line_{idx:02d}.png")cv2.imwrite(crop_p, img[y0:y1, x0:x1])ln_obj = {"line": len(doc_lines) + 1,"bbox": [x0, y0, x1, y1],"crop_relpath": os.path.relpath(crop_p, project_root).replace("\\", "/"),"crop_sha256": sha256_file(crop_p),"gt": txt,}if is_v4:ln_obj["verified_by_human"] = Truedoc_lines.append(ln_obj)assert doc_lines, "0 valid verified lines after filtering"new_doc = {"doc_id": doc_id,"source_type": "studio_human_verified_scan","archival_domain": domain,2 unmodified lines"page_sha256": sha256_file(dst_page),"line_count": len(doc_lines),"lines": doc_lines,}if is_v4:new_doc.update({"split": "verified_gold","verification_status": "human_verified","verified_by_human": True,"gold_eligible": True,"stratum": domain,"annotator_id": annotator,"review_round": int(review_round),})manifest["documents"].append(new_doc)recompute_v4_summary(manifest)else:manifest["documents"].append(new_doc)manifest["summary"]["real_camera_pages"] = sum(1 for d in manifest["documents"] if d["source_type"] in ("authentic_cham_poem_page", "studio_human_verified_scan"))manifest["summary"]["real_camera_lines"] = sum(d["line_count"] for d in manifest["documents"] if d["source_type"] in ("authentic_cham_poem_page", "studio_human_verified_scan"))manifest["summary"]["total_evaluated_lines"] = sum(len(d.get("lines", [])) for d in manifest["documents"])with open(manifest_path, "w", encoding="utf-8", newline="\n") as f:json.dump(manifest, f, indent=2, ensure_ascii=False)print(f"✅ Ingested `{doc_id}` ({len(doc_lines)} verified lines) -> {manifest_path}")return manifestdef verify_manifest_integrity(target_manifest: str, project_root: str = PROJECT_ROOT) -> dict:with open(target_manifest, "r", encoding="utf-8") as f:m = json.load(f)is_v4 = m.get("schema_version", "").startswith("4.")checked_files = 0missing_gitignored = 0for d in m["documents"]:if is_v4:if d["split"] == "verified_gold":assert d["verified_by_human"] is True and d["gold_eligible"] is True, f"Invalid gold flags on {d['doc_id']}"for ln in d.get("lines", []):assert ln.get("gt") and isinstance(ln["gt"], str), f"Gold line missing gt in {d['doc_id']}"elif d["split"] == "staging_review_queue":assert d["verified_by_human"] is False and d["gold_eligible"] is False, f"Staging leak on {d['doc_id']}"for ln in d.get("lines", []):assert ln.get("gt") is None, f"Circular GT violation in staging doc {d['doc_id']}!"if d.get("page_relpath"):p = os.path.join(project_root, d["page_relpath"].replace("/", os.sep))if os.path.exists(p):assert sha256_file(p) == d["page_sha256"], f"Page SHA mismatch: {p}"checked_files += 1elif is_v4 and not d.get("redistribution_allowed_in_git", True):missing_gitignored += 1else:raise FileNotFoundError(f"Missing required page file: {p}")items = list(d.get("lines", []))for grp in (d.get("groups") or {}).values():items.extend(grp)for ln in items:cp = os.path.join(project_root, ln["crop_relpath"].replace("/", os.sep))if os.path.exists(cp):assert sha256_file(cp) == ln["crop_sha256"], f"Crop SHA mismatch: {cp}"checked_files += 1elif is_v4 and not d.get("redistribution_allowed_in_git", True):missing_gitignored += 1else:raise FileNotFoundError(f"Missing required crop file: {cp}")return {"checked_files": checked_files, "missing_gitignored": missing_gitignored, "documents": len(m["documents"])}def main():ap = argparse.ArgumentParser(description="Ingest or promote human-verified Studio exports into RealScan-Gold v2/v3/v4")ap.add_argument("--image", help="Path to original manuscript page image (for brand-new page ingestion)")ap.add_argument("--studio-json", help="Path to exported Studio JSON (cham_ocr_transcription.json or training_pairs_manifest.json)")ap.add_argument("--doc-id", help="Unique document identifier (for brand-new page ingestion)")ap.add_argument("--domain", default="user_verified_manuscript", help="Archival domain / stratum tag")ap.add_argument("--version", choices=["v2", "v3", "v4"], default="v4", help="Target RealScan-Gold version (default: v4)")ap.add_argument("--promote-verified", action="store_true", help="Promote staging_review_queue folio(s) in v4 to verified_gold")ap.add_argument("--annotator", default="studio_reviewer", help="Human annotator identifier for provenance tracking")ap.add_argument("--review-round", type=int, default=1, help="Human verification round (1 = primary, 2 = dual-annotator adjudication)")ap.add_argument("--confirm-human-verified", action="store_true", help="Explicitly attest offline human verification if JSON status != 'Verified'")ap.add_argument("--verify-manifest", action="store_true", help="Verify SHA-256 & anti-circularity integrity of RealScan-Gold")args = ap.parse_args()target_manifest = MANIFEST_BY_VER[args.version]if args.verify_manifest:stats = verify_manifest_integrity(target_manifest)print(f"✅ RealScan-Gold {args.version} integrity & anti-circularity verified: "f"{stats['checked_files']} local files match SHA-256 100% "f"(documents={stats['documents']}, gitignored_unfetched={stats['missing_gitignored']}).")returnif args.promote_verified:if args.version != "v4" or not args.studio_json:ap.error("--promote-verified requires --version v4 and --studio-json")promote_verified_v4(args.studio_json,annotator=args.annotator,review_round=args.review_round,confirm_human_verified=args.confirm_human_verified,manifest_path=target_manifest,)returnif not (args.image and args.studio_json and args.doc_id):ap.error("Provide --promote-verified --studio-json ... OR --image, --studio-json, and --doc-id (or --verify-manifest)")ingest_page_json(args.image,args.studio_json,args.doc_id,domain=args.domain,manifest_path=target_manifest,annotator=args.annotator,review_round=args.review_round,confirm_human_verified=args.confirm_human_verified,)if __name__ == "__main__":
FUTURE_WORK.md+4
ocr-studio/app.py+453-41
ocr-studio/index.html+1-1
ocr-studio/static/js/studio.js+74-2
ocr-studio/tests/test_quality_gates.py+198
scripts/ingest_studio_to_realscan_gold.py+293-51