MesserMMP commited on
Commit
2ab01da
·
verified ·
1 Parent(s): 1024e04

Refine workspace and add verified full-cine cached examples

Browse files

Polish Light/Dark themes and bilingual cine controls. Add two selected public Philips studies with all 15 projections, full video sequences, expert references and verified GPU predictions. Open examples immediately from bundled media; verify and fetch source DICOM only for a new calculation. Preserve canonical inference and hosting hardware.

Files changed (43) hide show
  1. .gitattributes +30 -0
  2. README.md +5 -3
  3. service/api.py +137 -10
  4. service/example_cache.py +150 -0
  5. service/example_results/philips-positive.json +259 -0
  6. service/example_results/philips-zero.json +248 -0
  7. service/examples.json +239 -50
  8. service/storage.py +26 -3
  9. static/app.js +38 -19
  10. static/examples/philips-positive/01.mp4 +3 -0
  11. static/examples/philips-positive/01.png +3 -0
  12. static/examples/philips-positive/02.mp4 +3 -0
  13. static/examples/philips-positive/02.png +3 -0
  14. static/examples/philips-positive/03.mp4 +3 -0
  15. static/examples/philips-positive/03.png +3 -0
  16. static/examples/philips-positive/04.mp4 +3 -0
  17. static/examples/philips-positive/04.png +3 -0
  18. static/examples/philips-positive/05.mp4 +3 -0
  19. static/examples/philips-positive/05.png +3 -0
  20. static/examples/philips-positive/06.mp4 +3 -0
  21. static/examples/philips-positive/06.png +3 -0
  22. static/examples/philips-positive/07.mp4 +3 -0
  23. static/examples/philips-positive/07.png +3 -0
  24. static/examples/philips-positive/08.mp4 +3 -0
  25. static/examples/philips-positive/08.png +3 -0
  26. static/examples/philips-zero/01.mp4 +3 -0
  27. static/examples/philips-zero/01.png +3 -0
  28. static/examples/philips-zero/02.mp4 +3 -0
  29. static/examples/philips-zero/02.png +3 -0
  30. static/examples/philips-zero/03.mp4 +3 -0
  31. static/examples/philips-zero/03.png +3 -0
  32. static/examples/philips-zero/04.mp4 +3 -0
  33. static/examples/philips-zero/04.png +3 -0
  34. static/examples/philips-zero/05.mp4 +3 -0
  35. static/examples/philips-zero/05.png +3 -0
  36. static/examples/philips-zero/06.mp4 +3 -0
  37. static/examples/philips-zero/06.png +3 -0
  38. static/examples/philips-zero/07.mp4 +3 -0
  39. static/examples/philips-zero/07.png +3 -0
  40. static/index.html +20 -20
  41. static/workspace.css +33 -0
  42. tests/test_service.py +20 -12
  43. tests/test_service_cache.py +288 -0
.gitattributes CHANGED
@@ -33,3 +33,33 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ static/examples/philips-positive/01.mp4 filter=lfs diff=lfs merge=lfs -text
37
+ static/examples/philips-positive/01.png filter=lfs diff=lfs merge=lfs -text
38
+ static/examples/philips-positive/02.mp4 filter=lfs diff=lfs merge=lfs -text
39
+ static/examples/philips-positive/02.png filter=lfs diff=lfs merge=lfs -text
40
+ static/examples/philips-positive/03.mp4 filter=lfs diff=lfs merge=lfs -text
41
+ static/examples/philips-positive/03.png filter=lfs diff=lfs merge=lfs -text
42
+ static/examples/philips-positive/04.mp4 filter=lfs diff=lfs merge=lfs -text
43
+ static/examples/philips-positive/04.png filter=lfs diff=lfs merge=lfs -text
44
+ static/examples/philips-positive/05.mp4 filter=lfs diff=lfs merge=lfs -text
45
+ static/examples/philips-positive/05.png filter=lfs diff=lfs merge=lfs -text
46
+ static/examples/philips-positive/06.mp4 filter=lfs diff=lfs merge=lfs -text
47
+ static/examples/philips-positive/06.png filter=lfs diff=lfs merge=lfs -text
48
+ static/examples/philips-positive/07.mp4 filter=lfs diff=lfs merge=lfs -text
49
+ static/examples/philips-positive/07.png filter=lfs diff=lfs merge=lfs -text
50
+ static/examples/philips-positive/08.mp4 filter=lfs diff=lfs merge=lfs -text
51
+ static/examples/philips-positive/08.png filter=lfs diff=lfs merge=lfs -text
52
+ static/examples/philips-zero/01.mp4 filter=lfs diff=lfs merge=lfs -text
53
+ static/examples/philips-zero/01.png filter=lfs diff=lfs merge=lfs -text
54
+ static/examples/philips-zero/02.mp4 filter=lfs diff=lfs merge=lfs -text
55
+ static/examples/philips-zero/02.png filter=lfs diff=lfs merge=lfs -text
56
+ static/examples/philips-zero/03.mp4 filter=lfs diff=lfs merge=lfs -text
57
+ static/examples/philips-zero/03.png filter=lfs diff=lfs merge=lfs -text
58
+ static/examples/philips-zero/04.mp4 filter=lfs diff=lfs merge=lfs -text
59
+ static/examples/philips-zero/04.png filter=lfs diff=lfs merge=lfs -text
60
+ static/examples/philips-zero/05.mp4 filter=lfs diff=lfs merge=lfs -text
61
+ static/examples/philips-zero/05.png filter=lfs diff=lfs merge=lfs -text
62
+ static/examples/philips-zero/06.mp4 filter=lfs diff=lfs merge=lfs -text
63
+ static/examples/philips-zero/06.png filter=lfs diff=lfs merge=lfs -text
64
+ static/examples/philips-zero/07.mp4 filter=lfs diff=lfs merge=lfs -text
65
+ static/examples/philips-zero/07.png filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -18,17 +18,19 @@ tags:
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.
@@ -63,7 +65,7 @@ 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
 
 
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 curated public 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. Open a public example with full cine previews and a precomputed result, or upload de-identified DICOM files or a ZIP archive. Uploaded 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 two selected Philips holdout studies have reference SYNTAX scores of 0.00 and 35.17. The reference is the published six-expert mean. Their saved predictions were calculated with the pinned ensemble on a GPU; they are explicitly marked **Precomputed**. All projections and frames are included. Opening an example uses bundled videos and does not load model weights. **Identify arteries** or **Recalculate SYNTAX** downloads and verifies the source DICOM before running the model. Changing assignments or projection order clears the displayed result. These selected examples illustrate the workflow; aggregate performance is reported in the model card.
33
+
34
  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.
35
 
36
  This application is intended for research, not clinical decision-making. An artery classifier suggestion is not a SYNTAX confidence estimate.
 
65
  uvicorn app:app --host 127.0.0.1 --port 7860 --workers 1 --no-access-log
66
  ```
67
 
68
+ Open `http://127.0.0.1:7860`. The first inference needs network access to download approximately 1.5 GB of model files. The bundled examples open without model downloads. Their source DICOM files are fetched only for classification or recalculation. No Hugging Face token is required.
69
 
70
  For the CPU Docker image used by this Space:
71
 
service/api.py CHANGED
@@ -5,6 +5,8 @@ import importlib
5
  import json
6
  import os
7
  import secrets
 
 
8
  import shutil
9
  import tempfile
10
  import threading
@@ -19,6 +21,7 @@ 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
 
@@ -122,9 +125,75 @@ class Jobs:
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:
@@ -159,7 +228,11 @@ class Jobs:
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 = {}
@@ -168,11 +241,17 @@ class Jobs:
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:
@@ -201,6 +280,7 @@ class Jobs:
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:
@@ -224,13 +304,14 @@ class Jobs:
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:
@@ -283,22 +364,68 @@ def create_app(*, data_root: Path | None = None, limits: Limits | None = None, e
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
@@ -331,12 +458,13 @@ def create_app(*, data_root: Path | None = None, limits: Limits | None = None, e
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)
@@ -533,7 +661,6 @@ def create_app(*, data_root: Path | None = None, limits: Limits | None = None, e
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
 
 
5
  import json
6
  import os
7
  import secrets
8
+
9
+ import pydicom
10
  import shutil
11
  import tempfile
12
  import threading
 
21
  from fastapi.staticfiles import StaticFiles
22
  from pydantic import BaseModel, Field
23
 
24
+ from .example_cache import read_cache, verify_download, virtual_projections, sha256_file
25
  from .media import cached_video
26
  from .storage import InputError, Limits, Store, expand_zip, inspect_dicom, poster, animation
27
 
 
125
  'result': None, 'error': None, 'created_at': time.time(), 'updated_at': time.time()}
126
  self.items[job_id] = job
127
  study.active_job = job_id
128
+ study.cached_result_job_id = None
129
  self.executor.submit(self._execute, job_id)
130
  return dict(job)
131
 
132
+ def add_cached(self, study, result):
133
+ with self.store.lock, self.lock:
134
+ job_id = secrets.token_urlsafe(32)
135
+ job = {'id': job_id, 'study_id': study.id, 'kind': 'inference', 'status': 'completed',
136
+ 'progress': 1., 'message': 'Verified precomputed example result.', 'result': result,
137
+ 'error': None, 'created_at': time.time(), 'updated_at': time.time()}
138
+ self.items[job_id] = job
139
+ study.cached_result_job_id = job_id
140
+ return dict(job)
141
+
142
+ def completed_example(self, result=None, error=None):
143
+ with self.lock:
144
+ job_id = secrets.token_urlsafe(32)
145
+ job = {'id': job_id, 'study_id': None, 'kind': 'example',
146
+ 'status': 'failed' if error else 'completed', 'progress': 0. if error else 1.,
147
+ 'message': error or 'Example ready.', 'result': result, 'error': error,
148
+ 'created_at': time.time(), 'updated_at': time.time()}
149
+ self.items[job_id] = job
150
+ return dict(job)
151
+
152
+ def _hydrate(self, study, progress):
153
+ missing = [p for p in study.projections if not p.path.is_file()]
154
+ if not missing:
155
+ return
156
+ from huggingface_hub import hf_hub_download
157
+ staging = self.store.workspace('hydrate-')
158
+ ready = []
159
+ total = 0
160
+ try:
161
+ for index, projection in enumerate(missing):
162
+ source = projection.source
163
+ if not source:
164
+ raise InputError('A source DICOM is unavailable. Please upload the study again.')
165
+ progress('download', {'fraction': index / len(missing),
166
+ 'message': f'Downloading verified source DICOM {index + 1} of {len(missing)}.'})
167
+ try:
168
+ downloaded = Path(hf_hub_download(repo_id=source['repo_id'], repo_type='dataset',
169
+ revision=source['revision'], filename=source['path'], token=False))
170
+ except Exception as exc:
171
+ raise InputError('The verified source DICOM could not be downloaded. Please retry.') from exc
172
+ size = downloaded.stat().st_size
173
+ total += size
174
+ if size > self.store.limits.max_file_bytes or total > self.store.limits.max_request_bytes:
175
+ raise InputError('The source DICOM exceeds the study size limit.')
176
+ self.store.reserve(staging, size)
177
+ dest = staging / projection.id
178
+ shutil.copyfile(downloaded, dest)
179
+ if sha256_file(dest) != source['sha256']:
180
+ raise InputError('The source DICOM checksum did not match. No inference was run.')
181
+ uid, metadata = inspect_dicom(dest, projection.name, self.store.limits)
182
+ series = str(pydicom.dcmread(dest, stop_before_pixels=True, specific_tags=['SeriesInstanceUID']).get('SeriesInstanceUID', ''))
183
+ if (uid != study.study_uid or metadata.sop_uid != projection.sop_uid
184
+ or (metadata.frames, metadata.rows, metadata.columns) != (projection.frames, projection.rows, projection.columns)
185
+ or series != source['series_uid']):
186
+ raise InputError('The source DICOM identifiers or dimensions did not match. No inference was run.')
187
+ ready.append((projection, dest))
188
+ with self.store.lock:
189
+ self.store.capacity(total, 0, workspace=staging)
190
+ for projection, dest in ready:
191
+ dest.replace(projection.path)
192
+ progress('download', {'current': len(missing), 'total': len(missing),
193
+ 'message': 'Verified source DICOM ready.'})
194
+ finally:
195
+ self.store.remove_workspace(staging)
196
+
197
  def submit_example(self, loader):
198
  with self.lock:
199
  if self.pending() >= self.store.limits.max_pending_jobs:
 
228
  job = self.items[job_id]
229
  job.update(status='running', message='Preparing model input.', updated_at=time.time())
230
  study = self.store.get(job['study_id'])
231
+ hydration_units = sum(not p.path.is_file() for p in study.projections) if study else 0
232
+ engine_units = (sum(p.frames >= 10 for p in study.projections) if job['kind'] == 'classify'
233
+ else 5 * sum(p.artery in {'left', 'right'} for p in study.projections)) if study else 0
234
+ total_units = max(1, hydration_units + engine_units)
235
+ def report_progress(stage, detail=None, *, offset=0, units=0):
236
  detail = detail or {}
237
  if not isinstance(detail, dict):
238
  detail = {}
 
241
  fraction = detail.get('current', 0) / detail['total']
242
  with self.lock:
243
  if isinstance(fraction, (int, float)):
244
+ completed = offset + min(1., max(0., float(fraction))) * units
245
+ job['progress'] = max(job['progress'], min(.99, completed / total_units))
246
  job.update(message=detail.get('message', str(stage)), updated_at=time.time())
247
+ def hydration_progress(stage, detail=None):
248
+ report_progress(stage, detail, units=hydration_units)
249
+ def progress(stage, detail=None):
250
+ report_progress(stage, detail, offset=hydration_units, units=engine_units)
251
  try:
252
  if not study:
253
  raise InputError('The study has expired. Please upload it again.')
254
+ self._hydrate(study, hydration_progress)
255
  if job['kind'] == 'classify':
256
  eligible = [p for p in study.projections if p.frames >= 10]
257
  if not eligible:
 
280
  result['calibrated_score'] = result.get('calibrated')
281
  result['total'] = {'raw': result.get('raw'), 'calibrated': result.get('calibrated')}
282
  result['study_uid'] = study.study_uid
283
+ result['input_assignments'] = [{'id': p.id, 'artery': p.artery} for p in study.projections]
284
  result['input_counts'] = {'left': len(left), 'right': len(right),
285
  'excluded': sum(p.artery == 'exclude' for p in study.projections)}
286
  with self.lock:
 
304
  study.touched_at = time.time()
305
 
306
 
307
+ def create_app(*, data_root: Path | None = None, limits: Limits | None = None, engine=None, examples_path: Path | None = None, static_root: Path | None = None):
308
  limits = limits or Limits()
309
  root = data_root or Path(os.environ.get('SYNTAX_UPLOAD_DIR', Path(tempfile.gettempdir()) / 'cardiosyntax-uploads'))
310
  store = Store(root, limits)
311
  engine = engine or EngineAdapter()
312
  jobs = Jobs(store, engine)
313
  video_slot = threading.BoundedSemaphore(1)
314
+ static = static_root or Path(__file__).resolve().parents[1] / 'static'
315
 
316
  async def clean_periodically():
317
  while True:
 
364
  'retention_minutes': limits.ttl_seconds // 60})
365
  return info
366
 
367
+ examples_path = examples_path or Path(__file__).with_name('examples.json')
368
  examples = json.loads(examples_path.read_text()) if examples_path.exists() else []
369
 
370
  @app.get('/api/examples')
371
  def list_examples():
372
+ cards = []
373
+ for example in examples:
374
+ try:
375
+ cache = read_cache(example, base=examples_path.parent)
376
+ except InputError:
377
+ cache = None
378
+ cards.append({'id': example['id'], 'title': example.get('title', example.get('label', example['id'])),
379
+ 'description': example.get('description', 'A public annotated holdout study.'),
380
+ 'files': len(example['files']), 'reference_score': example.get('reference_score'),
381
+ 'vendor': example.get('vendor'),
382
+ 'cached_result_available': cache is not None,
383
+ 'prediction': {key: cache['result'][key] for key in ('raw', 'calibrated')} if cache else None})
384
+ return {'examples': cards}
385
+
386
+ def example_payload(example, created, cache):
387
+ example_id = example['id']
388
+ index = example.get('default_projection_index', 0)
389
+ if type(index) is not int or not 0 <= index < len(created.projections):
390
+ raise InputError('The example default projection index is invalid.')
391
+ created.default_projection_id = created.projections[index].id
392
+ created.reference_score = example.get('reference_score')
393
+ cached_job = None
394
+ if cache:
395
+ result = cache['result']
396
+ result.update(raw_score=result['raw'], calibrated_score=result['calibrated'],
397
+ total={'raw': result['raw'], 'calibrated': result['calibrated']},
398
+ input_assignments=[{'id': p.id, 'artery': p.artery} for p in created.projections],
399
+ input_counts={side: sum(p.artery == side for p in created.projections)
400
+ for side in ('left', 'right', 'exclude')},
401
+ source={'type': 'precomputed_example', 'example_id': example_id,
402
+ 'dataset': cache['dataset'], 'cache_sha256': cache['cache_sha256']})
403
+ result['input_counts']['excluded'] = result['input_counts'].pop('exclude')
404
+ created.source_type = 'precomputed_example'
405
+ cached_job = jobs.add_cached(created, result)
406
+ return {'studies': [created.public()], 'rejected': [], 'warnings': [],
407
+ 'example_id': example_id, 'cached_job': cached_job}
408
 
409
  @app.post('/api/examples/{example_id}/load')
410
  def load_example(example_id: str):
411
  example = next((x for x in examples if x['id'] == example_id), None)
412
  if example is None:
413
  raise HTTPException(404, 'Example not found.')
414
+ try:
415
+ cache = read_cache(example, base=examples_path.parent)
416
+ prepared = virtual_projections(example, cache, static)
417
+ if prepared:
418
+ created = store.add_virtual(example['study_uid'], prepared)
419
+ try:
420
+ return jobs.completed_example(example_payload(example, created, cache))
421
+ except Exception:
422
+ store.delete(created.id)
423
+ raise
424
+ except InputError as exc:
425
+ return jobs.completed_example(error=str(exc))
426
  def loader(progress):
427
  from huggingface_hub import hf_hub_download
428
+ cache = read_cache(example, base=examples_path.parent)
429
  staging = store.workspace('example-')
430
  projections = []
431
  created = None
 
458
  projection.artery = 'exclude' if projection.frames < 10 else item['artery']
459
  if projection.artery not in {'left', 'right', 'exclude'}:
460
  raise InputError('Invalid published artery assignment.')
461
+ if cache:
462
+ verify_download(cache, index, dest, projection)
463
  projections.append(projection)
464
  with store.lock:
465
  store.capacity(total, 1, workspace=staging)
466
  created = store.add(example['study_uid'], projections)
467
+ return example_payload(example, created, cache)
 
468
  except Exception:
469
  if created:
470
  store.delete(created.id)
 
661
  jobs.items = {key: item for key, item in jobs.items.items() if item['study_id'] != study_id}
662
  return {'deleted': True}
663
 
 
664
  if static.exists():
665
  app.mount('/static', StaticFiles(directory=static), name='static')
666
 
service/example_cache.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Validate immutable, precomputed example results without loading a model."""
2
+ from __future__ import annotations
3
+
4
+ import copy
5
+ import hashlib
6
+ import json
7
+ import math
8
+ import secrets
9
+
10
+ import pydicom
11
+ from pathlib import Path
12
+
13
+ from .storage import InputError, Projection
14
+
15
+
16
+ DATASET_REPOSITORY = 'MesserMMP/coronary-angiography-syntax'
17
+ SERVICE_DIRECTORY = Path(__file__).resolve().parent
18
+ MODEL_MANIFEST = SERVICE_DIRECTORY.parent / 'engine' / 'manifest.json'
19
+
20
+
21
+ def sha256_file(path: Path) -> str:
22
+ digest = hashlib.sha256()
23
+ with path.open('rb') as source:
24
+ for chunk in iter(lambda: source.read(1024 * 1024), b''):
25
+ digest.update(chunk)
26
+ return digest.hexdigest()
27
+
28
+
29
+ def _same_number(actual, expected):
30
+ return (type(actual) in (int, float) and math.isfinite(actual)
31
+ and math.isclose(actual, expected, rel_tol=1e-7, abs_tol=1e-6))
32
+
33
+
34
+ def _require(condition, message):
35
+ if not condition:
36
+ raise InputError('The precomputed example result could not be verified: ' + message)
37
+
38
+
39
+ def read_cache(example: dict, *, base: Path = SERVICE_DIRECTORY, model_manifest: Path = MODEL_MANIFEST):
40
+ """Absent optional cache is allowed. A configured but invalid cache fails closed."""
41
+ filename = example.get('cache_file')
42
+ if not filename:
43
+ return None
44
+ try:
45
+ relative = Path(filename)
46
+ root = (base / 'example_results').resolve()
47
+ path = (base / relative).resolve()
48
+ _require(not relative.is_absolute() and path.is_relative_to(root) and path.suffix == '.json', 'invalid cache path.')
49
+ _require(path.stat().st_size < 1024 * 1024, 'cache file is too large.')
50
+ payload = json.loads(path.read_text())
51
+ manifest = json.loads(model_manifest.read_text())
52
+ _require(payload.get('schema_version') == 1 and payload.get('example_id') == example['id'], 'example identity mismatch.')
53
+ dataset = {'repo_id': example.get('repository', DATASET_REPOSITORY),
54
+ 'revision': example.get('revision', example.get('dataset_revision'))}
55
+ _require(payload.get('dataset') == dataset, 'dataset revision mismatch.')
56
+ files = payload['files']
57
+ _require(len(files) == len(example['files']), 'file count mismatch.')
58
+ for recorded, expected in zip(files, example['files']):
59
+ _require(all(recorded.get(key) == expected.get(key) for key in ('path', 'sop_uid', 'artery')), 'ordered file manifest mismatch.')
60
+ digest = recorded.get('sha256', '')
61
+ _require(isinstance(digest, str) and len(digest) == 64 and all(c in '0123456789abcdef' for c in digest), 'invalid DICOM checksum.')
62
+ if expected.get('sha256'):
63
+ _require(digest == expected['sha256'], 'DICOM manifest checksum mismatch.')
64
+ result = payload['result']
65
+ _require(result.get('complete') is True and result.get('study_uid') == example['study_uid'], 'study identity or completeness mismatch.')
66
+ provenance = result['provenance']
67
+ _require(provenance.get('repo_id') == manifest['repo_id'] and provenance.get('revision') == manifest['revision'], 'model revision mismatch.')
68
+ expected_weights = [{'path': item['path'], 'sha256': item['sha256']} for item in manifest['score_weights']]
69
+ _require(provenance.get('weights') == expected_weights, 'model weight checksum mismatch.')
70
+ calibration = {key: manifest['calibration'][key] for key in ('path', 'sha256', 'folds')}
71
+ _require(provenance.get('calibration_source') == calibration, 'calibration checksum or coefficients mismatch.')
72
+ for side in ('left', 'right'):
73
+ expected_sops = [item['sop_uid'] for item in files if item['artery'] == side]
74
+ ordered = provenance['ordered_inputs'][side]
75
+ _require(expected_sops and [item['sop_uid'] for item in ordered] == expected_sops, 'ordered projection identifiers mismatch.')
76
+ _require(set(result[side]) == {'raw', 'per_fold', 'projections'}, 'unexpected artery result metadata.')
77
+ values = result[side]['per_fold']
78
+ _require(len(values) == 5 and all(type(v) in (int, float) and math.isfinite(v) for v in values), 'invalid per-fold artery scores.')
79
+ _require(_same_number(result[side]['raw'], sum(values) / 5), 'artery mean mismatch.')
80
+ _require(result[side]['projections'] == len(expected_sops), 'artery projection count mismatch.')
81
+ folds = result['per_fold']
82
+ _require(len(folds) == 5, 'the full five-fold ensemble is required.')
83
+ for index, (fold, coefficient) in enumerate(zip(folds, calibration['folds'])):
84
+ left, right = result['left']['per_fold'][index], result['right']['per_fold'][index]
85
+ _require(set(fold) == {'fold', 'left', 'right', 'raw', 'calibrated', 'a', 'b'}, 'unexpected fold metadata.')
86
+ expected = {'left': left, 'right': right, 'raw': left + right,
87
+ 'calibrated': coefficient['a'] * (left + right) + coefficient['b'], **coefficient}
88
+ _require(fold.get('fold') == index and all(_same_number(fold.get(key), value) for key, value in expected.items()), 'fold arithmetic mismatch.')
89
+ _require(_same_number(result['raw'], max(0., sum(fold['raw'] for fold in folds) / 5)), 'raw ensemble mismatch.')
90
+ _require(_same_number(result['calibrated'], max(0., sum(fold['calibrated'] for fold in folds) / 5)), 'calibrated ensemble mismatch.')
91
+ _require(result['projection_count'] == sum(item['artery'] in ('left', 'right') for item in files), 'input projection count mismatch.')
92
+ # The exported cache only carries engine results and public identifier provenance.
93
+ allowed_result = {'raw', 'calibrated', 'complete', 'study_uid', 'left', 'right', 'per_fold',
94
+ 'projection_count', 'provenance', 'message'}
95
+ allowed_provenance = {'repo_id', 'revision', 'architecture', 'precision', 'preprocessing',
96
+ 'projection_order', 'calibration', 'calibration_source', 'ordered_inputs', 'weights', 'device'}
97
+ _require(set(result) <= allowed_result and set(provenance) <= allowed_provenance, 'unexpected result metadata.')
98
+ for records in provenance['ordered_inputs'].values():
99
+ _require(all(set(record) <= {'sop_uid', 'series_uid', 'frames'} for record in records), 'unexpected input metadata.')
100
+ return {'result': copy.deepcopy(result), 'files': files, 'cache_sha256': sha256_file(path), 'dataset': dataset}
101
+ except InputError:
102
+ raise
103
+ except (OSError, ValueError, KeyError, TypeError, AttributeError) as exc:
104
+ raise InputError('The precomputed example result is unavailable or invalid. No cached score was used.') from exc
105
+
106
+
107
+ def verify_download(cache, index: int, path: Path, projection):
108
+ record = cache['files'][index]
109
+ _require(sha256_file(path) == record['sha256'], 'downloaded DICOM checksum mismatch.')
110
+ if record['artery'] in ('left', 'right'):
111
+ expected = next(x for x in cache['result']['provenance']['ordered_inputs'][record['artery']]
112
+ if x['sop_uid'] == projection.sop_uid)
113
+ _require(expected['frames'] == projection.frames, 'DICOM frame count mismatch.')
114
+ series = str(pydicom.dcmread(path, stop_before_pixels=True, specific_tags=['SeriesInstanceUID']).get('SeriesInstanceUID', ''))
115
+ _require(expected['series_uid'] == series, 'DICOM series identifier mismatch.')
116
+ _require(record['artery'] == projection.artery, 'DICOM eligibility or artery assignment mismatch.')
117
+
118
+
119
+ def virtual_projections(example, cache, static_root: Path):
120
+ """Packaged media creates a usable study without fetching source DICOM."""
121
+ if not cache or not any(item.get('preview') for item in example['files']):
122
+ return None
123
+ projections = []
124
+ for item, record in zip(example['files'], cache['files']):
125
+ preview = item.get('preview')
126
+ _require(isinstance(preview, dict), 'preview metadata is incomplete.')
127
+ urls = {}
128
+ for kind, suffix in (('video', '.mp4'), ('poster', '.png')):
129
+ relative = Path(preview.get(kind, ''))
130
+ path = (static_root / relative).resolve()
131
+ _require(not relative.is_absolute() and path.is_relative_to((static_root / 'examples').resolve())
132
+ and path.suffix == suffix, 'invalid packaged preview path.')
133
+ _require(path.is_file() and sha256_file(path) == preview.get(kind + '_sha256'), 'packaged preview checksum mismatch.')
134
+ urls[kind] = '/static/' + relative.as_posix()
135
+ frames, rows, columns = (preview.get(key) for key in ('frames', 'rows', 'columns'))
136
+ _require(all(type(value) is int and value > 0 for value in (frames, rows, columns)), 'invalid preview dimensions.')
137
+ _require(item['artery'] in ('left', 'right', 'exclude'), 'invalid preview artery assignment.')
138
+ _require(isinstance(preview.get('series_uid'), str) and bool(preview['series_uid']), 'missing preview series identifier.')
139
+ if item['artery'] in ('left', 'right'):
140
+ expected = next(x for x in cache['result']['provenance']['ordered_inputs'][item['artery']]
141
+ if x['sop_uid'] == item['sop_uid'])
142
+ _require(expected['frames'] == frames and expected['series_uid'] == preview.get('series_uid'),
143
+ 'packaged preview source metadata mismatch.')
144
+ _require(frames >= 10 or item['artery'] == 'exclude', 'short cine must remain excluded.')
145
+ source = {**cache['dataset'], 'path': item['path'], 'sha256': record['sha256'],
146
+ 'series_uid': preview.get('series_uid')}
147
+ projections.append(Projection(secrets.token_urlsafe(24), Path(), Path(item['path']).name,
148
+ frames, rows, columns, item['sop_uid'], artery=item['artery'],
149
+ source=source, static_preview=urls))
150
+ return projections
service/example_results/philips-positive.json ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": 1,
3
+ "example_id": "philips-positive",
4
+ "dataset": {
5
+ "repo_id": "MesserMMP/coronary-angiography-syntax",
6
+ "revision": "f5d6b5b4aa9856b12b8d65971beb8fce2f71e370"
7
+ },
8
+ "files": [
9
+ {
10
+ "path": "test_data/philips_97/1.3.46.670589.28.26690171363123020201002205159499515/IM-0004-0067.dcm",
11
+ "sop_uid": "1.3.46.670589.28.266901713631230202010070946267368032211512",
12
+ "artery": "left",
13
+ "sha256": "ab245fc1a216cdbba4b38fdbffe6996948476e0970da17429f87460b3554651d"
14
+ },
15
+ {
16
+ "path": "test_data/philips_97/1.3.46.670589.28.26690171363123020201002205159499515/IM-0002-0036.dcm",
17
+ "sop_uid": "1.3.46.670589.28.266901713631230202010070946266587912211512",
18
+ "artery": "left",
19
+ "sha256": "7483952482cbcf74d57639f47465882b31783ef3510c2d6a9be0951ec7d48860"
20
+ },
21
+ {
22
+ "path": "test_data/philips_97/1.3.46.670589.28.26690171363123020201002205159499515/IM-0006-0038.dcm",
23
+ "sop_uid": "1.3.46.670589.28.266901713631230202010070946267998152211512",
24
+ "artery": "left",
25
+ "sha256": "1b9ac97edef7b910e63f2d00a628c5953f83d3c4a268658b7175dfdbe83e016c"
26
+ },
27
+ {
28
+ "path": "test_data/philips_97/1.3.46.670589.28.26690171363123020201002205159499515/IM-0003-0036.dcm",
29
+ "sop_uid": "1.3.46.670589.28.266901713631230202010070946266897972211512",
30
+ "artery": "left",
31
+ "sha256": "b8f0ce75ab11e1b81de00de0484b5339c37aae49c74563e36279a651e3245e6c"
32
+ },
33
+ {
34
+ "path": "test_data/philips_97/1.3.46.670589.28.26690171363123020201002205159499515/IM-0005-0072.dcm",
35
+ "sop_uid": "1.3.46.670589.28.266901713631230202010070946267678092211512",
36
+ "artery": "left",
37
+ "sha256": "8af0fb2c7004a7348f56e4e4f1a98ea987337306f6f8b9bb1b8620a7d3c9f005"
38
+ },
39
+ {
40
+ "path": "test_data/philips_97/1.3.46.670589.28.26690171363123020201002205159499515/IM-0001-0046.dcm",
41
+ "sop_uid": "1.3.46.670589.28.266901713631230202010070946266277852211512",
42
+ "artery": "right",
43
+ "sha256": "46ffd2460e6c292ca2b3d1f031653a4f597135ef1e605e133b53f2b354b0af3c"
44
+ },
45
+ {
46
+ "path": "test_data/philips_97/1.3.46.670589.28.26690171363123020201002205159499515/IM-0007-0038.dcm",
47
+ "sop_uid": "1.3.46.670589.28.266901713631230202010070946268458212211512",
48
+ "artery": "left",
49
+ "sha256": "fe92841ff34d259510b1c1467dd9711ebaac69d1d20172b01dd95777c81d9532"
50
+ },
51
+ {
52
+ "path": "test_data/philips_97/1.3.46.670589.28.26690171363123020201002205159499515/IM-0008-0054.dcm",
53
+ "sop_uid": "1.3.46.670589.28.266901713631230202010070946268778272211512",
54
+ "artery": "left",
55
+ "sha256": "3f71d110dad0223f3fc5a5cb1bbbcf010cf13f7aad4f4efc172b70c482878811"
56
+ }
57
+ ],
58
+ "result": {
59
+ "raw": 25.511541259288787,
60
+ "calibrated": 35.91056801128387,
61
+ "per_fold": [
62
+ {
63
+ "fold": 0,
64
+ "left": 24.79285430908203,
65
+ "right": -0.05074620246887207,
66
+ "raw": 24.74210810661316,
67
+ "calibrated": 41.22447837591171,
68
+ "a": 1.65,
69
+ "b": 0.4
70
+ },
71
+ {
72
+ "fold": 1,
73
+ "left": 27.689054489135742,
74
+ "right": 0.01391756534576416,
75
+ "raw": 27.702972054481506,
76
+ "calibrated": 36.11683395028115,
77
+ "a": 1.29,
78
+ "b": 0.38
79
+ },
80
+ {
81
+ "fold": 2,
82
+ "left": 23.380096435546875,
83
+ "right": -0.07391375303268433,
84
+ "raw": 23.30618268251419,
85
+ "calibrated": 30.19691383361816,
86
+ "a": 1.28,
87
+ "b": 0.365
88
+ },
89
+ {
90
+ "fold": 3,
91
+ "left": 24.611312866210938,
92
+ "right": -0.21379274129867554,
93
+ "raw": 24.397520124912262,
94
+ "calibrated": 27.501247338652615,
95
+ "a": 1.11,
96
+ "b": 0.42
97
+ },
98
+ {
99
+ "fold": 4,
100
+ "left": 27.445209503173828,
101
+ "right": -0.03628617525100708,
102
+ "raw": 27.40892332792282,
103
+ "calibrated": 44.51336655795574,
104
+ "a": 1.61,
105
+ "b": 0.385
106
+ }
107
+ ],
108
+ "complete": true,
109
+ "study_uid": "1.3.46.670589.28.26690171363123020201002205159499515",
110
+ "left": {
111
+ "raw": 25.583705520629884,
112
+ "per_fold": [
113
+ 24.79285430908203,
114
+ 27.689054489135742,
115
+ 23.380096435546875,
116
+ 24.611312866210938,
117
+ 27.445209503173828
118
+ ],
119
+ "projections": 7
120
+ },
121
+ "right": {
122
+ "raw": -0.07216426134109497,
123
+ "per_fold": [
124
+ -0.05074620246887207,
125
+ 0.01391756534576416,
126
+ -0.07391375303268433,
127
+ -0.21379274129867554,
128
+ -0.03628617525100708
129
+ ],
130
+ "projections": 1
131
+ },
132
+ "projection_count": 8,
133
+ "provenance": {
134
+ "repo_id": "MesserMMP/coronary-syntax-prediction",
135
+ "revision": "f6099168eef127991e6cdbc420f24c0fc74d914c",
136
+ "architecture": "torchvision.r3d_18 + LSTM(512,128,proj_size=2), mean outputs",
137
+ "precision": "float32",
138
+ "preprocessing": "32 center frames; repeat short clips; RGB grayscale; 256x256; ImageNet normalization",
139
+ "projection_order": "input order within each artery",
140
+ "calibration": "max(0, mean_i(a_i * (left_i + right_i) + b_i))",
141
+ "calibration_source": {
142
+ "path": "scaling_coeffs/scaling_coeffs.json",
143
+ "sha256": "2d7fcea581914bccd5618b2534a67f85a2d559d70ecdb4861746f01497253427",
144
+ "folds": [
145
+ {
146
+ "a": 1.65,
147
+ "b": 0.4
148
+ },
149
+ {
150
+ "a": 1.29,
151
+ "b": 0.38
152
+ },
153
+ {
154
+ "a": 1.28,
155
+ "b": 0.365
156
+ },
157
+ {
158
+ "a": 1.11,
159
+ "b": 0.42
160
+ },
161
+ {
162
+ "a": 1.61,
163
+ "b": 0.385
164
+ }
165
+ ]
166
+ },
167
+ "ordered_inputs": {
168
+ "left": [
169
+ {
170
+ "sop_uid": "1.3.46.670589.28.266901713631230202010070946267368032211512",
171
+ "series_uid": "1.3.46.670589.28.26690171363123020201002210213759052.2.2",
172
+ "frames": 64
173
+ },
174
+ {
175
+ "sop_uid": "1.3.46.670589.28.266901713631230202010070946266587912211512",
176
+ "series_uid": "1.3.46.670589.28.26690171363123020201002210137460047.2.2",
177
+ "frames": 35
178
+ },
179
+ {
180
+ "sop_uid": "1.3.46.670589.28.266901713631230202010070946267998152211512",
181
+ "series_uid": "1.3.46.670589.28.26690171363123020201002210601739056.2.2",
182
+ "frames": 33
183
+ },
184
+ {
185
+ "sop_uid": "1.3.46.670589.28.266901713631230202010070946266897972211512",
186
+ "series_uid": "1.3.46.670589.28.26690171363123020201002210155305050.2.2",
187
+ "frames": 34
188
+ },
189
+ {
190
+ "sop_uid": "1.3.46.670589.28.266901713631230202010070946267678092211512",
191
+ "series_uid": "1.3.46.670589.28.26690171363123020201002210431483054.2.2",
192
+ "frames": 68
193
+ },
194
+ {
195
+ "sop_uid": "1.3.46.670589.28.266901713631230202010070946268458212211512",
196
+ "series_uid": "1.3.46.670589.28.26690171363123020201002210855973062.2.2",
197
+ "frames": 32
198
+ },
199
+ {
200
+ "sop_uid": "1.3.46.670589.28.266901713631230202010070946268778272211512",
201
+ "series_uid": "1.3.46.670589.28.26690171363123020201002210908251064.2.2",
202
+ "frames": 47
203
+ }
204
+ ],
205
+ "right": [
206
+ {
207
+ "sop_uid": "1.3.46.670589.28.266901713631230202010070946266277852211512",
208
+ "series_uid": "1.3.46.670589.28.26690171363123020201002210013318041.2.2",
209
+ "frames": 46
210
+ }
211
+ ]
212
+ },
213
+ "weights": [
214
+ {
215
+ "path": "full_model_weights/LeftBinSyntax_R3D_fold00_lstm_mean_post_best.safetensors",
216
+ "sha256": "d60de48ea47a3fbe516ca5d90ba79ec5d7dea5b04b037df20cf75e3a6f78ad66"
217
+ },
218
+ {
219
+ "path": "full_model_weights/LeftBinSyntax_R3D_fold01_lstm_mean_post_best.safetensors",
220
+ "sha256": "829b51322384437b6838fdc92ac5ca35c0d3de21e00d1ac95985e2ddb436f712"
221
+ },
222
+ {
223
+ "path": "full_model_weights/LeftBinSyntax_R3D_fold02_lstm_mean_post_best.safetensors",
224
+ "sha256": "79bfe68701be33d232037f8755b98729c48944f330b48fb6fa489d8151485221"
225
+ },
226
+ {
227
+ "path": "full_model_weights/LeftBinSyntax_R3D_fold03_lstm_mean_post_best.safetensors",
228
+ "sha256": "57f5cb930f30d42f16111dc8f66cbd419f6f11adb5bab601ccd8980b763daa93"
229
+ },
230
+ {
231
+ "path": "full_model_weights/LeftBinSyntax_R3D_fold04_lstm_mean_post_best.safetensors",
232
+ "sha256": "b8746300aa112d9077639664754e7c116d13c4ab88fa594eac7ffa1e35bd4dfe"
233
+ },
234
+ {
235
+ "path": "full_model_weights/RightBinSyntax_R3D_fold00_lstm_mean_post_best.safetensors",
236
+ "sha256": "b89a9368b9b040e7683b1590468d18d7c77cb44827749bc1ae7c95a7270eb696"
237
+ },
238
+ {
239
+ "path": "full_model_weights/RightBinSyntax_R3D_fold01_lstm_mean_post_best.safetensors",
240
+ "sha256": "ca2936688de41045cc1149364275d151c82d5da6d1aa9be123bed086fa3a48a3"
241
+ },
242
+ {
243
+ "path": "full_model_weights/RightBinSyntax_R3D_fold02_lstm_mean_post_best.safetensors",
244
+ "sha256": "804f8a7b1c1bfce0e290b83923f7f81e8043e44af19cef96e3b88af25ba5cec6"
245
+ },
246
+ {
247
+ "path": "full_model_weights/RightBinSyntax_R3D_fold03_lstm_mean_post_best.safetensors",
248
+ "sha256": "faf9994b09d27b4b48c7498bb2cbb4dde79636b4e766e6d6ee9f8ff61734ce1c"
249
+ },
250
+ {
251
+ "path": "full_model_weights/RightBinSyntax_R3D_fold04_lstm_mean_post_best.safetensors",
252
+ "sha256": "290a6dd922290fde6a4010146015404e4cdb748631bbb578bdbc0a94db025bda"
253
+ }
254
+ ],
255
+ "device": "cuda"
256
+ },
257
+ "message": null
258
+ }
259
+ }
service/example_results/philips-zero.json ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": 1,
3
+ "example_id": "philips-zero",
4
+ "dataset": {
5
+ "repo_id": "MesserMMP/coronary-angiography-syntax",
6
+ "revision": "f5d6b5b4aa9856b12b8d65971beb8fce2f71e370"
7
+ },
8
+ "files": [
9
+ {
10
+ "path": "test_data/philips_97/1.3.46.670589.28.26690171363123020220711060230180674/IM-0004-0044.dcm",
11
+ "sop_uid": "1.3.46.670589.28.266901713631230202207110612221246962211512",
12
+ "artery": "left",
13
+ "sha256": "c17ac712766b01e6283a9db9b4b1c20227ff71e4d59959bfc8446a31b844e961"
14
+ },
15
+ {
16
+ "path": "test_data/philips_97/1.3.46.670589.28.26690171363123020220711060230180674/IM-0002-0035.dcm",
17
+ "sop_uid": "1.3.46.670589.28.266901713631230202207110612220786842211512",
18
+ "artery": "right",
19
+ "sha256": "7f6079d83cbc2c9a120e75bb7b58e071daa81490da09af2631ac625799c5ad24"
20
+ },
21
+ {
22
+ "path": "test_data/philips_97/1.3.46.670589.28.26690171363123020220711060230180674/IM-0006-0040.dcm",
23
+ "sop_uid": "1.3.46.670589.28.266901713631230202207110612221877082211512",
24
+ "artery": "left",
25
+ "sha256": "fcd15f8e976b2adc93af1540bcb754fd67e248dfceac5cbd542cca1692a9c047"
26
+ },
27
+ {
28
+ "path": "test_data/philips_97/1.3.46.670589.28.26690171363123020220711060230180674/IM-0003-0035.dcm",
29
+ "sop_uid": "1.3.46.670589.28.266901713631230202207110612220936902211512",
30
+ "artery": "left",
31
+ "sha256": "a5c18da24d7620f2c06b31be3a58da3a80f7349938ed744dec334308c22de214"
32
+ },
33
+ {
34
+ "path": "test_data/philips_97/1.3.46.670589.28.26690171363123020220711060230180674/IM-0005-0042.dcm",
35
+ "sop_uid": "1.3.46.670589.28.266901713631230202207110612221567022211512",
36
+ "artery": "left",
37
+ "sha256": "087d7b25d0d16b87e0e9ec2666b19bfb0a0d55dc94c4d816bef0b46b7abd8753"
38
+ },
39
+ {
40
+ "path": "test_data/philips_97/1.3.46.670589.28.26690171363123020220711060230180674/IM-0001-0041.dcm",
41
+ "sop_uid": "1.3.46.670589.28.266901713631230202207110612220466782211512",
42
+ "artery": "right",
43
+ "sha256": "86144b72bf0dbeebd5bddfac29e9152e95f53bff221206a07d849b8fe5d7b170"
44
+ },
45
+ {
46
+ "path": "test_data/philips_97/1.3.46.670589.28.26690171363123020220711060230180674/IM-0007-0052.dcm",
47
+ "sop_uid": "1.3.46.670589.28.266901713631230202207110612222187142211512",
48
+ "artery": "left",
49
+ "sha256": "c1cd8c21ef396a8cad988087205f86c1caa49ef14c0042a129e72ef523901a3e"
50
+ }
51
+ ],
52
+ "result": {
53
+ "raw": 0.0,
54
+ "calibrated": 0.23774945414066315,
55
+ "per_fold": [
56
+ {
57
+ "fold": 0,
58
+ "left": -0.06528627872467041,
59
+ "right": -0.12990111112594604,
60
+ "raw": -0.19518738985061646,
61
+ "calibrated": 0.0779408067464829,
62
+ "a": 1.65,
63
+ "b": 0.4
64
+ },
65
+ {
66
+ "fold": 1,
67
+ "left": -0.06314408779144287,
68
+ "right": -0.06308174133300781,
69
+ "raw": -0.12622582912445068,
70
+ "calibrated": 0.2171686804294586,
71
+ "a": 1.29,
72
+ "b": 0.38
73
+ },
74
+ {
75
+ "fold": 2,
76
+ "left": 0.03350698947906494,
77
+ "right": 0.03245556354522705,
78
+ "raw": 0.06596255302429199,
79
+ "calibrated": 0.44943206787109374,
80
+ "a": 1.28,
81
+ "b": 0.365
82
+ },
83
+ {
84
+ "fold": 3,
85
+ "left": -0.11427980661392212,
86
+ "right": -0.15332776308059692,
87
+ "raw": -0.26760756969451904,
88
+ "calibrated": 0.12295559763908381,
89
+ "a": 1.11,
90
+ "b": 0.42
91
+ },
92
+ {
93
+ "fold": 4,
94
+ "left": -0.0009710192680358887,
95
+ "right": -0.03862518072128296,
96
+ "raw": -0.03959619998931885,
97
+ "calibrated": 0.32125011801719666,
98
+ "a": 1.61,
99
+ "b": 0.385
100
+ }
101
+ ],
102
+ "complete": true,
103
+ "study_uid": "1.3.46.670589.28.26690171363123020220711060230180674",
104
+ "left": {
105
+ "raw": -0.04203484058380127,
106
+ "per_fold": [
107
+ -0.06528627872467041,
108
+ -0.06314408779144287,
109
+ 0.03350698947906494,
110
+ -0.11427980661392212,
111
+ -0.0009710192680358887
112
+ ],
113
+ "projections": 5
114
+ },
115
+ "right": {
116
+ "raw": -0.07049604654312133,
117
+ "per_fold": [
118
+ -0.12990111112594604,
119
+ -0.06308174133300781,
120
+ 0.03245556354522705,
121
+ -0.15332776308059692,
122
+ -0.03862518072128296
123
+ ],
124
+ "projections": 2
125
+ },
126
+ "projection_count": 7,
127
+ "provenance": {
128
+ "repo_id": "MesserMMP/coronary-syntax-prediction",
129
+ "revision": "f6099168eef127991e6cdbc420f24c0fc74d914c",
130
+ "architecture": "torchvision.r3d_18 + LSTM(512,128,proj_size=2), mean outputs",
131
+ "precision": "float32",
132
+ "preprocessing": "32 center frames; repeat short clips; RGB grayscale; 256x256; ImageNet normalization",
133
+ "projection_order": "input order within each artery",
134
+ "calibration": "max(0, mean_i(a_i * (left_i + right_i) + b_i))",
135
+ "calibration_source": {
136
+ "path": "scaling_coeffs/scaling_coeffs.json",
137
+ "sha256": "2d7fcea581914bccd5618b2534a67f85a2d559d70ecdb4861746f01497253427",
138
+ "folds": [
139
+ {
140
+ "a": 1.65,
141
+ "b": 0.4
142
+ },
143
+ {
144
+ "a": 1.29,
145
+ "b": 0.38
146
+ },
147
+ {
148
+ "a": 1.28,
149
+ "b": 0.365
150
+ },
151
+ {
152
+ "a": 1.11,
153
+ "b": 0.42
154
+ },
155
+ {
156
+ "a": 1.61,
157
+ "b": 0.385
158
+ }
159
+ ]
160
+ },
161
+ "ordered_inputs": {
162
+ "left": [
163
+ {
164
+ "sop_uid": "1.3.46.670589.28.266901713631230202207110612221246962211512",
165
+ "series_uid": "1.3.46.670589.28.26690171363123020220711060918984094.2.2",
166
+ "frames": 41
167
+ },
168
+ {
169
+ "sop_uid": "1.3.46.670589.28.266901713631230202207110612221877082211512",
170
+ "series_uid": "1.3.46.670589.28.26690171363123020220711060947734098.2.2",
171
+ "frames": 35
172
+ },
173
+ {
174
+ "sop_uid": "1.3.46.670589.28.266901713631230202207110612220936902211512",
175
+ "series_uid": "1.3.46.670589.28.26690171363123020220711060905163092.2.2",
176
+ "frames": 33
177
+ },
178
+ {
179
+ "sop_uid": "1.3.46.670589.28.266901713631230202207110612221567022211512",
180
+ "series_uid": "1.3.46.670589.28.26690171363123020220711060935379096.2.2",
181
+ "frames": 38
182
+ },
183
+ {
184
+ "sop_uid": "1.3.46.670589.28.266901713631230202207110612222187142211512",
185
+ "series_uid": "1.3.46.670589.28.26690171363123020220711060959637100.2.2",
186
+ "frames": 46
187
+ }
188
+ ],
189
+ "right": [
190
+ {
191
+ "sop_uid": "1.3.46.670589.28.266901713631230202207110612220786842211512",
192
+ "series_uid": "1.3.46.670589.28.26690171363123020220711060802670087.2.2",
193
+ "frames": 34
194
+ },
195
+ {
196
+ "sop_uid": "1.3.46.670589.28.266901713631230202207110612220466782211512",
197
+ "series_uid": "1.3.46.670589.28.26690171363123020220711060752406085.2.2",
198
+ "frames": 41
199
+ }
200
+ ]
201
+ },
202
+ "weights": [
203
+ {
204
+ "path": "full_model_weights/LeftBinSyntax_R3D_fold00_lstm_mean_post_best.safetensors",
205
+ "sha256": "d60de48ea47a3fbe516ca5d90ba79ec5d7dea5b04b037df20cf75e3a6f78ad66"
206
+ },
207
+ {
208
+ "path": "full_model_weights/LeftBinSyntax_R3D_fold01_lstm_mean_post_best.safetensors",
209
+ "sha256": "829b51322384437b6838fdc92ac5ca35c0d3de21e00d1ac95985e2ddb436f712"
210
+ },
211
+ {
212
+ "path": "full_model_weights/LeftBinSyntax_R3D_fold02_lstm_mean_post_best.safetensors",
213
+ "sha256": "79bfe68701be33d232037f8755b98729c48944f330b48fb6fa489d8151485221"
214
+ },
215
+ {
216
+ "path": "full_model_weights/LeftBinSyntax_R3D_fold03_lstm_mean_post_best.safetensors",
217
+ "sha256": "57f5cb930f30d42f16111dc8f66cbd419f6f11adb5bab601ccd8980b763daa93"
218
+ },
219
+ {
220
+ "path": "full_model_weights/LeftBinSyntax_R3D_fold04_lstm_mean_post_best.safetensors",
221
+ "sha256": "b8746300aa112d9077639664754e7c116d13c4ab88fa594eac7ffa1e35bd4dfe"
222
+ },
223
+ {
224
+ "path": "full_model_weights/RightBinSyntax_R3D_fold00_lstm_mean_post_best.safetensors",
225
+ "sha256": "b89a9368b9b040e7683b1590468d18d7c77cb44827749bc1ae7c95a7270eb696"
226
+ },
227
+ {
228
+ "path": "full_model_weights/RightBinSyntax_R3D_fold01_lstm_mean_post_best.safetensors",
229
+ "sha256": "ca2936688de41045cc1149364275d151c82d5da6d1aa9be123bed086fa3a48a3"
230
+ },
231
+ {
232
+ "path": "full_model_weights/RightBinSyntax_R3D_fold02_lstm_mean_post_best.safetensors",
233
+ "sha256": "804f8a7b1c1bfce0e290b83923f7f81e8043e44af19cef96e3b88af25ba5cec6"
234
+ },
235
+ {
236
+ "path": "full_model_weights/RightBinSyntax_R3D_fold03_lstm_mean_post_best.safetensors",
237
+ "sha256": "faf9994b09d27b4b48c7498bb2cbb4dde79636b4e766e6d6ee9f8ff61734ce1c"
238
+ },
239
+ {
240
+ "path": "full_model_weights/RightBinSyntax_R3D_fold04_lstm_mean_post_best.safetensors",
241
+ "sha256": "290a6dd922290fde6a4010146015404e4cdb748631bbb578bdbc0a94db025bda"
242
+ }
243
+ ],
244
+ "device": "cuda"
245
+ },
246
+ "message": null
247
+ }
248
+ }
service/examples.json CHANGED
@@ -1,81 +1,270 @@
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
- ]
 
1
  [
2
  {
3
+ "id": "philips-zero",
4
+ "vendor": "Philips",
5
+ "title": "Philips",
6
+ "reference_score": 0.0,
7
+ "repository": "MesserMMP/coronary-angiography-syntax",
8
+ "revision": "f5d6b5b4aa9856b12b8d65971beb8fce2f71e370",
9
  "dataset_revision": "f5d6b5b4aa9856b12b8d65971beb8fce2f71e370",
10
+ "study_uid": "1.3.46.670589.28.26690171363123020220711060230180674",
11
+ "default_projection_index": 0,
12
+ "cache_file": "example_results/philips-zero.json",
13
  "files": [
14
  {
15
+ "path": "test_data/philips_97/1.3.46.670589.28.26690171363123020220711060230180674/IM-0004-0044.dcm",
16
+ "sop_uid": "1.3.46.670589.28.266901713631230202207110612221246962211512",
17
+ "artery": "left",
18
+ "sha256": "c17ac712766b01e6283a9db9b4b1c20227ff71e4d59959bfc8446a31b844e961",
19
+ "preview": {
20
+ "frames": 41,
21
+ "rows": 512,
22
+ "columns": 512,
23
+ "series_uid": "1.3.46.670589.28.26690171363123020220711060918984094.2.2",
24
+ "video": "examples/philips-zero/01.mp4",
25
+ "video_sha256": "d52aa5f3a84f228cdffe8424b26f502a1375823f1e55ceff046e43d3005db18b",
26
+ "poster": "examples/philips-zero/01.png",
27
+ "poster_sha256": "f98345dcfb8400e6fcb9657a7026220f23813f503c3adcf15aabc33f6d8c5949"
28
+ }
29
+ },
30
+ {
31
+ "path": "test_data/philips_97/1.3.46.670589.28.26690171363123020220711060230180674/IM-0002-0035.dcm",
32
+ "sop_uid": "1.3.46.670589.28.266901713631230202207110612220786842211512",
33
+ "artery": "right",
34
+ "sha256": "7f6079d83cbc2c9a120e75bb7b58e071daa81490da09af2631ac625799c5ad24",
35
+ "preview": {
36
+ "frames": 34,
37
+ "rows": 512,
38
+ "columns": 512,
39
+ "series_uid": "1.3.46.670589.28.26690171363123020220711060802670087.2.2",
40
+ "video": "examples/philips-zero/02.mp4",
41
+ "video_sha256": "88905a2e1365db759dd8c5398ddfe0572e01b7897a70714ececad4efb2097126",
42
+ "poster": "examples/philips-zero/02.png",
43
+ "poster_sha256": "a675aa9fff347c10db28bb29b7fd009e783be007438bcffd648914c40a90c0fb"
44
+ }
45
  },
46
  {
47
+ "path": "test_data/philips_97/1.3.46.670589.28.26690171363123020220711060230180674/IM-0006-0040.dcm",
48
+ "sop_uid": "1.3.46.670589.28.266901713631230202207110612221877082211512",
49
+ "artery": "left",
50
+ "sha256": "fcd15f8e976b2adc93af1540bcb754fd67e248dfceac5cbd542cca1692a9c047",
51
+ "preview": {
52
+ "frames": 35,
53
+ "rows": 512,
54
+ "columns": 512,
55
+ "series_uid": "1.3.46.670589.28.26690171363123020220711060947734098.2.2",
56
+ "video": "examples/philips-zero/03.mp4",
57
+ "video_sha256": "ca52f560c1a70438b5d2842d715f858feee8425d603210c22cebd35e4ca34d26",
58
+ "poster": "examples/philips-zero/03.png",
59
+ "poster_sha256": "765a4deae34977cd72e38c4276c48dd2806cf7af35a4bafa0c7ff7dbe92f9966"
60
+ }
61
  },
62
  {
63
+ "path": "test_data/philips_97/1.3.46.670589.28.26690171363123020220711060230180674/IM-0003-0035.dcm",
64
+ "sop_uid": "1.3.46.670589.28.266901713631230202207110612220936902211512",
65
+ "artery": "left",
66
+ "sha256": "a5c18da24d7620f2c06b31be3a58da3a80f7349938ed744dec334308c22de214",
67
+ "preview": {
68
+ "frames": 33,
69
+ "rows": 512,
70
+ "columns": 512,
71
+ "series_uid": "1.3.46.670589.28.26690171363123020220711060905163092.2.2",
72
+ "video": "examples/philips-zero/04.mp4",
73
+ "video_sha256": "2d899ce3ae9a1cfc5c6ca57434b6b18e13080ea56bbfc1b62056121f48be2cf3",
74
+ "poster": "examples/philips-zero/04.png",
75
+ "poster_sha256": "d417519fe7cabe00a35f39adea4566ff15aeb290a9d65348ac6125e9f1bd4bfc"
76
+ }
77
  },
78
  {
79
+ "path": "test_data/philips_97/1.3.46.670589.28.26690171363123020220711060230180674/IM-0005-0042.dcm",
80
+ "sop_uid": "1.3.46.670589.28.266901713631230202207110612221567022211512",
81
+ "artery": "left",
82
+ "sha256": "087d7b25d0d16b87e0e9ec2666b19bfb0a0d55dc94c4d816bef0b46b7abd8753",
83
+ "preview": {
84
+ "frames": 38,
85
+ "rows": 512,
86
+ "columns": 512,
87
+ "series_uid": "1.3.46.670589.28.26690171363123020220711060935379096.2.2",
88
+ "video": "examples/philips-zero/05.mp4",
89
+ "video_sha256": "8c0bf747399f49f840463ba6d5e52147c1e15f23bfdaae079ceeb62b1e5c5de0",
90
+ "poster": "examples/philips-zero/05.png",
91
+ "poster_sha256": "9e57610b64465ee4c801c4548c407ddf676d13cfecd3d3b6bcf2688d0285c581"
92
+ }
93
  },
94
  {
95
+ "path": "test_data/philips_97/1.3.46.670589.28.26690171363123020220711060230180674/IM-0001-0041.dcm",
96
+ "sop_uid": "1.3.46.670589.28.266901713631230202207110612220466782211512",
97
+ "artery": "right",
98
+ "sha256": "86144b72bf0dbeebd5bddfac29e9152e95f53bff221206a07d849b8fe5d7b170",
99
+ "preview": {
100
+ "frames": 41,
101
+ "rows": 512,
102
+ "columns": 512,
103
+ "series_uid": "1.3.46.670589.28.26690171363123020220711060752406085.2.2",
104
+ "video": "examples/philips-zero/06.mp4",
105
+ "video_sha256": "0945c2df0d8f6b68232b5add24771ccfb1d6157afda10fb374a033cc2289f473",
106
+ "poster": "examples/philips-zero/06.png",
107
+ "poster_sha256": "1b9c5fd9a917e536ad9ddf475d7df22b3d3fb79304e24d5042200ff3000f00ca"
108
+ }
109
+ },
110
+ {
111
+ "path": "test_data/philips_97/1.3.46.670589.28.26690171363123020220711060230180674/IM-0007-0052.dcm",
112
+ "sop_uid": "1.3.46.670589.28.266901713631230202207110612222187142211512",
113
+ "artery": "left",
114
+ "sha256": "c1cd8c21ef396a8cad988087205f86c1caa49ef14c0042a129e72ef523901a3e",
115
+ "preview": {
116
+ "frames": 46,
117
+ "rows": 512,
118
+ "columns": 512,
119
+ "series_uid": "1.3.46.670589.28.26690171363123020220711060959637100.2.2",
120
+ "video": "examples/philips-zero/07.mp4",
121
+ "video_sha256": "b4982940b55435b811c4587c48a7c11c0d816cc56f7bf7955694121dc99451a0",
122
+ "poster": "examples/philips-zero/07.png",
123
+ "poster_sha256": "69017794bca8642fdeec19b305beea806badaf09d3e050250e481197d5ed9426"
124
+ }
125
  }
126
+ ]
 
 
 
 
127
  },
128
  {
129
+ "id": "philips-positive",
130
+ "vendor": "Philips",
131
+ "title": "Philips",
132
+ "reference_score": 35.17,
133
+ "repository": "MesserMMP/coronary-angiography-syntax",
134
+ "revision": "f5d6b5b4aa9856b12b8d65971beb8fce2f71e370",
135
  "dataset_revision": "f5d6b5b4aa9856b12b8d65971beb8fce2f71e370",
136
+ "study_uid": "1.3.46.670589.28.26690171363123020201002205159499515",
137
+ "default_projection_index": 0,
138
+ "cache_file": "example_results/philips-positive.json",
139
  "files": [
140
  {
141
+ "path": "test_data/philips_97/1.3.46.670589.28.26690171363123020201002205159499515/IM-0004-0067.dcm",
142
+ "sop_uid": "1.3.46.670589.28.266901713631230202010070946267368032211512",
143
+ "artery": "left",
144
+ "sha256": "ab245fc1a216cdbba4b38fdbffe6996948476e0970da17429f87460b3554651d",
145
+ "preview": {
146
+ "frames": 64,
147
+ "rows": 512,
148
+ "columns": 512,
149
+ "series_uid": "1.3.46.670589.28.26690171363123020201002210213759052.2.2",
150
+ "video": "examples/philips-positive/01.mp4",
151
+ "video_sha256": "aea9f607f889bb87dced82380b02a78d97a20a78edbc50b5944dbf8f870a8c4b",
152
+ "poster": "examples/philips-positive/01.png",
153
+ "poster_sha256": "d012371dca03070d8c6e3f4b4442b906453f726edef8686ef0956b96c0b459e5"
154
+ }
155
+ },
156
+ {
157
+ "path": "test_data/philips_97/1.3.46.670589.28.26690171363123020201002205159499515/IM-0002-0036.dcm",
158
+ "sop_uid": "1.3.46.670589.28.266901713631230202010070946266587912211512",
159
+ "artery": "left",
160
+ "sha256": "7483952482cbcf74d57639f47465882b31783ef3510c2d6a9be0951ec7d48860",
161
+ "preview": {
162
+ "frames": 35,
163
+ "rows": 512,
164
+ "columns": 512,
165
+ "series_uid": "1.3.46.670589.28.26690171363123020201002210137460047.2.2",
166
+ "video": "examples/philips-positive/02.mp4",
167
+ "video_sha256": "36ba14ca030366f6205d49aeebd1be5ae0e585e787ff40c5f0684cec6e49c78d",
168
+ "poster": "examples/philips-positive/02.png",
169
+ "poster_sha256": "bf8e9e6e4ea955fdac5ca2a56bd296f3ff7c6a885bbd6ae99cb49ed5ac1d2fdf"
170
+ }
171
  },
172
  {
173
+ "path": "test_data/philips_97/1.3.46.670589.28.26690171363123020201002205159499515/IM-0006-0038.dcm",
174
+ "sop_uid": "1.3.46.670589.28.266901713631230202010070946267998152211512",
175
+ "artery": "left",
176
+ "sha256": "1b9ac97edef7b910e63f2d00a628c5953f83d3c4a268658b7175dfdbe83e016c",
177
+ "preview": {
178
+ "frames": 33,
179
+ "rows": 512,
180
+ "columns": 512,
181
+ "series_uid": "1.3.46.670589.28.26690171363123020201002210601739056.2.2",
182
+ "video": "examples/philips-positive/03.mp4",
183
+ "video_sha256": "692fb186be3e0b107037f662579fbdd331b1df5df974a848200f775ac3400e6e",
184
+ "poster": "examples/philips-positive/03.png",
185
+ "poster_sha256": "6ee90a06053a4494f3ed4c4f3641197c88ddaa06813f8f49db5835abe929a5f6"
186
+ }
187
  },
188
  {
189
+ "path": "test_data/philips_97/1.3.46.670589.28.26690171363123020201002205159499515/IM-0003-0036.dcm",
190
+ "sop_uid": "1.3.46.670589.28.266901713631230202010070946266897972211512",
191
+ "artery": "left",
192
+ "sha256": "b8f0ce75ab11e1b81de00de0484b5339c37aae49c74563e36279a651e3245e6c",
193
+ "preview": {
194
+ "frames": 34,
195
+ "rows": 512,
196
+ "columns": 512,
197
+ "series_uid": "1.3.46.670589.28.26690171363123020201002210155305050.2.2",
198
+ "video": "examples/philips-positive/04.mp4",
199
+ "video_sha256": "ece6dad70419ce6b3fbeea6264d0e6bb99fb23e1af4bfce00ada745565fdf197",
200
+ "poster": "examples/philips-positive/04.png",
201
+ "poster_sha256": "fcb4a76eaf694e0ff441a83040e13392c0c9000b55aad08a1f730f0b0d360682"
202
+ }
203
  },
204
  {
205
+ "path": "test_data/philips_97/1.3.46.670589.28.26690171363123020201002205159499515/IM-0005-0072.dcm",
206
+ "sop_uid": "1.3.46.670589.28.266901713631230202010070946267678092211512",
207
+ "artery": "left",
208
+ "sha256": "8af0fb2c7004a7348f56e4e4f1a98ea987337306f6f8b9bb1b8620a7d3c9f005",
209
+ "preview": {
210
+ "frames": 68,
211
+ "rows": 512,
212
+ "columns": 512,
213
+ "series_uid": "1.3.46.670589.28.26690171363123020201002210431483054.2.2",
214
+ "video": "examples/philips-positive/05.mp4",
215
+ "video_sha256": "1645bea2765afc2dba196a0aadfef72f84a5e6b6709e83385449b499e2ac1fcd",
216
+ "poster": "examples/philips-positive/05.png",
217
+ "poster_sha256": "793336186d5464c850fc77398de82bc5172d588266b95fa8a5e38a53b16e549c"
218
+ }
219
  },
220
  {
221
+ "path": "test_data/philips_97/1.3.46.670589.28.26690171363123020201002205159499515/IM-0001-0046.dcm",
222
+ "sop_uid": "1.3.46.670589.28.266901713631230202010070946266277852211512",
223
+ "artery": "right",
224
+ "sha256": "46ffd2460e6c292ca2b3d1f031653a4f597135ef1e605e133b53f2b354b0af3c",
225
+ "preview": {
226
+ "frames": 46,
227
+ "rows": 512,
228
+ "columns": 512,
229
+ "series_uid": "1.3.46.670589.28.26690171363123020201002210013318041.2.2",
230
+ "video": "examples/philips-positive/06.mp4",
231
+ "video_sha256": "50eb8db06c98a93007d751d45801fc20535dd1e6c54b06124cacd939a79a0e99",
232
+ "poster": "examples/philips-positive/06.png",
233
+ "poster_sha256": "8aa76a928387b70de79546b12806239f71d2f3c724d369afc9effae212899763"
234
+ }
235
  },
236
  {
237
+ "path": "test_data/philips_97/1.3.46.670589.28.26690171363123020201002205159499515/IM-0007-0038.dcm",
238
+ "sop_uid": "1.3.46.670589.28.266901713631230202010070946268458212211512",
239
+ "artery": "left",
240
+ "sha256": "fe92841ff34d259510b1c1467dd9711ebaac69d1d20172b01dd95777c81d9532",
241
+ "preview": {
242
+ "frames": 32,
243
+ "rows": 512,
244
+ "columns": 512,
245
+ "series_uid": "1.3.46.670589.28.26690171363123020201002210855973062.2.2",
246
+ "video": "examples/philips-positive/07.mp4",
247
+ "video_sha256": "09a91e0f5827379fb99767d9abb6bd033af86e7a1c7b9f2c8d266c18d011fa9e",
248
+ "poster": "examples/philips-positive/07.png",
249
+ "poster_sha256": "54ca695c678703bece16f952232054cdc6a25d1edd90fdf5e30de3cb29790127"
250
+ }
251
+ },
252
+ {
253
+ "path": "test_data/philips_97/1.3.46.670589.28.26690171363123020201002205159499515/IM-0008-0054.dcm",
254
+ "sop_uid": "1.3.46.670589.28.266901713631230202010070946268778272211512",
255
+ "artery": "left",
256
+ "sha256": "3f71d110dad0223f3fc5a5cb1bbbcf010cf13f7aad4f4efc172b70c482878811",
257
+ "preview": {
258
+ "frames": 47,
259
+ "rows": 512,
260
+ "columns": 512,
261
+ "series_uid": "1.3.46.670589.28.26690171363123020201002210908251064.2.2",
262
+ "video": "examples/philips-positive/08.mp4",
263
+ "video_sha256": "8bd648a471c8edc14fb7a64abaf31941c35e9c8cf466d0cf6d5f8bd1513897eb",
264
+ "poster": "examples/philips-positive/08.png",
265
+ "poster_sha256": "3e25b34f8cbeff64eba439f949287480c82c7e61b238603555459fdb9cdec8e2"
266
+ }
267
  }
268
+ ]
 
 
 
 
269
  }
270
+ ]
service/storage.py CHANGED
@@ -48,15 +48,17 @@ class Projection:
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
 
@@ -70,10 +72,19 @@ class Study:
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
 
@@ -274,6 +285,18 @@ class Store:
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)
 
48
  artery: str = 'unassigned'
49
  probability: float | None = None
50
  reason: str | None = None
51
+ source: dict | None = None
52
+ static_preview: dict | None = None
53
 
54
  def public(self, study_id: str) -> dict:
55
  return {
56
  'id': self.id, 'name': self.name, 'frames': self.frames,
57
  'rows': self.rows, 'columns': self.columns, 'artery': self.artery,
58
  'probability': self.probability, 'reason': self.reason,
59
+ 'preview_url': self.static_preview['poster'] if self.static_preview else f'/api/studies/{study_id}/projections/{self.id}/preview',
60
+ 'animation_url': None if self.static_preview else f'/api/studies/{study_id}/projections/{self.id}/preview?animated=true',
61
+ 'video_url': self.static_preview['video'] if self.static_preview else f'/api/studies/{study_id}/projections/{self.id}/video',
62
  }
63
 
64
 
 
72
  touched_at: float = field(default_factory=time.time)
73
  active_job: str | None = None
74
  readers: int = 0
75
+ cached_result_job_id: str | None = None
76
+ source_type: str = 'upload'
77
+ default_projection_id: str | None = None
78
+ reference_score: float | None = None
79
 
80
  def public(self) -> dict:
81
  return {'id': self.id, 'study_uid': self.study_uid,
82
  'created_at': self.created_at,
83
+ 'cached_result_job_id': self.cached_result_job_id,
84
+ 'source_type': self.source_type,
85
+ 'default_projection_id': self.default_projection_id,
86
+ 'reference_score': self.reference_score,
87
+ 'hydrated': all(p.path.is_file() for p in self.projections),
88
  'projections': [p.public(self.id) for p in self.projections]}
89
 
90
 
 
285
  self.studies[study_id] = study
286
  return study
287
 
288
+ def add_virtual(self, study_uid: str, projections: list[Projection]) -> Study:
289
+ with self.lock:
290
+ self.capacity(0, 1)
291
+ study_id = secrets.token_urlsafe(32)
292
+ directory = self.root / study_id
293
+ directory.mkdir(mode=0o700)
294
+ for projection in projections:
295
+ projection.path = directory / projection.id
296
+ study = Study(study_id, study_uid, projections, directory, source_type='precomputed_example')
297
+ self.studies[study_id] = study
298
+ return study
299
+
300
  def delete(self, study_id: str) -> bool:
301
  with self.lock:
302
  study = self.studies.get(study_id)
static/app.js CHANGED
@@ -1,17 +1,17 @@
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;}
@@ -20,43 +20,62 @@ function errorText(e){if(typeof e==='string')return localizeError(e);if(Array.is
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();
 
1
  'use strict';
2
  const $=id=>document.getElementById(id);
3
+ const words={en:{studies:'Studies',addStudy:'Add study',sidebarEmpty:'No studies loaded.',ephemeral:'Session',sessionHint:'Files expire after 1 hour of inactivity.',modelLink:'Model & methodology ↗',datasetLink:'Open dataset ↗',workspace:'SYNTAX analysis',initialTitle:'New study',initialSubtitle:'Upload DICOM or open a public example.',researchOnly:'Research use',stepUpload:'Upload',stepReview:'Review',stepResult:'Result',dropTitle:'Upload DICOM',dropDescription:'Drop study files or a ZIP archive.',chooseFiles:'Choose files',beforeStart:'Input requirements',prepareTitle:'De-identified DICOM',prepareText:'Remove personal information before upload.',runTitle:'LCA and RCA projections',runText:'Both arteries are required for a full-study score.',projection:'Projection',selectProjection:'Select a projection',dicomPreview:'DICOM · contrast-adjusted preview',projectionAssignment:'Artery',leftArtery:'Left',rightArtery:'Right',exclude:'Exclude',allProjections:'Projections',autoClassify:'Identify arteries',resultTitle:'Result',notCalculated:'Not calculated',resultEmpty:'Run analysis to calculate the score.',rawSideNote:'Before calibration',downloadResult:'Export JSON',readyToRun:'Projection summary',excluded:'Excluded',calculate:'Calculate SYNTAX',jobHint:'The first run downloads the model weights.',jobHintCpu:'CPU analysis can take several minutes.',reviewOne:'1 projection needs review.',reviewMany:'{count} projections need review.',methodTitle:'Model',ensemble:'Ensemble',ensembleValue:'5 folds · 10 models',calibration:'Calibration',calibrationValue:'Applied per fold',device:'Compute',modelVersion:'Model revision',modelScope:'Research use only.',foldResults:'Five-fold ensemble results',foldHint:'',rawScore:'Before calibration',calibratedScore:'After calibration',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 coronary arteries included.',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:'',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:'Public examples',referenceLabel:'Reference',referenceSyntaxLabel:'Reference SYNTAX',modelLabel:'Model',precomputedLabel:'Precomputed',exampleLoad:'Open example',exampleHint:'Published holdout studies.',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 artery assignments.',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.',lightTheme:'Light',darkTheme:'Dark',appearance:'Color theme',recalculate:'Recalculate SYNTAX',completeSubtitle:'Analysis complete.',partialSubtitle:'Partial analysis — one coronary artery is missing.',play:'Play',pause:'Pause',previousFrame:'Previous frame',nextFrame:'Next frame',seekFrame:'Frame',framePosition:'Frame {frame} of {total}',collapsePreview:'Return to study',playbackSpeed:'Playback speed',playbackSpeedValue:'Playback speed: {rate}×'},ru:{studies:'Исследования',addStudy:'Добавить исследование',sidebarEmpty:'Исследования не загружены.',ephemeral:'Сессия',sessionHint:'Файлы удаляются после 1 часа бездействия.',modelLink:'Модель и методология ↗',datasetLink:'Открытый датасет ↗',workspace:'Анализ SYNTAX',initialTitle:'Новое исследование',initialSubtitle:'Загрузите DICOM или откройте публичный пример.',researchOnly:'Для исследований',stepUpload:'Загрузить',stepReview:'Проверить',stepResult:'Результат',dropTitle:'Загрузить DICOM',dropDescription:'Перетащите файлы исс��едования или ZIP-архив.',chooseFiles:'Выбрать файлы',beforeStart:'Требования к данным',prepareTitle:'Обезличенные DICOM',prepareText:'Удалите персональную информацию до загрузки.',runTitle:'Проекции LCA и RCA',runText:'Для полной оценки нужны обе артерии.',projection:'Проекция',selectProjection:'Выберите проекцию',dicomPreview:'DICOM · контраст для просмотра',projectionAssignment:'Артерия',leftArtery:'Левая',rightArtery:'Правая',exclude:'Исключить',allProjections:'Проекции',autoClassify:'Определить артерии',resultTitle:'Результат',notCalculated:'Не рассчитан',resultEmpty:'Запустите анализ для расчёта оценки.',rawSideNote:'До калибровки',downloadResult:'Экспорт JSON',readyToRun:'Состав проекций',excluded:'Исключено',calculate:'Рассчитать SYNTAX',jobHint:'При первом запуске загружаются веса модели.',jobHintCpu:'Расчёт на CPU может занять несколько минут.',reviewOne:'Проверить проекции: 1.',reviewMany:'Проверить проекции: {count}.',methodTitle:'Модель',ensemble:'Ансамбль',ensembleValue:'5 фолдов · 10 моделей',calibration:'Калибровка',calibrationValue:'Для каждого фолда',device:'Вычисления',modelVersion:'Версия модели',modelScope:'Только для исследований.',foldResults:'Оценки по фолдам',foldHint:'',rawScore:'До калибровки',calibratedScore:'После калибровки',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:'Публичные примеры',referenceLabel:'Эталон',referenceSyntaxLabel:'Эталон SYNTAX',modelLabel:'Модель',precomputedLabel:'Сохранённый результат',exampleLoad:'Открыть пример',exampleHint:'Исследования из опубликованных 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:'Срок временного хранения истёк. Загрузите исследование заново.',lightTheme:'Светлая',darkTheme:'Тёмная',appearance:'Цветовая тема',recalculate:'Пересчитать SYNTAX',completeSubtitle:'Анализ завершён.',partialSubtitle:'Частичный анализ — отсутствует одна из артерий.',play:'Воспроизвести',pause:'Пауза',previousFrame:'Предыдущий кадр',nextFrame:'Следующий кадр',seekFrame:'Кадр',framePosition:'Кадр {frame} из {total}',collapsePreview:'Вернуться к исследованию',playbackSpeed:'Скорость воспроизведения',playbackSpeedValue:'Скорость воспроизведения: {rate}×'}};
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();document.querySelector('.theme-switch').setAttribute('aria-label',t('appearance'));cinePlayers.forEach(updateCine);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;}
 
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(){renderJobHint();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 renderJobHint(){const node=$('job-hint');if(!node)return;const cached=status?.cached===true||['cached','ready'].includes(status?.model?.status);const cpu=String(status?.device||'').toLowerCase()==='cpu';node.hidden=!status||(cached&&!cpu);node.textContent=(!cached?t('jobHint'):'')+(cpu?(!cached?' ':'')+t('jobHintCpu'):'');}
25
  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);});}
26
+ function defaultProjection(study){return study?.projections.find(p=>p.id===study.default_projection_id)?.id||study?.projections[0]?.id||null;}
27
+ function selectStudy(id){selectedStudyId=id;selectedProjectionId=defaultProjection(currentStudy());render();}
28
+ 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(resultByStudy.has(s.id)?resultByStudy.get(s.id).complete===false?'partialSubtitle':'completeSubtitle':'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){$('viewer-image').pause();return;}$('study-uid').textContent=s.study_uid;$('projection-count').textContent=s.projections.length;if(!s.projections.some(x=>x.id===selectedProjectionId))selectedProjectionId=defaultProjection(s);renderProjection();renderFilmstrip();renderCounts();renderResult();}
29
  function labelFor(artery){return {left:'LCA',right:'RCA',exclude:t('excluded'),unassigned:t('unassigned')}[artery]||t('unassigned');}
30
+ 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.dataset.frames=String(p.frames);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');});}
31
+ 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.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)));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);}}
32
+ 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=counts.unassigned?t(counts.unassigned===1?'reviewOne':'reviewMany').replace('{count}',String(counts.unassigned)):t(hint);$('run-button').querySelector('[data-t]').textContent=t(resultByStudy.has(s.id)?'recalculate':'calculate');$('run-button').disabled=busy||!!counts.unassigned||(!counts.left&&!counts.right);$('classify-button').disabled=busy||!s.projections.some(p=>p.frames>=10);}
33
  function invalidateResult(){const id=selectedStudyId;if(resultByStudy.has(id)){resultByStudy.delete(id);resultJobByStudy.delete(id);toast(t('resultStale'));}}
34
  function finite(...values){return values.find(v=>typeof v==='number'&&Number.isFinite(v));}
35
+ function number(value){return typeof value==='number'&&Number.isFinite(value)?value.toFixed(2):'—';}
36
+ function renderResult(){const result=resultByStudy.get(selectedStudyId);const reference=finite(currentStudy()?.reference_score);$('reference-score').hidden=reference===undefined;$('reference-score-value').textContent=number(reference);$('result-details').hidden=!result;$('result-origin').hidden=result?.source?.type!=='precomputed_example';$('result-origin').textContent=t('precomputedLabel');$('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}`;}}
37
+ function resultMatchesStudy(result,study){if(!result||!study)return false;const assignments=result.input_assignments;if(!Array.isArray(assignments))return result.source?.type!=='precomputed_example';return assignments.length===study.projections.length&&assignments.every((a,i)=>a.id===study.projections[i].id&&a.artery===study.projections[i].artery);}
38
+ function adoptCachedJob(job){if(!job||job.status!=='completed'||job.kind!=='inference')return;const study=studies.find(s=>s.id===job.study_id);if(!resultMatchesStudy(job.result,study))return;resultByStudy.set(study.id,job.result);resultJobByStudy.set(study.id,job.id);}
39
+ 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);}adoptCachedJob(data.cached_job);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();if(data.cached_job&&resultByStudy.get(selectedStudyId)?.source?.type==='precomputed_example'&&!window.matchMedia('(prefers-reduced-motion: reduce)').matches)$('viewer-image').play().catch(()=>{});}
40
  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();}}
41
 
42
  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();});}
43
 
44
  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);}}
45
  function finishJob(){busy=false;activeJob=null;clearTimeout(pollTimer);$('job-status').hidden=true;$('upload-overlay').hidden=true;render();refreshStatus();}
46
+ 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;if(selectedStudyId===updated.id){const unresolved=updated.projections.find(p=>p.artery==='unassigned');if(unresolved)selectedProjectionId=unresolved.id;}}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);}}}
47
  let examples=[];
48
+ function referenceNumber(value){return value.toFixed(2);}
49
+ 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;const reference=finite(example.reference_score),prediction=example.cached_result_available?finite(example.prediction?.calibrated):undefined;const vendor=example.vendor||example.title?.split(' · ')[0]||example.id;const header=el('span','example-card-header');const detail=el('span','example-detail');detail.append(el('strong','',vendor));if(Number.isFinite(example.files))detail.append(el('span','',`${example.files} ${t('projections')}`));header.append(detail,icon('arrow'));b.append(header);if(reference!==undefined||prediction!==undefined){b.classList.add('example-with-scores');const scores=el('span','example-scores');if(reference!==undefined){const cell=el('span','example-score');cell.append(el('small','',t('referenceLabel')+' SYNTAX'),el('strong','',referenceNumber(reference)));scores.append(cell);}if(prediction!==undefined){const cell=el('span','example-score');cell.append(el('small','',t('modelLabel')),el('strong','',prediction.toFixed(2)));scores.append(cell);}b.append(scores);if(prediction!==undefined)b.append(el('span','example-cache-label',t('precomputedLabel')));}b.setAttribute('aria-label',`${vendor}${reference!==undefined?` · ${t('referenceLabel')} SYNTAX ${referenceNumber(reference)}`:''}${prediction!==undefined?` · ${t('modelLabel')} ${prediction.toFixed(2)} · ${t('precomputedLabel')}`:''}`);b.addEventListener('click',()=>loadExample(example.id));box.append(b);}box.append(el('p','',t('exampleHint')));}
50
  async function loadExamples(){if(previewMode)return;try{const d=await request('/api/examples');examples=d.examples||[];renderExamples();}catch{}}
51
  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);}}
52
+ let expandedPlayback=null;
53
+ function openPreview(){const p=currentProjection();if(!p)return;const main=$('viewer-image'),video=$('dialog-image');expandedPlayback={projectionId:p.id,paused:main.paused};$('dialog-name').textContent=p.name;video.dataset.frames=String(p.frames);video.poster=p.preview_url;video.defaultPlaybackRate=main.playbackRate;video.playbackRate=main.playbackRate;const time=main.currentTime;main.pause();const sync=()=>{if(!expandedPlayback||expandedPlayback.projectionId!==p.id||!$('preview-dialog').open)return;video.currentTime=Math.min(time,Math.max(0,video.duration-.001));updateCine(cinePlayers[1]);if(!expandedPlayback?.paused)video.play().catch(()=>{});};$('preview-dialog').showModal();if(video.dataset.current!==p.video_url){video.dataset.current=p.video_url;video.src=p.video_url||'';video.addEventListener('loadedmetadata',sync,{once:true});video.load();}else sync();cinePlayers[1].play.focus();}
54
+ function closeExpandedPreview(){const video=$('dialog-image'),main=$('viewer-image');const paused=video.paused;video.pause();if(expandedPlayback&&currentProjection()?.id===expandedPlayback.projectionId){if(Number.isFinite(main.duration))main.currentTime=Math.min(video.currentTime,Math.max(0,main.duration-.001));if(!paused)main.play().catch(()=>{});}expandedPlayback=null;}
55
+ const cinePlayers=[];let cinePlaybackRate=1;
56
+ function setCineSpeed(rate){if(![.5,1].includes(rate))return;cinePlaybackRate=rate;for(const player of cinePlayers){player.video.defaultPlaybackRate=rate;player.video.playbackRate=rate;updateCine(player);}}
57
+ function buildCine(video){const controls=el('div','cine-controls');const play=el('button','cine-button cine-play');play.type='button';const previous=el('button','cine-button');previous.type='button';previous.append(icon('frame-back'));const next=el('button','cine-button');next.type='button';next.append(icon('frame-forward'));const range=el('input','cine-range');range.type='range';range.min='0';range.step='1';range.value='0';range.max='0';const counter=el('span','cine-counter','— / —');const speed=el('span','cine-speed');speed.setAttribute('role','group');const speedButtons=[.5,1].map(rate=>{const button=el('button','',`${rate}×`);button.type='button';button.dataset.rate=String(rate);button.addEventListener('click',()=>setCineSpeed(rate));speed.append(button);return button;});controls.append(play,previous,next,range,counter,speed);if(video.id==='viewer-image')$('viewer-canvas').after(controls);else video.after(controls);const player={video,play,previous,next,range,counter,speed,speedButtons};cinePlayers.push(player);video.defaultPlaybackRate=cinePlaybackRate;video.playbackRate=cinePlaybackRate;video.tabIndex=0;play.addEventListener('click',()=>toggleCine(player));previous.addEventListener('click',()=>stepCine(player,-1));next.addEventListener('click',()=>stepCine(player,1));range.addEventListener('input',()=>seekCine(player,Number(range.value)));for(const event of ['loadedmetadata','durationchange','timeupdate','play','pause','seeked','emptied','error','ratechange'])video.addEventListener(event,()=>updateCine(player));video.addEventListener('keydown',event=>{if(event.key===' '){event.preventDefault();toggleCine(player);}else if(event.key==='ArrowLeft'||event.key==='ArrowRight'){event.preventDefault();stepCine(player,event.key==='ArrowLeft'?-1:1);}});updateCine(player);}
58
+ function cineFrame(player){const {video}=player,frames=Number(video.dataset.frames)||0;return frames&&Number.isFinite(video.duration)&&video.duration>0?Math.min(frames-1,Math.floor(video.currentTime/video.duration*frames)):0;}
59
+ function seekCine(player,index){const {video}=player,frames=Number(video.dataset.frames)||0;if(!frames||!Number.isFinite(video.duration)||video.duration<=0)return;video.currentTime=Math.min(video.duration-.001,(Math.max(0,Math.min(frames-1,index))+.001)*video.duration/frames);updateCine(player);}
60
+ function stepCine(player,delta){player.video.pause();seekCine(player,cineFrame(player)+delta);}
61
+ function toggleCine(player){if(player.video.paused)player.video.play().catch(()=>{});else player.video.pause();}
62
+ function updateCine(player){const {video,play,previous,next,range,counter,speed,speedButtons}=player;speed.setAttribute('aria-label',t('playbackSpeed'));speed.title=t('playbackSpeed');for(const button of speedButtons){const selected=Number(button.dataset.rate)===video.playbackRate;button.classList.toggle('selected',selected);button.setAttribute('aria-pressed',String(selected));button.setAttribute('aria-label',t('playbackSpeedValue').replace('{rate}',button.dataset.rate));}const frames=Number(video.dataset.frames)||0;const ready=frames>0&&Number.isFinite(video.duration)&&video.duration>0&&!video.error;const frame=cineFrame(player);play.replaceChildren(icon(video.paused?'play':'pause'));play.setAttribute('aria-label',t(video.paused?'play':'pause'));play.title=t(video.paused?'play':'pause');previous.setAttribute('aria-label',t('previousFrame'));previous.title=t('previousFrame');next.setAttribute('aria-label',t('nextFrame'));next.title=t('nextFrame');range.setAttribute('aria-label',t('seekFrame'));range.max=String(Math.max(0,frames-1));range.value=String(frame);range.style.setProperty('--position',frames>1?`${frame/(frames-1)*100}%`:'0%');range.setAttribute('aria-valuetext',t('framePosition').replace('{frame}',String(frame+1)).replace('{total}',String(frames)));counter.textContent=frames?`${String(frame+1).padStart(2,'0')} / ${frames}`:'— / —';play.disabled=!ready;previous.disabled=!ready||frame===0;next.disabled=!ready||frame>=frames-1;range.disabled=!ready;}
63
  $('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)));
64
+ $('sidebar-upload').addEventListener('click',()=>{if(busy)return;$('viewer-image').pause();selectedStudyId=null;selectedProjectionId=null;hideError();render();});$('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);
65
+ 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',()=>$('preview-dialog').close());$('preview-dialog').addEventListener('close',closeExpandedPreview);$('preview-dialog').addEventListener('click',e=>{if(e.target===$('preview-dialog'))$('preview-dialog').close();});$('viewer-image').addEventListener('error',()=>{$('viewer-image').hidden=true;$('viewer-empty').hidden=false;});
66
  $('copy-uid').addEventListener('click',async()=>{try{await navigator.clipboard.writeText(currentStudy()?.study_uid||'');toast(t('copied'));}catch{toast(t('copyFailed'));}});
67
  $('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);});
68
  $('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);});
69
 
70
  let workspaceRestored=false;
71
  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{}}
72
+ 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'&&resultMatchesStudy(job.result,studies.find(s=>s.id===studyId))){resultByStudy.set(studyId,job.result);resultJobByStudy.set(studyId,jobId);}}catch{}}selectedStudyId=saved.selected_study_id===null?null:studies.some(s=>s.id===saved.selected_study_id)?saved.selected_study_id:studies[0]?.id||null;selectedProjectionId=defaultProjection(currentStudy());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();}
73
  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;}
74
 
75
  window.addEventListener('beforeunload',()=>clearTimeout(pollTimer));
76
+ const mobileLayout=window.matchMedia('(max-width: 760px)');
77
+ function placeFoldResults(){const fold=$('fold-results');const destination=mobileLayout.matches?$('workspace-grid'):document.querySelector('.study-panel');if(fold.parentElement!==destination)destination.append(fold);}
78
+ mobileLayout.addEventListener('change',placeFoldResults);
79
+
80
+ async function init(){placeFoldResults();buildCine($('viewer-image'));buildCine($('dialog-image'));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();}
81
  init();
static/examples/philips-positive/01.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:aea9f607f889bb87dced82380b02a78d97a20a78edbc50b5944dbf8f870a8c4b
3
+ size 3329112
static/examples/philips-positive/01.png ADDED

Git LFS Details

  • SHA256: d012371dca03070d8c6e3f4b4442b906453f726edef8686ef0956b96c0b459e5
  • Pointer size: 131 Bytes
  • Size of remote file: 183 kB
static/examples/philips-positive/02.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:36ba14ca030366f6205d49aeebd1be5ae0e585e787ff40c5f0684cec6e49c78d
3
+ size 1783855
static/examples/philips-positive/02.png ADDED

Git LFS Details

  • SHA256: bf8e9e6e4ea955fdac5ca2a56bd296f3ff7c6a885bbd6ae99cb49ed5ac1d2fdf
  • Pointer size: 131 Bytes
  • Size of remote file: 181 kB
static/examples/philips-positive/03.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:692fb186be3e0b107037f662579fbdd331b1df5df974a848200f775ac3400e6e
3
+ size 1853690
static/examples/philips-positive/03.png ADDED

Git LFS Details

  • SHA256: 6ee90a06053a4494f3ed4c4f3641197c88ddaa06813f8f49db5835abe929a5f6
  • Pointer size: 131 Bytes
  • Size of remote file: 183 kB
static/examples/philips-positive/04.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ece6dad70419ce6b3fbeea6264d0e6bb99fb23e1af4bfce00ada745565fdf197
3
+ size 1949794
static/examples/philips-positive/04.png ADDED

Git LFS Details

  • SHA256: fcb4a76eaf694e0ff441a83040e13392c0c9000b55aad08a1f730f0b0d360682
  • Pointer size: 131 Bytes
  • Size of remote file: 185 kB
static/examples/philips-positive/05.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1645bea2765afc2dba196a0aadfef72f84a5e6b6709e83385449b499e2ac1fcd
3
+ size 3586165
static/examples/philips-positive/05.png ADDED

Git LFS Details

  • SHA256: 793336186d5464c850fc77398de82bc5172d588266b95fa8a5e38a53b16e549c
  • Pointer size: 131 Bytes
  • Size of remote file: 185 kB
static/examples/philips-positive/06.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:50eb8db06c98a93007d751d45801fc20535dd1e6c54b06124cacd939a79a0e99
3
+ size 2992938
static/examples/philips-positive/06.png ADDED

Git LFS Details

  • SHA256: 8aa76a928387b70de79546b12806239f71d2f3c724d369afc9effae212899763
  • Pointer size: 131 Bytes
  • Size of remote file: 185 kB
static/examples/philips-positive/07.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:09a91e0f5827379fb99767d9abb6bd033af86e7a1c7b9f2c8d266c18d011fa9e
3
+ size 1801527
static/examples/philips-positive/07.png ADDED

Git LFS Details

  • SHA256: 54ca695c678703bece16f952232054cdc6a25d1edd90fdf5e30de3cb29790127
  • Pointer size: 131 Bytes
  • Size of remote file: 184 kB
static/examples/philips-positive/08.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8bd648a471c8edc14fb7a64abaf31941c35e9c8cf466d0cf6d5f8bd1513897eb
3
+ size 2722305
static/examples/philips-positive/08.png ADDED

Git LFS Details

  • SHA256: 3e25b34f8cbeff64eba439f949287480c82c7e61b238603555459fdb9cdec8e2
  • Pointer size: 131 Bytes
  • Size of remote file: 183 kB
static/examples/philips-zero/01.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d52aa5f3a84f228cdffe8424b26f502a1375823f1e55ceff046e43d3005db18b
3
+ size 2083085
static/examples/philips-zero/01.png ADDED

Git LFS Details

  • SHA256: f98345dcfb8400e6fcb9657a7026220f23813f503c3adcf15aabc33f6d8c5949
  • Pointer size: 131 Bytes
  • Size of remote file: 181 kB
static/examples/philips-zero/02.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:88905a2e1365db759dd8c5398ddfe0572e01b7897a70714ececad4efb2097126
3
+ size 1890937
static/examples/philips-zero/02.png ADDED

Git LFS Details

  • SHA256: a675aa9fff347c10db28bb29b7fd009e783be007438bcffd648914c40a90c0fb
  • Pointer size: 131 Bytes
  • Size of remote file: 182 kB
static/examples/philips-zero/03.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ca52f560c1a70438b5d2842d715f858feee8425d603210c22cebd35e4ca34d26
3
+ size 2032791
static/examples/philips-zero/03.png ADDED

Git LFS Details

  • SHA256: 765a4deae34977cd72e38c4276c48dd2806cf7af35a4bafa0c7ff7dbe92f9966
  • Pointer size: 131 Bytes
  • Size of remote file: 183 kB
static/examples/philips-zero/04.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2d899ce3ae9a1cfc5c6ca57434b6b18e13080ea56bbfc1b62056121f48be2cf3
3
+ size 1839199
static/examples/philips-zero/04.png ADDED

Git LFS Details

  • SHA256: d417519fe7cabe00a35f39adea4566ff15aeb290a9d65348ac6125e9f1bd4bfc
  • Pointer size: 131 Bytes
  • Size of remote file: 184 kB
static/examples/philips-zero/05.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8c0bf747399f49f840463ba6d5e52147c1e15f23bfdaae079ceeb62b1e5c5de0
3
+ size 2526312
static/examples/philips-zero/05.png ADDED

Git LFS Details

  • SHA256: 9e57610b64465ee4c801c4548c407ddf676d13cfecd3d3b6bcf2688d0285c581
  • Pointer size: 131 Bytes
  • Size of remote file: 185 kB
static/examples/philips-zero/06.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0945c2df0d8f6b68232b5add24771ccfb1d6157afda10fb374a033cc2289f473
3
+ size 2616017
static/examples/philips-zero/06.png ADDED

Git LFS Details

  • SHA256: 1b9c5fd9a917e536ad9ddf475d7df22b3d3fb79304e24d5042200ff3000f00ca
  • Pointer size: 131 Bytes
  • Size of remote file: 188 kB
static/examples/philips-zero/07.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b4982940b55435b811c4587c48a7c11c0d816cc56f7bf7955694121dc99451a0
3
+ size 2412106
static/examples/philips-zero/07.png ADDED

Git LFS Details

  • SHA256: 69017794bca8642fdeec19b305beea806badaf09d3e050250e481197d5ed9426
  • Pointer size: 131 Bytes
  • Size of remote file: 181 kB
static/index.html CHANGED
@@ -1,50 +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>
 
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"><link rel="stylesheet" href="/static/workspace.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
+ <symbol id="i-sun" viewBox="0 0 24 24"><circle cx="12" cy="12" r="3.8"/><path d="M12 2v2m0 16v2M2 12h2m16 0h2M4.93 4.93l1.42 1.42m11.3 11.3 1.42 1.42m0-14.14-1.42 1.42m-11.3 11.3-1.42 1.42"/></symbol><symbol id="i-moon" viewBox="0 0 24 24"><path d="M20.6 14.3A8.8 8.8 0 0 1 9.7 3.4a8.8 8.8 0 1 0 10.9 10.9Z"/></symbol><symbol id="i-play" viewBox="0 0 24 24"><path d="m9 5 10 7-10 7V5Z"/></symbol><symbol id="i-pause" viewBox="0 0 24 24"><path d="M8 5v14m8-14v14"/></symbol><symbol id="i-frame-back" viewBox="0 0 24 24"><path d="M5 5v14m13-14-9 7 9 7V5Z"/></symbol><symbol id="i-frame-forward" viewBox="0 0 24 24"><path d="M19 5v14M6 5l9 7-9 7V5Z"/></symbol></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="M16 4v8c0 7-6 9-6 16m6-16c0 6 8 6 10 12M16 9c-5 0-9 3-10 8m10 1c2 0 3 4 3 10"/><path class="brand-border" d="M4 4h4m20 0h-4"/></svg></span><span>Cardio<span class="brand-light">Syntax</span></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="Color theme"><button class="selected" data-theme-button="studio" aria-pressed="true"><svg aria-hidden="true"><use href="#i-sun"/></svg><span data-t="lightTheme">Light</span></button><button data-theme-button="lab" aria-pressed="false"><svg aria-hidden="true"><use href="#i-moon"/></svg><span data-t="darkTheme">Dark</span></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">No studies loaded.</div></div>
18
+ <div class="sidebar-bottom"><div class="session-note"><span class="tiny-dot"></span><span data-t="ephemeral">Session</span></div><p data-t="sessionHint">Files expire after 1 hour of inactivity.</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">SYNTAX analysis</div><h1 id="page-title">New study</h1><p class="page-subtitle" id="page-subtitle">Upload DICOM or open a public example.</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></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></div></div><span class="step-line"></span><div class="step" id="step-result"><span class="step-number">03</span><div><strong data-t="stepResult">Result</strong></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="upload-glyph"><svg><use href="#i-upload"/></svg></div><h2 data-t="dropTitle">Upload DICOM</h2><p data-t="dropDescription">Drop study files or a ZIP archive.</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"><section class="examples-box" id="examples-box"></section><section class="input-requirements"><h2 data-t="beforeStart">Input requirements</h2><div class="input-requirement"><svg aria-hidden="true"><use href="#i-file"/></svg><div><strong data-t="prepareTitle">De-identified DICOM</strong><p data-t="prepareText">Remove personal information before upload.</p></div></div><div class="input-requirement"><svg aria-hidden="true"><use href="#i-check"/></svg><div><strong data-t="runTitle">LCA and RCA projections</strong><p data-t="runText">Both arteries are required for a full-study score.</p></div></div></section></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" 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">Artery</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">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 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"></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></section>
35
  <aside class="analysis-panel">
36
+ <section class="result-card" id="result-card"><div class="card-title"><span class="eyebrow" data-t="resultTitle">Result</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">Run analysis to calculate the score.</p></div><div class="reference-score" id="reference-score" hidden><span data-t="referenceSyntaxLabel">Reference SYNTAX</span><strong id="reference-score-value">—</strong></div><span class="result-origin" id="result-origin" hidden></span><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><p class="fine-print" data-t="rawSideNote">Before calibration</p><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><button class="button outline full" id="download-result"><svg><use href="#i-download"/></svg><span data-t="downloadResult">Export JSON</span></button></div></section>
37
+ <section class="run-card"><div class="card-title"><span class="eyebrow" data-t="readyToRun">Projection summary</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 id="job-hint" hidden></p></div></section>
38
+ <section class="method-card"><span class="eyebrow" data-t="methodTitle">Model</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">Research use only.</p></section>
39
  </aside>
40
+
41
  </div>
42
+ <footer class="page-footer"><div><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><a href="https://huggingface.co/datasets/MesserMMP/coronary-angiography-syntax" target="_blank" rel="noopener" data-t="modelsLicense">Models & 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" 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/workspace.css ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Focused workspace styling; Light and Dark share one component system. */
2
+ :root{--bg:#f5f6f4;--surface:#ffffff;--sidebar:#f0f2ef;--ink:#1a2c2b;--muted:#697773;--line:#dde3dd;--accent:#196657;--accent-hover:#0e5043;--accent-pale:#e5efe8;--radius:12px;--shadow:0 2px 9px #182b2004}
3
+ html[data-theme=lab]{--bg:#10191c;--surface:#182327;--sidebar:#131d20;--ink:#e8eeeb;--muted:#a0b1a9;--line:#2c3b3f;--accent:#b5dac8;--accent-hover:#d0ecdf;--accent-pale:#253b33;--shadow:0 2px 8px #0000000b}
4
+ .topbar{height:72px;padding:0 32px 0 25px;gap:18px}.brand{font-size:23px;gap:10px;letter-spacing:-.8px}.brand-mark{width:32px;height:36px}.brand-mark svg{width:30px;height:32px;stroke-width:1.85}.brand-border{opacity:.3}.topbar-right{gap:20px}.server-indicator{font-size:11px}.theme-switch{padding:3px;gap:2px;background:var(--bg);border:1px solid var(--line);border-radius:9px}.theme-switch button{display:flex;align-items:center;gap:7px;padding:7px 11px;font-size:11px;font-weight:500;border:1px solid transparent;border-radius:6px;color:var(--muted);line-height:1.2}.theme-switch button svg{width:15px;height:15px;stroke-width:1.65}.theme-switch button.selected{color:var(--ink);background:var(--surface);border-color:var(--line);box-shadow:0 1px 3px #0a29120b}.theme-switch button.selected svg{color:var(--accent)}.theme-switch button:hover:not(.selected){color:var(--ink)}.language-button{height:32px;min-width:26px;font-size:11px;letter-spacing:.4px;border-left:1px solid var(--line);padding-left:15px}
5
+ .app-layout{grid-template-columns:212px minmax(0,1fr);min-height:calc(100vh - 72px)}.sidebar{padding:27px 15px 22px;background:var(--sidebar)}.sidebar-heading{padding:0 9px;margin-bottom:15px}.sidebar-upload{font-size:12px;padding:11px 10px;border-color:var(--line)}.sidebar-empty{font-size:12px;padding:6px 9px}.study-list{margin-top:18px;gap:7px}.study-item{padding:12px 9px;gap:10px;border-radius:8px}.study-item strong{font-size:12px}.study-item small{font-size:11px;line-height:1.5;margin-top:3px}.study-item-icon{width:30px;height:35px}.sidebar-bottom{padding:42px 9px 0;font-size:11px;line-height:1.6}.session-note{font-size:11px}.sidebar-bottom p{margin:8px 0 18px}.sidebar-bottom a{font-size:11px;margin-top:11px}
6
+ .main{padding:29px 32px 22px;max-width:1540px}.eyebrow{font-size:10px;letter-spacing:1.35px;font-weight:600}.page-heading{margin-bottom:21px;gap:16px}.page-heading .eyebrow{margin-bottom:7px}.page-heading h1{font-size:27px;letter-spacing:-.8px;font-weight:650}.page-subtitle{font-size:12px;margin-top:7px;line-height:1.55}.research-tag{font-size:10px;padding:7px 10px;background:transparent}.heading-actions{gap:10px}.workflow{padding:0 0 18px;margin-bottom:24px;background:transparent!important;border:0;border-bottom:1px solid var(--line);border-radius:0;gap:14px;max-width:none}.step{gap:9px;opacity:.58}.step strong{font-size:12px;font-weight:500}.step-number{width:24px;height:24px;font-size:10px;border-radius:7px}.step.active strong{font-weight:650;color:var(--ink)}.step.done .step-number{background:var(--accent-pale);border-color:transparent;color:var(--accent)}.step-line{height:1px;opacity:.65;max-width:70px;min-width:16px}
7
+ .button{font-size:12px;padding:11px 15px;border-radius:8px;gap:9px}.button.small{font-size:11px;padding:8px 10px}.button:focus-visible,.cine-button:focus-visible,.theme-switch button:focus-visible{outline-width:2px;outline-offset:3px}.count-badge{font-size:11px;height:23px;min-width:23px;border-radius:6px}.welcome{grid-template-columns:minmax(0,1.25fr) minmax(280px,.85fr);gap:28px;min-height:0;align-items:stretch}.welcome-main{min-height:345px;padding:34px 24px;background:var(--surface);border:1px solid var(--line);border-radius:12px;box-shadow:var(--shadow)}.welcome-main:hover,.welcome-main.dragging{background:var(--surface);border-color:var(--accent);box-shadow:inset 0 0 0 1px var(--accent)}.upload-glyph{width:58px;height:58px;border-radius:16px;background:var(--bg);border:1px solid var(--line)}.upload-glyph svg{width:25px;height:25px;stroke-width:1.5}.welcome-main h2{font-size:24px;letter-spacing:-.6px;margin:21px 0 10px}.welcome-main p{font-size:13px;line-height:1.65;max-width:300px}.welcome-main .button{margin-top:23px;min-width:147px}.format-note{font-size:11px;margin-top:14px}.welcome-aside{display:flex;flex-direction:column;max-width:none;padding:0;gap:22px}.examples-box{margin:0;padding:0;border:0}.examples-box:empty{display:none}.examples-box>.eyebrow{display:block;font-size:12px;color:var(--ink);text-transform:none;letter-spacing:0;font-weight:600;margin:1px 0 14px}.example-button{margin-top:9px;padding:14px;background:var(--surface);border:1px solid var(--line);border-radius:10px;gap:12px;box-shadow:var(--shadow)}.example-button>svg{width:16px;height:16px;transition:transform .15s}.example-button:hover:not(:disabled)>svg{transform:translateX(3px)}.example-icon{width:34px;height:39px;display:grid;place-items:center;border:1px solid var(--line);border-radius:7px;color:var(--accent);background:var(--bg);flex:none}.example-icon svg{width:18px;height:18px}.example-detail{display:flex;flex-direction:column;gap:4px;flex:1}.example-detail strong{font-size:13px;font-weight:600}.example-detail>span{font-size:11px;color:var(--muted)}.examples-box>p{font-size:11px;line-height:1.6;margin-top:13px;max-width:350px}.input-requirements{border-top:1px solid var(--line);padding-top:19px}.input-requirements h2{font-size:12px;letter-spacing:0;font-family:'DM Sans',sans-serif;font-weight:600;margin:0 0 15px}.input-requirement{display:flex;gap:10px;align-items:flex-start;margin-top:13px}.input-requirement>svg{width:16px;height:16px;color:var(--muted);margin-top:1px;stroke-width:1.5}.input-requirement strong{font-size:12px;font-weight:500;display:block}.input-requirement p{font-size:11px;line-height:1.6;color:var(--muted);margin-top:4px}
8
+ .workspace-grid{grid-template-columns:minmax(0,1fr) 300px;gap:24px;align-items:start}.viewer-shell{border:1px solid #20302e;border-radius:12px;box-shadow:none}.viewer-toolbar{padding:13px 16px;gap:12px}.viewer-toolbar>div:first-child{min-width:0}.viewer-kicker{font-size:10px;letter-spacing:1.2px;margin-bottom:5px;opacity:.65}.viewer-toolbar strong{font-size:12px;max-width:260px;font-weight:500}.viewer-tools{font-size:10px;gap:12px}.viewer-expand{width:30px;height:30px;display:grid;place-items:center;background:#ffffff07;border:1px solid #ffffff12;border-radius:6px;opacity:1}.viewer-expand svg{width:15px;height:15px}.viewer-canvas{height:365px;background:#080d0e}.viewer-artery{top:13px;left:14px;font-size:10px;letter-spacing:1px;padding:5px 8px;border-color:#ffffff30}.viewer-bottom{padding:9px 16px 12px;font-size:10px;letter-spacing:0;color:#98aaa3}.live-dot{display:none}.viewer-bottom>span:first-child{gap:0}.viewer-empty{font-size:12px}.viewer-canvas video:focus-visible{outline:2px solid #afcfbf;outline-offset:-3px}
9
+ .cine-controls{display:flex;align-items:center;gap:7px;padding:10px 13px 7px;background:var(--viewer);color:var(--viewer-ink);min-width:0}.cine-button{display:grid;place-items:center;width:27px;height:29px;border:0;background:none;border-radius:5px;color:#a4b9af;padding:5px;flex:none}.cine-button svg{width:16px;height:16px;stroke-width:1.7}.cine-button:hover:not(:disabled){background:#ffffff0c;color:#fff}.cine-button:disabled{opacity:.3}.cine-play{background:#dcebe114;color:#e7f2ec;width:31px;margin-right:2px;border:1px solid #c6dfd317}.cine-play svg{width:18px;height:18px}.cine-counter{font-size:11px;letter-spacing:.2px;font-variant-numeric:tabular-nums;min-width:58px;text-align:right;color:#afbeb8}.cine-range{appearance:none;flex:1;min-width:24px;cursor:pointer;height:24px;background:transparent;margin:0 5px;outline-offset:2px}.cine-range::-webkit-slider-runnable-track{height:3px;border-radius:3px;background:#46574e}.cine-range::-webkit-slider-thumb{appearance:none;width:9px;height:9px;border-radius:50%;background:#d4e9db;margin-top:-3px;box-shadow:0 0 0 3px #d4e9db10}.cine-range::-moz-range-track{height:3px;border-radius:3px;background:#46574e}.cine-range::-moz-range-progress{height:3px;border-radius:3px;background:#bfd9ca}.cine-range::-moz-range-thumb{width:9px;height:9px;border:0;border-radius:50%;background:#d4e9db}.cine-range:focus-visible{outline:2px solid #afcfbf;border-radius:4px}.cine-range:disabled{opacity:.35;cursor:default}.preview-dialog>video{max-height:calc(88vh - 110px)}.preview-dialog>.cine-controls{display:flex;padding:12px 18px}.preview-dialog>div:first-child{padding:13px 18px;font-size:12px}
10
+ .assignment-row{padding:16px 0;gap:14px;align-items:center}.assignment-row .eyebrow{font-size:11px;letter-spacing:0;text-transform:none;font-weight:500;color:var(--muted)}.assignment-help{font-size:11px;line-height:1.5;max-width:230px;margin-top:4px}.assignment-help:empty{display:none}.segmented{gap:3px;padding:3px;border-radius:8px;background:var(--surface)}.segmented button{font-size:11px;padding:7px 9px;min-width:55px;gap:5px;font-weight:600}.segmented button>span{font-size:10px}.segmented button[data-artery=exclude] svg{width:13px;height:13px}.projections-heading{margin:20px 0 12px;gap:12px}.projections-heading h2{font-size:13px;font-family:'DM Sans',sans-serif;font-weight:600;letter-spacing:0}.projections-heading h2 .count-badge{margin-left:5px}.filmstrip{grid-template-columns:repeat(5,minmax(0,1fr));gap:9px}.projection-card{border-radius:8px;padding:3px;border-color:var(--line);transition:border-color .15s}.projection-card.selected{border-color:var(--accent);box-shadow:0 0 0 1px var(--accent);background:var(--accent-pale)}.projection-card img{height:77px;border-radius:5px;object-fit:cover}.projection-card .projection-index{font-size:10px;font-variant-numeric:tabular-nums;top:8px;left:8px;padding:2px 4px;line-height:1.4}.projection-card-bottom{font-size:10px;padding:7px 3px 5px;gap:4px}.projection-tag{font-size:10px}.order-controls{margin-top:12px;font-size:11px;gap:14px}.order-controls button{font-size:11px;padding:5px 0}.study-footnote{margin-top:18px;padding-top:14px;font-size:10px;gap:10px}.study-footnote code{font-size:10px;line-height:1.5}.study-footnote .icon-button{padding:3px}.study-footnote svg{width:14px;height:14px}
11
+ .analysis-panel{gap:18px}.result-card,.run-card{padding:20px;border-radius:12px;box-shadow:var(--shadow)}.card-title .eyebrow{font-size:11px;letter-spacing:0;text-transform:none;font-weight:600;color:var(--ink)}.neutral-badge{font-size:10px;padding:4px 7px;border-radius:5px}.score-area{padding-top:23px}.score-label{font-size:12px;color:var(--muted)}.score-number{font-size:76px;line-height:1.12;margin:5px 0 9px;letter-spacing:-3.5px;font-weight:500}.score-number.empty{font-size:66px;line-height:1.15;color:#b4c2ba}.score-area p{font-size:12px;line-height:1.6;max-width:250px}.score-axis{margin-top:19px;height:3px}.axis-labels{font-size:10px}.result-classification{font-size:11px;margin:12px 0 18px}.fine-print{font-size:11px;line-height:1.5;margin:18px 0 9px;color:var(--muted)}.side-scores{padding-top:13px;border-top:1px solid var(--line);gap:15px;margin-bottom:19px}.side-scores span{font-size:11px}.side-scores small{font-size:10px;margin-left:4px}.side-scores strong{font-size:25px;margin-top:7px}.side-scores>div+div{padding-left:18px}.selection-counts{display:grid;grid-template-columns:repeat(3,1fr);gap:12px;margin-top:17px}.selection-counts>div{display:grid;grid-template-columns:6px 1fr;gap:6px;align-items:center;font-size:11px}.selection-counts strong{grid-column:2;font-size:20px;font-weight:500;margin:0;line-height:1.1}.artery-dot{width:5px;height:5px}.run-hint{font-size:11px;line-height:1.65;margin:17px 0}.method-card{padding:3px 4px}.method-card>.eyebrow{font-size:11px;text-transform:none;letter-spacing:0;font-weight:600;color:var(--ink)}.method-card dl{margin:14px 0}.method-card dl>div{font-size:11px;line-height:1.5;margin:10px 0;gap:10px}.method-card dd{font-size:11px}.method-card p{font-size:10px;line-height:1.6;padding-top:13px}.job-status-heading{font-size:11px;line-height:1.6}.job-status-heading strong{font-size:11px}.job-status p{font-size:11px;line-height:1.7;margin-top:11px}.fold-results{margin-top:23px;padding:0;grid-column:auto}.fold-results .projections-heading{margin:0 0 12px;display:flex;flex-direction:column;align-items:flex-start;gap:5px}.fold-results .muted{font-size:11px}.fold-table-wrap{border-radius:9px}table{font-size:12px}th{font-size:11px;padding:11px 14px}td{padding:10px 14px}
12
+ .page-footer{margin-top:28px;padding-top:17px;font-size:10px;line-height:1.5;gap:15px;align-items:flex-start}.page-footer>div{display:flex;gap:18px;flex-wrap:wrap}.page-footer a{color:var(--muted)}.notice{font-size:12px}.upload-overlay p{font-size:12px}.confirm-dialog p{font-size:13px}.preview-banner{font-size:11px}
13
+ @media(min-width:1500px){.main{padding:34px 42px 24px}.workspace-grid{grid-template-columns:minmax(0,1fr) 315px;gap:28px}.viewer-canvas{height:420px}.filmstrip{grid-template-columns:repeat(6,minmax(0,1fr))}.projection-card img{height:80px}}
14
+ @media(max-width:1190px){.app-layout{grid-template-columns:188px minmax(0,1fr)}.sidebar{padding:25px 12px 18px}.sidebar-upload{font-size:11px;gap:6px}.main{padding:26px 24px 20px}.workspace-grid{grid-template-columns:minmax(0,1fr) 265px;gap:19px}.result-card,.run-card{padding:18px}.viewer-canvas{height:310px}.viewer-toolbar{padding:12px 13px}.viewer-tools>span{display:none}.filmstrip{grid-template-columns:repeat(4,minmax(0,1fr))}.assignment-row{flex-wrap:wrap}.assignment-row>.segmented{margin-left:auto}.welcome{gap:23px;grid-template-columns:minmax(0,1fr) minmax(260px,.9fr)}.welcome-main{min-height:350px}.side-scores small{display:none}.sidebar-bottom{padding-left:8px;padding-right:8px}.study-item small{font-size:10px}.study-item-icon{display:none}.method-card dl>div,.method-card dd{font-size:11px}}
15
+ @media(max-width:960px){.app-layout{grid-template-columns:164px minmax(0,1fr)}.sidebar{padding-left:10px;padding-right:10px}.sidebar-upload{font-size:11px;padding:10px 8px;white-space:normal;text-align:left}.sidebar-heading .eyebrow{font-size:10px}.study-item strong{font-size:11px}.main{padding:24px 19px 20px}.workspace-grid{grid-template-columns:minmax(0,1fr) 242px;gap:17px}.result-card,.run-card{padding:16px}.score-number{font-size:67px}.card-title{flex-wrap:wrap}.viewer-canvas{height:280px}.filmstrip{grid-template-columns:repeat(3,minmax(0,1fr))}.segmented button>span{display:none}.segmented button[data-artery=exclude] span{display:block}.welcome{grid-template-columns:1fr}.welcome-main{min-height:290px}.welcome-aside{display:grid;grid-template-columns:1fr 1fr;gap:22px}.examples-box{grid-column:auto}.example-button{max-width:none}.input-requirements{border-top:0;border-left:1px solid var(--line);padding:0 0 0 22px}.topbar{padding:0 22px;gap:16px}.server-indicator{font-size:10px;max-width:150px}.topbar-right{gap:15px}.theme-switch button{padding:7px 9px}.page-heading h1{font-size:25px}.projections-heading{flex-wrap:wrap}.selection-counts{gap:7px}.selection-counts>div{font-size:10px}.selection-counts strong{font-size:19px}.sidebar-bottom a{font-size:10px}.sidebar-bottom p,.session-note{font-size:10px}.preview-dialog>.cine-controls{padding:12px 16px}}
16
+ @media(max-width:760px){.topbar{height:67px;padding:0 16px;gap:9px}.brand{font-size:19px;gap:6px;white-space:nowrap}.brand-mark{width:25px;height:29px}.brand-mark svg{width:24px;height:27px}.topbar-right{gap:10px}.theme-switch{padding:2px;gap:1px;border-radius:8px}.theme-switch button{gap:5px;padding:6px 8px;font-size:10px;border-radius:5px}.theme-switch button svg{width:13px;height:13px}.language-button{font-size:10px;min-width:24px;padding-left:9px}.app-layout{display:block;min-height:calc(100vh - 67px)}.sidebar{padding:11px 16px;gap:9px;flex-direction:row;overflow:auto}.sidebar-upload{font-size:11px;padding:9px 10px;width:auto;white-space:nowrap}.study-list{margin:0;gap:7px}.study-item{width:150px;padding:8px 10px}.study-item strong{font-size:11px}.study-item small{font-size:10px;margin-top:2px}.main{padding:23px 16px 18px}.page-heading{margin-bottom:19px;gap:12px}.page-heading .eyebrow{font-size:10px;letter-spacing:1.15px;margin-bottom:7px}.page-heading h1{font-size:26px}.page-subtitle{font-size:12px;margin-top:6px;max-width:330px}.workflow{padding-bottom:16px;margin-bottom:21px;gap:10px}.step{gap:7px}.step strong{font-size:11px}.step-number{width:23px;height:23px;font-size:10px;border-radius:6px}.step-line{min-width:9px;max-width:none}.welcome{gap:23px}.welcome-main{min-height:285px;padding:28px 20px}.welcome-main h2{font-size:23px}.welcome-main p{font-size:12px}.welcome-main .button{margin-top:22px}.format-note{font-size:11px}.welcome-aside{display:flex;gap:22px}.examples-box{grid-column:auto}.examples-box>.eyebrow{font-size:13px;margin-bottom:12px}.example-button{padding:14px}.examples-box>p{font-size:11px;max-width:none}.input-requirements{border-left:0;border-top:1px solid var(--line);padding:18px 0 0}.input-requirements h2{font-size:12px}.input-requirement{margin-top:14px}.workspace-grid{grid-template-columns:1fr;gap:22px}.viewer-toolbar{padding:13px 14px}.viewer-toolbar strong{font-size:12px;max-width:215px}.viewer-kicker{font-size:10px}.viewer-canvas{height:min(85vw,420px)}.viewer-tools>span{display:none}.cine-controls{gap:7px;padding:10px 11px 7px}.cine-range{margin:0 3px}.cine-counter{font-size:11px;min-width:55px}.viewer-bottom{font-size:10px;padding:8px 14px 11px}.assignment-row{padding:15px 0;flex-wrap:wrap;gap:10px}.assignment-row .eyebrow{font-size:11px}.assignment-help{font-size:11px;max-width:270px}.segmented button{font-size:11px;padding:7px 8px;min-width:48px}.segmented button>span{display:none}.segmented button[data-artery=exclude] span{display:block;font-size:10px}.projections-heading{margin:20px 0 12px;flex-wrap:nowrap;gap:10px}.projections-heading h2{font-size:13px}.projections-heading .button{font-size:11px;padding:8px 9px;gap:6px}.projections-heading .button svg{width:14px;height:14px}.filmstrip{grid-template-columns:repeat(4,minmax(0,1fr));gap:8px}.projection-card img{height:67px}.projection-card-bottom{font-size:9px;padding:7px 2px 4px}.projection-tag{font-size:9px}.projection-card .projection-index{font-size:9px;top:7px;left:7px}.order-controls{font-size:11px;gap:13px}.order-controls button{font-size:11px}.study-footnote,.study-footnote code{font-size:10px}.analysis-panel{display:grid;grid-template-columns:1fr;gap:17px}.result-card,.run-card{padding:21px}.result-card{order:2}.run-card{order:1}.method-card{order:3;padding:4px}.card-title{flex-wrap:nowrap}.score-number{font-size:77px}.score-area p{font-size:12px;max-width:none}.side-scores small{display:inline}.selection-counts{display:grid;grid-template-columns:repeat(3,1fr);gap:16px}.selection-counts>div{font-size:11px}.selection-counts strong{font-size:23px;margin:0}.run-hint{font-size:12px}.method-card dl>div,.method-card dd{font-size:11px}.method-card p{font-size:11px}.fold-results{margin-top:22px}.fold-results .projections-heading{flex-wrap:wrap}.fold-results .muted{font-size:11px}th{font-size:11px;padding:11px}td{font-size:12px;padding:11px}.page-footer{margin-top:25px;padding-top:16px;font-size:10px;gap:12px;flex-wrap:wrap}.page-footer>div{gap:16px}.preview-banner{font-size:10px;padding:8px 14px}}
17
+ @media(max-width:380px){.topbar{padding:0 12px;gap:7px}.brand{font-size:18px}.brand-mark{display:none}.topbar-right{gap:8px}.theme-switch button{padding:6px 7px}.language-button{padding-left:8px}.main{padding-left:14px;padding-right:14px}.sidebar{padding-left:14px;padding-right:14px}.cine-controls{gap:5px}.cine-button{width:24px}.cine-play{width:28px}.cine-counter{min-width:51px;font-size:10px}.step strong{font-size:10px}.workflow{gap:8px}.projection-card-bottom{font-size:8px}.projection-tag{font-size:9px}.projections-heading .button{font-size:10px;padding:8px}}
18
+
19
+ .projection-card-bottom,.projection-tag{font-size:11px;line-height:1.4}.projection-card-bottom{justify-content:flex-start}.projection-tag{white-space:normal;overflow-wrap:normal}.projection-card .projection-index{font-size:11px}@media(max-width:380px){.projection-card-bottom,.projection-tag{font-size:10px}.projection-card .projection-index{font-size:10px}}
20
+
21
+ .page-footer{font-size:11px}.study-footnote,.study-footnote code{font-size:11px}@media(max-width:760px){.research-tag{display:block;font-size:10px;padding:6px 8px}.heading-actions{gap:5px}.page-heading>div:first-child{min-width:0}.page-footer{font-size:11px}}
22
+
23
+ @media(min-width:761px){.page-footer>div{display:none}.page-footer{justify-content:flex-end}}
24
+
25
+ .fold-results .muted:empty{display:none}@media(max-width:760px){.research-tag{display:none}.workspace-grid>.fold-results{margin-top:0}}
26
+
27
+ .example-button{display:flex;flex-direction:column;align-items:stretch;gap:0;padding:15px 16px}.example-card-header{display:flex;align-items:center;justify-content:space-between;gap:12px}.example-card-header>svg{width:16px;height:16px;color:var(--accent);transition:transform .15s}.example-button:hover:not(:disabled) .example-card-header>svg{transform:translateX(3px)}.example-scores{display:grid;grid-template-columns:1fr 1fr;gap:18px;margin-top:16px;padding-top:13px;border-top:1px solid var(--line)}.example-score{display:flex;flex-direction:column;gap:5px}.example-score small{font-size:11px;color:var(--muted);line-height:1.4}.example-score strong{font-size:26px;line-height:1.15;font-weight:500;letter-spacing:-.6px;font-variant-numeric:tabular-nums}.example-score+ .example-score{border-left:1px solid var(--line);padding-left:18px}.example-cache-label{font-size:10px;color:var(--muted);margin-top:12px;line-height:1.4}.result-origin{display:inline-block;font-size:11px;color:var(--muted);margin-top:11px;padding:4px 7px;border:1px solid var(--line);border-radius:5px}.example-with-scores .example-detail>span{font-size:11px}@media(max-width:760px){.example-score strong{font-size:28px}.example-cache-label{font-size:11px}}
28
+
29
+ .score-number{font-size:clamp(54px,5.1vw,76px);font-variant-numeric:tabular-nums}.example-score strong,.side-scores strong,.fold-table-wrap td{font-variant-numeric:tabular-nums}@media(max-width:960px) and (min-width:761px){.score-number{font-size:58px;letter-spacing:-2.5px}}@media(max-width:760px){.score-number{font-size:72px;letter-spacing:-3px}}@media(max-width:380px){.score-number{font-size:66px}}
30
+
31
+ .cine-speed{display:flex;flex:none;gap:1px;margin-left:3px;padding:2px;border:1px solid #b8d1c524;border-radius:6px;background:#ffffff03}.cine-speed button{font-size:10px;line-height:1.2;min-width:26px;height:23px;padding:3px 5px;border:0;border-radius:3px;background:none;color:#97aaa1;font-variant-numeric:tabular-nums}.cine-speed button.selected{background:#c8dfd21a;color:#e2eee7;box-shadow:inset 0 0 0 1px #cee5d91a}.cine-speed button:hover:not(.selected){color:#e2eee7;background:#ffffff08}.cine-speed button:focus-visible{outline:2px solid #afcfbf;outline-offset:2px}@media(max-width:760px){.cine-controls{gap:5px}.cine-range{margin:0 2px}.cine-counter{min-width:51px}.cine-speed{margin-left:2px}.cine-speed button{padding:3px 4px;min-width:24px}}@media(max-width:380px){.cine-controls{gap:4px;padding-left:9px;padding-right:9px}.cine-speed button{font-size:10px;padding:3px;min-width:22px}.cine-counter{font-size:10px;min-width:48px}}
32
+
33
+ .reference-score{display:flex;align-items:center;justify-content:space-between;gap:15px;margin-top:16px;padding-top:13px;border-top:1px solid var(--line);font-size:11px;color:var(--muted)}.reference-score strong{color:var(--ink);font-size:15px;line-height:1.3;font-weight:500;font-variant-numeric:tabular-nums;letter-spacing:-.2px}
tests/test_service.py CHANGED
@@ -185,12 +185,17 @@ def test_expiry_and_unknown_ids(workspace):
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']
@@ -201,16 +206,19 @@ def test_animated_preview_and_fixed_example_loading(workspace, tmp_path, monkeyp
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):
 
185
  assert client.get('/api/status').json()['model']['loaded'] == 0
186
 
187
 
188
+ def test_animated_preview_and_fixed_example_loading(tmp_path, monkeypatch):
189
  import json
190
  import huggingface_hub
 
191
  examples = json.loads((Path(__file__).parents[1] / 'service' / 'examples.json').read_text())
192
  example = examples[0]
193
+ # This test exercises source download/GIF generation independently of bundled real caches.
194
+ example.pop('cache_file', None)
195
+ for entry in example['files']:
196
+ entry.pop('preview', None)
197
+ examples_path = tmp_path / 'examples.json'
198
+ examples_path.write_text(json.dumps([example]))
199
  paths = {}
200
  for entry in example['files']:
201
  path = tmp_path / entry['sop_uid']
 
206
  assert kwargs['repo_id'] == example['repository']
207
  return paths[kwargs['filename']]
208
  monkeypatch.setattr(huggingface_hub, 'hf_hub_download', fake_download)
209
+ engine = FakeEngine()
210
+ app = create_app(data_root=tmp_path / 'data', engine=engine, examples_path=examples_path)
211
+ with TestClient(app) as client:
212
+ assert client.get('/api/examples').json()['examples'][0]['id'] == example['id']
213
+ assert client.post('/api/examples/arbitrary-url/load').status_code == 404
214
+ job = client.post('/api/examples/' + example['id'] + '/load').json()
215
+ result = wait(client, job)
216
+ assert result['status'] == 'completed'
217
+ study = result['result']['studies'][0]
218
+ assert [p['artery'] for p in study['projections']] == [f['artery'] for f in example['files']]
219
+ gif = client.get(study['projections'][0]['animation_url'])
220
+ assert gif.status_code == 200 and gif.content.startswith(b'GIF')
221
+ assert engine.calls == []
222
 
223
 
224
  def test_disk_capacity_is_enforced(tmp_path):
tests/test_service_cache.py ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Lightweight cache integrity tests; predictions here are explicit synthetic fixtures."""
2
+ import copy
3
+ import hashlib
4
+ import io
5
+ import json
6
+ from pathlib import Path
7
+
8
+ import pydicom
9
+ import pytest
10
+ from fastapi.testclient import TestClient
11
+ from pydicom.uid import generate_uid
12
+
13
+ from service.api import create_app
14
+ from service.example_cache import read_cache
15
+ from service.storage import InputError
16
+ from test_service import FakeEngine, dicom, wait
17
+
18
+
19
+ @pytest.fixture
20
+ def cache_fixture(tmp_path, monkeypatch):
21
+ import huggingface_hub
22
+ manifest = json.loads((Path(__file__).parents[1] / 'engine' / 'manifest.json').read_text())
23
+ uid = generate_uid()
24
+ files, paths, ordered = [], {}, {'left': [], 'right': []}
25
+ for side in ('left', 'right'):
26
+ payload = dicom(uid)
27
+ ds = pydicom.dcmread(io.BytesIO(payload), stop_before_pixels=True)
28
+ name = side + '.dcm'
29
+ path = tmp_path / name
30
+ path.write_bytes(payload)
31
+ paths[name] = str(path)
32
+ files.append({'path': name, 'sop_uid': str(ds.SOPInstanceUID), 'artery': side,
33
+ 'sha256': hashlib.sha256(payload).hexdigest()})
34
+ ordered[side].append({'sop_uid': str(ds.SOPInstanceUID), 'series_uid': str(ds.SeriesInstanceUID), 'frames': 12})
35
+ left, right = [1., 2., 3., 4., 5.], [2., 3., 4., 5., 6.]
36
+ folds = [{'fold': index, 'left': l, 'right': r, 'raw': l + r,
37
+ 'calibrated': coeff['a'] * (l + r) + coeff['b'], **coeff}
38
+ for index, (l, r, coeff) in enumerate(zip(left, right, manifest['calibration']['folds']))]
39
+ result = {'raw': 7., 'calibrated': sum(f['calibrated'] for f in folds) / 5,
40
+ 'complete': True, 'study_uid': uid, 'per_fold': folds, 'projection_count': 2,
41
+ 'left': {'raw': 3., 'per_fold': left, 'projections': 1},
42
+ 'right': {'raw': 4., 'per_fold': right, 'projections': 1},
43
+ 'provenance': {'repo_id': manifest['repo_id'], 'revision': manifest['revision'],
44
+ 'weights': [{key: record[key] for key in ('path', 'sha256')}
45
+ for record in manifest['score_weights']],
46
+ 'calibration_source': {key: manifest['calibration'][key] for key in ('path', 'sha256', 'folds')},
47
+ 'ordered_inputs': ordered, 'device': 'synthetic-test'}}
48
+ example = {'id': 'synthetic', 'study_uid': uid, 'repository': 'public/test', 'revision': 'fixed-revision',
49
+ 'files': [{key: item[key] for key in ('path', 'sop_uid', 'artery')} for item in files],
50
+ 'reference_score': 0., 'cache_file': 'example_results/synthetic.json'}
51
+ payload = {'schema_version': 1, 'example_id': example['id'],
52
+ 'dataset': {'repo_id': example['repository'], 'revision': example['revision']},
53
+ 'files': files, 'result': result}
54
+ folder = tmp_path / 'example_results'; folder.mkdir()
55
+ cache_path = folder / 'synthetic.json'
56
+ cache_path.write_text(json.dumps(payload))
57
+ examples_path = tmp_path / 'examples.json'; examples_path.write_text(json.dumps([example]))
58
+ monkeypatch.setattr(huggingface_hub, 'hf_hub_download', lambda **kwargs: paths[kwargs['filename']])
59
+ return example, payload, cache_path, examples_path, paths
60
+
61
+
62
+ def test_verified_cache_load_has_result_without_inference(cache_fixture, tmp_path):
63
+ example, payload, _, examples_path, _ = cache_fixture
64
+ engine = FakeEngine()
65
+ app = create_app(data_root=tmp_path / 'uploads', engine=engine, examples_path=examples_path)
66
+ with TestClient(app) as client:
67
+ card = client.get('/api/examples').json()['examples'][0]
68
+ assert card['reference_score'] == 0. and card['cached_result_available']
69
+ assert card['prediction']['calibrated'] == payload['result']['calibrated']
70
+ loaded = wait(client, client.post('/api/examples/synthetic/load').json())
71
+ assert loaded['status'] == 'completed'
72
+ cached = loaded['result']['cached_job']
73
+ study = loaded['result']['studies'][0]
74
+ assert cached['study_id'] == study['id']
75
+ assert client.get('/api/jobs/' + cached['id']).json()['result']['calibrated'] == payload['result']['calibrated']
76
+ assert client.get('/api/studies/' + study['id']).json()['cached_result_job_id'] == cached['id']
77
+ assert cached['result']['input_assignments'] == [{'id': p['id'], 'artery': p['artery']} for p in study['projections']]
78
+ assert cached['result']['source']['type'] == 'precomputed_example'
79
+ assert 'PRIVATE' not in json.dumps(cached)
80
+ assert engine.calls == []
81
+ classify = client.post('/api/studies/' + study['id'] + '/classify').json()
82
+ assert wait(client, classify)['status'] == 'completed'
83
+ assert client.get('/api/studies/' + study['id']).json()['cached_result_job_id'] is None
84
+ assert client.delete('/api/studies/' + study['id']).status_code == 200
85
+ assert client.get('/api/jobs/' + cached['id']).status_code == 404
86
+
87
+
88
+ @pytest.mark.parametrize('change', ['model', 'weights', 'order', 'arithmetic', 'file_manifest', 'calibration', 'private_metadata'])
89
+ def test_cache_integrity_failures_never_expose_score(cache_fixture, tmp_path, change):
90
+ example, original, cache_path, examples_path, _ = cache_fixture
91
+ payload = copy.deepcopy(original)
92
+ result = payload['result']
93
+ if change == 'model': result['provenance']['revision'] = 'wrong'
94
+ elif change == 'weights': result['provenance']['weights'][0]['sha256'] = '0' * 64
95
+ elif change == 'order': result['provenance']['ordered_inputs']['left'][0]['sop_uid'] = '1.2.3'
96
+ elif change == 'arithmetic': result['calibrated'] += 1
97
+ elif change == 'file_manifest': payload['files'].reverse()
98
+ elif change == 'calibration': result['provenance']['calibration_source']['folds'][0]['a'] += 1
99
+ else: result['PatientName'] = 'must never be exposed'
100
+ cache_path.write_text(json.dumps(payload))
101
+ with pytest.raises(InputError): read_cache(example, base=examples_path.parent)
102
+ app = create_app(data_root=tmp_path / 'uploads', engine=FakeEngine(), examples_path=examples_path)
103
+ with TestClient(app) as client:
104
+ card = client.get('/api/examples').json()['examples'][0]
105
+ assert not card['cached_result_available'] and card['prediction'] is None
106
+ job = wait(client, client.post('/api/examples/synthetic/load').json())
107
+ assert job['status'] == 'failed' and job['result'] is None
108
+ assert not app.state.store.studies
109
+
110
+
111
+ def test_download_checksum_mismatch_discards_precomputed_result(cache_fixture, tmp_path):
112
+ _, _, _, examples_path, paths = cache_fixture
113
+ changed = pydicom.dcmread(paths['left.dcm'])
114
+ pixels = bytearray(changed.PixelData)
115
+ pixels[0] ^= 1
116
+ changed.PixelData = bytes(pixels)
117
+ changed.save_as(paths['left.dcm'], enforce_file_format=True)
118
+ app = create_app(data_root=tmp_path / 'uploads', engine=FakeEngine(), examples_path=examples_path)
119
+ with TestClient(app) as client:
120
+ job = wait(client, client.post('/api/examples/synthetic/load').json())
121
+ assert job['status'] == 'failed' and job['result'] is None
122
+ assert 'checksum' in job['error']
123
+ assert not app.state.store.studies and not app.state.store.workspaces
124
+
125
+
126
+ def test_missing_optional_cache_is_not_fabricated(cache_fixture, tmp_path):
127
+ example, _, _, examples_path, _ = cache_fixture
128
+ example.pop('cache_file')
129
+ examples_path.write_text(json.dumps([example]))
130
+ engine = FakeEngine()
131
+ app = create_app(data_root=tmp_path / 'uploads', engine=engine, examples_path=examples_path)
132
+ with TestClient(app) as client:
133
+ card = client.get('/api/examples').json()['examples'][0]
134
+ assert card['prediction'] is None and not card['cached_result_available']
135
+ result = wait(client, client.post('/api/examples/synthetic/load').json())
136
+ assert result['status'] == 'completed' and result['result']['cached_job'] is None
137
+ assert engine.calls == []
138
+
139
+
140
+ def test_cache_file_must_stay_in_curated_results_directory(cache_fixture):
141
+ example, _, _, examples_path, _ = cache_fixture
142
+ example['cache_file'] = '../outside.json'
143
+ with pytest.raises(InputError, match='invalid cache path'):
144
+ read_cache(example, base=examples_path.parent)
145
+
146
+
147
+ def add_packaged_previews(example, payload, examples_path, paths):
148
+ static = examples_path.parent / 'static'
149
+ destination = static / 'examples' / example['id']
150
+ destination.mkdir(parents=True)
151
+ example['vendor'] = 'Synthetic'
152
+ example['default_projection_index'] = 1
153
+ for item in example['files']:
154
+ ds = pydicom.dcmread(paths[item['path']], stop_before_pixels=True)
155
+ preview = {'frames': int(ds.NumberOfFrames), 'rows': int(ds.Rows), 'columns': int(ds.Columns),
156
+ 'series_uid': str(ds.SeriesInstanceUID)}
157
+ for kind, suffix in (('video', '.mp4'), ('poster', '.png')):
158
+ # Media decode is separately tested with real FFmpeg; here only immutable asset binding is relevant.
159
+ target = destination / (item['artery'] + suffix)
160
+ target.write_bytes(b'fixture-public-preview-' + kind.encode())
161
+ preview[kind] = target.relative_to(static).as_posix()
162
+ preview[kind + '_sha256'] = hashlib.sha256(target.read_bytes()).hexdigest()
163
+ item['preview'] = preview
164
+ examples_path.write_text(json.dumps([example]))
165
+ return static
166
+
167
+
168
+ def test_packaged_example_is_instant_and_hydrates_only_on_rerun(cache_fixture, tmp_path, monkeypatch):
169
+ import huggingface_hub
170
+ example, payload, _, examples_path, paths = cache_fixture
171
+ static = add_packaged_previews(example, payload, examples_path, paths)
172
+ downloads = []
173
+ def download(**kwargs):
174
+ downloads.append(kwargs['filename'])
175
+ return paths[kwargs['filename']]
176
+ monkeypatch.setattr(huggingface_hub, 'hf_hub_download', download)
177
+ engine = FakeEngine()
178
+ app = create_app(data_root=tmp_path / 'uploads', engine=engine, examples_path=examples_path, static_root=static)
179
+ with TestClient(app) as client:
180
+ assert client.get('/api/examples').json()['examples'][0]['vendor'] == 'Synthetic'
181
+ # A metadata-only open succeeds even when the compute queue has no free slots.
182
+ for index in range(3):
183
+ app.state.jobs.items['busy-fixture-' + str(index)] = {'status': 'running', 'updated_at': 0}
184
+ job = client.post('/api/examples/synthetic/load').json()
185
+ assert job['status'] == 'completed'
186
+ study = job['result']['studies'][0]
187
+ assert study['source_type'] == 'precomputed_example' and study['hydrated'] is False
188
+ assert study['default_projection_id'] == study['projections'][1]['id']
189
+ assert [p['artery'] for p in study['projections']] == ['left', 'right']
190
+ assert downloads == [] and engine.calls == []
191
+ assert not list(app.state.store.studies[study['id']].directory.iterdir())
192
+ for projection in study['projections']:
193
+ assert projection['video_url'].startswith('/static/examples/')
194
+ assert client.get(projection['preview_url']).status_code == 200
195
+ for index in range(3):
196
+ app.state.jobs.items.pop('busy-fixture-' + str(index))
197
+ assignments = [{'id': p['id'], 'artery': p['artery']} for p in reversed(study['projections'])]
198
+ run = client.post('/api/studies/' + study['id'] + '/run', json={'assignments': assignments}).json()
199
+ result = wait(client, run)
200
+ assert result['status'] == 'completed'
201
+ assert len(downloads) == 2 and len(engine.calls) == 1
202
+ current = client.get('/api/studies/' + study['id']).json()
203
+ assert current['hydrated'] is True
204
+ assert current['default_projection_id'] == study['default_projection_id']
205
+ assert [{'id': p['id'], 'artery': p['artery']} for p in current['projections']] == assignments
206
+ assert result['result']['input_assignments'] == assignments
207
+ assert 'source' not in result['result'] # A new model run is not labelled precomputed.
208
+
209
+
210
+ def test_lazy_hydration_rejects_changed_dicom_before_model(cache_fixture, tmp_path):
211
+ example, payload, _, examples_path, paths = cache_fixture
212
+ static = add_packaged_previews(example, payload, examples_path, paths)
213
+ changed = pydicom.dcmread(paths['left.dcm'])
214
+ pixels = bytearray(changed.PixelData); pixels[0] ^= 1
215
+ changed.PixelData = bytes(pixels)
216
+ changed.save_as(paths['left.dcm'], enforce_file_format=True)
217
+ engine = FakeEngine()
218
+ app = create_app(data_root=tmp_path / 'uploads', engine=engine, examples_path=examples_path, static_root=static)
219
+ with TestClient(app) as client:
220
+ loaded = client.post('/api/examples/synthetic/load').json()
221
+ assert loaded['status'] == 'completed'
222
+ study = loaded['result']['studies'][0]
223
+ job = client.post('/api/studies/' + study['id'] + '/run', json={}).json()
224
+ failed = wait(client, job)
225
+ assert failed['status'] == 'failed' and 'checksum' in failed['error']
226
+ assert engine.calls == []
227
+ assert not app.state.store.workspaces
228
+ assert not list(app.state.store.studies[study['id']].directory.iterdir())
229
+
230
+
231
+ def test_changed_packaged_preview_never_loads_as_verified(cache_fixture, tmp_path):
232
+ example, payload, _, examples_path, paths = cache_fixture
233
+ static = add_packaged_previews(example, payload, examples_path, paths)
234
+ (static / example['files'][0]['preview']['video']).write_bytes(b'changed')
235
+ app = create_app(data_root=tmp_path / 'uploads', engine=FakeEngine(), examples_path=examples_path, static_root=static)
236
+ with TestClient(app) as client:
237
+ job = client.post('/api/examples/synthetic/load').json()
238
+ assert job['status'] == 'failed' and 'preview checksum' in job['error']
239
+ assert not app.state.store.studies
240
+
241
+
242
+ @pytest.mark.parametrize('operation', ['run', 'classify'])
243
+ def test_hydration_and_engine_progress_count_completed_work_monotonically(cache_fixture, tmp_path, operation):
244
+ example, payload, _, examples_path, paths = cache_fixture
245
+ static = add_packaged_previews(example, payload, examples_path, paths)
246
+ engine = FakeEngine()
247
+ app = create_app(data_root=tmp_path / 'uploads', engine=engine, examples_path=examples_path, static_root=static)
248
+ snapshots = []
249
+ original_hydrate = app.state.jobs._hydrate
250
+ def current_progress():
251
+ return next(job['progress'] for job in app.state.jobs.items.values() if job['status'] == 'running')
252
+ def monitored_hydrate(study, callback):
253
+ def observed(stage, detail=None):
254
+ callback(stage, detail)
255
+ snapshots.append(('hydrate', current_progress()))
256
+ original_hydrate(study, observed)
257
+ app.state.jobs._hydrate = monitored_hydrate
258
+ engine_units = 10 if operation == 'run' else 2
259
+ original = engine.infer if operation == 'run' else engine.classify
260
+ def report_engine(callback):
261
+ # Weight downloads only update the message; they do not invent progress.
262
+ callback('download', {'message': 'Downloading verified model weights.'})
263
+ snapshots.append(('weights', current_progress()))
264
+ for current in range(1, engine_units + 1):
265
+ callback('infer' if operation == 'run' else 'classify', {'current': current, 'total': engine_units})
266
+ snapshots.append(('engine', current_progress()))
267
+ def infer(left, right, callback):
268
+ report_engine(callback)
269
+ return original(left, right, callback)
270
+ def classify(paths, callback):
271
+ report_engine(callback)
272
+ return original(paths, callback)
273
+ if operation == 'run': engine.infer = infer
274
+ else: engine.classify = classify
275
+ with TestClient(app) as client:
276
+ study = client.post('/api/examples/synthetic/load').json()['result']['studies'][0]
277
+ response = client.post('/api/studies/' + study['id'] + '/' + operation,
278
+ **({'json': {}} if operation == 'run' else {}))
279
+ finished = wait(client, response.json())
280
+ assert finished['status'] == 'completed' and finished['progress'] == 1.
281
+ values = [value for _, value in snapshots]
282
+ assert values == sorted(values)
283
+ hydration_end = [value for stage, value in snapshots if stage == 'hydrate'][-1]
284
+ assert hydration_end == pytest.approx(2 / (2 + engine_units))
285
+ assert next(value for stage, value in snapshots if stage == 'weights') == hydration_end
286
+ assert next(value for stage, value in snapshots if stage == 'engine') == pytest.approx(3 / (2 + engine_units))
287
+ if operation == 'run':
288
+ assert finished['result']['calibrated'] == 10.