Spaces:
Running on Zero
Running on Zero
Download space_api.py from ManasT2485/readloops: direct link, hf CLI and curl.
- Browser
- Download file 5.3 kB
-
https://huggingface.co/spaces/ManasT2485/readloops/resolve/main/space_api.py
- Command line
-
hf download hf://spaces/ManasT2485/readloops/space_api.py
-
curl -L -o space_api.py https://huggingface.co/spaces/ManasT2485/readloops/resolve/main/space_api.py
5.3 kB
| """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) | |
| 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() | |
| def new_visitor(): | |
| return {'token': visitors.create(), 'expires_after_inactive_seconds': visitors.TTL} | |
| class Consent(BaseModel): | |
| adult: bool | |
| audio: bool = False | |
| 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} | |
| def health(): | |
| return {'status': 'ok', 'service': 'readloops-space', 'version': '0.12.0-space', | |
| 'speech': {'ready': not TEXT_ONLY, 'model': MODEL_ID}, 'pilot': None} | |
| 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 | |
| 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 | |
| def records(language: Literal['en', 'el']): | |
| with Session(engine()) as db: | |
| return export_records(db, language) | |
| 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() | |