Download scripts/r5_showcase/showcase_detect.py from treoa/turkic-ocr-code: direct link, hf CLI and curl.
- Browser
- Download file 5.95 kB
-
https://huggingface.co/treoa/turkic-ocr-code/resolve/main/scripts/r5_showcase/showcase_detect.py
- Command line
-
hf download hf://treoa/turkic-ocr-code/scripts/r5_showcase/showcase_detect.py
-
curl -L -o showcase_detect.py https://huggingface.co/treoa/turkic-ocr-code/resolve/main/scripts/r5_showcase/showcase_detect.py
5.95 kB
| """Showcase, job B step 1 (.venv_kraken): the page list and the line detector on CPU. | |
| Pages (validation only): the handwritten generated pages and the School Notebooks page of selection.json (their detector | |
| pages and STORED stage-2 YOLO11s boxes come from det_eval: e2e_yolo_s2_{gen,school}_val_A1_long_pages.jsonl), and the typed | |
| "_T" pages rebuilt by job A (pages_typed_val.tsv; no stored boxes). The detector (release package | |
| turkic-line-detector-yolo11s/best.pt, the stage-2 weights) runs on CPU on every page with the settings of det_eval and of the | |
| release infer.py (image size 1280, confidence 0.25, NMS IoU 0.6, at most 300 boxes), so that every page has a measured | |
| detection time. Boxes used for reading: the stored boxes where they exist (so the reading equals the det_eval / page-check | |
| setting), else the CPU boxes. The CPU boxes are compared with the stored ones (greedy one-to-one IoU matching). | |
| usage: showcase_detect.py --selection JSON --gen_pages TSV --school_pages TSV --typed_pages TSV --stored_gen JSONL | |
| --stored_school JSONL --weights best.pt --out pages.json --threads 16 | |
| """ | |
| import argparse | |
| import csv | |
| import json | |
| import os | |
| import sys | |
| import time | |
| sys.path.insert(0, "/path/to/TURKIC_OCR_CODE/src") | |
| import numpy as np # noqa: E402 | |
| import torch # noqa: E402 | |
| from linedet import det_eval as DE # noqa: E402 | |
| csv.field_size_limit(10 ** 9) | |
| def read_tsv(p): | |
| with open(p, encoding="utf-8", newline="") as f: | |
| return {r["id"]: r for r in csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE)} | |
| def match_stats(a, b): | |
| if not a or not b: | |
| return dict(n_cpu=len(a), n_stored=len(b), matched_iou_0_9=0, mean_iou_matched=None) | |
| M = DE.iou_matrix(a, b) | |
| used, ious = set(), [] | |
| for i in np.argsort(-M.max(1)): | |
| j = [j for j in np.argsort(-M[i]) if j not in used] | |
| if j and M[i, j[0]] > 0.5: | |
| used.add(j[0]) | |
| ious.append(float(M[i, j[0]])) | |
| return dict(n_cpu=len(a), n_stored=len(b), matched_iou_0_5=len(ious), matched_iou_0_9=sum(1 for v in ious if v >= 0.9), | |
| mean_iou_matched=round(float(np.mean(ious)), 4) if ious else None) | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| for k in ("selection", "gen_pages", "school_pages", "typed_pages", "stored_gen", "stored_school", "weights", "out"): | |
| ap.add_argument("--" + k, required=True) | |
| ap.add_argument("--threads", type=int, default=16) | |
| a = ap.parse_args() | |
| for p in (a.gen_pages, a.school_pages, a.typed_pages): | |
| assert "test" not in os.path.basename(p).lower() | |
| torch.set_num_threads(a.threads) | |
| sel = json.load(open(a.selection, encoding="utf-8")) | |
| gen, sch, typ = read_tsv(a.gen_pages), read_tsv(a.school_pages), read_tsv(a.typed_pages) | |
| stored = {} | |
| for p in (a.stored_gen, a.stored_school): | |
| for ln in open(p, encoding="utf-8"): | |
| r = json.loads(ln) | |
| stored[r["id"]] = r | |
| pages = [] | |
| for h in sel["handwritten"]: | |
| r = gen[h["id"]] | |
| pages.append(dict(id=h["id"], set="handwritten", lang=h["lang"], kind=h["kind"], strength=h["strength"], row=r)) | |
| for t in sel["typed"]: | |
| pid = "pg_val_" + t["page_id"] | |
| pages.append(dict(id=pid, set="typed", lang=t["lang"], kind=t["kind"], strength=t["strength"], row=typ[pid])) | |
| for s in sel["real"]: | |
| pages.append(dict(id=s["id"], set="real", lang=s.get("lang", "ru"), kind=s.get("kind", "school_notebook_photo"), strength="real", row=sch[s["id"]])) | |
| from ultralytics import YOLO | |
| t0 = time.time() | |
| det = YOLO(a.weights) | |
| load_s = time.time() - t0 | |
| t0 = time.time() | |
| det.predict(pages[0]["row"]["image"], imgsz=1280, conf=0.25, iou=0.6, max_det=300, device="cpu", verbose=False) | |
| warm_s = time.time() - t0 | |
| out = [] | |
| for pg in pages: | |
| r = pg.pop("row") | |
| t0 = time.time() | |
| res = det.predict(r["image"], imgsz=1280, conf=0.25, iou=0.6, max_det=300, device="cpu", verbose=False)[0] | |
| ds = time.time() - t0 | |
| cpu_boxes = [[round(v, 1) for v in b] for b in res.boxes.xyxy.cpu().numpy().tolist()] | |
| cpu_scores = [round(float(s), 4) for s in res.boxes.conf.cpu().numpy().tolist()] | |
| st = stored.get(pg["id"]) | |
| pg.update(image=r["image"], width=int(r["width"]), height=int(r["height"]), scale=float(r["scale"]), ref_lines=json.loads(r["ref_lines_json"]), | |
| gt_boxes=json.loads(r["boxes_json"]), cpu_boxes=cpu_boxes, cpu_scores=cpu_scores, det_seconds_cpu=round(ds, 3)) | |
| if pg["id"].startswith("school_"): | |
| pg["reading_image"] = DE.school_orig(pg["id"]) | |
| elif r.get("reading_image"): | |
| pg["reading_image"] = r["reading_image"] | |
| if r.get("note"): | |
| pg["note"] = r["note"] | |
| if st is not None: | |
| pg.update(stored_boxes=st["boxes"], stored_scores=st["scores"], boxes_used="stored (det_eval e2e_yolo_s2 run, GPU)", boxes=st["boxes"]) | |
| pg["cpu_vs_stored"] = match_stats(cpu_boxes, st["boxes"]) | |
| else: | |
| pg.update(stored_boxes=None, boxes_used="cpu (this job)", boxes=cpu_boxes) | |
| # detection quality of the boxes used, as det_eval: TP at IoU 0.5 by greedy score order | |
| sc = st["scores"] if st is not None else cpu_scores | |
| pg["det_tp_iou_0_5"] = DE.match_count(pg["boxes"], sc, pg["gt_boxes"], 0.5) | |
| out.append(pg) | |
| print(pg["id"], "boxes used", len(pg["boxes"]), "cpu", len(cpu_boxes), "%.2f s" % ds, flush=True) | |
| info = dict(weights=a.weights, device="cpu", threads=a.threads, imgsz=1280, conf=0.25, iou=0.6, max_det=300, model_load_seconds=round(load_s, 2), | |
| warmup_first_predict_seconds=round(warm_s, 2), created_utc=time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), host=os.uname().nodename) | |
| json.dump(dict(info=info, pages=out), open(a.out, "w", encoding="utf-8"), ensure_ascii=False, indent=1) | |
| print("done", flush=True) | |
| if __name__ == "__main__": | |
| main() | |