deploy femoral-head annotator
Browse filesFiles changed (4)
- app.py+1013-993
- test_arc.py+107
- test_layout.py+39
- ui.py+179-35
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993"""Femoral-head annotation Space — two clicks per lateral radiograph, distributed.Mirrors the CTSpinoPelvic1K review service deliberately: HuggingFace token as identity,a dataset repo as the ledger, claim slots with a TTL, and double annotation withadjudication on disagreement. Same shape, so the same people already know how to use it.HF_TOKEN write token for the ledger dataset (Space secret)ANNOT_REPO dataset repo holding cases/ and annotations/IMAGE_REPO dataset repo holding the films (read-only)ADJUDICATORS comma/space-separated HF usernames allowed to adjudicateWHY THIS AND NOT ITK-SNAP-------------------------ITK-SNAP is a 3-D volume tool. Annotating two points on a 2-D radiograph through it meansconverting every film to a single-slice volume, installing software, and training peopleon a segmentation UI to place two dots. A browser canvas is two clicks and no install,and the Space is already how this group works.NO AUTOMATIC PROPOSAL IS EVER SHOWN. The whole purpose of these annotations is anINDEPENDENT reference for a hip point predicted from synthetic data. Displaying themodel's guess -- or the classical circle fit -- as a starting position would anchor theannotator to it, and agreement would then measure suggestibility rather than anatomy.This is the single most important design decision in the tool, and it is why the filecontains no call to any predictor.WHAT IS COLLECTED, AND WHY BOTH HEADS-------------------------------------Left and right femoral head centres separately, not the midpoint. On a true lateral thetwo heads superimpose, but rotation separates them -- and the bicoxofemoral point isDEFINED as the midpoint of the two centres (Legaye & Duval-Beaupere 1998). Collectingboth lets the midpoint be derived, lets their separation flag an oblique film, and lets areader mark only one when the other is genuinely invisible.CRITERIA � shown in the app and repeated here so the definition lives with the code.ANATOMICAL DEFINITIONThe bicoxofemoral (hip) axis is the line joining the CENTRES of the two femoral heads.The point used for PI, PT and SS is the MIDPOINT of that line (Legaye & Duval-Beaupere,Eur Spine J 1998). It is a geometric centre, not a surface point and not a palpablelandmark: the femoral head is very nearly a sphere, so its projection on any radiographis a circle and the point wanted is the centre of that circle.HOW TO FIND IT ON A LATERAL FILM1. Identify the femoral head: the round dense structure below and anterior to the S1endplate, seated in the acetabulum.2. Trace the SUBCHONDRAL CORTICAL MARGIN -- the thin dense arc of the articular surface.That arc is the circle to centre on. This is the Mose concentric-circle method doneby eye.3. Place the point at the centre of curvature of that arc, NOT at the densest part ofthe shadow. Overlap with the acetabulum and the opposite head makes the brightestregion sit medial to the true centre.WHAT NOT TO USE* the fovea capitis -- the medial notch where ligamentum teres attaches. It is a defectin the sphere; centring on it pulls the point medially.* the greater trochanter, the femoral neck, or the head-neck junction. None of them ispart of the sphere.* the acetabular roof or teardrop. They belong to the pelvis, not the head.ONE HEAD OR TWOOn a well-positioned lateral the two heads superimpose almost exactly and you will seeone circle -- mark it as LEFT and leave RIGHT empty. Rotation separates them into twooverlapping circles; then mark both, and their midpoint is derived automatically. Theirseparation is itself recorded, because a wide separation means an oblique film and thespinopelvic parameters from it are less trustworthy.WHEN TO SKIPProsthesis, both heads outside the collimated field, or a film so underexposed that thecortical arc cannot be traced. Skipping is a valid answer. A guessed centre becomes afabricated error in whatever this set is used to measure."""from __future__ import annotationsimport hashlibimport jsonimport osimport timefrom typing import Optionalfrom fastapi import Cookie, Depends, FastAPI, Form, Header, HTTPExceptionfrom fastapi.responses import HTMLResponse, JSONResponse, Responseimport store as store_mod # noqa: E402 (sibling, as in review_service)ANNOT_REPO = os.environ.get("ANNOT_REPO", "")IMAGE_REPO = os.environ.get("IMAGE_REPO", "")CLAIM_TTL = int(os.environ.get("CLAIM_TTL_SECONDS", 3 * 24 * 3600))N_PRIMARY = 2# Consensus tolerance, as a fraction of image width. Judged in NORMALISED units so it# means the same thing on every film regardless of pixel size.## 0.005, not the 0.02 this started at, and the difference matters. On a typical BUU film# (2012 px across roughly 400 mm, so ~5 px/mm) with the S1 midpoint about 125 mm from the# hip axis, a hip displacement of d mm moves PI and PT by atan(d/125):## 0.02 -> 40 px -> 8.0 mm -> up to 3.7 deg of PI error# 0.01 -> 20 px -> 4.0 mm -> up to 1.8 deg# 0.005 -> 10 px -> 2.0 mm -> up to 0.9 deg## The model being validated has an SS MAE of 2.3 deg. A reference whose own two readers# may disagree by 3.7 deg cannot measure a 2.3 deg error -- the ruler would be coarser# than the thing it is measuring. 0.005 keeps the reference's internal disagreement well# under the effect size; anything looser silently caps the precision of every conclusion# drawn from it.CONSENSUS_TOL = float(os.environ.get("CONSENSUS_TOL", 0.005))def _userset(name: str) -> set:return {u.strip().lower()for u in os.environ.get(name, "").replace(",", " ").split() if u.strip()}ADJUDICATORS = _userset("ADJUDICATORS")# Who may read films. Empty = anyone signed in, which is right for an open pilot and# wrong here: the films are BUU-LSPINE, redistribution is not ours to grant, and the# alternative (a private Space) 404s for every reader until each one is added as a# collaborator -- including the owner, because the .hf.space subdomain does not share a# huggingface.co login cookie. A public Space plus this list gives the readers a URL# that simply works while keeping the films to named people.READERS = _userset("READERS")app = FastAPI(title="Femoral head annotation")_WHOAMI: dict = {}# "local:/path" runs the whole Space off the filesystem: real ledger, real images, real# HTTP, no HuggingFace. That is what the test suite drives, and it is the only way to# exercise sign-in, claiming and the not-visible path without minting tokens and writing# to a live repo. On the Space ANNOT_REPO is an org/name repo id, so DEV_LOCAL is False.DEV_LOCAL = ANNOT_REPO.startswith("local:")def _store():if DEV_LOCAL:return store_mod.ReviewStore(store_mod.LocalBackend(ANNOT_REPO[6:]))if not ANNOT_REPO or not os.environ.get("HF_TOKEN"):raise HTTPException(500, "ANNOT_REPO and HF_TOKEN must be set")return store_mod.ReviewStore(store_mod.HFBackend(ANNOT_REPO, os.environ["HF_TOKEN"]))# ── in-memory ledger ────────────────────────────────────────────────────────────# store.list_cases() reads EVERY case json out of the dataset repo. At 2000 cases that# is 2000 file reads to answer one "give me the next film", on both /next and /peek --# tens of seconds per click, which is not a slow tool, it is an unusable one.## So the ledger is loaded once and held in memory, and writes go through a batched# background flush. Two consequences worth being explicit about:## * a submit returns as soon as memory is updated, so the annotator never waits on a# git commit to see the next film. Durability lags by at most FLUSH_SECONDS.# * dirty cases are batched into ONE commit. Per-case commits would mean ~4000 commits# for a double-read pass over 2000 films, which is slow and abuses the repo.## A Space runs a single replica, so memory is authoritative while it is up; on restart# the index is rebuilt from the repo. Nothing is stored only in RAM for longer than the# flush interval.import threading # noqa: E402FLUSH_SECONDS = float(os.environ.get("FLUSH_SECONDS", 3.0))_LOCK = threading.RLock()_INDEX: dict = {}_ORDER: list = []_DIRTY: set = set()_READY = threading.Event()_LOAD_ERR: list = []# index.json is a single consolidated copy of every case, written by the flusher. It# exists purely for boot time: fetching 2000 individual case files takes 25 s even at 16# workers, and /next blocks on it, so every Space restart looked broken for half a# minute. One file takes about a second.## The per-case files remain the source of truth -- they are what the seeder writes and# what any later analysis reads. index.json is a cache, and it is USED ONLY IF it still# covers exactly the case set manifest.json lists. A stale index would silently hide# films from the queue, so a mismatch falls back to the slow path rather than trusting it.INDEX_FILE = "index.json"INDEX_EVERY = float(os.environ.get("INDEX_EVERY", 120))_LAST_INDEX = [0.0]def _hf_json(path: str):from huggingface_hub import hf_hub_downloadfp = hf_hub_download(ANNOT_REPO, path, repo_type="dataset",token=os.environ.get("HF_TOKEN"))with open(fp, "rb") as fh:return json.loads(fh.read())def _load_from_index():try:want = set(_hf_json("manifest.json").get("cases") or [])cases = _hf_json(INDEX_FILE)if want and {c["case_id"] for c in cases} == want:return casesexcept Exception: # noqa: BLE001passreturn Nonedef _load_from_snapshot():from huggingface_hub import snapshot_downloadroot = snapshot_download(ANNOT_REPO, repo_type="dataset",allow_patterns="cases/*.json", max_workers=16,token=os.environ.get("HF_TOKEN"))cdir = os.path.join(root, "cases")cases = []for fn in os.listdir(cdir):if fn.endswith(".json"):with open(os.path.join(cdir, fn), "rb") as fh:cases.append(json.loads(fh.read()))return casesdef _write_index() -> None:"""Refresh the boot cache. Rate-limited: it is a couple of MB and boot time is theonly thing it buys, so it does not belong in every 3-second flush."""if DEV_LOCAL or time.time() - _LAST_INDEX[0] < INDEX_EVERY:returnwith _LOCK:blob = json.dumps(list(_INDEX.values())).encode()try:from huggingface_hub import HfApiHfApi(token=os.environ.get("HF_TOKEN")).upload_file(path_or_fileobj=blob, path_in_repo=INDEX_FILE, repo_id=ANNOT_REPO,repo_type="dataset", commit_message="refresh boot index")_LAST_INDEX[0] = time.time()except Exception: # noqa: BLE001passdef _load_index() -> None:"""Load the whole ledger once, in ONE repo fetch.store.list_cases() reads each case file over HTTP. At 2000 cases that is 2000round trips before the first reader can be handed anything -- and /next blocks onit, so every Space restart looked like the tool was broken for minutes. A snapshotof cases/ is one download, then the parsing is local disk."""try:if DEV_LOCAL:cases = _store().list_cases()else:cases = _load_from_index() or _load_from_snapshot()except Exception as exc: # noqa: BLE001_LOAD_ERR.append(f"{type(exc).__name__}: {exc}")_READY.set()returnwith _LOCK:_INDEX.clear()for c in cases:_INDEX[c["case_id"]] = c_ORDER[:] = sorted(_INDEX)_READY.set()threading.Thread(target=_prewarm, daemon=True).start()# ── image pre-warm ──────────────────────────────────────────────────────────────# The browser prefetches the NEXT film while you work on the current one, which hides# the download -- but only from the second film onward, and only if you pause long# enough. Rendering a few ahead server-side means the queue is already warm when the# reader arrives, including for the first film after a restart.PREWARM = int(os.environ.get("PREWARM", 12))def _prewarm() -> None:done = 0for cid in list(_ORDER):if done >= PREWARM:returnc = _INDEX.get(cid)if not c or c.get("final") or cid in _IMG_CACHE:continuetry:_render_jpeg(cid)done += 1except Exception: # noqa: BLE001continuedef _flush_once() -> int:with _LOCK:ids = list(_DIRTY)_DIRTY.clear()batch = [_INDEX[i] for i in ids if i in _INDEX]if not batch:return 0try:_store().put_cases(batch)except Exception: # noqa: BLE001with _LOCK: # put them back; try again next tick_DIRTY.update(ids)return 0_write_index()return len(batch)def _flusher() -> None:while True:time.sleep(FLUSH_SECONDS)try:_flush_once()except Exception: # noqa: BLE001pass@app.on_event("startup")def _boot() -> None:threading.Thread(target=_load_index, daemon=True).start()threading.Thread(target=_flusher, daemon=True).start()def _wait_ready() -> None:if not _READY.wait(timeout=120):raise HTTPException(503, "ledger still loading, try again in a moment")if _LOAD_ERR:raise HTTPException(500, f"ledger failed to load: {_LOAD_ERR[0]}")def _touch(case: dict) -> None:with _LOCK:_INDEX[case["case_id"]] = case_DIRTY.add(case["case_id"])def _hf_username(token: str) -> Optional[str]:"""Verified HF username, cached by sha256(token). The token itself is never stored."""if not token:return Nonek = hashlib.sha256(token.encode()).hexdigest()hit = _WHOAMI.get(k)if hit and time.time() - hit[1] < 900:return hit[0]try:from huggingface_hub import HfApiname = HfApi().whoami(token=token).get("name")except Exception: # noqa: BLE001return Noneif name:_WHOAMI[k] = (name, time.time())return name# ── sign in with HuggingFace ────────────────────────────────────────────────────# Set `hf_oauth: true` in the Space README and HF injects OAUTH_CLIENT_ID/SECRET. Then# signing in is one button, which matters: the readers are radiologists and medical# students, and "create a token, choose the right scopes, paste the string" is a step# where a good fraction of them simply stop.## The user's access token is used ONCE, to read their username, and is then discarded --# nothing here needs to act on their behalf. The session cookie carries the verified# username and an expiry, signed with the client secret. Pasting a token still works, so# the tool runs locally and in tests with no OAuth app at all.OAUTH_ID = os.environ.get("OAUTH_CLIENT_ID", "")OAUTH_SECRET = os.environ.get("OAUTH_CLIENT_SECRET", "")SPACE_HOST = os.environ.get("SPACE_HOST", "")OAUTH_ENABLED = bool(OAUTH_ID and OAUTH_SECRET)SESSION_DAYS = 30_SECRET = (OAUTH_SECRET or os.environ.get("HF_TOKEN", "") or "dev").encode()def _sign(payload: str) -> str:import hmacmac = hmac.new(_SECRET, payload.encode(), hashlib.sha256).hexdigest()[:32]return f"{payload}.{mac}"def _unsign(cookie: str) -> Optional[str]:import hmacif not cookie or "." not in cookie:return Nonepayload, _, mac = cookie.rpartition(".")good = hmac.new(_SECRET, payload.encode(), hashlib.sha256).hexdigest()[:32]if not hmac.compare_digest(mac, good):return Nonename, _, exp = payload.partition("|")try:if float(exp) < time.time():return Noneexcept ValueError:return Nonereturn name or Nonedef _redirect_uri() -> str:host = SPACE_HOST or "localhost:7860"scheme = "https" if SPACE_HOST else "http"return f"{scheme}://{host}/auth/callback"@app.get("/auth/login")def auth_login():from fastapi.responses import RedirectResponseif not OAUTH_ENABLED:raise HTTPException(503, "OAuth is not configured on this Space; paste a token")state = _sign(f"s|{time.time() + 600}")url = ("https://huggingface.co/oauth/authorize"f"?client_id={OAUTH_ID}&redirect_uri={_redirect_uri()}"f"&response_type=code&scope=openid%20profile&state={state}&prompt=consent")r = RedirectResponse(url, status_code=302)r.set_cookie("oauth_state", state, max_age=600, httponly=True, samesite="lax",secure=bool(SPACE_HOST))return r@app.get("/auth/callback")def auth_callback(code: str = "", state: str = "", error: str = ""):from fastapi.responses import RedirectResponseimport requestsif error:raise HTTPException(400, f"HuggingFace returned: {error}")if not code or not _unsign(state):raise HTTPException(400, "bad or expired sign-in state — start again from /")tok = requests.post("https://huggingface.co/oauth/token",data={"client_id": OAUTH_ID, "client_secret": OAUTH_SECRET,"grant_type": "authorization_code", "code": code,"redirect_uri": _redirect_uri()}, timeout=20)if not tok.ok:raise HTTPException(400, f"token exchange failed: {tok.text[:200]}")access = tok.json().get("access_token", "")info = requests.get("https://huggingface.co/oauth/userinfo",headers={"Authorization": f"Bearer {access}"}, timeout=20)name = (info.json() or {}).get("preferred_username") if info.ok else Noneif not name:raise HTTPException(400, "could not read your HuggingFace username")r = RedirectResponse("/", status_code=302)r.set_cookie("annot_session",_sign(f"{name}|{time.time() + SESSION_DAYS * 86400}"),max_age=SESSION_DAYS * 86400, httponly=True, samesite="lax",secure=bool(SPACE_HOST))r.delete_cookie("oauth_state")return r@app.get("/auth/logout")def auth_logout():from fastapi.responses import RedirectResponser = RedirectResponse("/", status_code=302)r.delete_cookie("annot_session")return rdef user(authorization: str = Header(default=""),x_annot_token: str = Header(default=""),annot_session: str = Cookie(default="")) -> dict:"""Identity, in order of preference: the signed session cookie (OAuth), then apasted token.The pasted token is read from X-Annot-Token, NOT just Authorization. On a PRIVATESpace the Hub's own proxy consumes the Authorization header to decide whether thecaller may reach the Space at all, so it never arrives here -- the token fallbacklooked broken while being eaten one layer up. Authorization is still accepted forlocal runs and tests, where nothing is in front of the app."""raw = x_annot_token.strip() or (authorization[7:] if authorization.lower().startswith("bearer ") else "")name = _unsign(annot_session)if not name and DEV_LOCAL:# dev only: whoami would need a real token and a network round trip. Reads the# SAME header the browser sends -- checking only Authorization here meant the# local UI 401'd the moment the frontend moved to X-Annot-Token.name = raw or Noneif not name:name = _hf_username(raw)if not name:raise HTTPException(401, "sign in with HuggingFace")low = name.lower()if READERS and low not in READERS and low not in ADJUDICATORS:raise HTTPException(403, f"{name} is not on the reader list for this study. Ask Greg to add "f"your HuggingFace username.")return {"id": name, "role": "adjudicator" if low in ADJUDICATORS else "primary"}@app.get("/whoami")def whoami_route(annot_session: str = Cookie(default="")):return {"user": _unsign(annot_session), "oauth": OAUTH_ENABLED}def _now() -> float:return time.time()def _claimable_slot(case: dict, who: str) -> Optional[str]:"""Which primary slot this annotator may take, or None.Same rule as the review service: a person cannot hold two slots on one case (thatwould make "double annotation" one person twice), and an expired unsubmitted claim isreclaimable so an abandoned case does not sit forever."""slots = case.setdefault("slots", {})if any(s.get("annotator") == who for s in slots.values()):return Nonefor k in ("1", "2"):s = slots.get(k)if s is None:return kif not s.get("done") and s.get("expires_at", 0) < _now():return kreturn None@app.get("/example")def example():"""A worked example, served from a bundled PNG.Built from a DRR, NOT from a real film, and that is the point: on a DRR the hip pointis a 3-D sphere fitted to the femoral head and projected, so the example shows anobjectively correct answer rather than one annotator's opinion. Using a marked-up realradiograph would put whoever marked it into every reader's head.It is a fixed teaching image and never one of the films being annotated, so it cannotanchor a specific case the way an on-image proposal would."""here = os.path.dirname(os.path.abspath(__file__))for name in ("example_femhead.png", "static/example_femhead.png"):fp = os.path.join(here, name)if os.path.exists(fp):return Response(open(fp, "rb").read(), media_type="image/png",headers={"Cache-Control": "public, max-age=86400"})raise HTTPException(404, "example image not bundled")@app.get("/reference")def reference():"""The 'where is it / what am I marking' figure, built by make_reference.py.Same reasoning as /example: it is drawn on a DRR, so the crosshair is ostk's ownsphere fit projected, not a person's opinion, and it is a fixed teaching image ratherthan any film in the queue."""return _png("reference_femhead.png")@app.get("/reference/{panel}")def reference_panel(panel: str):"""One panel of the teaching figure. The composite is 1648 px wide and illegible ina sidebar; the panels are served separately so they can be stacked at column width."""if panel not in ("a", "b", "c"):raise HTTPException(404, "no such panel")return _png(f"ref_{panel}.png")def _png(name: str):here = os.path.dirname(os.path.abspath(__file__))fp = os.path.join(here, name)if os.path.exists(fp):return Response(open(fp, "rb").read(), media_type="image/png",headers={"Cache-Control": "public, max-age=86400"})raise HTTPException(404, f"{name} not bundled")@app.get("/", response_class=HTMLResponse)def index():return PAGE@app.get("/next")def next_case(u: dict = Depends(user)):_wait_ready()with _LOCK:for cid in _ORDER:case = _INDEX.get(cid)if not case or case.get("final"):continueslot = _claimable_slot(case, u["id"])if slot is None:continuecase["slots"][slot] = {"annotator": u["id"], "claimed_at": _now(),"expires_at": _now() + CLAIM_TTL, "done": False}_touch(case)return {"case_id": case["case_id"], "slot": slot,"image_url": f"/image/{case['case_id']}","progress": _progress()}return JSONResponse({"detail": "nothing left to annotate"}, status_code=404)# Display width. A BUU film is ~2000x2400 and several MB; sending that raw makes every# "next film" a multi-second wait, which is the difference between annotating 120 films in# an afternoon and giving up. At 1100 px one displayed pixel is under 2 source pixels,# and the consensus tolerance is 0.005 of width (~10 source px), so the downscale costs# nothing that matters. Coordinates are normalised anyway, so precision is set by the# MAGNIFIER, not by the transport size.DISPLAY_W = int(os.environ.get("DISPLAY_W", 1100))_IMG_CACHE: dict = {}def _render_jpeg(case_id: str) -> bytes:if case_id in _IMG_CACHE:return _IMG_CACHE[case_id]from PIL import Imageif DEV_LOCAL:p = os.path.join(IMAGE_REPO[6:], f"{case_id}.jpg")if not os.path.exists(p):raise HTTPException(404, f"image not found: {p}")return _encode(Image.open(p).convert("L"), case_id)from huggingface_hub import hf_hub_downloadtry:p = hf_hub_download(IMAGE_REPO, f"images/{case_id}.jpg", repo_type="dataset",token=os.environ.get("HF_TOKEN"))except Exception as exc: # noqa: BLE001raise HTTPException(404, f"image not found: {exc}")return _encode(Image.open(p).convert("L"), case_id)def _encode(im, case_id: str) -> bytes:"""Downscale + JPEG. case_id is REQUIRED: it is the cache key, and defaulting it to"" cached every film under the same entry and served the first one forever."""from io import BytesIOfrom PIL import Imageif im.width > DISPLAY_W:im = im.resize((DISPLAY_W, round(im.height * DISPLAY_W / im.width)),Image.LANCZOS)buf = BytesIO()im.save(buf, format="JPEG", quality=88, optimize=True)data = buf.getvalue()if case_id and len(_IMG_CACHE) < 400: # bounded: a Space has finite memory_IMG_CACHE[case_id] = datareturn data@app.get("/image/{case_id}")def image(case_id: str, u: dict = Depends(user)):"""Stream the film THROUGH the Space so annotators never need read access to theimage repo, exactly as the review service streams labels."""return Response(_render_jpeg(case_id), media_type="image/jpeg",headers={"Cache-Control": "private, max-age=3600"})@app.get("/peek")def peek(u: dict = Depends(user)):"""The next case id WITHOUT claiming it, so the browser can prefetch its image.Claiming on prefetch would hand every annotator a second case the moment they openedone, and abandoned claims would pile up behind the TTL."""_wait_ready()with _LOCK:for cid in _ORDER:case = _INDEX.get(cid)if not case or case.get("final"):continue# The case being annotated right now already holds a slot belonging to this# user, and _claimable_slot refuses a second slot to the same person -- so# the first hit here is genuinely the NEXT film, not the current one.if _claimable_slot(case, u["id"]) is not None:return {"case_id": case["case_id"]}return JSONResponse({"detail": "none"}, status_code=404)@app.post("/submit")def submit(case_id: str = Form(...), slot: str = Form(...), points: str = Form(""),not_visible: str = Form(""), reason: str = Form(""),u: dict = Depends(user)):"""points: JSON {"left":[x,y]|null, "right":[x,y]|null, "note":str, "w":W, "h":H}Coordinates arrive NORMALISED to the displayed image and are stored that way. Thebrowser scales the film to fit a screen of unknown size, so raw canvas pixels wouldsilently encode each annotator's window size.NOT VISIBLE IS AN ANSWER, NOT AN ABANDONMENT. It fills the reader's slot and needsthe same double read as a marked film. This matters because the open question theseannotations exist to settle is precisely "on what fraction of films can a trained eyeplace this point at all" -- so an unreadable film is a DATUM. Releasing the slotinstead (which is what /skip does) would drop that film back in the pool and quietlydelete the very observation being collected."""_wait_ready()with _LOCK:case = _INDEX.get(case_id)if case is None:raise HTTPException(404, "unknown case")s = case.get("slots", {}).get(slot)if not s or s.get("annotator") != u["id"]:raise HTTPException(403, "that slot is not yours")nv = str(not_visible).lower() in ("1", "true", "yes", "on")p = json.loads(points) if points else {}if not nv and not heads(p):raise HTTPException(400, "mark at least one femoral head, or use Not visible")if nv:s.update(done=True, submitted_at=_now(), points=None,not_visible=True, reason=reason)else:s.update(done=True, submitted_at=_now(), points=p, not_visible=False)done = [case["slots"][k] for k in ("1", "2")if case.get("slots", {}).get(k, {}).get("done")]if len(done) >= N_PRIMARY:_resolve(case, done)_touch(case)status = ("final" if case.get("final")else "needs adjudication" if case.get("disagree")else "awaiting second read")return {"ok": True, "status": status, "progress": _progress()}def _resolve(case: dict, done: list) -> None:"""Decide a case once both reads are in.Three outcomes, kept distinct because they mean different things downstream:both readable and close -> final, point = mean of the twoboth not visible -> final with NO point. A settled, usable observation:this film has no placeable hip landmark.anything else -> disagreement, held for adjudication. That includes onereader marking a point the other could not see, whichis the most interesting disagreement in the set andmust not be silently resolved either way."""nv = [bool(s.get("not_visible")) for s in done]case.pop("disagree", None)if all(nv):case["final"] = {"points": None, "by": "consensus-not-visible"}case["agree"] = Nonereturnif any(nv):case["disagree"] = "one reader marked a point the other could not see"case["agree"] = Nonereturncase["agree"] = _agreement(done[0]["points"], done[1]["points"])if case["agree"] is not None and case["agree"] <= CONSENSUS_TOL:case["final"] = {"points": _mean_points(done[0]["points"], done[1]["points"]),"by": "consensus"}else:case["disagree"] = f"readers differ by {case['agree']:.4f} of image width"@app.post("/skip")def skip(case_id: str = Form(...), slot: str = Form(...), reason: str = Form(""),u: dict = Depends(user)):"""Put a film BACK for someone else -- "not now", not "not visible".Use this for an interruption or a film you would rather another reader took. Itreleases the slot and the case returns to the pool. If the femoral heads genuinelycannot be seen, that is an ANSWER and belongs in /submit with not_visible=1, where itcounts toward the double read."""_wait_ready()with _LOCK:case = _INDEX.get(case_id)if case is None:raise HTTPException(404, "unknown case")case.setdefault("passed_by", []).append({"by": u["id"], "reason": reason,"at": _now()})case.get("slots", {}).pop(slot, None)_touch(case)return {"ok": True}def _progress() -> dict:"""Cheap counters for the header. Runs over memory, so it is free to call per film."""with _LOCK:total = len(_INDEX)reads = final = 0for c in _INDEX.values():reads += sum(1 for k in ("1", "2")if c.get("slots", {}).get(k, {}).get("done"))final += bool(c.get("final"))return {"total": total, "reads": reads, "reads_needed": total * N_PRIMARY,"final": final}@app.get("/stats")def stats(u: dict = Depends(user)):"""Who has done what, and how much is left.Deliberately visible to every annotator, not just adjudicators: people finish a longrepetitive job far more reliably when they can see the pile going down and see thatothers are carrying their share."""_wait_ready()import statisticswith _LOCK:cases = list(_INDEX.values())by: dict = {}agrees, nv_cases = [], 0counts = {"total": len(cases), "untouched": 0, "one_read": 0, "two_reads": 0,"final": 0, "final_consensus": 0, "final_not_visible": 0,"needs_adjudication": 0, "in_progress": 0}for c in cases:slots = c.get("slots", {})done = [slots.get(k) for k in ("1", "2") if slots.get(k, {}).get("done")]claimed = [slots.get(k) for k in ("1", "2")if slots.get(k) and not slots[k].get("done")]for s in done:r = by.setdefault(s["annotator"], {"reads": 0, "not_visible": 0})r["reads"] += 1r["not_visible"] += bool(s.get("not_visible"))n = len(done)counts["untouched"] += (n == 0 and not claimed)counts["in_progress"] += bool(claimed)counts["one_read"] += (n == 1)counts["two_reads"] += (n >= 2)if c.get("final"):counts["final"] += 1if c["final"].get("by") == "consensus-not-visible":counts["final_not_visible"] += 1nv_cases += 1else:counts["final_consensus"] += 1counts["needs_adjudication"] += bool(c.get("disagree"))if c.get("agree") is not None:agrees.append(c["agree"])counts["reads_done"] = sum(r["reads"] for r in by.values())counts["reads_needed"] = counts["total"] * N_PRIMARYcounts["pct_complete"] = round(100 * counts["final"] / max(1, counts["total"]), 1)# The headline number this whole exercise exists to produce.settled = counts["final"] + counts["needs_adjudication"]counts["not_visible_rate_pct"] = (round(100 * nv_cases / settled, 1)if settled else None)agree_stats = Noneif agrees:agree_stats = {"n": len(agrees),"median": round(statistics.median(agrees), 5),"p90": round(sorted(agrees)[int(0.9 * (len(agrees) - 1))], 5),"within_tol_pct": round(100 * sum(a <= CONSENSUS_TOL for a in agrees)/ len(agrees), 1),"tolerance": CONSENSUS_TOL,}readers = sorted(({"annotator": k, **v} for k, v in by.items()),key=lambda r: -r["reads"])return {"counts": counts, "readers": readers, "agreement": agree_stats,"you": u["id"], "pending_writes": len(_DIRTY)}# ── flag + adjudicate ───────────────────────────────────────────────────────────# A reader sees exactly one film at a time, streamed through the Space, with no browse,# no re-open and no export. That is deliberate -- they never need access to the image# repo -- but it also means a reader who is unsure about a film has no way to raise it,# and an adjudicator has no way to look at what two readers actually did. Telling people# to "send me the ones you are unsure about" asked for something the tool cannot do.@app.post("/flag")def flag(case_id: str = Form(...), note: str = Form(""), u: dict = Depends(user)):"""Raise the CURRENT film for discussion without abandoning the read."""_wait_ready()with _LOCK:case = _INDEX.get(case_id)if case is None:raise HTTPException(404, "unknown case")case.setdefault("flagged", []).append({"by": u["id"], "note": note[:400], "at": _now()})_touch(case)return {"ok": True}def _adjudicator(u: dict = Depends(user)) -> dict:if u["role"] != "adjudicator":raise HTTPException(403, "adjudication is limited to the study leads")return u@app.get("/queue")def queue(u: dict = Depends(_adjudicator)):"""Everything a human needs to look at: disagreements first, then flagged films."""_wait_ready()with _LOCK:out = []for cid in _ORDER:c = _INDEX.get(cid) or {}if not c.get("disagree") and not c.get("flagged"):continueout.append({"case_id": cid,"why": c.get("disagree") or "flagged by a reader","flagged": c.get("flagged") or [],"agree": c.get("agree"),"settled": bool(c.get("final")),"reads": [{"annotator": s.get("annotator"),"not_visible": bool(s.get("not_visible")),"reason": s.get("reason", ""),"heads": heads(s.get("points"))}for k in ("1", "2")for s in [c.get("slots", {}).get(k)]if s and s.get("done")],})return {"n": len(out), "cases": out}@app.post("/adjudicate")def adjudicate(case_id: str = Form(...), points: str = Form(""),not_visible: str = Form(""), note: str = Form(""),u: dict = Depends(_adjudicator)):"""Settle a case. The adjudicator's own marks win outright -- this is the point atwhich a human has looked at the film and both reads, which no averaging cansubstitute for."""_wait_ready()with _LOCK:case = _INDEX.get(case_id)if case is None:raise HTTPException(404, "unknown case")nv = str(not_visible).lower() in ("1", "true", "yes", "on")p = json.loads(points) if points else {}if not nv and not heads(p):raise HTTPException(400, "mark a centre, or settle it as not visible")hs = heads(p)case["final"] = {"points": None if nv else {"heads": hs,"bicoxofemoral": [sum(h[0] for h in hs) / len(hs),sum(h[1] for h in hs) / len(hs)],},"by": "adjudicated", "adjudicator": u["id"], "note": note[:400],"not_visible": nv,}case.pop("disagree", None)_touch(case)return {"ok": True, "progress": _progress()}@app.get("/review", response_class=HTMLResponse)def review():return REVIEW@app.get("/board", response_class=HTMLResponse)def board():return BOARDdef heads(p: Optional[dict]) -> list:"""The marked femoral-head centres, as an UNORDERED list.A lateral radiograph cannot tell you which head is left and which is right: the twoare superimposed along the beam, and nothing in the image distinguishes them. Askinga reader to label them L and R asked for something unknowable, and comparing readerA's "left" against reader B's "left" would then score a coin flip as disagreement.It also does not matter. The bicoxofemoral point is the MIDPOINT of the two centres,which is identical either way round.Reads both shapes: {"heads":[[x,y],...]} and the older {"left":.., "right":..}."""if not p:return []if isinstance(p.get("heads"), list):# radii travel in p["radii"] alongside; they are a per-film scale reference# (an adult head is ~44-50 mm across) and a disagreement in radius between two# readers flags an arc that was ambiguous rather than a centre that was wrong.return [q for q in p["heads"] if q]return [q for q in (p.get("left"), p.get("right")) if q]def _agreement(a: dict, b: dict) -> Optional[float]:"""Worst distance between two readers, over the BEST pairing of their marks.Order-free: with two marks each, both pairings are tried and the better one wins.With unequal counts -- one reader saw two heads, the other one -- only the marksthat can be paired are scored, and the extra mark is left to adjudication ratherthan counted as an error, because "how many circles are there" is a differentdisagreement from "where is the centre"."""import mathA, B = heads(a), heads(b)if not A or not B:return Noned = lambda u, v: math.hypot(u[0] - v[0], u[1] - v[1]) # noqa: E731if len(A) == 2 and len(B) == 2:return min(max(d(A[0], B[0]), d(A[1], B[1])),max(d(A[0], B[1]), d(A[1], B[0])))return min(d(u, v) for u in A for v in B)def _mean_points(a: dict, b: dict) -> dict:"""Consensus marks, paired the same order-free way, plus the derived midpoint --which is the quantity PI actually needs."""import mathA, B = heads(a), heads(b)d = lambda u, v: math.hypot(u[0] - v[0], u[1] - v[1]) # noqa: E731mid = lambda u, v: [(u[0] + v[0]) / 2, (u[1] + v[1]) / 2] # noqa: E731if len(A) == 2 and len(B) == 2:if (max(d(A[0], B[1]), d(A[1], B[0]))< max(d(A[0], B[0]), d(A[1], B[1]))):B = [B[1], B[0]]hs = [mid(A[0], B[0]), mid(A[1], B[1])]else:pair = min(((u, v) for u in A for v in B), key=lambda t: d(*t))hs = [mid(*pair)]bicox = ([sum(h[0] for h in hs) / len(hs), sum(h[1] for h in hs) / len(hs)]if hs else None)out = {"heads": hs, "bicoxofemoral": bicox}if len(hs) == 2:out["separation"] = d(hs[0], hs[1]) # a wide one means an oblique filmreturn outfrom ui import BOARD, PAGE, REVIEW # noqa: E402 (markup lives next door)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013"""Femoral-head annotation Space — two clicks per lateral radiograph, distributed.Mirrors the CTSpinoPelvic1K review service deliberately: HuggingFace token as identity,a dataset repo as the ledger, claim slots with a TTL, and double annotation withadjudication on disagreement. Same shape, so the same people already know how to use it.HF_TOKEN write token for the ledger dataset (Space secret)ANNOT_REPO dataset repo holding cases/ and annotations/IMAGE_REPO dataset repo holding the films (read-only)ADJUDICATORS comma/space-separated HF usernames allowed to adjudicateWHY THIS AND NOT ITK-SNAP-------------------------ITK-SNAP is a 3-D volume tool. Annotating two points on a 2-D radiograph through it meansconverting every film to a single-slice volume, installing software, and training peopleon a segmentation UI to place two dots. A browser canvas is two clicks and no install,and the Space is already how this group works.NO AUTOMATIC PROPOSAL IS EVER SHOWN. The whole purpose of these annotations is anINDEPENDENT reference for a hip point predicted from synthetic data. Displaying themodel's guess -- or the classical circle fit -- as a starting position would anchor theannotator to it, and agreement would then measure suggestibility rather than anatomy.This is the single most important design decision in the tool, and it is why the filecontains no call to any predictor.WHAT IS COLLECTED, AND WHY BOTH HEADS-------------------------------------Left and right femoral head centres separately, not the midpoint. On a true lateral thetwo heads superimpose, but rotation separates them -- and the bicoxofemoral point isDEFINED as the midpoint of the two centres (Legaye & Duval-Beaupere 1998). Collectingboth lets the midpoint be derived, lets their separation flag an oblique film, and lets areader mark only one when the other is genuinely invisible.CRITERIA � shown in the app and repeated here so the definition lives with the code.ANATOMICAL DEFINITIONThe bicoxofemoral (hip) axis is the line joining the CENTRES of the two femoral heads.The point used for PI, PT and SS is the MIDPOINT of that line (Legaye & Duval-Beaupere,Eur Spine J 1998). It is a geometric centre, not a surface point and not a palpablelandmark: the femoral head is very nearly a sphere, so its projection on any radiographis a circle and the point wanted is the centre of that circle.HOW TO FIND IT ON A LATERAL FILM1. Identify the femoral head: the round dense structure below and anterior to the S1endplate, seated in the acetabulum.2. Trace the SUBCHONDRAL CORTICAL MARGIN -- the thin dense arc of the articular surface.That arc is the circle to centre on. This is the Mose concentric-circle method doneby eye.3. Place the point at the centre of curvature of that arc, NOT at the densest part ofthe shadow. Overlap with the acetabulum and the opposite head makes the brightestregion sit medial to the true centre.WHAT NOT TO USE* the fovea capitis -- the medial notch where ligamentum teres attaches. It is a defectin the sphere; centring on it pulls the point medially.* the greater trochanter, the femoral neck, or the head-neck junction. None of them ispart of the sphere.* the acetabular roof or teardrop. They belong to the pelvis, not the head.ONE HEAD OR TWOOn a well-positioned lateral the two heads superimpose almost exactly and you will seeone circle -- mark it as LEFT and leave RIGHT empty. Rotation separates them into twooverlapping circles; then mark both, and their midpoint is derived automatically. Theirseparation is itself recorded, because a wide separation means an oblique film and thespinopelvic parameters from it are less trustworthy.WHEN TO SKIPProsthesis, both heads outside the collimated field, or a film so underexposed that thecortical arc cannot be traced. Skipping is a valid answer. A guessed centre becomes afabricated error in whatever this set is used to measure."""from __future__ import annotationsimport hashlibimport jsonimport osimport timefrom typing import Optionalfrom fastapi import Cookie, Depends, FastAPI, Form, Header, HTTPExceptionfrom fastapi.responses import HTMLResponse, JSONResponse, Responseimport store as store_mod # noqa: E402 (sibling, as in review_service)ANNOT_REPO = os.environ.get("ANNOT_REPO", "")IMAGE_REPO = os.environ.get("IMAGE_REPO", "")CLAIM_TTL = int(os.environ.get("CLAIM_TTL_SECONDS", 3 * 24 * 3600))N_PRIMARY = 2# Consensus tolerance, as a fraction of image width. Judged in NORMALISED units so it# means the same thing on every film regardless of pixel size.## 0.005, not the 0.02 this started at, and the difference matters. On a typical BUU film# (2012 px across roughly 400 mm, so ~5 px/mm) with the S1 midpoint about 125 mm from the# hip axis, a hip displacement of d mm moves PI and PT by atan(d/125):## 0.02 -> 40 px -> 8.0 mm -> up to 3.7 deg of PI error# 0.01 -> 20 px -> 4.0 mm -> up to 1.8 deg# 0.005 -> 10 px -> 2.0 mm -> up to 0.9 deg## The model being validated has an SS MAE of 2.3 deg. A reference whose own two readers# may disagree by 3.7 deg cannot measure a 2.3 deg error -- the ruler would be coarser# than the thing it is measuring. 0.005 keeps the reference's internal disagreement well# under the effect size; anything looser silently caps the precision of every conclusion# drawn from it.CONSENSUS_TOL = float(os.environ.get("CONSENSUS_TOL", 0.005))def _userset(name: str) -> set:return {u.strip().lower()for u in os.environ.get(name, "").replace(",", " ").split() if u.strip()}ADJUDICATORS = _userset("ADJUDICATORS")# Who may read films. Empty = anyone signed in, which is right for an open pilot and# wrong here: the films are BUU-LSPINE, redistribution is not ours to grant, and the# alternative (a private Space) 404s for every reader until each one is added as a# collaborator -- including the owner, because the .hf.space subdomain does not share a# huggingface.co login cookie. A public Space plus this list gives the readers a URL# that simply works while keeping the films to named people.READERS = _userset("READERS")app = FastAPI(title="Femoral head annotation")_WHOAMI: dict = {}# "local:/path" runs the whole Space off the filesystem: real ledger, real images, real# HTTP, no HuggingFace. That is what the test suite drives, and it is the only way to# exercise sign-in, claiming and the not-visible path without minting tokens and writing# to a live repo. On the Space ANNOT_REPO is an org/name repo id, so DEV_LOCAL is False.DEV_LOCAL = ANNOT_REPO.startswith("local:")def _store():if DEV_LOCAL:return store_mod.ReviewStore(store_mod.LocalBackend(ANNOT_REPO[6:]))if not ANNOT_REPO or not os.environ.get("HF_TOKEN"):raise HTTPException(500, "ANNOT_REPO and HF_TOKEN must be set")return store_mod.ReviewStore(store_mod.HFBackend(ANNOT_REPO, os.environ["HF_TOKEN"]))# ── in-memory ledger ────────────────────────────────────────────────────────────# store.list_cases() reads EVERY case json out of the dataset repo. At 2000 cases that# is 2000 file reads to answer one "give me the next film", on both /next and /peek --# tens of seconds per click, which is not a slow tool, it is an unusable one.## So the ledger is loaded once and held in memory, and writes go through a batched# background flush. Two consequences worth being explicit about:## * a submit returns as soon as memory is updated, so the annotator never waits on a# git commit to see the next film. Durability lags by at most FLUSH_SECONDS.# * dirty cases are batched into ONE commit. Per-case commits would mean ~4000 commits# for a double-read pass over 2000 films, which is slow and abuses the repo.## A Space runs a single replica, so memory is authoritative while it is up; on restart# the index is rebuilt from the repo. Nothing is stored only in RAM for longer than the# flush interval.import threading # noqa: E402FLUSH_SECONDS = float(os.environ.get("FLUSH_SECONDS", 3.0))_LOCK = threading.RLock()_INDEX: dict = {}_ORDER: list = []_DIRTY: set = set()_READY = threading.Event()_LOAD_ERR: list = []# index.json is a single consolidated copy of every case, written by the flusher. It# exists purely for boot time: fetching 2000 individual case files takes 25 s even at 16# workers, and /next blocks on it, so every Space restart looked broken for half a# minute. One file takes about a second.## The per-case files remain the source of truth -- they are what the seeder writes and# what any later analysis reads. index.json is a cache, and it is USED ONLY IF it still# covers exactly the case set manifest.json lists. A stale index would silently hide# films from the queue, so a mismatch falls back to the slow path rather than trusting it.INDEX_FILE = "index.json"INDEX_EVERY = float(os.environ.get("INDEX_EVERY", 120))_LAST_INDEX = [0.0]def _hf_json(path: str):from huggingface_hub import hf_hub_downloadfp = hf_hub_download(ANNOT_REPO, path, repo_type="dataset",token=os.environ.get("HF_TOKEN"))with open(fp, "rb") as fh:return json.loads(fh.read())def _load_from_index():try:want = set(_hf_json("manifest.json").get("cases") or [])cases = _hf_json(INDEX_FILE)if want and {c["case_id"] for c in cases} == want:return casesexcept Exception: # noqa: BLE001passreturn Nonedef _load_from_snapshot():from huggingface_hub import snapshot_downloadroot = snapshot_download(ANNOT_REPO, repo_type="dataset",allow_patterns="cases/*.json", max_workers=16,token=os.environ.get("HF_TOKEN"))cdir = os.path.join(root, "cases")cases = []for fn in os.listdir(cdir):if fn.endswith(".json"):with open(os.path.join(cdir, fn), "rb") as fh:cases.append(json.loads(fh.read()))return casesdef _write_index() -> None:"""Refresh the boot cache. Rate-limited: it is a couple of MB and boot time is theonly thing it buys, so it does not belong in every 3-second flush."""if DEV_LOCAL or time.time() - _LAST_INDEX[0] < INDEX_EVERY:returnwith _LOCK:blob = json.dumps(list(_INDEX.values())).encode()try:from huggingface_hub import HfApiHfApi(token=os.environ.get("HF_TOKEN")).upload_file(path_or_fileobj=blob, path_in_repo=INDEX_FILE, repo_id=ANNOT_REPO,repo_type="dataset", commit_message="refresh boot index")_LAST_INDEX[0] = time.time()except Exception: # noqa: BLE001passdef _load_index() -> None:"""Load the whole ledger once, in ONE repo fetch.store.list_cases() reads each case file over HTTP. At 2000 cases that is 2000round trips before the first reader can be handed anything -- and /next blocks onit, so every Space restart looked like the tool was broken for minutes. A snapshotof cases/ is one download, then the parsing is local disk."""try:if DEV_LOCAL:cases = _store().list_cases()else:cases = _load_from_index() or _load_from_snapshot()except Exception as exc: # noqa: BLE001_LOAD_ERR.append(f"{type(exc).__name__}: {exc}")_READY.set()returnwith _LOCK:_INDEX.clear()for c in cases:_INDEX[c["case_id"]] = c_ORDER[:] = sorted(_INDEX)_READY.set()threading.Thread(target=_prewarm, daemon=True).start()# ── image pre-warm ──────────────────────────────────────────────────────────────# The browser prefetches the NEXT film while you work on the current one, which hides# the download -- but only from the second film onward, and only if you pause long# enough. Rendering a few ahead server-side means the queue is already warm when the# reader arrives, including for the first film after a restart.PREWARM = int(os.environ.get("PREWARM", 12))def _prewarm() -> None:done = 0for cid in list(_ORDER):if done >= PREWARM:returnc = _INDEX.get(cid)if not c or c.get("final") or cid in _IMG_CACHE:continuetry:_render_jpeg(cid)done += 1except Exception: # noqa: BLE001continuedef _flush_once() -> int:with _LOCK:ids = list(_DIRTY)_DIRTY.clear()batch = [_INDEX[i] for i in ids if i in _INDEX]if not batch:return 0try:_store().put_cases(batch)except Exception: # noqa: BLE001with _LOCK: # put them back; try again next tick_DIRTY.update(ids)return 0_write_index()return len(batch)def _flusher() -> None:while True:time.sleep(FLUSH_SECONDS)try:_flush_once()except Exception: # noqa: BLE001pass@app.on_event("startup")def _boot() -> None:threading.Thread(target=_load_index, daemon=True).start()threading.Thread(target=_flusher, daemon=True).start()def _wait_ready() -> None:if not _READY.wait(timeout=120):raise HTTPException(503, "ledger still loading, try again in a moment")if _LOAD_ERR:raise HTTPException(500, f"ledger failed to load: {_LOAD_ERR[0]}")def _touch(case: dict) -> None:with _LOCK:_INDEX[case["case_id"]] = case_DIRTY.add(case["case_id"])def _hf_username(token: str) -> Optional[str]:"""Verified HF username, cached by sha256(token). The token itself is never stored."""if not token:return Nonek = hashlib.sha256(token.encode()).hexdigest()hit = _WHOAMI.get(k)if hit and time.time() - hit[1] < 900:return hit[0]try:from huggingface_hub import HfApiname = HfApi().whoami(token=token).get("name")except Exception: # noqa: BLE001return Noneif name:_WHOAMI[k] = (name, time.time())return name# ── sign in with HuggingFace ────────────────────────────────────────────────────# Set `hf_oauth: true` in the Space README and HF injects OAUTH_CLIENT_ID/SECRET. Then# signing in is one button, which matters: the readers are radiologists and medical# students, and "create a token, choose the right scopes, paste the string" is a step# where a good fraction of them simply stop.## The user's access token is used ONCE, to read their username, and is then discarded --# nothing here needs to act on their behalf. The session cookie carries the verified# username and an expiry, signed with the client secret. Pasting a token still works, so# the tool runs locally and in tests with no OAuth app at all.OAUTH_ID = os.environ.get("OAUTH_CLIENT_ID", "")OAUTH_SECRET = os.environ.get("OAUTH_CLIENT_SECRET", "")SPACE_HOST = os.environ.get("SPACE_HOST", "")OAUTH_ENABLED = bool(OAUTH_ID and OAUTH_SECRET)SESSION_DAYS = 30_SECRET = (OAUTH_SECRET or os.environ.get("HF_TOKEN", "") or "dev").encode()def _sign(payload: str) -> str:import hmacmac = hmac.new(_SECRET, payload.encode(), hashlib.sha256).hexdigest()[:32]return f"{payload}.{mac}"def _unsign(cookie: str) -> Optional[str]:import hmacif not cookie or "." not in cookie:return Nonepayload, _, mac = cookie.rpartition(".")good = hmac.new(_SECRET, payload.encode(), hashlib.sha256).hexdigest()[:32]if not hmac.compare_digest(mac, good):return Nonename, _, exp = payload.partition("|")try:if float(exp) < time.time():return Noneexcept ValueError:return Nonereturn name or Nonedef _redirect_uri() -> str:host = SPACE_HOST or "localhost:7860"scheme = "https" if SPACE_HOST else "http"return f"{scheme}://{host}/auth/callback"@app.get("/auth/login")def auth_login():from fastapi.responses import RedirectResponseif not OAUTH_ENABLED:raise HTTPException(503, "OAuth is not configured on this Space; paste a token")state = _sign(f"s|{time.time() + 600}")url = ("https://huggingface.co/oauth/authorize"f"?client_id={OAUTH_ID}&redirect_uri={_redirect_uri()}"f"&response_type=code&scope=openid%20profile&state={state}&prompt=consent")r = RedirectResponse(url, status_code=302)r.set_cookie("oauth_state", state, max_age=600, httponly=True, samesite="lax",secure=bool(SPACE_HOST))return r@app.get("/auth/callback")def auth_callback(code: str = "", state: str = "", error: str = ""):from fastapi.responses import RedirectResponseimport requestsif error:raise HTTPException(400, f"HuggingFace returned: {error}")if not code or not _unsign(state):raise HTTPException(400, "bad or expired sign-in state — start again from /")tok = requests.post("https://huggingface.co/oauth/token",data={"client_id": OAUTH_ID, "client_secret": OAUTH_SECRET,"grant_type": "authorization_code", "code": code,"redirect_uri": _redirect_uri()}, timeout=20)if not tok.ok:raise HTTPException(400, f"token exchange failed: {tok.text[:200]}")access = tok.json().get("access_token", "")info = requests.get("https://huggingface.co/oauth/userinfo",headers={"Authorization": f"Bearer {access}"}, timeout=20)name = (info.json() or {}).get("preferred_username") if info.ok else Noneif not name:raise HTTPException(400, "could not read your HuggingFace username")r = RedirectResponse("/", status_code=302)r.set_cookie("annot_session",_sign(f"{name}|{time.time() + SESSION_DAYS * 86400}"),max_age=SESSION_DAYS * 86400, httponly=True, samesite="lax",secure=bool(SPACE_HOST))r.delete_cookie("oauth_state")return r@app.get("/auth/logout")def auth_logout():from fastapi.responses import RedirectResponser = RedirectResponse("/", status_code=302)r.delete_cookie("annot_session")return rdef user(authorization: str = Header(default=""),x_annot_token: str = Header(default=""),annot_session: str = Cookie(default="")) -> dict:"""Identity, in order of preference: the signed session cookie (OAuth), then apasted token.The pasted token is read from X-Annot-Token, NOT just Authorization. On a PRIVATESpace the Hub's own proxy consumes the Authorization header to decide whether thecaller may reach the Space at all, so it never arrives here -- the token fallbacklooked broken while being eaten one layer up. Authorization is still accepted forlocal runs and tests, where nothing is in front of the app."""raw = x_annot_token.strip() or (authorization[7:] if authorization.lower().startswith("bearer ") else "")name = _unsign(annot_session)if not name and DEV_LOCAL:# dev only: whoami would need a real token and a network round trip. Reads the# SAME header the browser sends -- checking only Authorization here meant the# local UI 401'd the moment the frontend moved to X-Annot-Token.name = raw or Noneif not name:name = _hf_username(raw)if not name:raise HTTPException(401, "sign in with HuggingFace")low = name.lower()if READERS and low not in READERS and low not in ADJUDICATORS:raise HTTPException(403, f"{name} is not on the reader list for this study. Ask Greg to add "f"your HuggingFace username.")return {"id": name, "role": "adjudicator" if low in ADJUDICATORS else "primary"}@app.get("/whoami")def whoami_route(annot_session: str = Cookie(default="")):return {"user": _unsign(annot_session), "oauth": OAUTH_ENABLED}def _now() -> float:return time.time()def _claimable_slot(case: dict, who: str) -> Optional[str]:"""Which primary slot this annotator may take, or None.Same rule as the review service: a person cannot hold two slots on one case (thatwould make "double annotation" one person twice), and an expired unsubmitted claim isreclaimable so an abandoned case does not sit forever."""slots = case.setdefault("slots", {})if any(s.get("annotator") == who for s in slots.values()):return Nonefor k in ("1", "2"):s = slots.get(k)if s is None:return kif not s.get("done") and s.get("expires_at", 0) < _now():return kreturn None@app.get("/example")def example():"""A worked example, served from a bundled PNG.Built from a DRR, NOT from a real film, and that is the point: on a DRR the hip pointis a 3-D sphere fitted to the femoral head and projected, so the example shows anobjectively correct answer rather than one annotator's opinion. Using a marked-up realradiograph would put whoever marked it into every reader's head.It is a fixed teaching image and never one of the films being annotated, so it cannotanchor a specific case the way an on-image proposal would."""here = os.path.dirname(os.path.abspath(__file__))for name in ("example_femhead.png", "static/example_femhead.png"):fp = os.path.join(here, name)if os.path.exists(fp):return Response(open(fp, "rb").read(), media_type="image/png",headers={"Cache-Control": "public, max-age=86400"})raise HTTPException(404, "example image not bundled")@app.get("/reference")def reference():"""The 'where is it / what am I marking' figure, built by make_reference.py.Same reasoning as /example: it is drawn on a DRR, so the crosshair is ostk's ownsphere fit projected, not a person's opinion, and it is a fixed teaching image ratherthan any film in the queue."""return _png("reference_femhead.png")@app.get("/reference/{panel}")def reference_panel(panel: str):"""One panel of the teaching figure. The composite is 1648 px wide and illegible ina sidebar; the panels are served separately so they can be stacked at column width."""if panel not in ("a", "b", "c"):raise HTTPException(404, "no such panel")return _png(f"ref_{panel}.png")def _png(name: str):"""A bundled PNG, cached hard and keyed by its own content.`immutable` is only honest because ui.py appends a content hash to these URLs: thebytes behind a given URL genuinely never change, and a rebuilt panel arrives as aDIFFERENT url. Before that, max-age=86400 meant replacing a teaching panel left everyreader who had already opened the page looking at the old one for a day -- which iswhat happened when the figure was rebuilt for the landmark method, leaving theinstructions and the picture beside them describing different things.The ETag makes an unversioned request (someone who bookmarked /reference/b) revalidatecheaply instead of re-downloading."""here = os.path.dirname(os.path.abspath(__file__))fp = os.path.join(here, name)if os.path.exists(fp):body = open(fp, "rb").read()return Response(body, media_type="image/png",headers={"Cache-Control": "public, max-age=31536000, immutable","ETag": '"%s"' % hashlib.md5(body).hexdigest()[:16]})raise HTTPException(404, f"{name} not bundled")# The pages are generated from ui.py at import, so a redeploy is meant to change them# immediately. Nothing may sit in front of that: a cached shell would keep serving the old# markup -- and the old asset URLs with it -- after the Space has already restarted.NOCACHE = {"Cache-Control": "no-store, must-revalidate", "Pragma": "no-cache"}@app.get("/", response_class=HTMLResponse)def index():return HTMLResponse(PAGE, headers=NOCACHE)@app.get("/next")def next_case(u: dict = Depends(user)):_wait_ready()with _LOCK:for cid in _ORDER:case = _INDEX.get(cid)if not case or case.get("final"):continueslot = _claimable_slot(case, u["id"])if slot is None:continuecase["slots"][slot] = {"annotator": u["id"], "claimed_at": _now(),"expires_at": _now() + CLAIM_TTL, "done": False}_touch(case)return {"case_id": case["case_id"], "slot": slot,"image_url": f"/image/{case['case_id']}","progress": _progress()}return JSONResponse({"detail": "nothing left to annotate"}, status_code=404)# Display width. A BUU film is ~2000x2400 and several MB; sending that raw makes every# "next film" a multi-second wait, which is the difference between annotating 120 films in# an afternoon and giving up. At 1100 px one displayed pixel is under 2 source pixels,# and the consensus tolerance is 0.005 of width (~10 source px), so the downscale costs# nothing that matters. Coordinates are normalised anyway, so precision is set by the# MAGNIFIER, not by the transport size.DISPLAY_W = int(os.environ.get("DISPLAY_W", 1100))_IMG_CACHE: dict = {}def _render_jpeg(case_id: str) -> bytes:if case_id in _IMG_CACHE:return _IMG_CACHE[case_id]from PIL import Imageif DEV_LOCAL:p = os.path.join(IMAGE_REPO[6:], f"{case_id}.jpg")if not os.path.exists(p):raise HTTPException(404, f"image not found: {p}")return _encode(Image.open(p).convert("L"), case_id)from huggingface_hub import hf_hub_downloadtry:p = hf_hub_download(IMAGE_REPO, f"images/{case_id}.jpg", repo_type="dataset",token=os.environ.get("HF_TOKEN"))except Exception as exc: # noqa: BLE001raise HTTPException(404, f"image not found: {exc}")return _encode(Image.open(p).convert("L"), case_id)def _encode(im, case_id: str) -> bytes:"""Downscale + JPEG. case_id is REQUIRED: it is the cache key, and defaulting it to"" cached every film under the same entry and served the first one forever."""from io import BytesIOfrom PIL import Imageif im.width > DISPLAY_W:im = im.resize((DISPLAY_W, round(im.height * DISPLAY_W / im.width)),Image.LANCZOS)buf = BytesIO()im.save(buf, format="JPEG", quality=88, optimize=True)data = buf.getvalue()if case_id and len(_IMG_CACHE) < 400: # bounded: a Space has finite memory_IMG_CACHE[case_id] = datareturn data@app.get("/image/{case_id}")def image(case_id: str, u: dict = Depends(user)):"""Stream the film THROUGH the Space so annotators never need read access to theimage repo, exactly as the review service streams labels."""return Response(_render_jpeg(case_id), media_type="image/jpeg",headers={"Cache-Control": "private, max-age=3600"})@app.get("/peek")def peek(u: dict = Depends(user)):"""The next case id WITHOUT claiming it, so the browser can prefetch its image.Claiming on prefetch would hand every annotator a second case the moment they openedone, and abandoned claims would pile up behind the TTL."""_wait_ready()with _LOCK:for cid in _ORDER:case = _INDEX.get(cid)if not case or case.get("final"):continue# The case being annotated right now already holds a slot belonging to this# user, and _claimable_slot refuses a second slot to the same person -- so# the first hit here is genuinely the NEXT film, not the current one.if _claimable_slot(case, u["id"]) is not None:return {"case_id": case["case_id"]}return JSONResponse({"detail": "none"}, status_code=404)@app.post("/submit")def submit(case_id: str = Form(...), slot: str = Form(...), points: str = Form(""),not_visible: str = Form(""), reason: str = Form(""),u: dict = Depends(user)):"""points: JSON {"left":[x,y]|null, "right":[x,y]|null, "note":str, "w":W, "h":H}Coordinates arrive NORMALISED to the displayed image and are stored that way. Thebrowser scales the film to fit a screen of unknown size, so raw canvas pixels wouldsilently encode each annotator's window size.NOT VISIBLE IS AN ANSWER, NOT AN ABANDONMENT. It fills the reader's slot and needsthe same double read as a marked film. This matters because the open question theseannotations exist to settle is precisely "on what fraction of films can a trained eyeplace this point at all" -- so an unreadable film is a DATUM. Releasing the slotinstead (which is what /skip does) would drop that film back in the pool and quietlydelete the very observation being collected."""_wait_ready()with _LOCK:case = _INDEX.get(case_id)if case is None:raise HTTPException(404, "unknown case")s = case.get("slots", {}).get(slot)if not s or s.get("annotator") != u["id"]:raise HTTPException(403, "that slot is not yours")nv = str(not_visible).lower() in ("1", "true", "yes", "on")p = json.loads(points) if points else {}if not nv and not heads(p):raise HTTPException(400, "mark at least one femoral head, or use Not visible")if nv:s.update(done=True, submitted_at=_now(), points=None,not_visible=True, reason=reason)else:s.update(done=True, submitted_at=_now(), points=p, not_visible=False)done = [case["slots"][k] for k in ("1", "2")if case.get("slots", {}).get(k, {}).get("done")]if len(done) >= N_PRIMARY:_resolve(case, done)_touch(case)status = ("final" if case.get("final")else "needs adjudication" if case.get("disagree")else "awaiting second read")return {"ok": True, "status": status, "progress": _progress()}def _resolve(case: dict, done: list) -> None:"""Decide a case once both reads are in.Three outcomes, kept distinct because they mean different things downstream:both readable and close -> final, point = mean of the twoboth not visible -> final with NO point. A settled, usable observation:this film has no placeable hip landmark.anything else -> disagreement, held for adjudication. That includes onereader marking a point the other could not see, whichis the most interesting disagreement in the set andmust not be silently resolved either way."""nv = [bool(s.get("not_visible")) for s in done]case.pop("disagree", None)if all(nv):case["final"] = {"points": None, "by": "consensus-not-visible"}case["agree"] = Nonereturnif any(nv):case["disagree"] = "one reader marked a point the other could not see"case["agree"] = Nonereturncase["agree"] = _agreement(done[0]["points"], done[1]["points"])if case["agree"] is not None and case["agree"] <= CONSENSUS_TOL:case["final"] = {"points": _mean_points(done[0]["points"], done[1]["points"]),"by": "consensus"}else:case["disagree"] = f"readers differ by {case['agree']:.4f} of image width"@app.post("/skip")def skip(case_id: str = Form(...), slot: str = Form(...), reason: str = Form(""),u: dict = Depends(user)):"""Put a film BACK for someone else -- "not now", not "not visible".Use this for an interruption or a film you would rather another reader took. Itreleases the slot and the case returns to the pool. If the femoral heads genuinelycannot be seen, that is an ANSWER and belongs in /submit with not_visible=1, where itcounts toward the double read."""_wait_ready()with _LOCK:case = _INDEX.get(case_id)if case is None:raise HTTPException(404, "unknown case")case.setdefault("passed_by", []).append({"by": u["id"], "reason": reason,"at": _now()})case.get("slots", {}).pop(slot, None)_touch(case)return {"ok": True}def _progress() -> dict:"""Cheap counters for the header. Runs over memory, so it is free to call per film."""with _LOCK:total = len(_INDEX)reads = final = 0for c in _INDEX.values():reads += sum(1 for k in ("1", "2")if c.get("slots", {}).get(k, {}).get("done"))final += bool(c.get("final"))return {"total": total, "reads": reads, "reads_needed": total * N_PRIMARY,"final": final}@app.get("/stats")def stats(u: dict = Depends(user)):"""Who has done what, and how much is left.Deliberately visible to every annotator, not just adjudicators: people finish a longrepetitive job far more reliably when they can see the pile going down and see thatothers are carrying their share."""_wait_ready()import statisticswith _LOCK:cases = list(_INDEX.values())by: dict = {}agrees, nv_cases = [], 0counts = {"total": len(cases), "untouched": 0, "one_read": 0, "two_reads": 0,"final": 0, "final_consensus": 0, "final_not_visible": 0,"needs_adjudication": 0, "in_progress": 0}for c in cases:slots = c.get("slots", {})done = [slots.get(k) for k in ("1", "2") if slots.get(k, {}).get("done")]claimed = [slots.get(k) for k in ("1", "2")if slots.get(k) and not slots[k].get("done")]for s in done:r = by.setdefault(s["annotator"], {"reads": 0, "not_visible": 0})r["reads"] += 1r["not_visible"] += bool(s.get("not_visible"))n = len(done)counts["untouched"] += (n == 0 and not claimed)counts["in_progress"] += bool(claimed)counts["one_read"] += (n == 1)counts["two_reads"] += (n >= 2)if c.get("final"):counts["final"] += 1if c["final"].get("by") == "consensus-not-visible":counts["final_not_visible"] += 1nv_cases += 1else:counts["final_consensus"] += 1counts["needs_adjudication"] += bool(c.get("disagree"))if c.get("agree") is not None:agrees.append(c["agree"])counts["reads_done"] = sum(r["reads"] for r in by.values())counts["reads_needed"] = counts["total"] * N_PRIMARYcounts["pct_complete"] = round(100 * counts["final"] / max(1, counts["total"]), 1)# The headline number this whole exercise exists to produce.settled = counts["final"] + counts["needs_adjudication"]counts["not_visible_rate_pct"] = (round(100 * nv_cases / settled, 1)if settled else None)agree_stats = Noneif agrees:agree_stats = {"n": len(agrees),"median": round(statistics.median(agrees), 5),"p90": round(sorted(agrees)[int(0.9 * (len(agrees) - 1))], 5),"within_tol_pct": round(100 * sum(a <= CONSENSUS_TOL for a in agrees)/ len(agrees), 1),"tolerance": CONSENSUS_TOL,}readers = sorted(({"annotator": k, **v} for k, v in by.items()),key=lambda r: -r["reads"])return {"counts": counts, "readers": readers, "agreement": agree_stats,"you": u["id"], "pending_writes": len(_DIRTY)}# ── flag + adjudicate ───────────────────────────────────────────────────────────# A reader sees exactly one film at a time, streamed through the Space, with no browse,# no re-open and no export. That is deliberate -- they never need access to the image# repo -- but it also means a reader who is unsure about a film has no way to raise it,# and an adjudicator has no way to look at what two readers actually did. Telling people# to "send me the ones you are unsure about" asked for something the tool cannot do.@app.post("/flag")def flag(case_id: str = Form(...), note: str = Form(""), u: dict = Depends(user)):"""Raise the CURRENT film for discussion without abandoning the read."""_wait_ready()with _LOCK:case = _INDEX.get(case_id)if case is None:raise HTTPException(404, "unknown case")case.setdefault("flagged", []).append({"by": u["id"], "note": note[:400], "at": _now()})_touch(case)return {"ok": True}def _adjudicator(u: dict = Depends(user)) -> dict:if u["role"] != "adjudicator":raise HTTPException(403, "adjudication is limited to the study leads")return u@app.get("/queue")def queue(u: dict = Depends(_adjudicator)):"""Everything a human needs to look at: disagreements first, then flagged films."""_wait_ready()with _LOCK:out = []for cid in _ORDER:c = _INDEX.get(cid) or {}if not c.get("disagree") and not c.get("flagged"):continueout.append({"case_id": cid,"why": c.get("disagree") or "flagged by a reader","flagged": c.get("flagged") or [],"agree": c.get("agree"),"settled": bool(c.get("final")),"reads": [{"annotator": s.get("annotator"),"not_visible": bool(s.get("not_visible")),"reason": s.get("reason", ""),"heads": heads(s.get("points"))}for k in ("1", "2")for s in [c.get("slots", {}).get(k)]if s and s.get("done")],})return {"n": len(out), "cases": out}@app.post("/adjudicate")def adjudicate(case_id: str = Form(...), points: str = Form(""),not_visible: str = Form(""), note: str = Form(""),u: dict = Depends(_adjudicator)):"""Settle a case. The adjudicator's own marks win outright -- this is the point atwhich a human has looked at the film and both reads, which no averaging cansubstitute for."""_wait_ready()with _LOCK:case = _INDEX.get(case_id)if case is None:raise HTTPException(404, "unknown case")nv = str(not_visible).lower() in ("1", "true", "yes", "on")p = json.loads(points) if points else {}if not nv and not heads(p):raise HTTPException(400, "mark a centre, or settle it as not visible")hs = heads(p)case["final"] = {"points": None if nv else {"heads": hs,"bicoxofemoral": [sum(h[0] for h in hs) / len(hs),sum(h[1] for h in hs) / len(hs)],},"by": "adjudicated", "adjudicator": u["id"], "note": note[:400],"not_visible": nv,}case.pop("disagree", None)_touch(case)return {"ok": True, "progress": _progress()}@app.get("/review", response_class=HTMLResponse)def review():return HTMLResponse(REVIEW, headers=NOCACHE)@app.get("/board", response_class=HTMLResponse)def board():return HTMLResponse(BOARD, headers=NOCACHE)def heads(p: Optional[dict]) -> list:"""The marked femoral-head centres, as an UNORDERED list.A lateral radiograph cannot tell you which head is left and which is right: the twoare superimposed along the beam, and nothing in the image distinguishes them. Askinga reader to label them L and R asked for something unknowable, and comparing readerA's "left" against reader B's "left" would then score a coin flip as disagreement.It also does not matter. The bicoxofemoral point is the MIDPOINT of the two centres,which is identical either way round.Reads both shapes: {"heads":[[x,y],...]} and the older {"left":.., "right":..}."""if not p:return []if isinstance(p.get("heads"), list):# radii travel in p["radii"] alongside; they are a per-film scale reference# (an adult head is ~44-50 mm across) and a disagreement in radius between two# readers flags an arc that was ambiguous rather than a centre that was wrong.return [q for q in p["heads"] if q]return [q for q in (p.get("left"), p.get("right")) if q]def _agreement(a: dict, b: dict) -> Optional[float]:"""Worst distance between two readers, over the BEST pairing of their marks.Order-free: with two marks each, both pairings are tried and the better one wins.With unequal counts -- one reader saw two heads, the other one -- only the marksthat can be paired are scored, and the extra mark is left to adjudication ratherthan counted as an error, because "how many circles are there" is a differentdisagreement from "where is the centre"."""import mathA, B = heads(a), heads(b)if not A or not B:return Noned = lambda u, v: math.hypot(u[0] - v[0], u[1] - v[1]) # noqa: E731if len(A) == 2 and len(B) == 2:return min(max(d(A[0], B[0]), d(A[1], B[1])),max(d(A[0], B[1]), d(A[1], B[0])))return min(d(u, v) for u in A for v in B)def _mean_points(a: dict, b: dict) -> dict:"""Consensus marks, paired the same order-free way, plus the derived midpoint --which is the quantity PI actually needs."""import mathA, B = heads(a), heads(b)d = lambda u, v: math.hypot(u[0] - v[0], u[1] - v[1]) # noqa: E731mid = lambda u, v: [(u[0] + v[0]) / 2, (u[1] + v[1]) / 2] # noqa: E731if len(A) == 2 and len(B) == 2:if (max(d(A[0], B[1]), d(A[1], B[0]))< max(d(A[0], B[0]), d(A[1], B[1]))):B = [B[1], B[0]]hs = [mid(A[0], B[0]), mid(A[1], B[1])]else:pair = min(((u, v) for u in A for v in B), key=lambda t: d(*t))hs = [mid(*pair)]bicox = ([sum(h[0] for h in hs) / len(hs), sum(h[1] for h in hs) / len(hs)]if hs else None)out = {"heads": hs, "bicoxofemoral": bicox}if len(hs) == 2:out["separation"] = d(hs[0], hs[1]) # a wide one means an oblique filmreturn outfrom ui import BOARD, PAGE, REVIEW # noqa: E402 (markup lives next door)
288 unmodified lines289290291292293294288 unmodified linescheck(not pg.evaluate("HD[0].skip['A']"),"u undoes a skip -- it is a decision too, and it is invisible on the film")print("\n[7] latency")lat = pg.evaluate("""([cx,cy,cr,asp]) => {const t=(f,n)=>{const s=performance.now(); for(let i=0;i<n;i++) f(i);288 unmodified lines289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401288 unmodified linescheck(not pg.evaluate("HD[0].skip['A']"),"u undoes a skip -- it is a decision too, and it is invisible on the film")print("\n[6b] the hand-off to the second head")pg.evaluate("() => { HD=[newHd()]; acur=0; sel2=null; HIST=[]; ""autoSwitched=false; pendingSwitch=false; fits=[]; draw(); }")box = pg.locator("#c").bounding_box()def click(deg, dx=0.0):q = rim(deg)pg.mouse.click(box["x"] + box["width"] * (q[0] + dx),box["y"] + box["height"] * q[1])pg.wait_for_timeout(80)for g in (180, 270, 0): # A, S, P on head 1click(g)check(pg.evaluate("HD.length") == 2 and pg.evaluate("acur") == 1,"naming the third landmark hands over to head 2 on its own")check(pg.evaluate("HD[0].pts.length") == 3 and pg.evaluate("HD[1].pts.length") == 0,"head 1 keeps its three, head 2 starts empty")check("HEAD 2" in pg.eval_on_selector("#msg", "e => e.textContent"),"and the header says so, because a one-head film has to go back")# THE HAND-OFF IS PROVISIONAL. On the far commoner one-head film the next click is# another rim point for the head just finished, and taking it as head 2 would build a# phantom head on top of the first -- the exact thing readers are told not to do.click(225)check(pg.evaluate("HD.length") == 1 and pg.evaluate("acur") == 0and pg.evaluate("HD[0].pts.length") == 4,"clicking back on head 1's own rim takes the hand-off back")check("still head 1" in pg.eval_on_selector("#msg", "e => e.textContent"),"and says so, rather than silently changing its mind")click(315)click(90)check(pg.evaluate("HD.length") == 1 and pg.evaluate("HD[0].pts.length") == 6,"so a reader adding rim points keeps adding them to the same head")check("good" in pg.eval_on_selector("#fitread", "e => e.textContent"),"which is what takes the fit from 'widen' to 'good'")# ...while a click that is NOT on head 1 confirms itpg.evaluate("() => { HD=[newHd()]; acur=0; sel2=null; HIST=[]; ""autoSwitched=false; pendingSwitch=false; fits=[]; draw(); }")for g in (180, 270, 0):click(g)click(270, dx=0.14)check(pg.evaluate("HD.length") == 2 and pg.evaluate("HD[1].pts.length") == 1,"a click away from head 1 confirms the hand-off and starts head 2")# a genuine second head fitted on top of the first is still called output([(180, 'A'), (270, 'S'), (0, 'P')])put([(180, 'A'), (270, 'S'), (0, 'P')], head=1, dx=0.004)pg.wait_for_timeout(150)tag = pg.eval_on_selector("#fitread", "e => e.textContent")print(f" two fits on the same anatomy: {tag!r}")check("SAME head" in tag,"two centres almost on top of each other are called out, not accepted")print("\n[6c] undo and delete")pg.evaluate("() => { HD=[newHd()]; acur=0; sel2=null; HIST=[]; ""autoSwitched=false; pendingSwitch=false; fits=[]; draw(); }")for g in (180, 270, 0):click(g)click(225) # comes back to head 1check(pg.evaluate("HD[0].pts.length") == 4, "four points on one head")pg.keyboard.press("Control+z")pg.wait_for_timeout(120)check(pg.evaluate("HD[0].pts.length") == 3, "Ctrl+Z undoes the last click")pg.keyboard.press("Control+z")pg.wait_for_timeout(120)# The hand-off is its own undo step, so taking it back leaves head 1 COMPLETE rather# than also removing the landmark that triggered it.check(pg.evaluate("HD[0].pts.length") == 3and pg.evaluate("ROLES.filter(r=>roleAt(HD[0],r)).join('')") == "ASP","and the next Ctrl+Z takes back the hand-off, leaving head 1 complete")# a RENAME must undo to the previous name, not delete the landmark -- the thing a# pop-the-last-point undo gets wrongput([(180, 'A'), (270, 'S'), (0, 'P')])pg.evaluate("() => { HIST=[]; sel2={arc:0,i:0}; }")pg.keyboard.press("2")pg.wait_for_timeout(120)check(pg.evaluate("HD[0].pts[0].role") == "S", "renaming A to S works")check(pg.evaluate("HD[0].pts.filter(p=>p.role==='S').length") == 1,"and demotes whatever used to be S")pg.keyboard.press("Control+z")pg.wait_for_timeout(120)check(pg.evaluate("ROLES.filter(r=>roleAt(HD[0],r)).join('')") == "ASP"and pg.evaluate("HD[0].pts.length") == 3,"and Ctrl+Z puts BOTH names back rather than deleting a point")# click a mark, press Deleteclick(270)check(pg.evaluate("sel2 !== null"), "clicking an existing point selects it")pg.keyboard.press("Delete")pg.wait_for_timeout(120)check(pg.evaluate("HD[0].pts.length") == 2and pg.evaluate("roleAt(HD[0],'S')") is None,"Delete removes the selected landmark")pg.keyboard.press("Control+z")pg.wait_for_timeout(120)check(pg.evaluate("roleAt(HD[0],'S') !== null"), "and Ctrl+Z brings it back")pg.evaluate("sel2={arc:0,i:0}")pg.keyboard.press("Backspace")pg.wait_for_timeout(120)check(pg.evaluate("HD[0].pts.length") == 2, "Backspace does the same")check(pg.evaluate("location.pathname") == "/","and does NOT navigate the browser back, which would lose the whole read")pg.keyboard.press("Control+z")pg.wait_for_timeout(120)print("\n[7] latency")lat = pg.evaluate("""([cx,cy,cr,asp]) => {const t=(f,n)=>{const s=performance.now(); for(let i=0;i<n;i++) f(i);
127 unmodified lines1281291301311321331 unmodified line135136137138139140127 unmodified linescheck(pg.evaluate("""(()=>[...document.querySelectorAll('#example img')].every(i=>i.naturalWidth>0))()"""),"every example panel image loaded")check(canvas["x"] > guide["x"] + guide["width"] - 2,"film is on the RIGHT, clear of the guide")check(guide["height"] <= VIEW["height"], "guide fits the window (scrolls internally)")1 unmodified line"return g.scrollHeight > g.clientHeight})()"),"guide actually scrolls rather than clipping")gap = VIEW["height"] - (canvas["y"] + canvas["height"])check(gap >= 50, f"bottom gutter clear of the taskbar ({gap:.0f} px below the film)")check(canvas["y"] + canvas["height"] <= VIEW["height"], "film is fully on screen")127 unmodified lines1281291301311321331341351361371381391401411421431441451461471481491501511521531541551 unmodified line157158159160161162163164165166167168169170171172173174175176177178179127 unmodified linescheck(pg.evaluate("""(()=>[...document.querySelectorAll('#example img')].every(i=>i.naturalWidth>0))()"""),"every example panel image loaded")# CACHE BUSTING. The panels are served immutable/1-year, which is only safe because# their URL carries a hash of their bytes. If the hash ever stops being appended, a# rebuilt teaching figure would never reach a reader who had already opened the page# -- they would follow landmark instructions beside the previous method's picture,# which is exactly the failure this guards.srcs = pg.eval_on_selector_all("#example img", "es => es.map(e => e.src)")import re as _recheck(all(_re.search(r"/reference/[abc]\?v=[0-9a-f]{6,}$", u) for u in srcs),f"every panel URL carries a content hash ({[u.split('/')[-1] for u in srcs]})")check(len({u.split("v=")[1] for u in srcs}) == 3,"and the three differ, so they are hashes of content rather than one build id")hdrs = pg.evaluate("""async () => {const r = await fetch(document.querySelector('#example img').src);const h = await fetch('/');return {img: r.headers.get('cache-control'),page: h.headers.get('cache-control')};}""")print(f" cache-control panel: {hdrs['img']} page: {hdrs['page']}")check("immutable" in (hdrs["img"] or ""),"the hashed panel is cached hard")check("no-store" in (hdrs["page"] or ""),"but the page itself is never cached, so a redeploy reaches readers at once")check(canvas["x"] > guide["x"] + guide["width"] - 2,"film is on the RIGHT, clear of the guide")check(guide["height"] <= VIEW["height"], "guide fits the window (scrolls internally)")1 unmodified line"return g.scrollHeight > g.clientHeight})()"),"guide actually scrolls rather than clipping")# A long status message must not re-wrap the header. When it did, #stage moved and# the film slid out from under the cursor: a click aimed at the cortex landed 60 px# away, silently, mid-annotation.h0 = pg.locator("header").bounding_box()["height"]y0 = pg.locator("#c").bounding_box()["y"]pg.evaluate("msg('head 1 done — now HEAD 2. Only one head? press h. ""and then some more text to be quite sure it would have wrapped')")pg.wait_for_timeout(200)h1 = pg.locator("header").bounding_box()["height"]y1 = pg.locator("#c").bounding_box()["y"]check(abs(h1 - h0) < 1 and abs(y1 - y0) < 1,f"a long status message does not move the film "f"(header {h0:.0f}->{h1:.0f} px, film y {y0:.0f}->{y1:.0f})")check(pg.eval_on_selector("#msg", "e => e.title").startswith("head 1 done"),"and the full text is still readable, in the tooltip")pg.evaluate("msg('')")gap = VIEW["height"] - (canvas["y"] + canvas["height"])check(gap >= 50, f"bottom gutter clear of the taskbar ({gap:.0f} px below the film)")check(canvas["y"] + canvas["height"] <= VIEW["height"], "film is fully on screen")
18 unmodified lines192021222324145 unmodified lines17017117217317417517617717817918018190 unmodified lines27227327427527627727827928028128228328428528628728828929029129229329429529629729829930011 unmodified lines312313314315316317318124 unmodified lines443444445446447448449450451452453454110 unmodified lines5655665675685695709 unmodified lines580581582583584585351 unmodified lines93793893994094194210 unmodified lines95395495595695795851 unmodified lines101010111012101310141015101644 unmodified lines1061106210631064106510661067284 unmodified lines135213531354135513561357135877 unmodified lines1436143714381439144014411442144314441445144614475 unmodified lines145314541455145614571458145914601461146214631464146514661467146814691470147114721 unmodified line1474147514761477147814794 unmodified lines148414851486148714881489149014919 unmodified lines1501150215031504150515061507120 unmodified lines162816291630163116321633127 unmodified lines176117621763176417651766176718 unmodified linessuggestibility instead of anatomy."""CRITERIA = """<aside id=guide><div class=helpbody>145 unmodified linesas small rings rather than labelled squares, they are not landmarks, and they existonly to tighten the circle. More is always better.</li><li><b>Drag any point</b> to correct it; the circle, the centre and the ellipsere-fit live. <kbd>u</kbd> removes the last point, and also undoes a<b>Can’t see it</b>.</li><li>The fitted circle is drawn <b>solid where you gave it evidence and dashed where itis extrapolating</b>. A mostly-dashed circle is a warning, not a finished mark.</li><li>For a <b>second head</b>, press <kbd>h</kbd> (or New head) and mark A, S and P onit too. <kbd>h</kbd> also switches back if you want to add points to the first.</li><li><b>Elsewhere the controls are a PACS.</b> Scroll zooms about the cursor,<b>left-drag</b> on bare film windows it (left-right contrast, up-downbrightness), <b>right-drag</b> pans, <kbd>r</kbd> resets. A faint arc usually90 unmodified lines</aside>"""EXAMPLES = """<aside id=example><h3>Worked example</h3><figure><img src="/reference/c" alt="two femoral heads, each with a fitted circle"><figcaption><b>Two heads.</b> Same diameter, offset front-to-back, a circle on each.The midpoint between the centres is derived for you.</figcaption></figure><figure><img src="/reference/b" alt="the concentric-circle construction on one head"><figcaption><b>One head.</b> Size the circle to the subchondral cortical arc, not tothe brightest shadow.</figcaption></figure><figure><img src="/reference/a" alt="where the femoral head sits on a lateral film"><figcaption><b>Where to look.</b> Below and anterior to the S1 endplate, seated inthe acetabulum.</figcaption></figure><p class=exnote>Drawn on a DRR of a segmented CT, so the marked centre is a 3-D spherefit projected — not anyone's opinion. The second head in the top panel is aschematic: a DRR integrates along the hip axis, so its two heads superimpose exactly.</p></aside>"""STYLE = """:root{--go:#0072B2;--lft:#00E5A0;--rgt:#FF3B30;--warn:#f5a524}11 unmodified lines.sk{background:#3a3a44;color:#ddd;font-weight:500}.ghost{background:transparent;color:#9aa;border:1px solid #3a3a44;font-weight:500}kbd{background:#333;padding:1px 5px;border-radius:3px;font-size:11px;font-weight:400}#msg{margin-left:auto;color:#9ad;font-variant-numeric:tabular-nums}#who{color:#8a8;font-size:12px}/* Only one tool's instructions and controls are ever shown. The class goes on <body>so it reaches the guide, the header hint and the buttons from one place. */124 unmodified lines<span class=ifcircle>click to drop a circle · hover it and <b>scroll</b> to size · drag to nudge</span><button class="ghost ifarc" id=btnface onclick=toggleFace()title="which way the patient faces on this film. Sticky — set it once and it carries to every film after. m">Faces ◀ anterior left</button><button class="ghost ifarc" onclick=autoName()title="name your existing clicks A/S/P from the shape of the circle they fit. Never adds a point; every name stays editable.">Auto-name <kbd>w</kbd></button><button class="ghost ifarc" id=btnskip onclick=skipRole()title="this extreme cannot be traced — derive it from the circle and record it as unobserved">Can’t see it <kbd>k</kbd></button><button class="ghost ifarc" id=btnhead onclick=newHead()>New head <kbd>h</kbd></button><button class=ghost onclick=undo()>Undo <kbd>u</kbd></button><button class=go onclick=send()>Submit <kbd>↵</kbd></button><button class=nv onclick=notVisible()>Not visible <kbd>v</kbd></button><button class=sk onclick=pass()>Pass <kbd>p</kbd></button>110 unmodified lines// pts [{x,y,role}] in placement order, role '' for an extra rim point// skip {A,S,P} an extreme the reader could not see; derived from the fit insteadlet HD=[{pts:[], skip:{}}], acur=0, fits=[], sel2=null; // sel2 = {arc,i} selected pointconst newHd=()=>({pts:[], skip:{}});// The landmark the next click will become: the first of A,S,P neither placed nor skipped,// then '' for extras. This is a SUGGESTION, never a constraint -- see relabel().9 unmodified lines// way backwards to fix a label, which is how you train people to submit a wrong one.function relabel(r, target){if(TOOL!=='arc') return;const t = target || sel2 || (HD[acur].pts.length? {arc:acur, i:HD[acur].pts.length-1} : null);if(!t){ msg('click a point first, then press '+(r||'e')+' to name it'); return; }351 unmodified linesif(tilt>12){ tag += ' A/P tilt '+Math.round(tilt)+'\\u00b0';if(cls==='ok') cls='mid'; }if(fits.some(f=>f&&f.swapped)){ tag += ' A/P LOOK SWAPPED'; cls='bad'; }if(all.length && onc<all.length && cls==='ok') cls='mid';// not just "add more points" -- which part of the rim, measuredif(cls!=='ok' && fits[acur]){10 unmodified linesif(TOOL!=='arc')return;const h=HD[acur], f=fits[acur];if(!f){ msg('mark at least 3 points first'); return; }const used=new Set();ROLES.forEach(r=>{if(h.skip[r]) return;51 unmodified lines// X-Annot-Token, not Authorization: on a private Space the Hub proxy// consumes Authorization before the app ever sees it.const H=()=>token?{'X-Annot-Token':token}:{};const msg=t=>$('msg').textContent=t;function useToken(){const v=$('tok').value.trim(); if(!v)return;44 unmodified lines}async function load(){if(busy)return; busy=true;circles=[]; sel=-1; HD=[newHd()]; acur=0; fits=[]; sel2=null; sel2=null; readout();const t0=performance.now();try{const r=await fetch('/next',{headers:H()});284 unmodified linesconst pt=(TOOL==='arc' && e.button===0) ? hitPt(e) : null;const i=(TOOL!=='arc' && e.button===0) ? hit(p) : -1;if(i>=0) sel=i;if(pt){ acur=pt.arc; sel2={arc:pt.arc, i:pt.i}; } // grabbing a point selects itdrag={x:e.clientX, y:e.clientY, b:gainB, c:gainC, moved:0, btn:e.button,circle:i, cx:i>=0?circles[i][0]:0, cy:i>=0?circles[i][1]:0,pt:pt, px:pt?HD[pt.arc].pts[pt.i].x:0, py:pt?HD[pt.arc].pts[pt.i].y:0,77 unmodified linesif(!img.width)return;const p=at(e);if(TOOL==='arc'){const h=HD[acur], r=nextRole(h);h.pts.push({x:p[0], y:p[1], role:r});sel2={arc:acur, i:h.pts.length-1};refit(); draw(); readout();const nx=nextRole(h);msg(!r ? (h.pts.length+' points on head '+(acur+1)): nx ? (ROLE_NAME[r]+' marked \\u2014 now the '+ROLE_NAME[nx]): 'all three marked \\u2014 add rim points to tighten it, or Submit');return;5 unmodified lines}function undo(){if(TOOL==='arc'){const h=HD[acur];// A skip is a decision too, and it is invisible on the film, so it has to be// undoable -- otherwise a mis-keyed skip permanently downgrades a landmark that the// reader could actually see.const lastSkip=ROLES.filter(r=>h.skip[r]).pop();if(h.pts.length) h.pts.pop();else if(lastSkip) delete h.skip[lastSkip];// an emptied second head is removed rather than left as a stub that submits as a headelse if(acur>0){ HD.splice(acur,1); acur=HD.length-1; }sel2=null; refit(); draw(); readout();return;}circles.pop(); sel=circles.length-1; draw();}// An extreme that genuinely cannot be traced. It is derived from the fitted circle and// exported as NOT observed, so the film is still usable for the centre without teaching a// detector to find a landmark that was never visible.1 unmodified lineif(TOOL!=='arc')return;const h=HD[acur], r=nextRole(h);if(!r){ msg('all three extremes are already marked'); return; }h.skip[r]=true;refit(); draw(); readout();const nx=nextRole(h);4 unmodified lines// missed piece of the first rim after starting the second should not have to undo to it.function newHead(){if(TOOL!=='arc')return;if(HD.length<2){if(HD[acur].pts.length<3){ msg('finish this head first — 3 points minimum'); return; }HD.push(newHd()); acur=1;} else {acur=(acur+1)%HD.length;9 unmodified linesfunction toggleTool(){TOOL = (TOOL==='arc') ? 'circle' : 'arc';try{localStorage.setItem('annot_tool',TOOL)}catch(e){}circles=[]; sel=-1; HD=[newHd()]; acur=0; fits=[];applyTool(); draw(); readout();msg('tool: '+TOOL+' — marks cleared');}120 unmodified lines}document.addEventListener('keydown',e=>{if(e.target.tagName==='INPUT'||e.target.tagName==='TEXTAREA')return;if(e.key==='u')undo();else if(e.key==='Enter')send();else if(e.key==='v')notVisible();127 unmodified lines<script>const $=i=>document.getElementById(i);const H=()=>{const t=localStorage.getItem('hf_tok');return t?{'X-Annot-Token':t}:{}};const msg=t=>$('msg').textContent=t;const COL=['#00E5A0','#FF3B30'];let cases=[], cur=null, img=new Image(), mine=[];const C=$('rc'), X=C.getContext('2d');18 unmodified lines19202122232425262728293031323334353637383940414243444546474849145 unmodified lines19519619719819920020120220320420520620720820921090 unmodified lines30130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433511 unmodified lines347348349350351352353354355356357358359124 unmodified lines484485486487488489490491492493494495496110 unmodified lines6076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456469 unmodified lines656657658659660661662351 unmodified lines10141015101610171018101910201021102210231024102510261027102810291030103110 unmodified lines104210431044104510461047104851 unmodified lines110011011102110311041105110644 unmodified lines11511152115311541155115611571158284 unmodified lines144314441445144614471448144977 unmodified lines1527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315745 unmodified lines1580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061 unmodified line16081609161016111612161316144 unmodified lines16191620162116221623162416251626162716289 unmodified lines16381639164016411642164316441645120 unmodified lines176617671768176917701771177217731774177517761777127 unmodified lines190519061907190819091910191118 unmodified linessuggestibility instead of anatomy."""import hashlibimport pathlibdef _v(name: str) -> str:"""Content hash of a bundled asset, for cache-busting its URL.The teaching panels are served with a long max-age -- they are the same bytes onevery request and re-fetching them per film would be wasteful. The cost of that isthat REPLACING one leaves every reader who has already opened the page looking at theold picture for a day, which is exactly what happened when the panels were rebuilt forthe landmark method: the instructions changed and the figure beside them did not.Hashing the file into its own URL fixes both ends. The URL only changes when the byteschange, so caching stays aggressive AND a new panel appears immediately."""try:return hashlib.md5(pathlib.Path(__file__).with_name(name).read_bytes()).hexdigest()[:10]except OSError:return "0" # not bundled yet; the route will 404 either wayREF_V = {k: _v(f"ref_{k}.png") for k in "abc"}CRITERIA = """<aside id=guide><div class=helpbody>145 unmodified linesas small rings rather than labelled squares, they are not landmarks, and they existonly to tighten the circle. More is always better.</li><li><b>Drag any point</b> to correct it; the circle, the centre and the ellipsere-fit live. <b>Click a point and press <kbd>Delete</kbd></b> to remove it.<b><kbd>Ctrl</kbd>+<kbd>Z</kbd></b> (or <kbd>u</kbd>) undoes the last thing youdid — a click, a rename, a drag, or a <b>Can’t see it</b>.</li><li>The fitted circle is drawn <b>solid where you gave it evidence and dashed where itis extrapolating</b>. A mostly-dashed circle is a warning, not a finished mark.</li><li><b>The tool moves to the second head on its own</b> as soon as you have namedA, S and P on the first — the header says so, and the second head’smarks are drawn in red. <b>If this film has only one head, press <kbd>h</kbd> togo back</b> to it (and add rim points), then Submit. <kbd>h</kbd> switches betweenthe two at any time.</li><li><b>Elsewhere the controls are a PACS.</b> Scroll zooms about the cursor,<b>left-drag</b> on bare film windows it (left-right contrast, up-downbrightness), <b>right-drag</b> pans, <kbd>r</kbd> resets. A faint arc usually90 unmodified lines</aside>"""EXAMPLES = ("""<aside id=example><h3>Worked example</h3><figure><img src="/reference/c?v=__VC__" alt="two femoral heads on a rotated view, A S and Pmarked on each"><figcaption><b>Two heads.</b> Same diameter, offset front-to-back, <b>A, S and P oneach</b>. The midpoint between the two fitted centres is derived for you.</figcaption></figure><figure><img src="/reference/b?v=__VB__" alt="anterior, superior and posterior extremes markedon one femoral head"><figcaption><b>One head.</b> The anterior-, superior- and posterior-most points of thearticular surface. Follow the subchondral cortical arc, not the brightestshadow.</figcaption></figure><figure><img src="/reference/a?v=__VA__" alt="where the femoral head sits on a lateral film"><figcaption><b>Where to look.</b> Below and anterior to the S1 endplate, seated inthe acetabulum.</figcaption></figure><p class=exnote>Drawn on a DRR of a segmented CT, so every mark is measured rather thananyone's opinion: the three landmarks are the extremes of a sphere fitted to the femoralhead at its contact with the acetabulum, and the circle through them recovers thatsphere's centre exactly. The two-head panel is the <b>same scan projected 8° off thehip axis</b> — a real rotation, so the heads are really that far apart.</p></aside>""".replace("__VA__", REF_V["a"]).replace("__VB__", REF_V["b"]).replace("__VC__", REF_V["c"]))STYLE = """:root{--go:#0072B2;--lft:#00E5A0;--rgt:#FF3B30;--warn:#f5a524}11 unmodified lines.sk{background:#3a3a44;color:#ddd;font-weight:500}.ghost{background:transparent;color:#9aa;border:1px solid #3a3a44;font-weight:500}kbd{background:#333;padding:1px 5px;border-radius:3px;font-size:11px;font-weight:400}/* The status line must never change the header's HEIGHT. The header is flex-wrap, so along message pushes onto a second row, #stage moves, and the film slides out fromunder the cursor mid-annotation -- a click aimed at the cortex lands 60 px away. It isthe same hazard #wl is fixed-width for. One line, clipped, full text in the tooltip. */#msg{margin-left:auto;color:#9ad;font-variant-numeric:tabular-nums;flex:0 1 auto;max-width:52ch;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}#who{color:#8a8;font-size:12px}/* Only one tool's instructions and controls are ever shown. The class goes on <body>so it reaches the guide, the header hint and the buttons from one place. */124 unmodified lines<span class=ifcircle>click to drop a circle · hover it and <b>scroll</b> to size · drag to nudge</span><button class="ghost ifarc" id=btnface onclick=toggleFace()title="which way the patient faces on this film. Sticky — set it once and it carries to every film after. m">Faces ◀ anterior left</button><button class=ghost onclick=undo()title="Ctrl+Z, or u. Undoes the last thing you did — a click, a rename, a drag, a skip.">Undo <kbd>⌘Z</kbd></button><button class="ghost ifarc" onclick=autoName()title="name your existing clicks A/S/P from the shape of the circle they fit. Never adds a point; every name stays editable.">Auto-name <kbd>w</kbd></button><button class="ghost ifarc" id=btnskip onclick=skipRole()title="this extreme cannot be traced — derive it from the circle and record it as unobserved">Can’t see it <kbd>k</kbd></button><button class="ghost ifarc" id=btnhead onclick=newHead()>New head <kbd>h</kbd></button><button class=go onclick=send()>Submit <kbd>↵</kbd></button><button class=nv onclick=notVisible()>Not visible <kbd>v</kbd></button><button class=sk onclick=pass()>Pass <kbd>p</kbd></button>110 unmodified lines// pts [{x,y,role}] in placement order, role '' for an extra rim point// skip {A,S,P} an extreme the reader could not see; derived from the fit insteadlet HD=[{pts:[], skip:{}}], acur=0, fits=[], sel2=null; // sel2 = {arc,i} selected point/* UNDO IS A STACK, not "remove the last point".Once points can be renamed, dragged, deleted, skipped and auto-assigned, "undo the lastclick" stops matching what the reader thinks they just did -- renaming A to S and thenpressing undo should put the name back, not delete a landmark. So every mutating actionsnapshots first and undo restores the snapshot. Ctrl+Z and u both run it. */let HIST=[];const MAXHIST=80;function snap(){return JSON.stringify({hd: HD.map(h=>({pts:h.pts.map(p=>({x:p.x, y:p.y, role:p.role})),skip:Object.assign({}, h.skip)})),acur:acur, sel2:sel2, auto:autoSwitched});}function pushHist(){if(TOOL!=='arc') return;HIST.push(snap());if(HIST.length>MAXHIST) HIST.shift();}function restore(js){const st=JSON.parse(js);HD = st.hd.map(h=>({pts:h.pts.map(p=>({x:p.x, y:p.y, role:p.role})),skip:h.skip||{}}));acur = Math.min(st.acur, HD.length-1);sel2 = st.sel2;autoSwitched = !!st.auto;refit(); draw(); readout();}// The film has ONE head on most laterals and two on a rotated one, so the tool cannot// know when the reader is finished. It can know when they have named all three landmarks// on the head they are working on, and that is the moment to offer the second -- see// place().let autoSwitched=false;// true only between the hand-off and the reader's next click -- see place()let pendingSwitch=false;const newHd=()=>({pts:[], skip:{}});// The landmark the next click will become: the first of A,S,P neither placed nor skipped,// then '' for extras. This is a SUGGESTION, never a constraint -- see relabel().9 unmodified lines// way backwards to fix a label, which is how you train people to submit a wrong one.function relabel(r, target){if(TOOL!=='arc') return;pushHist();const t = target || sel2 || (HD[acur].pts.length? {arc:acur, i:HD[acur].pts.length-1} : null);if(!t){ msg('click a point first, then press '+(r||'e')+' to name it'); return; }351 unmodified linesif(tilt>12){ tag += ' A/P tilt '+Math.round(tilt)+'\\u00b0';if(cls==='ok') cls='mid'; }if(fits.some(f=>f&&f.swapped)){ tag += ' A/P LOOK SWAPPED'; cls='bad'; }// The cost of handing head 2 over automatically: a reader who keeps clicking to add// rim points builds a second "head" on top of the first. Two fitted centres almost on// top of each other are not two heads, and the midpoint of that pair is meaningless --// so say so rather than accepting it.const F2=fits.filter(Boolean);if(F2.length===2){const d=Math.hypot(F2[0].a-F2[1].a, F2[0].b-F2[1].b);if(d < 0.5*(F2[0].R+F2[1].R)*0.5){tag += ' \u2190 these two are the SAME head (press h, then u)';cls='bad';}}if(all.length && onc<all.length && cls==='ok') cls='mid';// not just "add more points" -- which part of the rim, measuredif(cls!=='ok' && fits[acur]){10 unmodified linesif(TOOL!=='arc')return;const h=HD[acur], f=fits[acur];if(!f){ msg('mark at least 3 points first'); return; }pushHist();const used=new Set();ROLES.forEach(r=>{if(h.skip[r]) return;51 unmodified lines// X-Annot-Token, not Authorization: on a private Space the Hub proxy// consumes Authorization before the app ever sees it.const H=()=>token?{'X-Annot-Token':token}:{};const msg=t=>{ const e=$('msg'); e.textContent=t; e.title=t; };function useToken(){const v=$('tok').value.trim(); if(!v)return;44 unmodified lines}async function load(){if(busy)return; busy=true;circles=[]; sel=-1; HD=[newHd()]; acur=0; fits=[]; sel2=null;HIST=[]; autoSwitched=false; pendingSwitch=false; readout();const t0=performance.now();try{const r=await fetch('/next',{headers:H()});284 unmodified linesconst pt=(TOOL==='arc' && e.button===0) ? hitPt(e) : null;const i=(TOOL!=='arc' && e.button===0) ? hit(p) : -1;if(i>=0) sel=i;if(pt){ acur=pt.arc; sel2={arc:pt.arc, i:pt.i}; pushHist(); } // grabbing selects itdrag={x:e.clientX, y:e.clientY, b:gainB, c:gainC, moved:0, btn:e.button,circle:i, cx:i>=0?circles[i][0]:0, cy:i>=0?circles[i][1]:0,pt:pt, px:pt?HD[pt.arc].pts[pt.i].x:0, py:pt?HD[pt.arc].pts[pt.i].y:0,77 unmodified linesif(!img.width)return;const p=at(e);if(TOOL==='arc'){pushHist();// THE HAND-OFF IS PROVISIONAL. Moving to head 2 after the third landmark is right on// a rotated film and wrong on the far commoner one-head film, where the reader's next// click is another rim point for the head they just finished -- and would otherwise// start building a phantom second head on top of the first.//// The click itself says which it is. Land back inside head 1 and the hand-off is// taken back; land anywhere else and it stands. Only the FIRST click after the switch// is treated this way, so a genuine second head is not second-guessed later.let tookBack=false;if(pendingSwitch && acur===1 && HD[1] && !HD[1].pts.length){pendingSwitch=false;const f0=fits[0];if(f0 && Math.hypot(p[0]*img.width-f0.a, p[1]*img.height-f0.b) <= 1.35*f0.R){HD.splice(1,1); acur=0; sel2=null; tookBack=true;}}const h=HD[acur], r=nextRole(h);h.pts.push({x:p[0], y:p[1], role:r});sel2={arc:acur, i:h.pts.length-1};const nx=nextRole(h);// Naming the third landmark completes a head, so the next click starts the SECOND// one -- the common case on a rotated film, and it saves reaching for a key on every// film that has two. Fires once per film, only from the first head, and h goes// straight back if the reader wants to add rim points to head 1 instead.if(r && !nx && !autoSwitched && HD.length===1){// Its own undo step. The hand-off and the click that triggered it are one keystroke// but two things in the reader's head, and Ctrl+Z should take back the hand-off --// returning them to a complete head 1 -- rather than also deleting the landmark// they had just got right.pushHist();autoSwitched=true; pendingSwitch=true;HD.push(newHd()); acur=1; sel2=null;refit(); draw(); readout();msg('head 1 done \u2014 now HEAD 2. Only one head? press h');return;}refit(); draw(); readout();// tookBack first: the trailing status line would otherwise overwrite the one thing// the reader needs to know, which is that the tool just changed its mind for them.msg(tookBack ? 'still head 1 \\u2014 rim point added (h for head 2)': !r ? (h.pts.length+' points on head '+(acur+1)): nx ? (ROLE_NAME[r]+' marked \\u2014 now the '+ROLE_NAME[nx]): 'all three marked \\u2014 add rim points to tighten it, or Submit');return;5 unmodified lines}function undo(){if(TOOL==='arc'){if(!HIST.length){ msg('nothing to undo'); return; }restore(HIST.pop());msg('undone');return;}circles.pop(); sel=circles.length-1; draw();}// Delete / Backspace on the selected point. Clicking the offending mark and pressing// delete is what everyone reaches for first, and undo only helps when the mistake was// the most recent thing that happened.function delPoint(){if(TOOL!=='arc') return;if(!sel2 || !HD[sel2.arc] || !HD[sel2.arc].pts[sel2.i]){msg('click a point first, then Delete to remove it'); return; }pushHist();const gone=HD[sel2.arc].pts.splice(sel2.i,1)[0];// an emptied second head is dropped rather than left as a stub with no landmarksif(!HD[sel2.arc].pts.length && sel2.arc>0){ HD.splice(sel2.arc,1); acur=HD.length-1; }sel2=null; refit(); draw(); readout();msg(gone.role ? ('removed the '+ROLE_NAME[gone.role]) : 'removed a rim point');}// An extreme that genuinely cannot be traced. It is derived from the fitted circle and// exported as NOT observed, so the film is still usable for the centre without teaching a// detector to find a landmark that was never visible.1 unmodified lineif(TOOL!=='arc')return;const h=HD[acur], r=nextRole(h);if(!r){ msg('all three extremes are already marked'); return; }pushHist();h.skip[r]=true;refit(); draw(); readout();const nx=nextRole(h);4 unmodified lines// missed piece of the first rim after starting the second should not have to undo to it.function newHead(){if(TOOL!=='arc')return;pendingSwitch=false;if(HD.length<2){if(HD[acur].pts.length<3){ msg('finish this head first — 3 points minimum'); return; }pushHist();HD.push(newHd()); acur=1;} else {acur=(acur+1)%HD.length;9 unmodified linesfunction toggleTool(){TOOL = (TOOL==='arc') ? 'circle' : 'arc';try{localStorage.setItem('annot_tool',TOOL)}catch(e){}circles=[]; sel=-1; HD=[newHd()]; acur=0; fits=[]; sel2=null;HIST=[]; autoSwitched=false; pendingSwitch=false;applyTool(); draw(); readout();msg('tool: '+TOOL+' — marks cleared');}120 unmodified lines}document.addEventListener('keydown',e=>{if(e.target.tagName==='INPUT'||e.target.tagName==='TEXTAREA')return;// Ctrl+Z / Cmd+Z as well as u, and Delete/Backspace on the selected mark.// preventDefault on both: the browser would otherwise treat Ctrl+Z as page-level undo// and Backspace as navigate-back, which loses the whole read.if((e.ctrlKey||e.metaKey) && (e.key==='z'||e.key==='Z')){e.preventDefault(); undo(); return; }if(e.key==='Delete'||e.key==='Backspace'){ e.preventDefault(); delPoint(); return; }if(e.key==='u')undo();else if(e.key==='Enter')send();else if(e.key==='v')notVisible();127 unmodified lines<script>const $=i=>document.getElementById(i);const H=()=>{const t=localStorage.getItem('hf_tok');return t?{'X-Annot-Token':t}:{}};const msg=t=>{ const e=$('msg'); e.textContent=t; e.title=t; };const COL=['#00E5A0','#FF3B30'];let cases=[], cur=null, img=new Image(), mine=[];const C=$('rc'), X=C.getContext('2d');
app.py+1013-993
test_arc.py+107
test_layout.py+39
ui.py+179-35