Spaces:
Running on Zero
Running on Zero
Visualize paper decision tasks and stream paired imagery and live stage results
Browse filesFiles changed (8)
13 unmodified lines1415161713 unmodified linesSelect one of four LEVIR-CC image pairs and run Beam-15 generation and two-stage state-locked reranking. The app does not accept uploads or serve archived predictions as live output. [Project page](https://thirteen7.github.io/Critique-then-Rerank/)For deployment, select ZeroGPU hardware in Space Settings. Set `CTR_MODEL_READ_TOKEN` as a **Space secret** using a fine-grained token with read access only to `thirteen7/Critique-then-Rerank`. Do not use an account-wide token. The pinned public RSCaMa and Elephant-1 checkpoints are downloaded directly from the Hub; they are not bundled. The first startup after configuration downloads the checkpoints before accepting GPU work.13 unmodified lines14151617181913 unmodified linesSelect one of four LEVIR-CC image pairs and run Beam-15 generation and two-stage state-locked reranking. The app does not accept uploads or serve archived predictions as live output. [Project page](https://thirteen7.github.io/Critique-then-Rerank/)Each case includes a bilingual task guide, side-by-side images, and a four-second T₁ → T₂ clip made from the original two frames. The live decision trace streams Beam-15 and the two stage decisions as they become available. The β control reuses live Stage 2 scores without another GPU call and does not replace the reported paper setting.For deployment, select ZeroGPU hardware in Space Settings. Set `CTR_MODEL_READ_TOKEN` as a **Space secret** using a fine-grained token with read access only to `thirteen7/Critique-then-Rerank`. Do not use an account-wide token. The pinned public RSCaMa and Elephant-1 checkpoints are downloaded directly from the Hub; they are not bundled. The first startup after configuration downloads the checkpoints before accepting GPU work.
1 unmodified line23456789101112131415161718192019 unmodified lines40414243444546474849501 unmodified line525354555657585960616263646566676869707172737475767714 unmodified lines929394959697984 unmodified lines1031041051061071081091101111121131141151161171181191201211 unmodified linefrom html import escapeimport loggingimport osimport spacesimport gradio as grfrom PIL import Imagefrom inference import prepare, run_casefrom pipeline import ROOT, readLOGGER = logging.getLogger(__name__)PUBLIC = ROOT / 'public'CASES = {record['name']: record for record in read(PUBLIC / 'cases.json')}FIRST = next(iter(CASES))HERO = '''<header class="observatory"><div class="eyebrow">REMOTE SENSING / LEVIR-CC <span>ZERO GPU</span></div>19 unmodified lines.decision-card p { overflow-wrap: anywhere; }.decision-card.final { border-width: 2px; border-color: #0f766e; }.decision-card.routed { border-color: #d95d39; }'''def previews(case_name):return tuple(load_preview(PUBLIC / image) for image in CASES[case_name]['media'])def load_preview(path):1 unmodified linereturn image.convert('RGB')def cards(result):captions = result['captions']state = 'Changed / 有变化' if result['changed'] else 'Unchanged / 无变化'if not result['changed']:route = 'Bypassed / 跳过精排'elif len(result['stage2']) > 1:route = f"Reranked {len(result['stage2'])} same-state candidates / 同状态精排 · β = {result['beta']:.2f}"elif result['stage2']:route = 'One eligible candidate / 仅一条合格候选'else:route = 'No eligible candidates; retained Stage 1 / 无合格候选,保留第一阶段结果'return (f"### {result['name']} · Live result / 实时结果",f'<div class="decision-card"><h3>01 · Beam-15 Top-1</h3><p lang="en">{escape(captions[0])}</p></div>',f'<div class="decision-card"><h3>02 · State Gate</h3><p>{state}</p>'f'<p lang="en">{escape(captions[result["anchor"]])}</p></div>',f'<div class="decision-card final {"routed" if result["changed"] else ""}">'f'<h3>03 · Final Caption</h3><p>{route}</p><p lang="en">{escape(captions[result["final"]])}</p></div>',[[index + 1, caption] for index, caption in enumerate(captions)],)def load_checkpoints():14 unmodified linesraise gr.Error('Select a listed image pair. / 请选择列出的影像组。')if CHECKPOINTS is None:raise gr.Error('Model weights are not configured. / 尚未配置模型权重。')return cards(run_case(CASES[case_name], CHECKPOINTS))def build():4 unmodified lines'This Space cannot access the model weights. / 当前 Space 未能读取模型权重。')case = gr.Radio([(f"{record['en']} / {record['zh']} · {name}", name)for name, record in CASES.items()], value=FIRST, label='Test pair / 选择样例')before_img, after_img = previews(FIRST)with gr.Row():before = gr.Image(before_img, label='T₁ · Before / 变化前', interactive=False, buttons=[], height=300)after = gr.Image(after_img, label='T₂ · After / 变化后', interactive=False, buttons=[], height=300)run = gr.Button('Run live inference / 运行实时推理', variant='primary', elem_id='run-live',interactive=CHECKPOINTS is not None)heading = gr.Markdown('### Decision trace / 决策过程')with gr.Row():top, gate, final = gr.HTML(), gr.HTML(), gr.HTML()with gr.Accordion('Beam-15 candidates / 15 条候选', open=False):candidates = gr.Dataframe(headers=['Beam rank', 'Caption'], datatype=['number', 'str'], interactive=False)case.change(previews, case, [before, after], queue=False, api_visibility='private')run.click(run_live, case, [heading, top, gate, final, candidates], concurrency_limit=1,api_name='run_case', api_visibility='undocumented')return app.queue(max_size=8)1 unmodified line23456789101112131415161718192021222319 unmodified lines4344454647484950515253545556575859606162636465661 unmodified line686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412514 unmodified lines1401411421431441451461471481494 unmodified lines1541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881 unmodified linefrom html import escapeimport loggingimport mathimport osimport spacesimport gradio as grfrom PIL import Imagefrom inference import prepare, trace_casefrom pipeline import ROOT, decision, next_stage, profile, readLOGGER = logging.getLogger(__name__)PUBLIC = ROOT / 'public'CASES = {record['name']: record for record in read(PUBLIC / 'cases.json')}FIRST = next(iter(CASES))CONFIG = profile('levir')CHECKPOINTS = NoneHERO = '''<header class="observatory"><div class="eyebrow">REMOTE SENSING / LEVIR-CC <span>ZERO GPU</span></div>19 unmodified lines.decision-card p { overflow-wrap: anywhere; }.decision-card.final { border-width: 2px; border-color: #0f766e; }.decision-card.routed { border-color: #d95d39; }.case-brief { padding: 1rem 1.25rem; border-inline-start: .25rem solid #0f766e;border-radius: .5rem; background: var(--background-fill-secondary); }.case-brief p { margin-block: .5rem; }.trace-status { font-family: monospace; color: var(--body-text-color-subdued); }.trace-status progress { display: block; inline-size: 100%; margin-top: .5rem; accent-color: #0f766e; }'''def case_view(case_name):record = CASES[case_name]images = [load_preview(PUBLIC / image) for image in record['media']]brief = (f'<section class="case-brief"><h2>{escape(record["title_en"])}</h2>'f'<p lang="zh-CN"><strong>{escape(record["title_zh"])}</strong></p>'f'<p>{escape(record["summary_en"])}</p><p lang="zh-CN">{escape(record["summary_zh"])}</p>''<small>Paper case guide / 论文案例导读</small></section>')return brief, *images, PUBLIC / record['clip']def load_preview(path):1 unmodified linereturn image.convert('RGB')def progress_card(case_name, step):labels = {'beam': (0, 'Reading T₁/T₂ and generating 15 candidates / 编码双时相影像并生成候选'),'stage1': (1, 'Stage 1 is selecting the change state / 第一阶段正在判断变化状态'),'stage2': (2, 'Stage 2 is scoring changed captions / 第二阶段正在比较变化候选'),'done': (3, 'Live result ready / 实时推理完成'),}count, label = labels[step]return (f'<div class="trace-status"><div role="status">{escape(case_name)} · {label}</div>'f'<progress aria-label="Inference stages / 推理阶段" value="{count}" max="3"></progress></div>')def cards(step, result):captions = result.get('captions', [])anchor = Nonechanged = Noneif result.get('stage1'):anchor = max(result['stage1'], key=lambda pair: pair[1])[0]_, changed = next_stage('levir', captions, anchor, CONFIG['templates'])state = 'Changed / 有变化' if changed else 'Unchanged / 无变化'if changed is False:route = 'Bypassed / 跳过精排'elif step != 'done':route = 'Waiting for decision / 等待决策'elif len(result['stage2']) > 1:route = f"Reranked {len(result['stage2'])} same-state candidates / 同状态精排 · β = {result['beta']:.2f}"elif result['stage2']:route = 'One eligible candidate / 仅一条合格候选'else:route = 'No eligible candidates; retained Stage 1 / 无合格候选,保留第一阶段结果'top = escape(captions[0]) if captions else 'Pending / 等待生成'gate = f'{state}</p><p lang="en">{escape(captions[anchor])}' if anchor is not None else 'Pending / 等待判断'final = escape(captions[result['final']]) if step == 'done' else '—'candidates = [[index + 1, caption] for index, caption in enumerate(captions)]return (progress_card(result['name'], step),f'<div class="decision-card"><h3>01 · Beam-15 Top-1</h3><p>{top}</p></div>',f'<div class="decision-card"><h3>02 · State Gate</h3><p>{gate}</p></div>',f'<div class="decision-card final {"routed" if changed else ""}">'f'<h3>03 · Final Caption</h3><p>{route}</p><p lang="en">{final}</p></div>', candidates)def calibration(beta, result):if not result or len(result.get('stage2', [])) < 2:return '**β calibration / 长度校准:** Requires at least two Stage 2 candidates. / 需有至少两条第二阶段候选。', []beta = float(beta)captions = result['captions']winner = decision('levir', result, beta, CONFIG['templates'])ranks = sorted(((index, math.log(max(prob, 1e-30)) - beta * len(captions[index].split()))for index, prob in result['stage2']), key=lambda pair: -pair[1])return (f"**{result['name']} · β = {beta:.2f}** — Beam #{winner + 1} wins / 当前首选。 "f"Changes only ranking; the reported live result uses β = {CONFIG['beta']:.2f}. / 仅改变排序,上方实时结果仍使用论文 β。",[[index + 1, captions[index], len(captions[index].split()), round(score, 5)] for index, score in ranks])def load_checkpoints():14 unmodified linesraise gr.Error('Select a listed image pair. / 请选择列出的影像组。')if CHECKPOINTS is None:raise gr.Error('Model weights are not configured. / 尚未配置模型权重。')for step, result in trace_case(CASES[case_name], CHECKPOINTS):saved = result if step == 'done' else Nonenote, ranks = calibration(CONFIG['beta'], saved)yield (*cards(step, result), saved, gr.update(value=CONFIG['beta'], interactive=len(ranks) > 1), note, ranks)def build():4 unmodified lines'This Space cannot access the model weights. / 当前 Space 未能读取模型权重。')case = gr.Radio([(f"{record['en']} / {record['zh']} · {name}", name)for name, record in CASES.items()], value=FIRST, label='Test pair / 选择样例')intro, before_img, after_img, clip_path = case_view(FIRST)brief = gr.HTML(intro)with gr.Tabs():with gr.Tab('T₁ / T₂ · Side by side / 并排'):with gr.Row():before = gr.Image(before_img, label='T₁ · Before / 变化前', interactive=False, buttons=[], height=300)after = gr.Image(after_img, label='T₂ · After / 变化后', interactive=False, buttons=[], height=300)with gr.Tab('T₁ → T₂ · Playback / 时序播放'):gr.Markdown('Each frame holds for two seconds. Playback shows only the two original observations. / ''每个时相停留两秒,只播放两张原始影像,不插帧。')clip = gr.Video(clip_path, label='T₁ → T₂', interactive=False, autoplay=False, loop=False,include_audio=False, buttons=[], height=360)run = gr.Button('Run live inference / 运行实时推理', variant='primary', elem_id='run-live',interactive=CHECKPOINTS is not None)gr.Markdown('### Live decision trace / 实时决策过程')progress = gr.HTML()with gr.Row():top, gate, final = gr.HTML(), gr.HTML(), gr.HTML()with gr.Accordion('Beam-15 candidates / 15 条候选', open=False):candidates = gr.Dataframe(headers=['Beam rank', 'Caption'], datatype=['number', 'str'], interactive=False)with gr.Accordion('Length calibration / β 长度校准', open=True):beta = gr.Slider(0.0, 0.20, value=CONFIG['beta'], step=0.02, label='β', interactive=False)note = gr.Markdown('Run a changed case to explore calibration. / 运行一组有变化的案例以查看排序。')ranks = gr.Dataframe(headers=['Beam rank', 'Caption', 'Words', 'Score'],datatype=['number', 'str', 'number', 'number'], interactive=False)scores = gr.State()case.change(case_view, case, [brief, before, after, clip], queue=False, api_visibility='private')beta.input(calibration, [beta, scores], [note, ranks], queue=False, api_visibility='private')run.click(run_live, case, [progress, top, gate, final, candidates, scores, beta, note, ranks], concurrency_limit=1,api_name='run_case', api_visibility='undocumented')return app.queue(max_size=8)
59 unmodified lines606162636465667 unmodified lines7475767778794 unmodified lines8485868788894 unmodified lines949596979859 unmodified linesraisedef run_case(record, checkpoints):import torchfrom caption.runner import beam, image_features, initializefrom judge.questions import stage1_questions, stage2_questions7 unmodified linesmedia_root = ROOT / 'public'config = profile(dataset)name = record['name']features = image_features(dataset, 'test', [record], media_root, checkpoints.visual, 'cuda')captions = beam(dataset, features, checkpoints.generator, 'cuda')[0]row = {'name': name, 'captions': captions}4 unmodified linesstage2_questions(dataset, [record], rows, config['templates']))if not questions:continueruntime, bundle = load(dataset, stage, checkpoints.base, media_root, checkpoints.adapters / f'stage{stage}')try:row[f'stage{stage}'] = score(runtime, bundle, questions)[name]4 unmodified linesanchor = max(row['stage1'], key=lambda pair: pair[1])[0]_, changed = next_stage(dataset, captions, anchor, config['templates'])return {**row, 'anchor': anchor, 'changed': changed, 'beta': config['beta'],'final': decision(dataset, row, config['beta'], config['templates'])}59 unmodified lines606162636465667 unmodified lines747576777879804 unmodified lines858687888990914 unmodified lines9697989910059 unmodified linesraisedef trace_case(record, checkpoints):import torchfrom caption.runner import beam, image_features, initializefrom judge.questions import stage1_questions, stage2_questions7 unmodified linesmedia_root = ROOT / 'public'config = profile(dataset)name = record['name']yield 'beam', {'name': name}features = image_features(dataset, 'test', [record], media_root, checkpoints.visual, 'cuda')captions = beam(dataset, features, checkpoints.generator, 'cuda')[0]row = {'name': name, 'captions': captions}4 unmodified linesstage2_questions(dataset, [record], rows, config['templates']))if not questions:continueyield f'stage{stage}', {**row}runtime, bundle = load(dataset, stage, checkpoints.base, media_root, checkpoints.adapters / f'stage{stage}')try:row[f'stage{stage}'] = score(runtime, bundle, questions)[name]4 unmodified linesanchor = max(row['stage1'], key=lambda pair: pair[1])[0]_, changed = next_stage(dataset, captions, anchor, config['templates'])yield 'done', {**row, 'anchor': anchor, 'changed': changed, 'beta': config['beta'],'final': decision(dataset, row, config['beta'], config['templates'])}
1[{"name": "test_000033.png", "en": "False Positive Blocked", "zh": "误报拦截", "media": ["images/test_000033_A.png", "images/test_000033_B.png"]}, {"name": "test_001549.png", "en": "Same-State Reranking", "zh": "同状态精排", "media": ["images/test_001549_A.png", "images/test_001549_B.png"]}, {"name": "test_001324.png", "en": "Length Calibration (β)", "zh": "长度惩罚权衡", "media": ["images/test_001324_A.png", "images/test_001324_B.png"]}, {"name": "test_001095.png", "en": "Boundary / Failure Case", "zh": "边界与失败案例", "media": ["images/test_001095_A.png", "images/test_001095_B.png"]}]1[{"name": "test_000033.png", "en": "False Positive Blocked", "zh": "误报拦截", "media": ["images/test_000033_A.png", "images/test_000033_B.png"], "title_en": "Stage 1 Blocks Hallucinated Construction", "title_zh": "第一阶段拦截无变化幻觉", "summary_en": "Beam-15 top-1 hallucinates a new building at the bottom of the scene. Stage 1 locks the state to Unchanged and skips Stage 2 by construction.", "summary_zh": "Beam-15 首句在底部幻觉出新建筑;第一阶段将状态锁定为“无变化”,结构上直接跳过第二阶段精排。", "clip": "clips/test_000033.mp4"}, {"name": "test_001549.png", "en": "Same-State Reranking", "zh": "同状态精排", "media": ["images/test_001549_A.png", "images/test_001549_B.png"], "title_en": "Stage 2 Refines Singular to Plural Houses", "title_zh": "第二阶段修正对象与复数表达", "summary_en": "Both Beam-15 top-1 and Stage 1 select a changed caption (\"a building\"). Stage 2 compares only changed candidates and promotes \"some houses\", aligning with the scene.", "summary_zh": "Beam-15 首句与第一阶段都选中变化句(a building);第二阶段仅在变化候选内重排,选中更贴合画面的 some houses。", "clip": "clips/test_001549.mp4"}, {"name": "test_001324.png", "en": "Length Calibration (β)", "zh": "长度惩罚权衡", "media": ["images/test_001324_A.png", "images/test_001324_B.png"], "title_en": "Drag β to Observe Concise vs. Verbose Reranking", "title_zh": "拖动 β 观察简洁与冗长候选的切换", "summary_en": "At β = 0.00, Stage 2 prefers the longer phrase (\"at the bottom side of the scene\"). With Val-selected β = 0.12, length calibration selects the concise top candidate without rewriting text.", "summary_zh": "当 β = 0.00 时第二阶段偏向较长表达(at the bottom side of the scene);启用验证集选定的 β = 0.12 后,无需重写文本即可重排回更简洁的候选句。", "clip": "clips/test_001324.mp4"}, {"name": "test_001095.png", "en": "Boundary / Failure Case", "zh": "边界与失败案例", "media": ["images/test_001095_A.png", "images/test_001095_B.png"], "title_en": "Honest Boundary: Missed Change Cannot Be Flipped", "title_zh": "算法边界:初筛漏报锁定后不可翻转", "summary_en": "A small corner house appears on the right and is present in Beam-15 top-1, but Stage 1 predicts Unchanged. Because state-locking is structural, Stage 2 cannot override a Stage 1 false negative.", "summary_zh": "画面右侧出现小范围房屋变化且位于 Beam-15 首句中,但第一阶段误判为无变化;由于状态锁定是结构保证,第二阶段无法挽回初筛漏报。", "clip": "clips/test_001095.mp4"}]
README.md+2
app.py+92-25
inference.py+5-3
public/cases.json+1-1
public/clips/test_000033.mp4Added
public/clips/test_001095.mp4Added
public/clips/test_001324.mp4Added
public/clips/test_001549.mp4Added