COCODEDE04 commited on
Commit
094fd0a
·
verified ·
1 Parent(s): 8c45442

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +104 -0
app.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import numpy as np
4
+ import tensorflow as tf
5
+ import gradio as gr
6
+
7
+ # ---------- CONFIG ----------
8
+ MODEL_PATH = "best_model.h5" # or best_model.keras
9
+ STATS_PATH = "Means & Std for Excel.json" # must match filename in repo
10
+ CLASSES = ["Top", "Mid-Top", "Mid", "Mid-Low", "Low"]
11
+ # ----------------------------
12
+
13
+ print("Loading model and stats...")
14
+ model = tf.keras.models.load_model(MODEL_PATH, compile=False)
15
+
16
+ with open(STATS_PATH, "r") as f:
17
+ stats = json.load(f)
18
+
19
+ FEATURES = list(stats.keys())
20
+ print("Feature order:", FEATURES)
21
+
22
+
23
+ # ---------- Utility helpers ----------
24
+ def _zscore(val: float, mean: float, sd: float) -> float:
25
+ """Compute safe z-score (handles NaNs and zeros)."""
26
+ try:
27
+ v = float(val)
28
+ except (TypeError, ValueError):
29
+ v = 0.0
30
+ return 0.0 if (sd is None or sd == 0) else (v - mean) / sd
31
+
32
+
33
+ def coral_probs_from_logits(logits_np):
34
+ """Convert (N, K-1) CORAL logits → (N, K) probabilities."""
35
+ logits = tf.convert_to_tensor(logits_np, dtype=tf.float32)
36
+ sig = tf.math.sigmoid(logits)
37
+ left = tf.concat([tf.ones_like(sig[:, :1]), sig], axis=1)
38
+ right = tf.concat([sig, tf.zeros_like(sig[:, :1])], axis=1)
39
+ probs = tf.clip_by_value(left - right, 1e-12, 1.0)
40
+ return probs.numpy()
41
+
42
+
43
+ def predict_core(ratios: dict):
44
+ """
45
+ ratios: dict mapping feature name -> raw numeric ratio.
46
+ Returns dict with predicted_state, probabilities, z_scores, missing.
47
+ """
48
+ missing = [f for f in FEATURES if f not in ratios]
49
+
50
+ # Build z-score vector in same feature order
51
+ zscores, zscores_dict = [], {}
52
+ for f in FEATURES:
53
+ mean = stats[f]["mean"]
54
+ sd = stats[f]["std"]
55
+ val = ratios.get(f, 0.0)
56
+ z = _zscore(val, mean, sd)
57
+ zscores.append(z)
58
+ zscores_dict[f] = z
59
+
60
+ X = np.array([zscores], dtype=np.float32)
61
+ logits = model.predict(X, verbose=0)
62
+ probs = coral_probs_from_logits(logits)[0] # now 5 probabilities
63
+
64
+ pred_idx = int(np.argmax(probs))
65
+ pred_state = CLASSES[pred_idx]
66
+
67
+ return {
68
+ "input_ok": len(missing) == 0,
69
+ "missing": missing,
70
+ "z_scores": zscores_dict,
71
+ "probabilities": {CLASSES[i]: float(probs[i]) for i in range(len(CLASSES))},
72
+ "predicted_state": pred_state,
73
+ }
74
+
75
+
76
+ # ---------- Gradio interface ----------
77
+ def predict_from_json(payload, x_api_key: str = ""):
78
+ """
79
+ Accepts either:
80
+ {feature: value}
81
+ or [{feature: value}]
82
+ """
83
+ if isinstance(payload, list) and len(payload) == 1 and isinstance(payload[0], dict):
84
+ payload = payload[0]
85
+
86
+ if not isinstance(payload, dict):
87
+ return {"error": "Invalid payload: expected a JSON object mapping feature -> value."}
88
+
89
+ return predict_core(payload)
90
+
91
+
92
+ iface = gr.Interface(
93
+ fn=predict_from_json,
94
+ inputs=gr.JSON(label="ratios JSON (dict of feature -> value)"),
95
+ outputs="json",
96
+ title="Static Fingerprint Model API",
97
+ description=(
98
+ "POST JSON to /run/predict with a dict of your 21 ratios. "
99
+ "Server normalises using saved means/stds and returns probabilities + predicted state."
100
+ ),
101
+ )
102
+
103
+ if __name__ == "__main__":
104
+ iface.launch()