COCODEDE04 commited on
Commit
b8edb00
·
verified ·
1 Parent(s): 01a19dd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +83 -61
app.py CHANGED
@@ -1,20 +1,18 @@
1
  import json
 
2
  from typing import Any, Dict
3
- from fastapi import FastAPI
4
  import numpy as np
5
  import tensorflow as tf
6
- from fastapi import FastAPI, HTTPException
 
7
 
8
- # -----------------
9
- # Config
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
- x = float(v)
33
  except Exception:
34
  return 0.0
35
- if not sd or sd == 0.0:
36
  return 0.0
37
- return (x - mean) / sd
38
 
39
- def _coral_probs_from_logits(logits_np: np.ndarray) -> np.ndarray:
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) # (N, K-1)
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
- def _predict_core(ratios: Dict[str, Any]) -> Dict[str, Any]:
51
- missing = [f for f in FEATURES if f not in ratios]
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
- raw = model.predict(X, verbose=0) # (1, K) or (1, K-1)
57
- if raw.ndim != 2:
58
- raise ValueError(f"Unexpected model output shape: {raw.shape}")
59
-
60
- if raw.shape[1] == len(CLASSES) - 1:
61
- probs = _coral_probs_from_logits(raw)[0]
62
- elif raw.shape[1] == len(CLASSES):
63
- probs = raw[0]
64
- else:
65
- raise ValueError(f"Model output width {raw.shape[1]} incompatible with {len(CLASSES)} classes")
66
 
67
- probs = np.maximum(probs, 0.0)
68
- s = probs.sum()
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
- "input_ok": len(missing) == 0,
74
- "missing": missing,
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 {"status": "ok", "features": FEATURES, "classes": CLASSES}
 
 
 
 
 
 
87
 
88
  @app.post("/predict")
89
- def predict(payload: Any):
90
- # Accept either {feature:value,...} or [ {feature:value,...} ]
91
- if isinstance(payload, list) and len(payload) == 1 and isinstance(payload[0], dict):
92
- payload = payload[0]
 
 
 
 
 
 
 
93
  if not isinstance(payload, dict):
94
- raise HTTPException(status_code=400, detail="Expected JSON object mapping feature -> value.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
 
96
- try:
97
- return _predict_core(payload)
98
- except Exception as e:
99
- raise HTTPException(status_code=500, detail=str(e))
 
 
 
 
 
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
+ }