MesserMMP commited on
Commit
57ea0fa
·
verified ·
1 Parent(s): 24da0c6

Update the research workspace

Browse files

Refresh the application interface and improve loading reliability.

service/api.py CHANGED
@@ -2,6 +2,9 @@ from __future__ import annotations
2
 
3
  import asyncio
4
  import importlib
 
 
 
5
  import json
6
  import os
7
  import secrets
@@ -14,9 +17,10 @@ import time
14
  from concurrent.futures import ThreadPoolExecutor
15
  from contextlib import asynccontextmanager
16
  from pathlib import Path
 
17
 
18
- from fastapi import FastAPI, File, HTTPException, UploadFile
19
- from fastapi.responses import FileResponse, JSONResponse, Response
20
  from fastapi.staticfiles import StaticFiles
21
  from pydantic import BaseModel, ConfigDict
22
 
@@ -25,6 +29,29 @@ from .media import cached_video
25
  from .storage import InputError, Limits, Store, expand_zip, inspect_dicom, poster, animation, automatic_assignment
26
 
27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  class PayloadTooLarge(HTTPException):
29
  def __init__(self):
30
  super().__init__(413, 'Upload exceeds the request size limit.')
@@ -327,6 +354,7 @@ def create_app(*, data_root: Path | None = None, limits: Limits | None = None, e
327
  jobs = Jobs(store, engine)
328
  video_slot = threading.BoundedSemaphore(1)
329
  static = static_root or Path(__file__).resolve().parents[1] / 'static'
 
330
 
331
  async def clean_periodically():
332
  while True:
@@ -354,9 +382,17 @@ def create_app(*, data_root: Path | None = None, limits: Limits | None = None, e
354
  @app.middleware('http')
355
  async def private_responses(request, call_next):
356
  response = await call_next(request)
357
- if request.url.path.startswith('/api/'):
 
 
358
  response.headers['Cache-Control'] = 'no-store'
359
- response.headers['X-Content-Type-Options'] = 'nosniff'
 
 
 
 
 
 
360
  return response
361
 
362
  @app.get('/api/status')
@@ -677,11 +713,26 @@ def create_app(*, data_root: Path | None = None, limits: Limits | None = None, e
677
  if static.exists():
678
  app.mount('/static', StaticFiles(directory=static), name='static')
679
 
680
- @app.get('/')
681
- def home():
682
- index = static / 'index.html'
683
- if not index.exists():
 
 
 
 
 
 
 
 
 
 
 
 
 
684
  return JSONResponse({'detail': 'The interface is not installed.'}, status_code=503)
685
- return FileResponse(index)
 
 
686
 
687
  return app
 
2
 
3
  import asyncio
4
  import importlib
5
+ import hashlib
6
+ import mimetypes
7
+ import re
8
  import json
9
  import os
10
  import secrets
 
17
  from concurrent.futures import ThreadPoolExecutor
18
  from contextlib import asynccontextmanager
19
  from pathlib import Path
20
+ from urllib.parse import quote, unquote, urlsplit
21
 
22
+ from fastapi import FastAPI, File, HTTPException, Request, UploadFile
23
+ from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, Response
24
  from fastapi.staticfiles import StaticFiles
25
  from pydantic import BaseModel, ConfigDict
26
 
 
29
  from .storage import InputError, Limits, Store, expand_zip, inspect_dicom, poster, animation, automatic_assignment
30
 
31
 
32
+ def snapshot_interface(static: Path):
33
+ """Freeze one coherent HTML/CSS/JS release for the lifetime of this app process."""
34
+ index = static / 'index.html'
35
+ if not index.is_file():
36
+ return None, {}, None
37
+ original = index.read_text(encoding='utf-8')
38
+ assets = {}
39
+ pattern = re.compile(r"\b(src|href)=([\"'])(/static/[^\"']+)\2")
40
+ def fingerprint(match):
41
+ relative = unquote(urlsplit(match.group(3)).path[len('/static/'):])
42
+ path = (static / relative).resolve()
43
+ if not path.is_relative_to(static.resolve()) or not path.is_file():
44
+ raise RuntimeError('A referenced interface asset is missing or outside the static directory.')
45
+ content = path.read_bytes()
46
+ digest = hashlib.sha256(content).hexdigest()
47
+ assets[(digest, relative)] = (content, mimetypes.guess_type(relative)[0] or 'application/octet-stream')
48
+ return f'{match.group(1)}={match.group(2)}/assets/{digest}/{quote(relative, safe="/")}{match.group(2)}'
49
+ html = pattern.sub(fingerprint, original)
50
+ release = hashlib.sha256((original + ''.join(digest + name for digest, name in sorted(assets))).encode()).hexdigest()
51
+ html = html.replace('</head>', f'<meta name="cardiosyntax-release" content="{release}"></head>', 1)
52
+ return html, assets, release
53
+
54
+
55
  class PayloadTooLarge(HTTPException):
56
  def __init__(self):
57
  super().__init__(413, 'Upload exceeds the request size limit.')
 
354
  jobs = Jobs(store, engine)
355
  video_slot = threading.BoundedSemaphore(1)
356
  static = static_root or Path(__file__).resolve().parents[1] / 'static'
357
+ interface_html, interface_assets, interface_release = snapshot_interface(static)
358
 
359
  async def clean_periodically():
360
  while True:
 
382
  @app.middleware('http')
383
  async def private_responses(request, call_next):
384
  response = await call_next(request)
385
+ path = request.url.path
386
+ response.headers['X-Content-Type-Options'] = 'nosniff'
387
+ if path.startswith('/api/'):
388
  response.headers['Cache-Control'] = 'no-store'
389
+ elif path == '/' or (path.startswith('/assets/') and response.status_code >= 400):
390
+ response.headers['Cache-Control'] = 'no-store, max-age=0'
391
+ response.headers['Pragma'] = 'no-cache'
392
+ response.headers['Expires'] = '0'
393
+ elif path.startswith('/static/'):
394
+ # Legacy/unversioned URLs and public cine media must revalidate after a release.
395
+ response.headers['Cache-Control'] = 'no-cache, must-revalidate'
396
  return response
397
 
398
  @app.get('/api/status')
 
713
  if static.exists():
714
  app.mount('/static', StaticFiles(directory=static), name='static')
715
 
716
+ @app.api_route('/assets/{digest}/{asset_path:path}', methods=['GET', 'HEAD'])
717
+ def interface_asset(digest: str, asset_path: str, request: Request):
718
+ asset = interface_assets.get((digest, asset_path))
719
+ if asset is None:
720
+ raise HTTPException(404, 'Interface asset version not found. Reload the page for the current release.')
721
+ content, media_type = asset
722
+ etag = f'"{digest}"'
723
+ headers = {'Cache-Control': 'public, max-age=31536000, immutable', 'ETag': etag}
724
+ matches = [value.strip().removeprefix('W/') for value in request.headers.get('if-none-match', '').split(',')]
725
+ if etag in matches or '*' in matches:
726
+ return Response(status_code=304, headers=headers)
727
+ headers['Content-Length'] = str(len(content))
728
+ return Response(content=b'' if request.method == 'HEAD' else content, media_type=media_type, headers=headers)
729
+
730
+ @app.api_route('/', methods=['GET', 'HEAD'])
731
+ def home(request: Request):
732
+ if interface_html is None:
733
  return JSONResponse({'detail': 'The interface is not installed.'}, status_code=503)
734
+ content = interface_html.encode('utf-8')
735
+ headers = {'X-UI-Release': interface_release, 'Content-Length': str(len(content))}
736
+ return HTMLResponse(content=b'' if request.method == 'HEAD' else content, headers=headers)
737
 
738
  return app
static/app.js CHANGED
@@ -1,4 +1,28 @@
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:'Study',stepReview:'Projections',stepResult:'Results',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:'Model estimate',notCalculated:'Not calculated',resultEmpty:'Run analysis to calculate the score.',rawSideNote:'Before calibration',downloadResult:'Export JSON',readyToRun:'Study analysis',excluded:'Excluded',calculate:'Calculate SYNTAX',jobHint:'The first run downloads the model weights.',jobHintCpu:'CPU analysis can take several minutes.',methodTitle:'Model',ensemble:'Ensemble',ensembleValue:'5 folds · 10 models',calibration:'Calibration',calibrationValue:'Per fold, before averaging',device:'Compute',modelVersion:'Model revision',modelScope:'Research use only.',foldResults:'How the estimate is calculated',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:'Pending',ready:'Ready',complete:'Complete',partial:'Partial',calibratedCaption:'Final ensemble estimate',partialCaption:'Both coronary arteries are required for a study-level score.',greater22:'SYNTAX ≥ 22',notGreater22:'SYNTAX < 22',bothReady:'Both coronary arteries identified.',onlyLeft:'Only LCA was identified. The result will be partial.',onlyRight:'Only RCA was identified. The result will be partial.',noIncluded:'No usable coronary projections were identified.',shortProjection:'Fewer than 10 frames · excluded from 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.',exampleTitle:'Public examples',referenceLabel:'Expert mean',referenceSyntaxLabel:'Expert assessment',modelLabel:'Model',precomputedLabel:'Saved GPU result',exampleLoad:'Open example',exampleHint:'Published holdout studies.',loadingExample:'Loading the example',notAvailable:'Not available',deviceLocal:'Compute',atLeastOne:'Choose DICOM files or a ZIP archive.',readySubtitle:'Identify arteries, then calculate SYNTAX.',jobClassify:'Identifying arteries',jobInference:'Calculating SYNTAX',jobExample:'Loading public example',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',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}×',calibratedSyntax:'Calibrated SYNTAX',rawStudyTotal:'Before calibration',howCalculated:'How calculated',expertMeanSix:'Mean of six experts',expertMeanPublished:'Published expert mean',expertLabel:'Expert',expertContext:'For comparison only. Expert scores are not supplied to the model.',datasetAnnotation:'Dataset annotation ↗',foldDefinition:'A fold pairs LCA and RCA models trained on the same data split.',stepModelsTitle:'10 model outputs',stepModelsText:'Five LCA models and five RCA models.',stepSumsTitle:'5 study sums',stepSumsText:'Add the LCA and RCA output within each fold.',stepCalibrationTitle:'5 calibrated values',stepCalibrationText:'Apply each fold’s published a × sum + b.',stepAverageTitle:'Final estimate',stepAverageText:'Average the five calibrated values, then apply a minimum of zero.',foldLabel:'Fold',leftModel:'LCA model',rightModel:'RCA model',pairedSum:'LCA + RCA',foldFormula:'a × sum + b',foldCalibrated:'Calibrated',meanSums:'Mean LCA + RCA',meanCalibrated:'Mean after calibration',finalScore:'Final SYNTAX',beforeDisplayed:'Before calibration: {value}',beforeZeroLimit:'Before the final zero limit',finalFormula:'max(0, mean calibrated)',negativeOutputs:'Intermediate model estimates can fall below zero. This is expected; the final SYNTAX score is never negative.',roundingNote:'Intermediate values show three decimals; calculations use full precision.',fixedCalibration:'The app applies published coefficients and does not adjust them using this study’s expert scores.',calibrationSource:'Published coefficients ↗',partialCalculation:'Only the available artery outputs are shown. A study total and its calibration require both arteries.',classifiedSubtitle:'Arteries identified. Ready to calculate SYNTAX.',phaseArteries:'Arteries',phaseScore:'SYNTAX',classifierLabel:'Automatic artery identification',reasonPending:'Awaiting automatic identification.',reasonShort:'Fewer than 10 frames; excluded.',reasonUncertain:'Low classifier confidence; excluded.',reasonExcluded:'Excluded from analysis.',classificationPendingOne:'1 projection ready for artery identification.',classificationPendingMany:'{count} projections ready for artery identification.',classificationIncomplete:'Artery identification is incomplete.',noEligible:'No sequences with at least 10 frames are available.',phaseProgress:'Analysis stages',restoreTemporary:'Some studies or results are temporarily unavailable. Reload to try again.'},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 может занять несколько минут.',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',bothReady:'Обе коронарные артерии определены.',onlyLeft:'Определена только LCA. Результат будет частичным.',onlyRight:'Определена только RCA. Результат будет частичным.',noIncluded:'Подходящие коронарные проекции не найдены.',shortProjection:'Меньше 10 кадров · исключено из расчёта',copied:'StudyUID скопирован',copyFailed:'Не удалось скопировать StudyUID',deleted:'Исследование удалено',deleteConfirm:'Удалить исследование и загруженные файлы?',processing:'Обработка…',queued:'Ожидаем запуска…',failed:'Не удалось завершить операцию.',invalidResponse:'Сервис вернул неожиданный ответ.',loaded:'Исследование загружено',excludedFiles:'Файлы не добавлены',noStudies:'Подходящие исследования не найдены.',previewLabel:'Макет интерфейса · реальные публичные DICOM, без предсказания модели',previewHint:'Это макет интерфейса. Откройте рабочее пространство для загрузки и расчёта.',exampleTitle:'Публичные примеры',referenceLabel:'Среднее экспертов',referenceSyntaxLabel:'Оценка экспертов',modelLabel:'Модель',precomputedLabel:'Сохранённый расчёт на GPU',exampleLoad:'Открыть пример',exampleHint:'Исследования из опубликованных holdout.',loadingExample:'Загружаем пример',notAvailable:'Недоступно',deviceLocal:'Вычисления',atLeastOne:'Выберите DICOM-файлы или ZIP-архив.',readySubtitle:'Определите артерии, затем рассчитайте SYNTAX.',jobClassify:'Определяем артерии',jobInference:'Рассчитываем SYNTAX',jobExample:'Загружаем публичный пример',confirmDeleteTitle:'Удалить исследование?',dialogCancel:'Отмена',dialogContinue:'Продолжить',modelPreparing:'Подготовка ансамбля',downloadFailed:'Результат пока недоступен.',close:'Закрыть',expand:'Увеличить превью',copyUid:'Копировать StudyUID',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}×',calibratedSyntax:'Калиброванный SYNTAX',rawStudyTotal:'До калибровки',howCalculated:'Как получен результат',expertMeanSix:'Среднее шести экспертов',expertMeanPublished:'Опубликованное среднее экспертов',expertLabel:'Эксперт',expertContext:'Только для сравнения. Оценки экспертов не передаются модели.',datasetAnnotation:'Разметка датасета ↗',foldDefinition:'Фолд — пара моделей LCA и RCA, обученных на одном разбиении данных.',stepModelsTitle:'10 выходов моделей',stepModelsText:'Пять моделей LCA и пять моделей RCA.',stepSumsTitle:'5 сумм исследования',stepSumsText:'В каждом фолде складываем выходы LCA и RCA.',stepCalibrationTitle:'5 калиброванных значений',stepCalibrationText:'Применяем опубликованные a × сумма + b каждого фолда.',stepAverageTitle:'Итоговая оценка',stepAverageText:'Усредняем пять калиброванных значений и ограничиваем итог снизу нулём.',foldLabel:'Фолд',leftModel:'Модель LCA',rightModel:'Модель RCA',pairedSum:'LCA + RCA',foldFormula:'a × сумма + b',foldCalibrated:'После калибровки',meanSums:'Средняя сумма LCA + RCA',meanCalibrated:'Среднее после калибровки',finalScore:'Итоговый SYNTAX',beforeDisplayed:'До калибровки: {value}',beforeZeroLimit:'До ограничения итога снизу нулём',finalFormula:'max(0, среднее после калибровки)',negativeOutputs:'Промежуточные оценки моделей могут быть ниже нуля. Это не ошибка расчёта; итоговый SYNTAX неотрицателен.',roundingNote:'Промежуточные значения показаны с тремя знаками; расчёт использует полную точность.',fixedCalibration:'Приложение использует опубликованные коэффициенты и не подстраивает их под оценки этого исследования.',calibrationSource:'Опубликованные коэффициенты ↗',partialCalculation:'Показаны выходы моделей доступной артерии. Для общей суммы и её калибровки нужны обе артерии.',classifiedSubtitle:'Артерии определены. Можно рассчитать SYNTAX.',phaseArteries:'Артерии',phaseScore:'SYNTAX',classifierLabel:'Автоматическое определение артерии',reasonPending:'Ожидает автоматического определения.',reasonShort:'Менее 10 кадров; исключено.',reasonUncertain:'Низкая уверенность классификатора; исключено.',reasonExcluded:'Исключено из анализа.',classificationPendingOne:'1 проекция готова к определению артерии.',classificationPendingMany:'Проекций для определения артерий: {count}.',classificationIncomplete:'Определение артерий не завершено.',noEligible:'Нет последовательностей длиной не менее 10 кадров.',phaseProgress:'Этапы анализа',restoreTemporary:'Некоторые исследования или результаты временно недоступны. Перезагрузите страницу, чтобы повторить попытку.'}};
4
  const safeStored=(key,fallback)=>{try{return localStorage.getItem(key)||fallback;}catch{return fallback;}};
@@ -12,21 +36,22 @@ const currentStudy=()=>studies.find(x=>x.id===selectedStudyId);
12
  const currentProjection=()=>currentStudy()?.projections.find(x=>x.id===selectedProjectionId);
13
  function el(tag,cls,text){const n=document.createElement(tag);if(cls)n.className=cls;if(text!==undefined)n.textContent=text;return n;}
14
  function setStored(key,value){try{localStorage.setItem(key,value);}catch{}}
15
- 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'));$('classification-readout').setAttribute('aria-label',t('classifierLabel'));$('pipeline-steps').setAttribute('aria-label',t('phaseProgress'));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;}}}
16
  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);}
17
- function showError(message){$('notice-text').textContent=message;$('notice').hidden=false;}
18
- function hideError(){$('notice').hidden=true;}
19
- function toast(message){const old=document.querySelector('.toast');old?.remove();const n=el('div','toast',message);n.setAttribute('role','status');document.body.append(n);setTimeout(()=>n.remove(),2800);}
20
  function errorText(e){if(typeof e==='string')return localizeError(e);if(Array.isArray(e))return e.map(x=>errorText(x.msg||x.reason||x)).join('\n');if(e?.rejected?.length)return t('excludedFiles')+'\n'+e.rejected.map(x=>`${x.name}: ${localizeError(x.reason)}`).join('\n');if(e?.message||e?.detail)return errorText(e.message||e.detail);return t('failed');}
21
  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;}
22
  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;}
23
- async function refreshStatus(){if(previewMode)return;try{status=await request('/api/status');}catch{status=null;}statusChecked=true;renderStatus();}
24
- 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');$('server-indicator').title=$('server-label').textContent;$('server-indicator').setAttribute('aria-label',$('server-label').textContent);return;}if(!status){$('server-label').textContent=t(statusChecked?'offline':'connecting');dot.className='status-dot'+(statusChecked?' error':'');$('server-indicator').title=$('server-label').textContent;$('server-indicator').setAttribute('aria-label',$('server-label').textContent);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;$('server-indicator').title=`${device} · ${t(key)}`;$('server-indicator').setAttribute('aria-label',`${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':'файла'}`;}
25
  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'):'');}
26
  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);});}
27
  function defaultProjection(study){return study?.projections.find(p=>p.id===study.default_projection_id)?.id||study?.projections[0]?.id||null;}
28
  function selectStudy(id){unresolvedSelection=null;selectedStudyId=id;selectedProjectionId=defaultProjection(currentStudy());workflowView=currentStudy()?'projections':'study';render();}
29
  function render(){
 
30
  const s=currentStudy();
31
  if(!s)workflowView='study';
32
  if(workflowView==='results'&&!resultByStudy.has(s?.id))workflowView='projections';
@@ -43,7 +68,7 @@ function render(){
43
  if(!s.projections.some(x=>x.id===selectedProjectionId))selectedProjectionId=defaultProjection(s);
44
  renderProjection();renderFilmstrip();renderCounts();renderResult();
45
  }
46
- function renderWorkflow(){
47
  const study=currentStudy(),result=resultByStudy.get(study?.id);
48
  const reviewed=classificationComplete(study);
49
  const states={study:{enabled:!busy,done:!!study},projections:{enabled:!!study,done:reviewed},results:{enabled:!!result,done:!!result&&result.complete!==false}};
@@ -54,7 +79,7 @@ function renderWorkflow(){
54
  if(current)button.setAttribute('aria-current','step');else button.removeAttribute('aria-current');
55
  });
56
  }
57
- function navigateWorkflow(view){
58
  const study=currentStudy();
59
  if(!['study','projections','results'].includes(view)||(view==='study'&&busy)||(view!=='study'&&!study)||(view==='results'&&!resultByStudy.has(study?.id)))return;
60
  workflowScrollUntil=performance.now()+800;
@@ -63,7 +88,7 @@ function navigateWorkflow(view){
63
  target.focus({preventScroll:true});
64
  target.scrollIntoView({behavior:window.matchMedia('(prefers-reduced-motion: reduce)').matches?'auto':'smooth',block:'start'});
65
  }
66
- function markWorkflow(view){
67
  if(workflowView==='study'||workflowView===view||(view==='results'&&!resultByStudy.has(selectedStudyId)))return;
68
  workflowView=view;renderWorkflow();persistWorkspace();
69
  }
@@ -88,7 +113,7 @@ function studyAction(study){
88
  const eligible=(study?.projections||[]).filter(projection=>projection.frames>=10).length;
89
  return{complete,counts,eligible,kind:complete?'inference':'classify',allowed:complete?counts.unassigned===0&&(counts.left+counts.right)>0:eligible>0};
90
  }
91
- function renderProjection(){
92
  const projection=currentProjection();$('viewer-image').hidden=!projection;$('viewer-empty').hidden=!!projection;if(!projection)return;
93
  const video=$('viewer-image'),src=projection.video_url||'';video.dataset.frames=String(projection.frames);video.poster=projection.preview_url;
94
  if(video.dataset.current!==src){video.src=src;video.dataset.current=src;video.load();}
@@ -99,7 +124,7 @@ function renderProjection(){
99
  $('classification-label').textContent=labelFor(label);$('classification-label').className='classification-badge '+label;
100
  const reason=projectionReason(projection);$('classification-reason').textContent=reason;$('classification-reason').hidden=!reason;
101
  }
102
- function renderFilmstrip(){
103
  const strip=$('filmstrip');strip.replaceChildren();
104
  currentStudy().projections.forEach((projection,index)=>{const label=projectionLabel(projection),button=el('button','projection-card'+(projection.id===selectedProjectionId?' selected':''));
105
  button.setAttribute('aria-label',`${index+1}. ${projection.name}. ${labelFor(label)}`);button.setAttribute('aria-pressed',String(projection.id===selectedProjectionId));
@@ -109,7 +134,7 @@ function renderFilmstrip(){
109
  button.addEventListener('click',()=>{selectedProjectionId=projection.id;renderProjection();renderFilmstrip();});strip.append(button);
110
  });
111
  }
112
- function renderCounts(){
113
  const study=currentStudy(),action=studyAction(study),{counts}=action,hasResult=resultByStudy.has(study.id),running=busy&&(activeJob?.kind||action.kind);
114
  $('left-count').textContent=action.complete?counts.left:'—';$('right-count').textContent=action.complete?counts.right:'—';$('excluded-count').textContent=counts.exclude;
115
  let hint;if(!action.complete)hint=!action.eligible?t('noEligible'):t(action.eligible===1?'classificationPendingOne':'classificationPendingMany').replace('{count}',String(action.eligible));
@@ -170,29 +195,29 @@ function renderResult(){
170
  }
171
  function resultMatchesStudy(result,study){if(!result||!classificationComplete(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);}
172
  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);}
173
- 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(()=>{});}
174
- 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();}}
175
 
176
  async function confirmAction(){const dialog=$('confirm-dialog');if(dialog.open)return false;const previousFocus=document.activeElement;$('confirm-title').textContent=t('confirmDeleteTitle');$('confirm-message').textContent=t('deleteConfirm');$('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();});}
177
 
178
  async function startJob(){
179
- if(busy)return;if(previewMode){showError(t('previewHint'));return;}const study=currentStudy();if(!study)return;
180
  const action=studyAction(study);if(!action.allowed)return;const kind=action.kind;
181
  hideError();busy=true;render();$('job-status').hidden=false;$('job-message').textContent=t('queued');$('job-percentage').textContent='';$('job-progress').value=0;
182
  try{const options={method:'POST'};if(kind==='inference'){options.headers={'Content-Type':'application/json'};options.body='{}';}
183
  const job=await request(`/api/studies/${study.id}/${kind==='classify'?'classify':'run'}`,options);activeJob={...job,study_id:study.id};persistWorkspace();renderCounts();pollJob();
184
  }catch(error){finishJob();showError(error.message);}
185
  }
186
- function finishJob(){busy=false;activeJob=null;clearTimeout(pollTimer);$('job-status').hidden=true;$('upload-overlay').hidden=true;render();refreshStatus();}
187
- 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){studies[index]=updated;if(selectedStudyId===updated.id&&!updated.projections.some(p=>p.id===selectedProjectionId))selectedProjectionId=defaultProjection(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);}}}
188
  let examples=[];
189
  function referenceNumber(value){return value.toFixed(2);}
190
- 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('expertMeanSix')),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')));}
191
- async function loadExamples(){if(previewMode)return;try{const d=await request('/api/examples');examples=d.examples||[];renderExamples();}catch{}}
192
- 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);}}
193
  let expandedPlayback=null;
194
- 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();}
195
- 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;}
196
  const cinePlayers=[];let cinePlaybackRate=1;
197
  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);}}
198
  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','loadeddata','durationchange','timeupdate','play','pause','seeking','seeked','emptied','error','ratechange'])video.addEventListener(event,()=>updateCine(player));if(video.id==='viewer-image')video.addEventListener('loadedmetadata',()=>{const frames=Number(video.dataset.frames);if(frames>0&&Number.isFinite(video.duration)&&video.duration>0&&video.currentTime===0&&!video.seeking)video.currentTime=Math.min(.001,video.duration/frames/2);});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);}
@@ -200,16 +225,17 @@ function cineFrame(player){const {video}=player,frames=Number(video.dataset.fram
200
  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);}
201
  function stepCine(player,delta){player.video.pause();seekCine(player,cineFrame(player)+delta);}
202
  function toggleCine(player){if(player.video.paused)player.video.play().catch(()=>{});else player.video.pause();}
203
- 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%');if(video.readyState>=2&&!video.seeking)range.setAttribute('aria-valuetext',t('framePosition').replace('{frame}',String(frame+1)).replace('{total}',String(frames)));else range.removeAttribute('aria-valuetext');const visibleFrame=video.readyState>=2&&!video.seeking;counter.textContent=frames?`${visibleFrame?String(frame+1).padStart(2,'0'):'—'} / ${frames}`:'— / —';play.disabled=!ready;previous.disabled=!ready||frame===0;next.disabled=!ready||frame>=frames-1;range.disabled=!ready;}
204
  document.querySelectorAll('[data-workflow]').forEach(button=>button.addEventListener('click',()=>navigateWorkflow(button.dataset.workflow)));
205
  $('projections-panel').addEventListener('focusin',()=>markWorkflow('projections'));
206
  for(const id of ['result-card','fold-results'])$(id).addEventListener('focusin',()=>markWorkflow('results'));
207
  $('calculation-link').addEventListener('click',event=>{event.preventDefault();markWorkflow('results');$('fold-results').focus({preventScroll:true});$('fold-results').scrollIntoView({behavior:window.matchMedia('(prefers-reduced-motion: reduce)').matches?'auto':'smooth',block:'start'});});
208
  let workflowScrollFrame=null;
209
  window.addEventListener('scroll',()=>{
210
- if(workflowScrollFrame)return;
211
  workflowScrollFrame=requestAnimationFrame(()=>{
212
  workflowScrollFrame=null;
 
213
  if(performance.now()<workflowScrollUntil||workflowView==='study'||!resultByStudy.has(selectedStudyId))return;
214
  const edge=document.querySelector('.topbar').getBoundingClientRect().bottom+60;
215
  if($('fold-results').getBoundingClientRect().top<=edge)markWorkflow('results');
@@ -221,8 +247,8 @@ window.addEventListener('scroll',()=>{
221
  });
222
  },{passive:true});
223
  $('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)));
224
- $('sidebar-upload').addEventListener('click',()=>{if(busy)return;hideError();navigateWorkflow('study');});$('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);
225
- $('run-button').addEventListener('click',startJob);$('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;});
226
  $('copy-uid').addEventListener('click',async()=>{try{await navigator.clipboard.writeText(currentStudy()?.study_uid||'');toast(t('copied'));}catch{toast(t('copyFailed'));}});
227
  $('remove-study').addEventListener('click',async()=>{if(busy||!currentStudy()||!await confirmAction())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);forgetStudyRecovery(id);resultByStudy.delete(id);resultJobByStudy.delete(id);selectStudy(studies[0]?.id||null);});
228
  $('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);});
@@ -273,6 +299,7 @@ async function restoreWorkspace(){
273
  selectedProjectionId=defaultProjection(currentStudy());
274
  workflowView=completedExampleStudyId?'projections':['study','projections','results'].includes(saved.workflow_view)?saved.workflow_view:currentStudy()?'projections':'study';
275
  workspaceRestored=true;
 
276
  if(activeJob){busy=true;$('job-status').hidden=false;if(activeJob.kind==='example')$('upload-overlay').hidden=false;pollJob();}
277
  render();
278
  if(unresolvedStudyIds.size||unresolvedResultJobs.size||deferredJobs.size)showError(t('restoreTemporary'));
@@ -282,8 +309,10 @@ function localizeStage(message){if(!message||lang==='en')return message;const in
282
 
283
  window.addEventListener('beforeunload',()=>clearTimeout(pollTimer));
284
  const mobileLayout=window.matchMedia('(max-width: 760px)');
285
- function placeFoldResults(){const workspace=$('workspace-grid'),fold=$('fold-results'),action=$('run-card'),rail=document.querySelector('.analysis-panel');if(fold.parentElement!==workspace)workspace.append(fold);const destination=mobileLayout.matches?workspace:rail;if(action.parentElement!==destination||destination.firstElementChild!==action)destination.prepend(action);}
286
  mobileLayout.addEventListener('change',placeFoldResults);
287
 
288
- 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();}
289
- init();
 
 
 
1
  'use strict';
2
+ const UI_REVISION='classifier-workflow-4';
3
+ const REQUIRED_UI_IDS=["calculation-flow","calculation-link","calculation-partial","calculation-summary","calibration-source","classification-label","classification-readout","classification-reason","close-notice","close-preview","confirm-cancel","confirm-continue","confirm-dialog","confirm-message","confirm-title","copy-uid","dialog-image","dialog-name","download-result","dropzone","examples-box","excluded-count","expand-preview","expert-mean-caption","expert-scores","file-input","filmstrip","final-total-number","fold-results","fold-table-body","job-hint","job-message","job-percentage","job-progress","job-status","language-button","left-count","mean-calibrated-number","mean-raw-number","method-device","model-revision","negative-output-note","notice","notice-text","overlay-progress","page-subtitle","page-title","pipeline-arteries","pipeline-position","pipeline-score","pipeline-steps","preview-banner","preview-dialog","projection-count","projections-panel","raw-total-caption","raw-total-number","reference-score","reference-score-value","reference-source","remove-study","result-card","result-details","result-origin","result-state","right-count","run-button","run-button-arrow","run-button-label","run-button-spinner","run-card","run-hint","score-caption","score-number","server-indicator","server-label","sidebar-upload","study-count","study-list","study-uid","upload-hint","upload-limits","upload-overlay","upload-title","viewer-artery","viewer-canvas","viewer-dimensions","viewer-empty","viewer-image","viewer-name","viewer-position","welcome","workspace-grid"];
4
+ const REQUIRED_UI_SELECTORS=['.analysis-panel','.welcome-aside','.topbar','.workflow','.theme-switch','#server-indicator .status-dot'];
5
+ let interfaceRecoveryActive=false;
6
+ function interfaceCompatible(){return document.documentElement.dataset.uiVersion===UI_REVISION&&REQUIRED_UI_IDS.every(id=>document.getElementById(id))&&REQUIRED_UI_SELECTORS.every(selector=>document.querySelector(selector));}
7
+ function recoveryLanguage(){try{return localStorage.getItem('cardiosyntax-language')==='ru'?'ru':'en';}catch{return document.documentElement.lang==='ru'?'ru':'en';}}
8
+ function showInterfaceRecovery(allowAutomatic=true){
9
+ if(interfaceRecoveryActive)return;interfaceRecoveryActive=true;
10
+ const russian=recoveryLanguage()==='ru',url=new URL(location.href),key='cardiosyntax-ui-refresh';
11
+ let attempted=url.searchParams.get('ui_refresh')===UI_REVISION;
12
+ try{attempted=attempted||sessionStorage.getItem(key)===UI_REVISION;}catch{}
13
+ const automatic=allowAutomatic&&!attempted;
14
+ const shell=document.createElement('main'),panel=document.createElement('section'),title=document.createElement('h1'),message=document.createElement('p');
15
+ shell.className='interface-recovery';shell.setAttribute('role','status');shell.style.cssText='min-height:100vh;display:grid;place-items:center;padding:28px;box-sizing:border-box;background:#f3f6f2;color:#1d3430;font-family:system-ui,sans-serif';
16
+ panel.style.cssText='width:min(420px,100%);box-sizing:border-box;padding:28px;border:1px solid #d9e3dc;border-radius:14px;background:#fff';
17
+ title.style.cssText='font-size:22px;font-weight:600;line-height:1.3;margin:0 0 14px';message.style.cssText='font-size:14px;line-height:1.65;color:#62736b;margin:0';
18
+ title.textContent=russian?(automatic?'Обновляем интерфейс…':'Обновите интерфейс'):(automatic?'Refreshing the workspace…':'Refresh the workspace');
19
+ message.textContent=russian?'Страница загрузилась не полностью. Ссылки на ваши исследования сохранены.':'This page did not load completely. Your saved study links are preserved.';
20
+ panel.append(title,message);shell.append(panel);document.body.replaceChildren(shell);
21
+ const refresh=()=>{const target=new URL(location.href);target.searchParams.set('ui_refresh',UI_REVISION);target.searchParams.set('ui_reload',String(Date.now()));location.replace(target.href);};
22
+ if(automatic){try{sessionStorage.setItem(key,UI_REVISION);}catch{}refresh();return;}
23
+ const button=document.createElement('button');button.type='button';button.textContent=russian?'Перезагрузить':'Reload';button.style.cssText='margin-top:22px;padding:11px 18px;border:0;border-radius:7px;background:#196657;color:white;font:600 13px system-ui;cursor:pointer';button.addEventListener('click',refresh);panel.append(button);button.focus();
24
+ }
25
+ function startCardioSyntax(){
26
  const $=id=>document.getElementById(id);
27
  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:'Study',stepReview:'Projections',stepResult:'Results',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:'Model estimate',notCalculated:'Not calculated',resultEmpty:'Run analysis to calculate the score.',rawSideNote:'Before calibration',downloadResult:'Export JSON',readyToRun:'Study analysis',excluded:'Excluded',calculate:'Calculate SYNTAX',jobHint:'The first run downloads the model weights.',jobHintCpu:'CPU analysis can take several minutes.',methodTitle:'Model',ensemble:'Ensemble',ensembleValue:'5 folds · 10 models',calibration:'Calibration',calibrationValue:'Per fold, before averaging',device:'Compute',modelVersion:'Model revision',modelScope:'Research use only.',foldResults:'How the estimate is calculated',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:'Pending',ready:'Ready',complete:'Complete',partial:'Partial',calibratedCaption:'Final ensemble estimate',partialCaption:'Both coronary arteries are required for a study-level score.',greater22:'SYNTAX ≥ 22',notGreater22:'SYNTAX < 22',bothReady:'Both coronary arteries identified.',onlyLeft:'Only LCA was identified. The result will be partial.',onlyRight:'Only RCA was identified. The result will be partial.',noIncluded:'No usable coronary projections were identified.',shortProjection:'Fewer than 10 frames · excluded from 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.',exampleTitle:'Public examples',referenceLabel:'Expert mean',referenceSyntaxLabel:'Expert assessment',modelLabel:'Model',precomputedLabel:'Saved GPU result',exampleLoad:'Open example',exampleHint:'Published holdout studies.',loadingExample:'Loading the example',notAvailable:'Not available',deviceLocal:'Compute',atLeastOne:'Choose DICOM files or a ZIP archive.',readySubtitle:'Identify arteries, then calculate SYNTAX.',jobClassify:'Identifying arteries',jobInference:'Calculating SYNTAX',jobExample:'Loading public example',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',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}×',calibratedSyntax:'Calibrated SYNTAX',rawStudyTotal:'Before calibration',howCalculated:'How calculated',expertMeanSix:'Mean of six experts',expertMeanPublished:'Published expert mean',expertLabel:'Expert',expertContext:'For comparison only. Expert scores are not supplied to the model.',datasetAnnotation:'Dataset annotation ↗',foldDefinition:'A fold pairs LCA and RCA models trained on the same data split.',stepModelsTitle:'10 model outputs',stepModelsText:'Five LCA models and five RCA models.',stepSumsTitle:'5 study sums',stepSumsText:'Add the LCA and RCA output within each fold.',stepCalibrationTitle:'5 calibrated values',stepCalibrationText:'Apply each fold’s published a × sum + b.',stepAverageTitle:'Final estimate',stepAverageText:'Average the five calibrated values, then apply a minimum of zero.',foldLabel:'Fold',leftModel:'LCA model',rightModel:'RCA model',pairedSum:'LCA + RCA',foldFormula:'a × sum + b',foldCalibrated:'Calibrated',meanSums:'Mean LCA + RCA',meanCalibrated:'Mean after calibration',finalScore:'Final SYNTAX',beforeDisplayed:'Before calibration: {value}',beforeZeroLimit:'Before the final zero limit',finalFormula:'max(0, mean calibrated)',negativeOutputs:'Intermediate model estimates can fall below zero. This is expected; the final SYNTAX score is never negative.',roundingNote:'Intermediate values show three decimals; calculations use full precision.',fixedCalibration:'The app applies published coefficients and does not adjust them using this study’s expert scores.',calibrationSource:'Published coefficients ↗',partialCalculation:'Only the available artery outputs are shown. A study total and its calibration require both arteries.',classifiedSubtitle:'Arteries identified. Ready to calculate SYNTAX.',phaseArteries:'Arteries',phaseScore:'SYNTAX',classifierLabel:'Automatic artery identification',reasonPending:'Awaiting automatic identification.',reasonShort:'Fewer than 10 frames; excluded.',reasonUncertain:'Low classifier confidence; excluded.',reasonExcluded:'Excluded from analysis.',classificationPendingOne:'1 projection ready for artery identification.',classificationPendingMany:'{count} projections ready for artery identification.',classificationIncomplete:'Artery identification is incomplete.',noEligible:'No sequences with at least 10 frames are available.',phaseProgress:'Analysis stages',restoreTemporary:'Some studies or results are temporarily unavailable. Reload to try again.'},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 может занять несколько минут.',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',bothReady:'Обе коронарные артерии определены.',onlyLeft:'Определена только LCA. Результат будет частичным.',onlyRight:'Определена только RCA. Результат будет частичным.',noIncluded:'Подходящие коронарные проекции не найдены.',shortProjection:'Меньше 10 кадров · исключено из расчёта',copied:'StudyUID скопирован',copyFailed:'Не удалось скопировать StudyUID',deleted:'Исследование удалено',deleteConfirm:'Удалить исследование и загруженные файлы?',processing:'Обработка…',queued:'Ожидаем запуска…',failed:'Не удалось завершить операцию.',invalidResponse:'Сервис вернул неожиданный ответ.',loaded:'Исследование загружено',excludedFiles:'Файлы не добавлены',noStudies:'Подходящие исследования не найдены.',previewLabel:'Макет интерфейса · реальные публичные DICOM, без предсказания модели',previewHint:'Это макет интерфейса. Откройте рабочее пространство для загрузки и расчёта.',exampleTitle:'Публичные примеры',referenceLabel:'Среднее экспертов',referenceSyntaxLabel:'Оценка экспертов',modelLabel:'Модель',precomputedLabel:'Сохранённый расчёт на GPU',exampleLoad:'Открыть пример',exampleHint:'Исследования из опубликованных holdout.',loadingExample:'Загружаем пример',notAvailable:'Недоступно',deviceLocal:'Вычисления',atLeastOne:'Выберите DICOM-файлы или ZIP-архив.',readySubtitle:'Определите артерии, затем рассчитайте SYNTAX.',jobClassify:'Определяем артерии',jobInference:'Рассчитываем SYNTAX',jobExample:'Загружаем публичный пример',confirmDeleteTitle:'Удалить исследование?',dialogCancel:'Отмена',dialogContinue:'Продолжить',modelPreparing:'Подготовка ансамбля',downloadFailed:'Результат пока недоступен.',close:'Закрыть',expand:'Увеличить превью',copyUid:'Копировать StudyUID',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}×',calibratedSyntax:'Калиброванный SYNTAX',rawStudyTotal:'До калибровки',howCalculated:'Как получен результат',expertMeanSix:'Среднее шести экспертов',expertMeanPublished:'Опубликованное среднее экспертов',expertLabel:'Эксперт',expertContext:'Только для сравнения. Оценки экспертов не передаются модели.',datasetAnnotation:'Разметка датасета ↗',foldDefinition:'Фолд — пара моделей LCA и RCA, обученных на одном разбиении данных.',stepModelsTitle:'10 выходов моделей',stepModelsText:'Пять моделей LCA и пять моделей RCA.',stepSumsTitle:'5 сумм исследования',stepSumsText:'В каждом фолде складываем выходы LCA и RCA.',stepCalibrationTitle:'5 калиброванных значений',stepCalibrationText:'Применяем опубликованные a × сумма + b каждого фолда.',stepAverageTitle:'Итоговая оценка',stepAverageText:'Усредняем пять калиброванных значений и ограничиваем итог снизу нулём.',foldLabel:'Фолд',leftModel:'Модель LCA',rightModel:'Модель RCA',pairedSum:'LCA + RCA',foldFormula:'a × сумма + b',foldCalibrated:'После калибровки',meanSums:'Средняя сумма LCA + RCA',meanCalibrated:'Среднее после калибровки',finalScore:'Итоговый SYNTAX',beforeDisplayed:'До калибровки: {value}',beforeZeroLimit:'До ограничения итога снизу нулём',finalFormula:'max(0, среднее после калибровки)',negativeOutputs:'Промежуточные оценки моделей могут быть ниже нуля. Это не ошибка расчёта; итоговый SYNTAX неотрицателен.',roundingNote:'Промежуточные значения показаны с тремя знаками; расчёт использует полную точность.',fixedCalibration:'Приложение использует опубликованные коэффициенты и не подстраивает их под оценки этого исследования.',calibrationSource:'Опубликованные коэффициенты ↗',partialCalculation:'Показаны выходы моделей доступной артерии. Для общей суммы и её калибровки нужны обе артерии.',classifiedSubtitle:'Артерии определены. Можно рассчитать SYNTAX.',phaseArteries:'Артерии',phaseScore:'SYNTAX',classifierLabel:'Автоматическое определение артерии',reasonPending:'Ожидает автоматического определения.',reasonShort:'Менее 10 кадров; исключено.',reasonUncertain:'Низкая уверенность классификатора; исключено.',reasonExcluded:'Исключено из анализа.',classificationPendingOne:'1 проекция готова к определению артерии.',classificationPendingMany:'Проекций для определения артерий: {count}.',classificationIncomplete:'Определение артерий не завершено.',noEligible:'Нет последовательностей длиной не менее 10 кадров.',phaseProgress:'Этапы анализа',restoreTemporary:'Некоторые исследования или результаты временно недоступны. Перезагрузите страницу, чтобы повторить попытку.'}};
28
  const safeStored=(key,fallback)=>{try{return localStorage.getItem(key)||fallback;}catch{return fallback;}};
 
36
  const currentProjection=()=>currentStudy()?.projections.find(x=>x.id===selectedProjectionId);
37
  function el(tag,cls,text){const n=document.createElement(tag);if(cls)n.className=cls;if(text!==undefined)n.textContent=text;return n;}
38
  function setStored(key,value){try{localStorage.setItem(key,value);}catch{}}
39
+ function applyLanguage(){if(interfaceRecoveryActive)return;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'));$('classification-readout').setAttribute('aria-label',t('classifierLabel'));$('pipeline-steps').setAttribute('aria-label',t('phaseProgress'));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;}}}
40
  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);}
41
+ function showError(message){if(interfaceRecoveryActive)return;if(/Cannot (?:set|read) (?:properties|property) of (?:null|undefined)/i.test(String(message))){persistWorkspace();clearTimeout(pollTimer);workflowView='study';showInterfaceRecovery();return;}$('notice-text').textContent=message;$('notice').hidden=false;}
42
+ function hideError(){if(interfaceRecoveryActive)return;$('notice').hidden=true;}
43
+ function toast(message){if(interfaceRecoveryActive)return;const old=document.querySelector('.toast');old?.remove();const n=el('div','toast',message);n.setAttribute('role','status');document.body.append(n);setTimeout(()=>n.remove(),2800);}
44
  function errorText(e){if(typeof e==='string')return localizeError(e);if(Array.isArray(e))return e.map(x=>errorText(x.msg||x.reason||x)).join('\n');if(e?.rejected?.length)return t('excludedFiles')+'\n'+e.rejected.map(x=>`${x.name}: ${localizeError(x.reason)}`).join('\n');if(e?.message||e?.detail)return errorText(e.message||e.detail);return t('failed');}
45
  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;}
46
  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;}
47
+ async function refreshStatus(){if(interfaceRecoveryActive||previewMode)return;try{status=await request('/api/status');}catch{status=null;}statusChecked=true;renderStatus();}
48
+ function renderStatus(){if(interfaceRecoveryActive)return;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');$('server-indicator').title=$('server-label').textContent;$('server-indicator').setAttribute('aria-label',$('server-label').textContent);return;}if(!status){$('server-label').textContent=t(statusChecked?'offline':'connecting');dot.className='status-dot'+(statusChecked?' error':'');$('server-indicator').title=$('server-label').textContent;$('server-indicator').setAttribute('aria-label',$('server-label').textContent);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;$('server-indicator').title=`${device} · ${t(key)}`;$('server-indicator').setAttribute('aria-label',`${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':'файла'}`;}
49
  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'):'');}
50
  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);});}
51
  function defaultProjection(study){return study?.projections.find(p=>p.id===study.default_projection_id)?.id||study?.projections[0]?.id||null;}
52
  function selectStudy(id){unresolvedSelection=null;selectedStudyId=id;selectedProjectionId=defaultProjection(currentStudy());workflowView=currentStudy()?'projections':'study';render();}
53
  function render(){
54
+ if(interfaceRecoveryActive)return;
55
  const s=currentStudy();
56
  if(!s)workflowView='study';
57
  if(workflowView==='results'&&!resultByStudy.has(s?.id))workflowView='projections';
 
68
  if(!s.projections.some(x=>x.id===selectedProjectionId))selectedProjectionId=defaultProjection(s);
69
  renderProjection();renderFilmstrip();renderCounts();renderResult();
70
  }
71
+ function renderWorkflow(){if(interfaceRecoveryActive)return;
72
  const study=currentStudy(),result=resultByStudy.get(study?.id);
73
  const reviewed=classificationComplete(study);
74
  const states={study:{enabled:!busy,done:!!study},projections:{enabled:!!study,done:reviewed},results:{enabled:!!result,done:!!result&&result.complete!==false}};
 
79
  if(current)button.setAttribute('aria-current','step');else button.removeAttribute('aria-current');
80
  });
81
  }
82
+ function navigateWorkflow(view){if(interfaceRecoveryActive)return;
83
  const study=currentStudy();
84
  if(!['study','projections','results'].includes(view)||(view==='study'&&busy)||(view!=='study'&&!study)||(view==='results'&&!resultByStudy.has(study?.id)))return;
85
  workflowScrollUntil=performance.now()+800;
 
88
  target.focus({preventScroll:true});
89
  target.scrollIntoView({behavior:window.matchMedia('(prefers-reduced-motion: reduce)').matches?'auto':'smooth',block:'start'});
90
  }
91
+ function markWorkflow(view){if(interfaceRecoveryActive)return;
92
  if(workflowView==='study'||workflowView===view||(view==='results'&&!resultByStudy.has(selectedStudyId)))return;
93
  workflowView=view;renderWorkflow();persistWorkspace();
94
  }
 
113
  const eligible=(study?.projections||[]).filter(projection=>projection.frames>=10).length;
114
  return{complete,counts,eligible,kind:complete?'inference':'classify',allowed:complete?counts.unassigned===0&&(counts.left+counts.right)>0:eligible>0};
115
  }
116
+ function renderProjection(){if(interfaceRecoveryActive)return;
117
  const projection=currentProjection();$('viewer-image').hidden=!projection;$('viewer-empty').hidden=!!projection;if(!projection)return;
118
  const video=$('viewer-image'),src=projection.video_url||'';video.dataset.frames=String(projection.frames);video.poster=projection.preview_url;
119
  if(video.dataset.current!==src){video.src=src;video.dataset.current=src;video.load();}
 
124
  $('classification-label').textContent=labelFor(label);$('classification-label').className='classification-badge '+label;
125
  const reason=projectionReason(projection);$('classification-reason').textContent=reason;$('classification-reason').hidden=!reason;
126
  }
127
+ function renderFilmstrip(){if(interfaceRecoveryActive)return;
128
  const strip=$('filmstrip');strip.replaceChildren();
129
  currentStudy().projections.forEach((projection,index)=>{const label=projectionLabel(projection),button=el('button','projection-card'+(projection.id===selectedProjectionId?' selected':''));
130
  button.setAttribute('aria-label',`${index+1}. ${projection.name}. ${labelFor(label)}`);button.setAttribute('aria-pressed',String(projection.id===selectedProjectionId));
 
134
  button.addEventListener('click',()=>{selectedProjectionId=projection.id;renderProjection();renderFilmstrip();});strip.append(button);
135
  });
136
  }
137
+ function renderCounts(){if(interfaceRecoveryActive)return;
138
  const study=currentStudy(),action=studyAction(study),{counts}=action,hasResult=resultByStudy.has(study.id),running=busy&&(activeJob?.kind||action.kind);
139
  $('left-count').textContent=action.complete?counts.left:'—';$('right-count').textContent=action.complete?counts.right:'—';$('excluded-count').textContent=counts.exclude;
140
  let hint;if(!action.complete)hint=!action.eligible?t('noEligible'):t(action.eligible===1?'classificationPendingOne':'classificationPendingMany').replace('{count}',String(action.eligible));
 
195
  }
196
  function resultMatchesStudy(result,study){if(!result||!classificationComplete(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);}
197
  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);}
198
+ 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(!interfaceRecoveryActive&&data.cached_job&&resultByStudy.get(selectedStudyId)?.source?.type==='precomputed_example'&&!window.matchMedia('(prefers-reduced-motion: reduce)').matches)$('viewer-image').play().catch(()=>{});}
199
+ async function uploadFiles(files){if(interfaceRecoveryActive||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;if(!interfaceRecoveryActive){$('upload-overlay').hidden=true;$('file-input').value='';render();refreshStatus();}}}
200
 
201
  async function confirmAction(){const dialog=$('confirm-dialog');if(dialog.open)return false;const previousFocus=document.activeElement;$('confirm-title').textContent=t('confirmDeleteTitle');$('confirm-message').textContent=t('deleteConfirm');$('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();});}
202
 
203
  async function startJob(){
204
+ if(interfaceRecoveryActive||busy)return;if(previewMode){showError(t('previewHint'));return;}const study=currentStudy();if(!study)return;
205
  const action=studyAction(study);if(!action.allowed)return;const kind=action.kind;
206
  hideError();busy=true;render();$('job-status').hidden=false;$('job-message').textContent=t('queued');$('job-percentage').textContent='';$('job-progress').value=0;
207
  try{const options={method:'POST'};if(kind==='inference'){options.headers={'Content-Type':'application/json'};options.body='{}';}
208
  const job=await request(`/api/studies/${study.id}/${kind==='classify'?'classify':'run'}`,options);activeJob={...job,study_id:study.id};persistWorkspace();renderCounts();pollJob();
209
  }catch(error){finishJob();showError(error.message);}
210
  }
211
+ function finishJob(){if(interfaceRecoveryActive)return;busy=false;activeJob=null;clearTimeout(pollTimer);$('job-status').hidden=true;$('upload-overlay').hidden=true;render();refreshStatus();}
212
+ async function pollJob(){if(interfaceRecoveryActive||!activeJob)return;try{const job=await request(`/api/jobs/${activeJob.id}`);if(interfaceRecoveryActive)return;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){studies[index]=updated;if(selectedStudyId===updated.id&&!updated.projections.some(p=>p.id===selectedProjectionId))selectedProjectionId=defaultProjection(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);if(!interfaceRecoveryActive)pollTimer=setTimeout(pollJob,5000);}}}
213
  let examples=[];
214
  function referenceNumber(value){return value.toFixed(2);}
215
+ function renderExamples(){if(interfaceRecoveryActive)return;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('expertMeanSix')),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')));}
216
+ async function loadExamples(){if(interfaceRecoveryActive||previewMode)return;try{const d=await request('/api/examples');examples=d.examples||[];renderExamples();}catch{}}
217
+ async function loadExample(id){if(interfaceRecoveryActive||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);}}
218
  let expandedPlayback=null;
219
+ function openPreview(){if(interfaceRecoveryActive)return;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(interfaceRecoveryActive||!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();}
220
+ function closeExpandedPreview(){if(interfaceRecoveryActive)return;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;}
221
  const cinePlayers=[];let cinePlaybackRate=1;
222
  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);}}
223
  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','loadeddata','durationchange','timeupdate','play','pause','seeking','seeked','emptied','error','ratechange'])video.addEventListener(event,()=>updateCine(player));if(video.id==='viewer-image')video.addEventListener('loadedmetadata',()=>{const frames=Number(video.dataset.frames);if(frames>0&&Number.isFinite(video.duration)&&video.duration>0&&video.currentTime===0&&!video.seeking)video.currentTime=Math.min(.001,video.duration/frames/2);});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);}
 
225
  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);}
226
  function stepCine(player,delta){player.video.pause();seekCine(player,cineFrame(player)+delta);}
227
  function toggleCine(player){if(player.video.paused)player.video.play().catch(()=>{});else player.video.pause();}
228
+ function updateCine(player){if(interfaceRecoveryActive)return;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%');if(video.readyState>=2&&!video.seeking)range.setAttribute('aria-valuetext',t('framePosition').replace('{frame}',String(frame+1)).replace('{total}',String(frames)));else range.removeAttribute('aria-valuetext');const visibleFrame=video.readyState>=2&&!video.seeking;counter.textContent=frames?`${visibleFrame?String(frame+1).padStart(2,'0'):'—'} / ${frames}`:'— / —';play.disabled=!ready;previous.disabled=!ready||frame===0;next.disabled=!ready||frame>=frames-1;range.disabled=!ready;}
229
  document.querySelectorAll('[data-workflow]').forEach(button=>button.addEventListener('click',()=>navigateWorkflow(button.dataset.workflow)));
230
  $('projections-panel').addEventListener('focusin',()=>markWorkflow('projections'));
231
  for(const id of ['result-card','fold-results'])$(id).addEventListener('focusin',()=>markWorkflow('results'));
232
  $('calculation-link').addEventListener('click',event=>{event.preventDefault();markWorkflow('results');$('fold-results').focus({preventScroll:true});$('fold-results').scrollIntoView({behavior:window.matchMedia('(prefers-reduced-motion: reduce)').matches?'auto':'smooth',block:'start'});});
233
  let workflowScrollFrame=null;
234
  window.addEventListener('scroll',()=>{
235
+ if(interfaceRecoveryActive||workflowScrollFrame)return;
236
  workflowScrollFrame=requestAnimationFrame(()=>{
237
  workflowScrollFrame=null;
238
+ if(interfaceRecoveryActive)return;
239
  if(performance.now()<workflowScrollUntil||workflowView==='study'||!resultByStudy.has(selectedStudyId))return;
240
  const edge=document.querySelector('.topbar').getBoundingClientRect().bottom+60;
241
  if($('fold-results').getBoundingClientRect().top<=edge)markWorkflow('results');
 
247
  });
248
  },{passive:true});
249
  $('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)));
250
+ $('sidebar-upload').addEventListener('click',()=>{if(busy)return;hideError();navigateWorkflow('study');});$('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',()=>{if(!interfaceRecoveryActive)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);
251
+ $('run-button').addEventListener('click',startJob);$('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',()=>{if(interfaceRecoveryActive)return;$('viewer-image').hidden=true;$('viewer-empty').hidden=false;});
252
  $('copy-uid').addEventListener('click',async()=>{try{await navigator.clipboard.writeText(currentStudy()?.study_uid||'');toast(t('copied'));}catch{toast(t('copyFailed'));}});
253
  $('remove-study').addEventListener('click',async()=>{if(busy||!currentStudy()||!await confirmAction())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);forgetStudyRecovery(id);resultByStudy.delete(id);resultJobByStudy.delete(id);selectStudy(studies[0]?.id||null);});
254
  $('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);});
 
299
  selectedProjectionId=defaultProjection(currentStudy());
300
  workflowView=completedExampleStudyId?'projections':['study','projections','results'].includes(saved.workflow_view)?saved.workflow_view:currentStudy()?'projections':'study';
301
  workspaceRestored=true;
302
+ if(interfaceRecoveryActive)return;
303
  if(activeJob){busy=true;$('job-status').hidden=false;if(activeJob.kind==='example')$('upload-overlay').hidden=false;pollJob();}
304
  render();
305
  if(unresolvedStudyIds.size||unresolvedResultJobs.size||deferredJobs.size)showError(t('restoreTemporary'));
 
309
 
310
  window.addEventListener('beforeunload',()=>clearTimeout(pollTimer));
311
  const mobileLayout=window.matchMedia('(max-width: 760px)');
312
+ function placeFoldResults(){if(interfaceRecoveryActive)return;const workspace=$('workspace-grid'),fold=$('fold-results'),action=$('run-card'),rail=document.querySelector('.analysis-panel');if(fold.parentElement!==workspace)workspace.append(fold);const destination=mobileLayout.matches?workspace:rail;if(action.parentElement!==destination||destination.firstElementChild!==action)destination.prepend(action);}
313
  mobileLayout.addEventListener('change',placeFoldResults);
314
 
315
+ 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();if(interfaceRecoveryActive)return;await restoreWorkspace();if(interfaceRecoveryActive)return;busy=!!activeJob;render();loadExamples();}
316
+ init().catch(()=>showInterfaceRecovery(false));
317
+ }
318
+ if(interfaceCompatible())startCardioSyntax();else showInterfaceRecovery();
static/classifier-workflow.css CHANGED
@@ -73,9 +73,8 @@
73
  letter-spacing: .5px;
74
  }
75
  .pipeline-steps {
76
- display: grid;
77
- grid-template-columns: 1fr 1fr;
78
- gap: 6px;
79
  margin: 16px 0 18px;
80
  padding: 0;
81
  list-style: none;
@@ -84,41 +83,48 @@
84
  display: flex;
85
  align-items: center;
86
  gap: 7px;
 
87
  min-width: 0;
88
- padding: 8px 9px;
89
- border: 1px solid var(--line);
90
- border-radius: 7px;
91
  color: var(--muted);
92
  font-size: 11px;
93
- line-height: 1.3;
94
  font-weight: 500;
95
- background: transparent;
96
- }
97
- .pipeline-step.active {
98
- background: var(--detail-accent-surface);
99
- border-color: var(--detail-accent-line);
100
- color: var(--accent);
101
  }
 
 
 
 
 
 
 
 
 
 
102
  .pipeline-step.done { color: var(--accent); }
 
103
  .pipeline-step-icon {
104
  display: grid;
105
  place-items: center;
106
- width: 19px;
107
- height: 19px;
108
  flex: none;
109
- border: 1px solid var(--line);
110
- border-radius: 50%;
111
- font-size: 10px;
112
- font-variant-numeric: tabular-nums;
113
- }
114
- .pipeline-step.active .pipeline-step-icon {
115
- border-color: var(--detail-accent-line);
116
- background: var(--surface);
117
  }
 
 
 
118
  .pipeline-step-icon > svg { display: none; width: 12px; height: 12px; stroke-width: 1.8; }
119
- .pipeline-step.done .pipeline-step-icon { border-color: transparent; background: var(--accent-pale); }
120
- .pipeline-step.done .pipeline-step-icon > span { display: none; }
121
  .pipeline-step.done .pipeline-step-icon > svg { display: block; }
 
122
  #run-card .selection-counts { margin-top: 0; }
123
  #run-card .run-hint { min-height: 3.3em; margin: 16px 0; }
124
  #run-card #run-button { gap: 9px; min-height: 43px; }
@@ -136,14 +142,16 @@
136
  @media(max-width:960px) {
137
  .classification-row { align-items: flex-start; flex-wrap: wrap; gap: 9px; }
138
  .classification-reason { max-width: none; text-align: left; }
139
- .pipeline-step { padding: 8px 7px; gap: 6px; }
140
  }
141
  @media(max-width:760px) {
142
  .classification-row { align-items: center; gap: 10px 14px; padding: 15px 0; }
143
  .classification-badge { font-size: 12px; }
144
  .classification-reason { font-size: 11px; }
145
- .pipeline-step { padding: 9px 11px; font-size: 12px; gap: 8px; }
146
  #run-card .run-hint { font-size: 12px; }
147
  }
148
 
149
  #run-card{scroll-margin-top:calc(var(--header-height) + 24px)}#run-card:focus{outline:none}.workspace-grid>.run-card{grid-column:1/-1;order:0}@media(max-width:760px){.workspace-grid>.run-card{margin-bottom:0;padding:18px 20px}.workspace-grid>.run-card .pipeline-steps{margin-top:13px;margin-bottom:15px}.workspace-grid>.run-card .run-hint{min-height:0;margin:14px 0}.workspace-grid>.run-card .selection-counts{margin-top:0}}
 
 
 
73
  letter-spacing: .5px;
74
  }
75
  .pipeline-steps {
76
+ display: flex;
77
+ gap: 14px;
 
78
  margin: 16px 0 18px;
79
  padding: 0;
80
  list-style: none;
 
83
  display: flex;
84
  align-items: center;
85
  gap: 7px;
86
+ flex: 1;
87
  min-width: 0;
88
+ padding: 0;
89
+ border: 0;
90
+ border-radius: 0;
91
  color: var(--muted);
92
  font-size: 11px;
93
+ line-height: 1.4;
94
  font-weight: 500;
95
+ background: none;
96
+ cursor: default;
97
+ transition: color 180ms ease;
 
 
 
98
  }
99
+ .pipeline-step:first-child::after {
100
+ content: '';
101
+ flex: 1;
102
+ min-width: 12px;
103
+ height: 1px;
104
+ margin-left: 6px;
105
+ background: var(--line);
106
+ transition: background-color 180ms ease;
107
+ }
108
+ .pipeline-step.active { color: var(--accent); font-weight: 600; }
109
  .pipeline-step.done { color: var(--accent); }
110
+ .pipeline-step.done:first-child::after { background: var(--detail-accent-line); }
111
  .pipeline-step-icon {
112
  display: grid;
113
  place-items: center;
114
+ width: 12px;
115
+ height: 14px;
116
  flex: none;
117
+ border: 0;
118
+ border-radius: 0;
119
+ background: none;
 
 
 
 
 
120
  }
121
+ .pipeline-step-icon::before { content: ''; width: 5px; height: 5px; border: 1px solid currentColor; border-radius: 50%; opacity: .55; }
122
+ .pipeline-step.active .pipeline-step-icon::before { background: currentColor; opacity: 1; }
123
+ .pipeline-step-icon > span { display: none; }
124
  .pipeline-step-icon > svg { display: none; width: 12px; height: 12px; stroke-width: 1.8; }
125
+ .pipeline-step.done .pipeline-step-icon::before { display: none; }
 
126
  .pipeline-step.done .pipeline-step-icon > svg { display: block; }
127
+ .classification-badge { transition: color 180ms ease, background-color 180ms ease, border-color 180ms ease; }
128
  #run-card .selection-counts { margin-top: 0; }
129
  #run-card .run-hint { min-height: 3.3em; margin: 16px 0; }
130
  #run-card #run-button { gap: 9px; min-height: 43px; }
 
142
  @media(max-width:960px) {
143
  .classification-row { align-items: flex-start; flex-wrap: wrap; gap: 9px; }
144
  .classification-reason { max-width: none; text-align: left; }
145
+ .pipeline-step { gap: 6px; }
146
  }
147
  @media(max-width:760px) {
148
  .classification-row { align-items: center; gap: 10px 14px; padding: 15px 0; }
149
  .classification-badge { font-size: 12px; }
150
  .classification-reason { font-size: 11px; }
151
+ .pipeline-step { font-size: 12px; gap: 8px; }
152
  #run-card .run-hint { font-size: 12px; }
153
  }
154
 
155
  #run-card{scroll-margin-top:calc(var(--header-height) + 24px)}#run-card:focus{outline:none}.workspace-grid>.run-card{grid-column:1/-1;order:0}@media(max-width:760px){.workspace-grid>.run-card{margin-bottom:0;padding:18px 20px}.workspace-grid>.run-card .pipeline-steps{margin-top:13px;margin-bottom:15px}.workspace-grid>.run-card .run-hint{min-height:0;margin:14px 0}.workspace-grid>.run-card .selection-counts{margin-top:0}}
156
+
157
+ @media(prefers-reduced-motion:reduce){.pipeline-step,.pipeline-step::after,.classification-badge{transition:none}}
static/index.html CHANGED
@@ -1,5 +1,5 @@
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"><link rel="stylesheet" href="/static/result-design.css"><link rel="stylesheet" href="/static/navigation.css"><link rel="stylesheet" href="/static/classifier-workflow.css"><link rel="icon" href="/static/favicon.svg?v=cine-atlas" type="image/svg+xml"></head>
4
  <body>
5
  <svg class="icon-library" aria-hidden="true" xmlns="http://www.w3.org/2000/svg"><defs>
 
1
  <!doctype html>
2
+ <html lang="en" data-theme="studio" data-ui-version="classifier-workflow-4">
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"><link rel="stylesheet" href="/static/result-design.css"><link rel="stylesheet" href="/static/navigation.css"><link rel="stylesheet" href="/static/classifier-workflow.css"><link rel="icon" href="/static/favicon.svg?v=cine-atlas" type="image/svg+xml"></head>
4
  <body>
5
  <svg class="icon-library" aria-hidden="true" xmlns="http://www.w3.org/2000/svg"><defs>
tests/test_frontend.cjs ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+ // Lightweight DOM-contract tests: no browser, model weights, or DICOM decoding.
3
+ const test=require('node:test');
4
+ const assert=require('node:assert/strict');
5
+ const fs=require('node:fs');
6
+ const path=require('node:path');
7
+ const vm=require('node:vm');
8
+ const root=path.join(__dirname,'..');
9
+ const html=fs.readFileSync(path.join(root,'static/index.html'),'utf8');
10
+ const source=fs.readFileSync(path.join(root,'static/app.js'),'utf8');
11
+ const cache=JSON.parse(fs.readFileSync(path.join(root,'service/example_results/philips-zero.json'),'utf8'));
12
+
13
+ class Element {
14
+ constructor(tag,document){this.tagName=tag.toUpperCase();this.ownerDocument=document;this.children=[];this.parentElement=null;this.attributes={};this.dataset={};this.listeners={};this.className='';this._text='';this.hidden=false;this.disabled=false;this.open=false;this.currentTime=0;this.duration=NaN;this.readyState=0;this.paused=true;this.seeking=false;this.error=null;this.style={setProperty:(key,value)=>{this.style[key]=value;}};const element=this;this.classList={contains:name=>element.className.split(/\s+/).includes(name),add(...names){element.className=[...new Set([...element.className.split(/\s+/).filter(Boolean),...names])].join(' ');},remove(...names){element.className=element.className.split(/\s+/).filter(name=>!names.includes(name)).join(' ');},toggle(name,force){const enabled=force??!this.contains(name);enabled?this.add(name):this.remove(name);return enabled;}};}
15
+ get firstElementChild(){return this.children[0]||null;}
16
+ get isConnected(){let node=this;while(node.parentElement)node=node.parentElement;return node===this.ownerDocument.documentElement;}
17
+ get textContent(){return this._text+this.children.map(node=>node.textContent).join('');}
18
+ set textContent(value){this._text=String(value);this.children.forEach(node=>node.parentElement=null);this.children=[];}
19
+ get innerHTML(){return this.textContent;}
20
+ set innerHTML(value){this.textContent=String(value).replace(/<br\s*\/?\s*>/gi,'\n').replace(/<[^>]+>/g,'');}
21
+ setAttribute(name,value){this.attributes[name]=String(value);if(name==='id')this.id=String(value);if(name==='class')this.className=String(value);if(name==='lang')this.lang=String(value);if(name==='hidden')this.hidden=true;if(name==='disabled')this.disabled=true;if(name==='muted')this.muted=true;if(name.startsWith('data-'))this.dataset[name.slice(5).replace(/-([a-z])/g,(_,c)=>c.toUpperCase())]=String(value);}
22
+ getAttribute(name){return name==='class'?this.className:this.attributes[name]??null;}
23
+ removeAttribute(name){delete this.attributes[name];}
24
+ append(...nodes){for(let node of nodes){if(typeof node==='string'){const text=new Element('#text',this.ownerDocument);text.textContent=node;node=text;}node.remove();node.parentElement=this;this.children.push(node);}}
25
+ prepend(node){node.remove();node.parentElement=this;this.children.unshift(node);}
26
+ after(node){const parent=this.parentElement;if(!parent)throw Error('Detached node');node.remove();node.parentElement=parent;parent.children.splice(parent.children.indexOf(this)+1,0,node);}
27
+ remove(){if(this.parentElement)this.parentElement.children=this.parentElement.children.filter(node=>node!==this);this.parentElement=null;}
28
+ replaceChildren(...nodes){this.children.forEach(node=>node.parentElement=null);this.children=[];this._text='';this.append(...nodes);}
29
+ addEventListener(type,callback,options){(this.listeners[type]??=[]).push({callback,once:options?.once});}
30
+ async dispatch(type,event={}){for(const listener of [...(this.listeners[type]||[])]){await listener.callback({target:this,preventDefault(){},...event});if(listener.once)this.listeners[type]=this.listeners[type].filter(item=>item!==listener);}}
31
+ click(){if(!this.disabled)return this.dispatch('click');}
32
+ focus(){this.ownerDocument.activeElement=this;}
33
+ scrollIntoView(){}
34
+ getBoundingClientRect(){return{top:100,bottom:300,height:200,width:390};}
35
+ querySelector(selector){return this.querySelectorAll(selector)[0]||null;}
36
+ querySelectorAll(selector){return descendants(this).filter(node=>matches(node,selector));}
37
+ load(){this.readyState=0;this.duration=NaN;this.currentTime=0;this.paused=true;}
38
+ pause(){this.paused=true;}
39
+ play(){this.paused=false;return Promise.resolve();}
40
+ showModal(){this.open=true;}
41
+ close(){this.open=false;return this.dispatch('close');}
42
+ }
43
+ function descendants(root){return root.children.flatMap(node=>[node,...descendants(node)]);}
44
+ function simpleMatch(node,selector){if(selector.startsWith('#'))return node.id===selector.slice(1);if(selector.startsWith('.'))return node.classList.contains(selector.slice(1));const attr=selector.match(/^\[([^=\]]+)(?:=["']?([^"'\]]+)["']?)?\]$/);if(attr)return node.getAttribute(attr[1])!==null&&(attr[2]===undefined||node.getAttribute(attr[1])===attr[2]);return node.tagName===selector.toUpperCase();}
45
+ function matches(node,selector){const parts=selector.trim().split(/\s+/);if(!simpleMatch(node,parts.pop()))return false;for(const part of parts.reverse()){let parent=node.parentElement;while(parent&&!simpleMatch(parent,part))parent=parent.parentElement;if(!parent)return false;node=parent;}return true;}
46
+ function makeDocument(markup){const document={createElement:tag=>new Element(tag,document),createElementNS:(_,tag)=>new Element(tag,document),createTextNode:text=>{const node=new Element('#text',document);node.textContent=text;return node;}};const stack=[];const voids=new Set(['meta','link','img','input','br','hr','source']);for(const token of markup.match(/<[^>]+>|[^<]+/g)||[]){if(token.startsWith('<!'))continue;if(token.startsWith('</')){stack.pop();continue;}if(token.startsWith('<')){const tag=token.match(/^<([\w-]+)/)?.[1];if(!tag)continue;const node=document.createElement(tag);const attrs=token.slice(tag.length+1).replace(/\/?\s*>$/,'');for(const match of attrs.matchAll(/([^\s=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s]+)))?/g))node.setAttribute(match[1],match[2]??match[3]??match[4]??'');if(stack.length)stack.at(-1).append(node);if(tag==='html')document.documentElement=node;if(tag==='body')document.body=node;if(!voids.has(tag)&&!token.endsWith('/>'))stack.push(node);}else if(stack.length)stack.at(-1)._text+=token;}
47
+ document.getElementById=id=>[document.documentElement,...descendants(document.documentElement)].find(node=>node.id===id)||null;document.querySelectorAll=selector=>[document.documentElement,...descendants(document.documentElement)].filter(node=>matches(node,selector));document.querySelector=selector=>document.querySelectorAll(selector)[0]||null;return document;}
48
+ function storage(initial={}){const values=new Map(Object.entries(initial));return{getItem:key=>values.get(key)??null,setItem:(key,value)=>values.set(key,String(value)),removeItem:key=>values.delete(key),values};}
49
+ function environment({markup=html,url='https://example.test/',session=storage(),blockedStorage=false,mobile=false,routes={}}={}){
50
+ const document=makeDocument(markup),navigations=[],requests=[],windowEvents={},animationFrames=[];const unavailable={getItem(){throw Error('blocked');},setItem(){throw Error('blocked');}};
51
+ const context={document,URL,URLSearchParams,Date,Promise,Map,Set,console,sessionStorage:blockedStorage?unavailable:session,localStorage:storage(),location:{href:url,replace:value=>navigations.push(value)},performance:{now:()=>0},navigator:{clipboard:{writeText:async()=>{}}},setTimeout:()=>1,clearTimeout:()=>{},requestAnimationFrame:callback=>{animationFrames.push(callback);return animationFrames.length;},addEventListener(type,callback){(windowEvents[type]??=[]).push(callback);},matchMedia:query=>({matches:query.includes('760px')&&mobile,addEventListener(){}}),FormData:class{constructor(){this.files=[];}append(...data){this.files.push(data);}},Blob,fetch:async(url,options={})=>{requests.push({url,...options});const key=`${options.method||'GET'} ${url}`;let response=routes[key];if(typeof response==='function')response=await response(options);if(response===undefined&&url==='/api/status')response={service:'ready',device:'cpu',model:{status:'cached',revision:'pinned',repository:'test/model'},limits:{max_files:64,max_request_mb:512}};if(response===undefined&&url==='/api/examples')response={examples:[]};if(response instanceof Error)throw response;if(response===undefined)throw Error('Unexpected request '+key);const status=response.__status??200;return{ok:status>=200&&status<300,status,json:async()=>structuredClone(response.__body??response)};}};
52
+ context.window=context;vm.createContext(context);return{context,document,navigations,requests,session,windowEvents,animationFrames};}
53
+ const hook="globalThis.__app={init,refreshStatus,uploadFiles,acceptStudies,startJob,render,applyLanguage,studyAction,workspaceSnapshot,setLanguage(value){lang=value;applyLanguage();},state(){return{studies,selectedStudyId,busy,activeJob,resultByStudy,resultJobByStudy};}};";
54
+ function runApp(env){const marker='init().catch(()=>showInterfaceRecovery(false));';assert(source.includes(marker));vm.runInContext(source.replace(marker,hook),env.context);return env.context.__app;}
55
+ const settle=async()=>{for(let i=0;i<5;i++)await new Promise(resolve=>setImmediate(resolve));};
56
+ function projection(id,artery='unassigned',frames=64){return{id,name:id+'.dcm',frames,rows:512,columns:512,artery,preview_url:'/preview/'+id,video_url:'/video/'+id};}
57
+ function study(id='study-a',complete=false,projections=[projection('a'),projection('b'),projection('short','exclude',8)]){return{id,study_uid:'test-study-uid',classification_complete:complete,projections};}
58
+ function resultFor(study,precomputed=false){return{...structuredClone(cache.result),input_assignments:study.projections.map(p=>({id:p.id,artery:p.artery})),...(precomputed?{source:{type:'precomputed_example'}}:{})};}
59
+
60
+ test('DOM revision and every required runtime ID agree with the shipped HTML',()=>{const env=environment();assert(runApp(env));const refs=[...source.matchAll(/\$\('([^']+)'\)/g)].map(match=>match[1]);assert(refs.every(id=>env.document.getElementById(id)));assert.equal(env.document.querySelectorAll('[data-artery]').length,0);assert.equal(env.document.getElementById('run-card').querySelectorAll('button').length,1);assert.equal(env.document.getElementById('pipeline-steps').querySelectorAll('button').length,0);});
61
+
62
+ test('stale HTML refreshes once before any app listener or API call; handles survive',()=>{const session=storage({'cardiosyntax-workspace':JSON.stringify({study_ids:['saved-study'],result_jobs:[['saved-study','saved-result']]})});const stale=html.replace('data-ui-version="classifier-workflow-4"','data-ui-version="legacy"').replace('id="run-button-label"','id="old-label"');const original=session.getItem('cardiosyntax-workspace');const first=environment({markup:stale,session});assert.equal(runApp(first),undefined);assert.equal(first.navigations.length,1);assert.equal(first.requests.length,0);assert.equal(session.getItem('cardiosyntax-workspace'),original);const second=environment({markup:stale,session,url:first.navigations[0]});assert.equal(runApp(second),undefined);assert.equal(second.navigations.length,0);assert.match(second.document.body.textContent,/Refresh the workspace/);assert.equal(session.getItem('cardiosyntax-workspace'),original);});
63
+
64
+ test('missing element with current marker is guarded; blocked storage cannot create reload loop',()=>{const missing=html.replace('id="classification-label"','id="missing-label"');const first=environment({markup:missing,blockedStorage:true});assert.equal(runApp(first),undefined);assert.equal(first.navigations.length,1);const second=environment({markup:missing,blockedStorage:true,url:first.navigations[0]});assert.equal(runApp(second),undefined);assert.equal(second.navigations.length,0);assert(second.document.body.querySelector('button'));});
65
+
66
+ test('actual upload → classifier → inference uses one action node and an empty run payload',async()=>{const pending=study(),classified=study('study-a',true,[projection('a','left'),projection('b','right'),projection('short','exclude',8)]),result=resultFor(classified);const env=environment({routes:{'POST /api/studies':{studies:[pending],rejected:[],warnings:[]},'POST /api/studies/study-a/classify':{id:'classifier-job',kind:'classify',status:'queued'},'GET /api/jobs/classifier-job':{id:'classifier-job',kind:'classify',status:'completed',progress:1,result:{study:classified}},'POST /api/studies/study-a/run':options=>{assert.equal(options.body,'{}');return{id:'inference-job',kind:'inference',status:'queued'};},'GET /api/jobs/inference-job':{id:'inference-job',kind:'inference',status:'completed',progress:1,result}}});const app=runApp(env);await app.init();await settle();const button=env.document.getElementById('run-button');assert.equal(env.document.querySelectorAll('.cine-controls').length,2);await app.uploadFiles([{name:'siemens.dcm'}]);assert.equal(env.document.getElementById('run-button-label').textContent,'Identify arteries');assert.equal(env.document.getElementById('classification-label').textContent,'Pending');await app.startJob();await settle();assert.equal(env.document.getElementById('run-button-label').textContent,'Calculate SYNTAX');assert.equal(env.document.getElementById('classification-label').textContent,'LCA');assert.equal(env.document.getElementById('run-button'),button);await app.startJob();await settle();assert.equal(env.document.getElementById('run-button-label').textContent,'Recalculate SYNTAX');assert.equal(env.document.getElementById('run-button'),button);assert.equal(env.document.getElementById('score-number').textContent,result.calibrated.toFixed(2));assert.equal(env.document.getElementById('fold-table-body').children.length,5);assert(!env.document.body.textContent.includes('Cannot set properties'));});
67
+
68
+ test('verified cached example renders full result and six experts without classifying or inferring',async()=>{const example={...study('cached',true,[projection('l','left'),projection('r','right')]),reference_score:0,expert_scores:[0,0,0,0,0,0],reference_url:'https://huggingface.co/datasets/test/data/blob/pinned/annotations.json'};const result=resultFor(example,true),env=environment({mobile:true});const app=runApp(env);await app.init();await settle();app.acceptStudies({studies:[example],cached_job:{id:'saved-gpu',study_id:'cached',kind:'inference',status:'completed',result}});assert.equal(env.document.getElementById('run-button-label').textContent,'Recalculate SYNTAX');assert.equal(env.document.getElementById('expert-scores').children.length,6);assert.equal(env.document.getElementById('reference-score-value').textContent,'0.00');assert.equal(env.document.getElementById('result-origin').hidden,false);assert.equal(env.document.getElementById('workspace-grid').firstElementChild.id,'run-card');assert.equal(env.requests.filter(request=>request.method==='POST').length,0);app.setLanguage('ru');assert.equal(env.document.getElementById('run-button-label').textContent,'Пересчитать SYNTAX');});
69
+
70
+ test('short/all-excluded uploads and partial results stay renderable and read-only',async()=>{const env=environment();const app=runApp(env);await app.init();await settle();app.acceptStudies({studies:[study('short',false,[projection('short','exclude',8)])]});assert.equal(env.document.getElementById('run-button').disabled,true);assert.equal(env.document.getElementById('classification-label').textContent,'Excluded');const partial=study('partial',true,[projection('only-left','left')]);app.acceptStudies({studies:[partial],cached_job:{id:'partial-result',study_id:'partial',kind:'inference',status:'completed',result:{complete:false,raw:null,calibrated:null,per_fold:[],left:{per_fold:[-.1,0,.1,.2,.3]},right:{per_fold:[]},input_assignments:[{id:'only-left',artery:'left'}]}}});assert.equal(env.document.getElementById('score-number').textContent,'—');assert.equal(env.document.getElementById('fold-table-body').children.length,5);assert.equal(env.document.getElementById('result-state').textContent,'Partial');const excluded=study('excluded',true,[{...projection('uncertain','exclude'),reason:'Low-confidence artery classification; automatically excluded.'}]);app.acceptStudies({studies:[excluded]});assert.equal(env.document.getElementById('run-button').disabled,true);assert.match(env.document.getElementById('classification-reason').textContent,/Low classifier confidence/);assert(!source.includes('saved.drafts'));assert(!source.includes('projections.sort'));});
71
+
72
+
73
+ test('pending status and queued video/scroll events stay harmless after recovery replaces the DOM',async()=>{
74
+ const ready={service:'ready',device:'cpu',model:{status:'cached'}};let resolveStatus,statusCalls=0;
75
+ const env=environment({routes:{'GET /api/status':()=>++statusCalls===1?ready:new Promise(resolve=>{resolveStatus=resolve;})}});
76
+ const app=runApp(env);await app.init();await settle();
77
+ const example=study('recovering',true,[projection('left','left'),projection('right','right')]);
78
+ app.acceptStudies({studies:[example],cached_job:{id:'saved-recovery-result',study_id:example.id,kind:'inference',status:'completed',result:resultFor(example,true)}});
79
+ const video=env.document.getElementById('viewer-image'),dialog=env.document.getElementById('preview-dialog');
80
+ const handles=env.session.getItem('cardiosyntax-workspace');
81
+ const pending=app.refreshStatus();
82
+ env.windowEvents.scroll.forEach(callback=>callback());
83
+ assert.equal(env.animationFrames.length,1);
84
+ env.context.showInterfaceRecovery(false);
85
+ resolveStatus(ready);
86
+ await assert.doesNotReject(pending);
87
+ await assert.doesNotReject(video.dispatch('error'));
88
+ await assert.doesNotReject(dialog.dispatch('close'));
89
+ assert.doesNotThrow(()=>env.animationFrames.forEach(callback=>callback()));
90
+ assert.match(env.document.body.textContent,/Refresh the workspace/);
91
+ assert.equal(env.session.getItem('cardiosyntax-workspace'),handles);
92
+ assert.equal(env.navigations.length,0);
93
+ });
tests/test_service_cache_headers.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """HTML and executable assets must come from one immutable UI release."""
2
+ import hashlib
3
+ import re
4
+
5
+ from fastapi.testclient import TestClient
6
+
7
+ from service.api import create_app
8
+ from test_service import FakeEngine
9
+
10
+
11
+ def make_static(tmp_path):
12
+ static = tmp_path / 'static'
13
+ static.mkdir()
14
+ (static / 'index.html').write_text('<!doctype html><html><head><link rel="stylesheet" href="/static/styles.css?v=old"></head>'
15
+ '<body><script src="/static/app.js" defer></script></body></html>')
16
+ (static / 'styles.css').write_text('body{color:green}')
17
+ (static / 'app.js').write_text('window.uiRevision="first";')
18
+ return static
19
+
20
+
21
+ def asset_url(html, filename):
22
+ return re.search(r'(/assets/[0-9a-f]{64}/' + re.escape(filename) + r')', html).group(1)
23
+
24
+
25
+ def test_html_is_not_cached_and_references_fingerprinted_assets(tmp_path):
26
+ static = make_static(tmp_path)
27
+ app = create_app(data_root=tmp_path / 'uploads', static_root=static, engine=FakeEngine())
28
+ with TestClient(app) as client:
29
+ page = client.get('/')
30
+ assert page.status_code == 200
31
+ assert page.headers['cache-control'] == 'no-store, max-age=0'
32
+ assert page.headers['pragma'] == 'no-cache' and page.headers['expires'] == '0'
33
+ assert page.headers['x-ui-release'] in page.text
34
+ assert 'src="/static/app.js"' not in page.text
35
+ assert 'href="/static/styles.css' not in page.text
36
+ for filename in ('app.js', 'styles.css'):
37
+ response = client.get(asset_url(page.text, filename))
38
+ original = (static / filename).read_bytes()
39
+ assert response.content == original
40
+ assert response.headers['cache-control'] == 'public, max-age=31536000, immutable'
41
+ assert hashlib.sha256(original).hexdigest() in response.headers['etag']
42
+ head = client.head('/')
43
+ assert head.status_code == 200 and head.content == b''
44
+ assert head.headers['content-length'] == page.headers['content-length']
45
+
46
+
47
+ def test_release_snapshot_cannot_mix_old_html_with_new_javascript(tmp_path):
48
+ static = make_static(tmp_path)
49
+ first = create_app(data_root=tmp_path / 'first', static_root=static, engine=FakeEngine())
50
+ with TestClient(first) as old_client:
51
+ old_page = old_client.get('/')
52
+ old_url = asset_url(old_page.text, 'app.js')
53
+ old_content = old_client.get(old_url).content
54
+ (static / 'app.js').write_text('window.uiRevision="second";window.newPanel=true;')
55
+ (static / 'index.html').write_text((static / 'index.html').read_text().replace('<body>', '<body><div id="new-panel"></div>'))
56
+ assert old_client.get('/').text == old_page.text
57
+ assert old_client.get(old_url).content == old_content
58
+ second = create_app(data_root=tmp_path / 'second', static_root=static, engine=FakeEngine())
59
+ with TestClient(second) as new_client:
60
+ new_page = new_client.get('/')
61
+ new_url = asset_url(new_page.text, 'app.js')
62
+ assert new_url != old_url
63
+ assert new_page.headers['x-ui-release'] != old_page.headers['x-ui-release']
64
+ assert 'id="new-panel"' in new_page.text
65
+ assert new_client.get(new_url).content == (static / 'app.js').read_bytes()
66
+ mismatch = new_client.get(old_url)
67
+ assert mismatch.status_code == 404 and 'no-store' in mismatch.headers['cache-control']
68
+ assert 'immutable' not in mismatch.headers['cache-control']
69
+
70
+
71
+ def test_legacy_assets_revalidate_and_only_exact_version_can_be_immutable(tmp_path):
72
+ static = make_static(tmp_path)
73
+ app = create_app(data_root=tmp_path / 'uploads', static_root=static, engine=FakeEngine())
74
+ with TestClient(app) as client:
75
+ legacy = client.get('/static/app.js')
76
+ assert legacy.headers['cache-control'] == 'no-cache, must-revalidate'
77
+ assert 'etag' in legacy.headers and 'last-modified' in legacy.headers
78
+ assert client.get('/static/app.js', headers={'If-None-Match': legacy.headers['etag']}).status_code == 304
79
+ versioned_url = asset_url(client.get('/').text, 'app.js')
80
+ versioned = client.get(versioned_url)
81
+ not_modified = client.get(versioned_url, headers={'If-None-Match': versioned.headers['etag']})
82
+ assert not_modified.status_code == 304 and not_modified.content == b''
83
+ head = client.head(versioned_url)
84
+ assert head.status_code == 200 and head.content == b''
85
+ assert head.headers['content-length'] == str(len(versioned.content))
86
+ assert client.get('/assets/' + '0' * 64 + '/app.js').status_code == 404
87
+ assert client.get('/api/status').headers['cache-control'] == 'no-store'