Spaces:
Sleeping
Sleeping
Download service/api.py from MesserMMP/syntax-video-infer: direct link, hf CLI and curl.
- Browser
- Download file 38.6 kB
-
https://huggingface.co/spaces/MesserMMP/syntax-video-infer/resolve/main/service/api.py
- Command line
-
hf download hf://spaces/MesserMMP/syntax-video-infer/service/api.py
-
curl -L -o api.py https://huggingface.co/spaces/MesserMMP/syntax-video-infer/resolve/main/service/api.py
38.6 kB
| 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: | |
| 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() | |
| 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 | |
| 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 | |
| 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 [] | |
| 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} | |
| 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) | |
| 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 | |
| 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 | |
| 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) | |
| 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() | |
| def classify(study_id: str): | |
| return jobs.submit(get_study(study_id), 'classify') | |
| 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') | |
| 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) | |
| 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') | |
| 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) | |
| 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 | |