Spaces:
Running on Zero
Running on Zero
Download sessions.py from ManasT2485/readloops: direct link, hf CLI and curl.
- Browser
- Download file 16.8 kB
-
https://huggingface.co/spaces/ManasT2485/readloops/resolve/main/sessions.py
- Command line
-
hf download hf://spaces/ManasT2485/readloops/sessions.py
-
curl -L -o sessions.py https://huggingface.co/spaces/ManasT2485/readloops/resolve/main/sessions.py
16.8 kB
| """Persistent, idempotent session lifecycle and per-language policy reporting.""" | |
| import json | |
| import hashlib | |
| import math | |
| from pathlib import Path | |
| from uuid import UUID | |
| from fastapi import APIRouter, HTTPException, Request, Response | |
| from fastapi.concurrency import run_in_threadpool | |
| from pydantic import BaseModel, Field | |
| from sqlmodel import Session, select | |
| from typing import Literal | |
| from content import BY_ID, public_passage | |
| from scoring import align | |
| from audio_io import MAX_BYTES | |
| from database import ReadingSession, Recording, SpeechObservation, engine, transaction, now | |
| from pilot_runtime import guard_create, guard_review, participant | |
| from exercises import exercise_for, public_exercise | |
| from policy import select_exercise | |
| from learning import MODES, choose | |
| from database import LearningReward | |
| from jobs import invalidate | |
| router = APIRouter(prefix='/api') | |
| def benchmark_report(): | |
| return {'languages': [], 'limitations': 'This hosted adapter has not been benchmarked.'} | |
| class Draft(BaseModel): | |
| step: int = Field(default=0, ge=0, le=2) | |
| transcript: str = Field(default='', max_length=6000) | |
| source: Literal['manual', 'speech', 'speech-edited'] = 'manual' | |
| compared: bool = False | |
| transcript_reviewed: bool = False | |
| dismissed: list[str] = Field(default_factory=list, max_length=500) | |
| class CreateRequest(BaseModel): | |
| id: UUID | |
| passage_id: str | |
| mode: Literal['fixed', 'adaptive', 'comparison', 'learning-fixed', 'learning-epsilon', 'learning-linucb', 'learning-comparison'] = 'fixed' | |
| class SaveRequest(BaseModel): | |
| revision: int = Field(ge=0) | |
| write_id: UUID | |
| draft: Draft | |
| class ChoiceRequest(BaseModel): | |
| choice: int = Field(ge=0, le=2) | |
| def load(db, identifier): | |
| row = db.get(ReadingSession, identifier) | |
| if row is None: | |
| raise HTTPException(404, 'Session not found.') | |
| return row | |
| def comparison_for(row): | |
| draft = json.loads(row.draft) | |
| if not draft.get('compared'): | |
| return None | |
| if draft.get('source', 'manual').startswith('speech') and not draft.get('transcript_reviewed') and row.status == 'active': | |
| if row.decision: | |
| # Pre-v2 exercises cannot return to review. Finish them without | |
| # generating a new score from an unconfirmed speech transcript. | |
| return None | |
| raise HTTPException(422, 'Review the transcript against your recording before comparing words, or continue without comparison.') | |
| try: | |
| return align(BY_ID[row.passage_id]['text'], draft['transcript'], row.language) | |
| except ValueError as exc: | |
| raise HTTPException(422, str(exc)) from exc | |
| def serialize(row, has_audio=False): | |
| decision = json.loads(row.decision) if row.decision else None | |
| result = {'id': row.id, 'passage_id': row.passage_id, 'title': BY_ID[row.passage_id]['title'], 'language': row.language, 'split': row.split, 'status': row.status, 'mode': row.selection_mode, 'revision': row.revision, 'last_write_id': row.last_write_id, 'draft': json.loads(row.draft), 'created_at': row.created_at, 'updated_at': row.updated_at, 'has_audio': has_audio, 'decision': decision, 'answer': json.loads(row.answer) if row.answer else None, 'result': json.loads(row.result) if row.result else None} | |
| if decision: | |
| result['exercise'] = public_exercise(decision.get('exercise_snapshot') or exercise_for(row.passage_id, decision['action'])) | |
| # Keep the immutable answer key server-side until the learner answers. | |
| result['decision'] = {key: value for key, value in decision.items() if key != 'exercise_snapshot'} | |
| return result | |
| def create_session(body: CreateRequest): | |
| passage = BY_ID.get(body.passage_id) | |
| if passage is None: | |
| raise HTTPException(404, 'Passage not found.') | |
| with transaction() as db: | |
| existing = db.get(ReadingSession, str(body.id)) | |
| if existing: | |
| if existing.passage_id != body.passage_id or existing.selection_mode != body.mode: | |
| raise HTTPException(409, 'This request ID belongs to a different session request.') | |
| return serialize(existing, db.get(Recording, existing.id) is not None) | |
| if passage['split'] == 'evaluation' and db.exec(select(ReadingSession).where(ReadingSession.passage_id == passage['id'])).first(): | |
| raise HTTPException(409, 'This evaluation passage has already been opened on this computer. Resume it from Progress if unfinished.') | |
| if len(db.exec(select(ReadingSession)).all()) >= 40: | |
| raise HTTPException(429, 'This demo visit has reached its 40-session limit.') | |
| guard_create(body.id, body.passage_id, body.mode) | |
| row = ReadingSession(id=str(body.id), passage_id=passage['id'], language=passage['language'], split=passage['split'], selection_mode=body.mode, draft=Draft().model_dump_json()) | |
| db.add(row) | |
| db.flush() | |
| return serialize(row) | |
| def list_sessions(language: Literal['en', 'el']): | |
| with Session(engine()) as db: | |
| rows = db.exec(select(ReadingSession).where(ReadingSession.language == language).order_by(ReadingSession.created_at.desc())).all() | |
| return [serialize(row, db.get(Recording, row.id) is not None) for row in rows] | |
| def get_session(identifier: str): | |
| with Session(engine()) as db: | |
| row = load(db, identifier) | |
| return {**serialize(row, db.get(Recording, row.id) is not None), 'passage': public_passage(BY_ID[row.passage_id])} | |
| def save_session(identifier: str, body: SaveRequest): | |
| with transaction() as db: | |
| row = load(db, identifier) | |
| if row.last_write_id == str(body.write_id): | |
| if body.draft.model_dump() != Draft.model_validate_json(row.draft).model_dump(): | |
| raise HTTPException(409, 'A saved write ID cannot be reused for different words.') | |
| return serialize(row, db.get(Recording, identifier) is not None) | |
| if row.status != 'active': | |
| raise HTTPException(409, 'This session is finished. Open Progress to view it.') | |
| if row.revision != body.revision: | |
| raise HTTPException(409, 'This session changed in another tab. Your local draft is kept. Reopen the session before editing further.') | |
| if row.decision and body.draft.model_dump() != json.loads(row.draft): | |
| raise HTTPException(409, 'The exercise was already selected. Resume the saved exercise.') | |
| if body.draft.step == 2 and not row.decision: | |
| raise HTTPException(409, 'Choose the exercise before entering this step.') | |
| row.draft = body.draft.model_dump_json() | |
| comparison_for(row) | |
| row.revision += 1 | |
| row.last_write_id = str(body.write_id) | |
| row.updated_at = now() | |
| db.add(row) | |
| return serialize(row, db.get(Recording, identifier) is not None) | |
| async def read_audio(request): | |
| data = bytearray() | |
| async for chunk in request.stream(): | |
| if len(data) + len(chunk) > MAX_BYTES: | |
| raise HTTPException(413, 'Audio must be smaller than 12 MB.') | |
| data.extend(chunk) | |
| if not data: | |
| raise HTTPException(422, 'Record or choose audio first.') | |
| return bytes(data) | |
| def store_audio(identifier, data, content_type, revision): | |
| with transaction() as db: | |
| row = load(db, identifier) | |
| if row.status != 'active' or row.decision: | |
| raise HTTPException(409, 'Audio can only change before the exercise is selected.') | |
| old = db.get(Recording, identifier) | |
| used = sum(len(record.data) for record in db.exec(select(Recording)).all() if record.session_id != identifier) | |
| if used + len(data) > 24 * 1024 * 1024: | |
| raise HTTPException(413, 'This visit has reached its 24 MB recording limit. Delete an older recording from Progress.') | |
| audio_write = 'audio:' + hashlib.sha256(data).hexdigest() | |
| if revision != row.revision: | |
| if old and old.data == data and row.revision == revision + 1 and row.last_write_id == audio_write: | |
| return serialize(row, True) | |
| raise HTTPException(409, 'This session changed in another tab. Reopen it before replacing the recording.') | |
| if old and old.data == data: | |
| return serialize(row, True) | |
| invalidate(db, identifier) | |
| observation = db.get(SpeechObservation, identifier) | |
| if observation: | |
| db.delete(observation) | |
| if old: | |
| old.data, old.content_type = data, content_type | |
| db.add(old) | |
| else: | |
| db.add(Recording(session_id=identifier, data=data, content_type=content_type)) | |
| row.draft = Draft().model_dump_json() | |
| row.revision += 1 | |
| row.last_write_id = audio_write | |
| row.updated_at = now() | |
| db.add(row) | |
| return serialize(row, True) | |
| async def save_audio(identifier: str, request: Request): | |
| try: | |
| revision = int(request.headers['if-match']) | |
| except (KeyError, ValueError): | |
| raise HTTPException(428, 'Reopen the session before uploading audio. A saved revision is required.') | |
| data = await read_audio(request) | |
| content_type = request.headers.get('content-type', 'application/octet-stream').split(';')[0] | |
| if content_type not in {'audio/webm', 'audio/wav', 'audio/x-wav', 'audio/ogg', 'audio/mpeg', 'audio/mp4', 'video/webm', 'application/octet-stream'}: | |
| content_type = 'application/octet-stream' | |
| return await run_in_threadpool(store_audio, identifier, data, content_type, revision) | |
| def get_audio(identifier: str): | |
| with Session(engine()) as db: | |
| recording = db.get(Recording, identifier) | |
| if recording is None: | |
| raise HTTPException(404, 'No saved recording for this session.') | |
| return Response(recording.data, media_type=recording.content_type, headers={'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff'}) | |
| def transcribe_saved(identifier: str): | |
| from jobs import enqueue | |
| return enqueue(identifier) | |
| def assign_exercise(identifier: str): | |
| with transaction() as db: | |
| row = load(db, identifier) | |
| if row.decision: | |
| return serialize(row, db.get(Recording, identifier) is not None) | |
| if row.status != 'active': | |
| raise HTTPException(409, 'This session is not active.') | |
| guard_review(db, row) | |
| invalidate(db, identifier, active_only=True) | |
| history = [(json.loads(other.decision), json.loads(other.answer)) for other in db.exec(select(ReadingSession).where(ReadingSession.language == row.language, ReadingSession.split == 'practice')).all() if other.decision and other.answer] | |
| draft = json.loads(row.draft) | |
| if row.selection_mode in MODES and row.split == 'practice': | |
| decision = choose(db, row, comparison_for(row)) | |
| else: | |
| decision = select_exercise(row.selection_mode, row.language, draft, comparison_for(row), history, evaluation=row.split == 'evaluation') | |
| decision['exercise_snapshot'] = exercise_for(row.passage_id, decision['action']) | |
| if decision.get('support_level') == 'supported': | |
| decision['exercise_snapshot']['support_text'] = BY_ID[row.passage_id]['text'] | |
| row.decision = json.dumps(decision) | |
| draft['step'] = 2 | |
| row.draft = json.dumps(draft) | |
| row.revision += 1 | |
| row.updated_at = now() | |
| db.add(row) | |
| return serialize(row, db.get(Recording, identifier) is not None) | |
| def answer_exercise(identifier: str, body: ChoiceRequest): | |
| with transaction() as db: | |
| row = load(db, identifier) | |
| if row.answer: | |
| answer = json.loads(row.answer) | |
| if answer['choice'] != body.choice: | |
| raise HTTPException(409, 'The first answer is already saved. It cannot be replaced.') | |
| return answer | |
| if row.status != 'active' or not row.decision: | |
| raise HTTPException(409, 'Choose an exercise first.') | |
| decision = json.loads(row.decision) | |
| exercise = decision.get('exercise_snapshot') or exercise_for(row.passage_id, decision['action']) | |
| answer = {'choice': body.choice, 'correct': body.choice == exercise['answer'], 'answer': exercise['answer'], 'explanation': exercise['explanation']} | |
| row.answer = json.dumps(answer) | |
| row.updated_at = now() | |
| db.add(row) | |
| return answer | |
| def finish_session(identifier: str): | |
| with transaction() as db: | |
| row = load(db, identifier) | |
| if row.status == 'completed': | |
| return serialize(row, db.get(Recording, identifier) is not None) | |
| if not row.answer: | |
| raise HTTPException(409, 'Answer the exercise before finishing.') | |
| comparison = comparison_for(row) | |
| draft = json.loads(row.draft) | |
| row.status = 'completed' | |
| row.updated_at = now() | |
| row.result = json.dumps({'exercise_correct': json.loads(row.answer)['correct'], 'word_difference_rate': comparison['word_difference_rate'] if comparison else None, 'suggestions_kept': sum(item['id'] not in draft['dismissed'] for item in comparison['differences']) if comparison else None, 'source': draft['source'], 'transcript_reviewed': draft.get('transcript_reviewed', False), 'completed_at': row.updated_at}) | |
| db.add(row) | |
| return serialize(row, db.get(Recording, identifier) is not None) | |
| def delete_session(identifier: str): | |
| if participant() is not None: | |
| raise HTTPException(409, 'Pilot readings cannot be reset individually. You can stop now or ask the organiser to withdraw your whole participant record.') | |
| with transaction() as db: | |
| row = load(db, identifier) | |
| invalidate(db, identifier, delete=True) | |
| for reward in db.exec(select(LearningReward).where((LearningReward.decision_id == identifier) | (LearningReward.outcome_id == identifier))).all(): | |
| db.delete(reward) | |
| db.flush() | |
| observation = db.get(SpeechObservation, identifier) | |
| if observation: | |
| db.delete(observation) | |
| db.flush() | |
| audio = db.get(Recording, identifier) | |
| if audio: | |
| db.delete(audio) | |
| db.flush() | |
| # Retain exposure, but erase learner content and reward. It must not become unseen again. | |
| if row.split == 'evaluation': | |
| row.status, row.draft, row.answer, row.result, row.decision = 'deleted', '{}', None, None, None | |
| db.add(row) | |
| else: | |
| db.delete(row) | |
| return {'deleted': True} | |
| def wilson(successes, total): | |
| if not total: | |
| return None | |
| z = 1.96 | |
| p = successes / total | |
| centre = (p + z*z/(2*total)) / (1 + z*z/total) | |
| half = z * math.sqrt(p*(1-p)/total + z*z/(4*total*total)) / (1 + z*z/total) | |
| return [round(centre-half, 4), round(centre+half, 4)] | |
| def policy_report(language: Literal['en', 'el']): | |
| with Session(engine()) as db: | |
| rows = db.exec(select(ReadingSession).where(ReadingSession.language == language, ReadingSession.split == 'practice')).all() | |
| arms = [] | |
| for policy in ('fixed', 'adaptive'): | |
| assigned = [row for row in rows if row.selection_mode == 'comparison' and row.decision and json.loads(row.decision)['policy'] == policy] | |
| answered = [row for row in assigned if row.answer] | |
| wins = sum(json.loads(row.answer)['correct'] for row in answered) | |
| arms.append({'policy': policy, 'assigned': len(assigned), 'answered': len(answered), 'completed': sum(row.status == 'completed' for row in assigned), 'successes': wins, 'success_rate': wins/len(answered) if answered else None, 'wilson_95': wilson(wins, len(answered))}) | |
| return {'language': language, 'arms': arms, 'notice': 'Only randomized comparison sessions are included. First-attempt exercise correctness is a surrogate, not learning gain. Repeated sessions from one learner are dependent; intervals are descriptive. Missing answers are reported, not treated as incorrect. Unseen assessments never train the policy.'} | |