Integrate resize+levels finishing into the review UI's accept flow
Accept now writes two files: OUTDIR/{cid}.png stays the untouched
full-resolution archival crop exactly as before, and a new
OUTDIR/finished/{cid}.jpg holds the resized (long-edge default 800) and
gamma/black-point-leveled derivative, saved at quality 60. Gamma/black
point/pre-blur are per-cover overridable in a new "Finish" panel (same
nudge-button + live-preview pattern as "Crop edges"), defaulting to the
global settings (gamma 1.2, long edge 800, JPEG quality 60) configurable
in Setup. cdcrop_resize.resize_image() was split out from resize_one() so
the UI can call it in-memory without file I/O, same as cdcrop_levels'
apply_levels() already allowed.
This commit is contained in:
+26
-15
@@ -36,28 +36,39 @@ from PIL import Image, ImageFilter
|
|||||||
RESIZE_GAP = 3.0 # >=3.0: Pillow's box-reduce pre-pass is indistinguishable from a fair resample
|
RESIZE_GAP = 3.0 # >=3.0: Pillow's box-reduce pre-pass is indistinguishable from a fair resample
|
||||||
|
|
||||||
|
|
||||||
|
def resize_image(im, long_edge, pre_blur=0.0):
|
||||||
|
"""Core resize, usable on an in-memory image (no file I/O). Returns (image, was_resized)."""
|
||||||
|
w, h = im.size
|
||||||
|
scale = long_edge / max(w, h)
|
||||||
|
if scale >= 1.0:
|
||||||
|
return im, False
|
||||||
|
new_w, new_h = round(w * scale), round(h * scale)
|
||||||
|
if pre_blur > 0:
|
||||||
|
im = im.filter(ImageFilter.GaussianBlur(pre_blur))
|
||||||
|
im = im.resize((new_w, new_h), resample=Image.LANCZOS, reducing_gap=RESIZE_GAP)
|
||||||
|
return im, True
|
||||||
|
|
||||||
|
|
||||||
|
def sharpen_image(im, radius, percent, threshold):
|
||||||
|
return im.filter(ImageFilter.UnsharpMask(radius=radius, percent=percent, threshold=threshold))
|
||||||
|
|
||||||
|
|
||||||
def resize_one(path, outdir, long_edge, pre_blur, sharpen, sharpen_radius, sharpen_percent, sharpen_threshold):
|
def resize_one(path, outdir, long_edge, pre_blur, sharpen, sharpen_radius, sharpen_percent, sharpen_threshold):
|
||||||
im = Image.open(path)
|
im = Image.open(path)
|
||||||
mode = im.mode
|
mode = im.mode
|
||||||
w, h = im.size
|
w, h = im.size
|
||||||
scale = long_edge / max(w, h)
|
out, resized = resize_image(im, long_edge, pre_blur)
|
||||||
if scale >= 1.0:
|
if resized:
|
||||||
print(f" {os.path.basename(path)} {w}x{h} already <= {long_edge}px, copied as-is")
|
print(f" {os.path.basename(path)} {w}x{h} -> {out.size[0]}x{out.size[1]}"
|
||||||
new_w, new_h = w, h
|
|
||||||
else:
|
|
||||||
new_w, new_h = round(w * scale), round(h * scale)
|
|
||||||
if pre_blur > 0:
|
|
||||||
im = im.filter(ImageFilter.GaussianBlur(pre_blur))
|
|
||||||
im = im.resize((new_w, new_h), resample=Image.LANCZOS, reducing_gap=RESIZE_GAP)
|
|
||||||
print(f" {os.path.basename(path)} {w}x{h} -> {new_w}x{new_h}"
|
|
||||||
+ (f" (pre-blur {pre_blur:g})" if pre_blur > 0 else ""))
|
+ (f" (pre-blur {pre_blur:g})" if pre_blur > 0 else ""))
|
||||||
|
else:
|
||||||
|
print(f" {os.path.basename(path)} {w}x{h} already <= {long_edge}px, copied as-is")
|
||||||
if sharpen:
|
if sharpen:
|
||||||
im = im.filter(ImageFilter.UnsharpMask(radius=sharpen_radius, percent=sharpen_percent,
|
out = sharpen_image(out, sharpen_radius, sharpen_percent, sharpen_threshold)
|
||||||
threshold=sharpen_threshold))
|
if out.mode != mode:
|
||||||
if im.mode != mode:
|
out = out.convert(mode)
|
||||||
im = im.convert(mode)
|
|
||||||
out_path = os.path.join(outdir, os.path.basename(path))
|
out_path = os.path.join(outdir, os.path.basename(path))
|
||||||
im.save(out_path, format="PNG")
|
out.save(out_path, format="PNG")
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
|
|||||||
+100
-17
@@ -42,9 +42,12 @@ from urllib.parse import parse_qs, urlparse
|
|||||||
|
|
||||||
import cv2
|
import cv2
|
||||||
import numpy as np
|
import numpy as np
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||||
import cdcrop # noqa: E402
|
import cdcrop # noqa: E402
|
||||||
|
import cdcrop_levels # noqa: E402
|
||||||
|
import cdcrop_resize # noqa: E402
|
||||||
|
|
||||||
PREVIEW_SHRINK = 3 # cached preview source is 1/3 scale
|
PREVIEW_SHRINK = 3 # cached preview source is 1/3 scale
|
||||||
REGION_MARGIN = 120 # px of scan kept around each cover (for re-rendering)
|
REGION_MARGIN = 120 # px of scan kept around each cover (for re-rendering)
|
||||||
@@ -109,7 +112,7 @@ def _cover_entry(arr, gray, cov, base, idx, path, outdir, mode, dpi, inset, alig
|
|||||||
"edges": {k: (None if k in cov["soft"] else float(cdcrop.edge_theta(k, cov["edges"][k][1])))
|
"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")},
|
for k in ("left", "right", "top", "bottom")},
|
||||||
"flagged": flagged, "notes": notes, "size": [fr["W"], fr["H"]],
|
"flagged": flagged, "notes": notes, "size": [fr["W"], fr["H"]],
|
||||||
"chosen": None, "status": "auto", "edge_adj": {},
|
"chosen": None, "status": "auto", "edge_adj": {}, "finish": {},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -156,7 +159,7 @@ def _disc_entry(arr, gray, rect, base, idx, path, outdir, mode, dpi, scan_px=Non
|
|||||||
"auto": float(theta), "alt": None, "alt_why": None,
|
"auto": float(theta), "alt": None, "alt_why": None,
|
||||||
"named": {k: float(v) for k, v in ori["candidates"].items()}, "soft": [],
|
"named": {k: float(v) for k, v in ori["candidates"].items()}, "soft": [],
|
||||||
"edges": {}, "flagged": ori["flagged"], "notes": notes, "size": [fr["W"], fr["H"]],
|
"edges": {}, "flagged": ori["flagged"], "notes": notes, "size": [fr["W"], fr["H"]],
|
||||||
"chosen": None, "status": "auto"}
|
"chosen": None, "status": "auto", "finish": {}}
|
||||||
|
|
||||||
|
|
||||||
def process_scan(job):
|
def process_scan(job):
|
||||||
@@ -195,7 +198,8 @@ class Session:
|
|||||||
self.entries = {} # id -> entry
|
self.entries = {} # id -> entry
|
||||||
self.order = [] # ids in scan order
|
self.order = [] # ids in scan order
|
||||||
self.progress = {"running": False, "done": 0, "total": 0, "current": "", "errors": []}
|
self.progress = {"running": False, "done": 0, "total": 0, "current": "", "errors": []}
|
||||||
self.settings = {"count": 2, "inset": 1.0, "jobs": 2, "align": "auto"}
|
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
|
self._cache = {} # id -> (region, small, meta) small LRU
|
||||||
|
|
||||||
# -- persistence
|
# -- persistence
|
||||||
@@ -256,6 +260,7 @@ class Session:
|
|||||||
if old and old.get("status") == "reviewed":
|
if old and old.get("status") == "reviewed":
|
||||||
e["chosen"], e["status"] = old["chosen"], "reviewed"
|
e["chosen"], e["status"] = old["chosen"], "reviewed"
|
||||||
e["edge_adj"] = old.get("edge_adj", {})
|
e["edge_adj"] = old.get("edge_adj", {})
|
||||||
|
e["finish"] = old.get("finish", {})
|
||||||
self.entries[e["id"]] = e
|
self.entries[e["id"]] = e
|
||||||
if e["id"] not in self.order:
|
if e["id"] not in self.order:
|
||||||
self.order.append(e["id"])
|
self.order.append(e["id"])
|
||||||
@@ -268,7 +273,8 @@ class Session:
|
|||||||
ids = [e["id"] for e in res["entries"]]
|
ids = [e["id"] for e in res["entries"]]
|
||||||
chosen = [self.entries[i] for i in ids if self.entries[i]["status"] == "reviewed"]
|
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
|
for e in chosen: # keep an earlier manual choice after re-processing
|
||||||
self.render_full(e["id"], e["chosen"], e.get("edge_adj"))
|
_, _, 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()
|
self.save()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@@ -322,7 +328,40 @@ class Session:
|
|||||||
A = meta.get("A")
|
A = meta.get("A")
|
||||||
return cdcrop.frame_to_scan(fr, None if A is None else np.array(A)), meta
|
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):
|
# -- 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
|
"""margin: extra context shown around the crop, in crop px - clamped to
|
||||||
CTX_MARGIN so it never reaches past the cached region."""
|
CTX_MARGIN so it never reaches past the cached region."""
|
||||||
region, small, meta = self.load(cid)
|
region, small, meta = self.load(cid)
|
||||||
@@ -342,8 +381,9 @@ class Session:
|
|||||||
else:
|
else:
|
||||||
o = (o_full - [ox, oy])
|
o = (o_full - [ox, oy])
|
||||||
M = np.array([[ex[0] / s, ey[0] / s, o[0]], [ex[1] / s, ey[1] / s, o[1]]])
|
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,
|
out = cv2.warpAffine(src, M, size, flags=cv2.INTER_LINEAR | cv2.WARP_INVERSE_MAP,
|
||||||
borderMode=cv2.BORDER_REPLICATE)
|
borderMode=cv2.BORDER_REPLICATE)
|
||||||
|
return self.finish_preview(out, finish)
|
||||||
|
|
||||||
def patch(self, cid, theta, cx, cy, n, edge_adj=None):
|
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)."""
|
"""n x n patch of the crop at 1:1 (Lanczos), top-left at crop coords (cx, cy)."""
|
||||||
@@ -384,16 +424,19 @@ class Session:
|
|||||||
f2["origin"] = fr["origin"] - [ox, oy]
|
f2["origin"] = fr["origin"] - [ox, oy]
|
||||||
out = cdcrop.render(np.asarray(region).astype(np.float32), f2)
|
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"))
|
cdcrop.save_png(out, meta["mode"], meta["dpi"], os.path.join(self.outdir, cid + ".png"))
|
||||||
return fr["W"], fr["H"]
|
return fr["W"], fr["H"], out, meta["mode"]
|
||||||
|
|
||||||
def accept(self, cid, theta, how, edge_adj=None):
|
def accept(self, cid, theta, how, edge_adj=None, finish=None):
|
||||||
edge_adj = edge_adj or {}
|
edge_adj = edge_adj or {}
|
||||||
with self.lock:
|
with self.lock:
|
||||||
e = self.entries[cid]
|
e = self.entries[cid]
|
||||||
W, H = self.render_full(cid, theta, edge_adj)
|
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:
|
with self.lock:
|
||||||
e["chosen"], e["status"], e["size"], e["how"] = float(theta), "reviewed", [W, H], how
|
e["chosen"], e["status"], e["size"], e["how"] = float(theta), "reviewed", [W, H], how
|
||||||
e["edge_adj"] = edge_adj
|
e["edge_adj"] = edge_adj
|
||||||
|
e["finish"] = f
|
||||||
log = os.path.join(self.outdir, "cdcrop_decisions.csv")
|
log = os.path.join(self.outdir, "cdcrop_decisions.csv")
|
||||||
new = not os.path.exists(log)
|
new = not os.path.exists(log)
|
||||||
with open(log, "a", newline="") as fh:
|
with open(log, "a", newline="") as fh:
|
||||||
@@ -467,6 +510,15 @@ def _edge_adj(q):
|
|||||||
return {}
|
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):
|
class Handler(BaseHTTPRequestHandler):
|
||||||
def log_message(self, *a):
|
def log_message(self, *a):
|
||||||
pass
|
pass
|
||||||
@@ -519,7 +571,7 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
return self._send(200, S.info(q["id"], float(q["theta"]), _edge_adj(q)))
|
return self._send(200, S.info(q["id"], float(q["theta"]), _edge_adj(q)))
|
||||||
if u.path == "/img/preview":
|
if u.path == "/img/preview":
|
||||||
img = S.preview(q["id"], float(q["theta"]), int(q.get("w", 900)), float(q.get("margin", 0)),
|
img = S.preview(q["id"], float(q["theta"]), int(q.get("w", 900)), float(q.get("margin", 0)),
|
||||||
_edge_adj(q))
|
_edge_adj(q), _finish_adj(q))
|
||||||
return self._send(200, jpeg(img, 90), "image/jpeg", cache=True)
|
return self._send(200, jpeg(img, 90), "image/jpeg", cache=True)
|
||||||
if u.path == "/img/corner":
|
if u.path == "/img/corner":
|
||||||
fr, _ = S.frame(q["id"], float(q["theta"]), _edge_adj(q))
|
fr, _ = S.frame(q["id"], float(q["theta"]), _edge_adj(q))
|
||||||
@@ -560,11 +612,16 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
if u.path == "/api/usecal":
|
if u.path == "/api/usecal":
|
||||||
S.settings["use_cal"] = bool(body.get("on", True)); S.save()
|
S.settings["use_cal"] = bool(body.get("on", True)); S.save()
|
||||||
return self._send(200, {"ok": True})
|
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":
|
if u.path == "/api/open":
|
||||||
S.open(body["outdir"])
|
S.open(body["outdir"])
|
||||||
return self._send(200, {"ok": True})
|
return self._send(200, {"ok": True})
|
||||||
if u.path == "/api/accept":
|
if u.path == "/api/accept":
|
||||||
W, H = S.accept(body["id"], float(body["theta"]), body.get("how", "manual"), body.get("edge"))
|
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(200, {"ok": True, "size": [W, H]})
|
||||||
return self._send(404, {"error": "not found"})
|
return self._send(404, {"error": "not found"})
|
||||||
except Exception as ex:
|
except Exception as ex:
|
||||||
@@ -646,6 +703,10 @@ main{padding:16px}
|
|||||||
<div class="row"><label>Covers per scan</label><input id="count" type="number" min="1" max="6" value="2" style="width:70px">
|
<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">
|
<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>
|
<span class="muted">~1.5 GB RAM each</span></div>
|
||||||
|
<div class="row"><label>Finished long edge</label><input id="longEdge" type="number" min="100" max="4000" value="800" style="width:70px">
|
||||||
|
<label style="min-width:auto;margin-left:14px">Default gamma</label><input id="gammaSet" type="number" step="0.05" min="0.2" max="5" value="1.2" style="width:70px">
|
||||||
|
<label style="min-width:auto;margin-left:14px">JPEG quality</label><input id="jpegQ" type="number" min="1" max="100" value="60" style="width:70px">
|
||||||
|
<span class="muted">written to OUTDIR/finished/ on accept, alongside the full-res PNG</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="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 class="bar"><i id="prog"></i></div><div id="progTxt" class="muted"></div><div id="errs" class="err"></div>
|
||||||
</div>
|
</div>
|
||||||
@@ -690,6 +751,13 @@ main{padding:16px}
|
|||||||
<button id="blink" title="flip to the previous angle">Blink <kbd>Space</kbd></button><button id="gridBtn">Grid <kbd>G</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>
|
<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 class="status" id="dStatus"></div>
|
||||||
|
<h3>Finish <span class="muted" style="text-transform:none;letter-spacing:0;font-size:11px">resize + levels, written to OUTDIR/finished/ on accept; gamma starts at your default, black point & pre-blur start off</span></h3>
|
||||||
|
<div class="edgeadj" id="finishAdjBox">
|
||||||
|
<div class="ea-row"><span class="ea-name">Gamma</span><button data-finish="gamma" data-d="-0.1">−0.1</button><button data-finish="gamma" data-d="-0.05">−0.05</button><span class="ea-val" id="fGamma">1.20</span><button data-finish="gamma" data-d="0.05">+0.05</button><button data-finish="gamma" data-d="0.1">+0.1</button></div>
|
||||||
|
<div class="ea-row"><span class="ea-name">Black pt</span><button data-finish="black_point" data-d="-20">−20</button><button data-finish="black_point" data-d="-5">−5</button><span class="ea-val" id="fBlack">0</span><button data-finish="black_point" data-d="5">+5</button><button data-finish="black_point" data-d="20">+20</button></div>
|
||||||
|
<div class="ea-row"><span class="ea-name">Pre-blur</span><button data-finish="pre_blur" data-d="-0.2">−0.2</button><button data-finish="pre_blur" data-d="-0.1">−0.1</button><span class="ea-val" id="fPreblur">0.0</span><button data-finish="pre_blur" data-d="0.1">+0.1</button><button data-finish="pre_blur" data-d="0.2">+0.2</button></div>
|
||||||
|
<div class="row" style="margin:6px 0 0"><button id="faReset">Reset finish</button></div>
|
||||||
|
</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 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>
|
<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>
|
<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>
|
||||||
@@ -717,6 +785,13 @@ function edgeParam(){return encodeURIComponent(JSON.stringify(edgeAdj))}
|
|||||||
function updateEdgeUI(){ for(const k of ['top','bottom','left','right']){
|
function updateEdgeUI(){ for(const k of ['top','bottom','left','right']){
|
||||||
const v=edgeAdj[k]||0, el=$('#ea'+k[0].toUpperCase()+k.slice(1));
|
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)} }
|
el.textContent=(v>0?'+':'')+v+'px'; el.classList.toggle('adj',v!=0)} }
|
||||||
|
let finishAdj={gamma:1.2,black_point:0,pre_blur:0};
|
||||||
|
function defaultFinish(){return {gamma:(ST&&ST.settings.gamma)||1.2,black_point:0,pre_blur:0}}
|
||||||
|
function finishParam(){return encodeURIComponent(JSON.stringify(finishAdj))}
|
||||||
|
function updateFinishUI(){ const d=defaultFinish();
|
||||||
|
$('#fGamma').textContent=finishAdj.gamma.toFixed(2); $('#fGamma').classList.toggle('adj',Math.abs(finishAdj.gamma-d.gamma)>1e-6);
|
||||||
|
$('#fBlack').textContent=finishAdj.black_point; $('#fBlack').classList.toggle('adj',finishAdj.black_point!=0);
|
||||||
|
$('#fPreblur').textContent=finishAdj.pre_blur.toFixed(1); $('#fPreblur').classList.toggle('adj',finishAdj.pre_blur!=0); }
|
||||||
const fmt=t=>(t>=0?'+':'')+t.toFixed(3)+'°';
|
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()}
|
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 toast(m){const t=$('#toast');t.textContent=m;t.style.display='block';clearTimeout(t._h);t._h=setTimeout(()=>t.style.display='none',1800)}
|
||||||
@@ -749,6 +824,7 @@ function cands(e){const c=[['A','automatic',e.auto]];
|
|||||||
function openDetail(id){cur=ST.entries.find(e=>e.id==id); list=filtered(); if(!list.find(e=>e.id==id))list=ST.entries;
|
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);
|
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();
|
edgeAdj=Object.assign({left:0,right:0,top:0,bottom:0},cur.edge_adj||{}); updateEdgeUI();
|
||||||
|
finishAdj=Object.assign(defaultFinish(),cur.finish||{}); updateFinishUI();
|
||||||
theta=curAngle(cur); prevTheta=null; show('detail');
|
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>';
|
$('#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('');
|
$('#dNotes').innerHTML=cur.notes.map(n=>`<li>${n}</li>`).join('');
|
||||||
@@ -769,7 +845,7 @@ function render(){ $('#dAngle').textContent=fmt(theta);
|
|||||||
$$('#cands button').forEach(b=>b.classList.toggle('on',Math.abs(+b.dataset.t-theta)<0.0006));
|
$$('#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 w=Math.min(1600,Math.max(600,Math.round($('#stage').clientWidth*devicePixelRatio)));
|
||||||
const m=ctxOn?CTX_MARGIN:0;
|
const m=ctxOn?CTX_MARGIN:0;
|
||||||
$('#big').src=`/img/preview?id=${cur.id}&theta=${theta}&w=${w}&margin=${m}&edge=${edgeParam()}`;
|
$('#big').src=`/img/preview?id=${cur.id}&theta=${theta}&w=${w}&margin=${m}&edge=${edgeParam()}&finish=${finishParam()}`;
|
||||||
updateMask(cur.size);
|
updateMask(cur.size);
|
||||||
clearTimeout(rt); rt=setTimeout(details,120);
|
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)';}
|
$('#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)';}
|
||||||
@@ -797,9 +873,12 @@ $('#gridBtn').onclick=()=>{gridOn=!gridOn;$('#gridov').style.display=gridOn?'blo
|
|||||||
$('#ctxBtn').onclick=()=>{ctxOn=!ctxOn;$('#ctxBtn').classList.toggle('on',ctxOn);render()};
|
$('#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() });
|
$$('[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() };
|
$('#eaReset').onclick=()=>{ edgeAdj={left:0,right:0,top:0,bottom:0}; updateEdgeUI(); render() };
|
||||||
$('#accept').onclick=async()=>{ $('#dStatus').textContent='saving full-resolution PNG…';
|
$$('[data-finish]').forEach(b=>b.onclick=()=>{ const k=b.dataset.finish;
|
||||||
|
finishAdj[k]=Math.round((finishAdj[k]+ +b.dataset.d)*100)/100; updateFinishUI(); render() });
|
||||||
|
$('#faReset').onclick=()=>{ finishAdj=defaultFinish(); updateFinishUI(); render() };
|
||||||
|
$('#accept').onclick=async()=>{ $('#dStatus').textContent='saving full-resolution PNG + finished JPEG…';
|
||||||
const how=(cands(cur).find(c=>Math.abs(c[2]-theta)<0.0006)||[0,howLabel||'manual'])[1];
|
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}
|
const r=await api('/api/accept',{id:cur.id,theta,how,edge:edgeAdj,finish:finishAdj}); 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)};
|
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;
|
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)
|
let i=L.findIndex(e=>e.id==cur.id); if(afterSave&&i<0){ // current left the filter (e.g. reviewed)
|
||||||
@@ -849,11 +928,13 @@ async function browse(path){const r=await api('/api/ls?path='+encodeURIComponent
|
|||||||
$$('[data-browse]').forEach(b=>b.onclick=()=>{browseTarget=b.dataset.browse;browse($('#'+browseTarget).value||(ST&&ST.home))});
|
$$('[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'};
|
$('#bUse').onclick=()=>{$('#'+browseTarget).value=$('#bPath').dataset.p;$('#browser').style.display='none'};
|
||||||
$('#bClose').onclick=()=>$('#browser').style.display='none';
|
$('#bClose').onclick=()=>$('#browser').style.display='none';
|
||||||
|
function finishSettings(){return {long_edge:+$('#longEdge').value,gamma:+$('#gammaSet').value,jpeg_quality:+$('#jpegQ').value}}
|
||||||
async function go(redo){const body={scans_dir:$('#scansDir').value,outdir:$('#outDir').value,redo,
|
async function go(redo){const body={scans_dir:$('#scansDir').value,outdir:$('#outDir').value,redo,
|
||||||
settings:{align:$('#align').value,count:+$('#count').value,jobs:+$('#jobs').value}};
|
settings:Object.assign({align:$('#align').value,count:+$('#count').value,jobs:+$('#jobs').value},finishSettings())};
|
||||||
if(!body.scans_dir||!body.outdir){toast('Choose both folders first');return}
|
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}
|
const r=await api('/api/process',body); if(r.error){toast(r.error);return}
|
||||||
poll=setInterval(refresh,1500); refresh()}
|
poll=setInterval(refresh,1500); refresh()}
|
||||||
|
$$('#longEdge,#gammaSet,#jpegQ').forEach(el=>el.onchange=async()=>{await api('/api/settings',finishSettings());await refresh()});
|
||||||
$('#go').onclick=()=>go(false); $('#redo').onclick=()=>{if(confirm('Re-process every scan? Covers you already reviewed keep your chosen angle.'))go(true)};
|
$('#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')};
|
$('#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');
|
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');
|
||||||
@@ -865,7 +946,9 @@ async function measure(reset){ if(!$('#calA').value||!$('#calB').value){toast('P
|
|||||||
$('#calGo').onclick=()=>measure(false); $('#calReset').onclick=()=>measure(true);
|
$('#calGo').onclick=()=>measure(false); $('#calReset').onclick=()=>measure(true);
|
||||||
$('#calUse').onchange=async()=>{await api('/api/usecal',{on:$('#calUse').checked});await refresh();calStatus()};
|
$('#calUse').onchange=async()=>{await api('/api/usecal',{on:$('#calUse').checked});await refresh();calStatus()};
|
||||||
refresh().then(()=>{ 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)});
|
if(ST.settings){$('#count').value=ST.settings.count;$('#jobs').value=ST.settings.jobs;$('#align').value=ST.settings.align||'auto';
|
||||||
|
$('#longEdge').value=ST.settings.long_edge||800;$('#gammaSet').value=ST.settings.gamma||1.2;$('#jpegQ').value=ST.settings.jpeg_quality||60}
|
||||||
|
if(ST.entries.length){show('review')} else show('setup'); if(ST.progress.running)poll=setInterval(refresh,1500)});
|
||||||
</script></body></html>
|
</script></body></html>
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user