File size: 12,468 Bytes
24aaa76 | 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 | """Evaluate a line detector (YOLO or kraken BLLA) on validation pages, and run it end to end with the A1 line recognizer.
Detection: precision, recall and F1 of line boxes at IoU 0.5 and 0.75 (greedy matching by descending box score; micro over
pages), recall of text pixels (ink pixels inside the ground-truth line polygons that fall inside a predicted box), mean time
per page, and the per-line box scores (kept in the per-page JSONL).
End to end (--read A1:long): every detected box is cut from the page (school pages: from the full-resolution photograph),
read by the recognizer, and the page text is compared with the reference lines: reading-order page CER (M28 of eval_spec.json: lines sorted by (centre_y // 15, centre_x), joined by one space) and order-free page CER (hypothesis and reference lines matched one to one by minimum edit distance
with the Hungarian method; unmatched hypothesis lines count as insertions, unmatched reference lines as deletions: metric M29 of
records/R5/RESEVAL/eval_spec.json, rule gap G5). Validation pages only.
Usage: python -m linedet.det_eval --kind yolo --weights <best.pt> --pages <pages tsv> --name <label> [--read A1:long] [--max_pages N]
"""
import argparse
import json
import os
import time
os.environ.setdefault("YOLO_OFFLINE", "1")
os.environ.setdefault("YOLO_CONFIG_DIR", "/path/to/TURKIC_OCR_DATA/tmp/ultralytics_cfg")
import cv2
import numpy as np
import torch
from .common import DATA, LD_CKPT, LD_OUT, read_manifest, save_json, utcnow
SCHOOL = DATA + "/data/raw/school_notebooks_ru"
def iou_matrix(a, b):
a = np.asarray(a, dtype=np.float64).reshape(-1, 4)
b = np.asarray(b, dtype=np.float64).reshape(-1, 4)
ix0 = np.maximum(a[:, None, 0], b[None, :, 0])
iy0 = np.maximum(a[:, None, 1], b[None, :, 1])
ix1 = np.minimum(a[:, None, 2], b[None, :, 2])
iy1 = np.minimum(a[:, None, 3], b[None, :, 3])
inter = np.clip(ix1 - ix0, 0, None) * np.clip(iy1 - iy0, 0, None)
aa = (a[:, 2] - a[:, 0]) * (a[:, 3] - a[:, 1])
bb = (b[:, 2] - b[:, 0]) * (b[:, 3] - b[:, 1])
return inter / (aa[:, None] + bb[None, :] - inter + 1e-9)
def match_count(pred, scores, gt, thr):
"""Greedy one-to-one matching by descending score; returns the number of true positives."""
if len(pred) == 0 or len(gt) == 0:
return 0
order = np.argsort(-np.asarray(scores))
M = iou_matrix(np.asarray(pred)[order], gt)
used = np.zeros(len(gt), dtype=bool)
tp = 0
for i in range(M.shape[0]):
row = np.where(used, -1.0, M[i])
j = int(row.argmax())
if row[j] >= thr:
used[j] = True
tp += 1
return tp
def ink_recall(img_gray, gt_polys, pred_boxes):
"""Share of the ink pixels inside the ground-truth line polygons that lie inside some predicted box."""
h, w = img_gray.shape
ink = cv2.adaptiveThreshold(img_gray, 1, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 31, 12)
gtm = np.zeros((h, w), np.uint8)
for p in gt_polys:
cv2.fillPoly(gtm, [np.array(p, dtype=np.int32).reshape(-1, 1, 2)], 1)
pm = np.zeros((h, w), np.uint8)
for x0, y0, x1, y1 in pred_boxes:
pm[max(int(y0), 0):int(y1) + 1, max(int(x0), 0):int(x1) + 1] = 1
tot = int((ink & gtm).sum())
return int((ink & gtm & pm).sum()), tot
def page_cers(hyp_lines, ref_lines):
from rapidfuzz import process
from rapidfuzz.distance import Levenshtein
from scipy.optimize import linear_sum_assignment
nref = sum(len(r) for r in ref_lines)
ro = Levenshtein.distance(" ".join(hyp_lines), " ".join(ref_lines))
if not hyp_lines or not ref_lines:
of = sum(len(h) for h in hyp_lines) + nref
else:
C = process.cdist(hyp_lines, ref_lines, scorer=Levenshtein.distance, dtype=np.int32)
ri, ci = linear_sum_assignment(C)
matched = int(C[ri, ci].sum())
un_h = sum(len(hyp_lines[i]) for i in range(len(hyp_lines)) if i not in set(ri.tolist()))
un_r = sum(len(ref_lines[j]) for j in range(len(ref_lines)) if j not in set(ci.tolist()))
of = matched + un_h + un_r
return ro, of, nref
def school_orig(pid):
"""full-resolution photograph of a school val page"""
sp, num = pid.split("_")[1], int(pid.split("_")[2])
d = json.load(open("%s/annotations_%s.json" % (SCHOOL, sp), encoding="utf-8"))
fn = {im["id"]: im["file_name"] for im in d["images"]}[num]
return "%s/val_test_images/%s/%s" % (SCHOOL, sp, fn)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--kind", choices=["yolo", "blla"], required=True)
ap.add_argument("--weights", required=True)
ap.add_argument("--pages", required=True)
ap.add_argument("--name", required=True)
ap.add_argument("--read", default="", help="ARM:ckpt, for example A1:long, to run end to end")
ap.add_argument("--max_pages", type=int, default=0)
ap.add_argument("--conf", type=float, default=0.25)
ap.add_argument("--out", default=LD_OUT + "/det_eval")
a = ap.parse_args()
os.makedirs(a.out, exist_ok=True)
if os.path.isdir(a.weights): # BLLA: the newest best_*.safetensors of a training folder
import glob
cands = sorted(glob.glob(a.weights + "/best_*.safetensors"), key=os.path.getmtime)
if cands:
a.weights = cands[-1]
else: # training was stopped before ketos wrote its best weights: convert the newest Lightning checkpoint
from kraken.models.convert import convert_models
ck = sorted(glob.glob(a.weights + "/checkpoint_*.ckpt"), key=os.path.getmtime)[-1]
a.weights = convert_models([ck], os.path.join(a.out, a.name + "_converted.safetensors"), weights_format="safetensors")
pages = read_manifest(a.pages)
if a.max_pages:
pages = pages[:a.max_pages]
dev = torch.device("cuda")
torch.cuda.reset_peak_memory_stats()
if a.kind == "yolo":
from ultralytics import YOLO
det = YOLO(a.weights)
else:
from kraken.configs import SegmentationInferenceConfig
from kraken.tasks import SegmentationTaskModel
det = SegmentationTaskModel.load_model(a.weights)
scfg = SegmentationInferenceConfig(accelerator="gpu", device="0")
reader = None
if a.read:
from PIL import Image
from kraken.lib.codec import PytorchCodec
from . import data as D
from .models import build_arm_for_inference
arm_name, ck = a.read.split(":")
c = torch.load("%s/%s/%s.pt" % (LD_CKPT, arm_name, ck), map_location="cpu", weights_only=False)
codec = PytorchCodec(c["codec_c2l"])
reader = build_arm_for_inference(arm_name, codec)
reader.load_inference_state(c["state"])
reader.to(dev)
reader.eval()
spec = D.SPECS[arm_name]
l2c = codec.l2c_single
from .common import to_report_text
tp = {0.5: 0, 0.75: 0}
npred = ngt = 0
ink_in = ink_tot = 0
times = []
ro_e = of_e = ref_n = 0
pred_dump = open("%s/%s_pages.jsonl" % (a.out, a.name), "w")
for k, pg in enumerate(pages):
gt = json.loads(pg["boxes_json"])
polys = json.loads(pg["polys_json"])
im_bgr = cv2.imread(pg["image"], cv2.IMREAD_COLOR)
if a.kind == "yolo":
t0 = time.time()
r = det.predict(pg["image"], imgsz=1280, conf=a.conf, iou=0.6, max_det=300, device=0, verbose=False)[0]
torch.cuda.synchronize()
times.append(time.time() - t0)
boxes = r.boxes.xyxy.cpu().numpy().tolist()
scores = r.boxes.conf.cpu().numpy().tolist()
else:
from PIL import Image as PILImage
pil = PILImage.open(pg["image"]).convert("RGB")
t0 = time.time()
seg = det.predict(pil, scfg)
torch.cuda.synchronize()
times.append(time.time() - t0)
boxes, scores = [], []
for L in seg.lines:
pts = np.array(L.boundary if L.boundary else L.baseline, dtype=np.float64)
boxes.append([float(pts[:, 0].min()), float(pts[:, 1].min()), float(pts[:, 0].max()), float(pts[:, 1].max())])
scores.append(1.0) # BLLA gives no per-line score
for thr in tp:
tp[thr] += match_count(boxes, scores, gt, thr)
npred += len(boxes)
ngt += len(gt)
gray = cv2.cvtColor(im_bgr, cv2.COLOR_BGR2GRAY)
a_in, a_tot = ink_recall(gray, polys, boxes)
ink_in += a_in
ink_tot += a_tot
rec = {"id": pg["id"], "n_gt": len(gt), "n_pred": len(boxes), "boxes": [[round(v, 1) for v in b] for b in boxes], "scores": [round(float(s), 4) for s in scores]}
if reader is not None:
ref_lines = json.loads(pg["ref_lines_json"]) if pg.get("ref_lines_json") else []
if pg["id"].startswith("school_"):
big = cv2.imread(school_orig(pg["id"]), cv2.IMREAD_COLOR | cv2.IMREAD_IGNORE_ORIENTATION)
sc = 1.0 / float(pg["scale"])
else:
big, sc = im_bgr, 1.0
order = sorted(range(len(boxes)), key=lambda i: (int(((boxes[i][1] + boxes[i][3]) / 2) // 15), (boxes[i][0] + boxes[i][2]) / 2)) # M28: (centre_y // 15, centre_x) in the 1280 px page
crops = []
for i in order:
x0, y0, x1, y1 = boxes[i]
hh = y1 - y0
x0, x1 = x0 - 0.01 * (x1 - x0) - 2, x1 + 0.01 * (x1 - x0) + 2
y0, y1 = y0 - 0.1 * hh - 1, y1 + 0.1 * hh + 1
X0, Y0, X1, Y1 = [int(round(v * sc)) for v in (max(x0, 0), max(y0, 0), x1, y1)]
X0, Y0 = max(X0, 0), max(Y0, 0)
X1, Y1 = min(X1, big.shape[1]), min(Y1, big.shape[0])
if X1 - X0 < 4 or Y1 - Y0 < 4:
crops.append(None)
continue
crops.append(Image.fromarray(cv2.cvtColor(big[Y0:Y1, X0:X1], cv2.COLOR_BGR2RGB)))
hyp_lines = []
valid = [(i, c) for i, c in enumerate(crops) if c is not None]
for s0 in range(0, len(valid), 16):
chunk = valid[s0:s0 + 16]
ts = [D.pil_tensor(c, spec) for _, c in chunk]
wmax = max(t.shape[-1] for t in ts)
x = torch.stack([torch.nn.functional.pad(t, (0, wmax - t.shape[-1])) for t in ts])
sl = torch.LongTensor([t.shape[-1] for t in ts])
lp, ol = reader.infer(x, sl, dev)
am = lp.argmax(-1).cpu().numpy()
for b in range(len(chunk)):
prev, ch = 0, []
for t in range(int(ol[b])):
kk = int(am[b, t])
if kk != prev and kk != 0:
ch.append(l2c.get(kk, ""))
prev = kk
hyp_lines.append(to_report_text("".join(ch)).strip())
ref_n_lines = [r for r in ref_lines]
ro, of, nref = page_cers(hyp_lines, ref_n_lines)
ro_e += ro
of_e += of
ref_n += nref
rec["hyp_lines"] = hyp_lines
pred_dump.write(json.dumps(rec, ensure_ascii=False) + "\n")
pred_dump.close()
out = {"name": a.name, "kind": a.kind, "weights": a.weights, "pages_file": a.pages, "n_pages": len(pages), "n_gt_lines": ngt, "n_pred_lines": npred,
"conf_threshold": a.conf, "created": utcnow(), "gpu": torch.cuda.get_device_name(0),
"mean_seconds_per_page": float(np.mean(times)), "peak_gpu_gib_allocated": torch.cuda.max_memory_allocated() / 2 ** 30,
"peak_gpu_gib_reserved": torch.cuda.max_memory_reserved() / 2 ** 30,
"text_pixel_recall": ink_in / max(ink_tot, 1), "ink_pixels_in_ground_truth_polygons": ink_tot}
for thr, v in tp.items():
P, R = v / max(npred, 1), v / max(ngt, 1)
out["iou_%.2f" % thr] = {"tp": v, "precision": P, "recall": R, "f1": (2 * P * R / (P + R)) if P + R else 0.0}
if reader is not None:
out["end_to_end"] = {"reader": a.read, "reading_order_page_cer": ro_e / max(ref_n, 1), "order_free_page_cer": of_e / max(ref_n, 1),
"reference_chars": ref_n, "note": "reference = ground-truth lines of the page (school val: reconstructed from word annotations)"}
save_json("%s/%s.json" % (a.out, a.name), out)
print(json.dumps(out, indent=1, ensure_ascii=False))
if __name__ == "__main__":
main()
|