Spaces:
Running
Running
Deploy Cham-OCR V26.1 Priority A: Exact Pass-2 Recognizer Provenance (Zero Script Guessing) & Auto Router v2.2
Browse filesFiles changed (4)
- Dockerfile+2-2
- FUTURE_WORK.md+15-13
- ocr-studio/app.py+114-46
- ocr-studio/tests/test_quality_gates.py+99
18 unmodified lines192021222324252618 unmodified linesCOPY requirements.txt /app/requirements.txtRUN pip install --no-cache-dir -r requirements.txt# Force cache bust for updated app code & V26.1 Masked-SVTR + API Provenance Hardening + Auto Router v2.2RUN echo "Cache bust 2026-11-22T06:40:00Z - Cham-OCR Studio: V26.1 Masked-SVTR + P0/P1 API Contract & Provenance Hardening + Auto Router v2.2"# Copy application filesCOPY . /app18 unmodified lines192021222324252618 unmodified linesCOPY requirements.txt /app/requirements.txtRUN pip install --no-cache-dir -r requirements.txt# Force cache bust for updated app code & V26.1 Masked-SVTR + Exact Pass-2 Provenance (Priority A) + Auto Router v2.2RUN echo "Cache bust 2026-11-22T07:55:00Z - Cham-OCR Studio: V26.1 Masked-SVTR + Exact Pass-2 Provenance (Zero Script Guessing) + Auto Router v2.2"# Copy application filesCOPY . /app
113 unmodified lines114115116117118119120121122123124125126127128129130131132133134135113 unmodified lines8. **`V26.1` Frozen-Backbone + `BN`-Locked Masked-SVTR (`wise_s2_a65`, Promoted Live as `v24_1_r4` `1deee5f5ff351070`)**: Froze `backbone.conv1..blocks3` and locked their `BatchNorm2D` running statistics in `eval()` mode (`Global.freeze_bn_in_frozen_prefixes: true` in `tools/program.py`) across 16 epochs (2 Kaggle Dual T4x2 stages: `12,450.0s` Train Loop / `490.44s` Overhead / `12,940.44s` Wall-clock) with `5,801` calligraphic/bamboo-pen/elastic augmentation lines (`0` benchmark overlap). Preserved 100% linear mode connectivity with `v26_1_base`, enabling **all 6** in-basin `WiSE-FT` blends to pass **`6/6` `Frozen-838` Gates + `9/9` `RealScan-Gold v2` Promotion Checks**; winner `wise_s2_a65` (`1deee5f5ff351070`) reached `5.10%` Clean, `1.92%` Char, **`100.0%` (`280/280`)** 14 Symbols, `98.57%` Hyphens, `6.32%` FullPage, `2.73%` Stress-82, **`2.07%` Harum Crop (`2.96%` E2E)**, **`25.20%` OOD-180 Crop**, **`22.65%` OOD-12 E2E Doc CER** (`180/180`), and calibrated `T* = 0.8831` (`OOS ECE` `0.0165 -> 0.0039`).9. **`Cham-DBNet v3` Curved-Polygon Fine-Tuning & Inverse-Shrink Discovery (`REPORTS/CHAM_DBNET_V3_EVALUATION.md`)**: Trained 20 epochs on Kaggle Dual T4x2 (`3,537.0s` Train Loop / `3,915.5s` Wall-clock) on `detector_v3_2_poly` (`1,400` train / `160` val) and derived the exact analytical inverse expansion `unclip = 3.2` for `MakeShrinkMap(shrink_ratio=0.4)` ($h_k \approx 0.16 H$). Passed **`8/9` strict guards** (`Val-160` `95.1% -> 100.0%`, `short:5` `7.37% -> 6.68%`, `audit_18` `10.14% -> 9.75%`, `a4:1-4` `6.31% -> 6.13%`, `FullPage-50` `7.82% -> 7.59%`), while strictly holding `promoted = False` (`v1_poly_u1.8` retained active) due to `shrink_ratio = 0.4` eroding a `28px` single-glyph line on `a4:5` (`248/241`).10. **Tri-Specialist `Auto` Router v2.1 & `RealScan-Gold v3` (`434` Items)**: Upgraded `AutoRoutingOCRWrapper` (`V26.1 W=480` + `V24.1-R3.1 W=320` + multi-threaded MIT-compatible `PP-OCRv5-vi`) and built `RealScan-Gold v3` (`434` SHA-256-locked items covering **12/12 EFEO fonts**, **6/6 Held-Out weights**, curved *agal*, and bilingual Cham–Vietnamese commentary): `auto` preserves **`6/6` Gates**, cuts `OOD-v2` Crop CER to `24.55%` (`23.91%` / `24.56%` E2E across all 20 OOD pages), slashes Bilingual E2E CER from `64.53% -> 6.58%` (`28/28` lines), and averages **`5.56s/page` on CPU** (`< 15s` budget).11. **Independent Live Production Audit (`2026-11-22`, `REPORTS/live_v26_audit_2026_11_22/`) & API/Router Hardening (`Auto Router v2.2`)**: Executed a 947-call black-box E2E + Playwright Chrome audit across all 8 advertised modes on `https://ocr.cham.asia`:- **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`)** on 7 hyphen contexts, **`0%` Latin script leakage**, and **`0/4` blank/ruled/speckle false positives**.- **P0/P1 Provenance & API Contract Hardening (`ocr-studio/app.py`)**: 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 (eliminating `KeyError` → Cloudflare HTTP `502` in favor of HTTP `400` JSON), rejected invalid `method` / `reading_order` / degenerate `bbox` (`x2 <= x1` or out-of-bounds) with HTTP `400`, exposed per-line `selected_recognizer` provenance, and reclassified `v25` (`49.81%` E2E CER due to unmasked `W=480` padding & 162-token CTC Latin dispersion) under `Historical Baselines` (`V25 Bilingual (Legacy)`).- **`Auto Router v2.2` Digit-Heavy Vietnamese Fix & Benchmark Hygiene**: Added a low-Cham-ratio (`c_ratio < 0.35`) Latin+digit handoff branch to `AutoRoutingOCRWrapper` so numeral/punctuation-dense Vietnamese lines (e.g., `"Số trang: 0123456789, dấu ! ? : ; ( ) / -"` where `v_alpha < 0.42`) route cleanly to `vi`, and patched `scripts/benchmark_v26_cham_digits.py` to invert grayscale (`ImageOps.invert`) before cropping tight ink bounds and scoring via minimum-edit alignment.---## 5. Next-Generation Open Research Roadmap (`V27 Paleographic Generalization`, `Cham-DBNet v3.1` & Physical Archive Corpus)1. **`V27` Calligraphic Allograph Synthesis & Targeted Hard-Mining**:- **Close the Unseen Paleographic Hand Gap (`~18.5%–24%` OOD CER → `< 10%`)**: Synthesize diverse palm-leaf (*agal*) stylus incisions, bamboo-pen stroke modulation, and historical ligature allographs beyond modern printed *Noto Sans Cham*.- **ASCII Repeated-Digit CTC Anti-Collapse**: Apply variable `2–8px` inter-digit spacing + micro-dropout to repeated Latin numerals (`1990-2000`, `2000-2025`, `1999`) just as previously engineered for Cham numerals (`꩒꩐꩐꩞`).- **Boundary Punctuation & Thin Diacritic Hard-Mining**: Target line-final Danda/question retention (`꩝`, `?`) and high-confusion thin vowel/coda pairs (`ꨮ` ↔ `ꨩ`/`ꨱ`, `ꩌ` ↔ `ꨩ`/`ꩃ`, `ꨁ` ↔ `ꨄ`, `ꨰ` ↔ `ꨘ`).2. **`Cham-DBNet v3.1` (`MakeShrinkMap(shrink_ratio = 0.6)` + `unclip = 2.0..2.2`) & Pre-Detection Deskew (`> ±8°`)**: Prevent single-glyph erosion on `28px` lines (`test_387_a4_lvl5.png`) while adding lightweight global skew estimation prior to DBNet to eliminate steep-tilt E2E degradation (`-11°` / `-12°`).3. **Intra-Line Code-Switching & Multi-Column/Editorial Benchmark Separation**: Report decoupled *Polygon Detection IoU/F1*, *Strict CER*, and *Editorial-Normalized CER* (normalizing spacing before `꩝`/`꩞` and `–` ≡ `-`), alongside intra-line bilingual Cham–Vietnamese/French gloss evaluation.4. **Expert-Verified Physical Manuscript Hold-Out (`RealScan-Gold v4`, `≥ 50–100` Document-Split Folios) & Western Cham (*Cam Srak*)**: Partner with Cham scholars and community custodians to ingest document-split physical palm-leaf (*agal*), *kertas* ink manuscripts, mobile-photographed printed books, and Western Cham (*Cam Srak*) / epigraphic stone rubbings via `scripts/ingest_studio_to_realscan_gold.py`.---113 unmodified lines114115116117118119120121122123124125126127128129130131132133134135136137113 unmodified lines8. **`V26.1` Frozen-Backbone + `BN`-Locked Masked-SVTR (`wise_s2_a65`, Promoted Live as `v24_1_r4` `1deee5f5ff351070`)**: Froze `backbone.conv1..blocks3` and locked their `BatchNorm2D` running statistics in `eval()` mode (`Global.freeze_bn_in_frozen_prefixes: true` in `tools/program.py`) across 16 epochs (2 Kaggle Dual T4x2 stages: `12,450.0s` Train Loop / `490.44s` Overhead / `12,940.44s` Wall-clock) with `5,801` calligraphic/bamboo-pen/elastic augmentation lines (`0` benchmark overlap). Preserved 100% linear mode connectivity with `v26_1_base`, enabling **all 6** in-basin `WiSE-FT` blends to pass **`6/6` `Frozen-838` Gates + `9/9` `RealScan-Gold v2` Promotion Checks**; winner `wise_s2_a65` (`1deee5f5ff351070`) reached `5.10%` Clean, `1.92%` Char, **`100.0%` (`280/280`)** 14 Symbols, `98.57%` Hyphens, `6.32%` FullPage, `2.73%` Stress-82, **`2.07%` Harum Crop (`2.96%` E2E)**, **`25.20%` OOD-180 Crop**, **`22.65%` OOD-12 E2E Doc CER** (`180/180`), and calibrated `T* = 0.8831` (`OOS ECE` `0.0165 -> 0.0039`).9. **`Cham-DBNet v3` Curved-Polygon Fine-Tuning & Inverse-Shrink Discovery (`REPORTS/CHAM_DBNET_V3_EVALUATION.md`)**: Trained 20 epochs on Kaggle Dual T4x2 (`3,537.0s` Train Loop / `3,915.5s` Wall-clock) on `detector_v3_2_poly` (`1,400` train / `160` val) and derived the exact analytical inverse expansion `unclip = 3.2` for `MakeShrinkMap(shrink_ratio=0.4)` ($h_k \approx 0.16 H$). Passed **`8/9` strict guards** (`Val-160` `95.1% -> 100.0%`, `short:5` `7.37% -> 6.68%`, `audit_18` `10.14% -> 9.75%`, `a4:1-4` `6.31% -> 6.13%`, `FullPage-50` `7.82% -> 7.59%`), while strictly holding `promoted = False` (`v1_poly_u1.8` retained active) due to `shrink_ratio = 0.4` eroding a `28px` single-glyph line on `a4:5` (`248/241`).10. **Tri-Specialist `Auto` Router v2.1 & `RealScan-Gold v3` (`434` Items)**: Upgraded `AutoRoutingOCRWrapper` (`V26.1 W=480` + `V24.1-R3.1 W=320` + multi-threaded MIT-compatible `PP-OCRv5-vi`) and built `RealScan-Gold v3` (`434` SHA-256-locked items covering **12/12 EFEO fonts**, **6/6 Held-Out weights**, curved *agal*, and bilingual Cham–Vietnamese commentary): `auto` preserves **`6/6` Gates**, cuts `OOD-v2` Crop CER to `24.55%` (`23.91%` / `24.56%` E2E across all 20 OOD pages), slashes Bilingual E2E CER from `64.53% -> 6.58%` (`28/28` lines), and averages **`5.56s/page` on CPU** (`< 15s` budget).11. **Independent Live Production Audit (`2026-11-22`, `REPORTS/live_v26_audit_2026_11_22/`), Peer-Review Calibration & Priority A Hardening (`Auto Router v2.2`)**: Executed a 947-record black-box E2E + Playwright Chrome production audit across all 8 advertised modes on `https://ocr.cham.asia` (constituting an initial production audit and controlled baseline comparison across shared source images/transforms rather than a full real-world archival certification):- **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.---## 5. Evidence-Gated Research & Evaluation Roadmap (Priorities B -> C -> D)1. **Priority B — Methodological & Diagnostic Isolation Before Model Retraining**:- **Separate Fixed-Pipeline vs. Default-Workflow Benchmarks**: Distinguish *Fixed-Pipeline Recognition Comparison* (`reading_order='rows'` on single-column pages) from *Default-User-Workflow Evaluation* (`reading_order='auto'` evaluated on genuine multi-column layouts using explicit column-grouping and line-order metrics), preserving historical benchmark outputs without overwriting.- **Decouple Detector vs. Recognizer Errors & Audit Missed-Line Warnings**: Report *Detector Precision / Recall / F1*, *Missed-Line Error*, and *Matched-Line Recognition CER* separately (e.g., decomposing `synthetic_142`'s `7/8` detected lines and auditing whether `uncovered_ink_ratio >= 0.12` / `possible_missed_lines` catches single missed short lines despite `95.76%` recognition confidence).- **Strict CER Primary + Pre-Registered Philological Normalization**: Always publish **Strict CER** first; compute **Editorial-Normalized CER** only under pre-registered philological rules (never masking `–` deletions or arbitrary `:` / whitespace errors), score hyphens and numerals via positional alignment, and test Active Learning (`/save_correction`) strictly inside isolated non-production sandboxes.- **10-Dimension Acceptance Matrix (`PASS / FAIL / INCONCLUSIVE / NOT TESTED`)**: Replace subjective overall percentages with explicit status tracking across API contract, provenance, frozen non-regression, digits/punctuation, detector P/R/F1, multi-column order, intra/inter-line bilingual routing, multi-source real hold-out, confidence/page-risk calibration, and isolated sequential latency.2. **Priority C — Multi-Source Document-Split Physical Archive Hold-Out (`RealScan-Gold v4`)**:- Collect `>= 50–100` pages partitioned strictly by **independent document, scribe, collection, and capture condition** (preventing same-book or augmented-sibling leakage), with dual-annotator verified Cham Unicode Logical Order ground truth across palm-leaf (*agal*), *kertas* manuscripts, old printed books, and Western Cham (*Cam Srak*). Treat `geometry = 18.47%` CER as an observed benchmark result rather than an intrinsic model ceiling.3. **Priority D — Controlled Single-Factor Ablations to Gate `V27` & `DBNet` Decisions**:- Run controlled crop/width/spacing ablations on residual Cham numeral errors (`6.0%` tight-crop CER), repeated ASCII digits (`1990-2000`, testing whether losses stem from crop clipping, downscaling, training scarcity, or CTC decoding), `V25` crop behavior, intra-line Cham–Latin segments, and angle-sweep deskew A/B experiments (verifying both CER and line recall to guard against clipping border Cham diacritics before enabling any pre-detection deskew or `V27` retraining).---
275 unmodified lines27627727827928028128228328428597 unmodified lines383384385386387388389390852 unmodified lines1243124412451246124712482 unmodified lines125112521253125412551256125712581259126036 unmodified lines129712981299130013011302573 unmodified lines1876187718781879188018811882323 unmodified lines220622072208220922102211221222131 unmodified line221522162217221822192220222187 unmodified lines230923102311231223132314231523162317231823192320232123222323232423251 unmodified line232723282329233023312332233323342335233623372338233923402341234212 unmodified lines23552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238165 unmodified lines244724482449245024512452243 unmodified lines269626972698269927002701270227032704270527062707270827092710271127122713271427152716271721 unmodified lines273927402741274227432744274527462747274827492750275127522753275427552756275727584 unmodified lines276327642765276627672768276927702771792 unmodified lines356435653566356735683569357035711 unmodified line357335743575357635773578357935803581358235833584358535863587358835893590275 unmodified linesself.w320_ver = w320_verself.last_selected_versions = []def __call__(self, img_list):if not img_list:self.last_selected_versions = []return [], 0.0try:from scripts.generate_data import normalize_unicode as _norm_u97 unmodified linesfinal_results[i] = (c_txt, c_conf)selected_vers.append(c_ver)self.last_selected_versions = selected_versreturn final_results, 0.0def validate_requested_model(raw_model):"""Validates a client-supplied model identifier against ALLOWED_MODEL_IDS and local installation."""852 unmodified lines_model_manifest_cache[cache_key] = {}return _model_manifest_cache[cache_key]def calibrate_line_confidence(raw_conf, model_ver=None, text="", temperature=None):"""Post-hoc logit temperature scaling for recognizer confidence (identity when T=1.0)."""val = float(raw_conf)2 unmodified linesif val >= 1.0:return 1.0if temperature is None:target_ver = model_verif model_ver == 'auto':has_cham = any('\uAA00' <= ch <= '\uAA5F' for ch in (text or ''))target_ver = DEFAULT_CHAM_MODEL if has_cham else Nonemanifest = get_model_manifest(target_ver)try:T = float(manifest.get("confidence_temperature", 1.0))36 unmodified lines"dict_sha256_16": _file_fingerprint(p["dict_path"]),"rec_image_shape": rec_shape_info,"confidence_temperature": conf_temp})info["recognizers"] = recsif not det_model_info:info["detector"] = {"name": None, "mode": DET_MODE, "loaded": False}573 unmodified linesreturn Truereturn Falsedef segment_lines_advanced(img, base_coords, ocr_model):"""Advanced Multi-Crop Strategy with Risk-Gated Batched Inference"""323 unmodified linesif valid_imgs:try:print(f"DEBUG: [segment_lines_advanced] Calling ocr_model for Pass 1 ({len(valid_imgs)} images)...")results, _ = ocr_model(valid_imgs)sel_vers_p1 = getattr(ocr_model, 'last_selected_versions', None) or []print("DEBUG: [segment_lines_advanced] Pass 1 prediction finished.")for local_idx, (vi, res) in enumerate(zip(valid_indices, results)):pred_text, conf = res if res else ("", 0.0)1 unmodified linepass1_candidates[vi]["prediction"] = pred_textpass1_candidates[vi]["confidence"] = float(conf)pass1_candidates[vi]["pred_length"] = len(pred_text)if local_idx < len(sel_vers_p1):pass1_candidates[vi]["routed_version"] = sel_vers_p1[local_idx]except Exception as e:print(f"DEBUG: [segment_lines_advanced] Batch inference pass 1 failed: {e}")87 unmodified linespass2_candidates.append(cand_obj)line_meta["candidates"][ctype] = cand_obj# Run Batch Pass 2 with coordinate-level deduplicationt_pass2_rec = time.time()if pass2_candidates:# Cache for coordinate-level deduplication: (s, e) -> (prediction, confidence)seen_boxes = {}# Pre-populate seen_boxes with Pass 1 (safe) results to avoid re-running identical boxesfor line_meta in lines_meta:if "safe" in line_meta["candidates"]:safe_c = line_meta["candidates"]["safe"]seen_boxes[tuple(safe_c["crop_box"])] = (safe_c["prediction"], safe_c["confidence"])exec_candidates = [] # candidates that require actual OCR executiondeferred_copies = [] # candidates that will copy results from an identical box1 unmodified linefor cand in pass2_candidates:c_box = tuple(cand["crop_box"])if c_box in seen_boxes:res = seen_boxes[c_box]if res[0] != "" or res[1] > 0.0:cand["prediction"] = res[0]cand["confidence"] = res[1]cand["pred_length"] = len(res[0])else:deferred_copies.append((cand, c_box))else:exec_candidates.append(cand)seen_boxes[c_box] = ("", 0.0) # mark as pendingif exec_candidates:imgs = [preprocess_crop_for_rec(c["crop_img"]) for c in exec_candidates]12 unmodified linesif valid_imgs:try:print(f"DEBUG: [segment_lines_advanced] Calling ocr_model for Pass 2 ({len(valid_imgs)} images, deduplicated from {len(pass2_candidates)})...")results, _ = ocr_model(valid_imgs)print("DEBUG: [segment_lines_advanced] Pass 2 prediction finished.")for vi, res in zip(valid_indices, results):pred_text, conf = res if res else ("", 0.0)pred_text = pred_text.strip()exec_cand = exec_candidates[vi]exec_cand["prediction"] = pred_textexec_cand["confidence"] = float(conf)exec_cand["pred_length"] = len(pred_text)seen_boxes[tuple(exec_cand["crop_box"])] = (pred_text, float(conf))except Exception as e:print(f"DEBUG: [segment_lines_advanced] Batch inference pass 2 failed: {e}")# Process deferred copiesfor cand, c_box in deferred_copies:pred_text, conf = seen_boxes[c_box]cand["prediction"] = pred_textcand["confidence"] = confcand["pred_length"] = len(pred_text)recognition_batch_pass2_sec = time.time() - t_pass2_rec65 unmodified linesline_meta["crop_sanity_score"] = best_scoresel_data = cand_data[selected_ctype]# Flagsneeds_review_reasons = []243 unmodified linesif not final_crops:print("⚠️ DBNet found 0 text lines, falling back to Valley segmentation...")_, coords = segment_lines_valleys(img, window_size=win, min_dist=gap)final_crops, lines_metadata, adv_profiler = segment_lines_advanced(img, coords, ocr)profiler_dict.update(adv_profiler)profiler_dict['fallback'] = 'valley'doc_reasons.append('detector_found_no_lines')else:t_rec = time.time()rec_crops = [preprocess_crop_for_rec(c) for c in final_crops]rec_res, _ = ocr(rec_crops)rec_sec = time.time() - t_recprint(f"⏱️ DBNet batch recognition ({len(final_crops)} lines) took: {rec_sec:.4f}s")sel_vers = getattr(ocr, 'last_selected_versions', None) or []for idx, (pred_text, conf) in enumerate(rec_res):lines_metadata[idx]['candidates']['dbnet']['prediction'] = pred_textlines_metadata[idx]['candidates']['dbnet']['confidence'] = confif idx < len(sel_vers):lines_metadata[idx]['routed_version'] = sel_vers[idx]num_detected = len(lines_metadata)dropped_text_lines = []lines_metadata, final_crops = apply_line_quality_gates(lines_metadata, final_crops, dropped_text_lines)21 unmodified linest_adv = time.time()# Apply Advanced Segmentation and Multi-Cropfinal_crops, lines_metadata, adv_profiler = segment_lines_advanced(img, coords, ocr)profiler_dict.update(adv_profiler)print(f"⏱️ segment_lines_advanced took: {time.time() - t_adv:.4f}s")t_resp = time.time()# Prepare backward-compatible responseresults = []for idx, (line_img, meta) in enumerate(zip(final_crops, lines_metadata)):cand_sel = meta['candidates'][meta['selected_crop_type']]pred_text = cand_sel['prediction']confidence = cand_sel['confidence']if model_ver in ['auto', 'v24', 'v25', 'v26'] or str(model_ver).startswith('v24'):if model_ver != 'auto' or any('\uAA00' <= ch <= '\uAA5F' for ch in (pred_text or '')):try:from scripts.generate_data import normalize_unicodepred_text = normalize_unicode(pred_text)4 unmodified lines_, buffer = cv2.imencode('.png', line_img)line_b64 = base64.b64encode(buffer).decode('utf-8')cal_ver = meta.get('routed_version') or cand_sel.get('routed_version') or model_verif cal_ver == 'auto':cal_ver = DEFAULT_CHAM_MODEL if any('\uAA00' <= ch <= '\uAA5F' for ch in (pred_text or '')) else 'vi'cal_conf = calibrate_line_confidence(confidence, cal_ver, pred_text)# Backward-compatible format with explicit per-line recognizer provenance792 unmodified linestry:with _INFERENCE_LOCK:ocr = get_ocr_model(model_ver)res, _ = ocr([preprocess_crop_for_rec(crop_img)])sel_vers = list(getattr(ocr, 'last_selected_versions', None) or [])pred_text, conf = res[0] if res else ("", 0.0)except UnknownModelError as ume:self.send_json_response({'error': str(ume), 'allowed_models': list(ADVERTISED_MODEL_IDS)}, 400)1 unmodified lineexcept Exception as e:self.send_json_response({'error': f'Cropped OCR transcription error ({model_ver}): {e}'}, 500)returnif model_ver in ['auto', 'v24', 'v25', 'v26'] or str(model_ver).startswith('v24'):if model_ver != 'auto' or any('\uAA00' <= ch <= '\uAA5F' for ch in (pred_text or '')):try:from scripts.generate_data import normalize_unicodepred_text = normalize_unicode(pred_text)except Exception as e:print(f"Warning: normalize_unicode failed: {e}")sel_ver = sel_vers[0] if sel_vers else model_verif sel_ver == 'auto':sel_ver = DEFAULT_CHAM_MODEL if any('\uAA00' <= ch <= '\uAA5F' for ch in (pred_text or '')) else 'vi'_, buffer = cv2.imencode('.png', crop_img)crop_b64 = base64.b64encode(buffer).decode('utf-8')275 unmodified lines27627727827928028128228328428528697 unmodified lines384385386387388389390391392393394395852 unmodified lines1248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812892 unmodified lines129212931294129512961297129836 unmodified lines13351336133713381339134013411342573 unmodified lines1916191719181919192019211922323 unmodified lines2246224722482249225022512252225322541 unmodified line225622572258225922602261226287 unmodified lines23502351235223532354235523562357235823592360236123622363236423652366236723682369237023711 unmodified line237323742375237623772378237923802381238223832384238523862387238823892390239112 unmodified lines240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243765 unmodified lines25032504250525062507250825092510243 unmodified lines27542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277721 unmodified lines27992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528264 unmodified lines283128322833283428352836792 unmodified lines3629363036313632363336343635363636371 unmodified line36393640364136423643364436453646364736483649365036513652365336543655365636573658275 unmodified linesself.w320_ver = w320_verself.last_selected_versions = []def predict_with_provenance(self, img_list):"""Executes tri-specialist routing and returns (results, selected_versions, elapsed) directly."""if not img_list:self.last_selected_versions = []return [], [], 0.0try:from scripts.generate_data import normalize_unicode as _norm_u97 unmodified linesfinal_results[i] = (c_txt, c_conf)selected_vers.append(c_ver)self.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, elapseddef validate_requested_model(raw_model):"""Validates a client-supplied model identifier against ALLOWED_MODEL_IDS and local installation."""852 unmodified lines_model_manifest_cache[cache_key] = {}return _model_manifest_cache[cache_key]def resolve_actual_model_version(model_ver):"""Resolves canonical recognizer identifier from loaded on-disk paths / manifest (never 'auto')."""if not model_ver or model_ver == 'auto':return Nonep = ocr_model_paths.get(model_ver)if p and p.get("model_dir"):dir_base = os.path.basename(os.path.normpath(p["model_dir"]))inferred_ver = ("vi" if dir_base == "rec_vietnamese_infer"else (dir_base[len("rec_cham_inference_"):] if dir_base.startswith("rec_cham_inference_") else model_ver))manifest = get_model_manifest(inferred_ver)return str(manifest.get("model_id") or inferred_ver)manifest = get_model_manifest(model_ver)if manifest.get("model_id"):return str(manifest["model_id"])return str(model_ver)def invoke_recognizer_with_provenance(ocr_model, img_list, model_ver=None):"""Invokes a recognizer/router and returns (results, selected_versions, elapsed) without post-OCR script guessing."""if not img_list:return [], [], 0.0if hasattr(ocr_model, "predict_with_provenance"):res, sel_vers, elapsed = ocr_model.predict_with_provenance(img_list)return res, list(sel_vers), elapsedif hasattr(ocr_model, "last_selected_versions"):ocr_model.last_selected_versions = []res, elapsed = ocr_model(img_list)attr_vers = list(getattr(ocr_model, "last_selected_versions", None) or [])if len(attr_vers) == len(res):return res, attr_vers, elapsedsingle_ver = resolve_actual_model_version(model_ver)return res, [single_ver] * len(res), elapseddef calibrate_line_confidence(raw_conf, model_ver=None, text="", temperature=None):"""Post-hoc logit temperature scaling for recognizer confidence (identity when T=1.0)."""val = float(raw_conf)2 unmodified linesif val >= 1.0:return 1.0if temperature is None:target_ver = None if model_ver in (None, 'auto') else model_vermanifest = get_model_manifest(target_ver)try:T = float(manifest.get("confidence_temperature", 1.0))36 unmodified lines"dict_sha256_16": _file_fingerprint(p["dict_path"]),"rec_image_shape": rec_shape_info,"confidence_temperature": conf_temp})elif 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}573 unmodified linesreturn Truereturn Falsedef segment_lines_advanced(img, base_coords, ocr_model, model_ver=None):"""Advanced Multi-Crop Strategy with Risk-Gated Batched Inference"""323 unmodified linesif valid_imgs:try:print(f"DEBUG: [segment_lines_advanced] Calling ocr_model for Pass 1 ({len(valid_imgs)} images)...")results, sel_vers_p1, _ = invoke_recognizer_with_provenance(ocr_model, valid_imgs, model_ver=model_ver)print("DEBUG: [segment_lines_advanced] Pass 1 prediction finished.")for local_idx, (vi, res) in enumerate(zip(valid_indices, results)):pred_text, conf = res if res else ("", 0.0)1 unmodified linepass1_candidates[vi]["prediction"] = pred_textpass1_candidates[vi]["confidence"] = float(conf)pass1_candidates[vi]["pred_length"] = len(pred_text)if local_idx < len(sel_vers_p1) and sel_vers_p1[local_idx] is not None:pass1_candidates[vi]["routed_version"] = sel_vers_p1[local_idx]except Exception as e:print(f"DEBUG: [segment_lines_advanced] Batch inference pass 1 failed: {e}")87 unmodified linespass2_candidates.append(cand_obj)line_meta["candidates"][ctype] = cand_obj# Run Batch Pass 2 with coordinate-level deduplication (preserving exact recognizer provenance)t_pass2_rec = time.time()if pass2_candidates:# Cache for coordinate-level deduplication: (s, e) -> (prediction, confidence, routed_version)seen_boxes = {}pending_boxes = set()# Pre-populate seen_boxes with Pass 1 (safe) results to avoid re-running identical boxesfor line_meta in lines_meta:if "safe" in line_meta["candidates"]:safe_c = line_meta["candidates"]["safe"]seen_boxes[tuple(safe_c["crop_box"])] = (safe_c["prediction"],safe_c["confidence"],safe_c.get("routed_version"),)exec_candidates = [] # candidates that require actual OCR executiondeferred_copies = [] # candidates that will copy results from an identical box1 unmodified linefor cand in pass2_candidates:c_box = tuple(cand["crop_box"])if c_box in seen_boxes:if c_box in pending_boxes:deferred_copies.append((cand, c_box))else:p_txt, p_conf, p_ver = seen_boxes[c_box]cand["prediction"] = p_txtcand["confidence"] = p_confcand["pred_length"] = len(p_txt)if p_ver is not None:cand["routed_version"] = p_verelse:exec_candidates.append(cand)seen_boxes[c_box] = ("", 0.0, None)pending_boxes.add(c_box)if exec_candidates:imgs = [preprocess_crop_for_rec(c["crop_img"]) for c in exec_candidates]12 unmodified linesif valid_imgs:try:print(f"DEBUG: [segment_lines_advanced] Calling ocr_model for Pass 2 ({len(valid_imgs)} images, deduplicated from {len(pass2_candidates)})...")results, sel_vers_p2, _ = invoke_recognizer_with_provenance(ocr_model, valid_imgs, model_ver=model_ver)print("DEBUG: [segment_lines_advanced] Pass 2 prediction finished.")for local_idx, (vi, res) in enumerate(zip(valid_indices, results)):pred_text, conf = res if res else ("", 0.0)pred_text = pred_text.strip()r_ver = sel_vers_p2[local_idx] if local_idx < len(sel_vers_p2) else Noneexec_cand = exec_candidates[vi]exec_cand["prediction"] = pred_textexec_cand["confidence"] = float(conf)exec_cand["pred_length"] = len(pred_text)if r_ver is not None:exec_cand["routed_version"] = r_verseen_boxes[tuple(exec_cand["crop_box"])] = (pred_text, float(conf), r_ver)except Exception as e:print(f"DEBUG: [segment_lines_advanced] Batch inference pass 2 failed: {e}")# Process deferred copiesfor cand, c_box in deferred_copies:pred_text, conf, r_ver = seen_boxes[c_box]cand["prediction"] = pred_textcand["confidence"] = confcand["pred_length"] = len(pred_text)if r_ver is not None:cand["routed_version"] = r_verrecognition_batch_pass2_sec = time.time() - t_pass2_rec65 unmodified linesline_meta["crop_sanity_score"] = best_scoresel_data = cand_data[selected_ctype]if sel_data.get("routed_version") is not None:line_meta["routed_version"] = sel_data["routed_version"]# Flagsneeds_review_reasons = []243 unmodified linesif not final_crops:print("⚠️ DBNet found 0 text lines, falling back to Valley segmentation...")_, coords = segment_lines_valleys(img, window_size=win, min_dist=gap)final_crops, lines_metadata, adv_profiler = segment_lines_advanced(img, coords, ocr, model_ver=model_ver)profiler_dict.update(adv_profiler)profiler_dict['fallback'] = 'valley'doc_reasons.append('detector_found_no_lines')else:t_rec = time.time()rec_crops = [preprocess_crop_for_rec(c) for c in final_crops]rec_res, sel_vers, _ = invoke_recognizer_with_provenance(ocr, rec_crops, model_ver=model_ver)rec_sec = time.time() - t_recprint(f"⏱️ DBNet batch recognition ({len(final_crops)} lines) took: {rec_sec:.4f}s")for idx, (pred_text, conf) in enumerate(rec_res):lines_metadata[idx]['candidates']['dbnet']['prediction'] = pred_textlines_metadata[idx]['candidates']['dbnet']['confidence'] = confif idx < len(sel_vers) and sel_vers[idx] is not None:lines_metadata[idx]['routed_version'] = sel_vers[idx]lines_metadata[idx]['candidates']['dbnet']['routed_version'] = sel_vers[idx]num_detected = len(lines_metadata)dropped_text_lines = []lines_metadata, final_crops = apply_line_quality_gates(lines_metadata, final_crops, dropped_text_lines)21 unmodified linest_adv = time.time()# Apply Advanced Segmentation and Multi-Cropfinal_crops, lines_metadata, adv_profiler = segment_lines_advanced(img, coords, ocr, model_ver=model_ver)profiler_dict.update(adv_profiler)print(f"⏱️ segment_lines_advanced took: {time.time() - t_adv:.4f}s")t_resp = time.time()# Prepare backward-compatible response (provenance strictly from executed recognizer, never script-guessed)results = []for idx, (line_img, meta) in enumerate(zip(final_crops, lines_metadata)):cand_sel = meta['candidates'][meta['selected_crop_type']]pred_text = cand_sel['prediction']confidence = cand_sel['confidence']cal_ver = cand_sel.get('routed_version') or meta.get('routed_version')if 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:from scripts.generate_data import normalize_unicodepred_text = normalize_unicode(pred_text)4 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 provenance792 unmodified linestry:with _INFERENCE_LOCK:ocr = get_ocr_model(model_ver)res, sel_vers, _ = invoke_recognizer_with_provenance(ocr, [preprocess_crop_for_rec(crop_img)], model_ver=model_ver)pred_text, conf = res[0] if res else ("", 0.0)except UnknownModelError as ume:self.send_json_response({'error': str(ume), 'allowed_models': list(ADVERTISED_MODEL_IDS)}, 400)1 unmodified lineexcept Exception as e:self.send_json_response({'error': f'Cropped OCR transcription error ({model_ver}): {e}'}, 500)returnsel_ver = sel_vers[0] if sel_vers else (resolve_actual_model_version(model_ver) if model_ver != 'auto' else None)if (sel_ver and sel_ver not in ('vi', 'en', 'fr', 'japan')) and (sel_ver in ('v24', 'v25', 'v26') or str(sel_ver).startswith('v24')):if any('\uAA00' <= ch <= '\uAA5F' for ch in (pred_text or '')):try:from scripts.generate_data import normalize_unicodepred_text = normalize_unicode(pred_text)except Exception as e:print(f"Warning: normalize_unicode failed: {e}")_, buffer = cv2.imencode('.png', crop_img)crop_b64 = base64.b64encode(buffer).decode('utf-8')
734 unmodified lines735736737738739740734 unmodified lineshttpd.server_close()class TestQualityGates(unittest.TestCase):pass734 unmodified lines735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839734 unmodified lineshttpd.server_close()def test_priority_a_pass2_provenance_and_zero_script_guessing():"""Priority A regression: exact recognizer provenance across Pass 2 (valley/adaptive) & /ocr_crop without script guessing."""import base64from http.server import HTTPServerimport jsonimport threadingimport urllib.request# 1. calibrate_line_confidence must never infer recognizer temperature from output characters when model_ver='auto'assert app.calibrate_line_confidence(0.80, model_ver='auto', text='ꨀꨕꩅ') == 0.8assert app.calibrate_line_confidence(0.80, model_ver=None, text='ꨀꨕꩅ') == 0.8# 2. Construct a crisp synthetic line image that triggers Pass 1 (safe, taller) -> Pass 2 (tight, shorter)canvas = np.full((160, 360, 3), 255, dtype=np.uint8)for x in range(40, 310, 28):cv2.rectangle(canvas, (x, 66), (x + 14, 92), (15, 15, 15), -1)# Height of core ink is 26px (y=66..92).# Pass 1 'safe' crop expands >= 0.40 * h on top & bottom (~46px+ tall).# Pass 2 'tight' crop expands ~0.05 * h (~28px tall, ar48 = 360*48/28 is >420 unless cropped narrower;# make canvas width 200 so tight crop ~28x200 has ar48 = 200*48/28 = 342.8 in [104, 420) for W320!).canvas = canvas[:, :200].copy()def fake_w480(imgs):out = []for im in imgs:h = im.shape[0]if h >= 36:# Pass 1 safe/rescue/loose crops: low confidence (<0.75) to force Pass 2 executionout.append(('123 - 456', 0.62))else:# Pass 2 tight crop: sub-0.905 confidence so W=320 specialist adjudicatesout.append(('123 - 456', 0.82))return out, 0.0def fake_w320(imgs):# Pass 1 safe/rescue/loose crops stay <0.75 so Pass 2 is forced; Pass 2 tight crop (h < 36) wins with 0.94!return [('123 - 456', 0.65 if im.shape[0] >= 36 else 0.94) for im in imgs], 0.0def fake_vi(imgs):# Pure numerals/punctuation: v_lat_cnt == 0 -> Auto Router must NOT hand off to 'vi'return [('123 - 456', 0.91) for _ in imgs], 0.0router = app.AutoRoutingOCRWrapper(fake_w480, fake_vi, cham_w320_model=fake_w320, primary_ver='v24_1_r4', w320_ver='v24_1_r3_1')saved_auto = app.ocr_models.get('auto')app.ocr_models['auto'] = routertry:for seg_method in ('valley', 'adaptive'):resp = app.run_ocr_pipeline(canvas, model_ver='auto', method=seg_method)assert len(resp['lines']) == 1, (seg_method, resp)line = resp['lines'][0]assert line['segmentation']['selected_crop_type'] == 'tight', (seg_method, line)assert line['text'] == '123 - 456', (seg_method, line)# Crucial assertion: old post-OCR character check guessed 'vi' because '123 - 456' has no U+AA00..U+AA5F!# Exact Pass-2 provenance must report 'v24_1_r3_1'.assert line['selected_recognizer'] == 'v24_1_r3_1', (seg_method, line)# 3. Verify /ocr_crop with model='auto' on pure ASCII digits/hyphen ('7-8') reports 'v24_1_r4', never guesses 'vi'def crop_w480(imgs):return [('7-8', 0.95) for _ in imgs], 0.0def crop_vi(imgs):return [('7-8', 0.96) for _ in imgs], 0.0app.ocr_models['auto'] = app.AutoRoutingOCRWrapper(crop_w480, crop_vi, cham_w320_model=None, primary_ver='v24_1_r4')ok, buf = cv2.imencode('.png', canvas)assert okb64_img = base64.b64encode(buf.tobytes()).decode('ascii')httpd = HTTPServer(('127.0.0.1', 0), app.ChamOCRRequestHandler)port = httpd.server_address[1]th = threading.Thread(target=httpd.serve_forever, daemon=True)th.start()try:req = urllib.request.Request(f'http://127.0.0.1:{port}/ocr_crop',data=json.dumps({'image': b64_img, 'model': 'auto', 'bbox': [20, 55, 190, 105]}).encode('utf-8'),headers={'Content-Type': 'application/json'},method='POST',)with urllib.request.urlopen(req, timeout=10) as r:crop_body = json.loads(r.read().decode('utf-8'))assert crop_body['text'] == '7-8', crop_bodyassert crop_body['selected_recognizer'] == 'v24_1_r4', crop_bodyfinally:httpd.shutdown()httpd.server_close()finally:if saved_auto is None:app.ocr_models.pop('auto', None)else:app.ocr_models['auto'] = saved_autoclass TestQualityGates(unittest.TestCase):pass
Dockerfile+2-2
FUTURE_WORK.md+15-13
ocr-studio/app.py+114-46
ocr-studio/tests/test_quality_gates.py+99