#!/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 from PIL import Image sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import cdcrop # noqa: E402 import cdcrop_levels # noqa: E402 import cdcrop_resize # 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": {}, "finish": {}, } 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", "finish": {}} 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", "long_edge": 800, "gamma": 1.2, "jpeg_quality": 60} 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", {}) e["finish"] = old.get("finish", {}) 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 _, _, out, mode = self.render_full(e["id"], e["chosen"], e.get("edge_adj")) self.render_finished(e["id"], out, mode, e.get("finish")) 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 # -- finishing (resize + levels, applied on top of a rendered crop) def resolved_finish(self, finish=None): f = {"gamma": float(self.settings.get("gamma", 1.2)), "black_point": 0.0, "pre_blur": 0.0} f.update(finish or {}) f["gamma"] = min(max(f["gamma"], 0.2), 5.0) f["black_point"] = min(max(f["black_point"], 0.0), 254.0) f["pre_blur"] = min(max(f["pre_blur"], 0.0), 10.0) return f def finish_preview(self, arr, finish): """Apply the live finish settings to a rendered RGB array, for preview only (no resize).""" f = self.resolved_finish(finish) if f["pre_blur"] > 0: arr = cv2.GaussianBlur(arr.astype(np.float32), (0, 0), f["pre_blur"]) arr = np.clip(arr, 0, 255).astype(np.uint8) im = Image.fromarray(arr) if im.mode != "RGB": im = im.convert("RGB") im = cdcrop_levels.apply_levels(im, f["gamma"], int(round(f["black_point"]))) return np.asarray(im) def render_finished(self, cid, out_arr, mode, finish): """Resize + levels the just-rendered crop, saved as OUTDIR/finished/{cid}.jpg.""" f = self.resolved_finish(finish) im = Image.fromarray(out_arr, mode=mode) if im.mode != "RGB": im = im.convert("RGB") im, _ = cdcrop_resize.resize_image(im, int(self.settings.get("long_edge", 800)), f["pre_blur"]) im = cdcrop_levels.apply_levels(im, f["gamma"], int(round(f["black_point"]))) fdir = os.path.join(self.outdir, "finished") os.makedirs(fdir, exist_ok=True) im.save(os.path.join(fdir, cid + ".jpg"), format="JPEG", quality=int(self.settings.get("jpeg_quality", 60))) def preview(self, cid, theta, width, margin=0.0, edge_adj=None, finish=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]]]) out = cv2.warpAffine(src, M, size, flags=cv2.INTER_LINEAR | cv2.WARP_INVERSE_MAP, borderMode=cv2.BORDER_REPLICATE) return self.finish_preview(out, finish) 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"], out, meta["mode"] def accept(self, cid, theta, how, edge_adj=None, finish=None): edge_adj = edge_adj or {} with self.lock: e = self.entries[cid] W, H, out, mode = self.render_full(cid, theta, edge_adj) f = self.resolved_finish(finish) self.render_finished(cid, out, mode, f) with self.lock: e["chosen"], e["status"], e["size"], e["how"] = float(theta), "reviewed", [W, H], how e["edge_adj"] = edge_adj e["finish"] = f 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 {} def _finish_adj(q): """Parse the optional ?finish={"gamma":1.3,...} query param into a plain dict.""" try: f = json.loads(q.get("finish") or "{}") return {k: float(v) for k, v in f.items() if k in ("gamma", "black_point", "pre_blur")} 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), _finish_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/settings": S.settings.update({k: body[k] for k in ("long_edge", "gamma", "jpeg_quality") if k in body}) 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"), body.get("finish")) 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""" CD Crop Review

CD Crop Review

~1.5 GB RAM each
written to OUTDIR/finished/ on accept, alongside the full-res PNG
Scanner calibration
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).
How it works. 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 cdcrop_decisions.csv so the automatic choice can be calibrated to your eye. You can close this window and come back later.

    Candidates

    Fine tune

    Finish resize + levels, written to OUTDIR/finished/ on accept; gamma starts at your default, black point & pre-blur start off

    Gamma1.20
    Black pt0
    Pre-blur0.0

    Key art line

    Crop edges 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

    Top0px
    Bottom0px
    Left0px
    Right0px

    Corners at 1:1 (TL TR / BL BR)

    Edges vs. this angle

    Keys

    1–9 candidates · A/B auto/alt · ←→ ±0.01° (Shift 0.05, Ctrl 0.1)
    Space blink · G grid · C context · Enter accept · N/P next/prev · Esc grid
    Discs: ←→ ±0.1° (Shift 1°, Ctrl 0.01°) · Q/E quarter turn · L level a line · T point to top
    """ 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()