Spaces:
Sleeping
Sleeping
File size: 72,206 Bytes
1024e04 57ea0fa 1024e04 24da0c6 1024e04 eb88521 605754a 1024e04 2ab01da 1024e04 57ea0fa 1024e04 57ea0fa 1024e04 57ea0fa 2ab01da 1024e04 2ab01da 24da0c6 605754a 57ea0fa 605754a 24da0c6 605754a 57ea0fa 605754a 24da0c6 605754a 57ea0fa 605754a 24da0c6 605754a 57ea0fa 605754a 24da0c6 1024e04 24da0c6 57ea0fa 24da0c6 57ea0fa 24da0c6 57ea0fa 24da0c6 1024e04 2ab01da ae45c4e 24da0c6 2ab01da 57ea0fa 1024e04 24da0c6 1024e04 24da0c6 57ea0fa 24da0c6 57ea0fa 1024e04 2ab01da 57ea0fa 2ab01da 57ea0fa 2ab01da ae45c4e 2ab01da 57ea0fa 605754a 57ea0fa 605754a 57ea0fa 605754a 1024e04 57ea0fa 1024e04 24da0c6 1024e04 24da0c6 57ea0fa 24da0c6 1024e04 2ab01da 57ea0fa 2ab01da 57ea0fa | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 | 'use strict';
const UI_REVISION='classifier-workflow-4';
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"];
const REQUIRED_UI_SELECTORS=['.analysis-panel','.welcome-aside','.topbar','.workflow','.theme-switch','#server-indicator .status-dot'];
let interfaceRecoveryActive=false;
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));}
function recoveryLanguage(){try{return localStorage.getItem('cardiosyntax-language')==='ru'?'ru':'en';}catch{return document.documentElement.lang==='ru'?'ru':'en';}}
function showInterfaceRecovery(allowAutomatic=true){
if(interfaceRecoveryActive)return;interfaceRecoveryActive=true;
const russian=recoveryLanguage()==='ru',url=new URL(location.href),key='cardiosyntax-ui-refresh';
let attempted=url.searchParams.get('ui_refresh')===UI_REVISION;
try{attempted=attempted||sessionStorage.getItem(key)===UI_REVISION;}catch{}
const automatic=allowAutomatic&&!attempted;
const shell=document.createElement('main'),panel=document.createElement('section'),title=document.createElement('h1'),message=document.createElement('p');
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';
panel.style.cssText='width:min(420px,100%);box-sizing:border-box;padding:28px;border:1px solid #d9e3dc;border-radius:14px;background:#fff';
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';
title.textContent=russian?(automatic?'Обновляем интерфейс…':'Обновите интерфейс'):(automatic?'Refreshing the workspace…':'Refresh the workspace');
message.textContent=russian?'Страница загрузилась не полностью. Ссылки на ваши исследования сохранены.':'This page did not load completely. Your saved study links are preserved.';
panel.append(title,message);shell.append(panel);document.body.replaceChildren(shell);
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);};
if(automatic){try{sessionStorage.setItem(key,UI_REVISION);}catch{}refresh();return;}
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();
}
function startCardioSyntax(){
const $=id=>document.getElementById(id);
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:'Некоторые исследования или результаты временно недоступны. Перезагрузите страницу, чтобы повторить попытку.'}};
const safeStored=(key,fallback)=>{try{return localStorage.getItem(key)||fallback;}catch{return fallback;}};
let lang=safeStored('cardiosyntax-language','en');if(!words[lang])lang='en';
let studies=[],selectedStudyId=null,selectedProjectionId=null,status=null,statusChecked=false,busy=false,activeJob=null,pollTimer=null,resultByStudy=new Map(),resultJobByStudy=new Map();
let workflowView='study',workflowScrollUntil=0;
const previewMode=document.body.dataset.preview==='true';
const t=k=>words[lang][k]??words.en[k]??k;
const icon=name=>{const svg=document.createElementNS('http://www.w3.org/2000/svg','svg');const use=document.createElementNS('http://www.w3.org/2000/svg','use');use.setAttribute('href','#i-'+name);svg.append(use);return svg;};
const currentStudy=()=>studies.find(x=>x.id===selectedStudyId);
const currentProjection=()=>currentStudy()?.projections.find(x=>x.id===selectedProjectionId);
function el(tag,cls,text){const n=document.createElement(tag);if(cls)n.className=cls;if(text!==undefined)n.textContent=text;return n;}
function setStored(key,value){try{localStorage.setItem(key,value);}catch{}}
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;}}}
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);}
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;}
function hideError(){if(interfaceRecoveryActive)return;$('notice').hidden=true;}
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);}
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');}
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;}
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;}
async function refreshStatus(){if(interfaceRecoveryActive||previewMode)return;try{status=await request('/api/status');}catch{status=null;}statusChecked=true;renderStatus();}
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':'файла'}`;}
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'):'');}
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);});}
function defaultProjection(study){return study?.projections.find(p=>p.id===study.default_projection_id)?.id||study?.projections[0]?.id||null;}
function selectStudy(id){unresolvedSelection=null;selectedStudyId=id;selectedProjectionId=defaultProjection(currentStudy());workflowView=currentStudy()?'projections':'study';render();}
function render(){
if(interfaceRecoveryActive)return;
const s=currentStudy();
if(!s)workflowView='study';
if(workflowView==='results'&&!resultByStudy.has(s?.id))workflowView='projections';
const showStudy=!s||workflowView==='study';
persistWorkspace();renderSidebar();renderExamples();renderWorkflow();
$('welcome').hidden=!showStudy;$('workspace-grid').hidden=showStudy;
$('remove-study').hidden=showStudy;$('remove-study').disabled=busy;
const index=studies.findIndex(x=>x.id===selectedStudyId);
$('page-title').textContent=showStudy?t('initialTitle'):`${t('study')} ${String(index+1).padStart(2,'0')}`;
$('page-subtitle').textContent=showStudy?t('initialSubtitle'):t(resultByStudy.has(s.id)?resultByStudy.get(s.id).complete===false?'partialSubtitle':'completeSubtitle':classificationComplete(s)?'classifiedSubtitle':'readySubtitle');
$('sidebar-upload').disabled=busy;$('dropzone').setAttribute('aria-disabled',String(busy));
if(showStudy){$('viewer-image').pause();return;}
$('study-uid').textContent=s.study_uid;$('projection-count').textContent=s.projections.length;
if(!s.projections.some(x=>x.id===selectedProjectionId))selectedProjectionId=defaultProjection(s);
renderProjection();renderFilmstrip();renderCounts();renderResult();
}
function renderWorkflow(){if(interfaceRecoveryActive)return;
const study=currentStudy(),result=resultByStudy.get(study?.id);
const reviewed=classificationComplete(study);
const states={study:{enabled:!busy,done:!!study},projections:{enabled:!!study,done:reviewed},results:{enabled:!!result,done:!!result&&result.complete!==false}};
document.querySelectorAll('[data-workflow]').forEach(button=>{
const key=button.dataset.workflow,current=workflowView===key;
button.disabled=!states[key].enabled;
button.classList.toggle('active',current);button.classList.toggle('done',states[key].done);
if(current)button.setAttribute('aria-current','step');else button.removeAttribute('aria-current');
});
}
function navigateWorkflow(view){if(interfaceRecoveryActive)return;
const study=currentStudy();
if(!['study','projections','results'].includes(view)||(view==='study'&&busy)||(view!=='study'&&!study)||(view==='results'&&!resultByStudy.has(study?.id)))return;
workflowScrollUntil=performance.now()+800;
unresolvedSelection=null;workflowView=view;render();
const target=$(view==='study'?'welcome':view==='results'?'result-card':classificationComplete(study)?'projections-panel':'run-card');
target.focus({preventScroll:true});
target.scrollIntoView({behavior:window.matchMedia('(prefers-reduced-motion: reduce)').matches?'auto':'smooth',block:'start'});
}
function markWorkflow(view){if(interfaceRecoveryActive)return;
if(workflowView==='study'||workflowView===view||(view==='results'&&!resultByStudy.has(selectedStudyId)))return;
workflowView=view;renderWorkflow();persistWorkspace();
}
function classificationComplete(study){return study?.classification_complete===true;}
function projectionLabel(projection,study=currentStudy()){
if(classificationComplete(study))return ['left','right','exclude'].includes(projection.artery)?projection.artery:'unassigned';
return projection.frames<10?'exclude':'unassigned';
}
function labelFor(artery){return {left:'LCA',right:'RCA',exclude:t('excluded'),unassigned:t('unassigned')}[artery]||t('unassigned');}
function projectionReason(projection,study=currentStudy()){
const label=projectionLabel(projection,study),reason=projection.reason||'';
if(projection.frames<10||/fewer than 10 frames/i.test(reason))return t('reasonShort');
if(label==='unassigned')return t('reasonPending');
if(label!=='exclude')return '';
if(/low.confidence|uncertain/i.test(reason))return t('reasonUncertain');
return reason?localizeError(reason):t('reasonExcluded');
}
function studyAction(study){
const complete=classificationComplete(study),counts={left:0,right:0,exclude:0,unassigned:0};
for(const projection of study?.projections||[])counts[projectionLabel(projection,study)]++;
const eligible=(study?.projections||[]).filter(projection=>projection.frames>=10).length;
return{complete,counts,eligible,kind:complete?'inference':'classify',allowed:complete?counts.unassigned===0&&(counts.left+counts.right)>0:eligible>0};
}
function renderProjection(){if(interfaceRecoveryActive)return;
const projection=currentProjection();$('viewer-image').hidden=!projection;$('viewer-empty').hidden=!!projection;if(!projection)return;
const video=$('viewer-image'),src=projection.video_url||'';video.dataset.frames=String(projection.frames);video.poster=projection.preview_url;
if(video.dataset.current!==src){video.src=src;video.dataset.current=src;video.load();}
video.setAttribute('aria-label',`${t('projection')}: ${projection.name}`);$('viewer-name').textContent=projection.name;
$('viewer-dimensions').textContent=`${projection.rows||512} × ${projection.columns||512} · ${projection.frames} ${t('frames')}`;
$('viewer-position').textContent=`${String(currentStudy().projections.indexOf(projection)+1).padStart(2,'0')} / ${String(currentStudy().projections.length).padStart(2,'0')}`;
const label=projectionLabel(projection);$('viewer-artery').textContent=labelFor(label);
$('classification-label').textContent=labelFor(label);$('classification-label').className='classification-badge '+label;
const reason=projectionReason(projection);$('classification-reason').textContent=reason;$('classification-reason').hidden=!reason;
}
function renderFilmstrip(){if(interfaceRecoveryActive)return;
const strip=$('filmstrip');strip.replaceChildren();
currentStudy().projections.forEach((projection,index)=>{const label=projectionLabel(projection),button=el('button','projection-card'+(projection.id===selectedProjectionId?' selected':''));
button.setAttribute('aria-label',`${index+1}. ${projection.name}. ${labelFor(label)}`);button.setAttribute('aria-pressed',String(projection.id===selectedProjectionId));
const poster=el('img');poster.src=projection.preview_url;poster.alt='';poster.loading='lazy';
const meta=el('span','projection-card-bottom');meta.append(el('span','projection-tag '+label,labelFor(label)));
button.append(poster,el('span','projection-index',String(index+1).padStart(2,'0')),meta);
button.addEventListener('click',()=>{selectedProjectionId=projection.id;renderProjection();renderFilmstrip();});strip.append(button);
});
}
function renderCounts(){if(interfaceRecoveryActive)return;
const study=currentStudy(),action=studyAction(study),{counts}=action,hasResult=resultByStudy.has(study.id),running=busy&&(activeJob?.kind||action.kind);
$('left-count').textContent=action.complete?counts.left:'—';$('right-count').textContent=action.complete?counts.right:'—';$('excluded-count').textContent=counts.exclude;
let hint;if(!action.complete)hint=!action.eligible?t('noEligible'):t(action.eligible===1?'classificationPendingOne':'classificationPendingMany').replace('{count}',String(action.eligible));
else hint=t(counts.unassigned?'classificationIncomplete':!counts.left&&!counts.right?'noIncluded':counts.left&&counts.right?'bothReady':counts.left?'onlyLeft':'onlyRight');
$('run-hint').textContent=hint;
$('run-card').dataset.phase=action.complete?'score':'arteries';$('run-card').classList.toggle('is-running',!!running);
$('pipeline-position').textContent=action.complete?'2 / 2':'1 / 2';
for(const [node,active,done]of [[$('pipeline-arteries'),!action.complete,action.complete],[$('pipeline-score'),action.complete,hasResult]]){
node.classList.toggle('active',active);node.classList.toggle('done',done);if(active)node.setAttribute('aria-current','step');else node.removeAttribute('aria-current');
}
$('run-button-label').textContent=t(running?(running==='classify'?'jobClassify':'jobInference'):action.complete?(hasResult?'recalculate':'calculate'):'autoClassify');
$('run-button').disabled=busy||!action.allowed;$('run-button').setAttribute('aria-busy',String(!!running));$('run-button-spinner').hidden=!running;$('run-button-arrow').hidden=!!running;
}
function finite(...values){return values.find(v=>typeof v==='number'&&Number.isFinite(v));}
function number(value){return typeof value==='number'&&Number.isFinite(value)?value.toFixed(2):'—';}
function intermediateNumber(value){return typeof value==='number'&&Number.isFinite(value)?(Math.abs(value)<.0005?0:value).toFixed(3):'—';}
function coefficientNumber(value){return typeof value==='number'&&Number.isFinite(value)?String(value):'—';}
function resultRows(result){
if(!result)return[];
const recorded=result.per_fold||result.folds||[],left=result.left?.per_fold||[],right=result.right?.per_fold||[],coefficients=result.provenance?.calibration_source?.folds||[];
const length=Math.max(recorded.length,left.length,right.length);
return Array.from({length},(_,index)=>{const row=recorded[index]||{},coefficient=coefficients[row.fold??index]||{};return{fold:row.fold??index,left:finite(row.left,left[index]),right:finite(row.right,right[index]),raw:finite(row.raw,row.raw_score,row.total_raw),calibrated:finite(row.calibrated,row.calibrated_score,row.total_calibrated),a:finite(row.a,coefficient.a),b:finite(row.b,coefficient.b)};});
}
function meanComplete(rows,key){if(!rows.length||rows.some(row=>finite(row[key])===undefined))return undefined;return rows.reduce((sum,row)=>sum+row[key],0)/rows.length;}
function setSourceLink(node,url){try{const link=new URL(url);if(link.protocol!=='https:'||link.hostname!=='huggingface.co')throw new Error();node.href=link.href;node.hidden=false;}catch{node.removeAttribute('href');node.hidden=true;}}
function renderExperts(){
const study=currentStudy(),reference=finite(study?.reference_score),scores=Array.isArray(study?.expert_scores)&&study.expert_scores.length===6&&study.expert_scores.every(value=>finite(value)!==undefined)?study.expert_scores:[];
$('reference-score').hidden=reference===undefined&&!scores.length;
$('reference-score-value').textContent=number(reference);
$('expert-mean-caption').textContent=t(scores.length===6?'expertMeanSix':'expertMeanPublished');
const values=$('expert-scores');values.replaceChildren();values.hidden=!scores.length;
scores.forEach((value,index)=>{const cell=el('div','expert-score');cell.append(el('span','expert-label',`${t('expertLabel')} ${index}`),el('strong','',number(value)));values.append(cell);});
setSourceLink($('reference-source'),study?.reference_url);
}
function renderCalculation(result,rows){
const available=!!result&&rows.length>0,partial=result?.complete===false;
$('fold-results').hidden=!available;$('calculation-link').hidden=!available;
const body=$('fold-table-body');body.replaceChildren();
if(!available){$('mean-raw-number').textContent='—';$('mean-calibrated-number').textContent='—';$('final-total-number').textContent='—';$('negative-output-note').hidden=true;$('calibration-source').hidden=true;return;}
$('calculation-flow').hidden=partial;$('calculation-summary').hidden=partial;$('calculation-partial').hidden=!partial;
rows.forEach(row=>{const line=el('tr');const fold=el('th','',String(row.fold).padStart(2,'0'));fold.scope='row';let formula='—';if(row.a!==undefined&&row.b!==undefined&&row.raw!==undefined){const sum=intermediateNumber(row.raw);formula=`${coefficientNumber(row.a)} × ${row.raw<0?`(${sum})`:sum} ${row.b<0?'−':'+'} ${coefficientNumber(Math.abs(row.b))}`;}line.append(fold,el('td','model-output',intermediateNumber(row.left)),el('td','model-output',intermediateNumber(row.right)),el('td','paired-output',intermediateNumber(row.raw)),el('td','fold-formula',formula),el('td','calibrated-output',intermediateNumber(row.calibrated)));body.append(line);});
const rawMean=meanComplete(rows,'raw'),calibratedMean=meanComplete(rows,'calibrated');
$('mean-raw-number').textContent=intermediateNumber(rawMean);$('mean-calibrated-number').textContent=intermediateNumber(calibratedMean);$('final-total-number').textContent=number(finite(result.calibrated,result.calibrated_score,result.total?.calibrated));
$('raw-total-caption').textContent=t('beforeDisplayed').replace('{value}',number(finite(result.raw,result.raw_score,result.total?.raw)));
$('negative-output-note').hidden=!rows.some(row=>[row.left,row.right,row.raw,row.calibrated].some(value=>value!==undefined&&value<0));
const source=result.provenance?.calibration_source,revision=result.provenance?.revision||result.provenance?.model_revision,repo=result.provenance?.repo_id||result.provenance?.repository||result.provenance?.model_repository;
setSourceLink($('calibration-source'),source?.path&&revision&&repo?`https://huggingface.co/${repo}/blob/${revision}/${source.path}`:undefined);
}
function renderResult(){
const result=resultByStudy.get(selectedStudyId),rows=resultRows(result),calibrated=result?finite(result.calibrated,result.calibrated_score,result.total?.calibrated):undefined,raw=result?finite(result.raw,result.raw_score,result.total?.raw):undefined,complete=!!result&&result.complete!==false&&calibrated!==undefined;
$('result-card').classList.toggle('is-partial',!!result&&!complete);
$('result-details').hidden=!result;$('result-origin').hidden=result?.source?.type!=='precomputed_example';$('result-origin').textContent=t('precomputedLabel');
$('result-state').textContent=result?t(complete?'complete':'partial'):t('notCalculated');$('result-state').className='neutral-badge'+(result?' complete':'');
$('score-number').className='score-number'+(!result?' empty':'');$('score-number').textContent=complete?number(calibrated):'—';$('raw-total-number').textContent=result&&result.complete!==false?number(raw):'—';
$('score-caption').textContent=t(!result?'resultEmpty':complete?'calibratedCaption':'partialCaption');
renderExperts();renderCalculation(result,rows);
const revision=result?.provenance?.revision||result?.provenance?.model_revision;if(revision){$('model-revision').textContent=revision.slice(0,8);$('model-revision').href=`https://huggingface.co/${result.provenance.repo_id||result.provenance.repository||result.provenance.model_repository||'MesserMMP/coronary-syntax-prediction'}/tree/${revision}`;}
}
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);}
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);}
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(()=>{});}
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();}}}
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();});}
async function startJob(){
if(interfaceRecoveryActive||busy)return;if(previewMode){showError(t('previewHint'));return;}const study=currentStudy();if(!study)return;
const action=studyAction(study);if(!action.allowed)return;const kind=action.kind;
hideError();busy=true;render();$('job-status').hidden=false;$('job-message').textContent=t('queued');$('job-percentage').textContent='';$('job-progress').value=0;
try{const options={method:'POST'};if(kind==='inference'){options.headers={'Content-Type':'application/json'};options.body='{}';}
const job=await request(`/api/studies/${study.id}/${kind==='classify'?'classify':'run'}`,options);activeJob={...job,study_id:study.id};persistWorkspace();renderCounts();pollJob();
}catch(error){finishJob();showError(error.message);}
}
function finishJob(){if(interfaceRecoveryActive)return;busy=false;activeJob=null;clearTimeout(pollTimer);$('job-status').hidden=true;$('upload-overlay').hidden=true;render();refreshStatus();}
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);}}}
let examples=[];
function referenceNumber(value){return value.toFixed(2);}
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')));}
async function loadExamples(){if(interfaceRecoveryActive||previewMode)return;try{const d=await request('/api/examples');examples=d.examples||[];renderExamples();}catch{}}
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);}}
let expandedPlayback=null;
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();}
function closeExpandedPreview(){if(interfaceRecoveryActive)return;const video=$('dialog-image'),main=$('viewer-image');const paused=video.paused;video.pause();if(expandedPlayback&¤tProjection()?.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;}
const cinePlayers=[];let cinePlaybackRate=1;
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);}}
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);}
function cineFrame(player){const {video}=player,frames=Number(video.dataset.frames)||0;return frames&&Number.isFinite(video.duration)&&video.duration>0?Math.min(frames-1,Math.floor(video.currentTime/video.duration*frames)):0;}
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);}
function stepCine(player,delta){player.video.pause();seekCine(player,cineFrame(player)+delta);}
function toggleCine(player){if(player.video.paused)player.video.play().catch(()=>{});else player.video.pause();}
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;}
document.querySelectorAll('[data-workflow]').forEach(button=>button.addEventListener('click',()=>navigateWorkflow(button.dataset.workflow)));
$('projections-panel').addEventListener('focusin',()=>markWorkflow('projections'));
for(const id of ['result-card','fold-results'])$(id).addEventListener('focusin',()=>markWorkflow('results'));
$('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'});});
let workflowScrollFrame=null;
window.addEventListener('scroll',()=>{
if(interfaceRecoveryActive||workflowScrollFrame)return;
workflowScrollFrame=requestAnimationFrame(()=>{
workflowScrollFrame=null;
if(interfaceRecoveryActive)return;
if(performance.now()<workflowScrollUntil||workflowView==='study'||!resultByStudy.has(selectedStudyId))return;
const edge=document.querySelector('.topbar').getBoundingClientRect().bottom+60;
if($('fold-results').getBoundingClientRect().top<=edge)markWorkflow('results');
else if(window.matchMedia('(max-width: 760px)').matches){
const resultTop=$('result-card').getBoundingClientRect().top;
if(resultTop<=edge)markWorkflow('results');
else if(resultTop>window.innerHeight*.7&&$('projections-panel').getBoundingClientRect().bottom>edge)markWorkflow('projections');
}
});
},{passive:true});
$('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)));
$('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);
$('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;});
$('copy-uid').addEventListener('click',async()=>{try{await navigator.clipboard.writeText(currentStudy()?.study_uid||'');toast(t('copied'));}catch{toast(t('copyFailed'));}});
$('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);});
$('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);});
let workspaceRestored=false;
const unresolvedStudyIds=new Set(),unresolvedResultJobs=new Map(),deferredJobs=new Map();
let unresolvedSelection=null;
function jobHandle(job){return{id:job.id,kind:job.kind,study_id:job.study_id};}
function forgetStudyRecovery(id){unresolvedStudyIds.delete(id);unresolvedResultJobs.delete(id);for(const [jobId,job]of deferredJobs)if(job.study_id===id)deferredJobs.delete(jobId);if(unresolvedSelection?.id===id)unresolvedSelection=null;}
function workspaceSnapshot(){
return{study_ids:[...new Set([...studies.map(study=>study.id),...unresolvedStudyIds])],selected_study_id:unresolvedSelection?.id??selectedStudyId,workflow_view:unresolvedSelection?.view??workflowView,active_job:activeJob?jobHandle(activeJob):null,deferred_jobs:[...deferredJobs.values()].filter(job=>job.id!==activeJob?.id).map(jobHandle),result_jobs:[...new Map([...unresolvedResultJobs,...resultJobByStudy])]};
}
function persistWorkspace(){if(previewMode||!workspaceRestored)return;try{sessionStorage.setItem('cardiosyntax-workspace',JSON.stringify(workspaceSnapshot()));}catch{}}
async function restoreWorkspace(){
let saved;try{saved=JSON.parse(sessionStorage.getItem('cardiosyntax-workspace')||'null');}catch{workspaceRestored=true;return;}
if(!saved){workspaceRestored=true;return;}
const expiredStudyIds=new Set();
const restored=await Promise.all((saved.study_ids||[]).map(async id=>{
try{const data=await request('/api/studies/'+encodeURIComponent(id)),study=data.study||data;if(study?.id!==id||!Array.isArray(study.projections))throw new Error(t('invalidResponse'));return study;}
catch(error){if(error.status===404)expiredStudyIds.add(id);else unresolvedStudyIds.add(id);return null;}
}));
studies=restored.filter(Boolean);
for(const [studyId,jobId]of saved.result_jobs||[]){
const study=studies.find(item=>item.id===studyId);
if(!study){if(unresolvedStudyIds.has(studyId))unresolvedResultJobs.set(studyId,jobId);continue;}
try{const job=await request('/api/jobs/'+encodeURIComponent(jobId));if(job.status==='completed'&&job.kind==='inference'&&resultMatchesStudy(job.result,study)){resultByStudy.set(studyId,job.result);resultJobByStudy.set(studyId,jobId);}else if(!['completed','failed'].includes(job.status))unresolvedResultJobs.set(studyId,jobId);}
catch(error){if(error.status!==404)unresolvedResultJobs.set(studyId,jobId);}
}
const candidates=new Map();
for(const job of [saved.active_job,...(saved.deferred_jobs||[])])if(job?.id)candidates.set(job.id,jobHandle(job));
let completedExampleStudyId=null;
for(const candidate of candidates.values()){
if(candidate.kind!=='example'&&expiredStudyIds.has(candidate.study_id))continue;
if(candidate.kind!=='example'&&!studies.some(study=>study.id===candidate.study_id)){if(unresolvedStudyIds.has(candidate.study_id))deferredJobs.set(candidate.id,candidate);continue;}
try{
const job=await request('/api/jobs/'+encodeURIComponent(candidate.id));
if(job.status==='queued'||job.status==='running'){if(!activeJob)activeJob={...job,kind:job.kind||candidate.kind,study_id:job.study_id||candidate.study_id};else deferredJobs.set(candidate.id,candidate);}
else if(job.status==='completed'&&candidate.kind==='inference'){
const study=studies.find(item=>item.id===candidate.study_id);if(resultMatchesStudy(job.result,study)){resultByStudy.set(study.id,job.result);resultJobByStudy.set(study.id,job.id);unresolvedResultJobs.delete(study.id);}
}else if(job.status==='completed'&&candidate.kind==='classify'){const updated=job.result?.study;if(updated){const index=studies.findIndex(study=>study.id===updated.id);if(index>=0)studies[index]=updated;resultByStudy.delete(updated.id);resultJobByStudy.delete(updated.id);unresolvedResultJobs.delete(updated.id);}}else if(job.status==='completed'&&candidate.kind==='example'){
const payload=job.result||{};for(const study of payload.studies||[]){const index=studies.findIndex(item=>item.id===study.id);if(index<0)studies.push(study);else studies[index]=study;unresolvedStudyIds.delete(study.id);}
adoptCachedJob(payload.cached_job);completedExampleStudyId=payload.studies?.[0]?.id||completedExampleStudyId;
}else if(!['completed','failed'].includes(job.status))deferredJobs.set(candidate.id,candidate);
}catch(error){if(error.status!==404)deferredJobs.set(candidate.id,candidate);}
}
if(!completedExampleStudyId&&unresolvedStudyIds.has(saved.selected_study_id))unresolvedSelection={id:saved.selected_study_id,view:saved.workflow_view};
selectedStudyId=completedExampleStudyId||(saved.selected_study_id===null?null:studies.some(study=>study.id===saved.selected_study_id)?saved.selected_study_id:studies[0]?.id||null);
selectedProjectionId=defaultProjection(currentStudy());
workflowView=completedExampleStudyId?'projections':['study','projections','results'].includes(saved.workflow_view)?saved.workflow_view:currentStudy()?'projections':'study';
workspaceRestored=true;
if(interfaceRecoveryActive)return;
if(activeJob){busy=true;$('job-status').hidden=false;if(activeJob.kind==='example')$('upload-overlay').hidden=false;pollJob();}
render();
if(unresolvedStudyIds.size||unresolvedResultJobs.size||deferredJobs.size)showError(t('restoreTemporary'));
else if(expiredStudyIds.size&&!studies.length)showError(t('expired'));
}
function localizeStage(message){if(!message||lang==='en')return message;const inference=message.match(/Processing (left|right) artery.*model (\d+) of (\d+)/i);if(inference)return `Вычисляем ${inference[1].toLowerCase()==='left'?'LCA':'RCA'} · модель ${inference[2]} из ${inference[3]}`;const rules=[[/download/i,'Загружаем необходимые файлы…'],[/loading.*model|loading.*weight|preparing.*model/i,'Подготавливаем модели…'],[/classif|arter/i,'Определяем принадлежность проекций…'],[/fold\s*(\d+)/i,'Вычисляем результат ансамбля…'],[/decod|read.*dicom|extract/i,'Читаем DICOM…'],[/queued|waiting/i,'Ожидаем запуска…'],[/complete|finished/i,'Готово']];return rules.find(([pattern])=>pattern.test(message))?.[1]||message;}
window.addEventListener('beforeunload',()=>clearTimeout(pollTimer));
const mobileLayout=window.matchMedia('(max-width: 760px)');
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);}
mobileLayout.addEventListener('change',placeFoldResults);
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();}
init().catch(()=>showInterfaceRecovery(false));
}
if(interfaceCompatible())startCardioSyntax();else showInterfaceRecovery();
|