Spaces:
Running
Running
fix(studio): resolve crash on empty coords, Cham unicode block, and safe NMS
Browse files173 unmodified lines17417517617717817918030 unmodified lines211212213214215216164 unmodified lines3813823833843853863873887 unmodified lines396397398399400401402551 unmodified lines95495595695795895996096196296321 unmodified lines9859869879889899909913 unmodified lines99599699799899910001001100210031004100510064 unmodified lines10111012101310141015101610171 unmodified line1019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710488 unmodified lines10571058105910601061106210631064106541 unmodified lines1107110811091110111111121113173 unmodified linesif cham_conf >= 0.65:final_results[i] = (cham_text, cham_conf)else:viet_text, viet_conf = viet_res[viet_ptr]viet_ptr += 1if cham_conf >= 0.40 and cham_conf > viet_conf - 0.15:30 unmodified linesif not os.path.exists(model_dir):# Fallback to general data/output folders if version-specific folder is missingmodel_dir = os.path.join(PROJECT_ROOT, "data", "output", "rec_cham_inference")dict_path = os.path.join(PROJECT_ROOT, "data", "cham_dict.txt")sys_argv_backup = sys.argv164 unmodified linesfor d in diff:if d.startswith('- ') or d.startswith('+ '):char = d[2]# Cham pre-signs / final signs range: U+A800 to U+A82F, U+A840 to U+A87Fif '\uA800' <= char <= '\uA82F' or '\uA840' <= char <= '\uA87F':return Truereturn False7 unmodified linest_start = time.time()if not base_coords:return [], []img_h, img_w, _ = img.shapeheights = [float(e - s) for s, e in base_coords]551 unmodified linesif sel_data["overlap_prev_px"] > 5 or sel_data["overlap_next_px"] > 5:needs_review_reasons.append("adjacent_line_contamination")if len(cand_data) > 1:preds = [c["prediction"] for c in cand_data.values() if c["prediction"]]if len(set(preds)) == len(cand_data) and len(preds) > 1:needs_review_reasons.append("multi_crop_disagreement")line_meta["needs_review"] = len(needs_review_reasons) > 0line_meta["reason"] = needs_review_reasons21 unmodified linesfor m in lines_meta:print(f" Line {m['line_id']}: bbox={m['bbox']}, core_box={m['core_box']}")# Phase 7: Non-Text Background Line Pruning & 1D Vertical NMSfiltered_lines_meta = []filtered_final_crops = []3 unmodified linesconf = cand_sel.get("confidence", 0.0)pred = cand_sel.get("prediction", "").strip()has_cham_char = any('\uA800' <= char <= '\uA82F' or '\uA840' <= char <= '\uA87F' for char in pred)has_alphanumeric = any(char.isalnum() for char in pred)# Strict filter out false positive lines from background artwork (dragons, elephants, ocean graphics)# Any line with confidence < 0.50 that does NOT contain valid Cham characters is treated as fake background artworkis_fake_background = (conf < 0.50 and not has_cham_char)if not is_fake_background and conf >= 0.15:filtered_lines_meta.append(meta)filtered_final_crops.append(crop)4 unmodified linesfiltered_lines_meta = [lines_meta[best_i]]filtered_final_crops = [final_crops[best_i]]# 1D Vertical Non-Maximum Suppression (NMS) to eliminate overlapping border linesif len(filtered_lines_meta) > 1:indexed_items = []for meta, crop in zip(filtered_lines_meta, filtered_final_crops):1 unmodified linecand_sel = meta["candidates"].get(sel_type, {})conf = cand_sel.get("confidence", 0.0)box = meta["core_box"]indexed_items.append((conf, box, meta, crop))indexed_items.sort(key=lambda x: x[0], reverse=True)nms_kept = []for conf, box, meta, crop in indexed_items:s1, e1 = boxh1 = max(1, e1 - s1)keep = Truefor k_conf, k_box, _, _ in nms_kept:s2, e2 = k_boxh2 = max(1, e2 - s2)inter_s = max(s1, s2)inter_e = min(e1, e2)inter = max(0, inter_e - inter_s)iom = inter / min(h1, h2)if iom > 0.12:keep = Falsebreakif keep:nms_kept.append((conf, box, meta, crop))nms_kept.sort(key=lambda x: x[1][0])filtered_lines_meta = [x[2] for x in nms_kept]filtered_final_crops = [x[3] for x in nms_kept]# Relative confidence pruning against max document confidenceif len(filtered_lines_meta) > 1:8 unmodified linessel_type = meta.get("selected_crop_type", "safe")cand_sel = meta["candidates"].get(sel_type, {})conf = cand_sel.get("confidence", 0.0)# If a line's confidence is far below max_doc_conf (> 0.25 lower) and conf < 0.45, prune as noiseif conf < 0.45 and (max_doc_conf - conf > 0.25):continuerel_filtered_meta.append(meta)rel_filtered_crops.append(crop)41 unmodified linesclass ChamOCRRequestHandler(BaseHTTPRequestHandler):def do_GET(self):if self.path == '/':self.send_response(200)self.send_header('Content-type', 'text/html; charset=utf-8')self.send_header('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0')173 unmodified lines17417517617717817918018118218330 unmodified lines214215216217218219220164 unmodified lines3853863873883893903913923937 unmodified lines401402403404405406407408409410411412413414415416417551 unmodified lines96997097197297397497597697797897998098198298398498598698798898999099121 unmodified lines10131014101510161017101810193 unmodified lines1023102410251026102710281029103010311032103310344 unmodified lines10391040104110421043104410451 unmodified line1047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710888 unmodified lines10971098109911001101110211031104110511061107110841 unmodified lines11501151115211531154115511561157173 unmodified linesif cham_conf >= 0.65:final_results[i] = (cham_text, cham_conf)else:if viet_ptr < len(viet_res):viet_text, viet_conf = viet_res[viet_ptr]else:viet_text, viet_conf = ("", 0.0)viet_ptr += 1if cham_conf >= 0.40 and cham_conf > viet_conf - 0.15:30 unmodified linesif not os.path.exists(model_dir):# Fallback to general data/output folders if version-specific folder is missingmodel_dir = os.path.join(PROJECT_ROOT, "data", "output", "rec_cham_inference")if not os.path.exists(dict_path):dict_path = os.path.join(PROJECT_ROOT, "data", "cham_dict.txt")sys_argv_backup = sys.argv164 unmodified linesfor d in diff:if d.startswith('- ') or d.startswith('+ '):char = d[2]# Cham Unicode Block: U+AA00 to U+AA5F (with diacritics / vowels U+AA29 to U+AA4D)# Also support legacy ranges U+A800 to U+A87Fif '\uAA00' <= char <= '\uAA5F' or '\uA800' <= char <= '\uA87F':return Truereturn False7 unmodified linest_start = time.time()if not base_coords:return [], [], {"candidate_generation_sec": 0.0,"recognition_batch_pass1_sec": 0.0,"recognition_batch_pass2_sec": 0.0,"selection_sec": 0.0,"total_segmentation_sec": 0.0,"num_lines": 0,"num_candidates_pass1": 0,"num_candidates_pass2": 0,"ocr_model_calls": 0}img_h, img_w, _ = img.shapeheights = [float(e - s) for s, e in base_coords]551 unmodified linesif sel_data["overlap_prev_px"] > 5 or sel_data["overlap_next_px"] > 5:needs_review_reasons.append("adjacent_line_contamination")# Only flag needs_review for multi-crop disagreement if important Cham signs change# or if there is a significant confidence drop (>= 0.15) compared to safe cropif len(cand_data) > 1 and "safe" in cand_data:safe_pred = cand_data["safe"].get("prediction", "")safe_conf = cand_data["safe"].get("confidence", 0.0)has_cham_sign_diff = Falsefor ctype, cand in cand_data.items():if ctype != "safe" and has_important_cham_sign_changes(safe_pred, cand.get("prediction", "")):has_cham_sign_diff = Truebreakif has_cham_sign_diff:needs_review_reasons.append("important_cham_sign_change")if safe_conf - sel_data["confidence"] >= 0.15:needs_review_reasons.append("significant_confidence_drop")line_meta["needs_review"] = len(needs_review_reasons) > 0line_meta["reason"] = needs_review_reasons21 unmodified linesfor m in lines_meta:print(f" Line {m['line_id']}: bbox={m['bbox']}, core_box={m['core_box']}")# Phase 7: Non-Text Background Line Pruning & 2D Vertical/Horizontal NMSfiltered_lines_meta = []filtered_final_crops = []3 unmodified linesconf = cand_sel.get("confidence", 0.0)pred = cand_sel.get("prediction", "").strip()has_cham_char = any('\uAA00' <= char <= '\uAA5F' or '\uA800' <= char <= '\uA87F' for char in pred)has_alphanumeric = any(char.isalnum() for char in pred)# Strict filter out false positive lines from background artwork (dragons, elephants, ocean graphics)# Only treat as fake background artwork if confidence < 0.35 AND neither Cham nor alphanumeric characters are foundis_fake_background = (conf < 0.35 and not has_cham_char and not has_alphanumeric)if not is_fake_background and conf >= 0.15:filtered_lines_meta.append(meta)filtered_final_crops.append(crop)4 unmodified linesfiltered_lines_meta = [lines_meta[best_i]]filtered_final_crops = [final_crops[best_i]]# Non-Maximum Suppression (NMS) with 2D IoM (checks both vertical and horizontal overlaps)if len(filtered_lines_meta) > 1:indexed_items = []for meta, crop in zip(filtered_lines_meta, filtered_final_crops):1 unmodified linecand_sel = meta["candidates"].get(sel_type, {})conf = cand_sel.get("confidence", 0.0)box = meta["core_box"]bbox = meta.get("bbox", [0, box[0], img_w, box[1]])indexed_items.append((conf, box, bbox, meta, crop))indexed_items.sort(key=lambda x: x[0], reverse=True)nms_kept = []for conf, box, bbox, meta, crop in indexed_items:s1, e1 = boxh1 = max(1, e1 - s1)x1_min, _, x1_max, _ = bboxw1 = max(1, x1_max - x1_min)keep = Truefor k_conf, k_box, k_bbox, _, _ in nms_kept:s2, e2 = k_boxh2 = max(1, e2 - s2)inter_s = max(s1, s2)inter_e = min(e1, e2)inter_y = max(0, inter_e - inter_s)iom_y = inter_y / min(h1, h2)# Check horizontal overlap to avoid suppressing side-by-side columnsx2_min, _, x2_max, _ = k_bboxw2 = max(1, x2_max - x2_min)inter_x = max(0, min(x1_max, x2_max) - max(x1_min, x2_min))iom_x = inter_x / min(w1, w2)# Only suppress if both vertical and horizontal overlaps are significantif iom_y > 0.40 and iom_x > 0.30:keep = Falsebreakif keep:nms_kept.append((conf, box, bbox, meta, crop))nms_kept.sort(key=lambda x: x[1][0])filtered_lines_meta = [x[3] for x in nms_kept]filtered_final_crops = [x[4] for x in nms_kept]# Relative confidence pruning against max document confidenceif len(filtered_lines_meta) > 1:8 unmodified linessel_type = meta.get("selected_crop_type", "safe")cand_sel = meta["candidates"].get(sel_type, {})conf = cand_sel.get("confidence", 0.0)pred = cand_sel.get("prediction", "").strip()has_cham_char = any('\uAA00' <= char <= '\uAA5F' or '\uA800' <= char <= '\uA87F' for char in pred)# If a line has real Cham text, never prune it even if confidence is lower# Only prune pure low-confidence non-Cham noise blobsif conf < 0.35 and (max_doc_conf - conf > 0.35) and not has_cham_char:continuerel_filtered_meta.append(meta)rel_filtered_crops.append(crop)41 unmodified linesclass ChamOCRRequestHandler(BaseHTTPRequestHandler):def do_GET(self):parsed_path = urllib.parse.urlparse(self.path).pathif parsed_path in ('/', '/index.html'):self.send_response(200)self.send_header('Content-type', 'text/html; charset=utf-8')self.send_header('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0')
ocr-studio/app.py+69-25