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