COCODEDE04 commited on
Commit
cd479a0
·
verified ·
1 Parent(s): 5680bb6

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -99
app.py DELETED
@@ -1,99 +0,0 @@
1
- import json
2
- from typing import Any, Dict
3
-
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
-
21
- with open(STATS_PATH, "r") as f:
22
- stats: Dict[str, Dict[str, float]] = json.load(f)
23
-
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))