Spaces:
Running on Zero

File size: 3,031 Bytes
c38a7c7
a369496
 
 
 
 
c38a7c7
ac0f3cd
c38a7c7
ac0f3cd
a369496
7eaecad
c38a7c7
7eaecad
a369496
 
 
c38a7c7
a369496
8dcd89f
7eaecad
 
a369496
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c38a7c7
a369496
c38a7c7
d808dae
c38a7c7
 
 
 
 
 
 
 
 
 
 
 
 
8dcd89f
c38a7c7
a369496
 
ac0f3cd
 
 
 
 
 
 
 
c38a7c7
 
ac0f3cd
c38a7c7
 
 
 
 
ac0f3cd
 
 
 
99b9895
a369496
 
 
 
ac0f3cd
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
"""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()