"""CLAIR (Clause Intelligence and Retrieval): FastAPI service for semantic sentence search over the CLAUDETTE Terms-of-Service corpus. The backend frozen by the development evaluation (artifacts/selection.json) is loaded once at startup. The optional unfair-clause classifier is loaded if its artifact exists; its absence never blocks search. """ from __future__ import annotations import logging import os from contextlib import asynccontextmanager from pathlib import Path from fastapi import FastAPI, HTTPException from fastapi.responses import FileResponse, JSONResponse from fastapi.staticfiles import StaticFiles from pydantic import BaseModel, Field, field_validator from app.data import normalize from app.models import ARTIFACTS_DIR, load_backend, load_corpus, selected_method from app.retrieval import format_results, rank log = logging.getLogger("uvicorn.error") STATIC_DIR = Path(__file__).resolve().parent / "static" MAX_QUERY_CHARS = 2000 MAX_K = 50 state: dict = {"ready": False} @asynccontextmanager async def lifespan(_: FastAPI): artifacts = Path(os.environ.get("ARTIFACTS_DIR", ARTIFACTS_DIR)) method = os.environ.get("SEARCH_METHOD", selected_method(artifacts)) state["groups"] = load_corpus(artifacts) state["backend"] = load_backend(method, state["groups"], artifacts) state["method"] = method state["classifier"] = None clf_path = artifacts / "classifier.joblib" if clf_path.exists(): try: import joblib state["classifier"] = joblib.load(clf_path) except Exception: # classifier is optional: log and keep serving search log.exception("Could not load classifier from %s", clf_path) state["ready"] = True log.info("Ready: %s backend over %d sentence groups; classifier=%s", method, len(state["groups"]), state["classifier"] is not None) yield state.clear() state["ready"] = False app = FastAPI( title="CLAIR — Clause Intelligence and Retrieval", description="Retrieve functionally or topically similar Terms-of-Service clauses and flag " "potentially unfair ones. " "Scores are ranking scores (BM25 or cosine similarity), not probabilities.", version="1.0.0", lifespan=lifespan, ) class _TextIn(BaseModel): @staticmethod def _non_blank(v: str) -> str: v = v.strip() if not v: raise ValueError("must not be blank") return v class SearchRequest(_TextIn): query: str = Field(..., max_length=MAX_QUERY_CHARS, examples=["We may terminate your account at any time."]) k: int = Field(10, ge=1, le=MAX_K, strict=True) _check = field_validator("query")(_TextIn._non_blank) class ClassifyRequest(_TextIn): text: str = Field(..., max_length=MAX_QUERY_CHARS, examples=["We may terminate your account at any time."]) _check = field_validator("text")(_TextIn._non_blank) class Occurrence(BaseModel): contract: str position: int original: str class SearchHit(BaseModel): rank: int group_id: str text: str score: float method: str occurrences: list[Occurrence] class SearchResponse(BaseModel): query: str method: str k: int score_note: str = "Scores rank results within one method; they are not probabilities." results: list[SearchHit] class ClassifyResponse(BaseModel): text: str potentially_unfair: bool probability: float threshold: float note: str = ("Predicts the dataset's 'potentially unfair' annotation (CLAUDETTE); " "it is not a legal determination.") @app.get("/health") def health() -> dict: return {"status": "ok"} @app.get("/ready") def ready(): if not state.get("ready"): return JSONResponse(status_code=503, content={"ready": False}) return { "ready": True, "method": state["method"], "corpus_groups": len(state["groups"]), "classifier": state["classifier"] is not None, } def _require_ready() -> None: if not state.get("ready"): raise HTTPException(status_code=503, detail="Service is not ready") @app.post("/search", response_model=SearchResponse) def search(req: SearchRequest) -> SearchResponse: _require_ready() backend = state["backend"] scores = backend.scores(req.query) hits = format_results(state["groups"], scores, rank(scores, req.k), backend.method) return SearchResponse(query=req.query, method=backend.method, k=req.k, results=hits) @app.post("/classify", response_model=ClassifyResponse) def classify(req: ClassifyRequest) -> ClassifyResponse: _require_ready() clf = state["classifier"] if clf is None: raise HTTPException(status_code=503, detail="Classifier artifact not available") prob = float(clf["pipeline"].predict_proba([normalize(req.text)])[0, 1]) return ClassifyResponse(text=req.text, potentially_unfair=prob >= clf["threshold"], probability=round(prob, 4), threshold=round(clf["threshold"], 4)) @app.get("/", include_in_schema=False) def index() -> FileResponse: return FileResponse(STATIC_DIR / "index.html") app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")