gsstec commited on
Commit
845b313
·
verified ·
1 Parent(s): ebbc34f

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +188 -203
app.py CHANGED
@@ -8,44 +8,44 @@ from contextlib import asynccontextmanager
8
  import os
9
  import requests
10
  from pathlib import Path
 
11
 
12
- # Define the data schema for Window 7 Conductor requests (Virus Analysis)
13
  class EconRequest(BaseModel):
14
  virus_name: str
15
  econ_buffer: float # Value from 0.1 to 1.0 (IMF-WEO)
16
  population_exposure: float # Value from 100 to 100,000 (WorldPop)
17
 
18
- # Define the data schema for Window 4 Conductor Economic Analysis
19
  class ConductorEconRequest(BaseModel):
20
  conductor_prompt: str
21
  year: int
22
- stress_factors: list = []
23
  singularity_detected: bool = False
24
  timestamp: int
25
  market_shock_index: float = 0.0
26
  impact_classification: str = "Unknown"
27
- regional_vulnerabilities: dict = {}
28
- contagion_metrics: dict = {}
29
- tech_analysis_id: str = None
30
 
31
- # Global container for the model
32
  aegis_brain = {}
33
 
34
  def download_model():
35
- """Download the model from Hugging Face with authentication"""
36
  model_path = "aegis_window2_econ_v1.zip"
37
  model_url = "https://huggingface.co/gsstec/aegis_window2_econ_v1/resolve/main/aegis_window2_econ_v1.zip"
38
 
39
- # Get HF token from environment variable
40
  hf_token = os.getenv("HF_TOKEN")
41
  if not hf_token:
42
- print("⚠️ No HF_TOKEN environment variable found. Using public access only.")
43
- return False
44
 
45
  headers = {"Authorization": f"Bearer {hf_token}"}
46
 
47
  if not os.path.exists(model_path):
48
- print("📥 Downloading model from Hugging Face...")
49
  try:
50
  response = requests.get(model_url, headers=headers, stream=True)
51
  response.raise_for_status()
@@ -53,115 +53,104 @@ def download_model():
53
  with open(model_path, 'wb') as f:
54
  for chunk in response.iter_content(chunk_size=8192):
55
  f.write(chunk)
56
- print("✅ Model downloaded successfully!")
57
  return True
58
  except Exception as e:
59
- print(f"❌ Failed to download model: {e}")
60
- return False
61
  else:
62
- print("✅ Model file already exists")
63
  return True
64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
  @asynccontextmanager
66
  async def lifespan(app: FastAPI):
67
- # Download and load model on startup
68
- model_loaded = False
 
69
 
70
- if download_model():
71
- try:
72
- model_path = "aegis_window2_econ_v1.zip"
73
- regressor = TabNetRegressor()
74
- regressor.load_model(model_path)
75
- aegis_brain["model"] = regressor
76
- model_loaded = True
77
- print("✅ TabNet Model Loaded Successfully!")
78
- except Exception as e:
79
- print(f"⚠️ Failed to load TabNet model: {e}")
80
- print("🔄 Falling back to simulation mode...")
81
 
82
- # Load risk data for cross-referencing
83
  try:
84
- rankings_url = "https://huggingface.co/gsstec/aegis_window2_econ_v1/resolve/main/Rankings.csv"
85
- hf_token = os.getenv("HF_TOKEN")
86
-
87
- if hf_token:
88
- headers = {"Authorization": f"Bearer {hf_token}"}
89
- response = requests.get(rankings_url, headers=headers)
90
- if response.status_code == 200:
91
- from io import StringIO
92
- aegis_brain["rankings"] = pd.read_csv(StringIO(response.text))
93
- print("✅ Rankings data loaded from Hugging Face")
94
- else:
95
- raise Exception(f"Rankings CSV request failed: {response.status_code}")
96
- else:
97
- raise Exception("No HF token available")
98
  except Exception as e:
99
- print(f"⚠️ Could not load rankings from HF: {e}")
100
- # Create comprehensive mock rankings data
101
- aegis_brain["rankings"] = pd.DataFrame({
102
- 'Virus Name': [
103
- 'COVID-19', 'H1N1', 'SARS', 'MERS', 'Ebola', 'Zika',
104
- 'Influenza A', 'RSV', 'Marburg', 'Lassa', 'Nipah', 'Hendra'
105
- ],
106
- 'Original Score': [
107
- 0.85, 0.65, 0.75, 0.55, 0.95, 0.45,
108
- 0.60, 0.40, 0.90, 0.70, 0.80, 0.75
109
- ]
110
- })
111
- print("✅ Comprehensive Mock Rankings Data Loaded")
112
-
113
- aegis_brain["model_loaded"] = model_loaded
114
  yield
 
 
115
  aegis_brain.clear()
 
116
 
117
- app = FastAPI(lifespan=lifespan, title="Aegis Econ API")
 
 
 
 
 
118
 
119
  @app.post("/predict")
120
  async def get_stability_score(data: EconRequest):
121
- """Original virus-based economic stability prediction"""
122
  model = aegis_brain.get("model")
123
  df_rankings = aegis_brain.get("rankings")
124
- model_loaded = aegis_brain.get("model_loaded", False)
 
 
 
125
 
126
  if df_rankings is None:
127
- raise HTTPException(status_code=500, detail="Rankings data not initialized.")
128
 
129
- # 1. Fetch risk score from Rankings.csv
130
  virus_row = df_rankings[df_rankings['Virus Name'] == data.virus_name]
131
  if virus_row.empty:
132
- # If virus not found, use a default moderate risk score
133
- base_score = 0.7
134
- print(f"⚠️ Virus '{data.virus_name}' not found in database. Using default risk score.")
135
- else:
136
- base_score = virus_row.iloc[0]['Original Score']
137
 
 
138
  risk_impact = base_score * 0.7
139
 
140
- # 2. Predict Continental Stability
141
- if model_loaded and model is not None:
142
- # Use actual TabNet model
143
- input_vector = np.array([[base_score, risk_impact, data.econ_buffer, data.population_exposure]])
144
- prediction = model.predict(input_vector)
145
- stability_score = float(prediction[0][0])
146
- model_status = "trained_model"
147
- else:
148
- # Enhanced mathematical simulation
149
- econ_factor = data.econ_buffer * 0.35
150
- population_factor = min(data.population_exposure / 100000, 1.0) * 0.35
151
- virus_factor = (1 - base_score) * 0.30
152
-
153
- # More sophisticated calculation
154
- stability_score = max(0.0, min(1.0,
155
- econ_factor + (1 - population_factor) + (1 - virus_factor)
156
- ))
157
-
158
- # Add realistic variance based on input parameters
159
- variance = 0.03 + (data.population_exposure / 1000000) * 0.02
160
- stability_score += np.random.normal(0, variance)
161
- stability_score = max(0.0, min(1.0, stability_score))
162
- model_status = "enhanced_simulation"
163
-
164
- # Determine alert level with more nuanced thresholds
165
  if stability_score < 0.25:
166
  alert_level = "CRITICAL"
167
  elif stability_score < 0.45:
@@ -175,20 +164,27 @@ async def get_stability_score(data: EconRequest):
175
  "virus": data.virus_name,
176
  "stability_score": round(stability_score, 4),
177
  "alert_level": alert_level,
178
- "model_status": model_status,
179
  "base_risk_score": round(base_score, 3),
180
  "economic_buffer_impact": round(data.econ_buffer * 0.35, 3),
181
- "population_risk_factor": round(min(data.population_exposure / 100000, 1.0), 3)
 
182
  }
183
 
184
  @app.post("/conductor-predict")
185
  async def get_conductor_economic_analysis(data: ConductorEconRequest):
186
- """New conductor-based economic analysis for Window 4 → War → Disease pipeline"""
187
  model = aegis_brain.get("model")
188
  df_rankings = aegis_brain.get("rankings")
189
- model_loaded = aegis_brain.get("model_loaded", False)
190
 
191
- # Extract economic factors from conductor data
 
 
 
 
 
 
 
192
  base_risk_score = data.market_shock_index if data.market_shock_index > 0 else 0.5
193
 
194
  # Calculate stress factor impact
@@ -196,149 +192,131 @@ async def get_conductor_economic_analysis(data: ConductorEconRequest):
196
  if data.stress_factors:
197
  stress_impact = sum(factor.get('impact_level', 0.5) for factor in data.stress_factors) / len(data.stress_factors)
198
 
199
- # Regional vulnerability assessment
200
- regional_risk = 0.5
201
  if data.regional_vulnerabilities:
202
- regional_risk = sum(data.regional_vulnerabilities.values()) / len(data.regional_vulnerabilities)
203
 
204
- # Contagion metrics assessment
205
- contagion_risk = 0.5
206
  if data.contagion_metrics:
207
- spread_rate = data.contagion_metrics.get('spread_rate', 0.5)
208
- containment_difficulty = data.contagion_metrics.get('containment_difficulty', 0.5)
209
- contagion_risk = (spread_rate + containment_difficulty) / 2
210
-
211
- # Singularity detection impact
212
- singularity_multiplier = 1.5 if data.singularity_detected else 1.0
213
-
214
- # Calculate comprehensive economic stability
215
- if model_loaded and model is not None:
216
- # Use actual TabNet model with conductor data
217
- input_vector = np.array([[base_risk_score, stress_impact, regional_risk, contagion_risk]])
218
- prediction = model.predict(input_vector)
219
- stability_score = float(prediction[0][0]) * singularity_multiplier
220
- model_status = "trained_model_conductor"
221
- else:
222
- # Enhanced mathematical simulation for conductor data
223
- economic_stability = (
224
- (1 - base_risk_score) * 0.30 + # Market shock impact
225
- (1 - stress_impact) * 0.25 + # Stress factors
226
- (1 - regional_risk) * 0.25 + # Regional vulnerabilities
227
- (1 - contagion_risk) * 0.20 # Contagion metrics
228
- ) * singularity_multiplier
229
-
230
- # Year-based adjustment (future years have more uncertainty)
231
- year_factor = max(0.8, 1.0 - (data.year - 2024) * 0.02)
232
- stability_score = economic_stability * year_factor
233
-
234
- # Add realistic variance
235
- variance = 0.05 + (stress_impact * 0.03)
236
- stability_score += np.random.normal(0, variance)
237
- stability_score = max(0.0, min(1.0, stability_score))
238
- model_status = "enhanced_simulation_conductor"
239
-
240
- # Calculate market cap estimate (in billions)
241
- market_cap_estimate = max(50.0, 500.0 * stability_score * (2.0 - base_risk_score))
242
-
243
- # Generate key metrics
244
  key_metrics = [
245
  {
246
  "name": "Market Shock Index",
247
- "value": base_risk_score,
248
- "change": -15.2 if data.singularity_detected else -5.1,
249
  "unit": "index",
250
- "risk_level": "CRITICAL" if base_risk_score > 0.8 else "HIGH" if base_risk_score > 0.6 else "MEDIUM",
251
  "description": "Overall market disruption indicator"
252
  },
253
  {
254
- "name": "Regional Stability",
255
- "value": 1 - regional_risk,
256
- "change": -8.3 if regional_risk > 0.7 else 2.1,
257
  "unit": "stability",
258
- "risk_level": "HIGH" if regional_risk > 0.7 else "MEDIUM" if regional_risk > 0.5 else "LOW",
259
- "description": "Cross-regional economic stability"
260
  },
261
  {
262
- "name": "Contagion Risk",
263
- "value": contagion_risk,
264
- "change": 12.5 if contagion_risk > 0.6 else -3.2,
265
- "unit": "risk",
266
- "risk_level": "CRITICAL" if contagion_risk > 0.8 else "HIGH" if contagion_risk > 0.6 else "MEDIUM",
267
- "description": "Economic contagion spread potential"
268
  }
269
  ]
270
 
271
- # Determine alert level
272
- if stability_score < 0.25:
273
- alert_level = "CRITICAL"
274
  status = f"CRITICAL ECONOMIC INSTABILITY DETECTED ({data.year})"
275
- elif stability_score < 0.45:
276
- alert_level = "HIGH_RISK"
277
  status = f"HIGH ECONOMIC RISK IDENTIFIED ({data.year})"
278
- elif stability_score < 0.65:
279
- alert_level = "MONITOR"
280
- status = f"ECONOMIC MONITORING REQUIRED ({data.year})"
281
  else:
282
- alert_level = "STABLE"
283
  status = f"ECONOMIC STABILITY MAINTAINED ({data.year})"
284
 
285
- if data.singularity_detected:
286
- status = f"SINGULARITY EVENT - {status}"
287
-
288
- # Generate BRICS+ impact analysis
289
- brics_impact = {
290
- "inflation_pressure": min(15.0, base_risk_score * 20.0),
291
- "market_disruption": f"{'Severe' if base_risk_score > 0.7 else 'Moderate' if base_risk_score > 0.4 else 'Limited'} disruption expected across BRICS+ economies",
292
- "competitive_dynamics": f"{'Accelerated' if data.singularity_detected else 'Standard'} competitive realignment in emerging markets"
293
- }
294
-
295
- # Generate strategic recommendations
296
- recommendations = [
297
- f"Implement {'emergency' if alert_level == 'CRITICAL' else 'enhanced'} economic monitoring protocols",
298
- f"Activate {'Tier 1' if stability_score < 0.4 else 'Tier 2'} risk mitigation strategies",
299
- f"Coordinate with {'all' if data.singularity_detected else 'key'} international economic partners"
300
- ]
301
-
302
- if data.stress_factors:
303
- recommendations.append(f"Address {len(data.stress_factors)} identified stress factors immediately")
304
 
305
  return {
306
  "status": status,
307
- "market_analysis": f"Comprehensive economic analysis for {data.year} indicates {alert_level.lower()} conditions. Conductor analysis reveals {data.impact_classification.lower()} implications with {len(data.stress_factors)} stress factors identified. {'Singularity event detected - ' if data.singularity_detected else ''}Economic stability score: {stability_score:.3f}",
308
  "key_metrics": key_metrics,
309
  "market_cap_estimate": round(market_cap_estimate, 1),
310
- "operational_risk": f"{'Extreme' if alert_level == 'CRITICAL' else 'High' if alert_level == 'HIGH_RISK' else 'Moderate'} operational risk across {len(data.regional_vulnerabilities) if data.regional_vulnerabilities else 'multiple'} regions",
311
- "sovereign_advantage": f"{'Minimal' if stability_score < 0.3 else 'Limited' if stability_score < 0.6 else 'Moderate'} sovereign economic advantage maintained",
312
- "recommendations": recommendations,
313
- "brics_impact": brics_impact,
314
- "processing_time": 1200 + int(len(data.stress_factors) * 150),
315
- "confidence_score": max(0.6, min(0.95, stability_score + 0.1)),
316
- "conductor_metadata": {
317
- "tech_analysis_id": data.tech_analysis_id,
318
- "year": data.year,
319
- "singularity_detected": data.singularity_detected,
320
- "stress_factors_count": len(data.stress_factors),
321
- "regional_coverage": len(data.regional_vulnerabilities) if data.regional_vulnerabilities else 0,
322
- "model_status": model_status
323
- }
 
 
 
324
  }
325
 
326
  @app.get("/health")
327
  async def health():
 
 
 
 
 
 
 
 
 
 
328
  return {
329
- "status": "operational",
330
  "hardware": "T4 GPU Active" if torch.cuda.is_available() else "CPU Mode",
331
- "model_loaded": aegis_brain.get("model_loaded", False),
332
- "available_viruses": aegis_brain.get("rankings", pd.DataFrame())['Virus Name'].tolist() if aegis_brain.get("rankings") is not None else [],
 
333
  "total_virus_database": len(aegis_brain.get("rankings", pd.DataFrame())),
334
- "hf_token_available": bool(os.getenv("HF_TOKEN"))
 
 
 
335
  }
336
 
337
  @app.get("/")
338
  async def root():
 
339
  return {
340
  "message": "AEGIS Economic Stability Analysis API",
341
  "version": "2.0.0",
 
342
  "model_source": "https://huggingface.co/gsstec/aegis_window2_econ_v1",
343
  "features": [
344
  "Economic stability prediction",
@@ -354,5 +332,12 @@ async def root():
354
  "health": "GET /health - System status",
355
  "root": "GET / - API information"
356
  },
357
- "data_flow": "Conductor → Economic → War → Disease Analysis Pipeline"
 
 
 
 
 
 
 
358
  }
 
8
  import os
9
  import requests
10
  from pathlib import Path
11
+ from typing import List, Dict, Any
12
 
13
+ # Define the data schema for virus-based requests (legacy)
14
  class EconRequest(BaseModel):
15
  virus_name: str
16
  econ_buffer: float # Value from 0.1 to 1.0 (IMF-WEO)
17
  population_exposure: float # Value from 100 to 100,000 (WorldPop)
18
 
19
+ # Define the data schema for conductor-based requests (v2.0.0)
20
  class ConductorEconRequest(BaseModel):
21
  conductor_prompt: str
22
  year: int
23
+ stress_factors: List[Dict[str, Any]] = []
24
  singularity_detected: bool = False
25
  timestamp: int
26
  market_shock_index: float = 0.0
27
  impact_classification: str = "Unknown"
28
+ regional_vulnerabilities: Dict[str, float] = {}
29
+ contagion_metrics: Dict[str, float] = {}
30
+ tech_analysis_id: str = ""
31
 
32
+ # Global container for the model - PRODUCTION MODE (no fallbacks)
33
  aegis_brain = {}
34
 
35
  def download_model():
36
+ """Download the model from Hugging Face with authentication - REQUIRED"""
37
  model_path = "aegis_window2_econ_v1.zip"
38
  model_url = "https://huggingface.co/gsstec/aegis_window2_econ_v1/resolve/main/aegis_window2_econ_v1.zip"
39
 
40
+ # Get HF token from environment variable - REQUIRED
41
  hf_token = os.getenv("HF_TOKEN")
42
  if not hf_token:
43
+ raise Exception(" PRODUCTION ERROR: HF_TOKEN environment variable is required for model access")
 
44
 
45
  headers = {"Authorization": f"Bearer {hf_token}"}
46
 
47
  if not os.path.exists(model_path):
48
+ print("📥 Downloading production model from Hugging Face...")
49
  try:
50
  response = requests.get(model_url, headers=headers, stream=True)
51
  response.raise_for_status()
 
53
  with open(model_path, 'wb') as f:
54
  for chunk in response.iter_content(chunk_size=8192):
55
  f.write(chunk)
56
+ print("✅ Production model downloaded successfully!")
57
  return True
58
  except Exception as e:
59
+ raise Exception(f"❌ PRODUCTION ERROR: Failed to download model: {e}")
 
60
  else:
61
+ print("✅ Production model file already exists")
62
  return True
63
 
64
+ def load_rankings_data():
65
+ """Load rankings data from HuggingFace - REQUIRED"""
66
+ rankings_url = "https://huggingface.co/gsstec/aegis_window2_econ_v1/resolve/main/Rankings.csv"
67
+ hf_token = os.getenv("HF_TOKEN")
68
+
69
+ if not hf_token:
70
+ raise Exception("❌ PRODUCTION ERROR: HF_TOKEN required for rankings data access")
71
+
72
+ headers = {"Authorization": f"Bearer {hf_token}"}
73
+ response = requests.get(rankings_url, headers=headers)
74
+
75
+ if response.status_code != 200:
76
+ raise Exception(f"❌ PRODUCTION ERROR: Failed to load rankings data: {response.status_code}")
77
+
78
+ from io import StringIO
79
+ rankings_df = pd.read_csv(StringIO(response.text))
80
+ print("✅ Production rankings data loaded from Hugging Face")
81
+ return rankings_df
82
+
83
  @asynccontextmanager
84
  async def lifespan(app: FastAPI):
85
+ # PRODUCTION MODE: Require real model and data - NO FALLBACKS
86
+ print("🚀 Starting AEGIS Economic Analysis API v2.0.0 - PRODUCTION MODE")
87
+ print("⚠️ PRODUCTION MODE: No fallbacks, simulations, or mock data allowed")
88
 
89
+ # Download and load model - REQUIRED
90
+ if not download_model():
91
+ raise Exception("❌ PRODUCTION ERROR: Model download failed")
 
 
 
 
 
 
 
 
92
 
 
93
  try:
94
+ model_path = "aegis_window2_econ_v1.zip"
95
+ regressor = TabNetRegressor()
96
+ regressor.load_model(model_path)
97
+ aegis_brain["model"] = regressor
98
+ print("✅ Production TabNet Model Loaded Successfully!")
 
 
 
 
 
 
 
 
 
99
  except Exception as e:
100
+ raise Exception(f" PRODUCTION ERROR: Failed to load TabNet model: {e}")
101
+
102
+ # Load rankings data - REQUIRED
103
+ try:
104
+ aegis_brain["rankings"] = load_rankings_data()
105
+ except Exception as e:
106
+ raise Exception(f"❌ PRODUCTION ERROR: Failed to load rankings data: {e}")
107
+
108
+ aegis_brain["model_loaded"] = True
109
+ print("🎯 PRODUCTION MODE: All systems operational with real model and data")
110
+
 
 
 
 
111
  yield
112
+
113
+ # Cleanup
114
  aegis_brain.clear()
115
+ print("🔄 PRODUCTION MODE: Cleanup completed")
116
 
117
+ app = FastAPI(
118
+ lifespan=lifespan,
119
+ title="AEGIS Economic Analysis API v2.0.0 - PRODUCTION",
120
+ description="Production-grade economic analysis with real TabNet model - No fallbacks or simulations",
121
+ version="2.0.0"
122
+ )
123
 
124
  @app.post("/predict")
125
  async def get_stability_score(data: EconRequest):
126
+ """Legacy virus-based economic stability prediction - PRODUCTION MODE ONLY"""
127
  model = aegis_brain.get("model")
128
  df_rankings = aegis_brain.get("rankings")
129
+
130
+ # PRODUCTION MODE: Require model and data
131
+ if not model:
132
+ raise HTTPException(status_code=503, detail="PRODUCTION ERROR: TabNet model not loaded")
133
 
134
  if df_rankings is None:
135
+ raise HTTPException(status_code=503, detail="PRODUCTION ERROR: Rankings data not initialized")
136
 
137
+ # Get risk score from Rankings.csv
138
  virus_row = df_rankings[df_rankings['Virus Name'] == data.virus_name]
139
  if virus_row.empty:
140
+ raise HTTPException(
141
+ status_code=404,
142
+ detail=f"PRODUCTION ERROR: Virus '{data.virus_name}' not found in production database"
143
+ )
 
144
 
145
+ base_score = virus_row.iloc[0]['Original Score']
146
  risk_impact = base_score * 0.7
147
 
148
+ # Use ONLY the real TabNet model - NO SIMULATIONS
149
+ input_vector = np.array([[base_score, risk_impact, data.econ_buffer, data.population_exposure]])
150
+ prediction = model.predict(input_vector)
151
+ stability_score = float(prediction[0][0])
152
+
153
+ # Determine alert level
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
154
  if stability_score < 0.25:
155
  alert_level = "CRITICAL"
156
  elif stability_score < 0.45:
 
164
  "virus": data.virus_name,
165
  "stability_score": round(stability_score, 4),
166
  "alert_level": alert_level,
167
+ "model_status": "production_tabnet_model",
168
  "base_risk_score": round(base_score, 3),
169
  "economic_buffer_impact": round(data.econ_buffer * 0.35, 3),
170
+ "population_risk_factor": round(min(data.population_exposure / 100000, 1.0), 3),
171
+ "production_mode": True
172
  }
173
 
174
  @app.post("/conductor-predict")
175
  async def get_conductor_economic_analysis(data: ConductorEconRequest):
176
+ """Production conductor-based economic analysis for Window 4 → War → Disease pipeline"""
177
  model = aegis_brain.get("model")
178
  df_rankings = aegis_brain.get("rankings")
 
179
 
180
+ # PRODUCTION MODE: Require model and data
181
+ if not model:
182
+ raise HTTPException(status_code=503, detail="PRODUCTION ERROR: TabNet model not loaded")
183
+
184
+ if df_rankings is None:
185
+ raise HTTPException(status_code=503, detail="PRODUCTION ERROR: Rankings data not initialized")
186
+
187
+ # Extract base risk from conductor data
188
  base_risk_score = data.market_shock_index if data.market_shock_index > 0 else 0.5
189
 
190
  # Calculate stress factor impact
 
192
  if data.stress_factors:
193
  stress_impact = sum(factor.get('impact_level', 0.5) for factor in data.stress_factors) / len(data.stress_factors)
194
 
195
+ # Calculate regional vulnerability impact
196
+ regional_impact = 0.0
197
  if data.regional_vulnerabilities:
198
+ regional_impact = sum(data.regional_vulnerabilities.values()) / len(data.regional_vulnerabilities)
199
 
200
+ # Calculate contagion impact
201
+ contagion_impact = 0.0
202
  if data.contagion_metrics:
203
+ contagion_impact = sum(data.contagion_metrics.values()) / len(data.contagion_metrics)
204
+
205
+ # Use ONLY the real TabNet model - NO SIMULATIONS
206
+ input_vector = np.array([[
207
+ base_risk_score,
208
+ stress_impact,
209
+ regional_impact,
210
+ contagion_impact
211
+ ]])
212
+
213
+ prediction = model.predict(input_vector)
214
+ stability_score = float(prediction[0][0])
215
+
216
+ # Calculate market cap estimate (in billions) based on model prediction
217
+ market_cap_estimate = max(10, min(500, (1 - stability_score) * 200 + 50))
218
+
219
+ # Generate key metrics based on model prediction
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
220
  key_metrics = [
221
  {
222
  "name": "Market Shock Index",
223
+ "value": data.market_shock_index,
224
+ "change": -5.1 if stability_score < 0.5 else 2.3,
225
  "unit": "index",
226
+ "risk_level": "HIGH" if data.market_shock_index > 0.7 else "MEDIUM",
227
  "description": "Overall market disruption indicator"
228
  },
229
  {
230
+ "name": "Economic Stability",
231
+ "value": stability_score,
232
+ "change": -3.2 if stability_score < 0.4 else 1.8,
233
  "unit": "stability",
234
+ "risk_level": "CRITICAL" if stability_score < 0.3 else "MEDIUM",
235
+ "description": "TabNet model economic stability prediction"
236
  },
237
  {
238
+ "name": "Stress Factor Impact",
239
+ "value": stress_impact,
240
+ "change": -2.1 if stress_impact > 0.6 else 0.5,
241
+ "unit": "impact",
242
+ "risk_level": "HIGH" if stress_impact > 0.7 else "LOW",
243
+ "description": "Aggregated stress factor analysis"
244
  }
245
  ]
246
 
247
+ # Determine status based on model prediction
248
+ if stability_score < 0.2:
 
249
  status = f"CRITICAL ECONOMIC INSTABILITY DETECTED ({data.year})"
250
+ elif stability_score < 0.4:
 
251
  status = f"HIGH ECONOMIC RISK IDENTIFIED ({data.year})"
252
+ elif stability_score < 0.6:
253
+ status = f"MODERATE ECONOMIC CONCERNS ({data.year})"
 
254
  else:
 
255
  status = f"ECONOMIC STABILITY MAINTAINED ({data.year})"
256
 
257
+ # Generate market analysis based on model prediction
258
+ severity = "critical" if stability_score < 0.3 else "moderate" if stability_score < 0.6 else "manageable"
259
+ market_analysis = f"Production TabNet model analysis for {data.year} indicates {severity} economic conditions. " \
260
+ f"Conductor analysis reveals {data.impact_classification.lower()} implications with " \
261
+ f"{len(data.stress_factors)} stress factors identified. " \
262
+ f"Economic stability score: {stability_score:.3f}"
 
 
 
 
 
 
 
 
 
 
 
 
 
263
 
264
  return {
265
  "status": status,
266
+ "market_analysis": market_analysis,
267
  "key_metrics": key_metrics,
268
  "market_cap_estimate": round(market_cap_estimate, 1),
269
+ "operational_risk": f"Model-predicted risk level: {severity.upper()}",
270
+ "sovereign_advantage": f"Stability score indicates {('limited' if stability_score < 0.5 else 'moderate')} sovereign resilience",
271
+ "recommendations": [
272
+ f"Monitor economic indicators closely given {severity} stability prediction",
273
+ f"Implement risk mitigation strategies for {data.impact_classification.lower()}",
274
+ "Enhance economic monitoring systems based on model predictions"
275
+ ],
276
+ "brics_impact": {
277
+ "inflation_pressure": round(max(0, (1 - stability_score) * 10), 1),
278
+ "market_disruption": f"Model predicts {severity} market disruption potential",
279
+ "competitive_dynamics": f"Economic competitiveness {'severely impacted' if stability_score < 0.3 else 'moderately affected'}"
280
+ },
281
+ "processing_time": 1500, # Model inference time
282
+ "confidence_score": round(min(0.95, max(0.6, stability_score + 0.2)), 2),
283
+ "model_status": "production_tabnet_conductor",
284
+ "production_mode": True,
285
+ "model_prediction": round(stability_score, 4)
286
  }
287
 
288
  @app.get("/health")
289
  async def health():
290
+ """Production health check - requires real model and data"""
291
+ model_loaded = aegis_brain.get("model_loaded", False)
292
+ rankings_available = aegis_brain.get("rankings") is not None
293
+
294
+ if not model_loaded:
295
+ raise HTTPException(status_code=503, detail="PRODUCTION ERROR: TabNet model not loaded")
296
+
297
+ if not rankings_available:
298
+ raise HTTPException(status_code=503, detail="PRODUCTION ERROR: Rankings data not available")
299
+
300
  return {
301
+ "status": "production_operational",
302
  "hardware": "T4 GPU Active" if torch.cuda.is_available() else "CPU Mode",
303
+ "model_loaded": True,
304
+ "model_type": "TabNet Production Model",
305
+ "available_viruses": aegis_brain.get("rankings", pd.DataFrame())['Virus Name'].tolist(),
306
  "total_virus_database": len(aegis_brain.get("rankings", pd.DataFrame())),
307
+ "hf_token_available": bool(os.getenv("HF_TOKEN")),
308
+ "production_mode": True,
309
+ "fallbacks_disabled": True,
310
+ "simulations_disabled": True
311
  }
312
 
313
  @app.get("/")
314
  async def root():
315
+ """Production API information"""
316
  return {
317
  "message": "AEGIS Economic Stability Analysis API",
318
  "version": "2.0.0",
319
+ "mode": "PRODUCTION",
320
  "model_source": "https://huggingface.co/gsstec/aegis_window2_econ_v1",
321
  "features": [
322
  "Economic stability prediction",
 
332
  "health": "GET /health - System status",
333
  "root": "GET / - API information"
334
  },
335
+ "data_flow": "Conductor → Economic → War → Disease Analysis Pipeline",
336
+ "production_features": {
337
+ "real_tabnet_model": True,
338
+ "no_fallbacks": True,
339
+ "no_simulations": True,
340
+ "no_mock_data": True,
341
+ "requires_hf_token": True
342
+ }
343
  }