Spaces:
Running
Running
Deploy Cham-OCR V26.3: Sparse Negative Polarity, Short-Header 2-Col Order, Symmetric Inline Router v2.4, Legacy LRU & Studio JSON Re-Import Fix
Browse filesFiles changed (3)
666 unmodified lines6676686696706706716726736746756766776786796806816716726736746756766776786796806816826836846856866876886896886896906916926906916926936946956966971078 unmodified lines1776177717781777177817791780178117821783178417791780178117821783178417851786178717881789179017911792179317941795179617971798179918001788178917901791179217931794179517961797179817991800180118021803180118021803485 unmodified lines2289229022912295229222932294229522 unmodified lines2318231923202324232123222323232473 unmodified lines23982399240024012402240324042405666 unmodified linesdef _register_loaded_model(version, model_obj): """Caches `model_obj` while bounding resident non-core legacy C++ predictors to prevent OOM on multi-model sweeps.""" import gc with _INFERENCE_LOCK: pinned = set(_PINNED_RESIDENT_MODELS) | {DEFAULT_CHAM_MODEL} if version not in pinned: if version in _legacy_model_lru: _legacy_model_lru.remove(version) while len(_legacy_model_lru) >= max(1, _MAX_LEGACY_RESIDENT_MODELS): evict_ver = _legacy_model_lru.pop(0) if evict_ver not in pinned and evict_ver in ocr_models: ocr_models.pop(evict_ver, None) gc.collect() _legacy_model_lru.append(version) ocr_models[version] = model_obj return model_obj pinned = set(_PINNED_RESIDENT_MODELS) | {DEFAULT_CHAM_MODEL} if version not in pinned: if version in _legacy_model_lru: _legacy_model_lru.remove(version) while len(_legacy_model_lru) >= max(1, _MAX_LEGACY_RESIDENT_MODELS): evict_ver = _legacy_model_lru.pop(0) if evict_ver not in pinned and evict_ver in ocr_models: ocr_models.pop(evict_ver, None) gc.collect() _legacy_model_lru.append(version) ocr_models[version] = model_obj return model_obj
def get_ocr_model(version): """Loads and caches the PaddleOCR model for the given version dynamically""" global ocr_models version = validate_requested_model(version) with _INFERENCE_LOCK: if version in ocr_models: if version in _legacy_model_lru: _legacy_model_lru.remove(version) _legacy_model_lru.append(version) return ocr_models[version] if version in ocr_models: if version in _legacy_model_lru: _legacy_model_lru.remove(version) _legacy_model_lru.append(version) return ocr_models[version] if version in ['en', 'fr', 'japan']: ocr_model = OfficialPaddleOCRWrapper(lang=version)1078 unmodified lines cols = _split_columns(sec, rects, median_h, img_w, col_divider_x=col_divider_x) if len(sec) >= 6 else [sec] lead_hdrs, tail_ftrs = [], [] if len(cols) == 1 and len(sec) >= 7: # Peel up to 2 vertically isolated top headers and/or bottom footers (e.g. short centered title '* ... *' # or centered page number '- 30 -') ONLY if the remaining body cleanly splits into >=2 side-by-side columns. rem = list(sec) while len(lead_hdrs) < 2 and len(rem) > 6: cand = rem[0] if all((min(rects[cand][3], rects[j][3]) - max(rects[cand][1], rects[j][1])) <= 0.15 * median_h for j in rem[1:]): lead_hdrs.append(rem.pop(0)) test_cols = _split_columns(rem, rects, median_h, img_w, col_divider_x=col_divider_x) # Test minimum-peel combinations (1 top, 1 bottom, 1+1, 2 top, 2 bottom, 2+1, 1+2) of vertically # isolated header/footer lines (e.g. short centered title '* ... *' and/or centered page number '- 30 -') # ONLY if every peeled line has no vertical overlap with the remaining body AND the body splits cleanly. def _isolated_band(peeled, body): return all( (min(rects[p][3], rects[b][3]) - max(rects[p][1], rects[b][1])) <= 0.15 * median_h for p in peeled for b in body )
for n_top, n_bot in ((1, 0), (0, 1), (1, 1), (2, 0), (0, 2), (2, 1), (1, 2)): if len(sec) - n_top - n_bot < 6: continue cand_top = sec[:n_top] cand_bot = sec[len(sec) - n_bot:] if n_bot > 0 else [] rem_body = sec[n_top:len(sec) - n_bot if n_bot > 0 else len(sec)] if _isolated_band(cand_top + cand_bot, rem_body): test_cols = _split_columns(rem_body, rects, median_h, img_w, col_divider_x=col_divider_x) if len(test_cols) > 1: cols = test_cols lead_hdrs = list(cand_top) tail_ftrs = list(cand_bot) break else: break if len(cols) == 1: rem_t = list(rem) while len(tail_ftrs) < 2 and len(rem_t) > 6: cand = rem_t[-1] if all((min(rects[cand][3], rects[j][3]) - max(rects[cand][1], rects[j][1])) <= 0.15 * median_h for j in rem_t[:-1]): tail_ftrs.insert(0, rem_t.pop()) test_cols = _split_columns(rem_t, rects, median_h, img_w, col_divider_x=col_divider_x) if len(test_cols) > 1: cols = test_cols break else: break if len(cols) == 1: lead_hdrs, tail_ftrs = [], [] if len(cols) > 1: layout = {"reading_order": "columns", "columns": max(layout["columns"], len(cols))} order.extend(lead_hdrs)485 unmodified lines for s, e in line_ranges: s_pad = max(0, s - pad) e_pad = min(h, e + pad) cropped_lines.append(img[s_pad:e_pad, :]) cropped_lines.append(proc_img[s_pad:e_pad, :]) coords.append((s_pad, e_pad)) return cropped_lines, coords
22 unmodified lines e = split_points[idx + 1] if e - s < 15: continue cropped_lines.append(img[s:e, :]) cropped_lines.append(proc_img[s:e, :]) coords.append((s, e)) return cropped_lines, coords
73 unmodified lines "ocr_model_calls": 0 } if check_inverted_polarity(img): img = 255 - img img_h, img_w, _ = img.shape heights = [float(e - s) for s, e in base_coords] valid_heights = [h for h in heights if h <= 0.15 * img_h]542 unmodified lines54354454554654654754854955055155255355355455555618 unmodified lines57557657757857958058128 unmodified lines6106116126136146156166176166186196206212 unmodified lines624625626625627628629630631632319 unmodified lines9529539549519559569579589599559609619629632 unmodified lines966967968964969970971972973974975976977542 unmodified lines .toLowerCase(); }
async function applyImportedJsonPayload(payload) { async function applyImportedJsonPayload(payload, hydratedIdSet = null) { 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) { if (!folio && entries.length === 1 && state.activeFolioId && (!targetStem || state.queue.length === 1)) { folio = state.queue.find((q) => q.id === state.activeFolioId); } if (!folio) continue;18 unmodified lines } await dbPutFolio(folio); hydratedCount++; if (hydratedIdSet) hydratedIdSet.add(folio.id); if (folio.id === state.activeFolioId) { await selectFolio(folio.id, { skipSyncActive: true }); }28 unmodified lines }
let hydratedFolios = 0; const hydratedIds = new Set(); for (const jf of jsonFiles) { try { const rawTxt = await readFileAsText(jf); const parsed = JSON.parse(rawTxt); hydratedFolios += await applyImportedJsonPayload(parsed); hydratedFolios += await applyImportedJsonPayload(parsed, hydratedIds); appendLog(`Imported transcription JSON: ${jf.name}`, "success"); } catch (err) { toast(`JSON import error (${jf.name}): ${err.message}`);2 unmodified lines }
if (newlyAdded.length > 0 && (!state.activeFolioId || newlyAdded.length === 1)) { await selectFolio(newlyAdded[0].id, { skipSyncActive: hydratedFolios > 0 }); await selectFolio(newlyAdded[0].id, { skipSyncActive: Boolean(state.activeFolioId && hydratedIds.has(state.activeFolioId)) }); } if (jsonFiles.length > 0 && hydratedFolios === 0) { toast("No matching folio found in queue for imported JSON");319 unmodified lines if (state.currentImageBase64) { if (emptyCard) emptyCard.style.display = "none"; if (runBtn) runBtn.disabled = false; imgEl.onload = () => { const nextSrc = "data:image/png;base64," + state.currentImageBase64; const finishImageRender = (resetZoom) => { state.imageWidth = imgEl.naturalWidth; state.imageHeight = imgEl.naturalHeight; applyCanvasFilters(); zoomToFit(); if (resetZoom) zoomToFit(); renderOverlays(); renderEditor(); renderDocTelemetry();2 unmodified lines } }; imgEl.style.display = "block"; imgEl.src = "data:image/png;base64," + state.currentImageBase64; if (imgEl.src === nextSrc && imgEl.complete && imgEl.naturalWidth > 0) { finishImageRender(false); } else { imgEl.onload = () => finishImageRender(true); imgEl.src = nextSrc; } } else { imgEl.style.display = "none"; if (emptyCard) emptyCard.style.display = "flex";1113 unmodified lines111411151116111711181119112011211122112311241125112611271128112911301131113211331113 unmodified lines assert layout_div == {'reading_order': 'columns', 'columns': 2}, layout_div assert order_div == [0, 1, 4, 6, 2, 3, 5], order_div
# Two-column page with BOTH a short top header AND a short centered bottom page-number footer ('- 30 -') rects_2col_hdr_and_ftr = rects_2col_short_title + [[525, 560, 595, 592]] order_hf, layout_hf = app.order_lines_reading(rects_2col_hdr_and_ftr, 1250, col_divider_x=None) assert layout_hf == {'reading_order': 'columns', 'columns': 2}, layout_hf assert order_hf == [0, 1, 4, 6, 2, 3, 5, 7], order_hf
# P1-3: Sparse single-line white-on-black negative (~0.14% bright stroke pixels at left x=70..275) sparse_neg = np.zeros((220, 1050, 3), dtype=np.uint8) for x in range(72, 260, 22): cv2.line(sparse_neg, (x, 96), (x + 12, 122), (248, 248, 248), 2) assert app.check_inverted_polarity(sparse_neg) is True, "Missed sparse 0.14%-ink white-on-black negative!" assert app.check_inverted_polarity(np.zeros((220, 1050, 3), dtype=np.uint8)) is False, "False positive on pure black blank!" adap_crops, adap_coords = app.segment_lines_adaptive(sparse_neg) assert len(adap_crops) == 1 and float(np.median(adap_crops[0])) > 200.0, "segment_lines_adaptive failed to invert negative crop!"
# P1-4: Leading-Vietnamese + trailing-Cham inline split where Cham CTC outputs glued Cham-digit soup ('ꨚ꩗꩐꩐꩖ ꨏ/ꨮ;') mixed_lead_vi = np.full((64, 440, 3), 252, dtype=np.uint8)ocr-studio/app.py+42-43
ocr-studio/static/js/studio.js+17-7
ocr-studio/tests/test_quality_gates.py+8