photo-culling / render.py
Jayasurya23's picture
Caption cards: pair each caption with its photo
3ef599e verified
Raw History Blame Contribute Delete
16.9 kB
"""HTML fragments for the Review tab.
Why HTML rather than gr.Gallery: a Gallery caption is written as a text node (verified -
`innerHTML` appears zero times in Gallery-DPkPlalJ.js), so it cannot carry a score bar, a
coloured margin pill, or a four-state eye glyph at any size. And Gallery's CSS applies
`.fixed-height{max-height:55vh}` whenever height is falsy, with `.grid-wrap{overflow-y:
scroll}` unconditional - i.e. it always owns a scroll container. Plain HTML has neither
constraint, which is what makes a burst fully visible without an inner scrollbar.
"""
import base64
from pathlib import Path
# Weight key -> (label, colour). Order fixed so the stack reads the same on every frame.
BANDS = [
("subject_n", "subject sharpness", "#4c9aff"),
("sharpness_n", "global sharpness", "#7b61ff"),
("exposure", "exposure", "#f5a623"),
("eyes", "eyes open", "#2ecc71"),
("contrast_n", "contrast", "#8e8e93"),
("context_n", "context match", "#ff6b6b"),
]
WEIGHT_KEY = {"subject_n": "subject", "sharpness_n": "sharp", "exposure": "expo",
"eyes": "eyes", "contrast_n": "contrast", "context_n": "context"}
CSS = """
.vs-wrap{font-family:var(--font,system-ui);color:var(--body-text-color)}
.vs-strip,.vs-grid{display:flex;flex-wrap:wrap;gap:12px;margin:0;padding:0}
.vs-cell{width:150px;border:2px solid transparent;border-radius:10px;padding:6px;
background:var(--background-fill-secondary);box-sizing:border-box}
.vs-cell.win{border-color:#2ecc71;box-shadow:0 0 0 1px #2ecc71 inset}
.vs-cell.rival{border-color:#4c9aff}
.vs-imgwrap{position:relative;border-radius:6px;overflow:hidden;background:#000}
.vs-cell img{width:100%;height:100%;object-fit:contain;display:block;background:#000}
.vs-badge{position:absolute;top:6px;left:6px;padding:2px 7px;border-radius:9px;
font-size:10px;font-weight:700;background:rgba(0,0,0,.65);color:#fff}
.vs-badge.win{background:#2ecc71;color:#0b2016}
.vs-why{font-size:10px;opacity:.6;margin-top:3px;line-height:1.35}
.vs-id{font-size:10px;opacity:.65;margin-top:4px;white-space:nowrap;overflow:hidden;
text-overflow:ellipsis}
.vs-stack{display:flex;height:7px;border-radius:4px;overflow:hidden;margin-top:4px;
background:var(--background-fill-primary)}
.vs-stack i{display:block;height:100%}
.vs-meta{display:flex;justify-content:space-between;font-size:10px;margin-top:3px;opacity:.8}
.vs-pill{display:inline-block;padding:1px 6px;border-radius:9px;font-size:10px;font-weight:600}
.vs-eye{font-size:11px}
.vs-row{display:flex;align-items:center;gap:8px;margin:3px 0;font-size:12px}
.vs-row .lab{width:130px;opacity:.75}
.vs-row .bar{flex:1;height:9px;background:var(--background-fill-primary);border-radius:5px;
position:relative;overflow:hidden}
.vs-row .bar i{position:absolute;left:0;top:0;height:100%;border-radius:5px}
.vs-row .bar u{position:absolute;top:-2px;width:2px;height:13px;background:var(--body-text-color);
opacity:.55;text-decoration:none}
.vs-row .num{width:78px;text-align:right;font-variant-numeric:tabular-nums;font-size:11px}
.vs-note{font-size:11px;opacity:.7;margin-top:8px;line-height:1.5}
"""
def _b64(path: str) -> str:
try:
return "data:image/jpeg;base64," + base64.b64encode(Path(path).read_bytes()).decode()
except Exception:
return ""
def _b64_scaled(path: str, max_edge: int) -> str:
"""Inline a thumbnail no larger than it will be drawn.
A caption card shows the photo at 190 CSS px but the proxy is 512 px, and base64 adds
another third on top - so inlining the proxy costs ~54 KB per card, ~650 KB for a full
run of 12. Encoding at 2x the display size keeps it crisp on a retina panel for roughly
a quarter of the bytes.
"""
try:
from io import BytesIO
from PIL import Image
with Image.open(path) as im:
im = im.convert("RGB")
im.thumbnail((max_edge, max_edge), Image.LANCZOS)
buf = BytesIO()
im.save(buf, "JPEG", quality=82)
return "data:image/jpeg;base64," + base64.b64encode(buf.getvalue()).decode()
except Exception:
return _b64(path)
def _eye_glyph(row) -> str:
"""Four states, because 'no landmarks' and 'wide open' both score 1.0 and the user
should be able to tell a confident reading from an absent one."""
if not row.get("has_landmarks", False):
return "<span class='vs-eye' title='no landmarks found'>👁 –</span>"
v = float(row["eyes"])
if v < 0.2:
return "<span class='vs-eye' title='eyes closed' style='color:#ff6b6b'>● shut</span>"
if v < 0.7:
return "<span class='vs-eye' title='eyes half shut' style='color:#f5a623'>◐ half</span>"
return "<span class='vs-eye' title='eyes open' style='color:#2ecc71'>○ open</span>"
def _stack(row, weights: dict) -> str:
"""Stacked contribution bar: each band's width is its weighted share of the score, so
the segment you can see IS the reason that frame ranks where it does."""
segs = []
for col, _label, colour in BANDS:
w = weights.get(WEIGHT_KEY[col], 0.0)
if w <= 0:
continue
contrib = w * float(row.get(col, 0.0))
segs.append((contrib, colour))
total = sum(c for c, _ in segs) or 1.0
return "".join(
f"<i style='width:{100*c/total:.1f}%;background:{col}'></i>" for c, col in segs)
def _margin_pill(margin: float) -> str:
if margin < 0.02:
bg, txt = "#ff6b6b", "too close to call"
elif margin < 0.10:
bg, txt = "#f5a623", f"+{margin:.2f}"
else:
bg, txt = "#2ecc71", f"+{margin:.2f}"
return f"<span class='vs-pill' style='background:{bg};color:#111'>{txt}</span>"
def out_of_ten(v: float) -> str:
"""Scores are 0-1 internally. A 0-10 figure with one decimal reads as a judgement;
a stacked colour bar reads as decoration and has to be decoded before it means
anything. Same information, no legend required."""
return f"{max(0.0, min(1.0, float(v))) * 10:.1f}"
def burst_order(block):
"""THE ordering for a burst, best first.
Single source of truth on purpose: the gallery renders in this order and the click
handler maps an index back to a frame with it. If the two ever disagreed, clicking a
frame would silently select a different one - a bug with no error attached.
Best-first rather than capture order because the user's question is "is the keeper
right?", and that is answered by looking at rank 1 vs rank 2. Capture order buries the
runner-up somewhere in the middle.
"""
return block.sort_values(["score", "id"], ascending=[False, True])
def gallery_items(block, selected_id=None):
"""(filepath, caption) pairs for gr.Gallery, in capture order.
gr.Gallery is used rather than custom HTML for two reasons the brief demands: clicking
a frame opens Gradio's full-resolution lightbox, which is the only way to actually
judge focus and eyes; and selection is a first-class event instead of something bolted
on. Captions are plain text nodes, so the score has to BE text - which is what makes
the out-of-ten figure the right call rather than a compromise.
"""
items = []
for pos, r in enumerate(burst_order(block).itertuples(), start=1):
row = r._asdict()
score = out_of_ten(row["score"])
if row["is_winner"]:
cap = f"★ {score} · KEPT"
else:
cap = f"#{pos} {score} · {row['reason']}"
if row["id"] == selected_id and not row["is_winner"]:
cap = "▶ " + cap
items.append((row["proxy_path"], cap))
return items
def metric_panel(row, win, prompt_on: bool) -> str:
"""Per-metric scores out of 10 for the selected frame, against the keeper.
Kept as a table of numbers rather than bars: the numbers are the thing being compared,
and a delta column says more than two bar lengths ever did.
"""
rows = [
("Subject / face sharpness", "subject_n"),
("Eyes open", "eyes"),
("Exposure", "exposure"),
("Global sharpness", "sharpness_n"),
("Contrast", "contrast_n"),
]
if prompt_on:
rows.append(("Context match", "context_n"))
body = []
for label, col in rows:
a, b = float(win.get(col, 0)), float(row.get(col, 0))
# An unmeasured eye score is neutral 1.0 internally, which renders as a confident
# "10.0" - the single most misleading cell on this panel, since it looks like the
# best possible reading of something that was never read. The footnote alone was not
# enough; show no number at all when there were no landmarks.
if col == "eyes" and not row.get("has_landmarks", True):
body.append(
f"<tr><td style='padding:3px 10px 3px 0'>{label}</td>"
f"<td style='text-align:right;opacity:.45' title='no landmarks found'>—</td>"
f"<td style='text-align:right;padding-left:14px;opacity:.45'>n/a</td></tr>")
continue
d = (b - a) * 10
arrow = "—" if abs(d) < 0.05 else (f"▲ {d:+.1f}" if d > 0 else f"▼ {d:+.1f}")
colour = ("opacity:.5" if abs(d) < 0.05 else
("color:#2ecc71" if d > 0 else "color:#ff6b6b"))
body.append(
f"<tr><td style='padding:3px 10px 3px 0'>{label}</td>"
f"<td style='text-align:right;font-variant-numeric:tabular-nums'>{out_of_ten(b)}</td>"
f"<td style='text-align:right;padding-left:14px;{colour}'>{arrow}</td></tr>")
eye_note = ""
if not row.get("has_landmarks", True):
eye_note = ("<div style='font-size:11px;opacity:.6;margin-top:6px'>"
"No eye landmarks found in this frame - the eyes score is neutral, "
"not measured.</div>")
return (f"<style>{CSS}</style><div class='vs-wrap'>"
f"<div style='font-size:12px;opacity:.7;margin-bottom:6px'>"
f"Selected <b>{row['id']}</b> — total <b>{out_of_ten(row['score'])}</b> / 10 "
f"(keeper: {out_of_ten(win['score'])})</div>"
f"<table style='font-size:12px;border-collapse:collapse'>"
f"<tr style='opacity:.55'><td></td><td style='text-align:right'>this</td>"
f"<td style='text-align:right;padding-left:14px'>vs keeper</td></tr>"
f"{''.join(body)}</table>{eye_note}</div>")
def burst_grid(block, weights: dict, selected_id=None, cell: int = 250) -> str:
"""EVERY frame of one burst, large, in capture order.
Images are inlined as base64 rather than handed to gr.Image/gr.Gallery: Gallery cannot
render markup in a caption (so no score bars), and it owns an inner scroll container.
A plain grid grows to fit, so a 16-shot burst is fully visible by scrolling the page.
"""
img_h = int(cell * 0.72)
cells = []
for r in block.sort_values("timestamp").itertuples():
row = r._asdict()
klass = "win" if row["is_winner"] else ("rival" if row["id"] == selected_id else "")
badge = ("<span class='vs-badge win'>KEPT</span>" if row["is_winner"]
else f"<span class='vs-badge'>#{int(row['rank'])}</span>")
why = "" if row["is_winner"] else f"<div class='vs-why'>{row['reason']}</div>"
cells.append(
f"<div class='vs-cell {klass}' style='width:{cell}px'>"
f"<div class='vs-imgwrap' style='height:{img_h}px'>"
f"<img src='{_b64(row['proxy_path'])}' alt='{row['id']}'>{badge}</div>"
f"<div class='vs-stack'>{_stack(row, weights)}</div>"
f"<div class='vs-meta'>{_eye_glyph(row)}<span>{row['score']:.3f}</span></div>"
f"<div class='vs-id'>{row['id']}</div>{why}</div>")
return (f"<style>{CSS}</style><div class='vs-wrap'>"
f"<div class='vs-grid'>{''.join(cells)}</div></div>")
# kept under the old name so any external caller/test still works
filmstrip = burst_grid
def compare(win, rival, weights: dict, prompt_on: bool) -> str:
"""Per-metric bars for two frames, with a tick marking the winner's value so the gap
is visible without reading either number."""
rows = []
for col, label, colour in BANDS:
w = weights.get(WEIGHT_KEY[col], 0.0)
if w <= 0 or (col == "context_n" and not prompt_on):
continue
a, b = float(win.get(col, 0)), float(rival.get(col, 0))
delta = b - a
sign = "+" if delta >= 0 else ""
rows.append(
f"<div class='vs-row'><span class='lab'>{label}</span>"
f"<span class='bar'><i style='width:{100*b:.0f}%;background:{colour}'></i>"
f"<u style='left:calc({100*a:.0f}% - 1px)'></u></span>"
f"<span class='num'>{b:.2f} ({sign}{delta:.2f})</span></div>")
return (f"<style>{CSS}</style><div class='vs-wrap'>{''.join(rows)}"
f"<div class='vs-note'>Bar = the rejected frame. Tick = the kept frame. "
f"Bands with zero weight are hidden.</div></div>")
CAPTION_CSS = """
.cap-card{display:flex;gap:14px;align-items:flex-start;padding:12px;margin-bottom:12px;
border-radius:10px;background:var(--background-fill-secondary);
border:1px solid var(--border-color-primary)}
.cap-thumb{flex:0 0 auto;width:190px;border-radius:8px;display:block;background:#000}
.cap-body{flex:1 1 auto;min-width:0;font-size:13px;line-height:1.5}
.cap-id{font-family:var(--font-mono,monospace);font-size:11px;opacity:.6;margin-bottom:6px}
.cap-line{margin:0 0 5px}
.cap-style{display:inline-block;min-width:74px;font-size:10px;text-transform:uppercase;
letter-spacing:.4px;opacity:.6}
.cap-tags{margin-top:8px;font-size:12px;color:#4c9aff;word-break:break-word}
.cap-alt{margin-top:6px;font-size:11px;opacity:.55;font-style:italic}
.cap-err{color:#ff6b6b;font-size:12px}
@media (max-width:640px){.cap-card{flex-direction:column}.cap-thumb{width:100%}}
"""
CAPTION_THUMB_EDGE = 380 # 2x the 190px the card draws, for retina
def caption_cards(entries) -> str:
"""One card per photo: the thumbnail and ITS captions side by side.
Captions used to render as a single Markdown blob headed by the filename, with the
photos in a separate gr.Gallery above. Matching a caption to a picture meant reading an
id like `grad__DSF3252` off a heading and hunting for the same string in a gallery
tooltip - which is exactly the sort of cross-referencing the Review tab was rebuilt to
remove. Pairing them in one row means there is nothing to match up.
entries: iterable of (row, result) where result is generate_captions' dict.
"""
cards = []
for row, res in entries:
thumb = _b64_scaled(row["proxy_path"], CAPTION_THUMB_EDGE)
img = (f"<img class='cap-thumb' src='{thumb}' alt=''>" if thumb
else "<div class='cap-thumb' style='height:120px'></div>")
if "error" in res:
body = f"<div class='cap-err'>{res['error']}</div>"
else:
lines = "".join(
f"<p class='cap-line'><span class='cap-style'>{c.get('style','')}</span>"
f"{c.get('text','')}</p>"
for c in res.get("captions", []))
tags = " ".join(res.get("hashtags", []))
body = (lines
+ (f"<div class='cap-tags'>{tags}</div>" if tags else "")
+ (f"<div class='cap-alt'>alt: {res['alt_text']}</div>"
if res.get("alt_text") else ""))
cards.append(f"<div class='cap-card'>{img}"
f"<div class='cap-body'><div class='cap-id'>{row['id']}</div>"
f"{body}</div></div>")
return f"<style>{CAPTION_CSS}</style><div class='vs-wrap'>" + "".join(cards) + "</div>"
def queue_rows(scored, order, current) -> str:
"""The review queue. Default order is tightest-margin-first, because a burst decided
by 0.007 is the one a human should look at; a burst decided by 0.8 is not."""
sizes = scored.groupby("group_id").size()
marg = scored.groupby("group_id")["margin"].first()
wins = scored[scored["is_winner"]].set_index("group_id")
out = []
for gid in order[:60]:
n = int(sizes.get(gid, 0))
m = float(marg.get(gid, 0.0))
win = wins.loc[gid] if gid in wins.index else None
blink = ""
if win is not None:
grp = scored[scored["group_id"] == gid]
if (grp["eyes"] < 0.35).any() and float(win["eyes"]) > 0.8:
blink = " · blink caught"
sel = "background:var(--background-fill-secondary);font-weight:600;" if gid == current else ""
out.append(f"<div style='padding:4px 8px;border-radius:6px;font-size:12px;{sel}'>"
f"burst {gid} · {n} shots · {_margin_pill(m)}{blink}</div>")
return f"<style>{CSS}</style><div class='vs-wrap'>{''.join(out)}</div>"