Spaces:
Sleeping

File size: 5,244 Bytes
6444a02
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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")