COCODEDE04 commited on
Commit
36d37a3
·
verified ·
1 Parent(s): ba7aed7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -61
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
- # ---------------- CONFIG ----------------
7
- MODEL_PATH = "best_model.h5" # or "best_model.keras" if that’s the saved file
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
- val = float(val)
35
- if sd == 0 or sd is None:
36
- return 0.0
37
- return (val - mean) / sd
38
- except Exception:
39
- return 0.0
40
-
41
-
42
- def predict_from_json(ratios):
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
- sd = stats[f]["std"]
55
- z = zscore(ratios.get(f, 0.0), mean, sd)
56
- zvec.append(z)
57
- zmap[f] = z
58
-
59
- X = np.array([zvec], dtype=np.float32)
60
- y = model.predict(X, verbose=0)
61
-
62
- # Handle output shape
63
- if y.ndim == 2 and y.shape[1] == len(CLASSES):
64
- probs = y[0]
65
- elif y.ndim == 2 and y.shape[1] == len(CLASSES) - 1:
66
- probs = coral_probs_from_logits(y)[0]
 
 
67
  else:
68
- s = np.maximum(y[0].astype(np.float64).ravel(), 0.0)
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": True,
75
- "missing": [f for f in FEATURES if f not in ratios],
76
- "z_scores": zmap,
77
  "probabilities": {CLASSES[i]: float(probs[i]) for i in range(len(CLASSES))},
78
- "predicted_state": pred,
79
  }
80
 
 
 
 
 
 
 
81
 
82
- # ----------------- GRADIO APP -----------------
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
- iface.launch()
 
 
 
 
 
 
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"}