Spaces:
Running
Running
Deploy Cham-OCR V26.1 API Provenance Hardening (P0/P1 HTTP 400), Auto Router v2.2 & V25 Legacy Reclassification
Browse filesFiles changed (9)
- DESIGN.md+86-112
- Dockerfile+2-2
- FUTURE_WORK.md+12-5
- ocr-studio/README_STUDIO.md+80-92
- ocr-studio/README_STUDIO_VI.md+62-74
- ocr-studio/app.py+246-60
- ocr-studio/help.html+10-15
- ocr-studio/index.html+3-3
- ocr-studio/tests/test_quality_gates.py+91
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112---version: alphaname: Cham OCR Review Studio Warm Light Themecolors:primary: "#2B2118"secondary: "#6F6257"tertiary: "#9A8D80"bg_app: "#FAF7F2"bg_canvas: "#F7F1EA"bg_panel: "#FFFCF7"bg_panel_soft: "#FBF5EE"bg_elevated: "#FFFFFF"border_subtle: "#E8DED2"border_medium: "#D8C9BA"border_strong: "#BFAE9D"accent: "#C96442"accent_hover: "#B55336"accent_soft: "#FFF0E8"accent_soft_2: "#FBE1D4"selection_bg: "#FFF0E8"selection_border: "#D97757"confidence_high: "#2F7D5C"confidence_high_bg: "#EAF6EF"confidence_medium: "#B7791F"confidence_medium_bg: "#FFF4D8"confidence_low: "#C4513B"confidence_low_bg: "#FDE8E2"typography:body:fontFamily: "Google Sans Flex, Google Sans, system-ui, -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, sans-serif"fontSize: "14px"fontWeight: "400"heading:fontFamily: "Google Sans Flex, Google Sans, system-ui, -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, sans-serif"fontSize: "20px"fontWeight: "700"cham:fontFamily: "Noto Sans Cham, Google Sans Flex, sans-serif"fontSize: "20px"fontWeight: "400"mono:fontFamily: "JetBrains Mono, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace"fontSize: "12px"fontWeight: "500"spacing:xs: "4px"sm: "8px"md: "16px"lg: "24px"xl: "32px"rounded:sm: "8px"md: "12px"lg: "18px"xl: "24px"---# Design System - Claude-inspired Warm Light Theme## OverviewCham OCR Studio (`https://ocr.cham.asia`) and its companion Technical Report (`/research`) use a warm, archival-parchment visual identity inspired by Claude's editorial aesthetic. Warm ivory surfaces, deep espresso ink typography, fine sand-toned borders, and terracotta accents evoke physical *kertas* bark-paper and *agal* palm-leaf manuscripts while minimizing eye strain during extended paleographic transcription sessions.## Colors- **App background**: `--bg-app` (`#FAF7F2`) — Primary workbench background.- **Canvas background**: `--bg-canvas` (`#F7F1EA`) — Manuscript viewer stage surface.- **Panel background**: `--bg-panel` (`#FFFCF7`) — Primary surfaces for headers, editors, modals, and cards.- **Soft panel surface**: `--bg-panel-soft` (`#FBF5EE`) — Queue sidebar, filter bars, and secondary toolbars.- **Elevated surface**: `--bg-elevated` (`#FFFFFF`) — Active inputs, command palette, and floating popovers.- **Text hierarchy**: `--text-primary` (`#2B2118`), `--text-secondary` (`#6F6257`), `--text-tertiary` (`#9A8D80`).- **Borders**: `--border-subtle` (`#E8DED2`), `--border-medium` (`#D8C9BA`), `--border-strong` (`#BFAE9D`).- **Terracotta accent**: `--accent` (`#C96442`), `--accent-hover` (`#B55336`), `--accent-soft` (`#FFF0E8`), `--accent-soft-2` (`#FBE1D4`).## Typography- **UI & Editorial Prose (`Google Sans Flex`)**: Used across all workbench controls, navigation, tables, and academic prose for crisp legibility at compact and display sizes.- **Paleographic Script (`Noto Sans Cham`)**: Dedicated rendering face for *Akhar Thrah* Unicode text (`U+AA00`–`U+AA5F`) with generous line-height (`1.75`–`1.95`) to prevent clipping of stacked above/below vowel diacritics and subjoined medials.- **Diagnostic Monospace (`JetBrains Mono`)**: Used for Unicode codepoints, SHA-256 model fingerprints, latency profilers, and runtime logs.## Layout & SpacingThe Studio uses a flexible **Resizable 3-Pane Workbench** with four instant layout presets:1. **Workbench (`3-Pane`)**: Resizable Corpus Queue Sidebar (`220px`–`420px`) + Manuscript Canvas + Resizable Transcription Editor (`340px`–`680px`).2. **Side-by-Side (`2-Pane`)**: Collapses the Queue Sidebar to maximize horizontal comparison between manuscript image and transcription lines.3. **Stacked Split (`Horizontal–Vertical`)**: Places wide horizontal palm-leaf (*agal*) manuscripts in a top viewport above a full-width transcription editor below.4. **Focus Reader**: Expands the transcription and continuous paragraph/stanza flow view into a centered scholarly reading column with inline line-crop strips.## ElevationDepth relies on hairline sand borders (`1px solid #E8DED2`) paired with warm, low-opacity espresso shadows (`rgba(43, 33, 24, 0.05)` to `rgba(43, 33, 24, 0.14)`) for floating surfaces such as the Command Palette (`Ctrl+K`), Virtual Keyboard (`Alt+K`), and Unicode Cluster Inspector.## ShapesControls and badges use `6px`–`8px` radii; panels, cards, and modals use `10px`–`14px` radii; status pills and segmented view switchers use pill/capsule geometry for clear visual grouping.## Components### Document status badges (Corpus Queue & Header)Status badges strictly reuse existing semantic tokens without introducing off-palette colors:- **OCR done** (`accent_soft` fill / `accent` text): Automatic OCR completed without quality-gate warnings. Never implies human verification.- **Needs review** (`confidence_medium_bg` / `confidence_medium`): Server quality gates or user flagged the folio (low confidence, uncovered ink, merged-height risk, or manual flag).- **No text** (`bg_panel` fill, dashed `border_subtle`, `tertiary` text): Blank or non-text folio detected by the ink-analysis gate.- **Verified** (`confidence_high_bg` / `confidence_high`): Awarded exclusively after a human scholar verifies every line on the folio.### Ergonomic Paleographic Surfaces (Progressive Disclosure & Zero-Clutter HUD)- **Floating Canvas Pill HUD**: Manuscript viewport controls (zoom, fit, rotate, draw box, spotlight mode, polygon contours, 2.6× loupe, and non-destructive optical filters) float inside a translucent warm-parchment capsule (`rgba(255, 252, 247, 0.92)` with `backdrop-filter: blur(10px)`) centered at the bottom of the manuscript canvas rather than stacking a second full-width top toolbar.- **Progressive Disclosure & Auto-Collapsing Queue**: Empty landing states hide empty sidebars and drawers to present a serene central intake stage; single-folio workflows collapse the Corpus Queue by default (`Alt+Q` toggle) while multi-folio batches auto-expand it; post-OCR tools and the Unicode Cluster Inspector (`Alt+U`) appear only when needed.- **Spotlight Bounding Boxes & Active-Line Focus Crop**: Unselected lines render subtle `1.5px` baseline rules instead of dense 4-sided rectangles, illuminating full core-band boxes only on hover or selection, while the active editor line unfolds its synced manuscript cutout strip directly above the input field to minimize left-right eye saccades.### Command Palette & Batch Progress Bar- **Command Palette (`Ctrl+K`)**: Centered elevated modal (`#FFFCF7`) with instant fuzzy search across upload, batch OCR, model switching, layout presets, canvas filters, and corpus export.- **Batch Queue Progress Strip**: Non-blocking progress bar inside the Corpus Queue showing processed/total folios, active filename, and a one-click Stop control.## Do's and Don'ts- **Do**: Preserve the warm ivory/parchment surfaces (`#FAF7F2`, `#F7F1EA`, `#FFFCF7`) and terracotta primary accent (`#C96442`) across every screen and modal.- **Do**: Keep sand-toned 1px borders (`#E8DED2`) and interactive drag-resizers subtle until hovered (`#C96442`).- **Don't**: Introduce pure black (`#000000`), cold slate grays, or neon blues/purples that clash with the archival manuscript tone.- **Don't**: Clip vertical line-height around Cham script containers where super/subscript vowel signs (`ꨪ`, `ꨭ`, `ꨳ`, `ꩌ`) extend beyond the core consonant band.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586---version: alphaname: Cham OCR Review Studio Warm Light Themecolors:primary: "#2B2118"secondary: "#6F6257"tertiary: "#9A8D80"bg_app: "#FAF7F2"bg_canvas: "#F7F1EA"bg_panel: "#FFFCF7"bg_panel_soft: "#FBF5EE"bg_elevated: "#FFFFFF"border_subtle: "#E8DED2"border_medium: "#D8C9BA"border_strong: "#BFAE9D"accent: "#C96442"accent_hover: "#B55336"accent_soft: "#FFF0E8"accent_soft_2: "#FBE1D4"selection_bg: "#FFF0E8"selection_border: "#D97757"confidence_high: "#2F7D5C"confidence_high_bg: "#EAF6EF"confidence_medium: "#B7791F"confidence_medium_bg: "#FFF4D8"confidence_low: "#C4513B"confidence_low_bg: "#FDE8E2"typography:body:fontFamily: "Google Sans Flex, Google Sans, system-ui, -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, sans-serif"fontSize: "14px"fontWeight: "400"heading:fontFamily: "Google Sans Flex, Google Sans, system-ui, -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, sans-serif"fontSize: "20px"fontWeight: "700"spacing:xs: "4px"sm: "8px"md: "16px"lg: "24px"xl: "32px"rounded:sm: "8px"md: "12px"lg: "18px"xl: "24px"---# Design System - Claude-inspired Warm Light Theme## OverviewGiao diện của Cham OCR Review Studio được thiết kế theo phong cách ấm áp, tinh tế và thanh lịch lấy cảm hứng từ Claude. Tông màu ngà ấm áp kết hợp với các bề mặt mềm mịn, chữ màu nâu sẫm, viền mảnh tự nhiên mang lại cảm giác thân thiện giống như sách giấy và tài liệu thực thụ. Thiết kế tập trung vào tính rõ ràng, trải nghiệm đọc lâu không mỏi mắt, và không gian làm việc chuyên nghiệp.## Colors- **App background**: `--bg-app` (#FAF7F2) - Màu nền chính của ứng dụng.- **Canvas background**: `--bg-canvas` (#F7F1EA) - Màu nền của Document Viewer.- **Panel background**: `--bg-panel` (#FFFCF7) - Bề mặt các bảng điều khiển và editor.- **Text Primary**: `--text-primary` (#2B2118) - Chữ màu nâu sẫm sần, độ tương phản cao, dễ đọc.- **Accent terracotta**: `--accent` (#C96442) - Màu nhấn đất nung/coral ấm, dùng cho các nút bấm chính, các trạng thái active và highlight bbox.## Typography- **Google Sans Flex**: Sử dụng font chữ hiện đại, tối giản và sắc nét đặc trưng của Google cho toàn bộ giao diện (logo, tiêu đề, và nội dung văn bản). Font chữ này hỗ trợ các trục biến đổi linh hoạt mang lại trải nghiệm đọc rất mượt mà và trực quan trên các màn hình hiển thị.## Layout & SpacingBố cục 3 cột rõ ràng ngăn nắp, khoảng cách lề vừa phải để người dùng tập trung tối đa vào tài liệu và các dòng hiệu chỉnh.## ElevationSử dụng bóng đổ rất nhẹ và mềm (`rgba(43, 33, 24, 0.06)`) kết hợp với viền mảnh để phân tách chiều sâu thay vì dùng các hiệu ứng nổi bật quá mức.## ShapesSử dụng các góc bo mềm mại ở mức vừa phải (8px đến 12px) để tạo cảm giác thân thiện nhưng vẫn giữ được sự chuyên nghiệp, ngăn nắp.## Components### Document status badges (hàng đợi bản thảo)Badge trạng thái chỉ dùng token màu sẵn có, không thêm màu mới:- **OCR done** (`accent_soft` nền / `accent` chữ): OCR tự động hoàn tất, không có cờ cảnh báo. Đây **không** phải là đã kiểm chứng.- **Needs review** (`confidence_medium_bg` / `confidence_medium`): server hoặc người dùng gắn cờ (độ tin cậy thấp, nghi bỏ sót dòng, nghi gộp dòng...).- **No text** (`bg_panel` nền, viền nét đứt `border_subtle`, chữ `tertiary`): trang trắng, không có chữ để phiên âm.- **Verified** (`confidence_high_bg` / `confidence_high`): chỉ hiển thị sau khi người dùng xác nhận **tất cả** các dòng (accept / sửa / thêm / tách / gộp). Hệ thống tự động không bao giờ gán trạng thái này.## Do's and Don'ts- **Nên**: Sử dụng màu nền ngà ấm cho các khung đọc sách và hiệu chỉnh.- **Nên**: Giữ viền mảnh màu cát sẫm (#E8DED2) để phân định các vùng làm việc rõ ràng.- **Không nên**: Sử dụng màu đen thuần (#000) hoặc xám lạnh cho chữ và nền.- **Không nên**: Sử dụng màu tím hoặc xanh neon quá chói làm xao nhãng người dùng.
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 (6/6 Gates) + Auto Router v2.1 + RealScan-Gold v3RUN echo "Cache bust 2026-11-22T01:30:00Z - Cham-OCR Studio: V26.1 Masked-SVTR (6/6 Gates, 1deee5f5ff351070) + Auto Router v2.1 + RealScan-Gold v3"# 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 + 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 . /app
113 unmodified lines114115116117118119120121122123124125126127128113 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).---## 5. Next-Generation Open Research Roadmap (`Cham-DBNet v3.1` & Physical Archive Corpus)1. **`Cham-DBNet v3.1` (`MakeShrinkMap(shrink_ratio = 0.6)` + `unclip = 2.0..2.2`)**: Prevent single-glyph erosion on `28px` lines (`test_387_a4_lvl5.png`) while retaining `v3`'s `100.0%` Val-160 poly-IoU and sub-`10%` `audit_18` E2E CER to clear all `9/9` strict detector guards.2. **Expert-Verified Physical Manuscript Expansion (`RealScan-Gold v4`)**: Ingest scholar-verified physical palm-leaf (*agal*) and *kertas* camera folios exported from Studio (`scripts/ingest_studio_to_realscan_gold.py --version v3`) to close the remaining paleographic gap on historical regional scribal hands.3. **Western Cham (*Cam Srak*) & Stone Rubbing Epigraphy**: Extend dictionary coverage, paleographic priors, and topological noise modeling to Western Cham manuscripts and eroded epigraphic stone rubbings.3. **Field Manuscript Active-Learning Expansion (`RealScan-Gold v3`)**: Partner with Cham scholars and community custodians to ingest verified palm-leaf (*agal*) and bark-paper (*kertas*) folios exported from `https://ocr.cham.asia` via `scripts/ingest_studio_to_realscan_gold.py`, closing the ~43%–44% paleographic domain gap observed on unseen historical regional hands (`efeo_regional_folio`).---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`.---
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192**English** | [Tiếng Việt](README_STUDIO_VI.md)# Cham OCR Studio: Paleographic Transcription & Diagnostic WorkbenchCham OCR Studio is an interactive paleographic document analysis and transcription environment designed for digitized historical Cham manuscripts (*Akhar Thrah* and *Cam Srak*). It features deep neural text recognition (PP-OCRv4 SVTR), Indic Line Segmentation (PaddleOCR DBNet + Valley-Cut Heuristics), continuous ground-truth editing, and a built-in virtual paleographic keyboard.> 🌟 **Live Interactive Web Demo**: **[https://ocr.cham.asia](https://ocr.cham.asia)** (mirrored on [Hugging Face Spaces](https://huggingface.co/spaces/phucsd/cham-ocr-studio))---## 📁 Studio Directory Structure```ocr-studio/├── README_STUDIO.md # This documentation (English)├── README_STUDIO_VI.md # Vietnamese documentation├── app.py # HTTP Server backend, OCR pipeline & ZIP corpus exporter├── paragraph_flow.py # Cham stanza & continuous paragraph reconstruction engine├── index.html # Modular Studio Workbench shell (Academic English)├── research.html # Synchronized Technical Report (/research)├── static/ # Separated frontend assets (Claude Warm Light Theme)│ ├── css/│ │ ├── studio.css # Resizable multi-pane workbench stylesheet│ │ └── research.css # Editorial technical report stylesheet│ └── js/│ ├── studio.js # Batch queue, PDF rasterizer, canvas & editor engine│ ├── cham-keyboard.js # Akhar Thrah 5/6/9-row virtual keyboard│ ├── transliteration.js # Unicode U+AA00..U+AA5F cluster inspector & Romanizer│ └── research.js # TOC filter, ScrollSpy & BibTeX helper├── start_studio.py # Quick-launch helper script├── PaddleOCR/ # Standalone PaddleOCR inference library└── data/ # Inference data & model assets├── ocr_corrections.txt # Verified textline corrections log├── active_learning/ # JSONL & PNG crop active-learning store├── cham_dict_v*.txt # Character dictionaries for model versions└── output/ # Exported model checkpoints (inference format)├── rec_cham_inference_v24_1_r4/├── rec_cham_inference_v25/├── rec_cham_inference_v24_1_r3_1/└── ch_PP-OCRv4_det_cham_infer/```---## ⚡ System Requirements & Installation1. Install project dependencies from the repository root:```bashpip install -r requirements.txt```*Note*: On modern Python runtimes (Python 3.10+ / 3.13+), NumPy 2.x backward-compatibility monkeypatching is automatically applied.2. Verify that inference models are present in `ocr-studio/data/output/` alongside the corresponding dictionaries in `ocr-studio/data/`.---## 🚀 Launching the StudioRun the application from the repository root or from within the `ocr-studio` directory:```bashpython ocr-studio/app.py```Alternatively, use the quick-launch script:```bashpython ocr-studio/start_studio.py```The server automatically binds to an open port (defaulting to `7860`, `8080`, `8081`...):```======================================================================🚀 Cham OCR Diagnostic Studio is running at: http://localhost:7860📁 Corrections will be saved to: ocr-studio/data/ocr_corrections.txt======================================================================```Open your browser and visit `http://localhost:7860`.---## ⌨️ Reviewer Keybindings| Key | Action | Description || :---: | :--- | :--- || **A** | **Approve** | Marks current line as verified ($100\%$ confidence) and moves to the next line. || **M** | **Merge Below** | Merges selected line with the subsequent line below into a unified crop. || **S** | **Split Line** | Splits selected line into two equal halves. || **W** | **Flag Error** | Flags current line as inaccurate ($0\%$ confidence) for retraining. || **Alt + K** | **Virtual Keyboard** | Toggles the Cham paleographic virtual keyboard drawer. || **Arrow Up / Down** | **Navigation** | Traverses previous and subsequent textlines. || **Double Click** | **In-Place Edit** | Activates inline text editing for the target line. |1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980**English** | [Tiếng Việt](README_STUDIO_VI.md)# Cham OCR Studio: Paleographic Transcription & Diagnostic WorkbenchCham OCR Studio is an interactive paleographic document analysis and transcription environment designed for digitized historical Cham manuscripts (*Akhar Thrah* and *Cam Srak*). It features deep neural text recognition (PP-OCRv4 SVTR), Indic Line Segmentation (PaddleOCR DBNet + Valley-Cut Heuristics), continuous ground-truth editing, and a built-in virtual paleographic keyboard.> 🌟 **Live Interactive Web Demo**: **[https://ocr.cham.asia](https://ocr.cham.asia)** (mirrored on [Hugging Face Spaces](https://huggingface.co/spaces/phucsd/cham-ocr-studio))---## 📁 Studio Directory Structure```ocr-studio/├── README_STUDIO.md # This documentation (English)├── README_STUDIO_VI.md # Vietnamese documentation├── app.py # HTTP Server backend & multi-crop orchestrator├── index.html # Frontend UI (Claude Warm Light Theme, Google Sans Flex)├── start_studio.py # Quick-launch helper script├── PaddleOCR/ # Standalone PaddleOCR inference library└── data/ # Inference data & model assets├── ocr_corrections.txt # Verified textline corrections log├── cham_dict_v*.txt # Character dictionaries for model versions└── output/ # Exported model checkpoints (inference format)├── rec_cham_inference_v24/├── rec_cham_inference_v23/├── rec_cham_inference_v22/└── rec_cham_inference_v21/```---## ⚡ System Requirements & Installation1. Install project dependencies from the repository root:```bashpip install -r requirements.txt```*Note*: On modern Python runtimes (Python 3.10+ / 3.13+), NumPy 2.x backward-compatibility monkeypatching is automatically applied.2. Verify that inference models are present in `ocr-studio/data/output/` alongside the corresponding dictionaries in `ocr-studio/data/`.---## 🚀 Launching the StudioRun the application from the repository root or from within the `ocr-studio` directory:```bashpython ocr-studio/app.py```Alternatively, use the quick-launch script:```bashpython ocr-studio/start_studio.py```The server automatically binds to an open port (defaulting to `7860`, `8080`, `8081`...):```======================================================================🚀 Cham OCR Diagnostic Studio is running at: http://localhost:7860📁 Corrections will be saved to: ocr-studio/data/ocr_corrections.txt======================================================================```Open your browser and visit `http://localhost:7860`.---## ⌨️ Reviewer Keybindings| Key | Action | Description || :---: | :--- | :--- || **A** | **Approve** | Marks current line as verified ($100\%$ confidence) and moves to the next line. || **M** | **Merge Below** | Merges selected line with the subsequent line below into a unified crop. || **S** | **Split Line** | Splits selected line into two equal halves. || **W** | **Flag Error** | Flags current line as inaccurate ($0\%$ confidence) for retraining. || **Alt + K** | **Virtual Keyboard** | Toggles the Cham paleographic virtual keyboard drawer. || **Arrow Up / Down** | **Navigation** | Traverses previous and subsequent textlines. || **Double Click** | **In-Place Edit** | Activates inline text editing for the target line. |
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374[English](README_STUDIO.md) | **Tiếng Việt**# Cham OCR Diagnostic Studio (Giao diện Chẩn đoán & Review OCR)Ứng dụng này cung cấp giao diện web để thử nghiệm, chẩn đoán lỗi phân đoạn dòng (Line Segmentation) và kiểm tra độ chính xác của các mô hình nhận diện chữ viết tiếng Chăm khác nhau.> 🌟 **Trải nghiệm Trực tuyến**: [https://ocr.cham.asia](https://ocr.cham.asia)## 📁 Cấu trúc Thư mục Phân hệ Studio```ocr-studio/├── README_STUDIO.md # Bản tiếng Anh├── README_STUDIO_VI.md # Hướng dẫn này (Tiếng Việt)├── app.py # Web Server Backend, Pipeline OCR & Xuất bản gói ZIP├── paragraph_flow.py # Thuật toán tái tạo đoạn văn & khổ thơ Chăm├── index.html # Giao diện Workbench chính (Academic English)├── research.html # Báo cáo khoa học đồng bộ (/research)├── static/ # Tách biệt tài nguyên Frontend (Claude Warm Light Theme)│ ├── css/│ │ ├── studio.css # Bố cục 3 cột kéo giãn & 4 chế độ xem│ │ └── research.css # Giao diện báo cáo học thuật│ └── js/│ ├── studio.js # Xử lý Batch OCR, PDF đa trang, Canvas & Editor│ ├── cham-keyboard.js # Bàn phím ảo Akhar Thrah (5/6/9 hàng)│ ├── transliteration.js # Soi cụm mã Unicode U+AA00..U+AA5F & Phiên âm Latinh│ └── research.js # Mục lục thông minh, thanh tiến độ đọc & trích dẫn BibTeX├── start_studio.py # Script khởi động nhanh giao diện├── PaddleOCR/ # Bản sao thư viện PaddleOCR phục vụ suy luận cục bộ└── data/ # Dữ liệu phục vụ suy luận├── ocr_corrections.txt # Lưu trữ các chỉnh sửa nhãn của người dùng├── active_learning/ # Kho mẫu huấn luyện JSONL + ảnh crop├── cham_dict_v*.txt # Từ điển ký tự các phiên bản mô hình└── output/ # Thư mục chứa các mô hình nhận diện đã xuất (inference model)├── rec_cham_inference_v24_1_r4/├── rec_cham_inference_v25/├── rec_cham_inference_v24_1_r3_1/└── ch_PP-OCRv4_det_cham_infer/```---## ⚡ Yêu cầu hệ thống & Cài đặt1. Cài đặt các thư viện cần thiết từ thư mục gốc:```bashpip install -r requirements.txt```*Lưu ý*: Đối với môi trường Python mới (như Python 3.13+), ứng dụng đã tự động vá lỗi tương thích NumPy 2.x bằng monkeypatch.2. Đảm bảo bạn đã có các mô hình inference trong `ocr-studio/data/output/` và file từ điển tương ứng trong `ocr-studio/data/`.---## 🚀 Hướng dẫn khởi chạyChạy lệnh sau tại thư mục gốc của dự án hoặc trong thư mục `ocr-studio`:```bashpython ocr-studio/app.py```Hoặc sử dụng tệp khởi chạy nhanh:```bashpython ocr-studio/start_studio.py```Ứng dụng sẽ tìm kiếm cổng trống thích hợp (mặc định: `7860`, `8080`, `8081`...) và khởi chạy:```🚀 Cham OCR Diagnostic Studio is running at: http://localhost:7860📁 Corrections will be saved to: ocr-studio/data/ocr_corrections.txt```Mở trình duyệt và truy cập `http://localhost:7860` để bắt đầu làm việc.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162[English](README_STUDIO.md) | **Tiếng Việt**# Cham OCR Diagnostic Studio (Giao diện Chẩn đoán & Review OCR)Ứng dụng này cung cấp giao diện web để thử nghiệm, chẩn đoán lỗi phân đoạn dòng (Line Segmentation) và kiểm tra độ chính xác của các mô hình nhận diện chữ viết tiếng Chăm khác nhau.> 🌟 **Trải nghiệm Trực tuyến**: [https://ocr.cham.asia](https://ocr.cham.asia)## 📁 Cấu trúc Thư mục Phân hệ Studio```ocr-studio/├── README_STUDIO.md # Bản tiếng Anh├── README_STUDIO_VI.md # Hướng dẫn này (Tiếng Việt)├── app.py # Script chạy ứng dụng Web Server & Studio Backend├── index.html # Frontend Claude Warm Light Theme (Giao diện tiếng Anh học thuật)├── start_studio.py # Script khởi động nhanh giao diện├── PaddleOCR/ # Bản sao thư viện PaddleOCR phục vụ suy luận cục bộ└── data/ # Dữ liệu ph��c vụ suy luận├── ocr_corrections.txt # Lưu trữ các chỉnh sửa nhãn của người dùng├── cham_dict_v*.txt # Từ điển ký tự các phiên bản mô hình└── output/ # Thư mục chứa các mô hình nhận diện đã xuất (inference model)├── rec_cham_inference_v24/├── rec_cham_inference_v23/├── rec_cham_inference_v22/└── rec_cham_inference_v21/```---## ⚡ Yêu cầu hệ thống & Cài đặt1. Cài đặt các thư viện cần thiết từ thư mục gốc:```bashpip install -r requirements.txt```*Lưu ý*: Đối với môi trường Python mới (như Python 3.13+), ứng dụng đã tự động vá lỗi tương thích NumPy 2.x bằng monkeypatch.2. Đảm bảo bạn đã có các mô hình inference trong `ocr-studio/data/output/` và file từ điển tương ứng trong `ocr-studio/data/`.---## 🚀 Hướng dẫn khởi chạyChạy lệnh sau tại thư mục gốc của dự án hoặc trong thư mục `ocr-studio`:```bashpython ocr-studio/app.py```Hoặc sử dụng tệp khởi chạy nhanh:```bashpython ocr-studio/start_studio.py```Ứng dụng sẽ tìm kiếm cổng trống thích hợp (mặc định: `7860`, `8080`, `8081`...) và khởi chạy:```🚀 Cham OCR Diagnostic Studio is running at: http://localhost:7860📁 Corrections will be saved to: ocr-studio/data/ocr_corrections.txt```Mở trình duyệt và truy cập `http://localhost:7860` để bắt đầu làm việc.
86 unmodified lines878889909192132 unmodified lines22522622722822923088 unmodified lines3193203213223233243 unmodified lines3283293303313323337 unmodified lines34134234334434534634734834946 unmodified lines396397398399400401402403404796 unmodified lines120112021203120412051206120712081209121012111212121312141215910 unmodified lines2126212721282129213021312132213321342135213621372138524 unmodified lines266326642665266626672668266926707 unmodified lines267826792680268126822683268426852686268726882689269026912692239 unmodified lines29322933293429352936293729382939294029412942294329442945294621 unmodified lines29682969297029712972297339 unmodified lines3013301430153016301730183019236 unmodified lines32563257325832593260326132623263326432653266326732687 unmodified lines32763277327832793280328132823283328432853286328732883289329032913292329332943295329632972 unmodified lines33003301330233033304330533064 unmodified lines33113312331333143315331633171 unmodified line33193320332133223323332433253326332733283 unmodified lines33323333333433353336333733382 unmodified lines334133423343334433453346334733483349335033513352335333543355335633573358335933601 unmodified line33623363336433653366336733685 unmodified lines337433753376337733783379338033813382338333843 unmodified lines33883389339033913392339333943395339633973 unmodified lines3401340234033404340534061 unmodified line340834093410341134123413341486 unmodified lines# 'cham' : Cham-DBNet only. 'generic': legacy detector only (pre-2026-11-04 behaviour).DET_MODE = os.getenv("DET_MODE", "hybrid").lower()DEFAULT_CHAM_MODEL = os.getenv("DEFAULT_CHAM_MODEL", "v24_1_r4")CHAM_DET_DB_THRESH = float(os.getenv("CHAM_DET_DB_THRESH", "0.3"))CHAM_DET_BOX_THRESH = float(os.getenv("CHAM_DET_BOX_THRESH", "0.4"))CHAM_DET_UNCLIP = float(os.getenv("CHAM_DET_UNCLIP", "1.8"))132 unmodified linesreturn lat_cnt / float(len(non_space))class AutoRoutingOCRWrapper:"""Tri-specialist adaptive router combining W=480 Cham primary, W=320 archival Cham adjudicator, and Vi/Latin OCR."""88 unmodified linesv_conf = float(v_conf)c_ratio = _cham_script_ratio(c_txt)v_alpha = _latin_alpha_ratio(v_txt)take_viet = Falseif v_alpha >= 0.42:3 unmodified lineselse:# 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_conf < 0.25 and v_conf > c_conf + 0.25:take_viet = True7 unmodified linesself.last_selected_versions = selected_versreturn final_results, 0.0def get_ocr_model(version):"""Loads and caches the PaddleOCR model for the given version dynamically"""global ocr_modelsif version in ocr_models:return ocr_models[version]46 unmodified linesmodel_dir = os.path.join(PROJECT_ROOT, "data", "output", f"rec_cham_inference_{version}")dict_path = os.path.join(PROJECT_ROOT, "data", f"cham_dict_{version}.txt")if not os.path.exists(model_dir):# Fallback to Golden Baseline v23 if version-specific folder is missingmodel_dir = os.path.join(PROJECT_ROOT, "data", "output", "rec_cham_inference_v23")if not os.path.exists(dict_path):bundled_dict = os.path.join(model_dir, f"cham_dict_{version}.txt")if os.path.exists(bundled_dict):796 unmodified linesfor v in rec_versions:p = ocr_model_paths.get(v)if p:manifest = get_model_manifest(v)try:conf_temp = float(manifest.get("confidence_temperature", 1.0))except (TypeError, ValueError):conf_temp = 1.0rec_shape_info = manifest.get("rec_image_shape") or ("3, 48, 480" if (v == "v25" or str(v).startswith("v24_1_r4")) else "3, 48, 320")recs.append({"version": v,"model_dir": os.path.relpath(p["model_dir"], PROJECT_ROOT).replace("\\", "/"),"weights_sha256_16": _file_fingerprint(os.path.join(p["model_dir"], "inference.pdiparams")),"dict": os.path.basename(p["dict_path"]),910 unmodified linestry:print(f"DEBUG: [segment_lines_advanced] Calling ocr_model for Pass 1 ({len(valid_imgs)} images)...")results, _ = ocr_model(valid_imgs)print("DEBUG: [segment_lines_advanced] Pass 1 prediction finished.")for vi, res in zip(valid_indices, results):pred_text, conf = res if res else ("", 0.0)pred_text = pred_text.strip()pass1_candidates[vi]["prediction"] = pred_textpass1_candidates[vi]["confidence"] = float(conf)pass1_candidates[vi]["pred_length"] = len(pred_text)except Exception as e:print(f"DEBUG: [segment_lines_advanced] Batch inference pass 1 failed: {e}")524 unmodified lines# Prepare backward-compatible responseresults = []for idx, (line_img, meta) in enumerate(zip(final_crops, lines_metadata)):pred_text = meta['candidates'][meta['selected_crop_type']]['prediction']confidence = meta['candidates'][meta['selected_crop_type']]['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 '')):7 unmodified lines_, buffer = cv2.imencode('.png', line_img)line_b64 = base64.b64encode(buffer).decode('utf-8')cal_ver = meta.get('routed_version') or model_vercal_conf = calibrate_line_confidence(confidence, cal_ver, pred_text)# Backward-compatible formatresults.append({'index': idx + 1,'text': pred_text,'confidence': float(confidence),'calibrated_confidence': cal_conf,'coords': meta['core_box'],'bbox': meta.get('bbox', [0, meta['core_box'][0], img.shape[1], meta['core_box'][1]]),'polygon': meta.get('polygon'),239 unmodified lines"summary": "Padding-masked wide-canvas pure-Cham recognizer with frozen early-backbone WiSE-FT (6/6 Gates, 2.07% real-camera CER, 22.65% OOD-12 E2E).","folder": "rec_cham_inference_v24_1_r4"},{"id": "v25","label": "Cham V25 (40-Epoch Dual-T4x2 Bilingual SOTA)","short_label": "V25 SOTA","group": "Paleographic Cham Specialists","shape": "3, 48, 480","summary": "Official 40-epoch Kaggle Dual-T4x2 SOTA (90.96% Seq Acc, 0.72% Val CER on 10K frozen validation).","folder": "rec_cham_inference_v25"},{"id": "auto","label": "Auto Tri-Specialist Router (Cham W480 + W320 + Vietnamese)",21 unmodified lines"summary": "100% accuracy across all 14 editorial symbols and multi-context hyphens.","folder": "rec_cham_inference_v24_1_r2_1_6"},{"id": "v24","label": "Cham V24 (Logical Order Baseline)",39 unmodified linesif installed and item["id"] != "vi":has_pdm = os.path.exists(os.path.join(mdir, "inference.pdmodel"))has_jsn = os.path.exists(os.path.join(mdir, "inference.json"))if has_jsn and not has_pdm and paddle_major < 3:installed = Falseentry = dict(item)entry["installed"] = installed236 unmodified lineselse:self.send_error(404, 'File Not Found')def do_POST(self):import timet_start = time.time()print(f"📥 Received POST request: {self.path}...")if self.path == '/log':content_length = int(self.headers['Content-Length'])post_data = self.rfile.read(content_length)try:log_data = json.loads(post_data.decode('utf-8'))print(f"\n🚨 [FRONTEND LOG] {log_data.get('message')}\n")7 unmodified linesreturnif self.path == '/ocr':content_length = int(self.headers['Content-Length'])post_data = self.rfile.read(content_length)print(f"⏱️ Read request body in: {time.time() - t_start:.4f}s")t_parse = time.time()data = json.loads(post_data.decode('utf-8'))# Extract parametersimg_b64 = data['image']model_ver = data.get('model') or DEFAULT_CHAM_MODELmethod = data.get('method', 'dbnet')threshold = float(data.get('threshold', 0.05))gap = int(data.get('gap', 12))win = int(data.get('window', 25))reading_order = data.get('reading_order', 'auto')if reading_order not in ('auto', 'rows'):reading_order = 'auto'# Decode imageif ',' in img_b64:2 unmodified linesif missing_padding:img_b64 += '=' * (4 - missing_padding)try:img_data = base64.b64decode(img_b64)nparr = np.frombuffer(img_data, np.uint8)img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)except Exception as e:4 unmodified linesprint(f"⏱️ Parsed parameters and decoded image in: {time.time() - t_parse:.4f}s")if img is None:self.send_json_response({'error': 'Unable to read image (corrupted base64 payload)'}, 400)return# Serialize Paddle C++ model loading & inference safely while keeping HTTP GET/health non-blocking1 unmodified linet_model = time.time()try:get_ocr_model(model_ver)except Exception as e:import tracebackprint(f"❌ Error loading OCR model '{model_ver}': {traceback.format_exc()}")self.send_json_response({'error': f'Model loading failure ({model_ver}): {e}'}, 200)returnprint(f"⏱️ Loaded model in: {time.time() - t_model:.4f}s")3 unmodified linesexcept Exception as e:import tracebackprint(f"❌ Error during OCR pipeline: {traceback.format_exc()}")self.send_json_response({'error': f'OCR transcription engine error: {e}'}, 200)returnt_send = time.time()2 unmodified linesprint(f"🎉 Total POST /ocr execution time: {response['profiler']['backend_total_sec']:.4f}s (document status: {response['document']['status']})")elif self.path == '/save_correction':content_length = int(self.headers['Content-Length'])post_data = self.rfile.read(content_length)data = json.loads(post_data.decode('utf-8'))with _CORRECTION_LOCK:result = save_correction_entry(data)self.send_json_response(result)elif self.path == '/ocr_crop':content_length = int(self.headers['Content-Length'])post_data = self.rfile.read(content_length)data = json.loads(post_data.decode('utf-8'))img_b64 = data.get('image', '')model_ver = data.get('model') or DEFAULT_CHAM_MODELbbox = data.get('bbox', [0, 0, 0, 0])if ',' in img_b64:img_b64 = img_b64.split(',', 1)[1]1 unmodified lineif missing_padding:img_b64 += '=' * (4 - missing_padding)try:img_data = base64.b64decode(img_b64)nparr = np.frombuffer(img_data, np.uint8)img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)except Exception as e:5 unmodified linesreturnh, w = img.shape[:2]x1, y1, x2, y2 = [int(v) for v in bbox]x1 = max(0, min(w - 1, x1))x2 = max(x1 + 1, min(w, x2))y1 = max(0, min(h - 1, y1))y2 = max(y1 + 1, min(h, y2))crop_img = img[y1:y2, x1:x2]if crop_img.size == 0:3 unmodified linestry:with _INFERENCE_LOCK:ocr = get_ocr_model(model_ver)res, _ = ocr([crop_img])pred_text, conf = res[0] if res else ("", 0.0)except Exception as e:self.send_json_response({'error': f'Cropped OCR transcription error ({model_ver}): {e}'}, 200)returnif model_ver in ['auto', 'v24', 'v25', 'v26'] or str(model_ver).startswith('v24'):3 unmodified linespred_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')1 unmodified lineself.send_json_response({'text': pred_text,'confidence': float(conf),'calibrated_confidence': calibrate_line_confidence(conf, model_ver, pred_text),'image': crop_b64,'crop_image': f"data:image/png;base64,{crop_b64}",'bbox': [x1, y1, x2, y2]86 unmodified lines87888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124132 unmodified lines25725825926026126226326426526626726826927088 unmodified lines3593603613623633643653 unmodified lines3693703713723733743753763773787 unmodified lines38638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242346 unmodified lines470471472473474475476477478479796 unmodified lines127612771278127912801281128212831284128512861287128812891290129112921293129412951296910 unmodified lines2207220822092210221122122213221422152216221722182219222022212222524 unmodified lines2747274827492750275127522753275427557 unmodified lines276327642765276627672768276927702771277227732774277527762777277827792780239 unmodified lines30203021302230233024302521 unmodified lines304730483049305030513052305330543055305630573058305930603061306239 unmodified lines3102310331043105310631073108236 unmodified lines334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833797 unmodified lines3387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634372 unmodified lines34403441344234433444344534463447344834494 unmodified lines34543455345634573458345934601 unmodified line34623463346434653466346734683469347034713472347334743 unmodified lines34783479348034813482348334842 unmodified lines34873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835291 unmodified line35313532353335343535353635373538353935405 unmodified lines3546354735483549355035513552355335543555355635573558355935603 unmodified lines356435653566356735683569357035713572357335743575357635773 unmodified lines35813582358335843585358635873588358935901 unmodified line35923593359435953596359735983599360086 unmodified lines# 'cham' : Cham-DBNet only. 'generic': legacy detector only (pre-2026-11-04 behaviour).DET_MODE = os.getenv("DET_MODE", "hybrid").lower()DEFAULT_CHAM_MODEL = os.getenv("DEFAULT_CHAM_MODEL", "v24_1_r4")ADVERTISED_MODEL_IDS = ("v24_1_r4","auto","v24_1_r3_1","v24_1_r2_1_6","vi","v25","v24","v23",)ALLOWED_MODEL_IDS = ("v24_1_r4","auto","v24_1_r3_1","v24_1_r3","v24_1_r2_1_6","v25","v24","v23","v22","vi","en","fr","japan",)ALLOWED_SEG_METHODS = ("dbnet", "valley", "adaptive")ALLOWED_READING_ORDERS = ("auto", "rows")class UnknownModelError(ValueError):"""Raised when a client requests a non-existent or uninstalled recognizer model ID."""passCHAM_DET_DB_THRESH = float(os.getenv("CHAM_DET_DB_THRESH", "0.3"))CHAM_DET_BOX_THRESH = float(os.getenv("CHAM_DET_BOX_THRESH", "0.4"))CHAM_DET_UNCLIP = float(os.getenv("CHAM_DET_UNCLIP", "1.8"))132 unmodified linesreturn lat_cnt / float(len(non_space))def _latin_alpha_count(text):return sum(1 for ch in (text or '') if ('a' <= ch.lower() <= 'z') or ('\u00C0' <= ch <= '\u1EF9'))def _has_viet_diacritics(text):return any('\u00C0' <= ch <= '\u1EF9' for ch in (text or ''))class AutoRoutingOCRWrapper:"""Tri-specialist adaptive router combining W=480 Cham primary, W=320 archival Cham adjudicator, and Vi/Latin OCR."""88 unmodified linesv_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:3 unmodified lineselse:# 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 = True7 unmodified linesself.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."""if raw_model is None:ver = DEFAULT_CHAM_MODELelif isinstance(raw_model, str):ver = raw_model.strip() or DEFAULT_CHAM_MODELelse:raise UnknownModelError("Invalid 'model' parameter: expected a model identifier string.")if ver not in ALLOWED_MODEL_IDS:raise UnknownModelError(f"Unknown model '{ver}'. Allowed models: {', '.join(ADVERTISED_MODEL_IDS)}")if ver not in ('auto', 'vi', 'en', 'fr', 'japan'):mdir = os.path.join(PROJECT_ROOT, "data", "output", f"rec_cham_inference_{ver}")has_weights = os.path.exists(os.path.join(mdir, "inference.pdiparams")) and (os.path.exists(os.path.join(mdir, "inference.pdmodel"))or os.path.exists(os.path.join(mdir, "inference.json")))if not os.path.isdir(mdir) or not has_weights:raise UnknownModelError(f"Model '{ver}' is not installed on this server. Allowed installed models: "f"{', '.join(m['id'] for m in list_available_models()['models'] if m.get('installed'))}")return verdef get_ocr_model(version):"""Loads and caches the PaddleOCR model for the given version dynamically"""global ocr_modelsversion = validate_requested_model(version)if version in ocr_models:return ocr_models[version]46 unmodified linesmodel_dir = os.path.join(PROJECT_ROOT, "data", "output", f"rec_cham_inference_{version}")dict_path = os.path.join(PROJECT_ROOT, "data", f"cham_dict_{version}.txt")if not os.path.isdir(model_dir):raise UnknownModelError(f"Model directory missing for '{version}': expected rec_cham_inference_{version} (silent fallback is disabled).")if not os.path.exists(dict_path):bundled_dict = os.path.join(model_dir, f"cham_dict_{version}.txt")if os.path.exists(bundled_dict):796 unmodified linesfor v in rec_versions:p = ocr_model_paths.get(v)if p: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 v))manifest = get_model_manifest(inferred_ver)actual_ver = str(manifest.get("model_id") or inferred_ver)try:conf_temp = float(manifest.get("confidence_temperature", 1.0))except (TypeError, ValueError):conf_temp = 1.0rec_shape_info = manifest.get("rec_image_shape") or ("3, 48, 480" if (actual_ver == "v25" or str(actual_ver).startswith("v24_1_r4")) else "3, 48, 320")recs.append({"version": actual_ver,"model_dir": os.path.relpath(p["model_dir"], PROJECT_ROOT).replace("\\", "/"),"weights_sha256_16": _file_fingerprint(os.path.join(p["model_dir"], "inference.pdiparams")),"dict": os.path.basename(p["dict_path"]),910 unmodified linestry: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)pred_text = pred_text.strip()pass1_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}")524 unmodified lines# 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 '')):7 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 provenanceresults.append({'index': idx + 1,'text': pred_text,'confidence': float(confidence),'calibrated_confidence': cal_conf,'selected_recognizer': cal_ver,'coords': meta['core_box'],'bbox': meta.get('bbox', [0, meta['core_box'][0], img.shape[1], meta['core_box'][1]]),'polygon': meta.get('polygon'),239 unmodified lines"summary": "Padding-masked wide-canvas pure-Cham recognizer with frozen early-backbone WiSE-FT (6/6 Gates, 2.07% real-camera CER, 22.65% OOD-12 E2E).","folder": "rec_cham_inference_v24_1_r4"},{"id": "auto","label": "Auto Tri-Specialist Router (Cham W480 + W320 + Vietnamese)",21 unmodified lines"summary": "100% accuracy across all 14 editorial symbols and multi-context hyphens.","folder": "rec_cham_inference_v24_1_r2_1_6"},{"id": "v25","label": "Cham V25 (40-Epoch Dual-T4x2 Bilingual — Legacy Unmasked)","short_label": "V25 Bilingual (Legacy)","group": "Historical Baselines","shape": "3, 48, 480","deprecated": True,"summary": "40-epoch Kaggle Dual-T4x2 162-token bilingual model (90.96% Seq Acc / 0.72% CER on 10K in-domain validation; superseded in E2E production by V26.1 + Auto Router due to unmasked W=480 padding & CTC Latin dispersion).","folder": "rec_cham_inference_v25"},{"id": "v24","label": "Cham V24 (Logical Order Baseline)",39 unmodified linesif installed and item["id"] != "vi":has_pdm = os.path.exists(os.path.join(mdir, "inference.pdmodel"))has_jsn = os.path.exists(os.path.join(mdir, "inference.json"))if has_jsn and not has_pdm and 0 < paddle_major < 3:installed = Falseentry = dict(item)entry["installed"] = installed236 unmodified lineselse:self.send_error(404, 'File Not Found')def _read_json_object(self, allow_empty=False):try:content_length = int(self.headers.get('Content-Length') or 0)except (TypeError, ValueError):self.send_json_response({'error': 'Invalid Content-Length header'}, 400)return Noneif content_length <= 0:if allow_empty:return {}self.send_json_response({'error': 'Empty request body (expected JSON object)'}, 400)return Nonepost_data = self.rfile.read(content_length)try:data = json.loads(post_data.decode('utf-8'))except Exception as e:self.send_json_response({'error': f'Invalid JSON payload: {e}'}, 400)return Noneif not isinstance(data, dict):self.send_json_response({'error': 'JSON payload must be an object'}, 400)return Nonereturn datadef do_POST(self):import timet_start = time.time()print(f"📥 Received POST request: {self.path}...")if self.path == '/log':content_length = int(self.headers.get('Content-Length') or 0)post_data = self.rfile.read(content_length) if content_length > 0 else b'{}'try:log_data = json.loads(post_data.decode('utf-8'))print(f"\n🚨 [FRONTEND LOG] {log_data.get('message')}\n")7 unmodified linesreturnif self.path == '/ocr':data = self._read_json_object()if data is None:returnprint(f"⏱️ Read request body in: {time.time() - t_start:.4f}s")t_parse = time.time()# 1. Validate model against strict allowlist (prevents silent fallback / fake provenance)try:model_ver = validate_requested_model(data.get('model'))except UnknownModelError as ume:self.send_json_response({'error': str(ume), 'allowed_models': list(ADVERTISED_MODEL_IDS)}, 400)return# 2. Validate segmentation method, reading order, and numeric parameters explicitlymethod_raw = data.get('method')method = 'dbnet' if method_raw is None else str(method_raw).strip().lower()if method not in ALLOWED_SEG_METHODS:self.send_json_response({'error': f"Invalid segmentation method '{method_raw}'. Allowed methods: {', '.join(ALLOWED_SEG_METHODS)}",'allowed_methods': list(ALLOWED_SEG_METHODS),}, 400)returnorder_raw = data.get('reading_order')reading_order = 'auto' if order_raw is None else str(order_raw).strip().lower()if reading_order not in ALLOWED_READING_ORDERS:self.send_json_response({'error': f"Invalid reading_order '{order_raw}'. Allowed values: {', '.join(ALLOWED_READING_ORDERS)}",'allowed_reading_orders': list(ALLOWED_READING_ORDERS),}, 400)returntry:threshold = float(data.get('threshold', 0.05))gap = int(data.get('gap', 12))win = int(data.get('window', 25))except (TypeError, ValueError) as pe:self.send_json_response({'error': f'Invalid numeric segmentation parameter: {pe}'}, 400)return# 3. Validate image field presence before base64/OpenCV decoding (eliminates KeyError -> HTTP 502)if 'image' not in data or not isinstance(data.get('image'), str) or not data['image'].strip():self.send_json_response({'error': "Missing or empty 'image' field (expected base64-encoded image)"}, 400)returnimg_b64 = data['image'].strip()# Decode imageif ',' in img_b64:2 unmodified linesif missing_padding:img_b64 += '=' * (4 - missing_padding)try:img_data = base64.b64decode(img_b64, validate=False)if not img_data:self.send_json_response({'error': 'Decoded image payload is empty'}, 400)returnnparr = np.frombuffer(img_data, np.uint8)img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)except Exception as e:4 unmodified linesprint(f"⏱️ Parsed parameters and decoded image in: {time.time() - t_parse:.4f}s")if img is None:self.send_json_response({'error': 'Unable to read image (unsupported format or corrupted base64 payload)'}, 400)return# Serialize Paddle C++ model loading & inference safely while keeping HTTP GET/health non-blocking1 unmodified linet_model = time.time()try:get_ocr_model(model_ver)except UnknownModelError as ume:self.send_json_response({'error': str(ume), 'allowed_models': list(ADVERTISED_MODEL_IDS)}, 400)returnexcept Exception as e:import tracebackprint(f"❌ Error loading OCR model '{model_ver}': {traceback.format_exc()}")self.send_json_response({'error': f'Model loading failure ({model_ver}): {e}'}, 500)returnprint(f"⏱️ Loaded model in: {time.time() - t_model:.4f}s")3 unmodified linesexcept Exception as e:import tracebackprint(f"❌ Error during OCR pipeline: {traceback.format_exc()}")self.send_json_response({'error': f'OCR transcription engine error: {e}'}, 500)returnt_send = time.time()2 unmodified linesprint(f"🎉 Total POST /ocr execution time: {response['profiler']['backend_total_sec']:.4f}s (document status: {response['document']['status']})")elif self.path == '/save_correction':data = self._read_json_object()if data is None:returnwith _CORRECTION_LOCK:result = save_correction_entry(data)self.send_json_response(result)elif self.path == '/ocr_crop':data = self._read_json_object()if data is None:returntry:model_ver = validate_requested_model(data.get('model'))except UnknownModelError as ume:self.send_json_response({'error': str(ume), 'allowed_models': list(ADVERTISED_MODEL_IDS)}, 400)returnif 'image' not in data or not isinstance(data.get('image'), str) or not data['image'].strip():self.send_json_response({'error': "Missing or empty 'image' field (expected base64-encoded image)"}, 400)returnimg_b64 = data['image'].strip()raw_bbox = data.get('bbox')if not isinstance(raw_bbox, (list, tuple)) or len(raw_bbox) != 4:self.send_json_response({'error': "Invalid 'bbox': expected a 4-element array [x1, y1, x2, y2]"}, 400)returntry:rx1, ry1, rx2, ry2 = [float(v) for v in raw_bbox]except (TypeError, ValueError):self.send_json_response({'error': "Invalid 'bbox': coordinates must be numbers"}, 400)returnif not (math.isfinite(rx1) and math.isfinite(ry1) and math.isfinite(rx2) and math.isfinite(ry2)):self.send_json_response({'error': "Invalid 'bbox': coordinates must be finite numbers"}, 400)returnif rx2 <= rx1 or ry2 <= ry1:self.send_json_response({'error': f"Invalid 'bbox' {list(raw_bbox)}: must satisfy x2 > x1 and y2 > y1"}, 400)returnif ',' in img_b64:img_b64 = img_b64.split(',', 1)[1]1 unmodified lineif missing_padding:img_b64 += '=' * (4 - missing_padding)try:img_data = base64.b64decode(img_b64, validate=False)if not img_data:self.send_json_response({'error': 'Decoded image payload is empty'}, 400)returnnparr = np.frombuffer(img_data, np.uint8)img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)except Exception as e:5 unmodified linesreturnh, w = img.shape[:2]x1 = max(0, int(math.floor(rx1)))y1 = max(0, int(math.floor(ry1)))x2 = min(w, int(math.ceil(rx2)))y2 = min(h, int(math.ceil(ry2)))if x2 <= x1 or y2 <= y1:self.send_json_response({'error': f"Invalid 'bbox' {list(raw_bbox)}: region lies outside image bounds ({w}x{h})"}, 400)returncrop_img = img[y1:y2, x1:x2]if crop_img.size == 0:3 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)returnexcept 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'):3 unmodified linespred_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')1 unmodified lineself.send_json_response({'text': pred_text,'confidence': float(conf),'calibrated_confidence': calibrate_line_confidence(conf, sel_ver, pred_text),'selected_recognizer': sel_ver,'model_info': get_model_info(model_ver),'image': crop_b64,'crop_image': f"data:image/png;base64,{crop_b64}",'bbox': [x1, y1, x2, y2]
271 unmodified lines2722732742752762772782792802812822832842852862872882892906 unmodified lines297298299300301302303304305306307308309310216 unmodified lines527528529530531532533534535271 unmodified lines</thead><tbody><tr><td><strong>V24.1-R4 SOTA</strong> <em>(Default)</em></td><td><code>[3, 48, 480]</code></td><td><strong>Primary pure-Cham production specialist.</strong> Vocabulary-isolated <em>Akhar Thrah</em> recognizer with WiSE-FT real-scan calibration (2.55% real-camera CER); prevents stray Latin character hallucinations on aged manuscripts.</td></tr><tr><td><strong>V25 SOTA</strong></td><td><code>[3, 48, 480]</code></td><td><strong>Official 40-epoch Dual-T4x2 Bilingual SOTA</strong> (90.96% Sequence Accuracy, 0.72% CER on 10,000 frozen validation lines). Supports expanded 160-token mixed Cham + Latin inline glosses.</td></tr><tr><td><strong>Auto Router</strong></td><td>Adaptive Tri-Engine</td><td><strong>Best for interleaved Cham + Vietnamese pages.</strong> Runs W=480 Cham primary, selectively adjudicates narrow/lower-confidence crops with W=320 archival specialist, and hands off Vietnamese lines to PP-OCRv5.</td></tr><tr><td><strong>V24.1-R3.1</strong></td>6 unmodified lines<td>Clean HarfBuzz & editorial punctuation specialist (100% accuracy across 14 mandatory symbols and multi-context hyphens).</td></tr><tr><td><strong>Vietnamese</strong></td><td>Dynamic</td><td>Fine-tuned PP-OCRv5 recognizer dedicated to modern Vietnamese translations, headers, and catalog cards.</td></tr><tr><td><strong>V24 / V23 Baselines</strong></td><td><code>[3, 48, 320]</code></td><td>Historical reference models retained for longitudinal academic benchmarking.</td></tr></tbody></table>216 unmodified lines</details><details class="faq-item"><summary>When should I choose V24.1-R4 SOTA vs. V25 SOTA vs. Auto Router?</summary><div class="faq-answer">Use <strong>V24.1-R4 SOTA</strong> for pure Eastern Cham (<em>Akhar Thrah</em>) manuscripts and printed Cham poetry—its isolated 114-token vocabulary prevents stray Latin characters on noisy paper. Choose <strong>V25 SOTA</strong> when individual lines mix Cham script with inline Latin/Vietnamese words, or choose <strong>Auto Router</strong> when full lines alternate between Cham stanzas and Vietnamese translations.</div></details>271 unmodified lines2722732742752762772782792802812822832842856 unmodified lines292293294295296297298299300301302303304305216 unmodified lines522523524525526527528529530271 unmodified lines</thead><tbody><tr><td><strong>V26.1 SOTA (<code>v24_1_r4</code>)</strong> <em>(Default)</em></td><td><code>[3, 48, 480]</code></td><td><strong>Primary pure-Cham production specialist.</strong> Padding-masked 114-token <em>Akhar Thrah</em> Masked-SVTR with WiSE-FT real-scan calibration (6/6 Gates, 2.07% real-camera crop CER / 3.07% live E2E); prevents stray Latin character hallucinations on aged manuscripts.</td></tr><tr><td><strong>Auto Router (<code>auto</code>)</strong></td><td>Adaptive Tri-Engine</td><td><strong>Best for interleaved Cham + Vietnamese pages.</strong> Runs W=480 Cham primary, selectively adjudicates narrow/lower-confidence crops with W=320 archival specialist, and hands off Vietnamese lines (including digit/punctuation-heavy glosses) to PP-OCRv5 with per-line <code>selected_recognizer</code> provenance.</td></tr><tr><td><strong>V24.1-R3.1</strong></td>6 unmodified lines<td>Clean HarfBuzz & editorial punctuation specialist (100% accuracy across 14 mandatory symbols and multi-context hyphens).</td></tr><tr><td><strong>Vietnamese (<code>vi</code>)</strong></td><td>Dynamic</td><td>Fine-tuned PP-OCRv5 recognizer dedicated to modern Vietnamese translations, headers, and catalog cards.</td></tr><tr><td><strong>V25 Bilingual (Legacy) / V24 / V23</strong></td><td><code>[3, 48, 480 / 320]</code></td><td>Historical reference models retained for longitudinal academic benchmarking. Note: V25 (40-epoch 162-token unmasked bilingual experiment, 0.72% in-domain val CER) exhibits unmasked W=480 padding & CTC Latin dispersion on raw E2E crops—always prefer <strong>Auto Router</strong> or <strong>V26.1 SOTA</strong> for production use.</td></tr></tbody></table>216 unmodified lines</details><details class="faq-item"><summary>When should I choose V26.1 SOTA vs. Auto Router vs. Historical Baselines (V25 / V24 / V23)?</summary><div class="faq-answer">Use <strong>V26.1 SOTA (<code>v24_1_r4</code>)</strong> for pure Eastern Cham (<em>Akhar Thrah</em>) manuscripts and printed Cham poetry—its padding-masked W=480 canvas and isolated 114-token vocabulary prevent stray Latin characters on aged paper. Choose <strong>Auto Router</strong> whenever pages mix or alternate Cham stanzas with Vietnamese translations and headers. Keep <strong>V25 / V24 / V23</strong> strictly for historical comparative benchmarking rather than production transcription.</div></details>
34 unmodified lines353637383940412 unmodified lines444546474849635 unmodified lines68568668768868969069169269334 unmodified lines<select id="model-select" class="model-select" aria-label="Select Recognition Model"><optgroup label="Paleographic Cham Specialists"><option value="v24_1_r4" selected>V26.1 SOTA</option><option value="v25">V25 SOTA</option><option value="v24_1_r3_1">V24.1-R3.1</option><option value="v24_1_r2_1_6">V24.1-R2.1.6</option></optgroup>2 unmodified lines<option value="vi">Vietnamese</option></optgroup><optgroup label="Historical Baselines"><option value="v24">V24 Baseline</option><option value="v23">V23 Legacy</option></optgroup>635 unmodified lines</p></div><div style="padding: 12px; border: 1px solid var(--border-subtle); border-radius: 10px; background: var(--bg-elevated);"><strong style="color: var(--accent);">2. SOTA Recognition & Tri-Specialist Routing</strong><p style="margin-top: 4px; color: var(--text-secondary); font-size: 12px;">Deploys <strong>V24.1-R4</strong> (W=480 WiSE-FT pure-Cham SOTA, 2.55% real-camera CER), <strong>V25</strong> (40-epoch Dual-T4x2 SOTA, 90.96% Seq Acc / 0.72% Val CER), and the adaptive <strong>Auto Tri-Router</strong> with deterministic Logical Order normalization.</p></div></div>34 unmodified lines3536373839402 unmodified lines43444546474849635 unmodified lines68568668768868969069169269334 unmodified lines<select id="model-select" class="model-select" aria-label="Select Recognition Model"><optgroup label="Paleographic Cham Specialists"><option value="v24_1_r4" selected>V26.1 SOTA</option><option value="v24_1_r3_1">V24.1-R3.1</option><option value="v24_1_r2_1_6">V24.1-R2.1.6</option></optgroup>2 unmodified lines<option value="vi">Vietnamese</option></optgroup><optgroup label="Historical Baselines"><option value="v25">V25 Bilingual (Legacy)</option><option value="v24">V24 Baseline</option><option value="v23">V23 Legacy</option></optgroup>635 unmodified lines</p></div><div style="padding: 12px; border: 1px solid var(--border-subtle); border-radius: 10px; background: var(--bg-elevated);"><strong style="color: var(--accent);">2. Masked-SVTR Recognition & Tri-Specialist Routing</strong><p style="margin-top: 4px; color: var(--text-secondary); font-size: 12px;">Deploys <strong>V26.1 Masked-SVTR</strong> (W=480 padding-masked WiSE-FT pure-Cham SOTA, 6/6 Gates, 2.07% real-camera crop CER) and the adaptive <strong>Auto Tri-Router v2.2</strong> (W=480 + W=320 + Vietnamese PP-OCRv5) with per-line recognizer provenance and Logical Order normalization.</p></div></div>
643 unmodified lines644645646647648649643 unmodified lineshttpd.server_close()class TestQualityGates(unittest.TestCase):pass643 unmodified lines644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740643 unmodified lineshttpd.server_close()def test_v26_audit_api_contract_and_provenance_hardening():import base64import jsonimport urllib.requestimport urllib.errorimport threadingfrom http.server import HTTPServer# 1. Model catalog reclassifies V25 as Legacy/Deprecated under Historical Baselinescatalog = app.list_available_models()by_id = {m['id']: m for m in catalog['models']}assert by_id['v25']['group'] == 'Historical Baselines', by_id['v25']assert by_id['v25'].get('deprecated') is True, by_id['v25']assert 'SOTA' not in by_id['v25']['short_label'], by_id['v25']# 2. Strict model allowlist rejects unknown IDs (no silent fallback to V23)for bad_id in ('nonexistent_model_2026', 'model_does_not_exist', '../v23', 12345):try:app.validate_requested_model(bad_id)assert False, f"Expected UnknownModelError for {bad_id!r}"except app.UnknownModelError:passassert app.validate_requested_model(None) == app.DEFAULT_CHAM_MODELassert app.validate_requested_model('') == app.DEFAULT_CHAM_MODELassert app.validate_requested_model('v24_1_r4') == 'v24_1_r4'# 3. Auto Router v2.2 handles digit/punctuation-heavy Vietnamese lines without breaking Cham safetydef fake_cham_w480(imgs):return [(' {889- 0128466780} ꨏ}51/', 0.7554), # vietnamese_00 line 3: digit/symbol soup('ꨚꨯꨮ ꨆꨵꨯꨱꩃ ꨈꨣꨰ', 0.31), # degraded historical Cham line -> MUST stay Cham], 0.0def fake_vi(imgs):return [('Số trang: 0123456789, dấu ! ? : ; ( ) / -', 0.92),('38158"o) gi', 0.74),], 0.0router = app.AutoRoutingOCRWrapper(fake_cham_w480, fake_vi, cham_w320_model=None, primary_ver='v24_1_r4')dummy_crop = np.full((48, 320, 3), 245, dtype=np.uint8)routed_out, _ = router([dummy_crop, dummy_crop])assert routed_out[0][0].startswith('Số trang: 0123456789'), routed_out[0]assert router.last_selected_versions[0] == 'vi'assert routed_out[1][0] == 'ꨚꨯꨮ ꨆꨵꨯꨱꩃ ꨈꨣꨰ', routed_out[1]assert router.last_selected_versions[1] == 'v24_1_r4'# 4. HTTP 400 validation across /ocr and /ocr_crop (no HTTP 502 on missing image, no HTTP 200 on invalid params)valid_img = np.full((80, 240, 3), 250, dtype=np.uint8)ok, buf = cv2.imencode('.png', valid_img)assert okvalid_b64 = base64.b64encode(buf.tobytes()).decode('ascii')httpd = HTTPServer(('127.0.0.1', 0), app.ChamOCRRequestHandler)port = httpd.server_address[1]t = threading.Thread(target=httpd.serve_forever, daemon=True)t.start()def post_json(path, payload):req = urllib.request.Request(f'http://127.0.0.1:{port}{path}',data=(json.dumps(payload).encode('utf-8') if isinstance(payload, (dict, list)) else payload),headers={'Content-Type': 'application/json'},method='POST',)try:with urllib.request.urlopen(req, timeout=10) as resp:return resp.status, json.loads(resp.read().decode('utf-8'))except urllib.error.HTTPError as he:return he.code, json.loads(he.read().decode('utf-8'))try:for path, bad_payload in [('/ocr', {'model': 'v24_1_r4'}), # missing_image -> 400 JSON (was 502)('/ocr', {'image': valid_b64, 'model': 'nonexistent_model_2026'}), # invalid_model -> 400 (was 200 V23)('/ocr', {'image': valid_b64, 'model': 'v24_1_r4', 'method': 'not_a_method'}), # invalid_segmentation -> 400('/ocr', {'image': valid_b64, 'model': 'v24_1_r4', 'method': 'dbnet', 'reading_order': 'invalid'}), # -> 400('/ocr', {'image': '', 'model': 'v24_1_r4'}),('/ocr', b'not-valid-json{{{'),('/ocr_crop', {'image': valid_b64, 'model': 'nonexistent_model_2026', 'bbox': [0, 0, 100, 40]}),('/ocr_crop', {'image': valid_b64, 'model': 'v24_1_r4', 'bbox': [0, 0, 0, 0]}), # invalid_bbox_zero -> 400('/ocr_crop', {'image': valid_b64, 'model': 'v24_1_r4', 'bbox': [-200, -200, -1, -1]}), # negative -> 400('/ocr_crop', {'image': valid_b64, 'model': 'v24_1_r4', 'bbox': [500, 500, 700, 700]}), # outside image -> 400]:code, body = post_json(path, bad_payload)assert code == 400 and 'error' in body, (path, bad_payload, code, body)finally:httpd.shutdown()httpd.server_close()class TestQualityGates(unittest.TestCase):pass
DESIGN.md+86-112
Dockerfile+2-2
FUTURE_WORK.md+12-5
ocr-studio/README_STUDIO.md+80-92
ocr-studio/README_STUDIO_VI.md+62-74
ocr-studio/app.py+246-60
ocr-studio/help.html+10-15
ocr-studio/index.html+3-3
ocr-studio/tests/test_quality_gates.py+91