File size: 12,436 Bytes
9424af8 5800edb 9424af8 5800edb 9424af8 5800edb 9424af8 5800edb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 | """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"] # 0-1000 → пікселі
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 # лежить поруч у code/
return "\n".join(
km._normalize_text(r.get("text") or "", r.get("type", "handwritten"))
for r in regions)
# ---------------------------------------------------------------- Gemini API --
_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] # Gemini-натив → наш [x1,y1,x2,y2]
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>')) |