Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,20 +1,18 @@
|
|
| 1 |
import json
|
|
|
|
| 2 |
from typing import Any, Dict
|
| 3 |
-
|
| 4 |
import numpy as np
|
| 5 |
import tensorflow as tf
|
| 6 |
-
from fastapi import FastAPI,
|
|
|
|
| 7 |
|
| 8 |
-
# -----------------
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
MODEL_PATH = "best_model.h5" # upload alongside app.py
|
| 12 |
-
STATS_PATH = "means_std.json" # {"feature":{"mean":..., "std":...}, ...}
|
| 13 |
CLASSES = ["Top", "Mid-Top", "Mid", "Mid-Low", "Low"]
|
|
|
|
| 14 |
|
| 15 |
-
# -----------------
|
| 16 |
-
# Load artifacts
|
| 17 |
-
# -----------------
|
| 18 |
print("Loading model and stats...")
|
| 19 |
model = tf.keras.models.load_model(MODEL_PATH, compile=False)
|
| 20 |
|
|
@@ -24,76 +22,100 @@ with open(STATS_PATH, "r") as f:
|
|
| 24 |
FEATURES = list(stats.keys())
|
| 25 |
print("Feature order:", FEATURES)
|
| 26 |
|
| 27 |
-
|
| 28 |
-
# Helpers
|
| 29 |
-
# -----------------
|
| 30 |
-
def _z(v: Any, mean: float, sd: float) -> float:
|
| 31 |
try:
|
| 32 |
-
|
| 33 |
except Exception:
|
| 34 |
return 0.0
|
| 35 |
-
if not sd
|
| 36 |
return 0.0
|
| 37 |
-
return (
|
| 38 |
|
| 39 |
-
def
|
| 40 |
-
"""
|
| 41 |
-
For ordinal (K-1 logits): p_k = σ(z_{k-1}) - σ(z_k) with σ(z_0)=1, σ(z_K)=0
|
| 42 |
-
"""
|
| 43 |
logits = tf.convert_to_tensor(logits_np, dtype=tf.float32)
|
| 44 |
-
sig = tf.math.sigmoid(logits)
|
| 45 |
left = tf.concat([tf.ones_like(sig[:, :1]), sig], axis=1)
|
| 46 |
right = tf.concat([sig, tf.zeros_like(sig[:, :1])], axis=1)
|
| 47 |
probs = tf.clip_by_value(left - right, 1e-12, 1.0)
|
| 48 |
return probs.numpy()
|
| 49 |
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
z = [ _z(ratios.get(f, 0.0), stats[f]["mean"], stats[f]["std"]) for f in FEATURES ]
|
| 54 |
-
X = np.array([z], dtype=np.float32) # (1, D)
|
| 55 |
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
else:
|
| 65 |
-
raise ValueError(f"Model output width {raw.shape[1]} incompatible with {len(CLASSES)} classes")
|
| 66 |
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
probs = probs / s if s > 0 else np.ones(len(CLASSES)) / len(CLASSES)
|
| 70 |
-
|
| 71 |
-
pred_idx = int(np.argmax(probs))
|
| 72 |
return {
|
| 73 |
-
"
|
| 74 |
-
"
|
| 75 |
-
"probabilities": {CLASSES[i]: float(probs[i]) for i in range(len(CLASSES))},
|
| 76 |
-
"predicted_state": CLASSES[pred_idx],
|
| 77 |
}
|
| 78 |
|
| 79 |
-
# -----------------
|
| 80 |
-
# FastAPI app
|
| 81 |
-
# -----------------
|
| 82 |
-
app = FastAPI()
|
| 83 |
-
|
| 84 |
@app.get("/health")
|
| 85 |
def health():
|
| 86 |
-
return {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
|
| 88 |
@app.post("/predict")
|
| 89 |
-
def predict(
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
if not isinstance(payload, dict):
|
| 94 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import json
|
| 2 |
+
import os
|
| 3 |
from typing import Any, Dict
|
| 4 |
+
|
| 5 |
import numpy as np
|
| 6 |
import tensorflow as tf
|
| 7 |
+
from fastapi import FastAPI, Request
|
| 8 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 9 |
|
| 10 |
+
# ----------------- CONFIG -----------------
|
| 11 |
+
MODEL_PATH = os.getenv("MODEL_PATH", "best_model.h5")
|
| 12 |
+
STATS_PATH = os.getenv("STATS_PATH", "means_std.json")
|
|
|
|
|
|
|
| 13 |
CLASSES = ["Top", "Mid-Top", "Mid", "Mid-Low", "Low"]
|
| 14 |
+
# ------------------------------------------
|
| 15 |
|
|
|
|
|
|
|
|
|
|
| 16 |
print("Loading model and stats...")
|
| 17 |
model = tf.keras.models.load_model(MODEL_PATH, compile=False)
|
| 18 |
|
|
|
|
| 22 |
FEATURES = list(stats.keys())
|
| 23 |
print("Feature order:", FEATURES)
|
| 24 |
|
| 25 |
+
def _z(val: Any, mean: float, sd: float) -> float:
|
|
|
|
|
|
|
|
|
|
| 26 |
try:
|
| 27 |
+
v = float(val)
|
| 28 |
except Exception:
|
| 29 |
return 0.0
|
| 30 |
+
if not sd:
|
| 31 |
return 0.0
|
| 32 |
+
return (v - mean) / sd
|
| 33 |
|
| 34 |
+
def coral_probs_from_logits(logits_np: np.ndarray) -> np.ndarray:
|
| 35 |
+
"""(N, K-1) logits -> (N, K) probabilities for CORAL ordinal output."""
|
|
|
|
|
|
|
| 36 |
logits = tf.convert_to_tensor(logits_np, dtype=tf.float32)
|
| 37 |
+
sig = tf.math.sigmoid(logits) # (N, K-1)
|
| 38 |
left = tf.concat([tf.ones_like(sig[:, :1]), sig], axis=1)
|
| 39 |
right = tf.concat([sig, tf.zeros_like(sig[:, :1])], axis=1)
|
| 40 |
probs = tf.clip_by_value(left - right, 1e-12, 1.0)
|
| 41 |
return probs.numpy()
|
| 42 |
|
| 43 |
+
# ------------- FastAPI app ----------------
|
| 44 |
+
app = FastAPI(title="Static Fingerprint API", version="1.0.0")
|
|
|
|
|
|
|
|
|
|
| 45 |
|
| 46 |
+
# Allow Excel / local tools to call the API
|
| 47 |
+
app.add_middleware(
|
| 48 |
+
CORSMiddleware,
|
| 49 |
+
allow_origins=["*"],
|
| 50 |
+
allow_credentials=False,
|
| 51 |
+
allow_methods=["*"],
|
| 52 |
+
allow_headers=["*"],
|
| 53 |
+
)
|
|
|
|
|
|
|
| 54 |
|
| 55 |
+
@app.get("/")
|
| 56 |
+
def root():
|
|
|
|
|
|
|
|
|
|
| 57 |
return {
|
| 58 |
+
"message": "Static Fingerprint API is running.",
|
| 59 |
+
"try": ["GET /health", "POST /predict"],
|
|
|
|
|
|
|
| 60 |
}
|
| 61 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
@app.get("/health")
|
| 63 |
def health():
|
| 64 |
+
return {
|
| 65 |
+
"status": "ok",
|
| 66 |
+
"features": FEATURES,
|
| 67 |
+
"classes": CLASSES,
|
| 68 |
+
"model_file": MODEL_PATH,
|
| 69 |
+
"stats_file": STATS_PATH,
|
| 70 |
+
}
|
| 71 |
|
| 72 |
@app.post("/predict")
|
| 73 |
+
async def predict(req: Request):
|
| 74 |
+
"""
|
| 75 |
+
Body: a single JSON dict mapping feature -> numeric value.
|
| 76 |
+
Example:
|
| 77 |
+
{
|
| 78 |
+
"autosuf_oper": 1.0,
|
| 79 |
+
"cov_improductiva": 0.9,
|
| 80 |
+
...
|
| 81 |
+
}
|
| 82 |
+
"""
|
| 83 |
+
payload = await req.json()
|
| 84 |
if not isinstance(payload, dict):
|
| 85 |
+
return {"error": "Expected a JSON object mapping feature -> value."}
|
| 86 |
+
|
| 87 |
+
# Build z-scores in strict model order
|
| 88 |
+
z = []
|
| 89 |
+
z_detail = {}
|
| 90 |
+
missing = []
|
| 91 |
+
for f in FEATURES:
|
| 92 |
+
val = payload.get(f, 0)
|
| 93 |
+
mean = stats[f]["mean"]
|
| 94 |
+
sd = stats[f]["std"]
|
| 95 |
+
zf = _z(val, mean, sd)
|
| 96 |
+
z.append(zf)
|
| 97 |
+
z_detail[f] = zf
|
| 98 |
+
if f not in payload:
|
| 99 |
+
missing.append(f)
|
| 100 |
+
|
| 101 |
+
X = np.array([z], dtype=np.float32)
|
| 102 |
+
raw = model.predict(X, verbose=0)
|
| 103 |
+
|
| 104 |
+
# Detect CORAL (K-1) vs softmax (K)
|
| 105 |
+
if raw.ndim == 2 and raw.shape[1] == (len(CLASSES) - 1):
|
| 106 |
+
probs = coral_probs_from_logits(raw)[0]
|
| 107 |
+
else:
|
| 108 |
+
probs = raw[0]
|
| 109 |
+
# If it's not normalized, normalize defensively:
|
| 110 |
+
s = float(np.sum(probs))
|
| 111 |
+
if s > 0:
|
| 112 |
+
probs = probs / s
|
| 113 |
|
| 114 |
+
pred_idx = int(np.argmax(probs))
|
| 115 |
+
return {
|
| 116 |
+
"input_ok": (len(missing) == 0),
|
| 117 |
+
"missing": missing,
|
| 118 |
+
"z_scores": z_detail,
|
| 119 |
+
"probabilities": {CLASSES[i]: float(probs[i]) for i in range(len(CLASSES))},
|
| 120 |
+
"predicted_state": CLASSES[pred_idx],
|
| 121 |
+
}
|