#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
# Copyright (c) 2026 Rotem Tzemah (TaskVerdict). See LICENSE in this folder (MIT).
"""OCR exact-text scorer for the image exact-text suite (IMG-02 counting, IMG-03 poster, IMG-04 label).

Two phases, so no OCR number is ever published without a human look:
  1) score     : folder of images -> data/test_runs/<run_id>/ (copies of the originals, raw OCR text, results.jsonl,
                 human_review.csv, manifest.json with sha256 of every file). Status of every row = "pending_human_check".
  2) finalize  : merge the filled human_review.csv (the protocol asks for two raters) -> final exact-match verdicts,
                 status "ok", summary.json + summary.md, manifest re-hashed.
                 NOTE: published runs 1 and 2 did NOT use finalize. One lab reviewer made the visual check; the verdicts
                 are in each run's visual_review.json. The OCR numbers (phase 1) are what this script reproduces.

Usage
  python3 ocr_scorer.py score    --input <folder> --plan-tier "Free" [--suite <suite.json>] [--out <dir>] [--operator lab] [--note "..."]
  python3 ocr_scorer.py finalize --run <run_id or run dir> [--out <dir>]
  python3 ocr_scorer.py selftest [--out <dir>]   # synthetic PIL images (NOT a tool result)
  --suite defaults to suites/image_exact_text.json next to this script (lab repo) or ../suites/image_exact_text.v0.1.json
  (public replication pack layout, /lab/code/ + /lab/suites/). --out defaults to $HARNESS_RUNS_DIR or <repo>/data/test_runs.

Input file naming: <tool_id>__<TASK>__r<N>.<png|jpg|jpeg|webp>   e.g. ideogram__IMG-03__r1.png
Prompts/expected strings: the image exact-text suite (public copy: /lab/suites/image_exact_text.v0.1.json).

Metrics per expected string (best over several OCR passes: 3 preprocessings x 3 Tesseract page-segmentation modes):
  exact_verbatim   : the string appears verbatim (case + punctuation, whitespace collapsed) in some pass
  exact_normalized : case-insensitive, punctuation ignored (letters/digits/spaces only) - e.g. "FRIDAY 21:00 · FREE ENTRY"
                     matches "friday 2100 free entry". This is the headline OCR "exact match".
  char_accuracy    : 1 - (edit distance of the normalized string to its best-matching span in the OCR text) / length.
                     "OCR character accuracy" in our image benchmark protocol.
OCR misses stylised text (false negatives) and ignores extra letters around a match (false positives), so the FINAL
exact-match verdict is the human one (from the full-size image); OCR is the measured supporting signal.
"""
import argparse, csv, datetime as dt, hashlib, json, os, platform, re, shutil, subprocess, sys, tempfile, uuid
from pathlib import Path

ROOT = Path(__file__).resolve().parents[2]
_HERE = Path(__file__).resolve().parent
SUITE = next((p for p in (_HERE / "suites" / "image_exact_text.json", _HERE.parent / "suites" / "image_exact_text.v0.1.json") if p.exists()),
             _HERE / "suites" / "image_exact_text.json")
RUNS = Path(os.environ.get("HARNESS_RUNS_DIR", ROOT / "data" / "test_runs"))
VERSION = "0.1.0"
NAME_RE = re.compile(r"^(?P<tool>[a-z0-9][a-z0-9._-]*)__(?P<task>IMG-\d\d)__r(?P<rep>\d+)\.(png|jpe?g|webp)$", re.I)
PSMS = (11, 6, 3)

def now(): return dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
def sha_file(p): return hashlib.sha256(Path(p).read_bytes()).hexdigest()

def norm_verbatim(s): return re.sub(r"\s+", " ", s.replace("\u00a0", " ")).strip()
def norm_loose(s):
    s = s.upper()
    s = re.sub(r"[^0-9A-Z\u0590-\u05FF ]+", " ", s)   # letters (Latin/Hebrew), digits, spaces
    return re.sub(r"\s+", " ", s).strip()

def best_span_distance(pattern, text):
    """Sellers' algorithm: min edit distance between `pattern` and any substring of `text` (free start/end in text)."""
    if not pattern: return 0
    prev = [0] * (len(text) + 1)
    for i, pc in enumerate(pattern, 1):
        cur = [i] + [0] * len(text)
        for j, tc in enumerate(text, 1):
            cur[j] = min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (pc != tc))
        prev = cur
    return min(prev)

def tesseract_version():
    try: return subprocess.run(["tesseract", "--version"], capture_output=True, text=True).stdout.splitlines()[0]
    except Exception: return None

def ocr_passes(img_path, lang="eng"):
    """Return {pass_name: text}. Pre-processings: original, grayscale+autocontrast x2 upscale, inverted grayscale."""
    from PIL import Image, ImageOps
    im = Image.open(img_path); im.load()
    im = ImageOps.exif_transpose(im).convert("RGB")
    g = ImageOps.autocontrast(ImageOps.grayscale(im))
    if max(g.size) < 2000: g = g.resize((g.width * 2, g.height * 2), Image.LANCZOS)
    variants = {"orig": im, "gray2x": g, "inv2x": ImageOps.invert(g)}
    out = {}
    with tempfile.TemporaryDirectory() as td:
        for vname, v in variants.items():
            p = Path(td) / f"{vname}.png"; v.save(p)
            for psm in PSMS:
                r = subprocess.run(["tesseract", str(p), "stdout", "--psm", str(psm), "-l", lang], capture_output=True, text=True)
                out[f"{vname}_psm{psm}"] = r.stdout
    return out

def score_strings(strings, passes):
    res = []
    for s in strings:
        tv, tl = norm_verbatim(s), norm_loose(s)
        best = None
        for pname, txt in passes.items():
            ov, ol = norm_verbatim(txt), norm_loose(txt)
            d = best_span_distance(tl, ol)
            acc = max(0.0, 1 - d / max(1, len(tl)))
            cand = dict(target=s, exact_verbatim=tv in ov, exact_normalized=(d == 0), char_accuracy=round(acc, 4), best_pass=pname)
            key = (cand["exact_verbatim"], cand["exact_normalized"], cand["char_accuracy"])
            if best is None or key > (best["exact_verbatim"], best["exact_normalized"], best["char_accuracy"]): best = cand
        res.append(best)
    return res

def _apply_common(a):
    """--suite / --out overrides (so the script runs from the public pack with relative paths)."""
    global SUITE, RUNS
    if getattr(a, "suite", None): SUITE = Path(a.suite).resolve()
    if getattr(a, "out", None): RUNS = Path(a.out).resolve()
    if not SUITE.exists(): sys.exit(f"suite not found: {SUITE} (pass --suite)")

def load_suite():
    s = json.loads(SUITE.read_text()); return s, {i["task_id"]: i for i in s["items"]}

def write_manifest(rdir, base):
    files = {p.relative_to(rdir).as_posix(): sha_file(p) for p in sorted(rdir.rglob("*")) if p.is_file() and p.name != "manifest.json"}
    base["files"] = files
    (rdir / "manifest.json").write_text(json.dumps(base, indent=1, ensure_ascii=False))

REVIEW_COLS = ["output_id", "tool_id", "task_id", "repetition", "file", "ocr_exact_normalized_all", "ocr_char_accuracy_mean",
               "rater1_id", "rater1_text_exact", "rater1_apples", "rater1_bananas", "rater1_sides_ok",
               "rater2_id", "rater2_text_exact", "rater2_apples", "rater2_bananas", "rater2_sides_ok", "notes"]

def cmd_score(a, mode="manual_ui", out_root=None, extra_note=None):
    suite, by_task = load_suite()
    src = Path(a.input)
    imgs = sorted(p for p in src.iterdir() if p.is_file() and NAME_RE.match(p.name))
    skipped = sorted(p.name for p in src.iterdir() if p.is_file() and not NAME_RE.match(p.name) and p.suffix.lower() in (".png", ".jpg", ".jpeg", ".webp"))
    if not imgs: sys.exit(f"no images named <tool_id>__IMG-0X__r<N>.<ext> in {src}")
    run_id = dt.datetime.now(dt.timezone.utc).strftime("%Y%m%dT%H%M%SZ") + ("-selftest-" if mode == "scorer_selftest" else "-ocr-") + uuid.uuid4().hex[:6]
    rdir = (out_root or RUNS) / run_id
    (rdir / "outputs").mkdir(parents=True); (rdir / "ocr").mkdir()
    started = now(); results = []; review = []
    for p in imgs:
        m = NAME_RE.match(p.name); tool, task, rep = m["tool"], m["task"].upper(), int(m["rep"])
        if task not in by_task: print(f"skip {p.name}: {task} not in suite"); continue
        item = by_task[task]
        dst = rdir / "outputs" / p.name; shutil.copy2(p, dst)
        oid = f"{run_id}:{tool}:{item['item_id']}:{rep}"
        checks, auto = [], None
        if item["measured"] == "ocr_strings":
            passes = ocr_passes(dst)
            (rdir / "ocr" / (p.stem + ".json")).write_text(json.dumps(passes, indent=1, ensure_ascii=False))
            sc = score_strings(item["strings"], passes)
            checks = [dict(type="ocr_string", **x) for x in sc]
            auto = round(sum(x["char_accuracy"] for x in sc) / len(sc), 4)
        else:
            checks = [dict(type="human_counts", expect=item["expect"], note="filled in at finalize from human_review.csv")]
        results.append(dict(output_id=oid, run_id=run_id, target_id=tool, tool_id=tool, model=None, response_model=a.model or None,
                            task_id=task, item_id=item["item_id"], repetition=rep, prompt_sha256=item["prompt_sha256"],
                            output_path=f"outputs/{p.name}", output_sha256=sha_file(dst), started_at=started, latency_ms=None, ttft_ms=None,
                            input_tokens=None, output_tokens=None, cost_usd=None, cost_is_estimate=True, status="pending_human_check",
                            error=None, checks=checks, auto_score=auto, ocr_exact_normalized_all=(all(c.get("exact_normalized") for c in checks) if auto is not None else None),
                            human=None, final_exact=None, trap=False, timed_for_speed=False, judged_criteria=[], plan_tier=a.plan_tier))
        review.append({"output_id": oid, "tool_id": tool, "task_id": task, "repetition": rep, "file": f"outputs/{p.name}",
                       "ocr_exact_normalized_all": results[-1]["ocr_exact_normalized_all"], "ocr_char_accuracy_mean": auto})
    with open(rdir / "results.jsonl", "w") as f:
        for r in results: f.write(json.dumps(r, ensure_ascii=False) + "\n")
    with open(rdir / "human_review.csv", "w", newline="") as f:
        w = csv.DictWriter(f, fieldnames=REVIEW_COLS); w.writeheader()
        for r in review: w.writerow(r)
    note = extra_note or a.note or "Manual UI run. OCR scores are supporting evidence; final exact-match verdicts come from two human raters (finalize)."
    base = dict(run_id=run_id, suite_id=suite["suite_id"], suite_version=suite["version"], category_id="image", mode=mode,
                started_at=started, finished_at=now(), harness_version=f"ocr_scorer {VERSION}", methodology_version="0.2",
                operator=a.operator, reps=suite["protocol"]["repetitions"], targets=sorted({r["tool_id"] for r in results}),
                plan_tier=a.plan_tier, suite_sha256=sha_file(SUITE), skipped_files=skipped,
                environment=dict(python=platform.python_version(), os=platform.platform(), tesseract=tesseract_version(), ocr_passes=[f"{v}_psm{p}" for v in ("orig", "gray2x", "inv2x") for p in PSMS]),
                note=note)
    write_manifest(rdir, base)
    print(f"run_id={run_id}\ndir={rdir}\nimages={len(results)} skipped={len(skipped)}")
    for r in results:
        if r["auto_score"] is not None:
            print(f"  {r['tool_id']:<24} {r['task_id']} r{r['repetition']}  ocr_exact_all={r['ocr_exact_normalized_all']!s:<5}  char_acc={r['auto_score']:.3f}")
        else:
            print(f"  {r['tool_id']:<24} {r['task_id']} r{r['repetition']}  (counting: human_review.csv)")
    print(f"next: two raters fill {rdir/'human_review.csv'} then: ocr_scorer.py finalize --run {run_id}")
    return rdir

def _yn(v):
    v = (v or "").strip().lower()
    return True if v in ("y", "yes", "1", "true") else False if v in ("n", "no", "0", "false") else None

def cmd_finalize(a):
    rdir = Path(a.run) if Path(a.run).is_dir() else RUNS / a.run
    man = json.loads((rdir / "manifest.json").read_text())
    rows = {r["output_id"]: r for r in csv.DictReader(open(rdir / "human_review.csv"))}
    results = [json.loads(l) for l in open(rdir / "results.jsonl")]
    problems = []
    for r in results:
        h = rows.get(r["output_id"]) or {}
        if not h.get("rater1_id") or not h.get("rater2_id") or h["rater1_id"] == h["rater2_id"]:
            problems.append(f"{r['output_id']}: needs two different rater ids"); continue
        if r["task_id"] == "IMG-02":
            vals = []
            for k in ("rater1", "rater2"):
                try: ap, ba = int(h[f"{k}_apples"]), int(h[f"{k}_bananas"])
                except (TypeError, ValueError): problems.append(f"{r['output_id']}: {k} counts missing"); break
                sides = _yn(h.get(f"{k}_sides_ok"))
                if sides is None: problems.append(f"{r['output_id']}: {k}_sides_ok must be y/n"); break
                vals.append((ap, ba, sides))
            if len(vals) < 2: continue
            if vals[0] != vals[1]: problems.append(f"{r['output_id']}: raters disagree {vals} -> third rater, then make both rows agree"); continue
            ap, ba, sides = vals[0]; exp = r["checks"][0]["expect"]
            r["human"] = dict(apples=ap, bananas=ba, sides_ok=sides, raters=[h["rater1_id"], h["rater2_id"]])
            r["final_exact"] = (ap == exp["apples"] and ba == exp["bananas"] and sides)
            r["auto_score"] = 1.0 if r["final_exact"] else 0.0
        else:
            v1, v2 = _yn(h.get("rater1_text_exact")), _yn(h.get("rater2_text_exact"))
            if v1 is None or v2 is None: problems.append(f"{r['output_id']}: rater*_text_exact must be y/n"); continue
            if v1 != v2: problems.append(f"{r['output_id']}: raters disagree on exact text -> third rater, then make both rows agree"); continue
            r["human"] = dict(text_exact=v1, raters=[h["rater1_id"], h["rater2_id"]], notes=h.get("notes") or None)
            r["final_exact"] = v1
            if r.get("ocr_exact_normalized_all") is not None and r["ocr_exact_normalized_all"] != v1:
                r["ocr_human_disagree"] = True
        r["status"] = "ok"
    if problems:
        print("NOT finalized:\n  - " + "\n  - ".join(problems)); sys.exit(1)
    with open(rdir / "results.jsonl", "w") as f:
        for r in results: f.write(json.dumps(r, ensure_ascii=False) + "\n")
    summ = {}
    for r in results:
        s = summ.setdefault(r["tool_id"], {}).setdefault(r["task_id"], dict(n=0, exact=0, char_acc=[]))
        s["n"] += 1; s["exact"] += int(bool(r["final_exact"]))
        if r["task_id"] != "IMG-02" and r["checks"]: s["char_acc"].append(r["checks"] and sum(c["char_accuracy"] for c in r["checks"]) / len(r["checks"]))
    lines = [f"# Exact-text summary · run {man['run_id']}", "", f"Mode: {man['mode']} · plan tier: {man.get('plan_tier')} · finalized {now()}", "",
             "| Tool | Task | Images | Human-confirmed exact | OCR char accuracy (median) |", "|---|---|---:|---:|---:|"]
    for tool, tasks in sorted(summ.items()):
        for task, s in sorted(tasks.items()):
            ca = sorted(s.pop("char_acc")); med = ca[len(ca) // 2] if ca else None
            s["char_acc_median"] = med
            lines.append(f"| {tool} | {task} | {s['n']} | {s['exact']}/{s['n']} | {'' if med is None else f'{med:.3f}'} |")
    (rdir / "summary.json").write_text(json.dumps(summ, indent=1)); (rdir / "summary.md").write_text("\n".join(lines) + "\n")
    man["finalized_at"] = now(); write_manifest(rdir, man)
    print("\n".join(lines))

def cmd_selftest(a):
    """Synthetic images drawn with PIL to prove the scorer works. NOT a tool result; stored under data/test_runs/_selftest/."""
    from PIL import Image, ImageDraw, ImageFont
    font = "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"
    F = lambda n: ImageFont.truetype(font, n)
    td = Path(tempfile.mkdtemp(prefix="ocr_selftest_"))
    def poster(path, head, foot, bg=(16, 32, 96), fg=(255, 255, 255)):
        im = Image.new("RGB", (1024, 1024), bg); d = ImageDraw.Draw(im)
        d.text((512, 330), head, font=F(84), fill=fg, anchor="mm")
        d.ellipse((430, 450, 594, 614), outline=fg, width=10)   # stand-in for the saxophone illustration
        d.text((512, 900), foot, font=F(44), fill=fg, anchor="mm"); im.save(path)
    def label(path, lines):
        im = Image.new("RGB", (1024, 1024), (196, 160, 112)); d = ImageDraw.Draw(im)
        d.rectangle((212, 260, 812, 760), fill=(245, 240, 228))
        for k, (t, n) in enumerate(lines): d.text((512, 360 + k * 140), t, font=F(n), fill=(30, 30, 30), anchor="mm")
        im.save(path)
    # expected outcomes are asserted below
    poster(td / "selftest-correct__IMG-03__r1.png", "JAZZ ON THE ROOF", "FRIDAY 21:00 · FREE ENTRY")
    poster(td / "selftest-misspelt__IMG-03__r1.png", "JAZZ ON THE R0OF", "FRlDAY 21:00 · FREE ENTRV")
    Image.new("RGB", (1024, 1024), (16, 32, 96)).save(td / "selftest-blank__IMG-03__r1.png")
    label(td / "selftest-correct__IMG-04__r1.png", [("NORTHSTAR ROASTERS", 58), ("ETHIOPIA YIRGACHEFFE", 50), ("250 g · Light Roast", 46)])
    Image.new("RGB", (1024, 1024), (128, 128, 128)).save(td / "selftest-synthetic__IMG-02__r1.png")
    ns = argparse.Namespace(input=str(td), plan_tier="n/a (synthetic)", operator="lab-selftest", note=None, model="PIL synthetic")
    rdir = cmd_score(ns, mode="scorer_selftest", out_root=RUNS / "_selftest",
                     extra_note="SCORER SELF-TEST on synthetic images drawn with PIL by the lab. NOT a tool result, never ingest, never publish.")
    res = {r["tool_id"] + "/" + r["task_id"]: r for r in map(json.loads, open(rdir / "results.jsonl"))}
    expect = {"selftest-correct/IMG-03": True, "selftest-misspelt/IMG-03": False, "selftest-blank/IMG-03": False, "selftest-correct/IMG-04": True}
    ok = True
    for k, want in expect.items():
        got = res[k]["ocr_exact_normalized_all"]
        print(f"  [{'PASS' if got == want else 'FAIL'}] {k}: ocr_exact_all={got} expected={want} char_acc={res[k]['auto_score']}")
        ok &= (got == want)
    ok &= res["selftest-misspelt/IMG-03"]["auto_score"] < 1.0 and res["selftest-blank/IMG-03"]["auto_score"] < 0.3
    (rdir / "SELFTEST_README.txt").write_text("Scorer self-test on synthetic PIL images (not AI tool outputs). Checks that exact text is matched, misspellings and blanks are not.\n"
                                            f"Result: {'PASS' if ok else 'FAIL'}\n")
    man = json.loads((rdir / "manifest.json").read_text()); man["selftest_result"] = "PASS" if ok else "FAIL"; write_manifest(rdir, man)
    shutil.rmtree(td)
    print("SELFTEST", "PASS" if ok else "FAIL"); sys.exit(0 if ok else 1)

def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    sp = ap.add_subparsers(dest="cmd", required=True)
    s = sp.add_parser("score"); s.add_argument("--input", required=True); s.add_argument("--plan-tier", required=True, help="e.g. 'Free', 'Paid: Ideogram Plus', 'Vendor-provided'")
    s.add_argument("--operator", default="lab"); s.add_argument("--note"); s.add_argument("--model", help="model/version string shown in the UI (if one tool per folder)")
    f = sp.add_parser("finalize"); f.add_argument("--run", required=True)
    t = sp.add_parser("selftest")
    for x in (s, f, t):
        x.add_argument("--suite", help="suite JSON (default: see Usage)"); x.add_argument("--out", help="output root for run folders")
    a = ap.parse_args(); _apply_common(a)
    {"score": cmd_score, "finalize": cmd_finalize, "selftest": cmd_selftest}[a.cmd](a)

if __name__ == "__main__":
    main()
