Spaces:
Sleeping
Sleeping
Upload app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import tensorflow as tf
|
| 3 |
+
import numpy as np
|
| 4 |
+
import json
|
| 5 |
+
|
| 6 |
+
# ========== 1. Load model and stats once at startup ==========
|
| 7 |
+
MODEL_PATH = "best_model.keras"
|
| 8 |
+
STATS_PATH = "Means & Std for Excel.json"
|
| 9 |
+
|
| 10 |
+
print("Loading model and stats...")
|
| 11 |
+
model = tf.keras.models.load_model(MODEL_PATH)
|
| 12 |
+
with open(STATS_PATH, "r") as f:
|
| 13 |
+
stats = json.load(f)
|
| 14 |
+
|
| 15 |
+
# Feature order inferred from the JSON keys (keep stable)
|
| 16 |
+
FEATURES = list(stats.keys())
|
| 17 |
+
CLASSES = ["Normal", "Stressed", "Other"] # adjust if your model uses different labels
|
| 18 |
+
|
| 19 |
+
# ========== 2. Define prediction function ==========
|
| 20 |
+
def predict_ratios(input_dict):
|
| 21 |
+
"""
|
| 22 |
+
input_dict: dictionary of {indicator_name: value}
|
| 23 |
+
returns: dict with probabilities and predicted class
|
| 24 |
+
"""
|
| 25 |
+
# Build z-score vector in model’s feature order
|
| 26 |
+
zscores = []
|
| 27 |
+
zscore_dict = {}
|
| 28 |
+
|
| 29 |
+
for feat in FEATURES:
|
| 30 |
+
val = float(input_dict.get(feat, 0))
|
| 31 |
+
mean = stats[feat]["mean"]
|
| 32 |
+
std = stats[feat]["std"]
|
| 33 |
+
z = 0.0 if std == 0 else (val - mean) / std
|
| 34 |
+
zscores.append(z)
|
| 35 |
+
zscore_dict[feat] = z
|
| 36 |
+
|
| 37 |
+
X = np.array([zscores], dtype=np.float32)
|
| 38 |
+
|
| 39 |
+
# Predict
|
| 40 |
+
probs = model.predict(X, verbose=0)[0]
|
| 41 |
+
pred_idx = int(np.argmax(probs))
|
| 42 |
+
pred_state = CLASSES[pred_idx]
|
| 43 |
+
|
| 44 |
+
return {
|
| 45 |
+
"predicted_state": pred_state,
|
| 46 |
+
"probabilities": {CLASSES[i]: float(probs[i]) for i in range(len(CLASSES))},
|
| 47 |
+
"z_scores": zscore_dict
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
# ========== 3. Gradio interface ==========
|
| 51 |
+
# Build input components automatically for manual testing in the browser.
|
| 52 |
+
inputs = [gr.Number(label=f) for f in FEATURES]
|
| 53 |
+
|
| 54 |
+
iface = gr.Interface(
|
| 55 |
+
fn=lambda *vals: predict_ratios({f: v for f, v in zip(FEATURES, vals)}),
|
| 56 |
+
inputs=inputs,
|
| 57 |
+
outputs="json",
|
| 58 |
+
title="Static Fingerprint Model API",
|
| 59 |
+
description="Enter ratios below or call via POST /run/predict"
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
# Launch app
|
| 63 |
+
iface.launch()
|