File size: 1,060 Bytes
c2c9593
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from fastapi import FastAPI, Header, HTTPException
from pydantic import BaseModel
import os
from sklearn.linear_model import LogisticRegression
import numpy as np

app = FastAPI()
TOKEN = os.environ.get("API_TOKEN", "demo-token-change-me")

# Toy model — XOR-ish dataset, entrenado al arrancar el container
X_train = [[0, 0], [1, 1], [0, 1], [1, 0], [0.2, 0.1], [0.9, 0.8]]
y_train = [0, 1, 1, 0, 0, 1]
model = LogisticRegression().fit(X_train, y_train)


class Body(BaseModel):
    instances: list[dict]


@app.get("/")
def root():
    return {"status": "ok", "endpoint": "/predict"}


@app.post("/predict")
def predict(body: Body, authorization: str = Header(None)):
    if authorization != f"Bearer {TOKEN}":
        raise HTTPException(status_code=401, detail="invalid token")
    X = np.array([[r.get("x", 0), r.get("y", 0)] for r in body.instances])
    probs = model.predict_proba(X)[:, 1]
    return {
        "predictions": [
            {"score": float(p), "label": "positive" if p > 0.5 else "negative"}
            for p in probs
        ]
    }