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 lines6676686696706716726736746756766776786796806816826836846856866876886896906916926936946951078 unmodified lines177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806485 unmodified lines229222932294229522962297229822 unmodified lines232123222323232423252326232773 unmodified lines240124022403240424052406666 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 gcpinned = 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_objreturn model_objdef get_ocr_model(version):"""Loads and caches the PaddleOCR model for the given version dynamically"""global ocr_modelsversion = validate_requested_model(version)if version in ocr_models: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 linescols = _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)if len(test_cols) > 1:cols = test_colsbreakelse:breakif 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_colsbreakelse:breakif 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 linesfor 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, :])coords.append((s_pad, e_pad))return cropped_lines, coords22 unmodified linese = split_points[idx + 1]if e - s < 15:continuecropped_lines.append(img[s:e, :])coords.append((s, e))return cropped_lines, coords73 unmodified lines"ocr_model_calls": 0}img_h, img_w, _ = img.shapeheights = [float(e - s) for s, e in base_coords]valid_heights = [h for h in heights if h <= 0.15 * img_h]666 unmodified lines6676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966971078 unmodified lines1776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803485 unmodified lines228922902291229222932294229522 unmodified lines231823192320232123222323232473 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 gcwith _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_objreturn model_objdef get_ocr_model(version):"""Loads and caches the PaddleOCR model for the given version dynamically"""global ocr_modelsversion = 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 ['en', 'fr', 'japan']:ocr_model = OfficialPaddleOCRWrapper(lang=version)1078 unmodified linescols = _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:# 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_hfor 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:continuecand_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_colslead_hdrs = list(cand_top)tail_ftrs = list(cand_bot)breakif len(cols) > 1:layout = {"reading_order": "columns", "columns": max(layout["columns"], len(cols))}order.extend(lead_hdrs)485 unmodified linesfor s, e in line_ranges:s_pad = max(0, s - pad)e_pad = min(h, e + pad)cropped_lines.append(proc_img[s_pad:e_pad, :])coords.append((s_pad, e_pad))return cropped_lines, coords22 unmodified linese = split_points[idx + 1]if e - s < 15:continuecropped_lines.append(proc_img[s:e, :])coords.append((s, e))return cropped_lines, coords73 unmodified lines"ocr_model_calls": 0}if check_inverted_polarity(img):img = 255 - imgimg_h, img_w, _ = img.shapeheights = [float(e - s) for s, e in base_coords]valid_heights = [h for h in heights if h <= 0.15 * img_h]
542 unmodified lines54354454554654754854955055155255355455555618 unmodified lines57557657757857958028 unmodified lines6096106116126136146156166176186192 unmodified lines622623624625626627628319 unmodified lines9489499509519529539549559569579582 unmodified lines961962963964965966967542 unmodified lines.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;18 unmodified lines}await dbPutFolio(folio);hydratedCount++;if (folio.id === state.activeFolioId) {await selectFolio(folio.id, { skipSyncActive: true });}28 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}`);2 unmodified lines}if (newlyAdded.length > 0 && (!state.activeFolioId || newlyAdded.length === 1)) {await selectFolio(newlyAdded[0].id, { skipSyncActive: hydratedFolios > 0 });}if (jsonFiles.length > 0 && hydratedFolios === 0) {toast("No matching folio found in queue for imported JSON");319 unmodified linesif (state.currentImageBase64) {if (emptyCard) emptyCard.style.display = "none";if (runBtn) runBtn.disabled = false;imgEl.onload = () => {state.imageWidth = imgEl.naturalWidth;state.imageHeight = imgEl.naturalHeight;applyCanvasFilters();zoomToFit();renderOverlays();renderEditor();renderDocTelemetry();2 unmodified lines}};imgEl.style.display = "block";imgEl.src = "data:image/png;base64," + state.currentImageBase64;} else {imgEl.style.display = "none";if (emptyCard) emptyCard.style.display = "flex";542 unmodified lines54354454554654754854955055155255355455555618 unmodified lines57557657757857958058128 unmodified lines6106116126136146156166176186196206212 unmodified lines624625626627628629630631632319 unmodified lines9529539549559569579589599609619629632 unmodified lines966967968969970971972973974975976977542 unmodified lines.toLowerCase();}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 && (!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, 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: 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 linesif (state.currentImageBase64) {if (emptyCard) emptyCard.style.display = "none";if (runBtn) runBtn.disabled = false;const nextSrc = "data:image/png;base64," + state.currentImageBase64;const finishImageRender = (resetZoom) => {state.imageWidth = imgEl.naturalWidth;state.imageHeight = imgEl.naturalHeight;applyCanvasFilters();if (resetZoom) zoomToFit();renderOverlays();renderEditor();renderDocTelemetry();2 unmodified lines}};imgEl.style.display = "block";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 lines1114111511161117111811191120112111221123112411251113 unmodified linesassert layout_div == {'reading_order': 'columns', 'columns': 2}, layout_divassert order_div == [0, 1, 4, 6, 2, 3, 5], order_div# 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!"# 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)1113 unmodified lines111411151116111711181119112011211122112311241125112611271128112911301131113211331113 unmodified linesassert layout_div == {'reading_order': 'columns', 'columns': 2}, layout_divassert 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_hfassert 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