Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, Header, HTTPException
|
| 2 |
+
from pydantic import BaseModel
|
| 3 |
+
import os
|
| 4 |
+
from sklearn.linear_model import LogisticRegression
|
| 5 |
+
import numpy as np
|
| 6 |
+
|
| 7 |
+
app = FastAPI()
|
| 8 |
+
TOKEN = os.environ.get("API_TOKEN", "demo-token-change-me")
|
| 9 |
+
|
| 10 |
+
# Toy model — XOR-ish dataset, entrenado al arrancar el container
|
| 11 |
+
X_train = [[0, 0], [1, 1], [0, 1], [1, 0], [0.2, 0.1], [0.9, 0.8]]
|
| 12 |
+
y_train = [0, 1, 1, 0, 0, 1]
|
| 13 |
+
model = LogisticRegression().fit(X_train, y_train)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class Body(BaseModel):
|
| 17 |
+
instances: list[dict]
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@app.get("/")
|
| 21 |
+
def root():
|
| 22 |
+
return {"status": "ok", "endpoint": "/predict"}
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@app.post("/predict")
|
| 26 |
+
def predict(body: Body, authorization: str = Header(None)):
|
| 27 |
+
if authorization != f"Bearer {TOKEN}":
|
| 28 |
+
raise HTTPException(status_code=401, detail="invalid token")
|
| 29 |
+
X = np.array([[r.get("x", 0), r.get("y", 0)] for r in body.instances])
|
| 30 |
+
probs = model.predict_proba(X)[:, 1]
|
| 31 |
+
return {
|
| 32 |
+
"predictions": [
|
| 33 |
+
{"score": float(p), "label": "positive" if p > 0.5 else "negative"}
|
| 34 |
+
for p in probs
|
| 35 |
+
]
|
| 36 |
+
}
|