feat(items): one item record, so an annotation survives the zoom
The operator reported that zoomed-in images lose their annotations. That was
never a rendering bug. Three functions independently walked a booth and derived
overlapping subsets of the same facts -- build_gallery (kind, caption, blur,
doc), booth_view_file (kind, doc, image ring) and list_booths (kind counts,
cover) -- and the zoom route's subset was the smallest. Caption resolution lived
inside build_gallery's loop and nowhere else, so there was no code path by which
a caption could reach the zoom template. It was never sent.
booth/items.py is now the one truth: booth_items() returns the full record --
rel, kind, section, caption, blur, doc kind, size -- and the gallery, the zoom
view, the doc view and the index all read it. Patching view.html would have
fixed the symptom for images and left the next surface starting from the same
missing truth.
Two things fall out of the consolidation:
- the index and the booth page now agree on what an item IS. list_booths
counted every non-dot file, so an A/B pair with two caption sidecars read
as 4 items on the index and showed 2 tiles when you opened it.
- "section" (the item's subfolder) is computed and carried but nothing renders
it yet. That is deliberate: it is U7's whole input, and shipping the field
now makes U7 a template change rather than a resolver change.
Doc bodies are NOT rendered by the resolver -- the index touches every booth on
every page load, and rendering every markdown file in every booth would be the
price of that convenience. render_doc_body is a separate step for the one
surface that inlines them; an invariant test monkeypatches it to raise and
loads the index.
Verified beyond the suite, because this repo has shipped two dead controls that
every test passed: the caption was measured in a real browser at 1280x41 px,
visible, with elementFromPoint at its centre returning the caption itself.
layout-probe reports all controls hittable across index, gallery, zoom and doc.
192 tests pass (173 before, 19 new).
Contract: docs/contracts/u1_item_record.contract.md
This commit is contained in:
+109
-172
@@ -53,44 +53,42 @@ except ImportError: # optional dep — .md then degrades to a plain-text view
|
|||||||
|
|
||||||
TEMPLATES_DIR = Path(__file__).parent / "templates"
|
TEMPLATES_DIR = Path(__file__).parent / "templates"
|
||||||
|
|
||||||
# Browser-playable media buckets. Anything else renders as a download link.
|
# The item record lives in booth/items.py — ONE resolver every surface reads.
|
||||||
IMAGE_EXTS = {".png", ".jpg", ".jpeg", ".gif", ".webp", ".avif", ".svg", ".bmp"}
|
# These names are RE-EXPORTED rather than merely moved: 22 existing test sites
|
||||||
VIDEO_EXTS = {".webm", ".mp4", ".ogv", ".m4v", ".mov"}
|
# import them from booth.app by name, and a silent drop would be found by a
|
||||||
AUDIO_EXTS = {".mp3", ".wav", ".ogg", ".oga", ".flac", ".m4a", ".opus", ".aac"}
|
# consumer instead of by us. `test_app_still_exports_the_moved_names` asserts it.
|
||||||
|
from booth.items import ( # noqa: E402,F401
|
||||||
|
AUDIO_EXTS,
|
||||||
|
BLUR_FILE,
|
||||||
|
CAPTION_MAX,
|
||||||
|
DOC_MAX_BYTES,
|
||||||
|
IMAGE_EXTS,
|
||||||
|
MARKDOWN_EXTS,
|
||||||
|
TEXT_EXTS,
|
||||||
|
VIDEO_EXTS,
|
||||||
|
Item,
|
||||||
|
booth_items,
|
||||||
|
classify,
|
||||||
|
doc_kind,
|
||||||
|
find_item,
|
||||||
|
image_chain,
|
||||||
|
read_blurred,
|
||||||
|
render_doc,
|
||||||
|
render_doc_body,
|
||||||
|
)
|
||||||
|
|
||||||
CAPTION_MAX = 800 # chars of a sidecar .txt caption we render
|
# Sentinel dotfile that exempts a booth from the TTL sweep. A dotfile because
|
||||||
|
# the existing listing code already skips dotfiles, so it costs nothing in item
|
||||||
# Loose text docs that render as a readable in-booth page (not a download).
|
# counts or galleries, and because `touch`/`rm` is the entire user interface: no
|
||||||
MARKDOWN_EXTS = {".md", ".markdown", ".mdown"}
|
# flag to remember, no state anywhere but the filesystem.
|
||||||
TEXT_EXTS = {".txt", ".text", ".log"}
|
|
||||||
DOC_MAX_BYTES = 2 * 1024 * 1024 # above this, a doc is handed back raw, not rendered
|
|
||||||
|
|
||||||
# Sentinel dotfile that exempts a booth from the TTL sweep — see the "kept
|
|
||||||
# booths" note in the module docstring. A dotfile because the existing listing
|
|
||||||
# code already skips dotfiles, so it costs nothing in item counts or galleries,
|
|
||||||
# and because `touch`/`rm` is the entire user interface: no flag to remember, no
|
|
||||||
# state anywhere but the filesystem.
|
|
||||||
KEEP_MARKER = ".forever"
|
KEEP_MARKER = ".forever"
|
||||||
|
|
||||||
# Per-item blur state: one relative item path per line, like .pins is one id per
|
|
||||||
# line. Filesystem IS the state here, same as everything else in this service.
|
|
||||||
#
|
|
||||||
# ⚠⚠ BLUR IS COSMETIC, NOT ACCESS CONTROL. The file is still served at its own
|
# ⚠⚠ BLUR IS COSMETIC, NOT ACCESS CONTROL. The file is still served at its own
|
||||||
# URL, still in the zip, still on disk. This hides an item from a glance — a
|
# URL, still in the zip, still on disk. This hides an item from a glance — a
|
||||||
# shoulder, a screen-share, a scroll past something you did not want to see
|
# shoulder, a screen-share, a scroll past something you did not want to see
|
||||||
# full-size — and nothing more. The Booth has no auth by design; if a thing
|
# full-size — and nothing more. The Booth has no auth by design; if a thing
|
||||||
# must not be seen by whoever can reach port 8090, it must not be in a booth.
|
# must not be seen by whoever can reach port 8090, it must not be in a booth.
|
||||||
# Anyone who reads this marker as protection has misread it.
|
# Anyone who reads this marker as protection has misread it.
|
||||||
BLUR_FILE = ".blurred"
|
|
||||||
|
|
||||||
|
|
||||||
def read_blurred(booth: Path) -> set[str]:
|
|
||||||
"""Blurred item paths for a booth. Missing file -> empty set."""
|
|
||||||
try:
|
|
||||||
text = (booth / BLUR_FILE).read_text()
|
|
||||||
except (OSError, UnicodeDecodeError):
|
|
||||||
return set()
|
|
||||||
return {ln.strip() for ln in text.splitlines() if ln.strip()}
|
|
||||||
|
|
||||||
|
|
||||||
def set_blurred(booth: Path, rel: str, on: bool) -> set[str]:
|
def set_blurred(booth: Path, rel: str, on: bool) -> set[str]:
|
||||||
@@ -143,46 +141,6 @@ from booth.links import ( # noqa: E402
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def doc_kind(name: str) -> str | None:
|
|
||||||
"""'markdown' | 'text' | None — a booth file viewable as a readable page."""
|
|
||||||
ext = Path(name).suffix.lower()
|
|
||||||
if ext in MARKDOWN_EXTS:
|
|
||||||
return "markdown"
|
|
||||||
if ext in TEXT_EXTS:
|
|
||||||
return "text"
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def render_doc(text: str, kind: str) -> tuple[str, bool]:
|
|
||||||
"""(rendered, is_html). Markdown → HTML (fenced code, tables, sane lists);
|
|
||||||
plain text — or markdown when the lib is unavailable — → raw text for <pre>."""
|
|
||||||
if kind == "markdown" and _markdown is not None:
|
|
||||||
html = _markdown.markdown(text, extensions=["fenced_code", "tables", "sane_lists"])
|
|
||||||
return html, True
|
|
||||||
return text, False
|
|
||||||
|
|
||||||
|
|
||||||
def booth_image_names(child: Path) -> list[str]:
|
|
||||||
"""Image files in a booth, in gallery (sorted-rel) order — for viewer prev/next."""
|
|
||||||
return sorted(
|
|
||||||
p.relative_to(child).as_posix()
|
|
||||||
for p in child.rglob("*")
|
|
||||||
if p.is_file() and not p.name.startswith(".") and classify(p.name) == "image"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def classify(name: str) -> str:
|
|
||||||
"""image | video | audio | other, by extension."""
|
|
||||||
ext = Path(name).suffix.lower()
|
|
||||||
if ext in IMAGE_EXTS:
|
|
||||||
return "image"
|
|
||||||
if ext in VIDEO_EXTS:
|
|
||||||
return "video"
|
|
||||||
if ext in AUDIO_EXTS:
|
|
||||||
return "audio"
|
|
||||||
return "other"
|
|
||||||
|
|
||||||
|
|
||||||
def human_dur(seconds: float) -> str:
|
def human_dur(seconds: float) -> str:
|
||||||
s = int(seconds)
|
s = int(seconds)
|
||||||
if s <= 0:
|
if s <= 0:
|
||||||
@@ -263,6 +221,17 @@ def sweep_once(data_dir: Path, ttl_seconds: float, now: float | None = None) ->
|
|||||||
|
|
||||||
|
|
||||||
def list_booths(data_dir: Path, ttl_seconds: float, now: float | None = None) -> list[dict]:
|
def list_booths(data_dir: Path, ttl_seconds: float, now: float | None = None) -> list[dict]:
|
||||||
|
"""One card per booth for the index.
|
||||||
|
|
||||||
|
Counts and the cover come from `booth_items`, so the index agrees with the
|
||||||
|
booth page about what an item IS. It did not before: this function counted
|
||||||
|
every non-dot, non-ask file, which meant a caption sidecar was counted as an
|
||||||
|
item here and (correctly) not counted there — an A/B pair with two captions
|
||||||
|
read as "4 items" on the index and showed two tiles when you opened it.
|
||||||
|
|
||||||
|
Doc bodies are deliberately NOT rendered — see `booth_items`. The index
|
||||||
|
touches every booth on every page load.
|
||||||
|
"""
|
||||||
now = time.time() if now is None else now
|
now = time.time() if now is None else now
|
||||||
booths: list[dict] = []
|
booths: list[dict] = []
|
||||||
if not data_dir.is_dir():
|
if not data_dir.is_dir():
|
||||||
@@ -270,34 +239,31 @@ def list_booths(data_dir: Path, ttl_seconds: float, now: float | None = None) ->
|
|||||||
for child in data_dir.iterdir():
|
for child in data_dir.iterdir():
|
||||||
if not child.is_dir() or child.name.startswith("."):
|
if not child.is_dir() or child.name.startswith("."):
|
||||||
continue
|
continue
|
||||||
files = [
|
items = booth_items(child)
|
||||||
p for p in child.rglob("*")
|
|
||||||
if p.is_file() and not p.name.startswith(".")
|
|
||||||
and not is_ask_file(p.name) and not is_answer_file(p.name)
|
|
||||||
]
|
|
||||||
# Asks are questions, not items: counted separately so the index can
|
# Asks are questions, not items: counted separately so the index can
|
||||||
# flag a booth that is waiting on the operator.
|
# flag a booth that is waiting on the operator.
|
||||||
asks = list_asks(child)
|
asks = list_asks(child)
|
||||||
kinds = {"image": 0, "video": 0, "audio": 0, "other": 0}
|
kinds = {"image": 0, "video": 0, "audio": 0, "other": 0}
|
||||||
thumb_url = None
|
thumb_url = None
|
||||||
for f in files:
|
thumb_blurred = False
|
||||||
k = classify(f.name)
|
for it in items:
|
||||||
kinds[k] += 1
|
kinds[it.kind] += 1
|
||||||
if k == "image" and thumb_url is None:
|
if it.kind == "image" and thumb_url is None:
|
||||||
thumb_url = quote(f.relative_to(child).as_posix(), safe="/")
|
thumb_url = it.url
|
||||||
|
# If the cover image is blurred inside the booth, blur it on the
|
||||||
|
# index too — otherwise the front page cheerfully displays the
|
||||||
|
# exact thing someone asked to hide. Read off the record now,
|
||||||
|
# rather than re-opening .blurred here.
|
||||||
|
thumb_blurred = it.blurred
|
||||||
mtime = _newest_mtime(child)
|
mtime = _newest_mtime(child)
|
||||||
booths.append(
|
booths.append(
|
||||||
{
|
{
|
||||||
"name": child.name,
|
"name": child.name,
|
||||||
"name_url": quote(child.name, safe=""),
|
"name_url": quote(child.name, safe=""),
|
||||||
"count": len(files),
|
"count": len(items),
|
||||||
"kinds": kinds,
|
"kinds": kinds,
|
||||||
"thumb_url": thumb_url,
|
"thumb_url": thumb_url,
|
||||||
# If the cover image is blurred inside the booth, blur it on the
|
"thumb_blurred": thumb_blurred,
|
||||||
# index too — otherwise the front page cheerfully displays the
|
|
||||||
# exact thing someone asked to hide.
|
|
||||||
"thumb_blurred": thumb_url is not None
|
|
||||||
and unquote(thumb_url) in read_blurred(child),
|
|
||||||
"has_index": (child / "index.html").is_file(),
|
"has_index": (child / "index.html").is_file(),
|
||||||
"uploaded": (child / UPLOAD_MARKER).exists(),
|
"uploaded": (child / UPLOAD_MARKER).exists(),
|
||||||
"kept": is_kept(child),
|
"kept": is_kept(child),
|
||||||
@@ -312,84 +278,31 @@ def list_booths(data_dir: Path, ttl_seconds: float, now: float | None = None) ->
|
|||||||
|
|
||||||
|
|
||||||
def build_gallery(child: Path) -> list[dict]:
|
def build_gallery(child: Path) -> list[dict]:
|
||||||
"""Files in a booth as render items, with caption sidecars folded in.
|
"""The gallery's render dicts — a thin adapter over `booth_items`.
|
||||||
|
|
||||||
A `<file>.txt` (e.g. `a.png.txt`) or a same-stem `<stem>.txt` (e.g. `a.txt`
|
The resolver owns every fact about an item; this only shapes them for the
|
||||||
next to `a.png`) is consumed as that item's caption rather than shown itself —
|
template and pulls doc bodies for the one surface that inlines them. Kept as
|
||||||
the natural way to label an A/B pair.
|
a function (rather than inlined at the call site) because the existing test
|
||||||
|
suite reaches for it by name in nine places.
|
||||||
"""
|
"""
|
||||||
all_files = [
|
out = []
|
||||||
p for p in child.rglob("*")
|
for it in booth_items(child):
|
||||||
if p.is_file() and not p.name.startswith(".")
|
body = render_doc_body(child, it)
|
||||||
# `*.ask.json` / `*.answer.json` render as the asks panel, not as tiles
|
rendered, rendered_html = body if body is not None else (None, False)
|
||||||
and not is_ask_file(p.name) and not is_answer_file(p.name)
|
out.append(
|
||||||
]
|
|
||||||
by_rel = {p.relative_to(child).as_posix(): p for p in all_files}
|
|
||||||
caption: dict[str, str] = {}
|
|
||||||
sidecars: set[str] = set()
|
|
||||||
|
|
||||||
for rel, p in by_rel.items():
|
|
||||||
if not rel.lower().endswith(".txt"):
|
|
||||||
continue
|
|
||||||
target = None
|
|
||||||
base_full = rel[:-4] # strip ".txt" -> "a.png.txt" => "a.png"
|
|
||||||
if base_full in by_rel:
|
|
||||||
target = base_full
|
|
||||||
else: # "a.txt" beside "a.png"
|
|
||||||
parent = str(Path(rel).parent)
|
|
||||||
stem = Path(rel).stem
|
|
||||||
for q_rel, q in by_rel.items():
|
|
||||||
if q_rel == rel:
|
|
||||||
continue
|
|
||||||
if (
|
|
||||||
str(Path(q_rel).parent) == parent
|
|
||||||
and Path(q_rel).stem == stem
|
|
||||||
and classify(q.name) != "other"
|
|
||||||
):
|
|
||||||
target = q_rel
|
|
||||||
break
|
|
||||||
if target is not None:
|
|
||||||
try:
|
|
||||||
caption[target] = p.read_text(errors="replace").strip()[:CAPTION_MAX]
|
|
||||||
except OSError:
|
|
||||||
pass
|
|
||||||
sidecars.add(rel)
|
|
||||||
|
|
||||||
blurred = read_blurred(child)
|
|
||||||
items = []
|
|
||||||
for rel in sorted(by_rel):
|
|
||||||
if rel in sidecars:
|
|
||||||
continue
|
|
||||||
p = by_rel[rel]
|
|
||||||
dkind = doc_kind(p.name)
|
|
||||||
rendered = None
|
|
||||||
rendered_html = False
|
|
||||||
# Pre-render docs so the gallery can show them INLINE (collapsible)
|
|
||||||
# instead of linking out to a separate page. Bounded by DOC_MAX_BYTES:
|
|
||||||
# a giant log stays a download link rather than being inlined into every
|
|
||||||
# index render. Markdown → HTML (marked safe in the template); plain text
|
|
||||||
# is returned RAW and the template escapes it inside <pre> — pre-escaping
|
|
||||||
# here would double-encode under Jinja autoescape.
|
|
||||||
if dkind is not None:
|
|
||||||
try:
|
|
||||||
if p.stat().st_size <= DOC_MAX_BYTES:
|
|
||||||
text = p.read_text(errors="replace")
|
|
||||||
rendered, rendered_html = render_doc(text, dkind)
|
|
||||||
except OSError:
|
|
||||||
rendered = None
|
|
||||||
items.append(
|
|
||||||
{
|
{
|
||||||
"name": rel,
|
"name": it.rel,
|
||||||
"kind": classify(p.name),
|
"kind": it.kind,
|
||||||
"doc": dkind,
|
"doc": it.doc,
|
||||||
"url": quote(rel, safe="/"),
|
"url": it.url,
|
||||||
"caption": caption.get(rel),
|
"section": it.section,
|
||||||
|
"caption": it.caption,
|
||||||
"rendered": rendered,
|
"rendered": rendered,
|
||||||
"rendered_html": rendered_html,
|
"rendered_html": rendered_html,
|
||||||
"blurred": rel in blurred,
|
"blurred": it.blurred,
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
return items
|
return out
|
||||||
|
|
||||||
|
|
||||||
def zip_booth(booth: Path) -> bytes:
|
def zip_booth(booth: Path) -> bytes:
|
||||||
@@ -855,6 +768,14 @@ def create_app(
|
|||||||
|
|
||||||
@app.get("/b/{name}/view", response_class=HTMLResponse)
|
@app.get("/b/{name}/view", response_class=HTMLResponse)
|
||||||
def booth_view_file(request: Request, name: str, f: str):
|
def booth_view_file(request: Request, name: str, f: str):
|
||||||
|
"""Full-size view of ONE item — image zoom, or a doc as a readable page.
|
||||||
|
|
||||||
|
Reads the item's RECORD rather than re-deriving it. That is the whole
|
||||||
|
point of U1: this route used to call classify/doc_kind/render_doc and
|
||||||
|
booth_image_names itself, deriving a strictly smaller set of facts than
|
||||||
|
the gallery did, and the fact it lacked was the caption. An annotated
|
||||||
|
image lost its annotation at exactly the size where it is most readable.
|
||||||
|
"""
|
||||||
booth = resolve_booth(name)
|
booth = resolve_booth(name)
|
||||||
try:
|
try:
|
||||||
target = (booth / f).resolve()
|
target = (booth / f).resolve()
|
||||||
@@ -862,11 +783,24 @@ def create_app(
|
|||||||
raise HTTPException(status_code=404, detail="no such file")
|
raise HTTPException(status_code=404, detail="no such file")
|
||||||
if not str(target).startswith(str(booth) + os.sep) or not target.is_file():
|
if not str(target).startswith(str(booth) + os.sep) or not target.is_file():
|
||||||
raise HTTPException(status_code=404, detail="no such file")
|
raise HTTPException(status_code=404, detail="no such file")
|
||||||
file_url = quote(f, safe="/")
|
|
||||||
common = {**base_ctx, "name": name, "name_url": quote(name, safe=""), "file": f, "file_url": file_url}
|
items = booth_items(booth)
|
||||||
if classify(target.name) == "image":
|
item = find_item(items, f)
|
||||||
# prev/next image nav (wraps around; only when >1 image in the booth)
|
common = {
|
||||||
names = booth_image_names(booth)
|
**base_ctx,
|
||||||
|
"name": name,
|
||||||
|
"name_url": quote(name, safe=""),
|
||||||
|
"file": f,
|
||||||
|
"file_url": quote(f, safe="/"),
|
||||||
|
# The facts this route never used to carry.
|
||||||
|
"caption": item.caption if item else None,
|
||||||
|
"section": item.section if item else None,
|
||||||
|
"blurred": item.blurred if item else False,
|
||||||
|
}
|
||||||
|
|
||||||
|
if item is not None and item.kind == "image":
|
||||||
|
# prev/next ring (wraps; only when there is more than one image)
|
||||||
|
names = image_chain(items)
|
||||||
prev_url = next_url = None
|
prev_url = next_url = None
|
||||||
if f in names and len(names) > 1:
|
if f in names and len(names) > 1:
|
||||||
i = names.index(f)
|
i = names.index(f)
|
||||||
@@ -875,19 +809,22 @@ def create_app(
|
|||||||
return templates.TemplateResponse(
|
return templates.TemplateResponse(
|
||||||
request, "view.html", {**common, "prev_url": prev_url, "next_url": next_url}
|
request, "view.html", {**common, "prev_url": prev_url, "next_url": next_url}
|
||||||
)
|
)
|
||||||
|
|
||||||
# .md renders, .txt/.log show as text — viewable in-booth, no download
|
# .md renders, .txt/.log show as text — viewable in-booth, no download
|
||||||
dk = doc_kind(target.name)
|
if item is not None:
|
||||||
if dk:
|
body = render_doc_body(booth, item)
|
||||||
try:
|
if body is not None:
|
||||||
if target.stat().st_size <= DOC_MAX_BYTES:
|
rendered, is_html = body
|
||||||
body, is_html = render_doc(target.read_text(encoding="utf-8", errors="replace"), dk)
|
return templates.TemplateResponse(
|
||||||
return templates.TemplateResponse(
|
request,
|
||||||
request, "doc.html", {**common, "kind": dk, "body": body, "is_html": is_html}
|
"doc.html",
|
||||||
)
|
{**common, "kind": item.doc, "body": rendered, "is_html": is_html},
|
||||||
except OSError:
|
)
|
||||||
raise HTTPException(status_code=404, detail="no such file")
|
|
||||||
# nothing to render — hand back the raw file
|
# nothing to render — hand back the raw file
|
||||||
return RedirectResponse(url=f"/b/{quote(name, safe='')}/{file_url}", status_code=307)
|
return RedirectResponse(
|
||||||
|
url=f"/b/{quote(name, safe='')}/{quote(f, safe='/')}", status_code=307
|
||||||
|
)
|
||||||
|
|
||||||
@app.get("/b/{name}/{filepath:path}")
|
@app.get("/b/{name}/{filepath:path}")
|
||||||
def booth_file(name: str, filepath: str, dl: int = 0):
|
def booth_file(name: str, filepath: str, dl: int = 0):
|
||||||
|
|||||||
+244
@@ -0,0 +1,244 @@
|
|||||||
|
"""The item record — ONE resolver for what is in a booth.
|
||||||
|
|
||||||
|
Before this module, three functions independently walked a booth and derived
|
||||||
|
overlapping subsets of the same facts: `build_gallery` (kind, caption, blur,
|
||||||
|
doc), `booth_view_file` (kind, doc, image ring) and `list_booths` (kind counts,
|
||||||
|
cover thumb). The zoom route's subset was the smallest, and the fact it lacked
|
||||||
|
was the caption — so an annotated image lost its annotation at exactly the size
|
||||||
|
where the annotation is most readable.
|
||||||
|
|
||||||
|
That was never a rendering bug. It was three readers of one truth. This module
|
||||||
|
is the one truth; every surface reads its record and derives nothing itself.
|
||||||
|
|
||||||
|
See docs/contracts/u1_item_record.contract.md.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Sequence
|
||||||
|
from urllib.parse import quote
|
||||||
|
|
||||||
|
try: # optional: markdown rendering degrades to raw text without it
|
||||||
|
import markdown as _markdown
|
||||||
|
except ImportError: # pragma: no cover
|
||||||
|
_markdown = None
|
||||||
|
|
||||||
|
from booth.asks import is_answer_file, is_ask_file
|
||||||
|
|
||||||
|
# Browser-playable media buckets. Anything else renders as a download link.
|
||||||
|
IMAGE_EXTS = {".png", ".jpg", ".jpeg", ".gif", ".webp", ".avif", ".svg", ".bmp"}
|
||||||
|
VIDEO_EXTS = {".webm", ".mp4", ".ogv", ".m4v", ".mov"}
|
||||||
|
AUDIO_EXTS = {".mp3", ".wav", ".ogg", ".oga", ".flac", ".m4a", ".opus", ".aac"}
|
||||||
|
|
||||||
|
# Loose text docs that render as a readable page rather than a download.
|
||||||
|
MARKDOWN_EXTS = {".md", ".markdown", ".mdown"}
|
||||||
|
TEXT_EXTS = {".txt", ".text", ".log"}
|
||||||
|
|
||||||
|
CAPTION_MAX = 800 # chars of a sidecar .txt caption we render
|
||||||
|
DOC_MAX_BYTES = 2 * 1024 * 1024 # above this, a doc is handed back raw, not rendered
|
||||||
|
|
||||||
|
BLUR_FILE = ".blurred"
|
||||||
|
|
||||||
|
|
||||||
|
def classify(name: str) -> str:
|
||||||
|
"""image | video | audio | other, by extension."""
|
||||||
|
ext = Path(name).suffix.lower()
|
||||||
|
if ext in IMAGE_EXTS:
|
||||||
|
return "image"
|
||||||
|
if ext in VIDEO_EXTS:
|
||||||
|
return "video"
|
||||||
|
if ext in AUDIO_EXTS:
|
||||||
|
return "audio"
|
||||||
|
return "other"
|
||||||
|
|
||||||
|
|
||||||
|
def doc_kind(name: str) -> str | None:
|
||||||
|
"""'markdown' | 'text' | None — a booth file viewable as a readable page."""
|
||||||
|
ext = Path(name).suffix.lower()
|
||||||
|
if ext in MARKDOWN_EXTS:
|
||||||
|
return "markdown"
|
||||||
|
if ext in TEXT_EXTS:
|
||||||
|
return "text"
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def render_doc(text: str, kind: str) -> tuple[str, bool]:
|
||||||
|
"""(rendered, is_html). Markdown → HTML (fenced code, tables, sane lists);
|
||||||
|
plain text — or markdown when the lib is unavailable — → raw text for <pre>.
|
||||||
|
|
||||||
|
Text is returned RAW on purpose: the template escapes it inside <pre>, and
|
||||||
|
pre-escaping here would double-encode under Jinja autoescape.
|
||||||
|
"""
|
||||||
|
if kind == "markdown" and _markdown is not None:
|
||||||
|
html = _markdown.markdown(text, extensions=["fenced_code", "tables", "sane_lists"])
|
||||||
|
return html, True
|
||||||
|
return text, False
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Item:
|
||||||
|
"""One renderable file in a booth, with every fact any surface needs.
|
||||||
|
|
||||||
|
`rel` is the identity — the booth-relative POSIX path. Marks (U2) attach to
|
||||||
|
it, blur is keyed by it, and the zoom route resolves by it.
|
||||||
|
"""
|
||||||
|
|
||||||
|
rel: str
|
||||||
|
url: str
|
||||||
|
kind: str
|
||||||
|
section: str | None
|
||||||
|
caption: str | None
|
||||||
|
blurred: bool
|
||||||
|
doc: str | None
|
||||||
|
size: int
|
||||||
|
|
||||||
|
|
||||||
|
def read_blurred(booth: Path) -> set[str]:
|
||||||
|
"""Blurred item paths for a booth. Missing file -> empty set."""
|
||||||
|
try:
|
||||||
|
text = (booth / BLUR_FILE).read_text()
|
||||||
|
except (OSError, UnicodeDecodeError):
|
||||||
|
return set()
|
||||||
|
return {ln.strip() for ln in text.splitlines() if ln.strip()}
|
||||||
|
|
||||||
|
|
||||||
|
def _section_of(rel: str) -> str | None:
|
||||||
|
"""The item's parent directory relative to the booth; None at the root.
|
||||||
|
|
||||||
|
Derived, never stored. This is the whole input to the navigation fix (U7):
|
||||||
|
the structure a poster already created on disk, which `rglob` has been
|
||||||
|
flattening into one wall at render time.
|
||||||
|
"""
|
||||||
|
parent = Path(rel).parent
|
||||||
|
return None if str(parent) == "." else parent.as_posix()
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve_captions(by_rel: dict[str, Path]) -> tuple[dict[str, str], set[str]]:
|
||||||
|
"""(caption-by-rel, rels consumed as sidecars).
|
||||||
|
|
||||||
|
Two forms, in this precedence, preserved from the original gallery:
|
||||||
|
1. `<file>.txt` — `a.png.txt` captions `a.png`
|
||||||
|
2. `<stem>.txt` beside a same-stem MEDIA sibling — `a.txt` captions
|
||||||
|
`a.png`, but NOT `a.bin` (the `classify != "other"` guard, so a stray
|
||||||
|
`data.txt` next to `data.bin` stays an item of its own)
|
||||||
|
|
||||||
|
The sibling scan runs in sorted order rather than filesystem order: when two
|
||||||
|
media files share a stem in one directory (`a.png` and `a.webm`), the
|
||||||
|
original picked whichever `rglob` happened to yield first. Same rule, now
|
||||||
|
deterministic.
|
||||||
|
"""
|
||||||
|
caption: dict[str, str] = {}
|
||||||
|
sidecars: set[str] = set()
|
||||||
|
|
||||||
|
for rel in sorted(by_rel):
|
||||||
|
if not rel.lower().endswith(".txt"):
|
||||||
|
continue
|
||||||
|
p = by_rel[rel]
|
||||||
|
target = None
|
||||||
|
|
||||||
|
base_full = rel[:-4] # "a.png.txt" -> "a.png"
|
||||||
|
if base_full in by_rel:
|
||||||
|
target = base_full
|
||||||
|
else:
|
||||||
|
parent = str(Path(rel).parent)
|
||||||
|
stem = Path(rel).stem
|
||||||
|
for q_rel in sorted(by_rel):
|
||||||
|
if q_rel == rel:
|
||||||
|
continue
|
||||||
|
q = by_rel[q_rel]
|
||||||
|
if (
|
||||||
|
str(Path(q_rel).parent) == parent
|
||||||
|
and Path(q_rel).stem == stem
|
||||||
|
and classify(q.name) != "other"
|
||||||
|
):
|
||||||
|
target = q_rel
|
||||||
|
break
|
||||||
|
|
||||||
|
if target is not None:
|
||||||
|
try:
|
||||||
|
caption[target] = p.read_text(errors="replace").strip()[:CAPTION_MAX]
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
sidecars.add(rel)
|
||||||
|
|
||||||
|
return caption, sidecars
|
||||||
|
|
||||||
|
|
||||||
|
def booth_items(booth: Path) -> list[Item]:
|
||||||
|
"""Every renderable file in a booth, sorted by relative path.
|
||||||
|
|
||||||
|
Excluded: dotfiles, `*.ask.json` / `*.answer.json` (they render as the asks
|
||||||
|
panel, not as tiles), and any file consumed as another item's caption.
|
||||||
|
|
||||||
|
Doc BODIES are deliberately not rendered here. The index calls this once per
|
||||||
|
booth to count items and pick a cover; rendering every doc in every booth on
|
||||||
|
every page load would be the cost of that convenience. `render_doc_body` is
|
||||||
|
the separate step, for the one consumer that needs it.
|
||||||
|
"""
|
||||||
|
by_rel: dict[str, Path] = {}
|
||||||
|
for p in booth.rglob("*"):
|
||||||
|
if not p.is_file() or p.name.startswith("."):
|
||||||
|
continue
|
||||||
|
if is_ask_file(p.name) or is_answer_file(p.name):
|
||||||
|
continue
|
||||||
|
by_rel[p.relative_to(booth).as_posix()] = p
|
||||||
|
|
||||||
|
caption, sidecars = _resolve_captions(by_rel)
|
||||||
|
blurred = read_blurred(booth) # ONE read per call, not one per item
|
||||||
|
|
||||||
|
items: list[Item] = []
|
||||||
|
for rel in sorted(by_rel):
|
||||||
|
if rel in sidecars:
|
||||||
|
continue
|
||||||
|
p = by_rel[rel]
|
||||||
|
try:
|
||||||
|
size = p.stat().st_size
|
||||||
|
except OSError:
|
||||||
|
size = 0
|
||||||
|
items.append(
|
||||||
|
Item(
|
||||||
|
rel=rel,
|
||||||
|
url=quote(rel, safe="/"),
|
||||||
|
kind=classify(p.name),
|
||||||
|
section=_section_of(rel),
|
||||||
|
caption=caption.get(rel),
|
||||||
|
blurred=rel in blurred,
|
||||||
|
doc=doc_kind(p.name),
|
||||||
|
size=size,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return items
|
||||||
|
|
||||||
|
|
||||||
|
def image_chain(items: Sequence[Item]) -> list[str]:
|
||||||
|
"""The rels of the image items, in order — the zoom view's prev/next ring.
|
||||||
|
|
||||||
|
Replaces `booth_image_names`, which walked the tree a second time to derive
|
||||||
|
what the item list already knows.
|
||||||
|
"""
|
||||||
|
return [it.rel for it in items if it.kind == "image"]
|
||||||
|
|
||||||
|
|
||||||
|
def find_item(items: Sequence[Item], rel: str) -> Item | None:
|
||||||
|
"""The record for one rel, or None — the zoom/doc route's entry point."""
|
||||||
|
for it in items:
|
||||||
|
if it.rel == rel:
|
||||||
|
return it
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def render_doc_body(booth: Path, item: Item) -> tuple[str, bool] | None:
|
||||||
|
"""(body, is_html) for a doc item under DOC_MAX_BYTES, else None.
|
||||||
|
|
||||||
|
None means "do not inline this": either it is not a doc, or it is a log big
|
||||||
|
enough that inlining it into every page render is the wrong trade.
|
||||||
|
"""
|
||||||
|
if item.doc is None or item.size > DOC_MAX_BYTES:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
text = (booth / item.rel).read_text(encoding="utf-8", errors="replace")
|
||||||
|
except OSError:
|
||||||
|
return None
|
||||||
|
return render_doc(text, item.doc)
|
||||||
@@ -8,6 +8,9 @@
|
|||||||
<span class="vspacer"></span>
|
<span class="vspacer"></span>
|
||||||
<a class="vbtn" href="{{ file_url }}?dl=1" title="download {{ file }}">⬇</a>
|
<a class="vbtn" href="{{ file_url }}?dl=1" title="download {{ file }}">⬇</a>
|
||||||
</div>
|
</div>
|
||||||
|
{# Same record, same reason as the image viewer: the sidecar that says what
|
||||||
|
this doc IS travels with it to full-page view. #}
|
||||||
|
{% if caption %}<div class="doccap">{{ caption }}</div>{% endif %}
|
||||||
{% if is_html %}
|
{% if is_html %}
|
||||||
<article class="markdown-body">{{ body|safe }}</article>
|
<article class="markdown-body">{{ body|safe }}</article>
|
||||||
{% else %}
|
{% else %}
|
||||||
@@ -19,6 +22,10 @@
|
|||||||
gallery view). Only the full-page layout wrapper is page-specific. */
|
gallery view). Only the full-page layout wrapper is page-specific. */
|
||||||
.docview{max-width:52rem;margin:0 auto;padding:0 clamp(12px,3vw,20px) 4rem}
|
.docview{max-width:52rem;margin:0 auto;padding:0 clamp(12px,3vw,20px) 4rem}
|
||||||
.docview .textview{overflow-x:auto}
|
.docview .textview{overflow-x:auto}
|
||||||
|
.doccap{margin:.9rem 0 1.2rem;padding:.6rem .85rem;font-size:.85rem;line-height:1.5;
|
||||||
|
color:var(--fg-1);background:var(--rk-surface,rgba(255,255,255,.04));
|
||||||
|
border-left:2px solid var(--aus-bright-cyan,#42dcd1);border-radius:0 6px 6px 0;
|
||||||
|
white-space:pre-wrap}
|
||||||
</style>
|
</style>
|
||||||
<script>
|
<script>
|
||||||
document.addEventListener('keydown', function (e) {
|
document.addEventListener('keydown', function (e) {
|
||||||
|
|||||||
@@ -14,6 +14,11 @@
|
|||||||
{% if prev_url %}<a class="vnav vprev" href="?f={{ prev_url }}" title="previous (←)" aria-label="previous image">‹</a>{% endif %}
|
{% if prev_url %}<a class="vnav vprev" href="?f={{ prev_url }}" title="previous (←)" aria-label="previous image">‹</a>{% endif %}
|
||||||
{% if next_url %}<a class="vnav vnext" href="?f={{ next_url }}" title="next (→)" aria-label="next image">›</a>{% endif %}
|
{% if next_url %}<a class="vnav vnext" href="?f={{ next_url }}" title="next (→)" aria-label="next image">›</a>{% endif %}
|
||||||
<div class="vstage fit" id="vstage"><img id="vimg" src="{{ file_url }}" alt="{{ file }}"></div>
|
<div class="vstage fit" id="vstage"><img id="vimg" src="{{ file_url }}" alt="{{ file }}"></div>
|
||||||
|
{# THE ANNOTATION, at full size. It was never rendered here before U1 — not
|
||||||
|
because the template dropped it, but because the route never resolved it.
|
||||||
|
A caption is most useful at the size where you are actually judging the
|
||||||
|
thing, so it belongs here at least as much as in the grid. #}
|
||||||
|
{% if caption %}<div class="vcap">{{ caption }}</div>{% endif %}
|
||||||
</div>
|
</div>
|
||||||
<style>
|
<style>
|
||||||
.vnav{position:fixed;top:50%;transform:translateY(-50%);z-index:40;display:flex;
|
.vnav{position:fixed;top:50%;transform:translateY(-50%);z-index:40;display:flex;
|
||||||
@@ -23,6 +28,12 @@
|
|||||||
-webkit-backdrop-filter:blur(4px);backdrop-filter:blur(4px);transition:background .15s,border-color .15s}
|
-webkit-backdrop-filter:blur(4px);backdrop-filter:blur(4px);transition:background .15s,border-color .15s}
|
||||||
.vnav:hover{background:rgba(28,33,46,.92);border-color:var(--aus-bright-cyan,#42dcd1)}
|
.vnav:hover{background:rgba(28,33,46,.92);border-color:var(--aus-bright-cyan,#42dcd1)}
|
||||||
.vprev{left:0}.vnext{right:0}
|
.vprev{left:0}.vnext{right:0}
|
||||||
|
/* Bottom bar rather than the top chrome: a caption can run to CAPTION_MAX
|
||||||
|
(800 chars), which would shove the filename and the Fit/1:1 toggle around. */
|
||||||
|
.vcap{flex:0 0 auto;max-height:22vh;overflow-y:auto;padding:.6rem clamp(12px,3vw,20px);
|
||||||
|
font-size:.85rem;line-height:1.5;color:var(--fg-1);background:var(--rk-surface,rgba(20,23,32,.92));
|
||||||
|
border-top:1px solid rgba(255,255,255,.10);white-space:pre-wrap}
|
||||||
|
@media print{.vcap{max-height:none;overflow:visible}}
|
||||||
@media print{.vnav{display:none}}
|
@media print{.vnav{display:none}}
|
||||||
</style>
|
</style>
|
||||||
<script>
|
<script>
|
||||||
|
|||||||
@@ -0,0 +1,142 @@
|
|||||||
|
---
|
||||||
|
contract_version: "1.0"
|
||||||
|
module: "booth.items"
|
||||||
|
purpose: "ONE resolver for what is in a booth. `booth_items(booth)` returns the full record for every renderable file -- relative path, kind, section, caption, blur state, doc kind and size -- and the gallery, the zoom view, the doc view, the index thumbnail and the image prev/next chain all read from it. Today three independent paths (`build_gallery`, `booth_view_file`, `list_booths`) re-derive overlapping subsets of the same facts from the filesystem, and the zoom path derives a strictly smaller subset: it never resolves the caption at all, so an annotated image loses its annotation the moment it is opened full-size. That is not a rendering bug to patch in one template; it is three readers of one truth, and the fix is to have one."
|
||||||
|
depends_on:
|
||||||
|
- "booth.asks (is_ask_file, is_answer_file -- the two sidecar shapes excluded from items; unchanged by this unit, folded into marks at U2)"
|
||||||
|
language: "python"
|
||||||
|
complexity: "low"
|
||||||
|
estimated_loc: 180
|
||||||
|
confidence: 0.9
|
||||||
|
used_by:
|
||||||
|
- "booth.app.build_gallery (becomes a thin adapter over booth_items + render_doc_body)"
|
||||||
|
- "booth.app.booth_view_file (the zoom and doc routes -- gains caption/section/blur it never had)"
|
||||||
|
- "booth.app.list_booths (index counts + cover thumbnail: ONE classification path instead of a second inline loop)"
|
||||||
|
- "booth.app.booth_image_names (deleted -- becomes a filter over the item list)"
|
||||||
|
touches:
|
||||||
|
- "booth/items.py (new)"
|
||||||
|
- "booth/app.py (build_gallery reduced to an adapter; booth_view_file reads the record; list_booths uses the resolver; booth_image_names removed; classify/doc_kind/CAPTION_MAX/IMAGE_EXTS/VIDEO_EXTS/AUDIO_EXTS/MARKDOWN_EXTS/TEXT_EXTS/DOC_MAX_BYTES move to items.py and are re-exported so existing imports keep working)"
|
||||||
|
- "booth/templates/view.html (renders the caption, section and blur state it is now given)"
|
||||||
|
- "booth/templates/doc.html (same)"
|
||||||
|
- "tests/test_items.py (new)"
|
||||||
|
- "tests/test_booth.py (existing build_gallery/classify/doc_kind tests keep passing through the re-exports; new assertions that the zoom route carries the caption)"
|
||||||
|
assumptions:
|
||||||
|
- "RE-EXPORT, NOT MOVE-AND-BREAK. `classify`, `doc_kind`, `render_doc`, `CAPTION_MAX` and the extension sets are imported by name from `booth.app` in 20+ existing test sites. They move to `booth.items` and `booth.app` re-exports them, so no test is edited to chase an import. The re-export is load-bearing and is asserted by a test, not left to convention -- a silent drop would be found by a consumer, not by us."
|
||||||
|
- "DOC BODIES ARE NOT RENDERED BY THE RESOLVER. `build_gallery` today eagerly renders every markdown/text file under DOC_MAX_BYTES. If the resolver did that, the INDEX -- which calls it once per booth to count items and pick a cover -- would markdown-render every doc in every booth on every page load. So the record carries `doc` (the kind) and `size`, and a separate `render_doc_body(booth, item)` does the work for the one consumer that needs it. Same rendering, same DOC_MAX_BYTES bound, same raw-text-for-<pre> contract; strictly less work on the index."
|
||||||
|
- "CAPTION RESOLUTION IS PRESERVED EXACTLY, not re-specified. Two forms, in this precedence: (1) `<file>.txt` -- `a.png.txt` captions `a.png`; (2) `<stem>.txt` beside a same-stem non-`other` sibling -- `a.txt` captions `a.png`, but NOT `a.bin`. A file consumed as a caption is excluded from the item list. Truncated at CAPTION_MAX (800). This is existing behaviour with existing tests; the unit moves it, it does not improve it. Any change here is a separate unit."
|
||||||
|
- "SECTION is the item's parent directory relative to the booth, or None at the root. Purely derived -- no new state, no config. It is the navigation fix's whole input (U7) and it already exists on disk: `pewpew-ui-brief` has integration/ and blueprint/, `dfa-concepts` has source/. This unit computes and carries it; NOTHING renders it yet. That is deliberate -- U1 is the record, U7 is the view, and shipping the field early means U7 is a template change rather than a resolver change."
|
||||||
|
- "ORDER is `sorted(rel)` as today -- byte order over the POSIX relative path, which groups a subfolder's items together as a side effect. U7 may impose a section-aware order; until then the gallery renders in exactly the order it renders in now, so this unit is not allowed to move a single tile."
|
||||||
|
- "BLUR state is read once per resolver call, not once per item. `read_blurred` opens `.blurred` on every call; `build_gallery` already hoists it, `list_booths` does NOT (it calls read_blurred inside a conditional per booth). One read per call, passed down."
|
||||||
|
open_questions:
|
||||||
|
- "Whether `other`-kind files should carry a section header in U7 or stay in a trailing 'files' group -- a view question, deferred with U7."
|
||||||
|
- "Whether CAPTION_MAX should grow now that a caption also renders at full size in the zoom view, where there is room for it. Left at 800; changing it is a one-line follow-up with no structural consequence."
|
||||||
|
---
|
||||||
|
|
||||||
|
# U1 — the item record
|
||||||
|
|
||||||
|
## The defect, stated precisely
|
||||||
|
|
||||||
|
Three functions independently walk a booth and derive facts about its files:
|
||||||
|
|
||||||
|
| reader | derives | omits |
|
||||||
|
|---|---|---|
|
||||||
|
| `build_gallery` (app.py:314) | kind, caption, blur, doc kind, rendered body | section |
|
||||||
|
| `booth_view_file` (app.py:857) | kind, doc kind, rendered body, image prev/next | **caption**, blur, section |
|
||||||
|
| `list_booths` (app.py:265) | kind (counts), cover thumb, cover blur | everything else |
|
||||||
|
|
||||||
|
`booth_view_file` is the zoom and doc route. It calls `classify(target.name)`,
|
||||||
|
`booth_image_names(booth)`, `doc_kind(target.name)` and `render_doc(...)` — it
|
||||||
|
re-derives the item from scratch and, because caption resolution lives inside
|
||||||
|
`build_gallery`'s loop and nowhere else, **there is no code path by which a
|
||||||
|
caption could reach the zoom template.** The operator's report that "zoomed-in
|
||||||
|
images lose their annotations" is exact, and the annotation is not lost in
|
||||||
|
rendering: it is never sent.
|
||||||
|
|
||||||
|
Patching `view.html` fixes the symptom for images. The next template — the doc
|
||||||
|
view, the compare view, the zip manifest — starts from the same missing truth.
|
||||||
|
|
||||||
|
## The record
|
||||||
|
|
||||||
|
```python
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Item:
|
||||||
|
rel: str # booth-relative POSIX path; the item's identity
|
||||||
|
url: str # quote(rel, safe="/")
|
||||||
|
kind: str # "image" | "video" | "audio" | "other"
|
||||||
|
section: str | None # parent dir relative to the booth; None at the root
|
||||||
|
caption: str | None # resolved sidecar text, <= CAPTION_MAX
|
||||||
|
blurred: bool
|
||||||
|
doc: str | None # "markdown" | "text" | None
|
||||||
|
size: int # bytes; lets a consumer decide about DOC_MAX_BYTES
|
||||||
|
```
|
||||||
|
|
||||||
|
## Signatures
|
||||||
|
|
||||||
|
```python
|
||||||
|
def booth_items(booth: Path) -> list[Item]:
|
||||||
|
"""Every renderable file in a booth, sorted by rel.
|
||||||
|
|
||||||
|
Excluded: dotfiles, `*.ask.json` / `*.answer.json` (they render as the asks
|
||||||
|
panel, not as tiles), and any file consumed as another item's caption.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def image_chain(items: Sequence[Item]) -> list[str]:
|
||||||
|
"""The rels of the image items, in order -- the zoom view's prev/next ring.
|
||||||
|
Replaces booth_image_names, which walked the tree a second time."""
|
||||||
|
|
||||||
|
def find_item(items: Sequence[Item], rel: str) -> Item | None:
|
||||||
|
"""The record for one rel, or None. The zoom/doc route's entry point."""
|
||||||
|
|
||||||
|
def render_doc_body(booth: Path, item: Item) -> tuple[str, bool] | None:
|
||||||
|
"""(body, is_html) for a doc item under DOC_MAX_BYTES, else None.
|
||||||
|
Markdown -> HTML (marked safe by the caller); text -> RAW, escaped by the
|
||||||
|
template inside <pre>. Pre-escaping here double-encodes under autoescape."""
|
||||||
|
```
|
||||||
|
|
||||||
|
## Invariants
|
||||||
|
|
||||||
|
- **INV-1 — one truth.** No consumer classifies a file, resolves a caption, or
|
||||||
|
reads blur state on its own. Every fact about an item comes from its `Item`.
|
||||||
|
*Falsifiable:* no call to `classify`, `doc_kind` or `read_blurred` remains in
|
||||||
|
a route body.
|
||||||
|
- **INV-2 — the caption travels.** If `booth_items` resolves a caption for an
|
||||||
|
item, every surface that renders that item renders the caption: gallery, zoom,
|
||||||
|
doc view. *Falsifiable:* fetch `/b/<n>/view?f=<img>` for an item with a sidecar
|
||||||
|
and assert the caption text is in the served HTML.
|
||||||
|
- **INV-3 — order is unchanged.** For every booth, the rels from `booth_items`
|
||||||
|
equal, in order, the names from today's `build_gallery`. This unit reorganises
|
||||||
|
who computes what; it does not move a tile.
|
||||||
|
- **INV-4 — the index does not render docs.** `list_booths` completes without
|
||||||
|
calling `render_doc_body`. *Falsifiable:* monkeypatch it to raise, load `/`.
|
||||||
|
- **INV-5 — re-exports hold.** `classify`, `doc_kind`, `render_doc`,
|
||||||
|
`CAPTION_MAX` and the extension sets remain importable from `booth.app`.
|
||||||
|
|
||||||
|
## Steps
|
||||||
|
|
||||||
|
1. `booth/items.py`: the extension sets, `classify`, `doc_kind`, `render_doc`,
|
||||||
|
`CAPTION_MAX`, `DOC_MAX_BYTES`, the `Item` dataclass, `booth_items`,
|
||||||
|
`image_chain`, `find_item`, `render_doc_body`. Caption resolution moves
|
||||||
|
verbatim out of `build_gallery`.
|
||||||
|
2. `booth/app.py`: re-export the moved names. `build_gallery` becomes an adapter
|
||||||
|
returning today's dict shape (templates unchanged in this unit) built from
|
||||||
|
`booth_items` + `render_doc_body`. Delete `booth_image_names`.
|
||||||
|
3. `booth_view_file`: resolve through `find_item`; pass `caption`, `section`,
|
||||||
|
`blurred`, and `image_chain` for prev/next.
|
||||||
|
4. `list_booths`: counts and cover from `booth_items`; one `read_blurred`.
|
||||||
|
5. `view.html` / `doc.html`: render the caption and blur state they now receive.
|
||||||
|
|
||||||
|
## Tests
|
||||||
|
|
||||||
|
| test | asserts |
|
||||||
|
|---|---|
|
||||||
|
| `zoom_carries_the_caption` | `/b/<n>/view?f=a.png` with `a.png.txt` present contains the caption text — **the operator-reported bug, as a regression test** |
|
||||||
|
| `zoom_carries_the_stem_caption` | the `a.txt`-beside-`a.png` form too |
|
||||||
|
| `doc_view_carries_the_caption` | same for `/view?f=notes.md` |
|
||||||
|
| `section_is_the_parent_dir` | `v3/x.png` → `"v3"`; `x.png` → `None` |
|
||||||
|
| `order_matches_todays_gallery` | INV-3, over a fixture with subfolders, sidecars and mixed kinds |
|
||||||
|
| `caption_sidecars_are_not_items` | both forms excluded, as today |
|
||||||
|
| `a_txt_beside_a_bin_is_its_own_item` | the `classify != "other"` guard survives |
|
||||||
|
| `index_renders_no_doc_bodies` | INV-4 via monkeypatch |
|
||||||
|
| `app_still_exports_the_moved_names` | INV-5 — each name importable from `booth.app` |
|
||||||
|
| `image_chain_matches_booth_image_names` | the deleted helper's output, reproduced |
|
||||||
|
| `ask_sidecars_are_not_items` | `*.ask.json` / `*.answer.json` still excluded |
|
||||||
@@ -0,0 +1,260 @@
|
|||||||
|
"""U1 — the item record.
|
||||||
|
|
||||||
|
The headline here is `zoom_carries_the_caption`. The operator reported that
|
||||||
|
zoomed-in images lose their annotations; the cause was not a rendering bug but
|
||||||
|
three independent readers of one truth, of which the zoom route was the one that
|
||||||
|
never resolved a caption at all. These tests pin the record and pin the bug.
|
||||||
|
|
||||||
|
See docs/contracts/u1_item_record.contract.md.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
from booth.app import build_gallery, create_app, list_booths
|
||||||
|
from booth.items import (
|
||||||
|
Item,
|
||||||
|
booth_items,
|
||||||
|
find_item,
|
||||||
|
image_chain,
|
||||||
|
render_doc_body,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _touch(path, data=b"x"):
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
path.write_bytes(data)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def client(tmp_path):
|
||||||
|
app = create_app(tmp_path, ttl_hours=24, start_sweeper=False)
|
||||||
|
return TestClient(app), tmp_path
|
||||||
|
|
||||||
|
|
||||||
|
# ---- the record -------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_section_is_the_parent_dir(tmp_path):
|
||||||
|
_touch(tmp_path / "root.png")
|
||||||
|
_touch(tmp_path / "v3" / "x.png")
|
||||||
|
_touch(tmp_path / "v3" / "deep" / "y.png")
|
||||||
|
|
||||||
|
by_rel = {it.rel: it for it in booth_items(tmp_path)}
|
||||||
|
assert by_rel["root.png"].section is None
|
||||||
|
assert by_rel["v3/x.png"].section == "v3"
|
||||||
|
assert by_rel["v3/deep/y.png"].section == "v3/deep"
|
||||||
|
|
||||||
|
|
||||||
|
def test_caption_sidecars_are_not_items(tmp_path):
|
||||||
|
_touch(tmp_path / "a.png")
|
||||||
|
(tmp_path / "a.txt").write_text("variant A")
|
||||||
|
_touch(tmp_path / "b.png")
|
||||||
|
(tmp_path / "b.png.txt").write_text("variant B")
|
||||||
|
(tmp_path / "loose.txt").write_text("captions nothing")
|
||||||
|
|
||||||
|
by_rel = {it.rel: it for it in booth_items(tmp_path)}
|
||||||
|
assert by_rel["a.png"].caption == "variant A"
|
||||||
|
assert by_rel["b.png"].caption == "variant B"
|
||||||
|
assert "a.txt" not in by_rel and "b.png.txt" not in by_rel
|
||||||
|
assert "loose.txt" in by_rel # a caption with nothing to caption stays visible
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_txt_beside_a_bin_is_its_own_item(tmp_path):
|
||||||
|
"""The `classify != "other"` guard: a .txt only captions a MEDIA sibling."""
|
||||||
|
_touch(tmp_path / "data.bin")
|
||||||
|
(tmp_path / "data.txt").write_text("not a caption for a blob")
|
||||||
|
|
||||||
|
by_rel = {it.rel: it for it in booth_items(tmp_path)}
|
||||||
|
assert "data.txt" in by_rel
|
||||||
|
assert by_rel["data.bin"].caption is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_ask_sidecars_are_not_items(tmp_path):
|
||||||
|
_touch(tmp_path / "a.png")
|
||||||
|
(tmp_path / "pick.ask.json").write_text("{}")
|
||||||
|
(tmp_path / "pick.answer.json").write_text("{}")
|
||||||
|
|
||||||
|
rels = {it.rel for it in booth_items(tmp_path)}
|
||||||
|
assert rels == {"a.png"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_dotfiles_are_not_items(tmp_path):
|
||||||
|
_touch(tmp_path / "a.png")
|
||||||
|
_touch(tmp_path / ".forever")
|
||||||
|
_touch(tmp_path / ".blurred")
|
||||||
|
|
||||||
|
assert {it.rel for it in booth_items(tmp_path)} == {"a.png"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_blur_state_rides_on_the_item(tmp_path):
|
||||||
|
_touch(tmp_path / "a.png")
|
||||||
|
_touch(tmp_path / "b.png")
|
||||||
|
(tmp_path / ".blurred").write_text("a.png\n")
|
||||||
|
|
||||||
|
by_rel = {it.rel: it for it in booth_items(tmp_path)}
|
||||||
|
assert by_rel["a.png"].blurred is True
|
||||||
|
assert by_rel["b.png"].blurred is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_order_matches_todays_gallery(tmp_path):
|
||||||
|
"""INV-3: this unit reorganises who computes what. It must not move a tile."""
|
||||||
|
_touch(tmp_path / "z.png")
|
||||||
|
_touch(tmp_path / "a.png")
|
||||||
|
(tmp_path / "a.txt").write_text("cap")
|
||||||
|
_touch(tmp_path / "v3" / "b.png")
|
||||||
|
_touch(tmp_path / "v4" / "b.png")
|
||||||
|
(tmp_path / "notes.md").write_text("# hi")
|
||||||
|
_touch(tmp_path / "blob.bin")
|
||||||
|
|
||||||
|
assert [it.rel for it in booth_items(tmp_path)] == [
|
||||||
|
it["name"] for it in build_gallery(tmp_path)
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
# ---- helpers ----------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_image_chain_is_the_images_in_order(tmp_path):
|
||||||
|
_touch(tmp_path / "b.png")
|
||||||
|
_touch(tmp_path / "a.png")
|
||||||
|
_touch(tmp_path / "clip.webm")
|
||||||
|
(tmp_path / "notes.md").write_text("# hi")
|
||||||
|
|
||||||
|
assert image_chain(booth_items(tmp_path)) == ["a.png", "b.png"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_find_item(tmp_path):
|
||||||
|
_touch(tmp_path / "a.png")
|
||||||
|
items = booth_items(tmp_path)
|
||||||
|
assert find_item(items, "a.png").rel == "a.png"
|
||||||
|
assert find_item(items, "nope.png") is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_render_doc_body_markdown_and_text(tmp_path):
|
||||||
|
(tmp_path / "r.md").write_text("# Title\n\n- a\n- b\n")
|
||||||
|
(tmp_path / "n.txt").write_text("plain\ntext")
|
||||||
|
items = {it.rel: it for it in booth_items(tmp_path)}
|
||||||
|
|
||||||
|
html, is_html = render_doc_body(tmp_path, items["r.md"])
|
||||||
|
assert is_html and "<h1>" in html
|
||||||
|
body, is_html = render_doc_body(tmp_path, items["n.txt"])
|
||||||
|
assert not is_html and body == "plain\ntext"
|
||||||
|
|
||||||
|
|
||||||
|
def test_render_doc_body_is_none_for_a_huge_doc(tmp_path):
|
||||||
|
from booth.items import DOC_MAX_BYTES
|
||||||
|
|
||||||
|
(tmp_path / "huge.log").write_text("x" * (DOC_MAX_BYTES + 1))
|
||||||
|
items = {it.rel: it for it in booth_items(tmp_path)}
|
||||||
|
assert render_doc_body(tmp_path, items["huge.log"]) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_render_doc_body_is_none_for_a_non_doc(tmp_path):
|
||||||
|
_touch(tmp_path / "a.png")
|
||||||
|
items = {it.rel: it for it in booth_items(tmp_path)}
|
||||||
|
assert render_doc_body(tmp_path, items["a.png"]) is None
|
||||||
|
|
||||||
|
|
||||||
|
# ---- the bug this unit exists to close --------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_zoom_carries_the_caption(client):
|
||||||
|
"""THE operator-reported defect, as a regression test.
|
||||||
|
|
||||||
|
`a.png.txt` captions `a.png` in the gallery. Before U1 the zoom route
|
||||||
|
re-derived the item from scratch and never resolved a caption, so the
|
||||||
|
annotation vanished at exactly the size where it is most readable.
|
||||||
|
"""
|
||||||
|
c, data = client
|
||||||
|
b = data / "bo"
|
||||||
|
_touch(b / "a.png")
|
||||||
|
(b / "a.png.txt").write_text("the annotation that used to vanish")
|
||||||
|
|
||||||
|
r = c.get("/b/bo/view", params={"f": "a.png"})
|
||||||
|
assert r.status_code == 200
|
||||||
|
assert "the annotation that used to vanish" in r.text
|
||||||
|
|
||||||
|
|
||||||
|
def test_zoom_carries_the_stem_caption(client):
|
||||||
|
"""The other caption form -- `a.txt` beside `a.png`."""
|
||||||
|
c, data = client
|
||||||
|
b = data / "bo"
|
||||||
|
_touch(b / "a.png")
|
||||||
|
(b / "a.txt").write_text("stem-form annotation")
|
||||||
|
|
||||||
|
r = c.get("/b/bo/view", params={"f": "a.png"})
|
||||||
|
assert "stem-form annotation" in r.text
|
||||||
|
|
||||||
|
|
||||||
|
def test_doc_view_carries_the_caption(client):
|
||||||
|
c, data = client
|
||||||
|
b = data / "bo"
|
||||||
|
b.mkdir()
|
||||||
|
(b / "notes.md").write_text("# body")
|
||||||
|
(b / "notes.md.txt").write_text("what this doc is")
|
||||||
|
|
||||||
|
r = c.get("/b/bo/view", params={"f": "notes.md"})
|
||||||
|
assert r.status_code == 200
|
||||||
|
assert "what this doc is" in r.text
|
||||||
|
|
||||||
|
|
||||||
|
def test_zoom_prev_next_still_works(client):
|
||||||
|
"""image_chain replaces booth_image_names; the ring must be unchanged."""
|
||||||
|
c, data = client
|
||||||
|
b = data / "bo"
|
||||||
|
_touch(b / "a.png")
|
||||||
|
_touch(b / "b.png")
|
||||||
|
|
||||||
|
r = c.get("/b/bo/view", params={"f": "a.png"})
|
||||||
|
assert "b.png" in r.text # prev and next both wrap to the only other image
|
||||||
|
|
||||||
|
|
||||||
|
# ---- invariants -------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_index_renders_no_doc_bodies(client, monkeypatch):
|
||||||
|
"""INV-4: the index calls the resolver once per booth. If it also rendered
|
||||||
|
every doc, a page load would markdown-render every doc in every booth."""
|
||||||
|
c, data = client
|
||||||
|
b = data / "bo"
|
||||||
|
b.mkdir()
|
||||||
|
(b / "big.md").write_text("# hi")
|
||||||
|
_touch(b / "a.png")
|
||||||
|
|
||||||
|
import booth.items as items_mod
|
||||||
|
|
||||||
|
def boom(*a, **k):
|
||||||
|
raise AssertionError("the index must not render doc bodies")
|
||||||
|
|
||||||
|
monkeypatch.setattr(items_mod, "render_doc_body", boom)
|
||||||
|
assert c.get("/").status_code == 200
|
||||||
|
|
||||||
|
|
||||||
|
def test_app_still_exports_the_moved_names():
|
||||||
|
"""INV-5: 22 existing test sites import these from booth.app by name."""
|
||||||
|
import booth.app as app_mod
|
||||||
|
|
||||||
|
for name in (
|
||||||
|
"classify",
|
||||||
|
"doc_kind",
|
||||||
|
"render_doc",
|
||||||
|
"CAPTION_MAX",
|
||||||
|
"DOC_MAX_BYTES",
|
||||||
|
"IMAGE_EXTS",
|
||||||
|
"VIDEO_EXTS",
|
||||||
|
"AUDIO_EXTS",
|
||||||
|
"MARKDOWN_EXTS",
|
||||||
|
"TEXT_EXTS",
|
||||||
|
):
|
||||||
|
assert hasattr(app_mod, name), f"booth.app must still export {name}"
|
||||||
|
|
||||||
|
|
||||||
|
def test_list_booths_counts_match_the_resolver(tmp_path):
|
||||||
|
b = tmp_path / "bo"
|
||||||
|
_touch(b / "a.png")
|
||||||
|
_touch(b / "clip.webm")
|
||||||
|
(b / "a.txt").write_text("cap") # captions a.png # a sidecar is not an item
|
||||||
|
|
||||||
|
got = list_booths(tmp_path, ttl_seconds=86400)[0]
|
||||||
|
assert got["count"] == len(booth_items(b)) == 2
|
||||||
Reference in New Issue
Block a user