Spaces:
Running
Running
Deploy Cham OCR Studio Overhaul: Minimalist 3-Cluster Header, Floating Canvas HUD, Spotlight BBox, Focus Crop & /help Manual
Browse filesFiles changed (32)
- .gitattributes+6
- DESIGN.md+46-20
- Dockerfile+2-2
- FUTURE_WORK.md+8-9
- README.md+4-2
- README_VI.md+3-1
- RESEARCH.md+36-6
- ocr-studio/PaddleOCR/tools/infer/predict_rec.py+3-1
- ocr-studio/PaddleOCR/tools/infer/utility.py+2
- ocr-studio/PaddleOCR/tools/program.py+26
- ocr-studio/README_STUDIO.md+18-6
- ocr-studio/README_STUDIO_VI.md+18-6
- ocr-studio/app.py+648-57
- ocr-studio/help.htmlAdded+567
- ocr-studio/index.html
- ocr-studio/research.html
- ocr-studio/static/css/help.cssAdded+763
- ocr-studio/static/css/research.cssAdded+789
- ocr-studio/static/css/studio.cssAdded+2728
- ocr-studio/static/js/cham-keyboard.jsAdded+549
- ocr-studio/static/js/help.jsAdded+91
- ocr-studio/static/js/research.jsAdded+84
- ocr-studio/static/js/studio.jsAdded
- ocr-studio/static/js/transliteration.jsAdded+355
- ocr-studio/static/samples/ood_agal_01_panduranga.pngAdded
- ocr-studio/static/samples/ood_book_10_semibold.pngAdded
- ocr-studio/static/samples/ood_folio_06_wijaya_2col.pngAdded
- ocr-studio/static/samples/ood_v3_16_curved_panduranga.pngAdded
- ocr-studio/static/samples/ood_v3_21_bilingual_campa_vi.pngAdded
- ocr-studio/static/samples/test_006_lvl1.pngAdded
- ocr-studio/tests/test_quality_gates.py+151
- scripts/ingest_studio_to_realscan_gold.py+12-6
338 unmodified lines339340341338 unmodified linesocr-studio/data/output/rec_cham_inference_v24_1_r4/inference.pdiparams filter=lfs diff=lfs merge=lfs -textocr-studio/data/output/rec_cham_inference_v24_1_r4/inference.pdiparams.info filter=lfs diff=lfs merge=lfs -textocr-studio/data/output/rec_cham_inference_v24_1_r4/inference.pdmodel filter=lfs diff=lfs merge=lfs -text338 unmodified lines339340341342343344345346347338 unmodified linesocr-studio/data/output/rec_cham_inference_v24_1_r4/inference.pdiparams filter=lfs diff=lfs merge=lfs -textocr-studio/data/output/rec_cham_inference_v24_1_r4/inference.pdiparams.info filter=lfs diff=lfs merge=lfs -textocr-studio/data/output/rec_cham_inference_v24_1_r4/inference.pdmodel filter=lfs diff=lfs merge=lfs -textocr-studio/static/samples/ood_agal_01_panduranga.png filter=lfs diff=lfs merge=lfs -textocr-studio/static/samples/ood_book_10_semibold.png filter=lfs diff=lfs merge=lfs -textocr-studio/static/samples/ood_folio_06_wijaya_2col.png filter=lfs diff=lfs merge=lfs -textocr-studio/static/samples/ood_v3_16_curved_panduranga.png filter=lfs diff=lfs merge=lfs -textocr-studio/static/samples/ood_v3_21_bilingual_campa_vi.png filter=lfs diff=lfs merge=lfs -textocr-studio/static/samples/test_006_lvl1.png filter=lfs diff=lfs merge=lfs -text
33 unmodified lines34353637383910 unmodified lines5051525354555657585960616263646566676869707172737475767778798081828384858633 unmodified linesfontFamily: "Google Sans Flex, Google Sans, system-ui, -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, sans-serif"fontSize: "20px"fontWeight: "700"spacing:xs: "4px"sm: "8px"10 unmodified lines# 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.33 unmodified lines343536373839404142434445464710 unmodified lines58596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111233 unmodified linesfontFamily: "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"10 unmodified lines# 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.
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 & Cham-DBNet v1 poly + ribbon rectification + V24.1-R4.1 WiSE-FTRUN echo "Cache bust 2026-11-18T05:45:00Z - Cham-DBNet v1 poly (unclip=1.8) + ribbon rectify_polygon_line + V24.1-R4.1 WiSE-FT + V26 mask-ready runtime"# 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 & Cham-DBNet v1 poly + Minimalist Workbench + User Guide /helpRUN echo "Cache bust 2026-11-21T20:52:00Z - Cham-OCR Studio Comprehensive UX Overhaul + /help + Minimalist Header + Floating HUD"# Copy application filesCOPY . /app
99 unmodified lines10010110210310410510610710810911011111211311411511611711811912012112212312412599 unmodified lines---## 4. Completed Architectural Milestones (V24.1 Pure-Cham Lineage & Cham-DBNet Audits, Nov 2026)Following the 40-epoch V25 training milestone (`90.96%` Sequence Accuracy, `0.72%` CER on `cham_v25_val_freeze.zip`), a parallel vocabulary-isolated pure-Cham production track (**`V24.1`: `R2.1.6 -> R3 -> R3.1 (W=320) -> R4 / R4.1 WiSE-FT (W=480, T=60)`**, `114` tokens paired with `AutoRoutingOCRWrapper` for Vietnamese code-switching) was executed and deployed to `https://ocr.cham.asia`:1. **HarfBuzz OpenType Shaping Parity (`uharfbuzz` + `freetype`)**: Eliminated PIL `ImageDraw.text` pre-vowel / subjoined medial positioning discrepancies (`U+AA2F/AA30`, `U+AA33..AA36`) and verified OpenType contextual glyph substitutions (`hyphen.cham` `gid=10` vs `hyphen` `gid=118`).2. **`PPLCNetV3` Dynamic Width Pooling Fix (`rec_lcnetv3.py`)**: Replaced hardcoded `F.adaptive_avg_pool2d(x, [1, 40])` with `F.adaptive_avg_pool2d(x, [1, int(x.shape[3]) // 2])`, restoring exact train-eval temporal stride parity ($T = W / 8 = 60$ at $W = 480$) and cutting real camera line CER on `harum_palei_01` by `-44.8%` (`4.62% -> 2.55%`).3. **`DBNet` `MakeShrinkMap` `seed=1024` Bug Fix & Detached Diacritic Fragment Suppression**: Resolved the silent zero-GT bug where `build_dataloader(..., seed=1024)` overwrote `kwargs['epoch'] = 1024 > total_epoch`, and added geometric micro-diacritic speck suppression in `merge_line_boxes` (`100.0%` line recall across both `harum_palei_01` `25/25` and `RealScan-Gold v2` `180/180` OOD archival lines).4. **Post-Hoc Logit Temperature Scaling ($T^*$) & Active Learning Pipeline**: Calibrated `confidence_temperature` on held-out `Probe-100` (`calibrated_confidence` in `/ocr`), hardened `/save_correction` (`normalize_unicode` + lossless PNG crops + JSONL ledger), and shipped `export_active_learning_r4.py` and `scripts/ingest_studio_to_realscan_gold.py`.5. **`RealScan-Gold v1 & v2` (`212` Uncontaminated Lines)**: Established SHA-256-locked cross-domain benchmarks spanning authentic camera poetry (`harum_palei_01`), public-domain Wikimedia specimens, and 12 OOD archival pages rendered exclusively with unseen EFEO and held-out typefaces (`efeo_palm_leaf_agal`, `efeo_regional_folio`, `heldout_camera_book`).---## 5. Next-Generation Open Research Roadmap (V26 & Cham-DBNet v3)1. **Polygonal Bezier/TPS Curved Baseline Rectification (`Cham-DBNet v3`, `box_type='poly'`)**:- Head-to-head experiments with `Cham-DBNet v2.1` (`100.00%` H-Mean on `Val-120`, `99.77%` H-Mean / `100.0%` Precision on 16-vertex curved `Val-160`) demonstrated that `DBPostProcess` with rigid 4-point `cv2.minAreaRect` (`box_type='quad'`) inflates bounding-box height (`tallest box/glyph > 5.0`) when sinusoidal wave amplitude exceeds interline gap ($\text{Amplitude} > \text{Gap}$ on `Level-5`). Switching inference from `quad` to `poly` contour extraction followed by Thin-Plate Spline (TPS) de-warping before SVTR recognition is the principled geometric solution.2. **Padding-Masked SVTR Self-Attention for Variable-Aspect Crops**:- Wide-canvas `W = 480` (`T = 60`) eliminates horizontal compression on full manuscript lines (`> 320px`) but leaves `65%–80%` zero-padded frames on ultra-short crops (`< 160px`). Introducing an explicit `valid_ratio` attention mask inside `SVTR` global mixer blocks will unify short-crop punctuation sharpness and full-line stanza capacity within a single `W = 480` network.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 `~42%` paleographic domain gap observed on unseen historical regional hands (`efeo_regional_folio`).---99 unmodified lines10010110210310410510610710810911011111211311411511611711811912012112212312499 unmodified lines---## 4. Completed Architectural Milestones (V24.1, Cham-DBNet Poly & V26 Milestones, Nov 2026)Following the 40-epoch V25 training milestone (`90.96%` Sequence Accuracy, `0.72%` CER on `cham_v25_val_freeze.zip`), a parallel vocabulary-isolated pure-Cham production track (**`V24.1`: `R2.1.6 -> R3 -> R3.1 (W=320) -> R4 / R4.1 WiSE-FT (W=480, T=60)`**, `114` tokens paired with `AutoRoutingOCRWrapper` for Vietnamese code-switching) and next-generation detector/recognizer upgrades were executed:1. **HarfBuzz OpenType Shaping Parity (`uharfbuzz` + `freetype`)**: Eliminated PIL `ImageDraw.text` pre-vowel / subjoined medial positioning discrepancies (`U+AA2F/AA30`, `U+AA33..AA36`) and verified OpenType contextual glyph substitutions (`hyphen.cham` `gid=10` vs `hyphen` `gid=118`).2. **`PPLCNetV3` Dynamic Width Pooling Fix (`rec_lcnetv3.py`)**: Replaced hardcoded `F.adaptive_avg_pool2d(x, [1, 40])` with `F.adaptive_avg_pool2d(x, [1, int(x.shape[3]) // 2])`, restoring exact train-eval temporal stride parity ($T = W / 8 = 60$ at $W = 480$) and cutting real camera line CER on `harum_palei_01` by `-44.8%` (`4.62% -> 2.55%`).3. **`DBNet` `MakeShrinkMap` `seed=1024` Bug Fix & Detached Diacritic Fragment Suppression**: Resolved the silent zero-GT bug where `build_dataloader(..., seed=1024)` overwrote `kwargs['epoch'] = 1024 > total_epoch`, and added geometric micro-diacritic speck suppression in `merge_line_boxes` (`100.0%` line recall across both `harum_palei_01` `25/25` and `RealScan-Gold v2` `180/180` OOD archival lines).4. **Post-Hoc Logit Temperature Scaling ($T^*$) & Active Learning Pipeline**: Calibrated `confidence_temperature` on held-out `Probe-100` (`calibrated_confidence` in `/ocr`), hardened `/save_correction` (`normalize_unicode` + lossless PNG crops + JSONL ledger), and shipped `export_active_learning_r4.py` and `scripts/ingest_studio_to_realscan_gold.py`.5. **`RealScan-Gold v1 & v2` (`212` Uncontaminated Lines)**: Established SHA-256-locked cross-domain benchmarks spanning authentic camera poetry (`harum_palei_01`), public-domain Wikimedia specimens, and 12 OOD archival pages rendered exclusively with unseen EFEO and held-out typefaces (`efeo_palm_leaf_agal`, `efeo_regional_folio`, `heldout_camera_book`).6. **`Cham-DBNet` Polygon Extraction & Centerline Ribbon Rectification (`v1_poly_u1.8`, Deployed Live on `https://ocr.cham.asia`)**: Replaced `box_type='quad'` with native `DBPostProcess(box_type='poly')` (`unclip=1.8`), `merge_line_polygons`, and `rectify_polygon_line` (`vpad=0.15`, neighboring-polygon masking), raising `FullPage-Frozen 50` recall from `95.40% -> 99.58%` (**Level-5 recall `77.27% -> 100.00%`**) and halving E2E CER (`14.43% -> 7.99%`), verified live (`audit_18`: `10.16%` Doc CER, `harum_palei_01`: `3.43%` Doc CER, Commit `e46e8328`).7. **`V26` Padding-Masked SVTR (`use_valid_mask=True`, Phase A Causal Ablation & Phase B 30-Epoch `V26-Full`)**: Implemented zero-parameter key-padding masks inside `SVTRNet` + valid-width `SELayer` pooling, confirmed causal Stress-82/Harum gain in a 6-epoch controlled ablation, and trained `V26-Full` (`64,000` train / `6,400` val) for 30 unfrozen epochs (`26,514.0s` Train Loop across 3 Kaggle Dual T4x2 stages). All 9 checkpoints + Stage-3 soups passed **`6/6` Frozen-838 Release Gates** (`100.0%` symbols, `97.14%–100.0%` hyphens, `S3 E25` `1.42%` Char CER, `E26` `2.41%` Stress-82 / `1.46%` Harum CER, `24.96%` OOD-12 E2E Doc CER); held in staging (`promoted=False`) under strict zero-relaxation gate integrity because `efeo_regional_folio` crop CER shifted (`43.0% -> 47.77%`), while an in-basin WiSE-FT sweep back toward 6-epoch `V26-Masked` revealed a `4/6` inter-basin barrier across 30k unfrozen steps.---## 5. Next-Generation Open Research Roadmap (`Cham-DBNet v3` & `V26.1`)1. **Jointly Fine-Tuned Curved Polygon Detector (`Cham-DBNet v3`)**: Fine-tune DBNet head representations directly for 16-vertex curved ribbon boundaries to further lower `audit_18` (`10.14%`) beyond inference-time `v1_poly_u1.8`.2. **OOD Regional Paleographic Regularization (`V26.1` Masked-SVTR)**: Combine `V26-Full`'s `6/6`-Gate padding-masked `W=480` architecture with regional calligraphic variation and early-backbone regularization so `OOD-180` Crop CER drops below `26.35%` without sacrificing `1.42%` Char / `2.41%` Stress / `1.46%` Harum performance.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`).---
161 unmodified lines162163164165166167168169170161 unmodified lines| **Level 5: Extreme Overlap** | Gap 2–6px < wave amp 5.5–8px (Breaking Point) | 40 | 166 | **61.45%** | 60.02% | 77.63% || **Overall Suite Summary** | **Total across all 5 tiers** | **200** | **903** | **92.80%** | **23.24%** | **51.63%** |### 3. Model Progression: V23 vs V24 Baseline vs V25 SOTA & V24.1 Pure-Cham Wide-Canvas Production Track- **Version 24.1-R4.1 WiSE-FT (`v24_1_r4`, Default Production SOTA on `ocr.cham.asia`)**: Vocabulary-isolated 114-token Pure-Cham + Mandatory Editorial Punctuation wide-canvas model (`[3, 48, 480]`, $T = 60$ dynamic `PPLCNetV3` width pooling, 100% HarfBuzz OpenType shaping, $T^* = 0.9467$ Temperature Scaling). Passes **`5/6` Frozen-838 Release Gates** (`2.64%` Character-Frozen CER, **`99.29%` (`278/280`)** on 14 Mandatory Symbols, **`95.71%`** on Multi-Context Hyphens, `PASS` Blank Guard) and achieves **`2.55%` Crop CER (`8.56%` WER)** on authentic mobile-camera poetry (`harum_palei_01`, `25/25` lines detected). Paired with **`V24.1-R3.1` (`[3, 48, 320]`)**, which achieves **`24.24%` E2E Doc CER** (`180/180` line recall; **`7.19%`** on unseen `heldout_camera_book`, **`25.79%`** on unseen `efeo_palm_leaf_agal`) across the uncontaminated 212-line **`RealScan-Gold v2`** cross-domain benchmark.- **Version 25 (162-Token Bilingual SOTA)**: Completed full 40-epoch multi-stage distributed GPU training on Dual Tesla T4x2 accelerators (87,480 cumulative steps). Reaches **90.96% Sequence Accuracy** (exact match) and **99.28% Normalized Edit Distance (CER 0.72%)** on the standardized 10,000 frozen validation dataset (`cham_v25_val_freeze.zip`). Resolves CTC blank collapse on Double Danda (`꩝꩝`), eliminates numeral-to-consonant misclassifications (`꩔` vs `ꨤ`, `꩕` vs `ꨅ`), and sharply disambiguates diacritic minimal pairs (`ꨲ` vs `ꨶ`).- **Version 24 (Logical Baseline)**: First logical order model achieving **88.94% validation accuracy** and 13.88% CER across the 50-test stress suite.- **Version 23 (Visual Order Legacy)**: Maintained for historical visual rendering order comparison (84.12% validation accuracy).161 unmodified lines162163164165166167168169170171172161 unmodified lines| **Level 5: Extreme Overlap** | Gap 2–6px < wave amp 5.5–8px (Breaking Point) | 40 | 166 | **61.45%** | 60.02% | 77.63% || **Overall Suite Summary** | **Total across all 5 tiers** | **200** | **903** | **92.80%** | **23.24%** | **51.63%** |### 3. Model Progression: V23 vs V24 Baseline vs V25 SOTA, Cham-DBNet Poly & V24.1/V26 Track- **Live Line Detector — `Cham-DBNet` Polygon + Ribbon Rectification (`v1_poly_u1.8`, Active on `https://ocr.cham.asia`)**: Native `DBPostProcess(box_type='poly')` (`unclip=1.8`) + `merge_line_polygons` + `rectify_polygon_line` (`vpad=0.15`, neighboring-polygon masking), boosting `FullPage-Frozen 50` recall from `95.40%` to **`99.58%`** (**Level-5 curved-overlap recall `77.27%` $\to$ `100.00%`**) and halving overall E2E CER (`14.43%` $\to$ **`7.99%`**; live `audit_18`: **`10.16%`** Doc CER, `harum_palei_01`: **`3.43%`** Doc CER).- **Version 24.1-R4.1 WiSE-FT (`v24_1_r4`, Default Production Recognizer on `ocr.cham.asia`)**: Vocabulary-isolated 114-token Pure-Cham + Mandatory Editorial Punctuation wide-canvas model (`[3, 48, 480]`, $T = 60$ dynamic `PPLCNetV3` width pooling, 100% HarfBuzz OpenType shaping, $T^* = 0.9467$ Temperature Scaling). Passes **`5/6` Frozen-838 Release Gates** (`2.64%` Character-Frozen CER, **`99.29%` (`278/280`)** on 14 Mandatory Symbols, **`95.71%`** on Multi-Context Hyphens, `PASS` Blank Guard) and achieves **`2.55%` Crop CER (`8.56%` WER)** on authentic mobile-camera poetry (`harum_palei_01`, `25/25` lines detected). Paired with **`V24.1-R3.1` (`[3, 48, 320]`)**, which achieves **`24.24%` E2E Doc CER** (`180/180` line recall; **`7.19%`** on unseen `heldout_camera_book`, **`25.79%`** on unseen `efeo_palm_leaf_agal`) across the uncontaminated 212-line **`RealScan-Gold v2`** cross-domain benchmark.- **Version 26-Full Masked-SVTR (`30`-Epoch Staging Benchmark)**: Trained unfrozen across 3 Kaggle Dual T4x2 stages (`64,000` train / `6,400` val `W=480`, `26,514s` Train Loop / `29,191.16s` Wall-clock) with zero-parameter `use_valid_mask=True` attention + SE pooling. Every evaluated checkpoint (`E10..E30` + soups) passes **`6/6` Frozen-838 Release Gates** (`S3 E25`: `4.72%` Clean, **`1.42%`** Char CER, **`100.0%`** 14 Symbols, **`97.14%`** Hyphens, `2.49%` Stress-82, `1.58%` Harum, **`24.96%`** OOD-12 E2E Doc CER; `S3 E26`: `2.41%` Stress-82, **`1.46%`** Harum); retained in staging (`promoted=False`) under strict non-relaxation gates because `efeo_regional_folio` crop CER shifted (`43.0%` $\to$ `47.77%`), keeping `v24_1_r4` as live default.- **Version 25 (162-Token Bilingual SOTA)**: Completed full 40-epoch multi-stage distributed GPU training on Dual Tesla T4x2 accelerators (87,480 cumulative steps). Reaches **90.96% Sequence Accuracy** (exact match) and **99.28% Normalized Edit Distance (CER 0.72%)** on the standardized 10,000 frozen validation dataset (`cham_v25_val_freeze.zip`). Resolves CTC blank collapse on Double Danda (`꩝꩝`), eliminates numeral-to-consonant misclassifications (`꩔` vs `ꨤ`, `꩕` vs `ꨅ`), and sharply disambiguates diacritic minimal pairs (`ꨲ` vs `ꨶ`).- **Version 24 (Logical Baseline)**: First logical order model achieving **88.94% validation accuracy** and 13.88% CER across the 50-test stress suite.- **Version 23 (Visual Order Legacy)**: Maintained for historical visual rendering order comparison (84.12% validation accuracy).
111 unmodified lines112113114115116117118119111 unmodified lines- Được sinh bởi script `ocr-benchmark/scripts/generate_benchmark_200.py` từ ngữ liệu Chăm thực tế với 5 cấp độ biến dạng hình học và chất lượng giấy.- Tỷ lệ phát hiện dòng tổng thể đạt **92.80%**, CER trung bình **23.24%**, WER **51.63%**, tốc độ ~1.33s/trang trên CPU.- Xác định chính xác **điểm gãy sụp đổ (Breaking Point) ở Cấp độ 5**: khi biên độ uốn sóng lớn hơn khoảng cách giữa hai dòng ($\text{Amplitude} > \text{Gap}$), tỷ lệ bắt dòng giảm xuống 61.45% do các nét chữ cắt chéo và dính chùm vào nhau.3. **Tiến trình Mô hình: V23 vs V24 Baseline vs V25 SOTA & Dòng Thuần Chăm V24.1-R4.1 (Production)**:- **Version 24.1-R4.1 WiSE-FT (`v24_1_r4`, Mặc định trên `ocr.cham.asia`)**: Mô hình thuần Chăm + dấu biên tập bắt buộc (114 token cô lập từ điển kết hợp `AutoRoutingOCRWrapper`), khung rộng `[3, 48, 480]` ($T = 60$ nhờ vá pooling động `PPLCNetV3`), 100% HarfBuzz OpenType shaping và hiệu chuẩn độ tự tin Temperature Scaling ($T^* = 0.9467$). Đạt **`5/6` cổng nghiệm thu Frozen-838** (`2.64%` Character-Frozen CER, **`99.29%` (`278/280`)** trên 14 ký hiệu bắt buộc, **`95.71%`** trên Hyphen đa ngữ cảnh, `PASS` Blank Guard) và **`2.55%` Crop CER (`8.56%` WER)** trên ảnh chụp bài thơ thực tế `harum_palei_01` (`25/25` dòng). Song hành cùng **`V24.1-R3.1` (`[3, 48, 320]`)** đạt **`24.24%` E2E Doc CER** (`180/180` dòng phát hiện; **`7.19%`** trên phông sách in Held-Out, **`25.79%`** trên phông lá buông EFEO) trên bộ chuẩn xuyên miền 212 dòng **`RealScan-Gold v2`**.- **Version 25 (162-Token Song ngữ SOTA)**: Đã hoàn thành huấn luyện đa chặng 40 epoch trên GPU Dual Tesla T4x2 (87.480 bước huấn luyện tích lũy). Đạt độ chính xác chuỗi tuyệt đối **90.96%** và khoảng cách chỉnh sửa chuẩn hóa **99.28% (CER 0.72%)** trên tập 10.000 mẫu kiểm định đóng băng chuẩn (`cham_v25_val_freeze.zip`). Khắc phục triệt để lỗi sụp đổ CTC đối với dấu Double Danda (`꩝꩝`), triệt tiêu việc nhận nhầm số khổ thơ thành chữ cái (`꩔` vs `ꨤ`, `꩕` vs `ꨅ`), và phân biệt chuẩn xác các cặp dấu phụ vi mô (`ꨲ` vs `ꨶ`).- **Version 24 (Logical Baseline)**: Mô hình thứ tự Logic đầu tiên đạt độ chính xác kiểm định 88.94% và CER 13.88% trên 50 bài kiểm thử phân tầng.- **Version 23 (Visual Legacy)**: Duy trì đối chiếu cho chuẩn gõ theo thứ tự hiển thị trực quan (độ chính xác kiểm định 84.12%).111 unmodified lines112113114115116117118119120121111 unmodified lines- Được sinh bởi script `ocr-benchmark/scripts/generate_benchmark_200.py` từ ngữ liệu Chăm thực tế với 5 cấp độ biến dạng hình học và chất lượng giấy.- Tỷ lệ phát hiện dòng tổng thể đạt **92.80%**, CER trung bình **23.24%**, WER **51.63%**, tốc độ ~1.33s/trang trên CPU.- Xác định chính xác **điểm gãy sụp đổ (Breaking Point) ở Cấp độ 5**: khi biên độ uốn sóng lớn hơn khoảng cách giữa hai dòng ($\text{Amplitude} > \text{Gap}$), tỷ lệ bắt dòng giảm xuống 61.45% do các nét chữ cắt chéo và dính chùm vào nhau.3. **Tiến trình Mô hình: `Cham-DBNet Poly`, V23/V24, V25 SOTA, V24.1-R4.1 (Production) & V26-Full (Staging)**:- **Bộ dò dòng Production — `Cham-DBNet` Polygon + Ribbon Rectification (`v1_poly_u1.8`, đang chạy trên `https://ocr.cham.asia`)**: Dùng trực tiếp `DBPostProcess(box_type='poly')` (`unclip=1.8`) + `merge_line_polygons` + `rectify_polygon_line` (`vpad=0.15`, che vùng đa giác dòng lân cận), nâng recall trên `FullPage-Frozen 50` từ `95.40%` lên **`99.58%`** (**Cấp độ 5 sóng uốn cắt nhau tăng từ `77.27%` $\to$ `100.00%`**) và giảm gần một nửa E2E CER (`14.43%` $\to$ **`7.99%`**; kiểm thử live `audit_18`: **`10.16%`** Doc CER, `harum_palei_01`: **`3.43%`** Doc CER).- **Version 24.1-R4.1 WiSE-FT (`v24_1_r4`, Mặc định trên `ocr.cham.asia`)**: Mô hình thuần Chăm + dấu biên tập bắt buộc (114 token cô lập từ điển kết hợp `AutoRoutingOCRWrapper`), khung rộng `[3, 48, 480]` ($T = 60$ nhờ vá pooling động `PPLCNetV3`), 100% HarfBuzz OpenType shaping và hiệu chuẩn độ tự tin Temperature Scaling ($T^* = 0.9467$). Đạt **`5/6` cổng nghiệm thu Frozen-838** (`2.64%` Character-Frozen CER, **`99.29%` (`278/280`)** trên 14 ký hiệu bắt buộc, **`95.71%`** trên Hyphen đa ngữ cảnh, `PASS` Blank Guard) và **`2.55%` Crop CER (`8.56%` WER)** trên ảnh chụp bài thơ thực tế `harum_palei_01` (`25/25` dòng). Song hành cùng **`V24.1-R3.1` (`[3, 48, 320]`)** đạt **`24.24%` E2E Doc CER** (`180/180` dòng phát hiện; **`7.19%`** trên phông sách in Held-Out, **`25.79%`** trên phông lá buông EFEO) trên bộ chuẩn xuyên miền 212 dòng **`RealScan-Gold v2`**.- **Version 26-Full Masked-SVTR (`30` Epochs, Lưu chuẩn Staging)**: Huấn luyện toàn mạng `use_valid_mask=True` qua 3 chặng trên Kaggle Dual T4x2 (`64.000` train / `6.400` val `W=480`, `26.514s` Train Loop / `29.191,16s` Wall-clock). Mọi checkpoint `E10..E30` & soup đều pass **`6/6` cổng Frozen-838** (`S3 E25`: Clean `4.72%`, Char **`1.42%`**, 14 Symbols **`100.0%`**, Hyphens **`97.14%`**, Stress-82 `2.49%`, Harum `1.58%`, OOD-12 E2E **`24.96%`**; `S3 E26`: Stress-82 `2.41%`, Harum **`1.46%`**); giữ ở nhánh nghiên cứu (`promoted=False`) theo quy tắc không nới lỏng cổng vì `efeo_regional_folio` crop CER tăng từ `43.0%` lên `47.77%`, giữ `v24_1_r4` mặc định trên production.- **Version 25 (162-Token Song ngữ SOTA)**: Đã hoàn thành huấn luyện đa chặng 40 epoch trên GPU Dual Tesla T4x2 (87.480 bước huấn luyện tích lũy). Đạt độ chính xác chuỗi tuyệt đối **90.96%** và khoảng cách chỉnh sửa chuẩn hóa **99.28% (CER 0.72%)** trên tập 10.000 mẫu kiểm định đóng băng chuẩn (`cham_v25_val_freeze.zip`). Khắc phục triệt để lỗi sụp đổ CTC đối với dấu Double Danda (`꩝꩝`), triệt tiêu việc nhận nhầm số khổ thơ thành chữ cái (`꩔` vs `ꨤ`, `꩕` vs `ꨅ`), và phân biệt chuẩn xác các cặp dấu phụ vi mô (`ꨲ` vs `ꨶ`).- **Version 24 (Logical Baseline)**: Mô hình thứ tự Logic đầu tiên đạt độ chính xác kiểm định 88.94% và CER 13.88% trên 50 bài kiểm thử phân tầng.- **Version 23 (Visual Legacy)**: Duy trì đối chiếu cho chuẩn gõ theo thứ tự hiển thị trực quan (độ chính xác kiểm định 84.12%).
58 unmodified lines5960616263646566676869290 unmodified lines36036136236336436533 unmodified lines39940040140240340440540640740840958 unmodified lines- [6.2 Controlled 200-Page Synthetic Document Stress-Test (903 Textlines)](#62-controlled-200-page-synthetic-document-stress-test-903-textlines)- [6.3 Model Progression & Empirical Validation: V23 vs V24 vs V25 SOTA](#63-model-progression--empirical-validation-v23-vs-v24-vs-v25-sota)- [6.4 Multi-GPU Distributed Hardware Scaling & Cost Efficiency](#64-multi-gpu-distributed-hardware-scaling--cost-efficiency)- [7. Production Serving & Deployment Infrastructure](#7-production-serving--deployment-infrastructure)- [7.1 Containerized Microservice Architecture](#71-containerized-microservice-architecture)- [7.2 Concurrency Safeguards & NumPy 2.x Forward Compatibility](#72-concurrency-safeguards--numpy-2x-forward-compatibility)- [8. Limitations & Open Research Challenges](#8-limitations--open-research-challenges)- [8.5 Post-V25 Future Iterations (Planned V25.1 / V26 Improvements)](#85-post-v25-future-iterations-planned-v251--v26-improvements)- [9. BibTeX Citation & Academic References](#9-bibtex-citation--academic-references)---290 unmodified lines| **`V24.1-R4.1` (`W=480` Default)** | **2.55% (8.56%)** | 28.86% | 43.77% | 7.57% | 25.58% || **`Auto` Dual-Engine** | **2.55% (8.56%)** | 28.86% | 45.55% | 7.57% | 26.12% |---## 7. Production Serving & Deployment Infrastructure33 unmodified lines3. **Severe Biological Degradation & Epigraphy**: Inscription stone rubbings and severely mold-damaged palm leaves (where character ink has substantially eroded) remain beyond the capabilities of pure vision-based CTC sequence models. Integrating masked language models (MLMs) trained on historical Cham corpora is an active subject of future study.4. **Extreme Interlinear Overlap (Level 5)**: When severe paper wrinkling causes interlinear wave amplitude to exceed line spacing ($\text{Amplitude} > \text{Gap}$), 1D projection and horizontal bounding boxes collapse, indicating the need for 2D polygonal baseline tracking models in future iterations.### 8.5 Completed V24.1 Enhancements & Next-Generation V26 / Cham-DBNet v3 RoadmapFollowing the deployment of both Model Version 25 (`90.96%` Sequence Accuracy on frozen 10K validation) and the vocabulary-isolated `V24.1-R4.1 WiSE-FT` wide-canvas production model (`2.55%` real-camera CER, `5/6` Frozen-838 Release Gates), open research priorities tracked in [FUTURE_WORK.md](FUTURE_WORK.md) include:1. **Polygonal Bezier/TPS Curved Baseline Rectification (`Cham-DBNet v3`, `box_type='poly'`)**: Replacing 4-point `minAreaRect` (`box_type='quad'`) with 16-vertex polygonal contour extraction and Thin-Plate Spline (TPS) de-warping to resolve intersecting `Level-5` sinusoidal baselines ($\text{Amplitude} > \text{Gap}$).2. **Padding-Masked SVTR Self-Attention**: Incorporating `valid_ratio` key-padding masks inside SVTR global attention blocks so ultra-short crops (`< 160px`) and full-width stanzas (`480px`) share identical attention sharpness without right-padding dilution.3. **Dual-Script Composite Rendering & Field Manuscript Active Learning (`RealScan-Gold v3`)**: Expanding verified palm-leaf (*agal*) and regional manuscript benchmarks via human-in-the-loop Studio exports (`scripts/ingest_studio_to_realscan_gold.py`) to close the ~43% paleographic gap on unseen historical regional hands (`efeo_regional_folio`).---58 unmodified lines59606162636465666768697071290 unmodified lines36236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439533 unmodified lines42943043143243343443543643743843958 unmodified lines- [6.2 Controlled 200-Page Synthetic Document Stress-Test (903 Textlines)](#62-controlled-200-page-synthetic-document-stress-test-903-textlines)- [6.3 Model Progression & Empirical Validation: V23 vs V24 vs V25 SOTA](#63-model-progression--empirical-validation-v23-vs-v24-vs-v25-sota)- [6.4 Multi-GPU Distributed Hardware Scaling & Cost Efficiency](#64-multi-gpu-distributed-hardware-scaling--cost-efficiency)- [6.5 Vocabulary-Isolated Pure-Cham Production Lineage (`V24.1-R4.1`) & `RealScan-Gold v2`](#65-vocabulary-isolated-pure-cham-production-lineage-v241-r41--realscan-gold-v2-cross-domain-evaluation)- [6.6 `Cham-DBNet` Polygon Rectification & `V26` Padding-Masked SVTR (30 Epochs)](#66-cham-dbnet-polygon-rectification-v26-causal-ablation--v26-full-30-epoch-evaluation)- [7. Production Serving & Deployment Infrastructure](#7-production-serving--deployment-infrastructure)- [7.1 Containerized Microservice Architecture](#71-containerized-microservice-architecture)- [7.2 Concurrency Safeguards & NumPy 2.x Forward Compatibility](#72-concurrency-safeguards--numpy-2x-forward-compatibility)- [8. Limitations & Open Research Challenges](#8-limitations--open-research-challenges)- [8.5 Completed `Cham-DBNet poly` & `V26` Milestones + `V26.1` Roadmap](#85-completed-v241--v26-milestones--v261--realscan-gold-v3-roadmap)- [9. BibTeX Citation & Academic References](#9-bibtex-citation--academic-references)---290 unmodified lines| **`V24.1-R4.1` (`W=480` Default)** | **2.55% (8.56%)** | 28.86% | 43.77% | 7.57% | 25.58% || **`Auto` Dual-Engine** | **2.55% (8.56%)** | 28.86% | 45.55% | 7.57% | 26.12% |### 6.6 `Cham-DBNet` Polygon Rectification, `V26` Causal Ablation & `V26-Full` 30-Epoch Evaluation1. **`Cham-DBNet` Polygon Extraction & Ribbon Rectification (`v1_poly_u1.8`, Deployed Live on `https://ocr.cham.asia`)**:Replacing 4-point `minAreaRect` (`box_type='quad'`) with native `DBPostProcess(box_type='poly')`, `unclip=1.8`, `merge_line_polygons`, and centerline `rectify_polygon_line` (`vpad=0.15`, neighboring-polygon masking) while keeping `v24_1_r4` fixed resolved the sinusoidal **Level-5** line-overlap breaking point without re-training detector weights (`REPORTS/CHAM_DBNET_POLY_RECTIFY_EVALUATION.md`):- **`FullPage-Frozen 50` (239 GT lines)**: Overall recall increased from `95.40%` $\to$ **`99.58%`** (**Level-5 recall `77.27%` $\to$ `100.00%`**, Level-5 Matched CER `11.92%` $\to$ `10.12%`), cutting overall End-to-End CER nearly in half from **`14.43%` $\to$ `7.99%`**.- **Curved & Audit Stress Slices**: `short:5` Document CER fell from `16.40%` $\to$ **`7.37%`** (`64/64` exact lines), `a4:5` fell from `12.95%` $\to$ **`6.96%`** (`241/241` exact lines), and `audit_18` improved from `11.25%` $\to$ **`10.14%`** (`134/134`), with zero regression on Level 1–4 pages (`a4:1-4`: `6.45%` $\to$ `6.31%`, `1153/1153`) and `3.43%` E2E Doc CER on `harum_palei_01` (`25/25`, `100.0%`).- **Live Production Verification (`phucsd/cham-ocr-studio` Commit `e46e8328`)**: Confirmed **`0` blank hallucinations** (`no_text`), **`3.43%`** E2E Doc CER (`3.53%` Matched CER) on `harum_palei_01` (`25/25` lines), and **`10.16%`** Live Document CER (`10.53%` Matched CER, `134/134` lines) across `audit_18` (`REPORTS/LIVE_HF_R4_VERIFICATION.md`).2. **`V26` Phase A — Controlled Causal `use_valid_mask` Ablation (Zero Extra Parameters)**:To eliminate right-padding dilution inside `W=480` global self-attention and channel squeeze-and-excitation on narrow `<160px` crops, we injected a `valid_ratio` key-padding mask into `SVTRNet` global attention blocks and valid-width-masked pooling into `PPLCNetV3` `SELayer` (`use_valid_mask=True`, 0 extra trainable weights). In a strictly paired 6-epoch Dual T4x2 ablation (`REPORTS/V26_MASKED_FT_EVALUATION.md`), `V26 Masked` (`3,188.0s` Train Loop, `4,514.35s` Wall-clock) improved Stress-82 CER (`4.64%` at E3, `3.99%` at E4, `4.28%` in-basin soup `soup_50e3_50e4`) over both active production (`6.93%`) and the identically trained `use_valid_mask=False` `V26 Control` (`5.43%` at E2, `4.64%` at E6; `3,235.0s` Train Loop, `4,305.16s` Wall-clock) while cutting `harum` CER to `1.95%` (E4) / `2.31%` (`soup_50e3_50e4`).3. **`V26-Full` Phase B — 30-Epoch 3-Stage Unfrozen Training & In-Basin WiSE-FT Barrier Audit**:Building on the causal gain, we synthesized **`64,000` train / `6,400` val** HarfBuzz `W=480` lines (`REPORTS/v26_full_dataset_manifest.json`: `999/999` Cham stanza numerals, `6,357` `ꨲ`/`ꨶ` minimal pairs, `2,318` Double Danda `꩝꩝`, `1,592` multi-tier clusters `ꨣꨳꨪꩌ`, `0` benchmark overlap) and trained all `PPLCNetV3 + SVTR + MultiHead` parameters unfrozen across 3 state-preserving Kaggle Dual T4x2 stages (`global_step = 30,000`, Cosine LR `2.0e-5` $\to$ `1.0e-6`):- **Verified 3-Part Training Accounting (`REPORTS/V26_FULL_EVALUATION.md`)**: Stage 1 (`E1–10`: `8,737.0s` Train Loop / `969.65s` Overhead / `9,706.65s` Wall-clock, val `81.72%` Acc / `98.08%` NED) + Stage 2 (`E11–20`: `8,929.0s` / `638.42s` / `9,567.42s`, val `84.92%` Acc / `98.47%` NED) + Stage 3 (`E21–30`: `8,848.0s` / `1,069.09s` / `9,917.09s`, val `85.22%` Acc / `98.55%` NED) = **`26,514.0s` (`441.90m`) Train Loop / `2,677.16s` Overhead / `29,191.16s` (`486.52m`) Total Wall-clock**.- **Controlled & RealScan Results (under `box_type='poly'`)**:| Model Candidate | Clean CER | Char CER | 14 Symbols Acc | Hyphen Acc | FullPage CER | Stress-82 CER | Harum Crop CER | OOD-180 Crop (E2E Doc CER) | Release Gates || :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: || **`V24.1-R4.1` (Prod `85525b0c`)** | 5.28% | 2.64% | 99.29% (`278/280`) | 95.71% | 7.39% | 6.93% | 2.55% | **26.35%** (25.58%) | `5/6` || **`V26-Full S1 E10`** | **4.63%** | 1.59% | **100.0%** | **100.0%** | 6.24% | 2.69% | **1.46%** | 29.09% (25.40%) | **`6/6`** || **`V26-Full S2 E20`** | 4.73% | 1.52% | **100.0%** | 97.14% | **5.99%** | 2.46% | **1.46%** | — | **`6/6`** || **`V26-Full S3 E25`** (`epoch_best`) | 4.72% | **1.42%** | **100.0%** | 97.14% | 6.02% | 2.49% | 1.58% | 27.92% (**24.96%**) | **`6/6`** || **`V26-Full S3 E26`** | 4.73% | 1.57% | **100.0%** | 97.14% | **5.99%** | **2.41%** | **1.46%** | — | **`6/6`** || **`V26-Full soup_top2_e25_e27`** | 4.72% | 1.44% | **100.0%** | 97.14% | 6.04% | 2.43% | 1.58% | 27.89% (**24.98%**) | **`6/6`** || **`inbasin_wise_a25..lw_20_55`** | 5.24–5.50% | 2.62–2.86% | 96.07–98.57% | 87.14–91.43% | 6.51–6.65% | 4.67–5.28% | 1.58–1.70% | Barrier (`4/6` Gates) | `4/6` |- **Strict Non-Relaxation Gate Decision & Basin Barrier Finding (`promoted=False`)**: Every single evaluated `V26-Full` checkpoint (`E10, E20, E24..E30` + Stage 3 soups) passed **`6/6` Frozen-838 Release Gates** (`100.0%` symbols, `97.14%–100.0%` hyphens), halved Character/Stress/Harum CER (`2.64%` $\to$ `1.42%`, `6.93%` $\to$ `2.41%`, `2.55%` $\to$ `1.46%`), and beat production on **OOD-12 E2E Doc CER** (`24.96%` vs `25.58%`, `heldout_camera_book` `7.98%` vs `9.37%`, `efeo_palm_leaf_agal` E2E `26.20%` vs `28.86%`). However, 30 unfrozen epochs specialized `efeo_regional_folio` crop CER (`43.0%` $\to$ `47.77%`), leaving overall `OOD-180` Crop CER at `27.89%–27.92%` vs the strict non-regression ceiling (`26.65%`). A 5-point in-basin WiSE-FT sweep bridging back to 6-epoch `V26-Masked` landed on a loss barrier (`4/6` gates), proving 30k unfrozen steps move out of the 6-epoch basin while Stage 3 trajectories retain linear mode connectivity. Strictly honoring unrelaxed gate integrity, `v24_1_r4` (`85525b0ca091acaf`) remains production default while `V26-Full` defines the validated `6/6` staging benchmark for `V26.1`.---## 7. Production Serving & Deployment Infrastructure33 unmodified lines3. **Severe Biological Degradation & Epigraphy**: Inscription stone rubbings and severely mold-damaged palm leaves (where character ink has substantially eroded) remain beyond the capabilities of pure vision-based CTC sequence models. Integrating masked language models (MLMs) trained on historical Cham corpora is an active subject of future study.4. **Extreme Interlinear Overlap (Level 5)**: When severe paper wrinkling causes interlinear wave amplitude to exceed line spacing ($\text{Amplitude} > \text{Gap}$), 1D projection and horizontal bounding boxes collapse, indicating the need for 2D polygonal baseline tracking models in future iterations.### 8.5 Completed `V24.1` & `V26` Milestones + `V26.1` / `RealScan-Gold v3` RoadmapFollowing Model Version 25 (`90.96%` Sequence Accuracy, `0.72%` CER on frozen 10K validation), the `V24.1-R4.1 WiSE-FT` wide-canvas production model (`85525b0ca091acaf`, `2.55%` real-camera CER), live deployment of **`Cham-DBNet` `v1_poly_u1.8` (`box_type='poly'` + `rectify_polygon_line`)** (`FullPage-Frozen 50` `14.43% -> 7.99%` E2E, `100.0%` Level-5 recall), and **30-epoch `V26-Full` Padding-Masked SVTR** (`6/6` Frozen-838 Release Gates, `1.42%` Char CER, `2.41%` Stress-82 CER, `1.46%` Harum CER, `24.96%` OOD-12 E2E), remaining open research priorities tracked in [FUTURE_WORK.md](FUTURE_WORK.md) are:1. **Curved Baseline Poly Detector Re-Training (`Cham-DBNet v3`)**: End-to-end joint fine-tuning of DBNet regression heads directly under polygonal curvature targets to push beyond the fixed `v1_poly_u1.8` inference upgrade.2. **OOD Regional Paleographic Regularization (`V26.1` Masked-SVTR)**: Adding multi-style calligraphic / `efeo_regional_folio`-proxy stroke jitter and early-backbone regularization inside the `use_valid_mask=True` `W=480` architecture so `6/6` Frozen-838 Gates hold jointly with `<= 26.35%` OOD-180 Crop CER for automatic production promotion.3. **Dual-Script Composite Rendering & Field Manuscript Active Learning (`RealScan-Gold v3`)**: Expanding verified palm-leaf (*agal*) and regional manuscript benchmarks via human-in-the-loop Studio exports (`scripts/ingest_studio_to_realscan_gold.py`) to close the ~43%–44% paleographic gap on unseen historical regional hands (`efeo_regional_folio`).---
39 unmodified lines404142434445632 unmodified lines67867968068168268368439 unmodified linesself.rec_image_shape = [int(v) for v in args.rec_image_shape.split(",")]self.rec_batch_num = args.rec_batch_numself.rec_algorithm = args.rec_algorithmpostprocess_params = {'name': 'CTCLabelDecode',"character_dict_path": args.rec_char_dict_path,632 unmodified linespreds = outputselse:preds = outputs[0]self.predictor.try_shrink_memory()if self.postprocess_params['name'] == 'CTCLabelDecode':rec_result = self.postprocess_op(preds,39 unmodified lines40414243444546632 unmodified lines67968068168268368468568639 unmodified linesself.rec_image_shape = [int(v) for v in args.rec_image_shape.split(",")]self.rec_batch_num = args.rec_batch_numself.rec_algorithm = args.rec_algorithmself.use_gpu = bool(getattr(args, "use_gpu", False))postprocess_params = {'name': 'CTCLabelDecode',"character_dict_path": args.rec_char_dict_path,632 unmodified linespreds = outputselse:preds = outputs[0]if getattr(self, "use_gpu", False):self.predictor.try_shrink_memory()if self.postprocess_params['name'] == 'CTCLabelDecode':rec_result = self.postprocess_op(preds,
287 unmodified lines288289290291292293287 unmodified linesconfig.disable_onednn()if hasattr(config, "disable_mkldnn"):config.disable_mkldnn()# enable memory optimif not model_file_path.endswith('.json'):config.enable_memory_optim()287 unmodified lines288289290291292293294295287 unmodified linesconfig.disable_onednn()if hasattr(config, "disable_mkldnn"):config.disable_mkldnn()if hasattr(args, "cpu_threads") and args.cpu_threads:config.set_cpu_math_library_num_threads(int(args.cpu_threads))# enable memory optimif not model_file_path.endswith('.json'):config.enable_memory_optim()
230 unmodified lines23123223323423523626 unmodified lines263264265266267268211 unmodified lines480481482483484485230 unmodified linesmodel_average = Falsemodel.train()use_srn = config['Architecture']['algorithm'] == "SRN"extra_input_models = ["SRN", "NRTR", "SAR", "SEED", "SVTR", "SVTR_LCNet", "SPIN", "VisionLAN",26 unmodified lines) == "Windows" else len(train_dataloader)for epoch in range(start_epoch, epoch_num + 1):if train_dataloader.dataset.need_reset:train_dataloader = build_dataloader(config, 'Train', device, logger, seed=epoch)211 unmodified lineslog_writer.log_model(is_best=False, prefix='iter_epoch_{}'.format(epoch))best_str = 'best metric, {}'.format(', '.join(['{}: {}'.format(k, v) for k, v in best_model_dict.items()]))logger.info(best_str)230 unmodified lines23123223323423523623723823924024124224324424524624724824925025125225325425525626 unmodified lines283284285286287288289211 unmodified lines501502503504505506507508509510511230 unmodified linesmodel_average = Falsemodel.train()def _enforce_frozen_bn_eval():if not config['Global'].get('freeze_bn_in_frozen_prefixes', False):return 0f_prefs = config['Global'].get('freeze_prefixes') or []if isinstance(f_prefs, str):f_prefs = [f_prefs]frozen_bn_cnt = 0for s_name, s_layer in model.named_sublayers():c_name = s_name[len('_layers.'):] if s_name.startswith('_layers.') else s_nameif any(c_name == p or c_name.startswith(p + '.') for p in f_prefs):if isinstance(s_layer, paddle.nn.BatchNorm2D):s_layer.eval()frozen_bn_cnt += 1return frozen_bn_cnt_locked_bns = _enforce_frozen_bn_eval()if _locked_bns > 0 and dist.get_rank() == 0:logger.info("Locked {} BatchNorm2D layers in eval() mode under freeze_prefixes={}".format(_locked_bns, config['Global'].get('freeze_prefixes')))use_srn = config['Architecture']['algorithm'] == "SRN"extra_input_models = ["SRN", "NRTR", "SAR", "SEED", "SVTR", "SVTR_LCNet", "SPIN", "VisionLAN",26 unmodified lines) == "Windows" else len(train_dataloader)for epoch in range(start_epoch, epoch_num + 1):_enforce_frozen_bn_eval()if train_dataloader.dataset.need_reset:train_dataloader = build_dataloader(config, 'Train', device, logger, seed=epoch)211 unmodified lineslog_writer.log_model(is_best=False, prefix='iter_epoch_{}'.format(epoch))stage_end_epoch = config.get("Global", {}).get("stage_end_epoch", None)if stage_end_epoch is not None and epoch >= int(stage_end_epoch):logger.info("[STAGE EXIT] Reached stage_end_epoch {} at epoch {} (global_step {}).".format(stage_end_epoch, epoch, global_step))breakbest_str = 'best metric, {}'.format(', '.join(['{}: {}'.format(k, v) for k, v in best_model_dict.items()]))logger.info(best_str)
13 unmodified lines14151617181920212223242526272829303113 unmodified linesocr-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/```---13 unmodified lines14151617181920212223242526272829303132333435363738394041424313 unmodified linesocr-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/```---
11 unmodified lines12131415161718192021222324252627282911 unmodified linesocr-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/```---11 unmodified lines12131415161718192021222324252627282930313233343536373839404111 unmodified linesocr-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/```---
194 unmodified lines1951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482499 unmodified lines25926026126226326426526633 unmodified lines3003013023033043053063073083093103113 unmodified lines31531631731831932032127 unmodified lines349350351352353354355356357358359360361362709 unmodified lines107210731074107510761077107829 unmodified lines11081109111011111112111311141383 unmodified lines24982499250025012502250325042505250632 unmodified lines253925402541254225432544254525462547254825492550255125522553255425552556100 unmodified lines265726582659266026612662266326642665266614 unmodified lines2681268226832684268526862687268826892690147 unmodified lines2838283928402841284228432844284528462847284828492 unmodified lines285228532854285528562857285828592860194 unmodified linesresults.append(("", 0.0))return results, 0.0class AutoRoutingOCRWrapper:def __init__(self, cham_model, viet_model):self.cham_model = cham_modelself.viet_model = viet_modeldef __call__(self, img_list):if not img_list:return [], 0.0# 1. Predict all images with Cham model in a single batchprint(f"DEBUG: [AutoRouting] Calling Cham model for {len(img_list)} images...")cham_res, _ = self.cham_model(img_list)print("DEBUG: [AutoRouting] Cham model prediction finished.")# 2. Identify indices requiring Vietnamese OCRviet_indices = []viet_imgs = []for i, (cham_text, cham_conf) in enumerate(cham_res):if cham_conf < 0.65:viet_indices.append(i)viet_imgs.append(img_list[i])# 3. Predict those with Vietnamese model in a single batchviet_res = []if viet_imgs:print(f"DEBUG: [AutoRouting] Calling Viet model for {len(viet_imgs)} images...")viet_batch_res, _ = self.viet_model(viet_imgs)viet_res = viet_batch_resprint("DEBUG: [AutoRouting] Viet model prediction finished.")# 4. Merge results keeping router logicfinal_results = [None] * len(img_list)viet_ptr = 0for i in range(len(img_list)):cham_text, cham_conf = cham_res[i]if cham_conf >= 0.65:final_results[i] = (cham_text, cham_conf)else:if viet_ptr < len(viet_res):viet_text, viet_conf = viet_res[viet_ptr]else:viet_text, viet_conf = ("", 0.0)viet_ptr += 1if cham_conf >= 0.40 and cham_conf > viet_conf - 0.15:final_results[i] = (cham_text, cham_conf)else:final_results[i] = (viet_text, viet_conf)return final_results, 0.0def get_ocr_model(version):9 unmodified linesif version == 'auto':cham_model = get_ocr_model(DEFAULT_CHAM_MODEL)viet_model = get_ocr_model('vi')ocr_model = AutoRoutingOCRWrapper(cham_model, viet_model)ocr_models[version] = ocr_modelreturn ocr_model33 unmodified lines# 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):if str(version).startswith("v24_1"):dict_path = os.path.join(PROJECT_ROOT, "data", "cham_dict_v24_1.txt")elif str(version).startswith("v24"):dict_path = os.path.join(PROJECT_ROOT, "data", "cham_dict_v24.txt")else:dict_path = os.path.join(PROJECT_ROOT, "data", "cham_dict_v23.txt")sys_argv_backup = sys.argvsys.argv = [sys.argv[0]]3 unmodified linesargs.rec_model_dir = model_dirargs.rec_char_dict_path = dict_pathimport paddleargs.use_gpu = paddle.is_compiled_with_cuda()manifest_for_shape = {}if version != 'vi':27 unmodified linesargs.enable_mkldnn = env_mkldnnargs.mkldnn_cache_capacity = 32env_threads = os.getenv("CPU_THREADS")if env_threads:args.cpu_threads = int(env_threads)else:# Default to 1 thread to prevent OpenMP deadlocks on Windows socket serversargs.cpu_threads = 1args.ir_optim = False # Disable on CPU to prevent OneDNN crashargs.precision = "fp32"print(f"⚙️ Loading PaddleOCR Model {version} (GPU: {args.use_gpu}, MKLDNN: {args.enable_mkldnn}, Batch: {args.rec_batch_num}, Threads: {args.cpu_threads})...")709 unmodified linesdef get_model_info(model_ver):"""Returns provenance info (model id, weight fingerprints, detector, normalizer) for the response."""info = {"model": model_ver, "normalizer": None}rec_versions = [DEFAULT_CHAM_MODEL, 'vi'] if model_ver == 'auto' else [model_ver]recs = []for v in rec_versions:p = ocr_model_paths.get(v)29 unmodified linesinfo["paddle_version"] = _paddle.__version__except Exception:info["paddle_version"] = Noneif model_ver in ['v24', 'v25', 'v26'] or str(model_ver).startswith('v24'):info["normalizer"] = NORMALIZER_VERSIONreturn info1383 unmodified linesrec_res, _ = ocr(rec_crops)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'] = confnum_detected = len(lines_metadata)dropped_text_lines = []lines_metadata, final_crops = apply_line_quality_gates(lines_metadata, final_crops, dropped_text_lines)32 unmodified linespred_text = meta['candidates'][meta['selected_crop_type']]['prediction']confidence = meta['candidates'][meta['selected_crop_type']]['confidence']if model_ver in ['v24', 'v25', 'v26'] or str(model_ver).startswith('v24'):try:from scripts.generate_data import normalize_unicodepred_text = normalize_unicode(pred_text)except Exception as e:print(f"Warning: normalize_unicode failed: {e}")# Encode cropped line to base64 for frontend display_, buffer = cv2.imencode('.png', line_img)line_b64 = base64.b64encode(buffer).decode('utf-8')cal_conf = calibrate_line_confidence(confidence, model_ver, pred_text)# Backward-compatible formatresults.append({100 unmodified lines}# ==============================================================================# Web Server Request Handler# ==============================================================================class ChamOCRRequestHandler(BaseHTTPRequestHandler):def do_GET(self):parsed_path = urllib.parse.urlparse(self.path).path14 unmodified lineshtml_content = "<h1>Error: index.html not found!</h1>"self.wfile.write(html_content.encode('utf-8'))elif parsed_path in ('/research', '/research.html', '/methodology', '/paper'):self.send_response(200)self.send_header('Content-type', 'text/html; charset=utf-8')self.send_header('Cache-Control', 'public, max-age=1800')self.end_headers()dir_path = os.path.dirname(os.path.abspath(__file__))147 unmodified linesself.send_json_response({'error': f'Cropped OCR transcription error ({model_ver}): {e}'}, 200)returnif model_ver in ['v24', 'v25', 'v26'] or str(model_ver).startswith('v24'):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')2 unmodified lines'text': pred_text,'confidence': float(conf),'calibrated_confidence': calibrate_line_confidence(conf, model_ver, pred_text),'crop_image': f"data:image/png;base64,{crop_b64}",'bbox': [x1, y1, x2, y2]})else:self.send_error(404, 'Endpoint Not Found')194 unmodified lines1951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333349 unmodified lines34434534634734834935035135235335435535633 unmodified lines3903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224233 unmodified lines42742842943043143227 unmodified lines460461462463464465466467468469470471472473474475476709 unmodified lines118611871188118911901191119229 unmodified lines12221223122412251226122712281383 unmodified lines26122613261426152616261726182619262026212622262332 unmodified lines26562657265826592660266126622663266426652666266726682669267026712672267326742675100 unmodified lines27762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315614 unmodified lines3171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240147 unmodified lines33883389339033913392339333943395339633973398339934002 unmodified lines3403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451194 unmodified linesresults.append(("", 0.0))return results, 0.0_ROUTER_ILLEGAL_MEDIAL_RE = re.compile(r'[\uAA33\uAA34]{2,}|[\uAA2F\uAA30]{2,}')_ROUTER_EDITORIAL_SYMS = set('-/_*[]{}<>=+%@#')def _cham_script_ratio(text):non_space = [ch for ch in (text or '') if not ch.isspace()]if not non_space:return 0.0cham_cnt = sum(1 for ch in non_space if '\uAA00' <= ch <= '\uAA5F')return cham_cnt / float(len(non_space))def _latin_alpha_ratio(text):non_space = [ch for ch in (text or '') if not ch.isspace()]if not non_space:return 0.0lat_cnt = sum(1 for ch in non_space if ('a' <= ch.lower() <= 'z') or ('\u00C0' <= ch <= '\u1EF9'))return 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."""def __init__(self, cham_model, viet_model, cham_w320_model=None, primary_ver=None, w320_ver='v24_1_r3_1'):self.cham_model = cham_modelself.viet_model = viet_modelself.cham_w320_model = cham_w320_modelself.primary_ver = primary_ver or DEFAULT_CHAM_MODELself.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_uexcept Exception:_norm_u = lambda x: x# 1. Fast primary pass with W=480 Cham specialistcham_res, _ = self.cham_model(img_list)# 2. Selective W=320 Cham adjudication on medium-width lower-confidence textline cropsw320_indices = []w320_imgs = []if self.cham_w320_model is not None:for i, (t480, c480) in enumerate(cham_res):im = img_list[i]h, w = im.shape[:2] if hasattr(im, 'shape') and len(im.shape) >= 2 else (48, 320)ar48 = float(w) * 48.0 / max(1.0, float(h))if float(c480) < 0.905 and 104.0 <= ar48 < 420.0:w320_indices.append(i)w320_imgs.append(im)w320_map = {}if w320_imgs:w320_batch, _ = self.cham_w320_model(w320_imgs)for idx_orig, res320 in zip(w320_indices, w320_batch):w320_map[idx_orig] = res320best_cham = []best_cham_ver = []for i, (raw_t480, c480) in enumerate(cham_res):c480 = float(c480)t480 = _norm_u(raw_t480) if any('\uAA00' <= ch <= '\uAA5F' for ch in (raw_t480 or '')) else (raw_t480 or '')chosen_txt, chosen_conf, chosen_ver = t480, c480, self.primary_verif i in w320_map:raw_t320, c320 = w320_map[i]c320 = float(c320)t320 = _norm_u(raw_t320) if any('\uAA00' <= ch <= '\uAA5F' for ch in (raw_t320 or '')) else (raw_t320 or '')cal480 = calibrate_line_confidence(c480, self.primary_ver, t480)cal320 = calibrate_line_confidence(c320, self.w320_ver, t320)score480 = cal480 - (0.08 if _ROUTER_ILLEGAL_MEDIAL_RE.search(raw_t480 or '') else 0.0)score320 = cal320 - (0.08 if _ROUTER_ILLEGAL_MEDIAL_RE.search(raw_t320 or '') else 0.0)dropped_editorial = any(t480.count(s) > t320.count(s) for s in _ROUTER_EDITORIAL_SYMS) and c480 >= 0.70if (not dropped_editorial) and (score320 > score480 + 0.020):chosen_txt, chosen_conf, chosen_ver = t320, c320, self.w320_verbest_cham.append((chosen_txt, chosen_conf))best_cham_ver.append(chosen_ver)# 3. Selective Vietnamese / Latin multiscript handoff ONLY when Cham CTC emits non-Cham soup or severe uncertaintyviet_indices = []viet_imgs = []for i, (c_txt, c_conf) in enumerate(best_cham):c_ratio = _cham_script_ratio(c_txt)if (c_ratio < 0.62 and c_conf < 0.85) or c_conf < 0.34:viet_indices.append(i)viet_imgs.append(img_list[i])viet_map = {}if viet_imgs:viet_batch, _ = self.viet_model(viet_imgs)for idx_orig, v_res in zip(viet_indices, viet_batch):viet_map[idx_orig] = v_res# 4. Script-aware adjudication preventing false Vietnamese takeover on historical Cham manuscriptsfinal_results = [None] * len(img_list)selected_vers = []for i in range(len(img_list)):c_txt, c_conf = best_cham[i]c_ver = best_cham_ver[i]if i not in viet_map:final_results[i] = (c_txt, c_conf)selected_vers.append(c_ver)continuev_txt, v_conf = viet_map[i]v_conf = float(v_conf)c_ratio = _cham_script_ratio(c_txt)v_alpha = _latin_alpha_ratio(v_txt)take_viet = Falseif v_alpha >= 0.42:if c_ratio < 0.60:# ASCII digit/symbol soup from feeding Latin/Vietnamese into Cham CTC -> route to Vi/Latintake_viet = (v_conf >= 0.52 and v_conf >= c_conf - 0.08)else:# 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 = Trueif take_viet:final_results[i] = (v_txt, v_conf)selected_vers.append('vi')else:final_results[i] = (c_txt, c_conf)selected_vers.append(c_ver)self.last_selected_versions = selected_versreturn final_results, 0.0def get_ocr_model(version):9 unmodified linesif version == 'auto':cham_model = get_ocr_model(DEFAULT_CHAM_MODEL)w320_ver = 'v24_1_r3_1'w320_dir = os.path.join(PROJECT_ROOT, "data", "output", f"rec_cham_inference_{w320_ver}")cham_w320 = get_ocr_model(w320_ver) if (w320_ver != DEFAULT_CHAM_MODEL and os.path.exists(w320_dir)) else Noneviet_model = get_ocr_model('vi')ocr_model = AutoRoutingOCRWrapper(cham_model, viet_model, cham_w320_model=cham_w320, primary_ver=DEFAULT_CHAM_MODEL, w320_ver=w320_ver)ocr_models[version] = ocr_modelreturn ocr_model33 unmodified lines# 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):dict_path = bundled_dictelif str(version).startswith("v24_1"):dict_path = os.path.join(PROJECT_ROOT, "data", "cham_dict_v24_1.txt")elif str(version).startswith("v24"):dict_path = os.path.join(PROJECT_ROOT, "data", "cham_dict_v24.txt")else:dict_path = os.path.join(PROJECT_ROOT, "data", "cham_dict_v23.txt")import paddlehas_rec_pdmodel = os.path.exists(os.path.join(model_dir, "inference.pdmodel"))has_rec_json = os.path.exists(os.path.join(model_dir, "inference.json"))if has_rec_json and not has_rec_pdmodel:try:paddle_major = int(str(getattr(paddle, "__version__", "0")).split(".")[0])except Exception:paddle_major = 0if paddle_major < 3:if version == 'vi':print("⚠️ rec_vietnamese_infer is PIR (.json) on Paddle 2.x; falling back to OfficialPaddleOCRWrapper(lang='vi').")ocr_model = OfficialPaddleOCRWrapper(lang='vi')ocr_models[version] = ocr_modelreturn ocr_modelraise RuntimeError(f"Model '{version}' is exported in Paddle 3 PIR format (inference.json) and requires Paddle >= 3.0 "f"(current runtime: Paddle {getattr(paddle, '__version__', 'unknown')}). Please select V24.1-R4 or launch Studio with Python 3.13 / Paddle 3.x.")sys_argv_backup = sys.argvsys.argv = [sys.argv[0]]3 unmodified linesargs.rec_model_dir = model_dirargs.rec_char_dict_path = dict_pathargs.use_gpu = paddle.is_compiled_with_cuda()manifest_for_shape = {}if version != 'vi':27 unmodified linesargs.enable_mkldnn = env_mkldnnargs.mkldnn_cache_capacity = 32env_threads = os.getenv("VI_CPU_THREADS") if version == "vi" else os.getenv("CPU_THREADS")if env_threads:args.cpu_threads = int(env_threads)elif version == "vi":# Heavy PP-OCRv5_server_rec benefits ~3.2x from multi-thread math without MKLDNNargs.cpu_threads = min(8, max(1, os.cpu_count() or 2))else:# Default to 1 thread for lightweight SVTR_LCNet to prevent OpenMP contentionargs.cpu_threads = int(os.getenv("CPU_THREADS", "1"))args.ir_optim = (version == "vi") # Constant-fold PIR graph on heavy Vi model while MKLDNN stays disabledargs.precision = "fp32"print(f"⚙️ Loading PaddleOCR Model {version} (GPU: {args.use_gpu}, MKLDNN: {args.enable_mkldnn}, Batch: {args.rec_batch_num}, Threads: {args.cpu_threads})...")709 unmodified linesdef get_model_info(model_ver):"""Returns provenance info (model id, weight fingerprints, detector, normalizer) for the response."""info = {"model": model_ver, "normalizer": None}rec_versions = [DEFAULT_CHAM_MODEL, 'v24_1_r3_1', 'vi'] if model_ver == 'auto' else [model_ver]recs = []for v in rec_versions:p = ocr_model_paths.get(v)29 unmodified linesinfo["paddle_version"] = _paddle.__version__except Exception:info["paddle_version"] = Noneif model_ver in ['auto', 'v24', 'v25', 'v26'] or str(model_ver).startswith('v24'):info["normalizer"] = NORMALIZER_VERSIONreturn info1383 unmodified linesrec_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)32 unmodified linespred_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 '')):try:from scripts.generate_data import normalize_unicodepred_text = normalize_unicode(pred_text)except Exception as e:print(f"Warning: normalize_unicode failed: {e}")# Encode cropped line to base64 for frontend display_, 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({100 unmodified lines}# ==============================================================================# Studio Workbench Helpers (Samples, Model Catalog, Paragraph Flow, ZIP Export)# ==============================================================================_SAMPLE_SPECS = [{"id": "agal_panduranga","name": "Palm-Leaf Agal Folio — Panduranga","filename": "ood_agal_01_panduranga.png","relpath": "ocr-benchmark/data/realscan_gold_v2/pages/ood_agal_01_panduranga.png","category": "Palm-Leaf (Agal)","recommended_model": "v24_1_r4","description": "Traditional Panduranga calligraphic hand on elongated palm-leaf surface with tight interlinear spacing."},{"id": "curved_panduranga","name": "Curved Baseline Folio — Ribbon Rectification","filename": "ood_v3_16_curved_panduranga.png","relpath": "ocr-benchmark/data/realscan_gold_v3/pages/ood_v3_16_curved_panduranga.png","category": "Curved Baseline","recommended_model": "v24_1_r4","description": "Undulating folio baseline demonstrating Cham-DBNet v1_poly_u1.8 polygon ribbon straightening."},{"id": "two_col_wijaya","name": "Two-Column Manuscript Folio — Wijaya","filename": "ood_folio_06_wijaya_2col.png","relpath": "ocr-benchmark/data/realscan_gold_v2/pages/ood_folio_06_wijaya_2col.png","category": "Multi-Column","recommended_model": "v24_1_r4","description": "Dual-column historical layout showcasing automatic column-wise reading order reconstruction."},{"id": "bilingual_campa_vi","name": "Bilingual Cham–Vietnamese Glossary Folio","filename": "ood_v3_21_bilingual_campa_vi.png","relpath": "ocr-benchmark/data/realscan_gold_v3/pages/ood_v3_21_bilingual_campa_vi.png","category": "Bilingual Multiscript","recommended_model": "auto","description": "Interleaved Akhar Thrah and Vietnamese glosses demonstrating the Tri-Specialist Auto-Router."},{"id": "printed_book_semibold","name": "Printed Akhar Thrah Literary Page","filename": "ood_book_10_semibold.png","relpath": "ocr-benchmark/data/realscan_gold_v2/pages/ood_book_10_semibold.png","category": "Printed Book","recommended_model": "v24_1_r4","description": "Modern printed Eastern Cham verse and prose with Danda and Double Danda stanza markers."},{"id": "classical_verse_clean","name": "Classical Verse Stanza Folio (Clean)","filename": "test_006_lvl1.png","relpath": "ocr-benchmark/data/images/test_006_lvl1.png","category": "Classical Verse","recommended_model": "v24_1_r4","description": "Clean baseline folio featuring Cham stanza numerals and multi-directional vowel clusters."}]_sample_thumb_cache = {}def _resolve_sample_path(spec):bundled_p = os.path.join(PROJECT_ROOT, "static", "samples", spec["filename"])if os.path.isfile(bundled_p):return bundled_prepo_root = os.path.dirname(PROJECT_ROOT)fallback_p = os.path.join(repo_root, *spec["relpath"].split("/"))if os.path.isfile(fallback_p):return fallback_preturn Nonedef list_curated_samples():available = []for spec in _SAMPLE_SPECS:abs_p = _resolve_sample_path(spec)if not abs_p:continuethumb_b64 = _sample_thumb_cache.get(spec["id"])dims = _sample_thumb_cache.get(spec["id"] + ":dims")if thumb_b64 is None:try:im = cv2.imread(abs_p, cv2.IMREAD_COLOR)if im is not None and im.size > 0:ih, iw = im.shape[:2]dims = [int(iw), int(ih)]scale = min(220.0 / max(1, iw), 150.0 / max(1, ih), 1.0)tw, th = max(1, int(round(iw * scale))), max(1, int(round(ih * scale)))resized = cv2.resize(im, (tw, th), interpolation=cv2.INTER_AREA)ok, buf = cv2.imencode(".jpg", resized, [int(cv2.IMWRITE_JPEG_QUALITY), 72])if ok:thumb_b64 = base64.b64encode(buf.tobytes()).decode("ascii")_sample_thumb_cache[spec["id"]] = thumb_b64_sample_thumb_cache[spec["id"] + ":dims"] = dimsexcept Exception:thumb_b64 = ""available.append({"id": spec["id"],"name": spec["name"],"filename": spec["filename"],"category": spec["category"],"recommended_model": spec["recommended_model"],"description": spec["description"],"dimensions": dims or [0, 0],"thumb": thumb_b64 or ""})return availabledef load_curated_sample(sample_id):spec = next((s for s in _SAMPLE_SPECS if s["id"] == sample_id), None)if not spec:return Noneabs_p = _resolve_sample_path(spec)if not abs_p:return Nonewith open(abs_p, "rb") as f:raw_bytes = f.read()im = cv2.imdecode(np.frombuffer(raw_bytes, np.uint8), cv2.IMREAD_COLOR)ih, iw = im.shape[:2] if im is not None else (0, 0)return {"id": spec["id"],"name": spec["name"],"filename": spec["filename"],"category": spec["category"],"recommended_model": spec["recommended_model"],"description": spec["description"],"width": int(iw),"height": int(ih),"image": base64.b64encode(raw_bytes).decode("ascii")}def list_available_models():catalog = [{"id": "v24_1_r4","label": "Cham V24.1-R4 (Production SOTA — W=480)","short_label": "V24.1-R4 SOTA","group": "Paleographic Cham Specialists","shape": "3, 48, 480","summary": "Wide-canvas pure-Cham recognizer with WiSE-FT real-scan calibration (2.55% real-camera CER).","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)","short_label": "Auto Router","group": "Multiscript & Bilingual","shape": "Adaptive","summary": "Combines W=480 Cham primary, W=320 archival adjudicator, and Vietnamese PP-OCRv5 handoff.","folder": None},{"id": "v24_1_r3_1","label": "Cham V24.1-R3.1 (W=320 Level-5 Degradation Specialist)","short_label": "V24.1-R3.1","group": "Paleographic Cham Specialists","shape": "3, 48, 320","summary": "Compact W=320 specialist tuned for narrow/medium degraded archival crops and gate closure.","folder": "rec_cham_inference_v24_1_r3_1"},{"id": "v24_1_r2_1_6","label": "Cham V24.1-R2.1.6 (Clean HarfBuzz & 14-Symbol Polish)","short_label": "V24.1-R2.1.6","group": "Paleographic Cham Specialists","shape": "3, 48, 320","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)","short_label": "V24 Baseline","group": "Historical Baselines","shape": "3, 48, 320","summary": "Foundational Logical Order recognizer with Cham numerals (꩐–꩙) and Danda punctuation.","folder": "rec_cham_inference_v24"},{"id": "v23","label": "Cham V23 (Legacy Baseline)","short_label": "V23 Legacy","group": "Historical Baselines","shape": "3, 48, 320","summary": "Early 93-token baseline preserved for longitudinal benchmark comparison.","folder": "rec_cham_inference_v23"},{"id": "vi","label": "Vietnamese (Fine-Tuned PP-OCRv5)","short_label": "Vietnamese","group": "Multiscript & Bilingual","shape": "Dynamic","summary": "High-accuracy Vietnamese & Latin recognizer for modern glosses, headers, and translations.","folder": "rec_vietnamese_infer"}]out_root = os.path.join(PROJECT_ROOT, "data", "output")try:import paddle as _pdlpaddle_major = int(str(getattr(_pdl, "__version__", "0")).split(".")[0])except Exception:paddle_major = 0enriched = []for item in catalog:folder = item["folder"]if folder is None:installed = Trueelse:mdir = os.path.join(out_root, folder)installed = os.path.isdir(mdir)if 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"] = installedentry["is_default"] = (item["id"] == DEFAULT_CHAM_MODEL)enriched.append(entry)return {"default_model": DEFAULT_CHAM_MODEL, "det_mode": DET_MODE, "models": enriched}def build_corpus_export_zip(payload):import ioimport zipfiledocs = payload.get("documents") or []try:from scripts.generate_data import normalize_unicode as _norm_uexcept Exception:_norm_u = lambda s: smem_zip = io.BytesIO()train_pairs = []jsonl_records = []md_sections = ["# Cham OCR Studio — Paleographic Corpus Export",f"- **Generated (UTC)**: {datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S UTC')}",f"- **Total Folios**: {len(docs)}","- **Service**: https://ocr.cham.asia",""]with zipfile.ZipFile(mem_zip, mode="w", compression=zipfile.ZIP_DEFLATED) as zf:for d_idx, doc in enumerate(docs, start=1):raw_name = str(doc.get("name") or f"folio_{d_idx:03d}.png")stem = re.sub(r"[^A-Za-z0-9._-]+", "_", os.path.splitext(raw_name)[0]).strip("_") or f"folio_{d_idx:03d}"lines = doc.get("lines") or []model_used = str(doc.get("model") or DEFAULT_CHAM_MODEL)status = str(doc.get("status") or "OCR done")plain_lines = []md_sections.append(f"## {d_idx}. {raw_name}")md_sections.append(f"- **Status**: {status} | **Model**: `{model_used}` | **Lines**: {len(lines)}")md_sections.append("")for l_idx, ln in enumerate(lines, start=1):txt = (ln.get("text") or "").strip()if any("\uAA00" <= ch <= "\uAA5F" for ch in txt):try:txt = _norm_u(txt)except Exception:passplain_lines.append(txt)conf = float(ln.get("confidence") or 0.0)verified = bool(ln.get("human_verified"))md_sections.append(f"{l_idx}. `{conf * 100:.0f}%`{' [Verified]' if verified else ''} {txt}")crop_b64 = ln.get("image") or ""crop_rel = Noneif isinstance(crop_b64, str) and crop_b64.strip() and txt:if "," in crop_b64:crop_b64 = crop_b64.split(",", 1)[1]pad = len(crop_b64) % 4if pad:crop_b64 += "=" * (4 - pad)try:crop_bytes = base64.b64decode(crop_b64)crop_rel = f"crops/{stem}_L{l_idx:03d}.png"zf.writestr(crop_rel, crop_bytes)train_pairs.append(f"{crop_rel}\t{txt}")except Exception:crop_rel = Nonejsonl_records.append(json.dumps({"image_name": raw_name,"line_idx": l_idx,"text": txt,"confidence": conf,"human_verified": verified,"model": model_used,"bbox": ln.get("bbox"),"crop_relpath": crop_rel}, ensure_ascii=False))md_sections.append("")zf.writestr(f"transcriptions/{stem}.txt", "\n".join(plain_lines) + "\n")zf.writestr("transcriptions/combined_corpus.md", "\n".join(md_sections) + "\n")zf.writestr("train_list.txt", "\n".join(train_pairs) + ("\n" if train_pairs else ""))zf.writestr("corrections.jsonl", "\n".join(jsonl_records) + ("\n" if jsonl_records else ""))zf.writestr("corpus_manifest.json", json.dumps({"exported_at_utc": datetime.now(timezone.utc).isoformat(),"service": "https://ocr.cham.asia","total_documents": len(docs),"total_training_crops": len(train_pairs),"documents": [{"image_name": d.get("name"),"status": d.get("status"),"model": d.get("model"),"lines": [{"index": ln.get("index", i + 1),"text": ln.get("text", ""),"confidence": ln.get("confidence", 0.0),"bbox": ln.get("bbox"),"coords": ln.get("coords"),"human_verified": bool(ln.get("human_verified"))}for i, ln in enumerate(d.get("lines") or [])]}for d in docs]}, ensure_ascii=False, indent=2))zf.writestr("README.txt", ("Cham OCR Studio — Archival & Active Learning Package\n""====================================================\n""Generated by https://ocr.cham.asia\n\n""Contents:\n""- transcriptions/<folio>.txt : Canonical Unicode Logical Order plaintext per folio\n""- transcriptions/combined_corpus.md : Consolidated scholarly markdown report\n""- corpus_manifest.json : Structured bounding-box & line metadata\n""- corrections.jsonl : Active-learning JSONL records\n""- train_list.txt + crops/*.png : Ready-to-train PaddleOCR tab-delimited pairs\n"))return mem_zip.getvalue()# ==============================================================================# Web Server Request Handler# ==============================================================================_STATIC_MIME_TYPES = {".css": "text/css; charset=utf-8",".js": "application/javascript; charset=utf-8",".mjs": "application/javascript; charset=utf-8",".json": "application/json; charset=utf-8",".svg": "image/svg+xml",".png": "image/png",".jpg": "image/jpeg",".jpeg": "image/jpeg",".webp": "image/webp",".ico": "image/x-icon",".woff2": "font/woff2",".ttf": "font/ttf",}class ChamOCRRequestHandler(BaseHTTPRequestHandler):def do_GET(self):parsed_path = urllib.parse.urlparse(self.path).path14 unmodified lineshtml_content = "<h1>Error: index.html not found!</h1>"self.wfile.write(html_content.encode('utf-8'))elif parsed_path in ('/favicon.ico', '/favicon.svg'):svg_icon = ('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">''<rect width="64" height="64" rx="14" fill="#C96442"/>''<text x="32" y="45" font-size="36" text-anchor="middle" fill="#FFFCF7" font-family="sans-serif">ꨌ</text>''</svg>').encode('utf-8')self.send_response(200)self.send_header('Content-type', 'image/svg+xml')self.send_header('Content-Length', str(len(svg_icon)))self.send_header('Cache-Control', 'public, max-age=86400')self.end_headers()self.wfile.write(svg_icon)elif parsed_path.startswith('/static/'):dir_path = os.path.dirname(os.path.abspath(__file__))static_root = os.path.realpath(os.path.join(dir_path, 'static'))rel_sub = parsed_path[len('/static/'):].lstrip('/\\')candidate = os.path.realpath(os.path.join(static_root, rel_sub))try:common = os.path.commonpath([static_root, candidate])except ValueError:common = ""if common != static_root or not os.path.isfile(candidate):self.send_error(404, 'Static Asset Not Found')returnext = os.path.splitext(candidate)[1].lower()mime = _STATIC_MIME_TYPES.get(ext, 'application/octet-stream')with open(candidate, 'rb') as sf:payload = sf.read()self.send_response(200)self.send_header('Content-type', mime)self.send_header('Cache-Control', 'no-cache')self.send_header('Content-Length', str(len(payload)))self.end_headers()self.wfile.write(payload)elif parsed_path == '/api/samples':self.send_json_response({'samples': list_curated_samples()})elif parsed_path.startswith('/api/sample/'):sample_id = urllib.parse.unquote(parsed_path[len('/api/sample/'):]).strip('/')sample_data = load_curated_sample(sample_id)if sample_data is None:self.send_json_response({'error': f'Sample not found: {sample_id}'}, 404)else:self.send_json_response(sample_data)elif parsed_path == '/api/models':self.send_json_response(list_available_models())elif parsed_path in ('/help', '/help.html', '/guide', '/manual', '/docs'):self.send_response(200)self.send_header('Content-type', 'text/html; charset=utf-8')self.send_header('Cache-Control', 'no-cache')self.end_headers()dir_path = os.path.dirname(os.path.abspath(__file__))help_path = os.path.join(dir_path, 'help.html')if os.path.exists(help_path):with open(help_path, 'r', encoding='utf-8') as f:content = f.read()else:content = "<h1>Error: help.html not found!</h1>"self.wfile.write(content.encode('utf-8'))elif parsed_path in ('/research', '/research.html', '/methodology', '/paper'):self.send_response(200)self.send_header('Content-type', 'text/html; charset=utf-8')self.send_header('Cache-Control', 'no-cache')self.end_headers()dir_path = os.path.dirname(os.path.abspath(__file__))147 unmodified linesself.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'):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}")_, buffer = cv2.imencode('.png', crop_img)crop_b64 = base64.b64encode(buffer).decode('utf-8')2 unmodified lines'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]})elif self.path == '/reconstruct_paragraphs':content_length = int(self.headers.get('Content-Length') or 0)post_data = self.rfile.read(content_length) if content_length > 0 else b'{}'try:data = json.loads(post_data.decode('utf-8'))lines_in = data.get('lines') or []from paragraph_flow import reconstruct_paragraph_flowparagraphs, boundaries = reconstruct_paragraph_flow(lines_in)self.send_json_response({'paragraphs': paragraphs, 'boundaries': boundaries})except Exception as e:self.send_json_response({'error': f'Paragraph reconstruction failed: {e}', 'paragraphs': [], 'boundaries': []}, 200)elif self.path == '/normalize_text':content_length = int(self.headers.get('Content-Length') or 0)post_data = self.rfile.read(content_length) if content_length > 0 else b'{}'try:data = json.loads(post_data.decode('utf-8'))raw_text = str(data.get('text') or '')norm_text = raw_textif any('\uAA00' <= ch <= '\uAA5F' for ch in raw_text):from scripts.generate_data import normalize_unicodenorm_text = normalize_unicode(raw_text)self.send_json_response({'normalized_text': norm_text, 'changed': (norm_text != raw_text)})except Exception as e:self.send_json_response({'error': str(e), 'normalized_text': data.get('text', ''), 'changed': False}, 200)elif self.path == '/export_corpus_zip':content_length = int(self.headers.get('Content-Length') or 0)post_data = self.rfile.read(content_length) if content_length > 0 else b'{}'try:data = json.loads(post_data.decode('utf-8'))zip_bytes = build_corpus_export_zip(data)self.send_response(200)self.send_header('Content-type', 'application/zip')self.send_header('Content-Disposition', 'attachment; filename="cham_ocr_corpus_export.zip"')self.send_header('Content-Length', str(len(zip_bytes)))self.send_header('Access-Control-Allow-Origin', '*')self.end_headers()self.wfile.write(zip_bytes)except Exception as e:self.send_json_response({'error': f'Failed to build corpus ZIP: {e}'}, 500)else:self.send_error(404, 'Endpoint Not Found')
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>User Guide & Feature Manual — Cham OCR Studio (ocr.cham.asia)</title> <meta name="description" content="Complete user manual and paleographic feature reference for Cham OCR Studio (https://ocr.cham.asia) — layout modes, multi-page PDF & batch OCR, polygon ribbons, stanza flow, Unicode cluster inspector, virtual keyboard, and corpus export."> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Google+Sans+Flex:wght@300..800&family=JetBrains+Mono:wght@400;500;600;700&family=Noto+Sans+Cham:wght@400;600;700&display=swap" rel="stylesheet"> <link rel="stylesheet" href="/static/css/help.css"></head><body>
<!-- Top Reading Progress Bar --> <div class="help-progress-track" aria-hidden="true"> <div class="help-progress-bar" id="help-progress-bar"></div> </div>
<!-- Unified Top Navigation Header --> <header class="help-navbar"> <a href="/" class="help-brand" title="Return to Cham OCR Studio Workbench"> <span class="help-emblem" aria-hidden="true">ꨌ</span> <span class="help-brand-titles"> <span class="help-brand-main">Cham OCR Studio — User Guide</span> <span class="help-brand-sub">Complete Feature Manual & Paleographic Workflow Reference</span> </span> </a>
<div class="help-nav-actions"> <button type="button" class="help-btn mobile-menu-btn" onclick="toggleHelpMobileToc()"> <span>☰ Guide Sections</span> </button> <a href="/" class="help-btn help-btn-primary"> <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M19 12H5M12 19l-7-7 7-7"/></svg> <span>Open OCR Workbench</span> </a> <a href="/research" class="help-btn"> <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"/></svg> <span>Technical Report</span> </a> <button type="button" class="help-btn" onclick="window.print()" title="Print or Save User Guide as PDF"> <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="6 9 6 2 18 2 18 9"/><path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"/><rect x="6" y="14" width="12" height="8"/></svg> <span>Print Guide</span> </button> </div> </header>
<!-- Main 2-Column Documentation Container --> <div class="help-layout">
<!-- Sticky Searchable Sidebar TOC --> <aside class="help-sidebar" id="help-sidebar" aria-label="User Guide Navigation"> <div class="sidebar-label">Guide Contents</div> <div class="help-search-box"> <input type="search" id="help-search-input" class="help-search-input" placeholder="Search features or shortcuts (/)" oninput="filterHelpGuide(this.value)"> </div> <ul class="toc-nav-list"> <li class="toc-nav-item"><a href="#quickstart" class="toc-nav-link active">Quick-Start Workflow</a></li> <li class="toc-nav-item"> <a href="#sec-layouts" class="toc-nav-link">1. Workspace & Layout Modes</a> <ul class="toc-sub-list"> <li><a href="#sec-layouts-modes" class="toc-sub-link">1.1 Four View Modes</a></li> <li><a href="#sec-layouts-resizers" class="toc-sub-link">1.2 Split Resizers & Command Palette</a></li> </ul> </li> <li class="toc-nav-item"> <a href="#sec-intake" class="toc-nav-link">2. Upload, PDF & Batch Queue</a> <ul class="toc-sub-list"> <li><a href="#sec-intake-channels" class="toc-sub-link">2.1 Images, PDF & Specimens</a></li> <li><a href="#sec-intake-batch" class="toc-sub-link">2.2 Automated Batch OCR</a></li> <li><a href="#sec-intake-badges" class="toc-sub-link">2.3 Queue Filters & Status Badges</a></li> </ul> </li> <li class="toc-nav-item"> <a href="#sec-models" class="toc-nav-link">3. Models & Segmentation Engine</a> <ul class="toc-sub-list"> <li><a href="#sec-models-catalog" class="toc-sub-link">3.1 Choosing a Recognition Model</a></li> <li><a href="#sec-models-seg" class="toc-sub-link">3.2 Detection & Reading Order</a></li> </ul> </li> <li class="toc-nav-item"> <a href="#sec-canvas" class="toc-nav-link">4. Manuscript Canvas & HUD</a> <ul class="toc-sub-list"> <li><a href="#sec-canvas-nav" class="toc-sub-link">4.1 Zoom, Pan & 90° Rotation</a></li> <li><a href="#sec-canvas-boxes" class="toc-sub-link">4.2 BBoxes, Polygons & Draw Mode</a></li> <li><a href="#sec-canvas-optics" class="toc-sub-link">4.3 Magnifier Loupe & Optical Filters</a></li> </ul> </li> <li class="toc-nav-item"> <a href="#sec-editor" class="toc-nav-link">5. Transcription Editor & Linguistics</a> <ul class="toc-sub-list"> <li><a href="#sec-editor-modes" class="toc-sub-link">5.1 Diplomatic Lines vs Stanza Flow</a></li> <li><a href="#sec-editor-ling" class="toc-sub-link">5.2 Romanization & Cluster Inspector</a></li> <li><a href="#sec-editor-actions" class="toc-sub-link">5.3 Line Editing, Split, Merge & Undo</a></li> </ul> </li> <li class="toc-nav-item"><a href="#sec-keyboard" class="toc-nav-link">6. Akhar Thrah Virtual Keyboard</a></li> <li class="toc-nav-item"><a href="#sec-export" class="toc-nav-link">7. Multi-Format & ZIP Corpus Export</a></li> <li class="toc-nav-item"><a href="#sec-shortcuts" class="toc-nav-link">8. Master Keyboard Shortcuts</a></li> <li class="toc-nav-item"><a href="#sec-faq" class="toc-nav-link">9. Paleographic Tips & FAQ</a></li> </ul> </aside>
<!-- Main Documentation Article --> <main class="help-content">
<!-- Hero & 4-Step Quick-Start --> <section id="quickstart" class="help-hero"> <div class="hero-eyebrow">Official Documentation · https://ocr.cham.asia</div> <h1>Cham OCR Studio — Complete User Guide</h1> <p> Welcome to <strong>Cham OCR Studio</strong>, an open-source digital paleography and optical character recognition workbench purpose-built for historical and modern Eastern Cham (<em>Akhar Thrah</em>, <span class="cham-inline">ꨀꨇꩉ ꨔꨴꩍ</span>) manuscripts, bilingual glossaries, and multi-page archival corpora. </p>
<div class="quickstart-grid"> <div class="step-card"> <span class="step-num">1</span> <div class="step-title">Load Manuscripts</div> <div class="step-desc">Upload multiple images, rasterize a multi-page PDF, paste via <kbd>Ctrl+V</kbd>, or click an <strong>Archival Specimen</strong>.</div> </div> <div class="step-card"> <span class="step-num">2</span> <div class="step-title">Run Transcription</div> <div class="step-desc">Select a model (default <code>V24.1-R4 SOTA</code>) and click <strong>Transcribe</strong> (<kbd>Ctrl+Enter</kbd>) or <strong>Batch</strong> (<kbd>Ctrl+Shift+Enter</kbd>).</div> </div> <div class="step-card"> <span class="step-num">3</span> <div class="step-title">Inspect & Verify</div> <div class="step-desc">Inspect polygon ribbons, optical filters, Romanized transliteration, and Unicode clusters; verify lines with <kbd>A</kbd>.</div> </div> <div class="step-card"> <span class="step-num">4</span> <div class="step-title">Export Corpus</div> <div class="step-desc">Export active folio or full multi-page queue to <code>.txt</code>, <code>.md</code>, <code>.json</code>, <code>PAGE-XML</code>, or Active Learning <code>.zip</code>.</div> </div> </div> </section>
<!-- SECTION 1: WORKSPACE & LAYOUT MODES --> <section id="sec-layouts" class="guide-section"> <h2><span class="sec-badge">01</span> Workspace Architecture & Layout Modes</h2> <p> Different physical manuscript formats—from tall bark-paper codices (<em>kertas</em>) to wide horizontal palm-leaf strips (<em>agal</em>)—demand adaptable screen geometry. Use the <strong>Layout ▾</strong> dropdown in the right header cluster (or press <kbd>Alt+1..4</kbd>) to switch layouts instantaneously without losing your zoom, selection, or unsaved edits. </p>
<h3 id="sec-layouts-modes">1.1 Four Specialized View Modes</h3> <div class="feature-grid-2"> <div class="feature-card"> <div class="feature-card-head"> <span class="feature-card-title">3-Pane Workbench (Default)</span> <kbd>Alt + 1</kbd> </div> <div class="feature-card-body"> Displays the <strong>Corpus Queue</strong> on the left, the interactive <strong>Manuscript Canvas</strong> in the center, and the <strong>Transcription Editor</strong> on the right. Ideal for managing multi-page archival projects. </div> </div> <div class="feature-card"> <div class="feature-card-head"> <span class="feature-card-title">Compare (2-Pane Side-by-Side)</span> <kbd>Alt + 2</kbd> </div> <div class="feature-card-body"> Collapses the left Queue Sidebar to dedicate 100% of horizontal width to side-by-side diplomatic collation between the high-resolution folio scan and the extracted Cham textlines. </div> </div> <div class="feature-card"> <div class="feature-card-head"> <span class="feature-card-title">Stacked (Horizontal–Vertical Split)</span> <kbd>Alt + 3</kbd> </div> <div class="feature-card-body"> Places the Manuscript Canvas in a wide top viewport directly above a full-width Transcription Editor below. Purpose-built for elongated horizontal <strong>palm-leaf (<em>agal</em>) folios</strong> and wide epigraphic rubbings. </div> </div> <div class="feature-card"> <div class="feature-card-head"> <span class="feature-card-title">Reader (Focus Scholarly Edition)</span> <kbd>Alt + 4</kbd> </div> <div class="feature-card-body"> Hides surrounding chrome to present a centered, book-like reading column complete with inline cropped textline strips, stanza reconstruction, and Romanized subtitles. </div> </div> </div>
<h3 id="sec-layouts-resizers">1.2 Smart Queue Drawer, Draggable Resizers & Command Palette</h3> <ul> <li><strong>Smart Auto-Collapsing Queue (<kbd>Alt + Q</kbd>)</strong>: On initial launch or single-folio proofreading, the left <em>Corpus Queue</em> collapses automatically to maximize reading width; importing a multi-page batch or PDF expands it automatically. Click the floating <strong>Queue</strong> pill at the top-left of the canvas (or press <kbd>Alt + Q</kbd>) anytime to toggle it manually.</li> <li><strong>Drag-to-Resize Dividers</strong>: Drag the vertical hairline dividers between panes (or the horizontal divider in <em>Stacked</em> mode) to customize column proportions. All dimensions persist automatically in browser storage; <strong>double-click any divider</strong> to snap back to its default width.</li> <li><strong>Command Palette (<kbd>Ctrl + K</kbd> / <kbd>⌘K</kbd>)</strong>: Click <strong>Ctrl+K</strong> in the top header to fuzzy-search and trigger any Studio operation—switching layouts, running batch OCR, toggling overlays, or exporting corpora—entirely from the keyboard.</li> </ul> </section>
<!-- SECTION 2: UPLOAD, PDF & BATCH QUEUE --> <section id="sec-intake" class="guide-section"> <h2><span class="sec-badge">02</span> Corpus Intake, Multi-Page PDF Import & Batch Queue</h2>
<h3 id="sec-intake-channels">2.1 Five Ways to Load Manuscript Folios</h3> <ul> <li><strong>Add Images / PDF (<kbd>Ctrl + O</kbd>)</strong>: Select one or dozens of image files (<code>.png</code>, <code>.jpg</code>, <code>.webp</code>, <code>.bmp</code>) or a multi-page <code>.pdf</code> document simultaneously.</li> <li><strong>Drag & Drop</strong>: Drag image files or PDFs from your file manager directly onto either the left <em>Corpus Queue</em> intake box or the central <em>Manuscript Canvas</em>.</li> <li><strong>Direct Clipboard Paste (<kbd>Ctrl + V</kbd>)</strong>: Copy any screenshot or cropped manuscript region to your system clipboard and press <kbd>Ctrl + V</kbd> anywhere in the Studio to enqueue it immediately.</li> <li><strong>Multi-Page PDF Importer</strong>: Dropping or selecting a <code>.pdf</code> opens the <em>Import Multi-Page PDF</em> dialog: <ul> <li>Specify a flexible <strong>Page Range</strong> such as <code>1-10</code>, <code>1,4,7-12</code>, or <code>all</code>.</li> <li>Choose a <strong>Rasterization Resolution</strong>: <em>150 DPI</em> (fast preview), <em>220 DPI</em> (recommended paleographic fidelity), or <em>300 DPI</em> (ultra-fine epigraphic detail).</li> </ul> </li> <li><strong>Curated Archival Specimens</strong>: Click <strong>Specimens</strong> in the Corpus Queue (or click one of the <em>Instant Archival Specimens</em> cards on the empty stage) to load real benchmark folios—including Panduranga palm-leaf <em>agal</em>, curved baselines, two-column Wijaya layouts, and bilingual Cham–Vietnamese pages—or click <strong>Load 4-Folio Demo Batch</strong> to test batch processing immediately.</li> </ul>
<h3 id="sec-intake-batch">2.2 Automated Batch OCR Queue</h3> <ul> <li><strong>Batch Button (<kbd>Ctrl + Shift + Enter</kbd>)</strong>: Located directly in the <em>Corpus Queue</em> pane header, clicking <strong>Batch</strong> processes all <code>Pending / Unprocessed</code> folios in the queue sequentially. A live progress banner displays the current folio index, filename, progress bar, and a safe <strong>Stop</strong> button that halts cleanly after the active page finishes.</li> <li><strong>Auto-Transcribe on Upload</strong>: Enable the checkbox inside the Queue intake box to start OCR automatically whenever new images or PDF pages are imported.</li> <li><strong>Local IndexedDB Persistence</strong>: High-resolution manuscript images and extracted transcriptions are stored locally inside your browser's IndexedDB (<code>ChamOCRStudioDB</code>), preserving your queue across page refreshes without re-uploading.</li> </ul>
<h3 id="sec-intake-badges">2.3 Document Status Badges & Queue Controls</h3> <p>Each queued folio displays a strict semantic status badge that distinguishes machine output from human scholarly verification:</p> <div class="help-table-wrap"> <table class="help-table"> <thead> <tr> <th>Status Badge</th> <th>Meaning & Trigger Condition</th> </tr> </thead> <tbody> <tr> <td><span class="status-demo-pill pending">Unprocessed</span></td> <td>Folio has been loaded into the queue and is awaiting transcription.</td> </tr> <tr> <td><span class="status-demo-pill ocr_done">OCR done</span></td> <td>Automatic neural transcription completed with no quality-gate warnings. <strong>Note:</strong> Automatic OCR never marks a document as human-verified.</td> </tr> <tr> <td><span class="status-demo-pill needs_review">Needs review</span></td> <td>Server quality gates or user flagged the folio due to low line confidence (< 60%), uncovered text-like ink (≥ 12%), suspected merged line height, or manual <kbd>W</kbd> flagging.</td> </tr> <tr> <td><span class="status-demo-pill no_text">No text</span></td> <td>Blank or non-text page detected by the ink-density gate, preventing blank-page hallucinations.</td> </tr> <tr> <td><span class="status-demo-pill verified">Verified</span></td> <td>Awarded <strong>exclusively</strong> after a human scholar confirms every single line on the folio (via Verify <kbd>A</kbd>, inline edit, split, merge, or batch high-confidence verification).</td> </tr> </tbody> </table> </div> <p> Use the <strong>Filter Pills</strong> (<code>All</code>, <code>Review</code>, <code>OCR Done</code>, <code>Verified</code>, <code>Pending</code>) and filename search box to isolate pages needing attention, <strong>drag and drop folio cards</strong> to reorder pagination, or hover any card to re-run OCR (<code>▶</code>) or remove it (<code>✕</code>). </p> </section>
<!-- SECTION 3: MODELS & SEGMENTATION --> <section id="sec-models" class="guide-section"> <h2><span class="sec-badge">03</span> Neural Recognition Models & Segmentation Engine</h2>
<h3 id="sec-models-catalog">3.1 Choosing the Right Recognition Model</h3> <div class="help-table-wrap"> <table class="help-table"> <thead> <tr> <th>Model Selector</th> <th>Input Geometry</th> <th>Recommended Paleographic Use Case</th> </tr> </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> <td><code>[3, 48, 320]</code></td> <td>Compact W=320 specialist tuned for heavily degraded Level-5 archival crops and tight symbol gate closure.</td> </tr> <tr> <td><strong>V24.1-R2.1.6</strong></td> <td><code>[3, 48, 320]</code></td> <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> </div>
<h3 id="sec-models-seg">3.2 Segmentation Pipeline Parameters (<kbd>⚙</kbd> Popover)</h3> <p>Click the gear icon (<kbd>⚙</kbd>) beside the Model dropdown to configure line detection and reading order:</p> <ul> <li><strong>Hybrid Cham-DBNet (Polygon Ribbon)</strong> <em>(Recommended)</em>: Uses a Legacy-First quality gate paired with fine-tuned <code>Cham-DBNet v1_poly_u1.8</code> polygon contours that trace undulating baselines, rectify curved ribbons into straight horizontal strips, and mask out intruding ascenders/descenders from neighboring lines.</li> <li><strong>Indic Valley-Cut Projection / Adaptive Profile</strong>: Horizontal ink-projection fallbacks with Connected Component exclusion (<code>difference_update</code>) and a <code>0.40 × median_line_height</code> vertical diacritic cushion. Adjustable via the <strong>Minimum Interlinear Gap (px)</strong> slider.</li> <li><strong>Multi-Column Reading Order</strong>: <code>Automatic Column Detection</code> identifies dual-column folios (and full-width titles above columns) automatically; switch to <code>Strict Top-to-Bottom Rows</code> when transcribing single-column tables or fragmented scraps.</li> </ul> </section>
<!-- SECTION 4: MANUSCRIPT CANVAS & HUD --> <section id="sec-canvas" class="guide-section"> <h2><span class="sec-badge">04</span> Paleographic Manuscript Canvas & Optical HUD</h2>
<h3 id="sec-canvas-nav">4.1 Full-Bleed Canvas & Floating Glass Pill HUD</h3> <ul> <li><strong>Floating Glass Pill HUD</strong>: Instead of stacking a second top toolbar over the manuscript, viewport controls float inside a translucent warm-parchment capsule centered at the bottom of the canvas so historical scans extend edge-to-edge right beneath the main header.</li> <li><strong>Pan & Cursor-Centered Zoom</strong>: Drag anywhere on the canvas to pan; scroll the mouse wheel to zoom smoothly toward the cursor position (<code>8%</code> to <code>1000%</code>).</li> <li><strong>Quick Zoom Presets</strong>: Use HUD buttons for <strong>Fit Folio in Viewport</strong>, <strong>Fit Folio Width</strong>, <strong>1:1 Actual Pixel Size</strong>, Zoom Out (<code>−</code>), and Zoom In (<code>+</code>).</li> <li><strong>Rotate 90° Clockwise (<code>↻</code>)</strong>: Permanently rotates sideways camera scans by 90° clockwise and updates the thumbnail so subsequent OCR runs on upright textlines.</li> </ul>
<h3 id="sec-canvas-boxes">4.2 Spotlight Bounding Boxes, Polygons & Manual Region Annotation</h3> <ul> <li><strong>Spotlight Bounding Box Mode (<kbd>B</kbd>)</strong> <em>(Default)</em>: Eliminates visual "grid clutter" over delicate Cham vowel ascenders (<span class="cham-inline">◌ꨪ</span>, <span class="cham-inline">◌ꨫ</span>) and subjoined medials (<span class="cham-inline">◌ꨳ</span>, <span class="cham-inline">◌ꨶ</span>) by rendering subtle <code>1.5px</code> baseline rules on unselected lines (dashed amber for <code>Needs review</code>, sage for <code>Verified</code>) while illuminating full core-band boxes only on the hovered or active line. Press <kbd>B</kbd> (or click <strong>Spotlight</strong> in the HUD) to cycle <code>Spotlight → All Boxes → Hidden</code>.</li> <li><strong>Interactive Corner Resize Handles</strong>: Selecting any line reveals four corner handles (<code>NW</code>, <code>NE</code>, <code>SW</code>, <code>SE</code>) on its bounding box. Drag any corner to refine crop boundaries, then press <kbd>R</kbd> (<strong>Re-OCR</strong>) to re-transcribe the adjusted region.</li> <li><strong>Curved Polygon Ribbons (<kbd>P</kbd>)</strong>: Toggles the SVG polygonal contour layer generated by <code>Cham-DBNet</code> on wavy or warped folios.</li> <li><strong>Draw Manual Bounding Box (<kbd>D</kbd>)</strong>: Activates crosshair annotation mode—drag across any missed marginal note, stanza number, or interlinear gloss to crop, transcribe via <code>/ocr_crop</code>, and insert it at the exact vertical reading position.</li> </ul>
<h3 id="sec-canvas-optics">4.3 Paleographic Magnifier Loupe & Optical Filters</h3> <div class="feature-grid-2"> <div class="feature-card"> <div class="feature-card-head"> <span class="feature-card-title">2.6× Magnifier Loupe</span> <kbd>L</kbd> </div> <div class="feature-card-body"> Opens a circular 2.6× optical lens tracking your cursor across the folio—ideal for inspecting eroded vowel strokes, distinguishing <span class="cham-inline">◌ꨲ</span> (Vowel UE) from <span class="cham-inline">◌ꨶ</span> (Medial WA), or checking double dandas (<span class="cham-inline">꩝꩝</span> vs <span class="cham-inline">꩞</span>). </div> </div> <div class="feature-card"> <div class="feature-card-head"> <span class="feature-card-title">Non-Destructive Optical Filters</span> <span>◐ Icon</span> </div> <div class="feature-card-body"> Adjust <strong>Contrast</strong> (<code>60%–240%</code>), <strong>Brightness</strong> (<code>50%–180%</code>), <strong>Monochrome Desaturation</strong>, or toggle <strong>Invert Dark/Rubbing Ink</strong> to read low-contrast palm leaves, faded ink, and white-on-black stone inscription rubbings without altering the underlying file. </div> </div> </div> </section>
<!-- SECTION 5: TRANSCRIPTION EDITOR & LINGUISTICS --> <section id="sec-editor" class="guide-section"> <h2><span class="sec-badge">05</span> Scholarly Transcription Editor & Linguistic Tools</h2>
<h3 id="sec-editor-modes">5.1 Diplomatic Lines vs. Continuous Stanza Flow</h3> <ul> <li><strong>Lines (Diplomatic Edition)</strong>: Displays every detected textline in exact folio lineation with a color-coded confidence bar (Green <code>≥ 75%</code>, Amber <code>45%–74%</code>, Red <code>< 45%</code>). Clicking any line highlights its box on the canvas; clicking an individual Cham grapheme zooms the canvas to <code>175%</code> and highlights that specific character cluster proportionally.</li> <li><strong>Stanza Flow (<kbd>Alt + P</kbd>)</strong>: Invokes the linguistic & geometric reconstruction engine (<code>paragraph_flow.py</code>) to distinguish soft line wraps from hard stanza/paragraph breaks (using Danda/Double Danda terminators <span class="cham-inline">꩝</span> / <span class="cham-inline">꩞</span>, stanza numerals <span class="cham-inline">꩑꩞</span>, indentation, and interlinear gap ratios). Click any sentence segment to highlight its source line on the folio, or double-click to edit.</li> </ul>
<h3 id="sec-editor-ling">5.2 Line Crops, Romanized Transliteration & Unicode Cluster Inspector</h3> <div class="feature-grid-3"> <div class="feature-card"> <div class="feature-card-head"> <span class="feature-card-title">Crop: Focus</span> <kbd>Alt + C</kbd> </div> <div class="feature-card-body"> By default, unfolds the high-contrast manuscript cutout strip <strong>exclusively above the active line</strong> you are editing (eliminating left-right eye saccade fatigue without doubling list height). Cycle <code>Focus → All → Off</code> anytime. </div> </div> <div class="feature-card"> <div class="feature-card-head"> <span class="feature-card-title">Aa Roman</span> <kbd>Alt + T</kbd> </div> <div class="feature-card-body"> Generates live scholarly EFEO/Inrasara-style Latin transliteration beneath every Cham line and stanza (e.g., <span class="cham-inline">ꨌꩌ ꨚꨤꨬ</span> → <em>cam palei</em>) to accelerate cross-checking. </div> </div> <div class="feature-card"> <div class="feature-card-head"> <span class="feature-card-title">U+ Cluster Inspector</span> <kbd>Alt + U</kbd> </div> <div class="feature-card-body"> Opens the bottom paleographic inspector decomposing the selected grapheme into exact Unicode codepoints (<code>U+AA00</code>–<code>U+AA5F</code>), categories, canonical <em>Logical Order</em> status, and minimal-pair alerts. </div> </div> </div>
<div class="help-callout tip"> <strong>Canonical Brahmic Logical Order Guarantee</strong> Whenever you edit or save a line, Cham OCR Studio automatically canonicalizes combining marks into strict Unicode Logical Order: <code>Base Consonant → Medials (Ra/La, Ya/Wa) → Pre-Vowels (O/Ai) → Dependent Vowels → Lengthener AA → Final Signs</code>, preventing visual-order encoding corruption. </div>
<h3 id="sec-editor-actions">5.3 Typewriter Editing Flow, Inline Line Actions, Search & History</h3> <ul> <li><strong>Typewriter Inline Edit (<kbd>Enter</kbd> / <kbd>Shift+Enter</kbd> / <kbd>Ctrl+Enter</kbd>)</strong>: Double-click or press <kbd>Enter</kbd> on a selected line to open persistent Unicode Cham editing. While editing, press <kbd>Enter</kbd> to save and <strong>advance directly into editing the next line</strong> while gently centering the canvas (<kbd>Shift+Enter</kbd> steps up to the previous line; <kbd>Ctrl+Enter</kbd> or <strong>Save</strong> commits and exits edit mode).</li> <li><strong>Contextual Inline Action Bar</strong>: Selecting any line reveals <code>Edit</code>, <code>✓ Verify</code>, <code>↻ Re-OCR</code>, <code>Split</code>, <code>Merge ↓</code>, <code>Flag</code>, <code>U+</code>, and <code>🗑</code> directly inside that line card—eliminating eye travel to the bottom of the screen.</li> <li><strong>Verify (<kbd>A</kbd>) & Batch Verify (≥75%)</strong>: Marks the selected line as 100% human-verified and advances automatically to the next line, or approves all high-confidence lines (≥ 75%) in one click.</li> <li><strong>Split (<kbd>S</kbd>)</strong>: When inline edit mode is open, splits the line at your <strong>exact text cursor (caret) position</strong>; otherwise splits cleanly near the midpoint word/danda boundary while dividing the bounding box vertically.</li> <li><strong>Merge Down (<kbd>M</kbd>)</strong>: Concatenates the selected line with the line immediately below and unifies their bounding boxes.</li> <li><strong>Re-OCR (<kbd>R</kbd>), Flag (<kbd>W</kbd>), Delete (<kbd>Del</kbd>)</strong>: Re-runs recognition on the line's box, flags an ambiguous line for review, or removes false-positive noise detections.</li> <li><strong>Review Navigation (<kbd>[</kbd> and <kbd>]</kbd>)</strong>: Jumps directly to the previous or next unverified low-confidence / flagged line and centers the manuscript viewport on it.</li> <li><strong>Find & Replace (<kbd>Ctrl + F</kbd>) & Undo / Redo (<kbd>Ctrl + Z</kbd> / <kbd>Ctrl + Y</kbd>)</strong>: Full 40-step per-folio undo/redo stack covering edits, splits, merges, box adjustments, and batch replacements.</li> </ul> </section>
<!-- SECTION 6: VIRTUAL KEYBOARD --> <section id="sec-keyboard" class="guide-section"> <h2><span class="sec-badge">06</span> Akhar Thrah Virtual Keyboard (<kbd>Alt + K</kbd>)</h2> <p> Because standard operating systems rarely ship ergonomic Eastern Cham keymaps, Cham OCR Studio includes a floating, draggable paleographic keyboard covering the entire Unicode Cham block (<code>U+AA00</code>–<code>U+AA5F</code>), triggered via the <strong>KB</strong> button in the Transcription Editor toolbar or <kbd>Alt + K</kbd>: </p> <ul> <li><strong>Direct Non-Blur Typing</strong>: Open an inline line edit (<kbd>Enter</kbd>) and click keys on the Virtual Keyboard—characters insert directly at your cursor position without stealing input focus.</li> <li><strong>Three Ergonomic Grid Layouts</strong>: Choose <code>5-Row Compact</code> (17–19 keys/row), <code>6-Row Balanced</code> (14 keys/row), or <code>9-Row Canonical</code> (traditional articulatory varga grouping).</li> <li><strong>Phonetic Legends & Glyph Scaling</strong>: Switch key sub-labels between <code>Traditional</code> Cham romanization, <code>Sanskrit</code> indological equivalents, or <code>Glyph Only</code>, and scale keycap glyphs from <code>16px</code> to <code>22px</code>.</li> <li><strong>Scratchpad & Logical Order Normalizer</strong>: Compose text independently in the scratchpad bar, click <strong>Normalize</strong> to enforce canonical cluster order, <strong>Copy</strong> to clipboard, or click <strong>Insert ↵</strong> to append into the active transcription line. Drag the <code>⋮⋮</code> title bar anywhere on screen, or click <code>⟲</code> to re-dock to the bottom-right corner.</li> </ul> </section>
<!-- SECTION 7: EXPORT --> <section id="sec-export" class="guide-section"> <h2><span class="sec-badge">07</span> Multi-Format Corpus & Active Learning Export (<kbd>Ctrl + E</kbd>)</h2> <p> Click <strong>Export</strong> in the top header to export either the <strong>Active Manuscript Folio Only</strong> or the <strong>Entire Transcribed Corpus Queue (Multi-Page)</strong>: </p> <div class="feature-grid-2"> <div class="feature-card"> <div class="feature-card-title">📋 Copy Plaintext & 📄 Unicode TXT (<code>.txt</code>)</div> <div class="feature-card-body">Clean UTF-8 diplomatic line transcriptions normalized in canonical Brahmic Logical Order, separated by folio headers in multi-page mode.</div> </div> <div class="feature-card"> <div class="feature-card-title">📑 Scholarly Markdown Report (<code>.md</code>)</div> <div class="feature-card-body">Publication-ready document bundling folio status, numbered Cham textlines, confidence percentages, and italic Romanized transliterations.</div> </div> <div class="feature-card"> <div class="feature-card-title">🗂 Structured JSON (<code>.json</code>)</div> <div class="feature-card-body">Preserves exact bounding boxes, polygon vertices, confidences, and verification flags; 100% compatible with <code>scripts/ingest_studio_to_realscan_gold.py</code>.</div> </div> <div class="feature-card"> <div class="feature-card-title">🏛 Archival PAGE-XML (<code>.xml</code>)</div> <div class="feature-card-body">PRImA 2019 XML schema encoding polygonal <code><Coords></code> and <code><Unicode></code> text equivalents for interoperability with Transkribus and eScriptorium.</div> </div> </div> <div class="help-callout"> <strong>⚡ Active Learning Dataset Package (<code>.zip</code>)</strong> Select <strong>Active Learning Dataset (.zip)</strong> to generate a self-contained training archive on the server containing cropped line images (<code>crops/*.png</code>), tab-delimited PaddleOCR training pairs (<code>train_list.txt</code>), active-learning metadata (<code>corrections.jsonl</code>), <code>corpus_manifest.json</code>, and per-folio plaintext/Markdown transcriptions. </div> </section>
<!-- SECTION 8: MASTER SHORTCUTS --> <section id="sec-shortcuts" class="guide-section"> <h2><span class="sec-badge">08</span> Master Keyboard Shortcuts Reference</h2> <p>Type in the sidebar search box (<kbd>/</kbd>) to filter this shortcut table instantaneously:</p> <div class="help-table-wrap"> <table class="help-table" id="shortcuts-table"> <thead> <tr> <th>Shortcut</th> <th>Scope</th> <th>Action</th> </tr> </thead> <tbody> <tr><td><kbd>Ctrl + K</kbd> / <kbd>⌘K</kbd></td><td>Global</td><td>Open / close the fuzzy-search Command Palette</td></tr> <tr><td><kbd>Ctrl + O</kbd></td><td>Global</td><td>Open file picker to upload multiple images or a multi-page PDF</td></tr> <tr><td><kbd>Ctrl + V</kbd></td><td>Global</td><td>Paste manuscript image directly from system clipboard</td></tr> <tr><td><kbd>Ctrl + Enter</kbd></td><td>Global</td><td>Execute OCR transcription on the active manuscript folio</td></tr> <tr><td><kbd>Ctrl + Shift + Enter</kbd></td><td>Global</td><td>Start automated Batch OCR across all unprocessed folios in queue</td></tr> <tr><td><kbd>Ctrl + E</kbd></td><td>Global</td><td>Open the Multi-Format & ZIP Corpus Export modal</td></tr> <tr><td><kbd>Alt + 1</kbd> .. <kbd>Alt + 4</kbd></td><td>Layout</td><td>Switch between 3-Pane, Compare, Stacked, and Reader modes</td></tr> <tr><td><kbd>Alt + Q</kbd></td><td>Layout</td><td>Toggle the collapsible Corpus Queue drawer</td></tr> <tr><td><kbd>Alt + C</kbd></td><td>Editor</td><td>Cycle synced line cutout mode (<code>Focus → All → Off</code>)</td></tr> <tr><td><kbd>Alt + K</kbd></td><td>Keyboard</td><td>Toggle the floating Akhar Thrah Virtual Keyboard</td></tr> <tr><td><kbd>Alt + P</kbd></td><td>Editor</td><td>Toggle Diplomatic Lines ↔ Continuous Stanza / Paragraph Flow</td></tr> <tr><td><kbd>Alt + T</kbd></td><td>Editor</td><td>Toggle live Romanized transliteration subtitles (<code>Aa Roman</code>)</td></tr> <tr><td><kbd>Alt + U</kbd></td><td>Editor</td><td>Toggle the Unicode Paleographic Cluster Inspector drawer (<code>U+ Cluster</code>)</td></tr> <tr><td><kbd>Ctrl + F</kbd></td><td>Editor</td><td>Open Find & Replace across the active folio</td></tr> <tr><td><kbd>Ctrl + Z</kbd> / <kbd>Ctrl + Y</kbd></td><td>Editor</td><td>Undo / Redo editorial changes (40-step history stack)</td></tr> <tr><td><kbd>↑</kbd> / <kbd>↓</kbd></td><td>Editor</td><td>Select previous / next textline</td></tr> <tr><td><kbd>Enter</kbd></td><td>Editor</td><td>Open inline edit for selected line (or commit active edit)</td></tr> <tr><td><kbd>A</kbd></td><td>Review</td><td>Verify selected line (100% human-verified) and advance to next line</td></tr> <tr><td><kbd>W</kbd></td><td>Review</td><td>Flag selected line as <code>Needs review</code></td></tr> <tr><td><kbd>S</kbd></td><td>Review</td><td>Split selected line (at caret position when editing, or midpoint)</td></tr> <tr><td><kbd>M</kbd></td><td>Review</td><td>Merge selected line with the succeeding line below</td></tr> <tr><td><kbd>R</kbd></td><td>Review</td><td>Re-run neural OCR on the selected line's bounding box</td></tr> <tr><td><kbd>Delete</kbd> / <kbd>Backspace</kbd></td><td>Review</td><td>Delete selected textline (when not typing inside an input)</td></tr> <tr><td><kbd>[</kbd> / <kbd>]</kbd></td><td>Review</td><td>Jump to previous / next flagged or low-confidence textline</td></tr> <tr><td><kbd>B</kbd></td><td>Canvas</td><td>Cycle Bounding Box overlay (<code>Spotlight → All Boxes → Hidden</code>)</td></tr> <tr><td><kbd>D</kbd></td><td>Canvas</td><td>Toggle manual Draw Bounding Box mode</td></tr> <tr><td><kbd>P</kbd></td><td>Canvas</td><td>Toggle curved Cham-DBNet Polygon Ribbon overlay</td></tr> <tr><td><kbd>L</kbd></td><td>Canvas</td><td>Toggle 2.6× Paleographic Magnifier Loupe</td></tr> <tr><td><kbd>Esc</kbd></td><td>Global</td><td>Cancel inline edit, exit Draw/Loupe mode, or close open modal/keyboard</td></tr> </tbody> </table> </div> </section>
<!-- SECTION 9: FAQ & TROUBLESHOOTING --> <section id="sec-faq" class="guide-section"> <h2><span class="sec-badge">09</span> Paleographic Best Practices & Troubleshooting FAQ</h2>
<div class="faq-list"> <details class="faq-item" open> <summary>My palm-leaf or stone rubbing scan is sideways, dark, or white-ink-on-black. How should I prepare it?</summary> <div class="faq-answer"> First, if the folio is rotated 90°/270°, click the <strong>Rotate 90° Clockwise</strong> button in the canvas toolbar until textlines run horizontally—rotation updates the actual image sent to the OCR engine. For visual proofreading of dark palm leaves or white-on-black stone rubbings, open <strong>Optical Filters (◐)</strong> and enable <em>Invert Dark/Rubbing Ink</em> or boost <em>Contrast</em> to <code>150%–190%</code>. </div> </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>
<details class="faq-item"> <summary>A line was missed or its bounding box clipped a character at the margin. How do I fix it without re-running the whole page?</summary> <div class="faq-answer"> If an existing line's box is slightly too narrow, click the line to reveal its 4 corner resize handles, drag the corner outward to cover the clipped glyph, and press <kbd>R</kbd> (<strong>Re-OCR</strong>). If a line was missed altogether, press <kbd>D</kbd> (<strong>Draw Manual Bounding Box</strong>) and drag a rectangle over the missed textline—the Studio crops, transcribes, and inserts it into the exact vertical reading position automatically. </div> </details>
<details class="faq-item"> <summary>Why does my folio say "OCR done" instead of "Verified" even when all confidences are high?</summary> <div class="faq-answer"> To uphold archival ground-truth integrity, automatic neural predictions are <strong>never</strong> marked <code>Verified</code> on their own. Once you review the folio—or click <strong>Verify ≥75%</strong> and manually verify any remaining lines with <kbd>A</kbd>—the folio badge transitions to green <code>Verified</code>. </div> </details> </div> </section>
<!-- Footer --> <footer class="help-footer"> <div>Cham OCR Studio · Open-Source Digital Paleography (<a href="https://ocr.cham.asia" style="color:var(--accent);font-weight:600;text-decoration:none;">https://ocr.cham.asia</a>)</div> <div> <a href="/" style="color:var(--accent);font-weight:600;text-decoration:none;">Workbench</a> · <a href="/research" style="color:var(--accent);font-weight:600;text-decoration:none;">Technical Report</a> · <a href="https://github.com/phucsd/Cham-OCR" target="_blank" rel="noopener noreferrer" style="color:var(--accent);font-weight:600;text-decoration:none;">GitHub</a> </div> </footer>
</main> </div>
<script src="/static/js/help.js"></script></body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763/* ========================================================================== Cham OCR Studio — Comprehensive User Guide & Feature Manual (/help) Design System: Claude-inspired Warm Light Theme (DESIGN.md) ========================================================================== */
:root { --bg-app: #FAF7F2; --bg-canvas: #F7F1EA; --bg-panel: #FFFCF7; --bg-panel-soft: #FBF5EE; --bg-elevated: #FFFFFF;
--text-primary: #2B2118; --text-secondary: #6F6257; --text-tertiary: #9A8D80;
--border-subtle: #E8DED2; --border-medium: #D8C9BA; --border-strong: #BFAE9D;
--accent: #C96442; --accent-hover: #B55336; --accent-soft: #FFF0E8; --accent-soft-2: #FBE1D4;
--confidence-high: #2F7D5C; --confidence-high-bg: #EAF6EF; --confidence-medium: #B7791F; --confidence-medium-bg: #FFF4D8; --confidence-low: #C4513B; --confidence-low-bg: #FDE8E2;
--font-sans: "Google Sans Flex", "Google Sans", system-ui, -apple-system, sans-serif; --font-cham: "Noto Sans Cham", "Google Sans Flex", sans-serif; --font-mono: "JetBrains Mono", ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
--shadow-xs: 0 1px 2px rgba(43, 33, 24, 0.04); --shadow-sm: 0 2px 8px rgba(43, 33, 24, 0.06); --shadow-md: 0 8px 24px rgba(43, 33, 24, 0.10);
--radius-sm: 8px; --radius-md: 12px; --radius-lg: 18px;}
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0;}
html { scroll-behavior: smooth; scroll-padding-top: 82px;}
section[id], h2[id], h3[id] { scroll-margin-top: 82px;}
body { font-family: var(--font-sans); background-color: var(--bg-app); color: var(--text-primary); font-size: 15px; line-height: 1.68; -webkit-font-smoothing: antialiased;}
/* Reading Progress Bar */.help-progress-track { position: fixed; top: 0; left: 0; right: 0; height: 3px; z-index: 200;}
.help-progress-bar { height: 100%; width: 0%; background: var(--accent); transition: width 0.08s linear;}
/* Sticky Top Navigation Bar */.help-navbar { position: sticky; top: 0; z-index: 120; height: 56px; background: rgba(255, 252, 247, 0.94); backdrop-filter: blur(10px); border-bottom: 1px solid var(--border-subtle); padding: 0 24px; display: flex; align-items: center; justify-content: space-between; gap: 12px; box-shadow: var(--shadow-xs);}
.help-brand { display: inline-flex; align-items: center; gap: 10px; text-decoration: none; color: var(--text-primary);}
.help-emblem { width: 30px; height: 30px; border-radius: var(--radius-sm); background: var(--accent-soft); border: 1px solid var(--accent-soft-2); color: var(--accent); font-family: var(--font-cham); font-size: 16px; font-weight: 700; display: inline-flex; align-items: center; justify-content: center;}
.help-brand-titles { display: flex; flex-direction: column; line-height: 1.15;}
.help-brand-main { font-size: 15px; font-weight: 700; letter-spacing: -0.2px;}
.help-brand-sub { font-size: 11px; color: var(--text-tertiary); font-weight: 500;}
.help-nav-actions { display: flex; align-items: center; gap: 8px;}
.help-btn { display: inline-flex; align-items: center; gap: 6px; height: 34px; padding: 0 12px; border-radius: var(--radius-sm); border: 1px solid var(--border-medium); background: var(--bg-panel); color: var(--text-primary); font-family: inherit; font-size: 12.5px; font-weight: 600; text-decoration: none; cursor: pointer; box-shadow: var(--shadow-xs); transition: all 0.14s ease;}
.help-btn:hover { background: var(--accent-soft); border-color: var(--border-strong); color: var(--accent);}
.help-btn-primary { background: var(--accent); border-color: var(--accent); color: #FFFFFF;}
.help-btn-primary:hover { background: var(--accent-hover); border-color: var(--accent-hover); color: #FFFFFF;}
.mobile-menu-btn { display: none;}
/* Main 2-Column Documentation Layout */.help-layout { max-width: 1320px; margin: 0 auto; padding: 32px 24px 84px; display: grid; grid-template-columns: 280px minmax(0, 1fr); gap: 36px; align-items: start;}
/* Sticky Left Sidebar Navigation */.help-sidebar { position: sticky; top: 76px; max-height: calc(100vh - 96px); overflow-y: auto; background: var(--bg-panel); border: 1px solid var(--border-subtle); border-radius: var(--radius-md); padding: 16px; box-shadow: var(--shadow-xs);}
.sidebar-label { font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.7px; color: var(--text-tertiary); margin-bottom: 10px; padding-bottom: 8px; border-bottom: 1px solid var(--border-subtle);}
.help-search-box { position: relative; margin-bottom: 12px;}
.help-search-input { width: 100%; height: 32px; padding: 0 10px; border-radius: 7px; border: 1px solid var(--border-medium); background: var(--bg-app); font-family: inherit; font-size: 12.5px; color: var(--text-primary); outline: none;}
.help-search-input:focus { border-color: var(--accent); background: var(--bg-elevated);}
.toc-nav-list { list-style: none; display: flex; flex-direction: column; gap: 3px;}
.toc-nav-link { display: block; padding: 6px 9px; border-radius: 6px; font-size: 12.5px; font-weight: 500; color: var(--text-secondary); text-decoration: none; line-height: 1.38; transition: all 0.14s ease;}
.toc-nav-link:hover { background: var(--bg-canvas); color: var(--accent);}
.toc-nav-link.active { background: var(--accent-soft); color: var(--accent); font-weight: 700;}
.toc-sub-list { list-style: none; margin: 2px 0 4px 8px; padding-left: 10px; border-left: 1px solid var(--border-subtle); display: flex; flex-direction: column; gap: 2px;}
.toc-sub-link { display: block; padding: 4px 8px; border-radius: 5px; font-size: 11.5px; color: var(--text-tertiary); text-decoration: none; transition: all 0.14s ease;}
.toc-sub-link:hover,.toc-sub-link.active { color: var(--accent); background: var(--accent-soft); font-weight: 600;}
/* Main Guide Content Card */.help-content { background: var(--bg-panel); border: 1px solid var(--border-subtle); border-radius: var(--radius-lg); padding: 44px 52px; box-shadow: var(--shadow-sm); min-width: 0;}
/* Hero Banner */.help-hero { padding-bottom: 28px; margin-bottom: 32px; border-bottom: 1.5px solid var(--border-subtle);}
.hero-eyebrow { display: inline-flex; align-items: center; gap: 6px; padding: 3px 10px; border-radius: 999px; background: var(--accent-soft); border: 1px solid var(--accent-soft-2); color: var(--accent); font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 12px;}
.help-hero h1 { font-size: 29px; font-weight: 700; letter-spacing: -0.4px; line-height: 1.25; margin-bottom: 12px; color: var(--text-primary);}
.help-hero p { font-size: 15.5px; color: var(--text-secondary); max-width: 780px; margin-bottom: 22px;}
/* 4-Step Quick-Start Pipeline Strip */.quickstart-grid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 12px;}
.step-card { background: var(--bg-panel-soft); border: 1px solid var(--border-subtle); border-radius: var(--radius-md); padding: 14px; display: flex; flex-direction: column; gap: 6px;}
.step-num { display: inline-flex; align-items: center; justify-content: center; width: 24px; height: 24px; border-radius: 6px; background: var(--accent); color: #FFFFFF; font-family: var(--font-mono); font-size: 12px; font-weight: 700;}
.step-title { font-size: 13.5px; font-weight: 700; color: var(--text-primary);}
.step-desc { font-size: 12px; color: var(--text-secondary); line-height: 1.48;}
/* Guide Sections & Typography */.guide-section { margin-bottom: 44px;}
.guide-section h2 { font-size: 21px; font-weight: 700; color: var(--text-primary); letter-spacing: -0.25px; padding-bottom: 8px; margin-bottom: 16px; border-bottom: 1.5px solid var(--border-subtle); display: flex; align-items: center; gap: 9px;}
.sec-badge { font-family: var(--font-mono); font-size: 11.5px; font-weight: 700; padding: 2px 7px; border-radius: 5px; background: var(--accent-soft); color: var(--accent); border: 1px solid var(--accent-soft-2);}
.guide-section h3 { font-size: 16.5px; font-weight: 700; color: var(--accent); margin: 22px 0 10px;}
.guide-section p { margin-bottom: 12px; color: var(--text-primary);}
.guide-section ul,.guide-section ol { margin: 0 0 16px 22px;}
.guide-section li { margin-bottom: 6px;}
/* Feature Cards Grid */.feature-grid-2 { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 14px; margin: 14px 0 18px;}
.feature-grid-3 { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 12px; margin: 14px 0 18px;}
.feature-card { background: var(--bg-elevated); border: 1px solid var(--border-subtle); border-radius: var(--radius-md); padding: 15px 16px; display: flex; flex-direction: column; gap: 6px;}
.feature-card-head { display: flex; align-items: center; justify-content: space-between; gap: 8px;}
.feature-card-title { font-size: 14px; font-weight: 700; color: var(--text-primary);}
.feature-card-body { font-size: 13px; color: var(--text-secondary); line-height: 1.55;}
/* Keyboard Key & UI Badges */kbd, .kbd { font-family: var(--font-mono); font-size: 11px; font-weight: 600; padding: 2px 6px; border-radius: 5px; background: var(--bg-panel-soft); border: 1px solid var(--border-medium); box-shadow: 0 1px 0 var(--border-medium); color: var(--text-primary); white-space: nowrap;}
code { font-family: var(--font-mono); font-size: 0.88em; padding: 1px 5px; border-radius: 4px; background: var(--bg-app); border: 1px solid var(--border-subtle); color: var(--text-primary);}
.cham-inline { font-family: var(--font-cham); font-size: 1.14em; color: var(--accent); background: var(--bg-app); border: 1px solid var(--border-subtle); border-radius: 4px; padding: 0 6px; display: inline-block; line-height: 1.5;}
/* Canonical Document Status Badges Demo */.status-demo-pill { display: inline-flex; align-items: center; font-size: 11px; font-weight: 700; padding: 2px 8px; border-radius: 999px; white-space: nowrap;}.status-demo-pill.ocr_done { background: var(--accent-soft); color: var(--accent); border: 1px solid var(--accent-soft-2);}.status-demo-pill.needs_review { background: var(--confidence-medium-bg); color: var(--confidence-medium); border: 1px solid rgba(183, 121, 31, 0.3);}.status-demo-pill.verified { background: var(--confidence-high-bg); color: var(--confidence-high); border: 1px solid rgba(47, 125, 92, 0.3);}.status-demo-pill.no_text { background: var(--bg-panel); color: var(--text-tertiary); border: 1px dashed var(--border-medium);}.status-demo-pill.pending { background: var(--bg-panel-soft); color: var(--text-secondary); border: 1px solid var(--border-subtle);}
/* Tables */.help-table-wrap { overflow-x: auto; border: 1px solid var(--border-subtle); border-radius: var(--radius-md); margin: 14px 0 20px; box-shadow: var(--shadow-xs);}
.help-table { width: 100%; border-collapse: collapse; font-size: 13px; background: var(--bg-elevated); text-align: left;}
.help-table th { background: var(--bg-canvas); color: var(--text-primary); font-weight: 700; padding: 10px 14px; border-bottom: 1.5px solid var(--border-medium); white-space: nowrap;}
.help-table td { padding: 9px 14px; border-bottom: 1px solid var(--border-subtle); color: var(--text-primary); vertical-align: top;}
.help-table tr:nth-child(even) td { background: rgba(250, 247, 242, 0.5);}
.help-table tr:hover td { background: var(--accent-soft);}
/* Callout Tip / Caution Boxes */.help-callout { padding: 14px 18px; border-radius: var(--radius-md); border: 1px solid var(--border-subtle); border-left: 4px solid var(--accent); background: var(--accent-soft); margin: 16px 0; font-size: 13.5px;}
.help-callout.tip { border-left-color: var(--confidence-high); background: var(--confidence-high-bg);}
.help-callout.caution { border-left-color: var(--confidence-medium); background: var(--confidence-medium-bg);}
.help-callout strong { display: block; margin-bottom: 3px; color: var(--text-primary);}
/* FAQ Accordion Items */.faq-list { display: flex; flex-direction: column; gap: 10px; margin-top: 12px;}
.faq-item { border: 1px solid var(--border-subtle); border-radius: var(--radius-md); background: var(--bg-elevated); overflow: hidden;}
.faq-item summary { padding: 12px 16px; font-weight: 700; font-size: 14px; cursor: pointer; color: var(--text-primary); list-style: none; display: flex; align-items: center; justify-content: space-between; gap: 10px;}
.faq-item summary::-webkit-details-marker { display: none;}
.faq-item summary::after { content: "+"; font-family: var(--font-mono); font-size: 16px; color: var(--accent);}
.faq-item[open] summary::after { content: "−";}
.faq-item[open] summary { border-bottom: 1px solid var(--border-subtle); background: var(--bg-panel-soft);}
.faq-answer { padding: 12px 16px; font-size: 13.5px; color: var(--text-secondary); line-height: 1.6;}
/* Footer */.help-footer { margin-top: 48px; padding-top: 20px; border-top: 1px solid var(--border-subtle); display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 12px; font-size: 12.5px; color: var(--text-tertiary);}
/* Responsive */@media (max-width: 1040px) { .quickstart-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } .feature-grid-3 { grid-template-columns: repeat(2, minmax(0, 1fr)); } .help-layout { grid-template-columns: 1fr; padding: 20px 16px 60px; } .mobile-menu-btn { display: inline-flex; } .help-sidebar { display: none; position: fixed; top: 64px; left: 16px; right: 16px; z-index: 160; max-height: 74vh; box-shadow: var(--shadow-md); } .help-sidebar.mobile-open { display: block; } .help-content { padding: 26px 20px; }}
@media (max-width: 680px) { .quickstart-grid, .feature-grid-2, .feature-grid-3 { grid-template-columns: 1fr; }}
@media print { .help-progress-track, .help-navbar, .help-sidebar { display: none !important; } .help-layout { grid-template-columns: 1fr; padding: 0; } .help-content { border: none; box-shadow: none; padding: 0; } body { background: #FFFFFF; color: #000000; font-size: 11pt; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789/* ========================================================================== Cham-OCR Technical Report — Synchronized Warm Light Editorial Theme Aligned strictly with DESIGN.md tokens (#FAF7F2, #FFFCF7, #2B2118, #C96442) ========================================================================== */
:root { --bg-page: #FAF7F2; --bg-canvas: #F7F1EA; --bg-surface: #FFFCF7; --bg-surface-elevated: #FBF5EE; --bg-subtle: #F7F1EA; --bg-white: #FFFFFF;
--border-color: #E8DED2; --border-medium: #D8C9BA; --border-strong: #BFAE9D;
--text-primary: #2B2118; --text-secondary: #6F6257; --text-muted: #9A8D80;
--accent-primary: #C96442; --accent-hover: #B55336; --accent-subtle: #FFF0E8; --accent-soft-2: #FBE1D4;
--accent-green: #2F7D5C; --accent-green-bg: #EAF6EF; --accent-amber: #B7791F; --accent-amber-bg: #FFF4D8; --accent-red: #C4513B; --accent-red-bg: #FDE8E2;
--font-sans: "Google Sans Flex", "Google Sans", system-ui, -apple-system, sans-serif; --font-mono: "JetBrains Mono", ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; --font-cham: "Noto Sans Cham", "Google Sans Flex", sans-serif;
--shadow-xs: 0 1px 2px rgba(43, 33, 24, 0.04); --shadow-sm: 0 2px 8px rgba(43, 33, 24, 0.06); --shadow-md: 0 6px 20px rgba(43, 33, 24, 0.09);
--radius-sm: 8px; --radius-md: 12px; --radius-lg: 18px;}
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0;}
html { scroll-behavior: smooth; scroll-padding-top: 84px;}
section[id], h2[id], h3[id], [id] { scroll-margin-top: 84px;}
body { font-family: var(--font-sans); background-color: var(--bg-page); color: var(--text-primary); line-height: 1.74; font-size: 15.5px; -webkit-font-smoothing: antialiased;}
/* Top Reading Progress Bar */.reading-progress-track { position: fixed; top: 0; left: 0; right: 0; height: 3px; background: transparent; z-index: 200;}
.reading-progress-bar { height: 100%; width: 0%; background: var(--accent-primary); transition: width 0.08s linear;}
/* Unified Top Navigation Bar */.top-navbar { position: sticky; top: 0; z-index: 120; height: 56px; background: rgba(255, 252, 247, 0.94); backdrop-filter: blur(10px); border-bottom: 1px solid var(--border-color); padding: 0 24px; display: flex; justify-content: space-between; align-items: center; gap: 12px; box-shadow: var(--shadow-xs);}
.nav-brand { display: inline-flex; align-items: center; gap: 10px; text-decoration: none; color: var(--text-primary);}
.nav-emblem { width: 30px; height: 30px; border-radius: var(--radius-sm); background: var(--accent-subtle); border: 1px solid var(--accent-soft-2); color: var(--accent-primary); font-family: var(--font-cham); font-size: 16px; font-weight: 700; display: inline-flex; align-items: center; justify-content: center;}
.nav-brand-titles { display: flex; flex-direction: column; line-height: 1.15;}
.nav-brand-main { font-size: 15px; font-weight: 700; letter-spacing: -0.2px;}
.nav-brand-sub { font-size: 11px; color: var(--text-muted); font-weight: 500;}
.nav-actions { display: flex; gap: 8px; align-items: center;}
.nav-btn { display: inline-flex; align-items: center; gap: 6px; height: 34px; padding: 0 12px; font-family: inherit; font-size: 12.5px; font-weight: 600; border-radius: var(--radius-sm); text-decoration: none; transition: all 0.14s ease; cursor: pointer; border: 1px solid var(--border-medium); background: var(--bg-surface); color: var(--text-primary); box-shadow: var(--shadow-xs);}
.nav-btn:hover { background: var(--accent-subtle); border-color: var(--border-strong); color: var(--accent-primary);}
.nav-btn-primary { background: var(--accent-primary); border-color: var(--accent-primary); color: #FFFFFF;}
.nav-btn-primary:hover { background: var(--accent-hover); border-color: var(--accent-hover); color: #FFFFFF;}
.mobile-toc-btn { display: none;}
/* Main 2-Column Editorial Container */.page-container { max-width: 1320px; margin: 0 auto; padding: 36px 24px 84px; display: grid; grid-template-columns: 292px minmax(0, 1fr); gap: 40px; align-items: start;}
/* Sticky Table of Contents Sidebar */.sidebar { position: sticky; top: 76px; max-height: calc(100vh - 96px); overflow-y: auto; padding: 16px; background: var(--bg-surface); border: 1px solid var(--border-color); border-radius: var(--radius-md); box-shadow: var(--shadow-xs);}
.toc-header-row { display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; padding-bottom: 8px; border-bottom: 1px solid var(--border-color);}
.toc-title { font-size: 11.5px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.7px; color: var(--text-muted);}
.toc-filter-input { width: 100%; height: 30px; padding: 0 10px; margin-bottom: 10px; border-radius: 6px; border: 1px solid var(--border-color); background: var(--bg-page); font-family: inherit; font-size: 12px; color: var(--text-primary); outline: none;}
.toc-filter-input:focus { border-color: var(--accent-primary);}
.toc-list { list-style: none;}
.toc-item { margin-bottom: 4px;}
.toc-link { display: block; padding: 6px 9px; font-size: 12.5px; font-weight: 500; color: var(--text-secondary); text-decoration: none; border-radius: 6px; transition: all 0.14s ease; line-height: 1.38;}
.toc-link:hover { background: var(--bg-subtle); color: var(--accent-primary);}
.toc-link.active { background: var(--accent-subtle); color: var(--accent-primary); font-weight: 700;}
.toc-sublist { list-style: none; padding-left: 12px; margin-top: 2px; border-left: 1px solid var(--border-color); margin-left: 8px;}
.toc-sublink { display: block; padding: 4px 8px; font-size: 11.5px; color: var(--text-muted); text-decoration: none; border-radius: 5px; transition: all 0.14s ease;}
.toc-sublink:hover,.toc-sublink.active { color: var(--accent-primary); background: var(--accent-subtle); font-weight: 600;}
/* Main Publication Surface */.article-main { background: var(--bg-surface); padding: 48px 56px; border: 1px solid var(--border-color); border-radius: var(--radius-lg); box-shadow: var(--shadow-sm); min-width: 0;}
.paper-tag-strip { display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: 16px;}
.tag-pill { font-size: 11px; font-weight: 700; padding: 3px 10px; border-radius: 999px; text-transform: uppercase; letter-spacing: 0.45px; background: var(--bg-subtle); color: var(--text-secondary); border: 1px solid var(--border-color);}
.tag-pill-accent { background: var(--accent-subtle); color: var(--accent-primary); border-color: var(--accent-soft-2);}
.tag-pill-green { background: var(--accent-green-bg); color: var(--accent-green); border-color: rgba(47, 125, 92, 0.25);}
.tag-pill-blue { background: var(--accent-amber-bg); color: var(--accent-amber); border-color: rgba(183, 121, 31, 0.25);}
.paper-title { font-size: 29px; font-weight: 700; line-height: 1.26; color: var(--text-primary); margin-bottom: 18px; letter-spacing: -0.4px;}
.author-box { padding: 16px 20px; background: var(--bg-page); border: 1px solid var(--border-color); border-radius: var(--radius-md); margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 12px;}
.author-info { display: flex; flex-direction: column; gap: 2px;}
.author-name { font-size: 16px; font-weight: 700; color: var(--text-primary);}
.author-affiliation { font-size: 13px; color: var(--text-secondary);}
.author-meta { display: flex; flex-wrap: wrap; gap: 14px; font-size: 12.5px; color: var(--text-muted);}
/* Key Empirical Benchmark Highlights Grid */.kpi-highlights-grid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 12px; margin-bottom: 28px;}
.kpi-card { background: var(--bg-surface-elevated); border: 1px solid var(--border-color); border-radius: var(--radius-md); padding: 13px 14px; display: flex; flex-direction: column; gap: 3px;}
.kpi-value { font-family: var(--font-mono); font-size: 20px; font-weight: 700; color: var(--accent-primary); line-height: 1.2;}
.kpi-label { font-size: 12px; font-weight: 700; color: var(--text-primary);}
.kpi-sub { font-size: 11px; color: var(--text-secondary); line-height: 1.35;}
/* Abstract Box */.abstract-box { padding: 22px 26px; background: var(--bg-subtle); border-left: 4px solid var(--accent-primary); border-radius: 0 var(--radius-md) var(--radius-md) 0; margin-bottom: 36px;}
.abstract-title { font-size: 12.5px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.8px; color: var(--accent-primary); margin-bottom: 8px;}
.abstract-text { font-size: 14.5px; color: var(--text-primary); line-height: 1.7; text-align: justify;}
.keywords-strip { margin-top: 12px; font-size: 13px; color: var(--text-secondary);}
/* Section Typography */h2 { font-size: 21.5px; font-weight: 700; color: var(--text-primary); margin: 44px 0 16px; padding-bottom: 8px; border-bottom: 1.5px solid var(--border-color); letter-spacing: -0.3px;}
h3 { font-size: 17px; font-weight: 700; color: var(--accent-primary); margin: 28px 0 12px;}
h4 { font-size: 15px; font-weight: 600; color: var(--text-primary); margin: 20px 0 8px;}
p { margin-bottom: 16px; color: var(--text-primary); text-align: justify;}
ul, ol { margin: 0 0 18px 24px; color: var(--text-primary);}
li { margin-bottom: 6px;}
code { font-family: var(--font-mono); font-size: 0.88em; background: var(--bg-page); border: 1px solid var(--border-color); padding: 1px 5px; border-radius: 4px;}
.cham-script { font-family: var(--font-cham); font-size: 1.14em; color: var(--accent-primary); background: var(--bg-page); padding: 1px 6px; border-radius: 4px; border: 1px solid var(--border-color); display: inline-block; line-height: 1.5;}
/* Warm Callouts (No cold neon blues) */.academic-callout { padding: 16px 20px; margin: 20px 0; border-radius: var(--radius-md); border: 1px solid var(--border-color); background: var(--bg-page);}
.callout-title { font-weight: 700; font-size: 13.5px; margin-bottom: 6px; display: flex; align-items: center; gap: 6px;}
.callout-info { background: var(--accent-subtle); border-color: var(--accent-soft-2); color: var(--text-primary);}.callout-info .callout-title { color: var(--accent-primary); }
.callout-warning { background: var(--accent-amber-bg); border-color: rgba(183, 121, 31, 0.3); color: var(--text-primary);}.callout-warning .callout-title { color: var(--accent-amber); }
.callout-success { background: var(--accent-green-bg); border-color: rgba(47, 125, 92, 0.3); color: var(--text-primary);}.callout-success .callout-title { color: var(--accent-green); }
/* Data Tables */.table-responsive { overflow-x: auto; margin: 22px 0; border: 1px solid var(--border-color); border-radius: var(--radius-md); box-shadow: var(--shadow-xs);}
table { width: 100%; border-collapse: collapse; font-size: 13.5px; text-align: left; background: var(--bg-white);}
th { background: var(--bg-subtle); color: var(--text-primary); font-weight: 700; padding: 10px 14px; border-bottom: 2px solid var(--border-medium); white-space: nowrap;}
td { padding: 10px 14px; border-bottom: 1px solid var(--border-color); color: var(--text-primary);}
tr:nth-child(even) td { background: rgba(250, 247, 242, 0.55);}
tr:hover td { background: var(--accent-subtle);}
.num, th.num { font-family: var(--font-mono); font-size: 13px; text-align: right;}
.metric-badge { font-family: var(--font-mono); font-weight: 600; padding: 2px 7px; border-radius: 4px; font-size: 12px;}.metric-good { background: var(--accent-green-bg); color: var(--accent-green); }.metric-warn { background: var(--accent-amber-bg); color: var(--accent-amber); }.metric-bad { background: var(--accent-red-bg); color: var(--accent-red); }
/* Math & Code Blocks */.math-block { margin: 18px 0; padding: 14px 20px; background: var(--bg-page); border: 1px solid var(--border-color); border-radius: var(--radius-md); overflow-x: auto; text-align: center;}
.code-box { font-family: var(--font-mono); font-size: 13px; background: #2B2118; color: #FAF7F2; padding: 16px 20px; border-radius: var(--radius-md); overflow-x: auto; margin: 18px 0; line-height: 1.6; border: 1px solid #443629;}
.code-box pre, .code-box code { margin: 0; font-family: inherit; background: transparent; border: none; padding: 0; color: inherit;}
.code-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; padding-bottom: 6px; border-bottom: 1px solid #443629; font-size: 11px; color: #BFAE9D; text-transform: uppercase; letter-spacing: 0.5px;}
.copy-btn { background: #443629; color: #FAF7F2; border: none; padding: 3px 9px; border-radius: 5px; font-family: var(--font-sans); font-size: 11px; font-weight: 600; cursor: pointer; transition: background 0.14s ease;}
.copy-btn:hover { background: var(--accent-primary); color: #FFFFFF;}
.ref-item { margin-bottom: 12px; padding-left: 28px; text-indent: -28px; font-size: 13.5px; color: var(--text-secondary); line-height: 1.6;}
.ref-item a { color: var(--accent-primary); text-decoration: none; word-break: break-all;}.ref-item a:hover { text-decoration: underline; }
.paper-footer { margin-top: 56px; padding-top: 24px; border-top: 1px solid var(--border-color); display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 14px; font-size: 13px; color: var(--text-muted);}
.paper-toast { position: fixed; bottom: 24px; left: 50%; transform: translateX(-50%); background: var(--text-primary); color: var(--bg-surface); border: 1px solid var(--accent-primary); padding: 8px 18px; border-radius: 999px; font-size: 12.5px; font-weight: 600; box-shadow: var(--shadow-md); z-index: 500;}
@media (max-width: 1024px) { .kpi-highlights-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } .page-container { grid-template-columns: 1fr; gap: 20px; padding: 20px 16px 60px; } .mobile-toc-btn { display: inline-flex; } .sidebar { display: none; position: fixed; top: 64px; left: 16px; right: 16px; z-index: 160; max-height: 72vh; box-shadow: var(--shadow-md); } .sidebar.mobile-open { display: block; } .article-main { padding: 26px 20px; } .paper-title { font-size: 23px; }}
@media print { .reading-progress-track, .top-navbar, .sidebar, .copy-btn { display: none !important; } .page-container { grid-template-columns: 1fr; padding: 0; } .article-main { border: none; box-shadow: none; padding: 0; } body { background: #FFFFFF; color: #000000; font-size: 11.5pt; }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728/* ========================================================================== Cham OCR Studio — Paleographic Transcription & Diagnostic Workbench Design System: Claude-inspired Warm Light Theme (DESIGN.md) ========================================================================== */
:root { /* Core Surface & Text Tokens (DESIGN.md) */ --bg-app: #FAF7F2; --bg-canvas: #F7F1EA; --bg-panel: #FFFCF7; --bg-panel-soft: #FBF5EE; --bg-elevated: #FFFFFF;
--text-primary: #2B2118; --text-secondary: #6F6257; --text-tertiary: #9A8D80;
--border-subtle: #E8DED2; --border-medium: #D8C9BA; --border-strong: #BFAE9D;
--accent: #C96442; --accent-hover: #B55336; --accent-soft: #FFF0E8; --accent-soft-2: #FBE1D4; --accent-glow: rgba(201, 100, 66, 0.16);
--selection-bg: #FFF0E8; --selection-border: #D97757;
/* Semantic Confidence & Verification Tokens */ --confidence-high: #2F7D5C; --confidence-high-bg: #EAF6EF; --confidence-medium: #B7791F; --confidence-medium-bg: #FFF4D8; --confidence-low: #C4513B; --confidence-low-bg: #FDE8E2;
/* Typography */ --font-sans: "Google Sans Flex", "Google Sans", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; --font-cham: "Noto Sans Cham", "Google Sans Flex", sans-serif; --font-mono: "JetBrains Mono", ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
/* Elevation & Radii */ --shadow-xs: 0 1px 2px rgba(43, 33, 24, 0.04); --shadow-sm: 0 2px 6px rgba(43, 33, 24, 0.06); --shadow-md: 0 6px 18px rgba(43, 33, 24, 0.09); --shadow-lg: 0 14px 38px rgba(43, 33, 24, 0.15);
--radius-xs: 5px; --radius-sm: 8px; --radius-md: 12px; --radius-lg: 18px; --radius-xl: 24px;
/* Resizable Pane Dimensions */ --sidebar-width: 288px; --editor-width: 470px; --stacked-viewer-height: 50%;}
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0;}
html, body { height: 100%; overflow: hidden; font-family: var(--font-sans); font-size: 14px; color: var(--text-primary); background-color: var(--bg-app); -webkit-font-smoothing: antialiased;}
body { display: flex; flex-direction: column;}
/* Custom Warm Scrollbars */::-webkit-scrollbar { width: 7px; height: 7px;}::-webkit-scrollbar-track { background: transparent;}::-webkit-scrollbar-thumb { background: var(--border-medium); border-radius: 999px;}::-webkit-scrollbar-thumb:hover { background: var(--border-strong);}
/* ========================================================================== 1. Top Command Header ========================================================================== */
.studio-header { height: 50px; background: var(--bg-panel); border-bottom: 1px solid var(--border-subtle); padding: 0 18px; display: grid; grid-template-columns: 1fr auto 1fr; align-items: center; gap: 16px; flex-shrink: 0; z-index: 90; box-shadow: var(--shadow-xs);}
.header-cluster { display: flex; align-items: center; gap: 8px; flex-shrink: 0;}
.header-cluster-left { justify-self: start; min-width: 0;}
.header-cluster-center { justify-self: center;}
.header-cluster-right { justify-self: end;}
.header-brand { display: inline-flex; align-items: center; gap: 9px; text-decoration: none; color: var(--text-primary); white-space: nowrap;}
.brand-emblem { width: 30px; height: 30px; border-radius: var(--radius-sm); background: var(--accent-soft); border: 1px solid var(--accent-soft-2); color: var(--accent); display: inline-flex; align-items: center; justify-content: center; font-family: var(--font-cham); font-size: 16px; font-weight: 700; line-height: 1; flex-shrink: 0;}
.brand-text-wrap { display: flex; flex-direction: column; line-height: 1.15;}
.brand-title { font-size: 15px; font-weight: 700; letter-spacing: -0.25px;}
.brand-subtitle { font-size: 10.5px; color: var(--text-tertiary); font-weight: 500;}
.header-sep { width: 1px; height: 22px; background: var(--border-subtle); flex-shrink: 0;}
/* Active Folio Breadcrumb Pill */.active-folio-chip { display: inline-flex; align-items: center; gap: 6px; padding: 3px 9px; background: var(--bg-panel-soft); border: 1px solid var(--border-subtle); border-radius: 999px; max-width: 185px; min-width: 0;}
.folio-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--border-strong); flex-shrink: 0;}
.folio-dot.ready { background: var(--confidence-high);}
.folio-dot.review { background: var(--confidence-medium);}
.folio-name { font-size: 11.5px; font-weight: 600; color: var(--text-secondary); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 95px;}
/* Segmented View Mode Switcher */.view-switcher { display: inline-flex; align-items: center; background: var(--bg-panel-soft); border: 1px solid var(--border-subtle); border-radius: var(--radius-sm); padding: 2px; gap: 2px; flex-shrink: 0;}
.view-btn { border: none; background: transparent; color: var(--text-secondary); font-family: inherit; font-size: 11.5px; font-weight: 600; padding: 4px 8px; border-radius: 6px; cursor: pointer; display: inline-flex; align-items: center; gap: 5px; transition: all 0.14s ease; white-space: nowrap;}
.view-btn:hover { color: var(--text-primary); background: rgba(201, 100, 66, 0.07);}
.view-btn.active { background: var(--bg-elevated); color: var(--accent); box-shadow: var(--shadow-xs);}
/* Compact Model & Engine Control Bar */.engine-bar { display: inline-flex; align-items: center; background: var(--bg-panel-soft); border: 1px solid var(--border-medium); border-radius: var(--radius-sm); height: 32px; padding: 0 3px 0 8px; gap: 5px; flex-shrink: 0;}
.engine-bar:focus-within { border-color: var(--accent); box-shadow: 0 0 0 2px var(--accent-glow);}
.engine-label { font-size: 10px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.4px; color: var(--text-tertiary); white-space: nowrap;}
.model-select { border: none; background: transparent; font-family: inherit; font-size: 12.5px; font-weight: 600; color: var(--text-primary); outline: none; cursor: pointer; width: 152px; height: 28px; line-height: 28px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; padding-right: 4px;}
.engine-gear-btn { width: 25px; height: 25px; border: none; border-left: 1px solid var(--border-subtle); background: transparent; color: var(--text-secondary); cursor: pointer; display: inline-flex; align-items: center; justify-content: center; border-radius: 0 5px 5px 0; flex-shrink: 0;}
.engine-gear-btn:hover,.engine-gear-btn.active { color: var(--accent); background: var(--accent-soft);}
/* Buttons */.btn { height: 32px; padding: 0 9px; border-radius: var(--radius-sm); border: 1px solid var(--border-medium); background: var(--bg-panel); color: var(--text-primary); font-family: inherit; font-size: 12px; font-weight: 600; display: inline-flex; align-items: center; justify-content: center; gap: 5px; cursor: pointer; text-decoration: none; white-space: nowrap; user-select: none; flex-shrink: 0; transition: background 0.14s ease, border-color 0.14s ease, color 0.14s ease, transform 0.08s ease; box-shadow: var(--shadow-xs);}
.btn:hover:not(:disabled) { background: var(--accent-soft); border-color: var(--border-strong); color: var(--text-primary);}
.btn:active:not(:disabled) { transform: translateY(1px);}
.btn:disabled { opacity: 0.5; cursor: not-allowed; box-shadow: none;}
.btn.active { background: var(--accent-soft); border-color: var(--accent); color: var(--accent);}
.btn-primary { background: var(--accent); border-color: var(--accent); color: #FFFFFF; box-shadow: 0 2px 6px rgba(201, 100, 66, 0.24);}
.btn-primary:hover:not(:disabled) { background: var(--accent-hover); border-color: var(--accent-hover); color: #FFFFFF;}
.btn-soft-accent { background: var(--accent-soft); border-color: var(--selection-border); color: var(--accent);}
.btn-soft-accent:hover:not(:disabled) { background: var(--accent-soft-2); border-color: var(--accent); color: var(--accent-hover);}
.btn-sm { height: 27px; padding: 0 8px; font-size: 11.5px; border-radius: 6px;}
.btn-xs { height: 23px; padding: 0 6px; font-size: 11px; border-radius: 5px;}
.icon-btn { width: 32px; height: 32px; padding: 0; border-radius: var(--radius-sm); border: 1px solid transparent; background: transparent; color: var(--text-secondary); display: inline-flex; align-items: center; justify-content: center; cursor: pointer; transition: all 0.14s ease; flex-shrink: 0;}
.icon-btn:hover { background: var(--accent-soft); color: var(--accent); border-color: var(--border-subtle);}
.icon-btn.active { background: var(--accent-soft); color: var(--accent); border-color: var(--selection-border);}
/* Command Palette Trigger Pill */.cmdk-trigger { height: 32px; padding: 0 8px; border-radius: var(--radius-sm); border: 1px solid var(--border-subtle); background: var(--bg-panel-soft); color: var(--text-secondary); font-family: inherit; font-size: 12px; font-weight: 500; display: inline-flex; align-items: center; gap: 6px; cursor: pointer; flex-shrink: 0; transition: all 0.15s ease;}
.cmdk-trigger:hover { border-color: var(--border-strong); background: var(--bg-elevated); color: var(--text-primary);}
.kbd-hint { font-family: var(--font-mono); font-size: 10px; font-weight: 600; padding: 1px 5px; border-radius: 4px; background: var(--bg-panel); border: 1px solid var(--border-medium); color: var(--text-tertiary);}
/* Popover / Dropdown Menus */.popover-anchor { position: relative; display: inline-flex;}
.popover-menu { display: none; position: absolute; top: calc(100% + 6px); right: 0; min-width: 245px; background: var(--bg-elevated); border: 1px solid var(--border-medium); border-radius: var(--radius-md); box-shadow: var(--shadow-lg); padding: 6px; z-index: 400;}
.popover-menu.align-left { right: auto; left: 0;}
.popover-menu.popover-upward { top: auto; bottom: calc(100% + 10px); right: 0;}
.popover-menu.open { display: block;}
.popover-section-label { font-size: 10.5px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.6px; color: var(--text-tertiary); padding: 6px 10px 4px;}
.popover-item { width: 100%; border: none; background: transparent; padding: 7px 10px; border-radius: var(--radius-sm); font-family: inherit; font-size: 12.5px; font-weight: 500; color: var(--text-primary); display: flex; align-items: center; justify-content: space-between; gap: 10px; cursor: pointer; text-decoration: none; white-space: nowrap; text-align: left;}
.popover-item-left { display: inline-flex; align-items: center; gap: 8px;}
.popover-item:hover,.popover-item.active { background: var(--accent-soft); color: var(--accent);}
.popover-item.active { font-weight: 700;}
.popover-divider { height: 1px; background: var(--border-subtle); margin: 5px 4px;}
.popover-form-row { padding: 6px 10px; display: flex; flex-direction: column; gap: 4px;}
.popover-form-row label { font-size: 11.5px; font-weight: 600; color: var(--text-secondary); display: flex; justify-content: space-between;}
.popover-select { width: 100%; padding: 5px 8px; border-radius: 6px; border: 1px solid var(--border-medium); background: var(--bg-panel); font-family: inherit; font-size: 12px; color: var(--text-primary);}
/* ========================================================================== 2. Flexible Resizable Multi-Mode Workspace ========================================================================== */
.workspace { flex: 1; min-height: 0; display: flex; overflow: hidden; position: relative; background: var(--bg-app);}
/* Split Pane Resizers */.pane-resizer-v { width: 5px; cursor: col-resize; background: transparent; position: relative; flex-shrink: 0; z-index: 30; transition: background 0.15s ease;}
.pane-resizer-v::after { content: ""; position: absolute; top: 0; bottom: 0; left: 2px; width: 1px; background: var(--border-subtle); transition: background 0.15s ease, width 0.15s ease;}
.pane-resizer-v:hover::after,.pane-resizer-v.dragging::after { left: 1px; width: 3px; background: var(--accent);}
.pane-resizer-h { display: none; height: 6px; cursor: row-resize; background: transparent; position: relative; flex-shrink: 0; z-index: 30;}
.pane-resizer-h::after { content: ""; position: absolute; left: 0; right: 0; top: 2px; height: 1px; background: var(--border-subtle);}
.pane-resizer-h:hover::after,.pane-resizer-h.dragging::after { top: 1px; height: 3px; background: var(--accent);}
/* Main Split Content Wrapper (Viewer + Editor) */.main-split-stage { flex: 1; min-width: 0; min-height: 0; display: flex; flex-direction: row; overflow: hidden;}
/* Layout Mode 1: Workbench (3-Pane Default) */.workspace.layout-workbench .sidebar-pane { width: var(--sidebar-width); display: flex;}.workspace.layout-workbench .viewer-pane { flex: 1; display: flex;}.workspace.layout-workbench .editor-pane { width: var(--editor-width); display: flex;}
/* Layout Mode 2: Side-by-Side (2-Pane Compare) */.workspace.layout-side .sidebar-pane,.workspace.layout-side #resizer-sidebar { display: none;}.workspace.layout-side .viewer-pane { flex: 1; display: flex;}.workspace.layout-side .editor-pane { width: var(--editor-width); display: flex;}
/* Layout Mode 3: Stacked Horizontal-Vertical (Ideal for Wide Palm-Leaf Folios!) */.workspace.layout-stacked .sidebar-pane { width: var(--sidebar-width); display: flex;}.workspace.layout-stacked .main-split-stage { flex-direction: column;}.workspace.layout-stacked #resizer-editor-v { display: none;}.workspace.layout-stacked #resizer-editor-h { display: block;}.workspace.layout-stacked .viewer-pane { height: var(--stacked-viewer-height); flex: none;}.workspace.layout-stacked .editor-pane { width: 100% !important; flex: 1;}
/* Layout Mode 4: Focus Scholarly Reader */.workspace.layout-focus .sidebar-pane,.workspace.layout-focus #resizer-sidebar,.workspace.layout-focus .viewer-pane,.workspace.layout-focus #resizer-editor-v,.workspace.layout-focus #resizer-editor-h { display: none;}.workspace.layout-focus .editor-pane { width: 100% !important; flex: 1; background: var(--bg-app);}.workspace.layout-focus .editor-scroll-body { max-width: 920px; margin: 16px auto; width: calc(100% - 32px); background: var(--bg-panel); border: 1px solid var(--border-subtle); border-radius: var(--radius-lg); box-shadow: var(--shadow-sm); padding: 12px 18px;}
/* Manual & Smart Auto Sidebar Collapse Override */.sidebar-pane.collapsed { display: none !important;}.sidebar-pane.collapsed + .pane-resizer-v { display: none !important;}
/* Zero-Clutter Progressive Disclosure Landing State (0 Folios) */.workspace.is-empty-landing .sidebar-pane,.workspace.is-empty-landing #resizer-sidebar,.workspace.is-empty-landing #resizer-editor-v,.workspace.is-empty-landing #resizer-editor-h,.workspace.is-empty-landing .editor-pane { display: none !important;}.workspace.is-empty-landing .viewer-pane { display: flex !important; flex: 1 !important; width: 100% !important; height: 100% !important;}
/* ========================================================================== 3. Left Pane: Manuscript Corpus Queue & Batch Engine ========================================================================== */
.sidebar-pane { background: var(--bg-panel-soft); display: flex; flex-direction: column; min-width: 220px; max-width: 460px; flex-shrink: 0; overflow: hidden;}
.pane-header { height: 40px; padding: 0 12px; background: var(--bg-panel); border-bottom: 1px solid var(--border-subtle); display: flex; align-items: center; justify-content: space-between; gap: 8px; flex-shrink: 0;}
.pane-title { font-size: 12.5px; font-weight: 700; color: var(--text-primary); display: inline-flex; align-items: center; gap: 6px;}
.count-pill { font-size: 11px; font-weight: 700; padding: 1px 7px; border-radius: 999px; background: var(--accent-soft); color: var(--accent); border: 1px solid var(--accent-soft-2);}
/* Sidebar Intake Dropzone */.intake-box { margin: 10px 10px 8px; padding: 10px; border: 1.5px dashed var(--border-medium); border-radius: var(--radius-md); background: var(--bg-panel); display: flex; flex-direction: column; gap: 7px; transition: all 0.15s ease;}
.intake-box.drag-over { border-color: var(--accent); background: var(--accent-soft);}
.intake-actions { display: flex; gap: 6px;}
.intake-actions .btn { flex: 1;}
.intake-meta-row { display: flex; align-items: center; justify-content: space-between; font-size: 11px; color: var(--text-secondary);}
.toggle-switch-label { display: inline-flex; align-items: center; gap: 6px; cursor: pointer; user-select: none; font-weight: 500;}
.toggle-switch-label input { accent-color: var(--accent); cursor: pointer;}
/* Batch Progress Strip */.batch-progress-card { display: none; margin: 0 10px 8px; padding: 9px 10px; background: var(--accent-soft); border: 1px solid var(--selection-border); border-radius: var(--radius-sm); flex-direction: column; gap: 6px;}
.batch-progress-card.active { display: flex;}
.batch-progress-top { display: flex; align-items: center; justify-content: space-between; gap: 6px; font-size: 11.5px; font-weight: 600; color: var(--text-primary);}
.batch-progress-track { height: 6px; background: var(--bg-elevated); border-radius: 999px; overflow: hidden; border: 1px solid var(--accent-soft-2);}
.batch-progress-fill { height: 100%; width: 0%; background: var(--accent); transition: width 0.25s ease;}
.batch-progress-sub { font-size: 10.5px; color: var(--text-secondary); white-space: nowrap; overflow: hidden; text-overflow: ellipsis;}
/* Queue Search & Filter Bar */.queue-filter-section { padding: 0 10px 8px; border-bottom: 1px solid var(--border-subtle); display: flex; flex-direction: column; gap: 6px;}
.queue-search-input { width: 100%; height: 28px; padding: 0 9px; border-radius: 6px; border: 1px solid var(--border-subtle); background: var(--bg-panel); font-family: inherit; font-size: 12px; color: var(--text-primary); outline: none;}
.queue-search-input:focus { border-color: var(--accent);}
.filter-pills { display: flex; flex-wrap: wrap; gap: 4px;}
.filter-pill { border: 1px solid var(--border-subtle); background: var(--bg-panel); color: var(--text-secondary); font-family: inherit; font-size: 10.5px; font-weight: 600; padding: 2px 7px; border-radius: 999px; cursor: pointer; transition: all 0.12s ease;}
.filter-pill:hover { border-color: var(--border-strong); color: var(--text-primary);}
.filter-pill.active { background: var(--accent); border-color: var(--accent); color: #FFFFFF;}
/* Queue List & Folio Cards */.queue-list { flex: 1; overflow-y: auto; padding: 8px 10px; display: flex; flex-direction: column; gap: 6px;}
.queue-empty { padding: 26px 12px; text-align: center; color: var(--text-tertiary); font-size: 12px; line-height: 1.55;}
.folio-card { display: flex; align-items: center; gap: 9px; padding: 7px 8px; background: var(--bg-panel); border: 1px solid var(--border-subtle); border-radius: var(--radius-sm); cursor: pointer; position: relative; transition: all 0.14s ease;}
.folio-card:hover { border-color: var(--border-strong); background: var(--bg-elevated);}
.folio-card.active { background: var(--selection-bg); border-color: var(--selection-border); box-shadow: var(--shadow-xs);}
.folio-card.drag-target { border-top: 2px solid var(--accent);}
.folio-thumb { width: 44px; height: 44px; border-radius: 6px; background: var(--bg-canvas); border: 1px solid var(--border-subtle); overflow: hidden; display: flex; align-items: center; justify-content: center; flex-shrink: 0; position: relative;}
.folio-thumb img { width: 100%; height: 100%; object-fit: cover;}
.folio-index-tag { position: absolute; bottom: 2px; left: 2px; background: rgba(43, 33, 24, 0.72); color: #FFFCF7; font-size: 9px; font-weight: 700; padding: 0 4px; border-radius: 3px;}
.folio-meta { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 3px;}
.folio-title { font-size: 12px; font-weight: 600; color: var(--text-primary); white-space: nowrap; overflow: hidden; text-overflow: ellipsis;}
.folio-sub { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; font-size: 10.5px; color: var(--text-tertiary);}
/* Canonical Document Status Badges (DESIGN.md) */.doc-badge { display: inline-flex; align-items: center; gap: 4px; font-size: 10px; font-weight: 700; padding: 1px 6px; border-radius: 999px; white-space: nowrap;}
.doc-badge.ocr_done { background: var(--accent-soft); color: var(--accent); border: 1px solid var(--accent-soft-2);}
.doc-badge.needs_review { background: var(--confidence-medium-bg); color: var(--confidence-medium); border: 1px solid rgba(183, 121, 31, 0.28);}
.doc-badge.verified { background: var(--confidence-high-bg); color: var(--confidence-high); border: 1px solid rgba(47, 125, 92, 0.28);}
.doc-badge.no_text { background: var(--bg-panel); color: var(--text-tertiary); border: 1px dashed var(--border-subtle);}
.doc-badge.unprocessed,.doc-badge.processing { background: var(--bg-panel-soft); color: var(--text-secondary); border: 1px solid var(--border-subtle);}
.folio-actions { display: none; align-items: center; gap: 2px;}
.folio-card:hover .folio-actions { display: inline-flex;}
.folio-mini-btn { width: 22px; height: 22px; border: none; border-radius: 4px; background: transparent; color: var(--text-secondary); cursor: pointer; display: inline-flex; align-items: center; justify-content: center; font-size: 12px;}
.folio-mini-btn:hover { background: var(--accent-soft-2); color: var(--accent);}
.folio-mini-btn.danger:hover { background: var(--confidence-low-bg); color: var(--confidence-low);}
/* Corpus Summary Footer */.sidebar-footer { padding: 9px 12px; background: var(--bg-panel); border-top: 1px solid var(--border-subtle); display: flex; flex-direction: column; gap: 5px; flex-shrink: 0;}
.corpus-stats-row { display: flex; justify-content: space-between; font-size: 11px; color: var(--text-secondary);}
.corpus-stats-row strong { color: var(--text-primary);}
.corpus-verified-bar { height: 4px; background: var(--bg-canvas); border-radius: 999px; overflow: hidden;}
.corpus-verified-fill { height: 100%; width: 0%; background: var(--confidence-high); transition: width 0.25s ease;}
/* ========================================================================== 4. Center Pane: Paleographic Document Canvas & Inspection HUD ========================================================================== */
.viewer-pane { background: var(--bg-canvas); display: flex; flex-direction: column; min-width: 260px; min-height: 200px; position: relative; overflow: hidden;}
/* Top-Left Floating Context Pill (Queue Drawer Toggle + Active Folio Status) */.canvas-top-pill { position: absolute; top: 12px; left: 12px; z-index: 32; display: inline-flex; align-items: center; gap: 6px; max-width: calc(100% - 24px); pointer-events: auto;}
.canvas-queue-btn { height: 30px; padding: 0 10px; border-radius: 999px; border: 1px solid var(--border-medium); background: rgba(255, 252, 247, 0.92); backdrop-filter: blur(8px); box-shadow: var(--shadow-sm); color: var(--text-primary); font-family: inherit; font-size: 11.5px; font-weight: 600; display: inline-flex; align-items: center; gap: 6px; cursor: pointer; transition: all 0.14s ease;}
.canvas-queue-btn:hover,.canvas-queue-btn.active { border-color: var(--accent); color: var(--accent); background: var(--bg-elevated);}
.canvas-queue-badge { font-family: var(--font-mono); font-size: 10px; font-weight: 700; padding: 1px 6px; border-radius: 999px; background: var(--accent-soft); color: var(--accent);}
.canvas-top-pill .active-folio-chip { height: 30px; padding: 0 10px; background: rgba(255, 252, 247, 0.92); backdrop-filter: blur(8px); border: 1px solid var(--border-medium); box-shadow: var(--shadow-sm); max-width: 260px;}
.canvas-top-pill .folio-name { max-width: 140px;}
/* Bottom-Center Floating Glass Pill HUD (Figma / Preview Style) */.canvas-floating-hud { position: absolute; bottom: 16px; left: 50%; transform: translateX(-50%); z-index: 35; display: inline-flex; align-items: center; gap: 2px; padding: 4px 10px; background: rgba(255, 252, 247, 0.92); backdrop-filter: blur(10px); border: 1px solid var(--border-medium); border-radius: 999px; box-shadow: var(--shadow-md); opacity: 0.90; transition: opacity 0.16s ease, box-shadow 0.16s ease; max-width: calc(100% - 24px); pointer-events: auto;}
.canvas-floating-hud:hover,.canvas-floating-hud:focus-within { opacity: 1; box-shadow: var(--shadow-lg);}
.hud-pill-btn { height: 28px; min-width: 28px; padding: 0 6px; border: 1px solid transparent; border-radius: 999px; background: transparent; color: var(--text-secondary); font-family: inherit; font-size: 11px; font-weight: 600; display: inline-flex; align-items: center; justify-content: center; gap: 4px; cursor: pointer; transition: all 0.12s ease; white-space: nowrap;}
.hud-pill-btn:hover { color: var(--text-primary); background: var(--bg-panel-soft);}
.hud-pill-btn.active { color: var(--accent); background: var(--accent-soft); border-color: var(--accent-soft-2);}
.hud-pill-label { font-size: 10.5px; font-weight: 600;}
.hud-group { display: inline-flex; align-items: center; gap: 3px;}
.hud-divider { width: 1px; height: 18px; background: var(--border-subtle); margin: 0 4px;}
.zoom-readout { min-width: 46px; text-align: center; font-family: var(--font-mono); font-size: 11px; font-weight: 600; color: var(--text-secondary); padding: 2px 6px; background: var(--bg-panel-soft); border: 1px solid var(--border-subtle); border-radius: 999px;}
.viewer-stage { flex: 1; position: relative; overflow: hidden; cursor: grab; outline: none; background-color: var(--bg-canvas); background-image: radial-gradient(var(--border-medium) 0.75px, transparent 0.75px); background-size: 20px 20px;}
.viewer-stage:active { cursor: grabbing;}
.viewer-stage.draw-mode { cursor: crosshair !important;}
.viewer-transform-layer { position: absolute; top: 0; left: 0; transform-origin: 0 0; will-change: transform;}
.manuscript-img { display: none; max-width: none; user-select: none; -webkit-user-drag: none; box-shadow: var(--shadow-md); border-radius: 2px; transition: filter 0.12s ease;}
/* Curved Polygon SVG Overlay */.polygon-svg-overlay { position: absolute; top: 0; left: 0; pointer-events: none; overflow: visible;}
.polygon-ribbon { fill: rgba(201, 100, 66, 0.08); stroke: rgba(201, 100, 66, 0.55); stroke-width: 1.5; vector-effect: non-scaling-stroke; transition: fill 0.15s ease, stroke 0.15s ease;}
.polygon-ribbon.active { fill: rgba(201, 100, 66, 0.18); stroke: var(--accent); stroke-width: 2.2;}
.polygon-ribbon.verified { fill: rgba(47, 125, 92, 0.10); stroke: rgba(47, 125, 92, 0.65);}
/* Spotlight Dimming for Polygon Ribbons */.polygon-svg-overlay.spotlight-mode .polygon-ribbon:not(.active) { fill: transparent; stroke: rgba(201, 100, 66, 0.18); stroke-width: 1;}
/* Core-Band Bounding Boxes (Preserving AGENTS.md Vertical & Horizontal Rules) */.bbox-layer { position: absolute; top: 0; left: 0; right: 0; bottom: 0; pointer-events: none;}
.bbox-rect { position: absolute; border: 1.5px solid rgba(201, 100, 66, 0.52); background: rgba(201, 100, 66, 0.04); border-radius: 3px; pointer-events: auto; cursor: pointer; transition: background 0.12s ease, border-color 0.12s ease, box-shadow 0.12s ease;}
/* Spotlight Mode: Subtle Baselines at Rest, Full Core-Band Highlight on Hover/Active */.bbox-layer.spotlight-mode .bbox-rect:not(.active):not(:hover) { border-color: transparent; border-bottom: 1.5px solid rgba(201, 100, 66, 0.30); background: transparent; border-radius: 0;}
.bbox-layer.spotlight-mode .bbox-rect.needs-review:not(.active):not(:hover) { border-color: transparent; border-bottom: 2px dashed rgba(183, 121, 31, 0.75); background: rgba(183, 121, 31, 0.03);}
.bbox-layer.spotlight-mode .bbox-rect.verified:not(.active):not(:hover) { border-color: transparent; border-bottom: 1.5px solid rgba(47, 125, 92, 0.36); background: transparent;}
.bbox-rect:hover { background: rgba(201, 100, 66, 0.12) !important; border: 1.5px solid var(--accent) !important; border-radius: 3px !important;}
.bbox-rect.needs-review { border-color: var(--confidence-medium); border-style: dashed; background: rgba(183, 121, 31, 0.08);}
.bbox-rect.verified { border-color: rgba(47, 125, 92, 0.62); background: rgba(47, 125, 92, 0.05);}
.bbox-rect.active { border: 2px solid var(--accent); background: rgba(201, 100, 66, 0.15); box-shadow: 0 0 0 3px rgba(201, 100, 66, 0.16); z-index: 12;}
.bbox-line-tag { position: absolute; top: -17px; left: -1px; background: var(--accent); color: #FFFFFF; font-family: var(--font-mono); font-size: 9.5px; font-weight: 700; padding: 1px 5px; border-radius: 3px 3px 3px 0; pointer-events: none; opacity: 0; white-space: nowrap;}
.bbox-rect:hover .bbox-line-tag,.bbox-rect.active .bbox-line-tag { opacity: 1;}
/* Interactive Resize Handles on Active BBox */.bbox-handle { position: absolute; width: 8px; height: 8px; background: #FFFFFF; border: 2px solid var(--accent); border-radius: 2px; z-index: 15;}.bbox-handle.nw { top: -5px; left: -5px; cursor: nwse-resize; }.bbox-handle.ne { top: -5px; right: -5px; cursor: nesw-resize; }.bbox-handle.sw { bottom: -5px; left: -5px; cursor: nesw-resize; }.bbox-handle.se { bottom: -5px; right: -5px; cursor: nwse-resize; }
/* Estimated Grapheme Cluster Highlight Box */.char-bbox-rect { position: absolute; border: 2px solid var(--confidence-high); background: rgba(47, 125, 92, 0.22); border-radius: 2px; pointer-events: none; z-index: 14;}
/* Drawing Preview Rectangle */.drawing-bbox-rect { position: absolute; border: 2px dashed var(--accent); background: rgba(201, 100, 66, 0.16); pointer-events: none; z-index: 20;}
/* Paleographic Magnifier Loupe */.magnifier-loupe { display: none; position: absolute; width: 176px; height: 176px; border-radius: 50%; border: 3px solid var(--accent); box-shadow: var(--shadow-lg); background-color: var(--bg-panel); background-repeat: no-repeat; pointer-events: none; z-index: 40;}
/* Empty Stage Onboarding & Quick Specimen Cards */.empty-stage-card { position: absolute; inset: 0; padding: 18px; overflow-y: auto; display: flex; flex-direction: column; align-items: center; justify-content: center; text-align: center; gap: 12px; pointer-events: auto;}
.empty-hero-box { max-width: 560px; width: 100%; background: var(--bg-panel); border: 1px solid var(--border-subtle); border-radius: var(--radius-lg); padding: 20px 22px 18px; box-shadow: var(--shadow-sm); display: flex; flex-direction: column; align-items: center; gap: 9px;}
.empty-icon-circle { width: 44px; height: 44px; border-radius: 13px; background: var(--accent-soft); color: var(--accent); border: 1px solid var(--accent-soft-2); display: flex; align-items: center; justify-content: center;}
.empty-hero-title { font-size: 17px; font-weight: 700; color: var(--text-primary);}
.empty-hero-desc { font-size: 13px; color: var(--text-secondary); line-height: 1.55; max-width: 460px;}
.empty-cta-row { display: flex; flex-wrap: wrap; justify-content: center; gap: 8px; margin-top: 4px;}
.quick-samples-strip { width: 100%; margin-top: 8px; padding-top: 14px; border-top: 1px solid var(--border-subtle); display: flex; flex-direction: column; gap: 8px; text-align: left;}
.quick-samples-header { display: flex; justify-content: space-between; align-items: center; font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px; color: var(--text-tertiary);}
.quick-samples-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px;}
.quick-sample-item { border: 1px solid var(--border-subtle); background: var(--bg-panel-soft); border-radius: var(--radius-sm); padding: 7px; cursor: pointer; display: flex; flex-direction: column; gap: 5px; transition: all 0.14s ease; text-align: left;}
.quick-sample-item:hover { border-color: var(--accent); background: var(--accent-soft);}
.quick-sample-thumb { height: 56px; width: 100%; border-radius: 5px; background: var(--bg-canvas); overflow: hidden; border: 1px solid var(--border-subtle);}
.quick-sample-thumb img { width: 100%; height: 100%; object-fit: cover;}
.quick-sample-label { font-size: 11px; font-weight: 600; color: var(--text-primary); line-height: 1.3; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden;}
.quick-sample-cat { font-size: 9.5px; font-weight: 700; color: var(--accent);}
/* OCR Processing Overlay */.ocr-loading-overlay { display: none; position: absolute; inset: 0; background: rgba(250, 247, 242, 0.82); backdrop-filter: blur(4px); flex-direction: column; align-items: center; justify-content: center; gap: 12px; z-index: 50;}
.ocr-spinner { width: 34px; height: 34px; border: 3px solid var(--border-medium); border-top-color: var(--accent); border-radius: 50%; animation: studio-spin 0.8s linear infinite;}
@keyframes studio-spin { to { transform: rotate(360deg); }}
.ocr-loading-text { font-size: 13px; font-weight: 600; color: var(--text-primary);}
/* ========================================================================== 5. Right Pane: Scholarly Transcription Editor & Linguistic Inspector ========================================================================== */
.editor-pane { background: var(--bg-panel); display: flex; flex-direction: column; min-width: 320px; min-height: 200px; overflow: hidden;}
.editor-toolbar { height: 40px; padding: 0 10px; background: var(--bg-panel); border-bottom: 1px solid var(--border-subtle); display: flex; align-items: center; justify-content: space-between; gap: 6px; flex-wrap: nowrap; overflow-x: auto; scrollbar-width: none; flex-shrink: 0;}
.editor-toolbar::-webkit-scrollbar { display: none;}
.editor-mode-pills { display: inline-flex; background: var(--bg-panel-soft); border: 1px solid var(--border-subtle); border-radius: 7px; padding: 2px; gap: 2px;}
.editor-mode-btn { border: none; background: transparent; font-family: inherit; font-size: 11.5px; font-weight: 600; color: var(--text-secondary); padding: 3px 9px; border-radius: 5px; cursor: pointer;}
.editor-mode-btn.active { background: var(--bg-elevated); color: var(--accent); box-shadow: var(--shadow-xs);}
/* Find & Replace Bar */.find-replace-bar { display: none; padding: 7px 10px; background: var(--bg-panel-soft); border-bottom: 1px solid var(--border-subtle); gap: 6px; align-items: center; flex-wrap: wrap;}
.find-replace-bar.open { display: flex;}
.find-input { flex: 1; min-width: 110px; height: 27px; padding: 0 8px; border: 1px solid var(--border-medium); border-radius: 5px; background: var(--bg-elevated); font-family: var(--font-cham); font-size: 13px; color: var(--text-primary);}
/* Document Telemetry Banner (Uncovered ink, Multi-column notice, Latency) */.doc-telemetry-strip { display: none; padding: 5px 12px; background: var(--bg-panel-soft); border-bottom: 1px solid var(--border-subtle); font-size: 11px; color: var(--text-secondary); align-items: center; justify-content: space-between; gap: 8px; flex-wrap: wrap;}
.doc-telemetry-strip.visible { display: flex;}
.doc-telemetry-strip.warn { background: var(--confidence-medium-bg); color: var(--confidence-medium);}
/* Main Editor Scroll Area */.editor-scroll-body { flex: 1; overflow-y: auto; padding: 8px 10px; display: flex; flex-direction: column; gap: 4px;}
.editor-empty-state { margin: auto; padding: 36px 20px; text-align: center; color: var(--text-tertiary); font-size: 12.5px; line-height: 1.6;}
/* Diplomatic Line Row */.editor-line-row { display: flex; align-items: stretch; gap: 8px; padding: 7px 9px; border-radius: var(--radius-sm); border: 1px solid transparent; background: transparent; cursor: pointer; transition: background 0.12s ease, border-color 0.12s ease; position: relative;}
.editor-line-row:hover { background: var(--bg-panel-soft); border-color: var(--border-subtle);}
.editor-line-row.active { background: var(--selection-bg); border-color: var(--selection-border);}
.line-gutter { width: 28px; font-family: var(--font-mono); font-size: 11px; font-weight: 600; color: var(--text-tertiary); display: flex; flex-direction: column; align-items: center; padding-top: 4px; gap: 4px; flex-shrink: 0; user-select: none;}
.editor-line-row.active .line-gutter { color: var(--accent);}
.conf-bar { width: 4px; border-radius: 999px; flex-shrink: 0; margin: 2px 0;}.conf-bar.high { background: var(--confidence-high); }.conf-bar.medium { background: var(--confidence-medium); }.conf-bar.low { background: var(--confidence-low); }
.line-body { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 4px;}
.line-crop-strip { max-height: 46px; background: var(--bg-canvas); border: 1px solid var(--border-subtle); border-radius: 6px; padding: 3px 5px; overflow: hidden; display: inline-flex; align-items: center; align-self: flex-start; max-width: 100%; cursor: zoom-in; transition: border-color 0.14s ease, box-shadow 0.14s ease;}
.line-crop-strip:hover { border-color: var(--accent);}
.line-crop-strip img { max-height: 38px; width: auto; max-width: 100%; object-fit: contain; display: block;}
.line-crop-strip.focus-strip { max-height: 62px; padding: 4px 7px; border-color: var(--selection-border); background: var(--bg-elevated); box-shadow: var(--shadow-xs);}
.line-crop-strip.focus-strip img { max-height: 52px;}
.editor-ready-card { margin: auto; max-width: 340px; padding: 24px 20px; text-align: center; display: flex; flex-direction: column; align-items: center; gap: 10px; color: var(--text-secondary);}
.editor-ready-title { font-size: 14.5px; font-weight: 700; color: var(--text-primary);}
.editor-ready-desc { font-size: 12.5px; line-height: 1.55; color: var(--text-secondary);}
.editor-ready-actions { display: flex; flex-wrap: wrap; justify-content: center; gap: 8px; margin-top: 4px;}
.line-cham-view { font-family: var(--font-cham); font-size: 20px; line-height: 1.85; color: var(--text-primary); word-break: break-word; padding: 1px 2px;}
.line-cham-view.low-conf { text-decoration: underline wavy var(--confidence-medium); text-underline-offset: 5px;}
.char-span { padding: 1px 1px; border-radius: 3px; transition: background 0.1s ease;}
.char-span:hover { background: var(--accent-soft-2);}
.char-span.active { background: var(--confidence-high-bg); outline: 1.5px solid var(--confidence-high); color: var(--text-primary);}
.char-span.search-hit { background: #FFE8A3; border-radius: 2px;}
.line-edit-wrap { display: none; gap: 5px; align-items: center;}
.line-edit-wrap.open { display: flex;}
.line-cham-input { flex: 1; font-family: var(--font-cham); font-size: 20px; line-height: 1.65; padding: 3px 8px; border: 1.5px solid var(--accent); border-radius: 6px; background: var(--bg-elevated); color: var(--text-primary); outline: none; box-shadow: 0 0 0 3px var(--accent-glow);}
.line-roman-sub { font-family: var(--font-sans); font-size: 12px; font-style: italic; color: var(--text-secondary); line-height: 1.4;}
.line-badges-row { display: flex; align-items: center; justify-content: space-between; gap: 6px;}
.line-meta-tags { display: inline-flex; align-items: center; gap: 5px; flex-wrap: wrap;}
.micro-tag { font-family: var(--font-mono); font-size: 9.5px; font-weight: 600; padding: 1px 5px; border-radius: 4px; background: var(--bg-panel-soft); border: 1px solid var(--border-subtle); color: var(--text-tertiary);}
.micro-tag.verified { background: var(--confidence-high-bg); color: var(--confidence-high); border-color: rgba(47, 125, 92, 0.25);}
.micro-tag.review { background: var(--confidence-medium-bg); color: var(--confidence-medium); border-color: rgba(183, 121, 31, 0.25);}
.line-hover-tools { opacity: 0; display: inline-flex; align-items: center; gap: 3px; transition: opacity 0.12s ease;}
.editor-line-row:hover .line-hover-tools,.editor-line-row.active .line-hover-tools { opacity: 1;}
/* Continuous Paragraph / Stanza Flow Cards */.para-card { padding: 12px 14px; background: var(--bg-panel-soft); border: 1px solid var(--border-subtle); border-left: 3px solid var(--accent); border-radius: var(--radius-sm); margin-bottom: 8px; display: flex; flex-direction: column; gap: 6px;}
.para-header { display: flex; justify-content: space-between; align-items: center; font-size: 11px; font-weight: 700; color: var(--text-tertiary); text-transform: uppercase; letter-spacing: 0.4px;}
.para-cham-text { font-family: var(--font-cham); font-size: 20px; line-height: 1.92; color: var(--text-primary);}
.para-segment { cursor: pointer; border-radius: 4px; padding: 1px 2px; transition: background 0.12s ease;}
.para-segment:hover,.para-segment.active { background: var(--accent-soft-2);}
.para-roman-text { font-size: 12.5px; font-style: italic; color: var(--text-secondary); line-height: 1.5; border-top: 1px dashed var(--border-subtle); padding-top: 6px;}
/* Collapsible Unicode Cluster Inspector Drawer */.inspector-drawer { display: none; border-top: 1px solid var(--border-medium); background: var(--bg-panel-soft); max-height: 205px; overflow-y: auto; padding: 8px 12px; flex-shrink: 0;}
.inspector-drawer.open { display: block;}
.inspector-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 6px;}
.inspector-title { font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px; color: var(--accent);}
.cp-chips-grid { display: flex; flex-wrap: wrap; gap: 6px;}
.cp-chip { background: var(--bg-panel); border: 1px solid var(--border-subtle); border-radius: 6px; padding: 4px 8px; display: inline-flex; align-items: center; gap: 7px;}
.cp-glyph { font-family: var(--font-cham); font-size: 19px; color: var(--accent); line-height: 1.3;}
.cp-details { display: flex; flex-direction: column; font-size: 10.5px; line-height: 1.25;}
.cp-hex { font-family: var(--font-mono); font-weight: 700; color: var(--text-primary);}
.cp-name { color: var(--text-secondary);}
/* Sticky Bottom Line Action Bar */.line-action-bar { min-height: 40px; padding: 5px 10px; background: var(--bg-panel-soft); border-top: 1px solid var(--border-subtle); display: flex; align-items: center; justify-content: space-between; gap: 8px; flex-wrap: wrap; flex-shrink: 0;}
.action-bar-status { font-size: 11.5px; color: var(--text-secondary); display: flex; align-items: center; gap: 6px; min-width: 0;}
.action-bar-btns { display: flex; align-items: center; gap: 4px; flex-wrap: wrap;}
/* ========================================================================== 6. Floating Cham Paleographic Virtual Keyboard (Alt+K) ========================================================================== */
.cham-kb-panel { position: fixed; bottom: 20px; right: 20px; width: min(820px, calc(100vw - 24px)); background: var(--bg-panel); border: 1px solid var(--border-strong); border-radius: var(--radius-md); box-shadow: var(--shadow-lg); z-index: 650; display: flex; flex-direction: column; overflow: hidden;}
.cham-kb-panel.closed { display: none;}
.cham-kb-header { padding: 7px 12px; background: var(--bg-panel-soft); border-bottom: 1px solid var(--border-subtle); display: flex; align-items: center; justify-content: space-between; gap: 10px; cursor: move; user-select: none;}
.cham-kb-title { font-size: 12.5px; font-weight: 700; color: var(--text-primary); display: inline-flex; align-items: center; gap: 7px;}
.cham-kb-controls { display: inline-flex; align-items: center; gap: 8px; flex-wrap: wrap;}
.cham-kb-controls label { font-size: 11px; color: var(--text-secondary); font-weight: 600;}
.cham-kb-controls select { font-family: inherit; font-size: 11.5px; padding: 2px 6px; border-radius: 5px; border: 1px solid var(--border-medium); background: var(--bg-elevated); color: var(--text-primary);}
.cham-kb-scratchbar { padding: 6px 10px; border-bottom: 1px solid var(--border-subtle); background: var(--bg-panel); display: flex; align-items: center; gap: 6px;}
.cham-kb-scratchpad { flex: 1; height: 32px; padding: 0 10px; border: 1px solid var(--border-medium); border-radius: 6px; background: var(--bg-elevated); font-family: var(--font-cham); font-size: 17px; color: var(--text-primary); outline: none;}
.cham-kb-scratchpad::placeholder { font-family: var(--font-sans); font-size: 12.5px; color: var(--text-tertiary);}
.cham-kb-scratchpad:focus { border-color: var(--accent);}
.cham-kb-body { padding: 8px; background: var(--bg-canvas); display: flex; flex-direction: column; gap: 4px; max-height: 320px; overflow-y: auto;}
.cham-kb-row { display: flex; gap: 4px; justify-content: center;}
.cham-kb-key { flex: 1; min-width: 34px; min-height: 44px; padding: 3px 2px; border-radius: 6px; border: 1px solid var(--border-medium); background: var(--bg-panel); color: var(--text-primary); cursor: pointer; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 1px; box-shadow: 0 1px 0 var(--border-medium); transition: background 0.1s ease, border-color 0.1s ease, transform 0.06s ease;}
.cham-kb-key:hover { background: var(--accent-soft); border-color: var(--accent);}
.cham-kb-key:active { transform: translateY(1px);}
.cham-kb-key.key-space { flex: 2.3;}
.cham-kb-key.key-action { flex: 1.4; background: var(--bg-panel-soft); font-weight: 700;}
.cham-kb-glyph { font-family: var(--font-cham); line-height: 1.3; color: var(--text-primary);}
.dotted-circle { color: var(--text-tertiary); font-size: 0.85em;}
.cham-kb-sub { font-family: var(--font-sans); font-size: 9.5px; color: var(--text-tertiary); line-height: 1;}
/* ========================================================================== 7. Modals & Command Palette (Ctrl+K) ========================================================================== */
.modal-backdrop { display: none; position: fixed; inset: 0; background: rgba(43, 33, 24, 0.42); backdrop-filter: blur(3px); align-items: center; justify-content: center; padding: 20px; z-index: 800;}
.modal-backdrop.open { display: flex;}
.modal-dialog { width: 100%; max-width: 680px; max-height: 86vh; background: var(--bg-panel); border: 1px solid var(--border-medium); border-radius: var(--radius-lg); box-shadow: var(--shadow-lg); display: flex; flex-direction: column; overflow: hidden;}
.modal-dialog.modal-wide { max-width: 880px;}
.modal-header { padding: 14px 18px; border-bottom: 1px solid var(--border-subtle); display: flex; align-items: center; justify-content: space-between; gap: 12px; background: var(--bg-panel-soft);}
.modal-header h2 { font-size: 16px; font-weight: 700; color: var(--text-primary); display: flex; align-items: center; gap: 8px;}
.modal-body { padding: 18px; overflow-y: auto; display: flex; flex-direction: column; gap: 14px;}
.modal-footer { padding: 12px 18px; border-top: 1px solid var(--border-subtle); background: var(--bg-panel-soft); display: flex; align-items: center; justify-content: space-between; gap: 10px;}
/* Command Palette (Ctrl+K) */.cmdk-dialog { width: 100%; max-width: 580px; background: var(--bg-elevated); border: 1px solid var(--border-strong); border-radius: var(--radius-md); box-shadow: var(--shadow-lg); overflow: hidden; align-self: flex-start; margin-top: 8vh;}
.cmdk-input-row { display: flex; align-items: center; gap: 10px; padding: 12px 14px; border-bottom: 1px solid var(--border-subtle); background: var(--bg-panel);}
.cmdk-input { flex: 1; border: none; background: transparent; font-family: inherit; font-size: 14.5px; color: var(--text-primary); outline: none;}
.cmdk-list { max-height: 360px; overflow-y: auto; padding: 6px;}
.cmdk-group-title { font-size: 10.5px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.6px; color: var(--text-tertiary); padding: 8px 10px 4px;}
.cmdk-item { padding: 8px 10px; border-radius: var(--radius-sm); display: flex; align-items: center; justify-content: space-between; gap: 10px; cursor: pointer; font-size: 13px; color: var(--text-primary);}
.cmdk-item.selected,.cmdk-item:hover { background: var(--accent-soft); color: var(--accent);}
.cmdk-item-sub { font-size: 11px; color: var(--text-tertiary); margin-left: 6px;}
/* Sample Gallery Cards in Modal */.samples-modal-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px;}
.sample-gallery-card { border: 1px solid var(--border-subtle); border-radius: var(--radius-md); background: var(--bg-elevated); padding: 12px; display: flex; gap: 12px; cursor: pointer; transition: all 0.14s ease;}
.sample-gallery-card:hover { border-color: var(--accent); background: var(--accent-soft);}
.sample-gallery-thumb { width: 96px; height: 76px; border-radius: 7px; background: var(--bg-canvas); border: 1px solid var(--border-subtle); overflow: hidden; flex-shrink: 0;}
.sample-gallery-thumb img { width: 100%; height: 100%; object-fit: cover;}
/* Export Cards Grid */.export-options-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px;}
.export-card { border: 1px solid var(--border-subtle); border-radius: var(--radius-md); background: var(--bg-elevated); padding: 12px 14px; cursor: pointer; display: flex; flex-direction: column; gap: 4px; text-align: left; transition: all 0.14s ease;}
.export-card:hover { border-color: var(--accent); background: var(--accent-soft);}
.export-card-title { font-size: 13px; font-weight: 700; color: var(--text-primary);}
.export-card-desc { font-size: 11.5px; color: var(--text-secondary); line-height: 1.45;}
/* Toast Notification */.toast-stack { position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%); display: flex; flex-direction: column; gap: 6px; z-index: 1200; pointer-events: none;}
.studio-toast { background: var(--text-primary); color: var(--bg-panel); border: 1px solid var(--accent); padding: 8px 16px; border-radius: 999px; font-size: 12.5px; font-weight: 500; box-shadow: var(--shadow-lg); transition: opacity 0.25s ease, transform 0.25s ease;}
/* Responsive Breakpoints */@media (max-width: 1120px) { .brand-subtitle, .header-hide-md { display: none; } :root { --sidebar-width: 245px; --editor-width: 390px; }}
@media (max-width: 860px) { .studio-header { display: flex; height: auto; padding: 8px 12px; flex-wrap: wrap; justify-content: space-between; } .workspace, .main-split-stage { flex-direction: column !important; } .sidebar-pane, .editor-pane, .viewer-pane { width: 100% !important; max-width: none !important; } .sidebar-pane { max-height: 220px; } .viewer-pane { min-height: 280px; flex: 1; } .editor-pane { flex: 1; } .pane-resizer-v { display: none !important; } .quick-samples-grid, .samples-modal-grid, .export-options-grid { grid-template-columns: 1fr; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549/** * Cham Paleographic Virtual Keyboard (Akhar Thrah) — Pure Academic English Edition * Supports 5-row (Compact), 6-row (Balanced), and 9-row (Canonical) layouts, * Traditional & Sanskrit phonetic legends, draggable floating window, and non-blur cursor insertion. */(function (global) { "use strict";
const CHAM_KEYBOARD_LAYOUTS = { "5": [ [ { char: "꩑", display: "꩑", trad: "1", sanskrit: "1", title: "U+AA51 Cham Digit One" }, { char: "꩒", display: "꩒", trad: "2", sanskrit: "2", title: "U+AA52 Cham Digit Two" }, { char: "꩓", display: "꩓", trad: "3", sanskrit: "3", title: "U+AA53 Cham Digit Three" }, { char: "꩔", display: "꩔", trad: "4", sanskrit: "4", title: "U+AA54 Cham Digit Four" }, { char: "꩕", display: "꩕", trad: "5", sanskrit: "5", title: "U+AA55 Cham Digit Five" }, { char: "꩖", display: "꩖", trad: "6", sanskrit: "6", title: "U+AA56 Cham Digit Six" }, { char: "꩗", display: "꩗", trad: "7", sanskrit: "7", title: "U+AA57 Cham Digit Seven" }, { char: "꩘", display: "꩘", trad: "8", sanskrit: "8", title: "U+AA58 Cham Digit Eight" }, { char: "꩙", display: "꩙", trad: "9", sanskrit: "9", title: "U+AA59 Cham Digit Nine" }, { char: "꩐", display: "꩐", trad: "0", sanskrit: "0", title: "U+AA50 Cham Digit Zero" }, { char: "ꨀ", display: "ꨀ", trad: "a", sanskrit: "a", title: "U+AA00 Cham Letter A" }, { char: "ꨁ", display: "ꨁ", trad: "i", sanskrit: "i", title: "U+AA01 Cham Letter I" }, { char: "ꨂ", display: "ꨂ", trad: "u", sanskrit: "u", title: "U+AA02 Cham Letter U" }, { char: "ꨃ", display: "ꨃ", trad: "e", sanskrit: "e", title: "U+AA03 Cham Letter E" }, { char: "ꨄ", display: "ꨄ", trad: "ai", sanskrit: "ai", title: "U+AA04 Cham Letter Ai" }, { char: "ꨅ", display: "ꨅ", trad: "o", sanskrit: "o", title: "U+AA05 Cham Letter O" }, { char: "'", display: "'", trad: "'", sanskrit: "'", title: "Apostrophe" } ], [ { char: "ꨆ", display: "ꨆ", trad: "ka", sanskrit: "ka", title: "U+AA06 Cham Letter Ka" }, { char: "ꨇ", display: "ꨇ", trad: "kha", sanskrit: "kha", title: "U+AA07 Cham Letter Kha" }, { char: "ꨈ", display: "ꨈ", trad: "ga", sanskrit: "ga", title: "U+AA08 Cham Letter Ga" }, { char: "ꨉ", display: "ꨉ", trad: "gha", sanskrit: "gha", title: "U+AA09 Cham Letter Gha" }, { char: "ꨊ", display: "ꨊ", trad: "ngâ", sanskrit: "ṅa", title: "U+AA0A Cham Letter Ngue" }, { char: "ꨋ", display: "ꨋ", trad: "nga", sanskrit: "ṅga", title: "U+AA0B Cham Letter Nga" }, { char: "ꨌ", display: "ꨌ", trad: "ca", sanskrit: "ca", title: "U+AA0C Cham Letter Cha" }, { char: "ꨍ", display: "ꨍ", trad: "cha", sanskrit: "cha", title: "U+AA0D Cham Letter Chha" }, { char: "ꨎ", display: "ꨎ", trad: "ja", sanskrit: "ja", title: "U+AA0E Cham Letter Ja" }, { char: "ꨏ", display: "ꨏ", trad: "jha", sanskrit: "jha", title: "U+AA0F Cham Letter Jha" }, { char: "ꨐ", display: "ꨐ", trad: "nyâ", sanskrit: "ña", title: "U+AA10 Cham Letter Nhue" }, { char: "ꨑ", display: "ꨑ", trad: "nya", sanskrit: "ñja", title: "U+AA11 Cham Letter Nha" }, { char: "ꨒ", display: "ꨒ", trad: "nja", sanskrit: "ṇḍa", title: "U+AA12 Cham Letter Nhja" }, { char: "ꨓ", display: "ꨓ", trad: "ta", sanskrit: "ta", title: "U+AA13 Cham Letter Ta" }, { char: "ꨔ", display: "ꨔ", trad: "tha", sanskrit: "tha", title: "U+AA14 Cham Letter Tha" }, { char: "ꨕ", display: "ꨕ", trad: "da", sanskrit: "da", title: "U+AA15 Cham Letter Da" }, { char: "ꨖ", display: "ꨖ", trad: "dha", sanskrit: "dha", title: "U+AA16 Cham Letter Dha" }, { char: "ꨗ", display: "ꨗ", trad: "nâ", sanskrit: "na", title: "U+AA17 Cham Letter Nue" } ], [ { char: "ꨘ", display: "ꨘ", trad: "na", sanskrit: "ṇa", title: "U+AA18 Cham Letter Na" }, { char: "ꨙ", display: "ꨙ", trad: "nda", sanskrit: "nda", title: "U+AA19 Cham Letter Dda" }, { char: "ꨚ", display: "ꨚ", trad: "pa", sanskrit: "pa", title: "U+AA1A Cham Letter Pa" }, { char: "ꨛ", display: "ꨛ", trad: "ppa", sanskrit: "ppa", title: "U+AA1B Cham Letter Ppa" }, { char: "ꨜ", display: "ꨜ", trad: "pha", sanskrit: "pha", title: "U+AA1C Cham Letter Pha" }, { char: "ꨝ", display: "ꨝ", trad: "ba", sanskrit: "ba", title: "U+AA1D Cham Letter Ba" }, { char: "ꨞ", display: "ꨞ", trad: "bha", sanskrit: "bha", title: "U+AA1E Cham Letter Bha" }, { char: "ꨟ", display: "ꨟ", trad: "mâ", sanskrit: "ma", title: "U+AA1F Cham Letter Mue" }, { char: "ꨠ", display: "ꨠ", trad: "ma", sanskrit: "mma", title: "U+AA20 Cham Letter Ma" }, { char: "ꨡ", display: "ꨡ", trad: "mba", sanskrit: "mba", title: "U+AA21 Cham Letter Bba" }, { char: "ꨢ", display: "ꨢ", trad: "ya", sanskrit: "ya", title: "U+AA22 Cham Letter Ya" }, { char: "ꨣ", display: "ꨣ", trad: "ra", sanskrit: "ra", title: "U+AA23 Cham Letter Ra" }, { char: "ꨤ", display: "ꨤ", trad: "la", sanskrit: "la", title: "U+AA24 Cham Letter La" }, { char: "ꨥ", display: "ꨥ", trad: "wa", sanskrit: "va", title: "U+AA25 Cham Letter Va" }, { char: "ꨦ", display: "ꨦ", trad: "śa", sanskrit: "śa", title: "U+AA26 Cham Letter Ssa" }, { char: "ꨧ", display: "ꨧ", trad: "sa", sanskrit: "sa", title: "U+AA27 Cham Letter Sa" }, { char: "ꨨ", display: "ꨨ", trad: "ha", sanskrit: "ha", title: "U+AA28 Cham Letter Ha" }, { type: "backspace", display: "⌫", trad: "Back", sanskrit: "Back", title: "Backspace (Delete preceding character)" } ], [ { char: "ꨩ", display: '<span class="dotted-circle">◌</span>ꨩ', trad: "-ā", sanskrit: "-ā", title: "U+AA29 Vowel Sign Aa" }, { char: "ꨪ", display: '<span class="dotted-circle">◌</span>ꨪ', trad: "-i", sanskrit: "-i", title: "U+AA2A Vowel Sign I" }, { char: "ꨫ", display: '<span class="dotted-circle">◌</span>ꨫ', trad: "-ī", sanskrit: "-ī", title: "U+AA2B Vowel Sign Ii" }, { char: "ꨬ", display: '<span class="dotted-circle">◌</span>ꨬ', trad: "-ei", sanskrit: "-ei", title: "U+AA2C Vowel Sign Ei" }, { char: "ꨭ", display: '<span class="dotted-circle">◌</span>ꨭ', trad: "-u", sanskrit: "-u", title: "U+AA2D Vowel Sign U" }, { char: "ꨮ", display: '<span class="dotted-circle">◌</span>ꨮ', trad: "-ơ", sanskrit: "-ē", title: "U+AA2E Vowel Sign Oe" }, { char: "ꨯ", display: 'ꨯ<span class="dotted-circle">◌</span>', trad: "-o", sanskrit: "-o", title: "U+AA2F Vowel Sign O (Pre-base)" }, { char: "ꨰ", display: 'ꨰ<span class="dotted-circle">◌</span>', trad: "-ai", sanskrit: "-ai", title: "U+AA30 Vowel Sign Ai (Pre-base)" }, { char: "ꨱ", display: '<span class="dotted-circle">◌</span>ꨱ', trad: "-au", sanskrit: "-ao", title: "U+AA31 Vowel Sign Au" }, { char: "ꨲ", display: '<span class="dotted-circle">◌</span>ꨲ', trad: "-ư", sanskrit: "-au", title: "U+AA32 Vowel Sign Ue" }, { char: "ꨳ", display: '<span class="dotted-circle">◌</span>ꨳ', trad: "-ia", sanskrit: "-ya", title: "U+AA33 Medial Ya" }, { char: "ꨴ", display: '<span class="dotted-circle">◌</span>ꨴ', trad: "-r", sanskrit: "-ra", title: "U+AA34 Medial Ra" }, { char: "ꨵ", display: '<span class="dotted-circle">◌</span>ꨵ', trad: "-l", sanskrit: "-la", title: "U+AA35 Medial La" }, { char: "ꨶ", display: '<span class="dotted-circle">◌</span>ꨶ', trad: "-ua", sanskrit: "-va", title: "U+AA36 Medial Wa" }, { char: "꩜", display: "꩜", trad: "§", sanskrit: "§", title: "U+AA5C Cham Spiral" }, { char: "꩝", display: "꩝", trad: "|", sanskrit: "|", title: "U+AA5D Cham Danda" }, { char: "꩞", display: "꩞", trad: "||", sanskrit: "||", title: "U+AA5E Cham Double Danda" }, { char: "꩟", display: "꩟", trad: "|||", sanskrit: "|||", title: "U+AA5F Cham Triple Danda" } ], [ { char: "ꩀ", display: "ꩀ", trad: "-k", sanskrit: "-k", title: "U+AA40 Final K" }, { char: "ꩁ", display: "ꩁ", trad: "-g", sanskrit: "-g", title: "U+AA41 Final G" }, { char: "ꩂ", display: "ꩂ", trad: "-ng", sanskrit: "-ṅ", title: "U+AA42 Final Ng" }, { char: "ꩃ", display: '<span class="dotted-circle">◌</span>ꩃ', trad: "-ng", sanskrit: "-ṅg", title: "U+AA43 Sign Final Ng" }, { char: "ꩄ", display: "ꩄ", trad: "-c", sanskrit: "-c", title: "U+AA44 Final Ch" }, { char: "ꩅ", display: "ꩅ", trad: "-t", sanskrit: "-t", title: "U+AA45 Final T" }, { char: "ꩆ", display: "ꩆ", trad: "-n", sanskrit: "-n", title: "U+AA46 Final N" }, { char: "ꩇ", display: "ꩇ", trad: "-p", sanskrit: "-p", title: "U+AA47 Final P" }, { char: "ꩈ", display: "ꩈ", trad: "-y", sanskrit: "-y", title: "U+AA48 Final Y" }, { char: "ꩉ", display: "ꩉ", trad: "-r", sanskrit: "-r", title: "U+AA49 Final R" }, { char: "ꩊ", display: "ꩊ", trad: "-l", sanskrit: "-l", title: "U+AA4A Final L" }, { char: "ꩋ", display: "ꩋ", trad: "-s", sanskrit: "-s", title: "U+AA4B Final Ss" }, { char: "ꩌ", display: '<span class="dotted-circle">◌</span>ꩌ', trad: "-m", sanskrit: "-ṃ", title: "U+AA4C Sign Final M (Anusvara)" }, { char: "ꩍ", display: '<span class="dotted-circle">◌</span>ꩍ', trad: "-h", sanskrit: "-ḥ", title: "U+AA4D Sign Final H (Visarga)" }, { char: "ꨥ", display: "ꨥ", trad: "-w", sanskrit: "-v", title: "U+AA25 Syllable-Final Va" }, { char: "(", display: "(", trad: "(", sanskrit: "(", title: "Left Parenthesis" }, { char: ")", display: ")", trad: ")", sanskrit: ")", title: "Right Parenthesis" }, { type: "space", char: " ", display: "ꨌꩌꨛꨩ", trad: "Space", sanskrit: "Space", title: "Insert Whitespace" }, { type: "enter", display: "↵", trad: "Commit", sanskrit: "Commit", title: "Commit Active Line Edit" } ] ], "6": [ [ { char: "꩑", display: "꩑", trad: "1", sanskrit: "1", title: "U+AA51 Cham Digit One" }, { char: "꩒", display: "꩒", trad: "2", sanskrit: "2", title: "U+AA52 Cham Digit Two" }, { char: "꩓", display: "꩓", trad: "3", sanskrit: "3", title: "U+AA53 Cham Digit Three" }, { char: "꩔", display: "꩔", trad: "4", sanskrit: "4", title: "U+AA54 Cham Digit Four" }, { char: "꩕", display: "꩕", trad: "5", sanskrit: "5", title: "U+AA55 Cham Digit Five" }, { char: "꩖", display: "꩖", trad: "6", sanskrit: "6", title: "U+AA56 Cham Digit Six" }, { char: "꩗", display: "꩗", trad: "7", sanskrit: "7", title: "U+AA57 Cham Digit Seven" }, { char: "꩘", display: "꩘", trad: "8", sanskrit: "8", title: "U+AA58 Cham Digit Eight" }, { char: "꩙", display: "꩙", trad: "9", sanskrit: "9", title: "U+AA59 Cham Digit Nine" }, { char: "꩐", display: "꩐", trad: "0", sanskrit: "0", title: "U+AA50 Cham Digit Zero" }, { char: "ꨀ", display: "ꨀ", trad: "a", sanskrit: "a", title: "U+AA00 Cham Letter A" }, { char: "ꨁ", display: "ꨁ", trad: "i", sanskrit: "i", title: "U+AA01 Cham Letter I" }, { char: "ꨂ", display: "ꨂ", trad: "u", sanskrit: "u", title: "U+AA02 Cham Letter U" }, { char: "ꨃ", display: "ꨃ", trad: "e", sanskrit: "e", title: "U+AA03 Cham Letter E" } ], [ { char: "ꨄ", display: "ꨄ", trad: "ai", sanskrit: "ai", title: "U+AA04 Cham Letter Ai" }, { char: "ꨅ", display: "ꨅ", trad: "o", sanskrit: "o", title: "U+AA05 Cham Letter O" }, { char: "ꨆ", display: "ꨆ", trad: "ka", sanskrit: "ka", title: "U+AA06 Cham Letter Ka" }, { char: "ꨇ", display: "ꨇ", trad: "kha", sanskrit: "kha", title: "U+AA07 Cham Letter Kha" }, { char: "ꨈ", display: "ꨈ", trad: "ga", sanskrit: "ga", title: "U+AA08 Cham Letter Ga" }, { char: "ꨉ", display: "ꨉ", trad: "gha", sanskrit: "gha", title: "U+AA09 Cham Letter Gha" }, { char: "ꨊ", display: "ꨊ", trad: "ngâ", sanskrit: "ṅa", title: "U+AA0A Cham Letter Ngue" }, { char: "ꨋ", display: "ꨋ", trad: "nga", sanskrit: "ṅga", title: "U+AA0B Cham Letter Nga" }, { char: "ꨌ", display: "ꨌ", trad: "ca", sanskrit: "ca", title: "U+AA0C Cham Letter Cha" }, { char: "ꨍ", display: "ꨍ", trad: "cha", sanskrit: "cha", title: "U+AA0D Cham Letter Chha" }, { char: "ꨎ", display: "ꨎ", trad: "ja", sanskrit: "ja", title: "U+AA0E Cham Letter Ja" }, { char: "ꨏ", display: "ꨏ", trad: "jha", sanskrit: "jha", title: "U+AA0F Cham Letter Jha" }, { char: "ꨐ", display: "ꨐ", trad: "nyâ", sanskrit: "ña", title: "U+AA10 Cham Letter Nhue" }, { char: "ꨑ", display: "ꨑ", trad: "nya", sanskrit: "ñja", title: "U+AA11 Cham Letter Nha" } ], [ { char: "ꨒ", display: "ꨒ", trad: "nja", sanskrit: "ṇḍa", title: "U+AA12 Cham Letter Nhja" }, { char: "ꨓ", display: "ꨓ", trad: "ta", sanskrit: "ta", title: "U+AA13 Cham Letter Ta" }, { char: "ꨔ", display: "ꨔ", trad: "tha", sanskrit: "tha", title: "U+AA14 Cham Letter Tha" }, { char: "ꨕ", display: "ꨕ", trad: "da", sanskrit: "da", title: "U+AA15 Cham Letter Da" }, { char: "ꨖ", display: "ꨖ", trad: "dha", sanskrit: "dha", title: "U+AA16 Cham Letter Dha" }, { char: "ꨗ", display: "ꨗ", trad: "nâ", sanskrit: "na", title: "U+AA17 Cham Letter Nue" }, { char: "ꨘ", display: "ꨘ", trad: "na", sanskrit: "ṇa", title: "U+AA18 Cham Letter Na" }, { char: "ꨙ", display: "ꨙ", trad: "nda", sanskrit: "nda", title: "U+AA19 Cham Letter Dda" }, { char: "ꨚ", display: "ꨚ", trad: "pa", sanskrit: "pa", title: "U+AA1A Cham Letter Pa" }, { char: "ꨛ", display: "ꨛ", trad: "ppa", sanskrit: "ppa", title: "U+AA1B Cham Letter Ppa" }, { char: "ꨜ", display: "ꨜ", trad: "pha", sanskrit: "pha", title: "U+AA1C Cham Letter Pha" }, { char: "ꨝ", display: "ꨝ", trad: "ba", sanskrit: "ba", title: "U+AA1D Cham Letter Ba" }, { char: "ꨞ", display: "ꨞ", trad: "bha", sanskrit: "bha", title: "U+AA1E Cham Letter Bha" }, { char: "ꨟ", display: "ꨟ", trad: "mâ", sanskrit: "ma", title: "U+AA1F Cham Letter Mue" } ], [ { char: "ꨠ", display: "ꨠ", trad: "ma", sanskrit: "mma", title: "U+AA20 Cham Letter Ma" }, { char: "ꨡ", display: "ꨡ", trad: "mba", sanskrit: "mba", title: "U+AA21 Cham Letter Bba" }, { char: "ꨢ", display: "ꨢ", trad: "ya", sanskrit: "ya", title: "U+AA22 Cham Letter Ya" }, { char: "ꨣ", display: "ꨣ", trad: "ra", sanskrit: "ra", title: "U+AA23 Cham Letter Ra" }, { char: "ꨤ", display: "ꨤ", trad: "la", sanskrit: "la", title: "U+AA24 Cham Letter La" }, { char: "ꨥ", display: "ꨥ", trad: "wa", sanskrit: "va", title: "U+AA25 Cham Letter Va" }, { char: "ꨦ", display: "ꨦ", trad: "śa", sanskrit: "śa", title: "U+AA26 Cham Letter Ssa" }, { char: "ꨧ", display: "ꨧ", trad: "sa", sanskrit: "sa", title: "U+AA27 Cham Letter Sa" }, { char: "ꨨ", display: "ꨨ", trad: "ha", sanskrit: "ha", title: "U+AA28 Cham Letter Ha" }, { char: "ꨳ", display: '<span class="dotted-circle">◌</span>ꨳ', trad: "-ia", sanskrit: "-ya", title: "U+AA33 Medial Ya" }, { char: "ꨴ", display: '<span class="dotted-circle">◌</span>ꨴ', trad: "-r", sanskrit: "-ra", title: "U+AA34 Medial Ra" }, { char: "ꨵ", display: '<span class="dotted-circle">◌</span>ꨵ', trad: "-l", sanskrit: "-la", title: "U+AA35 Medial La" }, { char: "ꨶ", display: '<span class="dotted-circle">◌</span>ꨶ', trad: "-ua", sanskrit: "-va", title: "U+AA36 Medial Wa" }, { type: "backspace", display: "⌫", trad: "Back", sanskrit: "Back", title: "Backspace" } ], [ { char: "ꨩ", display: '<span class="dotted-circle">◌</span>ꨩ', trad: "-ā", sanskrit: "-ā", title: "U+AA29 Vowel Sign Aa" }, { char: "ꨪ", display: '<span class="dotted-circle">◌</span>ꨪ', trad: "-i", sanskrit: "-i", title: "U+AA2A Vowel Sign I" }, { char: "ꨫ", display: '<span class="dotted-circle">◌</span>ꨫ', trad: "-ī", sanskrit: "-ī", title: "U+AA2B Vowel Sign Ii" }, { char: "ꨬ", display: '<span class="dotted-circle">◌</span>ꨬ', trad: "-ei", sanskrit: "-ei", title: "U+AA2C Vowel Sign Ei" }, { char: "ꨭ", display: '<span class="dotted-circle">◌</span>ꨭ', trad: "-u", sanskrit: "-u", title: "U+AA2D Vowel Sign U" }, { char: "ꨮ", display: '<span class="dotted-circle">◌</span>ꨮ', trad: "-ơ", sanskrit: "-ē", title: "U+AA2E Vowel Sign Oe" }, { char: "ꨯ", display: 'ꨯ<span class="dotted-circle">◌</span>', trad: "-o", sanskrit: "-o", title: "U+AA2F Vowel Sign O" }, { char: "ꨰ", display: 'ꨰ<span class="dotted-circle">◌</span>', trad: "-ai", sanskrit: "-ai", title: "U+AA30 Vowel Sign Ai" }, { char: "ꨱ", display: '<span class="dotted-circle">◌</span>ꨱ', trad: "-au", sanskrit: "-ao", title: "U+AA31 Vowel Sign Au" }, { char: "ꨲ", display: '<span class="dotted-circle">◌</span>ꨲ', trad: "-ư", sanskrit: "-au", title: "U+AA32 Vowel Sign Ue" }, { char: "꩜", display: "꩜", trad: "§", sanskrit: "§", title: "U+AA5C Cham Spiral" }, { char: "꩝", display: "꩝", trad: "|", sanskrit: "|", title: "U+AA5D Cham Danda" }, { char: "꩞", display: "꩞", trad: "||", sanskrit: "||", title: "U+AA5E Cham Double Danda" }, { char: "꩟", display: "꩟", trad: "|||", sanskrit: "|||", title: "U+AA5F Cham Triple Danda" } ], [ { char: "ꩀ", display: "ꩀ", trad: "-k", sanskrit: "-k", title: "U+AA40 Final K" }, { char: "ꩁ", display: "ꩁ", trad: "-g", sanskrit: "-g", title: "U+AA41 Final G" }, { char: "ꩂ", display: "ꩂ", trad: "-ng", sanskrit: "-ṅ", title: "U+AA42 Final Ng" }, { char: "ꩃ", display: '<span class="dotted-circle">◌</span>ꩃ', trad: "-ng", sanskrit: "-ṅg", title: "U+AA43 Sign Final Ng" }, { char: "ꩄ", display: "ꩄ", trad: "-c", sanskrit: "-c", title: "U+AA44 Final Ch" }, { char: "ꩅ", display: "ꩅ", trad: "-t", sanskrit: "-t", title: "U+AA45 Final T" }, { char: "ꩆ", display: "ꩆ", trad: "-n", sanskrit: "-n", title: "U+AA46 Final N" }, { char: "ꩇ", display: "ꩇ", trad: "-p", sanskrit: "-p", title: "U+AA47 Final P" }, { char: "ꩈ", display: "ꩈ", trad: "-y", sanskrit: "-y", title: "U+AA48 Final Y" }, { char: "ꩉ", display: "ꩉ", trad: "-r", sanskrit: "-r", title: "U+AA49 Final R" }, { char: "ꩊ", display: "ꩊ", trad: "-l", sanskrit: "-l", title: "U+AA4A Final L" }, { char: "ꩋ", display: "ꩋ", trad: "-s", sanskrit: "-s", title: "U+AA4B Final Ss" }, { char: "ꩌ", display: '<span class="dotted-circle">◌</span>ꩌ', trad: "-m", sanskrit: "-ṃ", title: "U+AA4C Sign Final M" }, { char: "ꩍ", display: '<span class="dotted-circle">◌</span>ꩍ', trad: "-h", sanskrit: "-ḥ", title: "U+AA4D Sign Final H" }, { char: "ꨥ", display: "ꨥ", trad: "-w", sanskrit: "-v", title: "U+AA25 Final Va" }, { char: "(", display: "(", trad: "(", sanskrit: "(", title: "Left Parenthesis" }, { char: ")", display: ")", trad: ")", sanskrit: ")", title: "Right Parenthesis" }, { char: "'", display: "'", trad: "'", sanskrit: "'", title: "Apostrophe" }, { type: "space", char: " ", display: "ꨌꩌꨛꨩ", trad: "Space", sanskrit: "Space", title: "Space" }, { type: "enter", display: "↵", trad: "Commit", sanskrit: "Commit", title: "Commit Active Line Edit" } ] ], "9": [ [ { char: "꩑", display: "꩑", trad: "1", sanskrit: "1", title: "U+AA51 Cham Digit One" }, { char: "꩒", display: "꩒", trad: "2", sanskrit: "2", title: "U+AA52 Cham Digit Two" }, { char: "꩓", display: "꩓", trad: "3", sanskrit: "3", title: "U+AA53 Cham Digit Three" }, { char: "꩔", display: "꩔", trad: "4", sanskrit: "4", title: "U+AA54 Cham Digit Four" }, { char: "꩕", display: "꩕", trad: "5", sanskrit: "5", title: "U+AA55 Cham Digit Five" }, { char: "꩖", display: "꩖", trad: "6", sanskrit: "6", title: "U+AA56 Cham Digit Six" }, { char: "꩗", display: "꩗", trad: "7", sanskrit: "7", title: "U+AA57 Cham Digit Seven" }, { char: "꩘", display: "꩘", trad: "8", sanskrit: "8", title: "U+AA58 Cham Digit Eight" }, { char: "꩙", display: "꩙", trad: "9", sanskrit: "9", title: "U+AA59 Cham Digit Nine" }, { char: "꩐", display: "꩐", trad: "0", sanskrit: "0", title: "U+AA50 Cham Digit Zero" } ], [ { char: "ꨀ", display: "ꨀ", trad: "a", sanskrit: "a", title: "U+AA00 Cham Letter A" }, { char: "ꨁ", display: "ꨁ", trad: "i", sanskrit: "i", title: "U+AA01 Cham Letter I" }, { char: "ꨂ", display: "ꨂ", trad: "u", sanskrit: "u", title: "U+AA02 Cham Letter U" }, { char: "ꨃ", display: "ꨃ", trad: "e", sanskrit: "e", title: "U+AA03 Cham Letter E" }, { char: "ꨄ", display: "ꨄ", trad: "ai", sanskrit: "ai", title: "U+AA04 Cham Letter Ai" }, { char: "ꨅ", display: "ꨅ", trad: "o", sanskrit: "o", title: "U+AA05 Cham Letter O" }, { char: "ꨆ", display: "ꨆ", trad: "ka", sanskrit: "ka", title: "U+AA06 Cham Letter Ka" }, { char: "ꨇ", display: "ꨇ", trad: "kha", sanskrit: "kha", title: "U+AA07 Cham Letter Kha" }, { char: "ꨈ", display: "ꨈ", trad: "ga", sanskrit: "ga", title: "U+AA08 Cham Letter Ga" }, { char: "ꨉ", display: "ꨉ", trad: "gha", sanskrit: "gha", title: "U+AA09 Cham Letter Gha" } ], [ { char: "ꨊ", display: "ꨊ", trad: "ngâ", sanskrit: "ṅa", title: "U+AA0A Cham Letter Ngue" }, { char: "ꨋ", display: "ꨋ", trad: "nga", sanskrit: "ṅga", title: "U+AA0B Cham Letter Nga" }, { char: "ꨌ", display: "ꨌ", trad: "ca", sanskrit: "ca", title: "U+AA0C Cham Letter Cha" }, { char: "ꨍ", display: "ꨍ", trad: "cha", sanskrit: "cha", title: "U+AA0D Cham Letter Chha" }, { char: "ꨎ", display: "ꨎ", trad: "ja", sanskrit: "ja", title: "U+AA0E Cham Letter Ja" }, { char: "ꨏ", display: "ꨏ", trad: "jha", sanskrit: "jha", title: "U+AA0F Cham Letter Jha" }, { char: "ꨐ", display: "ꨐ", trad: "nyâ", sanskrit: "ña", title: "U+AA10 Cham Letter Nhue" }, { char: "ꨑ", display: "ꨑ", trad: "nya", sanskrit: "ñja", title: "U+AA11 Cham Letter Nha" }, { char: "ꨒ", display: "ꨒ", trad: "nja", sanskrit: "ṇḍa", title: "U+AA12 Cham Letter Nhja" }, { char: "ꨓ", display: "ꨓ", trad: "ta", sanskrit: "ta", title: "U+AA13 Cham Letter Ta" } ], [ { char: "ꨔ", display: "ꨔ", trad: "tha", sanskrit: "tha", title: "U+AA14 Cham Letter Tha" }, { char: "ꨕ", display: "ꨕ", trad: "da", sanskrit: "da", title: "U+AA15 Cham Letter Da" }, { char: "ꨖ", display: "ꨖ", trad: "dha", sanskrit: "dha", title: "U+AA16 Cham Letter Dha" }, { char: "ꨗ", display: "ꨗ", trad: "nâ", sanskrit: "na", title: "U+AA17 Cham Letter Nue" }, { char: "ꨘ", display: "ꨘ", trad: "na", sanskrit: "ṇa", title: "U+AA18 Cham Letter Na" }, { char: "ꨙ", display: "ꨙ", trad: "nda", sanskrit: "nda", title: "U+AA19 Cham Letter Dda" }, { char: "ꨚ", display: "ꨚ", trad: "pa", sanskrit: "pa", title: "U+AA1A Cham Letter Pa" }, { char: "ꨛ", display: "ꨛ", trad: "ppa", sanskrit: "ppa", title: "U+AA1B Cham Letter Ppa" }, { char: "ꨜ", display: "ꨜ", trad: "pha", sanskrit: "pha", title: "U+AA1C Cham Letter Pha" }, { char: "ꨝ", display: "ꨝ", trad: "ba", sanskrit: "ba", title: "U+AA1D Cham Letter Ba" } ], [ { char: "ꨞ", display: "ꨞ", trad: "bha", sanskrit: "bha", title: "U+AA1E Cham Letter Bha" }, { char: "ꨟ", display: "ꨟ", trad: "mâ", sanskrit: "ma", title: "U+AA1F Cham Letter Mue" }, { char: "ꨠ", display: "ꨠ", trad: "ma", sanskrit: "mma", title: "U+AA20 Cham Letter Ma" }, { char: "ꨡ", display: "ꨡ", trad: "mba", sanskrit: "mba", title: "U+AA21 Cham Letter Bba" }, { char: "ꨢ", display: "ꨢ", trad: "ya", sanskrit: "ya", title: "U+AA22 Cham Letter Ya" }, { char: "ꨣ", display: "ꨣ", trad: "ra", sanskrit: "ra", title: "U+AA23 Cham Letter Ra" }, { char: "ꨤ", display: "ꨤ", trad: "la", sanskrit: "la", title: "U+AA24 Cham Letter La" }, { char: "ꨥ", display: "ꨥ", trad: "wa", sanskrit: "va", title: "U+AA25 Cham Letter Va" }, { char: "ꨦ", display: "ꨦ", trad: "śa", sanskrit: "śa", title: "U+AA26 Cham Letter Ssa" }, { char: "ꨧ", display: "ꨧ", trad: "sa", sanskrit: "sa", title: "U+AA27 Cham Letter Sa" } ], [ { char: "ꨨ", display: "ꨨ", trad: "ha", sanskrit: "ha", title: "U+AA28 Cham Letter Ha" }, { char: "ꨩ", display: '<span class="dotted-circle">◌</span>ꨩ', trad: "-ā", sanskrit: "-ā", title: "U+AA29 Vowel Sign Aa" }, { char: "ꨪ", display: '<span class="dotted-circle">◌</span>ꨪ', trad: "-i", sanskrit: "-i", title: "U+AA2A Vowel Sign I" }, { char: "ꨫ", display: '<span class="dotted-circle">◌</span>ꨫ', trad: "-ī", sanskrit: "-ī", title: "U+AA2B Vowel Sign Ii" }, { char: "ꨬ", display: '<span class="dotted-circle">◌</span>ꨬ', trad: "-ei", sanskrit: "-ei", title: "U+AA2C Vowel Sign Ei" }, { char: "ꨭ", display: '<span class="dotted-circle">◌</span>ꨭ', trad: "-u", sanskrit: "-u", title: "U+AA2D Vowel Sign U" }, { char: "ꨮ", display: '<span class="dotted-circle">◌</span>ꨮ', trad: "-ơ", sanskrit: "-ē", title: "U+AA2E Vowel Sign Oe" }, { char: "ꨯ", display: 'ꨯ<span class="dotted-circle">◌</span>', trad: "-o", sanskrit: "-o", title: "U+AA2F Vowel Sign O" }, { char: "ꨰ", display: 'ꨰ<span class="dotted-circle">◌</span>', trad: "-ai", sanskrit: "-ai", title: "U+AA30 Vowel Sign Ai" }, { char: "ꨱ", display: '<span class="dotted-circle">◌</span>ꨱ', trad: "-au", sanskrit: "-ao", title: "U+AA31 Vowel Sign Au" } ], [ { char: "ꨲ", display: '<span class="dotted-circle">◌</span>ꨲ', trad: "-ư", sanskrit: "-au", title: "U+AA32 Vowel Sign Ue" }, { char: "ꨳ", display: '<span class="dotted-circle">◌</span>ꨳ', trad: "-ia", sanskrit: "-ya", title: "U+AA33 Medial Ya" }, { char: "ꨴ", display: '<span class="dotted-circle">◌</span>ꨴ', trad: "-r", sanskrit: "-ra", title: "U+AA34 Medial Ra" }, { char: "ꨵ", display: '<span class="dotted-circle">◌</span>ꨵ', trad: "-l", sanskrit: "-la", title: "U+AA35 Medial La" }, { char: "ꨶ", display: '<span class="dotted-circle">◌</span>ꨶ', trad: "-ua", sanskrit: "-va", title: "U+AA36 Medial Wa" }, { char: "ꩀ", display: "ꩀ", trad: "-k", sanskrit: "-k", title: "U+AA40 Final K" }, { char: "ꩁ", display: "ꩁ", trad: "-g", sanskrit: "-g", title: "U+AA41 Final G" }, { char: "ꩂ", display: "ꩂ", trad: "-ng", sanskrit: "-ṅ", title: "U+AA42 Final Ng" }, { char: "ꩃ", display: '<span class="dotted-circle">◌</span>ꩃ', trad: "-ng", sanskrit: "-ṅg", title: "U+AA43 Sign Final Ng" }, { char: "ꩄ", display: "ꩄ", trad: "-c", sanskrit: "-c", title: "U+AA44 Final Ch" } ], [ { char: "ꩅ", display: "ꩅ", trad: "-t", sanskrit: "-t", title: "U+AA45 Final T" }, { char: "ꩆ", display: "ꩆ", trad: "-n", sanskrit: "-n", title: "U+AA46 Final N" }, { char: "ꩇ", display: "ꩇ", trad: "-p", sanskrit: "-p", title: "U+AA47 Final P" }, { char: "ꩈ", display: "ꩈ", trad: "-y", sanskrit: "-y", title: "U+AA48 Final Y" }, { char: "ꩉ", display: "ꩉ", trad: "-r", sanskrit: "-r", title: "U+AA49 Final R" }, { char: "ꩊ", display: "ꩊ", trad: "-l", sanskrit: "-l", title: "U+AA4A Final L" }, { char: "ꩋ", display: "ꩋ", trad: "-s", sanskrit: "-s", title: "U+AA4B Final Ss" }, { char: "ꩌ", display: '<span class="dotted-circle">◌</span>ꩌ', trad: "-m", sanskrit: "-ṃ", title: "U+AA4C Sign Final M" }, { char: "ꩍ", display: '<span class="dotted-circle">◌</span>ꩍ', trad: "-h", sanskrit: "-ḥ", title: "U+AA4D Sign Final H" }, { char: "ꨥ", display: "ꨥ", trad: "-w", sanskrit: "-v", title: "U+AA25 Final Va" }, { type: "backspace", display: "⌫", trad: "Back", sanskrit: "Back", title: "Backspace" } ], [ { char: "꩜", display: "꩜", trad: "§", sanskrit: "§", title: "U+AA5C Cham Spiral" }, { char: "꩝", display: "꩝", trad: "|", sanskrit: "|", title: "U+AA5D Cham Danda" }, { char: "꩞", display: "꩞", trad: "||", sanskrit: "||", title: "U+AA5E Cham Double Danda" }, { char: "꩟", display: "꩟", trad: "|||", sanskrit: "|||", title: "U+AA5F Cham Triple Danda" }, { type: "space", char: " ", display: "ꨌꩌꨛꨩ", trad: "Space", sanskrit: "Space", title: "Space" }, { char: "(", display: "(", trad: "(", sanskrit: "(", title: "Left Parenthesis" }, { char: ")", display: ")", trad: ")", sanskrit: ")", title: "Right Parenthesis" }, { char: "'", display: "'", trad: "'", sanskrit: "'", title: "Apostrophe" }, { type: "enter", display: "↵", trad: "Commit", sanskrit: "Commit", title: "Commit Active Line Edit" } ] ] };
const state = { isOpen: false, rowLayout: localStorage.getItem("cham_kb_row_layout") || "5", phoneticMode: localStorage.getItem("cham_kb_phonetic") || "traditional", fontSize: parseInt(localStorage.getItem("cham_kb_font_size") || "18", 10), dragInit: false };
function renderGrid() { const body = document.getElementById("cham-kb-body"); if (!body) return; const rows = CHAM_KEYBOARD_LAYOUTS[state.rowLayout] || CHAM_KEYBOARD_LAYOUTS["5"]; body.innerHTML = "";
rows.forEach((rowKeys) => { const rowEl = document.createElement("div"); rowEl.className = "cham-kb-row"; rowKeys.forEach((key) => { const btn = document.createElement("button"); btn.type = "button"; btn.className = "cham-kb-key"; if (key.type === "space") btn.classList.add("key-space"); if (key.type === "backspace" || key.type === "enter") btn.classList.add("key-action"); btn.title = key.title || "";
// Prevent stealing focus from active transcription line input! btn.addEventListener("mousedown", (e) => e.preventDefault()); btn.addEventListener("click", () => handleVirtualKeyPress(key));
let subLabel = ""; if (state.phoneticMode === "traditional" && key.trad) subLabel = key.trad; else if (state.phoneticMode === "sanskrit" && key.sanskrit) subLabel = key.sanskrit;
btn.innerHTML = ` <span class="cham-kb-glyph" style="font-size:${state.fontSize}px">${key.display}</span> ${subLabel ? `<span class="cham-kb-sub">${subLabel}</span>` : ""} `; rowEl.appendChild(btn); }); body.appendChild(rowEl); }); }
function getTargetInput() { const activeTarget = global.StudioApp && global.StudioApp.getActiveLineInput ? global.StudioApp.getActiveLineInput() : null; if (activeTarget && document.body.contains(activeTarget)) return activeTarget; return document.getElementById("cham-kb-scratchpad"); }
function handleVirtualKeyPress(key) { if (key.type === "enter") { if (global.StudioApp && global.StudioApp.commitActiveEdit) { global.StudioApp.commitActiveEdit(); } return; }
const input = getTargetInput(); if (!input) return;
const start = typeof input.selectionStart === "number" ? input.selectionStart : input.value.length; const end = typeof input.selectionEnd === "number" ? input.selectionEnd : input.value.length; const val = input.value || "";
if (key.type === "backspace") { if (start !== end) { input.value = val.slice(0, start) + val.slice(end); input.setSelectionRange(start, start); } else if (start > 0) { const chars = Array.from(val.slice(0, start)); chars.pop(); const prefix = chars.join(""); input.value = prefix + val.slice(end); input.setSelectionRange(prefix.length, prefix.length); } } else { const insertStr = key.char || ""; input.value = val.slice(0, start) + insertStr + val.slice(end); const nextPos = start + insertStr.length; input.setSelectionRange(nextPos, nextPos); }
input.focus(); input.dispatchEvent(new Event("input", { bubbles: true })); }
function toggle(forceState) { const panel = document.getElementById("cham-kb-panel"); const triggerBtn = document.getElementById("btn-header-keyboard"); if (!panel) return;
state.isOpen = typeof forceState === "boolean" ? forceState : !state.isOpen; if (state.isOpen) { renderGrid(); initDrag(); panel.classList.remove("closed"); panel.classList.add("open"); if (triggerBtn) triggerBtn.classList.add("active"); } else { panel.classList.remove("open"); panel.classList.add("closed"); if (triggerBtn) triggerBtn.classList.remove("active"); } }
function setRowLayout(val) { state.rowLayout = String(val); localStorage.setItem("cham_kb_row_layout", state.rowLayout); renderGrid(); }
function setPhoneticMode(val) { state.phoneticMode = String(val); localStorage.setItem("cham_kb_phonetic", state.phoneticMode); renderGrid(); }
function setFontSize(val) { state.fontSize = parseInt(val, 10) || 18; localStorage.setItem("cham_kb_font_size", String(state.fontSize)); renderGrid(); }
function resetPosition() { const panel = document.getElementById("cham-kb-panel"); if (!panel) return; panel.style.top = ""; panel.style.left = ""; panel.style.bottom = "20px"; panel.style.right = "20px"; if (global.StudioApp && global.StudioApp.toast) { global.StudioApp.toast("Keyboard docked to default corner"); } }
function copyScratchpad() { const sp = document.getElementById("cham-kb-scratchpad"); if (!sp || !sp.value) return; navigator.clipboard.writeText(sp.value).then(() => { if (global.StudioApp) global.StudioApp.toast("Scratchpad copied to clipboard"); }); }
function insertScratchpadToLine() { const sp = document.getElementById("cham-kb-scratchpad"); if (!sp || !sp.value) return; if (global.StudioApp && global.StudioApp.insertTextIntoSelectedLine) { global.StudioApp.insertTextIntoSelectedLine(sp.value); } }
function clearScratchpad() { const sp = document.getElementById("cham-kb-scratchpad"); if (sp) sp.value = ""; }
function normalizeScratchpad() { const sp = document.getElementById("cham-kb-scratchpad"); if (!sp || !sp.value || !global.ChamLinguistics) return; sp.value = global.ChamLinguistics.normalizeChamLogicalClient(sp.value); if (global.StudioApp) global.StudioApp.toast("Normalized to canonical Brahmic Logical Order"); }
function initDrag() { if (state.dragInit) return; const header = document.getElementById("cham-kb-header"); const panel = document.getElementById("cham-kb-panel"); if (!header || !panel) return; state.dragInit = true;
let dragging = false; let sx = 0, sy = 0, initL = 0, initT = 0;
header.addEventListener("mousedown", (e) => { if (e.target.closest("select, button, input")) return; dragging = true; const r = panel.getBoundingClientRect(); sx = e.clientX; sy = e.clientY; initL = r.left; initT = r.top; panel.style.bottom = "auto"; panel.style.right = "auto"; panel.style.left = `${r.left}px`; panel.style.top = `${r.top}px`; document.body.style.userSelect = "none"; });
document.addEventListener("mousemove", (e) => { if (!dragging) return; const maxL = Math.max(8, window.innerWidth - panel.offsetWidth - 8); const maxT = Math.max(8, window.innerHeight - panel.offsetHeight - 8); const nl = Math.max(8, Math.min(maxL, initL + (e.clientX - sx))); const nt = Math.max(8, Math.min(maxT, initT + (e.clientY - sy))); panel.style.left = `${nl}px`; panel.style.top = `${nt}px`; });
document.addEventListener("mouseup", () => { if (dragging) { dragging = false; document.body.style.userSelect = ""; } }); }
global.ChamKeyboard = { toggle, isOpen: () => state.isOpen, setRowLayout, setPhoneticMode, setFontSize, resetPosition, copyScratchpad, insertScratchpadToLine, clearScratchpad, normalizeScratchpad, renderGrid };})(window);12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091/** * Cham OCR Studio — Interactive User Guide & Feature Manual Controller (/help) * Provides ScrollSpy TOC, Reading Progress Bar, Mobile TOC Drawer, and Live Guide Search. */(function () { "use strict";
window.toggleHelpMobileToc = function () { const sb = document.getElementById("help-sidebar"); if (sb) sb.classList.toggle("mobile-open"); };
window.filterHelpGuide = function (rawQuery) { const q = String(rawQuery || "").trim().toLowerCase();
// Filter TOC items document.querySelectorAll("#help-sidebar .toc-nav-item").forEach((li) => { if (!q) { li.style.display = ""; return; } li.style.display = li.innerText.toLowerCase().includes(q) ? "" : "none"; });
// Filter shortcut rows if searching inside shortcuts document.querySelectorAll("#shortcuts-table tbody tr").forEach((row) => { if (!q) { row.style.display = ""; return; } row.style.display = row.innerText.toLowerCase().includes(q) ? "" : "none"; }); };
document.addEventListener("DOMContentLoaded", () => { const progressBar = document.getElementById("help-progress-bar"); const links = Array.from(document.querySelectorAll(".toc-nav-link, .toc-sub-link")); const NAV_OFFSET = 82; const tracked = [];
links.forEach((link) => { const href = link.getAttribute("href"); if (href && href.startsWith("#")) { const target = document.querySelector(href); if (target) { tracked.push({ link, target }); link.addEventListener("click", (e) => { e.preventDefault(); const top = target.getBoundingClientRect().top + window.pageYOffset - NAV_OFFSET; window.scrollTo({ top, behavior: "smooth" }); history.pushState(null, "", href); document.getElementById("help-sidebar")?.classList.remove("mobile-open"); }); } } });
function onScroll() { const scrollTop = window.scrollY || document.documentElement.scrollTop; const maxScroll = Math.max(1, document.documentElement.scrollHeight - window.innerHeight); if (progressBar) { progressBar.style.width = `${Math.min(100, Math.max(0, (scrollTop / maxScroll) * 100))}%`; }
const probe = scrollTop + 120; for (let i = tracked.length - 1; i >= 0; i--) { const top = tracked[i].target.getBoundingClientRect().top + window.pageYOffset; if (top <= probe) { links.forEach((l) => l.classList.remove("active")); tracked[i].link.classList.add("active"); break; } } }
window.addEventListener("scroll", onScroll, { passive: true }); onScroll();
// Allow '/' or Ctrl+K on /help to focus the guide search input document.addEventListener("keydown", (e) => { if (((e.ctrlKey || e.metaKey) && (e.key === "k" || e.key === "K")) || (e.key === "/" && !["INPUT", "TEXTAREA"].includes(document.activeElement?.tagName || ""))) { e.preventDefault(); const inp = document.getElementById("help-search-input"); if (inp) { inp.focus(); inp.select(); } } }); });})();123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384/** * Cham-OCR Technical Report — Interactive Navigation, Reading Progress & Citation Helper */(function () { "use strict";
function showPaperToast(msg) { const el = document.createElement("div"); el.className = "paper-toast"; el.innerText = msg; document.body.appendChild(el); setTimeout(() => el.remove(), 2200); }
window.copyBibtexCitation = function () { const codeEl = document.getElementById("bibtex-code"); if (!codeEl) return; navigator.clipboard.writeText(codeEl.innerText).then(() => { showPaperToast("Copied BibTeX citation to clipboard"); }); };
window.toggleMobileToc = function () { const sb = document.getElementById("paper-sidebar"); if (sb) sb.classList.toggle("mobile-open"); };
window.filterTocSections = function (query) { const q = String(query || "").trim().toLowerCase(); document.querySelectorAll("#paper-sidebar .toc-item").forEach((li) => { if (!q) { li.style.display = ""; return; } const text = li.innerText.toLowerCase(); li.style.display = text.includes(q) ? "" : "none"; }); };
document.addEventListener("DOMContentLoaded", () => { const progressBar = document.getElementById("reading-progress-bar"); const links = Array.from(document.querySelectorAll(".toc-link, .toc-sublink")); const NAV_OFFSET = 84; const sections = [];
links.forEach((link) => { const href = link.getAttribute("href"); if (href && href.startsWith("#")) { const target = document.querySelector(href); if (target) { sections.push({ link, target }); link.addEventListener("click", (e) => { e.preventDefault(); const top = target.getBoundingClientRect().top + window.pageYOffset - NAV_OFFSET; window.scrollTo({ top, behavior: "smooth" }); history.pushState(null, "", href); document.getElementById("paper-sidebar")?.classList.remove("mobile-open"); }); } } });
function updateScrollState() { const scrollTop = window.scrollY || document.documentElement.scrollTop; const docHeight = Math.max(1, document.documentElement.scrollHeight - window.innerHeight); if (progressBar) { progressBar.style.width = `${Math.min(100, Math.max(0, (scrollTop / docHeight) * 100))}%`; }
const probe = scrollTop + 125; for (let i = sections.length - 1; i >= 0; i--) { const top = sections[i].target.getBoundingClientRect().top + window.pageYOffset; if (top <= probe) { links.forEach((l) => l.classList.remove("active")); sections[i].link.classList.add("active"); break; } } }
window.addEventListener("scroll", updateScrollState, { passive: true }); updateScrollState(); });})();123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355/** * Cham Paleographic Unicode Inspector & Scholarly Transliteration Engine * Covers Unicode Cham Block (U+AA00..U+AA5F) in Canonical Brahmic Logical Order. */(function (global) { "use strict";
const CHAM_UNICODE_TABLE = { // Independent Vowels (U+AA00..U+AA05) 0xAA00: { name: "CHAM LETTER A", cat: "Independent Vowel", rom: "a", skt: "a" }, 0xAA01: { name: "CHAM LETTER I", cat: "Independent Vowel", rom: "i", skt: "i" }, 0xAA02: { name: "CHAM LETTER U", cat: "Independent Vowel", rom: "u", skt: "u" }, 0xAA03: { name: "CHAM LETTER E", cat: "Independent Vowel", rom: "é", skt: "e" }, 0xAA04: { name: "CHAM LETTER AI", cat: "Independent Vowel", rom: "ai", skt: "ai" }, 0xAA05: { name: "CHAM LETTER O", cat: "Independent Vowel", rom: "o", skt: "o" },
// Consonants (U+AA06..U+AA28) 0xAA06: { name: "CHAM LETTER KA", cat: "Base Consonant", base: "k", inherent: "a", skt: "ka" }, 0xAA07: { name: "CHAM LETTER KHA", cat: "Base Consonant", base: "kh", inherent: "a", skt: "kha" }, 0xAA08: { name: "CHAM LETTER GA", cat: "Base Consonant", base: "g", inherent: "a", skt: "ga", pair: "ꨓ (U+AA13 TA) / ꨤ (U+AA24 LA)" }, 0xAA09: { name: "CHAM LETTER GHA", cat: "Base Consonant", base: "gh", inherent: "a", skt: "gha" }, 0xAA0A: { name: "CHAM LETTER NGUE", cat: "Base Consonant", base: "ng", inherent: "â", skt: "ṅa", pair: "ꨕ (U+AA15 DA)" }, 0xAA0B: { name: "CHAM LETTER NGA", cat: "Base Consonant", base: "ng", inherent: "a", skt: "ṅga" }, 0xAA0C: { name: "CHAM LETTER CHA", cat: "Base Consonant", base: "c", inherent: "a", skt: "ca" }, 0xAA0D: { name: "CHAM LETTER CHHA", cat: "Base Consonant", base: "ch", inherent: "a", skt: "cha" }, 0xAA0E: { name: "CHAM LETTER JA", cat: "Base Consonant", base: "j", inherent: "a", skt: "ja" }, 0xAA0F: { name: "CHAM LETTER JHA", cat: "Base Consonant", base: "jh", inherent: "a", skt: "jha" }, 0xAA10: { name: "CHAM LETTER NHUE", cat: "Base Consonant", base: "ny", inherent: "â", skt: "ña" }, 0xAA11: { name: "CHAM LETTER NHA", cat: "Base Consonant", base: "ny", inherent: "a", skt: "ñja", pair: "ꨒ (U+AA12 NHJA)" }, 0xAA12: { name: "CHAM LETTER NHJA", cat: "Base Consonant", base: "nj", inherent: "a", skt: "ṇḍa", pair: "ꨑ (U+AA11 NHA)" }, 0xAA13: { name: "CHAM LETTER TA", cat: "Base Consonant", base: "t", inherent: "a", skt: "ta", pair: "ꨈ (U+AA08 GA)" }, 0xAA14: { name: "CHAM LETTER THA", cat: "Base Consonant", base: "th", inherent: "a", skt: "tha", pair: "ꨟ (U+AA1F MA)" }, 0xAA15: { name: "CHAM LETTER DA", cat: "Base Consonant", base: "d", inherent: "a", skt: "da", pair: "ꨊ (U+AA0A NGUE)" }, 0xAA16: { name: "CHAM LETTER DHA", cat: "Base Consonant", base: "dh", inherent: "a", skt: "dha" }, 0xAA17: { name: "CHAM LETTER NUE", cat: "Base Consonant", base: "n", inherent: "â", skt: "na" }, 0xAA18: { name: "CHAM LETTER NA", cat: "Base Consonant", base: "n", inherent: "a", skt: "ṇa" }, 0xAA19: { name: "CHAM LETTER DDA", cat: "Base Consonant", base: "nd", inherent: "a", skt: "nda" }, 0xAA1A: { name: "CHAM LETTER PA", cat: "Base Consonant", base: "p", inherent: "a", skt: "pa" }, 0xAA1B: { name: "CHAM LETTER PPA", cat: "Base Consonant", base: "p", inherent: "a", skt: "ppa" }, 0xAA1C: { name: "CHAM LETTER PHA", cat: "Base Consonant", base: "ph", inherent: "a", skt: "pha" }, 0xAA1D: { name: "CHAM LETTER BA", cat: "Base Consonant", base: "b", inherent: "a", skt: "ba", pair: "ꨟ (U+AA1F MA)" }, 0xAA1E: { name: "CHAM LETTER BHA", cat: "Base Consonant", base: "bh", inherent: "a", skt: "bha" }, 0xAA1F: { name: "CHAM LETTER MUE", cat: "Base Consonant", base: "m", inherent: "â", skt: "ma", pair: "ꨔ (U+AA14 THA) / ꨝ (U+AA1D BA)" }, 0xAA20: { name: "CHAM LETTER MA", cat: "Base Consonant", base: "m", inherent: "a", skt: "mma" }, 0xAA21: { name: "CHAM LETTER BBA", cat: "Base Consonant", base: "mb", inherent: "a", skt: "mba", pair: "ꨥ (U+AA25 VA)" }, 0xAA22: { name: "CHAM LETTER YA", cat: "Base Consonant", base: "y", inherent: "a", skt: "ya" }, 0xAA23: { name: "CHAM LETTER RA", cat: "Base Consonant", base: "r", inherent: "a", skt: "ra" }, 0xAA24: { name: "CHAM LETTER LA", cat: "Base Consonant", base: "l", inherent: "a", skt: "la", pair: "ꨈ (U+AA08 GA)" }, 0xAA25: { name: "CHAM LETTER VA", cat: "Base / Final Consonant", base: "w", inherent: "a", finalRom: "w", skt: "va", pair: "ꨡ (U+AA21 BBA)" }, 0xAA26: { name: "CHAM LETTER SSA", cat: "Base Consonant", base: "s", inherent: "a", skt: "śa" }, 0xAA27: { name: "CHAM LETTER SA", cat: "Base Consonant", base: "s", inherent: "a", skt: "sa" }, 0xAA28: { name: "CHAM LETTER HA", cat: "Base Consonant", base: "h", inherent: "a", skt: "ha" },
// Dependent Vowel Signs (U+AA29..U+AA32) 0xAA29: { name: "CHAM VOWEL SIGN AA", cat: "Vowel Lengthener", vowel: "ā", skt: "ā", order: 5 }, 0xAA2A: { name: "CHAM VOWEL SIGN I", cat: "Dependent Vowel (Above)", vowel: "i", skt: "i", order: 4, pair: "ꨫ (U+AA2B II)" }, 0xAA2B: { name: "CHAM VOWEL SIGN II", cat: "Dependent Vowel (Above)", vowel: "ī", skt: "ī", order: 4, pair: "ꨪ (U+AA2A I)" }, 0xAA2C: { name: "CHAM VOWEL SIGN EI", cat: "Dependent Vowel (Above)", vowel: "ei", skt: "ei", order: 4 }, 0xAA2D: { name: "CHAM VOWEL SIGN U", cat: "Dependent Vowel (Below)", vowel: "u", skt: "u", order: 4 }, 0xAA2E: { name: "CHAM VOWEL SIGN OE", cat: "Dependent Vowel (Post)", vowel: "ơ", skt: "ē", order: 4 }, 0xAA2F: { name: "CHAM VOWEL SIGN O", cat: "Pre-Base Vowel (Left)", vowel: "o", skt: "o", order: 3 }, 0xAA30: { name: "CHAM VOWEL SIGN AI", cat: "Pre-Base Vowel (Left)", vowel: "ai", skt: "ai", order: 3 }, 0xAA31: { name: "CHAM VOWEL SIGN AU", cat: "Dependent Vowel (Post)", vowel: "au", skt: "ao", order: 4 }, 0xAA32: { name: "CHAM VOWEL SIGN UE", cat: "Dependent Vowel (Below)", vowel: "ư", skt: "au", order: 4, pair: "ꨶ (U+AA36 Medial WA)" },
// Consonant Signs / Medials (U+AA33..U+AA36) 0xAA33: { name: "CHAM CONSONANT SIGN YA", cat: "Subjoined Medial", medial: "i", skt: "y", order: 2 }, 0xAA34: { name: "CHAM CONSONANT SIGN RA", cat: "Pre/Subjoined Medial", medial: "r", skt: "r", order: 1 }, 0xAA35: { name: "CHAM CONSONANT SIGN LA", cat: "Subjoined Medial", medial: "l", skt: "l", order: 1 }, 0xAA36: { name: "CHAM CONSONANT SIGN WA", cat: "Subjoined Medial", medial: "u", skt: "v", order: 2, pair: "ꨲ (U+AA32 Vowel UE)" },
// Final Consonants & Signs (U+AA40..U+AA4D) 0xAA40: { name: "CHAM LETTER FINAL K", cat: "Final Consonant", coda: "k", order: 6 }, 0xAA41: { name: "CHAM LETTER FINAL G", cat: "Final Consonant", coda: "g", order: 6 }, 0xAA42: { name: "CHAM LETTER FINAL NG", cat: "Final Consonant", coda: "ng", order: 6, pair: "ꩍ (U+AA4D Final H)" }, 0xAA43: { name: "CHAM CONSONANT SIGN FINAL NG", cat: "Combining Coda (Above)", coda: "ng", order: 6, pair: "꩝ (U+AA5D Danda) / ꩌ (U+AA4C Final M)" }, 0xAA44: { name: "CHAM LETTER FINAL CH", cat: "Final Consonant", coda: "c", order: 6 }, 0xAA45: { name: "CHAM LETTER FINAL T", cat: "Final Consonant", coda: "t", order: 6, pair: "ꩊ (U+AA4A Final L)" }, 0xAA46: { name: "CHAM LETTER FINAL N", cat: "Final Consonant", coda: "n", order: 6 }, 0xAA47: { name: "CHAM LETTER FINAL P", cat: "Final Consonant", coda: "p", order: 6 }, 0xAA48: { name: "CHAM LETTER FINAL Y", cat: "Final Consonant", coda: "y", order: 6 }, 0xAA49: { name: "CHAM LETTER FINAL R", cat: "Final Consonant", coda: "r", order: 6 }, 0xAA4A: { name: "CHAM LETTER FINAL L", cat: "Final Consonant", coda: "l", order: 6, pair: "ꩅ (U+AA45 Final T)" }, 0xAA4B: { name: "CHAM LETTER FINAL SS", cat: "Final Consonant", coda: "s", order: 6 }, 0xAA4C: { name: "CHAM CONSONANT SIGN FINAL M", cat: "Combining Coda (Anusvara)", coda: "m", order: 6, pair: "ꩃ (U+AA43 Final NG)" }, 0xAA4D: { name: "CHAM CONSONANT SIGN FINAL H", cat: "Combining Coda (Visarga)", coda: "h", order: 6, pair: "ꩂ (U+AA42 Final NG)" },
// Digits (U+AA50..U+AA59) 0xAA50: { name: "CHAM DIGIT ZERO", cat: "Cham Numeral", rom: "0" }, 0xAA51: { name: "CHAM DIGIT ONE", cat: "Cham Numeral", rom: "1" }, 0xAA52: { name: "CHAM DIGIT TWO", cat: "Cham Numeral", rom: "2" }, 0xAA53: { name: "CHAM DIGIT THREE", cat: "Cham Numeral", rom: "3" }, 0xAA54: { name: "CHAM DIGIT FOUR", cat: "Cham Numeral", rom: "4" }, 0xAA55: { name: "CHAM DIGIT FIVE", cat: "Cham Numeral", rom: "5" }, 0xAA56: { name: "CHAM DIGIT SIX", cat: "Cham Numeral", rom: "6" }, 0xAA57: { name: "CHAM DIGIT SEVEN", cat: "Cham Numeral", rom: "7" }, 0xAA58: { name: "CHAM DIGIT EIGHT", cat: "Cham Numeral", rom: "8" }, 0xAA59: { name: "CHAM DIGIT NINE", cat: "Cham Numeral", rom: "9" },
// Punctuation (U+AA5C..U+AA5F) 0xAA5C: { name: "CHAM PUNCTUATION SPIRAL", cat: "Section / Invocation", rom: "§" }, 0xAA5D: { name: "CHAM PUNCTUATION DANDA", cat: "Clause Punctuation", rom: " | " }, 0xAA5E: { name: "CHAM PUNCTUATION DOUBLE DANDA", cat: "Stanza / Section Mark", rom: " || " }, 0xAA5F: { name: "CHAM PUNCTUATION TRIPLE DANDA", cat: "Major Closure Mark", rom: " ||| " } };
function formatCodepoint(cp) { return "U+" + cp.toString(16).toUpperCase().padStart(4, "0"); }
function isChamCodepoint(cp) { return cp >= 0xAA00 && cp <= 0xAA5F; }
function isCombiningCham(cp) { return (cp >= 0xAA29 && cp <= 0xAA36) || cp === 0xAA43 || cp === 0xAA4C || cp === 0xAA4D; }
/** * Inspects a grapheme cluster or substring and returns detailed paleographic metadata. */ function inspectCluster(clusterStr) { if (!clusterStr) return { cluster: "", codepoints: [], isCanonicalOrder: true, romanized: "", warnings: [] }; const chars = Array.from(clusterStr); const codepoints = chars.map((ch) => { const cp = ch.codePointAt(0); const meta = CHAM_UNICODE_TABLE[cp] || null; return { char: ch, display: isCombiningCham(cp) ? ("◌" + ch) : ch, hex: formatCodepoint(cp), cp: cp, name: meta ? meta.name : (cp === 0x20 ? "SPACE" : `UNICODE CHARACTER (${formatCodepoint(cp)})`), category: meta ? meta.cat : (cp < 128 ? "ASCII / Punctuation" : "Extended Script"), minimalPair: meta && meta.pair ? meta.pair : null, orderSlot: meta && typeof meta.order === "number" ? meta.order : 0 }; });
// Verify canonical Brahmic ordering among combining marks attached to a base let isCanonical = true; const warnings = []; let maxSlotSeen = 0; for (let i = 0; i < codepoints.length; i++) { const item = codepoints[i]; if (i === 0 && isCombiningCham(item.cp)) { isCanonical = false; warnings.push(`Detached combining mark ${item.hex} (${item.name}) without preceding base consonant.`); } if (item.orderSlot > 0) { if (item.orderSlot < maxSlotSeen) { isCanonical = false; warnings.push(`Non-canonical mark sequence at ${item.hex}: expected Base → Medials → Pre-Vowels → Vowels → Finals.`); } maxSlotSeen = Math.max(maxSlotSeen, item.orderSlot); } }
return { cluster: clusterStr, codepoints: codepoints, isCanonicalOrder: isCanonical, romanized: transliterateCham(clusterStr), warnings: warnings }; }
/** * Converts Unicode Eastern Cham (Akhar Thrah) text into readable scholarly EFEO/Inrasara-style Romanization. */ function transliterateCham(text) { if (!text) return ""; const cps = Array.from(text).map((c) => c.codePointAt(0)); let out = ""; let i = 0;
while (i < cps.length) { const cp = cps[i]; const info = CHAM_UNICODE_TABLE[cp];
if (!info) { out += String.fromCodePoint(cp); i++; continue; }
// Standalone vowel, digit, or punctuation if (info.rom !== undefined && !info.base) { // Attach combining coda if attached directly to an independent vowel (e.g. ꨀꩌ -> am) let seg = info.rom; i++; while (i < cps.length) { const nextInfo = CHAM_UNICODE_TABLE[cps[i]]; if (nextInfo && (cps[i] === 0xAA29 || cps[i] === 0xAA43 || cps[i] === 0xAA4C || cps[i] === 0xAA4D)) { if (cps[i] === 0xAA29 && seg === "a") seg = "ā"; else if (nextInfo.coda) seg += nextInfo.coda; i++; } else { break; } } out += seg; continue; }
// Standalone final consonant glyph (if unattached or following syllable) if (info.coda && !info.base) { out += info.coda; i++; continue; }
// Base Consonant syllable assembly if (info.base) { let onset = info.base; let medials = ""; let preVowel = ""; let depVowel = ""; let hasAA = false; let coda = ""; i++;
while (i < cps.length) { const mCp = cps[i]; const mInfo = CHAM_UNICODE_TABLE[mCp]; if (!mInfo) break;
if (mInfo.medial) { medials += mInfo.medial; i++; } else if (mCp === 0xAA2F || mCp === 0xAA30) { preVowel = mInfo.vowel; i++; } else if (mCp >= 0xAA2A && mCp <= 0xAA32) { depVowel = mInfo.vowel; i++; } else if (mCp === 0xAA29) { hasAA = true; i++; } else if (mCp === 0xAA43 || mCp === 0xAA4C || mCp === 0xAA4D) { coda += mInfo.coda; i++; } else if (mCp >= 0xAA40 && mCp <= 0xAA4B) { coda += mInfo.coda; i++; break; } else if (mCp === 0xAA25) { // U+AA25 VA acts as final -w only when NOT followed by any dependent vowel/medial const lookahead = i + 1 < cps.length ? cps[i + 1] : 0; const laCombining = isCombiningCham(lookahead); if (!laCombining) { coda += "w"; i++; break; } else { break; } } else { break; } }
// Compose vowel nucleus (including compound Cham diphthongs like ꨯ + ꨮ -> o / ô, ꨯ + ꨱ -> au) let nucleus = ""; if (preVowel === "o" && depVowel === "ơ") { nucleus = "ô"; } else if (preVowel === "o" && depVowel === "au") { nucleus = "ao"; } else if (preVowel && depVowel) { nucleus = preVowel + depVowel; } else if (preVowel) { nucleus = hasAA ? (preVowel === "o" ? "ô" : preVowel) : preVowel; } else if (depVowel) { nucleus = depVowel; } else if (hasAA) { nucleus = "ā"; } else if (medials === "i") { nucleus = "ia"; medials = ""; } else if (medials === "u") { nucleus = "ua"; medials = ""; } else { nucleus = info.inherent || "a"; }
out += onset + medials + nucleus + coda; continue; }
out += String.fromCodePoint(cp); i++; }
return out.replace(/\s{2,}/g, " ").trim(); }
/** * Client-side canonical Logical Order normalizer fallback (mirrors scripts/generate_data.py). * Canonical order inside a consonant cluster: * Base + Medial Ra/La (AA34, AA35) + Medial Ya/Wa (AA33, AA36) + Pre-Vowels (AA2F, AA30) * + Other Dependent Vowels (AA2A..AA2E, AA31, AA32) + Lengthener AA (AA29) + Combining Codas (AA43, AA4C, AA4D) */ function normalizeChamLogicalClient(text) { if (!text) return ""; const cps = Array.from(text).map((c) => c.codePointAt(0)); const rankOf = (cp) => { if (cp === 0xAA34 || cp === 0xAA35) return 1; if (cp === 0xAA33 || cp === 0xAA36) return 2; if (cp === 0xAA2F || cp === 0xAA30) return 3; if ((cp >= 0xAA2A && cp <= 0xAA2E) || cp === 0xAA31 || cp === 0xAA32) return 4; if (cp === 0xAA29) return 5; if (cp === 0xAA43 || cp === 0xAA4C || cp === 0xAA4D) return 6; return 0; };
const result = []; let i = 0; while (i < cps.length) { const cp = cps[i]; if ((cp >= 0xAA06 && cp <= 0xAA28) || (cp >= 0xAA00 && cp <= 0xAA05)) { result.push(cp); i++; const marks = []; while (i < cps.length && rankOf(cps[i]) > 0) { marks.push(cps[i]); i++; } if (marks.length > 1) { marks.sort((a, b) => rankOf(a) - rankOf(b)); } // Deduplicate accidental adjacent identical combining marks for (let k = 0; k < marks.length; k++) { if (k === 0 || marks[k] !== marks[k - 1]) { result.push(marks[k]); } } } else { result.push(cp); i++; } } return String.fromCodePoint(...result); }
global.ChamLinguistics = { CHAM_UNICODE_TABLE, formatCodepoint, isChamCodepoint, isCombiningCham, inspectCluster, transliterateCham, normalizeChamLogicalClient };})(window);492 unmodified lines493494495496497498492 unmodified linesassert abs(app.CHAM_DET_UNCLIP - float(os.getenv('CHAM_DET_UNCLIP', '1.8'))) < 1e-6class TestQualityGates(unittest.TestCase):pass492 unmodified lines493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649492 unmodified linesassert abs(app.CHAM_DET_UNCLIP - float(os.getenv('CHAM_DET_UNCLIP', '1.8'))) < 1e-6def test_auto_routing_v2_tri_specialist_adjudication():calls = {'w480': 0, 'w320': 0, 'vi': 0}def fake_w480(imgs):calls['w480'] += len(imgs)# [0]: high-conf clean Cham (fast-exit, skips w320 & vi)# [1]: medium-width unseen EFEO Cham folio (lower w480 conf, out-of-order cluster -> rescued by w320)# [2]: editorial double-hyphen '--' line where w480 preserves '--' and w320 collapses to '-'# [3]: degraded historical Cham folio (conf=0.58 -> w320=0.62, pure Cham -> skips vi completely!)# [4]: severe degraded Cham folio (conf=0.28 -> w320=0.33, pure Cham -> queries vi but rejects fake Vi 0.74!)# [5]: genuine Vietnamese gloss (ASCII soup in Cham CTC -> routes cleanly to Vi!)return [('ꨀꨇꩉ ꨌꩌ', 0.985),('ꨙꨯꨳꨮ ꨚꨤꨬ', 0.84),('ꨌꩌ--ꨚꨤꨬ', 0.86),('ꨨꨣꨭꩌ ꨚꨤꨬ ꨣꩌ', 0.58),('ꨚꨯꨮ ꨆꨵꨯꨱꩃ ꨈꨣꨰ', 0.28),('56꩝ {0] 2026꩞', 0.47),], 0.0def fake_w320(imgs):calls['w320'] += len(imgs)# Called on [1], [2], [3], [4], [5] (NOT [0] because c480 >= 0.905!)return [('ꨙꨳꨯꨮ ꨚꨤꨬ ꨣꩌ', 0.94),('ꨌꩌ-ꨚꨤꨬ', 0.92),('ꨨꨣꨭꩌ ꨚꨤꨬ ꨣꩌ', 0.62),('ꨚꨯꨮ ꨆꨵꨯꨱꩃ ꨈꨣꨰ', 0.33),('5꩒꩞ 06] 2026', 0.48),], 0.0def fake_vi(imgs):calls['vi'] += len(imgs)# Called ONLY on [4] (c_conf=0.32 < 0.34) and [5] (_cham_script_ratio < 0.62) — NOT [3]!return [('38158"o) gi', 0.74),('Bản dịch cổ thư Chăm năm 2026', 0.97),], 0.0med_img = np.zeros((48, 280, 3), dtype=np.uint8)router = app.AutoRoutingOCRWrapper(fake_w480, fake_vi, cham_w320_model=fake_w320, primary_ver='v24_1_r4', w320_ver='v24_1_r3_1')out, _ = router([med_img] * 6)assert calls == {'w480': 6, 'w320': 5, 'vi': 2}, callsassert out[0][0] == 'ꨀꨇꩉ ꨌꩌ' and router.last_selected_versions[0] == 'v24_1_r4'assert out[1][0] == 'ꨙꨳꨯꨮ ꨚꨤꨬ ꨣꩌ' and router.last_selected_versions[1] == 'v24_1_r3_1'assert '--' in out[2][0] and router.last_selected_versions[2] == 'v24_1_r4'assert out[3][0] == 'ꨨꨣꨭꩌ ꨚꨤꨬ ꨣꩌ' and router.last_selected_versions[3] == 'v24_1_r3_1'assert out[4][0] == 'ꨚꨯꨮ ꨆꨵꨯꨱꩃ ꨈꨣꨰ' and router.last_selected_versions[4] == 'v24_1_r3_1'assert out[5][0] == 'Bản dịch cổ thư Chăm năm 2026' and router.last_selected_versions[5] == 'vi'info_auto = app.get_model_info('auto')assert info_auto['normalizer'] == app.NORMALIZER_VERSIONdef test_realscan_gold_v3_manifest_integrity():import jsonrepo_root = os.path.dirname(app.PROJECT_ROOT)m_path = os.path.join(repo_root, 'ocr-benchmark', 'data', 'realscan_gold_v3', 'manifest.json')assert os.path.exists(m_path), m_pathm = json.load(open(m_path, 'r', encoding='utf-8'))assert m['schema_version'] == '3.0.0'assert m['summary']['efeo_fonts_covered'] == '12/12'assert m['summary']['heldout_weights_covered'] == '6/6'assert m['summary']['total_evaluated_items'] >= 430def test_workbench_samples_models_and_corpus_zip_export():import base64import ioimport jsonimport zipfilecatalog = app.list_available_models()assert catalog['default_model'] == 'v24_1_r4'ids = {m['id']: m for m in catalog['models']}assert 'v24_1_r4' in ids and ids['v24_1_r4']['installed'] is Trueassert 'v25' in ids and ids['v25']['installed'] is Trueassert 'auto' in ids and ids['auto']['installed'] is Truesamples = app.list_curated_samples()assert len(samples) >= 4, sampless0 = app.load_curated_sample(samples[0]['id'])assert s0 is not None and s0['width'] > 50 and len(s0['image']) > 100# Verify corpus ZIP export normalizes Cham Logical Order (ꨙꨯꨳꨮ -> ꨙꨳꨯꨮ) and packs cropsdummy_crop = np.full((32, 100, 3), 240, dtype=np.uint8)ok, buf = cv2.imencode('.png', dummy_crop)assert okcrop_b64 = base64.b64encode(buf.tobytes()).decode('ascii')zip_bytes = app.build_corpus_export_zip({'documents': [{'name': 'agal_folio_01.png','status': 'Verified','model': 'v24_1_r4','lines': [{'index': 1, 'text': 'ꨙꨯꨳꨮ ꨨꨣꨭꩌ', 'confidence': 1.0, 'bbox': [10, 10, 110, 42], 'image': crop_b64, 'human_verified': True}]}]})with zipfile.ZipFile(io.BytesIO(zip_bytes), 'r') as zf:names = set(zf.namelist())assert 'train_list.txt' in namesassert 'corpus_manifest.json' in namesassert 'transcriptions/combined_corpus.md' in namestrain_line = zf.read('train_list.txt').decode('utf-8').strip()assert train_line.endswith('\tꨙꨳꨯꨮ ꨨꨣꨭꩌ'), train_linecrop_rel = train_line.split('\t', 1)[0]assert crop_rel in namesdef test_static_asset_separation_and_http_routes():import urllib.requestimport threadingfrom http.server import HTTPServerstatic_dir = os.path.join(app.PROJECT_ROOT, 'static')for rel in ('css/studio.css', 'css/research.css', 'css/help.css', 'js/studio.js', 'js/cham-keyboard.js', 'js/transliteration.js', 'js/research.js', 'js/help.js'):assert os.path.isfile(os.path.join(static_dir, *rel.split('/'))), relhttpd = HTTPServer(('127.0.0.1', 0), app.ChamOCRRequestHandler)port = httpd.server_address[1]t = threading.Thread(target=httpd.serve_forever, daemon=True)t.start()try:with urllib.request.urlopen(f'http://127.0.0.1:{port}/') as r:html = r.read().decode('utf-8')assert '/static/css/studio.css' in html and '/static/js/studio.js' in html and 'href="/help"' in htmlwith urllib.request.urlopen(f'http://127.0.0.1:{port}/help') as r:h_html = r.read().decode('utf-8')assert '/static/css/help.css' in h_html and '/static/js/help.js' in h_html and 'shortcuts-table' in h_htmlwith urllib.request.urlopen(f'http://127.0.0.1:{port}/research') as r:r_html = r.read().decode('utf-8')assert '/static/css/research.css' in r_html and 'sec7-3' in r_html and 'href="/help"' in r_htmlwith urllib.request.urlopen(f'http://127.0.0.1:{port}/static/css/studio.css') as r:css = r.read().decode('utf-8')assert '#FAF7F2' in css and '#C96442' in css# Ensure directory traversal outside /static/ is strictly blocked with HTTP 404try:urllib.request.urlopen(f'http://127.0.0.1:{port}/static/../app.py')assert False, 'Expected 404 on path traversal'except urllib.error.HTTPError as he:assert he.code == 404finally:httpd.shutdown()httpd.server_close()class TestQualityGates(unittest.TestCase):pass
28 unmodified lines29303132333481 unmodified lines11611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614728 unmodified linesfrom generate_data import normalize_unicodeMANIFEST_V2 = os.path.join(PROJECT_ROOT, "ocr-benchmark", "data", "realscan_gold_v2", "manifest.json")def sha256_file(path: str) -> str:81 unmodified linesdef main():ap = argparse.ArgumentParser(description="Ingest human-verified Studio exports into RealScan-Gold v2")ap.add_argument("--image", help="Path to original manuscript page image")ap.add_argument("--studio-json", help="Path to exported Studio JSON (cham_ocr_transcription.json or training_pairs_manifest.json)")ap.add_argument("--doc-id", help="Unique document identifier (e.g. panduranga_folio_02)")ap.add_argument("--domain", default="user_verified_manuscript", help="Archival domain tag")ap.add_argument("--verify-manifest", action="store_true", help="Verify SHA-256 integrity of all RealScan-Gold v2 assets")args = ap.parse_args()if args.verify_manifest:m = json.load(open(MANIFEST_V2, "r", encoding="utf-8"))checked = 0for d in m["documents"]:if d.get("page_relpath"):p = os.path.join(PROJECT_ROOT, d["page_relpath"].replace("/", os.sep))assert sha256_file(p) == d["page_sha256"], f"Page SHA mismatch: {p}"checked += 1for ln in d.get("lines", []):cp = os.path.join(PROJECT_ROOT, ln["crop_relpath"].replace("/", os.sep))assert sha256_file(cp) == ln["crop_sha256"], f"Crop SHA mismatch: {cp}"checked += 1print(f"✅ RealScan-Gold v2 integrity verified: {checked} files match SHA-256 100%.")returnif not (args.image and args.studio_json and args.doc_id):ap.error("Provide --image, --studio-json, and --doc-id (or --verify-manifest)")ingest_page_json(args.image, args.studio_json, args.doc_id, domain=args.domain)if __name__ == "__main__":28 unmodified lines2930313233343581 unmodified lines11711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215328 unmodified linesfrom generate_data import normalize_unicodeMANIFEST_V2 = os.path.join(PROJECT_ROOT, "ocr-benchmark", "data", "realscan_gold_v2", "manifest.json")MANIFEST_V3 = os.path.join(PROJECT_ROOT, "ocr-benchmark", "data", "realscan_gold_v3", "manifest.json")def sha256_file(path: str) -> str:81 unmodified linesdef main():ap = argparse.ArgumentParser(description="Ingest human-verified Studio exports into RealScan-Gold v2/v3")ap.add_argument("--image", help="Path to original manuscript page image")ap.add_argument("--studio-json", help="Path to exported Studio JSON (cham_ocr_transcription.json or training_pairs_manifest.json)")ap.add_argument("--doc-id", help="Unique document identifier (e.g. panduranga_folio_02)")ap.add_argument("--domain", default="user_verified_manuscript", help="Archival domain tag")ap.add_argument("--version", choices=["v2", "v3"], default="v3", help="Target RealScan-Gold version (default: v3)")ap.add_argument("--verify-manifest", action="store_true", help="Verify SHA-256 integrity of all RealScan-Gold assets")args = ap.parse_args()target_manifest = MANIFEST_V3 if args.version == "v3" else MANIFEST_V2if args.verify_manifest:m = json.load(open(target_manifest, "r", encoding="utf-8"))checked = 0for d in m["documents"]:if d.get("page_relpath"):p = os.path.join(PROJECT_ROOT, d["page_relpath"].replace("/", os.sep))assert sha256_file(p) == d["page_sha256"], f"Page SHA mismatch: {p}"checked += 1items = list(d.get("lines", []))for grp in (d.get("groups") or {}).values():items.extend(grp)for ln in items:cp = os.path.join(PROJECT_ROOT, ln["crop_relpath"].replace("/", os.sep))assert sha256_file(cp) == ln["crop_sha256"], f"Crop SHA mismatch: {cp}"checked += 1print(f"✅ RealScan-Gold {args.version} integrity verified: {checked} files match SHA-256 100%.")returnif not (args.image and args.studio_json and args.doc_id):ap.error("Provide --image, --studio-json, and --doc-id (or --verify-manifest)")ingest_page_json(args.image, args.studio_json, args.doc_id, domain=args.domain, manifest_path=target_manifest)if __name__ == "__main__":
.gitattributes+6
DESIGN.md+46-20
Dockerfile+2-2
FUTURE_WORK.md+8-9
README.md+4-2
README_VI.md+3-1
RESEARCH.md+36-6
ocr-studio/PaddleOCR/tools/infer/predict_rec.py+3-1
ocr-studio/PaddleOCR/tools/infer/utility.py+2
ocr-studio/PaddleOCR/tools/program.py+26
ocr-studio/README_STUDIO.md+18-6
ocr-studio/README_STUDIO_VI.md+18-6
ocr-studio/app.py+648-57
ocr-studio/help.htmlAdded+567
ocr-studio/index.html
ocr-studio/research.html
ocr-studio/static/css/help.cssAdded+763
ocr-studio/static/css/research.cssAdded+789
ocr-studio/static/css/studio.cssAdded+2728
ocr-studio/static/js/cham-keyboard.jsAdded+549
ocr-studio/static/js/help.jsAdded+91
ocr-studio/static/js/research.jsAdded+84
ocr-studio/static/js/studio.jsAdded
ocr-studio/static/js/transliteration.jsAdded+355
ocr-studio/static/samples/ood_agal_01_panduranga.pngAdded

Large File Pointer Details
- SHA256: 51854c9d5a6d27cf7798b5d1eaf0b01f4a3d9139871c133723bbec57e8f9d2ed
- Pointer size: 132 Bytes
- Size of remote file: 1.13 MB
ocr-studio/static/samples/ood_book_10_semibold.pngAdded

Large File Pointer Details
- SHA256: bc6bca99b3bc5f93b91ade91a5174c480f5e1351773c5827dd53eaf8a13e5f2a
- Pointer size: 132 Bytes
- Size of remote file: 1.38 MB
ocr-studio/static/samples/ood_folio_06_wijaya_2col.pngAdded

Large File Pointer Details
- SHA256: 18b11ba1d0a962fdb35ac5dcb02313fd3ccdd5d60ca897b16fac1505be162c7f
- Pointer size: 132 Bytes
- Size of remote file: 1.66 MB
ocr-studio/static/samples/ood_v3_16_curved_panduranga.pngAdded

Large File Pointer Details
- SHA256: 4cd329c2988408e0de52a974fec70ebabc728f4f299862928cb7aed528e6b6a9
- Pointer size: 132 Bytes
- Size of remote file: 1.13 MB
ocr-studio/static/samples/ood_v3_21_bilingual_campa_vi.pngAdded

Large File Pointer Details
- SHA256: 8d4904b07e85f9c51b7ee97263c9754250b00bfcb1820c31c9af7f4c9c62a9e2
- Pointer size: 132 Bytes
- Size of remote file: 1.54 MB
ocr-studio/static/samples/test_006_lvl1.pngAdded

Large File Pointer Details
- SHA256: 36ca0b380b148a22f7c0c7f6ff9d82074f4fa1f50b5509b44d8d2cd70057726f
- Pointer size: 131 Bytes
- Size of remote file: 115 kB
ocr-studio/tests/test_quality_gates.py+151
scripts/ingest_studio_to_realscan_gold.py+12-6