gsstec commited on
Commit
e8573ca
·
verified ·
1 Parent(s): 1040a55

Deploy AEGIS Economics Stability Analysis App

Browse files
Files changed (1) hide show
  1. app.py +67 -23
app.py CHANGED
@@ -19,14 +19,22 @@ class EconRequest(BaseModel):
19
  aegis_brain = {}
20
 
21
  def download_model():
22
- """Download the model from Hugging Face if not present"""
23
  model_path = "aegis_window2_econ_v1.zip"
24
  model_url = "https://huggingface.co/gsstec/aegis_window2_econ_v1/resolve/main/aegis_window2_econ_v1.zip"
25
 
 
 
 
 
 
 
 
 
26
  if not os.path.exists(model_path):
27
  print("📥 Downloading model from Hugging Face...")
28
  try:
29
- response = requests.get(model_url, stream=True)
30
  response.raise_for_status()
31
 
32
  with open(model_path, 'wb') as f:
@@ -61,20 +69,33 @@ async def lifespan(app: FastAPI):
61
  # Load risk data for cross-referencing
62
  try:
63
  rankings_url = "https://huggingface.co/gsstec/aegis_window2_econ_v1/resolve/main/Rankings.csv"
64
- response = requests.get(rankings_url)
65
- if response.status_code == 200:
66
- aegis_brain["rankings"] = pd.read_csv(rankings_url)
67
- print("✅ Rankings data loaded from Hugging Face")
 
 
 
 
 
 
 
68
  else:
69
- raise Exception("Rankings CSV not found")
70
  except Exception as e:
71
  print(f"⚠️ Could not load rankings from HF: {e}")
72
- # Create mock rankings data
73
  aegis_brain["rankings"] = pd.DataFrame({
74
- 'Virus Name': ['COVID-19', 'H1N1', 'SARS', 'MERS', 'Ebola', 'Zika', 'Influenza A', 'RSV'],
75
- 'Original Score': [0.85, 0.65, 0.75, 0.55, 0.95, 0.45, 0.60, 0.40]
 
 
 
 
 
 
76
  })
77
- print("✅ Mock Rankings Data Loaded")
78
 
79
  aegis_brain["model_loaded"] = model_loaded
80
  yield
@@ -110,26 +131,40 @@ async def get_stability_score(data: EconRequest):
110
  stability_score = float(prediction[0][0])
111
  model_status = "trained_model"
112
  else:
113
- # Fallback to mathematical simulation
114
- econ_factor = data.econ_buffer * 0.3
115
- population_factor = min(data.population_exposure / 100000, 1.0) * 0.4
116
- virus_factor = (1 - base_score) * 0.3
117
 
 
118
  stability_score = max(0.0, min(1.0,
119
  econ_factor + (1 - population_factor) + (1 - virus_factor)
120
  ))
121
 
122
- # Add some realistic variance
123
- stability_score += np.random.normal(0, 0.05)
 
124
  stability_score = max(0.0, min(1.0, stability_score))
125
- model_status = "simulation"
 
 
 
 
 
 
 
 
 
 
126
 
127
  return {
128
  "virus": data.virus_name,
129
  "stability_score": round(stability_score, 4),
130
- "alert_level": "CRITICAL" if stability_score < 0.3 else "MONITOR" if stability_score < 0.6 else "STABLE",
131
  "model_status": model_status,
132
- "base_risk_score": round(base_score, 3)
 
 
133
  }
134
 
135
  @app.get("/health")
@@ -138,17 +173,26 @@ async def health():
138
  "status": "operational",
139
  "hardware": "T4 GPU Active" if torch.cuda.is_available() else "CPU Mode",
140
  "model_loaded": aegis_brain.get("model_loaded", False),
141
- "available_viruses": aegis_brain.get("rankings", pd.DataFrame())['Virus Name'].tolist() if aegis_brain.get("rankings") is not None else []
 
 
142
  }
143
 
144
  @app.get("/")
145
  async def root():
146
  return {
147
  "message": "AEGIS Economic Stability Analysis API",
148
- "version": "1.0.0",
149
  "model_source": "https://huggingface.co/gsstec/aegis_window2_econ_v1",
 
 
 
 
 
 
150
  "endpoints": {
151
  "predict": "POST /predict - Get stability prediction",
152
- "health": "GET /health - System status"
 
153
  }
154
  }
 
19
  aegis_brain = {}
20
 
21
  def download_model():
22
+ """Download the model from Hugging Face with authentication"""
23
  model_path = "aegis_window2_econ_v1.zip"
24
  model_url = "https://huggingface.co/gsstec/aegis_window2_econ_v1/resolve/main/aegis_window2_econ_v1.zip"
25
 
26
+ # Get HF token from environment variable
27
+ hf_token = os.getenv("HF_TOKEN")
28
+ if not hf_token:
29
+ print("⚠️ No HF_TOKEN environment variable found. Using public access only.")
30
+ return False
31
+
32
+ headers = {"Authorization": f"Bearer {hf_token}"}
33
+
34
  if not os.path.exists(model_path):
35
  print("📥 Downloading model from Hugging Face...")
36
  try:
37
+ response = requests.get(model_url, headers=headers, stream=True)
38
  response.raise_for_status()
39
 
40
  with open(model_path, 'wb') as f:
 
69
  # Load risk data for cross-referencing
70
  try:
71
  rankings_url = "https://huggingface.co/gsstec/aegis_window2_econ_v1/resolve/main/Rankings.csv"
72
+ hf_token = os.getenv("HF_TOKEN")
73
+
74
+ if hf_token:
75
+ headers = {"Authorization": f"Bearer {hf_token}"}
76
+ response = requests.get(rankings_url, headers=headers)
77
+ if response.status_code == 200:
78
+ from io import StringIO
79
+ aegis_brain["rankings"] = pd.read_csv(StringIO(response.text))
80
+ print("✅ Rankings data loaded from Hugging Face")
81
+ else:
82
+ raise Exception(f"Rankings CSV request failed: {response.status_code}")
83
  else:
84
+ raise Exception("No HF token available")
85
  except Exception as e:
86
  print(f"⚠️ Could not load rankings from HF: {e}")
87
+ # Create comprehensive mock rankings data
88
  aegis_brain["rankings"] = pd.DataFrame({
89
+ 'Virus Name': [
90
+ 'COVID-19', 'H1N1', 'SARS', 'MERS', 'Ebola', 'Zika',
91
+ 'Influenza A', 'RSV', 'Marburg', 'Lassa', 'Nipah', 'Hendra'
92
+ ],
93
+ 'Original Score': [
94
+ 0.85, 0.65, 0.75, 0.55, 0.95, 0.45,
95
+ 0.60, 0.40, 0.90, 0.70, 0.80, 0.75
96
+ ]
97
  })
98
+ print("✅ Comprehensive Mock Rankings Data Loaded")
99
 
100
  aegis_brain["model_loaded"] = model_loaded
101
  yield
 
131
  stability_score = float(prediction[0][0])
132
  model_status = "trained_model"
133
  else:
134
+ # Enhanced mathematical simulation
135
+ econ_factor = data.econ_buffer * 0.35
136
+ population_factor = min(data.population_exposure / 100000, 1.0) * 0.35
137
+ virus_factor = (1 - base_score) * 0.30
138
 
139
+ # More sophisticated calculation
140
  stability_score = max(0.0, min(1.0,
141
  econ_factor + (1 - population_factor) + (1 - virus_factor)
142
  ))
143
 
144
+ # Add realistic variance based on input parameters
145
+ variance = 0.03 + (data.population_exposure / 1000000) * 0.02
146
+ stability_score += np.random.normal(0, variance)
147
  stability_score = max(0.0, min(1.0, stability_score))
148
+ model_status = "enhanced_simulation"
149
+
150
+ # Determine alert level with more nuanced thresholds
151
+ if stability_score < 0.25:
152
+ alert_level = "CRITICAL"
153
+ elif stability_score < 0.45:
154
+ alert_level = "HIGH_RISK"
155
+ elif stability_score < 0.65:
156
+ alert_level = "MONITOR"
157
+ else:
158
+ alert_level = "STABLE"
159
 
160
  return {
161
  "virus": data.virus_name,
162
  "stability_score": round(stability_score, 4),
163
+ "alert_level": alert_level,
164
  "model_status": model_status,
165
+ "base_risk_score": round(base_score, 3),
166
+ "economic_buffer_impact": round(data.econ_buffer * 0.35, 3),
167
+ "population_risk_factor": round(min(data.population_exposure / 100000, 1.0), 3)
168
  }
169
 
170
  @app.get("/health")
 
173
  "status": "operational",
174
  "hardware": "T4 GPU Active" if torch.cuda.is_available() else "CPU Mode",
175
  "model_loaded": aegis_brain.get("model_loaded", False),
176
+ "available_viruses": aegis_brain.get("rankings", pd.DataFrame())['Virus Name'].tolist() if aegis_brain.get("rankings") is not None else [],
177
+ "total_virus_database": len(aegis_brain.get("rankings", pd.DataFrame())),
178
+ "hf_token_available": bool(os.getenv("HF_TOKEN"))
179
  }
180
 
181
  @app.get("/")
182
  async def root():
183
  return {
184
  "message": "AEGIS Economic Stability Analysis API",
185
+ "version": "1.2.0",
186
  "model_source": "https://huggingface.co/gsstec/aegis_window2_econ_v1",
187
+ "features": [
188
+ "Economic stability prediction",
189
+ "Multi-virus risk assessment",
190
+ "Population exposure modeling",
191
+ "Real-time alert classification"
192
+ ],
193
  "endpoints": {
194
  "predict": "POST /predict - Get stability prediction",
195
+ "health": "GET /health - System status",
196
+ "root": "GET / - API information"
197
  }
198
  }