import { moveCards, renderProbes, tasks } from './tasks.js?v=rank-settle'; const byId = id => document.getElementById(id); const escape = value => String(value ?? '').replace(/[&<>"']/g, char => ({'&':'&', '<':'<', '>':'>', '"':'"', "'":'''}[char])); const steps = ['encode', 'generate', 'score', 'lock', 'filter', 'rerank', 'output']; const events = ['encode', 'beam', 'stage1', 'gate', 'filter', 'stage2', 'done']; const activities = { submit: [0, -1, 'Submitting the GPU request…', '正在提交 GPU 请求…'], wait: [0, -1, 'Waiting for ZeroGPU to start the request…', '正在等待 ZeroGPU 调度并启动…'], runtime: [0, -1, 'GPU assigned. Initializing the inference runtime…', '已分配 GPU,正在初始化推理运行环境…'], encode: [1, 0, 'Loading RSCaMa and encoding the image pair…', '正在加载 RSCaMa 并编码双时相影像…'], beam: [2, 1, 'Loading the SCST decoder and generating Beam-15…', '正在加载 SCST 解码器并生成 Beam-15…'], stage1_load: [3, 2, 'Stage 1 · Loading Elephant-1 and its ranking adapter…', '第一阶段 · 正在加载 Elephant-1 与排序适配器…'], stage1_score: [3, 2, 'Stage 1 · Scoring all 15 candidates…', '第一阶段 · 正在为全部 15 条候选评分…'], gate: [3, 3, 'Locking the change state from the highest-scoring caption…', '正在根据最高分描述锁定变化状态…'], filter: [4, 4, 'Filtering no-change and duplicate captions…', '正在过滤无变化与重复描述…'], stage2_load: [4, 5, 'Stage 2 · Loading Elephant-1 and its change adapter…', '第二阶段 · 正在加载 Elephant-1 与变化适配器…'], stage2_score: [4, 5, 'Stage 2 · Comparing the eligible change captions…', '第二阶段 · 正在比较保留的变化描述…'], output: [5, 6, 'Selecting the final caption and mapping to its original Beam ID…', '正在选定最终描述并回映至原始 Beam ID…'], }; const monitorNodes = [['ZeroGPU','ZeroGPU'], ['Image encoding','影像编码'], ['Beam-15','Beam-15'], ['Stage 1','第一阶段'], ['Stage 2','第二阶段'], ['Caption','最终描述']]; const labels = { heroMethod: ['Reranking with a System-1 Decision Model','System-1 决策模型辅助重排'], project: ['Project ↗','项目主页 ↗'], headline: ['The best caption isn’t always ranked first.','排名第一的,不一定是最好的描述。'], lede: ['Check what changed, then select the caption that best matches both images.','先判断场景是否变化,再选出最符合双时相影像的描述。'], observations: ['Bi-temporal observations','双时相观测'], trace: ['Live GPU Inference','GPU 实时推理'], openInference: ['Live GPU Inference','GPU 实时推理'], inferencePath: ['Image pair → Beam-15 → Final caption','双时相影像 → Beam-15 → 最终描述'], results: ['Benchmark results','基准成果'], baseline: ['SCST Beam-15 Top-1 → Critique-then-Rerank','SCST Beam-15 首选 → 两阶段重排'], listTitle: ['From two images to one caption','从双时相影像到变化描述'], listIntro: ['Choose a preset LEVIR-CC pair to run live. Each pair contains before and after images of the same location.','选择一组 LEVIR-CC 预置影像即可开始实时推理。每组都是同一地点的前后两期影像。'], pairs: ['Browse LEVIR-CC image pairs','浏览 LEVIR-CC 双时相影像'], followTrace: ['Follow the decision trace ↓','查看决策过程 ↓'], decisionLabs: ['One model, four decisions','一个模型,四项决策任务'], decisionIntro: ['Explore how Elephant-1 detects change, verifies a caption, compares two captions, and selects from the Beam-15 pool. These examples don’t use GPU quota.','看 Elephant-1 如何判断变化、核验描述、比较两句描述,以及从 Beam-15 候选池中选出最终描述。浏览示例不消耗 GPU 配额。'], taskState: tasks[0].label, taskVerify: ['Caption verification','描述核验'], taskPair: tasks[2].label, taskList: tasks[3].label, taskStateHint: ['Images only','仅输入影像'], taskVerifyHint: ['Yes / No','支持 / 不支持'], decisionTitle: ['State-Routed Decision Trace','状态分流与决策过程'], traceIntro: ['Stage 1 locks the change state. That decision determines whether to exit, return a candidate directly, or run Stage 2.','第一阶段锁定变化状态,随后按状态与候选数量决定提前退出、直接返回候选,或执行第二阶段。'], rankingTitle: ['Candidate Ranking Explorer','候选重排探索'], encode: ['Encode the pair','编码双图'], generate: ['Generate Beam-15','生成 Beam-15'], score: ['Score all candidates','全候选评分'], lock: ['Route by state','按状态分流'], filter: ['Filter the pool','过滤候选池'], rerank: ['Compare + calibrate','精排与长度校准'], output: ['Map to original Beam ID','回映原始 Beam ID'], play: ['▷ Step through','▷ 逐步演示'], pause: ['Ⅱ Pause','Ⅱ 暂停演示'], live: ['Run on GPU','开始 GPU 推理'], monitor: ['Runtime monitor','实时运行监控'], elapsed: ['Elapsed','已用时'], }; const inferenceHash = '#trace-title'; const hubOrigin = 'https://huggingface.co'; const zeroGpuHandshake = 'supports-zerogpu-headers'; let lang = new URLSearchParams(location.search).get('lang') === 'zh' ? 'zh' : 'en'; const text = (en, zh) => lang === 'zh' ? zh : en; const label = key => text(...labels[key]); let catalog, selected, trace, phase = 3, mode = 'archive', liveEvent, busy = false, follow = true, failure = null, timer; let liveActivity, runTimes, clockTimer; let view = 'swipe', divider = 50, beta = 0.12; let activeTask = 0, rankedView = false, explorerBeta; let probeControls; const pulseTimes = new Map(); const pulseLength = 720; const taskPanels = ['task-state', 'task-verify', 'task-pair', 'task-list']; const taskTabs = [...byId('task-grid').querySelectorAll('[role="tab"]')]; function translate() { document.documentElement.lang = text('en','zh-CN'); document.title = `Critique-then-Rerank · ${text('Decision Lab','决策工作台')}`; for (const node of document.querySelectorAll('[data-t]')) node.textContent = label(node.dataset.t); byId('language').textContent = text('中文','EN'); byId('language').setAttribute('aria-label', text('切换到中文','Switch to English')); } const media = path => `./media/${path.split('/').map(encodeURIComponent).join('/')}`; const stateLabel = changed => changed ? text('Changed','有变化') : text('Unchanged','无变化'); const rankLabel = index => `#${String(index + 1).padStart(2, '0')}`; const compareValue = value => text(`Reveal: T₁ ${value}%, T₂ ${100 - value}%`, `显示范围:T₁ ${value}%,T₂ ${100 - value}%`); const image = (path, later) => `${later ? text('T₂: later satellite image','T₂:后一时相遥感影像') : text('T₁: earlier satellite image','T₁:前一时相遥感影像')}`; const frame = (path, later) => `
${image(path, later)}${later ? 'T₂' : 'T₁'}
`; const pair = item => `
${item.media.map((path, index) => frame(path, index === 1)).join('')}
`; const evidence = item => `
${text('VISUAL EVIDENCE','影像证据')}${pair(item)}
LEVIR-CC · ${escape(item.name)}
`; function selectTask(index) { activeTask = index; taskTabs.forEach((button, position) => { const current = index === position; button.setAttribute('aria-selected', current); button.tabIndex = current ? 0 : -1; byId(taskPanels[position]).hidden = !current; if (position === 0) { if (current) byId(taskPanels[position]).tabIndex = 0; else byId(taskPanels[position]).removeAttribute('tabindex'); } }); taskTabs[index].focus({preventScroll:true}); taskTabs[index].scrollIntoView({block:'nearest', inline:'nearest', container:'nearest'}); } function renderExplorer() { const example = catalog.cases.find(item => item.name === 'test_000125.png'); const {captions, final} = example.replay; byId('rank-explorer').innerHTML = `
${evidence(example)}
${final + 1} → 1${text('Beam rank → final rank','原始 Beam 排名 → 最终排名')} · β = ${catalog.beta.toFixed(2)}
${escape(captions[final])}

${text('How does Beam #15 rise to first?', 'Beam #15 如何升到第一?')}

${text('Compare the generator and visual ranking of all 15 beams. Then adjust β to see how caption length changes the winner.', '对比全部 15 条候选的生成与视觉重排顺序,再调节 β,看看句长如何影响首选。')}

log(max(P(slot), 10⁻³⁰)) − β × words

    ${captions.map((caption, index) => `
  1. ${escape(caption)}
    Beam ${rankLabel(index)}
  2. `).join('')}
`; updateExplorer(example); } function updateExplorer(example) { const {captions, stage2} = example.replay; const ranked = calibrated(stage2, captions, explorerBeta); const winner = ranked[0].index; const order = rankedView ? ranked.map(candidate => candidate.index) : captions.map((_, index) => index); const scores = new Map(ranked.map(candidate => [candidate.index, candidate.score])); byId('explorer-beta-value').textContent = explorerBeta.toFixed(2); byId('explorer-beta').setAttribute('aria-valuetext', explorerBeta.toFixed(2)); byId('explorer-beta').style.setProperty('--fill', `${explorerBeta * 500}%`); byId('explorer-winner').textContent = text(`At β = ${explorerBeta.toFixed(2)}: Beam ${rankLabel(winner)} wins.`, `β = ${explorerBeta.toFixed(2)} 时:选中 Beam ${rankLabel(winner)}。`); for (const button of byId('rank-explorer').querySelectorAll('[data-rank]')) button.setAttribute('aria-pressed', (button.dataset.rank === '1') === rankedView); const pool = byId('explorer-pool'); pool.scrollTop = 0; moveCards(pool, order.map(index => pool.querySelector(`[data-beam="${index}"]`)), (card, rank) => { const index = Number(card.dataset.beam); card.classList.toggle('winner', index === winner); card.firstElementChild.textContent = rank + 1; const score = card.querySelector('small'); score.hidden = !rankedView; score.textContent = scores.get(index)?.toFixed(4) ?? '—'; }); } function renderTasks() { probeControls ??= renderProbes({byId, text, evidence, pair, escape, catalog}); probeControls(); renderExplorer(); } function renderCases() { byId('case-grid').innerHTML = catalog.cases.map((item, index) => ``).join(''); } function renderViewer() { const current = selected; byId('case-id').textContent = current.name.replace('.png',''); const [before, after] = current.media; const modes = [['swipe',text('Swipe','拉帘')],['pair',text('Side by side','并排')],['video',text('Playback','时序播放')]]; let stage; if (view === 'swipe') stage = `
${image(before, false)}
${image(after, true)}
T₁ ${text('Before','变化前')}T₂ ${text('After','变化后')}
`; if (view === 'pair') stage = `
${frame(before, false)}${frame(after, true)}
`; if (view === 'video') stage = `

${text('Original frames only · 2 s per observation','仅播放两张原始影像 · 每个时相 2 秒')}

`; byId('viewer').innerHTML = `
${modes.map(([key, title]) => ``).join('')}
${stage}`; byId('case-context').innerHTML = `LEVIR-CC · ${text('PRESET PAIR','预置影像')}

${escape(text(selected.title_en, selected.title_zh))}

`; } function select(index) { if (busy) return; stopReplay(); pulseTimes.clear(); selected = catalog.cases[index]; trace = selected.replay; phase = 3; mode = 'archive'; beta = catalog.beta; divider = 50; failure = null; renderCases(); renderViewer(); render(); } function stopReplay() { clearInterval(timer); timer = undefined; } function replay() { if (busy) return; if (timer) { stopReplay(); render(); return; } trace = selected.replay; mode = 'archive'; pulseTimes.clear(); phase = 0; beta = catalog.beta; failure = null; timer = setInterval(() => { phase = (phase === 3 && trace.changed === false) || (phase === 4 && trace.eligible.length <= 1) ? 6 : phase + 1; if (phase === 6) stopReplay(); render(true); }, 1650); render(); } function level() { return mode === 'archive' ? steps.length - 1 : events.indexOf(liveEvent); } function updateClock() { const showing = mode === 'live' && Boolean(runTimes); byId('run-elapsed').hidden = !showing; if (!showing) return; const seconds = Math.floor(((runTimes.ended ?? performance.now()) - runTimes.started) / 1000); const clock = byId('run-clock'); clock.dateTime = `PT${seconds}S`; clock.textContent = `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`; } function renderMonitor(completed, early, direct, flowing) { const current = mode === 'live' && liveActivity !== 'filter' ? activities[liveActivity]?.[0] : undefined; const timing = mode === 'live' ? runTimes?.timings ?? {} : {}; const duration = (key, title) => Number.isFinite(timing[key]) ? `${title} ${timing[key].toFixed(1)} s` : ''; const breakdown = stage => [duration(`${stage}_load`, text('Load','加载')), duration(`${stage}_score`, text('Score','评分'))].filter(Boolean).join(' · '); const wait = runTimes?.gpuStarted - runTimes?.submitted; const details = [ [Number.isFinite(wait) ? text(`Start wait ${(wait / 1000).toFixed(1)} s`, `启动等待 ${(wait / 1000).toFixed(1)} 秒`) : '', duration('runtime', text('Init','初始化'))].filter(Boolean).join(' · '), duration('encode', text('Load + encode','加载与编码')), duration('beam', text('Load + decode','加载与解码')), breakdown('stage1'), breakdown('stage2'), completed >= 6 && mode === 'live' ? `Beam ${rankLabel(trace.final)}` : '', ]; const done = [completed >= 0 || (Number.isFinite(runTimes?.gpuStarted) && current !== 0), completed >= 0, completed >= 1, completed >= 3, completed >= 5 && !early && !direct, completed >= 6]; byId('live-nodes').innerHTML = monitorNodes.map(([en, zh], index) => { const state = mode !== 'live' ? 'pending' : index === 4 && early ? 'skipped' : index === 4 && direct ? 'direct' : index === current ? (failure ? 'failed' : 'running') : done[index] ? 'done' : 'pending'; const stateText = { pending: text('Pending','待运行'), running: text('In progress','进行中'), done: text('Done','完成'), skipped: text('Skipped — Early Exit','已跳过 — 提前退出'), direct: text('No Stage 2 call','未调用 Stage 2'), failed: text('Interrupted','已中断'), }[state]; const connected = mode === 'live' && index < 5 && done[index] && (index !== 3 || done[4] || current === 4 && !failure); return `
  • ${text(en, zh)}
    ${stateText}${mode === 'live' && details[index] ? `${details[index]}` : ''}${index < 5 ? `` : ''}
  • `; }).join(''); const progress = byId('live-progress'); progress.hidden = !busy || completed < 0 || liveEvent === 'done'; progress.value = completed + 1; progress.setAttribute('aria-valuetext', text(`Trace checkpoint ${completed + 1} of 7`, `决策流程进度 ${completed + 1} / 7`)); updateClock(); } function pulse(edge, active, flowing, path) { if (!active || !flowing) return ''; const now = performance.now(); if (!pulseTimes.has(edge)) pulseTimes.set(edge, now); const elapsed = now - pulseTimes.get(edge); if (elapsed >= pulseLength) return ''; const delay = `--pulse-delay:-${elapsed.toFixed(1)}ms`; return path ? `` : ``; } function render(replayTick = false) { const reached = level(); const completed = timer ? phase : reached; const focused = document.activeElement?.dataset.step; const early = trace?.changed === false && completed >= 3; const direct = trace?.changed === true && completed >= 4 && trace.eligible?.length <= 1; const activeStep = mode === 'live' && busy ? activities[liveActivity]?.[1] : undefined; const flowing = mode === 'live' ? !failure : Boolean(timer) || replayTick; renderMonitor(completed, early, direct, flowing); byId('pipeline').innerHTML = routing(completed, activeStep, early, direct, flowing); if (focused !== undefined) byId('pipeline').querySelector(`[data-step="${focused}"]`)?.focus({preventScroll: true}); byId('source').textContent = mode === 'archive' ? text('Case walkthrough','案例演示') : text('ZeroGPU · live run','ZeroGPU · 实时推理'); byId('source').dataset.source = mode; const result = failure ? null : mode === 'live' ? liveEvent === 'done' ? trace : null : !timer ? trace : null; byId('run-output').innerHTML = result ? captionSelection(result) : ''; byId('replay').textContent = label(timer ? 'pause' : 'play'); byId('replay').disabled = busy; byId('live').disabled = busy || !catalog.live; const status = failure ? failureMessage(failure) : (mode === 'archive' ? (catalog.live ? text('Select a step to see how the model made its decision.', '点击任意步骤,查看模型如何做出决策。') : text('Explore the case below. Live inference is temporarily unavailable.', '可以继续查看案例,实时推理暂不可用。')) : (liveActivity ? text(...activities[liveActivity].slice(2)) : ({ encode: text('Images encoded.','双图编码完成。'), beam: text('Beam-15 ready.','Beam-15 已生成。'), stage1: text('Stage 1 scored all candidates.','第一阶段已完成全候选评分。'), gate: trace?.changed ? text('Changed locked.','已锁定有变化。') : text('Unchanged locked. Stage 2 skipped.','已锁定无变化,跳过第二阶段。'), filter: text('Change pool ready.','变化候选池已就绪。'), stage2: text('Stage 2 scored the pool.','第二阶段已完成评分。'), done: text('Inference complete. Inspect any step.','推理完成,可回看任意步骤。'), }[liveEvent] ?? ''))); if (byId('status').textContent !== status) byId('status').textContent = status; byId('inspector').innerHTML = reached < 0 ? `
    ${failure ? text('No live result. Choose Step through to explore this pair without using GPU quota.', '本次没有实时结果。点击「逐步演示」可查看这组影像的推理流程,不消耗 GPU 配额。') : text('The trace opens as soon as the first step finishes.','第一步完成后即可查看决策记录。')}
    ` : inspect(); if (phase === 5 && trace?.stage2?.length > 1) updateRanking(); } function head(index, description) { const time = trace?.timings?.[['encode','beam','stage1',null,null,'stage2'][index]]; return `
    STEP 0${index + 1}

    ${label(steps[index])}

    ${time === undefined ? '' : ``}

    ${description}

    `; } function routeSummary(result) { if (!result.changed) return text('Unchanged · Early Exit','无变化 · 提前退出'); if (!result.eligible.length) return text('Empty pool · Stage 1 anchor kept','候选池为空 · 保留第一阶段锚点'); if (result.eligible.length === 1) return text('One candidate · Returned directly','仅一条候选 · 直接返回'); return text('Change branch · Stage 2 invoked','变化分支 · 已执行第二阶段'); } function highlightEdit(original, final) { if (original === final) return escape(final); const source = original.split(/(\s+)/u); const target = final.split(/(\s+)/u); let start = 0, end = 0; while (start < target.length && start < source.length && target[start] === source[start]) start++; while (end < target.length - start && end < source.length - start && target.at(-end - 1) === source.at(-end - 1)) end++; const edited = escape(target.slice(start, target.length - end).join('')); return escape(target.slice(0, start).join('')) + (edited ? `${edited}` : '') + escape(target.slice(target.length - end).join('')); } function captionSelection(result) { const original = result.captions[0]; const final = result.captions[result.final]; const caseId = escape((result.name ?? selected.name).replace(/\.png$/u, '')); return `

    ${text('Caption Selection','描述选择')}

    ${mode === 'live' ? text('LIVE RESULT','实时结果') : text('PREVIEW','样例预览')} · LEVIR-CC · ${caseId}
    ${text('GENERATOR','生成器')} · BEAM #01

    ${escape(original)}

    ${text('Original top-1','原始首选')}
    ${result.eligible?.length > 1 ? text('RERANKED','重排后') : text('OUTPUT','输出')} · BEAM ${rankLabel(result.final)}

    ${highlightEdit(original, final)}

    ${text('Final selection','最终选择')}
    ${[[text('Generator','生成器'), 0], ['Stage 1', result.anchor], [text('Final','最终'), result.final]].map(([title,index]) => `
    ${title}
    ${rankLabel(index)}
    `).join('')}
    `; } function routing(completed, activeStep, early, direct, flowing) { const short = ['RSCaMa', 'SCST', 'ELEPHANT-1', text('STATE GATE','状态门控'), text('CHANGED','有变化'), 'STAGE 2 · β', 'CAPTION']; const stage2 = !early && !direct && (activeStep === 5 || completed >= 5); const step = (index, title = label(steps[index])) => { const skipped = early && (index === 4 || index === 5); const bypass = direct && index === 5; const state = skipped ? 'skipped' : bypass ? 'direct' : index === activeStep ? 'running' : index <= completed ? 'done' : 'pending'; return ``; }; const gate = completed >= 3; const output = completed >= 6 || activeStep === 6; const changed = gate && trace.changed; const edge = (id, path, active, kind = 'pre') => `${pulse(id, active, flowing, path)}`; const wires = (branches, className = '') => ``; const entry = [0,1,2].map(index => index < 2 ? `${step(index)}` : step(index)).join(''); return `
    ${entry}
    ${wires(edge('feed-gate', 'M83.5 0V11H50V22', completed >= 2), 'trace-feed')}
    ${step(3, gate ? `Beam ${rankLabel(trace.anchor)} · ${stateLabel(trace.changed)}` : undefined)}
    ${wires(edge('route-early', 'M50 0V10H25V22', early, 'early') + edge('route-change', 'M50 0V10H75V22', changed, 'change'))}
    ${stateLabel(false)}${text('Early Exit','提前退出')}${text('Return Stage 1 anchor','返回第一阶段锚点')}
    ${step(4)}
    0${text('Keep anchor','保留锚点')}
    1${text('Return survivor','返回保留候选')}
    2+${text('Run Stage 2','执行第二阶段')}
    ${wires(edge('enter-stage2', 'M50 0V22', stage2, 'change'), 'trace-pool-feed')}${step(5, early ? text('Skipped — Early Exit','已跳过 — 提前退出') : direct ? text('No Stage 2 call','未调用第二阶段') : undefined)}${direct ? wires(edge('bypass-stage2', 'M40 0H72Q90 0 90 3V19Q90 22 72 22H40', true, 'change'), 'trace-bypass') : ''}
    ${wires(edge('return-early', 'M25 0V10H50V22', output && early, 'early') + edge('return-change', 'M75 0V10H50V22', output && changed, 'change'))}
    ${step(6)}
    `; } function inspect() { if (phase === 0) return head(0, text('RSCaMa encodes the earlier and later views of the same location into joint visual features for the caption generator.','RSCaMa 将同一地点的前后影像编码为联合视觉特征,交给描述生成器。')) + `
    ${selected.media.map((path, index) => `
    ${image(path, index === 1)}T${index + 1}
    `).join('')}
    RSCaMa${trace?.feature_shape ? trace.feature_shape.join(' × ') : text('Joint visual features','联合视觉特征')}

    ${text('Feature icon is schematic. Both Elephant-1 stages also receive the original image pair when they run.','特征图标为示意;Elephant-1 两阶段执行时也会读取原始双时相影像。')}

    `; if (phase === 1) return head(1, text('The SCST RSCaMa decoder uses beam search to propose 15 captions. Beam #01 is the generator’s baseline; every beam goes to Stage 1.','SCST RSCaMa 通过束搜索生成 15 条描述。Beam #01 是生成器的基线输出,所有候选都进入第一阶段。')) + (trace?.captions ? `
    BEAM ${rankLabel(0)} / TOP-1${escape(trace.captions[0])}
    ${text('Inspect all Beam-15 candidates','查看全部 15 条候选')}
      ${trace.captions.map((caption, index) => `
    1. ${rankLabel(index)}${escape(caption)}
    2. `).join('')}
    ` : pending()); if (phase === 2) return head(2, text('Elephant-1 reads both images and scores all 15 caption slots.','Elephant-1 读取双图并为全部 15 个候选槽位打分。')) + (trace?.stage1 ? `
    ${text('Stage 1 slots · sorted by probability','第一阶段槽位 · 按概率排序')}P(slot)
      ${trace.stage1.slice().sort((first, second) => second[1] - first[1]).map(([index, prob]) => { const isAnchor = index === trace.anchor; return `
    1. ${rankLabel(index)}
      ${escape(trace.captions[index])}caption_${index + 1} · ${stateLabel(!catalog.templates.includes(trace.captions[index]))}${isAnchor ? ` · ${text('ANCHOR','锚点')}` : ''}
      ${(prob * 100).toFixed(2)}%
    2. `; }).join('')}
    ` : pending()) + task(0); if (phase === 3) { const confidence = trace.stage1.find(([index]) => index === trace.anchor)?.[1]; const next = trace.changed ? text('Next: remove no-change and duplicate captions.','下一步:去掉无变化与重复描述。') : text('Early Exit: return this caption without running Stage 2.','提前退出:直接返回这句描述,不执行第二阶段。'); return head(3, text('The highest-scoring caption anchors the decision. Its state determines which branch runs.','得分最高的描述成为锚点,由它的变化状态决定走哪条分支。')) + `
    BEAM ${rankLabel(trace.anchor)} · ${stateLabel(trace.changed)}${Number.isFinite(confidence) ? `P(slot) ${(confidence * 100).toFixed(1)}%` : ''}

    ${escape(trace.captions[trace.anchor])}

    ${next}

    `; } if (phase === 4 || phase === 5) { if (trace.changed === false) return head(phase, text('Stage 1 locked Unchanged. The anchor goes straight to the output.','第一阶段已锁定无变化,锚点直接作为最终输出。')) + `

    ${text('Skipped — Early Exit','已跳过 — 提前退出')}

    ${text('No change candidates were filtered or scored by Stage 2.','这条路径不进行变化候选过滤,也不调用第二阶段。')}

    `; if (phase === 4) return head(4, text('Drop no-change captions and duplicates before comparing change details.','先去掉无变化描述和重复描述,再比较变化细节。')) + `
    ${trace.eligible?.length ?? 0} / ${trace.captions.length} ${text('kept','条保留')}${trace.captions.map((caption, index) => `${rankLabel(index)}`).join('')}
      ${trace.captions.map((caption, index) => `
    1. ${rankLabel(index)}${escape(caption)}${trace.eligible?.includes(index) ? text('Kept','保留') : text('Filtered','已过滤')}
    2. `).join('')}
    `; return head(5, text('Elephant-1 compares the remaining descriptions. β calibrates the score by caption length.','Elephant-1 比较剩余描述,再按句长用 β 校准得分。')) + (trace.stage2?.length > 1 ? `
    log(max(P(slot), 10⁻³⁰)) − β × words

    ${text('The slider explores this fixed pool. The model output uses the validation-selected β.', '滑块只探索当前候选池;正式输出使用验证集选定的 β。')}

    ` : `
    ${trace.eligible?.length ? text('One eligible caption: selected directly.','仅一条合格候选,直接选择。') : text('No eligible captions: keep the Stage 1 anchor.','无合格候选,保留第一阶段锚点。')}
    `) + task(1); } const slot = trace.stage2?.findIndex(([index]) => index === trace.final); const mapping = slot >= 0 && trace.stage2.length > 1 ? `item_${slot + 1} → Beam ${rankLabel(trace.final)}` : `Beam ${rankLabel(trace.final)}`; return head(6, `${routeSummary(trace)}.${trace.stage2?.length > 1 ? ` β = ${catalog.beta.toFixed(2)}.` : ''}`) + `

    ${mapping}

    ${[ [text('Generator baseline','生成器基线'),0], [text('Stage 1 anchor','第一阶段锚点'),trace.anchor], [text('Final caption','最终描述'),trace.final], ].map(([title, index]) => `
    ${title} · BEAM ${rankLabel(index)}

    ${escape(trace.captions[index])}

    `).join('')}
    `; } const pending = () => ''; const task = index => `
    ${text('Inspect the actual task instruction','查看实际任务指令(英文)')}

    ${escape(catalog.tasks[index])}

    `; function calibrated(scores, captions, penalty) { return scores.map(([index, probability], slot) => { const caption = captions[index]; const words = caption.trim() ? caption.trim().split(/\s+/u).length : 0; const log = Math.log(Math.max(probability, 1e-30)); return {index, probability, slot, words, log, score: log - penalty * words, caption}; }).sort((first, second) => second.score - first.score); } function updateRanking() { byId('beta-value').textContent = beta.toFixed(2); byId('beta').setAttribute('aria-valuetext', beta.toFixed(2)); byId('beta').style.setProperty('--fill', `${beta * 500}%`); const ranked = calibrated(trace.stage2, trace.captions, beta); byId('ranks').innerHTML = `
    ${text('Eligible pool · sorted by calibrated score','同状态候选 · 按校准分排序')}${text('Score','得分')}
      ${ranked.map(({index, probability, slot, words, log, score, caption}, position) => `
    1. ${rankLabel(index)}
      ${escape(caption)}item_${slot + 1} · P ${(probability * 100).toFixed(2)}% · ln P ${log.toFixed(3)} · ${words} ${text('words','词')} · −${(beta * words).toFixed(3)}
      ${score.toFixed(4)}${position === 0 ? `${text('SELECTED','选中')}` : ''}
    2. `).join('')}
    `; } async function zeroGpuHeaders() { const headers = new Headers({'Content-Type': 'application/json'}); if (window.parent === window) return headers; const support = new AbortController(); const supported = await new Promise(resolve => { const timer = setTimeout(() => resolve(false), 2000); window.addEventListener('message', event => { if (event.source !== window.parent || event.origin !== hubOrigin || event.data !== zeroGpuHandshake) return; clearTimeout(timer); resolve(true); }, {signal: support.signal}); window.parent.postMessage(zeroGpuHandshake, hubOrigin); }).finally(() => support.abort()); if (!supported) return headers; const channel = new MessageChannel(); const identity = await new Promise(resolve => { const timer = setTimeout(() => resolve(null), 2000); channel.port1.onmessage = event => { clearTimeout(timer); resolve(event.data); }; window.parent.postMessage('zerogpu-headers', hubOrigin, [channel.port2]); }).finally(() => channel.port1.close()); for (const name of ['X-ZeroGPU-Token', 'X-ZeroGPU-UUID']) { const value = identity?.[name]; if (typeof value === 'string' && value && !/[\r\n\0]/.test(value)) headers.set(name, value); } return headers; } function streamFailure(event) { try { const payload = JSON.parse(event.data); const message = typeof payload === 'string' ? payload : payload?.error; if (payload?.title === 'ZeroGPU quota exceeded' || /exceeded your (?:free |pro )?zerogpu quota/i.test(message)) { const quota = /([\d.]+)\s*s requested\s+vs\.\s+([\d.]+)\s*s left/i.exec(message); const needsLogin = /authenticate with a hugging face token/i.test(message); return {kind: 'quota', quota: quota?.slice(1), needsLogin}; } } catch { return {kind: 'interrupted'}; } return {kind: 'interrupted'}; } function failureMessage({kind, quota, needsLogin}) { if (kind === 'quota') { const details = quota ? text(` This run requests ${quota[0]} s; ${quota[1]} s remain.`, `本次需要 ${quota[0]} 秒,剩余 ${quota[1]} 秒。`) : ''; return text('Not enough ZeroGPU quota to start.', 'ZeroGPU 配额不足,未开始推理。') + details + (needsLogin ? text(' This request used guest quota. Sign in on huggingface.co and run from the Space’s App tab with that tab active.', '本次请求使用了访客额度。请在 huggingface.co 登录,在 Space 的 App 标签页保持前台并重试。') : text(' Retry after your ZeroGPU quota resets.', '请在 ZeroGPU 配额重置后重试。')); } return text('Live inference was interrupted. Try again or choose Step through.', '实时推理中断,可重试或点击「逐步演示」。'); } async function run() { if (busy || !catalog.live) return; stopReplay(); pulseTimes.clear(); busy = true; mode = 'live'; failure = null; follow = true; trace = null; liveEvent = undefined; liveActivity = 'submit'; runTimes = {started: performance.now()}; clockTimer = setInterval(updateClock, 1000); phase = 0; beta = catalog.beta; renderCases(); render(); let source; try { const endpoint = './gradio_api/call/run_case'; const headers = await zeroGpuHeaders(); liveActivity = 'wait'; runTimes.submitted = performance.now(); render(); const response = await fetch(endpoint, {method:'POST', headers, redirect:'error', body:JSON.stringify({data:[selected.name]})}); if (!response.ok) throw new Error('Queue rejected the run'); const {event_id: eventId} = await response.json(); if (!eventId) throw new Error('Missing event id'); source = new EventSource(`${endpoint}/${encodeURIComponent(eventId)}`); await new Promise((resolve, reject) => { const onTrace = event => { try { const [payload] = JSON.parse(event.data); if (payload?.name !== selected.name) throw new Error('Invalid trace'); const activity = payload.activity; if (activity === undefined ? !events.includes(payload.step) : payload.step !== undefined || !Object.hasOwn(activities, activity) || activity === 'submit' || activity === 'wait') throw new Error('Invalid trace'); if (event.type === 'complete' && payload.step !== 'done') throw new Error('Incomplete trace'); if (activity === 'runtime') runTimes.gpuStarted ??= performance.now(); runTimes.timings = payload.timings; if (activity) { liveActivity = activity; render(); return; } liveActivity = undefined; trace = payload; liveEvent = payload.step; if (follow) phase = level(); if (event.type === 'complete') resolve(); render(); } catch (error) { reject(error); } }; source.addEventListener('generating', onTrace); source.addEventListener('complete', onTrace); source.addEventListener('error', event => reject(streamFailure(event))); }); } catch (error) { failure = error?.kind === 'quota' ? error : {kind: 'interrupted'}; } finally { source?.close(); runTimes.ended = performance.now(); clearInterval(clockTimer); busy = false; renderCases(); render(); } } byId('language').addEventListener('click', () => { lang = lang === 'en' ? 'zh' : 'en'; const url = new URL(location.href); if (lang === 'zh') url.searchParams.set('lang', 'zh'); else url.searchParams.delete('lang'); history.replaceState(null, '', url); translate(); if (catalog) { renderCases(); renderViewer(); renderTasks(); render(); } }); byId('task-grid').addEventListener('click', event => { const button = event.target.closest('[data-task]'); if (!button || !catalog || Number(button.dataset.task) === activeTask) return; selectTask(Number(button.dataset.task)); }); byId('task-grid').addEventListener('keydown', event => { if (!catalog || !event.target.closest('[data-task]')) return; const count = taskTabs.length; const next = {ArrowLeft:(activeTask + count - 1) % count, ArrowRight:(activeTask + 1) % count, Home:0, End:count - 1}[event.key]; if (next === undefined) return; event.preventDefault(); selectTask(next); }); byId('rank-explorer').addEventListener('click', event => { const button = event.target.closest('[data-rank]'); if (!button || (button.dataset.rank === '1') === rankedView) return; rankedView = button.dataset.rank === '1'; updateExplorer(catalog.cases.find(item => item.name === 'test_000125.png')); }); byId('rank-explorer').addEventListener('input', event => { if (event.target.id !== 'explorer-beta') return; explorerBeta = Number(event.target.value); rankedView = true; updateExplorer(catalog.cases.find(item => item.name === 'test_000125.png')); }); byId('case-grid').addEventListener('click', event => { const button = event.target.closest('[data-case]'); if (button) { select(Number(button.dataset.case)); byId('case-grid').querySelector(`[data-case="${button.dataset.case}"]`)?.focus({preventScroll:true}); } }); byId('viewer').addEventListener('click', event => { const button = event.target.closest('[data-view]'); if (button && button.dataset.view !== view) { view = button.dataset.view; renderViewer(); byId('viewer').querySelector(`[data-view="${view}"]`)?.focus({preventScroll:true}); } }); byId('viewer').addEventListener('input', event => { if (event.target.id !== 'divider') return; divider = Number(event.target.value); byId('viewer').querySelector('.swipe').style.setProperty('--split', `${divider}%`); event.target.setAttribute('aria-valuetext', compareValue(divider)); byId('divider-value').textContent = `${divider}%`; }); byId('pipeline').addEventListener('click', event => { const button = event.target.closest('[data-step]'); if (!button) return; stopReplay(); follow = false; phase = Number(button.dataset.step); render(); }); byId('inspector').addEventListener('input', event => { if (event.target.id !== 'beta') return; beta = Number(event.target.value); updateRanking(); }); byId('replay').addEventListener('click', () => { if (catalog) replay(); }); byId('live').addEventListener('click', () => { if (catalog) run(); }); translate(); byId('live').disabled = byId('replay').disabled = true; try { const response = await fetch('./catalog'); if (!response.ok) throw new Error('Catalog unavailable'); catalog = await response.json(); explorerBeta = catalog.beta; select(0); renderTasks(); if (location.hash === inferenceHash) byId('trace-title').scrollIntoView(); } catch { byId('load-error').textContent = text('Examples could not load. Refresh to retry.', '未能加载示例,请刷新重试。'); }