Initial commit: CdCrop engine, review UI, and tuner
This commit is contained in:
+12
@@ -0,0 +1,12 @@
|
|||||||
|
.venv/
|
||||||
|
.venv1/
|
||||||
|
.idea/
|
||||||
|
.claude/
|
||||||
|
__pycache__/
|
||||||
|
*.pyc
|
||||||
|
|
||||||
|
# local machine state (regenerated by the app, has your local paths)
|
||||||
|
cdcrop_ui_last.json
|
||||||
|
|
||||||
|
# scan test data, review previews/output — large binaries, not code
|
||||||
|
test_match/
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
# CdCrop — project notes for Claude
|
||||||
|
|
||||||
|
Alex is scanning a large CD collection: two items per flatbed scan, 600 dpi,
|
||||||
|
5100×7019 RGB BMPs. These tools find each item, straighten and crop it, and
|
||||||
|
save it as an otherwise unaltered lossless PNG (same mode and DPI, just a
|
||||||
|
smaller file than BMP). Everything runs locally; no cloud vision services.
|
||||||
|
|
||||||
|
## Files
|
||||||
|
- `cdcrop.py` — the engine, which also runs from the command line (`python cdcrop.py scan.bmp -o out`).
|
||||||
|
- `cdcrop_ui.py` — the local review interface on 127.0.0.1:8765 (stdlib server and single-page JS). It writes `cdcrop_decisions.csv` to the output folder. Remembers the last-used scans/output folder and settings across restarts (`cdcrop_ui_last.json`). The detail view has a "Context" toggle (shows scan around the crop, darkened outside the boundary) and a "Crop edges" control (manual per-side px push in/out) for covers whose insert isn't quite square — the automatic crop is conservative (sized off whichever corner needs the most trim), so a non-rectangular insert can cost real art at the other corner; the manual push recovers it.
|
||||||
|
- `cdcrop_tune.py` — fits the angle-choice weights to Alex's picks in the decisions CSV. It saves `cdcrop_tuning.json` only if leave-one-out validation beats the current settings.
|
||||||
|
- `scanner_calibration.json` — the scanner's geometry correction (see Calibration below).
|
||||||
|
- `cdcrop_tuning.json` — optional tuned weights; delete it to revert.
|
||||||
|
|
||||||
|
## Covers: what Alex wants
|
||||||
|
- The art is straight, with as much art kept as possible and no scanner lid.
|
||||||
|
- Rotation uses one Lanczos warp in float, rounded once.
|
||||||
|
- **Default alignment is the left edge**, unless horizontal lines near the top or bottom argue otherwise.
|
||||||
|
- Lines that should be parallel to the sides end up parallel.
|
||||||
|
- Lettering and deliberate borders matter more than blurry photo detail.
|
||||||
|
- Don't keep out-of-focus art at the edges.
|
||||||
|
- Borders should look as the artist intended (trim bleed so a frame's border is even).
|
||||||
|
- He prefers consistent results over chasing slim-margin picks, and wants calibration to his picks over time.
|
||||||
|
|
||||||
|
## Discs
|
||||||
|
The output is a square of side 2(R+6) around the disc; lid showing in the corners is fine.
|
||||||
|
|
||||||
|
Orientation rubric:
|
||||||
|
1. Text-heavy discs: put the text upright.
|
||||||
|
2. Otherwise: put the label logo upright.
|
||||||
|
3. Otherwise: center the rim text at the top.
|
||||||
|
4. A clear photo upright overrides these.
|
||||||
|
5. Otherwise he doesn't care.
|
||||||
|
|
||||||
|
## How it works (engine)
|
||||||
|
**Finding items**
|
||||||
|
- The lid is flood-filled using the per-channel gradient max (threshold 2.0 at 1/3 scale).
|
||||||
|
- Items with circularity ≥ 0.9 are discs.
|
||||||
|
|
||||||
|
**Fitting edges (`fit_edge`)**
|
||||||
|
- Takes the outermost strong peak group, then the innermost line within that group.
|
||||||
|
- Refines to sub-pixel, then fits a Huber line.
|
||||||
|
- Soft edges (strength < 6) borrow their angle from another edge.
|
||||||
|
|
||||||
|
**Choosing the angle (`angle_components` → `combine_angle`)**
|
||||||
|
The choice weighs:
|
||||||
|
- art lines (LSD: verticals first, plus horizontals near the top or bottom);
|
||||||
|
- the salience of art that would be lost;
|
||||||
|
- a left-edge bias;
|
||||||
|
- edge consensus;
|
||||||
|
- a blur term (`W_BLUR`).
|
||||||
|
|
||||||
|
**Calibration**
|
||||||
|
- Model: scan = M·true, with M = [[1,k],[0,sy]].
|
||||||
|
- It is measured from two scans of the same item at different angles (SIFT matching plus an affine least-squares fit).
|
||||||
|
- Analysis runs in true space, and the correction is folded into the final render.
|
||||||
|
- Alex's calibration: stretch +0.457%, shear −0.105°.
|
||||||
|
|
||||||
|
## Status (2026-10-13)
|
||||||
|
**Results on Alex's 12 reviewed covers:** 9 of 12 picks reproduced within 2 px of drift. The misses:
|
||||||
|
- DJ C (448_2): out-of-focus art along the top edge; he picks the bottom-edge angle.
|
||||||
|
- Simple Minds (451_1): trims bleed so the grey border is even. Subtle; likely stays manual.
|
||||||
|
- Dirty Pretty Things (447_1).
|
||||||
|
|
||||||
|
**Blur detector:** compares the ratio of fine to medium detail at the edge with the same ratio 60 px inside.
|
||||||
|
- It already scales down the "art worth keeping" weight, which fixed DFC.
|
||||||
|
- An extra cost (`W_BLUR` > 0) breaks other covers, so it defaults to 0. The tuner can try 0, 0.25 and 0.5.
|
||||||
|
|
||||||
|
**Open items**
|
||||||
|
- Flag more of the misses in review.
|
||||||
|
- Watch the scan folder (deferred until Alex asks).
|
||||||
|
- Scanner integration (discussed, not started).
|
||||||
|
|
||||||
|
Alex runs this from PyCharm on Windows, in its venv (`python -m pip install` the dependencies there).
|
||||||
+16
@@ -0,0 +1,16 @@
|
|||||||
|
@echo off
|
||||||
|
REM Launches the CdCrop review UI (cdcrop_ui.py) using its project venv.
|
||||||
|
REM Double-click from the desktop, a shortcut, or anywhere else.
|
||||||
|
|
||||||
|
set "PROJECT_DIR=C:\Users\aarbi\PycharmProjects\CdCrop"
|
||||||
|
set "PYTHON=%PROJECT_DIR%\.venv\Scripts\python.exe"
|
||||||
|
|
||||||
|
if not exist "%PYTHON%" (
|
||||||
|
echo Could not find %PYTHON%
|
||||||
|
echo Edit CdCrop.bat if the project or venv has moved.
|
||||||
|
pause
|
||||||
|
exit /b 1
|
||||||
|
)
|
||||||
|
|
||||||
|
cd /d "%PROJECT_DIR%"
|
||||||
|
start "CdCrop" "%PYTHON%" cdcrop_ui.py
|
||||||
+233
@@ -0,0 +1,233 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""
|
||||||
|
cdcrop_tune.py - tune cdcrop's automatic angle choice to your own picks.
|
||||||
|
|
||||||
|
python cdcrop_tune.py --scans "C:\\path\\to\\scans" --decisions "C:\\path\\to\\output\\cdcrop_decisions.csv"
|
||||||
|
|
||||||
|
Runs on your computer with your scans, so the result matches exactly what the
|
||||||
|
cropper does there. For every cover you reviewed in the interface, it
|
||||||
|
measures everything the automatic choice weighs, then tries a few thousand
|
||||||
|
weightings and keeps the one that reproduces your picks best - preferring
|
||||||
|
settings in the middle of a good region, so small differences on new covers
|
||||||
|
don't flip results. The winner is saved to cdcrop_tuning.json next to
|
||||||
|
cdcrop.py and used automatically from then on (delete that file to go back
|
||||||
|
to the built-in weights). Run it again whenever you've reviewed a new batch.
|
||||||
|
|
||||||
|
A pick counts as reproduced when the automatic angle lands within --tol px
|
||||||
|
(default 2) of yours, measured as drift across the whole cover. New weights
|
||||||
|
are only saved if they predict covers they weren't tuned on (leave-one-out)
|
||||||
|
better than the current ones - otherwise they'd just be memorising.
|
||||||
|
"""
|
||||||
|
import argparse
|
||||||
|
import csv
|
||||||
|
import itertools
|
||||||
|
import json
|
||||||
|
import math
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
import warnings
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||||
|
import cdcrop # noqa: E402
|
||||||
|
|
||||||
|
DETAIL_GRID = {"DEEP_BLEND": (0.0, 0.5, 1.0), "SAL_POWER": (1.0, 2.0), "SAL_FLOOR": (50, 60, 70)}
|
||||||
|
WEIGHT_GRID = {"W_V": (0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 4.0, 6.0, 8.0),
|
||||||
|
"W_LEFT": (0.0, 0.05, 0.1, 0.2, 0.4),
|
||||||
|
"W_EDGE": (0.0, 0.01, 0.02, 0.05),
|
||||||
|
"W_BLUR": (0.0, 0.25, 0.5)}
|
||||||
|
H_RATIO = 0.5 # W_H = W_V * H_RATIO (horizontal lines count half, as calibrated so far)
|
||||||
|
|
||||||
|
|
||||||
|
def read_picks(path):
|
||||||
|
"""Latest reviewed angle per cover (discs are skipped - they're tuned by hand)."""
|
||||||
|
picks = {}
|
||||||
|
with open(path, newline="") as fh:
|
||||||
|
for row in csv.DictReader(fh):
|
||||||
|
cands = json.loads(row.get("candidates") or "{}")
|
||||||
|
if "as scanned" in cands: # a disc
|
||||||
|
continue
|
||||||
|
picks[row["cover"]] = {"chosen": float(row["chosen_deg"]), "how": row["how"],
|
||||||
|
"logged": {k: row.get(f"{k}_deg") for k in ("left", "right", "top", "bottom")}}
|
||||||
|
return picks
|
||||||
|
|
||||||
|
|
||||||
|
def analyse(scans_dir, picks, inset, cal):
|
||||||
|
"""angle_components for every reviewed cover, with one loss per detail variant."""
|
||||||
|
by_scan = {}
|
||||||
|
for cid in picks:
|
||||||
|
base, idx = cid.rsplit("_", 1)
|
||||||
|
by_scan.setdefault(base, []).append(int(idx))
|
||||||
|
variants = [dict(zip(DETAIL_GRID, v)) for v in itertools.product(*DETAIL_GRID.values())]
|
||||||
|
covers = {}
|
||||||
|
for base, idxs in sorted(by_scan.items()):
|
||||||
|
path = next((os.path.join(scans_dir, f) for f in os.listdir(scans_dir)
|
||||||
|
if os.path.splitext(f)[0] == base and f.lower().endswith(".bmp")), None)
|
||||||
|
if not path:
|
||||||
|
print(f" !! {base}.bmp not found in the scans folder - skipping its covers")
|
||||||
|
continue
|
||||||
|
t0 = time.time()
|
||||||
|
arr8, _, dpi = cdcrop.load_scan(path)
|
||||||
|
arr, _ = cdcrop.true_space(arr8.astype(np.float32), cal)
|
||||||
|
gray = arr[..., :3].mean(axis=2) if arr.ndim == 3 else arr
|
||||||
|
objs = cdcrop.find_objects(arr, max(max(idxs), 2), dpi)
|
||||||
|
for idx, (kind, rect, _) in enumerate(objs, start=1):
|
||||||
|
cid = f"{base}_{idx}"
|
||||||
|
if idx not in idxs or kind != "cover":
|
||||||
|
continue
|
||||||
|
cov = cdcrop.analyze_cover(arr, rect)
|
||||||
|
comp = cdcrop.angle_components(gray, cov, inset)
|
||||||
|
losses, blurs = [], []
|
||||||
|
for v in variants:
|
||||||
|
saved = {k: getattr(cdcrop, k) for k in v}
|
||||||
|
for k, val in v.items():
|
||||||
|
setattr(cdcrop, k, val)
|
||||||
|
losses.append(cdcrop.component_loss(comp, gray))
|
||||||
|
blurs.append(comp["blur"])
|
||||||
|
for k, val in saved.items():
|
||||||
|
setattr(cdcrop, k, val)
|
||||||
|
comp["losses"], comp["blurs"] = losses, blurs
|
||||||
|
# sanity check: do our edge angles match what the interface logged?
|
||||||
|
mism = []
|
||||||
|
for k, v in picks[cid]["logged"].items():
|
||||||
|
if v not in (None, "", "soft") and k in comp["named"]:
|
||||||
|
if abs(float(v) - comp["named"][k]) > 0.01:
|
||||||
|
mism.append(f"{k} {float(v):+.3f} logged vs {comp['named'][k]:+.3f} now")
|
||||||
|
covers[cid] = comp
|
||||||
|
note = (" !! differs from the logged run: " + "; ".join(mism)) if mism else ""
|
||||||
|
print(f" {cid}: measured{note}")
|
||||||
|
print(f" ({base}: {time.time() - t0:.0f}s)")
|
||||||
|
return covers, variants
|
||||||
|
|
||||||
|
|
||||||
|
def evaluate(covers, picks, variants, tol):
|
||||||
|
"""Score every weighting: how many picks it reproduces, and how closely."""
|
||||||
|
names = list(WEIGHT_GRID)
|
||||||
|
grid = list(itertools.product(range(len(variants)), *[range(len(v)) for v in WEIGHT_GRID.values()]))
|
||||||
|
results = []
|
||||||
|
cids = sorted(covers)
|
||||||
|
for gi in grid:
|
||||||
|
vi, wi = gi[0], gi[1:]
|
||||||
|
W = {n: WEIGHT_GRID[n][j] for n, j in zip(names, wi)}
|
||||||
|
errs = []
|
||||||
|
for cid in cids:
|
||||||
|
c = covers[cid]
|
||||||
|
total = (c["losses"][vi] + W["W_V"] * c["conf_v"] * c["cv"]
|
||||||
|
+ W["W_V"] * H_RATIO * c["conf_h"] * c["chh"]
|
||||||
|
+ W["W_LEFT"] * c["left_px"] + W["W_EDGE"] * c["edge_px"]
|
||||||
|
+ W["W_BLUR"] * c["blurs"][vi])
|
||||||
|
best = c["thetas"][int(np.argmin(total))]
|
||||||
|
errs.append(abs(best - picks[cid]["chosen"]) * math.pi / 180 * c["side"])
|
||||||
|
errs = np.array(errs)
|
||||||
|
results.append((gi, int((errs <= tol).sum()), float(np.minimum(errs, 20).sum()), errs))
|
||||||
|
return results, cids
|
||||||
|
|
||||||
|
|
||||||
|
def robust_best(results, mask=None, tol=2.0):
|
||||||
|
"""Most picks reproduced (only covers in mask, if given); among those, the
|
||||||
|
setting whose grid neighbours do as well (the middle of a good region),
|
||||||
|
then the smallest total error."""
|
||||||
|
sel = (lambda e: e) if mask is None else (lambda e: e[mask])
|
||||||
|
score = {r[0]: int((sel(r[3]) <= tol).sum()) for r in results}
|
||||||
|
err = {r[0]: float(np.minimum(sel(r[3]), 20).sum()) for r in results}
|
||||||
|
top = max(score.values())
|
||||||
|
def support(gi):
|
||||||
|
n = 0
|
||||||
|
for d in range(len(gi)):
|
||||||
|
for s in (-1, 1):
|
||||||
|
nb = list(gi); nb[d] += s
|
||||||
|
if score.get(tuple(nb)) == top:
|
||||||
|
n += 1
|
||||||
|
return n
|
||||||
|
cands = [r for r in results if score[r[0]] == top]
|
||||||
|
return max(cands, key=lambda r: (support(r[0]), -err[r[0]])), top
|
||||||
|
|
||||||
|
|
||||||
|
def leave_one_out(results, n, tol):
|
||||||
|
"""Tune on all covers but one, check the one left out; repeat for each.
|
||||||
|
The honest measure of whether tuning learned your taste or just fit
|
||||||
|
these particular covers."""
|
||||||
|
hits = 0
|
||||||
|
for k in range(n):
|
||||||
|
mask = np.ones(n, bool); mask[k] = False
|
||||||
|
(r, _) = robust_best(results, mask, tol)
|
||||||
|
hits += int(r[3][k] <= tol)
|
||||||
|
return hits
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||||
|
ap.add_argument("--scans", required=True, help="folder with the original scan BMPs")
|
||||||
|
ap.add_argument("--decisions", required=True, help="cdcrop_decisions.csv from the interface's output folder")
|
||||||
|
ap.add_argument("--tol", type=float, default=2.0, help="px of drift across the cover that counts as a match")
|
||||||
|
ap.add_argument("--inset", type=float, default=1.0)
|
||||||
|
ap.add_argument("--no-calibration", action="store_true", help="tune without the scanner calibration")
|
||||||
|
ap.add_argument("--dry-run", action="store_true", help="report only; don't save cdcrop_tuning.json")
|
||||||
|
ap.add_argument("--force", action="store_true", help="save the tuned weights even if they don't beat the current ones on unseen covers")
|
||||||
|
a = ap.parse_args()
|
||||||
|
warnings.simplefilter("ignore")
|
||||||
|
|
||||||
|
cal_path = os.path.join(os.path.dirname(os.path.abspath(cdcrop.__file__)), "scanner_calibration.json")
|
||||||
|
cal = None
|
||||||
|
if not a.no_calibration and os.path.exists(cal_path):
|
||||||
|
with open(cal_path) as fh:
|
||||||
|
cal = json.load(fh)
|
||||||
|
print(f"scanner calibration: stretch {cal['y_stretch_pct']:+.3f}%, shear {cal['shear_deg']:+.4f} deg")
|
||||||
|
else:
|
||||||
|
print("no scanner calibration in use")
|
||||||
|
picks = read_picks(a.decisions)
|
||||||
|
print(f"{len(picks)} reviewed covers in {os.path.basename(a.decisions)}; measuring them…")
|
||||||
|
covers, variants = analyse(a.scans, picks, a.inset, cal)
|
||||||
|
if len(covers) < 3:
|
||||||
|
print("!! need at least 3 reviewed covers to tune"); return
|
||||||
|
|
||||||
|
results, cids = evaluate(covers, picks, variants, a.tol)
|
||||||
|
# the current settings, for comparison
|
||||||
|
cur = {k: getattr(cdcrop, k) for k in cdcrop.TUNABLE}
|
||||||
|
cur_errs = []
|
||||||
|
for cid in cids:
|
||||||
|
c = covers[cid]
|
||||||
|
ch = cdcrop.combine_angle(c) # uses the loss computed at current detail settings
|
||||||
|
cur_errs.append(abs(ch["theta"] - picks[cid]["chosen"]) * math.pi / 180 * c["side"])
|
||||||
|
cur_errs = np.array(cur_errs)
|
||||||
|
(gi, n, tot, errs), top = robust_best(results, None, a.tol)
|
||||||
|
cur_hits = int((cur_errs <= a.tol).sum())
|
||||||
|
loo = leave_one_out(results, len(cids), a.tol)
|
||||||
|
W = {"W_V": WEIGHT_GRID["W_V"][gi[1]], "W_LEFT": WEIGHT_GRID["W_LEFT"][gi[2]], "W_EDGE": WEIGHT_GRID["W_EDGE"][gi[3]],
|
||||||
|
"W_BLUR": WEIGHT_GRID["W_BLUR"][gi[4]]}
|
||||||
|
W["W_H"] = W["W_V"] * H_RATIO
|
||||||
|
W.update(variants[gi[0]])
|
||||||
|
|
||||||
|
print(f"\ncurrent settings reproduce {int((cur_errs <= a.tol).sum())} of {len(cids)} picks; "
|
||||||
|
f"tuned settings reproduce {n} of {len(cids)}")
|
||||||
|
print(f"{'cover':22s} {'your pick':>10s} {'current':>9s} {'tuned':>9s} (px of drift from your pick)")
|
||||||
|
for cid, e_now, e_new in zip(cids, cur_errs, errs):
|
||||||
|
c = covers[cid]
|
||||||
|
print(f"{cid:22s} {picks[cid]['chosen']:+10.3f} {e_now:8.1f}px {e_new:8.1f}px"
|
||||||
|
+ (" <- still off" if e_new > a.tol else ""))
|
||||||
|
print("\ntuned weights: " + ", ".join(f"{k}={v:g}" for k, v in W.items()))
|
||||||
|
print(f"check on unseen covers (leave-one-out): tuned settings predict {loo} of {len(cids)}, "
|
||||||
|
f"current settings {cur_hits} of {len(cids)}")
|
||||||
|
if loo <= cur_hits and not a.force:
|
||||||
|
print("-> tuning doesn't predict unseen covers any better than the current settings yet, so it was NOT "
|
||||||
|
"saved (it would only be fitting these particular covers). Review more covers and run this again; "
|
||||||
|
"use --force to save anyway.")
|
||||||
|
return
|
||||||
|
if a.dry_run:
|
||||||
|
return
|
||||||
|
W = {**cur, **W} # keep any tunables this script doesn't touch (e.g. CORNER_LENIENCY,
|
||||||
|
# fit by cdcrop_tune_crop.py) at their current value instead of dropping them
|
||||||
|
out = {"weights": W, "picks": len(cids), "reproduced": n, "tolerance_px": a.tol,
|
||||||
|
"calibrated": cal is not None, "date": time.strftime("%Y-%m-%d %H:%M"),
|
||||||
|
"previous": cur}
|
||||||
|
if os.path.exists(cdcrop.TUNING_PATH):
|
||||||
|
os.replace(cdcrop.TUNING_PATH, cdcrop.TUNING_PATH + ".bak")
|
||||||
|
with open(cdcrop.TUNING_PATH, "w") as fh:
|
||||||
|
json.dump(out, fh, indent=2)
|
||||||
|
print(f"saved to {cdcrop.TUNING_PATH} (previous version kept as .bak). Re-process to apply.")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,188 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""
|
||||||
|
cdcrop_tune_crop.py - tune how far cdcrop's crop relaxes from the conservative
|
||||||
|
corner on each side, to your own manual "Crop edges" pushes.
|
||||||
|
|
||||||
|
python cdcrop_tune_crop.py --scans "C:\\path\\to\\scans" --decisions "C:\\path\\to\\output\\cdcrop_decisions.csv"
|
||||||
|
|
||||||
|
The automatic crop sizes every side off whichever of its two corners needs
|
||||||
|
the most trim (see frame_at's docstring in cdcrop.py) - safe, but on a
|
||||||
|
non-rectangular insert it can cost real art at the other corner, which is
|
||||||
|
what the interface's "Crop edges" push is for. For every cover you reviewed,
|
||||||
|
this measures how much slack existed at each side (the gap between its two
|
||||||
|
corners) and fits CORNER_LENIENCY per side: the fraction of that slack to
|
||||||
|
give back automatically, so fewer covers need a manual push.
|
||||||
|
|
||||||
|
Saved into the same cdcrop_tuning.json cdcrop_tune.py uses (merged in, not
|
||||||
|
overwritten) and used automatically from then on. Only saved if leave-one-out
|
||||||
|
validation beats the current setting - otherwise it would just be
|
||||||
|
memorising your pushes. Run it again whenever you've reviewed a new batch.
|
||||||
|
"""
|
||||||
|
import argparse
|
||||||
|
import csv
|
||||||
|
import json
|
||||||
|
import math
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||||
|
import cdcrop # noqa: E402
|
||||||
|
|
||||||
|
SIDES = ("left", "right", "top", "bottom")
|
||||||
|
BETA_GRID = tuple(round(b, 2) for b in np.arange(0.0, 1.0001, 0.05))
|
||||||
|
|
||||||
|
|
||||||
|
def read_pushes(path):
|
||||||
|
"""Latest reviewed push per cover and side, px (0 if none pushed). Discs skipped."""
|
||||||
|
picks = {}
|
||||||
|
with open(path, newline="") as fh:
|
||||||
|
for row in csv.DictReader(fh):
|
||||||
|
cands = json.loads(row.get("candidates") or "{}")
|
||||||
|
if "as scanned" in cands: # a disc
|
||||||
|
continue
|
||||||
|
push = {k: (float(row[f"{k}_push_px"]) if row.get(f"{k}_push_px") else 0.0) for k in SIDES}
|
||||||
|
picks[row["cover"]] = {"theta": float(row["chosen_deg"]), "push": push}
|
||||||
|
return picks
|
||||||
|
|
||||||
|
|
||||||
|
def analyse(scans_dir, picks, inset, cal):
|
||||||
|
"""Per-side corner gap (px) for every reviewed cover, at its chosen angle."""
|
||||||
|
by_scan = {}
|
||||||
|
for cid in picks:
|
||||||
|
base, idx = cid.rsplit("_", 1)
|
||||||
|
by_scan.setdefault(base, []).append(int(idx))
|
||||||
|
covers = {}
|
||||||
|
for base, idxs in sorted(by_scan.items()):
|
||||||
|
path = next((os.path.join(scans_dir, f) for f in os.listdir(scans_dir)
|
||||||
|
if os.path.splitext(f)[0] == base and f.lower().endswith(".bmp")), None)
|
||||||
|
if not path:
|
||||||
|
print(f" !! {base}.bmp not found in the scans folder - skipping its covers")
|
||||||
|
continue
|
||||||
|
t0 = time.time()
|
||||||
|
arr8, _, dpi = cdcrop.load_scan(path)
|
||||||
|
arr, _ = cdcrop.true_space(arr8.astype(np.float32), cal)
|
||||||
|
objs = cdcrop.find_objects(arr, max(max(idxs), 2), dpi)
|
||||||
|
for idx, (kind, rect, _) in enumerate(objs, start=1):
|
||||||
|
cid = f"{base}_{idx}"
|
||||||
|
if idx not in idxs or kind != "cover":
|
||||||
|
continue
|
||||||
|
cov = cdcrop.analyze_cover(arr, rect)
|
||||||
|
fr = cdcrop.frame_at(cov, picks[cid]["theta"], inset)
|
||||||
|
covers[cid] = fr["corner_gaps"]
|
||||||
|
print(f" ({base}: {time.time() - t0:.0f}s)")
|
||||||
|
return covers
|
||||||
|
|
||||||
|
|
||||||
|
def evaluate(covers, picks, cids, tol):
|
||||||
|
"""error[beta_index, cover_index, side_index] = |beta*gap - actual push| (px)."""
|
||||||
|
gaps = np.array([[covers[cid][s] for s in SIDES] for cid in cids]) # (N,4)
|
||||||
|
push = np.array([[picks[cid]["push"][s] for s in SIDES] for cid in cids]) # (N,4)
|
||||||
|
betas = np.array(BETA_GRID)
|
||||||
|
err = np.abs(betas[:, None, None] * gaps[None] - push[None])
|
||||||
|
return err, gaps, push
|
||||||
|
|
||||||
|
|
||||||
|
def best_betas(err, mask, tol):
|
||||||
|
"""Per-side beta that matches the most covers; ties broken toward a grid
|
||||||
|
neighbour that does as well (the middle of a good region), then smallest error."""
|
||||||
|
e = err if mask is None else err[:, mask, :]
|
||||||
|
hits = (e <= tol).sum(axis=1) # (nbeta, 4)
|
||||||
|
tot = np.minimum(e, 20).sum(axis=1) # (nbeta, 4)
|
||||||
|
out = []
|
||||||
|
for s in range(len(SIDES)):
|
||||||
|
top = hits[:, s].max()
|
||||||
|
cand = [i for i in range(len(BETA_GRID)) if hits[i, s] == top]
|
||||||
|
def support(i):
|
||||||
|
return sum(1 for d in (-1, 1) if 0 <= i + d < len(BETA_GRID) and hits[i + d, s] == top)
|
||||||
|
out.append(max(cand, key=lambda i: (support(i), -tot[i, s])))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def leave_one_out(err, n, tol):
|
||||||
|
hits = 0
|
||||||
|
for k in range(n):
|
||||||
|
mask = np.ones(n, bool); mask[k] = False
|
||||||
|
idx = best_betas(err, mask, tol)
|
||||||
|
hits += sum(int(err[idx[s], k, s] <= tol) for s in range(len(SIDES)))
|
||||||
|
return hits, n * len(SIDES)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||||
|
ap.add_argument("--scans", required=True, help="folder with the original scan BMPs")
|
||||||
|
ap.add_argument("--decisions", required=True, help="cdcrop_decisions.csv from the interface's output folder")
|
||||||
|
ap.add_argument("--tol", type=float, default=2.0, help="px of push left unexplained that still counts as a match")
|
||||||
|
ap.add_argument("--inset", type=float, default=1.0)
|
||||||
|
ap.add_argument("--no-calibration", action="store_true", help="measure without the scanner calibration")
|
||||||
|
ap.add_argument("--dry-run", action="store_true", help="report only; don't save cdcrop_tuning.json")
|
||||||
|
ap.add_argument("--force", action="store_true", help="save the tuned setting even if it doesn't beat the current one on unseen covers")
|
||||||
|
a = ap.parse_args()
|
||||||
|
|
||||||
|
cal_path = os.path.join(os.path.dirname(os.path.abspath(cdcrop.__file__)), "scanner_calibration.json")
|
||||||
|
cal = None
|
||||||
|
if not a.no_calibration and os.path.exists(cal_path):
|
||||||
|
with open(cal_path) as fh:
|
||||||
|
cal = json.load(fh)
|
||||||
|
print(f"scanner calibration: stretch {cal['y_stretch_pct']:+.3f}%, shear {cal['shear_deg']:+.4f} deg")
|
||||||
|
else:
|
||||||
|
print("no scanner calibration in use")
|
||||||
|
|
||||||
|
picks = read_pushes(a.decisions)
|
||||||
|
print(f"{len(picks)} reviewed covers in {os.path.basename(a.decisions)}; measuring them…")
|
||||||
|
covers = analyse(a.scans, picks, a.inset, cal)
|
||||||
|
cids = sorted(covers)
|
||||||
|
if len(cids) < 6:
|
||||||
|
print("!! need at least a handful of reviewed covers to tune"); return
|
||||||
|
|
||||||
|
err, gaps, push = evaluate(covers, picks, cids, a.tol)
|
||||||
|
|
||||||
|
cur = {k: getattr(cdcrop, k) for k in cdcrop.TUNABLE}
|
||||||
|
cur_cl = cur["CORNER_LENIENCY"]
|
||||||
|
cur_beta = {s: (cur_cl if not isinstance(cur_cl, dict) else cur_cl.get(s, 0.0)) for s in SIDES}
|
||||||
|
cur_err = np.abs(np.array([cur_beta[s] for s in SIDES])[None, :] * gaps - push)
|
||||||
|
cur_hits = int((cur_err <= a.tol).sum())
|
||||||
|
total = len(cids) * len(SIDES)
|
||||||
|
|
||||||
|
idx = best_betas(err, None, a.tol)
|
||||||
|
tuned_beta = {s: BETA_GRID[idx[i]] for i, s in enumerate(SIDES)}
|
||||||
|
tuned_err = np.stack([err[idx[i], :, i] for i in range(len(SIDES))], axis=1) # (N,4)
|
||||||
|
tuned_hits = int((tuned_err <= a.tol).sum())
|
||||||
|
|
||||||
|
loo_hits, loo_total = leave_one_out(err, len(cids), a.tol)
|
||||||
|
|
||||||
|
print(f"\ncurrent setting ({', '.join(f'{s}={cur_beta[s]:g}' for s in SIDES)}) "
|
||||||
|
f"matches {cur_hits} of {total} side-pushes within {a.tol:.0f}px")
|
||||||
|
print(f"tuned setting ({', '.join(f'{s}={tuned_beta[s]:g}' for s in SIDES)}) "
|
||||||
|
f"matches {tuned_hits} of {total}")
|
||||||
|
print(f"{'cover':22s}" + "".join(f"{s:>9s}" for s in SIDES) + " (px of push left unexplained, tuned)")
|
||||||
|
for i, cid in enumerate(cids):
|
||||||
|
row = tuned_err[i]
|
||||||
|
flag = " <- still needs a push" if (row > a.tol).any() else ""
|
||||||
|
print(f"{cid:22s}" + "".join(f"{v:9.1f}" for v in row) + flag)
|
||||||
|
|
||||||
|
print(f"\ncheck on unseen covers (leave-one-out): tuned setting predicts {loo_hits} of {loo_total} "
|
||||||
|
f"side-pushes, current setting {cur_hits} of {total}")
|
||||||
|
if loo_hits <= cur_hits and not a.force:
|
||||||
|
print("-> tuning doesn't predict unseen covers any better than the current setting yet, so it was NOT "
|
||||||
|
"saved (it would only be fitting these particular covers). Review more covers and run this again; "
|
||||||
|
"use --force to save anyway.")
|
||||||
|
return
|
||||||
|
if a.dry_run:
|
||||||
|
return
|
||||||
|
|
||||||
|
W = {**cur, "CORNER_LENIENCY": tuned_beta}
|
||||||
|
out = {"weights": W, "picks": len(cids), "reproduced": tuned_hits, "of": total, "tolerance_px": a.tol,
|
||||||
|
"calibrated": cal is not None, "date": time.strftime("%Y-%m-%d %H:%M"), "previous": cur}
|
||||||
|
if os.path.exists(cdcrop.TUNING_PATH):
|
||||||
|
shutil.copy2(cdcrop.TUNING_PATH, cdcrop.TUNING_PATH + ".bak")
|
||||||
|
with open(cdcrop.TUNING_PATH, "w") as fh:
|
||||||
|
json.dump(out, fh, indent=2)
|
||||||
|
print(f"saved to {cdcrop.TUNING_PATH} (previous version kept as .bak). Re-process to apply.")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
+897
@@ -0,0 +1,897 @@
|
|||||||
|
#!/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 & add</button><button id="calReset">Measure & 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 & 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()
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
{
|
||||||
|
"sy": 1.0045673391446617,
|
||||||
|
"k": -0.0018456983223492352,
|
||||||
|
"shear_deg": -0.10526980224259717,
|
||||||
|
"y_stretch_pct": 0.4567339144661675,
|
||||||
|
"scans": [
|
||||||
|
"average of 2 pair(s)"
|
||||||
|
],
|
||||||
|
"pairs": 2,
|
||||||
|
"history": [
|
||||||
|
{
|
||||||
|
"sy": 1.004341498347653,
|
||||||
|
"k": -0.0019650586352377205,
|
||||||
|
"shear_deg": -0.11210272881360409,
|
||||||
|
"y_stretch_pct": 0.4341498347653072,
|
||||||
|
"scans": [
|
||||||
|
"test457.bmp",
|
||||||
|
"test458.bmp"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"sy": 1.0047931799416703,
|
||||||
|
"k": -0.0017263380094607497,
|
||||||
|
"shear_deg": -0.09843994426373696,
|
||||||
|
"y_stretch_pct": 0.4793179941670278,
|
||||||
|
"scans": [
|
||||||
|
"test455.bmp",
|
||||||
|
"test456.bmp"
|
||||||
|
],
|
||||||
|
"turn_deg": -89.39149175232839
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"spread_shear_deg": 0.013662784549867121,
|
||||||
|
"spread_stretch_pct": 0.04516815940172059
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user