Files
music-album-art-processor/cdcrop_ui.py
T

898 lines
56 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""
cdcrop_ui.py - local review interface for cdcrop.
python cdcrop_ui.py (opens http://127.0.0.1:8765 in your browser)
python cdcrop_ui.py --port 9000 --no-browser
Everything runs on this computer: the server only listens on 127.0.0.1 and
nothing is sent anywhere. Put cdcrop.py next to this file.
Workflow
1. Choose a scans folder and an output folder, press Process. Every cover is
cropped at the automatic choice and written straight away, so covers you
never open are already done.
2. Review: flagged covers come first. Open one, pick an angle, press Enter.
The full-resolution PNG is re-rendered and your choice is logged to
OUTDIR/cdcrop_decisions.csv (used to calibrate the automatic choice).
3. Close the window and re-open later: reviewing resumes where you left off.
Keys in the detail view
1-9 pick a candidate (shown on its button) A / B automatic / alternative
< > nudge 0.01 deg (Shift: 0.05, Ctrl: 0.1)
Space blink: flip to the previous angle and back
G grid overlay Z zoom panel on/off
Enter accept & save Esc back to grid
N / P next / previous cover
"""
import argparse
import csv
import io
import json
import math
import os
import pickle
import sys
import threading
import time
import traceback
import webbrowser
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlparse
import cv2
import numpy as np
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import cdcrop # noqa: E402
PREVIEW_SHRINK = 3 # cached preview source is 1/3 scale
REGION_MARGIN = 120 # px of scan kept around each cover (for re-rendering)
CTX_MARGIN = 100 # px of that margin the "context" view is allowed to show
LAST_RUN_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "cdcrop_ui_last.json")
# ---------------------------------------------------------------- processing
def _cover_entry(arr, gray, cov, base, idx, path, outdir, mode, dpi, inset, align, scan_px=None, A=None):
"""Crop one cover at the automatic angle, write it, cache what review needs."""
ch = cdcrop.choose_angle(arr, gray, cov, inset)
theta = ch["theta"]
if align != "auto":
src = cov["borrowed"].get(align, align)
if src in cov["edges"]:
theta = cdcrop.edge_theta(src, cov["edges"][src][1])
fr = cdcrop.frame_at(cov, theta, inset)
scan_px = arr if scan_px is None else scan_px
out = cdcrop.render(scan_px, cdcrop.frame_to_scan(fr, A))
cdcrop.save_png(out, mode, dpi, os.path.join(outdir, f"{base}_{idx}.png"))
# cache the scan region around the cover (uint8) + a 1/3-scale copy for previews
q = np.array([_to_scan(p_, A) for p_ in fr["corners"]])
x0, y0 = np.maximum(np.floor(q.min(axis=0)).astype(int) - REGION_MARGIN, 0)
x1 = min(int(np.ceil(q[:, 0].max())) + REGION_MARGIN, scan_px.shape[1])
y1 = min(int(np.ceil(q[:, 1].max())) + REGION_MARGIN, scan_px.shape[0])
region = np.clip(np.rint(scan_px[y0:y1, x0:x1]), 0, 255).astype(np.uint8)
small = cv2.resize(region, (region.shape[1] // PREVIEW_SHRINK, region.shape[0] // PREVIEW_SHRINK),
interpolation=cv2.INTER_AREA)
cid = f"{base}_{idx}"
cdir = os.path.join(outdir, "_cache")
os.makedirs(cdir, exist_ok=True)
cv2.imwrite(os.path.join(cdir, cid + "_small.jpg"), cv2.cvtColor(small, cv2.COLOR_RGB2BGR),
[cv2.IMWRITE_JPEG_QUALITY, 95])
named = {k: float(v["theta"]) for k, v in ch["named"].items()}
key = None
if ch["segs"]:
vs = [s for s in ch["segs"] if s[2]] or list(ch["segs"])
P, Q, vert, L = max(vs, key=lambda s: s[3])
key = {"P": [float(P[0]), float(P[1])], "Q": [float(Q[0]), float(Q[1])], "vert": bool(vert), "L": float(L)}
with open(os.path.join(cdir, cid + "_cov.pkl"), "wb") as fh:
pickle.dump({"cov": cov, "offset": (int(x0), int(y0)), "end": (int(x1), int(y1)),
"mode": mode, "dpi": dpi, "inset": inset, "key": key,
"scan_path": os.path.abspath(path), "A": None if A is None else A.tolist()}, fh)
notes = []
for k in cov["soft"]:
notes.append(f"{k} edge has no crisp line (fold / lifted / worn); cropped where in-focus art begins")
if abs(fr["W"] / fr["H"] - 1) > 0.02:
notes.append(f"not square ({fr['W'] / fr['H']:.3f}) - fine for inlays/digipaks")
flagged = ch["alt"] is not None
if flagged:
notes.insert(0, ("close call" if ch["alt_why"] == "close call"
else f"turned {theta - ch['alt']:+.2f} deg from the left edge") +
f" - alternative {ch['alt']:+.3f} deg")
return {
"id": cid, "scan": os.path.basename(path), "cover": idx,
"auto": float(theta), "alt": None if ch["alt"] is None else float(ch["alt"]),
"alt_why": ch["alt_why"], "named": named, "soft": cov["soft"],
"edges": {k: (None if k in cov["soft"] else float(cdcrop.edge_theta(k, cov["edges"][k][1])))
for k in ("left", "right", "top", "bottom")},
"flagged": flagged, "notes": notes, "size": [fr["W"], fr["H"]],
"chosen": None, "status": "auto", "edge_adj": {},
}
def _to_scan(p, A):
p = np.asarray(p, float)
return p if A is None else np.asarray(A)[:, :2] @ p + np.asarray(A)[:, 2]
def _cache_region(arr, poly, cid, outdir, A=None):
q = np.array([_to_scan(p_, A) for p_ in poly])
x0, y0 = np.maximum(np.floor(q.min(axis=0)).astype(int) - REGION_MARGIN, 0)
x1 = min(int(np.ceil(q[:, 0].max())) + REGION_MARGIN, arr.shape[1])
y1 = min(int(np.ceil(q[:, 1].max())) + REGION_MARGIN, arr.shape[0])
region = np.clip(np.rint(arr[y0:y1, x0:x1]), 0, 255).astype(np.uint8)
small = cv2.resize(region, (region.shape[1] // PREVIEW_SHRINK, region.shape[0] // PREVIEW_SHRINK),
interpolation=cv2.INTER_AREA)
cdir = os.path.join(outdir, "_cache")
os.makedirs(cdir, exist_ok=True)
cv2.imwrite(os.path.join(cdir, cid + "_small.jpg"), cv2.cvtColor(small, cv2.COLOR_RGB2BGR),
[cv2.IMWRITE_JPEG_QUALITY, 95])
return (int(x0), int(y0)), (int(x1), int(y1))
def _disc_entry(arr, gray, rect, base, idx, path, outdir, mode, dpi, scan_px=None, A=None):
(cx0, cy0), (w0, h0), _ = rect
center, R = cdcrop.fit_disc(arr, (cx0, cy0), (dpi or (600, 600))[0], (w0 + h0) / 2)
ori = cdcrop.disc_orientation(gray, center, R)
theta = ori["auto"]
fr = cdcrop.disc_frame(center, R, theta)
scan_px = arr if scan_px is None else scan_px
cdcrop.save_png(cdcrop.render(scan_px, cdcrop.frame_to_scan(fr, A)), mode, dpi,
os.path.join(outdir, f"{base}_{idx}.png"))
cid = f"{base}_{idx}"
off, end = _cache_region(scan_px, fr["corners"], cid, outdir, A)
with open(os.path.join(outdir, "_cache", cid + "_cov.pkl"), "wb") as fh:
pickle.dump({"type": "disc", "center": [float(center[0]), float(center[1])], "R": float(R),
"offset": off, "end": end, "mode": mode, "dpi": dpi,
"scan_path": os.path.abspath(path), "A": None if A is None else A.tolist()}, fh)
mm = 2 * R / (dpi or (600,))[0] * 25.4
notes = [f"disc {mm:.1f} mm - {ori['why']}"]
if ori["flagged"]:
notes.insert(0, "orientation needs a look")
return {"id": cid, "scan": os.path.basename(path), "cover": idx, "type": "disc",
"auto": float(theta), "alt": None, "alt_why": None,
"named": {k: float(v) for k, v in ori["candidates"].items()}, "soft": [],
"edges": {}, "flagged": ori["flagged"], "notes": notes, "size": [fr["W"], fr["H"]],
"chosen": None, "status": "auto"}
def process_scan(job):
"""Worker: one scan -> list of cover entries (runs in a separate process)."""
path, outdir, count, inset, align, cal = job
import warnings
warnings.simplefilter("ignore")
try:
arr8, mode, dpi = cdcrop.load_scan(path)
scan_px = arr8.astype(np.float32)
arr, A = cdcrop.true_space(scan_px, cal) # measure in true geometry
gray = arr[..., :3].mean(axis=2) if arr.ndim == 3 else arr
objs = cdcrop.find_objects(arr, count, dpi)
base = os.path.splitext(os.path.basename(path))[0]
entries = []
for idx, (kind, rect, _) in enumerate(objs, start=1):
if kind == "disc":
entries.append(_disc_entry(arr, gray, rect, base, idx, path, outdir, mode, dpi, scan_px, A))
else:
cov = cdcrop.analyze_cover(arr, rect)
entries.append(_cover_entry(arr, gray, cov, base, idx, path, outdir, mode, dpi, inset, align,
scan_px, A))
err = None if len(objs) == count else f"found {len(objs)} item(s), expected {count}"
return {"scan": os.path.basename(path), "entries": entries, "error": err}
except Exception as e:
return {"scan": os.path.basename(path), "entries": [], "error": f"{e}\n{traceback.format_exc()}"}
class Session:
"""All state for one output folder. Persists to OUTDIR/_cache/index.json."""
def __init__(self):
self.lock = threading.Lock()
self.outdir = None
self.scans_dir = None
self.entries = {} # id -> entry
self.order = [] # ids in scan order
self.progress = {"running": False, "done": 0, "total": 0, "current": "", "errors": []}
self.settings = {"count": 2, "inset": 1.0, "jobs": 2, "align": "auto"}
self._cache = {} # id -> (region, small, meta) small LRU
# -- persistence
def index_path(self):
return os.path.join(self.outdir, "_cache", "index.json")
def save(self):
if not self.outdir:
return
os.makedirs(os.path.join(self.outdir, "_cache"), exist_ok=True)
with self.lock:
data = {"scans_dir": self.scans_dir, "settings": self.settings,
"order": self.order, "entries": self.entries}
tmp = self.index_path() + ".tmp"
with open(tmp, "w") as fh:
json.dump(data, fh)
os.replace(tmp, self.index_path())
def open(self, outdir, scans_dir=None):
self.outdir = os.path.abspath(outdir)
self.entries, self.order, self._cache = {}, [], {}
if os.path.exists(self.index_path()):
with open(self.index_path()) as fh:
data = json.load(fh)
self.entries = data.get("entries", {})
self.order = sorted(data.get("order", []))
self.settings.update(data.get("settings", {}))
self.scans_dir = data.get("scans_dir")
if scans_dir:
self.scans_dir = os.path.abspath(scans_dir)
with open(LAST_RUN_PATH, "w") as fh: # so the next launch reopens this folder
json.dump({"outdir": self.outdir}, fh)
# -- processing
def start(self, scans_dir, outdir, settings, redo=False):
if self.progress["running"]:
return "already processing"
os.makedirs(os.path.join(os.path.abspath(outdir), "_cache"), exist_ok=True)
self.open(outdir, scans_dir)
self.settings.update(settings)
files = sorted(f for f in os.listdir(self.scans_dir) if f.lower().endswith(".bmp"))
done_scans = {e["scan"] for e in self.entries.values()}
todo = [f for f in files if redo or f not in done_scans]
self.progress = {"running": True, "done": 0, "total": len(todo), "current": "", "errors": []}
threading.Thread(target=self._run, args=(todo,), daemon=True).start()
return None
def _run(self, todo):
s = self.settings
cal = self.calibration()
jobs = [(os.path.join(self.scans_dir, f), self.outdir, int(s["count"]), float(s["inset"]), s["align"], cal)
for f in todo]
def absorb(res):
with self.lock:
for e in res["entries"]:
old = self.entries.get(e["id"])
if old and old.get("status") == "reviewed":
e["chosen"], e["status"] = old["chosen"], "reviewed"
e["edge_adj"] = old.get("edge_adj", {})
self.entries[e["id"]] = e
if e["id"] not in self.order:
self.order.append(e["id"])
self.order.sort()
self._cache = {}
if res["error"]:
self.progress["errors"].append(f"{res['scan']}: {res['error'].splitlines()[0]}")
self.progress["done"] += 1
if res["entries"]:
ids = [e["id"] for e in res["entries"]]
chosen = [self.entries[i] for i in ids if self.entries[i]["status"] == "reviewed"]
for e in chosen: # keep an earlier manual choice after re-processing
self.render_full(e["id"], e["chosen"], e.get("edge_adj"))
self.save()
try:
if int(s["jobs"]) > 1 and len(jobs) > 1:
from multiprocessing import get_context
with get_context("spawn").Pool(int(s["jobs"])) as pool:
for res in pool.imap(process_scan, jobs):
absorb(res)
else:
for j in jobs:
self.progress["current"] = os.path.basename(j[0])
absorb(process_scan(j))
finally:
self.progress["running"] = False
self.progress["current"] = ""
self.save()
# -- scanner calibration (scanner_calibration.json next to cdcrop.py)
CAL_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "scanner_calibration.json")
def calibration(self):
if self.settings.get("use_cal", True) and os.path.exists(self.CAL_PATH):
with open(self.CAL_PATH) as fh:
return json.load(fh)
return None
# -- rendering
def load(self, cid):
"""Metadata + 1/3-scale preview from the cache; full-resolution pixels
are read from your original scan when needed (zooms, saving)."""
if cid in self._cache:
return self._cache[cid]
cdir = os.path.join(self.outdir, "_cache")
with open(os.path.join(cdir, cid + "_cov.pkl"), "rb") as fh:
meta = pickle.load(fh)
small = cv2.cvtColor(cv2.imread(os.path.join(cdir, cid + "_small.jpg")), cv2.COLOR_BGR2RGB)
if len(self._cache) > 12:
self._cache.pop(next(iter(self._cache)))
self._cache[cid] = (_LazyRegion(meta), small, meta)
return self._cache[cid]
def frame(self, cid, theta, edge_adj=None):
region, small, meta = self.load(cid)
if meta.get("type") == "disc":
return cdcrop.disc_frame(meta["center"], meta["R"], float(theta)), meta
return cdcrop.frame_at(meta["cov"], float(theta), meta["inset"], edge_adj), meta
def scan_frame(self, cid, theta, edge_adj=None):
"""Output frame in true geometry, expressed in the original scan's pixels."""
fr, meta = self.frame(cid, theta, edge_adj)
A = meta.get("A")
return cdcrop.frame_to_scan(fr, None if A is None else np.array(A)), meta
def preview(self, cid, theta, width, margin=0.0, edge_adj=None):
"""margin: extra context shown around the crop, in crop px - clamped to
CTX_MARGIN so it never reaches past the cached region."""
region, small, meta = self.load(cid)
fr, _ = self.scan_frame(cid, theta, edge_adj)
ox, oy = meta["offset"]
s = width / fr["W"] # output px per crop px
m = min(margin, CTX_MARGIN)
k = PREVIEW_SHRINK
ex, ey = fr["ex"], fr["ey"]
o_full = fr["origin"] - m * ex - m * ey
size = (int(round((fr["W"] + 2 * m) * s)), int(round((fr["H"] + 2 * m) * s)))
src = small if s * k <= 1.0 else np.asarray(region)
if src is small:
o = (o_full - [ox, oy]) / k
M = np.array([[ex[0] / (s * k), ey[0] / (s * k), o[0]],
[ex[1] / (s * k), ey[1] / (s * k), o[1]]])
else:
o = (o_full - [ox, oy])
M = np.array([[ex[0] / s, ey[0] / s, o[0]], [ex[1] / s, ey[1] / s, o[1]]])
return cv2.warpAffine(src, M, size, flags=cv2.INTER_LINEAR | cv2.WARP_INVERSE_MAP,
borderMode=cv2.BORDER_REPLICATE)
def patch(self, cid, theta, cx, cy, n, edge_adj=None):
"""n x n patch of the crop at 1:1 (Lanczos), top-left at crop coords (cx, cy)."""
region, small, meta = self.load(cid)
fr, _ = self.scan_frame(cid, theta, edge_adj)
ox, oy = meta["offset"]
o = fr["origin"] - [ox, oy] + cx * fr["ex"] + cy * fr["ey"]
ex, ey = fr["ex"], fr["ey"]
M = np.array([[ex[0], ey[0], o[0]], [ex[1], ey[1], o[1]]])
return cv2.warpAffine(np.asarray(region), M, (n, n), flags=cv2.INTER_LANCZOS4 | cv2.WARP_INVERSE_MAP,
borderMode=cv2.BORDER_REPLICATE)
def info(self, cid, theta, edge_adj=None):
fr, meta = self.frame(cid, theta, edge_adj)
if meta.get("type") == "disc":
return {"size": [fr["W"], fr["H"]], "disc": True, "edge_dev": {}}
res = {"size": [fr["W"], fr["H"]],
"edge_dev": {k: (None if k in meta["cov"]["soft"] else round(float(v), 3))
for k, v in fr["edge_dev_deg"].items()}}
key = meta.get("key")
if key:
P, Q = np.array(key["P"]), np.array(key["Q"])
uv = lambda p: np.array([(p - fr["origin"]) @ fr["ex"], (p - fr["origin"]) @ fr["ey"]])
p, q = uv(P), uv(Q)
if key["vert"]:
e0, e1 = (p, q) if p[1] < q[1] else (q, p); lean = e1[0] - e0[0]
else:
e0, e1 = (p, q) if p[0] < q[0] else (q, p); lean = e1[1] - e0[1]
res["key"] = {"vert": key["vert"], "L": round(key["L"]), "lean": round(float(lean), 2),
"e0": [float(e0[0]), float(e0[1])], "e1": [float(e1[0]), float(e1[1])]}
return res
def render_full(self, cid, theta, edge_adj=None):
region, small, meta = self.load(cid)
fr, _ = self.scan_frame(cid, theta, edge_adj)
ox, oy = meta["offset"]
f2 = dict(fr)
f2["origin"] = fr["origin"] - [ox, oy]
out = cdcrop.render(np.asarray(region).astype(np.float32), f2)
cdcrop.save_png(out, meta["mode"], meta["dpi"], os.path.join(self.outdir, cid + ".png"))
return fr["W"], fr["H"]
def accept(self, cid, theta, how, edge_adj=None):
edge_adj = edge_adj or {}
with self.lock:
e = self.entries[cid]
W, H = self.render_full(cid, theta, edge_adj)
with self.lock:
e["chosen"], e["status"], e["size"], e["how"] = float(theta), "reviewed", [W, H], how
e["edge_adj"] = edge_adj
log = os.path.join(self.outdir, "cdcrop_decisions.csv")
new = not os.path.exists(log)
with open(log, "a", newline="") as fh:
w = csv.writer(fh)
if new:
w.writerow(["time", "cover", "chosen_deg", "how", "auto_deg", "alt_deg", "flagged",
"left_deg", "right_deg", "top_deg", "bottom_deg",
"left_push_px", "right_push_px", "top_push_px", "bottom_push_px", "candidates"])
ed = e["edges"]
w.writerow([time.strftime("%Y-%m-%d %H:%M:%S"), cid, f"{theta:.4f}", how, f"{e['auto']:.4f}",
"" if e["alt"] is None else f"{e['alt']:.4f}", int(e["flagged"]),
*[("" if k not in ed else "soft" if ed[k] is None else f"{ed[k]:.4f}")
for k in ("left", "right", "top", "bottom")],
*[f"{edge_adj.get(k, 0.0):.1f}" for k in ("left", "right", "top", "bottom")],
json.dumps({k: round(v, 4) for k, v in e["named"].items()})])
self.save()
return W, H
_SCANS = {} # path -> uint8 array; the two most recent scans stay in memory
_SCANS_LOCK = threading.Lock()
def _scan_pixels(path):
with _SCANS_LOCK:
if path not in _SCANS:
if not os.path.exists(path):
raise FileNotFoundError(f"original scan not found: {path} (moved or renamed?)")
arr, _, _ = cdcrop.load_scan(path)
if len(_SCANS) >= 2:
_SCANS.pop(next(iter(_SCANS)))
_SCANS[path] = arr
return _SCANS[path]
class _LazyRegion:
"""The cover's region of the original scan, loaded on first use."""
def __init__(self, meta):
self.meta = meta
self._a = None
def __array__(self, dtype=None, copy=None):
if self._a is None:
x0, y0 = self.meta["offset"]; x1, y1 = self.meta["end"]
self._a = _scan_pixels(self.meta["scan_path"])[y0:y1, x0:x1]
return self._a if dtype is None else self._a.astype(dtype)
S = Session()
# --------------------------------------------------------------------- server
def jpeg(img_rgb, q=88):
ok, buf = cv2.imencode(".jpg", cv2.cvtColor(np.ascontiguousarray(img_rgb), cv2.COLOR_RGB2BGR),
[cv2.IMWRITE_JPEG_QUALITY, q])
return buf.tobytes()
def png(img_rgb):
ok, buf = cv2.imencode(".png", cv2.cvtColor(np.ascontiguousarray(img_rgb), cv2.COLOR_RGB2BGR))
return buf.tobytes()
def _edge_adj(q):
"""Parse the optional ?edge={"top":12,...} query param into a plain dict."""
try:
e = json.loads(q.get("edge") or "{}")
return {k: float(v) for k, v in e.items() if k in ("left", "right", "top", "bottom")}
except (ValueError, TypeError):
return {}
class Handler(BaseHTTPRequestHandler):
def log_message(self, *a):
pass
def _send(self, code, body, ctype="application/json", cache=False):
if isinstance(body, (dict, list)):
body = json.dumps(body).encode()
elif isinstance(body, str):
body = body.encode()
self.send_response(code)
self.send_header("Content-Type", ctype)
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "max-age=3600" if cache else "no-store")
self.end_headers()
self.wfile.write(body)
def do_GET(self):
u = urlparse(self.path)
q = {k: v[0] for k, v in parse_qs(u.query).items()}
try:
if u.path == "/":
return self._send(200, PAGE, "text/html; charset=utf-8")
if u.path == "/api/state":
with S.lock:
ents = [S.entries[i] for i in S.order if i in S.entries]
return self._send(200, {"outdir": S.outdir, "scans_dir": S.scans_dir, "settings": S.settings,
"progress": S.progress, "entries": ents,
"home": os.path.expanduser("~"), "calibration": S.calibration(),
"cal_file": os.path.exists(S.CAL_PATH)})
if u.path == "/api/ls":
p = os.path.abspath(os.path.expanduser(q.get("path") or "~"))
if not os.path.isdir(p):
return self._send(200, {"path": p, "error": "not a folder", "dirs": [], "bmps": 0})
dirs, bmps, files = [], 0, []
try:
for name in sorted(os.listdir(p), key=str.lower):
full = os.path.join(p, name)
if name.startswith(".") or name.startswith("_"):
continue
if os.path.isdir(full):
dirs.append(name)
elif name.lower().endswith(".bmp"):
bmps += 1
files.append(name)
except PermissionError:
pass
return self._send(200, {"path": p, "parent": os.path.dirname(p), "dirs": dirs, "bmps": bmps,
"files": files[:400]})
if u.path == "/api/info":
return self._send(200, S.info(q["id"], float(q["theta"]), _edge_adj(q)))
if u.path == "/img/preview":
img = S.preview(q["id"], float(q["theta"]), int(q.get("w", 900)), float(q.get("margin", 0)),
_edge_adj(q))
return self._send(200, jpeg(img, 90), "image/jpeg", cache=True)
if u.path == "/img/corner":
fr, _ = S.frame(q["id"], float(q["theta"]), _edge_adj(q))
n = int(q.get("n", 160))
c = q["c"]
cx = 0 if c[1] == "l" else fr["W"] - n
cy = 0 if c[0] == "t" else fr["H"] - n
return self._send(200, png(S.patch(q["id"], float(q["theta"]), cx, cy, n, _edge_adj(q))),
"image/png", cache=True)
if u.path == "/img/keyend":
inf = S.info(q["id"], float(q["theta"]), _edge_adj(q))
if "key" not in inf:
return self._send(404, {"error": "no key line"})
e = inf["key"]["e0" if q["end"] == "0" else "e1"]
n = 60
return self._send(200, png(S.patch(q["id"], float(q["theta"]), int(round(e[0])) - n // 2,
int(round(e[1])) - n // 2, n, _edge_adj(q))),
"image/png", cache=True)
return self._send(404, {"error": "not found"})
except Exception as ex:
return self._send(500, {"error": str(ex), "trace": traceback.format_exc()})
def do_POST(self):
u = urlparse(self.path)
n = int(self.headers.get("Content-Length") or 0)
body = json.loads(self.rfile.read(n) or b"{}")
try:
if u.path == "/api/process":
err = S.start(body["scans_dir"], body["outdir"], body.get("settings", {}), body.get("redo", False))
return self._send(200 if not err else 409, {"error": err})
if u.path == "/api/calibrate":
res = cdcrop.calibrate_pair(body["a"], body["b"], verbose=False)
out = cdcrop.add_calibration(S.CAL_PATH, res, reset=bool(body.get("reset")))
out["this_pair"] = {k: res[k] for k in ("y_stretch_pct", "shear_deg")}
if "warning" in res:
out["warning"] = res["warning"]
return self._send(200, out)
if u.path == "/api/usecal":
S.settings["use_cal"] = bool(body.get("on", True)); S.save()
return self._send(200, {"ok": True})
if u.path == "/api/open":
S.open(body["outdir"])
return self._send(200, {"ok": True})
if u.path == "/api/accept":
W, H = S.accept(body["id"], float(body["theta"]), body.get("how", "manual"), body.get("edge"))
return self._send(200, {"ok": True, "size": [W, H]})
return self._send(404, {"error": "not found"})
except Exception as ex:
return self._send(500, {"error": str(ex), "trace": traceback.format_exc()})
PAGE = r"""<!doctype html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>CD Crop Review</title>
<style>
:root{--bg:#1d1e20;--panel:#26282b;--line:#3a3d42;--text:#e8e8e6;--dim:#9a9c9f;--acc:#e0b04a;--ok:#5fb37a;--warn:#e07a4a;--sel:#3d5a80}
*{box-sizing:border-box}html,body{margin:0;height:100%;background:var(--bg);color:var(--text);font:14px/1.4 system-ui,-apple-system,Segoe UI,Roboto,sans-serif}
button{font:inherit;color:var(--text);background:#33363a;border:1px solid var(--line);border-radius:6px;padding:6px 10px;cursor:pointer}
button:hover{border-color:#5a5e64}button.primary{background:var(--acc);color:#1a1a1a;border-color:var(--acc);font-weight:600}
button.on{background:var(--sel);border-color:#6d8fbf}button:disabled{opacity:.45;cursor:default}
input,select{font:inherit;color:var(--text);background:#151618;border:1px solid var(--line);border-radius:6px;padding:6px 8px}
kbd{font:12px ui-monospace,monospace;background:#151618;border:1px solid var(--line);border-bottom-width:2px;border-radius:4px;padding:0 4px;color:var(--dim)}
header{display:flex;align-items:center;gap:14px;padding:10px 16px;border-bottom:1px solid var(--line);background:var(--panel)}
header h1{font-size:15px;margin:0;font-weight:600;letter-spacing:.2px}header .sp{flex:1}
.tabs button{border-radius:6px}.muted{color:var(--dim)}
main{padding:16px}
.card{background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:16px;margin-bottom:16px;max-width:980px}
.row{display:flex;gap:10px;align-items:center;flex-wrap:wrap;margin:8px 0}.row label{min-width:110px;color:var(--dim)}
.row input.path{flex:1;min-width:280px}
.browser{border:1px solid var(--line);border-radius:8px;max-height:260px;overflow:auto;margin-top:6px;background:#151618}
.browser div{padding:4px 10px;cursor:pointer}.browser div:hover{background:#2b2e32}
.bar{height:8px;background:#151618;border-radius:4px;overflow:hidden;margin:8px 0}.bar i{display:block;height:100%;background:var(--acc);width:0}
.filters{display:flex;gap:6px;align-items:center;margin-bottom:12px}
.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(190px,1fr));gap:12px}
.tile{background:var(--panel);border:1px solid var(--line);border-radius:8px;overflow:hidden;cursor:pointer;position:relative}
.tile:hover{border-color:#6a6e74}.tile img{display:block;width:100%;aspect-ratio:1;object-fit:contain;background:#111}
.tile .cap{padding:6px 8px;font-size:12px;display:flex;justify-content:space-between;gap:6px}
.badge{font-size:11px;padding:1px 6px;border-radius:9px;border:1px solid}
.b-flag{color:var(--warn);border-color:var(--warn)}.b-ok{color:var(--ok);border-color:var(--ok)}.b-auto{color:var(--dim);border-color:var(--line)}
#detail{display:none;height:calc(100vh - 53px)}
.dwrap{display:grid;grid-template-columns:minmax(0,1fr) 380px;height:100%}
.stage{position:relative;display:flex;align-items:center;justify-content:center;background:#111;overflow:hidden}
.stage{padding:10px}
.imgbox{position:relative;display:inline-block;line-height:0}
.imgbox img{display:block;max-width:calc(100vw - 380px - 20px);max-height:calc(100vh - 53px - 20px)}
.gridov{position:absolute;inset:0;pointer-events:none;display:none;
background-image:linear-gradient(to right,rgba(0,255,255,.55) 1px,transparent 1px),linear-gradient(to bottom,rgba(0,255,255,.55) 1px,transparent 1px);
background-size:10% 10%;background-position:0 0}
.cropmask{position:absolute;pointer-events:none;display:none;box-shadow:0 0 0 2000px rgba(0,0,0,.5);border:1.5px solid #ffdd55}
.side{border-left:1px solid var(--line);background:var(--panel);overflow:auto;padding:14px}
.side h2{font-size:15px;margin:0 0 2px}.side h3{font-size:12px;text-transform:uppercase;letter-spacing:.6px;color:var(--dim);margin:16px 0 6px;font-weight:600}
.angle{font:600 26px ui-monospace,monospace;margin:4px 0}
.cands{display:flex;flex-direction:column;gap:5px}
.cands button{display:flex;justify-content:space-between;text-align:left}.cands button span.k{color:var(--dim);font:12px ui-monospace,monospace}
.nudge{display:flex;gap:5px;flex-wrap:wrap}
.zooms{display:grid;grid-template-columns:1fr 1fr;gap:4px}.zooms img{width:100%;image-rendering:pixelated;display:block;background:#111}
.keyends{display:grid;grid-template-columns:1fr 1fr;gap:4px;position:relative}.keyends div{position:relative}
.keyends img{width:100%;image-rendering:pixelated;display:block}
.keyends .g{position:absolute;background:rgba(0,255,255,.9)}
.notes{font-size:12.5px;color:#d9c7a0;margin:6px 0 0;padding-left:16px}
.edges{font:12px ui-monospace,monospace;color:var(--dim);display:grid;grid-template-columns:auto auto;gap:2px 12px}
.edgeadj .ea-row{display:flex;align-items:center;gap:4px;margin:3px 0}
.edgeadj .ea-row button{padding:3px 7px}
.ea-name{min-width:46px;color:var(--dim);font-size:12px}
.ea-val{min-width:44px;text-align:center;font:12px ui-monospace,monospace}
.ea-val.adj{color:var(--acc)}
.status{font-size:12px;margin-top:8px;min-height:18px}
.help{font-size:12px;color:var(--dim);line-height:1.8}
.stage.tool #big{cursor:crosshair}
.toast{position:fixed;bottom:18px;left:50%;transform:translateX(-50%);background:#2f3a2f;border:1px solid var(--ok);padding:8px 14px;border-radius:8px;display:none}
.err{color:var(--warn);white-space:pre-wrap;font-size:12px}
</style></head><body>
<header><h1>CD Crop Review</h1><div class="tabs"><button id="tSetup">Setup</button> <button id="tReview">Review</button></div>
<div class="sp"></div><span id="hdrStat" class="muted"></span></header>
<main id="setup">
<div class="card">
<div class="row"><label>Scans folder</label><input class="path" id="scansDir" placeholder="folder with your scan BMPs"><button data-browse="scansDir">Browse…</button></div>
<div class="row"><label>Output folder</label><input class="path" id="outDir" placeholder="where cropped PNGs go"><button data-browse="outDir">Browse…</button></div>
<div id="browser" style="display:none"><div class="row" style="margin:0"><span class="muted" id="bPath"></span><span class="sp"></span>
<button id="bUse">Use this folder</button> <button id="bClose">Close</button></div><div class="browser" id="bList"></div></div>
<div class="row"><label>Rotation</label><select id="align"><option value="auto">auto (art lines, art kept, left edge)</option>
<option value="left">always left edge</option><option value="right">always right edge</option><option value="top">always top edge</option><option value="bottom">always bottom edge</option></select></div>
<div class="row"><label>Covers per scan</label><input id="count" type="number" min="1" max="6" value="2" style="width:70px">
<label style="min-width:auto;margin-left:14px">Parallel scans</label><input id="jobs" type="number" min="1" max="8" value="2" style="width:70px">
<span class="muted">~1.5 GB RAM each</span></div>
<div class="row"><button class="primary" id="go">Process new scans</button><button id="redo">Re-process all</button><button id="openOnly">Open output folder for review</button></div>
<div class="bar"><i id="prog"></i></div><div id="progTxt" class="muted"></div><div id="errs" class="err"></div>
</div>
<div class="card"><b>Scanner calibration</b> <span class="muted" id="calStat"></span>
<div class="help" style="margin:6px 0">Corrects your scanner's own stretch and shear so squares stay square. Scan one flat, detailed cover,
turn it roughly a quarter turn on the glass, scan it again, then pick the two scans and press Measure. It is stored next to cdcrop.py and
applied to everything processed afterwards (use “Re-process all” for earlier scans).</div>
<div class="row"><label>First scan</label><input class="path" id="calA" data-file="1"><button data-browse="calA">Browse…</button></div>
<div class="row"><label>Second scan</label><input class="path" id="calB" data-file="1"><button data-browse="calB">Browse…</button></div>
<div class="row"><button id="calGo">Measure &amp; add</button><button id="calReset">Measure &amp; start over</button>
<label style="min-width:auto"><input type="checkbox" id="calUse" checked> apply calibration</label></div>
</div>
<div class="card help"><b>How it works.</b> Every cover is cropped at the automatic choice and written to the output folder right away.
Review only what you want - flagged covers first. Your choices re-render the full-resolution PNG and are logged to
<code>cdcrop_decisions.csv</code> so the automatic choice can be calibrated to your eye. You can close this window and come back later.</div>
</main>
<main id="review" style="display:none">
<div class="filters"><button data-f="flag" class="on">Flagged</button><button data-f="todo">Not reviewed</button><button data-f="done">Reviewed</button><button data-f="all">All</button>
<span class="sp"></span><span class="muted" id="cnt"></span></div>
<div class="grid" id="grid"></div>
</main>
<section id="detail"><div class="dwrap">
<div class="stage" id="stage"><div class="imgbox" id="imgbox"><img id="big" alt=""><div class="gridov" id="gridov"></div><div class="cropmask" id="cropmask"></div><svg id="marks" style="position:absolute;inset:0;width:100%;height:100%;pointer-events:none"></svg></div></div>
<div class="side">
<div style="display:flex;justify-content:space-between;align-items:center"><h2 id="dTitle"></h2><span id="dBadge"></span></div>
<div class="muted" id="dSize"></div>
<div class="angle" id="dAngle"></div>
<ul class="notes" id="dNotes"></ul>
<h3>Candidates</h3><div class="cands" id="cands"></div>
<h3>Fine tune</h3><div class="nudge">
<button data-n="-0.1">−0.1</button><button data-n="-0.05">−0.05</button><button data-n="-0.01">−0.01</button>
<button data-n="0.01">+0.01</button><button data-n="0.05">+0.05</button><button data-n="0.1">+0.1</button>
<input id="exact" style="width:90px" placeholder="exact °"></div>
<div id="discBox" style="display:none"><h3>Disc</h3><div class="nudge">
<button id="q90">⟲ 90° <kbd>Q</kbd></button><button id="e90">⟳ 90° <kbd>E</kbd></button><button id="r180">180°</button>
<button data-n="-1">−1°</button><button data-n="1">+1°</button></div>
<div class="nudge" style="margin-top:6px"><button id="toolLevel">Level a line <kbd>L</kbd></button><button id="toolTop">Point to top <kbd>T</kbd></button></div>
<div class="muted" id="toolHint" style="font-size:12px;margin-top:4px">Level: click two points along a baseline or logo edge. To top: click the middle of the rim text.</div></div>
<div class="row" style="margin-top:10px"><button class="primary" id="accept">Accept &amp; save <kbd>Enter</kbd></button>
<button id="blink" title="flip to the previous angle">Blink <kbd>Space</kbd></button><button id="gridBtn">Grid <kbd>G</kbd></button>
<button id="ctxBtn" title="show a bit of the scan around the crop">Context <kbd>C</kbd></button></div>
<div class="status" id="dStatus"></div>
<div id="coverBox"><div id="keyBox"><h3>Key art line <span class="muted" id="keyLean" style="text-transform:none;letter-spacing:0"></span></h3>
<div class="keyends" id="keyEnds"></div></div>
<h3>Crop edges <span class="muted" style="text-transform:none;letter-spacing:0;font-size:11px">push a side out to recover trimmed art (a non-square insert may show a sliver of lid on the other side), or in to trim more</span></h3>
<div class="edgeadj" id="edgeAdjBox">
<div class="ea-row"><span class="ea-name">Top</span><button data-edge="top" data-d="-20">−20</button><button data-edge="top" data-d="-5">−5</button><button data-edge="top" data-d="-1">−1</button><span class="ea-val" id="eaTop">0px</span><button data-edge="top" data-d="1">+1</button><button data-edge="top" data-d="5">+5</button><button data-edge="top" data-d="20">+20</button></div>
<div class="ea-row"><span class="ea-name">Bottom</span><button data-edge="bottom" data-d="-20">−20</button><button data-edge="bottom" data-d="-5">−5</button><button data-edge="bottom" data-d="-1">−1</button><span class="ea-val" id="eaBottom">0px</span><button data-edge="bottom" data-d="1">+1</button><button data-edge="bottom" data-d="5">+5</button><button data-edge="bottom" data-d="20">+20</button></div>
<div class="ea-row"><span class="ea-name">Left</span><button data-edge="left" data-d="-20">−20</button><button data-edge="left" data-d="-5">−5</button><button data-edge="left" data-d="-1">−1</button><span class="ea-val" id="eaLeft">0px</span><button data-edge="left" data-d="1">+1</button><button data-edge="left" data-d="5">+5</button><button data-edge="left" data-d="20">+20</button></div>
<div class="ea-row"><span class="ea-name">Right</span><button data-edge="right" data-d="-20">−20</button><button data-edge="right" data-d="-5">−5</button><button data-edge="right" data-d="-1">−1</button><span class="ea-val" id="eaRight">0px</span><button data-edge="right" data-d="1">+1</button><button data-edge="right" data-d="5">+5</button><button data-edge="right" data-d="20">+20</button></div>
<div class="row" style="margin:6px 0 0"><button id="eaReset">Reset edges</button></div>
</div>
<h3>Corners at 1:1 <span class="muted" style="text-transform:none;letter-spacing:0">(TL TR / BL BR)</span></h3><div class="zooms" id="zooms"></div>
<h3>Edges vs. this angle</h3><div class="edges" id="dEdges"></div></div>
<h3>Keys</h3><div class="help"><kbd>1</kbd>–<kbd>9</kbd> candidates · <kbd>A</kbd>/<kbd>B</kbd> auto/alt · <kbd>←</kbd><kbd>→</kbd> ±0.01° (<kbd>Shift</kbd> 0.05, <kbd>Ctrl</kbd> 0.1)<br>
<kbd>Space</kbd> blink · <kbd>G</kbd> grid · <kbd>C</kbd> context · <kbd>Enter</kbd> accept · <kbd>N</kbd>/<kbd>P</kbd> next/prev · <kbd>Esc</kbd> grid<br>
Discs: <kbd>←</kbd><kbd>→</kbd> ±0.1° (<kbd>Shift</kbd> 1°, <kbd>Ctrl</kbd> 0.01°) · <kbd>Q</kbd>/<kbd>E</kbd> quarter turn · <kbd>L</kbd> level a line · <kbd>T</kbd> point to top</div>
</div></div></section>
<div class="toast" id="toast"></div>
<script>
const $=s=>document.querySelector(s), $$=s=>[...document.querySelectorAll(s)];
let ST=null, filter='flag', cur=null, theta=0, prevTheta=null, list=[], gridOn=false, ctxOn=false, browseTarget=null, poll=null;
const CTX_MARGIN=100; // px of scan context shown around the crop (matches the server's cap)
let edgeAdj={left:0,right:0,top:0,bottom:0};
function edgeParam(){return encodeURIComponent(JSON.stringify(edgeAdj))}
function updateEdgeUI(){ for(const k of ['top','bottom','left','right']){
const v=edgeAdj[k]||0, el=$('#ea'+k[0].toUpperCase()+k.slice(1));
el.textContent=(v>0?'+':'')+v+'px'; el.classList.toggle('adj',v!=0)} }
const fmt=t=>(t>=0?'+':'')+t.toFixed(3)+'°';
async function api(p,b){const r=await fetch(p,b?{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(b)}:{});return r.json()}
function toast(m){const t=$('#toast');t.textContent=m;t.style.display='block';clearTimeout(t._h);t._h=setTimeout(()=>t.style.display='none',1800)}
function show(v){$('#setup').style.display=v=='setup'?'block':'none';$('#review').style.display=v=='review'?'block':'none';$('#detail').style.display=v=='detail'?'block':'none';
$('#tSetup').classList.toggle('on',v=='setup');$('#tReview').classList.toggle('on',v!='setup');}
async function refresh(){ST=await api('/api/state');
if(ST.outdir&&!$('#outDir').value)$('#outDir').value=ST.outdir; if(ST.scans_dir&&!$('#scansDir').value)$('#scansDir').value=ST.scans_dir;
const p=ST.progress;$('#prog').style.width=(p.total?100*p.done/p.total:0)+'%';
$('#progTxt').textContent=p.running?`Processing… ${p.done} of ${p.total} scans done`:(p.total?`Done: ${p.done} scans processed.`:'');
$('#errs').textContent=(p.errors||[]).join('\n');
const n=ST.entries.length,f=ST.entries.filter(e=>e.flagged&&e.status!='reviewed').length,r=ST.entries.filter(e=>e.status=='reviewed').length;
$('#hdrStat').textContent=n?`${n} items · ${f} flagged to review · ${r} reviewed`:'';
if(!p.running&&poll){clearInterval(poll);poll=null;}
drawGrid();}
function filtered(){return ST.entries.filter(e=>filter=='all'||(filter=='flag'&&e.flagged&&e.status!='reviewed')||(filter=='todo'&&e.status!='reviewed')||(filter=='done'&&e.status=='reviewed'))}
function curAngle(e){return e.chosen!=null?e.chosen:e.auto}
function drawGrid(){ if(!ST)return; list=filtered(); $('#cnt').textContent=`${list.length} shown`;
const g=$('#grid'); g.innerHTML='';
if(!list.length){g.innerHTML='<div class="muted">Nothing here.</div>';return}
for(const e of list){const d=document.createElement('div');d.className='tile';
const b=e.status=='reviewed'?'<span class="badge b-ok">reviewed</span>':e.flagged?'<span class="badge b-flag">review</span>':'<span class="badge b-auto">auto</span>';
d.innerHTML=`<img loading="lazy" src="/img/preview?id=${e.id}&theta=${curAngle(e)}&w=380"><div class="cap"><span>${e.id}</span>${b}</div>`;
d.onclick=()=>openDetail(e.id); g.appendChild(d);} }
$$('.filters button').forEach(b=>b.onclick=()=>{filter=b.dataset.f;$$('.filters button').forEach(x=>x.classList.toggle('on',x==b));drawGrid()});
function cands(e){const c=[['A','automatic',e.auto]];
if(e.type=='disc'){let i=1;for(const k of ['as scanned','level text','rim text at top']){if(e.named[k]!=null)c.push([String(i++),k,e.named[k]])}return c}if(e.alt!=null)c.push(['B',e.alt_why=='left edge'?'left edge (B)':'alternative (B)',e.alt]);
const order=['left','right','top','bottom','art verticals','edge horizontals'];let i=1;
for(const k of order){if(e.named[k]!=null)c.push([String(i++),k,e.named[k]])} return c}
function openDetail(id){cur=ST.entries.find(e=>e.id==id); list=filtered(); if(!list.find(e=>e.id==id))list=ST.entries;
const isDisc=cur.type=='disc'; $('#discBox').style.display=isDisc?'block':'none'; $('#coverBox').style.display=isDisc?'none':'block'; setTool(null);
edgeAdj=Object.assign({left:0,right:0,top:0,bottom:0},cur.edge_adj||{}); updateEdgeUI();
theta=curAngle(cur); prevTheta=null; show('detail');
$('#dTitle').textContent=cur.id; $('#dBadge').innerHTML=cur.status=='reviewed'?'<span class="badge b-ok">reviewed</span>':cur.flagged?'<span class="badge b-flag">review</span>':'<span class="badge b-auto">auto</span>';
$('#dNotes').innerHTML=cur.notes.map(n=>`<li>${n}</li>`).join('');
const cb=$('#cands');cb.innerHTML='';
for(const [k,name,t] of cands(cur)){const b=document.createElement('button');b.dataset.t=t;b.dataset.k=k;
b.innerHTML=`<span>${name}</span><span><span style="font-family:ui-monospace,monospace">${fmt(t)}</span> <span class="k">${k}</span></span>`;
b.onclick=()=>setTheta(t,name);cb.appendChild(b)}
setTheta(theta,null,true)}
let howLabel='automatic';
let nudging=false;
function setTheta(t,how,keepPrev){ // blink compares against the angle before the last jump or nudge run
t=((t+180)%360+360)%360-180;
const isNudge=how=='manual';
if(!keepPrev&&Math.abs(t-theta)>1e-9&&!(isNudge&&nudging))prevTheta=theta;
nudging=isNudge; theta=Math.round(t*10000)/10000; if(how)howLabel=how; render() }
let rt=null;
function render(){ $('#dAngle').textContent=fmt(theta);
$$('#cands button').forEach(b=>b.classList.toggle('on',Math.abs(+b.dataset.t-theta)<0.0006));
const w=Math.min(1600,Math.max(600,Math.round($('#stage').clientWidth*devicePixelRatio)));
const m=ctxOn?CTX_MARGIN:0;
$('#big').src=`/img/preview?id=${cur.id}&theta=${theta}&w=${w}&margin=${m}&edge=${edgeParam()}`;
updateMask(cur.size);
clearTimeout(rt); rt=setTimeout(details,120);
$('#dStatus').textContent= cur.status=='reviewed'?`saved at ${fmt(cur.chosen)}`+(Math.abs(cur.chosen-theta)>1e-6?' — not saved yet':''):'not reviewed (auto crop already written)';}
function updateMask(sz){ const mask=$('#cropmask'); if(!ctxOn||!sz){mask.style.display='none';return}
const W=sz[0],H=sz[1],m=CTX_MARGIN;
const x0=m/(W+2*m)*100,x1=(W+m)/(W+2*m)*100,y0=m/(H+2*m)*100,y1=(H+m)/(H+2*m)*100;
mask.style.left=x0+'%';mask.style.top=y0+'%';mask.style.width=(x1-x0)+'%';mask.style.height=(y1-y0)+'%';mask.style.display='block'}
async function details(){ if(cur.type=='disc'){const inf=await api(`/api/info?id=${cur.id}&theta=${theta}`);$('#dSize').textContent=`${inf.size[0]} × ${inf.size[1]} px`;updateMask(inf.size);return}
const z=$('#zooms'); z.innerHTML=['tl','tr','bl','br'].map(c=>`<img src="/img/corner?id=${cur.id}&theta=${theta}&c=${c}&n=160&edge=${edgeParam()}">`).join('');
const inf=await api(`/api/info?id=${cur.id}&theta=${theta}&edge=${edgeParam()}`);
$('#dSize').textContent=`${inf.size[0]} × ${inf.size[1]} px`;
updateMask(inf.size);
$('#dEdges').innerHTML=Object.entries(inf.edge_dev).map(([k,v])=>`<span>${k}</span><span>${v==null?'soft':(v>=0?'+':'')+v.toFixed(3)+'°'}</span>`).join('');
if(inf.key){$('#keyBox').style.display='block';
$('#keyLean').textContent=`— leans ${Math.abs(inf.key.lean).toFixed(1)} px over ${inf.key.L} px`;
const k=inf.key, e0=k.e0, n=60;
const ends=[0,1].map(i=>{const e=i?k.e1:k.e0;const cx=Math.round(e[0])-n/2, cy=Math.round(e[1])-n/2;
const g=k.vert?`left:${((e0[0]-cx+0.5)/n*100).toFixed(2)}%;top:0;bottom:0;width:1px`:`top:${((e0[1]-cy+0.5)/n*100).toFixed(2)}%;left:0;right:0;height:1px`;
return `<div><img src="/img/keyend?id=${cur.id}&theta=${theta}&end=${i}&edge=${edgeParam()}"><i class="g" style="${g}"></i></div>`});
$('#keyEnds').innerHTML=ends.join('');} else $('#keyBox').style.display='none'; }
$$('[data-n]').forEach(b=>b.onclick=()=>setTheta(theta+ +b.dataset.n,'manual'));
$('#exact').onkeydown=e=>{if(e.key=='Enter'){const v=parseFloat(e.target.value);if(!isNaN(v))setTheta(v,'manual');e.target.blur();e.stopPropagation()}};
$('#blink').onclick=()=>{if(prevTheta!=null){const t=prevTheta;prevTheta=theta;theta=t;nudging=false;render()}};
$('#gridBtn').onclick=()=>{gridOn=!gridOn;$('#gridov').style.display=gridOn?'block':'none';$('#gridBtn').classList.toggle('on',gridOn)};
$('#ctxBtn').onclick=()=>{ctxOn=!ctxOn;$('#ctxBtn').classList.toggle('on',ctxOn);render()};
$$('[data-edge]').forEach(b=>b.onclick=()=>{ edgeAdj[b.dataset.edge]=(edgeAdj[b.dataset.edge]||0)+ +b.dataset.d; updateEdgeUI(); render() });
$('#eaReset').onclick=()=>{ edgeAdj={left:0,right:0,top:0,bottom:0}; updateEdgeUI(); render() };
$('#accept').onclick=async()=>{ $('#dStatus').textContent='saving full-resolution PNG…';
const how=(cands(cur).find(c=>Math.abs(c[2]-theta)<0.0006)||[0,howLabel||'manual'])[1];
const r=await api('/api/accept',{id:cur.id,theta,how,edge:edgeAdj}); if(r.error){$('#dStatus').textContent=r.error;return}
toast(`Saved ${cur.id} at ${fmt(theta)}`); const id=cur.id; await refresh(); cur=ST.entries.find(e=>e.id==id); step(1,true)};
function step(d,afterSave){ const L=filtered().length&&filter!='all'?filtered():ST.entries;
let i=L.findIndex(e=>e.id==cur.id); if(afterSave&&i<0){ // current left the filter (e.g. reviewed)
const all=ST.entries, j=all.findIndex(e=>e.id==cur.id); const nxt=all.slice(j+1).find(e=>L.includes(e)); if(nxt)return openDetail(nxt.id); show('review');drawGrid();return}
const n=L[i+d]; if(n)openDetail(n.id); else{toast(d>0?'Last cover':'First cover')}}
// ---- disc tools: level a line (two clicks) / point to top (one click)
let tool=null, pts=[];
function setTool(t){tool=(tool==t)?null:t; pts=[]; $('#marks').innerHTML='';
$('#stage').classList.toggle('tool',!!tool); $('#toolLevel').classList.toggle('on',tool=='level'); $('#toolTop').classList.toggle('on',tool=='top')}
$('#toolLevel').onclick=()=>setTool('level'); $('#toolTop').onclick=()=>setTool('top');
$('#q90').onclick=()=>setTheta(theta-90,'quarter turn'); $('#e90').onclick=()=>setTheta(theta+90,'quarter turn'); $('#r180').onclick=()=>setTheta(theta+180,'half turn');
$('#big').addEventListener('click',ev=>{ if(!tool||!cur)return;
const r=$('#big').getBoundingClientRect(), S=cur.size[0], m=ctxOn?CTX_MARGIN:0, tot=S+2*m;
const x=(ev.clientX-r.left)/r.width*tot-m, y=(ev.clientY-r.top)/r.height*tot-m, c=(S-1)/2;
const mk=(X,Y)=>`<circle cx="${X/S*100}%" cy="${Y/S*100}%" r="5" fill="none" stroke="#ff3b30" stroke-width="2"/>`;
if(tool=='top'){ const phi=Math.atan2(y-c,x-c)*180/Math.PI; setTool(null); setTheta(theta+(-90-phi),'point to top'); return }
pts.push([x,y]); $('#marks').innerHTML=pts.map(p=>mk(p[0],p[1])).join('');
if(pts.length==2){ const [a,b]=pts; let beta=Math.atan2(b[1]-a[1],b[0]-a[0])*180/Math.PI;
beta=((beta+90)%180+180)%180-90; // a line has no direction: -90..90
setTool(null); setTheta(theta-beta,'levelled line') } });
document.addEventListener('keydown',e=>{ if($('#detail').style.display!='block'||e.target.tagName=='INPUT')return;
const disc=cur&&cur.type=='disc';
const k=e.key; let s=disc?(e.shiftKey?1:(e.ctrlKey||e.metaKey)?0.01:0.1):(e.shiftKey?0.05:(e.ctrlKey||e.metaKey)?0.1:0.01);
if(disc&&(k=='q'||k=='Q')){$('#q90').click();return} if(disc&&(k=='e'||k=='E')){$('#e90').click();return}
if(disc&&(k=='l'||k=='L')){setTool('level');return} if(disc&&(k=='t'||k=='T')){setTool('top');return}
if(k=='Escape'&&tool){setTool(null);return}
if(k=='ArrowRight'||k=='.'||k=='>'){setTheta(theta+s,'manual');e.preventDefault()}
else if(k=='ArrowLeft'||k==','||k=='<'){setTheta(theta-s,'manual');e.preventDefault()}
else if(k==' '){$('#blink').click();e.preventDefault()}
else if(k=='Enter'){$('#accept').click();e.preventDefault()}
else if(k=='Escape'){show('review');drawGrid()}
else if(k=='g'||k=='G')$('#gridBtn').click()
else if(k=='c'||k=='C')$('#ctxBtn').click()
else if(k=='n'||k=='N')step(1)
else if(k=='p'||k=='P')step(-1)
else{const b=$$('#cands button').find(b=>b.dataset.k.toLowerCase()==k.toLowerCase()); if(b)b.click()} });
// setup
$('#tSetup').onclick=()=>show('setup'); $('#tReview').onclick=()=>{show('review');refresh()};
async function browse(path){const r=await api('/api/ls?path='+encodeURIComponent(path||'~'));$('#browser').style.display='block';
$('#bPath').textContent=r.path+(r.bmps?` · ${r.bmps} BMP files`:''); $('#bPath').dataset.p=r.path;
const L=$('#bList'); L.innerHTML=''; const up=document.createElement('div'); up.textContent='⬑ ..'; up.onclick=()=>browse(r.parent); L.appendChild(up);
const sep=r.path.includes('\\')?'\\':'/', base=r.path.replace(/[\\/]$/,'');
for(const d of r.dirs){const x=document.createElement('div');x.textContent='📁 '+d;x.onclick=()=>browse(base+sep+d);L.appendChild(x)}
if($('#'+browseTarget).dataset.file) for(const f of r.files||[]){const x=document.createElement('div');x.textContent='🖼 '+f;
x.onclick=()=>{$('#'+browseTarget).value=base+sep+f;$('#browser').style.display='none'};L.appendChild(x)} }
$$('[data-browse]').forEach(b=>b.onclick=()=>{browseTarget=b.dataset.browse;browse($('#'+browseTarget).value||(ST&&ST.home))});
$('#bUse').onclick=()=>{$('#'+browseTarget).value=$('#bPath').dataset.p;$('#browser').style.display='none'};
$('#bClose').onclick=()=>$('#browser').style.display='none';
async function go(redo){const body={scans_dir:$('#scansDir').value,outdir:$('#outDir').value,redo,
settings:{align:$('#align').value,count:+$('#count').value,jobs:+$('#jobs').value}};
if(!body.scans_dir||!body.outdir){toast('Choose both folders first');return}
const r=await api('/api/process',body); if(r.error){toast(r.error);return}
poll=setInterval(refresh,1500); refresh()}
$('#go').onclick=()=>go(false); $('#redo').onclick=()=>{if(confirm('Re-process every scan? Covers you already reviewed keep your chosen angle.'))go(true)};
$('#openOnly').onclick=async()=>{if(!$('#outDir').value){toast('Choose the output folder');return}await api('/api/open',{outdir:$('#outDir').value});await refresh();show('review')};
function calStatus(){const c=ST&&ST.calibration; $('#calStat').textContent=c?`— in use: stretch ${c.y_stretch_pct>=0?'+':''}${c.y_stretch_pct.toFixed(3)}%, shear ${c.shear_deg>=0?'+':''}${c.shear_deg.toFixed(4)}° (${(c.pairs||1)>1?`average of ${c.pairs} pairs, which differ by up to ${c.spread_stretch_pct.toFixed(3)}% / ${c.spread_shear_deg.toFixed(4)}°`:'from '+c.scans.join(' + ')})`:(ST&&ST.cal_file?'— measured but turned off':'— not measured yet');
$('#calUse').checked=!ST||ST.settings.use_cal!==false}
async function measure(reset){ if(!$('#calA').value||!$('#calB').value){toast('Pick both scans');return}
$('#calStat').textContent='— measuring…'; const r=await api('/api/calibrate',{a:$('#calA').value,b:$('#calB').value,reset});
if(r.error){$('#calStat').textContent='— '+r.error;return}
const t=r.this_pair; toast(`This pair: stretch ${t.y_stretch_pct.toFixed(3)}%, shear ${t.shear_deg.toFixed(4)}°`+(r.warning?' — '+r.warning:'')); await refresh(); calStatus()}
$('#calGo').onclick=()=>measure(false); $('#calReset').onclick=()=>measure(true);
$('#calUse').onchange=async()=>{await api('/api/usecal',{on:$('#calUse').checked});await refresh();calStatus()};
refresh().then(()=>{ calStatus();
if(ST.settings){$('#count').value=ST.settings.count;$('#jobs').value=ST.settings.jobs;$('#align').value=ST.settings.align||'auto'} if(ST.entries.length){show('review')} else show('setup'); if(ST.progress.running)poll=setInterval(refresh,1500)});
</script></body></html>
"""
def main():
ap = argparse.ArgumentParser(description="Local review interface for cdcrop.")
ap.add_argument("--port", type=int, default=8765)
ap.add_argument("--out", help="open this output folder for review on start")
ap.add_argument("--no-browser", action="store_true")
a = ap.parse_args()
outdir = a.out
if not outdir and os.path.exists(LAST_RUN_PATH): # reopen wherever the last run left off
with open(LAST_RUN_PATH) as fh:
outdir = json.load(fh).get("outdir")
if outdir and os.path.isdir(outdir):
S.open(outdir)
srv = ThreadingHTTPServer(("127.0.0.1", a.port), Handler)
url = f"http://127.0.0.1:{a.port}/"
print(f"CD Crop Review running at {url} (only this computer can reach it; Ctrl+C to stop)")
if not a.no_browser:
threading.Timer(0.6, lambda: webbrowser.open(url)).start()
try:
srv.serve_forever()
except KeyboardInterrupt:
pass
if __name__ == "__main__":
main()