Spaces:
Running on Zero

File size: 5,297 Bytes
3e6f84d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Same React API contract, with explicit public visitor isolation and consent."""
import json
import threading
from typing import Literal
import numpy as np
from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import JSONResponse
from fastapi.concurrency import run_in_threadpool
from pydantic import BaseModel, Field
from sqlmodel import Session, select
import visitors
from database import engine, InferenceJob
from sessions import router as sessions_router
from jobs import router as jobs_router, status
from content import BY_ID, PASSAGES
from scoring import align, tokenize
from learning import export_records, ACTIONS, VERSION, REWARD
from ope import evaluate
from inference import TEXT_ONLY, MODEL_ID

app = FastAPI(title='ReadLoops public demo', docs_url=None, redoc_url=None, openapi_url=None)
app.include_router(sessions_router)
app.include_router(jobs_router)


@app.middleware('http')
async def visitor_scope(request: Request, call_next):
    if request.url.path.endswith('/api/visitor') and request.method == 'POST':
        return await call_next(request)
    token = request.headers.get('authorization', '').removeprefix('Bearer ')
    try:
        visitor = visitors.lookup(token)
    except HTTPException as exc:
        return JSONResponse({'detail': exc.detail}, status_code=exc.status_code)
    acquired = await run_in_threadpool(visitor.lock.acquire, True, 10)
    if not acquired:
        return JSONResponse({'detail': 'This visit is busy. Retry shortly.'}, status_code=503)
    context = visitors.current.set(visitor)
    try:
        if request.method == 'POST' and request.url.path.endswith('/api/sessions') and not visitor.adult:
            return JSONResponse({'detail': 'Confirm that you are 18 or older first.'}, status_code=403)
        if request.method == 'PUT' and request.url.path.endswith('/audio') and not visitor.audio_consent:
            return JSONResponse({'detail': 'Consent to sending audio to Hugging Face first.'}, status_code=403)
        response = await call_next(request)
        response.headers['Cache-Control'] = 'no-store'
        return response
    finally:
        visitors.current.reset(context)
        visitor.lock.release()


@app.post('/api/visitor')
def new_visitor():
    return {'token': visitors.create(), 'expires_after_inactive_seconds': visitors.TTL}


class Consent(BaseModel):
    adult: bool
    audio: bool = False


@app.post('/api/consent')
def consent(body: Consent):
    if not body.adult:
        raise HTTPException(403, 'This demo is for adults aged 18 and older.')
    visitor = visitors.active()
    visitor.adult, visitor.audio_consent = body.adult, body.audio
    return {'adult': visitor.adult, 'audio': visitor.audio_consent}


@app.get('/api/health')
def health():
    return {'status': 'ok', 'service': 'readloops-space', 'version': '0.12.0-space',
            'speech': {'ready': not TEXT_ONLY, 'model': MODEL_ID}, 'pilot': None}


@app.get('/api/passages')
def passages(language: Literal['en', 'el'], split: Literal['practice', 'evaluation'] = 'practice'):
    return [{k: p[k] for k in ('id', 'title', 'language', 'split')} |
            {'word_count': len(tokenize(p['text'], language))}
            for p in PASSAGES if p['language'] == language and p['split'] == split]


class Comparison(BaseModel):
    passage_id: str
    transcript: str = Field(min_length=1, max_length=6000)
    source: Literal['manual', 'speech', 'speech-edited'] = 'manual'
    transcript_reviewed: bool = False


@app.post('/api/compare')
def compare(body: Comparison):
    if body.passage_id not in BY_ID:
        raise HTTPException(404, 'Passage not found.')
    if body.source.startswith('speech') and not body.transcript_reviewed:
        raise HTTPException(422, 'Check the transcript against your recording before comparing words.')
    passage = BY_ID[body.passage_id]
    try:
        return align(passage['text'], body.transcript, passage['language'])
    except ValueError as exc:
        raise HTTPException(422, str(exc)) from None


@app.get('/api/lab/records')
def records(language: Literal['en', 'el']):
    with Session(engine()) as db:
        return export_records(db, language)


@app.get('/api/lab/report')
def report(language: Literal['en', 'el']):
    rows = records(language)
    with Session(engine()) as db:
        outcomes = [json.loads(j.result) for j in db.exec(select(InferenceJob)).all() if j.result]
    selected = [r for r in outcomes if r.get('language') == language]
    durations = [r['end_to_end_seconds'] for r in selected]
    return {'version': VERSION, 'reward': REWARD, 'language': language, 'jobs': status(),
            'ope': evaluate(rows, {a: 1 / len(ACTIONS) for a in ACTIONS}), 'calibration': {},
            'inference': {'completed': len(selected), 'cascade_runs': 0,
                'p50_end_to_end_seconds': float(np.median(durations)) if durations else None,
                'p95_end_to_end_seconds': float(np.quantile(durations, .95)) if durations else None},
            'notice': 'Only this temporary visit is included. No hosted benchmark or reviewed calibration is available. Individual sessions do not establish policy superiority or learning gains.'}


threading.Thread(target=visitors.cleanup_loop, name='visit-expiry', daemon=True).start()