Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,12 +2,12 @@ import json
|
|
| 2 |
import numpy as np
|
| 3 |
import tensorflow as tf
|
| 4 |
import gradio as gr
|
|
|
|
| 5 |
|
| 6 |
-
#
|
| 7 |
-
MODEL_PATH = "best_model.h5"
|
| 8 |
STATS_PATH = "Means & Std for Excel.json"
|
| 9 |
CLASSES = ["Top", "Mid-Top", "Mid", "Mid-Low", "Low"]
|
| 10 |
-
# ----------------------------------------
|
| 11 |
|
| 12 |
print("Loading model and stats...")
|
| 13 |
model = tf.keras.models.load_model(MODEL_PATH, compile=False)
|
|
@@ -17,78 +17,64 @@ with open(STATS_PATH, "r") as f:
|
|
| 17 |
FEATURES = list(stats.keys())
|
| 18 |
print("Feature order:", FEATURES)
|
| 19 |
|
| 20 |
-
|
| 21 |
-
def coral_probs_from_logits(logits_np):
|
| 22 |
-
"""Convert CORAL logits to probabilities if model output is ordinal."""
|
| 23 |
-
logits = tf.convert_to_tensor(logits_np, dtype=tf.float32)
|
| 24 |
-
sig = tf.math.sigmoid(logits)
|
| 25 |
-
left = tf.concat([tf.ones_like(sig[:, :1]), sig], axis=1)
|
| 26 |
-
right = tf.concat([sig, tf.zeros_like(sig[:, :1])], axis=1)
|
| 27 |
-
probs = tf.clip_by_value(left - right, 1e-12, 1.0)
|
| 28 |
-
return probs.numpy()
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
def zscore(val, mean, sd):
|
| 32 |
-
"""Z-score normalization (gracefully handles 0 std)."""
|
| 33 |
try:
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
"""Main callable function for Gradio."""
|
| 44 |
-
if isinstance(ratios, list) and len(ratios) == 1 and isinstance(ratios[0], dict):
|
| 45 |
-
ratios = ratios[0]
|
| 46 |
-
if not isinstance(ratios, dict):
|
| 47 |
-
return {"error": "Invalid input, must be dict of feature->value"}
|
| 48 |
-
|
| 49 |
-
# Compute z-scores
|
| 50 |
-
zvec = []
|
| 51 |
-
zmap = {}
|
| 52 |
for f in FEATURES:
|
| 53 |
mean = stats[f]["mean"]
|
| 54 |
-
|
| 55 |
-
z =
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
|
|
|
|
|
|
| 67 |
else:
|
| 68 |
-
|
| 69 |
-
probs = s / s.sum() if s.sum() > 0 else np.ones(len(CLASSES)) / len(CLASSES)
|
| 70 |
-
|
| 71 |
-
pred = CLASSES[int(np.argmax(probs))]
|
| 72 |
|
|
|
|
| 73 |
return {
|
| 74 |
-
"input_ok":
|
| 75 |
-
"missing":
|
| 76 |
-
"z_scores": zmap,
|
| 77 |
"probabilities": {CLASSES[i]: float(probs[i]) for i in range(len(CLASSES))},
|
| 78 |
-
"predicted_state":
|
| 79 |
}
|
| 80 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
|
| 82 |
-
#
|
| 83 |
iface = gr.Interface(
|
| 84 |
fn=predict_from_json,
|
| 85 |
inputs=gr.JSON(label="ratios JSON (dict of feature -> value)"),
|
| 86 |
outputs="json",
|
| 87 |
title="Static Fingerprint Model API",
|
| 88 |
-
description=
|
| 89 |
-
"POST JSON to `/run/predict` with a dict of your 21 ratios. "
|
| 90 |
-
"Server normalises using saved means/stds and returns probabilities + predicted state."
|
| 91 |
-
),
|
| 92 |
)
|
| 93 |
|
| 94 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
import numpy as np
|
| 3 |
import tensorflow as tf
|
| 4 |
import gradio as gr
|
| 5 |
+
from fastapi import FastAPI
|
| 6 |
|
| 7 |
+
# --- CONFIG ---
|
| 8 |
+
MODEL_PATH = "best_model.h5" # or .keras
|
| 9 |
STATS_PATH = "Means & Std for Excel.json"
|
| 10 |
CLASSES = ["Top", "Mid-Top", "Mid", "Mid-Low", "Low"]
|
|
|
|
| 11 |
|
| 12 |
print("Loading model and stats...")
|
| 13 |
model = tf.keras.models.load_model(MODEL_PATH, compile=False)
|
|
|
|
| 17 |
FEATURES = list(stats.keys())
|
| 18 |
print("Feature order:", FEATURES)
|
| 19 |
|
| 20 |
+
def _z(x, m, s):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
try:
|
| 22 |
+
x = float(x)
|
| 23 |
+
except:
|
| 24 |
+
x = 0.0
|
| 25 |
+
return 0.0 if s == 0 else (x - m) / s
|
| 26 |
+
|
| 27 |
+
def _predict_core(ratios: dict):
|
| 28 |
+
missing = [f for f in FEATURES if f not in ratios]
|
| 29 |
+
zs = []
|
| 30 |
+
zdict = {}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
for f in FEATURES:
|
| 32 |
mean = stats[f]["mean"]
|
| 33 |
+
std = stats[f]["std"]
|
| 34 |
+
z = _z(ratios.get(f, 0.0), mean, std)
|
| 35 |
+
zs.append(z)
|
| 36 |
+
zdict[f] = z
|
| 37 |
+
X = np.array([zs], dtype=np.float32)
|
| 38 |
+
|
| 39 |
+
raw = model.predict(X, verbose=0)[0]
|
| 40 |
+
if len(raw) == len(CLASSES):
|
| 41 |
+
probs = np.clip(raw, 0.0, 1.0)
|
| 42 |
+
probs /= probs.sum()
|
| 43 |
+
elif len(raw) == len(CLASSES) - 1: # CORAL-style
|
| 44 |
+
sig = 1 / (1 + np.exp(-raw))
|
| 45 |
+
left = np.concatenate([[1.0], sig])
|
| 46 |
+
right = np.concatenate([sig, [0.0]])
|
| 47 |
+
probs = left - right
|
| 48 |
else:
|
| 49 |
+
raise ValueError("Unexpected output length")
|
|
|
|
|
|
|
|
|
|
| 50 |
|
| 51 |
+
pred_idx = int(np.argmax(probs))
|
| 52 |
return {
|
| 53 |
+
"input_ok": len(missing) == 0,
|
| 54 |
+
"missing": missing,
|
|
|
|
| 55 |
"probabilities": {CLASSES[i]: float(probs[i]) for i in range(len(CLASSES))},
|
| 56 |
+
"predicted_state": CLASSES[pred_idx],
|
| 57 |
}
|
| 58 |
|
| 59 |
+
def predict_from_json(payload):
|
| 60 |
+
if isinstance(payload, list) and len(payload) == 1 and isinstance(payload[0], dict):
|
| 61 |
+
payload = payload[0]
|
| 62 |
+
if not isinstance(payload, dict):
|
| 63 |
+
return {"error": "Expected a JSON object mapping feature->value."}
|
| 64 |
+
return _predict_core(payload)
|
| 65 |
|
| 66 |
+
# ---- GRADIO INTERFACE ----
|
| 67 |
iface = gr.Interface(
|
| 68 |
fn=predict_from_json,
|
| 69 |
inputs=gr.JSON(label="ratios JSON (dict of feature -> value)"),
|
| 70 |
outputs="json",
|
| 71 |
title="Static Fingerprint Model API",
|
| 72 |
+
description="POST JSON to /run/predict with your 21 ratios."
|
|
|
|
|
|
|
|
|
|
| 73 |
)
|
| 74 |
|
| 75 |
+
app = FastAPI()
|
| 76 |
+
app = gr.mount_gradio_app(app, iface, path="/")
|
| 77 |
+
|
| 78 |
+
@app.get("/health")
|
| 79 |
+
def health():
|
| 80 |
+
return {"status": "ok"}
|