MesserMMP commited on
Commit
1024e04
·
verified ·
1 Parent(s): 493dec4

Rebuild CardioSyntax with custom bilingual UI and verified inference

Browse files

Replace legacy weight discovery with pinned, checksum-verified checkpoints and fold calibration. Add study review, full cine playback, explicit artery assignment, ordered projection inputs, bounded upload jobs and public examples. Preserve existing hardware configuration.

.DS_Store DELETED
Binary file (8.2 kB)
 
.dockerignore ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .git
2
+ __pycache__
3
+ .pytest_cache
4
+ *.pyc
5
+ .env
6
+ .venv
7
+ venv
8
+ weights
9
+ model-cache
10
+ fixtures
11
+ tests
12
+ *.log
13
+ .DS_Store
14
+ static/design-preview.html
15
+ static/design-fixture.json
16
+ static/assets/
.gitignore CHANGED
@@ -1,74 +1,13 @@
1
- # --- Python & venv ---
2
  __pycache__/
3
- *.py[cod]
4
- *.pyo
5
- *.pyd
6
- *.so
7
- *.egg-info/
8
  .env
9
  .venv/
10
- venv/
11
- env/
12
- .ipynb_checkpoints/
13
  *.log
14
-
15
- # --- System files ---
16
  .DS_Store
17
- Thumbs.db
18
- *.swp
19
- *.tmp
20
- *.bak
21
-
22
- # --- IDE / Editors ---
23
- .vscode/
24
- .idea/
25
- *.sublime-workspace
26
- *.sublime-project
27
-
28
- # --- Build / cache ---
29
- build/
30
- dist/
31
- *.egg
32
- *.egg-info/
33
- .eggs/
34
- .cache/
35
- .pytest_cache/
36
- .hypothesis/
37
-
38
- # --- Data / artifacts ---
39
- weights/
40
- data/
41
- datasets/
42
- checkpoints/
43
- runs/
44
- lightning_logs/
45
- experiments/
46
- *.pt
47
- *.ckpt
48
- *.pth
49
- *.npz
50
- *.npy
51
- *.csv
52
- *.json
53
- *.zip
54
- *.tar
55
- *.tar.gz
56
- *.pkl
57
-
58
- # --- Gradio / HF specific ---
59
- gradio_cached_examples/
60
- gradio_tmp/
61
- outputs/
62
- tmp/
63
- uploads/
64
- logs/
65
- *.db
66
-
67
- # --- Jupyter ---
68
- .ipynb_checkpoints/
69
- *.ipynb
70
-
71
- # --- OS / backup ---
72
- *.bak
73
- *.old
74
- *~
 
 
1
  __pycache__/
2
+ .pytest_cache/
3
+ *.pyc
 
 
 
4
  .env
5
  .venv/
6
+ weights/
7
+ model-cache/
8
+ fixtures/
9
  *.log
 
 
10
  .DS_Store
11
+ static/design-preview.html
12
+ static/design-fixture.json
13
+ static/assets/
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Dockerfile ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.12-slim
2
+ RUN apt-get update && apt-get install -y --no-install-recommends ffmpeg \
3
+ && rm -rf /var/lib/apt/lists/*
4
+ RUN useradd --create-home --uid 1000 app
5
+ WORKDIR /app
6
+ ARG TORCH_INDEX_URL=https://download.pytorch.org/whl/cpu
7
+ RUN pip install --no-cache-dir torch==2.6.0 torchvision==0.21.0 --index-url ${TORCH_INDEX_URL}
8
+ COPY requirements.txt .
9
+ RUN pip install --no-cache-dir -r requirements.txt
10
+ COPY --chown=app:app . .
11
+ USER app
12
+ ENV HOME=/home/app PYTHONUNBUFFERED=1 HF_HOME=/home/app/.cache/huggingface \
13
+ SYNTAX_MODEL_CACHE=/home/app/.cache/cardiosyntax SYNTAX_DEVICE=cpu
14
+ EXPOSE 7860
15
+ CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860", "--workers", "1", "--no-access-log"]
README.md CHANGED
@@ -1,14 +1,13 @@
1
  ---
2
- title: SYNTAX-Video Inference
3
  emoji: 🫀
4
- colorFrom: indigo
5
- colorTo: blue
6
- sdk: gradio
7
- sdk_version: 5.49.1
8
- python_version: '3.11'
9
- app_file: app.py
10
  pinned: false
11
  license: apache-2.0
 
12
  tags:
13
  - medical-imaging
14
  - video
@@ -17,61 +16,83 @@ tags:
17
  - cardiology
18
  ---
19
 
20
- # 🫀 SYNTAX-Video — Multi-study Inference
21
 
22
- **SYNTAX-Video** — это интерфейс для автоматической оценки **SYNTAX-score** по видеозаписям коронарной ангиографии.
23
- Модель анализирует DICOM-файлы левой и правой коронарной артерии, вычисляя вклад каждой и итоговый суммарный показатель.
24
 
25
- ---
26
 
27
- ## 🚀 Возможности
28
 
29
- * Загрузка исследований в формате **DICOM**
30
- * Поддержка **многомодельного ансамбля** (усреднение только по моделям)
31
- * Обработка **нескольких клипов** одной артерии как единой последовательности
32
- * Интерфейс для **множественных исследований** в одном сеансе
33
- * Автоматическое определение весов модели (`weights/left`, `weights/right`)
34
 
35
- ---
36
 
37
- ## 🧭 Как использовать
38
 
39
- 1. Укажите **ID исследования** и при необходимости краткое **описание**.
40
- 2. Загрузите **DICOM-файлы** для **левой** и/или **правой** артерии.
41
- 3. Нажмите **“Add study”**, затем **“Run inference”**.
42
- 4. Результаты отобразятся в виде JSON-структуры с:
43
 
44
- * предсказаниями по каждой модели,
45
- * средним значением для каждой артерии,
46
- * суммарным SYNTAX-score,
47
- * пометкой «High-risk» при превышении порога.
48
 
49
- ---
 
 
50
 
51
- ## ⚙️ Технические детали
52
 
53
- * **Backbone:** `r3d_18` (torchvision)
54
- * **Head:** `lstm_mean` (возможно использование других вариантов: GRU, mean, BERT-head и др.)
55
- * **Формат входа:** `(1, S, C, T, H, W)` — пакет клипов одной артерии
56
- * **Нормализация:** стандарт ImageNet
57
- * **Усреднение:** только по моделям ансамбля (без усреднения по клипам внутри исследования)
58
- * **Пороговые значения:**
59
 
60
- * левая артерия ≥ 15
61
- * правая артерия ≥ 5
62
- * общее исследование ≥ 22
63
 
64
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
 
66
- ## 🧩 Структура проекта
67
 
 
 
 
68
  ```
69
- configs/
70
- └── default.yaml # Основная конфигурация
71
- src/syntax_pred/
72
- ├── model.py # Архитектура и загрузка весов
73
- ├── preprocess.py # Обработка DICOM и трансформации
74
- ├── data.py # Минималистичный датасет для инференса
75
- ├── utils.py # Поддержка: выбор устройства, поиск весов
76
- app.py # Gradio-интерфейс
77
- ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: CardioSyntax
3
  emoji: 🫀
4
+ colorFrom: gray
5
+ colorTo: green
6
+ sdk: docker
7
+ app_port: 7860
 
 
8
  pinned: false
9
  license: apache-2.0
10
+ short_description: Coronary angiography review and SYNTAX inference
11
  tags:
12
  - medical-imaging
13
  - video
 
16
  - cardiology
17
  ---
18
 
19
+ # CardioSyntax
20
 
21
+ A research workspace for reviewing coronary angiography and estimating the study-level SYNTAX score. English and Russian interfaces, light and dark themes, and public Philips and Siemens examples are included.
 
22
 
23
+ **[Model & methodology](https://huggingface.co/MesserMMP/coronary-syntax-prediction)** · **[Dataset](https://huggingface.co/datasets/MesserMMP/coronary-angiography-syntax)**
24
 
25
+ ## Use the workspace
26
 
27
+ 1. Load a public example, or upload de-identified DICOM files or a ZIP archive. Files are grouped by `StudyInstanceUID`.
28
+ 2. Review each projection. Assign it to LCA, RCA or Exclude, or use **Identify arteries** to suggest assignments. Uncertain suggestions require review. Clips shorter than 10 frames remain excluded.
29
+ 3. Check projection order and select **Calculate SYNTAX**. Both arteries are required for a total score; an incomplete study produces only the available artery contribution.
30
+ 4. Download the result as JSON. It includes the uncalibrated and calibrated scores, predictions for each fold, model revision and checkpoint hashes.
 
31
 
32
+ The cine player is a display preview. Display contrast adjustment and video compression do not alter the DICOM files or the model input. The model uses its own fixed preprocessing.
33
 
34
+ This application is intended for research, not clinical decision-making. An artery classifier suggestion is not a SYNTAX confidence estimate.
35
 
36
+ ## Model source
 
 
 
37
 
38
+ Weights come exclusively from [`MesserMMP/coronary-syntax-prediction`](https://huggingface.co/MesserMMP/coronary-syntax-prediction/tree/f6099168eef127991e6cdbc420f24c0fc74d914c), pinned to revision `f6099168eef127991e6cdbc420f24c0fc74d914c`. The complete file list and SHA-256 checksums are in [`engine/manifest.json`](engine/manifest.json).
 
 
 
39
 
40
+ - Five LCA and five RCA checkpoints: `full_model_weights/{Left,Right}BinSyntax_R3D_fold{00..04}_lstm_mean_post_best.safetensors`.
41
+ - Artery classifier: `classifier_weights/r3d_art.safetensors`.
42
+ - Calibration: `scaling_coeffs/scaling_coeffs.json` from the same revision.
43
 
44
+ The application downloads and verifies required files on demand. It loads one model at a time. Missing or corrupt weights cause an explicit failure; a partial ensemble is never silently substituted.
45
 
46
+ For fold *i*, `left_i` and `right_i` are the inverse log-transformed model outputs. The displayed calibrated total is:
 
 
 
 
 
47
 
48
+ ```text
49
+ max(0, mean_i(a_i × (left_i + right_i) + b_i))
50
+ ```
51
 
52
+ Calibration is applied per fold before averaging. Artery contributions are uncalibrated. Input order within each artery is preserved and can be adjusted before inference.
53
+
54
+ ## Run locally
55
+
56
+ Python 3.12 and FFmpeg are required. On a CPU machine:
57
+
58
+ ```bash
59
+ python3.12 -m venv .venv
60
+ source .venv/bin/activate
61
+ pip install torch==2.6.0 torchvision==0.21.0
62
+ pip install -r requirements.txt
63
+ uvicorn app:app --host 127.0.0.1 --port 7860 --workers 1 --no-access-log
64
+ ```
65
+
66
+ Open `http://127.0.0.1:7860`. The first inference needs network access to download approximately 1.5 GB of model files. Public examples are downloaded separately. No Hugging Face token is required.
67
 
68
+ For the CPU Docker image used by this Space:
69
 
70
+ ```bash
71
+ docker build -t cardiosyntax .
72
+ docker run --rm -p 7860:7860 cardiosyntax
73
  ```
74
+
75
+ The default is CPU with two compute threads. GPU inference is supported when compatible CUDA-enabled PyTorch and an NVIDIA GPU are available; set `SYNTAX_DEVICE=cuda`. Changing this variable alone does not add GPU support to the default CPU image.
76
+
77
+ | Setting | Default | Purpose |
78
+ |---|---|---|
79
+ | `SYNTAX_DEVICE` | `cpu` | Explicit inference device: `cpu` or `cuda` |
80
+ | `SYNTAX_CPU_THREADS` | `2` | PyTorch CPU thread count |
81
+ | `SYNTAX_MODEL_CACHE` | See `engine/weights.py` | Downloaded and verified model files |
82
+ | `SYNTAX_UPLOAD_DIR` | System temporary directory / `cardiosyntax-uploads` | Temporary uploaded studies |
83
+
84
+ Use **one** application worker: the inference queue and study registry are held in process memory. CPU inference is slower than GPU inference; the interface reports actual job progress. Hosting availability and runtime resources depend on the Space configuration.
85
+
86
+ ## Uploads and session lifetime
87
+
88
+ Upload only de-identified data. Files are processed on the application host. There is no external analytics service and no automatic publication of uploaded files.
89
+
90
+ The default limits are 64 files, 8 studies and 512 MB per upload, 128 MB per file, and 1,024 frames per sequence. Supported inputs are unsigned 8-bit or 16-bit monochrome DICOM. A decoded sequence must fit within 512 MiB. Invalid inputs and repeated SOP identifiers are reported.
91
+
92
+ Studies can be removed from the sidebar. Inactive studies are deleted after approximately one hour; active jobs are protected from cleanup. Results should be downloaded before closing the workspace. A server restart ends the in-memory session.
93
+
94
+ ## Source and attribution
95
+
96
+ The scoring architecture, preprocessing, checkpoints and calibration follow the [coronary-syntax-prediction project](https://huggingface.co/MesserMMP/coronary-syntax-prediction). Model and dataset licensing and scholarly attribution are provided in their respective repository cards (CC BY 4.0). The Space application retains its Apache 2.0 license declaration.
97
+
98
+ The service is organized into `engine/` (inference), `service/` (uploads and jobs), and `static/` (the custom interface). No model weights or uploaded studies are committed to this Space.
app.py CHANGED
@@ -1,1268 +1,9 @@
1
- import os
2
- import base64
3
- import json
4
- import tempfile
5
- from datetime import datetime
6
- from dataclasses import asdict
7
- from typing import List, Dict, Any
8
- from pathlib import Path
9
 
10
- import gradio as gr
11
- import pydicom
12
 
13
- from src.syntax_pred.config import CFG
14
- from src.syntax_pred.infer import Study, run_inference
15
-
16
- # ==================== КОНФИГУРАЦИЯ ДИЗАЙНА ====================
17
- APPLE_STYLE_CSS = """
18
- /* Сбалансированная современная цветовая гамма */
19
- :root {
20
- --bg-primary: #4f46e5;
21
- --bg-secondary: #7c3aed;
22
- --bg-gradient: linear-gradient(135deg, #4f46e5 0%, #7c3aed 50%, #a855f7 100%);
23
- --bg-surface: linear-gradient(135deg, rgba(255,255,255,0.97) 0%, rgba(255,255,255,0.94) 100%);
24
-
25
- --accent-cyan: #06b6d4;
26
- --accent-teal: #3b82f6;
27
- --accent-purple: #8b5cf6;
28
- --accent-pink: #d946ef;
29
- --accent-orange: #f97316;
30
- --accent-green: #10b981;
31
- --accent-red: #ef4444;
32
- --accent-yellow: #eab308;
33
-
34
- --accent-cyan-light: rgba(6, 182, 212, 0.08);
35
- --accent-teal-light: rgba(59, 130, 246, 0.08);
36
- --accent-purple-light: rgba(139, 92, 246, 0.08);
37
- --accent-pink-light: rgba(217, 70, 239, 0.08);
38
- --accent-green-light: rgba(16, 185, 129, 0.08);
39
- --accent-red-light: rgba(239, 68, 68, 0.08);
40
- --accent-orange-light: rgba(249, 115, 22, 0.08);
41
-
42
- --text-primary: #1e293b;
43
- --text-secondary: #64748b;
44
- --text-light: #94a3b8;
45
- --text-white: #ffffff;
46
-
47
- --border-color: rgba(255, 255, 255, 0.2);
48
- --border-dark: rgba(0, 0, 0, 0.06);
49
- --shadow-sm: 0 4px 6px -1px rgba(0, 0, 0, 0.05);
50
- --shadow-md: 0 10px 15px -3px rgba(0, 0, 0, 0.08);
51
- --shadow-lg: 0 20px 25px -5px rgba(0, 0, 0, 0.1);
52
- --shadow-glow: 0 0 0 3px rgba(6, 182, 212, 0.2);
53
- --shadow-glow-purple: 0 0 0 3px rgba(139, 92, 246, 0.2);
54
- }
55
-
56
- * {
57
- font-family: -apple-system, "SF Pro Text", "SF Pro Display", "Inter", "Helvetica Neue", system-ui, sans-serif;
58
- }
59
-
60
- body, .gradio-container {
61
- background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 50%, #a855f7 100%) !important;
62
- position: relative;
63
- }
64
-
65
- body::before {
66
- content: '';
67
- position: fixed;
68
- top: 0;
69
- left: 0;
70
- right: 0;
71
- bottom: 0;
72
- background: radial-gradient(circle at 20% 50%, rgba(255,255,255,0.08) 0%, transparent 70%);
73
- pointer-events: none;
74
- z-index: 0;
75
- }
76
-
77
- .gradio-container {
78
- position: relative;
79
- z-index: 1;
80
- }
81
-
82
- .gr-box, .gr-form, .panel, .tabs, .tab-nav, .accordion {
83
- background: transparent !important;
84
- border: none !important;
85
- }
86
-
87
- .apple-container {
88
- max-width: 1400px;
89
- margin: 0 auto;
90
- padding: 2rem 1.5rem;
91
- }
92
-
93
- .apple-header {
94
- text-align: center;
95
- margin-bottom: 2rem;
96
- position: relative;
97
- padding: 1rem 0;
98
- }
99
-
100
- .apple-title {
101
- font-size: 3.2rem;
102
- font-weight: 800;
103
- background: linear-gradient(135deg, #ffffff 0%, #e2e8f0 100%);
104
- -webkit-background-clip: text;
105
- -webkit-text-fill-color: transparent;
106
- background-clip: text;
107
- letter-spacing: -0.02em;
108
- margin: 0;
109
- text-shadow: 0 2px 10px rgba(0,0,0,0.05);
110
- }
111
-
112
- .apple-subtitle {
113
- font-size: 1.1rem;
114
- color: rgba(255, 255, 255, 0.85);
115
- margin-top: 0.5rem;
116
- font-weight: 400;
117
- }
118
-
119
- .apple-card {
120
- background: rgba(255, 255, 255, 0.96);
121
- backdrop-filter: blur(20px);
122
- border-radius: 24px;
123
- border: 1px solid rgba(255, 255, 255, 0.3);
124
- box-shadow: var(--shadow-md);
125
- transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
126
- overflow: hidden;
127
- }
128
-
129
- .apple-card:hover {
130
- transform: translateY(-2px);
131
- box-shadow: var(--shadow-lg);
132
- background: rgba(255, 255, 255, 0.98);
133
- }
134
-
135
- .apple-card-header {
136
- padding: 1.25rem 1.5rem;
137
- border-bottom: 1px solid rgba(0, 0, 0, 0.05);
138
- background: linear-gradient(135deg, rgba(255,255,255,0.4) 0%, rgba(255,255,255,0.2) 100%);
139
- }
140
-
141
- .apple-card-title {
142
- font-size: 1.25rem;
143
- font-weight: 700;
144
- background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%);
145
- -webkit-background-clip: text;
146
- -webkit-text-fill-color: transparent;
147
- background-clip: text;
148
- margin: 0;
149
- display: flex;
150
- align-items: center;
151
- gap: 0.5rem;
152
- }
153
-
154
- .apple-card-content {
155
- padding: 1.5rem;
156
- }
157
-
158
- .add-study-card {
159
- background: linear-gradient(135deg, rgba(255,255,255,0.98) 0%, rgba(255,255,255,0.96) 100%);
160
- border: 1px solid rgba(255,255,255,0.4);
161
- position: relative;
162
- overflow: hidden;
163
- }
164
-
165
- .apple-button {
166
- background: linear-gradient(135deg, #06b6d4 0%, #3b82f6 100%);
167
- color: white;
168
- border: none;
169
- border-radius: 980px;
170
- padding: 0.75rem 1.5rem;
171
- font-size: 0.9375rem;
172
- font-weight: 600;
173
- cursor: pointer;
174
- transition: all 0.3s ease;
175
- box-shadow: var(--shadow-sm);
176
- display: inline-flex;
177
- align-items: center;
178
- gap: 0.5rem;
179
- position: relative;
180
- overflow: hidden;
181
- }
182
-
183
- .apple-button::before {
184
- content: '';
185
- position: absolute;
186
- top: 0;
187
- left: -100%;
188
- width: 100%;
189
- height: 100%;
190
- background: linear-gradient(90deg, transparent, rgba(255,255,255,0.15), transparent);
191
- transition: left 0.5s;
192
- }
193
-
194
- .apple-button:hover::before {
195
- left: 100%;
196
- }
197
-
198
- .apple-button:hover {
199
- transform: translateY(-1px);
200
- box-shadow: var(--shadow-md);
201
- background: linear-gradient(135deg, #0891b2 0%, #2563eb 100%);
202
- }
203
-
204
- .apple-button-add {
205
- background: linear-gradient(135deg, #8b5cf6 0%, #a855f7 100%);
206
- color: white;
207
- border: none;
208
- border-radius: 980px;
209
- padding: 0.75rem 1.5rem;
210
- font-size: 0.9375rem;
211
- font-weight: 600;
212
- cursor: pointer;
213
- transition: all 0.3s ease;
214
- box-shadow: var(--shadow-sm);
215
- display: inline-flex;
216
- align-items: center;
217
- gap: 0.5rem;
218
- position: relative;
219
- overflow: hidden;
220
- }
221
-
222
- .apple-button-add::before {
223
- content: '';
224
- position: absolute;
225
- top: 0;
226
- left: -100%;
227
- width: 100%;
228
- height: 100%;
229
- background: linear-gradient(90deg, transparent, rgba(255,255,255,0.15), transparent);
230
- transition: left 0.5s;
231
- }
232
-
233
- .apple-button-add:hover::before {
234
- left: 100%;
235
- }
236
-
237
- .apple-button-add:hover {
238
- transform: translateY(-1px);
239
- box-shadow: var(--shadow-md);
240
- background: linear-gradient(135deg, #7c3aed 0%, #9333ea 100%);
241
- }
242
-
243
- .apple-button-clear {
244
- background: linear-gradient(135deg, #f97316 0%, #fbbf24 100%);
245
- color: white;
246
- border: none;
247
- border-radius: 980px;
248
- padding: 0.75rem 1.5rem;
249
- font-size: 0.9375rem;
250
- font-weight: 600;
251
- cursor: pointer;
252
- transition: all 0.3s ease;
253
- box-shadow: var(--shadow-sm);
254
- display: inline-flex;
255
- align-items: center;
256
- gap: 0.5rem;
257
- position: relative;
258
- overflow: hidden;
259
- }
260
-
261
- .apple-button-clear::before {
262
- content: '';
263
- position: absolute;
264
- top: 0;
265
- left: -100%;
266
- width: 100%;
267
- height: 100%;
268
- background: linear-gradient(90deg, transparent, rgba(255,255,255,0.15), transparent);
269
- transition: left 0.5s;
270
- }
271
-
272
- .apple-button-clear:hover::before {
273
- left: 100%;
274
- }
275
-
276
- .apple-button-clear:hover {
277
- transform: translateY(-1px);
278
- box-shadow: var(--shadow-md);
279
- background: linear-gradient(135deg, #ea580c 0%, #eab308 100%);
280
- }
281
-
282
- .apple-input {
283
- border: 1.5px solid rgba(0, 0, 0, 0.05) !important;
284
- border-radius: 14px !important;
285
- padding: 0.75rem 1rem !important;
286
- font-size: 0.9375rem !important;
287
- background: rgba(255, 255, 255, 0.95) !important;
288
- transition: all 0.3s ease !important;
289
- }
290
-
291
- .apple-input:focus {
292
- outline: none !important;
293
- border-color: #06b6d4 !important;
294
- box-shadow: var(--shadow-glow) !important;
295
- background: white !important;
296
- }
297
-
298
- .apple-table {
299
- border-radius: 16px;
300
- overflow: hidden;
301
- border: none;
302
- }
303
-
304
- .apple-table table {
305
- background: rgba(255, 255, 255, 0.95) !important;
306
- border-collapse: collapse !important;
307
- width: 100%;
308
- }
309
-
310
- .apple-table th {
311
- background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%) !important;
312
- color: white !important;
313
- font-weight: 600 !important;
314
- font-size: 0.875rem !important;
315
- padding: 12px 16px !important;
316
- border-bottom: none !important;
317
- border-top: none !important;
318
- border-left: none !important;
319
- border-right: none !important;
320
- }
321
-
322
- .apple-table td {
323
- background: rgba(255, 255, 255, 0.98) !important;
324
- color: var(--text-primary) !important;
325
- padding: 12px 16px !important;
326
- border-bottom: 1px solid rgba(0, 0, 0, 0.05) !important;
327
- border-top: none !important;
328
- border-left: none !important;
329
- border-right: none !important;
330
- }
331
-
332
- .apple-table tr:last-child td {
333
- border-bottom: none !important;
334
- }
335
-
336
- .apple-table tr:hover td {
337
- background: rgba(139, 92, 246, 0.04) !important;
338
- }
339
-
340
- .status-badge {
341
- display: inline-flex;
342
- align-items: center;
343
- gap: 0.375rem;
344
- padding: 0.25rem 0.75rem;
345
- border-radius: 20px;
346
- font-size: 0.8125rem;
347
- font-weight: 600;
348
- white-space: nowrap;
349
- }
350
-
351
- .status-running {
352
- background: linear-gradient(135deg, #06b6d4 0%, #3b82f6 100%);
353
- color: white;
354
- box-shadow: var(--shadow-sm);
355
- }
356
-
357
- .status-done {
358
- background: linear-gradient(135deg, #10b981 0%, #059669 100%);
359
- color: white;
360
- box-shadow: var(--shadow-sm);
361
- }
362
-
363
- .status-error {
364
- background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
365
- color: white;
366
- box-shadow: var(--shadow-sm);
367
- }
368
-
369
- .status-queued {
370
- background: linear-gradient(135deg, #64748b 0%, #475569 100%);
371
- color: white;
372
- box-shadow: var(--shadow-sm);
373
- }
374
-
375
- @keyframes pulse {
376
- 0%, 100% {
377
- opacity: 1;
378
- transform: scale(1);
379
- }
380
- 50% {
381
- opacity: 0.85;
382
- transform: scale(1.02);
383
- }
384
- }
385
-
386
- .pulse {
387
- animation: pulse 1.5s ease-in-out infinite;
388
- }
389
-
390
- ::-webkit-scrollbar {
391
- width: 8px;
392
- height: 8px;
393
- }
394
-
395
- ::-webkit-scrollbar-track {
396
- background: rgba(255, 255, 255, 0.15);
397
- border-radius: 4px;
398
- }
399
-
400
- ::-webkit-scrollbar-thumb {
401
- background: linear-gradient(135deg, #06b6d4 0%, #3b82f6 100%);
402
- border-radius: 4px;
403
- }
404
-
405
- ::-webkit-scrollbar-thumb:hover {
406
- background: linear-gradient(135deg, #0891b2 0%, #2563eb 100%);
407
- }
408
-
409
- .upload-grid {
410
- display: grid;
411
- grid-template-columns: 1fr 1fr;
412
- gap: 1rem;
413
- }
414
-
415
- .instruction-box {
416
- background: linear-gradient(135deg, rgba(139, 92, 246, 0.06) 0%, rgba(6, 182, 212, 0.06) 100%);
417
- border-radius: 16px;
418
- padding: 1rem;
419
- margin-top: 1rem;
420
- border: 1px solid rgba(139, 92, 246, 0.15);
421
- backdrop-filter: blur(10px);
422
- }
423
-
424
- .instruction-title {
425
- font-size: 0.875rem;
426
- font-weight: 700;
427
- background: linear-gradient(135deg, #8b5cf6 0%, #a855f7 100%);
428
- -webkit-background-clip: text;
429
- -webkit-text-fill-color: transparent;
430
- margin-bottom: 0.5rem;
431
- display: flex;
432
- align-items: center;
433
- gap: 0.5rem;
434
- }
435
-
436
- .instruction-list {
437
- list-style: none;
438
- padding: 0;
439
- margin: 0;
440
- display: grid;
441
- grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
442
- gap: 0.5rem;
443
- }
444
-
445
- .instruction-list li {
446
- font-size: 0.8125rem;
447
- color: var(--text-secondary);
448
- display: flex;
449
- align-items: center;
450
- gap: 0.5rem;
451
- font-weight: 500;
452
- }
453
-
454
- @media (max-width: 768px) {
455
- .upload-grid {
456
- grid-template-columns: 1fr;
457
- gap: 1rem;
458
- }
459
-
460
- .instruction-list {
461
- grid-template-columns: 1fr;
462
- }
463
-
464
- .apple-title {
465
- font-size: 2rem;
466
- }
467
- }
468
- """
469
-
470
- # Логотип (base64)
471
- DEFAULT_LOGO = "assets/logo.png"
472
- LOGO_PATH = os.environ.get("LOGO_PATH", DEFAULT_LOGO)
473
-
474
-
475
- def _logo_html() -> str:
476
- """Генерация HTML для логотипа"""
477
- path = LOGO_PATH
478
- if not path or not os.path.exists(path):
479
- return ""
480
- try:
481
- with open(path, "rb") as f:
482
- data = base64.b64encode(f.read()).decode("ascii")
483
- ext = os.path.splitext(path)[1].lower()
484
- mime = "image/png" if ext in {".png", ""} else "image/jpeg"
485
- return f'<img src="data:{mime};base64,{data}" alt="Логотип" style="height: 36px; width: auto; border-radius: 10px; filter: drop-shadow(0 2px 6px rgba(0,0,0,0.08));" />'
486
- except Exception:
487
- return ""
488
-
489
-
490
- def _is_dicom_path(path: str) -> bool:
491
- """Проверка на DICOM файл"""
492
- if not os.path.exists(path):
493
- return False
494
- ext = os.path.splitext(path)[1].lower()
495
- if ext not in {".dcm", ""}:
496
- return False
497
- try:
498
- pydicom.dcmread(path, stop_before_pixels=True)
499
- return True
500
- except Exception:
501
- return False
502
-
503
-
504
- def _files_to_paths(files) -> List[str]:
505
- """Конвертация файлов в пути"""
506
- if not files:
507
- return []
508
- raw_paths = [f.name for f in files if hasattr(f, "name") and os.path.exists(f.name)]
509
- return [p for p in raw_paths if _is_dicom_path(p)]
510
-
511
-
512
- def _collect_input_paths(files_all, folder_files) -> List[str]:
513
- """Сбор всех путей из загрузок"""
514
- combined = _files_to_paths(files_all) + _files_to_paths(folder_files)
515
- return list(dict.fromkeys(combined))
516
-
517
-
518
- def _build_report_file(result: Dict[str, Any]) -> str:
519
- """Создание отчета в JSON"""
520
- ts = datetime.now().strftime("%Y%m%d_%H%M%S")
521
- with tempfile.NamedTemporaryFile(
522
- mode="w",
523
- prefix=f"autoangioscore_report_{ts}_",
524
- suffix=".json",
525
- encoding="utf-8",
526
- delete=False,
527
- ) as f:
528
- json.dump(result, f, ensure_ascii=False, indent=2)
529
- return f.name
530
-
531
-
532
- def _status_badge_html(state: str, with_animation: bool = False) -> str:
533
- """Генерация HTML для статус бейджа"""
534
- state = state.lower()
535
-
536
- status_config = {
537
- "running": {"class": "status-running", "icon": "⏱️", "text": "Выполняется"},
538
- "done": {"class": "status-done", "icon": "✅", "text": "Завершено"},
539
- "error": {"class": "status-error", "icon": "❌", "text": "Ошибка"},
540
- "queued": {"class": "status-queued", "icon": "⏳", "text": "В очереди"}
541
- }
542
-
543
- config = status_config.get(state, status_config["queued"])
544
- animation_class = " pulse" if with_animation and state == "running" else ""
545
-
546
- return f'<span class="status-badge {config["class"]}{animation_class}">{config["icon"]} {config["text"]}</span>'
547
-
548
-
549
- def _update_status_table(studies, status: str) -> List[List]:
550
- """Обновление таблицы со статусами"""
551
- badge = _status_badge_html(status, with_animation=(status == "running"))
552
- return [
553
- [s.get("name", "-"), s.get("description", "-") or "-", len(s.get("files", [])), badge]
554
- for s in (studies or [])
555
- ]
556
-
557
-
558
- def _format_results_html(result: Dict[str, Any]) -> str:
559
- """Форматирование результатов в красивом HTML с детальной информацией (одна кнопка ��а исследование)"""
560
- if not result:
561
- return '''
562
- <div class="apple-card" style="padding: 2rem; text-align: center;">
563
- <div style="color: var(--text-secondary);">
564
- 📊 Результаты появятся после запуска анализа
565
- </div>
566
- </div>
567
- '''
568
-
569
- if "error" in result:
570
- return f'''
571
- <div class="apple-card" style="padding: 1.5rem; background: linear-gradient(135deg, rgba(239,68,68,0.10) 0%, rgba(220,38,38,0.10) 100%);">
572
- <div style="color: var(--accent-red); display: flex; align-items: center; gap: 0.75rem;">
573
- <span style="font-size: 1.5rem;">⚠️</span>
574
- <div>
575
- <strong>Ошибка</strong>
576
- <div style="margin-top: 0.25rem;">{result.get("error", "Неизвестная ошибка")}</div>
577
- </div>
578
- </div>
579
- </div>
580
- '''
581
-
582
- studies = result.get("studies", []) or []
583
- if not studies:
584
- return '''
585
- <div class="apple-card" style="padding: 2rem; text-align: center;">
586
- <div style="color: var(--text-secondary);">
587
- 📋 Нет исследований для отображения
588
- </div>
589
- </div>
590
- '''
591
-
592
- # Добавляем стили для аккордеона и кнопки (без JavaScript)
593
- accordion_styles = """
594
- <style>
595
- .detail-accordion {
596
- margin-top: 1rem;
597
- border-radius: 12px;
598
- overflow: hidden;
599
- }
600
- .detail-accordion summary {
601
- cursor: pointer;
602
- list-style: none;
603
- display: flex;
604
- align-items: center;
605
- justify-content: center;
606
- padding: 0;
607
- }
608
- .detail-accordion summary::-webkit-details-marker {
609
- display: none;
610
- }
611
- .detail-button {
612
- background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%);
613
- color: white;
614
- border: none;
615
- border-radius: 980px;
616
- padding: 0.6rem 1.5rem;
617
- font-size: 0.875rem;
618
- font-weight: 600;
619
- cursor: pointer;
620
- transition: all 0.3s ease;
621
- display: inline-flex;
622
- align-items: center;
623
- gap: 0.5rem;
624
- margin: 0 auto;
625
- }
626
- .detail-button:hover {
627
- transform: translateY(-1px);
628
- box-shadow: var(--shadow-md);
629
- background: linear-gradient(135deg, #5b52e8 0%, #8b4ced 100%);
630
- }
631
- .detail-accordion[open] .detail-button {
632
- background: linear-gradient(135deg, #f97316 0%, #fbbf24 100%);
633
- }
634
- .detail-accordion[open] .detail-button:hover {
635
- background: linear-gradient(135deg, #ea580c 0%, #eab308 100%);
636
- }
637
- /* Меняем текст кнопки через CSS псевдоэлементы */
638
- .detail-button .toggle-text-open {
639
- display: inline;
640
- }
641
- .detail-button .toggle-text-close {
642
- display: none;
643
- }
644
- .detail-accordion[open] .detail-button .toggle-text-open {
645
- display: none;
646
- }
647
- .detail-accordion[open] .detail-button .toggle-text-close {
648
- display: inline;
649
- }
650
- .detail-button .toggle-icon-open {
651
- display: inline;
652
- }
653
- .detail-button .toggle-icon-close {
654
- display: none;
655
- }
656
- .detail-accordion[open] .detail-button .toggle-icon-open {
657
- display: none;
658
- }
659
- .detail-accordion[open] .detail-button .toggle-icon-close {
660
- display: inline;
661
- }
662
- .files-list {
663
- margin-top: 8px;
664
- max-height: 300px;
665
- overflow-y: auto;
666
- }
667
- .file-item {
668
- display: flex;
669
- justify-content: space-between;
670
- align-items: center;
671
- font-size: 11px;
672
- padding: 6px 0;
673
- border-bottom: 1px solid rgba(0,0,0,0.05);
674
- }
675
- .file-name {
676
- color: var(--text-secondary);
677
- font-size: 11px;
678
- }
679
- .file-prob {
680
- font-weight: 500;
681
- font-size: 11px;
682
- }
683
- .other-file-item {
684
- display: flex;
685
- justify-content: space-between;
686
- align-items: center;
687
- font-size: 11px;
688
- padding: 6px 0;
689
- border-bottom: 1px solid rgba(0,0,0,0.05);
690
- }
691
- .other-file-info {
692
- display: flex;
693
- flex-direction: column;
694
- align-items: flex-start;
695
- }
696
- .other-file-name {
697
- color: var(--text-secondary);
698
- font-size: 11px;
699
- }
700
- .other-file-status {
701
- font-size: 9px;
702
- }
703
- .other-file-prob {
704
- text-align: right;
705
- }
706
- .other-file-prob-value {
707
- font-weight: 600;
708
- font-size: 11px;
709
- }
710
- .other-file-prob-label {
711
- font-size: 9px;
712
- color: var(--text-light);
713
- }
714
- </style>
715
- """
716
-
717
- cards_html = [accordion_styles]
718
-
719
- for idx, s in enumerate(studies):
720
- study_name = s.get("study", "-")
721
- description = s.get("description", "")
722
- unique_id = f"details_{idx}_{study_name.replace(' ', '_').replace('/', '_')}"
723
-
724
- left_data = s.get("left", {})
725
- right_data = s.get("right", {})
726
- other_data = s.get("other", [])
727
- total_obj = s.get("total", {})
728
-
729
- left_mean = left_data.get("mean", 0.0)
730
- right_mean = right_data.get("mean", 0.0)
731
- total_mean = total_obj.get("mean", 0.0)
732
-
733
- left_files_count = left_data.get("n_files", 0)
734
- right_files_count = right_data.get("n_files", 0)
735
- other_files_count = len(other_data)
736
-
737
- left_per_model = left_data.get("per_model", [])
738
- right_per_model = right_data.get("per_model", [])
739
-
740
- risk_key = next((k for k in total_obj.keys() if "High-risk" in str(k)), None)
741
- is_high_risk = bool(total_obj.get(risk_key, False)) if risk_key else total_mean > 0.5
742
-
743
- if is_high_risk:
744
- badge_bg = "#fee2e2"
745
- badge_color = "#991b1b"
746
- badge_text = "⚠️ Высокий риск"
747
- else:
748
- badge_bg = "#dcfce7"
749
- badge_color = "#14532d"
750
- badge_text = "✅ Низкий риск"
751
-
752
- badge_style = f"""
753
- background: {badge_bg};
754
- color: {badge_color};
755
- padding: 8px 16px;
756
- border-radius: 20px;
757
- font-size: 14px;
758
- font-weight: 700;
759
- display: inline-flex;
760
- align-items: center;
761
- gap: 6px;
762
- border: 1px solid rgba(0,0,0,0.05);
763
- """
764
-
765
- # Генерация HTML для моделей левой артерии
766
- left_models_html = ""
767
- if left_per_model:
768
- left_models_html = '<div style="margin-top: 8px;">'
769
- for i, model_info in enumerate(left_per_model, 1):
770
- model_score = model_info.get("score", 0.0)
771
- left_models_html += f'''
772
- <div class="file-item">
773
- <span class="file-name">🎯 Модель {i}</span>
774
- <span class="file-prob" style="color: #06b6d4;">{model_score:.3f}</span>
775
- </div>
776
- '''
777
- left_models_html += '</div>'
778
- else:
779
- left_models_html = '<div style="margin-top: 8px; font-size: 11px; color: var(--text-light); text-align: center;">Нет данных моделей</div>'
780
-
781
- # Генерация HTML для моделей правой артерии
782
- right_models_html = ""
783
- if right_per_model:
784
- right_models_html = '<div style="margin-top: 8px;">'
785
- for i, model_info in enumerate(right_per_model, 1):
786
- model_score = model_info.get("score", 0.0)
787
- right_models_html += f'''
788
- <div class="file-item">
789
- <span class="file-name">🎯 Модель {i}</span>
790
- <span class="file-prob" style="color: #8b5cf6;">{model_score:.3f}</span>
791
- </div>
792
- '''
793
- right_models_html += '</div>'
794
- else:
795
- right_models_html = '<div style="margin-top: 8px; font-size: 11px; color: var(--text-light); text-align: center;">Нет данных моделей</div>'
796
-
797
- # Файлы левой артерии (ВСЕ файлы)
798
- left_files_with_probs = left_data.get("files", [])
799
- left_files_html = ""
800
- if left_files_with_probs:
801
- left_files_html = '<div class="files-list">'
802
- for file_info in left_files_with_probs:
803
- file_path = file_info.get("path", "unknown")
804
- file_name = os.path.basename(file_path) if file_path else "unknown"
805
- artery_prob = file_info.get("artery_prob", 0.0)
806
- left_files_html += f'''
807
- <div class="file-item">
808
- <span class="file-name">📄 {file_name[:50]}</span>
809
- <span class="file-prob" style="color: #06b6d4;">{artery_prob:.3f}</span>
810
- </div>
811
- '''
812
- left_files_html += '</div>'
813
- else:
814
- left_files_html = '<div style="margin-top: 8px; font-size: 11px; color: var(--text-light); text-align: center;">Нет файлов</div>'
815
-
816
- # Файлы правой артерии (ВСЕ файлы)
817
- right_files_with_probs = right_data.get("files", [])
818
- right_files_html = ""
819
- if right_files_with_probs:
820
- right_files_html = '<div class="files-list">'
821
- for file_info in right_files_with_probs:
822
- file_path = file_info.get("path", "unknown")
823
- file_name = os.path.basename(file_path) if file_path else "unknown"
824
- artery_prob = file_info.get("artery_prob", 0.0)
825
- right_files_html += f'''
826
- <div class="file-item">
827
- <span class="file-name">📄 {file_name[:50]}</span>
828
- <span class="file-prob" style="color: #8b5cf6;">{artery_prob:.3f}</span>
829
- </div>
830
- '''
831
- right_files_html += '</div>'
832
- else:
833
- right_files_html = '<div style="margin-top: 8px; font-size: 11px; color: var(--text-light); text-align: center;">Нет файлов</div>'
834
-
835
- # Нераспознанные файлы (ВСЕ файлы)
836
- other_files_html = ""
837
- if other_data:
838
- other_files_html = '<div class="files-list">'
839
- for file_info in other_data:
840
- file_path = file_info.get("path", "unknown")
841
- file_name = os.path.basename(file_path) if file_path else "unknown"
842
- artery_prob = file_info.get("artery_prob", 0.0)
843
-
844
- left_threshold = 0.10
845
- right_threshold = 0.90
846
-
847
- if artery_prob <= left_threshold:
848
- prob_status = "⚠️ Ниже порога левой артерии"
849
- prob_color = "#f97316"
850
- elif artery_prob >= right_threshold:
851
- prob_status = "⚠️ Выше порога правой артерии"
852
- prob_color = "#f97316"
853
- else:
854
- prob_status = "❓ В серой зоне (неопределён)"
855
- prob_color = "#ef4444"
856
-
857
- other_files_html += f'''
858
- <div class="other-file-item">
859
- <div class="other-file-info">
860
- <span class="other-file-name">📄 {file_name[:50]}</span>
861
- <span class="other-file-status" style="color: {prob_color};">{prob_status}</span>
862
- </div>
863
- <div class="other-file-prob">
864
- <div class="other-file-prob-value" style="color: #f97316;">{artery_prob:.3f}</div>
865
- <div class="other-file-prob-label">вероятность</div>
866
- </div>
867
- </div>
868
- '''
869
- other_files_html += '</div>'
870
- else:
871
- other_files_html = '<div style="margin-top: 8px; font-size: 11px; color: var(--text-light); text-align: center;">Нераспознанных файлов нет</div>'
872
-
873
- card_html = f'''
874
- <div class="apple-card" style="margin-bottom: 1rem;">
875
- <div class="apple-card-header">
876
- <div style="display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 10px;">
877
- <div style="display: flex; align-items: center; gap: 8px;">
878
- <span style="font-size: 1.25rem; font-weight: 700; color: var(--text-primary);">🏥 {study_name}</span>
879
- </div>
880
- <div style="{badge_style}">
881
- {badge_text}
882
- </div>
883
- </div>
884
- {f'<div style="font-size: 0.875rem; color: var(--text-secondary); margin-top: 0.5rem;">{description}</div>' if description else ''}
885
- </div>
886
- <div class="apple-card-content">
887
-
888
- <!-- Три основных показателя (всегда видны) -->
889
- <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 1rem; margin-bottom: 0rem;">
890
-
891
- <div style="text-align: center;
892
- background: linear-gradient(135deg, rgba(6,182,212,0.10) 0%, rgba(59,130,246,0.10) 100%);
893
- border-radius: 16px;
894
- padding: 0.85rem;
895
- border: 1px solid rgba(59,130,246,0.15);">
896
- <div style="font-size: 0.875rem; color: var(--text-secondary); margin-bottom: 0.5rem;">
897
- 🧬 Левая артерия
898
- </div>
899
- <div style="font-size: 1.5rem; font-weight: 800;
900
- background: linear-gradient(135deg, #06b6d4 0%, #3b82f6 100%);
901
- -webkit-background-clip: text; -webkit-text-fill-color: transparent;">
902
- {left_mean:.3f}
903
- </div>
904
- <div style="font-size: 0.7rem; color: var(--text-secondary); margin-top: 0.25rem;">
905
- SYNTAX Score
906
- </div>
907
- <div style="font-size: 0.7rem; color: var(--text-muted); margin-top: 0.25rem;">
908
- 📁 {left_files_count} файлов
909
- </div>
910
- </div>
911
-
912
- <div style="text-align: center;
913
- background: linear-gradient(135deg, rgba(139,92,246,0.10) 0%, rgba(168,85,247,0.10) 100%);
914
- border-radius: 16px;
915
- padding: 0.85rem;
916
- border: 1px solid rgba(168,85,247,0.15);">
917
- <div style="font-size: 0.875rem; color: var(--text-secondary); margin-bottom: 0.5rem;">
918
- 🧬 Правая артерия
919
- </div>
920
- <div style="font-size: 1.5rem; font-weight: 800;
921
- background: linear-gradient(135deg, #8b5cf6 0%, #a855f7 100%);
922
- -webkit-background-clip: text; -webkit-text-fill-color: transparent;">
923
- {right_mean:.3f}
924
- </div>
925
- <div style="font-size: 0.7rem; color: var(--text-secondary); margin-top: 0.25rem;">
926
- SYNTAX Score
927
- </div>
928
- <div style="font-size: 0.7rem; color: var(--text-muted); margin-top: 0.25rem;">
929
- 📁 {right_files_count} файлов
930
- </div>
931
- </div>
932
-
933
- <div style="text-align: center;
934
- background: linear-gradient(135deg, rgba(249,115,22,0.10) 0%, rgba(251,191,36,0.10) 100%);
935
- border-radius: 16px;
936
- padding: 0.85rem;
937
- border: 1px solid rgba(249,115,22,0.20);">
938
- <div style="font-size: 0.875rem; color: var(--text-secondary); margin-bottom: 0.5rem;">
939
- 📊 Общий SYNTAX Score
940
- </div>
941
- <div style="font-size: 1.75rem; font-weight: 900;
942
- background: linear-gradient(135deg, #f97316 0%, #fbbf24 100%);
943
- -webkit-background-clip: text; -webkit-text-fill-color: transparent;">
944
- {total_mean:.3f}
945
- </div>
946
- <div style="font-size: 0.7rem; color: var(--text-secondary); margin-top: 0.25rem;">
947
- {'⚠️ Рекомендовано вмешательство' if is_high_risk else '✅ Плановое наблюдение'}
948
- </div>
949
- </div>
950
-
951
- </div>
952
-
953
- <!-- Кнопка для раскрытия детальной информации (без JavaScript, через CSS) -->
954
- <details id="{unique_id}" class="detail-accordion">
955
- <summary>
956
- <div class="detail-button">
957
- <span class="toggle-icon-open">▼</span>
958
- <span class="toggle-icon-close">▲</span>
959
- <span class="toggle-text-open">Показать детальную информацию</span>
960
- <span class="toggle-text-close">Скрыть детальную информацию</span>
961
- </div>
962
- </summary>
963
-
964
- <!-- Детальная информация (появляется после клика) -->
965
- <div style="margin-top: 1.5rem;">
966
-
967
- <!-- Оценка по моделям -->
968
- <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; margin-bottom: 1rem;">
969
-
970
- <div style="background: rgba(6,182,212,0.04); border-radius: 12px; padding: 0.75rem; border: 1px solid rgba(6,182,212,0.1);">
971
- <div style="font-size: 0.8125rem; font-weight: 700; color: #06b6d4; margin-bottom: 0.5rem; display: flex; align-items: center; gap: 0.5rem;">
972
- <span>🎯</span> SYNTAX Score по моделям (левая артерия)
973
- </div>
974
- {left_models_html}
975
- </div>
976
-
977
- <div style="background: rgba(139,92,246,0.04); border-radius: 12px; padding: 0.75rem; border: 1px solid rgba(139,92,246,0.1);">
978
- <div style="font-size: 0.8125rem; font-weight: 700; color: #8b5cf6; margin-bottom: 0.5rem; display: flex; align-items: center; gap: 0.5rem;">
979
- <span>🎯</span> SYNTAX Score по моделям (правая артерия)
980
- </div>
981
- {right_models_html}
982
- </div>
983
-
984
- </div>
985
-
986
- <!-- Файлы левой артерии (ВСЕ) -->
987
- <div style="background: rgba(6,182,212,0.03); border-radius: 12px; padding: 0.75rem; margin-bottom: 0.75rem; border: 1px solid rgba(6,182,212,0.1);">
988
- <div style="font-size: 0.75rem; font-weight: 700; color: #06b6d4; margin-bottom: 0.5rem; display: flex; align-items: center; gap: 0.5rem;">
989
- <span>📂</span> Файлы левой артерии (вероятность ≤ 0.10)
990
- <span style="background: #06b6d4; color: white; padding: 0 6px; border-radius: 12px; font-size: 9px;">{left_files_count}</span>
991
- </div>
992
- {left_files_html}
993
- </div>
994
-
995
- <!-- Файлы правой артерии (ВСЕ) -->
996
- <div style="background: rgba(139,92,246,0.03); border-radius: 12px; padding: 0.75rem; margin-bottom: 0.75rem; border: 1px solid rgba(139,92,246,0.1);">
997
- <div style="font-size: 0.75rem; font-weight: 700; color: #8b5cf6; margin-bottom: 0.5rem; display: flex; align-items: center; gap: 0.5rem;">
998
- <span>📂</span> Файлы правой артерии (вероятность ≥ 0.90)
999
- <span style="background: #8b5cf6; color: white; padding: 0 6px; border-radius: 12px; font-size: 9px;">{right_files_count}</span>
1000
- </div>
1001
- {right_files_html}
1002
- </div>
1003
-
1004
- <!-- Нераспознанные файлы (ВСЕ) -->
1005
- <div style="background: rgba(249,115,22,0.03); border-radius: 12px; padding: 0.75rem; border: 1px solid rgba(249,115,22,0.1);">
1006
- <div style="font-size: 0.75rem; font-weight: 700; color: #f97316; margin-bottom: 0.5rem; display: flex; align-items: center; gap: 0.5rem;">
1007
- <span>❓</span> Нераспознанные файлы (0.10 < вероятность < 0.90)
1008
- <span style="background: #f97316; color: white; padding: 0 6px; border-radius: 12px; font-size: 9px;">{other_files_count}</span>
1009
- </div>
1010
- {other_files_html}
1011
- <div style="font-size: 0.65rem; color: var(--text-light); margin-top: 0.5rem; padding-top: 0.25rem; border-top: 1px solid rgba(0,0,0,0.05);">
1012
- 💡 Вероятность классификации артерии: ≤0.10 → левая, ≥0.90 → правая
1013
- </div>
1014
- </div>
1015
-
1016
- </div>
1017
- </details>
1018
-
1019
- <!-- Дополнительная статистика (всегда видна) -->
1020
- <div style="margin-top: 1rem; padding-top: 0.75rem; border-top: 1px solid rgba(0,0,0,0.05); display: flex; justify-content: space-between; font-size: 0.65rem; color: var(--text-light);">
1021
- <span>🎯 Порог высокого риска SYNTAX: ≥22.0</span>
1022
- <span>🧠 Ансамбль моделей: {len(left_per_model)} левых / {len(right_per_model)} правых</span>
1023
- </div>
1024
- </div>
1025
- </div>
1026
- '''
1027
- cards_html.append(card_html)
1028
-
1029
- return "".join(cards_html)
1030
- def create_ui():
1031
- """Создание интерфейса в стиле Apple"""
1032
-
1033
- with gr.Blocks(title="AutoAngioScore", css=APPLE_STYLE_CSS) as demo:
1034
-
1035
- # Главный контейнер
1036
- with gr.Column(elem_classes="apple-container"):
1037
-
1038
- # Хедер
1039
- with gr.Row(elem_classes="apple-header"):
1040
- with gr.Column(scale=1, min_width=0):
1041
- logo_html = _logo_html()
1042
- if logo_html:
1043
- gr.HTML(f'<div style="margin-bottom: 1rem;">{logo_html}</div>')
1044
-
1045
- gr.HTML('''
1046
- <h1 class="apple-title">AutoAngioScore</h1>
1047
- <p class="apple-subtitle">Автоматическая оценка степени коронарного поражения по видеозаписям ангиографии</p>
1048
- ''')
1049
-
1050
- # ==================== БЛОК ДОБАВЛЕНИЯ ИССЛЕДОВАНИЯ ====================
1051
- with gr.Group(elem_classes="apple-card add-study-card"):
1052
- with gr.Column(elem_classes="apple-card-header"):
1053
- gr.HTML('<h3 class="apple-card-title">✨ Добавление нового исследования</h3>')
1054
-
1055
- with gr.Column(elem_classes="apple-card-content"):
1056
- # Информация об исследовании
1057
- with gr.Row():
1058
- study_name = gr.Textbox(
1059
- label="Идентификатор исследования",
1060
- placeholder="Например: INV-2024-001",
1061
- elem_classes="apple-input",
1062
- scale=1
1063
- )
1064
- study_desc = gr.Textbox(
1065
- label="Описан��е (необязательно)",
1066
- placeholder="Клинические данные, особенности...",
1067
- elem_classes="apple-input",
1068
- scale=1
1069
- )
1070
-
1071
- # Загрузка DICOM - две колонки
1072
- gr.HTML('<div class="upload-grid">')
1073
-
1074
- with gr.Column(elem_classes="apple-card", variant="panel"):
1075
- with gr.Column(elem_classes="apple-card-header"):
1076
- gr.HTML('<h3 class="apple-card-title" style="font-size: 1rem;">📄 Отдельные файлы</h3>')
1077
-
1078
- with gr.Column(elem_classes="apple-card-content"):
1079
- files_all = gr.File(
1080
- label="Выберите DICOM файлы",
1081
- file_count="multiple",
1082
- elem_classes="apple-input"
1083
- )
1084
- gr.HTML('''
1085
- <div style="font-size: 0.75rem; color: var(--text-secondary); margin-top: 0.5rem;">
1086
- ✓ Поддерживаются файлы .dcm
1087
- </div>
1088
- ''')
1089
-
1090
- with gr.Column(elem_classes="apple-card", variant="panel"):
1091
- with gr.Column(elem_classes="apple-card-header"):
1092
- gr.HTML('<h3 class="apple-card-title" style="font-size: 1rem;">📁 Папка с исследованием</h3>')
1093
-
1094
- with gr.Column(elem_classes="apple-card-content"):
1095
- files_folder = gr.File(
1096
- label="Выберите папку",
1097
- file_count="directory",
1098
- elem_classes="apple-input"
1099
- )
1100
- gr.HTML('''
1101
- <div style="font-size: 0.75rem; color: var(--text-secondary); margin-top: 0.5rem;">
1102
- ✓ Выберите папку, содержащую DICOM файлы
1103
- </div>
1104
- ''')
1105
-
1106
- gr.HTML('</div>')
1107
-
1108
- # Кнопки управления добавлением
1109
- with gr.Row():
1110
- btn_add = gr.Button(
1111
- "✨ Добавить в очередь",
1112
- elem_classes="apple-button-add",
1113
- scale=1
1114
- )
1115
- btn_clear = gr.Button(
1116
- "🗑️ Очистить форму",
1117
- elem_classes="apple-button-clear",
1118
- scale=1
1119
- )
1120
-
1121
- # Краткая инструкция
1122
- gr.HTML('''
1123
- <div class="instruction-box">
1124
- <div class="instruction-title">
1125
- <span>🎯</span> Быстрый старт
1126
- </div>
1127
- <ul class="instruction-list">
1128
- <li>📝 1. Укажите ID исследования</li>
1129
- <li>📂 2. Загрузите DICOM файлы</li>
1130
- <li>➕ 3. Добавьте в очередь</li>
1131
- <li>🚀 4. Запустите анализ</li>
1132
- </ul>
1133
- </div>
1134
- ''')
1135
-
1136
- # ==================== ОЧЕРЕДЬ ИССЛЕДОВАНИЙ ====================
1137
- with gr.Group(elem_classes="apple-card"):
1138
- with gr.Column(elem_classes="apple-card-header"):
1139
- gr.HTML('<h3 class="apple-card-title">📋 Очередь исследований</h3>')
1140
-
1141
- with gr.Column(elem_classes="apple-card-content"):
1142
- queue_table = gr.Dataframe(
1143
- headers=["Исследование", "Описание", "Файлов", "Статус"],
1144
- datatype=["str", "str", "number", "html"],
1145
- interactive=False,
1146
- elem_classes="apple-table",
1147
- row_count=(0, "dynamic"),
1148
- wrap=True
1149
- )
1150
-
1151
- gr.HTML('''
1152
- <div style="font-size: 0.8125rem; color: var(--text-secondary); margin-top: 0.75rem; text-align: center;">
1153
- 💡 Добавьте исследования в очередь для пакетного анализа
1154
- </div>
1155
- ''')
1156
-
1157
- # ==================== ЗАПУСК АНАЛИЗА ====================
1158
- with gr.Row():
1159
- run_btn = gr.Button(
1160
- "🚀 Запустить анализ очереди",
1161
- elem_classes="apple-button"
1162
- )
1163
-
1164
- # ==================== РЕЗУЛЬТАТЫ ====================
1165
- with gr.Group(elem_classes="apple-card"):
1166
- with gr.Column(elem_classes="apple-card-header"):
1167
- gr.HTML('<h3 class="apple-card-title">📊 Результаты анализа</h3>')
1168
-
1169
- with gr.Column(elem_classes="apple-card-content"):
1170
- out_summary = gr.HTML(label="")
1171
- out_json = gr.JSON(label="Подробные данные", visible=False) # Скрытый JSON для логики
1172
-
1173
- with gr.Row():
1174
- out_report = gr.File(
1175
- label="📥 Скачать отчет JSON",
1176
- interactive=False,
1177
- elem_classes="apple-input"
1178
- )
1179
-
1180
- # Footer
1181
- gr.HTML('''
1182
- <div style="margin-top: 3rem; padding-top: 1.5rem; border-top: 1px solid rgba(255,255,255,0.15); text-align: center; font-size: 0.75rem; color: rgba(255,255,255,0.7);">
1183
- <p>⚠️ Для исследовательских целей. Не является медицинским устройством.</p>
1184
- <p>© 2024 AutoAngioScore | Инновационная оценка коронарного поражения</p>
1185
- </div>
1186
- ''')
1187
-
1188
- # ==================== ЛОГИКА ====================
1189
- studies_state = gr.State([])
1190
-
1191
- def _add_study_fn(studies: List[Dict[str, Any]], name: str, desc: str, files, folder):
1192
- name = (name or "").strip() or f"Исследование_{len(studies)+1}"
1193
- desc = (desc or "").strip()
1194
- paths = _collect_input_paths(files, folder)
1195
-
1196
- if not paths:
1197
- table = _update_status_table(studies, "Queued")
1198
- return studies, table, name, desc, files, folder
1199
-
1200
- new_study = {
1201
- "name": name,
1202
- "description": desc,
1203
- "files": paths
1204
- }
1205
- studies = studies + [new_study]
1206
- table = _update_status_table(studies, "Queued")
1207
- return studies, table, "", "", None, None
1208
-
1209
- btn_add.click(
1210
- _add_study_fn,
1211
- inputs=[studies_state, study_name, study_desc, files_all, files_folder],
1212
- outputs=[studies_state, queue_table, study_name, study_desc, files_all, files_folder]
1213
- )
1214
-
1215
- def _clear_form():
1216
- return "", "", None, None
1217
-
1218
- btn_clear.click(_clear_form, inputs=None, outputs=[study_name, study_desc, files_all, files_folder])
1219
-
1220
- def _clear_all():
1221
- return [], []
1222
-
1223
- # Добавляем кнопку очистки очереди (скрытая функциональность)
1224
- with gr.Row(visible=False):
1225
- clear_queue = gr.Button("Очистить очередь")
1226
- clear_queue.click(_clear_all, inputs=None, outputs=[studies_state, queue_table])
1227
-
1228
- def _before_run(studies):
1229
- return _update_status_table(studies, "Running")
1230
-
1231
- def _run_infer(studies):
1232
- study_objs = []
1233
- for s in (studies or []):
1234
- study_objs.append(Study(name=s["name"], description=s.get("description", ""), files=s["files"]))
1235
- result = run_inference(study_objs)
1236
- report_path = _build_report_file(result)
1237
- return result, report_path
1238
-
1239
- def _after_run(studies, result, report_path):
1240
- table = _update_status_table(studies, "Done")
1241
- return _format_results_html(result), result, report_path, table
1242
-
1243
- run_btn.click(
1244
- _before_run,
1245
- inputs=[studies_state],
1246
- outputs=[queue_table]
1247
- ).then(
1248
- _run_infer,
1249
- inputs=[studies_state],
1250
- outputs=[out_json, out_report]
1251
- ).then(
1252
- _after_run,
1253
- inputs=[studies_state, out_json, out_report],
1254
- outputs=[out_summary, out_json, out_report, queue_table]
1255
- )
1256
-
1257
- return demo
1258
-
1259
-
1260
- if __name__ == "__main__":
1261
- favicon = LOGO_PATH if (LOGO_PATH and os.path.exists(LOGO_PATH)) else None
1262
- demo = create_ui()
1263
- demo.launch(
1264
- favicon_path=favicon,
1265
- server_name="0.0.0.0",
1266
- server_port=7860,
1267
- share=False,
1268
- )
 
1
+ """Hugging Face Docker Space entrypoint; model assets load only when requested."""
2
+ from service.api import create_app
 
 
 
 
 
 
3
 
4
+ app = create_app()
 
5
 
6
+ if __name__ == '__main__':
7
+ import os
8
+ import uvicorn
9
+ uvicorn.run(app, host='0.0.0.0', port=int(os.environ.get('PORT', '7860')), access_log=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
configs/default.yaml DELETED
@@ -1,65 +0,0 @@
1
- # configs/default.yaml — unified config for inference + artery classifier
2
-
3
- # ===== General =====
4
- seed: 42
5
- device: auto # 'cpu' | 'cuda' | 'mps' | 'auto'
6
- precision: bf16 # 'bf16' | 'fp16' | 'fp32'
7
-
8
- # Video clip packing for SYNTAX inference
9
- num_classes: 2 # [p(stenosis>=thr), log(1+score)]
10
- frames_per_clip: 32
11
- video_size: [256, 256]
12
-
13
- # ===== Backbone / Head =====
14
- backbone: r3d_18 # torchvision.models.video.r3d_18
15
- backbone_weights: DEFAULT # torchvision default Kinetics weights
16
-
17
- # Head variant: mean_out | mean | lstm_mean | lstm_last | gru_mean | gru_last | bert_mean | bert_cls | bert_cls2
18
- variant: lstm_mean
19
-
20
- a_rnn:
21
- hidden_div: 4 # hidden_size = in_features // hidden_div
22
- dropout: 0.2
23
-
24
- bert:
25
- nhead: 4
26
- num_layers: 1
27
- ff_div: 4
28
- dropout: 0.2
29
-
30
- # ===== Thresholds (reporting) =====
31
- thresholds:
32
- left: 15.0
33
- right: 5.0
34
- both: 22.0
35
-
36
- # ===== Ensemble weights (leave empty to auto-discover in weights/{left,right}) =====
37
- weights:
38
- left: [] # e.g. ["weights/left/Left_fold00.pt", ...]
39
- right: [] # e.g. ["weights/right/Right_fold00.pt", ...]
40
-
41
- # Optional: HF model repo to auto-fetch weights if local not found.
42
- # Can be overridden by env var WEIGHTS_REPO.
43
- weights_repo: "MesserMMP/syntax-video-weights"
44
-
45
- # ===== Artery classifier (do NOT change preprocessing; keep identical to training) =====
46
- classifier:
47
- # path to Lightning/pt weights; must exist in the runtime
48
- weights: "assets/r3d_art.pt"
49
- # subdir in weights_repo
50
- hf_subdir: "classifier"
51
-
52
- # preprocessing params used in the classifier pipeline
53
- video_size: [224, 224]
54
- mean: [0.485, 0.456, 0.406]
55
- std: [0.229, 0.224, 0.225]
56
-
57
- # routing thresholds on sigmoid probability:
58
- # prob <= left_max -> LEFT
59
- # prob >= right_min -> RIGHT
60
- thresholds:
61
- left_max: 0.10
62
- right_min: 0.90
63
-
64
- # ===== Inference loader (not strictly used, kept for completeness) =====
65
- batch_size: 1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
engine/README.md ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Inference contract
2
+
3
+ `engine` exposes `inspect(path)`, `classify(paths, progress=None)`,
4
+ `infer(left_paths, right_paths, progress=None)`, and `status()`.
5
+ The progress callback receives `(stage: str, detail: dict)`; detail includes
6
+ `fraction`, `current`, and `total` when the amount of work is known.
7
+ Importing the API and calling `status()` neither downloads nor loads a model.
8
+
9
+ ## Provenance and loading
10
+
11
+ The source is `MesserMMP/coronary-syntax-prediction` at the immutable revision
12
+ in `manifest.json`. Ten complete R3D-18 + projected-LSTM checkpoints are used:
13
+ five left and five right models, paired by fold. The artery classifier is a
14
+ separate R3D-18. Safetensors are loaded strictly, after verifying their SHA-256
15
+ hash and expected size. Calibration is fetched from the same revision and
16
+ its checksum and coefficients are also verified. No legacy pickle checkpoints,
17
+ secondary weights repository, randomly initialized fallback, or incomplete
18
+ ensemble is used.
19
+
20
+ Set `SYNTAX_MODEL_CACHE` to a directory whose relative paths match the model
21
+ repository. Missing files are fetched on demand. Set `SYNTAX_DEVICE=cpu`
22
+ (default) or `cuda` on a compatible machine; `SYNTAX_CPU_THREADS` defaults to 2.
23
+ Models run sequentially in float32 and are released after use. Only one
24
+ projection's backbone activations are retained at a time, followed by the
25
+ original LSTM over the ordered features.
26
+
27
+ ## Input and preprocessing
28
+
29
+ The supported input is an unsigned 8-bit or 16-bit, single-channel DICOM cine
30
+ with 10–1024 frames and at most 512 MiB of decoded pixels. DICOM header
31
+ dimensions must match the pixels. StudyInstanceUID and SOPInstanceUID must be
32
+ retained. Mixed-study inputs and repeated SOPInstanceUIDs are rejected. Source
33
+ files are read without modification. Returned metadata excludes patient names,
34
+ patient identifiers, dates, institution names, and free-text DICOM fields.
35
+
36
+ The score transform matches `full_model/rnn_dataset.py`: uint16 is scaled by
37
+ the maximum value of the entire sequence to uint8; shorter-than-32-frame clips
38
+ are doubled repeatedly, then the central 32 frames are selected. Grayscale is
39
+ replicated into RGB, scaled to [0, 1], bilinearly resized to 256×256 with
40
+ antialiasing, and normalized with ImageNet mean and standard deviation.
41
+ Windowing, rescale, and MONOCHROME1 inversion are not applied because the
42
+ published pipeline reads `pixel_array` directly. Unsupported signed, color,
43
+ or single-frame input is rejected instead of being silently reinterpreted.
44
+
45
+ Within each artery, input order is retained exactly. The LSTM is
46
+ order-sensitive, so filename sorting would change predictions. To reproduce
47
+ an evaluation study, pass the paths in `videos_left` and `videos_right` order.
48
+
49
+ ## Artery assignment
50
+
51
+ The classifier uses all original frames, RGB grayscale at 224×224, bilinear
52
+ tensor resizing with `antialias=False`, and ImageNet normalization.
53
+ `probability_right` is sigmoid of its one output:
54
+ left is ≤0.1, right is ≥0.9, and values between these thresholds are unassigned.
55
+ This is artery probability, not confidence in a SYNTAX estimate. The service
56
+ can supply manually reviewed left/right lists directly to `infer`.
57
+
58
+ The antialias setting is explicit because torchvision changed its unspecified
59
+ default in version 0.17. The archived Philips probabilities are reproduced by
60
+ `False`; the recently repaired Siemens examples were classified with `True`.
61
+ All artery groups in the two verification studies agree under both settings,
62
+ but their probabilities differ. This does not guarantee identical grouping for
63
+ every possible input, so automatic assignments remain reviewable. Published
64
+ examples use their existing JSON assignments. The score model separately uses
65
+ `antialias=True`, as explicitly specified by its reference inference code.
66
+ See the [official Resize documentation](https://docs.pytorch.org/vision/0.21/generated/torchvision.transforms.Resize.html).
67
+
68
+ For long sequences, classifier convolution uses temporal tiles with 56-frame
69
+ context on either side, aligned to the final temporal stride of 8. R3D-18 has
70
+ a 109-frame temporal receptive field. Disjoint final feature positions are
71
+ averaged once, so all original frames contribute without subsampling. Minor
72
+ floating-point differences relative to one large batch are expected.
73
+
74
+ ## Scores and calibration
75
+
76
+ Each artery model's second output is log(1 + artery SYNTAX). Its score is
77
+ `float(torch.exp(output)) - 1`. The first output is an artery-specific binary
78
+ logit and is not exposed as a total disease probability.
79
+
80
+ For fold i, calculate `raw_i = left_i + right_i` and
81
+ `calibrated_i = a_i * raw_i + b_i`. Average each of those five values, then
82
+ clip only the final study score at zero. Do not clip artery/fold intermediate
83
+ values, apply calibration separately to arteries, or calibrate an ensemble
84
+ mean with averaged coefficients. The returned `per_fold` values preserve the
85
+ unclipped intermediates for reproducibility.
86
+
87
+ If a side is absent, its score is `null` and both study totals are `null` with
88
+ `complete=false`. The present side can still be inspected. The original batch
89
+ evaluation represented missing sides by zero; this interactive service instead
90
+ makes incompleteness explicit, because absence of an artery view does not show
91
+ that the artery has no disease.
92
+
93
+ ## Validation
94
+
95
+ Run `python -m unittest engine.test_engine -v` for offline transform, tiling,
96
+ architecture, calibration, and checkpoint-integrity checks.
97
+ `python -m engine.validate_reference --help` describes the optional real-data
98
+ check. It compares explicit JSON grouping/order to archived evaluation results,
99
+ and can execute the original source model and dataset on CPU for an independent
100
+ batched comparison. It does not download or alter input studies.
engine/__init__.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pinned, lazy inference API. Importing this module never loads a model."""
2
+ from .dicom import InferenceError, inspect, read_video
3
+ from .weights import status
4
+
5
+
6
+ def classify(paths, progress=None):
7
+ from .runtime import classify as run
8
+ return run(paths, progress=progress)
9
+
10
+
11
+ def infer(left_paths, right_paths, progress=None):
12
+ from .runtime import infer as run
13
+ return run(left_paths, right_paths, progress=progress)
14
+
15
+
16
+ def preprocess(video, *, classifier=False):
17
+ from .preprocessing import preprocess_classifier, preprocess_score
18
+ return preprocess_classifier(video) if classifier else preprocess_score(video)
19
+
20
+
21
+ __all__ = ["InferenceError", "inspect", "read_video", "preprocess", "classify", "infer", "status"]
engine/architecture.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Inference-only architecture with state keys identical to the published checkpoint."""
2
+ import torch
3
+ from torch import nn
4
+ from torchvision.models.video import r3d_18
5
+
6
+
7
+ class SyntaxModel(nn.Module):
8
+ def __init__(self):
9
+ super().__init__()
10
+ # Full checkpoints already contain the backbone. No Kinetics download.
11
+ self.model = r3d_18(weights=None)
12
+ self.model.fc = nn.Identity()
13
+ self.lstm = nn.LSTM(512, 128, proj_size=2, batch_first=True)
14
+
15
+ def aggregate(self, features):
16
+ outputs, _ = self.lstm(features)
17
+ return outputs.mean(dim=1)
18
+
19
+ def forward(self, clips):
20
+ batch, sequence = clips.shape[:2]
21
+ features = self.model(clips.flatten(0, 1)).unflatten(0, (batch, sequence))
22
+ return self.aggregate(features)
23
+
24
+ def forward_stream(self, clips, device="cpu", progress=None):
25
+ features = []
26
+ for index, clip in enumerate(clips):
27
+ features.append(self.model(clip.unsqueeze(0).to(device)))
28
+ if progress:
29
+ progress(index + 1)
30
+ return self.aggregate(torch.stack(features, dim=1))
31
+
32
+
33
+ def artery_model():
34
+ model = r3d_18(weights=None)
35
+ model.fc = nn.Linear(512, 1)
36
+ return model
37
+
38
+
39
+ def classifier_stream(model, frame_count, get_clip, device="cpu", chunk_outputs=16):
40
+ """Exact R3D-18 temporal tiling, with bounded activation memory.
41
+
42
+ Its final feature map has temporal stride 8 and receptive field 109. A
43
+ 56-frame context (rounded up to a multiple of 8) on either side therefore
44
+ preserves every output's complete context and global stride alignment.
45
+ Only disjoint final feature positions contribute to global average pooling;
46
+ overlap is context, never a duplicate acquisition or a repeated prediction.
47
+ get_clip(start, stop) returns the normalized C,T,H,W source interval.
48
+ """
49
+ total_outputs = (frame_count + 7) // 8
50
+ pooled_sum = None
51
+ for output_start in range(0, total_outputs, chunk_outputs):
52
+ output_stop = min(output_start + chunk_outputs, total_outputs)
53
+ source_start = max(0, output_start * 8 - 56)
54
+ source_stop = min(frame_count, output_stop * 8 + 56)
55
+ clip = get_clip(source_start, source_stop).unsqueeze(0).to(device)
56
+ features = model.layer4(model.layer3(model.layer2(model.layer1(model.stem(clip)))))
57
+ first = output_start - source_start // 8
58
+ features = features[:, :, first:first + output_stop - output_start]
59
+ contribution = features.mean(dim=(-2, -1)).sum(dim=2)
60
+ pooled_sum = contribution if pooled_sum is None else pooled_sum + contribution
61
+ del clip, features
62
+ return model.fc(pooled_sum / total_outputs)
engine/dicom.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """DICOM input checks; no source files or patient metadata are modified."""
2
+ from pathlib import Path
3
+
4
+ MIN_FRAMES = 10
5
+ MAX_FRAMES = 1024
6
+ MAX_DECODED_BYTES = 512 * 1024 * 1024
7
+
8
+
9
+ class InferenceError(RuntimeError):
10
+ """An actionable validation or inference failure, never a numeric fallback."""
11
+
12
+
13
+ def inspect(path):
14
+ import pydicom
15
+ tags = ["StudyInstanceUID", "SeriesInstanceUID", "SOPInstanceUID", "NumberOfFrames",
16
+ "Rows", "Columns", "SamplesPerPixel", "BitsAllocated", "PixelRepresentation",
17
+ "PhotometricInterpretation"]
18
+ try:
19
+ ds = pydicom.dcmread(str(path), stop_before_pixels=True, specific_tags=tags)
20
+ result = {
21
+ "path": str(path),
22
+ "study_uid": str(ds.get("StudyInstanceUID", "")),
23
+ "series_uid": str(ds.get("SeriesInstanceUID", "")),
24
+ "sop_uid": str(ds.get("SOPInstanceUID", "")),
25
+ "frames": int(ds.get("NumberOfFrames", 1)),
26
+ "rows": int(ds.get("Rows", 0)),
27
+ "columns": int(ds.get("Columns", 0)),
28
+ "samples_per_pixel": int(ds.get("SamplesPerPixel", 1)),
29
+ "bits_allocated": int(ds.get("BitsAllocated", 0)),
30
+ "pixel_representation": int(ds.get("PixelRepresentation", 0)),
31
+ "photometric_interpretation": str(ds.get("PhotometricInterpretation", "")),
32
+ }
33
+ except Exception as exc:
34
+ raise InferenceError(f"Cannot read DICOM header: {Path(path).name}.") from exc
35
+ result["eligible"] = (
36
+ MIN_FRAMES <= result["frames"] <= MAX_FRAMES
37
+ and result["rows"] > 0 and result["columns"] > 0
38
+ and result["samples_per_pixel"] == 1
39
+ and result["bits_allocated"] in (8, 16)
40
+ and result["pixel_representation"] == 0
41
+ and result["photometric_interpretation"] in ("MONOCHROME1", "MONOCHROME2")
42
+ )
43
+ return result
44
+
45
+
46
+ def read_video(path):
47
+ """Return raw unsigned grayscale frames; preserve the reference pixel convention."""
48
+ import numpy as np
49
+ import pydicom
50
+ meta = inspect(path)
51
+ if not meta["eligible"]:
52
+ raise InferenceError(
53
+ f"{Path(path).name}: use an unsigned 8/16-bit grayscale DICOM cine "
54
+ f"with {MIN_FRAMES}–{MAX_FRAMES} frames."
55
+ )
56
+ if meta["frames"] * meta["rows"] * meta["columns"] * (meta["bits_allocated"] // 8) > MAX_DECODED_BYTES:
57
+ raise InferenceError(f"{Path(path).name}: the decoded video exceeds the memory limit.")
58
+ try:
59
+ video = pydicom.dcmread(str(path)).pixel_array
60
+ except Exception as exc:
61
+ raise InferenceError(f"Cannot decode DICOM pixels: {Path(path).name}.") from exc
62
+ if video.ndim != 3 or tuple(video.shape) != (meta["frames"], meta["rows"], meta["columns"]):
63
+ raise InferenceError(f"{Path(path).name}: pixel dimensions do not match its DICOM header.")
64
+ if video.dtype.kind != "u" or video.dtype.itemsize not in (1, 2):
65
+ raise InferenceError(f"{Path(path).name}: unsupported pixel data type.")
66
+ # Rescale/windowing and MONOCHROME1 inversion are deliberately not applied:
67
+ # the published model reads pixel_array directly using these conventions.
68
+ return np.asarray(video)
69
+
70
+
71
+ def validate_study(paths):
72
+ """Reject mixed studies and duplicate acquisitions without reordering paths."""
73
+ records = [inspect(path) for path in paths]
74
+ if not records:
75
+ raise InferenceError("Select at least one angiography projection.")
76
+ if any(not record["study_uid"] or not record["sop_uid"] for record in records):
77
+ raise InferenceError("Each DICOM must retain StudyInstanceUID and SOPInstanceUID.")
78
+ if len({r["study_uid"] for r in records}) != 1:
79
+ raise InferenceError("The selected projections belong to different studies.")
80
+ if len({r["sop_uid"] for r in records}) != len(records):
81
+ raise InferenceError("A projection is included more than once (duplicate SOPInstanceUID).")
82
+ if any(not r["eligible"] for r in records):
83
+ raise InferenceError("Remove unsupported or fewer-than-10-frame projections before inference.")
84
+ return records
engine/manifest.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "repo_id": "MesserMMP/coronary-syntax-prediction",
3
+ "revision": "f6099168eef127991e6cdbc420f24c0fc74d914c",
4
+ "architecture": "torchvision.r3d_18 + LSTM(512,128,proj_size=2), mean outputs",
5
+ "preprocessing": {
6
+ "score": {"frames":32,"size":256,"antialias":true,"normalization":"ImageNet"},
7
+ "classifier": {"frames":"all","size":224,"antialias":false,"normalization":"ImageNet","profile":"historical_tensor_resize"}
8
+ },
9
+ "score_weights": [
10
+ {"side":"left","fold":0,"path":"full_model_weights/LeftBinSyntax_R3D_fold00_lstm_mean_post_best.safetensors","size":133773944,"sha256":"d60de48ea47a3fbe516ca5d90ba79ec5d7dea5b04b037df20cf75e3a6f78ad66"},
11
+ {"side":"left","fold":1,"path":"full_model_weights/LeftBinSyntax_R3D_fold01_lstm_mean_post_best.safetensors","size":133773944,"sha256":"829b51322384437b6838fdc92ac5ca35c0d3de21e00d1ac95985e2ddb436f712"},
12
+ {"side":"left","fold":2,"path":"full_model_weights/LeftBinSyntax_R3D_fold02_lstm_mean_post_best.safetensors","size":133773944,"sha256":"79bfe68701be33d232037f8755b98729c48944f330b48fb6fa489d8151485221"},
13
+ {"side":"left","fold":3,"path":"full_model_weights/LeftBinSyntax_R3D_fold03_lstm_mean_post_best.safetensors","size":133773944,"sha256":"57f5cb930f30d42f16111dc8f66cbd419f6f11adb5bab601ccd8980b763daa93"},
14
+ {"side":"left","fold":4,"path":"full_model_weights/LeftBinSyntax_R3D_fold04_lstm_mean_post_best.safetensors","size":133773944,"sha256":"b8746300aa112d9077639664754e7c116d13c4ab88fa594eac7ffa1e35bd4dfe"},
15
+ {"side":"right","fold":0,"path":"full_model_weights/RightBinSyntax_R3D_fold00_lstm_mean_post_best.safetensors","size":133773944,"sha256":"b89a9368b9b040e7683b1590468d18d7c77cb44827749bc1ae7c95a7270eb696"},
16
+ {"side":"right","fold":1,"path":"full_model_weights/RightBinSyntax_R3D_fold01_lstm_mean_post_best.safetensors","size":133773944,"sha256":"ca2936688de41045cc1149364275d151c82d5da6d1aa9be123bed086fa3a48a3"},
17
+ {"side":"right","fold":2,"path":"full_model_weights/RightBinSyntax_R3D_fold02_lstm_mean_post_best.safetensors","size":133773944,"sha256":"804f8a7b1c1bfce0e290b83923f7f81e8043e44af19cef96e3b88af25ba5cec6"},
18
+ {"side":"right","fold":3,"path":"full_model_weights/RightBinSyntax_R3D_fold03_lstm_mean_post_best.safetensors","size":133773944,"sha256":"faf9994b09d27b4b48c7498bb2cbb4dde79636b4e766e6d6ee9f8ff61734ce1c"},
19
+ {"side":"right","fold":4,"path":"full_model_weights/RightBinSyntax_R3D_fold04_lstm_mean_post_best.safetensors","size":133773944,"sha256":"290a6dd922290fde6a4010146015404e4cdb748631bbb578bdbc0a94db025bda"}
20
+ ],
21
+ "classifier": {"path":"classifier_weights/r3d_art.safetensors","size":132717196,"sha256":"d3516fbad1d4b82927a553763bc1b5751ea5196e78299743d33326c5e0cbd312"},
22
+ "calibration": {
23
+ "path":"scaling_coeffs/scaling_coeffs.json",
24
+ "sha256":"2d7fcea581914bccd5618b2534a67f85a2d559d70ecdb4861746f01497253427",
25
+ "folds":[{"a":1.65,"b":0.4},{"a":1.29,"b":0.38},{"a":1.28,"b":0.365},{"a":1.11,"b":0.42},{"a":1.61,"b":0.385}]
26
+ }
27
+ }
engine/preprocessing.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The published inference transforms, without augmentation or temporal resampling."""
2
+ import numpy as np
3
+ import torch
4
+ from torchvision.transforms import InterpolationMode
5
+ from torchvision.transforms.functional import resize
6
+
7
+ from .dicom import InferenceError
8
+
9
+ MEAN = (0.485, 0.456, 0.406)
10
+ STD = (0.229, 0.224, 0.225)
11
+
12
+
13
+ def to_uint8(video):
14
+ video = np.asarray(video)
15
+ if video.ndim != 3 or video.shape[0] == 0:
16
+ raise InferenceError("Expected a non-empty grayscale video with shape frames × height × width.")
17
+ if video.dtype.kind != "u" or video.dtype.itemsize not in (1, 2):
18
+ raise InferenceError("Only unsigned 8-bit and 16-bit videos are supported.")
19
+ if video.dtype.itemsize == 2:
20
+ vmax = int(video.max())
21
+ if vmax <= 0:
22
+ raise InferenceError("The 16-bit video has no usable pixel intensities.")
23
+ return (video.astype(np.float32) * (255.0 / vmax)).clip(0, 255).astype(np.uint8)
24
+ return video.astype(np.uint8, copy=False)
25
+
26
+
27
+ def _transform(video, size, *, antialias):
28
+ # Identical to ToTensorVideo -> Resize -> pytorchvideo.Normalize.
29
+ rgb = np.stack([video, video, video], axis=-1)
30
+ x = torch.from_numpy(rgb).permute(3, 0, 1, 2).to(dtype=torch.float32).div(255.0)
31
+ x = resize(x, [size, size], interpolation=InterpolationMode.BILINEAR, antialias=antialias)
32
+ mean = x.new_tensor(MEAN).view(3, 1, 1, 1)
33
+ std = x.new_tensor(STD).view(3, 1, 1, 1)
34
+ return (x - mean) / std
35
+
36
+
37
+ def preprocess_score(video):
38
+ video = to_uint8(video)
39
+ while video.shape[0] < 32:
40
+ video = np.concatenate([video, video], axis=0)
41
+ begin = (video.shape[0] - 32) // 2
42
+ return _transform(video[begin:begin + 32], 256, antialias=True)
43
+
44
+
45
+ def preprocess_classifier(video):
46
+ # The classifier uses every original frame, not the score model's 32-frame clip.
47
+ # Explicit legacy tensor resize reproduces the archived Philips classifier
48
+ # probabilities. Torchvision changed its unspecified default in version 0.17.
49
+ return _transform(to_uint8(video), 224, antialias=False)
engine/runtime.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """One model at a time; preserve projection order and fail on incomplete ensembles."""
2
+ import gc
3
+ import math
4
+ import os
5
+ import threading
6
+
7
+ import torch
8
+ from safetensors.torch import load_file
9
+
10
+ from .architecture import SyntaxModel, artery_model, classifier_stream
11
+ from .dicom import InferenceError, inspect, read_video, validate_study
12
+ from .preprocessing import preprocess_classifier, preprocess_score, to_uint8
13
+ from .weights import MANIFEST, calibration, weight_file
14
+
15
+ _lock = threading.Lock()
16
+
17
+
18
+ def _device():
19
+ requested = os.environ.get("SYNTAX_DEVICE", "cpu").lower()
20
+ if requested == "cpu":
21
+ torch.set_num_threads(max(1, int(os.environ.get("SYNTAX_CPU_THREADS", "2"))))
22
+ return torch.device("cpu")
23
+ if requested == "cuda" and torch.cuda.is_available():
24
+ return torch.device("cuda")
25
+ # Projected LSTM support differs across MPS builds; no silent device fallback.
26
+ raise InferenceError("The configured inference device is unavailable. Use cpu or an available cuda device.")
27
+
28
+
29
+ def _load(factory, record, device, progress):
30
+ path = weight_file(record, progress)
31
+ model = factory()
32
+ try:
33
+ model.load_state_dict(load_file(str(path), device="cpu"), strict=True)
34
+ model.to(device).eval()
35
+ except Exception as exc:
36
+ raise InferenceError(f"The required checkpoint could not be loaded: {record['path']}.") from exc
37
+ return model
38
+
39
+
40
+ def _release(device):
41
+ gc.collect()
42
+ if device.type == "cuda":
43
+ torch.cuda.empty_cache()
44
+
45
+
46
+ def classify(paths, progress=None):
47
+ paths = [str(path) for path in paths]
48
+ records = [inspect(path) for path in paths]
49
+ eligible = [r for r in records if r["eligible"]]
50
+ outputs = []
51
+ if not eligible:
52
+ return [{"path": r["path"], "artery": "exclude", "probability": None,
53
+ "probability_right": None, "reason": "Unsupported DICOM or fewer than 10 usable frames"}
54
+ for r in records]
55
+ with _lock, torch.inference_mode():
56
+ device = _device()
57
+ model = _load(artery_model, MANIFEST["classifier"], device, progress)
58
+ try:
59
+ for index, record in enumerate(records):
60
+ if not record["eligible"]:
61
+ outputs.append({"path": record["path"], "artery": "exclude", "probability": None,
62
+ "probability_right": None, "reason": "Unsupported DICOM or fewer than 10 usable frames"})
63
+ continue
64
+ if progress:
65
+ progress("classify", {"current": index, "total": len(records),
66
+ "fraction": index / len(records), "message": "Identifying coronary artery"})
67
+ video = to_uint8(read_video(record["path"]))
68
+ logits = classifier_stream(model, len(video),
69
+ lambda start, stop: preprocess_classifier(video[start:stop]), device=device)
70
+ probability = float(torch.sigmoid(logits)[0, 0].cpu())
71
+ del video, logits
72
+ if not math.isfinite(probability):
73
+ raise InferenceError("The artery classifier returned a non-finite result.")
74
+ side = "left" if probability <= 0.1 else "right" if probability >= 0.9 else "unassigned"
75
+ outputs.append({"path": record["path"], "artery": side, "probability": probability,
76
+ "probability_right": probability,
77
+ "preprocessing": MANIFEST["preprocessing"]["classifier"],
78
+ "reason": "Review uncertain artery" if side == "unassigned" else None})
79
+ finally:
80
+ del model
81
+ _release(device)
82
+ if progress:
83
+ progress("classify", {"current": len(records), "total": len(records), "fraction": 1.0})
84
+ return outputs
85
+
86
+
87
+ def combine_folds(left, right, coefficients):
88
+ if len(left) != 5 or len(right) != 5 or len(coefficients) != 5:
89
+ raise InferenceError("The complete five-fold ensemble is required for each artery.")
90
+ if not all(math.isfinite(float(value)) for value in left + right):
91
+ raise InferenceError("The model returned a non-finite score.")
92
+ folds = []
93
+ for index, (lval, rval, coeff) in enumerate(zip(left, right, coefficients)):
94
+ raw = lval + rval
95
+ adjusted = coeff["a"] * raw + coeff["b"]
96
+ if not math.isfinite(adjusted):
97
+ raise InferenceError("Calibration returned a non-finite score.")
98
+ folds.append({"fold": index, "left": lval, "right": rval, "raw": raw,
99
+ "calibrated": adjusted, "a": coeff["a"], "b": coeff["b"]})
100
+ return {
101
+ "raw": max(0.0, sum(f["raw"] for f in folds) / 5),
102
+ "calibrated": max(0.0, sum(f["calibrated"] for f in folds) / 5),
103
+ "per_fold": folds,
104
+ }
105
+
106
+
107
+ def infer(left_paths, right_paths, progress=None):
108
+ left_paths, right_paths = list(map(str, left_paths)), list(map(str, right_paths))
109
+ records = validate_study(left_paths + right_paths)
110
+ complete = bool(left_paths and right_paths)
111
+ provenance = {
112
+ "repo_id": MANIFEST["repo_id"], "revision": MANIFEST["revision"],
113
+ "architecture": MANIFEST["architecture"], "precision": "float32",
114
+ "preprocessing": "32 center frames; repeat short clips; RGB grayscale; 256x256; ImageNet normalization",
115
+ "projection_order": "input order within each artery",
116
+ "calibration": "max(0, mean_i(a_i * (left_i + right_i) + b_i))",
117
+ "calibration_source": {"path": MANIFEST["calibration"]["path"],
118
+ "sha256": MANIFEST["calibration"]["sha256"],
119
+ "folds": MANIFEST["calibration"]["folds"]},
120
+ "ordered_inputs": {
121
+ "left": [{key: record[key] for key in ("sop_uid", "series_uid", "frames")}
122
+ for record in records[:len(left_paths)]],
123
+ "right": [{key: record[key] for key in ("sop_uid", "series_uid", "frames")}
124
+ for record in records[len(left_paths):]],
125
+ },
126
+ "weights": [],
127
+ }
128
+ predictions = {"left": [], "right": []}
129
+ total_steps = 5 * (len(left_paths) + len(right_paths))
130
+ completed_steps = 0
131
+ with _lock, torch.inference_mode():
132
+ device = _device()
133
+ provenance["device"] = str(device)
134
+ coefficients = calibration(progress)
135
+ for side, paths in (("left", left_paths), ("right", right_paths)):
136
+ if not paths:
137
+ continue
138
+ # One preprocessed clip at a time bounds activation memory. Each backbone
139
+ # is in eval mode, so per-projection feature extraction is equivalent to a batch.
140
+ for record in [r for r in MANIFEST["score_weights"] if r["side"] == side]:
141
+ model = _load(SyntaxModel, record, device, progress)
142
+ fold = record["fold"]
143
+ def report(current):
144
+ if progress:
145
+ progress("infer", {"side": side, "fold": fold, "current": completed_steps + current,
146
+ "total": total_steps, "fraction": (completed_steps + current) / total_steps,
147
+ "message": f"Processing {side} artery · model {fold + 1} of 5"})
148
+ try:
149
+ clips = (preprocess_score(read_video(path)) for path in paths)
150
+ output = model.forward_stream(clips, device=device, progress=report)
151
+ # Match canonical float32 torch.exp then float subtraction exactly.
152
+ value = float(torch.exp(output[0, 1]).cpu()) - 1.0
153
+ if not math.isfinite(value):
154
+ raise InferenceError("A model returned a non-finite artery score.")
155
+ predictions[side].append(value)
156
+ provenance["weights"].append({"path": record["path"], "sha256": record["sha256"]})
157
+ completed_steps += len(paths)
158
+ finally:
159
+ del model
160
+ _release(device)
161
+ result = combine_folds(predictions["left"], predictions["right"], coefficients) if complete else {
162
+ "raw": None, "calibrated": None, "per_fold": [],
163
+ }
164
+ result.update({
165
+ "complete": complete, "study_uid": records[0]["study_uid"],
166
+ "left": {"raw": sum(predictions["left"]) / 5 if left_paths else None,
167
+ "per_fold": predictions["left"], "projections": len(left_paths)},
168
+ "right": {"raw": sum(predictions["right"]) / 5 if right_paths else None,
169
+ "per_fold": predictions["right"], "projections": len(right_paths)},
170
+ "projection_count": len(records), "provenance": provenance,
171
+ "message": None if complete else "Incomplete study: both left and right coronary projections are required for a total SYNTAX estimate.",
172
+ })
173
+ return result
engine/test_engine.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Offline contract tests: python -m unittest engine.test_engine -v."""
2
+ import hashlib
3
+ import os
4
+ import tempfile
5
+ import unittest
6
+ from pathlib import Path
7
+ from unittest.mock import patch
8
+
9
+ import numpy as np
10
+ import torch
11
+ from torchvision.transforms import Resize
12
+ from torchvision.transforms._transforms_video import ToTensorVideo
13
+
14
+ from .architecture import SyntaxModel, artery_model, classifier_stream
15
+ from .dicom import InferenceError
16
+ from .preprocessing import MEAN, STD, preprocess_classifier, preprocess_score, to_uint8
17
+ from .runtime import combine_folds
18
+ from .weights import MANIFEST, weight_file
19
+
20
+
21
+ class EngineTests(unittest.TestCase):
22
+ def test_transform_matches_reference_and_repeat_center_order(self):
23
+ source = np.arange(10 * 25 * 27, dtype=np.uint16).reshape(10, 25, 27)
24
+ video = (source.astype(np.float32) * (255.0 / int(source.max()))).clip(0, 255).astype(np.uint8)
25
+ video = np.concatenate([video, video, video, video])[4:36]
26
+ expected = ToTensorVideo()(torch.from_numpy(np.stack([video] * 3, axis=-1)))
27
+ expected = Resize((256, 256), antialias=True)(expected)
28
+ expected = (expected - torch.tensor(MEAN)[:, None, None, None]) / torch.tensor(STD)[:, None, None, None]
29
+ torch.testing.assert_close(preprocess_score(source), expected, rtol=0, atol=0)
30
+
31
+ def test_signed_and_empty_inputs_fail(self):
32
+ for video in [np.zeros((10, 2, 2), dtype=np.int16), np.zeros((0, 2, 2), dtype=np.uint8),
33
+ np.zeros((10, 2, 2), dtype=np.uint16)]:
34
+ with self.assertRaises(InferenceError):
35
+ to_uint8(video)
36
+
37
+ def test_classifier_transform_pins_historical_resize_and_all_frames(self):
38
+ source = np.random.default_rng(7).integers(0, 256, (35, 29, 31), dtype=np.uint8)
39
+ expected = ToTensorVideo()(torch.from_numpy(np.stack([source] * 3, axis=-1)))
40
+ expected = Resize((224, 224), antialias=False)(expected)
41
+ expected = (expected - torch.tensor(MEAN)[:, None, None, None]) / torch.tensor(STD)[:, None, None, None]
42
+ torch.testing.assert_close(preprocess_classifier(source), expected, rtol=0, atol=0)
43
+ self.assertFalse(MANIFEST["preprocessing"]["classifier"]["antialias"])
44
+ self.assertTrue(MANIFEST["preprocessing"]["score"]["antialias"])
45
+
46
+ def test_calibration_pairs_folds_and_clips_only_final_mean(self):
47
+ left = [-4., 1., 2., 3., 4.]
48
+ right = [1., 2., -4., 0., 1.]
49
+ coefficients = MANIFEST["calibration"]["folds"]
50
+ result = combine_folds(left, right, coefficients)
51
+ expected = sum(c["a"] * (l + r) + c["b"] for l, r, c in zip(left, right, coefficients)) / 5
52
+ self.assertAlmostEqual(result["calibrated"], max(0., expected))
53
+ self.assertEqual(result["per_fold"][0]["raw"], -3.)
54
+ self.assertEqual(result["per_fold"][2]["raw"], -2.)
55
+ with self.assertRaises(InferenceError):
56
+ combine_folds(left[:-1], right, coefficients)
57
+ with self.assertRaises(InferenceError):
58
+ combine_folds([float("nan")] * 5, right, coefficients)
59
+
60
+ def test_streamed_architecture_matches_batched_and_uses_projection_order(self):
61
+ torch.manual_seed(1)
62
+ torch.set_num_threads(2)
63
+ model = SyntaxModel().eval()
64
+ clips = torch.randn(1, 3, 3, 4, 32, 32)
65
+ with torch.inference_mode():
66
+ batch = model(clips)
67
+ stream = model.forward_stream(iter(clips[0]))
68
+ reverse = model.forward_stream(iter(clips[0].flip(0)))
69
+ torch.testing.assert_close(batch, stream, rtol=1e-5, atol=1e-6)
70
+ self.assertFalse(torch.allclose(stream, reverse, rtol=1e-5, atol=1e-6))
71
+
72
+ def test_corrupt_checkpoint_rejected_before_loading(self):
73
+ with tempfile.TemporaryDirectory() as folder, patch.dict(os.environ, {"SYNTAX_MODEL_CACHE": folder}):
74
+ path = Path(folder) / "model.safetensors"
75
+ path.write_bytes(b"bad")
76
+ with self.assertRaisesRegex(InferenceError, "checksum"):
77
+ weight_file({"path": path.name, "size": 3, "sha256": hashlib.sha256(b"yes").hexdigest()})
78
+
79
+ def test_classifier_temporal_tiling_matches_all_frames(self):
80
+ torch.manual_seed(9)
81
+ torch.set_num_threads(2)
82
+ model = artery_model().eval()
83
+ # Exercise real boundaries and non-stride-aligned total lengths.
84
+ for frames in (7, 127, 195):
85
+ clip = torch.randn(3, frames, 24, 24)
86
+ with torch.inference_mode():
87
+ full = model(clip.unsqueeze(0))
88
+ tiled = classifier_stream(model, frames, lambda a, b: clip[:, a:b], chunk_outputs=4)
89
+ torch.testing.assert_close(full, tiled, rtol=2e-5, atol=2e-6)
90
+
91
+
92
+ if __name__ == "__main__":
93
+ unittest.main()
engine/validate_classifier.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Compare explicit reference classifier transforms with archived probabilities."""
2
+ import argparse
3
+ import json
4
+ from pathlib import Path
5
+
6
+ import numpy as np
7
+ import torch
8
+ from safetensors.torch import load_file
9
+ from torchvision.models.video import r3d_18
10
+ from torchvision.transforms import Resize
11
+ from torchvision.transforms._transforms_video import ToTensorVideo
12
+
13
+ from .dicom import read_video
14
+ from .preprocessing import to_uint8
15
+ from .runtime import _device
16
+ from .weights import MANIFEST, weight_file
17
+
18
+
19
+ def main():
20
+ parser = argparse.ArgumentParser()
21
+ parser.add_argument("--fixtures", type=Path, required=True)
22
+ parser.add_argument("--output", type=Path, required=True)
23
+ parser.add_argument("--dataset", default="philips_97")
24
+ parser.add_argument("--all-frames-only", action="store_true")
25
+ parser.add_argument("--antialias", choices=("true", "false", "both"), default="both")
26
+ args = parser.parse_args()
27
+ device = _device()
28
+ model = r3d_18(weights=None)
29
+ model.fc = torch.nn.Linear(512, 1)
30
+ model.load_state_dict(load_file(str(weight_file(MANIFEST["classifier"])), device="cpu"), strict=True)
31
+ model.to(device).eval()
32
+ report = []
33
+ with torch.inference_mode():
34
+ for case in json.loads(args.fixtures.read_text()):
35
+ if case["dataset"] != args.dataset:
36
+ continue
37
+ for projection in case["study"]["videos"]:
38
+ raw = read_video(args.fixtures.parent / projection["path"])
39
+ video = to_uint8(raw)
40
+ item = {"filename": Path(projection["path"]).name, "frames": len(video), "dtype": str(raw.dtype),
41
+ "max_pixel": int(raw.max()), "stored_probability": projection["artery_prob"], "variants": {}}
42
+ for temporal in (("all_frames",) if args.all_frames_only else ("all_frames", "center32")):
43
+ frames = video
44
+ if temporal == "center32":
45
+ while len(frames) < 32:
46
+ frames = np.concatenate([frames, frames])
47
+ start = (len(frames) - 32) // 2
48
+ frames = frames[start:start + 32]
49
+ for antialias in ((True, False) if args.antialias == "both" else (args.antialias == "true",)):
50
+ x = ToTensorVideo()(torch.from_numpy(np.stack([frames] * 3, axis=-1)))
51
+ x = Resize((224, 224), antialias=antialias)(x)
52
+ x = (x - torch.tensor([.485, .456, .406])[:, None, None, None]) / torch.tensor([.229, .224, .225])[:, None, None, None]
53
+ probability = float(model(x.unsqueeze(0).to(device)).sigmoid().cpu()[0, 0])
54
+ item["variants"][f"{temporal}_antialias_{antialias}"] = probability
55
+ del x
56
+ print(json.dumps(item), flush=True)
57
+ report.append(item)
58
+ args.output.write_text(json.dumps(report, indent=2))
59
+
60
+
61
+ if __name__ == "__main__":
62
+ main()
engine/validate_reference.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Reproducible real-checkpoint parity check against published study results.
2
+
3
+ Inputs are a fixture manifest [{"dataset": "philips_97", "study": <JSON record>}]
4
+ and CSVs from the original five-fold evaluation. DICOM paths are relative to
5
+ the manifest directory. No source files or checkpoints are modified.
6
+ """
7
+ import argparse
8
+ import ast
9
+ import csv
10
+ import hashlib
11
+ import json
12
+ import os
13
+ import time
14
+ from pathlib import Path
15
+ from types import SimpleNamespace
16
+
17
+ from . import classify, infer
18
+
19
+
20
+ def canonical_cpu(study, base, source_root):
21
+ """Execute the original source class/dataset, only disabling an unused download.
22
+
23
+ Lightning training dependencies are substituted by nn.Module; the source
24
+ constructor, checkpoint loading, forward, and dataset are unchanged.
25
+ """
26
+ import importlib.util
27
+ import torch
28
+ import typing
29
+ import torch.nn.functional as F
30
+ from safetensors.torch import load_file
31
+ from torch import nn
32
+ import torchvision.models.video as tvmv
33
+ from torchvision.transforms import Resize
34
+ from torchvision.transforms._transforms_video import ToTensorVideo
35
+ from .weights import MANIFEST, weight_file
36
+ class InferenceLightning(nn.Module):
37
+ def save_hyperparameters(self):
38
+ pass
39
+ model_path = source_root / "full_model/rnn_model.py"
40
+ source = model_path.read_text()
41
+ tree = ast.parse(source)
42
+ class_node = next(node for node in tree.body if isinstance(node, ast.ClassDef) and node.name == "SyntaxLightningModule")
43
+ torch.set_num_threads(max(1, int(os.environ.get("SYNTAX_CPU_THREADS", "2"))))
44
+ namespace = {"pl": SimpleNamespace(LightningModule=InferenceLightning), "torch": torch, "nn": nn, "Any": typing.Any,
45
+ "F": F, "load_file": load_file,
46
+ "tvmv": SimpleNamespace(r3d_18=lambda **kw: tvmv.r3d_18(weights=None),
47
+ R3D_18_Weights=tvmv.R3D_18_Weights)}
48
+ exec(compile(ast.Module(body=[class_node], type_ignores=[]), str(model_path), "exec"), namespace)
49
+ spec = importlib.util.spec_from_file_location("canonical_dataset", source_root / "full_model/rnn_dataset.py")
50
+ module = importlib.util.module_from_spec(spec)
51
+ spec.loader.exec_module(module)
52
+ def transform(x):
53
+ x = Resize((256, 256), antialias=True)(ToTensorVideo()(x))
54
+ return (x - torch.tensor([.485, .456, .406])[:, None, None, None]) / torch.tensor([.229, .224, .225])[:, None, None, None]
55
+ predictions = {}
56
+ with torch.inference_mode():
57
+ for side in ("left", "right"):
58
+ # __getitem__ only needs these attributes; avoid writing a temporary JSON.
59
+ dataset = object.__new__(module.SyntaxDataset)
60
+ dataset.dataset, dataset.base_dir = [study], base
61
+ dataset.train, dataset.inference = False, True
62
+ dataset.label, dataset.artery = "", side
63
+ dataset.length, dataset.transform = 32, transform
64
+ clips = dataset[0][0].unsqueeze(0)
65
+ values = []
66
+ for weight in [w for w in MANIFEST["score_weights"] if w["side"] == side]:
67
+ model = namespace["SyntaxLightningModule"](num_classes=2, lr=1e-5, variant="lstm_mean",
68
+ pl_weight_path=weight_file(weight)).eval()
69
+ output = model(clips)
70
+ values.append(float(torch.exp(output[0, 1])) - 1.0)
71
+ del model
72
+ predictions[side] = values
73
+ predictions["source_sha256"] = hashlib.sha256(source.encode()).hexdigest()
74
+ return predictions
75
+
76
+
77
+ def main():
78
+ parser = argparse.ArgumentParser()
79
+ parser.add_argument("--fixtures", type=Path, required=True)
80
+ parser.add_argument("--predictions", type=Path, required=True)
81
+ parser.add_argument("--output", type=Path, required=True)
82
+ parser.add_argument("--classifier", action="store_true")
83
+ parser.add_argument("--reference-source", type=Path)
84
+ parser.add_argument("--resume", action="store_true", help="Reuse completed engine results and validate original CPU code")
85
+ args = parser.parse_args()
86
+ cases = json.loads(args.fixtures.read_text())
87
+ previous = json.loads(args.output.read_text()) if args.resume and args.output.exists() else []
88
+ report = []
89
+ for case in cases:
90
+ study = case["study"]
91
+ base = args.fixtures.parent
92
+ left = [str(base / v["path"]) for v in study["videos_left"]]
93
+ right = [str(base / v["path"]) for v in study["videos_right"]]
94
+ vendor = case["dataset"].split("_")[0]
95
+ expected = next(row for row in csv.DictReader((args.predictions / f"{vendor}_predictions.csv").open())
96
+ if row["study_uid"] == study["study_uid"])
97
+ start = time.monotonic()
98
+ def progress(stage, detail):
99
+ if stage == "infer" and detail["current"] % (len(left) + len(right)) == 0:
100
+ print(f"{case['dataset']}: {detail['current']}/{detail['total']} projections", flush=True)
101
+ saved = next((item for item in previous if item["study_uid"] == study["study_uid"]), None)
102
+ result = saved["result"] if saved else infer(left, right, progress=progress)
103
+ delta = abs(result["calibrated"] - float(expected["new_prediction"]))
104
+ item = {**(saved or {}), "dataset": case["dataset"], "study_uid": study["study_uid"],
105
+ "expected_calibrated": float(expected["new_prediction"]),
106
+ "actual_calibrated": result["calibrated"], "absolute_difference": delta,
107
+ "inference_seconds": saved["inference_seconds"] if saved else time.monotonic() - start, "result": result,
108
+ "pass": delta < 0.01}
109
+ print(json.dumps({k: v for k, v in item.items() if k != "result"}), flush=True)
110
+ if args.reference_source:
111
+ reference = canonical_cpu(study, base, args.reference_source)
112
+ errors = [abs(a - b) for side in ("left", "right")
113
+ for a, b in zip(reference[side], result[side]["per_fold"])]
114
+ item["canonical_cpu"] = reference
115
+ item["canonical_cpu_max_fold_difference"] = max(errors)
116
+ item["canonical_cpu_parity"] = max(errors) < 0.0001
117
+ item["pass"] = item["pass"] and item["canonical_cpu_parity"]
118
+ print(f"{case['dataset']}: original CPU max fold delta={max(errors)}", flush=True)
119
+ if args.classifier:
120
+ from .weights import MANIFEST
121
+ paths = [str(base / v["path"]) for v in study["videos"]]
122
+ classified = classify(paths)
123
+ comparisons = []
124
+ for source, actual in zip(study["videos"], classified):
125
+ expected_side = "left" if source["artery_prob"] <= .1 else "right" if source["artery_prob"] >= .9 else "unassigned"
126
+ comparisons.append({"filename": Path(source["path"]).name,
127
+ "expected_probability_right": source["artery_prob"],
128
+ "actual_probability_right": actual["probability_right"],
129
+ "expected_artery": expected_side, "actual_artery": actual["artery"]})
130
+ item["classifier"] = comparisons
131
+ item["classifier_preprocessing"] = MANIFEST["preprocessing"]["classifier"]
132
+ item["classifier_groups_match"] = all(c["expected_artery"] == c["actual_artery"] for c in comparisons)
133
+ print(f"{case['dataset']}: classifier groups match={item['classifier_groups_match']}", flush=True)
134
+ report.append(item)
135
+ args.output.write_text(json.dumps(report, indent=2))
136
+ if not all(item["pass"] and item.get("classifier_groups_match", True) for item in report):
137
+ raise SystemExit("Reference parity failed; review the JSON report.")
138
+
139
+
140
+ if __name__ == "__main__":
141
+ main()
engine/validate_tiling.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Check temporal tiling using real published weights and a supplied public cine."""
2
+ import argparse
3
+ import json
4
+ import time
5
+ from pathlib import Path
6
+
7
+ import numpy as np
8
+ import torch
9
+
10
+ from .architecture import artery_model, classifier_stream
11
+ from .dicom import read_video
12
+ from .preprocessing import preprocess_classifier, to_uint8
13
+ from .runtime import _device, _load
14
+ from .weights import MANIFEST
15
+
16
+
17
+ def main():
18
+ parser = argparse.ArgumentParser()
19
+ parser.add_argument("--dicom", required=True, type=Path)
20
+ parser.add_argument("--output", required=True, type=Path)
21
+ args = parser.parse_args()
22
+ source = to_uint8(read_video(args.dicom))
23
+ # An in-memory repeated fixture crosses multiple temporal tiles without
24
+ # changing any source DICOM or claiming this is a new clinical study.
25
+ video = np.concatenate([source] * ((195 + len(source) - 1) // len(source)))[:195]
26
+ device = _device()
27
+ started = time.monotonic()
28
+ with torch.inference_mode():
29
+ model = _load(artery_model, MANIFEST["classifier"], device, None)
30
+ whole_clip = preprocess_classifier(video).unsqueeze(0).to(device)
31
+ whole = model(whole_clip)
32
+ del whole_clip
33
+ tiled = classifier_stream(model, len(video), lambda a, b: preprocess_classifier(video[a:b]), device)
34
+ torch.testing.assert_close(whole, tiled, rtol=2e-5, atol=2e-5)
35
+ result = {"frames": len(video), "fixture": "repeated source frames in memory; original DICOM unchanged",
36
+ "whole_logit": float(whole.cpu()[0, 0]), "tiled_logit": float(tiled.cpu()[0, 0]),
37
+ "absolute_logit_difference": float(abs(whole - tiled).cpu()[0, 0]),
38
+ "whole_probability_right": float(whole.sigmoid().cpu()[0, 0]),
39
+ "tiled_probability_right": float(tiled.sigmoid().cpu()[0, 0]),
40
+ "classifier_sha256": MANIFEST["classifier"]["sha256"],
41
+ "classifier_preprocessing": MANIFEST["preprocessing"]["classifier"],
42
+ "seconds": time.monotonic() - started, "pass": True}
43
+ args.output.write_text(json.dumps(result, indent=2))
44
+ print(json.dumps(result), flush=True)
45
+
46
+
47
+ if __name__ == "__main__":
48
+ main()
engine/weights.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Download only pinned tensor-only checkpoints and verify every checksum."""
2
+ import hashlib
3
+ import json
4
+ import os
5
+ from pathlib import Path
6
+
7
+ from .dicom import InferenceError
8
+
9
+ MANIFEST = json.loads(Path(__file__).with_name("manifest.json").read_text())
10
+ _verified = {}
11
+
12
+
13
+ def cache_root():
14
+ return Path(os.environ.get("SYNTAX_MODEL_CACHE", str(Path.home() / ".cache" / "syntax-space" / MANIFEST["revision"])))
15
+
16
+
17
+ def status():
18
+ files = MANIFEST["score_weights"] + [MANIFEST["classifier"]]
19
+ root = cache_root()
20
+ cached = sum((root / f["path"]).is_file() and (root / f["path"]).stat().st_size == f["size"] for f in files)
21
+ return {
22
+ "repo_id": MANIFEST["repo_id"], "revision": MANIFEST["revision"],
23
+ "models": 10, "classifier": True, "cached_files": cached,
24
+ "total_files": len(files), "cached": cached == len(files),
25
+ "device": os.environ.get("SYNTAX_DEVICE", "cpu"),
26
+ "loaded": False, "lazy": True,
27
+ "classifier_preprocessing": MANIFEST["preprocessing"]["classifier"],
28
+ }
29
+
30
+
31
+ def weight_file(record, progress=None):
32
+ path = cache_root() / record["path"]
33
+ if not path.is_file():
34
+ if progress:
35
+ progress("download", {"file": record["path"], "message": "Downloading a verified model checkpoint"})
36
+ from huggingface_hub import hf_hub_download
37
+ try:
38
+ path = Path(hf_hub_download(
39
+ repo_id=MANIFEST["repo_id"], filename=record["path"],
40
+ revision=MANIFEST["revision"], local_dir=str(cache_root()), token=False,
41
+ ))
42
+ except Exception as exc:
43
+ raise InferenceError("A required model checkpoint could not be downloaded. Please retry.") from exc
44
+ stat = path.stat()
45
+ if "size" in record and stat.st_size != record["size"]:
46
+ raise InferenceError(f"Model checkpoint is incomplete: {record['path']}.")
47
+ key = (str(path.resolve()), stat.st_size, stat.st_mtime_ns, stat.st_ino)
48
+ if _verified.get(key) != record["sha256"]:
49
+ digest = hashlib.sha256()
50
+ with path.open("rb") as stream:
51
+ for chunk in iter(lambda: stream.read(8 * 1024 * 1024), b""):
52
+ digest.update(chunk)
53
+ if digest.hexdigest() != record["sha256"]:
54
+ raise InferenceError(f"Model checksum mismatch: {record['path']}. The checkpoint was not used.")
55
+ _verified[key] = record["sha256"]
56
+ return path
57
+
58
+
59
+ def calibration(progress=None):
60
+ record = MANIFEST["calibration"]
61
+ source = json.loads(weight_file(record, progress).read_text())
62
+ folds = [{"a": source[f"fold{i}"]["a"], "b": source[f"fold{i}"]["b"]} for i in range(5)]
63
+ if folds != record["folds"]:
64
+ raise InferenceError("Calibration coefficients do not match the pinned model release.")
65
+ return folds
huggingface.yaml DELETED
@@ -1,3 +0,0 @@
1
- sdk: gradio
2
- python_version: "3.11"
3
- app_file: app.py
 
 
 
 
requirements.txt CHANGED
@@ -1,11 +1,12 @@
1
- torch
2
- torchvision
3
- lightning
4
- pydicom
5
- pytorchvideo @ git+https://github.com/facebookresearch/pytorchvideo.git
6
- omegaconf
7
- gradio
8
- numpy
9
- scikit-learn
10
- plotly
11
- huggingface_hub>=0.24
 
 
1
+ # Install torch==2.6.0 and torchvision==0.21.0 separately (see Dockerfile/README).
2
+ fastapi==0.115.12
3
+ uvicorn[standard]==0.34.2
4
+ python-multipart==0.0.20
5
+ pydicom==3.0.1
6
+ numpy==2.2.6
7
+ Pillow==11.2.1
8
+ safetensors==0.5.3
9
+ huggingface_hub==0.36.0
10
+ pylibjpeg==2.0.1
11
+ pylibjpeg-libjpeg==2.3.0
12
+ pylibjpeg-openjpeg==2.5.0
service/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Ephemeral, bounded study workspaces for the public research demo."""
service/api.py ADDED
@@ -0,0 +1,547 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import importlib
5
+ import json
6
+ import os
7
+ import secrets
8
+ import shutil
9
+ import tempfile
10
+ import threading
11
+ import time
12
+ from concurrent.futures import ThreadPoolExecutor
13
+ from contextlib import asynccontextmanager
14
+ from pathlib import Path
15
+ from typing import Literal
16
+
17
+ from fastapi import FastAPI, File, HTTPException, UploadFile
18
+ from fastapi.responses import FileResponse, JSONResponse, Response
19
+ from fastapi.staticfiles import StaticFiles
20
+ from pydantic import BaseModel, Field
21
+
22
+ from .media import cached_video
23
+ from .storage import InputError, Limits, Store, expand_zip, inspect_dicom, poster, animation
24
+
25
+
26
+ class PayloadTooLarge(HTTPException):
27
+ def __init__(self):
28
+ super().__init__(413, 'Upload exceeds the request size limit.')
29
+
30
+
31
+ class BodyLimitMiddleware:
32
+ def __init__(self, app, maximum: int):
33
+ self.app, self.maximum = app, maximum
34
+ self.upload_slot = threading.BoundedSemaphore(1)
35
+
36
+ async def __call__(self, scope, receive, send):
37
+ if scope['type'] != 'http':
38
+ return await self.app(scope, receive, send)
39
+ is_upload = scope.get('method') == 'POST' and scope.get('path') == '/api/studies'
40
+ if is_upload and not self.upload_slot.acquire(blocking=False):
41
+ return await JSONResponse({'detail': 'Another upload is in progress. Please retry shortly.'}, status_code=429)(scope, receive, send)
42
+ try:
43
+ await self._bounded(scope, receive, send)
44
+ finally:
45
+ if is_upload:
46
+ self.upload_slot.release()
47
+
48
+ async def _bounded(self, scope, receive, send):
49
+ headers = dict(scope.get('headers', []))
50
+ try:
51
+ size = int(headers.get(b'content-length', b'0'))
52
+ except ValueError:
53
+ size = self.maximum + 1
54
+ if size > self.maximum:
55
+ return await JSONResponse({'detail': 'Upload exceeds the request size limit.'}, status_code=413)(scope, receive, send)
56
+ received = 0
57
+ async def bounded_receive():
58
+ nonlocal received
59
+ message = await receive()
60
+ received += len(message.get('body', b''))
61
+ if received > self.maximum:
62
+ raise PayloadTooLarge()
63
+ return message
64
+ try:
65
+ await self.app(scope, bounded_receive, send)
66
+ except PayloadTooLarge:
67
+ await JSONResponse({'detail': 'Upload exceeds the request size limit.'}, status_code=413)(scope, receive, send)
68
+
69
+
70
+ class EngineAdapter:
71
+ @staticmethod
72
+ def _module():
73
+ return importlib.import_module('engine')
74
+
75
+ def status(self):
76
+ return self._module().status()
77
+
78
+ def classify(self, paths, progress):
79
+ return self._module().classify(paths, progress=progress)
80
+
81
+ def infer(self, left, right, progress):
82
+ return self._module().infer(left, right, progress=progress)
83
+
84
+
85
+ class Assignment(BaseModel):
86
+ id: str
87
+ artery: Literal['left', 'right', 'unassigned', 'exclude']
88
+
89
+
90
+ class RunRequest(BaseModel):
91
+ assignments: list[Assignment] | None = Field(default=None, max_length=64)
92
+
93
+
94
+ class Jobs:
95
+ def __init__(self, store: Store, engine):
96
+ self.store, self.engine = store, engine
97
+ self.executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix='syntax-worker')
98
+ self.items: dict[str, dict] = {}
99
+ self.lock = threading.RLock()
100
+
101
+ def pending(self):
102
+ with self.lock:
103
+ return sum(j['status'] in {'queued', 'running'} for j in self.items.values())
104
+
105
+ def cleanup(self):
106
+ with self.lock:
107
+ cutoff = time.time() - self.store.limits.ttl_seconds
108
+ self.items = {key: job for key, job in self.items.items()
109
+ if job['status'] in {'queued', 'running'} or job['updated_at'] > cutoff}
110
+
111
+ def submit(self, study, kind):
112
+ with self.store.lock, self.lock:
113
+ if self.store.studies.get(study.id) is not study:
114
+ raise HTTPException(404, 'Study not found or expired. Please upload it again.')
115
+ if study.active_job:
116
+ raise HTTPException(409, 'This study already has an active job.')
117
+ if self.pending() >= self.store.limits.max_pending_jobs:
118
+ raise HTTPException(429, 'The inference queue is full. Please try again shortly.')
119
+ job_id = secrets.token_urlsafe(32)
120
+ job = {'id': job_id, 'study_id': study.id, 'kind': kind, 'status': 'queued',
121
+ 'progress': 0.0, 'message': 'Waiting for the inference worker.',
122
+ 'result': None, 'error': None, 'created_at': time.time(), 'updated_at': time.time()}
123
+ self.items[job_id] = job
124
+ study.active_job = job_id
125
+ self.executor.submit(self._execute, job_id)
126
+ return dict(job)
127
+
128
+ def submit_example(self, loader):
129
+ with self.lock:
130
+ if self.pending() >= self.store.limits.max_pending_jobs:
131
+ raise HTTPException(429, 'The inference queue is full. Please try again shortly.')
132
+ job_id = secrets.token_urlsafe(32)
133
+ job = {'id': job_id, 'study_id': None, 'kind': 'example', 'status': 'queued',
134
+ 'progress': 0.0, 'message': 'Waiting to load the public example.',
135
+ 'result': None, 'error': None, 'created_at': time.time(), 'updated_at': time.time()}
136
+ self.items[job_id] = job
137
+ self.executor.submit(self._execute_example, job_id, loader)
138
+ return dict(job)
139
+
140
+ def _execute_example(self, job_id, loader):
141
+ with self.lock:
142
+ job = self.items[job_id]
143
+ job.update(status='running', message='Loading public example.', updated_at=time.time())
144
+ def progress(fraction, message):
145
+ with self.lock:
146
+ job.update(progress=min(.99, float(fraction)), message=message, updated_at=time.time())
147
+ try:
148
+ result = loader(progress)
149
+ with self.lock:
150
+ job.update(status='completed', result=result, progress=1.,
151
+ message='Example ready.', updated_at=time.time())
152
+ except Exception as exc:
153
+ message = str(exc) if isinstance(exc, InputError) else 'The public example could not be downloaded. Please retry.'
154
+ with self.lock:
155
+ job.update(status='failed', error=message, message=message, updated_at=time.time())
156
+
157
+ def _execute(self, job_id):
158
+ with self.lock:
159
+ job = self.items[job_id]
160
+ job.update(status='running', message='Preparing model input.', updated_at=time.time())
161
+ study = self.store.get(job['study_id'])
162
+ def progress(stage, detail=None):
163
+ detail = detail or {}
164
+ if not isinstance(detail, dict):
165
+ detail = {}
166
+ fraction = detail.get('fraction', detail.get('progress'))
167
+ if fraction is None and detail.get('total'):
168
+ fraction = detail.get('current', 0) / detail['total']
169
+ with self.lock:
170
+ if isinstance(fraction, (int, float)):
171
+ job['progress'] = min(.99, max(0., float(fraction)))
172
+ job.update(message=detail.get('message', str(stage)), updated_at=time.time())
173
+ try:
174
+ if not study:
175
+ raise InputError('The study has expired. Please upload it again.')
176
+ if job['kind'] == 'classify':
177
+ eligible = [p for p in study.projections if p.frames >= 10]
178
+ if not eligible:
179
+ raise InputError('No sequences with at least 10 frames are available.')
180
+ result = self.engine.classify([str(p.path) for p in eligible], progress)
181
+ if len(result) != len(eligible):
182
+ raise RuntimeError('Classification did not return a result for every projection.')
183
+ with self.store.lock:
184
+ for projection, output in zip(eligible, result):
185
+ if output.get('path') and Path(output['path']) != projection.path:
186
+ raise RuntimeError('Classification projection order mismatch.')
187
+ artery = output.get('artery', 'unassigned')
188
+ if artery not in {'left', 'right', 'unassigned', 'exclude'}:
189
+ raise RuntimeError('Invalid artery classifier output.')
190
+ projection.artery = artery
191
+ projection.probability = output.get('probability_right', output.get('probability'))
192
+ projection.reason = output.get('reason')
193
+ result = {'study': study.public()}
194
+ else:
195
+ left = [str(p.path) for p in study.projections if p.artery == 'left']
196
+ right = [str(p.path) for p in study.projections if p.artery == 'right']
197
+ result = self.engine.infer(left, right, progress)
198
+ # Friendly stable aliases for UI consumers; do not synthesize scores.
199
+ result = dict(result)
200
+ result['raw_score'] = result.get('raw')
201
+ result['calibrated_score'] = result.get('calibrated')
202
+ result['total'] = {'raw': result.get('raw'), 'calibrated': result.get('calibrated')}
203
+ result['study_uid'] = study.study_uid
204
+ result['input_counts'] = {'left': len(left), 'right': len(right),
205
+ 'excluded': sum(p.artery == 'exclude' for p in study.projections)}
206
+ with self.lock:
207
+ job.update(status='completed', progress=1., message='Analysis complete.', result=result,
208
+ updated_at=time.time())
209
+ except Exception as exc:
210
+ if isinstance(exc, InputError):
211
+ message = str(exc)
212
+ elif isinstance(exc, (MemoryError,)) or 'out of memory' in str(exc).lower():
213
+ message = 'Insufficient memory for this study. Use fewer projections or a larger runtime.'
214
+ else:
215
+ # Never disclose uploaded filesystem paths or DICOM metadata in public errors/logs.
216
+ message = ('The model could not complete this job. Check model availability and runtime resources, '
217
+ 'then try again. No score was produced.')
218
+ with self.lock:
219
+ job.update(status='failed', error=message, message=message, updated_at=time.time())
220
+ finally:
221
+ if study:
222
+ with self.store.lock:
223
+ study.active_job = None
224
+ study.touched_at = time.time()
225
+
226
+
227
+ def create_app(*, data_root: Path | None = None, limits: Limits | None = None, engine=None):
228
+ limits = limits or Limits()
229
+ root = data_root or Path(os.environ.get('SYNTAX_UPLOAD_DIR', Path(tempfile.gettempdir()) / 'cardiosyntax-uploads'))
230
+ store = Store(root, limits)
231
+ engine = engine or EngineAdapter()
232
+ jobs = Jobs(store, engine)
233
+ video_slot = threading.BoundedSemaphore(1)
234
+
235
+ async def clean_periodically():
236
+ while True:
237
+ await asyncio.sleep(60)
238
+ await asyncio.to_thread(store.cleanup)
239
+ jobs.cleanup()
240
+
241
+ @asynccontextmanager
242
+ async def lifespan(app):
243
+ store.cleanup()
244
+ cleaner = asyncio.create_task(clean_periodically())
245
+ yield
246
+ cleaner.cancel()
247
+ try:
248
+ await cleaner
249
+ except asyncio.CancelledError:
250
+ pass
251
+ jobs.executor.shutdown(wait=False, cancel_futures=True)
252
+
253
+ app = FastAPI(title='CardioSyntax research workspace', docs_url=None, redoc_url=None,
254
+ openapi_url=None, lifespan=lifespan)
255
+ app.add_middleware(BodyLimitMiddleware, maximum=limits.max_request_bytes)
256
+ app.state.store, app.state.jobs = store, jobs
257
+
258
+ @app.middleware('http')
259
+ async def private_responses(request, call_next):
260
+ response = await call_next(request)
261
+ if request.url.path.startswith('/api/'):
262
+ response.headers['Cache-Control'] = 'no-store'
263
+ response.headers['X-Content-Type-Options'] = 'nosniff'
264
+ return response
265
+
266
+ @app.get('/api/status')
267
+ def status():
268
+ try:
269
+ info = dict(engine.status())
270
+ except Exception:
271
+ info = {'device': os.environ.get('SYNTAX_DEVICE', 'cpu'),
272
+ 'model': {'status': 'unavailable', 'loaded': 0, 'total': 10},
273
+ 'message': 'Inference engine is unavailable.'}
274
+ info.setdefault('model', {'repository': info.get('repo_id'), 'revision': info.get('revision'),
275
+ 'status': 'cached' if info.get('cached') else 'not_loaded',
276
+ 'loaded': 0, 'total': info.get('models', 10),
277
+ 'cached_files': info.get('cached_files', 0),
278
+ 'total_files': info.get('total_files', 11)})
279
+ info.update(service='ready', active_job=bool(jobs.pending()),
280
+ limits={'max_files': limits.max_files, 'max_studies': limits.max_studies,
281
+ 'max_request_mb': limits.max_request_bytes // (1024 * 1024),
282
+ 'max_file_mb': limits.max_file_bytes // (1024 * 1024),
283
+ 'retention_minutes': limits.ttl_seconds // 60})
284
+ return info
285
+
286
+ examples_path = Path(__file__).with_name('examples.json')
287
+ examples = json.loads(examples_path.read_text()) if examples_path.exists() else []
288
+
289
+ @app.get('/api/examples')
290
+ def list_examples():
291
+ return {'examples': [{'id': x['id'], 'title': x.get('title', x.get('label', x['id'])),
292
+ 'description': x.get('description', 'A public annotated holdout study.'),
293
+ 'files': len(x['files'])} for x in examples]}
294
+
295
+ @app.post('/api/examples/{example_id}/load')
296
+ def load_example(example_id: str):
297
+ example = next((x for x in examples if x['id'] == example_id), None)
298
+ if example is None:
299
+ raise HTTPException(404, 'Example not found.')
300
+ def loader(progress):
301
+ from huggingface_hub import hf_hub_download
302
+ staging = store.workspace('example-')
303
+ projections = []
304
+ created = None
305
+ try:
306
+ entries = example['files']
307
+ if not 0 < len(entries) <= limits.max_files:
308
+ raise InputError('The example exceeds the file limit.')
309
+ total = 0
310
+ seen_sops = set()
311
+ for index, item in enumerate(entries):
312
+ progress(index / len(entries), f"Loading example projection {index + 1} of {len(entries)}.")
313
+ source = hf_hub_download(
314
+ repo_id=example.get('repository', 'MesserMMP/coronary-angiography-syntax'),
315
+ repo_type='dataset', revision=example.get('revision', example.get('dataset_revision')),
316
+ filename=item['path'], token=False,
317
+ )
318
+ size = Path(source).stat().st_size
319
+ total += size
320
+ if size > limits.max_file_bytes or total > limits.max_request_bytes:
321
+ raise InputError('The example exceeds the upload size limit.')
322
+ dest = staging / secrets.token_hex(16)
323
+ store.reserve(staging, size)
324
+ shutil.copyfile(source, dest)
325
+ uid, projection = inspect_dicom(dest, Path(item['path']).name, limits)
326
+ if uid != example['study_uid'] or projection.sop_uid != item['sop_uid']:
327
+ raise InputError('The example does not match its published identifiers.')
328
+ if projection.sop_uid in seen_sops:
329
+ raise InputError('The example contains a repeated projection identifier.')
330
+ seen_sops.add(projection.sop_uid)
331
+ projection.artery = 'exclude' if projection.frames < 10 else item['artery']
332
+ if projection.artery not in {'left', 'right', 'exclude'}:
333
+ raise InputError('Invalid published artery assignment.')
334
+ projections.append(projection)
335
+ with store.lock:
336
+ store.capacity(total, 1, workspace=staging)
337
+ created = store.add(example['study_uid'], projections)
338
+ return {'studies': [created.public()], 'rejected': [], 'warnings': [],
339
+ 'example_id': example_id}
340
+ except Exception:
341
+ if created:
342
+ store.delete(created.id)
343
+ raise
344
+ finally:
345
+ store.remove_workspace(staging)
346
+ return jobs.submit_example(loader)
347
+
348
+ @app.post('/api/studies')
349
+ async def upload(files: list[UploadFile] = File(...)):
350
+ store.cleanup()
351
+ if not files or len(files) > limits.max_files:
352
+ raise HTTPException(422, f'Select between 1 and {limits.max_files} files.')
353
+ staging = store.workspace('incoming-')
354
+ rejected, warnings = [], []
355
+ candidates = []
356
+ total = 0
357
+ expanded = 0
358
+ created = []
359
+ try:
360
+ for item in files:
361
+ name = Path((item.filename or 'unnamed.dcm').replace('\\', '/')).name[:240]
362
+ path = staging / secrets.token_hex(16)
363
+ count = 0
364
+ with path.open('wb') as out:
365
+ while chunk := await item.read(1024 * 1024):
366
+ count += len(chunk)
367
+ total += len(chunk)
368
+ if count > limits.max_file_bytes or total > limits.max_request_bytes:
369
+ raise HTTPException(413, 'Upload exceeds the supported file or request size limit.')
370
+ try:
371
+ store.reserve(staging, len(chunk))
372
+ except InputError as exc:
373
+ raise HTTPException(507, str(exc)) from exc
374
+ out.write(chunk)
375
+ if name.lower().endswith('.zip'):
376
+ try:
377
+ extracted = await asyncio.to_thread(
378
+ expand_zip, path, staging, limits, remaining_bytes=limits.max_request_bytes - expanded,
379
+ reserve=lambda size: store.reserve(staging, size))
380
+ candidates.extend(extracted)
381
+ expanded += sum(p.stat().st_size for p, _ in extracted)
382
+ except InputError as exc:
383
+ rejected.append({'name': name, 'reason': str(exc)})
384
+ finally:
385
+ path.unlink(missing_ok=True)
386
+ store.unreserve(staging, count)
387
+ else:
388
+ expanded += count
389
+ if expanded > limits.max_request_bytes:
390
+ raise HTTPException(413, 'Combined expanded files exceed the upload size limit.')
391
+ candidates.append((path, name))
392
+ if len(candidates) > limits.max_files:
393
+ raise HTTPException(413, f'An upload can contain at most {limits.max_files} projections.')
394
+ grouped = {}
395
+ seen_sops = set()
396
+ for path, name in candidates:
397
+ try:
398
+ uid, projection = await asyncio.to_thread(inspect_dicom, path, name, limits)
399
+ if projection.sop_uid in seen_sops:
400
+ raise InputError('Duplicate SOPInstanceUID in this upload; the repeated file was not added.')
401
+ seen_sops.add(projection.sop_uid)
402
+ grouped.setdefault(uid, []).append(projection)
403
+ except InputError as exc:
404
+ rejected.append({'name': name, 'reason': str(exc)})
405
+ if len(grouped) > limits.max_studies:
406
+ raise HTTPException(422, f'Upload contains more than {limits.max_studies} studies.')
407
+ if not grouped:
408
+ return JSONResponse({'studies': [], 'rejected': rejected, 'warnings': warnings}, status_code=422)
409
+ with store.lock:
410
+ try:
411
+ store.capacity(sum(p.path.stat().st_size for values in grouped.values() for p in values), len(grouped), workspace=staging)
412
+ except InputError as exc:
413
+ raise HTTPException(507, str(exc)) from exc
414
+ for uid, projections in grouped.items():
415
+ created.append(store.add(uid, projections))
416
+ return {'studies': [s.public() for s in created], 'rejected': rejected, 'warnings': warnings}
417
+ except Exception:
418
+ for study in created:
419
+ store.delete(study.id)
420
+ raise
421
+ finally:
422
+ for file in files:
423
+ await file.close()
424
+ store.remove_workspace(staging)
425
+
426
+ def get_study(study_id):
427
+ study = store.get(study_id)
428
+ if not study:
429
+ raise HTTPException(404, 'Study not found or expired. Please upload it again.')
430
+ return study
431
+
432
+ @app.get('/api/studies/{study_id}')
433
+ def study_info(study_id: str):
434
+ return get_study(study_id).public()
435
+
436
+ def acquire_projection(study_id, projection_id):
437
+ study = store.acquire(study_id)
438
+ if not study:
439
+ raise HTTPException(404, 'Study not found or expired. Please upload it again.')
440
+ projection = next((p for p in study.projections if p.id == projection_id), None)
441
+ if not projection:
442
+ store.release(study)
443
+ raise HTTPException(404, 'Projection not found.')
444
+ return study, projection
445
+
446
+ @app.get('/api/studies/{study_id}/projections/{projection_id}/preview')
447
+ def preview(study_id: str, projection_id: str, animated: bool = False):
448
+ study, projection = acquire_projection(study_id, projection_id)
449
+ try:
450
+ data = animation(projection) if animated else poster(projection)
451
+ return Response(data, media_type='image/gif' if animated else 'image/png')
452
+ except Exception:
453
+ raise HTTPException(422, 'Unable to generate the image preview.') from None
454
+ finally:
455
+ store.release(study)
456
+
457
+ class LeasedVideoResponse(FileResponse):
458
+ async def __call__(self, scope, receive, send):
459
+ try:
460
+ await super().__call__(scope, receive, send)
461
+ finally:
462
+ store.release(self.leased_study)
463
+
464
+ @app.get('/api/studies/{study_id}/projections/{projection_id}/video')
465
+ def video(study_id: str, projection_id: str):
466
+ study, projection = acquire_projection(study_id, projection_id)
467
+ acquired = False
468
+ try:
469
+ # Limit display encoding independently of the single model worker.
470
+ acquired = video_slot.acquire(timeout=30)
471
+ if not acquired:
472
+ raise HTTPException(503, 'The video encoder is busy. Please retry shortly.')
473
+ path = cached_video(store, study, projection)
474
+ response = LeasedVideoResponse(path, media_type='video/mp4')
475
+ response.leased_study = study
476
+ return response
477
+ except HTTPException:
478
+ store.release(study)
479
+ raise
480
+ except Exception as exc:
481
+ store.release(study)
482
+ message = str(exc) if isinstance(exc, InputError) else 'Unable to generate the complete cine preview.'
483
+ raise HTTPException(422, message) from None
484
+ finally:
485
+ if acquired:
486
+ video_slot.release()
487
+
488
+ @app.post('/api/studies/{study_id}/classify')
489
+ def classify(study_id: str):
490
+ return jobs.submit(get_study(study_id), 'classify')
491
+
492
+ @app.post('/api/studies/{study_id}/run')
493
+ def run(study_id: str, body: RunRequest):
494
+ study = get_study(study_id)
495
+ with store.lock:
496
+ if study.active_job:
497
+ raise HTTPException(409, 'This study already has an active job.')
498
+ if body.assignments is not None:
499
+ ids = [a.id for a in body.assignments]
500
+ if len(ids) != len(set(ids)) or set(ids) != {p.id for p in study.projections}:
501
+ raise HTTPException(422, 'Assignments must include each projection exactly once.')
502
+ lookup = {p.id: p for p in study.projections}
503
+ for assignment in body.assignments:
504
+ if lookup[assignment.id].frames < 10 and assignment.artery != 'exclude':
505
+ raise HTTPException(422, 'Sequences shorter than 10 frames must remain excluded.')
506
+ # Preserve explicit user ordering, important to recurrent model inputs.
507
+ study.projections = [lookup[a.id] for a in body.assignments]
508
+ for assignment in body.assignments:
509
+ lookup[assignment.id].artery = assignment.artery
510
+ if any(p.artery == 'unassigned' for p in study.projections):
511
+ raise HTTPException(422, 'Assign every projection to LCA, RCA, or Exclude before running inference.')
512
+ if not any(p.artery in {'left', 'right'} for p in study.projections):
513
+ raise HTTPException(422, 'At least one eligible LCA or RCA projection is required.')
514
+ return jobs.submit(study, 'inference')
515
+
516
+ @app.get('/api/jobs/{job_id}')
517
+ def job_status(job_id: str):
518
+ jobs.cleanup()
519
+ with jobs.lock:
520
+ job = jobs.items.get(job_id)
521
+ if not job:
522
+ raise HTTPException(404, 'Job not found or expired.')
523
+ return dict(job)
524
+
525
+ @app.delete('/api/studies/{study_id}')
526
+ def remove(study_id: str):
527
+ get_study(study_id)
528
+ try:
529
+ store.delete(study_id)
530
+ except InputError as exc:
531
+ raise HTTPException(409, str(exc)) from exc
532
+ with jobs.lock:
533
+ jobs.items = {key: item for key, item in jobs.items.items() if item['study_id'] != study_id}
534
+ return {'deleted': True}
535
+
536
+ static = Path(__file__).resolve().parents[1] / 'static'
537
+ if static.exists():
538
+ app.mount('/static', StaticFiles(directory=static), name='static')
539
+
540
+ @app.get('/')
541
+ def home():
542
+ index = static / 'index.html'
543
+ if not index.exists():
544
+ return JSONResponse({'detail': 'The interface is not installed.'}, status_code=503)
545
+ return FileResponse(index)
546
+
547
+ return app
service/examples.json ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "id": "philips",
4
+ "label": "Philips \u00b7 5 projections",
5
+ "dataset_revision": "f5d6b5b4aa9856b12b8d65971beb8fce2f71e370",
6
+ "study_uid": "1.3.46.670589.28.26690171363123020201128175110834238",
7
+ "files": [
8
+ {
9
+ "path": "test_data/philips_97/1.3.46.670589.28.26690171363123020201128175110834238/IM-0004-0039.dcm",
10
+ "sop_uid": "1.3.46.670589.28.266901713631230202011281917151892602211512",
11
+ "artery": "left"
12
+ },
13
+ {
14
+ "path": "test_data/philips_97/1.3.46.670589.28.26690171363123020201128175110834238/IM-0002-0043.dcm",
15
+ "sop_uid": "1.3.46.670589.28.266901713631230202011281917151262482211512",
16
+ "artery": "right"
17
+ },
18
+ {
19
+ "path": "test_data/philips_97/1.3.46.670589.28.26690171363123020201128175110834238/IM-0003-0031.dcm",
20
+ "sop_uid": "1.3.46.670589.28.266901713631230202011281917151572542211512",
21
+ "artery": "exclude"
22
+ },
23
+ {
24
+ "path": "test_data/philips_97/1.3.46.670589.28.26690171363123020201128175110834238/IM-0005-0039.dcm",
25
+ "sop_uid": "1.3.46.670589.28.266901713631230202011281917152042662211512",
26
+ "artery": "left"
27
+ },
28
+ {
29
+ "path": "test_data/philips_97/1.3.46.670589.28.26690171363123020201128175110834238/IM-0001-0043.dcm",
30
+ "sop_uid": "1.3.46.670589.28.266901713631230202011281917150952422211512",
31
+ "artery": "right"
32
+ }
33
+ ],
34
+ "title": "Philips \u00b7 5 projections",
35
+ "description": "An anonymized public holdout study. Artery assignments follow the published annotations.",
36
+ "repository": "MesserMMP/coronary-angiography-syntax",
37
+ "revision": "f5d6b5b4aa9856b12b8d65971beb8fce2f71e370"
38
+ },
39
+ {
40
+ "id": "siemens",
41
+ "label": "Siemens \u00b7 6 projections",
42
+ "dataset_revision": "f5d6b5b4aa9856b12b8d65971beb8fce2f71e370",
43
+ "study_uid": "1.2.826.0.1.3680043.2.706.1288491258.50798.17078.133.31.189.3253",
44
+ "files": [
45
+ {
46
+ "path": "test_data/siemens_20/1.2.826.0.1.3680043.2.706.1288491258.50798.17078.133.31.189.3253/im00001",
47
+ "sop_uid": "1.2.826.0.1.3680043.2.706.2259389430.41752.16525.175.174.133.102",
48
+ "artery": "left"
49
+ },
50
+ {
51
+ "path": "test_data/siemens_20/1.2.826.0.1.3680043.2.706.1288491258.50798.17078.133.31.189.3253/im00002",
52
+ "sop_uid": "1.2.826.0.1.3680043.2.706.3165698307.64654.20473.142.16.253.2281",
53
+ "artery": "exclude"
54
+ },
55
+ {
56
+ "path": "test_data/siemens_20/1.2.826.0.1.3680043.2.706.1288491258.50798.17078.133.31.189.3253/im00003",
57
+ "sop_uid": "1.2.826.0.1.3680043.2.706.2664535715.37729.19102.128.100.141.241",
58
+ "artery": "right"
59
+ },
60
+ {
61
+ "path": "test_data/siemens_20/1.2.826.0.1.3680043.2.706.1288491258.50798.17078.133.31.189.3253/im00004",
62
+ "sop_uid": "1.2.826.0.1.3680043.2.706.4248148477.11594.17258.150.192.45.1312",
63
+ "artery": "right"
64
+ },
65
+ {
66
+ "path": "test_data/siemens_20/1.2.826.0.1.3680043.2.706.1288491258.50798.17078.133.31.189.3253/im00005",
67
+ "sop_uid": "1.2.826.0.1.3680043.2.706.3107403860.64617.19044.158.57.243.2311",
68
+ "artery": "left"
69
+ },
70
+ {
71
+ "path": "test_data/siemens_20/1.2.826.0.1.3680043.2.706.1288491258.50798.17078.133.31.189.3253/im00006",
72
+ "sop_uid": "1.2.826.0.1.3680043.2.706.3266353610.421.17336.155.231.139.61641",
73
+ "artery": "left"
74
+ }
75
+ ],
76
+ "title": "Siemens \u00b7 6 projections",
77
+ "description": "An anonymized public holdout study. Artery assignments follow the published annotations.",
78
+ "repository": "MesserMMP/coronary-angiography-syntax",
79
+ "revision": "f5d6b5b4aa9856b12b8d65971beb8fce2f71e370"
80
+ }
81
+ ]
service/media.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Display-only cine encoding. This module never changes inference input files."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import math
6
+ import shutil
7
+ import subprocess
8
+ import tempfile
9
+ from pathlib import Path
10
+
11
+ import numpy as np
12
+ import pydicom
13
+ from PIL import Image
14
+ from pydicom.pixels import iter_pixels, pixel_array
15
+
16
+ from .storage import InputError, Projection, Store, Study
17
+
18
+
19
+ MAX_VIDEO_BYTES = 64 * 1024 * 1024
20
+
21
+
22
+ def encode_video(projection: Projection, destination: Path):
23
+ ffmpeg, ffprobe = shutil.which('ffmpeg'), shutil.which('ffprobe')
24
+ if not ffmpeg or not ffprobe:
25
+ raise InputError('The video encoder is unavailable in this runtime.')
26
+ ds = pydicom.dcmread(projection.path, stop_before_pixels=True,
27
+ specific_tags=['PhotometricInterpretation', 'CineRate', 'FrameTime', 'FrameTimeVector'])
28
+ try:
29
+ if ds.get('FrameTimeVector'):
30
+ durations = [float(x) for x in ds.FrameTimeVector if float(x) > 0]
31
+ rate = 1000 / float(np.mean(durations)) if durations else 15.
32
+ elif float(ds.get('FrameTime', 0) or 0) > 0:
33
+ rate = 1000 / float(ds.FrameTime)
34
+ else:
35
+ rate = float(ds.get('CineRate', 15) or 15)
36
+ if not math.isfinite(rate) or rate <= 0:
37
+ rate = 15.
38
+ except (ValueError, TypeError, ZeroDivisionError):
39
+ rate = 15.
40
+ rate = min(120., max(1., rate))
41
+ sample = pixel_array(projection.path, index=projection.frames // 2)
42
+ lo, hi = np.percentile(sample, [1, 99.5])
43
+ if hi <= lo:
44
+ lo, hi = float(sample.min()), float(sample.max())
45
+ ratio = min(1., 512 / max(projection.rows, projection.columns))
46
+ width = max(2, int(projection.columns * ratio) // 2 * 2)
47
+ height = max(2, int(projection.rows * ratio) // 2 * 2)
48
+ command = [ffmpeg, '-hide_banner', '-loglevel', 'error', '-nostdin', '-y',
49
+ '-f', 'rawvideo', '-pix_fmt', 'gray', '-s:v', f'{width}x{height}',
50
+ '-r', str(rate), '-i', 'pipe:0', '-an', '-c:v', 'libx264',
51
+ '-preset', 'veryfast', '-crf', '20', '-pix_fmt', 'yuv420p',
52
+ '-threads', '2', '-fps_mode', 'passthrough', '-movflags', '+faststart',
53
+ '-fs', str(MAX_VIDEO_BYTES), str(destination)]
54
+ process = None
55
+ try:
56
+ with tempfile.TemporaryFile() as errors:
57
+ process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=errors)
58
+ count = 0
59
+ for raw in iter_pixels(projection.path):
60
+ display = np.clip((raw.astype(np.float32) - lo) * (255 / max(hi - lo, 1)), 0, 255).astype(np.uint8)
61
+ if ds.get('PhotometricInterpretation') == 'MONOCHROME1':
62
+ display = 255 - display
63
+ frame = Image.fromarray(display).resize((width, height), Image.Resampling.LANCZOS)
64
+ process.stdin.write(frame.tobytes())
65
+ count += 1
66
+ process.stdin.close()
67
+ if process.wait(timeout=120) != 0 or count != projection.frames:
68
+ raise InputError('The complete sequence could not be encoded for display.')
69
+ check = subprocess.run([ffprobe, '-v', 'error', '-select_streams', 'v:0',
70
+ '-show_entries', 'stream=nb_frames', '-of', 'json', str(destination)],
71
+ capture_output=True, check=True, timeout=30)
72
+ encoded_frames = int(json.loads(check.stdout)['streams'][0]['nb_frames'])
73
+ if encoded_frames != projection.frames or destination.stat().st_size > MAX_VIDEO_BYTES:
74
+ raise InputError('The full cine exceeds the display preview limit.')
75
+ except Exception:
76
+ if process is not None and process.poll() is None:
77
+ process.kill()
78
+ process.wait()
79
+ destination.unlink(missing_ok=True)
80
+ raise
81
+
82
+
83
+ def cached_video(store: Store, study: Study, projection: Projection) -> Path:
84
+ destination = study.directory / (projection.id + '.mp4')
85
+ if destination.exists():
86
+ return destination
87
+ workspace = store.workspace('cine-')
88
+ try:
89
+ store.reserve(workspace, MAX_VIDEO_BYTES)
90
+ temporary = workspace / 'preview.mp4'
91
+ encode_video(projection, temporary)
92
+ with store.lock:
93
+ store.capacity(temporary.stat().st_size, 0, workspace=workspace)
94
+ temporary.replace(destination)
95
+ return destination
96
+ finally:
97
+ store.remove_workspace(workspace)
service/storage.py ADDED
@@ -0,0 +1,299 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import io
4
+ import os
5
+ import secrets
6
+ import shutil
7
+ import stat
8
+ import tempfile
9
+ import threading
10
+ import time
11
+ import zipfile
12
+ from dataclasses import dataclass, field
13
+ from pathlib import Path, PurePosixPath
14
+
15
+ import numpy as np
16
+ import pydicom
17
+ from PIL import Image
18
+ from pydicom.pixels import pixel_array, iter_pixels
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class Limits:
23
+ max_request_bytes: int = 512 * 1024 * 1024
24
+ max_file_bytes: int = 128 * 1024 * 1024
25
+ max_files: int = 64
26
+ max_studies: int = 8
27
+ max_frames: int = 1024
28
+ max_decoded_bytes: int = 512 * 1024 * 1024
29
+ ttl_seconds: int = 3600
30
+ max_pending_jobs: int = 3
31
+ max_stored_bytes: int = 2 * 1024 * 1024 * 1024
32
+ max_stored_studies: int = 32
33
+
34
+
35
+ class InputError(ValueError):
36
+ pass
37
+
38
+
39
+ @dataclass
40
+ class Projection:
41
+ id: str
42
+ path: Path
43
+ name: str
44
+ frames: int
45
+ rows: int
46
+ columns: int
47
+ sop_uid: str
48
+ artery: str = 'unassigned'
49
+ probability: float | None = None
50
+ reason: str | None = None
51
+
52
+ def public(self, study_id: str) -> dict:
53
+ return {
54
+ 'id': self.id, 'name': self.name, 'frames': self.frames,
55
+ 'rows': self.rows, 'columns': self.columns, 'artery': self.artery,
56
+ 'probability': self.probability, 'reason': self.reason,
57
+ 'preview_url': f'/api/studies/{study_id}/projections/{self.id}/preview',
58
+ 'animation_url': f'/api/studies/{study_id}/projections/{self.id}/preview?animated=true',
59
+ 'video_url': f'/api/studies/{study_id}/projections/{self.id}/video',
60
+ }
61
+
62
+
63
+ @dataclass
64
+ class Study:
65
+ id: str
66
+ study_uid: str
67
+ projections: list[Projection]
68
+ directory: Path
69
+ created_at: float = field(default_factory=time.time)
70
+ touched_at: float = field(default_factory=time.time)
71
+ active_job: str | None = None
72
+ readers: int = 0
73
+
74
+ def public(self) -> dict:
75
+ return {'id': self.id, 'study_uid': self.study_uid,
76
+ 'created_at': self.created_at,
77
+ 'projections': [p.public(self.id) for p in self.projections]}
78
+
79
+
80
+ def inspect_dicom(path: Path, name: str, limits: Limits) -> tuple[str, Projection]:
81
+ try:
82
+ ds = pydicom.dcmread(path, stop_before_pixels=True)
83
+ except Exception as exc:
84
+ raise InputError('Not a readable DICOM file.') from exc
85
+ uid = str(ds.get('StudyInstanceUID', ''))
86
+ sop = str(ds.get('SOPInstanceUID', ''))
87
+ if not uid or not sop:
88
+ raise InputError('DICOM must contain StudyInstanceUID and SOPInstanceUID.')
89
+ try:
90
+ frames = int(ds.get('NumberOfFrames', 1))
91
+ rows, columns = int(ds.Rows), int(ds.Columns)
92
+ bits = int(ds.BitsAllocated)
93
+ samples = int(ds.get('SamplesPerPixel', 1))
94
+ except Exception as exc:
95
+ raise InputError('Missing or invalid image dimensions.') from exc
96
+ if frames < 1 or frames > limits.max_frames or min(rows, columns) < 16 or max(rows, columns) > 4096:
97
+ raise InputError('Image dimensions exceed the supported limits.')
98
+ if samples != 1 or str(ds.get('PhotometricInterpretation', '')) not in {'MONOCHROME1', 'MONOCHROME2'}:
99
+ raise InputError('Only monochrome angiography DICOM sequences are supported.')
100
+ if bits not in {8, 16} or int(ds.get('PixelRepresentation', 0)) != 0:
101
+ raise InputError('Only unsigned 8-bit or 16-bit DICOM pixels are supported.')
102
+ if frames * rows * columns * (bits // 8) > limits.max_decoded_bytes:
103
+ raise InputError('Decoded sequence is too large for this demo.')
104
+ try:
105
+ # Decode one frame, not an entire cine, when validating the upload.
106
+ sample = pixel_array(path, index=frames // 2)
107
+ if sample.shape != (rows, columns):
108
+ raise ValueError('Unexpected frame shape')
109
+ except Exception as exc:
110
+ raise InputError('Cannot decode DICOM pixels. The compression may be unsupported.') from exc
111
+ short = frames < 10
112
+ return uid, Projection(secrets.token_urlsafe(24), path, name, frames, rows, columns, sop,
113
+ artery='exclude' if short else 'unassigned',
114
+ reason='Fewer than 10 frames; excluded from model input.' if short else None)
115
+
116
+
117
+ def poster(projection: Projection) -> bytes:
118
+ frame = pixel_array(projection.path, index=projection.frames // 2)
119
+ # This is a display-only mapping. Inference uses its own canonical preprocessing.
120
+ lo, hi = np.percentile(frame, [1, 99.5])
121
+ if hi <= lo:
122
+ lo, hi = float(frame.min()), float(frame.max())
123
+ display = np.clip((frame.astype(np.float32) - lo) * (255 / max(hi - lo, 1)), 0, 255).astype(np.uint8)
124
+ ds = pydicom.dcmread(projection.path, stop_before_pixels=True, specific_tags=['PhotometricInterpretation'])
125
+ if ds.get('PhotometricInterpretation') == 'MONOCHROME1':
126
+ display = 255 - display
127
+ image = Image.fromarray(display)
128
+ image.thumbnail((512, 512))
129
+ out = io.BytesIO()
130
+ image.save(out, format='PNG')
131
+ return out.getvalue()
132
+
133
+
134
+ def animation(projection: Projection) -> bytes:
135
+ """Small center-cine preview, independent of the model input transformation."""
136
+ length = min(projection.frames, 48)
137
+ start = (projection.frames - length) // 2
138
+ ds = pydicom.dcmread(projection.path, stop_before_pixels=True,
139
+ specific_tags=['PhotometricInterpretation', 'CineRate'])
140
+ frames = []
141
+ lo, hi = None, None
142
+ for raw in iter_pixels(projection.path, indices=range(start, start + length)):
143
+ if lo is None:
144
+ lo, hi = np.percentile(raw, [1, 99.5])
145
+ if hi <= lo:
146
+ lo, hi = float(raw.min()), float(raw.max())
147
+ display = np.clip((raw.astype(np.float32) - lo) * (255 / max(hi - lo, 1)), 0, 255).astype(np.uint8)
148
+ if ds.get('PhotometricInterpretation') == 'MONOCHROME1':
149
+ display = 255 - display
150
+ image = Image.fromarray(display)
151
+ image.thumbnail((320, 320))
152
+ frames.append(image)
153
+ if not frames:
154
+ raise InputError('No image frames were available.')
155
+ rate = float(ds.get('CineRate', 15) or 15)
156
+ out = io.BytesIO()
157
+ frames[0].save(out, format='GIF', save_all=True, append_images=frames[1:], loop=0,
158
+ duration=max(20, round(1000 / max(rate, 1))), optimize=False)
159
+ return out.getvalue()
160
+
161
+
162
+ def expand_zip(path: Path, target: Path, limits: Limits, *, remaining_bytes: int | None = None, reserve=None) -> list[tuple[Path, str]]:
163
+ """Extract validated regular files to generated names, never archive paths."""
164
+ try:
165
+ archive = zipfile.ZipFile(path)
166
+ except (zipfile.BadZipFile, OSError) as exc:
167
+ raise InputError('Invalid ZIP archive.') from exc
168
+ with archive:
169
+ entries = [info for info in archive.infolist() if not info.is_dir()]
170
+ if not entries or len(entries) > limits.max_files:
171
+ raise InputError(f'ZIP must contain between 1 and {limits.max_files} files.')
172
+ total = 0
173
+ for info in entries:
174
+ name = info.filename.replace('\\', '/')
175
+ parts = PurePosixPath(name)
176
+ mode = info.external_attr >> 16
177
+ if parts.is_absolute() or '..' in parts.parts or ':' in name or stat.S_ISLNK(mode):
178
+ raise InputError('ZIP contains unsafe paths or symbolic links.')
179
+ if info.flag_bits & 1:
180
+ raise InputError('Encrypted ZIP archives are not supported.')
181
+ total += info.file_size
182
+ if info.file_size > limits.max_file_bytes or total > min(limits.max_request_bytes, remaining_bytes if remaining_bytes is not None else limits.max_request_bytes):
183
+ raise InputError('ZIP exceeds the uncompressed size limit.')
184
+ if reserve:
185
+ reserve(total)
186
+ results = []
187
+ for info in entries:
188
+ dest = target / secrets.token_hex(16)
189
+ written = 0
190
+ try:
191
+ with archive.open(info) as source, dest.open('wb') as output:
192
+ while chunk := source.read(1024 * 1024):
193
+ written += len(chunk)
194
+ if written > limits.max_file_bytes:
195
+ raise InputError('Expanded file exceeds the size limit.')
196
+ output.write(chunk)
197
+ except (zipfile.BadZipFile, RuntimeError) as exc:
198
+ raise InputError('ZIP could not be decoded.') from exc
199
+ results.append((dest, Path(info.filename.replace('\\', '/')).name))
200
+ return results
201
+
202
+
203
+ class Store:
204
+ def __init__(self, root: Path, limits: Limits):
205
+ self.root = root
206
+ self.root.mkdir(parents=True, exist_ok=True, mode=0o700)
207
+ self.limits = limits
208
+ self.studies: dict[str, Study] = {}
209
+ self.workspaces: dict[Path, int] = {}
210
+ self.lock = threading.RLock()
211
+
212
+ def _occupied(self):
213
+ return sum(p.stat().st_size for s in self.studies.values() for p in s.directory.iterdir() if p.is_file())
214
+
215
+ def get(self, study_id: str) -> Study | None:
216
+ with self.lock:
217
+ study = self.studies.get(study_id)
218
+ if study and not study.active_job and not study.readers and time.time() - study.touched_at > self.limits.ttl_seconds:
219
+ self.delete(study_id)
220
+ return None
221
+ if study:
222
+ study.touched_at = time.time()
223
+ return study
224
+
225
+ def acquire(self, study_id: str) -> Study | None:
226
+ with self.lock:
227
+ study = self.get(study_id)
228
+ if study:
229
+ study.readers += 1
230
+ return study
231
+
232
+ def release(self, study: Study):
233
+ with self.lock:
234
+ study.readers = max(0, study.readers - 1)
235
+ study.touched_at = time.time()
236
+
237
+ def workspace(self, prefix: str) -> Path:
238
+ with self.lock:
239
+ path = Path(tempfile.mkdtemp(prefix=prefix, dir=self.root))
240
+ self.workspaces[path] = 0
241
+ return path
242
+
243
+ def reserve(self, workspace: Path, size: int):
244
+ with self.lock:
245
+ if self._occupied() + sum(self.workspaces.values()) + size > self.limits.max_stored_bytes:
246
+ raise InputError('Temporary storage is full. Remove unused studies or try again later.')
247
+ self.workspaces[workspace] += size
248
+
249
+ def unreserve(self, workspace: Path, size: int):
250
+ with self.lock:
251
+ self.workspaces[workspace] = max(0, self.workspaces[workspace] - size)
252
+
253
+ def remove_workspace(self, workspace: Path):
254
+ with self.lock:
255
+ shutil.rmtree(workspace, ignore_errors=True)
256
+ self.workspaces.pop(workspace, None)
257
+
258
+ def capacity(self, incoming_bytes: int, incoming_studies: int, *, workspace: Path | None = None):
259
+ with self.lock:
260
+ reserved = sum(size for path, size in self.workspaces.items() if path != workspace)
261
+ if self._occupied() + reserved + incoming_bytes > self.limits.max_stored_bytes or len(self.studies) + incoming_studies > self.limits.max_stored_studies:
262
+ raise InputError('Temporary storage is full. Remove unused studies or try again later.')
263
+
264
+ def add(self, study_uid: str, projections: list[Projection]) -> Study:
265
+ study_id = secrets.token_urlsafe(32)
266
+ directory = self.root / study_id
267
+ directory.mkdir(mode=0o700)
268
+ for projection in projections:
269
+ dest = directory / projection.id
270
+ shutil.move(str(projection.path), dest)
271
+ projection.path = dest
272
+ study = Study(study_id, study_uid, projections, directory)
273
+ with self.lock:
274
+ self.studies[study_id] = study
275
+ return study
276
+
277
+ def delete(self, study_id: str) -> bool:
278
+ with self.lock:
279
+ study = self.studies.get(study_id)
280
+ if not study:
281
+ return False
282
+ if study.active_job or study.readers:
283
+ raise InputError('Wait for the active job or preview to finish before removing this study.')
284
+ self.studies.pop(study_id)
285
+ shutil.rmtree(study.directory, ignore_errors=True)
286
+ return True
287
+
288
+ def cleanup(self):
289
+ now = time.time()
290
+ with self.lock:
291
+ expired = [s.id for s in self.studies.values()
292
+ if not s.active_job and not s.readers and now - s.touched_at > self.limits.ttl_seconds]
293
+ for study_id in expired:
294
+ self.delete(study_id)
295
+ # Active upload/example/video staging is explicitly protected, including long downloads.
296
+ known = {s.directory for s in self.studies.values()} | set(self.workspaces)
297
+ for entry in self.root.iterdir():
298
+ if entry.is_dir() and entry not in known and now - entry.stat().st_mtime > self.limits.ttl_seconds:
299
+ shutil.rmtree(entry, ignore_errors=True)
src/syntax_pred/__init__.py DELETED
@@ -1 +0,0 @@
1
-
 
 
src/syntax_pred/__pycache__/__init__.cpython-313.pyc DELETED
Binary file (154 Bytes)
 
src/syntax_pred/__pycache__/data.cpython-313.pyc DELETED
Binary file (3.16 kB)
 
src/syntax_pred/__pycache__/model.cpython-313.pyc DELETED
Binary file (12.5 kB)
 
src/syntax_pred/__pycache__/preprocess.cpython-313.pyc DELETED
Binary file (3.24 kB)
 
src/syntax_pred/__pycache__/utils.cpython-313.pyc DELETED
Binary file (1.97 kB)
 
src/syntax_pred/artery_cls.py DELETED
@@ -1,108 +0,0 @@
1
- # src/syntax_pred/artery_cls.py
2
- from __future__ import annotations
3
- from typing import List, Dict, Any
4
- import os
5
- import numpy as np
6
- import torch
7
- import torch.nn as nn
8
- import pydicom
9
- import torchvision.models.video as tvmv
10
- from torchvision.transforms import transforms as T
11
- from torchvision.transforms._transforms_video import ToTensorVideo
12
- from pytorchvideo.transforms import Normalize
13
-
14
- from .config import CFG, DEVICE
15
- from .hf_weights import fetch_classifier_weight # ← добавили импорт
16
-
17
- _ARTERY_MODEL: nn.Module | None = None
18
-
19
- def _resolve_classifier_weights_path() -> str:
20
- """
21
- 1) Берём CFG.classifier.weights, если файл существует.
22
- 2) Иначе — скачиваем из HF-репозитория (ENV WEIGHTS_REPO или CFG.weights_repo)
23
- из подпапки CFG.classifier.hf_subdir (по умолчанию 'classifier').
24
- """
25
- local_path = str(getattr(CFG.classifier, "weights", "") or "").strip()
26
- if local_path and os.path.isfile(local_path):
27
- return local_path
28
-
29
- repo_id = os.environ.get("WEIGHTS_REPO", getattr(CFG, "weights_repo", "") or "")
30
- subdir = str(getattr(CFG.classifier, "hf_subdir", "classifier"))
31
- if repo_id:
32
- pulled = fetch_classifier_weight(repo_id=repo_id, subdir=subdir)
33
- if pulled and os.path.isfile(pulled):
34
- return pulled
35
-
36
- # не нашли — вернём что есть (вызовущий код выбросит понятную ошибку)
37
- return local_path
38
-
39
- def _load_artery_model() -> nn.Module:
40
- global _ARTERY_MODEL
41
- if _ARTERY_MODEL is not None:
42
- return _ARTERY_MODEL
43
-
44
- weights_path = _resolve_classifier_weights_path()
45
- if not weights_path or not os.path.exists(weights_path):
46
- raise FileNotFoundError(
47
- f"Classifier weights not found. "
48
- f"Set a valid path in configs/default.yaml: classifier.weights "
49
- f"or ensure HF repo '{getattr(CFG, 'weights_repo', '')}' has '{getattr(CFG.classifier, 'hf_subdir', 'classifier')}/*.pt|*.ckpt'."
50
- )
51
-
52
- model = tvmv.r3d_18(weights=None)
53
- in_features = model.fc.in_features
54
- model.fc = nn.Linear(in_features=in_features, out_features=1, bias=True)
55
-
56
- raw = torch.load(weights_path, map_location="cpu", weights_only=False)
57
- sd = raw["state_dict"] if (isinstance(raw, dict) and "state_dict" in raw) else raw
58
- model_sd = {}
59
- for k, v in sd.items():
60
- assert k.startswith("model.")
61
- model_sd[k.split(".", 1)[1]] = v
62
-
63
- load_result = model.load_state_dict(model_sd, strict=False)
64
- if load_result.missing_keys or load_result.unexpected_keys:
65
- print("[classifier] load warnings:", load_result)
66
-
67
- model.to(DEVICE).eval()
68
- _ARTERY_MODEL = model
69
- return model
70
-
71
- def _artery_transform() -> T.Compose:
72
- video_size = tuple(CFG.classifier.video_size)
73
- mean = CFG.classifier.mean
74
- std = CFG.classifier.std
75
- return T.Compose([
76
- ToTensorVideo(),
77
- T.Resize(size=video_size),
78
- Normalize(mean=mean, std=std),
79
- ])
80
-
81
- @torch.no_grad()
82
- def classify_artery(files: List[str]) -> Dict[str, Any]:
83
- model = _load_artery_model()
84
- tx = _artery_transform()
85
- left_max = float(CFG.classifier.thresholds.left_max)
86
- right_min = float(CFG.classifier.thresholds.right_min)
87
-
88
- left, right, other = [], [], []
89
- for p in files:
90
- ds = pydicom.dcmread(p)
91
- arr = ds.pixel_array
92
- if arr.ndim == 2:
93
- arr = np.expand_dims(arr, axis=0)
94
- if arr.dtype == np.uint16:
95
- vmax = float(arr.max()) or 1.0
96
- arr = (arr.astype(np.float32) * (255.0 / vmax)).astype(np.uint8)
97
-
98
- thwc = np.stack([arr, arr, arr], axis=-1)
99
- x = tx(torch.tensor(thwc)).unsqueeze(0).to(DEVICE)
100
- prob = float(torch.sigmoid(model(x))[0, 0].detach().cpu())
101
- rec = {"path": p, "artery_prob": prob}
102
- if prob <= left_max:
103
- left.append(rec)
104
- elif prob >= right_min:
105
- right.append(rec)
106
- else:
107
- other.append(rec)
108
- return {"left": left, "right": right, "other": other}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/syntax_pred/config.py DELETED
@@ -1,7 +0,0 @@
1
- # src/syntax_pred/config.py — единая конфигурация и устройство
2
-
3
- from omegaconf import OmegaConf
4
- from .utils import pick_device
5
-
6
- CFG = OmegaConf.load("configs/default.yaml")
7
- DEVICE = pick_device(CFG.device)
 
 
 
 
 
 
 
 
src/syntax_pred/data.py DELETED
@@ -1,64 +0,0 @@
1
- from __future__ import annotations
2
- from typing import List, Tuple, Optional
3
- import os
4
- import numpy as np
5
- import torch
6
- from torch.utils.data import Dataset
7
-
8
- from .preprocess import (
9
- read_dicom_uint8,
10
- ensure_length_center_crop,
11
- test_like_transform,
12
- IMAGENET_MEAN,
13
- IMAGENET_STD,
14
- )
15
-
16
- DTYPE = torch.float16
17
-
18
- class SyntaxInferenceDataset(Dataset):
19
- """
20
- Загрузчик DICOM для инференса одной артерии.
21
- Возвращает:
22
- videos: (S=1, C, T, H, W) — один клип на элемент, RGB получен дублированием серого канала
23
- label: заглушка (torch.tensor([0], dtype=DTYPE))
24
- target: заглушка (torch.tensor([0.0], dtype=DTYPE))
25
- uid: имя файла
26
- """
27
- def __init__(
28
- self,
29
- files: List[str],
30
- frames_per_clip: int,
31
- video_size: Tuple[int, int],
32
- mean: Tuple[float, float, float] = IMAGENET_MEAN,
33
- std: Tuple[float, float, float] = IMAGENET_STD,
34
- transform: Optional[torch.nn.Module] = None,
35
- ):
36
- self.files = list(files)
37
- self.frames = int(frames_per_clip)
38
- self.video_size = video_size
39
- self.mean = mean
40
- self.std = std
41
- self.transform = transform or test_like_transform(video_size)
42
-
43
- def __len__(self) -> int:
44
- return len(self.files)
45
-
46
- def __getitem__(self, idx: int):
47
- path = self.files[idx]
48
- uid = os.path.basename(path)
49
-
50
- # (T,H,W) uint8 → выравнивание длины
51
- arr = read_dicom_uint8(path)
52
- arr = ensure_length_center_crop(arr, self.frames)
53
-
54
- # (T,H,W,3): серый → RGB
55
- vid_thwc = np.stack([arr, arr, arr], axis=-1)
56
- vid_thwc = torch.tensor(vid_thwc)
57
-
58
- # (C,T,H,W) → добавляем размерность последовательности S=1
59
- vid_cthw = self.transform(vid_thwc)
60
- videos = vid_cthw.unsqueeze(0)
61
-
62
- label = torch.tensor([0], dtype=DTYPE)
63
- target = torch.tensor([0.0], dtype=DTYPE)
64
- return videos, label, target, uid
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/syntax_pred/hf_weights.py DELETED
@@ -1,35 +0,0 @@
1
- # src/syntax_pred/hf_weights.py
2
- from __future__ import annotations
3
- import os, glob
4
- from typing import Dict, List, Iterable
5
- from huggingface_hub import snapshot_download
6
-
7
- def _collect(dirpath: str, patterns: Iterable[str] = ("*.pt", "*.ckpt")) -> List[str]:
8
- out: List[str] = []
9
- for pat in patterns:
10
- out.extend(glob.glob(os.path.join(dirpath, pat)))
11
- return sorted(out)
12
-
13
- def fetch_weights(repo_id: str,
14
- allow_patterns: Iterable[str] = ("left/*.pt","left/*.ckpt","right/*.pt","right/*.ckpt")
15
- ) -> Dict[str, List[str]]:
16
- cache_dir = snapshot_download(repo_id=repo_id, allow_patterns=list(allow_patterns))
17
- left_dir = os.path.join(cache_dir, "left")
18
- right_dir = os.path.join(cache_dir, "right")
19
- return {
20
- "left": _collect(left_dir) if os.path.isdir(left_dir) else [],
21
- "right": _collect(right_dir) if os.path.isdir(right_dir) else [],
22
- }
23
-
24
- def fetch_classifier_weight(repo_id: str,
25
- subdir: str = "classifier",
26
- file_patterns: Iterable[str] = ("*.pt", "*.ckpt")) -> str:
27
- """
28
- Скачивает веса классификатора из HF-репозитория.
29
- Возвращает путь к первому (отсортированному) найденному файлу или "".
30
- """
31
- allow = [f"{subdir}/{p}" for p in file_patterns]
32
- cache_dir = snapshot_download(repo_id=repo_id, allow_patterns=allow)
33
- target_dir = os.path.join(cache_dir, subdir)
34
- files = _collect(target_dir, patterns=file_patterns) if os.path.isdir(target_dir) else []
35
- return files[0] if files else ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/syntax_pred/infer.py DELETED
@@ -1,238 +0,0 @@
1
- # src/syntax_pred/infer.py — инференс SYNTAX (среднее по моделям), сортировка, Study
2
-
3
- from __future__ import annotations
4
- from dataclasses import dataclass
5
- from typing import List, Dict, Any, Tuple
6
-
7
- import os
8
- import numpy as np
9
- import torch
10
- import pydicom
11
-
12
- from .config import CFG, DEVICE
13
- from .utils import discover_weights
14
- from .model import SyntaxLightningModule
15
- from .preprocess import read_dicom_uint8, ensure_length_center_crop, test_like_transform
16
- from .hf_weights import fetch_weights
17
- from .artery_cls import classify_artery
18
-
19
-
20
- # -------- Data structure --------
21
- @dataclass
22
- class Study:
23
- name: str
24
- description: str
25
- files: List[str]
26
-
27
-
28
- # -------- Weights & model --------
29
- def build_model(weight_path: str) -> SyntaxLightningModule:
30
- m = SyntaxLightningModule(
31
- num_classes=CFG.num_classes,
32
- lr=1e-5,
33
- variant=CFG.variant,
34
- pl_weight_path=weight_path,
35
- rnn_hidden_div=CFG.a_rnn.hidden_div,
36
- rnn_dropout=CFG.a_rnn.dropout,
37
- bert_nhead=CFG.bert.nhead,
38
- bert_layers=CFG.bert.num_layers,
39
- bert_ff_div=CFG.bert.ff_div,
40
- bert_dropout=CFG.bert.dropout,
41
- precision=CFG.precision,
42
- )
43
- m = m.to(DEVICE).eval()
44
- return m
45
-
46
-
47
- def list_weights() -> Tuple[List[str], List[str]]:
48
- """
49
- Приоритет:
50
- 1) CFG.weights.left/right
51
- 2) weights/left|right
52
- 3) HF repo (ENV WEIGHTS_REPO или CFG.weights_repo)
53
- """
54
- left = list(getattr(CFG.weights, "left", [])) or []
55
- right = list(getattr(CFG.weights, "right", [])) or []
56
-
57
- if not left:
58
- left = discover_weights("weights/left")
59
- if not right:
60
- right = discover_weights("weights/right")
61
-
62
- if not left and not right:
63
- repo_id = os.environ.get("WEIGHTS_REPO", getattr(CFG, "weights_repo", "")) or ""
64
- if repo_id:
65
- pulled = fetch_weights(repo_id)
66
- left, right = pulled["left"], pulled["right"]
67
-
68
- return left, right
69
-
70
-
71
- # -------- Глобальные модели, инициализируемые при импорте --------
72
- _LEFT_MODEL_PATHS, _RIGHT_MODEL_PATHS = list_weights()
73
- _LEFT_MODELS: List[SyntaxLightningModule] = []
74
- _RIGHT_MODELS: List[SyntaxLightningModule] = []
75
-
76
- for wp in _LEFT_MODEL_PATHS:
77
- try:
78
- _LEFT_MODELS.append(build_model(wp))
79
- except Exception as e:
80
- print(f"[WARN] failed to init LEFT model {wp}: {e}")
81
-
82
- for wp in _RIGHT_MODEL_PATHS:
83
- try:
84
- _RIGHT_MODELS.append(build_model(wp))
85
- except Exception as e:
86
- print(f"[WARN] failed to init RIGHT model {wp}: {e}")
87
-
88
- if not _LEFT_MODELS and not _RIGHT_MODELS:
89
- print("[ERROR] No models initialized: check weights/ and HF repo configuration.")
90
-
91
-
92
- # -------- Stable sort --------
93
- def _stable_sort_paths(paths: List[str]) -> List[str]:
94
- """
95
- Сортировка в духе старого пайплайна:
96
- (SeriesInstanceUID, basename, fullpath)
97
- """
98
- def key(p: str):
99
- try:
100
- ds = pydicom.dcmread(p, stop_before_pixels=True, specific_tags=["SeriesInstanceUID"])
101
- series = str(getattr(ds, "SeriesInstanceUID", ""))
102
- except Exception:
103
- series = ""
104
- return (series, os.path.basename(p), p)
105
- return sorted(paths, key=key)
106
-
107
-
108
- def _filter_dicom_paths(paths: List[str]) -> List[str]:
109
- """Защитная фильтрация: оставляем только корректные DICOM."""
110
- out = []
111
- for p in paths:
112
- if not os.path.exists(p):
113
- continue
114
- try:
115
- pydicom.dcmread(p, stop_before_pixels=True)
116
- out.append(p)
117
- except Exception:
118
- continue
119
- return out
120
-
121
-
122
- # -------- Packing one side --------
123
- def _pack_study_side_to_tensor(
124
- file_paths: List[str],
125
- frames_per_clip: int,
126
- video_size: Tuple[int, int],
127
- ) -> torch.Tensor | None:
128
- if not file_paths:
129
- return None
130
- tx = test_like_transform(video_size)
131
- clips = []
132
- for p in file_paths:
133
- arr = read_dicom_uint8(p)
134
- arr = ensure_length_center_crop(arr, frames_per_clip)
135
- thwc = np.stack([arr, arr, arr], axis=-1) # (T,H,W,3)
136
- cthw = tx(torch.tensor(thwc, dtype=torch.uint8))
137
- clips.append(cthw)
138
- if not clips:
139
- return None
140
- return torch.stack(clips, dim=0).unsqueeze(0) # (1,S,C,T,H,W)
141
-
142
-
143
- @torch.no_grad()
144
- def _score_side_by_models(
145
- side_paths: List[str],
146
- models: List[SyntaxLightningModule],
147
- model_paths: List[str],
148
- frames_per_clip: int,
149
- video_size: Tuple[int, int],
150
- ) -> Dict[str, Any]:
151
- if not side_paths:
152
- return {"mean": 0.0, "per_model": [], "n_files": 0}
153
-
154
- x = _pack_study_side_to_tensor(side_paths, frames_per_clip, video_size)
155
- if x is None:
156
- return {"mean": 0.0, "per_model": [], "n_files": 0}
157
- x = x.to(DEVICE)
158
-
159
- per_model_scores: List[float] = []
160
- used_models: List[str] = []
161
-
162
- for m, wp in zip(models, model_paths):
163
- try:
164
- y = m(x) # (1,2)
165
- reg_log = float(y[0, 1].detach().cpu().numpy())
166
- score = float(max(0.0, np.exp(reg_log) - 1.0)) # inverse log(1+score)
167
- per_model_scores.append(score)
168
- used_models.append(os.path.basename(wp))
169
- except Exception as e:
170
- print(f"[WARN] model {wp} failed: {e}")
171
-
172
- mean_score = float(np.mean(per_model_scores)) if per_model_scores else 0.0
173
- return {
174
- "mean": mean_score,
175
- "per_model": [{"model": n, "score": round(s, 3)} for n, s in zip(used_models, per_model_scores)],
176
- "n_files": len(side_paths),
177
- }
178
-
179
-
180
- # -------- Top-level inference --------
181
- def run_inference(studies: List[Study]) -> Dict[str, Any]:
182
- if not _LEFT_MODEL_PATHS and not _RIGHT_MODEL_PATHS:
183
- return {"error": "No weights found. Upload to weights/left and weights/right."}
184
- if not _LEFT_MODELS and not _RIGHT_MODELS:
185
- return {"error": "Models failed to initialize. See logs."}
186
-
187
- results = {"studies": []}
188
- thr = CFG.thresholds.both
189
- video_size = tuple(CFG.video_size)
190
- frames = CFG.frames_per_clip
191
-
192
- for st in studies:
193
- st_files = _filter_dicom_paths(st.files)
194
-
195
- cls = classify_artery(st_files) # {"left":[{path,prob}], "right":[...], "other":[...]}
196
-
197
- left_paths = _stable_sort_paths([r["path"] for r in cls["left"]])
198
- right_paths = _stable_sort_paths([r["path"] for r in cls["right"]])
199
-
200
- left_res = _score_side_by_models(
201
- left_paths,
202
- _LEFT_MODELS,
203
- _LEFT_MODEL_PATHS,
204
- frames,
205
- video_size,
206
- )
207
- right_res = _score_side_by_models(
208
- right_paths,
209
- _RIGHT_MODELS,
210
- _RIGHT_MODEL_PATHS,
211
- frames,
212
- video_size,
213
- )
214
-
215
- total = left_res["mean"] + right_res["mean"]
216
-
217
- results["studies"].append({
218
- "study": st.name,
219
- "description": st.description or "",
220
- "left": {
221
- "mean": round(left_res["mean"], 3),
222
- "per_model": left_res["per_model"],
223
- "n_files": left_res["n_files"],
224
- "files": cls["left"],
225
- },
226
- "right": {
227
- "mean": round(right_res["mean"], 3),
228
- "per_model": right_res["per_model"],
229
- "n_files": right_res["n_files"],
230
- "files": cls["right"],
231
- },
232
- "other": cls["other"],
233
- "total": {
234
- "mean": round(total, 3),
235
- f"High-risk (≥{thr:.1f})": bool(total >= thr),
236
- },
237
- })
238
- return results
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/syntax_pred/model.py DELETED
@@ -1,204 +0,0 @@
1
- # src/syntax_pred/model.py — removed sigma & yulie, robust auto-loading, backward-compatible **kwargs
2
- from __future__ import annotations
3
- from typing import Any, Dict, List, Optional, Tuple
4
- import torch
5
- import torch.nn as nn
6
- import torch.nn.functional as F
7
- import torchvision.models.video as tvmv
8
- import lightning.pytorch as pl
9
-
10
- class SyntaxLightningModule(pl.LightningModule):
11
- """
12
- R3D-18 backbone с настраиваемой "головой" для последовательностей.
13
- На выходе тензор (B, 2): [логит классификации, регрессия = log(1 + score)].
14
- """
15
- def __init__(
16
- self,
17
- num_classes: int,
18
- lr: float,
19
- variant: str,
20
- weight_decay: float = 0.0,
21
- max_epochs: Optional[int] = None,
22
- weight_path: Optional[str] = None, # загрузка только бэкбона (опционально)
23
- pl_weight_path: Optional[str] = None, # загрузка целого модуля (ckpt/pt)
24
- rnn_hidden_div: int = 4,
25
- rnn_dropout: float = 0.2,
26
- bert_nhead: int = 4,
27
- bert_layers: int = 1,
28
- bert_ff_div: int = 4,
29
- bert_dropout: float = 0.2,
30
- precision: str = "bf16",
31
- **_ignore, # игнорирование лишних/неиспользуемых аргументов в вызове
32
- ) -> None:
33
- super().__init__()
34
- self.save_hyperparameters()
35
- self.num_classes = num_classes
36
- self.variant = variant
37
- self.lr = lr
38
- self.weight_decay = weight_decay
39
- self.max_epochs = max_epochs
40
-
41
- # --- Backbone (R3D-18)
42
- self.model = tvmv.r3d_18(weights=tvmv.R3D_18_Weights.DEFAULT)
43
- in_features = self.model.fc.in_features
44
- self.model.fc = nn.Linear(in_features, 2, bias=True)
45
-
46
- if weight_path is not None:
47
- self._load_backbone_weight(weight_path, self.model)
48
-
49
- # Для последовательных голов используем признаки до FC
50
- if self.variant != "mean_out":
51
- self.model.fc = nn.Identity()
52
-
53
- # --- Heads
54
- if self.variant == "mean_out":
55
- pass
56
- elif self.variant in ("gru_mean", "gru_last"):
57
- self.rnn = nn.GRU(in_features, in_features // rnn_hidden_div, batch_first=True)
58
- self.dropout = nn.Dropout(rnn_dropout)
59
- self.fc = nn.Linear(in_features // rnn_hidden_div, num_classes)
60
- elif self.variant in ("lstm_mean", "lstm_last"):
61
- self.lstm = nn.LSTM(
62
- input_size=in_features,
63
- hidden_size=in_features // rnn_hidden_div,
64
- proj_size=num_classes,
65
- batch_first=True,
66
- )
67
- elif self.variant == "mean":
68
- self.fc = nn.Linear(in_features, num_classes)
69
- elif self.variant in ("bert_mean", "bert_cls", "bert_cls2"):
70
- enc_layer = nn.TransformerEncoderLayer(
71
- d_model=in_features,
72
- nhead=bert_nhead,
73
- batch_first=True,
74
- dim_feedforward=in_features // bert_ff_div,
75
- dropout=bert_dropout,
76
- )
77
- self.encoder = nn.TransformerEncoder(enc_layer, num_layers=bert_layers)
78
- self.dropout = nn.Dropout(bert_dropout)
79
- self.fc = nn.Linear(in_features, num_classes)
80
- if self.variant == "bert_cls2":
81
- self.cls = nn.Parameter(torch.randn(1, 1, in_features))
82
- else:
83
- raise ValueError(f"Unknown variant: {self.variant}")
84
-
85
- # Загрузка полного state_dict (поддерживает форматы ckpt/pt)
86
- if pl_weight_path is not None:
87
- self._load_full_module(pl_weight_path)
88
-
89
- # Лоссы
90
- self.loss_clf = nn.BCEWithLogitsLoss(reduction="none")
91
- self.loss_reg = nn.MSELoss(reduction="none")
92
-
93
- # Кэши для валидационных метрик
94
- self.y_val: List[int] = []
95
- self.p_val: List[float] = []
96
- self.r_val: List[int] = []
97
- self.ty_val: List[float] = []
98
- self.tp_val: List[float] = []
99
-
100
- # ---------------- weights -----------------
101
- @staticmethod
102
- def _strip_prefix(key: str) -> str:
103
- for pref in ("model.", "backbone.", "module.", "net."):
104
- if key.startswith(pref):
105
- return key[len(pref):]
106
- return key
107
-
108
- def _load_backbone_weight(self, weight_path: str, model: nn.Module) -> None:
109
- ckpt = torch.load(weight_path, map_location="cpu")
110
- if isinstance(ckpt, dict) and "state_dict" in ckpt:
111
- ckpt = ckpt["state_dict"]
112
- new_sd = {
113
- self._strip_prefix(k).replace("fc.", ""): v
114
- for k, v in ckpt.items()
115
- if k.startswith(("model.", "backbone.", "module."))
116
- }
117
- model.load_state_dict(new_sd, strict=False)
118
-
119
- def _load_block(self, sd: Dict[str, torch.Tensor], module: nn.Module, prefix: str) -> None:
120
- filtered = {k.replace(f"{prefix}.", ""): v for k, v in sd.items() if k.startswith(prefix)}
121
- missing, unexpected = module.load_state_dict(filtered, strict=False)
122
- if missing:
123
- print(f"[load] Missing for {prefix}: {missing}")
124
- if unexpected:
125
- print(f"[load] Unexpected for {prefix}: {unexpected}")
126
-
127
- def _load_full_module(self, path: str) -> None:
128
- raw = torch.load(path, map_location="cpu")
129
- sd: Dict[str, torch.Tensor] = raw["state_dict"] if (isinstance(raw, dict) and "state_dict" in raw) else raw
130
- self._load_block(sd, self.model, "model")
131
- if self.variant == "mean_out":
132
- pass
133
- elif self.variant in ("gru_mean", "gru_last"):
134
- self._load_block(sd, self.rnn, "rnn")
135
- self._load_block(sd, self.fc, "fc")
136
- elif self.variant in ("lstm_mean", "lstm_last"):
137
- self._load_block(sd, self.lstm, "lstm")
138
- elif self.variant == "mean":
139
- self._load_block(sd, self.fc, "fc")
140
- elif self.variant in ("bert_mean", "bert_cls", "bert_cls2"):
141
- self._load_block(sd, self.encoder, "encoder")
142
- self._load_block(sd, self.fc, "fc")
143
- if self.variant == "bert_cls2" and "cls" in sd:
144
- with torch.no_grad():
145
- self.cls.copy_(sd["cls"])
146
-
147
- # ---------------- forward -----------------
148
- def forward(self, x: torch.Tensor) -> torch.Tensor:
149
- """
150
- Подача батча последовательностей формы (B,S,C,T,H,W),
151
- где S — число клипов внутри исследования для одной артерии.
152
- """
153
- b, s = x.shape[:2]
154
- x = x.flatten(0, 1) # (B*S, C, T, H, W)
155
- x = self.model(x) # (B*S, 2) или (B*S, F) при fc=Identity
156
- x = x.unflatten(0, (b, s)) # (B, S, ...)
157
-
158
- if self.variant == "mean_out":
159
- x = x.mean(dim=1)
160
- elif self.variant in ("gru_mean", "gru_last"):
161
- all_outs, last = self.rnn(x)
162
- x = all_outs.mean(dim=1) if self.variant == "gru_mean" else last[0]
163
- x = self.dropout(x)
164
- x = self.fc(x)
165
- elif self.variant in ("lstm_mean", "lstm_last"):
166
- all_outs, (last_out, _) = self.lstm(x)
167
- x = all_outs.mean(dim=1) if self.variant == "lstm_mean" else last_out
168
- elif self.variant == "mean":
169
- x = x.mean(dim=1)
170
- x = self.fc(x)
171
- elif self.variant in ("bert_mean", "bert_cls", "bert_cls2"):
172
- if self.variant == "bert_cls":
173
- x = F.pad(x, (0, 0, 1, 0), value=0.0) # добавление CLS токена
174
- elif self.variant == "bert_cls2":
175
- bs = x.size(0)
176
- x = torch.cat([self.cls.expand(bs, -1, -1), x], dim=1)
177
- x = self.encoder(x)
178
- x = x.mean(dim=1) if self.variant == "bert_mean" else x[:, 0, :]
179
- x = self.dropout(x)
180
- x = self.fc(x)
181
- else:
182
- raise ValueError(self.variant)
183
- return x # (B, 2)
184
-
185
- # --------------- training (kept for completeness) ---------------
186
- def training_step(self, batch, batch_idx):
187
- x, y, target, _ = batch
188
- y_hat = self(x)
189
- yp_clf = y_hat[:, 0:1]
190
- yp_reg = y_hat[:, 1:]
191
-
192
- weights_clf = torch.where(y > 0, 1.0, 0.2)
193
- clf_loss = (self.loss_clf(yp_clf, y) * weights_clf).mean()
194
-
195
- reg_loss = self.loss_reg(yp_reg, target).mean()
196
- return clf_loss + 0.5 * reg_loss
197
-
198
- def configure_optimizers(self):
199
- params = [p for p in self.parameters() if p.requires_grad]
200
- opt = torch.optim.Adam(params, lr=self.lr, weight_decay=self.weight_decay)
201
- if self.max_epochs:
202
- sch = torch.optim.lr_scheduler.OneCycleLR(opt, max_lr=self.lr, total_steps=self.max_epochs)
203
- return [opt], [sch]
204
- return opt
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/syntax_pred/preprocess.py DELETED
@@ -1,41 +0,0 @@
1
- # src/syntax_pred/preprocess.py — чтение DICOM и тестовый пайплайн трансформаций
2
-
3
- from __future__ import annotations
4
- from typing import Tuple
5
- import os
6
- import numpy as np
7
- import torch
8
- from torchvision.transforms import transforms as T
9
- from torchvision.transforms._transforms_video import ToTensorVideo
10
- from pytorchvideo.transforms import Normalize
11
- import pydicom
12
-
13
- IMAGENET_MEAN: Tuple[float, float, float] = (0.485, 0.456, 0.406)
14
- IMAGENET_STD: Tuple[float, float, float] = (0.229, 0.224, 0.225)
15
-
16
- def read_dicom_uint8(path: str) -> np.ndarray:
17
- ds = pydicom.dcmread(path)
18
- arr = ds.pixel_array # (T,H,W) или (H,W)
19
- if arr.ndim == 2:
20
- arr = np.expand_dims(arr, axis=0)
21
- if arr.dtype == np.uint16:
22
- vmax = float(arr.max()) or 1.0
23
- arr = (arr.astype(np.float32) * (255.0 / vmax)).astype(np.uint8)
24
- if arr.dtype != np.uint8:
25
- raise TypeError(f"Expected uint8 after conversion, got {arr.dtype} for {os.path.basename(path)}")
26
- return arr
27
-
28
- def ensure_length_center_crop(arr: np.ndarray, frames: int) -> np.ndarray:
29
- t_now = arr.shape[0]
30
- while t_now < frames:
31
- arr = np.concatenate([arr, arr], axis=0)
32
- t_now = arr.shape[0]
33
- start = (t_now - frames) // 2
34
- return arr[start:start + frames]
35
-
36
- def test_like_transform(video_size: Tuple[int, int]) -> T.Compose:
37
- return T.Compose([
38
- ToTensorVideo(),
39
- T.Resize(size=video_size, antialias=True),
40
- Normalize(mean=IMAGENET_MEAN, std=IMAGENET_STD),
41
- ])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/syntax_pred/utils.py DELETED
@@ -1,27 +0,0 @@
1
- from __future__ import annotations
2
- import glob, os
3
- import torch
4
-
5
- def pick_device(pref: str = "auto") -> torch.device:
6
- """
7
- Выбор устройства для вычислений: CUDA → MPS → CPU.
8
- При явном указании pref возвращается соответствующее устройство.
9
- """
10
- if pref == "auto":
11
- if torch.cuda.is_available():
12
- return torch.device("cuda")
13
- if hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
14
- return torch.device("mps")
15
- return torch.device("cpu")
16
- return torch.device(pref)
17
-
18
- def discover_weights(dirpath: str) -> list[str]:
19
- """
20
- Поиск весов моделей по маскам *.pt и *.ckpt внутри указанной директории.
21
- Возвращает отсортированный список путей.
22
- """
23
- pats = [os.path.join(dirpath, "*.pt"), os.path.join(dirpath, "*.ckpt")]
24
- found = []
25
- for p in pats:
26
- found.extend(glob.glob(p))
27
- return sorted(found)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
static/app.js ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+ const $=id=>document.getElementById(id);
3
+ const words={en:{studies:'Studies',addStudy:'Add study',sidebarEmpty:'Your studies will appear here after upload.',ephemeral:'Temporary workspace',sessionHint:'Download your results before you finish.',modelLink:'Model & methodology ↗',datasetLink:'Open dataset ↗',workspace:'Coronary angiography analysis',initialTitle:'From study to score.',initialSubtitle:'Upload DICOM, review the projections, and run the model.',researchOnly:'Research use',stepUpload:'Upload',stepUploadHint:'Study DICOM files',stepReview:'Review',stepReviewHint:'Left and right arteries',stepResult:'Get a score',stepResultHint:'10-model ensemble',dropTitle:'Bring your study',dropDescription:'Drop DICOM files or a ZIP archive.<br>Projections are grouped by StudyUID.',chooseFiles:'Choose files',beforeStart:'Before you begin',oneStudy:'The complete study.<br>One study-level estimate.',welcomeExplanation:'The model reads a set of left and right coronary artery projections. Individual clips are parts of one study.',prepareTitle:'Prepare the files',prepareText:'Use de-identified DICOM with no personal information.',reviewTitle:'Review the assignments',reviewText:'Identify the arteries automatically, or assign them yourself.',runTitle:'Run the ensemble',runText:'A full-study estimate requires both coronary arteries.',projection:'Projection',selectProjection:'Select a projection',dicomPreview:'DICOM · contrast-adjusted preview',projectionAssignment:'Projection assignment',leftArtery:'Left',rightArtery:'Right',exclude:'Exclude',allProjections:'All projections',autoClassify:'Identify arteries',resultTitle:'Model estimate',notCalculated:'Not calculated',resultEmpty:'Your study-level estimate will appear here after analysis.',rawSideNote:'Artery contributions before calibration. Calibration is applied to the whole study.',downloadResult:'Download result · JSON',readyToRun:'Study composition',excluded:'Excluded',calculate:'Calculate SYNTAX',jobHint:'The first run downloads model weights. CPU processing can take several minutes.',methodTitle:'A reproducible result',ensemble:'Ensemble',ensembleValue:'5 folds · 10 models',calibration:'Calibration',calibrationValue:'Applied per fold',device:'Compute',modelVersion:'Model revision',modelScope:'An estimate for research. Not a clinical conclusion.',foldResults:'Five-fold ensemble results',foldHint:'Study-level score for each fold',rawScore:'Before calibration',calibratedScore:'After calibration',footer:'Open model. Traceable result.',uploading:'Reading your study',uploadingHint:'Checking DICOM and grouping projections by StudyUID.',connecting:'Connecting…',offline:'Service unavailable',weightsDemand:'weights on demand',modelReady:'model available',weightsCached:'weights cached',modelLoading:'loading weights',modelError:'model unavailable',study:'Study',projections:'projections',frames:'frames',unassigned:'Unassigned',ready:'Ready',complete:'Complete',partial:'Partial',calibratedCaption:'Calibrated ensemble estimate',partialCaption:'A full-study score needs both arteries. Available artery estimates are shown below.',greater22:'SYNTAX ≥ 22',notGreater22:'SYNTAX < 22',reviewUnassigned:'Assign or exclude every projection before running.',bothReady:'Both arteries are represented. Ready for the ensemble.',onlyLeft:'Only LCA is represented. The result will be partial.',onlyRight:'Only RCA is represented. The result will be partial.',noIncluded:'Assign at least one eligible projection to an artery.',shortProjection:'Fewer than 10 frames · excluded from inference',shortCannotAssign:'Clips shorter than 10 frames cannot be included.',assignmentDefault:'Review the artery before inference.',copied:'StudyUID copied',copyFailed:'Could not copy StudyUID',deleted:'Study removed',deleteConfirm:'Remove this study and its uploaded files?',processing:'Processing…',queued:'Waiting to start…',failed:'The operation could not be completed.',invalidResponse:'The service returned an unexpected response.',loaded:'Study loaded',excludedFiles:'Files not added',noStudies:'No usable studies were found.',previewLabel:'Design preview · real public DICOM, no model prediction',previewHint:'This is a design preview. Open the workspace to upload a study and run the model.',earlier:'Move earlier',later:'Move later',order:'Projection order',exampleTitle:'Explore a public example',exampleLoad:'Open example',exampleHint:'Real anonymized DICOM from the published holdouts. Predictions are calculated on request.',loadingExample:'Loading the example',notAvailable:'Not available',deviceLocal:'Compute',resultStale:'Assignments changed. Run the model again.',atLeastOne:'Choose DICOM files or a ZIP archive.',readySubtitle:'Review the projections, then calculate the study-level score.',lowConfidence:'Review suggested assignment',jobClassify:'Identifying arteries',jobInference:'Calculating SYNTAX',jobExample:'Loading public example',confirmAuto:'Automatic classification will replace the current artery assignments for this study.',confirmClassifyTitle:'Replace artery assignments?',confirmDeleteTitle:'Remove this study?',dialogCancel:'Cancel',dialogContinue:'Continue',modelPreparing:'Preparing the ensemble',downloadFailed:'No result is available yet.',close:'Close',expand:'Expand preview',copyUid:'Copy StudyUID',arteryControls:'Artery assignment',workflow:'Workflow',previewVideo:'Angiography display preview',expandedVideo:'Expanded angiography display preview',removeStudy:'Remove study',modelsLicense:'Models & data · CC BY 4.0',expired:'This temporary session has expired. Please upload the study again.'},ru:{studies:'Исследования',addStudy:'Добавить исследование',sidebarEmpty:'Ваши исследования появятся здесь после загрузки.',ephemeral:'Временная рабочая сессия',sessionHint:'Скачайте результат перед завершением работы.',modelLink:'Модель и методология ↗',datasetLink:'Открытый датасет ↗',workspace:'Анализ коронарной ангиографии',initialTitle:'От исследования — к оценке.',initialSubtitle:'Загрузите DICOM, проверьте проекции и запустите модель.',researchOnly:'Для исследований',stepUpload:'Загрузить',stepUploadHint:'DICOM исследования',stepReview:'Проверить',stepReviewHint:'Левая и правая артерии',stepResult:'Получить оценку',stepResultHint:'Ансамбль из 10 моделей',dropTitle:'Добавьте исследование',dropDescription:'Перетащите DICOM-файлы или ZIP-архив.<br>Проекции будут объединены по StudyUID.',chooseFiles:'Выбрать файлы',beforeStart:'Перед началом',oneStudy:'Всё исследование.<br>Одна итоговая оценка.',welcomeExplanation:'Модель анализирует набор проекций левой и правой коронарных артерий. Отдельные клипы — части одного исследования.',prepareTitle:'Подготовьте файлы',prepareText:'Используйте обезличенные DICOM без персональной информации.',reviewTitle:'Проверьте распределение',reviewText:'Автоматически определите артерии или назначьте их вручную.',runTitle:'Запустите расчёт',runText:'Для общей оценки нужны проекции обеих артерий.',projection:'Проекция',selectProjection:'Выберите проекцию',dicomPreview:'DICOM · контраст для просмотра',projectionAssignment:'Артерия этой проекции',leftArtery:'Левая',rightArtery:'Правая',exclude:'Исключить',allProjections:'Все проекции',autoClassify:'Определить артерии',resultTitle:'Результат модели',notCalculated:'Не рассчитан',resultEmpty:'Итоговая оценка появится после расчёта.',rawSideNote:'Вклады артерий до калибровки. Итог калибруется для всего исследования.',downloadResult:'Скачать результат · JSON',readyToRun:'Состав исследования',excluded:'Исключено',calculate:'Рассчитать SYNTAX',jobHint:'Первый запуск включает загрузку весов. На CPU расчёт может занять несколько минут.',methodTitle:'Воспроизводимый расчёт',ensemble:'Ансамбль',ensembleValue:'5 фолдов · 10 моделей',calibration:'Калибровка',calibrationValue:'Для каждого fold',device:'Вычисления',modelVersion:'Версия модели',modelScope:'Исследовательская оценка модели. Не является клиническим заключением.',foldResults:'Результаты пяти фолдов ансамбля',foldHint:'Общий score для каждого fold',rawScore:'До калибровки',calibratedScore:'После калибровки',footer:'Открытая модель. Прослеживаемый результат.',uploading:'Читаем исследование',uploadingHint:'Проверяем DICOM и собираем проекции по StudyUID.',connecting:'Подключение…',offline:'Сервис недоступен',weightsDemand:'веса по запросу',modelReady:'модель доступна',weightsCached:'веса загружены',modelLoading:'загрузка весов',modelError:'модель недоступна',study:'Исследование',projections:'проекций',frames:'кадров',unassigned:'Не назначена',ready:'Готово',complete:'Рассчитан',partial:'Частичный',calibratedCaption:'Калиброва��ная оценка ансамбля',partialCaption:'Для итоговой оценки нужны обе артерии. Ниже показаны доступные вклады.',greater22:'SYNTAX ≥ 22',notGreater22:'SYNTAX < 22',reviewUnassigned:'Назначьте или исключите каждую проекцию перед расчётом.',bothReady:'Обе артерии представлены. Можно запускать ансамбль.',onlyLeft:'Представлена только LCA. Результат будет частичным.',onlyRight:'Представлена только RCA. Результат будет частичным.',noIncluded:'Назначьте хотя бы одну подходящую проекцию артерии.',shortProjection:'Меньше 10 кадров · исключено из расчёта',shortCannotAssign:'Видео короче 10 кадров нельзя включить в расчёт.',assignmentDefault:'Проверьте принадлежность проекции перед расчётом.',copied:'StudyUID скопирован',copyFailed:'Не удалось скопировать StudyUID',deleted:'Исследование удалено',deleteConfirm:'Удалить исследование и загруженные файлы?',processing:'Обработка…',queued:'Ожидаем запуска…',failed:'Не удалось завершить операцию.',invalidResponse:'Сервис вернул неожиданный ответ.',loaded:'Исследование загружено',excludedFiles:'Файлы не добавлены',noStudies:'Подходящие исследования не найдены.',previewLabel:'Макет интерфейса · реальные публичные DICOM, без предсказания модели',previewHint:'Это макет интерфейса. Откройте рабочее пространство для загрузки и расчёта.',earlier:'Раньше',later:'Позже',order:'Порядок проекций',exampleTitle:'Открыть публичный пример',exampleLoad:'Открыть пример',exampleHint:'Реальные обезличенные DICOM опубликованных holdout. Предсказания рассчитываются по запросу.',loadingExample:'Загружаем пример',notAvailable:'Недоступно',deviceLocal:'Вычисления',resultStale:'Назначения изменены. Запустите расчёт заново.',atLeastOne:'Выберите DICOM-файлы или ZIP-архив.',readySubtitle:'Проверьте проекции и рассчитайте оценку исследования.',lowConfidence:'Проверьте предложенную артерию',jobClassify:'Определяем артерии',jobInference:'Рассчитываем SYNTAX',jobExample:'Загружаем публичный пример',confirmAuto:'Автоматическое определение заменит текущие назначения артерий для этого исследования.',confirmClassifyTitle:'Заменить назначения артерий?',confirmDeleteTitle:'Удалить исследование?',dialogCancel:'Отмена',dialogContinue:'Продолжить',modelPreparing:'Подготовка ансамбля',downloadFailed:'Результат пока недоступен.',close:'Закрыть',expand:'Увеличить превью',copyUid:'Копировать StudyUID',arteryControls:'Назначение артерии',workflow:'Этапы анализа',previewVideo:'Превью коронарной ангиографии',expandedVideo:'Увеличенное превью коронарной ангиографии',removeStudy:'Удалить исследование',modelsLicense:'Модели и данные · CC BY 4.0',expired:'Срок временного хранения истёк. Загрузите исследование заново.'}};
4
+ const safeStored=(key,fallback)=>{try{return localStorage.getItem(key)||fallback;}catch{return fallback;}};
5
+ let lang=safeStored('cardiosyntax-language','en');if(!words[lang])lang='en';
6
+ let studies=[],selectedStudyId=null,selectedProjectionId=null,status=null,busy=false,activeJob=null,pollTimer=null,resultByStudy=new Map(),resultJobByStudy=new Map();
7
+ const previewMode=document.body.dataset.preview==='true';
8
+ const t=k=>words[lang][k]||words.en[k]||k;
9
+ const icon=name=>{const svg=document.createElementNS('http://www.w3.org/2000/svg','svg');const use=document.createElementNS('http://www.w3.org/2000/svg','use');use.setAttribute('href','#i-'+name);svg.append(use);return svg;};
10
+ const currentStudy=()=>studies.find(x=>x.id===selectedStudyId);
11
+ const currentProjection=()=>currentStudy()?.projections.find(x=>x.id===selectedProjectionId);
12
+ function el(tag,cls,text){const n=document.createElement(tag);if(cls)n.className=cls;if(text!==undefined)n.textContent=text;return n;}
13
+ function setStored(key,value){try{localStorage.setItem(key,value);}catch{}}
14
+ function applyLanguage(){document.documentElement.lang=lang;document.querySelectorAll('[data-t]').forEach(node=>node.innerHTML=t(node.dataset.t));$('language-button').textContent=lang==='en'?'RU':'EN';$('language-button').setAttribute('aria-label',lang==='en'?'Переключить на русский':'Switch to English');$('dropzone').setAttribute('aria-label',t('chooseFiles'));$('remove-study').setAttribute('aria-label',t('removeStudy'));$('study-list').setAttribute('aria-label',t('studies'));$('close-notice').setAttribute('aria-label',t('close'));$('close-preview').setAttribute('aria-label',t('close'));$('expand-preview').setAttribute('aria-label',t('expand'));$('copy-uid').setAttribute('aria-label',t('copyUid'));$('artery-controls').setAttribute('aria-label',t('arteryControls'));document.querySelector('.workflow').setAttribute('aria-label',t('workflow'));$('viewer-image').setAttribute('aria-label',t('previewVideo'));$('dialog-image').setAttribute('aria-label',t('expandedVideo'));$('preview-banner').textContent=t('previewLabel');render();renderStatus();renderExamples();if(activeJob){$('job-message').textContent=localizeStage(activeJob.message)||t(activeJob.kind==='classify'?'jobClassify':activeJob.kind==='example'?'jobExample':'jobInference');if(activeJob.kind==='example'){$('upload-title').textContent=t('loadingExample');$('upload-hint').textContent=$('job-message').textContent;}}}
15
+ function setTheme(theme){if(!['studio','lab'].includes(theme))theme='studio';document.documentElement.dataset.theme=theme;document.querySelectorAll('[data-theme-button]').forEach(b=>{const on=b.dataset.themeButton===theme;b.classList.toggle('selected',on);b.setAttribute('aria-pressed',String(on));});setStored('cardiosyntax-theme',theme);}
16
+ function showError(message){$('notice-text').textContent=message;$('notice').hidden=false;}
17
+ function hideError(){$('notice').hidden=true;}
18
+ function toast(message){const old=document.querySelector('.toast');old?.remove();const n=el('div','toast',message);n.setAttribute('role','status');document.body.append(n);setTimeout(()=>n.remove(),2800);}
19
+ function errorText(e){if(typeof e==='string')return localizeError(e);if(Array.isArray(e))return e.map(x=>errorText(x.msg||x.reason||x)).join('\n');if(e?.rejected?.length)return t('excludedFiles')+'\n'+e.rejected.map(x=>`${x.name}: ${localizeError(x.reason)}`).join('\n');if(e?.message||e?.detail)return errorText(e.message||e.detail);return t('failed');}
20
+ function localizeError(message){if(lang==='en'||typeof message!=='string')return message;const map=[[/expired/i,t('expired')],[/Insufficient memory/i,'Недостаточно памяти для исследования. Уменьшите число проекций или используйте более мощный сервер.'],[/model could not complete/i,'Модель не смогла завершить расчёт. Проверьте доступность весов и ресурсы сервера, затем повторите попытку. Оценка не рассчитана.'],[/another.*job|job.*running|already.*running|busy/i,'Сервер выполняет другой расчёт. Повторите попытку после его завершения.'],[/upload exceeds|expanded files exceed/i,'Превышен допустимый размер загружаемых файлов.'],[/Duplicate SOPInstanceUID/i,'Файл с таким SOPInstanceUID уже есть в загрузке; повторная копия не добавлена.'],[/not.*DICOM|invalid DICOM/i,'Файл не является корректным DICOM.']];return map.find(([pattern])=>pattern.test(message))?.[1]||message;}
21
+ async function request(url,options={}){let response;try{response=await fetch(url,{cache:'no-store',...options});}catch{throw new Error(t('offline'));}let data;try{data=await response.json();}catch{throw new Error(t('invalidResponse'));}if(!response.ok){const e=new Error(errorText(data.detail||data.error||data));e.status=response.status;throw e;}return data;}
22
+ async function refreshStatus(){if(previewMode)return;try{status=await request('/api/status');renderStatus();}catch{status=null;renderStatus();}}
23
+ function renderStatus(){const dot=$('server-indicator').querySelector('.status-dot');if(previewMode){$('server-label').textContent=lang==='en'?'Design preview':'Макет интерфейса';dot.className='status-dot';$('method-device').textContent=t('notAvailable');return;}if(!status){$('server-label').textContent=t('offline');dot.className='status-dot error';return;}const device=String(status.device||'cpu').toUpperCase();const state=status.model?.status||'not_loaded';const key={not_loaded:'weightsDemand',loading:'modelLoading',ready:'modelReady',cached:'weightsCached',error:'modelError',unavailable:'modelError'}[state]||'weightsDemand';$('server-label').textContent=`${device} · ${t(key)}`;dot.className='status-dot'+(['error','unavailable'].includes(state)?' error':' ready');$('method-device').textContent=device;const revision=status.model?.revision||status.revision;if(revision){$('model-revision').textContent=revision.slice(0,8);$('model-revision').href=`https://huggingface.co/${status.model?.repository||status.repo_id||'MesserMMP/coronary-syntax-prediction'}/tree/${revision}`;}const limits=status.limits;if(limits)$('upload-limits').textContent=`DICOM · ZIP · ${limits.max_request_mb||512} MB · ${limits.max_files||64} ${lang==='en'?'files':'файла'}`;}
24
+ function renderSidebar(){$('study-count').textContent=studies.length;const list=$('study-list');list.replaceChildren();if(!studies.length){list.append(el('div','sidebar-empty',t('sidebarEmpty')));return;}studies.forEach((s,i)=>{const b=el('button','study-item'+(s.id===selectedStudyId?' selected':''));b.disabled=busy;b.setAttribute('aria-current',s.id===selectedStudyId?'true':'false');const logo=el('span','study-item-icon');logo.append(icon('file'));const text=el('span','study-item-text');text.append(el('strong','',`${t('study')} ${String(i+1).padStart(2,'0')}`),el('small','',`${s.projections.length} ${t('projections')}${resultByStudy.has(s.id)?' · '+t(resultByStudy.get(s.id).complete===false?'partial':'complete'):''}`));b.append(logo,text);if(resultByStudy.has(s.id))b.append(el('span','status-mini'));b.addEventListener('click',()=>selectStudy(s.id));list.append(b);});}
25
+ function selectStudy(id){selectedStudyId=id;selectedProjectionId=currentStudy()?.projections[0]?.id||null;render();}
26
+ function render(){persistWorkspace();renderSidebar();renderExamples();const s=currentStudy();$('welcome').hidden=!!s;$('workspace-grid').hidden=!s;$('remove-study').hidden=!s;$('remove-study').disabled=busy;const index=studies.findIndex(x=>x.id===selectedStudyId);$('page-title').textContent=s?`${t('study')} ${String(index+1).padStart(2,'0')}`:t('initialTitle');$('page-subtitle').textContent=s?t('readySubtitle'):t('initialSubtitle');$('step-upload').className='step '+(s?'done':'active');$('step-review').className='step '+(s?(resultByStudy.has(s.id)?'done':'active'):'');$('step-result').className='step '+(s&&resultByStudy.has(s.id)?'done':busy?'active':'');$('sidebar-upload').disabled=busy;$('dropzone').setAttribute('aria-disabled',String(busy));if(!s)return;$('study-uid').textContent=s.study_uid;$('projection-count').textContent=s.projections.length;if(!s.projections.some(x=>x.id===selectedProjectionId))selectedProjectionId=s.projections[0]?.id||null;renderProjection();renderFilmstrip();renderCounts();renderResult();}
27
+ function labelFor(artery){return {left:'LCA',right:'RCA',exclude:t('excluded'),unassigned:t('unassigned')}[artery]||t('unassigned');}
28
+ function renderProjection(){const p=currentProjection();$('viewer-image').hidden=!p;$('viewer-empty').hidden=!!p;if(!p)return;const img=$('viewer-image');const src=p.video_url||'';img.poster=p.preview_url;if(img.dataset.current!==src){img.src=src;img.dataset.current=src;img.load();}img.setAttribute('aria-label',`${t('projection')}: ${p.name}`);$('viewer-name').textContent=p.name;$('viewer-dimensions').textContent=`${p.rows||512} × ${p.columns||512} · ${p.frames} ${t('frames')}`;$('viewer-position').textContent=`${String(currentStudy().projections.indexOf(p)+1).padStart(2,'0')} / ${String(currentStudy().projections.length).padStart(2,'0')}`;$('viewer-artery').textContent=labelFor(p.artery);$('assignment-help').textContent=p.frames<10?t('shortProjection'):p.reason&&p.artery==='unassigned'?t('lowConfidence'):t('assignmentDefault');document.querySelectorAll('[data-artery]').forEach(b=>{b.classList.toggle('selected',b.dataset.artery===p.artery);b.setAttribute('aria-pressed',String(b.dataset.artery===p.artery));b.disabled=busy||(p.frames<10&&b.dataset.artery!=='exclude');});}
29
+ function renderFilmstrip(){const strip=$('filmstrip');strip.replaceChildren();const s=currentStudy();s.projections.forEach((p,i)=>{const b=el('button','projection-card'+(p.id===selectedProjectionId?' selected':''));b.disabled=busy;b.setAttribute('aria-label',`${i+1}. ${p.name}. ${labelFor(p.artery)}`);b.setAttribute('aria-pressed',String(p.id===selectedProjectionId));const img=el('img');img.src=p.preview_url;img.alt='';img.loading='lazy';const meta=el('span','projection-card-bottom');meta.append(el('span','projection-tag '+p.artery,labelFor(p.artery)),el('span','',`${p.frames} f`));b.append(img,el('span','projection-index',String(i+1).padStart(2,'0')),meta);b.addEventListener('click',()=>{selectedProjectionId=p.id;renderProjection();renderFilmstrip();});strip.append(b);});let order=$('order-controls');if(!order){order=el('div','order-controls');order.id='order-controls';strip.after(order);}order.replaceChildren(el('span','',t('order')));for(const [delta,key,sign]of [[-1,'earlier','←'],[1,'later','→']]){const b=el('button','',`${sign} ${t(key)}`);const index=s.projections.findIndex(p=>p.id===selectedProjectionId);b.disabled=busy||index+delta<0||index+delta>=s.projections.length;b.addEventListener('click',()=>{const other=index+delta;[s.projections[index],s.projections[other]]=[s.projections[other],s.projections[index]];invalidateResult();render();});order.append(b);}}
30
+ function renderCounts(){const s=currentStudy();const counts={left:0,right:0,exclude:0,unassigned:0};s.projections.forEach(p=>counts[p.artery in counts?p.artery:'unassigned']++);$('left-count').textContent=counts.left;$('right-count').textContent=counts.right;$('excluded-count').textContent=counts.exclude;let hint=counts.unassigned?'reviewUnassigned':!counts.left&&!counts.right?'noIncluded':counts.left&&counts.right?'bothReady':counts.left?'onlyLeft':'onlyRight';$('run-hint').textContent=t(hint);$('run-button').disabled=busy||!!counts.unassigned||(!counts.left&&!counts.right);$('classify-button').disabled=busy||!s.projections.some(p=>p.frames>=10);}
31
+ function invalidateResult(){const id=selectedStudyId;if(resultByStudy.has(id)){resultByStudy.delete(id);resultJobByStudy.delete(id);toast(t('resultStale'));}}
32
+ function finite(...values){return values.find(v=>typeof v==='number'&&Number.isFinite(v));}
33
+ function number(value){return typeof value==='number'&&Number.isFinite(value)?value.toFixed(1):'—';}
34
+ function renderResult(){const result=resultByStudy.get(selectedStudyId);$('result-details').hidden=!result;$('fold-results').hidden=!result;$('result-state').textContent=result?t(result.complete===false?'partial':'complete'):t('notCalculated');$('result-state').className='neutral-badge'+(result?' complete':'');$('score-number').className='score-number'+(!result?' empty':'');const calibrated=result?finite(result.calibrated,result.calibrated_score,result.total?.calibrated):undefined;const complete=!!result&&result.complete!==false&&calibrated!==undefined;$('score-number').replaceChildren(document.createTextNode(complete?number(calibrated):'—'));$('score-caption').textContent=t(!result?'resultEmpty':complete?'calibratedCaption':'partialCaption');if(!result){$('result-classification').textContent='';$('left-score').textContent='—';$('right-score').textContent='—';$('fold-table-body').replaceChildren();return;}$('score-axis-dot').style.left=`${Math.min(60,Math.max(0,calibrated||0))/60*100}%`;$('score-axis-dot').parentElement.hidden=!complete;document.querySelector('.axis-labels').hidden=!complete;$('result-classification').textContent=complete?t(calibrated>=22?'greater22':'notGreater22'):'';$('left-score').textContent=number(finite(result.left_score,result.left?.raw,result.left?.mean,result.sides?.left?.raw));$('right-score').textContent=number(finite(result.right_score,result.right?.raw,result.right?.mean,result.sides?.right?.raw));const rows=result.per_fold||result.folds||[];const body=$('fold-table-body');body.replaceChildren();rows.forEach((r,i)=>{const row=el('tr');row.append(el('td','',String(r.fold??i).padStart(2,'0')),el('td','',number(finite(r.raw,r.raw_score,r.total_raw))),el('td','',number(finite(r.calibrated,r.calibrated_score,r.total_calibrated))));body.append(row);});$('fold-results').hidden=!rows.length;const revision=result.provenance?.revision||result.provenance?.model_revision;if(revision){$('model-revision').textContent=revision.slice(0,8);$('model-revision').href=`https://huggingface.co/${result.provenance.repo_id||result.provenance.repository||result.provenance.model_repository||'MesserMMP/coronary-syntax-prediction'}/tree/${revision}`;}}
35
+ function acceptStudies(data){const incoming=data.studies||(data.study?[data.study]:[]);for(const s of incoming){const old=studies.findIndex(x=>x.id===s.id);if(old>=0)studies[old]=s;else studies.push(s);}if(incoming.length)selectStudy(incoming[0].id);const messages=[];const errors=(data.rejected||[]).map(x=>`${x.name}: ${localizeError(x.reason)}`);if(errors.length)messages.push(t('excludedFiles')+'\n'+errors.join('\n'));else if(!incoming.length)messages.push(t('noStudies'));const warnings=data.warnings||[];if(warnings.length)messages.push(warnings.map(x=>typeof x==='string'?x:JSON.stringify(x)).join('\n'));if(messages.length)showError(messages.join('\n\n'));render();}
36
+ async function uploadFiles(files){if(busy)return;if(previewMode){showError(t('previewHint'));return;}if(!files.length){showError(t('atLeastOne'));return;}hideError();busy=true;$('upload-overlay').hidden=false;$('upload-title').textContent=t('uploading');$('upload-hint').textContent=t('uploadingHint');$('overlay-progress').hidden=true;render();const data=new FormData();for(const file of files)data.append('files',file);try{acceptStudies(await request('/api/studies',{method:'POST',body:data}));}catch(e){showError(e.message);}finally{busy=false;$('upload-overlay').hidden=true;$('file-input').value='';render();refreshStatus();}}
37
+
38
+ async function confirmAction(kind){const dialog=$('confirm-dialog');if(dialog.open)return false;const previousFocus=document.activeElement;$('confirm-title').textContent=t(kind==='delete'?'confirmDeleteTitle':'confirmClassifyTitle');$('confirm-message').textContent=t(kind==='delete'?'deleteConfirm':'confirmAuto');$('confirm-cancel').textContent=t('dialogCancel');$('confirm-continue').textContent=t('dialogContinue');dialog.returnValue='';return new Promise(resolve=>{dialog.addEventListener('close',()=>{const accepted=dialog.returnValue==='continue';if(previousFocus?.isConnected)previousFocus.focus();resolve(accepted);},{once:true});dialog.showModal();$('confirm-cancel').focus();});}
39
+
40
+ async function startJob(kind){if(busy)return;if(previewMode){showError(t('previewHint'));return;}const s=currentStudy();if(!s)return;if(kind==='classify'&&s.projections.some(p=>p.artery==='left'||p.artery==='right')&&!await confirmAction('classify'))return;hideError();busy=true;render();$('job-status').hidden=false;$('job-message').textContent=t('queued');$('job-percentage').textContent='';$('job-progress').value=0;try{const options={method:'POST'};if(kind==='inference'){options.headers={'Content-Type':'application/json'};options.body=JSON.stringify({assignments:s.projections.map(p=>({id:p.id,artery:p.artery}))});}const job=await request(`/api/studies/${s.id}/${kind==='classify'?'classify':'run'}`,options);activeJob={...job,study_id:s.id};persistWorkspace();pollJob();}catch(e){finishJob();showError(e.message);}}
41
+ function finishJob(){busy=false;activeJob=null;clearTimeout(pollTimer);$('job-status').hidden=true;$('upload-overlay').hidden=true;render();refreshStatus();}
42
+ async function pollJob(){if(!activeJob)return;try{const job=await request(`/api/jobs/${activeJob.id}`);activeJob.message=job.message;hideError();refreshStatus();const progress=Math.min(1,Math.max(0,Number(job.progress)||0));$('job-progress').value=progress;$('job-percentage').textContent=progress?`${Math.round(progress*100)}%`:'';$('job-message').textContent=localizeStage(job.message)||t(job.status==='queued'?'queued':activeJob.kind==='classify'?'jobClassify':activeJob.kind==='example'?'jobExample':'jobInference');if(activeJob.kind==='example'){$('upload-title').textContent=t('loadingExample');$('upload-hint').textContent=$('job-message').textContent;$('overlay-progress').hidden=false;$('overlay-progress').value=progress;}if(job.status==='completed'){if(activeJob.kind==='example')acceptStudies(job.result||{});else if(activeJob.kind==='classify'){const updated=job.result?.study;if(updated){const index=studies.findIndex(s=>s.id===updated.id);if(index>=0){const order=studies[index].projections.map(p=>p.id);updated.projections.sort((a,b)=>order.indexOf(a.id)-order.indexOf(b.id));studies[index]=updated;}resultByStudy.delete(updated.id);resultJobByStudy.delete(updated.id);}}else {resultByStudy.set(activeJob.study_id,job.result);resultJobByStudy.set(activeJob.study_id,job.id);}finishJob();return;}if(job.status==='failed'){const message=errorText(job.error);finishJob();showError(message);return;}pollTimer=setTimeout(pollJob,1200);}catch(e){if(e.status===404){finishJob();showError(t('expired'));}else{showError(e.message);pollTimer=setTimeout(pollJob,5000);}}}
43
+ let examples=[];
44
+ function renderExamples(){let box=$('examples-box');if(!box){box=el('section','examples-box');box.id='examples-box';document.querySelector('.welcome-aside').append(box);}box.replaceChildren();if(!examples.length)return;box.append(el('span','eyebrow',t('exampleTitle')));for(const example of examples){const b=el('button','example-button');b.disabled=busy;b.append(el('span','',example.title),icon('arrow'));b.addEventListener('click',()=>loadExample(example.id));box.append(b);}box.append(el('p','',t('exampleHint')));}
45
+ async function loadExamples(){if(previewMode)return;try{const d=await request('/api/examples');examples=d.examples||[];renderExamples();}catch{}}
46
+ async function loadExample(id){if(busy)return;busy=true;hideError();render();renderExamples();$('upload-overlay').hidden=false;$('upload-title').textContent=t('loadingExample');$('upload-hint').textContent=t('queued');$('overlay-progress').hidden=false;$('overlay-progress').value=0;try{const job=await request(`/api/examples/${encodeURIComponent(id)}/load`,{method:'POST'});activeJob={...job,kind:'example'};persistWorkspace();pollJob();}catch(e){finishJob();showError(e.message);}}
47
+ function openPreview(){const p=currentProjection();if(!p)return;$('dialog-name').textContent=p.name;$('dialog-image').src=p.video_url||'';$('dialog-image').poster=p.preview_url;$('viewer-image').pause();$('preview-dialog').showModal();$('dialog-image').play().catch(()=>{});}
48
+ $('language-button').addEventListener('click',()=>{lang=lang==='en'?'ru':'en';setStored('cardiosyntax-language',lang);applyLanguage();});document.querySelectorAll('[data-theme-button]').forEach(b=>b.addEventListener('click',()=>setTheme(b.dataset.themeButton)));
49
+ $('sidebar-upload').addEventListener('click',()=>previewMode?showError(t('previewHint')):$('file-input').click());$('dropzone').addEventListener('click',()=>{if(!busy)$('file-input').click();});$('dropzone').addEventListener('keydown',e=>{if(e.key==='Enter'||e.key===' '){e.preventDefault();if(!busy)$('file-input').click();}});$('file-input').addEventListener('change',()=>uploadFiles([...$('file-input').files]));for(const evt of ['dragenter','dragover'])$('dropzone').addEventListener(evt,e=>{e.preventDefault();$('dropzone').classList.add('dragging');});for(const evt of ['dragleave','drop'])$('dropzone').addEventListener(evt,e=>{e.preventDefault();$('dropzone').classList.remove('dragging');});$('dropzone').addEventListener('drop',e=>uploadFiles([...e.dataTransfer.files]));$('close-notice').addEventListener('click',hideError);
50
+ document.querySelectorAll('[data-artery]').forEach(b=>b.addEventListener('click',()=>{const p=currentProjection();if(!p||busy)return;p.artery=b.dataset.artery;invalidateResult();render();}));$('classify-button').addEventListener('click',()=>startJob('classify'));$('run-button').addEventListener('click',()=>startJob('inference'));$('expand-preview').addEventListener('click',openPreview);$('close-preview').addEventListener('click',()=>{$('dialog-image').pause();$('preview-dialog').close();});$('preview-dialog').addEventListener('close',()=>$('dialog-image').pause());$('preview-dialog').addEventListener('click',e=>{if(e.target===$('preview-dialog')){$('dialog-image').pause();$('preview-dialog').close();}});$('viewer-image').addEventListener('error',()=>{$('viewer-image').hidden=true;$('viewer-empty').hidden=false;});
51
+ $('copy-uid').addEventListener('click',async()=>{try{await navigator.clipboard.writeText(currentStudy()?.study_uid||'');toast(t('copied'));}catch{toast(t('copyFailed'));}});
52
+ $('remove-study').addEventListener('click',async()=>{if(busy||!currentStudy()||!await confirmAction('delete'))return;const id=selectedStudyId;try{if(!previewMode)await request(`/api/studies/${id}`,{method:'DELETE'});}catch(e){if(e.status!==404){showError(e.message);return;}}studies=studies.filter(s=>s.id!==id);resultByStudy.delete(id);resultJobByStudy.delete(id);selectStudy(studies[0]?.id||null);});
53
+ $('download-result').addEventListener('click',()=>{const result=resultByStudy.get(selectedStudyId);if(!result){showError(t('downloadFailed'));return;}const blob=new Blob([JSON.stringify({study_uid:currentStudy()?.study_uid,...result},null,2)],{type:'application/json'});const url=URL.createObjectURL(blob);const a=el('a');a.href=url;a.download='cardiosyntax-result.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);});
54
+
55
+ let workspaceRestored=false;
56
+ function persistWorkspace(){if(previewMode||!workspaceRestored)return;try{sessionStorage.setItem('cardiosyntax-workspace',JSON.stringify({study_ids:studies.map(s=>s.id),selected_study_id:selectedStudyId,active_job:activeJob?{id:activeJob.id,kind:activeJob.kind,study_id:activeJob.study_id}:null,result_jobs:[...resultJobByStudy],drafts:Object.fromEntries(studies.map(s=>[s.id,s.projections.map(p=>({id:p.id,artery:p.artery}))]))}));}catch{}}
57
+ async function restoreWorkspace(){let saved;try{saved=JSON.parse(sessionStorage.getItem('cardiosyntax-workspace')||'null');}catch{workspaceRestored=true;return;}if(!saved){workspaceRestored=true;return;}const restored=await Promise.all((saved.study_ids||[]).map(async id=>{try{const d=await request('/api/studies/'+encodeURIComponent(id));return d.study||d;}catch{return null;}}));studies=restored.filter(Boolean);if(saved.study_ids?.length&&!studies.length)showError(t('expired'));for(const study of studies){const draft=saved.drafts?.[study.id];if(!Array.isArray(draft)||draft.length!==study.projections.length)continue;const byId=new Map(study.projections.map(p=>[p.id,p]));if(new Set(draft.map(p=>p.id)).size!==byId.size||draft.some(p=>!byId.has(p.id)||!['left','right','exclude','unassigned'].includes(p.artery)))continue;study.projections=draft.map(item=>{const p=byId.get(item.id);p.artery=p.frames<10?'exclude':item.artery;return p;});}for(const [studyId,jobId]of saved.result_jobs||[]){if(!studies.some(s=>s.id===studyId))continue;try{const job=await request('/api/jobs/'+encodeURIComponent(jobId));if(job.status==='completed'&&job.kind==='inference'){resultByStudy.set(studyId,job.result);resultJobByStudy.set(studyId,jobId);}}catch{}}selectedStudyId=studies.some(s=>s.id===saved.selected_study_id)?saved.selected_study_id:studies[0]?.id||null;selectedProjectionId=currentStudy()?.projections[0]?.id||null;workspaceRestored=true;if(saved.active_job&&(saved.active_job.kind==='example'||studies.some(s=>s.id===saved.active_job.study_id))){activeJob=saved.active_job;busy=true;$('job-status').hidden=false;if(activeJob.kind==='example')$('upload-overlay').hidden=false;pollJob();}render();}
58
+ function localizeStage(message){if(!message||lang==='en')return message;const inference=message.match(/Processing (left|right) artery.*model (\d+) of (\d+)/i);if(inference)return `Вычисляем ${inference[1].toLowerCase()==='left'?'LCA':'RCA'} · модель ${inference[2]} из ${inference[3]}`;const rules=[[/download/i,'Загружаем необходимые файлы…'],[/loading.*model|loading.*weight|preparing.*model/i,'Подготавливаем модели…'],[/classif|arter/i,'Определяем принадлежность проекций…'],[/fold\s*(\d+)/i,'Вычисляем результат ансамбля…'],[/decod|read.*dicom|extract/i,'Читаем DICOM…'],[/queued|waiting/i,'Ожидаем запуска…'],[/complete|finished/i,'Готово']];return rules.find(([pattern])=>pattern.test(message))?.[1]||message;}
59
+
60
+ window.addEventListener('beforeunload',()=>clearTimeout(pollTimer));
61
+ async function init(){busy=!previewMode;const queryTheme=new URLSearchParams(location.search).get('theme');setTheme(queryTheme||safeStored('cardiosyntax-theme','studio'));applyLanguage();if(previewMode){$('preview-banner').hidden=false;try{const r=await fetch('/static/design-fixture.json');const fixture=await r.json();studies=fixture.studies;selectStudy(studies[0]?.id);}catch(e){showError(e.message);}return;}await refreshStatus();await restoreWorkspace();busy=!!activeJob;render();loadExamples();}
62
+ init();
static/index.html ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en" data-theme="studio">
3
+ <head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="theme-color" content="#f3f5f3"><title>CardioSyntax — Research Workspace</title><link rel="stylesheet" href="/static/styles.css"></head>
4
+ <body>
5
+ <svg class="icon-library" aria-hidden="true" xmlns="http://www.w3.org/2000/svg"><defs>
6
+ <symbol id="i-plus" viewBox="0 0 24 24"><path d="M12 5v14M5 12h14"/></symbol><symbol id="i-upload" viewBox="0 0 24 24"><path d="M12 16V3m-5 5 5-5 5 5M4 15v5h16v-5"/></symbol><symbol id="i-arrow" viewBox="0 0 24 24"><path d="m13 5 7 7-7 7M20 12H4"/></symbol><symbol id="i-expand" viewBox="0 0 24 24"><path d="M8 3H3v5m13-5h5v5M3 16v5h5m13-5v5h-5"/></symbol><symbol id="i-close" viewBox="0 0 24 24"><path d="m6 6 12 12M6 18 18 6"/></symbol><symbol id="i-file" viewBox="0 0 24 24"><path d="M14 3H5v18h14V8l-5-5Zm0 0v5h5M8 13h8m-8 4h6"/></symbol><symbol id="i-trash" viewBox="0 0 24 24"><path d="M3 6h18M9 6V3h6v3M5 6l1 15h12l1-15M10 10v7m4-7v7"/></symbol><symbol id="i-check" viewBox="0 0 24 24"><path d="m5 12 4 4L19 6"/></symbol><symbol id="i-download" viewBox="0 0 24 24"><path d="M12 3v13m-5-5 5 5 5-5M4 17v4h16v-4"/></symbol><symbol id="i-spark" viewBox="0 0 24 24"><path d="m12 3 2.6 6.4L21 12l-6.4 2.6L12 21l-2.6-6.4L3 12l6.4-2.6L12 3Z"/></symbol><symbol id="i-chevron" viewBox="0 0 24 24"><path d="m9 5 7 7-7 7"/></symbol><symbol id="i-info" viewBox="0 0 24 24"><circle cx="12" cy="12" r="9"/><path d="M12 11v6m0-10v1"/></symbol><symbol id="i-copy" viewBox="0 0 24 24"><path d="M8 8h12v13H8zM16 8V3H3v13h5"/></symbol>
7
+ </defs></svg>
8
+ <div class="preview-banner" id="preview-banner" hidden></div>
9
+ <header class="topbar">
10
+ <a class="brand" href="/" aria-label="CardioSyntax home"><span class="brand-mark"><svg viewBox="0 0 32 32" aria-hidden="true"><path d="M5 17h6l4-10 4 18 4-8h4"/><path class="brand-border" d="M9 3H3v6m20-6h6v6M3 23v6h6m14 0h6v-6"/></svg></span><span>Cardio<span class="brand-light">Syntax</span><small>RESEARCH WORKSPACE</small></span></a>
11
+ <div class="topbar-right"><div class="server-indicator" id="server-indicator"><span class="status-dot"></span><span id="server-label">Connecting…</span></div><div class="theme-switch" role="group" aria-label="Appearance"><button class="selected" data-theme-button="studio" aria-pressed="true">Studio</button><button data-theme-button="lab" aria-pressed="false">Lab</button></div><button class="language-button" id="language-button" aria-label="Switch language">RU</button></div>
12
+ </header>
13
+ <div class="app-layout">
14
+ <aside class="sidebar">
15
+ <div class="sidebar-heading"><span class="eyebrow" data-t="studies">Studies</span><span class="count-badge" id="study-count">0</span></div>
16
+ <button class="button sidebar-upload" id="sidebar-upload"><svg><use href="#i-plus"/></svg><span data-t="addStudy">Add study</span></button>
17
+ <div class="study-list" id="study-list" aria-label="Studies"><div class="sidebar-empty" data-t="sidebarEmpty">Your studies will appear here after upload.</div></div>
18
+ <div class="sidebar-bottom"><div class="session-note"><span class="tiny-dot"></span><span data-t="ephemeral">Temporary workspace</span></div><p data-t="sessionHint">Download your results before you finish.</p><a href="https://huggingface.co/MesserMMP/coronary-syntax-prediction" target="_blank" rel="noopener" data-t="modelLink">Model & methodology ↗</a><a href="https://huggingface.co/datasets/MesserMMP/coronary-angiography-syntax" target="_blank" rel="noopener" data-t="datasetLink">Open dataset ↗</a></div>
19
+ </aside>
20
+ <main class="main">
21
+ <div class="page-heading"><div><div class="eyebrow" data-t="workspace">Coronary angiography analysis</div><h1 id="page-title">From study to score.</h1><p class="page-subtitle" id="page-subtitle">Upload DICOM, review the projections, and run the model.</p></div><div class="heading-actions"><button class="icon-button" id="remove-study" hidden aria-label="Remove study"><svg><use href="#i-trash"/></svg></button><span class="research-tag" data-t="researchOnly">Research use</span></div></div>
22
+ <div class="notice error-notice" id="notice" role="alert" hidden><svg><use href="#i-info"/></svg><div id="notice-text"></div><button class="icon-button" id="close-notice" aria-label="Close"><svg><use href="#i-close"/></svg></button></div>
23
+ <nav class="workflow" aria-label="Workflow"><div class="step active" id="step-upload"><span class="step-number">01</span><div><strong data-t="stepUpload">Upload</strong><span data-t="stepUploadHint">Study DICOM files</span></div></div><span class="step-line"></span><div class="step" id="step-review"><span class="step-number">02</span><div><strong data-t="stepReview">Review</strong><span data-t="stepReviewHint">Left and right arteries</span></div></div><span class="step-line"></span><div class="step" id="step-result"><span class="step-number">03</span><div><strong data-t="stepResult">Get a score</strong><span data-t="stepResultHint">10-model ensemble</span></div></div></nav>
24
+ <section class="welcome" id="welcome">
25
+ <div class="welcome-main dropzone" id="dropzone" tabindex="0" role="button" aria-label="Upload DICOM files"><div class="drop-corners"><i></i><i></i><i></i><i></i></div><div class="upload-glyph"><svg><use href="#i-upload"/></svg></div><h2 data-t="dropTitle">Bring your study</h2><p data-t="dropDescription">Drop DICOM files or a ZIP archive.<br>Projections are grouped by StudyUID.</p><span class="button primary" data-t="chooseFiles">Choose files</span><span class="format-note" id="upload-limits">DICOM · ZIP</span></div>
26
+ <div class="welcome-aside"><span class="eyebrow" data-t="beforeStart">Before you begin</span><h2 data-t="oneStudy">The complete study.<br>One study-level estimate.</h2><p data-t="welcomeExplanation">The model reads a set of left and right coronary artery projections. Individual clips are parts of one study.</p><div class="preflight-item"><span>01</span><div><strong data-t="prepareTitle">Prepare the files</strong><p data-t="prepareText">Use de-identified DICOM with no personal information.</p></div></div><div class="preflight-item"><span>02</span><div><strong data-t="reviewTitle">Review the assignments</strong><p data-t="reviewText">Identify the arteries automatically, or assign them yourself.</p></div></div><div class="preflight-item"><span>03</span><div><strong data-t="runTitle">Run the ensemble</strong><p data-t="runText">A full-study estimate requires both coronary arteries.</p></div></div></div>
27
+ </section>
28
+ <div class="workspace-grid" id="workspace-grid" hidden>
29
+ <section class="study-panel">
30
+ <div class="viewer-shell"><div class="viewer-toolbar"><div><span class="viewer-kicker" data-t="projection">Projection</span><strong id="viewer-name">—</strong></div><div class="viewer-tools"><span id="viewer-dimensions"></span><button class="viewer-expand" id="expand-preview" aria-label="Expand preview"><svg><use href="#i-expand"/></svg></button></div></div><div class="viewer-canvas" id="viewer-canvas"><video id="viewer-image" aria-label="Angiography display preview" controls muted loop playsinline preload="metadata"></video><div class="viewer-empty" id="viewer-empty"><svg><use href="#i-file"/></svg><span data-t="selectProjection">Select a projection</span></div><span class="viewer-artery" id="viewer-artery">—</span></div><div class="viewer-bottom"><span><span class="live-dot"></span><span data-t="dicomPreview">DICOM · contrast-adjusted preview</span></span><span id="viewer-position">—</span></div></div>
31
+ <div class="assignment-row"><div><span class="eyebrow" data-t="projectionAssignment">Projection assignment</span><span class="assignment-help" id="assignment-help"></span></div><div class="segmented" id="artery-controls" role="group" aria-label="Artery assignment"><button data-artery="left">LCA<span data-t="leftArtery">Left</span></button><button data-artery="right">RCA<span data-t="rightArtery">Right</span></button><button data-artery="exclude"><svg><use href="#i-close"/></svg><span data-t="exclude">Exclude</span></button></div></div>
32
+ <div class="projections-heading"><h2><span data-t="allProjections">All projections</span> <span class="count-badge" id="projection-count">0</span></h2><button class="button quiet small" id="classify-button"><svg><use href="#i-spark"/></svg><span data-t="autoClassify">Identify arteries</span></button></div><div class="filmstrip" id="filmstrip"></div>
33
+ <div class="study-footnote"><span>StudyUID</span><code id="study-uid"></code><button class="icon-button small" id="copy-uid" aria-label="Copy StudyUID"><svg><use href="#i-copy"/></svg></button></div>
34
+ </section>
35
+ <aside class="analysis-panel">
36
+ <section class="result-card" id="result-card"><div class="card-title"><span class="eyebrow" data-t="resultTitle">Model estimate</span><span class="neutral-badge" id="result-state" data-t="notCalculated">Not calculated</span></div><div class="score-area"><span class="score-label">SYNTAX score</span><div class="score-number" id="score-number">—<span></span></div><p id="score-caption" data-t="resultEmpty">Your study-level estimate will appear here after analysis.</p></div><div id="result-details" hidden><div class="score-axis"><span class="score-axis-dot" id="score-axis-dot"></span><span class="axis-threshold"></span></div><div class="axis-labels"><span>0</span><span>22</span><span>60+</span></div><div class="result-classification" id="result-classification"></div><div class="side-scores"><div><span>LCA <small data-t="leftArtery">Left</small></span><strong id="left-score">—</strong></div><div><span>RCA <small data-t="rightArtery">Right</small></span><strong id="right-score">—</strong></div></div><p class="fine-print" data-t="rawSideNote">Artery contributions before calibration. Calibration is applied to the whole study.</p><button class="button outline full" id="download-result"><svg><use href="#i-download"/></svg><span data-t="downloadResult">Download result · JSON</span></button></div></section>
37
+ <section class="run-card"><div class="card-title"><span class="eyebrow" data-t="readyToRun">Study composition</span></div><div class="selection-counts"><div><span class="artery-dot left"></span><span>LCA</span><strong id="left-count">0</strong></div><div><span class="artery-dot right"></span><span>RCA</span><strong id="right-count">0</strong></div><div><span class="artery-dot excluded"></span><span data-t="excluded">Excluded</span><strong id="excluded-count">0</strong></div></div><p class="run-hint" id="run-hint"></p><button class="button primary full" id="run-button" disabled><span data-t="calculate">Calculate SYNTAX</span><svg><use href="#i-arrow"/></svg></button><div class="job-status" id="job-status" role="status" aria-live="polite" hidden><div class="job-status-heading"><span class="spinner"></span><strong id="job-message"></strong><span id="job-percentage"></span></div><progress id="job-progress" max="1" value="0"></progress><p data-t="jobHint">The first run downloads model weights. CPU processing can take several minutes.</p></div></section>
38
+ <section class="method-card"><span class="eyebrow" data-t="methodTitle">A reproducible result</span><dl><div><dt data-t="ensemble">Ensemble</dt><dd data-t="ensembleValue">5 folds · 10 models</dd></div><div><dt data-t="calibration">Calibration</dt><dd data-t="calibrationValue">Applied per fold</dd></div><div><dt data-t="device">Compute</dt><dd id="method-device">—</dd></div><div><dt data-t="modelVersion">Model revision</dt><dd><a id="model-revision" target="_blank" rel="noopener">—</a></dd></div></dl><p data-t="modelScope">An estimate for research. Not a clinical conclusion.</p></section>
39
+ </aside>
40
+ <section class="fold-results" id="fold-results" hidden><div class="projections-heading"><h2 data-t="foldResults">Five-fold ensemble results</h2><span class="muted" data-t="foldHint">Study-level score for each fold</span></div><div class="fold-table-wrap"><table><thead><tr><th>Fold</th><th data-t="rawScore">Before calibration</th><th data-t="calibratedScore">After calibration</th></tr></thead><tbody id="fold-table-body"></tbody></table></div></section>
41
+ </div>
42
+ <footer class="page-footer"><span>CardioSyntax</span><span data-t="footer">Open model. Traceable result.</span><a href="https://huggingface.co/datasets/MesserMMP/coronary-angiography-syntax" target="_blank" rel="noopener" data-t="modelsLicense">Models &amp; data · CC BY 4.0</a></footer>
43
+ </main>
44
+ </div>
45
+ <input type="file" id="file-input" multiple accept=".dcm,.dicom,.zip,application/dicom,application/zip" hidden>
46
+ <div class="upload-overlay" id="upload-overlay" hidden role="status" aria-live="polite"><div><span class="spinner"></span><h2 id="upload-title" data-t="uploading">Reading your study</h2><p id="upload-hint" data-t="uploadingHint">Checking DICOM and grouping projections by StudyUID.</p><progress id="overlay-progress" max="1" value="0" hidden></progress></div></div>
47
+ <dialog class="preview-dialog" id="preview-dialog"><div><span id="dialog-name"></span><button class="icon-button" id="close-preview" aria-label="Close"><svg><use href="#i-close"/></svg></button></div><video id="dialog-image" aria-label="Expanded angiography display preview" controls muted loop playsinline preload="metadata"></video></dialog>
48
+ <dialog class="confirm-dialog" id="confirm-dialog" aria-labelledby="confirm-title" aria-describedby="confirm-message"><form method="dialog"><div class="confirm-dialog-heading"><span class="eyebrow">CardioSyntax</span><h2 id="confirm-title"></h2></div><p id="confirm-message"></p><div class="confirm-dialog-actions"><button class="button outline" id="confirm-cancel" value="cancel" type="submit" autofocus>Cancel</button><button class="button primary" id="confirm-continue" value="continue" type="submit">Continue</button></div></form></dialog>
49
+ <script src="/static/app.js" defer></script>
50
+ </body></html>
static/styles.css ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @import url('https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;450;500;550;600;650;700&family=Manrope:wght@400;500;600;650;700;750;800&display=swap');
2
+ :root{--bg:#f4f6f4;--surface:#fff;--sidebar:#edf1ee;--ink:#172b2a;--muted:#70807c;--line:#dfe6e1;--accent:#16695a;--accent-hover:#0b5044;--accent-pale:#e3f0e9;--viewer:#101a1b;--viewer-ink:#dce6df;--right:#a1b8d0;--shadow:0 8px 30px #1b332806;--danger:#a34232;--danger-bg:#fff0e9;--radius:14px;font-family:'DM Sans',system-ui,-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;color:var(--ink);background:var(--bg);font-synthesis:none;color-scheme:light}
3
+ html[data-theme=lab]{--bg:#10191d;--surface:#182429;--sidebar:#131e23;--ink:#e6eeeb;--muted:#9baea8;--line:#2c3d42;--accent:#afdac6;--accent-hover:#d3efe1;--accent-pale:#243e34;--viewer:#080e12;--viewer-ink:#e6eeeb;--right:#9bb9d6;--shadow:none;--danger:#ffc4aa;--danger-bg:#442b25;color-scheme:dark}
4
+ *{box-sizing:border-box}body{margin:0}button,input{font:inherit}button,a{-webkit-tap-highlight-color:transparent}button{cursor:pointer}button:disabled{cursor:not-allowed;opacity:.45}button:focus-visible,a:focus-visible,[tabindex]:focus-visible{outline:3px solid #76b6a1;outline-offset:4px}button{color:inherit}a{color:var(--accent);text-decoration:none}a:hover{text-decoration:underline}svg{width:20px;height:20px;fill:none;stroke:currentColor;stroke-width:1.6;stroke-linecap:round;stroke-linejoin:round;flex-shrink:0}h1,h2,p{margin:0}h1,h2,.brand,.score-number{font-family:'Manrope','DM Sans',sans-serif}h1{font-size:30px;line-height:1.23;letter-spacing:-1.15px;font-weight:650}h2{font-size:17px;font-weight:650;letter-spacing:-.4px}[hidden]{display:none!important}.icon-library{position:absolute;width:0;height:0;overflow:hidden}.topbar{height:86px;border-bottom:1px solid var(--line);background:var(--surface);display:flex;align-items:center;justify-content:space-between;padding:0 36px 0 28px;gap:24px}.brand{color:var(--ink);display:flex;gap:12px;align-items:center;font-size:23px;font-weight:800;letter-spacing:-.8px;text-decoration:none!important;line-height:1}.brand-light{font-weight:500}.brand small{display:block;font-family:'DM Sans',sans-serif;font-weight:500;letter-spacing:2px;font-size:8px;margin-top:8px;color:var(--muted)}.brand-mark{width:38px;height:38px;display:grid;place-items:center;color:var(--accent)}.brand-mark svg{width:34px;height:34px;stroke-width:1.6}.brand-border{opacity:.35}.topbar-right{display:flex;align-items:center;gap:23px}.server-indicator{display:flex;align-items:center;gap:8px;font-size:11px;color:var(--muted)}.status-dot,.tiny-dot{width:6px;height:6px;border-radius:50%;background:var(--muted);flex:none}.status-dot.ready{background:#438a6c}.status-dot.error{background:#c76e54}.theme-switch{padding:3px;border:1px solid var(--line);border-radius:8px;display:flex;gap:1px}.theme-switch button{border:0;background:transparent;padding:5px 12px;border-radius:5px;font-size:10px;color:var(--muted)}.theme-switch button.selected{background:var(--ink);color:var(--surface)}.language-button{font-size:11px;letter-spacing:1px;font-weight:650;padding:6px 0;border:0;background:none}.app-layout{display:grid;grid-template-columns:230px minmax(0,1fr);min-height:calc(100vh - 86px)}.sidebar{background:var(--sidebar);border-right:1px solid var(--line);padding:30px 18px 20px;display:flex;flex-direction:column;min-width:0}.sidebar-heading{display:flex;align-items:center;justify-content:space-between;padding:0 10px;margin-bottom:18px}.eyebrow{text-transform:uppercase;letter-spacing:1.7px;font-size:9px;line-height:1.5;font-weight:650;color:var(--muted)}.count-badge{display:inline-flex;justify-content:center;align-items:center;font-family:'DM Sans',sans-serif;font-size:10px;font-weight:500;line-height:1;min-width:22px;height:22px;padding:0 6px;border:1px solid var(--line);border-radius:6px;color:var(--muted);vertical-align:middle;letter-spacing:0}.button{display:inline-flex;align-items:center;justify-content:center;gap:10px;border:1px solid transparent;background:var(--surface);border-radius:8px;padding:12px 17px;font-size:11px;font-weight:600;line-height:1.3;transition:background .16s,border-color .16s,color .16s;white-space:nowrap}.button svg{width:17px;height:17px}.primary{background:var(--accent);color:var(--surface);border-color:var(--accent)}.primary:hover:not(:disabled){background:var(--accent-hover);border-color:var(--accent-hover)}.outline{border-color:var(--line);background:transparent}.outline:hover:not(:disabled),.quiet:hover:not(:disabled){background:var(--accent-pale);border-color:var(--accent)}.quiet{border-color:var(--line);background:transparent}.small{padding:7px 10px;font-size:10px}.full{width:100%}.sidebar-upload{width:100%;background:transparent;border-color:#c4d1c9;justify-content:flex-start;padding-left:10px;font-size:10px}.sidebar-upload:hover{background:var(--surface);border-color:var(--accent)}.study-list{margin-top:23px;display:flex;flex-direction:column;gap:8px}.sidebar-empty{font-size:11px;line-height:1.8;padding:8px 10px;color:var(--muted)}.study-item{display:flex;align-items:center;gap:10px;text-align:left;border:1px solid transparent;border-radius:10px;padding:13px 10px;background:transparent;width:100%}.study-item.selected{background:var(--surface);border-color:var(--line);box-shadow:var(--shadow)}.study-item:not(.selected):hover{background:var(--surface)}.study-item-icon{width:30px;height:36px;display:grid;place-items:center;color:var(--muted);border:1px solid var(--line);border-radius:5px;background:var(--bg);flex:none}.study-item.selected .study-item-icon{color:var(--accent);border-color:transparent;background:var(--accent-pale)}.study-item-text{min-width:0;flex:1}.study-item strong{font-size:11px;display:block;font-weight:600}.study-item small{font-size:9px;display:block;color:var(--muted);margin-top:5px}.study-item .status-mini{width:5px;height:5px;background:var(--accent);border-radius:50%}.sidebar-bottom{margin-top:auto;padding:60px 10px 0;color:var(--muted);font-size:9px;line-height:1.7}.session-note{display:flex;align-items:center;gap:6px;font-size:9px}.sidebar-bottom p{margin:8px 0 22px}.sidebar-bottom a{display:block;margin-top:9px;color:var(--muted);font-size:10px}.main{padding:35px 36px 20px;min-width:0;max-width:1570px;width:100%;margin:0 auto}.page-heading{display:flex;align-items:center;justify-content:space-between;gap:18px;margin-bottom:25px}.page-heading .eyebrow{margin-bottom:10px}.page-subtitle{margin-top:10px;font-size:11px;line-height:1.7;color:var(--muted)}.heading-actions{display:flex;align-items:center;gap:12px}.research-tag{display:block;font-size:9px;white-space:nowrap;border:1px solid var(--line);border-radius:30px;padding:8px 12px;color:var(--muted)}.workflow{display:flex;align-items:center;padding:17px 21px;background:var(--surface);border:1px solid var(--line);border-radius:10px;margin-bottom:24px;gap:20px}.step{display:flex;align-items:center;gap:11px;opacity:.52;flex-shrink:0}.step.active,.step.done{opacity:1}.step-number{height:29px;width:29px;border-radius:50%;display:grid;place-items:center;font-size:10px;font-weight:600;border:1px solid var(--line);color:var(--muted)}.step.active .step-number{color:var(--accent);border-color:var(--accent);background:var(--accent-pale)}.step.done .step-number{background:var(--accent);color:var(--surface);border-color:var(--accent)}.step strong{font-size:10px;font-weight:600;display:block}.step span:not(.step-number){font-size:9px;color:var(--muted);display:block;margin-top:4px}.step-line{height:1px;background:var(--line);flex:1;min-width:15px}.welcome{display:grid;grid-template-columns:1.35fr 1fr;gap:40px;min-height:482px;align-items:stretch}.welcome-main{min-height:470px;background:var(--surface);border:1px solid var(--line);border-radius:var(--radius);position:relative;display:flex;flex-direction:column;align-items:center;justify-content:center;padding:35px 25px;text-align:center;cursor:pointer;transition:background .2s,border-color .2s}.welcome-main:hover,.welcome-main.dragging{border-color:var(--accent);background:var(--accent-pale)}.welcome-main h2{font-size:24px;letter-spacing:-.9px;font-weight:600;margin:22px 0 13px}.welcome-main p{font-size:12px;color:var(--muted);line-height:1.9}.welcome-main .button{margin-top:26px;min-width:150px}.upload-glyph{width:68px;height:68px;border:1px solid var(--line);border-radius:20px;display:grid;place-items:center;color:var(--accent);background:var(--bg)}.upload-glyph svg{width:27px;height:27px;stroke-width:1.4}.format-note{font-size:9px;color:var(--muted);margin-top:15px}.drop-corners i{position:absolute;width:14px;height:14px;border-color:#aabfb0;border-style:solid;border-width:0}.drop-corners i:nth-child(1){top:19px;left:19px;border-top-width:1px;border-left-width:1px}.drop-corners i:nth-child(2){top:19px;right:19px;border-top-width:1px;border-right-width:1px}.drop-corners i:nth-child(3){bottom:19px;left:19px;border-bottom-width:1px;border-left-width:1px}.drop-corners i:nth-child(4){bottom:19px;right:19px;border-bottom-width:1px;border-right-width:1px}.welcome-aside{padding:26px 16px 15px 0;max-width:390px}.welcome-aside h2{font-size:27px;letter-spacing:-1px;line-height:1.4;margin:14px 0}.welcome-aside>p{font-size:12px;line-height:1.9;color:var(--muted);margin-bottom:25px}.preflight-item{display:flex;gap:15px;padding:17px 0;border-top:1px solid var(--line)}.preflight-item>span{font-size:10px;line-height:1.8;color:var(--accent);font-weight:600}.preflight-item strong{font-size:11px;font-weight:600}.preflight-item p{font-size:10px;line-height:1.8;color:var(--muted);margin-top:5px}.workspace-grid{display:grid;grid-template-columns:minmax(0,1fr) 300px;gap:24px}.study-panel{min-width:0}.viewer-shell{border-radius:var(--radius);background:var(--viewer);overflow:hidden;color:var(--viewer-ink);box-shadow:var(--shadow)}.viewer-toolbar{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:16px 18px;border-bottom:1px solid #ffffff12}.viewer-kicker{display:block;text-transform:uppercase;font-size:8px;letter-spacing:1.5px;opacity:.48;margin-bottom:5px}.viewer-toolbar strong{font-size:10px;font-weight:450;display:block;max-width:220px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.viewer-tools{display:flex;align-items:center;gap:15px;font-size:8px;color:#93a5a0}.viewer-expand{background:none;border:0;padding:3px;color:var(--viewer-ink);opacity:.7}.viewer-expand:hover{opacity:1}.viewer-expand svg{width:15px;height:15px}.viewer-canvas{position:relative;height:355px;display:flex;align-items:center;justify-content:center;overflow:hidden;background:#080d0e}.viewer-canvas>img{height:100%;width:100%;object-fit:contain;cursor:zoom-in}.viewer-artery{position:absolute;left:18px;top:15px;color:#e6efe9;font-size:9px;letter-spacing:1.5px;border:1px solid #ffffff35;background:#0d161ac9;border-radius:4px;padding:5px 8px}.viewer-empty{color:#6e8582;display:flex;flex-direction:column;align-items:center;gap:12px;font-size:10px}.viewer-empty svg{width:30px;height:30px}.viewer-bottom{padding:11px 18px;display:flex;justify-content:space-between;font-size:8px;color:#9eafaa;letter-spacing:.4px}.viewer-bottom>span:first-child{display:flex;align-items:center;gap:6px}.live-dot{width:4px;height:4px;border-radius:50%;background:#9ec0ac}.assignment-row{display:flex;align-items:center;justify-content:space-between;gap:10px;padding:18px 0;border-bottom:1px solid var(--line)}.assignment-help{display:block;font-size:9px;color:var(--muted);line-height:1.5;margin-top:5px;max-width:200px}.segmented{display:flex;gap:3px;border:1px solid var(--line);border-radius:7px;padding:3px;background:var(--surface)}.segmented button{border:0;background:transparent;border-radius:4px;min-width:52px;padding:6px 8px;font-size:9px;font-weight:600;display:flex;gap:4px;align-items:center}.segmented button>span{font-size:8px;font-weight:400;color:var(--muted)}.segmented button svg{width:11px;height:11px}.segmented button.selected{background:var(--accent-pale);color:var(--accent)}.segmented button.selected>span{color:var(--accent)}.projections-heading{display:flex;justify-content:space-between;align-items:center;gap:12px;margin:22px 0 14px}.projections-heading h2{font-family:'DM Sans',sans-serif;font-size:12px;font-weight:600;letter-spacing:0}.projections-heading .count-badge{margin-left:6px}.filmstrip{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:9px}.projection-card{position:relative;border:1px solid var(--line);background:var(--surface);border-radius:7px;padding:3px;min-width:0;text-align:left;overflow:hidden}.projection-card.selected{border-color:var(--accent);box-shadow:0 0 0 1px var(--accent)}.projection-card img{height:70px;width:100%;object-fit:cover;display:block;background:var(--viewer);border-radius:4px}.projection-card .projection-index{position:absolute;top:8px;left:8px;background:#10201dc9;color:#fff;border-radius:3px;padding:2px 4px;font-size:8px}.projection-card-bottom{display:flex;align-items:center;justify-content:space-between;font-size:8px;padding:7px 4px 4px;gap:4px;color:var(--muted)}.projection-tag{display:flex;gap:4px;align-items:center;font-size:8px}.projection-tag.left{color:var(--accent)}.projection-tag.right{color:#6686aa}.projection-tag.unassigned{color:#aa8050}.projection-tag.exclude{opacity:.55}.projection-tag::before{content:'';display:block;width:4px;height:4px;border-radius:50%;background:currentColor}.order-controls{display:flex;align-items:center;gap:5px;margin-top:10px;justify-content:flex-end}.order-controls span{font-size:9px;color:var(--muted);margin-right:4px}.order-controls button{background:var(--surface);border:1px solid var(--line);border-radius:5px;font-size:9px;padding:5px 9px}.order-controls button:hover:not(:disabled){border-color:var(--accent)}.study-footnote{display:flex;align-items:center;gap:8px;font-size:8px;color:var(--muted);margin-top:16px;padding:10px 0;border-top:1px solid var(--line)}.study-footnote code{font-size:8px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;flex:1}.icon-button{background:none;border:0;padding:6px;display:inline-grid;place-items:center;border-radius:5px;color:var(--muted)}.icon-button:hover{background:var(--accent-pale);color:var(--accent)}.icon-button.small{padding:3px}.icon-button.small svg{width:12px;height:12px}.analysis-panel{display:flex;flex-direction:column;gap:16px;min-width:0}.result-card,.run-card{background:var(--surface);border:1px solid var(--line);border-radius:var(--radius);padding:22px;box-shadow:var(--shadow)}.card-title{display:flex;align-items:center;justify-content:space-between;gap:8px}.neutral-badge{font-size:8px;font-weight:500;color:var(--muted);background:var(--bg);border:1px solid var(--line);border-radius:4px;padding:4px 6px;white-space:nowrap}.neutral-badge.complete{background:var(--accent-pale);color:var(--accent);border-color:transparent}.score-area{padding-top:27px}.score-label{font-size:11px;color:var(--muted)}.score-number{font-size:74px;font-weight:500;line-height:1.15;letter-spacing:-4px;color:var(--ink);font-variant-numeric:tabular-nums;margin:4px 0 10px}.score-number.empty{color:#b8c6bd}.score-number>span{font-size:14px;letter-spacing:0;color:var(--muted);margin-left:8px}.score-area p{font-size:10px;color:var(--muted);line-height:1.7;max-width:210px}.score-axis{margin-top:23px;height:4px;background:var(--line);border-radius:3px;position:relative}.axis-threshold{position:absolute;left:36.66%;height:10px;top:-3px;width:1px;background:var(--muted);opacity:.65}.score-axis-dot{position:absolute;left:0;top:-3px;width:10px;height:10px;transform:translateX(-50%);border:2px solid var(--surface);box-shadow:0 0 0 1px var(--accent);border-radius:50%;background:var(--accent)}.axis-labels{display:flex;justify-content:space-between;color:var(--muted);font-size:8px;margin-top:9px;position:relative}.axis-labels span:nth-child(2){position:absolute;left:36.66%;transform:translateX(-50%)}.result-classification{font-size:10px;color:var(--accent);padding:13px 0 18px}.side-scores{display:grid;grid-template-columns:1fr 1fr;border-top:1px solid var(--line);padding-top:17px;gap:18px}.side-scores>div+div{border-left:1px solid var(--line);padding-left:20px}.side-scores span{font-size:9px;font-weight:600;display:block}.side-scores small{font-weight:400;color:var(--muted);margin-left:5px}.side-scores strong{font-size:23px;font-weight:500;display:block;margin-top:5px;font-variant-numeric:tabular-nums;letter-spacing:-.5px}.fine-print{font-size:8px;color:var(--muted);line-height:1.8;margin:13px 0 19px}.selection-counts{display:flex;flex-direction:column;gap:10px;margin:18px 0}.selection-counts>div{display:flex;align-items:center;gap:8px;font-size:10px}.selection-counts strong{margin-left:auto;font-size:11px;font-weight:500;font-variant-numeric:tabular-nums}.artery-dot{width:5px;height:5px;border-radius:50%;background:var(--accent)}.artery-dot.right{background:var(--right)}.artery-dot.excluded{background:var(--muted);opacity:.5}.run-hint{font-size:9px;color:var(--muted);line-height:1.8;margin-bottom:14px}.run-card>.primary{justify-content:space-between;padding:13px 14px;font-size:10px}.method-card{padding:6px 7px}.method-card dl{margin:13px 0}.method-card dl>div{display:flex;align-items:center;justify-content:space-between;font-size:9px;margin:10px 0;gap:10px}.method-card dt{color:var(--muted)}.method-card dd{margin:0;font-size:9px}.method-card p{font-size:8px;color:var(--muted);line-height:1.8;border-top:1px solid var(--line);padding-top:13px}.job-status{margin-top:16px}.job-status-heading{display:flex;align-items:center;gap:7px;font-size:9px}.job-status-heading strong{font-size:9px;font-weight:500;flex:1;overflow-wrap:anywhere}.spinner{display:inline-block;border:1.5px solid var(--line);border-top-color:var(--accent);width:15px;height:15px;flex:none;border-radius:50%;animation:spin .8s linear infinite}.job-status progress{appearance:none;display:block;width:100%;height:3px;border:0;margin-top:12px}.job-status progress::-webkit-progress-bar{background:var(--line);border-radius:3px}.job-status progress::-webkit-progress-value{background:var(--accent);border-radius:3px}.job-status p{font-size:8px;line-height:1.8;color:var(--muted);margin-top:10px}.fold-results{grid-column:1/-1;padding-top:4px}.fold-results .projections-heading{margin-top:4px}.muted{font-size:9px;color:var(--muted)}.fold-table-wrap{border:1px solid var(--line);border-radius:10px;overflow:hidden;background:var(--surface)}table{width:100%;border-collapse:collapse;font-size:10px;font-variant-numeric:tabular-nums}th{text-align:left;font-weight:500;color:var(--muted);background:var(--bg);font-size:9px;padding:12px 18px}td{padding:11px 18px;border-top:1px solid var(--line)}td:not(:first-child),th:not(:first-child){text-align:right}.page-footer{display:flex;justify-content:space-between;gap:15px;padding-top:24px;margin-top:36px;border-top:1px solid var(--line);font-size:8px;color:var(--muted)}.page-footer span:first-child{font-weight:600;color:var(--ink)}.notice{border:1px solid #dcab94;background:var(--danger-bg);border-radius:9px;padding:12px 13px;margin-bottom:18px;display:flex;gap:10px;align-items:flex-start;color:var(--danger);font-size:11px;line-height:1.7}.notice>svg{width:17px;height:17px;margin-top:2px}.notice>div{flex:1;overflow-wrap:anywhere;white-space:pre-line}.notice .icon-button{padding:0;color:inherit}.notice .icon-button svg{width:15px;height:15px}.upload-overlay{position:fixed;inset:0;background:#0b1b1ba8;backdrop-filter:blur(5px);display:grid;place-items:center;z-index:30}.upload-overlay>div{background:var(--surface);border:1px solid var(--line);border-radius:17px;text-align:center;padding:35px 40px;max-width:calc(100% - 40px)}.upload-overlay .spinner{width:28px;height:28px;margin-bottom:18px}.upload-overlay h2{font-size:20px}.upload-overlay p{font-size:11px;line-height:1.8;color:var(--muted);margin-top:12px}.preview-dialog{background:var(--viewer);color:var(--viewer-ink);border:1px solid #ffffff25;border-radius:12px;width:min(90vw,900px);max-height:93vh;padding:0;overflow:hidden}.preview-dialog::backdrop{background:#03090de8;backdrop-filter:blur(5px)}.preview-dialog>div{display:flex;align-items:center;justify-content:space-between;padding:10px 18px;font-size:11px}.preview-dialog>video{display:block;max-height:calc(90vh - 55px);height:auto;width:100%;object-fit:contain;background:#080d0e}.preview-dialog .icon-button{color:var(--viewer-ink)}.preview-banner{background:#e5f0e8;color:#265a44;padding:8px 24px;text-align:center;font-size:10px;font-weight:500;border-bottom:1px solid #bfd4c5}.preview-banner a{color:inherit;text-decoration:underline}.toast{position:fixed;bottom:25px;left:50%;transform:translateX(-50%);padding:10px 18px;border-radius:7px;background:var(--ink);color:var(--surface);font-size:11px;z-index:50}.lab-view .viewer-canvas{height:400px}@keyframes spin{to{transform:rotate(360deg)}}
5
+ @media(min-width:1500px){.main{padding-top:42px;padding-left:48px;padding-right:48px}.workspace-grid{grid-template-columns:minmax(0,1fr) 330px;gap:30px}.viewer-canvas{height:440px}.filmstrip{grid-template-columns:repeat(6,minmax(0,1fr))}.projection-card img{height:84px}}
6
+ @media(max-width:1190px){.app-layout{grid-template-columns:195px minmax(0,1fr)}.sidebar{padding-left:12px;padding-right:12px}.main{padding:28px 25px 20px}.workspace-grid{grid-template-columns:minmax(0,1fr) 260px;gap:18px}.result-card,.run-card{padding:18px}.workflow{gap:12px;padding:15px}.step{gap:8px}.step span:not(.step-number){font-size:8px}.viewer-canvas{height:310px}.assignment-row{flex-wrap:wrap}.assignment-row>.segmented{margin-left:auto}.filmstrip{grid-template-columns:repeat(4,minmax(0,1fr))}.topbar{padding-right:25px}.topbar-right{gap:16px}.welcome{gap:25px}.welcome-aside h2{font-size:23px}.welcome-aside{padding-top:20px}.page-heading h1{font-size:25px}.server-indicator{max-width:200px}}
7
+ @media(max-width:960px){.app-layout{grid-template-columns:165px minmax(0,1fr)}.sidebar{padding-left:9px;padding-right:9px}.sidebar-upload{font-size:9px;gap:5px;padding-left:7px;padding-right:6px}.sidebar-heading{padding:0 7px}.sidebar-heading .eyebrow{font-size:8px}.study-item{padding:11px 7px;gap:7px}.study-item strong{font-size:10px}.study-item-icon{display:none}.study-item small{font-size:8px}.main{padding:25px 20px 20px}.workspace-grid{grid-template-columns:minmax(0,1fr) 235px;gap:15px}.workflow{gap:10px;padding:13px}.step-number{width:23px;height:23px;font-size:8px}.step strong{font-size:9px}.step span:not(.step-number){display:none}.viewer-tools>span{display:none}.viewer-canvas{height:280px}.viewer-toolbar{padding:12px}.result-card,.run-card{padding:16px}.card-title{flex-wrap:wrap}.score-area{padding-top:20px}.score-number{font-size:64px}.segmented button{min-width:45px}.segmented button span{display:none}.segmented button[data-artery=exclude] span{display:block}.projections-heading{flex-wrap:wrap;gap:8px}.filmstrip{grid-template-columns:repeat(3,minmax(0,1fr))}.welcome{grid-template-columns:1fr;gap:15px}.welcome-main{min-height:370px}.welcome-aside{max-width:none;padding:15px 0;display:grid;grid-template-columns:repeat(3,1fr);gap:15px}.welcome-aside>.eyebrow,.welcome-aside>h2,.welcome-aside>p{display:none}.preflight-item{gap:8px}.topbar{height:76px;padding-left:18px}.brand{font-size:20px}.brand small{font-size:7px}.topbar-right{gap:12px}.server-indicator{font-size:9px}.research-tag{font-size:8px;padding:6px 8px}}
8
+ @media(max-width:760px){.topbar{height:72px;padding:0 18px}.brand{font-size:20px;gap:8px}.brand-mark{width:29px}.brand-mark svg{width:29px;height:29px}.brand small{font-size:6px;letter-spacing:1.5px;margin-top:6px}.server-indicator{display:none}.topbar-right{gap:11px}.theme-switch button{font-size:9px;padding:4px 8px}.language-button{font-size:10px}.app-layout{display:block;min-height:calc(100vh - 72px)}.sidebar{border-right:0;border-bottom:1px solid var(--line);padding:11px 18px;display:flex;flex-direction:row;gap:10px;align-items:center;overflow:auto}.sidebar-heading,.sidebar-bottom,.sidebar-empty{display:none}.sidebar-upload{width:auto;flex:none;padding:8px 9px;background:var(--surface)}.sidebar-upload svg{width:14px;height:14px}.study-list{display:flex;flex-direction:row;gap:6px;margin:0}.study-item{width:142px;padding:7px 10px;white-space:nowrap;border-radius:6px}.study-item strong{font-size:9px}.study-item small{font-size:7px;margin-top:3px}.main{padding:25px 18px 17px}.page-heading{margin-bottom:21px;align-items:flex-start}.page-heading h1{font-size:27px;letter-spacing:-1px}.page-heading .eyebrow{font-size:8px;margin-bottom:9px}.page-subtitle{font-size:10px;margin-top:8px;max-width:300px}.heading-actions{gap:3px}.research-tag{display:none}.workflow{margin-bottom:20px;gap:9px;padding:13px 10px}.step{gap:6px}.step strong{font-size:8px}.step-number{width:23px;height:23px}.step-line{min-width:8px}.welcome-main{min-height:345px;padding:25px 18px}.welcome-main h2{font-size:23px}.welcome-main p{font-size:10px}.upload-glyph{width:57px;height:57px;border-radius:16px}.welcome-aside{grid-template-columns:1fr;gap:0;padding:5px 5px 0}.preflight-item{padding:15px 0;gap:14px}.preflight-item strong{font-size:11px}.preflight-item p{font-size:10px}.workspace-grid{grid-template-columns:1fr;gap:22px}.viewer-canvas{height:min(85vw,440px)}.viewer-toolbar{padding:13px 15px}.viewer-toolbar strong{font-size:10px}.viewer-tools>span{display:block;font-size:8px}.viewer-bottom{padding:11px 15px}.assignment-row{flex-wrap:nowrap;padding:17px 0}.assignment-row .eyebrow{font-size:8px;letter-spacing:1px}.assignment-help{font-size:8px}.segmented button{font-size:8px;min-width:42px;padding:6px}.projections-heading{flex-wrap:nowrap}.projections-heading h2{font-size:11px}.projections-heading .button{font-size:9px;gap:5px;padding:7px 8px}.projections-heading .button svg{width:13px;height:13px}.filmstrip{grid-template-columns:repeat(4,minmax(0,1fr));gap:8px}.projection-card img{height:65px}.projection-card-bottom{font-size:7px;padding:6px 2px 3px}.projection-tag{font-size:7px}.analysis-panel{display:grid;grid-template-columns:1fr;gap:16px}.result-card,.run-card{padding:22px}.result-card{order:2}.run-card{order:1}.method-card{order:3}.score-area{padding-top:18px}.score-number{font-size:77px}.score-area p{max-width:none}.side-scores strong{font-size:27px}.card-title{flex-wrap:nowrap}.selection-counts{flex-direction:row;gap:20px}.selection-counts>div{flex:1}.selection-counts strong{margin-left:4px}.run-hint{font-size:10px}.method-card dl>div{font-size:10px}.method-card dd{font-size:10px}.method-card p{font-size:9px}.fold-results{grid-column:auto}.page-footer{margin-top:25px;flex-wrap:wrap;font-size:7px;gap:9px;padding-top:18px}.page-footer span:nth-child(2){margin-left:auto}.page-footer span:last-child{display:none}.preview-banner{font-size:9px;padding:8px 15px}}
9
+ @media(prefers-reduced-motion:reduce){*,*::before,*::after{animation-duration:.001ms!important;transition:none!important}}
10
+ .examples-box{margin-top:20px;padding-top:18px;border-top:1px solid var(--line)}.example-button{display:flex;align-items:center;justify-content:space-between;gap:12px;background:var(--surface);border:1px solid var(--line);border-radius:7px;padding:10px 12px;text-align:left;font-size:10px;margin-top:10px;width:100%}.example-button:hover:not(:disabled){border-color:var(--accent);background:var(--accent-pale)}.example-button svg{width:15px;height:15px;color:var(--accent)}.examples-box>p{font-size:9px;color:var(--muted);line-height:1.8;margin-top:10px}@media(max-width:960px) and (min-width:761px){.examples-box{grid-column:1/-1;margin-top:0}.example-button{max-width:360px}}@media(min-width:761px){html[data-theme=lab] .sidebar{background:#0d171b}html[data-theme=lab] .viewer-shell{border:1px solid #2c3d42}html[data-theme=lab] .research-tag{border-color:#385047}html[data-theme=lab] .workflow{background:transparent}}
11
+
12
+ .viewer-canvas video{width:100%;height:100%;object-fit:contain;cursor:default}.order-controls{display:flex;align-items:center;justify-content:flex-end;gap:12px;margin-top:12px;font-size:10px;color:var(--muted)}.order-controls>span{margin-right:auto}.order-controls button{border:0;background:none;font-size:10px;padding:6px 0;color:var(--accent)}.examples-box{grid-column:1/-1}
13
+
14
+ .upload-overlay progress{display:block;width:100%;height:4px;margin-top:20px;accent-color:var(--accent)}.page-footer a{color:var(--muted)}
15
+
16
+ .confirm-dialog{width:min(440px,calc(100vw - 36px));padding:0;border:1px solid var(--line);border-radius:16px;background:var(--surface);color:var(--ink);box-shadow:0 22px 70px #06171430}.confirm-dialog::backdrop{background:#0818178f;backdrop-filter:blur(5px)}.confirm-dialog form{padding:28px}.confirm-dialog-heading .eyebrow{display:block;margin-bottom:13px}.confirm-dialog h2{font-size:22px;line-height:1.35;letter-spacing:-.65px}.confirm-dialog p{margin-top:15px;font-size:13px;line-height:1.8;color:var(--muted)}.confirm-dialog-actions{display:flex;justify-content:flex-end;gap:10px;padding-top:26px}.confirm-dialog-actions .button{font-size:12px;min-width:100px}@media(max-width:480px){.confirm-dialog form{padding:23px}.confirm-dialog h2{font-size:20px}.confirm-dialog-actions .button{flex:1}}
tests/test_service.py ADDED
@@ -0,0 +1,339 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import time
3
+ import zipfile
4
+ from pathlib import Path
5
+
6
+ import numpy as np
7
+ import pytest
8
+ from fastapi.testclient import TestClient
9
+ from pydicom.dataset import FileDataset, FileMetaDataset
10
+ from pydicom.uid import ExplicitVRLittleEndian, generate_uid
11
+
12
+ from service.api import create_app
13
+ from service.storage import Limits
14
+
15
+
16
+ def dicom(uid=None, sop=None, frames=12):
17
+ meta = FileMetaDataset()
18
+ meta.TransferSyntaxUID = ExplicitVRLittleEndian
19
+ meta.MediaStorageSOPClassUID = '1.2.840.10008.5.1.4.1.1.12.1'
20
+ meta.MediaStorageSOPInstanceUID = sop or generate_uid()
21
+ ds = FileDataset(None, {}, file_meta=meta, preamble=b'\0' * 128)
22
+ ds.SOPClassUID = meta.MediaStorageSOPClassUID
23
+ ds.SOPInstanceUID = meta.MediaStorageSOPInstanceUID
24
+ ds.StudyInstanceUID = uid or generate_uid()
25
+ ds.SeriesInstanceUID = generate_uid()
26
+ ds.PatientName = 'PRIVATE^PERSON'
27
+ ds.PatientID = 'PRIVATE_PATIENT_ID'
28
+ ds.Rows = ds.Columns = 16
29
+ ds.NumberOfFrames = frames
30
+ ds.BitsAllocated = ds.BitsStored = 8
31
+ ds.HighBit = 7
32
+ ds.PixelRepresentation = 0
33
+ ds.SamplesPerPixel = 1
34
+ ds.PhotometricInterpretation = 'MONOCHROME2'
35
+ ds.PixelData = np.arange(frames * 256, dtype=np.uint8).tobytes()
36
+ output = io.BytesIO()
37
+ ds.save_as(output, enforce_file_format=True)
38
+ return output.getvalue()
39
+
40
+
41
+ class FakeEngine:
42
+ def __init__(self):
43
+ self.calls = []
44
+ self.fail = False
45
+
46
+ def status(self):
47
+ return {'device': 'cpu', 'model': {'status': 'not_loaded', 'loaded': 0, 'total': 10}}
48
+
49
+ def classify(self, paths, progress):
50
+ return [{'path': p, 'artery': 'left' if i % 2 == 0 else 'right', 'probability_right': i % 2}
51
+ for i, p in enumerate(paths)]
52
+
53
+ def infer(self, left, right, progress):
54
+ self.calls.append((left, right))
55
+ if self.fail:
56
+ raise RuntimeError('/private/upload/SECRET invalid')
57
+ complete = bool(left and right)
58
+ return {'raw': 8. if complete else None, 'calibrated': 10. if complete else None,
59
+ 'complete': complete, 'per_fold': [], 'provenance': {'test_fixture': True}}
60
+
61
+
62
+ @pytest.fixture
63
+ def workspace(tmp_path):
64
+ engine = FakeEngine()
65
+ app = create_app(data_root=tmp_path / 'data', engine=engine)
66
+ with TestClient(app) as client:
67
+ yield client, app, engine
68
+
69
+
70
+ def upload(client, payloads):
71
+ return client.post('/api/studies', files=[('files', (f'projection{i}.dcm', p, 'application/dicom')) for i, p in enumerate(payloads)])
72
+
73
+
74
+ def wait(client, job):
75
+ for _ in range(200):
76
+ status = client.get('/api/jobs/' + job['id']).json()
77
+ if status['status'] in {'completed', 'failed'}:
78
+ return status
79
+ time.sleep(.01)
80
+ pytest.fail('job did not complete')
81
+
82
+
83
+ def test_upload_groups_by_study_and_rejects_duplicate(workspace):
84
+ client, app, _ = workspace
85
+ uid = generate_uid()
86
+ a = dicom(uid)
87
+ response = upload(client, [a, dicom(uid), dicom(), a])
88
+ assert response.status_code == 200
89
+ result = response.json()
90
+ assert len(result['studies']) == 2
91
+ assert len(result['studies'][0]['projections']) == 2
92
+ assert len(result['rejected']) == 1
93
+ assert 'PRIVATE' not in response.text
94
+ image = client.get(result['studies'][0]['projections'][0]['preview_url'])
95
+ assert image.status_code == 200 and image.content.startswith(b'\x89PNG')
96
+ assert image.headers['cache-control'] == 'no-store'
97
+
98
+
99
+ def test_classification_inference_and_delete(workspace):
100
+ client, app, engine = workspace
101
+ uid = generate_uid()
102
+ study = upload(client, [dicom(uid), dicom(uid)]).json()['studies'][0]
103
+ job = client.post(f"/api/studies/{study['id']}/classify").json()
104
+ classification = wait(client, job)
105
+ assert classification['status'] == 'completed'
106
+ assert [p['artery'] for p in classification['result']['study']['projections']] == ['left', 'right']
107
+ job = client.post(f"/api/studies/{study['id']}/run", json={}).json()
108
+ result = wait(client, job)
109
+ assert result['result']['calibrated'] == 10.
110
+ assert client.delete('/api/studies/' + study['id']).status_code == 200
111
+ assert client.get('/api/studies/' + study['id']).status_code == 404
112
+ assert client.get('/api/jobs/' + job['id']).status_code == 404
113
+ assert not any(app.state.store.root.iterdir())
114
+
115
+
116
+ def test_preserves_user_order_and_validates_complete_assignment(workspace):
117
+ client, _, engine = workspace
118
+ uid = generate_uid()
119
+ study = upload(client, [dicom(uid), dicom(uid), dicom(uid)]).json()['studies'][0]
120
+ ids = [p['id'] for p in study['projections']]
121
+ path = f"/api/studies/{study['id']}/run"
122
+ assert client.post(path, json={'assignments': [{'id': ids[0], 'artery': 'left'}]}).status_code == 422
123
+ assert client.post(path, json={'assignments': [{'id': ids[0], 'artery': 'left'}] * 3}).status_code == 422
124
+ assignments = [{'id': ids[2], 'artery': 'left'}, {'id': ids[0], 'artery': 'left'}, {'id': ids[1], 'artery': 'right'}]
125
+ assert wait(client, client.post(path, json={'assignments': assignments}).json())['status'] == 'completed'
126
+ assert [Path(p).name for p in engine.calls[-1][0]] == [ids[2], ids[0]]
127
+
128
+
129
+ def test_short_and_unassigned_projections_cannot_be_scored(workspace):
130
+ client, _, _ = workspace
131
+ uid = generate_uid()
132
+ study = upload(client, [dicom(uid, frames=5), dicom(uid)]).json()['studies'][0]
133
+ assert study['projections'][0]['artery'] == 'exclude'
134
+ path = f"/api/studies/{study['id']}/run"
135
+ assert client.post(path, json={}).status_code == 422
136
+ assert client.post(path, json={'assignments': [{'id': p['id'], 'artery': 'left'} for p in study['projections']]}).status_code == 422
137
+
138
+
139
+ def test_missing_side_remains_partial_and_failure_has_no_score(workspace):
140
+ client, _, engine = workspace
141
+ study = upload(client, [dicom()]).json()['studies'][0]
142
+ body = {'assignments': [{'id': study['projections'][0]['id'], 'artery': 'left'}]}
143
+ path = f"/api/studies/{study['id']}/run"
144
+ result = wait(client, client.post(path, json=body).json())
145
+ assert result['result']['complete'] is False
146
+ assert result['result']['total']['calibrated'] is None
147
+ engine.fail = True
148
+ result = wait(client, client.post(path, json=body).json())
149
+ assert result['status'] == 'failed' and result['result'] is None
150
+ assert 'SECRET' not in result['error']
151
+
152
+
153
+ def test_unsafe_zip_and_unreadable_files_rejected(workspace):
154
+ client, app, _ = workspace
155
+ output = io.BytesIO()
156
+ with zipfile.ZipFile(output, 'w') as z:
157
+ z.writestr('../../escape.dcm', dicom())
158
+ response = client.post('/api/studies', files=[('files', ('bad.zip', output.getvalue(), 'application/zip'))])
159
+ assert response.status_code == 422
160
+ assert response.json()['studies'] == []
161
+ assert 'unsafe' in response.json()['rejected'][0]['reason']
162
+ assert not any(app.state.store.root.iterdir())
163
+ assert upload(client, [b'not DICOM']).status_code == 422
164
+
165
+
166
+ def test_safe_zip_and_size_limit(workspace, tmp_path):
167
+ client, _, _ = workspace
168
+ output = io.BytesIO()
169
+ with zipfile.ZipFile(output, 'w') as z:
170
+ z.writestr('study/image.dcm', dicom())
171
+ response = client.post('/api/studies', files=[('files', ('study.zip', output.getvalue(), 'application/zip'))])
172
+ assert response.status_code == 200
173
+ app = create_app(data_root=tmp_path / 'limited', engine=FakeEngine(), limits=Limits(max_request_bytes=10))
174
+ with TestClient(app) as limited:
175
+ assert limited.post('/api/studies', content=b'x' * 11).status_code == 413
176
+
177
+
178
+ def test_expiry_and_unknown_ids(workspace):
179
+ client, app, _ = workspace
180
+ study = upload(client, [dicom()]).json()['studies'][0]
181
+ app.state.store.studies[study['id']].touched_at = 0
182
+ app.state.store.cleanup()
183
+ assert client.get('/api/studies/' + study['id']).status_code == 404
184
+ assert client.get('/api/jobs/not-a-capability').status_code == 404
185
+ assert client.get('/api/status').json()['model']['loaded'] == 0
186
+
187
+
188
+ def test_animated_preview_and_fixed_example_loading(workspace, tmp_path, monkeypatch):
189
+ import json
190
+ import huggingface_hub
191
+ client, _, engine = workspace
192
+ examples = json.loads((Path(__file__).parents[1] / 'service' / 'examples.json').read_text())
193
+ example = examples[0]
194
+ paths = {}
195
+ for entry in example['files']:
196
+ path = tmp_path / entry['sop_uid']
197
+ path.write_bytes(dicom(example['study_uid'], entry['sop_uid']))
198
+ paths[entry['path']] = str(path)
199
+ def fake_download(**kwargs):
200
+ assert kwargs['revision'] == example['revision']
201
+ assert kwargs['repo_id'] == example['repository']
202
+ return paths[kwargs['filename']]
203
+ monkeypatch.setattr(huggingface_hub, 'hf_hub_download', fake_download)
204
+ assert client.get('/api/examples').json()['examples'][0]['id'] == example['id']
205
+ assert client.post('/api/examples/arbitrary-url/load').status_code == 404
206
+ job = client.post('/api/examples/' + example['id'] + '/load').json()
207
+ result = wait(client, job)
208
+ assert result['status'] == 'completed'
209
+ study = result['result']['studies'][0]
210
+ assert [p['artery'] for p in study['projections']] == [f['artery'] for f in example['files']]
211
+ gif = client.get(study['projections'][0]['animation_url'])
212
+ assert gif.status_code == 200 and gif.content.startswith(b'GIF')
213
+ assert engine.calls == []
214
+
215
+
216
+ def test_disk_capacity_is_enforced(tmp_path):
217
+ payload = dicom()
218
+ app = create_app(data_root=tmp_path / 'quota', engine=FakeEngine(),
219
+ limits=Limits(max_stored_bytes=len(payload)))
220
+ with TestClient(app) as client:
221
+ assert upload(client, [payload]).status_code == 200
222
+ assert upload(client, [dicom()]).status_code == 507
223
+ assert len(app.state.store.studies) == 1
224
+
225
+
226
+ def test_full_video_keeps_every_frame_and_supports_seeking(workspace):
227
+ import json
228
+ import shutil
229
+ import subprocess
230
+ if not shutil.which('ffmpeg') or not shutil.which('ffprobe'):
231
+ pytest.skip('Local FFmpeg is required for complete cine preview test')
232
+ client, app, _ = workspace
233
+ study = upload(client, [dicom(frames=60)]).json()['studies'][0]
234
+ url = study['projections'][0]['video_url']
235
+ video = client.get(url)
236
+ assert video.status_code == 200 and video.headers['content-type'] == 'video/mp4'
237
+ stored = app.state.store.studies[study['id']]
238
+ path = stored.directory / (study['projections'][0]['id'] + '.mp4')
239
+ info = subprocess.run(['ffprobe', '-v', 'error', '-show_entries', 'stream=nb_frames,width,height',
240
+ '-of', 'json', str(path)], check=True, capture_output=True)
241
+ assert int(json.loads(info.stdout)['streams'][0]['nb_frames']) == 60
242
+ mtime = path.stat().st_mtime_ns
243
+ part = client.get(url, headers={'Range': 'bytes=0-99'})
244
+ assert part.status_code == 206 and len(part.content) == 100
245
+ assert path.stat().st_mtime_ns == mtime
246
+ assert stored.readers == 0
247
+ assert not app.state.store.workspaces
248
+ assert client.delete('/api/studies/' + study['id']).status_code == 200
249
+ assert not path.exists()
250
+
251
+
252
+ def test_expansion_limit_is_shared_between_archives(tmp_path):
253
+ payload1, payload2 = dicom(), dicom()
254
+ archives = []
255
+ for index, payload in enumerate((payload1, payload2)):
256
+ stream = io.BytesIO()
257
+ with zipfile.ZipFile(stream, 'w', compression=zipfile.ZIP_DEFLATED) as z:
258
+ z.writestr('image.dcm', payload)
259
+ archives.append(('files', (f'{index}.zip', stream.getvalue(), 'application/zip')))
260
+ app = create_app(data_root=tmp_path / 'data', engine=FakeEngine(),
261
+ limits=Limits(max_request_bytes=len(payload1) + 100))
262
+ with TestClient(app) as client:
263
+ response = client.post('/api/studies', files=archives)
264
+ assert response.status_code == 200
265
+ assert len(response.json()['studies']) == 1
266
+ assert len(response.json()['rejected']) == 1
267
+ assert 'uncompressed size limit' in response.json()['rejected'][0]['reason']
268
+ assert not app.state.store.workspaces
269
+
270
+
271
+ def test_active_workspace_and_preview_are_not_expired(workspace):
272
+ import os
273
+ client, app, _ = workspace
274
+ store = app.state.store
275
+ study = upload(client, [dicom()]).json()['studies'][0]
276
+ held = store.acquire(study['id'])
277
+ held.touched_at = 0
278
+ staging = store.workspace('incoming-')
279
+ os.utime(staging, (0, 0))
280
+ store.cleanup()
281
+ assert staging.exists() and held.directory.exists()
282
+ assert client.delete('/api/studies/' + study['id']).status_code == 409
283
+ store.release(held)
284
+ held.touched_at = 0
285
+ assert client.get('/api/studies/' + study['id']).status_code == 404
286
+ store.remove_workspace(staging)
287
+
288
+
289
+ def test_streamed_body_without_content_length_is_bounded(tmp_path):
290
+ app = create_app(data_root=tmp_path / 'data', engine=FakeEngine(), limits=Limits(max_request_bytes=100))
291
+ with TestClient(app) as client:
292
+ response = client.post('/api/studies', content=iter([b'--xxx\r\n', b'a' * 101]),
293
+ headers={'Content-Type': 'multipart/form-data; boundary=xxx'})
294
+ assert response.status_code == 413
295
+
296
+
297
+ def test_concurrent_upload_is_bounded_before_parsing(workspace, monkeypatch):
298
+ import threading
299
+ from concurrent.futures import ThreadPoolExecutor
300
+ import service.api as api
301
+ client, _, _ = workspace
302
+ entered, release = threading.Event(), threading.Event()
303
+ original = api.inspect_dicom
304
+ def slow_inspect(*args, **kwargs):
305
+ entered.set()
306
+ assert release.wait(2)
307
+ return original(*args, **kwargs)
308
+ monkeypatch.setattr(api, 'inspect_dicom', slow_inspect)
309
+ with ThreadPoolExecutor(max_workers=1) as pool:
310
+ first = pool.submit(upload, client, [dicom()])
311
+ assert entered.wait(2)
312
+ try:
313
+ assert upload(client, [dicom()]).status_code == 429
314
+ finally:
315
+ release.set()
316
+ assert first.result().status_code == 200
317
+
318
+
319
+ def test_queue_and_active_study_deletion_are_bounded(tmp_path):
320
+ import threading
321
+ engine = FakeEngine()
322
+ entered, release = threading.Event(), threading.Event()
323
+ original = engine.classify
324
+ def delayed(paths, progress):
325
+ entered.set()
326
+ assert release.wait(2)
327
+ return original(paths, progress)
328
+ engine.classify = delayed
329
+ app = create_app(data_root=tmp_path / 'data', engine=engine, limits=Limits(max_pending_jobs=1))
330
+ with TestClient(app) as client:
331
+ studies = upload(client, [dicom(), dicom()]).json()['studies']
332
+ job = client.post('/api/studies/' + studies[0]['id'] + '/classify').json()
333
+ assert entered.wait(2)
334
+ try:
335
+ assert client.post('/api/studies/' + studies[1]['id'] + '/classify').status_code == 429
336
+ assert client.delete('/api/studies/' + studies[0]['id']).status_code == 409
337
+ finally:
338
+ release.set()
339
+ assert wait(client, job)['status'] == 'completed'