| """Helpers for the RUKOPYS workshop notebook. |
| |
| Import after adding this dir to sys.path (the notebook does it right after |
| snapshot_download); relative image paths assume CWD = package root: |
| |
| import sys; sys.path.insert(0, "code") |
| from workshop_utils import (show_page, parse_regions, page_text, |
| gemini_regions, compare_table) |
| |
| Regions everywhere are {"bbox": [x1,y1,x2,y2] in 0-1000, "type", "text"}. |
| """ |
|
|
| from __future__ import annotations |
|
|
| import base64 |
| import html |
| import json |
| import os |
| import re |
| from io import BytesIO |
|
|
| from PIL import Image, ImageDraw |
|
|
| TYPE_COLORS = {"handwritten": "#e6194b", "printed": "#3cb44b", "formula": "#4363d8", |
| "table": "#f58231", "annotation": "#911eb4", "image": "#808000", |
| "graph": "#469990"} |
|
|
|
|
| def show_page(rec, regions=None, max_side=900, n_texts=8): |
| """Показує сторінку з bbox-рамками за типами регіонів. |
| |
| rec — запис із train/val.jsonl |
| regions — список регіонів; за замовчуванням GT із rec["target"], |
| але можна передати й передбачення моделі |
| """ |
| from IPython.display import display |
|
|
| if regions is None: |
| regions = json.loads(rec["target"])["regions"] |
| img = Image.open(rec["image_path"]).convert("RGB") |
| w, h = img.size |
| draw = ImageDraw.Draw(img) |
| for reg in regions: |
| x1, y1, x2, y2 = reg["bbox"] |
| draw.rectangle((x1 * w / 1000, y1 * h / 1000, x2 * w / 1000, y2 * h / 1000), |
| outline=TYPE_COLORS.get(reg.get("type"), "red"), width=3) |
| print(f"{rec['uuid']} ({rec['source']}): {len(regions)} регіонів") |
| for reg in regions[:n_texts]: |
| print(f" [{reg.get('type', '?'):<11}] {(reg.get('text') or '')[:70]}") |
| scale = max_side / max(w, h) |
| if scale < 1: |
| img = img.resize((int(w * scale), int(h * scale))) |
| display(img) |
|
|
|
|
| def parse_regions(raw: str) -> list[dict]: |
| """Вивід моделі → список регіонів. Терпить <think>-блоки, ```json-фенси, |
| текст навколо JSON; повертає [] якщо JSON не рятується. |
| (Адаптація _parse_regions з конкурсного pipelines/infer_ft_e2e.py.) |
| """ |
| raw = re.sub(r"<think>[\s\S]*?</think>", "", raw or "").strip() |
| raw = re.sub(r"```json\s*", "", raw) |
| raw = re.sub(r"```\s*$", "", raw).strip() |
| try: |
| data = json.loads(raw) |
| except json.JSONDecodeError: |
| m = re.search(r"\{[\s\S]*\}", raw) |
| if not m: |
| return [] |
| try: |
| data = json.loads(m.group()) |
| except json.JSONDecodeError: |
| return [] |
| out = [] |
| for r in data.get("regions", []) or []: |
| bbox = r.get("bbox") or [] |
| if len(bbox) < 4: |
| continue |
| out.append({"bbox": bbox[:4], "type": r.get("type", "handwritten"), |
| "text": r.get("text") or ""}) |
| return out |
|
|
|
|
| def page_text(regions) -> str: |
| """Регіони → один рядок на сторінку, нормалізований офіційним скорером |
| (типо-залежно: formula розгортає LaTeX, handwritten — фолдинг лукалайків). |
| Порівнюй CER тільки між двома викликами page_text — обидві сторони мають |
| пройти однакову нормалізацію.""" |
| import kaggle_metric as km |
|
|
| return "\n".join( |
| km._normalize_text(r.get("text") or "", r.get("type", "handwritten")) |
| for r in regions) |
|
|
|
|
| |
|
|
| _gemini_client = None |
|
|
|
|
| def _client(): |
| global _gemini_client |
| if _gemini_client is None: |
| from google import genai |
| _gemini_client = genai.Client(api_key=os.environ["GEMINI_API_KEY"]) |
| return _gemini_client |
|
|
|
|
| def gemini_regions(rec, model="gemini-3-flash", max_pixels=1_600_000) -> list[dict]: |
| """Той самий whole-page таск через Gemini API → регіони у нашій схемі. |
| |
| Нюанси (виведені в конкурсі, див. pipelines/gcp_api/infer_e2e.py): |
| - Gemini-нативний порядок bbox = [ymin,xmin,ymax,xmax] — транспонуємо; |
| - response_schema обов'язкова, без неї модель дрейфує у box_2d-формат; |
| - family-дефолти: thinking_level="low", temperature=1.0. |
| """ |
| from google.genai import types |
|
|
| from ft_qwen_unsloth import PROMPT, load_image |
|
|
| prompt = (PROMPT.replace("[x1,y1,x2,y2]", "[ymin,xmin,ymax,xmax]") |
| + "\n- one region per text LINE (never per word)") |
| schema = types.Schema( |
| type=types.Type.OBJECT, required=["regions"], |
| properties={"regions": types.Schema( |
| type=types.Type.ARRAY, |
| items=types.Schema( |
| type=types.Type.OBJECT, required=["bbox", "type", "text"], |
| properties={ |
| "bbox": types.Schema(type=types.Type.ARRAY, |
| items=types.Schema(type=types.Type.INTEGER)), |
| "type": types.Schema(type=types.Type.STRING), |
| "text": types.Schema(type=types.Type.STRING), |
| }))}) |
| img = load_image(rec["image_path"], max_pixels) |
| buf = BytesIO() |
| img.save(buf, format="JPEG", quality=90) |
| resp = _client().models.generate_content( |
| model=model, |
| contents=[types.Content(role="user", parts=[ |
| types.Part.from_bytes(data=buf.getvalue(), mime_type="image/jpeg"), |
| types.Part.from_text(text=prompt)])], |
| config=types.GenerateContentConfig( |
| temperature=1.0, max_output_tokens=8192, |
| thinking_config=types.ThinkingConfig(thinking_level="low"), |
| response_mime_type="application/json", |
| response_schema=schema, |
| )) |
| out = [] |
| for r in json.loads(resp.text).get("regions", []): |
| b = r.get("bbox") or [] |
| if len(b) < 4: |
| continue |
| y1, x1, y2, x2 = b[:4] |
| out.append({"bbox": [x1, y1, x2, y2], |
| "type": r.get("type", "handwritten"), |
| "text": r.get("text") or ""}) |
| return out |
|
|
|
|
| def page_metrics(rec, regions) -> dict: |
| """4 компоненти конкурсної метрики + композит для ОДНІЄЇ сторінки. |
| |
| Точна реплікація tools/kaggle_metric.score() (вендорений офіційний скорер) |
| на одній сторінці: той самий greedy IoU@0.5 матчинг, той самий нормалізатор, |
| той самий центр-бакет порядок читання. Єдина відмінність від Kaggle: бокси |
| тут у 0-1000 шкалі, а не в пікселях (IoU шкало-інваріантний; бакет //15 — |
| 1.5% висоти сторінки замість ~15 px, на ~1000px-високих картинках те саме). |
| """ |
| import kaggle_metric as km |
|
|
| gt = json.loads(rec["target"])["regions"] |
| pred = regions |
| matched, unmatched_gt, unmatched_pred = km._greedy_match(gt, pred, threshold=0.5) |
|
|
| det_prec = len(matched) / max(len(matched) + len(unmatched_pred), 1) |
| det_rec = len(matched) / max(len(matched) + len(unmatched_gt), 1) |
| det_f1 = 2 * det_prec * det_rec / max(det_prec + det_rec, 1e-9) |
|
|
| class_acc = (sum(gt[gi]["type"] == pred[pi].get("type") for gi, pi in matched) |
| / max(len(matched), 1)) |
|
|
| cers = [] |
| for gi, pi in matched: |
| if km._is_scorable(gt[gi]): |
| rtype = gt[gi].get("type", "handwritten") |
| g = km._normalize_text(gt[gi].get("text", ""), rtype) |
| p = km._normalize_text(pred[pi].get("text", ""), rtype) |
| cers.append(km._levenshtein(p, g) / max(len(g), 1)) |
| cer = sum(cers) / len(cers) if cers else 1.0 |
|
|
| pred_drop = {pi for gi, pi in matched if not km._is_scorable(gt[gi])} |
| gt_page = km._build_page_text(gt, normalize=True) |
| pred_page = km._build_page_text(pred, normalize=True, drop_indices=pred_drop) |
| page_cer = km._levenshtein(pred_page, gt_page) / len(gt_page) if gt_page else 1.0 |
|
|
| return { |
| "Det F1 (×0.15)": det_f1, |
| "Class Acc (×0.05)": class_acc, |
| "1−CER (×0.30)": max(0.0, 1.0 - cer), |
| "1−PageCER (×0.50)": max(0.0, 1.0 - page_cer), |
| "Score": (0.15 * det_f1 + 0.05 * class_acc |
| + 0.30 * max(0.0, 1.0 - cer) + 0.50 * max(0.0, 1.0 - page_cer)), |
| } |
|
|
|
|
| |
|
|
| def _iou(a, b) -> float: |
| ix = max(0, min(a[2], b[2]) - max(a[0], b[0])) |
| iy = max(0, min(a[3], b[3]) - max(a[1], b[1])) |
| inter = ix * iy |
| if not inter: |
| return 0.0 |
| ua = (a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter |
| return inter / ua |
|
|
|
|
| def _crop_b64(img, bbox, pad=6, max_w=340) -> str: |
| w, h = img.size |
| box = (max(0, bbox[0] * w // 1000 - pad), max(0, bbox[1] * h // 1000 - pad), |
| min(w, bbox[2] * w // 1000 + pad), min(h, bbox[3] * h // 1000 + pad)) |
| c = img.crop(box) |
| if c.width > max_w: |
| c = c.resize((max_w, max(1, round(c.height * max_w / c.width)))) |
| buf = BytesIO() |
| c.save(buf, format="JPEG", quality=85) |
| return base64.b64encode(buf.getvalue()).decode() |
|
|
|
|
| def compare_table(rec, preds: dict, iou_thr=0.3, max_rows=12, |
| add_metrics_table=False): |
| """HTML-таблиця: рядок = GT-регіон (кроп + текст), колонка = модель. |
| |
| preds = {"назва колонки": regions-список у 0-1000 шкалі}. Передбачення |
| чіпляються до GT-рядка через IoU ≥ iou_thr; не знайдено → «—». Текст |
| показується СИРИМ (без метрика-нормалізації) — це наочне порівняння, |
| CER рахуйте окремо через page_text. |
| |
| add_metrics_table=True — під таблицею друга: рядки = 4 компоненти |
| конкурсної метрики + композитний Score (див. page_metrics), колонки ті ж. |
| """ |
| from IPython.display import HTML, display |
|
|
| img = Image.open(rec["image_path"]).convert("RGB") |
| gt = json.loads(rec["target"])["regions"] |
| td = 'style="border:1px solid #ccc;padding:4px;vertical-align:top;font-size:13px"' |
| rows = [] |
| for g in gt[:max_rows]: |
| cells = [f'<img src="data:image/jpeg;base64,{_crop_b64(img, g["bbox"])}">', |
| html.escape(g.get("text") or "")] |
| for regs in preds.values(): |
| best, best_iou = None, 0.0 |
| for r in regs: |
| v = _iou(g["bbox"], r["bbox"]) |
| if v > best_iou: |
| best, best_iou = r, v |
| cells.append(html.escape(best.get("text") or "") if best_iou >= iou_thr |
| else "—") |
| rows.append("<tr>" + "".join(f"<td {td}>{c}</td>" for c in cells) + "</tr>") |
| head = "".join(f"<th {td}>{html.escape(c)}</th>" |
| for c in ["кроп", "GT"] + list(preds)) |
| display(HTML(f'<table style="border-collapse:collapse">{head}{"".join(rows)}</table>')) |
|
|
| if not add_metrics_table: |
| return |
| mets = {name: page_metrics(rec, regs) for name, regs in preds.items()} |
| metric_names = next(iter(mets.values())).keys() |
| mrows = [] |
| for mn in metric_names: |
| bold = mn == "Score" |
| cells = [f"<b>{html.escape(mn)}</b>" if bold else html.escape(mn)] |
| cells += [f"<b>{mets[n][mn]:.3f}</b>" if bold else f"{mets[n][mn]:.3f}" |
| for n in preds] |
| mrows.append("<tr>" + "".join(f"<td {td}>{c}</td>" for c in cells) + "</tr>") |
| mhead = "".join(f"<th {td}>{html.escape(c)}</th>" |
| for c in ["метрика"] + list(preds)) |
| display(HTML('<table style="border-collapse:collapse;margin-top:10px">' |
| f'{mhead}{"".join(mrows)}</table>')) |