Spaces:
Sleeping

File size: 8,274 Bytes
9682a14
 
 
 
 
 
 
44c3bc0
 
 
 
 
61b25c5
44c3bc0
 
 
61b25c5
a30b560
 
 
 
 
 
 
44c3bc0
 
 
 
e24fbd1
61b25c5
dc24afc
 
 
e24fbd1
44c3bc0
 
 
 
 
 
 
 
 
189ed5c
 
 
 
 
 
44c3bc0
 
 
 
 
 
 
 
 
 
e24fbd1
 
44c3bc0
 
 
 
 
 
 
 
 
 
8738edc
44c3bc0
 
 
 
 
 
 
 
 
 
 
e24fbd1
 
 
 
61b25c5
44c3bc0
 
 
 
e24fbd1
44c3bc0
 
 
 
 
dc24afc
61b25c5
44c3bc0
 
 
 
 
 
61b25c5
dc24afc
e24fbd1
61b25c5
e24fbd1
 
dc24afc
e24fbd1
 
 
 
dc24afc
 
e24fbd1
 
 
 
dc24afc
 
 
 
 
 
 
 
 
 
 
 
 
44c3bc0
 
 
e24fbd1
44c3bc0
 
 
 
 
56238c9
 
a30b560
 
 
 
 
56238c9
 
44c3bc0
 
 
 
a30b560
 
 
 
 
 
 
44c3bc0
 
 
 
 
 
 
 
 
 
5823afb
 
 
8473813
44c3bc0
 
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
import spaces

# Register ZeroGPU compatibility without allocating GPU resources.
@spaces.GPU(duration=1)
def _noop():
    pass  # Never called: survey and persistence stay on CPU.

import os, json, hashlib, hmac, random, uuid, threading, time
from pathlib import Path
from datetime import datetime, timezone
from fastapi import FastAPI, HTTPException
from fastapi.responses import FileResponse
from pydantic import BaseModel, Field, StrictInt

ROOT = Path(__file__).parent
import zipfile
for bundle in ('assets.zip', 'study_r2_assets.zip', 'study_score_guide.zip'):
 if not (ROOT / bundle).is_file(): continue
 with zipfile.ZipFile(ROOT / bundle) as archive:
     for member in archive.infolist():
         target = (ROOT / member.filename).resolve()
         if not target.is_relative_to(ROOT.resolve()):
             raise RuntimeError('Invalid packaged asset path')
     archive.extractall(ROOT)
DATA = ROOT / 'data'
DEMO = os.getenv('DEMO_MODE', 'true').lower() == 'true'
SECRET = os.getenv('ASSIGNMENT_SECRET', 'demo-only-secret')
REPO = os.getenv('HF_DATASET_REPO', '')
LEGACY_VERSION = 'curated30-v1'
RANK_VERSION = 'curated30-rank-v2'
RANK_SCORE_VERSION = 'curated30-rank-score-v3'
VERSION = 'curated30-score-v4'
VERSIONS = {LEGACY_VERSION, RANK_VERSION, RANK_SCORE_VERSION, VERSION}
RANK_KEYS = {'instruction', 'physics'}
if not DEMO and (len(SECRET) < 32 or not REPO or not os.getenv('HF_TOKEN')):
    raise RuntimeError('Set ASSIGNMENT_SECRET (32+ characters), HF_DATASET_REPO and HF_TOKEN')
META = json.loads((DATA / 'metadata.json').read_text())
MODELS = META['models']
assert len(MODELS) == 4 and len(set(MODELS)) == 4
SAMPLES = META['samples']
assert len({s['id'] for s in SAMPLES}) == len(SAMPLES)
LOCK = threading.Lock()
app = FastAPI()
from tutorial_routes import register_tutorial_routes
register_tutorial_routes(app, ROOT)

@app.get("/static/outbox.js")
def outbox_script():
    return FileResponse(ROOT / "static/outbox.js", media_type="application/javascript", headers={"Cache-Control": "no-store"})

def participant(pid):
    try: return str(uuid.UUID(pid))
    except ValueError: raise HTTPException(400, 'Invalid participant')

def sample(sid):
    for s in SAMPLES:
        if s['id'] == sid: return s
    raise HTTPException(404)

def order(pid, sid, version):
    seed = hmac.new(SECRET.encode(), f'{version}:{participant(pid)}:{sid}'.encode(), hashlib.sha256).digest()
    result = MODELS.copy()
    random.Random(seed).shuffle(result)
    return result

def asset(path):
    p = (DATA / path).resolve()
    if not p.is_relative_to(DATA.resolve()) or not p.is_file(): raise HTTPException(404)
    return FileResponse(p, headers={'Cache-Control': 'no-store'})

@app.get('/')
def home(): return FileResponse(ROOT / 'index.html', headers={'Cache-Control': 'no-store'})

@app.get('/api/study')
def study(pid: str):
    participant(pid)
    samples = SAMPLES.copy()
    seed = hmac.new(SECRET.encode(), f'{VERSION}:{participant(pid)}:sample-order'.encode(), hashlib.sha256).digest()
    random.Random(seed).shuffle(samples)
    return {'version': VERSION, 'demo': DEMO, 'samples': [{'id': s['id'], 'instruction': s['instruction']} for s in samples]}

@app.get('/api/media/{pid}/{sid}/{slot}')
def media(pid: str, sid: str, slot: str):
    return versioned_media(LEGACY_VERSION, pid, sid, slot)

@app.get('/api/media/{version}/{pid}/{sid}/{slot}')
def versioned_media(version: str, pid: str, sid: str, slot: str):
    if version not in VERSIONS: raise HTTPException(404)
    s = sample(sid)
    participant(pid)
    if slot == 'input': return asset(s['input'])
    if slot not in 'ABCD' or len(slot) != 1: raise HTTPException(404)
    return asset(s['results'][order(pid, sid, version)['ABCD'.index(slot)]])

class Response(BaseModel):
    participant_id: str
    sample_id: str
    version: str
    answers: dict[str, str | list[str]] | None = None
    scores: dict[str, dict[str, StrictInt]] | None = None
    submitted_at: str = Field(max_length=40)

@app.post('/api/submit')
def submit(body: Response):
    pid = participant(body.participant_id)
    s = sample(body.sample_id)
    if body.version not in VERSIONS: raise HTTPException(409, 'Survey version changed; reload')
    if body.version not in {RANK_SCORE_VERSION, VERSION} and body.scores is not None: raise HTTPException(400, 'Scores are not supported in this version')
    mapping = dict(zip('ABCD', order(pid, s['id'], body.version)))
    record = {**body.model_dump(exclude_none=True), 'session_id': s['session_id'], 'turn': s['turn'],
              'dataset': s.get('dataset', 'unknown'), 'mapping': mapping}
    if body.version == LEGACY_VERSION:
        if body.answers is None or set(body.answers) != RANK_KEYS | {'overall'} or any(
            not isinstance(v, str) or v not in list('ABCD') for v in body.answers.values()
        ):
            raise HTTPException(400, 'Answer all three questions')
        record['selected_models'] = {k: mapping[v] for k, v in body.answers.items()}
    elif body.version in {RANK_VERSION, RANK_SCORE_VERSION}:
        if body.answers is None or set(body.answers) != RANK_KEYS or any(
            not isinstance(v, list) or len(v) != 4 or set(v) != set('ABCD') for v in body.answers.values()
        ):
            raise HTTPException(400, 'Rank each result once for both criteria')
        record['ranked_models'] = {k: [mapping[letter] for letter in v] for k, v in body.answers.items()}
    elif body.answers is not None:
        raise HTTPException(400, 'Rank answers are not supported in this version')
    if body.version in {RANK_SCORE_VERSION, VERSION}:
        scores = body.scores
        if scores is None or set(scores) != RANK_KEYS or any(
            set(per_slot) != set('ABCD') or any(not 1 <= value <= 5 for value in per_slot.values())
            for per_slot in scores.values()
        ):
            raise HTTPException(400, 'Give each result a score from 1 to 5 for both criteria')
        record['scores_by_model'] = {
            k: {mapping[letter]: value for letter, value in per_slot.items()}
            for k, per_slot in scores.items()
        }
    payload = json.dumps(record, ensure_ascii=False, sort_keys=True).encode()
    # Immutable event: identical retry = identical path and bytes. Analysis deduplicates participant/sample.
    digest = hashlib.sha256(payload).hexdigest()
    path = f'responses/{body.version}/{pid}/{digest}.json'
    if DEMO: return {'saved': False, 'demo': True}
    save_payload(payload, path)
    return {'saved': True}

def save_payload(payload, path):
    from storage_writer import save_payload as save_batched
    try:
        if os.getenv('HF_RESPONSE_BUCKET'):
            from bucket_storage import save_payload as save_durable
            save_durable(payload, path)
        else:
            save_batched(payload, path, REPO)
    except Exception:
        raise HTTPException(503, 'Storage unavailable. Retry the same response.') from None


@app.on_event('startup')
async def check_live_storage():
    if os.getenv('HF_RESPONSE_BUCKET'):
        from starlette.concurrency import run_in_threadpool
        from bucket_storage import initialize
        if os.getenv('BUCKET_STORAGE_SELFTEST', 'false').lower() == 'true':
            from bucket_selftest import run_selftest
            app.state.bucket_storage_test = await run_in_threadpool(run_selftest)
        await run_in_threadpool(initialize)
    if os.getenv('LIVE_STORAGE_SELFTEST', 'false').lower() == 'true':
        if DEMO:
            raise RuntimeError('Storage self-test requires live storage configuration')
        from starlette.concurrency import run_in_threadpool
        from storage_selftest import run_selftest
        app.state.storage_test = await run_in_threadpool(run_selftest, save_payload, REPO)

if __name__ == '__main__':
    # Hugging Face Gradio SDK launches app_file with Python. This serves the
    # existing FastAPI study on the SDK's expected port without changing its UI.
    import gradio as gr
    with gr.Blocks() as compatibility:
        gr.Markdown('Image editing study service')
    compatibility.launch(server_name='127.0.0.1', server_port=8765, prevent_thread_lock=True, show_api=False, quiet=True)
    import uvicorn
    uvicorn.run(app, host='0.0.0.0', port=7860, workers=1)