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

Show connection progress before the first service response

Browse files
Files changed (1) hide show
  1. static/app.js +3 -3
static/app.js CHANGED
@@ -3,7 +3,7 @@ const $=id=>document.getElementById(id);
3
  const words={en:{studies:'Studies',addStudy:'Add study',sidebarEmpty:'No studies loaded.',ephemeral:'Session',sessionHint:'Files expire after 1 hour of inactivity.',modelLink:'Model & methodology ↗',datasetLink:'Open dataset ↗',workspace:'SYNTAX analysis',initialTitle:'New study',initialSubtitle:'Upload DICOM or open a public example.',researchOnly:'Research use',stepUpload:'Upload',stepReview:'Review',stepResult:'Result',dropTitle:'Upload DICOM',dropDescription:'Drop study files or a ZIP archive.',chooseFiles:'Choose files',beforeStart:'Input requirements',prepareTitle:'De-identified DICOM',prepareText:'Remove personal information before upload.',runTitle:'LCA and RCA projections',runText:'Both arteries are required for a full-study score.',projection:'Projection',selectProjection:'Select a projection',dicomPreview:'DICOM · contrast-adjusted preview',projectionAssignment:'Artery',leftArtery:'Left',rightArtery:'Right',exclude:'Exclude',allProjections:'Projections',autoClassify:'Identify arteries',resultTitle:'Result',notCalculated:'Not calculated',resultEmpty:'Run analysis to calculate the score.',rawSideNote:'Before calibration',downloadResult:'Export JSON',readyToRun:'Projection summary',excluded:'Excluded',calculate:'Calculate SYNTAX',jobHint:'The first run downloads the model weights.',jobHintCpu:'CPU analysis can take several minutes.',reviewOne:'1 projection needs review.',reviewMany:'{count} projections need review.',methodTitle:'Model',ensemble:'Ensemble',ensembleValue:'5 folds · 10 models',calibration:'Calibration',calibrationValue:'Applied per fold',device:'Compute',modelVersion:'Model revision',modelScope:'Research use only.',foldResults:'Five-fold ensemble results',foldHint:'',rawScore:'Before calibration',calibratedScore:'After calibration',uploading:'Reading your study',uploadingHint:'Checking DICOM and grouping projections by StudyUID.',connecting:'Connecting…',offline:'Service unavailable',weightsDemand:'weights on demand',modelReady:'model available',weightsCached:'weights cached',modelLoading:'loading weights',modelError:'model unavailable',study:'Study',projections:'projections',frames:'frames',unassigned:'Unassigned',ready:'Ready',complete:'Complete',partial:'Partial',calibratedCaption:'Calibrated ensemble estimate',partialCaption:'A full-study score needs both arteries. Available artery estimates are shown below.',greater22:'SYNTAX ≥ 22',notGreater22:'SYNTAX < 22',reviewUnassigned:'Assign or exclude every projection before running.',bothReady:'Both coronary arteries included.',onlyLeft:'Only LCA is represented. The result will be partial.',onlyRight:'Only RCA is represented. The result will be partial.',noIncluded:'Assign at least one eligible projection to an artery.',shortProjection:'Fewer than 10 frames · excluded from inference',shortCannotAssign:'Clips shorter than 10 frames cannot be included.',assignmentDefault:'',copied:'StudyUID copied',copyFailed:'Could not copy StudyUID',deleted:'Study removed',deleteConfirm:'Remove this study and its uploaded files?',processing:'Processing…',queued:'Waiting to start…',failed:'The operation could not be completed.',invalidResponse:'The service returned an unexpected response.',loaded:'Study loaded',excludedFiles:'Files not added',noStudies:'No usable studies were found.',previewLabel:'Design preview · real public DICOM, no model prediction',previewHint:'This is a design preview. Open the workspace to upload a study and run the model.',earlier:'Move earlier',later:'Move later',order:'Projection order',exampleTitle:'Public examples',referenceLabel:'Reference',referenceSyntaxLabel:'Reference SYNTAX',modelLabel:'Model',precomputedLabel:'Precomputed',exampleLoad:'Open example',exampleHint:'Published holdout studies.',loadingExample:'Loading the example',notAvailable:'Not available',deviceLocal:'Compute',resultStale:'Assignments changed. Run the model again.',atLeastOne:'Choose DICOM files or a ZIP archive.',readySubtitle:'Review the artery assignments.',lowConfidence:'Review suggested assignment',jobClassify:'Identifying arteries',jobInference:'Calculating SYNTAX',jobExample:'Loading public example',confirmAuto:'Automatic classification will replace the current artery assignments for this study.',confirmClassifyTitle:'Replace artery assignments?',confirmDeleteTitle:'Remove this study?',dialogCancel:'Cancel',dialogContinue:'Continue',modelPreparing:'Preparing the ensemble',downloadFailed:'No result is available yet.',close:'Close',expand:'Expand preview',copyUid:'Copy StudyUID',arteryControls:'Artery assignment',workflow:'Workflow',previewVideo:'Angiography display preview',expandedVideo:'Expanded angiography display preview',removeStudy:'Remove study',modelsLicense:'Models & data · CC BY 4.0',expired:'This temporary session has expired. Please upload the study again.',lightTheme:'Light',darkTheme:'Dark',appearance:'Color theme',recalculate:'Recalculate SYNTAX',completeSubtitle:'Analysis complete.',partialSubtitle:'Partial analysis — one coronary artery is missing.',play:'Play',pause:'Pause',previousFrame:'Previous frame',nextFrame:'Next frame',seekFrame:'Frame',framePosition:'Frame {frame} of {total}',collapsePreview:'Return to study',playbackSpeed:'Playback speed',playbackSpeedValue:'Playback speed: {rate}×'},ru:{studies:'Исследования',addStudy:'Добавить исследование',sidebarEmpty:'Исследования не загружены.',ephemeral:'Сессия',sessionHint:'Файлы удаляются после 1 часа бездействия.',modelLink:'Модель и методология ↗',datasetLink:'Открытый датасет ↗',workspace:'Анализ SYNTAX',initialTitle:'Новое исследование',initialSubtitle:'Загрузите DICOM или откройте публичный пример.',researchOnly:'Для исследований',stepUpload:'Загрузить',stepReview:'Проверить',stepResult:'Результат',dropTitle:'Загрузить DICOM',dropDescription:'Перетащите файлы исследования или ZIP-архив.',chooseFiles:'Выбрать файлы',beforeStart:'Требования к данным',prepareTitle:'Обезличенные DICOM',prepareText:'Удалите персональную информацию до загрузки.',runTitle:'Проекции LCA и RCA',runText:'Для полной оценки нужны обе артерии.',projection:'Проекция',selectProjection:'Выберите проекцию',dicomPreview:'DICOM · контраст для просмотра',projectionAssignment:'Артерия',leftArtery:'Левая',rightArtery:'Правая',exclude:'Исключить',allProjections:'Проекции',autoClassify:'Определить артерии',resultTitle:'Результат',notCalculated:'Не рассчитан',resultEmpty:'Запустите анализ для расчёта оценки.',rawSideNote:'До калибровки',downloadResult:'Экспорт JSON',readyToRun:'Состав проекций',excluded:'Исключено',calculate:'Рассчитать SYNTAX',jobHint:'При первом запуске загружаются веса модели.',jobHintCpu:'Расчёт на CPU может занять несколько минут.',reviewOne:'Проверить проекции: 1.',reviewMany:'Проверить проекции: {count}.',methodTitle:'Модель',ensemble:'Ансамбль',ensembleValue:'5 фолдов · 10 моделей',calibration:'Калибровка',calibrationValue:'Для каждого фолда',device:'Вычисления',modelVersion:'Версия модели',modelScope:'Только для исследований.',foldResults:'Оценки по фолдам',foldHint:'',rawScore:'До калибровки',calibratedScore:'После калибровки',uploading:'Читаем исследование',uploadingHint:'Проверяем DICOM и собираем проекции по StudyUID.',connecting:'Подключение…',offline:'Сервис недоступен',weightsDemand:'веса по запросу',modelReady:'модель доступна',weightsCached:'веса загружены',modelLoading:'загрузка весов',modelError:'модель недоступна',study:'Исследование',projections:'проекций',frames:'кадров',unassigned:'Не назначена',ready:'Готово',complete:'Рассчитан',partial:'Частичный',calibratedCaption:'Калиброванная оценка ансамбля',partialCaption:'Для итоговой оценки нужны обе артерии. Ниже показаны доступные вклады.',greater22:'SYNTAX ≥ 22',notGreater22:'SYNTAX < 22',reviewUnassigned:'Назначьте или исключите каждую проекцию перед расчётом.',bothReady:'Обе коронарные артерии включены.',onlyLeft:'Представлена только LCA. Результат будет частичным.',onlyRight:'Представлена только RCA. Результат будет частичным.',noIncluded:'Назначьте хотя бы одну подходящую проекцию артерии.',shortProjection:'Меньше 10 кадров · исключено из расчёта',shortCannotAssign:'Видео короче 10 кадров нельзя включить в расчёт.',assignmentDefault:'',copied:'StudyUID скопирован',copyFailed:'Не удалось скопировать StudyUID',deleted:'Исследование удалено',deleteConfirm:'Удалить исследование и загруженные файлы?',processing:'Обработка…',queued:'Ожидаем запуска…',failed:'Не удалось завершить операцию.',invalidResponse:'Сервис вернул неожиданный ответ.',loaded:'Исследование загружено',excludedFiles:'Файлы не добавлены',noStudies:'Подходящие исследования не найдены.',previewLabel:'Макет интерфейса · реальные публичные DICOM, без предсказания модели',previewHint:'Это макет интерфейса. Откройте рабочее пространство для загрузки и расчёта.',earlier:'Раньше',later:'Позже',order:'Порядок проекций',exampleTitle:'Публичные примеры',referenceLabel:'Эталон',referenceSyntaxLabel:'Эталон SYNTAX',modelLabel:'Модель',precomputedLabel:'Сохранённый результат',exampleLoad:'Открыть пример',exampleHint:'Исследования из опубликованных holdout.',loadingExample:'Загружаем пример',notAvailable:'Недоступно',deviceLocal:'Вычисления',resultStale:'Назначения изменены. Запустите расчёт заново.',atLeastOne:'Выберите DICOM-файлы или ZIP-архив.',readySubtitle:'Проверьте назначения артерий.',lowConfidence:'Проверьте предложенную артерию',jobClassify:'Определяем артерии',jobInference:'Рассчитываем SYNTAX',jobExample:'Загружаем публичный пример',confirmAuto:'Автоматическое определение заменит текущие назначения артерий для этого исследования.',confirmClassifyTitle:'Заменить назначения артерий?',confirmDeleteTitle:'Удалить исследование?',dialogCancel:'Отмена',dialogContinue:'Продолжить',modelPreparing:'Подготовка ансамбля',downloadFailed:'Результат пока недоступен.',close:'Закрыть',expand:'Увеличить превью',copyUid:'Копировать StudyUID',arteryControls:'Назначение артерии',workflow:'Этапы анализа',previewVideo:'Превью коронарной ангиографии',expandedVideo:'Увеличенное превью коронарной ангиографии',removeStudy:'Удалить исследование',modelsLicense:'Модели и данные · CC BY 4.0',expired:'Срок временного хранения истёк. Загрузите исследование заново.',lightTheme:'Светлая',darkTheme:'Тёмная',appearance:'Цветовая тема',recalculate:'Пересчитать SYNTAX',completeSubtitle:'Анализ завершён.',partialSubtitle:'Частичный анализ — отсутствует одна из артерий.',play:'Воспроизвести',pause:'Пауза',previousFrame:'Предыдущий кадр',nextFrame:'Следующий кадр',seekFrame:'Кадр',framePosition:'Кадр {frame} из {total}',collapsePreview:'Вернуться к исследованию',playbackSpeed:'Скорость воспроизведения',playbackSpeedValue:'Скорость воспроизведения: {rate}×'}};
4
  const safeStored=(key,fallback)=>{try{return localStorage.getItem(key)||fallback;}catch{return fallback;}};
5
  let lang=safeStored('cardiosyntax-language','en');if(!words[lang])lang='en';
6
- let studies=[],selectedStudyId=null,selectedProjectionId=null,status=null,busy=false,activeJob=null,pollTimer=null,resultByStudy=new Map(),resultJobByStudy=new Map();
7
  const previewMode=document.body.dataset.preview==='true';
8
  const t=k=>words[lang][k]??words.en[k]??k;
9
  const icon=name=>{const svg=document.createElementNS('http://www.w3.org/2000/svg','svg');const use=document.createElementNS('http://www.w3.org/2000/svg','use');use.setAttribute('href','#i-'+name);svg.append(use);return svg;};
@@ -19,8 +19,8 @@ function toast(message){const old=document.querySelector('.toast');old?.remove()
19
  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');}
20
  function localizeError(message){if(lang==='en'||typeof message!=='string')return message;const map=[[/expired/i,t('expired')],[/Insufficient memory/i,'Недостаточно памяти для исследования. Уменьшите число проекций или используйте более мощный сервер.'],[/model could not complete/i,'Модель не смогла завершить расчёт. Проверьте доступность весов и ресурсы сервера, затем повторите попытку. Оценка не рассчитана.'],[/another.*job|job.*running|already.*running|busy/i,'Сервер выполняет другой расчёт. Повторите попытку после его завершения.'],[/upload exceeds|expanded files exceed/i,'Превышен допустимый размер загружаемых файлов.'],[/Duplicate SOPInstanceUID/i,'Файл с таким SOPInstanceUID уже есть в загрузке; повторная копия не добавлена.'],[/not.*DICOM|invalid DICOM/i,'Файл не является корректным DICOM.']];return map.find(([pattern])=>pattern.test(message))?.[1]||message;}
21
  async function request(url,options={}){let response;try{response=await fetch(url,{cache:'no-store',...options});}catch{throw new Error(t('offline'));}let data;try{data=await response.json();}catch{throw new Error(t('invalidResponse'));}if(!response.ok){const e=new Error(errorText(data.detail||data.error||data));e.status=response.status;throw e;}return data;}
22
- async function refreshStatus(){if(previewMode)return;try{status=await request('/api/status');renderStatus();}catch{status=null;renderStatus();}}
23
- function renderStatus(){renderJobHint();const dot=$('server-indicator').querySelector('.status-dot');if(previewMode){$('server-label').textContent=lang==='en'?'Design preview':'Макет интерфейса';dot.className='status-dot';$('method-device').textContent=t('notAvailable');return;}if(!status){$('server-label').textContent=t('offline');dot.className='status-dot error';return;}const device=String(status.device||'cpu').toUpperCase();const state=status.model?.status||'not_loaded';const key={not_loaded:'weightsDemand',loading:'modelLoading',ready:'modelReady',cached:'weightsCached',error:'modelError',unavailable:'modelError'}[state]||'weightsDemand';$('server-label').textContent=`${device} · ${t(key)}`;dot.className='status-dot'+(['error','unavailable'].includes(state)?' error':' ready');$('method-device').textContent=device;const revision=status.model?.revision||status.revision;if(revision){$('model-revision').textContent=revision.slice(0,8);$('model-revision').href=`https://huggingface.co/${status.model?.repository||status.repo_id||'MesserMMP/coronary-syntax-prediction'}/tree/${revision}`;}const limits=status.limits;if(limits)$('upload-limits').textContent=`DICOM · ZIP · ${limits.max_request_mb||512} MB · ${limits.max_files||64} ${lang==='en'?'files':'файла'}`;}
24
  function renderJobHint(){const node=$('job-hint');if(!node)return;const cached=status?.cached===true||['cached','ready'].includes(status?.model?.status);const cpu=String(status?.device||'').toLowerCase()==='cpu';node.hidden=!status||(cached&&!cpu);node.textContent=(!cached?t('jobHint'):'')+(cpu?(!cached?' ':'')+t('jobHintCpu'):'');}
25
  function renderSidebar(){$('study-count').textContent=studies.length;const list=$('study-list');list.replaceChildren();if(!studies.length){list.append(el('div','sidebar-empty',t('sidebarEmpty')));return;}studies.forEach((s,i)=>{const b=el('button','study-item'+(s.id===selectedStudyId?' selected':''));b.disabled=busy;b.setAttribute('aria-current',s.id===selectedStudyId?'true':'false');const logo=el('span','study-item-icon');logo.append(icon('file'));const text=el('span','study-item-text');text.append(el('strong','',`${t('study')} ${String(i+1).padStart(2,'0')}`),el('small','',`${s.projections.length} ${t('projections')}${resultByStudy.has(s.id)?' · '+t(resultByStudy.get(s.id).complete===false?'partial':'complete'):''}`));b.append(logo,text);if(resultByStudy.has(s.id))b.append(el('span','status-mini'));b.addEventListener('click',()=>selectStudy(s.id));list.append(b);});}
26
  function defaultProjection(study){return study?.projections.find(p=>p.id===study.default_projection_id)?.id||study?.projections[0]?.id||null;}
 
3
  const words={en:{studies:'Studies',addStudy:'Add study',sidebarEmpty:'No studies loaded.',ephemeral:'Session',sessionHint:'Files expire after 1 hour of inactivity.',modelLink:'Model & methodology ↗',datasetLink:'Open dataset ↗',workspace:'SYNTAX analysis',initialTitle:'New study',initialSubtitle:'Upload DICOM or open a public example.',researchOnly:'Research use',stepUpload:'Upload',stepReview:'Review',stepResult:'Result',dropTitle:'Upload DICOM',dropDescription:'Drop study files or a ZIP archive.',chooseFiles:'Choose files',beforeStart:'Input requirements',prepareTitle:'De-identified DICOM',prepareText:'Remove personal information before upload.',runTitle:'LCA and RCA projections',runText:'Both arteries are required for a full-study score.',projection:'Projection',selectProjection:'Select a projection',dicomPreview:'DICOM · contrast-adjusted preview',projectionAssignment:'Artery',leftArtery:'Left',rightArtery:'Right',exclude:'Exclude',allProjections:'Projections',autoClassify:'Identify arteries',resultTitle:'Result',notCalculated:'Not calculated',resultEmpty:'Run analysis to calculate the score.',rawSideNote:'Before calibration',downloadResult:'Export JSON',readyToRun:'Projection summary',excluded:'Excluded',calculate:'Calculate SYNTAX',jobHint:'The first run downloads the model weights.',jobHintCpu:'CPU analysis can take several minutes.',reviewOne:'1 projection needs review.',reviewMany:'{count} projections need review.',methodTitle:'Model',ensemble:'Ensemble',ensembleValue:'5 folds · 10 models',calibration:'Calibration',calibrationValue:'Applied per fold',device:'Compute',modelVersion:'Model revision',modelScope:'Research use only.',foldResults:'Five-fold ensemble results',foldHint:'',rawScore:'Before calibration',calibratedScore:'After calibration',uploading:'Reading your study',uploadingHint:'Checking DICOM and grouping projections by StudyUID.',connecting:'Connecting…',offline:'Service unavailable',weightsDemand:'weights on demand',modelReady:'model available',weightsCached:'weights cached',modelLoading:'loading weights',modelError:'model unavailable',study:'Study',projections:'projections',frames:'frames',unassigned:'Unassigned',ready:'Ready',complete:'Complete',partial:'Partial',calibratedCaption:'Calibrated ensemble estimate',partialCaption:'A full-study score needs both arteries. Available artery estimates are shown below.',greater22:'SYNTAX ≥ 22',notGreater22:'SYNTAX < 22',reviewUnassigned:'Assign or exclude every projection before running.',bothReady:'Both coronary arteries included.',onlyLeft:'Only LCA is represented. The result will be partial.',onlyRight:'Only RCA is represented. The result will be partial.',noIncluded:'Assign at least one eligible projection to an artery.',shortProjection:'Fewer than 10 frames · excluded from inference',shortCannotAssign:'Clips shorter than 10 frames cannot be included.',assignmentDefault:'',copied:'StudyUID copied',copyFailed:'Could not copy StudyUID',deleted:'Study removed',deleteConfirm:'Remove this study and its uploaded files?',processing:'Processing…',queued:'Waiting to start…',failed:'The operation could not be completed.',invalidResponse:'The service returned an unexpected response.',loaded:'Study loaded',excludedFiles:'Files not added',noStudies:'No usable studies were found.',previewLabel:'Design preview · real public DICOM, no model prediction',previewHint:'This is a design preview. Open the workspace to upload a study and run the model.',earlier:'Move earlier',later:'Move later',order:'Projection order',exampleTitle:'Public examples',referenceLabel:'Reference',referenceSyntaxLabel:'Reference SYNTAX',modelLabel:'Model',precomputedLabel:'Precomputed',exampleLoad:'Open example',exampleHint:'Published holdout studies.',loadingExample:'Loading the example',notAvailable:'Not available',deviceLocal:'Compute',resultStale:'Assignments changed. Run the model again.',atLeastOne:'Choose DICOM files or a ZIP archive.',readySubtitle:'Review the artery assignments.',lowConfidence:'Review suggested assignment',jobClassify:'Identifying arteries',jobInference:'Calculating SYNTAX',jobExample:'Loading public example',confirmAuto:'Automatic classification will replace the current artery assignments for this study.',confirmClassifyTitle:'Replace artery assignments?',confirmDeleteTitle:'Remove this study?',dialogCancel:'Cancel',dialogContinue:'Continue',modelPreparing:'Preparing the ensemble',downloadFailed:'No result is available yet.',close:'Close',expand:'Expand preview',copyUid:'Copy StudyUID',arteryControls:'Artery assignment',workflow:'Workflow',previewVideo:'Angiography display preview',expandedVideo:'Expanded angiography display preview',removeStudy:'Remove study',modelsLicense:'Models & data · CC BY 4.0',expired:'This temporary session has expired. Please upload the study again.',lightTheme:'Light',darkTheme:'Dark',appearance:'Color theme',recalculate:'Recalculate SYNTAX',completeSubtitle:'Analysis complete.',partialSubtitle:'Partial analysis — one coronary artery is missing.',play:'Play',pause:'Pause',previousFrame:'Previous frame',nextFrame:'Next frame',seekFrame:'Frame',framePosition:'Frame {frame} of {total}',collapsePreview:'Return to study',playbackSpeed:'Playback speed',playbackSpeedValue:'Playback speed: {rate}×'},ru:{studies:'Исследования',addStudy:'Добавить исследование',sidebarEmpty:'Исследования не загружены.',ephemeral:'Сессия',sessionHint:'Файлы удаляются после 1 часа бездействия.',modelLink:'Модель и методология ↗',datasetLink:'Открытый датасет ↗',workspace:'Анализ SYNTAX',initialTitle:'Новое исследование',initialSubtitle:'Загрузите DICOM или откройте публичный пример.',researchOnly:'Для исследований',stepUpload:'Загрузить',stepReview:'Проверить',stepResult:'Результат',dropTitle:'Загрузить DICOM',dropDescription:'Перетащите файлы исследования или ZIP-архив.',chooseFiles:'Выбрать файлы',beforeStart:'Требования к данным',prepareTitle:'Обезличенные DICOM',prepareText:'Удалите персональную информацию до загрузки.',runTitle:'Проекции LCA и RCA',runText:'Для полной оценки нужны обе артерии.',projection:'Проекция',selectProjection:'Выберите проекцию',dicomPreview:'DICOM · контраст для просмотра',projectionAssignment:'Артерия',leftArtery:'Левая',rightArtery:'Правая',exclude:'Исключить',allProjections:'Проекции',autoClassify:'Определить артерии',resultTitle:'Результат',notCalculated:'Не рассчитан',resultEmpty:'Запустите анализ для расчёта оценки.',rawSideNote:'До калибровки',downloadResult:'Экспорт JSON',readyToRun:'Состав проекций',excluded:'Исключено',calculate:'Рассчитать SYNTAX',jobHint:'При первом запуске загружаются веса модели.',jobHintCpu:'Расчёт на CPU может занять несколько минут.',reviewOne:'Проверить проекции: 1.',reviewMany:'Проверить проекции: {count}.',methodTitle:'Модель',ensemble:'Ансамбль',ensembleValue:'5 фолдов · 10 моделей',calibration:'Калибровка',calibrationValue:'Для каждого фолда',device:'Вычисления',modelVersion:'Версия модели',modelScope:'Только для исследований.',foldResults:'Оценки по фолдам',foldHint:'',rawScore:'До калибровки',calibratedScore:'После калибровки',uploading:'Читаем исследование',uploadingHint:'Проверяем DICOM и собираем проекции по StudyUID.',connecting:'Подключение…',offline:'Сервис недоступен',weightsDemand:'веса по запросу',modelReady:'модель доступна',weightsCached:'веса загружены',modelLoading:'загрузка весов',modelError:'модель недоступна',study:'Исследование',projections:'проекций',frames:'кадров',unassigned:'Не назначена',ready:'Готово',complete:'Рассчитан',partial:'Частичный',calibratedCaption:'Калиброванная оценка ансамбля',partialCaption:'Для итоговой оценки нужны обе артерии. Ниже показаны доступные вклады.',greater22:'SYNTAX ≥ 22',notGreater22:'SYNTAX < 22',reviewUnassigned:'Назначьте или исключите каждую проекцию перед расчётом.',bothReady:'Обе коронарные артерии включены.',onlyLeft:'Представлена только LCA. Результат будет частичным.',onlyRight:'Представлена только RCA. Результат будет частичным.',noIncluded:'Назначьте хотя бы одну подходящую проекцию артерии.',shortProjection:'Меньше 10 кадров · исключено из расчёта',shortCannotAssign:'Видео короче 10 кадров нельзя включить в расчёт.',assignmentDefault:'',copied:'StudyUID скопирован',copyFailed:'Не удалось скопировать StudyUID',deleted:'Исследование удалено',deleteConfirm:'Удалить исследование и загруженные файлы?',processing:'Обработка…',queued:'Ожидаем запуска…',failed:'Не удалось завершить операцию.',invalidResponse:'Сервис вернул неожиданный ответ.',loaded:'Исследование загружено',excludedFiles:'Файлы не добавлены',noStudies:'Подходящие исследования не найдены.',previewLabel:'Макет интерфейса · реальные публичные DICOM, без предсказания модели',previewHint:'Это макет интерфейса. Откройте рабочее пространство для загрузки и расчёта.',earlier:'Раньше',later:'Позже',order:'Порядок проекций',exampleTitle:'Публичные примеры',referenceLabel:'Эталон',referenceSyntaxLabel:'Эталон SYNTAX',modelLabel:'Модель',precomputedLabel:'Сохранённый результат',exampleLoad:'Открыть пример',exampleHint:'Исследования из опубликованных holdout.',loadingExample:'Загружаем пример',notAvailable:'Недоступно',deviceLocal:'Вычисления',resultStale:'Назначения изменены. Запустите расчёт заново.',atLeastOne:'Выберите DICOM-файлы или ZIP-архив.',readySubtitle:'Проверьте назначения артерий.',lowConfidence:'Проверьте предложенную артерию',jobClassify:'Определяем артерии',jobInference:'Рассчитываем SYNTAX',jobExample:'Загружаем публичный пример',confirmAuto:'Автоматическое определение заменит текущие назначения артерий для этого исследования.',confirmClassifyTitle:'Заменить назначения артерий?',confirmDeleteTitle:'Удалить исследование?',dialogCancel:'Отмена',dialogContinue:'Продолжить',modelPreparing:'Подготовка ансамбля',downloadFailed:'Результат пока недоступен.',close:'Закрыть',expand:'Увеличить превью',copyUid:'Копировать StudyUID',arteryControls:'Назначение артерии',workflow:'Этапы анализа',previewVideo:'Превью коронарной ангиографии',expandedVideo:'Увеличенное превью коронарной ангиографии',removeStudy:'Удалить исследование',modelsLicense:'Модели и данные · CC BY 4.0',expired:'Срок временного хранения истёк. Загрузите исследование заново.',lightTheme:'Светлая',darkTheme:'Тёмная',appearance:'Цветовая тема',recalculate:'Пересчитать SYNTAX',completeSubtitle:'Анализ завершён.',partialSubtitle:'Частичный анализ — отсутствует одна из артерий.',play:'Воспроизвести',pause:'Пауза',previousFrame:'Предыдущий кадр',nextFrame:'Следующий кадр',seekFrame:'Кадр',framePosition:'Кадр {frame} из {total}',collapsePreview:'Вернуться к исследованию',playbackSpeed:'Скорость воспроизведения',playbackSpeedValue:'Скорость воспроизведения: {rate}×'}};
4
  const safeStored=(key,fallback)=>{try{return localStorage.getItem(key)||fallback;}catch{return fallback;}};
5
  let lang=safeStored('cardiosyntax-language','en');if(!words[lang])lang='en';
6
+ let studies=[],selectedStudyId=null,selectedProjectionId=null,status=null,statusChecked=false,busy=false,activeJob=null,pollTimer=null,resultByStudy=new Map(),resultJobByStudy=new Map();
7
  const previewMode=document.body.dataset.preview==='true';
8
  const t=k=>words[lang][k]??words.en[k]??k;
9
  const icon=name=>{const svg=document.createElementNS('http://www.w3.org/2000/svg','svg');const use=document.createElementNS('http://www.w3.org/2000/svg','use');use.setAttribute('href','#i-'+name);svg.append(use);return svg;};
 
19
  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');}
20
  function localizeError(message){if(lang==='en'||typeof message!=='string')return message;const map=[[/expired/i,t('expired')],[/Insufficient memory/i,'Недостаточно памяти для исследования. Уменьшите число проекций или используйте более мощный сервер.'],[/model could not complete/i,'Модель не смогла завершить расчёт. Проверьте доступность весов и ресурсы сервера, затем повторите попытку. Оценка не рассчитана.'],[/another.*job|job.*running|already.*running|busy/i,'Сервер выполняет другой расчёт. Повторите попытку после его завершения.'],[/upload exceeds|expanded files exceed/i,'Превышен допустимый размер загружаемых файлов.'],[/Duplicate SOPInstanceUID/i,'Файл с таким SOPInstanceUID уже есть в загрузке; повторная копия не добавлена.'],[/not.*DICOM|invalid DICOM/i,'Файл не является корректным DICOM.']];return map.find(([pattern])=>pattern.test(message))?.[1]||message;}
21
  async function request(url,options={}){let response;try{response=await fetch(url,{cache:'no-store',...options});}catch{throw new Error(t('offline'));}let data;try{data=await response.json();}catch{throw new Error(t('invalidResponse'));}if(!response.ok){const e=new Error(errorText(data.detail||data.error||data));e.status=response.status;throw e;}return data;}
22
+ async function refreshStatus(){if(previewMode)return;try{status=await request('/api/status');}catch{status=null;}statusChecked=true;renderStatus();}
23
+ function renderStatus(){renderJobHint();const dot=$('server-indicator').querySelector('.status-dot');if(previewMode){$('server-label').textContent=lang==='en'?'Design preview':'Макет интерфейса';dot.className='status-dot';$('method-device').textContent=t('notAvailable');return;}if(!status){$('server-label').textContent=t(statusChecked?'offline':'connecting');dot.className='status-dot'+(statusChecked?' error':'');return;}const device=String(status.device||'cpu').toUpperCase();const state=status.model?.status||'not_loaded';const key={not_loaded:'weightsDemand',loading:'modelLoading',ready:'modelReady',cached:'weightsCached',error:'modelError',unavailable:'modelError'}[state]||'weightsDemand';$('server-label').textContent=`${device} · ${t(key)}`;dot.className='status-dot'+(['error','unavailable'].includes(state)?' error':' ready');$('method-device').textContent=device;const revision=status.model?.revision||status.revision;if(revision){$('model-revision').textContent=revision.slice(0,8);$('model-revision').href=`https://huggingface.co/${status.model?.repository||status.repo_id||'MesserMMP/coronary-syntax-prediction'}/tree/${revision}`;}const limits=status.limits;if(limits)$('upload-limits').textContent=`DICOM · ZIP · ${limits.max_request_mb||512} MB · ${limits.max_files||64} ${lang==='en'?'files':'файла'}`;}
24
  function renderJobHint(){const node=$('job-hint');if(!node)return;const cached=status?.cached===true||['cached','ready'].includes(status?.model?.status);const cpu=String(status?.device||'').toLowerCase()==='cpu';node.hidden=!status||(cached&&!cpu);node.textContent=(!cached?t('jobHint'):'')+(cpu?(!cached?' ':'')+t('jobHintCpu'):'');}
25
  function renderSidebar(){$('study-count').textContent=studies.length;const list=$('study-list');list.replaceChildren();if(!studies.length){list.append(el('div','sidebar-empty',t('sidebarEmpty')));return;}studies.forEach((s,i)=>{const b=el('button','study-item'+(s.id===selectedStudyId?' selected':''));b.disabled=busy;b.setAttribute('aria-current',s.id===selectedStudyId?'true':'false');const logo=el('span','study-item-icon');logo.append(icon('file'));const text=el('span','study-item-text');text.append(el('strong','',`${t('study')} ${String(i+1).padStart(2,'0')}`),el('small','',`${s.projections.length} ${t('projections')}${resultByStudy.has(s.id)?' · '+t(resultByStudy.get(s.id).complete===false?'partial':'complete'):''}`));b.append(logo,text);if(resultByStudy.has(s.id))b.append(el('span','status-mini'));b.addEventListener('click',()=>selectStudy(s.id));list.append(b);});}
26
  function defaultProjection(study){return study?.projections.find(p=>p.id===study.default_projection_id)?.id||study?.projections[0]?.id||null;}