File size: 38,607 Bytes
1024e04
 
 
 
57ea0fa
 
 
1024e04
 
 
2ab01da
 
1024e04
 
 
 
 
 
 
57ea0fa
1024e04
57ea0fa
 
1024e04
24da0c6
1024e04
24da0c6
1024e04
24da0c6
1024e04
 
57ea0fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1024e04
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24da0c6
 
1024e04
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2ab01da
24da0c6
 
 
 
1024e04
 
 
2ab01da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1024e04
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2ab01da
 
 
 
 
1024e04
 
 
 
 
 
 
 
2ab01da
 
1024e04
2ab01da
 
 
 
1024e04
 
 
2ab01da
1024e04
 
24da0c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1024e04
24da0c6
 
 
 
 
1024e04
 
 
 
 
 
 
 
 
 
 
24da0c6
2ab01da
1024e04
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2ab01da
1024e04
 
 
 
 
 
2ab01da
57ea0fa
1024e04
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57ea0fa
 
 
1024e04
57ea0fa
 
 
 
 
 
 
1024e04
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2ab01da
1024e04
 
 
 
2ab01da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae45c4e
 
2ab01da
 
24da0c6
 
 
 
 
 
2ab01da
24da0c6
2ab01da
 
 
 
 
 
 
 
 
 
 
 
1024e04
 
 
 
 
 
2ab01da
 
 
 
 
 
 
 
 
 
 
 
1024e04
 
2ab01da
1024e04
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24da0c6
 
2ab01da
 
1024e04
 
 
 
2ab01da
1024e04
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24da0c6
 
 
 
1024e04
24da0c6
1024e04
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57ea0fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1024e04
57ea0fa
 
 
1024e04
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
from __future__ import annotations

import asyncio
import importlib
import hashlib
import mimetypes
import re
import json
import os
import secrets

import pydicom
import shutil
import tempfile
import threading
import time
from concurrent.futures import ThreadPoolExecutor
from contextlib import asynccontextmanager
from pathlib import Path
from urllib.parse import quote, unquote, urlsplit

from fastapi import FastAPI, File, HTTPException, Request, UploadFile
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, Response
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel, ConfigDict

from .example_cache import read_cache, verify_download, virtual_projections, sha256_file, classifier_provenance
from .media import cached_video
from .storage import InputError, Limits, Store, expand_zip, inspect_dicom, poster, animation, automatic_assignment


def snapshot_interface(static: Path):
    """Freeze one coherent HTML/CSS/JS release for the lifetime of this app process."""
    index = static / 'index.html'
    if not index.is_file():
        return None, {}, None
    original = index.read_text(encoding='utf-8')
    assets = {}
    pattern = re.compile(r"\b(src|href)=([\"'])(/static/[^\"']+)\2")
    def fingerprint(match):
        relative = unquote(urlsplit(match.group(3)).path[len('/static/'):])
        path = (static / relative).resolve()
        if not path.is_relative_to(static.resolve()) or not path.is_file():
            raise RuntimeError('A referenced interface asset is missing or outside the static directory.')
        content = path.read_bytes()
        digest = hashlib.sha256(content).hexdigest()
        assets[(digest, relative)] = (content, mimetypes.guess_type(relative)[0] or 'application/octet-stream')
        return f'{match.group(1)}={match.group(2)}/assets/{digest}/{quote(relative, safe="/")}{match.group(2)}'
    html = pattern.sub(fingerprint, original)
    release = hashlib.sha256((original + ''.join(digest + name for digest, name in sorted(assets))).encode()).hexdigest()
    html = html.replace('</head>', f'<meta name="cardiosyntax-release" content="{release}"></head>', 1)
    return html, assets, release


class PayloadTooLarge(HTTPException):
    def __init__(self):
        super().__init__(413, 'Upload exceeds the request size limit.')


class BodyLimitMiddleware:
    def __init__(self, app, maximum: int):
        self.app, self.maximum = app, maximum
        self.upload_slot = threading.BoundedSemaphore(1)

    async def __call__(self, scope, receive, send):
        if scope['type'] != 'http':
            return await self.app(scope, receive, send)
        is_upload = scope.get('method') == 'POST' and scope.get('path') == '/api/studies'
        if is_upload and not self.upload_slot.acquire(blocking=False):
            return await JSONResponse({'detail': 'Another upload is in progress. Please retry shortly.'}, status_code=429)(scope, receive, send)
        try:
            await self._bounded(scope, receive, send)
        finally:
            if is_upload:
                self.upload_slot.release()

    async def _bounded(self, scope, receive, send):
        headers = dict(scope.get('headers', []))
        try:
            size = int(headers.get(b'content-length', b'0'))
        except ValueError:
            size = self.maximum + 1
        if size > self.maximum:
            return await JSONResponse({'detail': 'Upload exceeds the request size limit.'}, status_code=413)(scope, receive, send)
        received = 0
        async def bounded_receive():
            nonlocal received
            message = await receive()
            received += len(message.get('body', b''))
            if received > self.maximum:
                raise PayloadTooLarge()
            return message
        try:
            await self.app(scope, bounded_receive, send)
        except PayloadTooLarge:
            await JSONResponse({'detail': 'Upload exceeds the request size limit.'}, status_code=413)(scope, receive, send)


class EngineAdapter:
    @staticmethod
    def _module():
        return importlib.import_module('engine')

    def status(self):
        return self._module().status()

    def classify(self, paths, progress):
        return self._module().classify(paths, progress=progress)

    def infer(self, left, right, progress):
        return self._module().infer(left, right, progress=progress)


class RunRequest(BaseModel):
    # Client input cannot override classifier decisions or projection order.
    model_config = ConfigDict(extra='forbid')


class Jobs:
    def __init__(self, store: Store, engine):
        self.store, self.engine = store, engine
        self.executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix='syntax-worker')
        self.items: dict[str, dict] = {}
        self.lock = threading.RLock()

    def pending(self):
        with self.lock:
            return sum(j['status'] in {'queued', 'running'} for j in self.items.values())

    def cleanup(self):
        with self.lock:
            cutoff = time.time() - self.store.limits.ttl_seconds
            self.items = {key: job for key, job in self.items.items()
                          if job['status'] in {'queued', 'running'} or job['updated_at'] > cutoff}

    def submit(self, study, kind):
        with self.store.lock, self.lock:
            if self.store.studies.get(study.id) is not study:
                raise HTTPException(404, 'Study not found or expired. Please upload it again.')
            if study.active_job:
                raise HTTPException(409, 'This study already has an active job.')
            if self.pending() >= self.store.limits.max_pending_jobs:
                raise HTTPException(429, 'The inference queue is full. Please try again shortly.')
            job_id = secrets.token_urlsafe(32)
            job = {'id': job_id, 'study_id': study.id, 'kind': kind, 'status': 'queued',
                   'progress': 0.0, 'message': 'Waiting for the inference worker.',
                   'result': None, 'error': None, 'created_at': time.time(), 'updated_at': time.time()}
            self.items[job_id] = job
            study.active_job = job_id
            study.cached_result_job_id = None
            if kind == 'classify':
                study.classification_complete = False
                study.classification_source = None
                study.classification_metadata = None
            self.executor.submit(self._execute, job_id)
            return dict(job)

    def add_cached(self, study, result):
        with self.store.lock, self.lock:
            job_id = secrets.token_urlsafe(32)
            job = {'id': job_id, 'study_id': study.id, 'kind': 'inference', 'status': 'completed',
                   'progress': 1., 'message': 'Verified precomputed example result.', 'result': result,
                   'error': None, 'created_at': time.time(), 'updated_at': time.time()}
            self.items[job_id] = job
            study.cached_result_job_id = job_id
            return dict(job)

    def completed_example(self, result=None, error=None):
        with self.lock:
            job_id = secrets.token_urlsafe(32)
            job = {'id': job_id, 'study_id': None, 'kind': 'example',
                   'status': 'failed' if error else 'completed', 'progress': 0. if error else 1.,
                   'message': error or 'Example ready.', 'result': result, 'error': error,
                   'created_at': time.time(), 'updated_at': time.time()}
            self.items[job_id] = job
            return dict(job)

    def _hydrate(self, study, progress):
        missing = [p for p in study.projections if not p.path.is_file()]
        if not missing:
            return
        from huggingface_hub import hf_hub_download
        staging = self.store.workspace('hydrate-')
        ready = []
        total = 0
        try:
            for index, projection in enumerate(missing):
                source = projection.source
                if not source:
                    raise InputError('A source DICOM is unavailable. Please upload the study again.')
                progress('download', {'fraction': index / len(missing),
                                     'message': f'Downloading verified source DICOM {index + 1} of {len(missing)}.'})
                try:
                    downloaded = Path(hf_hub_download(repo_id=source['repo_id'], repo_type='dataset',
                        revision=source['revision'], filename=source['path'], token=False))
                except Exception as exc:
                    raise InputError('The verified source DICOM could not be downloaded. Please retry.') from exc
                size = downloaded.stat().st_size
                total += size
                if size > self.store.limits.max_file_bytes or total > self.store.limits.max_request_bytes:
                    raise InputError('The source DICOM exceeds the study size limit.')
                self.store.reserve(staging, size)
                dest = staging / projection.id
                shutil.copyfile(downloaded, dest)
                if sha256_file(dest) != source['sha256']:
                    raise InputError('The source DICOM checksum did not match. No inference was run.')
                uid, metadata = inspect_dicom(dest, projection.name, self.store.limits)
                series = str(pydicom.dcmread(dest, stop_before_pixels=True, specific_tags=['SeriesInstanceUID']).get('SeriesInstanceUID', ''))
                if (uid != study.study_uid or metadata.sop_uid != projection.sop_uid
                    or (metadata.frames, metadata.rows, metadata.columns) != (projection.frames, projection.rows, projection.columns)
                    or series != source['series_uid']):
                    raise InputError('The source DICOM identifiers or dimensions did not match. No inference was run.')
                ready.append((projection, dest))
            with self.store.lock:
                self.store.capacity(total, 0, workspace=staging)
                for projection, dest in ready:
                    dest.replace(projection.path)
            progress('download', {'current': len(missing), 'total': len(missing),
                                  'message': 'Verified source DICOM ready.'})
        finally:
            self.store.remove_workspace(staging)

    def submit_example(self, loader):
        with self.lock:
            if self.pending() >= self.store.limits.max_pending_jobs:
                raise HTTPException(429, 'The inference queue is full. Please try again shortly.')
            job_id = secrets.token_urlsafe(32)
            job = {'id': job_id, 'study_id': None, 'kind': 'example', 'status': 'queued',
                   'progress': 0.0, 'message': 'Waiting to load the public example.',
                   'result': None, 'error': None, 'created_at': time.time(), 'updated_at': time.time()}
            self.items[job_id] = job
            self.executor.submit(self._execute_example, job_id, loader)
            return dict(job)

    def _execute_example(self, job_id, loader):
        with self.lock:
            job = self.items[job_id]
            job.update(status='running', message='Loading public example.', updated_at=time.time())
        def progress(fraction, message):
            with self.lock:
                job.update(progress=min(.99, float(fraction)), message=message, updated_at=time.time())
        try:
            result = loader(progress)
            with self.lock:
                job.update(status='completed', result=result, progress=1.,
                           message='Example ready.', updated_at=time.time())
        except Exception as exc:
            message = str(exc) if isinstance(exc, InputError) else 'The public example could not be downloaded. Please retry.'
            with self.lock:
                job.update(status='failed', error=message, message=message, updated_at=time.time())

    def _execute(self, job_id):
        with self.lock:
            job = self.items[job_id]
            job.update(status='running', message='Preparing model input.', updated_at=time.time())
        study = self.store.get(job['study_id'])
        hydration_units = sum(not p.path.is_file() for p in study.projections) if study else 0
        engine_units = (sum(p.frames >= 10 for p in study.projections) if job['kind'] == 'classify'
                        else 5 * sum(p.artery in {'left', 'right'} for p in study.projections)) if study else 0
        total_units = max(1, hydration_units + engine_units)
        def report_progress(stage, detail=None, *, offset=0, units=0):
            detail = detail or {}
            if not isinstance(detail, dict):
                detail = {}
            fraction = detail.get('fraction', detail.get('progress'))
            if fraction is None and detail.get('total'):
                fraction = detail.get('current', 0) / detail['total']
            with self.lock:
                if isinstance(fraction, (int, float)):
                    completed = offset + min(1., max(0., float(fraction))) * units
                    job['progress'] = max(job['progress'], min(.99, completed / total_units))
                job.update(message=detail.get('message', str(stage)), updated_at=time.time())
        def hydration_progress(stage, detail=None):
            report_progress(stage, detail, units=hydration_units)
        def progress(stage, detail=None):
            report_progress(stage, detail, offset=hydration_units, units=engine_units)
        try:
            if not study:
                raise InputError('The study has expired. Please upload it again.')
            self._hydrate(study, hydration_progress)
            if job['kind'] == 'classify':
                eligible = [p for p in study.projections if p.frames >= 10]
                outputs = self.engine.classify([str(p.path) for p in eligible], progress) if eligible else []
                if not isinstance(outputs, list) or len(outputs) != len(eligible):
                    raise InputError('Classification did not return a result for every eligible projection.')
                pending = {}
                for projection, output in zip(eligible, outputs):
                    if not isinstance(output, dict) or not output.get('path') or Path(output['path']) != projection.path:
                        raise InputError('Classification projection order mismatch.')
                    if ('probability_right' in output and 'probability' in output
                            and output['probability_right'] != output['probability']):
                        raise InputError('Classifier probability fields do not agree.')
                    artery, probability, reason = automatic_assignment(
                        projection.frames, output.get('probability_right', output.get('probability')))
                    expected_output = 'unassigned' if artery == 'exclude' else artery
                    if output.get('artery') != expected_output:
                        raise InputError('Classifier label does not match its probability.')
                    pending[projection.id] = (artery, probability, reason)
                for projection in study.projections:
                    if projection.frames < 10:
                        pending[projection.id] = automatic_assignment(projection.frames, None)
                metadata = classifier_provenance([
                    {'sop_uid': projection.sop_uid, 'frames': projection.frames,
                     'artery': pending[projection.id][0], 'probability_right': pending[projection.id][1],
                     'reason': pending[projection.id][2]} for projection in study.projections])
                # Commit only after every output has been validated; failures leave all assignments intact.
                with self.store.lock:
                    for projection in study.projections:
                        projection.artery, projection.probability, projection.reason = pending[projection.id]
                    study.classification_metadata = metadata
                    study.classification_source = 'server_classifier'
                    study.classification_complete = True
                    result = {'study': study.public()}
            else:
                left = [str(p.path) for p in study.projections if p.artery == 'left']
                right = [str(p.path) for p in study.projections if p.artery == 'right']
                result = self.engine.infer(left, right, progress)
                # Friendly stable aliases for UI consumers; do not synthesize scores.
                result = dict(result)
                result['raw_score'] = result.get('raw')
                result['calibrated_score'] = result.get('calibrated')
                result['total'] = {'raw': result.get('raw'), 'calibrated': result.get('calibrated')}
                result['study_uid'] = study.study_uid
                result['classification'] = study.classification_metadata
                result['input_assignments'] = [{'id': p.id, 'artery': p.artery} for p in study.projections]
                result['input_counts'] = {'left': len(left), 'right': len(right),
                                          'excluded': sum(p.artery == 'exclude' for p in study.projections)}
            with self.lock:
                job.update(status='completed', progress=1., message='Analysis complete.', result=result,
                           updated_at=time.time())
        except Exception as exc:
            if isinstance(exc, InputError):
                message = str(exc)
            elif isinstance(exc, (MemoryError,)) or 'out of memory' in str(exc).lower():
                message = 'Insufficient memory for this study. Use fewer projections or a larger runtime.'
            else:
                # Never disclose uploaded filesystem paths or DICOM metadata in public errors/logs.
                message = ('The model could not complete this job. Check model availability and runtime resources, '
                           'then try again. No score was produced.')
            with self.lock:
                job.update(status='failed', error=message, message=message, updated_at=time.time())
        finally:
            if study:
                with self.store.lock:
                    study.active_job = None
                    study.touched_at = time.time()


def create_app(*, data_root: Path | None = None, limits: Limits | None = None, engine=None, examples_path: Path | None = None, static_root: Path | None = None):
    limits = limits or Limits()
    root = data_root or Path(os.environ.get('SYNTAX_UPLOAD_DIR', Path(tempfile.gettempdir()) / 'cardiosyntax-uploads'))
    store = Store(root, limits)
    engine = engine or EngineAdapter()
    jobs = Jobs(store, engine)
    video_slot = threading.BoundedSemaphore(1)
    static = static_root or Path(__file__).resolve().parents[1] / 'static'
    interface_html, interface_assets, interface_release = snapshot_interface(static)

    async def clean_periodically():
        while True:
            await asyncio.sleep(60)
            await asyncio.to_thread(store.cleanup)
            jobs.cleanup()

    @asynccontextmanager
    async def lifespan(app):
        store.cleanup()
        cleaner = asyncio.create_task(clean_periodically())
        yield
        cleaner.cancel()
        try:
            await cleaner
        except asyncio.CancelledError:
            pass
        jobs.executor.shutdown(wait=False, cancel_futures=True)

    app = FastAPI(title='CardioSyntax research workspace', docs_url=None, redoc_url=None,
                  openapi_url=None, lifespan=lifespan)
    app.add_middleware(BodyLimitMiddleware, maximum=limits.max_request_bytes)
    app.state.store, app.state.jobs = store, jobs

    @app.middleware('http')
    async def private_responses(request, call_next):
        response = await call_next(request)
        path = request.url.path
        response.headers['X-Content-Type-Options'] = 'nosniff'
        if path.startswith('/api/'):
            response.headers['Cache-Control'] = 'no-store'
        elif path == '/' or (path.startswith('/assets/') and response.status_code >= 400):
            response.headers['Cache-Control'] = 'no-store, max-age=0'
            response.headers['Pragma'] = 'no-cache'
            response.headers['Expires'] = '0'
        elif path.startswith('/static/'):
            # Legacy/unversioned URLs and public cine media must revalidate after a release.
            response.headers['Cache-Control'] = 'no-cache, must-revalidate'
        return response

    @app.get('/api/status')
    def status():
        try:
            info = dict(engine.status())
        except Exception:
            info = {'device': os.environ.get('SYNTAX_DEVICE', 'cpu'),
                    'model': {'status': 'unavailable', 'loaded': 0, 'total': 10},
                    'message': 'Inference engine is unavailable.'}
        info.setdefault('model', {'repository': info.get('repo_id'), 'revision': info.get('revision'),
                                  'status': 'cached' if info.get('cached') else 'not_loaded',
                                  'loaded': 0, 'total': info.get('models', 10),
                                  'cached_files': info.get('cached_files', 0),
                                  'total_files': info.get('total_files', 11)})
        info.update(service='ready', active_job=bool(jobs.pending()),
                    limits={'max_files': limits.max_files, 'max_studies': limits.max_studies,
                            'max_request_mb': limits.max_request_bytes // (1024 * 1024),
                            'max_file_mb': limits.max_file_bytes // (1024 * 1024),
                            'retention_minutes': limits.ttl_seconds // 60})
        return info

    examples_path = examples_path or Path(__file__).with_name('examples.json')
    examples = json.loads(examples_path.read_text()) if examples_path.exists() else []

    @app.get('/api/examples')
    def list_examples():
        cards = []
        for example in examples:
            try:
                cache = read_cache(example, base=examples_path.parent)
            except InputError:
                cache = None
            cards.append({'id': example['id'], 'title': example.get('title', example.get('label', example['id'])),
                          'description': example.get('description', 'A public annotated holdout study.'),
                          'files': len(example['files']), 'reference_score': example.get('reference_score'),
                          'vendor': example.get('vendor'),
                          'cached_result_available': cache is not None,
                          'prediction': {key: cache['result'][key] for key in ('raw', 'calibrated')} if cache else None})
        return {'examples': cards}

    def example_payload(example, created, cache):
        example_id = example['id']
        index = example.get('default_projection_index', 0)
        if type(index) is not int or not 0 <= index < len(created.projections):
            raise InputError('The example default projection index is invalid.')
        created.default_projection_id = created.projections[index].id
        created.reference_score = example.get('reference_score')
        created.expert_scores = example.get('expert_scores')
        created.reference_url = example.get('reference_url')
        cached_job = None
        if cache:
            created.classification_complete = True
            created.classification_source = 'verified_cached_classifier'
            created.classification_metadata = cache['classification']
            for projection, output in zip(created.projections, cache['classification']['outputs']):
                projection.artery, projection.probability, projection.reason = (
                    output['artery'], output['probability_right'], output['reason'])
            result = cache['result']
            result['classification'] = cache['classification']
            result.update(raw_score=result['raw'], calibrated_score=result['calibrated'],
                          total={'raw': result['raw'], 'calibrated': result['calibrated']},
                          input_assignments=[{'id': p.id, 'artery': p.artery} for p in created.projections],
                          input_counts={side: sum(p.artery == side for p in created.projections)
                                        for side in ('left', 'right', 'exclude')},
                          source={'type': 'precomputed_example', 'example_id': example_id,
                                  'dataset': cache['dataset'], 'cache_sha256': cache['cache_sha256']})
            result['input_counts']['excluded'] = result['input_counts'].pop('exclude')
            created.source_type = 'precomputed_example'
            cached_job = jobs.add_cached(created, result)
        return {'studies': [created.public()], 'rejected': [], 'warnings': [],
                'example_id': example_id, 'cached_job': cached_job}

    @app.post('/api/examples/{example_id}/load')
    def load_example(example_id: str):
        example = next((x for x in examples if x['id'] == example_id), None)
        if example is None:
            raise HTTPException(404, 'Example not found.')
        try:
            cache = read_cache(example, base=examples_path.parent)
            prepared = virtual_projections(example, cache, static)
            if prepared:
                created = store.add_virtual(example['study_uid'], prepared)
                try:
                    return jobs.completed_example(example_payload(example, created, cache))
                except Exception:
                    store.delete(created.id)
                    raise
        except InputError as exc:
            return jobs.completed_example(error=str(exc))
        def loader(progress):
            from huggingface_hub import hf_hub_download
            cache = read_cache(example, base=examples_path.parent)
            staging = store.workspace('example-')
            projections = []
            created = None
            try:
                entries = example['files']
                if not 0 < len(entries) <= limits.max_files:
                    raise InputError('The example exceeds the file limit.')
                total = 0
                seen_sops = set()
                for index, item in enumerate(entries):
                    progress(index / len(entries), f"Loading example projection {index + 1} of {len(entries)}.")
                    source = hf_hub_download(
                        repo_id=example.get('repository', 'MesserMMP/coronary-angiography-syntax'),
                        repo_type='dataset', revision=example.get('revision', example.get('dataset_revision')),
                        filename=item['path'], token=False,
                    )
                    size = Path(source).stat().st_size
                    total += size
                    if size > limits.max_file_bytes or total > limits.max_request_bytes:
                        raise InputError('The example exceeds the upload size limit.')
                    dest = staging / secrets.token_hex(16)
                    store.reserve(staging, size)
                    shutil.copyfile(source, dest)
                    uid, projection = inspect_dicom(dest, Path(item['path']).name, limits)
                    if uid != example['study_uid'] or projection.sop_uid != item['sop_uid']:
                        raise InputError('The example does not match its published identifiers.')
                    if projection.sop_uid in seen_sops:
                        raise InputError('The example contains a repeated projection identifier.')
                    seen_sops.add(projection.sop_uid)
                    if cache:
                        projection.artery = cache['classification']['outputs'][index]['artery']
                    if cache:
                        verify_download(cache, index, dest, projection)
                    projections.append(projection)
                with store.lock:
                    store.capacity(total, 1, workspace=staging)
                    created = store.add(example['study_uid'], projections)
                return example_payload(example, created, cache)
            except Exception:
                if created:
                    store.delete(created.id)
                raise
            finally:
                store.remove_workspace(staging)
        return jobs.submit_example(loader)

    @app.post('/api/studies')
    async def upload(files: list[UploadFile] = File(...)):
        store.cleanup()
        if not files or len(files) > limits.max_files:
            raise HTTPException(422, f'Select between 1 and {limits.max_files} files.')
        staging = store.workspace('incoming-')
        rejected, warnings = [], []
        candidates = []
        total = 0
        expanded = 0
        created = []
        try:
            for item in files:
                name = Path((item.filename or 'unnamed.dcm').replace('\\', '/')).name[:240]
                path = staging / secrets.token_hex(16)
                count = 0
                with path.open('wb') as out:
                    while chunk := await item.read(1024 * 1024):
                        count += len(chunk)
                        total += len(chunk)
                        if count > limits.max_file_bytes or total > limits.max_request_bytes:
                            raise HTTPException(413, 'Upload exceeds the supported file or request size limit.')
                        try:
                            store.reserve(staging, len(chunk))
                        except InputError as exc:
                            raise HTTPException(507, str(exc)) from exc
                        out.write(chunk)
                if name.lower().endswith('.zip'):
                    try:
                        extracted = await asyncio.to_thread(
                            expand_zip, path, staging, limits, remaining_bytes=limits.max_request_bytes - expanded,
                            reserve=lambda size: store.reserve(staging, size))
                        candidates.extend(extracted)
                        expanded += sum(p.stat().st_size for p, _ in extracted)
                    except InputError as exc:
                        rejected.append({'name': name, 'reason': str(exc)})
                    finally:
                        path.unlink(missing_ok=True)
                        store.unreserve(staging, count)
                else:
                    expanded += count
                    if expanded > limits.max_request_bytes:
                        raise HTTPException(413, 'Combined expanded files exceed the upload size limit.')
                    candidates.append((path, name))
                if len(candidates) > limits.max_files:
                    raise HTTPException(413, f'An upload can contain at most {limits.max_files} projections.')
            grouped = {}
            seen_sops = set()
            for path, name in candidates:
                try:
                    uid, projection = await asyncio.to_thread(inspect_dicom, path, name, limits)
                    if projection.sop_uid in seen_sops:
                        raise InputError('Duplicate SOPInstanceUID in this upload; the repeated file was not added.')
                    seen_sops.add(projection.sop_uid)
                    grouped.setdefault(uid, []).append(projection)
                except InputError as exc:
                    rejected.append({'name': name, 'reason': str(exc)})
            if len(grouped) > limits.max_studies:
                raise HTTPException(422, f'Upload contains more than {limits.max_studies} studies.')
            if not grouped:
                return JSONResponse({'studies': [], 'rejected': rejected, 'warnings': warnings}, status_code=422)
            with store.lock:
                try:
                    store.capacity(sum(p.path.stat().st_size for values in grouped.values() for p in values), len(grouped), workspace=staging)
                except InputError as exc:
                    raise HTTPException(507, str(exc)) from exc
                for uid, projections in grouped.items():
                    created.append(store.add(uid, projections))
            return {'studies': [s.public() for s in created], 'rejected': rejected, 'warnings': warnings}
        except Exception:
            for study in created:
                store.delete(study.id)
            raise
        finally:
            for file in files:
                await file.close()
            store.remove_workspace(staging)

    def get_study(study_id):
        study = store.get(study_id)
        if not study:
            raise HTTPException(404, 'Study not found or expired. Please upload it again.')
        return study

    @app.get('/api/studies/{study_id}')
    def study_info(study_id: str):
        return get_study(study_id).public()

    def acquire_projection(study_id, projection_id):
        study = store.acquire(study_id)
        if not study:
            raise HTTPException(404, 'Study not found or expired. Please upload it again.')
        projection = next((p for p in study.projections if p.id == projection_id), None)
        if not projection:
            store.release(study)
            raise HTTPException(404, 'Projection not found.')
        return study, projection

    @app.get('/api/studies/{study_id}/projections/{projection_id}/preview')
    def preview(study_id: str, projection_id: str, animated: bool = False):
        study, projection = acquire_projection(study_id, projection_id)
        try:
            data = animation(projection) if animated else poster(projection)
            return Response(data, media_type='image/gif' if animated else 'image/png')
        except Exception:
            raise HTTPException(422, 'Unable to generate the image preview.') from None
        finally:
            store.release(study)

    class LeasedVideoResponse(FileResponse):
        async def __call__(self, scope, receive, send):
            try:
                await super().__call__(scope, receive, send)
            finally:
                store.release(self.leased_study)

    @app.get('/api/studies/{study_id}/projections/{projection_id}/video')
    def video(study_id: str, projection_id: str):
        study, projection = acquire_projection(study_id, projection_id)
        acquired = False
        try:
            # Limit display encoding independently of the single model worker.
            acquired = video_slot.acquire(timeout=30)
            if not acquired:
                raise HTTPException(503, 'The video encoder is busy. Please retry shortly.')
            path = cached_video(store, study, projection)
            response = LeasedVideoResponse(path, media_type='video/mp4')
            response.leased_study = study
            return response
        except HTTPException:
            store.release(study)
            raise
        except Exception as exc:
            store.release(study)
            message = str(exc) if isinstance(exc, InputError) else 'Unable to generate the complete cine preview.'
            raise HTTPException(422, message) from None
        finally:
            if acquired:
                video_slot.release()

    @app.post('/api/studies/{study_id}/classify')
    def classify(study_id: str):
        return jobs.submit(get_study(study_id), 'classify')

    @app.post('/api/studies/{study_id}/run')
    def run(study_id: str, body: RunRequest):
        study = get_study(study_id)
        with store.lock:
            if study.active_job:
                raise HTTPException(409, 'This study already has an active job.')
            if not study.classification_complete:
                raise HTTPException(409, 'Identify arteries before calculating SYNTAX. Assignments are determined by the classifier.')
            if any(p.artery not in {'left', 'right', 'exclude'} for p in study.projections):
                raise HTTPException(409, 'The server classification is incomplete. Identify arteries again.')
            if not any(p.artery in {'left', 'right'} for p in study.projections):
                raise HTTPException(422, 'No confident eligible coronary projections remain after automatic classification.')
            return jobs.submit(study, 'inference')

    @app.get('/api/jobs/{job_id}')
    def job_status(job_id: str):
        jobs.cleanup()
        with jobs.lock:
            job = jobs.items.get(job_id)
            if not job:
                raise HTTPException(404, 'Job not found or expired.')
            return dict(job)

    @app.delete('/api/studies/{study_id}')
    def remove(study_id: str):
        get_study(study_id)
        try:
            store.delete(study_id)
        except InputError as exc:
            raise HTTPException(409, str(exc)) from exc
        with jobs.lock:
            jobs.items = {key: item for key, item in jobs.items.items() if item['study_id'] != study_id}
        return {'deleted': True}

    if static.exists():
        app.mount('/static', StaticFiles(directory=static), name='static')

    @app.api_route('/assets/{digest}/{asset_path:path}', methods=['GET', 'HEAD'])
    def interface_asset(digest: str, asset_path: str, request: Request):
        asset = interface_assets.get((digest, asset_path))
        if asset is None:
            raise HTTPException(404, 'Interface asset version not found. Reload the page for the current release.')
        content, media_type = asset
        etag = f'"{digest}"'
        headers = {'Cache-Control': 'public, max-age=31536000, immutable', 'ETag': etag}
        matches = [value.strip().removeprefix('W/') for value in request.headers.get('if-none-match', '').split(',')]
        if etag in matches or '*' in matches:
            return Response(status_code=304, headers=headers)
        headers['Content-Length'] = str(len(content))
        return Response(content=b'' if request.method == 'HEAD' else content, media_type=media_type, headers=headers)

    @app.api_route('/', methods=['GET', 'HEAD'])
    def home(request: Request):
        if interface_html is None:
            return JSONResponse({'detail': 'The interface is not installed.'}, status_code=503)
        content = interface_html.encode('utf-8')
        headers = {'X-UI-Release': interface_release, 'Content-Length': str(len(content))}
        return HTMLResponse(content=b'' if request.method == 'HEAD' else content, headers=headers)

    return app