"""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 "👁 –" v = float(row["eyes"]) if v < 0.2: return "● shut" if v < 0.7: return "◐ half" return "○ open" 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"" 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"{txt}" 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"
| this | " f"vs keeper |
{c.get('style','')}" f"{c.get('text','')}
" for c in res.get("captions", [])) tags = " ".join(res.get("hashtags", [])) body = (lines + (f"" if tags else "") + (f"