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 (5)
18 unmodified lines192021222324252618 unmodified linesCOPY requirements.txt /app/requirements.txtRUN pip install --no-cache-dir -r requirements.txt# Force cache bust for updated app code & Pipeline v26.3.1 + Studio JSON Re-Import Fix + Static Cache-BustingRUN echo "Cache bust 2026-11-23T09:00:00Z - Cham-OCR Studio: Pipeline v26.3.1 + Studio Multi-Folio JSON Re-Import + Cache-Control no-store"# Copy application filesCOPY . /app18 unmodified lines192021222324252618 unmodified linesCOPY requirements.txt /app/requirements.txtRUN pip install --no-cache-dir -r requirements.txt# Force cache bust for updated app code & Pipeline v26.3.2 + Studio Auto-Retry + Short 2-Col + Sparse Corner NegativeRUN echo "Cache bust 2026-11-23T10:30:00Z - Cham-OCR Studio: Pipeline v26.3.2 + Short 2x2 Grid + Scale-Invariant Negative + Valley/Adaptive Trim"# Copy application filesCOPY . /app
682 unmodified lines683684685686687688689690691692693694695696697277 unmodified lines975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610072 unmodified lines10101011101210131014101510161017101810191020102110221023102410251026520 unmodified lines1547154815491550155115521553155415551556155715581559105 unmodified lines1665166616671668166916701671167257 unmodified lines17301731173217331734173517362 unmodified lines1739174017411742174317448 unmodified lines175317541755175617571758175913 unmodified lines1773177417751776177717781779178017814 unmodified lines178617871788178917901791179294 unmodified lines1887188818891890189118921893189418954 unmodified lines190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923106 unmodified lines20302031203220332034203596 unmodified lines2132213321342135213621372138430 unmodified lines256925702571257225732574115 unmodified lines2690269126922693269426952696153 unmodified lines28502851285228532854285528561196 unmodified lines4053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408176 unmodified lines41584159416041614162416341644165416641674168682 unmodified linesdef 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)277 unmodified lineson wavy / perspective / tightly spaced pages where Cham-DBNet finds 8/8, 7/8, 5/5, 14/14)."""global cham_det_model, _cham_det_failedif cham_det_model is not None or _cham_det_failed:return cham_det_modelcham_det_dir = CHAM_DET_DIRhas_pdmodel = os.path.exists(os.path.join(cham_det_dir, "inference.pdmodel"))has_json = os.path.exists(os.path.join(cham_det_dir, "inference.json"))has_cham_model = os.path.exists(os.path.join(cham_det_dir, "inference.pdiparams")) and (has_pdmodel or has_json)if not has_cham_model:_cham_det_failed = Truereturn Noneif not has_pdmodel and has_json:try:import paddle as _paddlemajor_ver = int(str(getattr(_paddle, "__version__", "0")).split(".")[0])except Exception:major_ver = 0if major_ver < 3:_cham_det_failed = Trueprint("⚠️ Cham DBNet is PIR (.json) and requires Paddle >= 3.0; skipping on Paddle 2.x.")return Nonetry:cham_det_model = _build_text_detector(cham_det_dir, CHAM_DET_DB_THRESH, CHAM_DET_BOX_THRESH, CHAM_DET_UNCLIP,box_type=CHAM_DET_BOX_TYPE)print(f"🌟 Cham Text Detection model ready: {cham_det_dir} (box_type={CHAM_DET_BOX_TYPE})")except Exception as e:_cham_det_failed = Trueprint(f"⚠️ Failed to load Cham DBNet detector ({e}); legacy generic detector only.")return cham_det_modeldef get_det_model():"""Loads and caches the primary PaddleOCR TextDetector model for DBNet segmentation.2 unmodified lines'cham' uses the Cham-DBNet detector as primary (falls back to generic if it cannot load)."""global det_modelif det_model is not None:return det_modelif DET_MODE == 'cham' and get_cham_det_model() is not None:det_model = get_cham_det_model()det_model_info.update({"name": "cham_dbnet", "dir": CHAM_DET_DIR, "mode": DET_MODE})else:det_model = get_generic_det_model()det_model_info.update({"name": "generic_ppocrv4_dbnet", "dir": _ensure_generic_det_dir(), "mode": DET_MODE})if DET_MODE == 'hybrid':get_cham_det_model() # preload so the first hard page doesn't pay the load costreturn det_modeldef _quad_centerline(pts):"""(y-at-x function, perpendicular thickness) of a 4-point text quad (tl, tr, br, bl)."""520 unmodified lines"""Invokes a recognizer/router and returns (results, selected_versions, elapsed) without post-OCR script guessing."""if not img_list:return [], [], 0.0if hasattr(ocr_model, "predict_with_provenance"):res, sel_vers, elapsed = ocr_model.predict_with_provenance(img_list)return res, list(sel_vers), elapsedif hasattr(ocr_model, "last_selected_versions"):ocr_model.last_selected_versions = []res, elapsed = ocr_model(img_list)attr_vers = list(getattr(ocr_model, "last_selected_versions", None) or [])if len(attr_vers) == len(res):return res, attr_vers, elapsedsingle_ver = resolve_actual_model_version(model_ver)105 unmodified lines"ink_ratio": ink_px / float(max(1, h * w)), "num_components": len(keep), "shape": (h, w)}def is_blank_page(ink):"""True when the page has no text-like ink (blank / near-blank paper)."""return ink["num_components"] < 4 or ink["ink_ratio"] < 0.0003def compute_uncovered_ink(ink, polygons, median_line_h=None):"""Fraction of text-like ink (area-weighted) whose component centroid lies outside every detected line.57 unmodified lineselse:cols[-1][1] = max(cols[-1][1], r[1])cols[-1][2].extend(r[2])if len(cols) < 2 or any(len(c[2]) < 3 for c in cols):return [idx]# Columns must sit side by side (overlapping vertical extents), not be stacked blocksfor a, b in zip(cols, cols[1:]):2 unmodified linesinter = max(0.0, min(ay2, by2) - max(ay1, by1))if inter < 0.5 * min(ay2 - ay1, by2 - by1):return [idx]return [c[2] for c in cols]def order_lines_reading(rects, img_w, col_divider_x=None):8 unmodified linesyc = lambda i: (rects[i][1] + rects[i][3]) / 2.0order_y = sorted(range(n), key=yc)layout = {"reading_order": "rows", "columns": 1}if n < 6:return order_y, layoutmedian_h = float(np.median([r[3] - r[1] for r in rects]))x0 = min(r[0] for r in rects)13 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:# 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.4 unmodified lines)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 []94 unmodified linesint(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)4 unmodified linesse = 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):106 unmodified linesreturn cv2.cvtColor(bin_inv, cv2.COLOR_GRAY2BGR)return crop_imgdef _aabb(poly):pts = np.array(poly, dtype=np.float32)return float(np.min(pts[:, 0])), float(np.min(pts[:, 1])), float(np.max(pts[:, 0])), float(np.max(pts[:, 1]))96 unmodified linesinfo["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, col_divider_x=col_divider_x)430 unmodified linesxmax = max(stats[i][0] + stats[i][2] for i in best_cluster)ymin = min(stats[i][1] for i in best_cluster)ymax = max(stats[i][1] + stats[i][3] for i in best_cluster)else:xmin, xmax = 0, img_wymin, ymax = int(s), int(e)115 unmodified lines# Phase 3: Pass 1 Batch Recognitiont_pass1 = time.time()if pass1_candidates:imgs = [preprocess_crop_for_rec(c["crop_img"]) for c in pass1_candidates]# ocr_model accepts a list of images and returns list of (text, conf)# However, PaddleOCR's predict() might fail if empty list or invalid dims.valid_imgs = []153 unmodified linespending_boxes.add(c_box)if exec_candidates:imgs = [preprocess_crop_for_rec(c["crop_img"]) for c in exec_candidates]valid_imgs = []valid_indices = []for i, m in enumerate(imgs):1196 unmodified linesself.send_json_response({'error': 'Unable to read image (unsupported format or corrupted base64 payload)'}, 400)return# Serialize Paddle C++ model loading & inference safely while keeping HTTP GET/health non-blockingwith _INFERENCE_LOCK:t_model = time.time()try:get_ocr_model(model_ver)except UnknownModelError as ume:self.send_json_response({'error': str(ume), 'allowed_models': list(ADVERTISED_MODEL_IDS)}, 400)returnexcept Exception as e:import tracebackprint(f"❌ Error loading OCR model '{model_ver}': {traceback.format_exc()}")self.send_json_response({'error': f'Model loading failure ({model_ver}): {e}'}, 500)returnprint(f"⏱️ Loaded model in: {time.time() - t_model:.4f}s")try:response = run_ocr_pipeline(img, model_ver=model_ver, method=method, threshold=threshold,gap=gap, win=win, reading_order=reading_order, t_start=t_start)except Exception as e:import tracebackprint(f"❌ Error during OCR pipeline: {traceback.format_exc()}")self.send_json_response({'error': f'OCR transcription engine error: {e}'}, 500)returnt_send = time.time()self.send_json_response(response)76 unmodified linesreturntry:with _INFERENCE_LOCK:ocr = get_ocr_model(model_ver)res, sel_vers, _ = invoke_recognizer_with_provenance(ocr, [preprocess_crop_for_rec(crop_img)], model_ver=model_ver)pred_text, conf = res[0] if res else ("", 0.0)except UnknownModelError as ume:self.send_json_response({'error': str(ume), 'allowed_models': list(ADVERTISED_MODEL_IDS)}, 400)682 unmodified lines683684685686687688689690691692693694695696697698699700701277 unmodified lines97998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110122 unmodified lines101510161017101810191020102110221023102410251026102710281029103010311032520 unmodified lines15531554155515561557155815591560156115621563156415651566105 unmodified lines1672167316741675167616771678167916801681168216831684168516861687168816891690169157 unmodified lines17491750175117521753175417552 unmodified lines175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817898 unmodified lines179817991800180118021803180413 unmodified lines1818181918201821182218231824182518264 unmodified lines183118321833183418351836183794 unmodified lines19321933193419351936193719381939194019411942194319444 unmodified lines194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978106 unmodified lines2085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211396 unmodified lines22102211221222132214221522162217430 unmodified lines2648264926502651265226532654265526562657265826592660266126622663115 unmodified lines2779278027812782278327842785153 unmodified lines29392940294129422943294429451196 unmodified lines414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416976 unmodified lines42464247424842494250425142524253425442554256682 unmodified linesdef get_ocr_model(version):"""Loads and caches the PaddleOCR model for the given version dynamically (thread-safe via RLock)."""with _INFERENCE_LOCK:return _get_ocr_model_unlocked(version)def _get_ocr_model_unlocked(version):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)277 unmodified lineson wavy / perspective / tightly spaced pages where Cham-DBNet finds 8/8, 7/8, 5/5, 14/14)."""global cham_det_model, _cham_det_failedwith _INFERENCE_LOCK:if cham_det_model is not None or _cham_det_failed:return cham_det_modelcham_det_dir = CHAM_DET_DIRhas_pdmodel = os.path.exists(os.path.join(cham_det_dir, "inference.pdmodel"))has_json = os.path.exists(os.path.join(cham_det_dir, "inference.json"))has_cham_model = os.path.exists(os.path.join(cham_det_dir, "inference.pdiparams")) and (has_pdmodel or has_json)if not has_cham_model:_cham_det_failed = Truereturn Noneif not has_pdmodel and has_json:try:import paddle as _paddlemajor_ver = int(str(getattr(_paddle, "__version__", "0")).split(".")[0])except Exception:major_ver = 0if major_ver < 3:_cham_det_failed = Trueprint("⚠️ Cham DBNet is PIR (.json) and requires Paddle >= 3.0; skipping on Paddle 2.x.")return Nonetry:cham_det_model = _build_text_detector(cham_det_dir, CHAM_DET_DB_THRESH, CHAM_DET_BOX_THRESH, CHAM_DET_UNCLIP,box_type=CHAM_DET_BOX_TYPE)print(f"🌟 Cham Text Detection model ready: {cham_det_dir} (box_type={CHAM_DET_BOX_TYPE})")except Exception as e:_cham_det_failed = Trueprint(f"⚠️ Failed to load Cham DBNet detector ({e}); legacy generic detector only.")return cham_det_modeldef get_det_model():"""Loads and caches the primary PaddleOCR TextDetector model for DBNet segmentation.2 unmodified lines'cham' uses the Cham-DBNet detector as primary (falls back to generic if it cannot load)."""global det_modelwith _INFERENCE_LOCK:if det_model is not None:return det_modelif DET_MODE == 'cham' and get_cham_det_model() is not None:det_model = get_cham_det_model()det_model_info.update({"name": "cham_dbnet", "dir": CHAM_DET_DIR, "mode": DET_MODE})else:det_model = get_generic_det_model()det_model_info.update({"name": "generic_ppocrv4_dbnet", "dir": _ensure_generic_det_dir(), "mode": DET_MODE})if DET_MODE == 'hybrid':get_cham_det_model() # preload so the first hard page doesn't pay the load costreturn det_modeldef _quad_centerline(pts):"""(y-at-x function, perpendicular thickness) of a 4-point text quad (tl, tr, br, bl)."""520 unmodified lines"""Invokes a recognizer/router and returns (results, selected_versions, elapsed) without post-OCR script guessing."""if not img_list:return [], [], 0.0with _INFERENCE_LOCK:if hasattr(ocr_model, "predict_with_provenance"):res, sel_vers, elapsed = ocr_model.predict_with_provenance(img_list)return res, list(sel_vers), elapsedif hasattr(ocr_model, "last_selected_versions"):ocr_model.last_selected_versions = []res, elapsed = ocr_model(img_list)attr_vers = list(getattr(ocr_model, "last_selected_versions", None) or [])if len(attr_vers) == len(res):return res, attr_vers, elapsedsingle_ver = resolve_actual_model_version(model_ver)105 unmodified lines"ink_ratio": ink_px / float(max(1, h * w)), "num_components": len(keep), "shape": (h, w)}def is_blank_page(ink):"""True when the page has no text-like ink (blank / near-blank paper), while preserving a compact sparse text line on a large canvas."""if ink["num_components"] < 4:return Trueif ink["ink_ratio"] >= 0.0003:return False# Compact single-line text cluster on a very large page (e.g. 500-800px ink on a 3000x2000 canvas):cents = ink.get("centroids")h = (ink.get("shape") or (1000, 1000))[0]if ink["num_components"] >= 5 and ink.get("ink_px", 0) >= 300 and cents is not None and len(cents) >= 5:ys = np.sort(cents[:, 1])y_span = float(ys[int(round(0.85 * (len(ys) - 1)))] - ys[int(round(0.15 * (len(ys) - 1)))])if y_span <= max(64.0, 0.12 * float(h)):return Falsereturn Truedef compute_uncovered_ink(ink, polygons, median_line_h=None):"""Fraction of text-like ink (area-weighted) whose component centroid lies outside every detected line.57 unmodified lineselse:cols[-1][1] = max(cols[-1][1], r[1])cols[-1][2].extend(r[2])if len(cols) < 2 or any(len(c[2]) < 2 for c in cols):return [idx]# Columns must sit side by side (overlapping vertical extents), not be stacked blocksfor a, b in zip(cols, cols[1:]):2 unmodified linesinter = max(0.0, min(ay2, by2) - max(ay1, by1))if inter < 0.5 * min(ay2 - ay1, by2 - by1):return [idx]# Short-column anti-false-column guard: when any column has only 2 lines (e.g. 2x2 grid),# require strict left-margin alignment, wide inter-column gutter (or explicit divider), bounded# column width, and 1-to-1 row Y-overlap so split word fragments on a 1-col page never form columns.if any(len(c[2]) == 2 for c in cols):strict_gutter = max(3.5 * median_h, 0.12 * img_w)for c in cols:if (c[1] - c[0]) > 0.45 * img_w:return [idx]xs1 = [rects[i][0] for i in c[2]]if max(xs1) - min(xs1) > max(18.0, 1.2 * median_h):return [idx]for a, b in zip(cols, cols[1:]):div_ab = (col_divider_x is not Noneand a[1] <= col_divider_x + 8and b[0] >= col_divider_x - 8)if not (div_ab or (b[0] - a[1] >= strict_gutter)):return [idx]other_boxes_for = lambda k: [j for m, c in enumerate(cols) if m != k for j in c[2]]for k, c in enumerate(cols):if len(c[2]) == 2:others = other_boxes_for(k)for i in c[2]:if not any((min(rects[i][3], rects[j][3]) - max(rects[i][1], rects[j][1])) > 0.35 * median_h for j in others):return [idx]return [c[2] for c in cols]def order_lines_reading(rects, img_w, col_divider_x=None):8 unmodified linesyc = lambda i: (rects[i][1] + rects[i][3]) / 2.0order_y = sorted(range(n), key=yc)layout = {"reading_order": "rows", "columns": 1}if n < 4:return order_y, layoutmedian_h = float(np.median([r[3] - r[1] for r in rects]))x0 = min(r[0] for r in rects)13 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) >= 4 else [sec]lead_hdrs, tail_ftrs = [], []if len(cols) == 1 and len(sec) >= 5:# 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.4 unmodified lines)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 < 4:continuecand_top = sec[:n_top]cand_bot = sec[len(sec) - n_bot:] if n_bot > 0 else []94 unmodified linesint(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_edge = gray[int(h * 0.015):max(int(h * 0.015) + 1, int(h * 0.985)),int(w * 0.015):max(int(w * 0.015) + 1, int(w * 0.985)),]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_dense=True, 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)4 unmodified linesse = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (k, k))opened = cv2.morphologyEx(work, cv2.MORPH_OPEN, se)if allow_dense: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:# Canvas-size-invariant sparse white-on-black text detector (e.g. 0.01%-0.15% white stroke pixels in a corner):# only fire when >=98.5% of opened background is genuinely dark (<65), so dark-framed folios or bright pages on# dark tables (op_p985 >= 110..255) are never inverted; require multi-component high-contrast Top-Hat strokes.op_p985 = float(np.percentile(opened, 98.5))if op_p985 < 65.0:tophat = cv2.subtract(work, opened)if int((tophat > 60).sum()) >= 24 and int((tophat > 110).sum()) >= 10:nth, _, th_stats, _ = cv2.connectedComponentsWithStats((tophat > 75).astype(np.uint8), connectivity=8)valid_th = sum(1 for i in range(1, nth) if int(th_stats[i, cv2.CC_STAT_AREA]) >= 4)if valid_th >= 3:return Truereturn Falseif _eval_roi(roi_mid, allow_dense=True, allow_sparse=False):return Trueif _eval_roi(roi_wide, allow_dense=True, allow_sparse=True):return Truereturn _eval_roi(roi_edge, allow_dense=False, allow_sparse=True)def detect_vertical_column_divider(img):106 unmodified linesreturn cv2.cvtColor(bin_inv, cv2.COLOR_GRAY2BGR)return crop_imgdef _trim_horizontal_whitespace_for_rec(crop_img):"""Trims wide blank horizontal page margins on projection-based line strips (valley/adaptive)so short lines + trailing punctuation (e.g. '?') are not crushed when resized to W<=480."""if crop_img is None or crop_img.size == 0:return crop_imgch, cw = crop_img.shape[:2]if ch < 8 or cw < 48 or (cw / float(max(1, ch))) <= 6.5:return crop_imggray = cv2.cvtColor(crop_img, cv2.COLOR_BGR2GRAY) if len(crop_img.shape) == 3 else crop_imgink_cols = np.where((gray < 225).sum(axis=0) >= 1)[0]if len(ink_cols) == 0:return crop_imgx0, x1 = int(ink_cols[0]), int(ink_cols[-1])if (x1 - x0 + 1) >= 0.72 * cw:return crop_imgpad_x = max(14, int(round(0.55 * ch)))tx0 = max(0, x0 - pad_x)tx1 = min(cw, x1 + 1 + pad_x)if tx1 - tx0 < 16:return crop_imgreturn crop_img[:, tx0:tx1]def _aabb(poly):pts = np.array(poly, dtype=np.float32)return float(np.min(pts[:, 0])), float(np.min(pts[:, 1])), float(np.max(pts[:, 0])), float(np.max(pts[:, 1]))96 unmodified linesinfo["column_divider_x"] = int(col_divider_x)def _detect(detector):with _INFERENCE_LOCK: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, col_divider_x=col_divider_x)430 unmodified linesxmax = max(stats[i][0] + stats[i][2] for i in best_cluster)ymin = min(stats[i][1] for i in best_cluster)ymax = max(stats[i][1] + stats[i][3] for i in best_cluster)# Extend horizontal bbox to include adjacent small punctuation (e.g. '?', '.', '꩝' with area < 25)p_reach = max(24, int(round(1.1 * median_line_height)))band_x0 = max(0, int(xmin) - p_reach)band_x1 = min(img_w, int(xmax) + p_reach)band_gray = gray[max(0, int(ymin) - 2):min(img_h, int(ymax) + 3), band_x0:band_x1]if band_gray.size > 0:p_cols = np.where((band_gray < 215).sum(axis=0) >= 2)[0]if len(p_cols) > 0:xmin = min(int(xmin), band_x0 + int(p_cols[0]))xmax = max(int(xmax), band_x0 + int(p_cols[-1]) + 1)else:xmin, xmax = 0, img_wymin, ymax = int(s), int(e)115 unmodified lines# Phase 3: Pass 1 Batch Recognitiont_pass1 = time.time()if pass1_candidates:imgs = [_trim_horizontal_whitespace_for_rec(preprocess_crop_for_rec(c["crop_img"])) for c in pass1_candidates]# ocr_model accepts a list of images and returns list of (text, conf)# However, PaddleOCR's predict() might fail if empty list or invalid dims.valid_imgs = []153 unmodified linespending_boxes.add(c_box)if exec_candidates:imgs = [_trim_horizontal_whitespace_for_rec(preprocess_crop_for_rec(c["crop_img"])) for c in exec_candidates]valid_imgs = []valid_indices = []for i, m in enumerate(imgs):1196 unmodified linesself.send_json_response({'error': 'Unable to read image (unsupported format or corrupted base64 payload)'}, 400)return# C++ predictors lock internally via _INFERENCE_LOCK so OpenCV deskew/cropping/PNG encoding run concurrentlyt_model = time.time()try:get_ocr_model(model_ver)except UnknownModelError as ume:self.send_json_response({'error': str(ume), 'allowed_models': list(ADVERTISED_MODEL_IDS)}, 400)returnexcept Exception as e:import tracebackprint(f"❌ Error loading OCR model '{model_ver}': {traceback.format_exc()}")self.send_json_response({'error': f'Model loading failure ({model_ver}): {e}'}, 500)returnprint(f"⏱️ Loaded model in: {time.time() - t_model:.4f}s")try:response = run_ocr_pipeline(img, model_ver=model_ver, method=method, threshold=threshold,gap=gap, win=win, reading_order=reading_order, t_start=t_start)except Exception as e:import tracebackprint(f"❌ Error during OCR pipeline: {traceback.format_exc()}")self.send_json_response({'error': f'OCR transcription engine error: {e}'}, 500)returnt_send = time.time()self.send_json_response(response)76 unmodified linesreturntry:pre_crop = preprocess_crop_for_rec(crop_img)ocr = get_ocr_model(model_ver)res, sel_vers, _ = invoke_recognizer_with_provenance(ocr, [pre_crop], model_ver=model_ver)pred_text, conf = res[0] if res else ("", 0.0)except UnknownModelError as ume:self.send_json_response({'error': str(ume), 'allowed_models': list(ADVERTISED_MODEL_IDS)}, 400)
7 unmodified lines891011121314723 unmodified lines7387397407417427437447457 unmodified lines<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin><link href="https://fonts.googleapis.com/css2?family=Google+Sans+Flex:wght@300..800&family=JetBrains+Mono:wght@400;500;600;700&family=Noto+Sans+Cham:wght@400;600;700&display=swap" rel="stylesheet"><link rel="stylesheet" href="/static/css/studio.css?v=26.3.1"></head><body>723 unmodified lines<div class="toast-stack" id="toast-stack"></div><!-- Modular Studio Scripts --><script src="/static/js/transliteration.js?v=26.3.1"></script><script src="/static/js/cham-keyboard.js?v=26.3.1"></script><script src="/static/js/studio.js?v=26.3.1"></script></body></html>7 unmodified lines891011121314723 unmodified lines7387397407417427437447457 unmodified lines<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin><link href="https://fonts.googleapis.com/css2?family=Google+Sans+Flex:wght@300..800&family=JetBrains+Mono:wght@400;500;600;700&family=Noto+Sans+Cham:wght@400;600;700&display=swap" rel="stylesheet"><link rel="stylesheet" href="/static/css/studio.css?v=26.3.2"></head><body>723 unmodified lines<div class="toast-stack" id="toast-stack"></div><!-- Modular Studio Scripts --><script src="/static/js/transliteration.js?v=26.3.2"></script><script src="/static/js/cham-keyboard.js?v=26.3.2"></script><script src="/static/js/studio.js?v=26.3.2"></script></body></html>
1222 unmodified lines1223122412251226122712284 unmodified lines1233123412351236123712381239603 unmodified lines18431844184518461847184818491222 unmodified lines// =========================================================================// Single-Folio & Automated Batch OCR Execution// =========================================================================async function executeOcrRequestForFolio(folioItem) {if (!folioItem.image) {const dbRec = await dbGetFolio(folioItem.id);4 unmodified linesconst modelSelect = document.getElementById("model-select");const chosenModel = modelSelect ? modelSelect.value : (folioItem.model || "v24_1_r4");const res = await fetch("/ocr", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({603 unmodified linestoast("Transcribing selected manuscript region...");try {const res = await fetch("/ocr_crop", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({1222 unmodified lines1223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112524 unmodified lines1257125812591260126112621263603 unmodified lines18671868186918701871187218731222 unmodified lines// =========================================================================// Single-Folio & Automated Batch OCR Execution// =========================================================================async function fetchWithTransientRetry(url, init, maxRetries = 1) {let lastErr = null;for (let attempt = 0; attempt <= maxRetries; attempt++) {try {const res = await fetch(url, init);if ((res.status === 502 || res.status === 503 || res.status === 504) && attempt < maxRetries) {appendLog(`Transient HTTP ${res.status} on ${url}; retrying in 900ms...`, "warn");await new Promise((r) => setTimeout(r, 900));continue;}return res;} catch (err) {lastErr = err;if (attempt < maxRetries) {appendLog(`Transient network error on ${url}; retrying in 900ms...`, "warn");await new Promise((r) => setTimeout(r, 900));continue;}throw lastErr;}}throw lastErr || new Error(`Request to ${url} failed`);}async function executeOcrRequestForFolio(folioItem) {if (!folioItem.image) {const dbRec = await dbGetFolio(folioItem.id);4 unmodified linesconst modelSelect = document.getElementById("model-select");const chosenModel = modelSelect ? modelSelect.value : (folioItem.model || "v24_1_r4");const res = await fetchWithTransientRetry("/ocr", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({603 unmodified linestoast("Transcribing selected manuscript region...");try {const res = await fetchWithTransientRetry("/ocr_crop", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({
1181 unmodified lines1182118311841185118611871181 unmodified linesapp._legacy_model_lru[:] = saved_lruclass TestQualityGates(unittest.TestCase):pass1181 unmodified lines1182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381181 unmodified linesapp._legacy_model_lru[:] = saved_lrudef test_stage_v26_3_2_adversarial_regressions():"""Adversarial regression gate for Pipeline v26.3.2 (5-line 2x2 grid, mega-canvas corner negative, valley/adaptive trim, transient retry)."""# 1. Short 5-line two-column layout (1 centered title + 2 rows x 2 cols) -> columns: 2, order [0, 1, 4, 2, 3]rects_5line_2col = [[514, 54, 671, 79], # 0: short centered header[123, 234, 275, 273], # 1: left row 1[755, 241, 953, 270], # 2: right row 1[754, 409, 896, 448], # 3: right row 2[125, 413, 291, 446], # 4: left row 2]ord_5, lay_5 = app.order_lines_reading(rects_5line_2col, 1250)assert lay_5 == {'reading_order': 'columns', 'columns': 2}, lay_5assert ord_5 == [0, 1, 4, 2, 3], ord_5# Anti-false-column guards: narrow word-gap fragments and unaligned right starts must remain 1-column rows_, lay_gap = app.order_lines_reading([[80, 100, 320, 134], [385, 102, 690, 135], [82, 170, 340, 204], [410, 172, 710, 205]], 1000)assert lay_gap == {'reading_order': 'rows', 'columns': 1}, lay_gap_, lay_stag = app.order_lines_reading([[80, 100, 250, 134], [520, 102, 720, 135], [82, 170, 260, 204], [640, 172, 830, 205]], 1000)assert lay_stag == {'reading_order': 'rows', 'columns': 1}, lay_stag# 2. Canvas-size-invariant sparse corner negative (1600x980 with ~0.015% corner strokes) vs single dust speckcorner_neg = np.zeros((980, 1600, 3), dtype=np.uint8)for k in range(6):x = 1260 + k * 24cv2.line(corner_neg, (x, 68), (x + 11, 98), (245, 245, 245), 2)assert app.check_inverted_polarity(corner_neg) is True, "Missed sparse top-right corner negative on 1600x980!"assert app.is_blank_page(app.analyze_text_ink(corner_neg)) is False, "Sparse corner negative falsely marked blank!"dust_only = np.zeros((980, 1600, 3), dtype=np.uint8)cv2.circle(dust_only, (400, 400), 4, (245, 245, 245), -1)assert app.check_inverted_polarity(dust_only) is False, "Single dust speck falsely marked inverted!"# 3. Horizontal whitespace trim on wide valley/adaptive strip preserves trailing '?' without altering full-width stripswide_strip = np.full((46, 1050, 3), 255, dtype=np.uint8)cv2.rectangle(wide_strip, (90, 10), (225, 36), (20, 20, 20), -1)cv2.circle(wide_strip, (238, 33), 2, (35, 35, 35), -1) # tiny trailing '?' dottrimmed = app._trim_horizontal_whitespace_for_rec(wide_strip)assert trimmed.shape[0] == 46 and 160 <= trimmed.shape[1] <= 240, trimmed.shapeassert int((trimmed < 100).sum()) == int((wide_strip < 100).sum()), "Horizontal trim clipped glyph/punctuation ink!"full_strip = np.full((46, 600, 3), 255, dtype=np.uint8)cv2.rectangle(full_strip, (30, 10), (560, 36), (20, 20, 20), -1)assert app._trim_horizontal_whitespace_for_rec(full_strip).shape == (46, 600, 3)# 4. Studio JS transient 502/503/504 auto-retry helper presentjs_src = open(os.path.join(app.PROJECT_ROOT, 'static', 'js', 'studio.js'), 'r', encoding='utf-8').read()assert 'async function fetchWithTransientRetry(' in js_srcassert 'fetchWithTransientRetry("/ocr"' in js_srcassert 'fetchWithTransientRetry("/ocr_crop"' in js_srcclass TestQualityGates(unittest.TestCase):pass
Dockerfile+2-2
ocr-studio/app.py+186-98
ocr-studio/index.html+4-4
ocr-studio/static/js/studio.js+26-2
ocr-studio/tests/test_quality_gates.py+51