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)
67 unmodified lines686970717273175 unmodified lines249250251252253254255322 unmodified lines57857958058158258358473 unmodified lines658659660661662663664665666667668147 unmodified lines816817818819820821822823847 unmodified lines16711672167316741675167616771678167916801681168216833 unmodified lines16871688168916901691169216939 unmodified lines17031704170517061707170817091710171117121713171420 unmodified lines1735173617371738173917401741174217431744174571 unmodified lines181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840277 unmodified lines21182119212021212122212321242073 unmodified lines419841994200420142024203420467 unmodified lines# Global variables for OCR modelsocr_models = {}det_model = Nonegeneric_det_model = Nonecham_det_model = None175 unmodified linesr'|[BCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz]{5,})')_ROUTER_CHAM_SOUP_RE = re.compile(r'(?:[{}\[\]_\\]|/[0-9 ]|[0-9][\uAA00-\uAA5F]|[\uAA00-\uAA5F][0-9])')_ROUTER_LATIN_VOWELS = set('aeiouyàáảãạăằắẳẵặâầấẩẫậèéẻẽẹêềếểễệìíỉĩịòóỏõọôồốổỗộơờớởỡợùúủũụưừứửữựỳýỷỹỵœæ')322 unmodified lineselse:# Line defaulted to Cham: only flip a chunk to Vi if Cham failed/garbled AND Vi decoded plausible Latin wordscham_garbled = (cr < 0.45) or (cc < 0.78) or cham_soupif 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')73 unmodified linesreturn verdef get_ocr_model(version):"""Loads and caches the PaddleOCR model for the given version dynamically"""global ocr_modelsversion = validate_requested_model(version)if version in ocr_models:return ocr_models[version]if version in ['en', 'fr', 'japan']:147 unmodified linesexcept Exception as e:print(f"Failed to warmup model: {e}")ocr_models[version] = ocr_modelreturn ocr_modeldef _ensure_generic_det_dir():"""Returns the generic PP-OCRv4 detector directory, downloading it if missing."""847 unmodified linesidxs.append(i)return (uncovered / float(total) if total else 0.0), idxsdef _split_columns(idx, rects, median_h, img_w):"""Splits a group of non-spanning line boxes into side-by-side columns using vertical gutters."""ivs = sorted(idx, key=lambda i: rects[i][0])runs = [] # [x_start, x_end, members]for i in ivs:x1, _, x2, _ = rects[i]if runs and x1 <= runs[-1][1]:runs[-1][1] = max(runs[-1][1], x2)runs[-1][2].append(i)else:3 unmodified linesmin_gutter = max(1.5 * median_h, 0.025 * img_w)cols = [runs[0]]for r in runs[1:]:if r[0] - cols[-1][1] >= min_gutter:cols.append([r[0], r[1], list(r[2])])else:cols[-1][1] = max(cols[-1][1], r[1])9 unmodified linesreturn [idx]return [c[2] for c in cols]def order_lines_reading(rects, img_w):"""Column-aware reading order for line boxes [x1, y1, x2, y2].Full-width (spanning) lines split the page into sections; inside each section, side-by-sidecolumns separated by a clear vertical gutter are read top-to-bottom, left column first.Single-column pages keep the legacy top-to-bottom order.Returns (order, layout) where layout = {"reading_order": "rows"|"columns", "columns": k}."""n = len(rects)20 unmodified linessections.append(cur)order = []for sec in sections:cols = _split_columns(sec, rects, median_h, img_w) if len(sec) >= 6 else [sec]if len(cols) > 1:layout = {"reading_order": "columns", "columns": max(layout["columns"], len(cols))}for col in cols:order.extend(sorted(col, key=yc))return order, layoutdef apply_line_quality_gates(lines_metadata, final_crops, dropped=None):71 unmodified linesif float(np.median(gray)) >= 130.0:return Falseif 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 = grayscale = 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)))) | 1se = 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):277 unmodified lines# Column-aware reading order (fixes left/right interleaving on multi-column pages)if reading_order != 'rows' and len(dt_boxes) > 1:rects = [_reading_rect(b) for b in dt_boxes] if use_poly else [_aabb(b) for b in dt_boxes]order, layout = order_lines_reading(rects, w)dt_boxes = [dt_boxes[i] for i in order]info["layout"] = layout2073 unmodified linesprint(f"📁 Corrections will be saved to: ocr-studio/data/ocr_corrections.txt")print(f"======================================================================")for _preload_ver in dict.fromkeys([DEFAULT_CHAM_MODEL, 'v24_1_r2_1_6', 'v24']):try:get_ocr_model(_preload_ver)except Exception as e:67 unmodified lines686970717273747576175 unmodified lines252253254255256257258259260322 unmodified lines58358458558658758858959073 unmodified lines664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694147 unmodified lines842843844845846847848847 unmodified lines16961697169816991700170117021703170417051706170717081709171017111712171317143 unmodified lines1718171917201721172217231724172517261727172817299 unmodified lines17391740174117421743174417451746174717481749175020 unmodified lines1771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181471 unmodified lines18861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926277 unmodified lines22042205220622072208220922102073 unmodified lines428442854286428742884289429067 unmodified lines# Global variables for OCR modelsocr_models = {}_PINNED_RESIDENT_MODELS = frozenset({"v24_1_r4", "v24_1_r3_1", "vi", "auto"})_MAX_LEGACY_RESIDENT_MODELS = int(os.getenv("MAX_LEGACY_RESIDENT_MODELS", "2"))_legacy_model_lru = []det_model = Nonegeneric_det_model = Nonecham_det_model = None175 unmodified linesr'|[BCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz]{5,})')_ROUTER_CHAM_SOUP_RE = re.compile(r'(?:[{}\[\]_\\]|/[0-9 ]|/[\uAA00-\uAA5F]|[\uAA00-\uAA5F]/'r'|[0-9][\uAA00-\uAA5F]|[\uAA00-\uAA5F][0-9]'r'|[\uAA00-\uAA4F][\uAA50-\uAA59]+|[\uAA50-\uAA59]+[\uAA00-\uAA4F])')_ROUTER_LATIN_VOWELS = set('aeiouyàáảãạăằắẳẵặâầấẩẫậèéẻẽẹêềếểễệìíỉĩịòóỏõọôồốổỗộơờớởỡợùúủũụưừứửữựỳýỷỹỵœæ')322 unmodified lineselse:# Line defaulted to Cham: only flip a chunk to Vi if Cham failed/garbled AND Vi decoded plausible Latin wordscham_garbled = (cr < 0.45) or (cc < 0.78) or cham_soupmin_vc = 0.74 if cham_soup else max(0.74, cc + 0.06)if cham_garbled and vc >= min_vc and (_is_plausible_latin_span(vt) or _has_viet_diacritics(vt)):labels.append('vi')else:labels.append('cham')73 unmodified linesreturn verdef _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']:147 unmodified linesexcept Exception as e:print(f"Failed to warmup model: {e}")return _register_loaded_model(version, ocr_model)def _ensure_generic_det_dir():"""Returns the generic PP-OCRv4 detector directory, downloading it if missing."""847 unmodified linesidxs.append(i)return (uncovered / float(total) if total else 0.0), idxsdef _split_columns(idx, rects, median_h, img_w, col_divider_x=None):"""Splits a group of non-spanning line boxes into side-by-side columns using vertical gutters or divider x."""ivs = sorted(idx, key=lambda i: rects[i][0])runs = [] # [x_start, x_end, members]for i in ivs:x1, _, x2, _ = rects[i]crosses_div = (col_divider_x is not Noneand runsand runs[-1][1] <= col_divider_x + 6and x1 >= col_divider_x - 6)if runs and x1 <= runs[-1][1] and not crosses_div:runs[-1][1] = max(runs[-1][1], x2)runs[-1][2].append(i)else:3 unmodified linesmin_gutter = max(1.5 * median_h, 0.025 * img_w)cols = [runs[0]]for r in runs[1:]:div_between = (col_divider_x is not Noneand cols[-1][1] <= col_divider_x + 8and r[0] >= col_divider_x - 8)if div_between or (r[0] - cols[-1][1] >= min_gutter):cols.append([r[0], r[1], list(r[2])])else:cols[-1][1] = max(cols[-1][1], r[1])9 unmodified linesreturn [idx]return [c[2] for c in cols]def order_lines_reading(rects, img_w, col_divider_x=None):"""Column-aware reading order for line boxes [x1, y1, x2, y2].Full-width (spanning) lines AND vertically isolated top/bottom centered headers/footers split the pageinto sections; inside each section, side-by-side columns separated by a vertical gutter or `col_divider_x`are read top-to-bottom, left column first. Single-column pages keep the legacy top-to-bottom order.Returns (order, layout) where layout = {"reading_order": "rows"|"columns", "columns": k}."""n = len(rects)20 unmodified linessections.append(cur)order = []for sec in sections: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)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)for col in cols:order.extend(sorted(col, key=yc))order.extend(tail_ftrs)else:order.extend(sorted(sec, key=yc))return order, layoutdef apply_line_quality_gates(lines_metadata, final_crops, dropped=None):71 unmodified linesif float(np.median(gray)) >= 130.0:return Falseroi_wide = gray[int(h * 0.04):max(int(h * 0.04) + 1, int(h * 0.96)),int(w * 0.04):max(int(w * 0.04) + 1, int(w * 0.96)),]roi_mid = gray[int(h * 0.14):int(h * 0.68), int(w * 0.16):int(w * 0.84)] if (h >= 180 and w >= 240) else roi_widedef _eval_roi(roi_arr, allow_sparse=False):scale = min(1.0, 900.0 / float(max(roi_arr.shape[:2])))work = (cv2.resize(roi_arr, (max(8, int(roi_arr.shape[1] * scale)), max(8, int(roi_arr.shape[0] * scale))), interpolation=cv2.INTER_AREA)if scale < 1.0 else roi_arr)wh, ww = work.shape[:2]k = int(max(7, min(21, round(min(wh, ww) / 8)))) | 1se = 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))if op_p95 < 85.0 and (fg_p992 - op_p95) > 45.0:return Trueif allow_sparse:# Sparse single-line white-on-black page (e.g. 0.1% white stroke pixels):# only fire when >=98.5% of opened background is genuinely dark (<65), so dark-framed folios# with a bright paper/palm-leaf interior (op_p985 >= 110) are never inverted.op_p985 = float(np.percentile(opened, 98.5))if op_p985 < 65.0:tophat = cv2.subtract(work, opened)if int((tophat > 60).sum()) >= 28 and float(np.percentile(tophat, 99.92)) > 55.0:return Truereturn Falseif _eval_roi(roi_mid, allow_sparse=False):return Truereturn _eval_roi(roi_wide, allow_sparse=True)def detect_vertical_column_divider(img):277 unmodified lines# Column-aware reading order (fixes left/right interleaving on multi-column pages)if reading_order != 'rows' and len(dt_boxes) > 1:rects = [_reading_rect(b) for b in dt_boxes] if use_poly else [_aabb(b) for b in dt_boxes]order, layout = order_lines_reading(rects, w, col_divider_x=col_divider_x)dt_boxes = [dt_boxes[i] for i in order]info["layout"] = layout2073 unmodified linesprint(f"📁 Corrections will be saved to: ocr-studio/data/ocr_corrections.txt")print(f"======================================================================")for _preload_ver in dict.fromkeys([DEFAULT_CHAM_MODEL, 'v24_1_r3_1']):try:get_ocr_model(_preload_ver)except Exception as e:
561 unmodified lines56256356456556656756856957057157257357457539 unmodified lines615616617618619620621622623269 unmodified lines893894895896897898899900901902903904561 unmodified linescalibrated_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) {39 unmodified lines}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`);} else if (newlyAdded.length > 1) {toast(`Added ${newlyAdded.length} manuscript folios to queue`);269 unmodified lines// =========================================================================// Queue Selection, Filtering, Drag-Reordering & Deletion// =========================================================================async function selectFolio(folioId) {const item = state.queue.find((x) => x.id === folioId);if (!item) return;// Save current active folio lines back into queue item before switchingsyncActiveFolioToQueue();state.activeFolioId = folioId;state.queue.forEach((x) => { x.active = (x.id === folioId); });561 unmodified lines56256356456556656756856957057157257357457557657757857958058158239 unmodified lines622623624625626627628629630631632269 unmodified lines902903904905906907908909910911912913914915561 unmodified linescalibrated_confidence: Number(ln.calibrated_confidence ?? ln.draft_calibrated_confidence ?? ln.confidence ?? 0),human_verified: Boolean(ln.human_verified)}));if (entry.document) folio.document = entry.document;if (entry.profiler) folio.profiler = entry.profiler;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);if (folio.id === state.activeFolioId) {state.lines = folio.lines;state.documentMeta = folio.document || null;state.profilerMeta = folio.profiler || null;}await dbPutFolio(folio);hydratedCount++;if (folio.id === state.activeFolioId) {await selectFolio(folio.id, { skipSyncActive: true });}}if (hydratedCount > 0) {39 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");} else if (hydratedFolios > 0) {toast(`Hydrated ${hydratedFolios} folio(s) from Review Queue JSON`);} else if (newlyAdded.length > 1) {toast(`Added ${newlyAdded.length} manuscript folios to queue`);269 unmodified lines// =========================================================================// Queue Selection, Filtering, Drag-Reordering & Deletion// =========================================================================async function selectFolio(folioId, options = {}) {const item = state.queue.find((x) => x.id === folioId);if (!item) return;// Save current active folio lines back into queue item before switching (unless hydrating new state onto active folio)if (!options.skipSyncActive) {syncActiveFolioToQueue();}state.activeFolioId = folioId;state.queue.forEach((x) => { x.active = (x.id === folioId); });
568 unmodified lines569570571572573574575576506 unmodified lines108310841085108610871088568 unmodified linescatalog = app.list_available_models()assert catalog['default_model'] == 'v24_1_r4'ids = {m['id']: m for m in catalog['models']}assert 'v24_1_r4' in ids and ids['v24_1_r4']['installed'] is Trueassert 'v25' in ids and ids['v25']['installed'] is Trueassert 'auto' in ids and ids['auto']['installed'] is Truesamples = app.list_curated_samples()506 unmodified linesassert ok_res['accepted_records'] == 1class TestQualityGates(unittest.TestCase):pass568 unmodified lines569570571572573574575576577578579580581506 unmodified lines10881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179568 unmodified linescatalog = app.list_available_models()assert catalog['default_model'] == 'v24_1_r4'ids = {m['id']: m for m in catalog['models']}try:import paddlepaddle_major = int(str(getattr(paddle, '__version__', '0')).split('.')[0])except Exception:paddle_major = 0assert 'v24_1_r4' in ids and ids['v24_1_r4']['installed'] is Trueassert 'v25' in ids and ids['v25']['installed'] is (not (0 < paddle_major < 3))assert 'auto' in ids and ids['auto']['installed'] is Truesamples = app.list_curated_samples()506 unmodified linesassert ok_res['accepted_records'] == 1def test_stage_v26_3_qa_p1_p2_regressions():"""Adversarial regression gate for all 4 P1 bugs and 2 P2 issues from Independent QA (2026-11-23)."""# P1-1: Studio JS active-folio JSON re-import must update state.lines before dbPutFolio and pass skipSyncActive: truejs_p = os.path.join(app.PROJECT_ROOT, 'static', 'js', 'studio.js')js_src = open(js_p, 'r', encoding='utf-8').read()assert 'selectFolio(folio.id, { skipSyncActive: true })' in js_srcassert 'if (!options.skipSyncActive)' in js_src# P1-2: Two-column page with a SHORT centered top header (and optional centered bottom footer)rects_2col_short_title = [[489, 47, 633, 83], # 0: short centered title (< 0.6 * text_w!)[95, 159, 246, 195], # 1: left 1[758, 159, 905, 197], # 2: right 1[759, 299, 917, 336], # 3: right 2[96, 305, 215, 336], # 4: left 2[759, 439, 900, 477], # 5: right 3[94, 441, 201, 475], # 6: left 3]order_open, layout_open = app.order_lines_reading(rects_2col_short_title, 1250, col_divider_x=None)assert layout_open == {'reading_order': 'columns', 'columns': 2}, layout_openassert order_open == [0, 1, 4, 6, 2, 3, 5], order_openorder_div, layout_div = app.order_lines_reading(rects_2col_short_title, 1250, col_divider_x=637)assert 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)cv2.rectangle(mixed_lead_vi, (24, 16), (170, 48), (18, 18, 18), -1) # 'Người Chăm:'cv2.rectangle(mixed_lead_vi, (215, 16), (410, 48), (18, 18, 18), -1) # 'ꨚꨗꩍ ꨓꨶꨮꩉ ?'def _mock_cham_lead(imgs):outs = []for im in imgs:w = im.shape[1]if w > 380:outs.append(('ꨚ꩗꩐꩐꩖ ꨏ/ꨮ; ꨚꨗꩍ ꨓꨶꨮꩉ ?', 0.74))elif w < 190:outs.append(('ꨚ꩗꩐꩐꩖ ꨏ/ꨮ;', 0.83))else:outs.append(('ꨚꨗꩍ ꨓꨶꨮꩉ ?', 0.96))return outs, 0.01def _mock_vi_lead(imgs):outs = []for im in imgs:w = im.shape[1]if w > 380:outs.append(('Người Chăm: 2ZwY ?', 0.88))elif w < 190:outs.append(('Người Chăm:', 0.97))else:outs.append(('2ZwY ?', 0.58))return outs, 0.01router_bi = app.AutoRoutingOCRWrapper(_mock_cham_lead, _mock_vi_lead, cham_w320_model=None, primary_ver='v24_1_r4')res_bi, vers_bi, _ = router_bi.predict_with_provenance([mixed_lead_vi])assert vers_bi == ['v24_1_r4+vi'], (res_bi, vers_bi)assert res_bi[0][0] == 'Người Chăm: ꨚꨗꩍ ꨓꨶꨮꩉ ?', res_bi# P2-1: Bounded LRU cache for non-pinned legacy modelssaved_models = dict(app.ocr_models)saved_lru = list(app._legacy_model_lru)try:app.ocr_models.clear()app._legacy_model_lru.clear()app._register_loaded_model('v24_1_r4', 'core_r4')app._register_loaded_model('v23', 'leg_23')app._register_loaded_model('v24', 'leg_24')app._register_loaded_model('v25', 'leg_25')assert 'v24_1_r4' in app.ocr_modelsassert 'v23' not in app.ocr_modelsassert app._legacy_model_lru == ['v24', 'v25']finally:app.ocr_models.clear()app.ocr_models.update(saved_models)app._legacy_model_lru[:] = saved_lruclass TestQualityGates(unittest.TestCase):pass
ocr-studio/app.py+119-33
ocr-studio/static/js/studio.js+17-6
ocr-studio/tests/test_quality_gates.py+92-1