wanhanisah commited on
Commit
07a152c
·
verified ·
1 Parent(s): caf1e11

Upload folder using huggingface_hub

Browse files
.streamlit/config.toml ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ [server]
2
+ enableStaticServing = true
3
+ # Needed inside the Hugging Face iframe (drawable canvas + file serving)
4
+ enableXsrfProtection = false
5
+ enableCORS = false
6
+
7
+ [browser]
8
+ gatherUsageStats = false
Dockerfile ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.10-slim
2
+
3
+ # DejaVu font (GIF labels) + libGL-free OpenCV runtime libs
4
+ RUN apt-get update && \
5
+ apt-get install -y --no-install-recommends fonts-dejavu-core libglib2.0-0 && \
6
+ rm -rf /var/lib/apt/lists/*
7
+
8
+ WORKDIR /app
9
+ COPY requirements.txt /app/requirements.txt
10
+ RUN pip install --no-cache-dir -r requirements.txt
11
+
12
+ COPY . /app
13
+
14
+ # Spaces run the container as a non-root user: the app writes its working
15
+ # folders (cache/, results/, the downloaded dataset) under /app.
16
+ RUN mkdir -p /app/cache /app/results /app/static && chmod -R 777 /app
17
+
18
+ ENV STREAMLIT_BROWSER_GATHER_USAGE_STATS=false \
19
+ PYTHONUNBUFFERED=1 \
20
+ MPLCONFIGDIR=/tmp/mpl \
21
+ HF_HOME=/tmp/hf_home
22
+
23
+ EXPOSE 7860
24
+
25
+ CMD ["streamlit", "run", "roundel_app_biventricular.py", "--server.port=7860", "--server.address=0.0.0.0"]
README.md CHANGED
@@ -1,13 +1,21 @@
1
  ---
2
  title: Biventricular Segmentation
3
- emoji: 🫀
4
- colorFrom: blue
5
- colorTo: red
6
- sdk: gradio
7
- sdk_version: 6.31.0
8
- python_version: '3.12'
9
- app_file: app.py
10
  pinned: false
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  title: Biventricular Segmentation
3
+ emoji: ⭕️
4
+ colorFrom: red
5
+ colorTo: yellow
6
+ sdk: docker
7
+ app_port: 7860
 
 
8
  pinned: false
9
  ---
10
 
11
+ # Roundel (2D Biventricular) — Supervisor Review
12
+
13
+ Review and edit of the Horos_Roundel_Mouse_2026_final segmentations (50 mice).
14
+
15
+ - Case data is read from the private dataset `wanhanisah/Horos_Roundel_Mouse_2026_review`.
16
+ - Edits start from Wan's saved segmentation and are saved to the dataset's `sv/` folder
17
+ by **Save Masks and Metrics 💾**, **Save All Masks and Metrics 💾**, **Save note** and the
18
+ **Status: Complete** checkbox. Wan's original files are never changed.
19
+ - **Reset Current Mask** puts the current slice/frame back to Wan's segmentation.
20
+
21
+ Space settings → Variables and secrets: add a secret `HF_TOKEN` (a token with write access to the dataset).
frame_selector_component/index.html ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html>
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <style>
6
+ html, body {
7
+ margin: 0;
8
+ padding: 0;
9
+ font-family: "Source Sans Pro", sans-serif;
10
+ background: transparent;
11
+ }
12
+ .option {
13
+ display: flex;
14
+ align-items: center;
15
+ gap: 8px;
16
+ padding: 4px 2px;
17
+ cursor: pointer;
18
+ user-select: none;
19
+ }
20
+ .dot {
21
+ width: 16px;
22
+ height: 16px;
23
+ border-radius: 50%;
24
+ border: 2px solid rgb(49, 51, 63);
25
+ background: rgb(255, 255, 255);
26
+ box-sizing: border-box;
27
+ flex-shrink: 0;
28
+ }
29
+ .option.selected .dot {
30
+ background: rgb(255, 75, 75);
31
+ }
32
+ .option:not(.selected) .dot {
33
+ background: rgba(49, 51, 63, 0.1);
34
+ }
35
+ .label {
36
+ font-size: 16px;
37
+ color: rgb(49, 51, 63);
38
+ line-height: 1.4;
39
+ }
40
+ </style>
41
+ </head>
42
+ <body>
43
+ <div id="root"></div>
44
+ <script>
45
+ // Minimal Streamlit Components JS protocol, implemented directly
46
+ // (no streamlit-component-lib bundle needed for something this small).
47
+ //
48
+ // UPDATED 2026-09-17: this component exists specifically so the Frame
49
+ // selector's own visual highlight updates INSTANTLY and LOCALLY on click,
50
+ // the same way the mask-editing canvas (streamlit_drawable_canvas) never
51
+ // visibly freezes under rapid interaction -- that component also renders
52
+ // its own clicked/drawn state immediately in its own iframe, independent
53
+ // of whether Streamlit's Python-side rerun for that interaction has
54
+ // finished (or even survived being cancelled by a later interaction).
55
+ // A plain st.radio() cannot do this: it is a fully Streamlit-controlled
56
+ // widget that only repaints once a full script rerun completes without
57
+ // being cancelled by a newer interaction, which is exactly what produced
58
+ // the "orange dot stuck one-or-more clicks behind, while the preview is
59
+ // already correct" symptom -- confirmed live, and NOT fully resolvable
60
+ // from the Python side (a cancelled rerun's corrected value never reaches
61
+ // the browser to repaint from). Rendering + highlighting locally in this
62
+ // component's own click handler, and only using Streamlit's message
63
+ // channel to REPORT the choice (never to decide how to render it),
64
+ // sidesteps the cancelled-rerun problem entirely for the visual state.
65
+
66
+ var root = document.getElementById("root");
67
+ var currentValue = null;
68
+ var currentOptions = [];
69
+
70
+ // Guards against a real race: Python's render responses arrive
71
+ // asynchronously and, under rapid clicking, multiple can end up queued
72
+ // server-side and arrive back OUT OF ORDER -- a stale response from an
73
+ // earlier click landing AFTER a newer click's own local update. Without
74
+ // this guard, that stale response's render() call would silently
75
+ // overwrite the newer local click with old data -- confirmed as the
76
+ // actual remaining cause of "orange dot needs a second click" under fast
77
+ // real clicking (my own slower automated testing never happened to
78
+ // trigger this ordering). While pendingValue is set, incoming renders
79
+ // that don't match it are assumed stale and ignored; the render that
80
+ // finally DOES match clears it. pendingTimeout is a safety net so a
81
+ // genuinely different Python-side change (e.g. a case switch resetting
82
+ // Frame) is never permanently ignored if no matching echo ever arrives.
83
+ var pendingValue = null;
84
+ var pendingTimeout = null;
85
+
86
+ function render(options, value) {
87
+ currentOptions = options;
88
+ currentValue = value;
89
+ root.innerHTML = "";
90
+ options.forEach(function(opt) {
91
+ var row = document.createElement("div");
92
+ row.className = "option" + (opt === value ? " selected" : "");
93
+ row.setAttribute("data-value", opt);
94
+
95
+ var dot = document.createElement("div");
96
+ dot.className = "dot";
97
+
98
+ var label = document.createElement("div");
99
+ label.className = "label";
100
+ label.textContent = opt;
101
+
102
+ row.appendChild(dot);
103
+ row.appendChild(label);
104
+ row.addEventListener("click", function() {
105
+ selectLocally(opt);
106
+ });
107
+ root.appendChild(row);
108
+ });
109
+ setFrameHeight();
110
+ }
111
+
112
+ function selectLocally(opt) {
113
+ // Instant, local, optimistic visual update -- happens synchronously in
114
+ // this click handler, with zero dependency on any Streamlit rerun
115
+ // completing. This is the actual fix: the dot can never visually lag,
116
+ // because nothing about its rendering waits on the Python round trip.
117
+ if (opt === currentValue) return;
118
+ currentValue = opt;
119
+ Array.prototype.forEach.call(root.children, function(row) {
120
+ row.className = "option" + (row.getAttribute("data-value") === opt ? " selected" : "");
121
+ });
122
+
123
+ pendingValue = opt;
124
+ if (pendingTimeout) { clearTimeout(pendingTimeout); }
125
+ pendingTimeout = setTimeout(function() {
126
+ // Safety net only -- see pendingValue's own comment. 2s is far
127
+ // longer than any real Streamlit rerun should ever take, so this
128
+ // firing means something unusual happened, not normal rapid
129
+ // clicking; resume trusting Python's renders again either way.
130
+ pendingValue = null;
131
+ pendingTimeout = null;
132
+ }, 2000);
133
+
134
+ sendValue(opt);
135
+ }
136
+
137
+ function sendValue(value) {
138
+ window.parent.postMessage({
139
+ isStreamlitMessage: true,
140
+ type: "streamlit:setComponentValue",
141
+ value: value,
142
+ dataType: "json",
143
+ }, "*");
144
+ }
145
+
146
+ function setFrameHeight() {
147
+ var height = root.scrollHeight;
148
+ window.parent.postMessage({
149
+ isStreamlitMessage: true,
150
+ type: "streamlit:setFrameHeight",
151
+ height: height,
152
+ }, "*");
153
+ }
154
+
155
+ window.addEventListener("message", function(event) {
156
+ // Verified against Streamlit's own streamlit-component-lib source
157
+ // (Streamlit.sendBackMsg): isStreamlitMessage:true is a field OUTGOING
158
+ // component->Streamlit messages add, not something Streamlit itself
159
+ // sets on the INCOMING streamlit:render event it sends to a component
160
+ // -- requiring it here silently discarded every real render message
161
+ // (confirmed live: the component's own root div stayed empty forever).
162
+ // Streamlit's real onMessageEvent only ever checks event.data["type"].
163
+ var data = event.data;
164
+ if (!data) return;
165
+ if (data.type === "streamlit:render") {
166
+ var args = (data.args || {});
167
+ var options = args.options || [];
168
+ var value = args.value;
169
+
170
+ if (pendingValue !== null) {
171
+ if (value !== pendingValue) {
172
+ // A stale, out-of-order echo of an OLDER click than the one
173
+ // we're currently waiting on -- discard it rather than let it
174
+ // overwrite the newer local state. See pendingValue's comment.
175
+ return;
176
+ }
177
+ // This render matches the click we were waiting on -- confirmed,
178
+ // Python has caught up. Stop waiting.
179
+ pendingValue = null;
180
+ if (pendingTimeout) { clearTimeout(pendingTimeout); pendingTimeout = null; }
181
+ }
182
+
183
+ render(options, value);
184
+ }
185
+ });
186
+
187
+ // Handshake: tell Streamlit this component is ready to receive renders.
188
+ window.parent.postMessage({
189
+ isStreamlitMessage: true,
190
+ type: "streamlit:componentReady",
191
+ apiVersion: 1,
192
+ }, "*");
193
+
194
+ setFrameHeight();
195
+ </script>
196
+ </body>
197
+ </html>
hf_sync.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # hf_sync.py
2
+ # Hugging Face review copy of Horos_Roundel_Mouse_2026_final.
3
+ #
4
+ # The Space's own disk is wiped on every restart, so the case data lives in a
5
+ # private Hugging Face dataset and this module:
6
+ # - downloads it once per container start (prepare_workspace),
7
+ # - builds the reviewer's working folders (cache/sv, results/sv) from the
8
+ # reviewer's last saved files in the dataset (sv/...) or, for a case the
9
+ # reviewer has not saved yet, from Wan's segmentation (wan/...),
10
+ # - uploads the reviewer's files back to sv/... on every save (push_*).
11
+ # Wan's own files (wan/..., data/wan/...) are only ever read, never written.
12
+ #
13
+ # Dataset layout:
14
+ # data/wan/image___<uid>.nii.gz, masks___<uid>.nii.gz, saxdf___<uid>.csv
15
+ # wan/cache/config___<uid>.json, masks___<uid>.npz Wan's segmentation
16
+ # wan/results/masks/<uid>.nii.gz, edited_sax_df/<uid>.csv
17
+ # sv/... same layout, written here
18
+ #
19
+ # Environment:
20
+ # HF_TOKEN write token (Space secret)
21
+ # HF_DATASET_REPO default wanhanisah/Horos_Roundel_Mouse_2026_review
22
+ # ROUNDEL_LOCAL_DATASET local folder used instead of the Hub (local testing)
23
+
24
+ import json
25
+ import os
26
+ import shutil
27
+ import tempfile
28
+ from pathlib import Path
29
+
30
+ import numpy as np
31
+ import streamlit as st
32
+
33
+ APP_DIR = Path(__file__).resolve().parent
34
+ ORIGINAL = "wan" # Wan's segmentation (read-only)
35
+ REVIEWER = "sv" # supervisor's working copy
36
+ DATASET_REPO = os.environ.get("HF_DATASET_REPO", "wanhanisah/Horos_Roundel_Mouse_2026_review")
37
+ LOCAL_DATASET = os.environ.get("ROUNDEL_LOCAL_DATASET", "").strip()
38
+
39
+ CACHE_DIR = APP_DIR / "cache" / REVIEWER
40
+ RESULTS_DIR = APP_DIR / "results" / REVIEWER
41
+
42
+
43
+ def _token():
44
+ return os.environ.get("HF_TOKEN") or None
45
+
46
+
47
+ def _copy_tree_files(src: Path, dst: Path, pattern: str):
48
+ dst.mkdir(parents=True, exist_ok=True)
49
+ if src.is_dir():
50
+ for p in src.glob(pattern):
51
+ shutil.copy2(p, dst / p.name)
52
+
53
+
54
+ @st.cache_resource(show_spinner="Downloading the case data (first start only)...")
55
+ def prepare_workspace() -> str:
56
+ """Download the dataset and build cache/sv + results/sv. Returns the
57
+ dataset folder (the images are read from <dataset>/data/wan directly)."""
58
+ if LOCAL_DATASET:
59
+ ds = Path(LOCAL_DATASET).resolve()
60
+ else:
61
+ from huggingface_hub import snapshot_download
62
+ ds = Path(snapshot_download(
63
+ repo_id=DATASET_REPO, repo_type="dataset", token=_token(),
64
+ local_dir=str(APP_DIR / "_hf_dataset"),
65
+ ))
66
+ if not (ds / "data" / ORIGINAL).is_dir():
67
+ raise FileNotFoundError(f"No data/{ORIGINAL} folder in the dataset ({ds}).")
68
+
69
+ # Configs (ED/ES frames), final masks and metrics: Wan's first, then the
70
+ # reviewer's saved ones on top. The big .npy edit masks are unpacked per
71
+ # case on first open (ensure_case_cache), not all at start-up.
72
+ for who in (ORIGINAL, REVIEWER):
73
+ _copy_tree_files(ds / who / "cache", CACHE_DIR, "config___*.json")
74
+ _copy_tree_files(ds / who / "results" / "masks", RESULTS_DIR / "masks", "*.nii.gz")
75
+ _copy_tree_files(ds / who / "results" / "edited_sax_df", RESULTS_DIR / "edited_sax_df", "*.csv")
76
+
77
+ # Notes / Status: the reviewer's own only (Wan's notes are not copied,
78
+ # so every case starts with an empty note and To-do status).
79
+ sv_db = ds / REVIEWER / "results" / "case_db.json"
80
+ if sv_db.exists():
81
+ shutil.copy2(sv_db, RESULTS_DIR / "case_db.json")
82
+ elif not (RESULTS_DIR / "case_db.json").exists():
83
+ (RESULTS_DIR / "case_db.json").write_text("{}")
84
+ return str(ds)
85
+
86
+
87
+ def _dataset_dir() -> Path:
88
+ return Path(prepare_workspace())
89
+
90
+
91
+ def _load_npz_mask(path: Path) -> np.ndarray:
92
+ with np.load(path) as z:
93
+ return z["mask"]
94
+
95
+
96
+ def ensure_case_cache(uid: str):
97
+ """Unpack this case's edit mask into cache/sv/masks___<uid>.npy (the file
98
+ the app reads and autosaves to) unless it is already there."""
99
+ out = CACHE_DIR / f"masks___{uid}.npy"
100
+ if out.exists():
101
+ return
102
+ ds = _dataset_dir()
103
+ for who in (REVIEWER, ORIGINAL):
104
+ src = ds / who / "cache" / f"masks___{uid}.npz"
105
+ if src.exists():
106
+ out.parent.mkdir(parents=True, exist_ok=True)
107
+ np.save(out, _load_npz_mask(src))
108
+ return
109
+
110
+
111
+ def load_original_mask(uid: str):
112
+ """Wan's saved segmentation for this case (what Reset Current Mask goes
113
+ back to), or None if there is none."""
114
+ src = _dataset_dir() / ORIGINAL / "cache" / f"masks___{uid}.npz"
115
+ return _load_npz_mask(src) if src.exists() else None
116
+
117
+
118
+ def _upload(files, message):
119
+ """files: list of (local Path, path in dataset). Returns (ok, message)."""
120
+ files = [(Path(a), b) for a, b in files if Path(a).exists()]
121
+ if not files:
122
+ return False, "nothing to upload"
123
+ try:
124
+ if LOCAL_DATASET:
125
+ ds = _dataset_dir()
126
+ for local, remote in files:
127
+ (ds / remote).parent.mkdir(parents=True, exist_ok=True)
128
+ shutil.copy2(local, ds / remote)
129
+ else:
130
+ from huggingface_hub import CommitOperationAdd, HfApi
131
+ HfApi(token=_token()).create_commit(
132
+ repo_id=DATASET_REPO, repo_type="dataset", commit_message=message,
133
+ operations=[CommitOperationAdd(path_in_repo=remote, path_or_fileobj=str(local))
134
+ for local, remote in files],
135
+ )
136
+ return True, f"uploaded {len(files)} file(s)"
137
+ except Exception as exc:
138
+ return False, str(exc)
139
+
140
+
141
+ def push_case(uid: str):
142
+ """Upload one case's saved mask, ED/ES config, final mask, metrics and the
143
+ notes file to sv/ in the dataset."""
144
+ with tempfile.TemporaryDirectory() as tmp:
145
+ files = []
146
+ npy = CACHE_DIR / f"masks___{uid}.npy"
147
+ if npy.exists():
148
+ npz = Path(tmp) / f"masks___{uid}.npz"
149
+ np.savez_compressed(npz, mask=np.load(npy))
150
+ files.append((npz, f"{REVIEWER}/cache/masks___{uid}.npz"))
151
+ files += [
152
+ (CACHE_DIR / f"config___{uid}.json", f"{REVIEWER}/cache/config___{uid}.json"),
153
+ (RESULTS_DIR / "masks" / f"{uid}.nii.gz", f"{REVIEWER}/results/masks/{uid}.nii.gz"),
154
+ (RESULTS_DIR / "edited_sax_df" / f"{uid}.csv", f"{REVIEWER}/results/edited_sax_df/{uid}.csv"),
155
+ (RESULTS_DIR / "case_db.json", f"{REVIEWER}/results/case_db.json"),
156
+ ]
157
+ return _upload(files, f"Supervisor review: save {uid}")
158
+
159
+
160
+ def push_case_db(uid: str = ""):
161
+ """Upload the notes/status file only."""
162
+ return _upload([(RESULTS_DIR / "case_db.json", f"{REVIEWER}/results/case_db.json")],
163
+ f"Supervisor review: notes/status {uid}".strip())
164
+
165
+
166
+ def push_all_results(uids):
167
+ """Upload every case's final mask + metrics, the combined metrics CSV and
168
+ the notes file (after Save All Masks and Metrics)."""
169
+ files = [(RESULTS_DIR / "case_db.json", f"{REVIEWER}/results/case_db.json"),
170
+ (RESULTS_DIR / "edited_sax_df" / "all_cases_metrics.csv",
171
+ f"{REVIEWER}/results/edited_sax_df/all_cases_metrics.csv")]
172
+ for uid in uids:
173
+ files += [
174
+ (RESULTS_DIR / "masks" / f"{uid}.nii.gz", f"{REVIEWER}/results/masks/{uid}.nii.gz"),
175
+ (RESULTS_DIR / "edited_sax_df" / f"{uid}.csv", f"{REVIEWER}/results/edited_sax_df/{uid}.csv"),
176
+ ]
177
+ return _upload(files, "Supervisor review: save all masks and metrics")
requirements.txt ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -----------------------------
2
+ # Core scientific stack
3
+ # -----------------------------
4
+ numpy==1.26.4
5
+ scipy==1.11.4
6
+ pandas==2.0.3
7
+ matplotlib==3.8.2
8
+
9
+ # -----------------------------
10
+ # Medical imaging
11
+ # -----------------------------
12
+ nibabel==5.2.1
13
+ pydicom==2.4.4
14
+
15
+ # -----------------------------
16
+ # Image processing
17
+ # -----------------------------
18
+ opencv-python-headless==4.9.0.80
19
+ Pillow==10.2.0
20
+ imageio==2.33.1
21
+
22
+ # -----------------------------
23
+ # ML / utilities
24
+ # -----------------------------
25
+ scikit-image==0.22.0
26
+ scikit-learn==1.3.2
27
+ tqdm==4.66.1
28
+
29
+ # -----------------------------
30
+ # DICOM compression (optional but safe)
31
+ # -----------------------------
32
+ pylibjpeg==1.4.0
33
+ pylibjpeg-libjpeg==1.3.4
34
+ pylibjpeg-openjpeg==1.3.2
35
+
36
+ # -----------------------------
37
+ # Streamlit app
38
+ # -----------------------------
39
+ streamlit==1.40.1
40
+ streamlit-drawable-canvas==0.9.3
41
+
42
+ # -----------------------------
43
+ # Hugging Face dataset download/upload (hf_sync.py)
44
+ # -----------------------------
45
+ huggingface_hub==0.26.2
46
+
47
+ # -----------------------------
48
+ # Compatibility fixes
49
+ # -----------------------------
50
+ protobuf>=3.20,<5
roundel_app_biventricular.py ADDED
@@ -0,0 +1,769 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # roundel_app_biventricular.py
2
+ # python3.10 -m streamlit run roundel_app_biventricular.py
3
+
4
+ import streamlit as st
5
+
6
+ # Hugging Face review copy: set before the utils import, which downloads the
7
+ # dataset on first start and shows a spinner while it does (set_page_config
8
+ # must be the first Streamlit call).
9
+ st.set_page_config(page_title="Roundel (Biventricular)", page_icon="⭕️", layout="wide")
10
+
11
+ from roundel_biventricular_utils import *
12
+ # Explicit named import: `import *` silently drops underscore-prefixed
13
+ # names (no __all__ is defined in that module), so this helper -- used
14
+ # by the Save Masks and Metrics handler below to keep the cache in sync
15
+ # -- would otherwise raise NameError at runtime the first time it's
16
+ # actually called (confirmed live: it did, for every app this fix was
17
+ # applied to, silently leaving the cache-sync half of that fix dead).
18
+ from roundel_biventricular_utils import _save_current_combined_mask_to_cache
19
+ import hf_sync
20
+
21
+
22
+ all_sax_series_uid_list = sorted([
23
+ uid.replace("image___", "").split("/")[-1].replace(".nii.gz", "")
24
+ for uid in glob.glob(f"{data_path}/*") if "image" in uid
25
+ ])
26
+
27
+ if len(all_sax_series_uid_list) == 0:
28
+ st.error("No cases found in data folder.")
29
+ st.stop()
30
+
31
+ st.write("# Roundel App (2D Biventricular) — Supervisor Review")
32
+ st.caption(
33
+ "Edits in the Mask Editor are kept only after **Save Masks and Metrics 💾** "
34
+ "(Final Result tab) or **Save All Masks and Metrics 💾**. Notes are kept after **Save note**."
35
+ )
36
+
37
+ filter_mode = st.radio(
38
+ "Filter",
39
+ options=["All", "To-do", "Complete"],
40
+ horizontal=True,
41
+ key="case_filter_mode",
42
+ )
43
+
44
+
45
+ def _is_done(uid: str) -> bool:
46
+ return bool(get_case_meta(uid).get("done", False))
47
+
48
+
49
+ if filter_mode == "To-do":
50
+ sax_series_uid_list = [u for u in all_sax_series_uid_list if not _is_done(u)]
51
+ elif filter_mode == "Complete":
52
+ sax_series_uid_list = [u for u in all_sax_series_uid_list if _is_done(u)]
53
+ else:
54
+ sax_series_uid_list = list(all_sax_series_uid_list)
55
+
56
+ if len(sax_series_uid_list) == 0:
57
+ st.success("No cases in this view.")
58
+ st.info("Switch filter to **All** or **Complete** to select a case.")
59
+ st.stop()
60
+
61
+ col1, col2 = st.columns([0.35, 0.65])
62
+
63
+ with col1:
64
+ if "sax_series_uid_selectbox" not in st.session_state:
65
+ if "_pending_case_correction" in st.session_state:
66
+ # Set by the self-heal block below on the PREVIOUS rerun, right
67
+ # before it deleted this same key and forced a rerun -- re-seed
68
+ # here so the widget reopens on the case the user actually had
69
+ # selected, not silently fall back to the first option in the
70
+ # list. Higher priority than last_selection.json below.
71
+ _pending = st.session_state.pop("_pending_case_correction")
72
+ if _pending in sax_series_uid_list:
73
+ st.session_state["sax_series_uid_selectbox"] = _pending
74
+ if "sax_series_uid_selectbox" not in st.session_state:
75
+ # Reopen-on-last-case (ported from HGK/Hand1/ISO/Patches/
76
+ # External/Diabetic/TAC_T7/ISOExtra_2, 2026-08-07/2026-09-22):
77
+ # only seeds session_state the first time this widget's key is
78
+ # created in a session, and only when the saved case is
79
+ # actually present in the CURRENT filtered list (e.g. still
80
+ # matches the active Status filter).
81
+ _last_selection = load_last_selection()
82
+ if _last_selection.get("sax_series_uid") in sax_series_uid_list:
83
+ st.session_state["sax_series_uid_selectbox"] = _last_selection["sax_series_uid"]
84
+
85
+ # Recorded BEFORE the widget call so the self-heal check below has
86
+ # something trustworthy to compare against.
87
+ _expected_sax_series_uid = st.session_state.get("sax_series_uid_selectbox")
88
+
89
+ sax_series_uid = st.selectbox(
90
+ "Select SAX Series UID",
91
+ options=sax_series_uid_list,
92
+ format_func=lambda uid: build_case_label(uid),
93
+ key="sax_series_uid_selectbox",
94
+ )
95
+
96
+ # Self-heal: same fix already applied in HGK/Hand1/ISO/Patches/External/
97
+ # Diabetic/TAC T7 (2026-09-16/22) -- this widget can silently reset
98
+ # itself to a different, earlier case on the SAME rerun that a
99
+ # completely different widget's on_change/button callback fires (e.g.
100
+ # clicking "Save note"). The unconditional index=0 previously passed on
101
+ # every rerun above was the actual cause (it kept re-asserting "first
102
+ # case" as the widget's default instead of letting session_state[key]
103
+ # simply persist); this self-heal is the same safety net the other apps
104
+ # carry in case Streamlit's own widget-state quirks resurface it some
105
+ # other way. Streamlit forbids reassigning an already-instantiated
106
+ # widget's session_state key directly (raises StreamlitAPIException),
107
+ # so this deletes the key instead and reruns, letting Streamlit re-seed
108
+ # it from the CURRENT session_state value (still intact under a
109
+ # different variable name) next pass.
110
+ if (
111
+ _expected_sax_series_uid is not None
112
+ and _expected_sax_series_uid in sax_series_uid_list
113
+ and sax_series_uid != _expected_sax_series_uid
114
+ ):
115
+ del st.session_state["sax_series_uid_selectbox"]
116
+ st.session_state["_pending_case_correction"] = _expected_sax_series_uid
117
+ st.rerun()
118
+
119
+ # Persist this case as "last used" for next launch -- only writes to
120
+ # disk when the selection actually changed (tracked via session_state),
121
+ # not on every unrelated rerun (e.g. dragging Slice Index in the Mask
122
+ # Editor also reruns this script from the top). `subdir` is this app's
123
+ # fixed single dataset ("wan") -- see load_last_selection/
124
+ # save_last_selection's own docstrings for why it's still passed
125
+ # explicitly.
126
+ if st.session_state.get("_last_persisted_selection") != (subdir, sax_series_uid):
127
+ save_last_selection(subdir, sax_series_uid)
128
+ st.session_state["_last_persisted_selection"] = (subdir, sax_series_uid)
129
+
130
+ if st.button("Save All Masks and Metrics 💾", type="primary", use_container_width=True):
131
+ progress = st.progress(0.0)
132
+ status = st.empty()
133
+
134
+ def _batch_progress(done, total, uid):
135
+ progress.progress(float(done) / float(total) if total else 1.0)
136
+ if uid:
137
+ status.caption(f"Saving {done + 1}/{total}: {uid}")
138
+
139
+ with st.spinner("Saving all masks and metrics..."):
140
+ batch_result = save_all_masks_and_metrics(
141
+ all_sax_series_uid_list,
142
+ backup=True,
143
+ progress_callback=_batch_progress,
144
+ )
145
+
146
+ saved_count = len(batch_result["saved"])
147
+ skipped_count = len(batch_result["skipped"])
148
+ failed_count = len(batch_result["failed"])
149
+ st.success(f"Saved {saved_count} cases. Skipped {skipped_count}. Failed {failed_count}.")
150
+
151
+ # Hugging Face review copy: upload the saved masks + metrics to the
152
+ # dataset (the Space's own disk is wiped on restart).
153
+ with st.spinner("Uploading to the Hugging Face dataset..."):
154
+ _ok, _msg = hf_sync.push_all_results(batch_result["saved"])
155
+ if _ok:
156
+ st.caption(f"Saved to Hugging Face ({_msg}).")
157
+ else:
158
+ st.error(f"Could not upload to Hugging Face: {_msg}")
159
+
160
+ if batch_result.get("all_metrics_path"):
161
+ st.caption(f"Combined metrics: {batch_result['all_metrics_path']}")
162
+
163
+ if skipped_count > 0:
164
+ with st.expander("Skipped cases"):
165
+ st.dataframe(pd.DataFrame(batch_result["skipped"]), use_container_width=True)
166
+
167
+ if failed_count > 0:
168
+ with st.expander("Failed cases"):
169
+ st.dataframe(pd.DataFrame(batch_result["failed"]), use_container_width=True)
170
+
171
+
172
+ initialize_app(data_path, sax_series_uid, N, preprocess=True)
173
+
174
+ pixelspacing = st.session_state.raw["pixelspacing"]
175
+ thickness = st.session_state.raw["thickness"]
176
+
177
+ # Frame interval is read/calculated in roundel_biventricular_utils.py.
178
+ # It is used for TVC and dV/dt timing.
179
+ # Display stays clean: no fallback warning/caption is shown in the app.
180
+ frame_interval_ms = st.session_state.raw.get("frame_interval_ms", DEFAULT_FRAME_INTERVAL_MS)
181
+ frame_interval_source = st.session_state.raw.get("frame_interval_source", "fallback_default")
182
+ frame_interval_is_fallback = bool(st.session_state.raw.get("frame_interval_is_fallback", True))
183
+
184
+
185
+ def _save_note_callback(uid: str):
186
+ key = f"case_note__{uid}"
187
+ note_val = st.session_state.get(key, "")
188
+ set_case_meta(uid, note=note_val)
189
+ return hf_sync.push_case_db(uid)
190
+
191
+
192
+ def _save_done_callback(uid: str):
193
+ key = f"case_done__{uid}"
194
+ done_val = bool(st.session_state.get(key, False))
195
+ set_case_meta(uid, done=done_val)
196
+ hf_sync.push_case_db(uid)
197
+
198
+
199
+ with col2:
200
+ # Clean display only: no "fallback" label, no warning box, no source caption.
201
+ frame_interval_label = f"{frame_interval_ms:.3g} ms"
202
+
203
+ # Display-only rounding: this app's saxdf___*.csv pixelspacing comes
204
+ # from the NIfTI conversion pipeline with full float precision (e.g.
205
+ # 0.1171874761581421), unlike the DICOM-native Preclinical apps whose
206
+ # PixelSpacing tag is already a clean round value -- per explicit
207
+ # request, shown here rounded to 1 decimal place for a matching clean
208
+ # display. The actual `pixelspacing` variable used in every volume/SV
209
+ # calculation below is completely untouched (still full precision) --
210
+ # only this label's text changes.
211
+ pixelspacing_label = f"{pixelspacing:.1f}"
212
+
213
+ st.markdown(
214
+ f"**Pixel Size**: {pixelspacing_label} x {pixelspacing_label} mm | "
215
+ f"**Slice Thickness**: {thickness} mm | "
216
+ f"**Frame Interval**: {frame_interval_label}"
217
+ )
218
+
219
+ meta = get_case_meta(sax_series_uid)
220
+ note_default = meta.get("note", "")
221
+ done_default = bool(meta.get("done", False))
222
+
223
+ note_key = f"case_note__{sax_series_uid}"
224
+ done_key = f"case_done__{sax_series_uid}"
225
+
226
+ # If the bottom "Save Masks and Metrics" just marked this case complete, tick the
227
+ # checkbox by setting its session_state BEFORE the widget is created. A widget-owned
228
+ # key cannot be assigned after the widget is instantiated (that was the crash).
229
+ if st.session_state.get("_pending_mark_done_uid") == sax_series_uid:
230
+ st.session_state.pop("_pending_mark_done_uid", None)
231
+ done_default = True
232
+ st.session_state[done_key] = True
233
+
234
+ if note_key not in st.session_state:
235
+ st.session_state[note_key] = note_default
236
+ if done_key not in st.session_state:
237
+ st.session_state[done_key] = done_default
238
+
239
+ st.checkbox(
240
+ "Status: Complete",
241
+ key=done_key,
242
+ on_change=_save_done_callback,
243
+ args=(sax_series_uid,),
244
+ )
245
+
246
+ st.text_area(
247
+ "Notes",
248
+ key=note_key,
249
+ height=90,
250
+ placeholder="Type notes for this case…",
251
+ )
252
+
253
+ col_save_note, col_meta = st.columns([0.2, 0.8])
254
+ with col_save_note:
255
+ if st.button("Save note", use_container_width=True, key=f"save_note_btn__{sax_series_uid}"):
256
+ _note_ok, _note_msg = _save_note_callback(sax_series_uid)
257
+ if not _note_ok:
258
+ st.error(f"Note saved here but could not upload to Hugging Face: {_note_msg}")
259
+ else:
260
+ try:
261
+ st.toast("Note saved ✅")
262
+ except Exception:
263
+ st.success("Note saved ✅")
264
+
265
+ with col_meta:
266
+ db = load_case_db()
267
+ updated_at = db.get(sax_series_uid, {}).get("updated_at", None)
268
+ if updated_at:
269
+ st.caption(f"Last saved: {updated_at} (UTC)")
270
+
271
+ view = st.segmented_control(
272
+ "Tab",
273
+ options=["EDV/ESV Finder 🔍", "Mask Editor 📝", "Final Result ✅"],
274
+ default="EDV/ESV Finder 🔍",
275
+ label_visibility="hidden",
276
+ )
277
+ st.divider()
278
+
279
+ if view == "EDV/ESV Finder 🔍":
280
+ edv_esv_view()
281
+
282
+ if view == "Mask Editor 📝":
283
+ mask_editor_view()
284
+
285
+ if view == "Final Result ✅":
286
+ raw = st.session_state.raw
287
+ preprocessed = st.session_state.preprocessed
288
+
289
+ raw_image = raw["image"]
290
+ raw_mask = raw["mask"]
291
+ preprocessed_image = preprocessed["image"]
292
+
293
+ D, T, N_ = preprocessed["D"], preprocessed["T"], preprocessed["N"]
294
+ crop_box = preprocessed["crop_box"]
295
+
296
+ if not st.session_state.edv_esv_selected["confirmed"]:
297
+ st.error("Select and confirm EDV/ESV first.")
298
+ st.stop()
299
+
300
+ raw_lv_dia_idx = raw["raw_lv_dia_idx"]
301
+ raw_lv_sys_idx = raw["raw_lv_sys_idx"]
302
+ raw_rv_dia_idx = raw["raw_rv_dia_idx"]
303
+ raw_rv_sys_idx = raw["raw_rv_sys_idx"]
304
+
305
+ lv_dia_idx = int(st.session_state["edv_esv_selected"]["lv_dia_idx"])
306
+ lv_sys_idx = int(st.session_state["edv_esv_selected"]["lv_sys_idx"])
307
+ rv_dia_idx = int(st.session_state["edv_esv_selected"]["rv_dia_idx"])
308
+ rv_sys_idx = int(st.session_state["edv_esv_selected"]["rv_sys_idx"])
309
+
310
+ final_lv_gif_path = f"results/{subdir}/gifs/{sax_series_uid}_lv.gif"
311
+ final_rv_gif_path = f"results/{subdir}/gifs/{sax_series_uid}_rv.gif"
312
+ final_lv_tvc_dvdt_gif_path = f"results/{subdir}/gifs/{sax_series_uid}_lv_TVC_dVdt.gif"
313
+ final_rv_tvc_dvdt_gif_path = f"results/{subdir}/gifs/{sax_series_uid}_rv_TVC_dVdt.gif"
314
+
315
+ # Downsample edited masks from subpixel editor resolution back to native/preprocessed resolution.
316
+ lv_mask = cv_zoom(
317
+ st.session_state["edited_mask_lv"],
318
+ zoom=[
319
+ 1 / st.session_state["subpixel_resolution"],
320
+ 1 / st.session_state["subpixel_resolution"],
321
+ 1,
322
+ 1,
323
+ ],
324
+ interpolation=cv2.INTER_NEAREST,
325
+ )
326
+ rv_mask = cv_zoom(
327
+ st.session_state["edited_mask_rv"],
328
+ zoom=[
329
+ 1 / st.session_state["subpixel_resolution"],
330
+ 1 / st.session_state["subpixel_resolution"],
331
+ 1,
332
+ 1,
333
+ ],
334
+ interpolation=cv2.INTER_NEAREST,
335
+ )
336
+
337
+ combined_mask = merge_masks(lv_mask, rv_mask)
338
+
339
+ lv_metrics = calculate_sax_metrics(
340
+ mask=combined_mask,
341
+ pixelspacing=pixelspacing,
342
+ thickness=thickness,
343
+ blood_pool_idx=lv_idx,
344
+ myo_idx=lv_myo_idx,
345
+ dia_idx=lv_dia_idx,
346
+ sys_idx=lv_sys_idx,
347
+ )
348
+ raw_lv_metrics = calculate_sax_metrics(
349
+ mask=raw_mask,
350
+ pixelspacing=pixelspacing,
351
+ thickness=thickness,
352
+ blood_pool_idx=lv_idx,
353
+ myo_idx=lv_myo_idx,
354
+ dia_idx=raw_lv_dia_idx,
355
+ sys_idx=raw_lv_sys_idx,
356
+ )
357
+
358
+ rv_metrics = calculate_sax_metrics(
359
+ mask=combined_mask,
360
+ pixelspacing=pixelspacing,
361
+ thickness=thickness,
362
+ blood_pool_idx=rv_idx,
363
+ myo_idx=rv_myo_idx,
364
+ dia_idx=rv_dia_idx,
365
+ sys_idx=rv_sys_idx,
366
+ )
367
+ raw_rv_metrics = calculate_sax_metrics(
368
+ mask=raw_mask,
369
+ pixelspacing=pixelspacing,
370
+ thickness=thickness,
371
+ blood_pool_idx=rv_idx,
372
+ myo_idx=rv_myo_idx,
373
+ dia_idx=raw_rv_dia_idx,
374
+ sys_idx=raw_rv_sys_idx,
375
+ )
376
+ sv_qc = calculate_sv_difference_qc(lv_metrics["sv_ul"], rv_metrics["sv_ul"])
377
+
378
+ x_min, y_min, x_max, y_max = crop_box
379
+
380
+ # Build the final full-size label mask in original raw-image space.
381
+ # raw_mask is one-hot: H, W, D, T, C.
382
+ final_mask_onehot = np.zeros_like(raw_mask, dtype=np.uint8)
383
+ final_mask_onehot[y_min:y_max, x_min:x_max, :, :, :] = combined_mask.astype(np.uint8)
384
+ final_label_mask = np.argmax(final_mask_onehot, axis=-1).astype(np.uint8)
385
+
386
+ # Hash used to avoid stale GIFs and avoid regenerating unnecessarily on every Streamlit rerun.
387
+ # Includes a version string so changes to dV/dt units / all-frame GIF logic force regeneration.
388
+ #
389
+ # frame_interval_source and frame_interval_is_fallback are kept internally/exported,
390
+ # but they are not shown in the app display.
391
+ final_result_hash = mask_hash(combined_mask) + (
392
+ f"__lvED{lv_dia_idx}_lvES{lv_sys_idx}"
393
+ f"__rvED{rv_dia_idx}_rvES{rv_sys_idx}"
394
+ f"__dt{frame_interval_ms:.6f}"
395
+ f"__src{frame_interval_source}"
396
+ f"__legend{bool(SHOW_PROGRESSIVE_FIGURE_LEGEND)}"
397
+ f"__curvline{bool(SHOW_PROGRESSIVE_CURRENT_FRAME_VLINE)}"
398
+ f"__fullcycleaxis{bool(SHOW_PROGRESSIVE_FULL_CYCLE_TIME_AXIS)}"
399
+ f"__axpad{float(PROGRESSIVE_TIME_AXIS_PADDING_FRAME_FRACTION):.3f}"
400
+ f"__v{FINAL_RESULT_GIF_VERSION}"
401
+ )
402
+
403
+ needs_final_regen = (
404
+ st.session_state.get("final_result_hash") != final_result_hash
405
+ or not os.path.exists(final_lv_gif_path)
406
+ or not os.path.exists(final_rv_gif_path)
407
+ or not os.path.exists(final_lv_tvc_dvdt_gif_path)
408
+ or not os.path.exists(final_rv_tvc_dvdt_gif_path)
409
+ )
410
+
411
+ if needs_final_regen:
412
+ with st.spinner("Generating final LV/RV masks and TVC/dVdt GIFs..."):
413
+ # ----------------------------------------------------------
414
+ # Final ED/ES mask GIFs
415
+ # ----------------------------------------------------------
416
+ # IMPORTANT FIX:
417
+ # Final LV Mask should show LV-only overlay.
418
+ # Final RV Mask should show RV-only overlay.
419
+ make_video(
420
+ preprocessed_image,
421
+ final_label_mask[y_min:y_max, x_min:x_max, :, :],
422
+ save_file=final_lv_gif_path,
423
+ mask_frames=[lv_dia_idx, lv_sys_idx],
424
+ ventricle="lv",
425
+ )
426
+ make_video(
427
+ preprocessed_image,
428
+ final_label_mask[y_min:y_max, x_min:x_max, :, :],
429
+ save_file=final_rv_gif_path,
430
+ mask_frames=[rv_dia_idx, rv_sys_idx],
431
+ ventricle="rv",
432
+ )
433
+
434
+ # ----------------------------------------------------------
435
+ # Progressive TVC + dV/dt + montage GIFs
436
+ # ----------------------------------------------------------
437
+ # IMPORTANT:
438
+ # These GIFs use ALL frames, not only ED/ES.
439
+ # The function loops through f = 0 ... T-1 internally.
440
+ #
441
+ # LV GIF uses LV blood pool only for TVC/dVdt and LV overlay only.
442
+ make_progressive_tvc_dvdt_montage_gif(
443
+ image=preprocessed_image,
444
+ mask=combined_mask,
445
+ save_file=final_lv_tvc_dvdt_gif_path,
446
+ pixelspacing=pixelspacing,
447
+ thickness=thickness,
448
+ ventricle="lv",
449
+ frame_interval_ms=frame_interval_ms,
450
+ fps=FINAL_RESULT_GIF_FPS,
451
+ ed_frame_idx=lv_dia_idx,
452
+ es_frame_idx=lv_sys_idx,
453
+ show_figure_legend=SHOW_PROGRESSIVE_FIGURE_LEGEND,
454
+ show_current_frame_vline=SHOW_PROGRESSIVE_CURRENT_FRAME_VLINE,
455
+ )
456
+
457
+ # RV GIF uses RV blood pool only for TVC/dVdt and RV overlay only.
458
+ make_progressive_tvc_dvdt_montage_gif(
459
+ image=preprocessed_image,
460
+ mask=combined_mask,
461
+ save_file=final_rv_tvc_dvdt_gif_path,
462
+ pixelspacing=pixelspacing,
463
+ thickness=thickness,
464
+ ventricle="rv",
465
+ frame_interval_ms=frame_interval_ms,
466
+ fps=FINAL_RESULT_GIF_FPS,
467
+ ed_frame_idx=rv_dia_idx,
468
+ es_frame_idx=rv_sys_idx,
469
+ show_figure_legend=SHOW_PROGRESSIVE_FIGURE_LEGEND,
470
+ show_current_frame_vline=SHOW_PROGRESSIVE_CURRENT_FRAME_VLINE,
471
+ )
472
+
473
+ st.session_state["final_result_hash"] = final_result_hash
474
+
475
+ col_lv, _, col_rv = st.columns([1, 0.05, 1])
476
+
477
+ with col_lv:
478
+ st.markdown("#### Left Ventricle")
479
+ colA, colB = st.columns([0.34, 0.66])
480
+
481
+ with colA:
482
+ st.caption("LV Metrics")
483
+ st.metric(
484
+ "EDV",
485
+ f"{lv_metrics['edv_ul']:.1f} µL",
486
+ delta=format_delta(lv_metrics["edv_ul"], raw_lv_metrics["edv_ul"], " µL"),
487
+ )
488
+ st.metric(
489
+ "ESV",
490
+ f"{lv_metrics['esv_ul']:.1f} µL",
491
+ delta=format_delta(lv_metrics["esv_ul"], raw_lv_metrics["esv_ul"], " µL"),
492
+ )
493
+ st.metric(
494
+ "SV",
495
+ f"{lv_metrics['sv_ul']:.1f} µL",
496
+ delta=format_delta(lv_metrics["sv_ul"], raw_lv_metrics["sv_ul"], " µL"),
497
+ )
498
+ st.metric(
499
+ "EF",
500
+ f"{lv_metrics['ef_percent']:.1f} %",
501
+ delta=format_delta(
502
+ lv_metrics["ef_percent"],
503
+ raw_lv_metrics["ef_percent"],
504
+ "%",
505
+ round_digits=1,
506
+ ),
507
+ )
508
+ st.metric(
509
+ "Mass (ED)",
510
+ f"{lv_metrics['mass_ed_mg']:.1f} mg",
511
+ delta=format_delta(lv_metrics["mass_ed_mg"], raw_lv_metrics["mass_ed_mg"], " mg"),
512
+ )
513
+ st.metric(
514
+ "Mass (ES)",
515
+ f"{lv_metrics['mass_es_mg']:.1f} mg",
516
+ delta=format_delta(lv_metrics["mass_es_mg"], raw_lv_metrics["mass_es_mg"], " mg"),
517
+ )
518
+
519
+ if "tvc_result_lv" in st.session_state:
520
+ lv_tvc = st.session_state["tvc_result_lv"]
521
+ st.caption("LV Dynamic Indices")
522
+ st.metric("PER", f"{ul_per_s_to_ml_per_s(lv_tvc.get('per', np.nan)):.3f} mL/s")
523
+ st.metric("PFR", f"{ul_per_s_to_ml_per_s(lv_tvc.get('pfr', np.nan)):.3f} mL/s")
524
+
525
+ with colB:
526
+ st.caption("Final LV Mask")
527
+ show_gif_stable_synced(final_lv_gif_path, key=f"{sax_series_uid}_lv", use_container_width=True)
528
+
529
+ st.caption("LV Progressive TVC + dV/dt")
530
+ show_gif_stable_synced(final_lv_tvc_dvdt_gif_path, key=f"{sax_series_uid}_lv_tvc", use_container_width=True)
531
+
532
+ with col_rv:
533
+ st.markdown("#### Right Ventricle")
534
+ colA, colB = st.columns([0.34, 0.66])
535
+
536
+ with colA:
537
+ st.caption("RV Metrics")
538
+ st.metric(
539
+ "EDV",
540
+ f"{rv_metrics['edv_ul']:.1f} µL",
541
+ delta=format_delta(rv_metrics["edv_ul"], raw_rv_metrics["edv_ul"], " µL"),
542
+ )
543
+ st.metric(
544
+ "ESV",
545
+ f"{rv_metrics['esv_ul']:.1f} µL",
546
+ delta=format_delta(rv_metrics["esv_ul"], raw_rv_metrics["esv_ul"], " µL"),
547
+ )
548
+ st.metric(
549
+ "SV",
550
+ f"{rv_metrics['sv_ul']:.1f} µL",
551
+ delta=format_delta(rv_metrics["sv_ul"], raw_rv_metrics["sv_ul"], " µL"),
552
+ )
553
+ st.metric(
554
+ "EF",
555
+ f"{rv_metrics['ef_percent']:.1f} %",
556
+ delta=format_delta(
557
+ rv_metrics["ef_percent"],
558
+ raw_rv_metrics["ef_percent"],
559
+ "%",
560
+ round_digits=1,
561
+ ),
562
+ )
563
+ st.metric(
564
+ "Mass (ED)",
565
+ f"{rv_metrics['mass_ed_mg']:.1f} mg",
566
+ delta=format_delta(rv_metrics["mass_ed_mg"], raw_rv_metrics["mass_ed_mg"], " mg"),
567
+ )
568
+ st.metric(
569
+ "Mass (ES)",
570
+ f"{rv_metrics['mass_es_mg']:.1f} mg",
571
+ delta=format_delta(rv_metrics["mass_es_mg"], raw_rv_metrics["mass_es_mg"], " mg"),
572
+ )
573
+
574
+ if "tvc_result_rv" in st.session_state:
575
+ rv_tvc = st.session_state["tvc_result_rv"]
576
+ st.caption("RV Dynamic Indices")
577
+ st.metric("PER", f"{ul_per_s_to_ml_per_s(rv_tvc.get('per', np.nan)):.3f} mL/s")
578
+ st.metric("PFR", f"{ul_per_s_to_ml_per_s(rv_tvc.get('pfr', np.nan)):.3f} mL/s")
579
+
580
+ with colB:
581
+ st.caption("Final RV Mask")
582
+ show_gif_stable_synced(final_rv_gif_path, key=f"{sax_series_uid}_rv", use_container_width=True)
583
+
584
+ st.caption("RV Progressive TVC + dV/dt")
585
+ show_gif_stable_synced(final_rv_tvc_dvdt_gif_path, key=f"{sax_series_uid}_rv_tvc", use_container_width=True)
586
+
587
+ st.divider()
588
+ st.markdown("#### LV/RV Stroke Volume QC")
589
+ sv_qc_message = (
590
+ f"LV SV: {sv_qc['lv_sv_ul']:.1f} µL | "
591
+ f"RV SV: {sv_qc['rv_sv_ul']:.1f} µL | "
592
+ f"Difference: {sv_qc['sv_diff_ul']:.1f} µL "
593
+ f"({sv_qc['sv_diff_percent']:.1f}%) | "
594
+ f"Acceptable threshold: <{sv_qc['sv_diff_threshold_percent']:.1f}%"
595
+ )
596
+ if sv_qc["sv_diff_flag_gt_threshold"]:
597
+ st.error(f"⚠️ SV difference flag: {sv_qc_message}")
598
+ else:
599
+ st.success(f"✅ SV difference OK: {sv_qc_message}")
600
+
601
+ if st.button("Save Masks and Metrics 💾", type="primary", use_container_width=True):
602
+ # Staleness guard: refuse to overwrite if this case's cache file has
603
+ # changed since THIS session loaded it (recorded by initialize_app,
604
+ # see st.session_state["_cache_mtime_at_load"]). Real, confirmed
605
+ # failure mode this prevents: a second/stale browser tab or session,
606
+ # still holding an OLDER in-memory view of this case (e.g. left open
607
+ # from earlier, or never revisited after a newer edit was saved
608
+ # elsewhere), silently overwrites that newer edit -- with no error,
609
+ # since from that stale session's own perspective nothing looks
610
+ # wrong ("nothing edited, just re-saving to be safe"). Comparing the
611
+ # cache file's own mtime against what was recorded at load time is
612
+ # what actually catches this; the live view alone has no way to
613
+ # know it's stale.
614
+ _cache_path_now = st.session_state.get("cache_mask_path")
615
+ _mtime_at_load = st.session_state.get("_cache_mtime_at_load")
616
+ _mtime_now = (
617
+ os.path.getmtime(_cache_path_now)
618
+ if _cache_path_now and os.path.exists(_cache_path_now) else None
619
+ )
620
+ if _mtime_now != _mtime_at_load:
621
+ st.error(
622
+ "This case was saved from somewhere else (another tab/session, or a "
623
+ "different save) since you opened it here -- NOT saving, to avoid "
624
+ "overwriting that newer version with this possibly-outdated view. "
625
+ "Reselect this case (or reload the page) to load the current version, "
626
+ "then re-apply your edit if it's still needed.",
627
+ icon="🚫",
628
+ )
629
+ st.stop()
630
+
631
+ st.success("Masks and Metrics Saved!")
632
+ save_mask(final_label_mask, f"{results_path}/masks/{sax_series_uid}.nii.gz")
633
+ # Keep the per-case .npy cache byte-for-byte in sync with this save --
634
+ # "Save This Case + Horos JSON" and "Save All Masks and Metrics" both
635
+ # read from that cache (see save_final_mask_and_metrics_from_cache),
636
+ # not from this live view. Without this, the cache stays exactly as
637
+ # stale as this case's last manual paint edit, so those two buttons
638
+ # could silently write back an OLDER mask than what this save just
639
+ # persisted -- with no error or warning. This guarantees they can
640
+ # never disagree with what was just saved here.
641
+ _save_current_combined_mask_to_cache()
642
+
643
+ lv_tvc_result = st.session_state.get("tvc_result_lv", {})
644
+ rv_tvc_result = st.session_state.get("tvc_result_rv", {})
645
+
646
+ lv_df = pd.DataFrame({
647
+ "sax_series_uid": [sax_series_uid],
648
+ "chamber": ["LV"],
649
+ "ed_frame": [lv_dia_idx],
650
+ "es_frame": [lv_sys_idx],
651
+ "edv_ul": [lv_metrics["edv_ul"]],
652
+ "esv_ul": [lv_metrics["esv_ul"]],
653
+ "stroke_volume_ul": [lv_metrics["sv_ul"]],
654
+ "ejection_fraction_percent": [lv_metrics["ef_percent"]],
655
+ "mass_ed_mg": [lv_metrics["mass_ed_mg"]],
656
+ "mass_es_mg": [lv_metrics["mass_es_mg"]],
657
+
658
+ # Internally PER/PFR are computed in µL/s.
659
+ # For reporting/export, mL/s is cleaner for dV/dt-style dynamic indices.
660
+ "per_ml_per_s": [ul_per_s_to_ml_per_s(lv_tvc_result.get("per", np.nan))],
661
+ "pfr_ml_per_s": [ul_per_s_to_ml_per_s(lv_tvc_result.get("pfr", np.nan))],
662
+ "per_signed_ml_per_s": [ul_per_s_to_ml_per_s(lv_tvc_result.get("per_signed", np.nan))],
663
+ "pfr_signed_ml_per_s": [ul_per_s_to_ml_per_s(lv_tvc_result.get("pfr_signed", np.nan))],
664
+
665
+ # Also keep raw µL/s columns for traceability/backward compatibility.
666
+ "per_ul_per_s": [lv_tvc_result.get("per", np.nan)],
667
+ "pfr_ul_per_s": [lv_tvc_result.get("pfr", np.nan)],
668
+ "per_signed_ul_per_s": [lv_tvc_result.get("per_signed", np.nan)],
669
+ "pfr_signed_ul_per_s": [lv_tvc_result.get("pfr_signed", np.nan)],
670
+
671
+ "per_time_ms": [
672
+ lv_tvc_result.get("per_time_s", np.nan) * 1000.0
673
+ if "per_time_s" in lv_tvc_result else np.nan
674
+ ],
675
+ "pfr_time_ms": [
676
+ lv_tvc_result.get("pfr_time_s", np.nan) * 1000.0
677
+ if "pfr_time_s" in lv_tvc_result else np.nan
678
+ ],
679
+ "frame_interval_ms": [frame_interval_ms],
680
+ "frame_interval_source": [frame_interval_source],
681
+ "frame_interval_is_fallback": [frame_interval_is_fallback],
682
+ "pixelspacing_mm": [pixelspacing],
683
+ "thickness_mm": [thickness],
684
+ "voxel_volume_ul": [voxel_volume_ul(pixelspacing, thickness)],
685
+ "num_slices": [lv_mask.shape[2]],
686
+ "num_frames": [lv_mask.shape[3]],
687
+ "lv_sv_ul_for_qc": [sv_qc["lv_sv_ul"]],
688
+ "rv_sv_ul_for_qc": [sv_qc["rv_sv_ul"]],
689
+ "sv_diff_ul": [sv_qc["sv_diff_ul"]],
690
+ "sv_diff_percent": [sv_qc["sv_diff_percent"]],
691
+ "sv_diff_threshold_percent": [sv_qc["sv_diff_threshold_percent"]],
692
+ "sv_diff_flag_gt_threshold": [sv_qc["sv_diff_flag_gt_threshold"]],
693
+ })
694
+
695
+ rv_df = pd.DataFrame({
696
+ "sax_series_uid": [sax_series_uid],
697
+ "chamber": ["RV"],
698
+ "ed_frame": [rv_dia_idx],
699
+ "es_frame": [rv_sys_idx],
700
+ "edv_ul": [rv_metrics["edv_ul"]],
701
+ "esv_ul": [rv_metrics["esv_ul"]],
702
+ "stroke_volume_ul": [rv_metrics["sv_ul"]],
703
+ "ejection_fraction_percent": [rv_metrics["ef_percent"]],
704
+ "mass_ed_mg": [rv_metrics["mass_ed_mg"]],
705
+ "mass_es_mg": [rv_metrics["mass_es_mg"]],
706
+
707
+ # Internally PER/PFR are computed in µL/s.
708
+ # For reporting/export, mL/s is cleaner for dV/dt-style dynamic indices.
709
+ "per_ml_per_s": [ul_per_s_to_ml_per_s(rv_tvc_result.get("per", np.nan))],
710
+ "pfr_ml_per_s": [ul_per_s_to_ml_per_s(rv_tvc_result.get("pfr", np.nan))],
711
+ "per_signed_ml_per_s": [ul_per_s_to_ml_per_s(rv_tvc_result.get("per_signed", np.nan))],
712
+ "pfr_signed_ml_per_s": [ul_per_s_to_ml_per_s(rv_tvc_result.get("pfr_signed", np.nan))],
713
+
714
+ # Also keep raw µL/s columns for traceability/backward compatibility.
715
+ "per_ul_per_s": [rv_tvc_result.get("per", np.nan)],
716
+ "pfr_ul_per_s": [rv_tvc_result.get("pfr", np.nan)],
717
+ "per_signed_ul_per_s": [rv_tvc_result.get("per_signed", np.nan)],
718
+ "pfr_signed_ul_per_s": [rv_tvc_result.get("pfr_signed", np.nan)],
719
+
720
+ "per_time_ms": [
721
+ rv_tvc_result.get("per_time_s", np.nan) * 1000.0
722
+ if "per_time_s" in rv_tvc_result else np.nan
723
+ ],
724
+ "pfr_time_ms": [
725
+ rv_tvc_result.get("pfr_time_s", np.nan) * 1000.0
726
+ if "pfr_time_s" in rv_tvc_result else np.nan
727
+ ],
728
+ "frame_interval_ms": [frame_interval_ms],
729
+ "frame_interval_source": [frame_interval_source],
730
+ "frame_interval_is_fallback": [frame_interval_is_fallback],
731
+ "pixelspacing_mm": [pixelspacing],
732
+ "thickness_mm": [thickness],
733
+ "voxel_volume_ul": [voxel_volume_ul(pixelspacing, thickness)],
734
+ "num_slices": [rv_mask.shape[2]],
735
+ "num_frames": [rv_mask.shape[3]],
736
+ "lv_sv_ul_for_qc": [sv_qc["lv_sv_ul"]],
737
+ "rv_sv_ul_for_qc": [sv_qc["rv_sv_ul"]],
738
+ "sv_diff_ul": [sv_qc["sv_diff_ul"]],
739
+ "sv_diff_percent": [sv_qc["sv_diff_percent"]],
740
+ "sv_diff_threshold_percent": [sv_qc["sv_diff_threshold_percent"]],
741
+ "sv_diff_flag_gt_threshold": [sv_qc["sv_diff_flag_gt_threshold"]],
742
+ })
743
+
744
+ combined_df = pd.concat([lv_df, rv_df], ignore_index=True)
745
+ combined_df.to_csv(f"{results_path}/edited_sax_df/{sax_series_uid}.csv", index=False)
746
+
747
+ # Hugging Face review copy: saving does NOT mark the case complete --
748
+ # the supervisor ticks "Status: Complete" themselves when done.
749
+
750
+ # Hugging Face review copy: upload this case's mask, ED/ES frames,
751
+ # metrics and notes to the dataset (the Space's own disk is wiped on
752
+ # restart, so this is what keeps the edit).
753
+ with st.spinner("Uploading to the Hugging Face dataset..."):
754
+ _ok, _msg = hf_sync.push_case(sax_series_uid)
755
+ if _ok:
756
+ st.caption(f"Saved to Hugging Face ({_msg}).")
757
+ else:
758
+ st.error(f"Could not upload to Hugging Face -- this edit is NOT kept after a restart: {_msg}")
759
+ st.session_state["saved"] = True
760
+
761
+ if st.session_state.get("saved", False):
762
+ if st.button("Next Patient ➡️", use_container_width=True):
763
+ try:
764
+ cur_idx = sax_series_uid_list.index(sax_series_uid)
765
+ next_idx = (cur_idx + 1) % len(sax_series_uid_list)
766
+ st.session_state["sax_series_uid_selectbox"] = sax_series_uid_list[next_idx]
767
+ except Exception:
768
+ pass
769
+ st.rerun()
roundel_biventricular_utils.py ADDED
The diff for this file is too large to render. See raw diff