Spaces:
Running on Zero

thirteen7's picture
Show live inference nodes and per-stage timings
d808dae verified
Raw History Blame Contribute Delete
3.03 kB
"""Serve the decision workbench and its queued ZeroGPU trace."""
import logging
import os
import gradio as gr
import spaces
from fastapi.responses import FileResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from starlette.routing import Mount, Route
from inference import prepare, trace_case
from judge.questions import CHANGED, GENERAL
from pipeline import ROOT, decision, next_stage, profile, read
LOGGER = logging.getLogger(__name__)
PUBLIC = ROOT / 'public'
FRONTEND = ROOT / 'workbench'
CASES = {record['name']: record for record in read(PUBLIC / 'cases.json')}
TASK_PAIRS = read(PUBLIC / 'task_pairs.json')
CONFIG = profile('levir')
CHECKPOINTS = None
def load_checkpoints():
token = os.environ.get('CTR_MODEL_READ_TOKEN')
if not token:
return None
try:
return prepare(token)
except Exception as error:
LOGGER.error('Checkpoint preparation failed (%s). Check Space secret permissions and model availability.',
type(error).__name__)
return None
@spaces.GPU(duration=120)
def run_live(case_name):
if case_name not in CASES:
raise gr.Error('Select a listed image pair.')
if CHECKPOINTS is None:
raise gr.Error('GPU weights are unavailable.')
yield from trace_case(CASES[case_name], CHECKPOINTS)
def catalog():
records = []
for name, record in CASES.items():
row = record['replay']
captions = row['captions']
anchor = max(row['stage1'], key=lambda pair: pair[1])[0]
_, changed = next_stage('levir', captions, anchor, CONFIG['templates'])
trace = {**row, 'name': name, 'anchor': anchor, 'changed': changed,
'eligible': [index for index, _ in row['stage2']],
'final': decision('levir', row, CONFIG['beta'], CONFIG['templates'])}
records.append({**record, 'replay': trace})
return {'cases': records, 'task_pairs': TASK_PAIRS, 'templates': CONFIG['templates'], 'beta': CONFIG['beta'],
'tasks': [GENERAL, CHANGED], 'live': CHECKPOINTS is not None}
def workbench_routes():
return [
Route('/', lambda request: FileResponse(FRONTEND / 'index.html')),
Route('/catalog', lambda request: JSONResponse(catalog())),
Mount('/workbench', StaticFiles(directory=FRONTEND)),
Mount('/media/images', StaticFiles(directory=PUBLIC / 'images')),
Mount('/media/clips', StaticFiles(directory=PUBLIC / 'clips')),
]
def build():
with gr.Blocks(analytics_enabled=False) as api:
case = gr.Textbox(visible=False)
result = gr.JSON(visible=False)
submit = gr.Button(visible=False)
submit.click(run_live, case, result, api_name='run_case', api_visibility='undocumented', concurrency_limit=1)
return api.queue(max_size=8)
def launch():
build().launch(app_kwargs={'routes': workbench_routes()}, show_error=False, blocked_paths=[str(ROOT)], ssr_mode=False)
if __name__ == '__main__':
CHECKPOINTS = load_checkpoints()
launch()