arcalab commited on
Commit
fd9b733
Β·
verified Β·
1 Parent(s): c7bf23d

Upload folder using huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +670 -359
app.py CHANGED
@@ -1,3 +1,4 @@
 
1
  import os
2
  from datetime import datetime
3
  from typing import Any, Dict, List, Optional, Tuple
@@ -6,15 +7,24 @@ import pandas as pd
6
  import requests
7
  import streamlit as st
8
 
9
- st.set_page_config(
10
- page_title="Simulation & Prescriptive Analysis Engine",
11
- layout="wide",
12
- initial_sidebar_state="collapsed",
13
- )
14
 
15
  COMPLEXITY_FACTORS = {"Low": 0.85, "Medium": 1.0, "High": 1.25, "Critical": 1.55}
16
  TECH_RISK_FACTORS = {"Low": 0.8, "Medium": 1.0, "High": 1.3}
17
  CLIENT_TIER_FACTORS = {"SMB": 0.95, "Mid-Market": 1.0, "Enterprise": 1.08}
 
 
 
 
 
 
 
 
 
 
 
 
 
18
 
19
 
20
  def clamp(value: float, min_value: float, max_value: float) -> float:
@@ -23,9 +33,9 @@ def clamp(value: float, min_value: float, max_value: float) -> float:
23
 
24
  def safe_get_api_key() -> Optional[str]:
25
  try:
26
- secret_key = st.secrets.get("GEMINI_API_KEY")
27
- if secret_key:
28
- return secret_key
29
  except Exception:
30
  pass
31
  env_key = os.getenv("GEMINI_API_KEY")
@@ -35,7 +45,7 @@ def safe_get_api_key() -> Optional[str]:
35
  @st.cache_data
36
  def load_historical_data() -> pd.DataFrame:
37
  df = pd.read_csv("data/historical_projects.csv")
38
- numeric_cols = [
39
  "budget",
40
  "team_size",
41
  "timeline_weeks",
@@ -44,54 +54,48 @@ def load_historical_data() -> pd.DataFrame:
44
  "success_score",
45
  "delivery_risk_score",
46
  "year",
47
- ]
48
- for col in numeric_cols:
49
  df[col] = pd.to_numeric(df[col], errors="coerce")
50
  return df
51
 
52
 
53
  def initialize_state() -> None:
54
  defaults = {
55
- "project_name": "",
56
- "scope_complexity": "Medium",
57
- "budget": 350000,
58
- "team_size": 8,
59
- "timeline_weeks": 20,
60
- "tech_risk": "Medium",
61
- "client_tier": "Mid-Market",
62
- "dependencies": 1,
63
  "request_timestamps": [],
64
- "simulation_result": None,
65
- "example_loaded_at": None,
 
 
 
66
  }
67
- for key, value in defaults.items():
68
- if key not in st.session_state:
69
- st.session_state[key] = value
70
 
71
 
72
- def _load_example_callback() -> None:
73
- st.session_state.project_name = "Aurora ERP + CRM Modernization"
74
- st.session_state.scope_complexity = "High"
75
- st.session_state.budget = 860000
76
- st.session_state.team_size = 14
77
- st.session_state.timeline_weeks = 28
78
- st.session_state.tech_risk = "Medium"
79
- st.session_state.client_tier = "Enterprise"
80
- st.session_state.dependencies = 3
81
- st.session_state.example_loaded_at = datetime.utcnow().isoformat()
82
 
83
 
84
- def get_inputs_from_state() -> Dict[str, Any]:
85
- return {
86
- "project_name": st.session_state.project_name.strip() or "Untitled Opportunity",
87
- "scope_complexity": st.session_state.scope_complexity,
88
- "budget": float(st.session_state.budget),
89
- "team_size": int(st.session_state.team_size),
90
- "timeline_weeks": int(st.session_state.timeline_weeks),
91
- "tech_risk": st.session_state.tech_risk,
92
- "client_tier": st.session_state.client_tier,
93
- "dependencies": int(st.session_state.dependencies),
94
- }
 
 
 
95
 
96
 
97
  def timeline_pressure_score(inputs: Dict[str, Any]) -> float:
@@ -109,15 +113,13 @@ def compute_margin_estimate(inputs: Dict[str, Any]) -> float:
109
  tier_factor = CLIENT_TIER_FACTORS[inputs["client_tier"]]
110
  budget_scale = min(inputs["budget"] / 1000000, 2.4)
111
  team_density = inputs["team_size"] / max(inputs["budget"] / 100000, 1.0)
112
- timeline_pressure = timeline_pressure_score(inputs)
113
-
114
  base_margin = 23.5
115
  size_bonus = budget_scale * 2.8
116
  complexity_drag = (complexity - 1.0) * 9.5
117
  tech_drag = (tech_factor - 1.0) * 8.2
118
  staffing_drag = max(0, (team_density - 1.55) * 4.2)
119
- pressure_drag = max(0, timeline_pressure) * 0.09
120
-
121
  margin = (base_margin + size_bonus - complexity_drag - tech_drag - staffing_drag - pressure_drag) * tier_factor
122
  return clamp(margin, 3.0, 48.0)
123
 
@@ -127,12 +129,12 @@ def compute_risk_score(inputs: Dict[str, Any]) -> float:
127
  tech_weight = {"Low": 7, "Medium": 16, "High": 30}[inputs["tech_risk"]]
128
  dependency_weight = inputs["dependencies"] * 7.5
129
  pressure_weight = max(0, timeline_pressure_score(inputs)) * 0.65
130
- raw_risk = complexity_weight + tech_weight + dependency_weight + pressure_weight
131
  if inputs["client_tier"] == "Enterprise":
132
- raw_risk += 4.5
133
  if inputs["team_size"] < 4 and inputs["scope_complexity"] in {"High", "Critical"}:
134
- raw_risk += 9
135
- return clamp(raw_risk, 6, 97)
136
 
137
 
138
  def compute_success_probability(inputs: Dict[str, Any], margin: float, risk_score: float) -> float:
@@ -158,91 +160,111 @@ def risk_level_label(score: float) -> str:
158
  return "Critical"
159
 
160
 
161
- def simulate_scenarios(inputs: Dict[str, Any]) -> Tuple[pd.DataFrame, Dict[str, Any]]:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
162
  margin = compute_margin_estimate(inputs)
163
  risk = compute_risk_score(inputs)
164
- success = compute_success_probability(inputs, margin, risk)
165
- baseline_timeline = inputs["timeline_weeks"]
166
-
167
- baseline = {
168
- "Scenario": "Baseline",
169
- "Projected Margin %": round(margin, 1),
170
- "Success Probability %": round(success, 1),
171
- "Delivery Risk": risk_level_label(risk),
172
- "Risk Score": round(risk, 1),
173
- "Projected Timeline (weeks)": int(round(baseline_timeline)),
174
- "Assumption": "As-entered plan with current parameters.",
175
- }
176
- conservative_risk = clamp(risk - 10, 4, 95)
177
- conservative_margin = clamp(margin - 3.2, 2, 50)
178
- conservative_success = clamp(success + 7, 5, 98)
179
- conservative = {
180
- "Scenario": "Conservative",
181
- "Projected Margin %": round(conservative_margin, 1),
182
- "Success Probability %": round(conservative_success, 1),
183
- "Delivery Risk": risk_level_label(conservative_risk),
184
- "Risk Score": round(conservative_risk, 1),
185
- "Projected Timeline (weeks)": int(round(baseline_timeline * 1.2)),
186
- "Assumption": "Adds delivery buffer and stronger governance coverage.",
187
- }
188
- aggressive_risk = clamp(risk + 12, 4, 99)
189
- aggressive_margin = clamp(margin + 3.8, 2, 55)
190
- aggressive_success = clamp(success - 8.5, 4, 96)
191
- aggressive = {
192
- "Scenario": "Aggressive",
193
- "Projected Margin %": round(aggressive_margin, 1),
194
- "Success Probability %": round(aggressive_success, 1),
195
- "Delivery Risk": risk_level_label(aggressive_risk),
196
- "Risk Score": round(aggressive_risk, 1),
197
- "Projected Timeline (weeks)": int(round(max(4, baseline_timeline * 0.85))),
198
- "Assumption": "Timeline compression with lean staffing and tighter scope cuts.",
199
- }
200
- ordered = pd.DataFrame([conservative, baseline, aggressive])
201
- model_summary = {
202
- "baseline_margin": margin,
203
- "baseline_risk_score": risk,
204
- "baseline_success": success,
205
- "timeline_pressure": timeline_pressure_score(inputs),
206
  }
207
- return ordered, model_summary
208
 
209
 
210
- def compute_capacity_impact(inputs: Dict[str, Any], historical_df: pd.DataFrame) -> Dict[str, Any]:
211
- recent = historical_df[historical_df["year"] >= 2023].copy()
212
- if recent.empty:
213
- recent = historical_df.copy()
214
- avg_team_size = float(recent["team_size"].mean())
215
- active_reference = max(5, int(round(len(recent) * 0.45)))
216
- org_capacity = max(40, int(round(avg_team_size * active_reference * 1.42)))
217
- current_committed = int(round(avg_team_size * active_reference * 0.88))
218
- projected_committed = current_committed + inputs["team_size"]
219
- current_util = (current_committed / org_capacity) * 100
220
- projected_util = (projected_committed / org_capacity) * 100
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
221
 
222
- high_risk_recent = recent[recent["delivery_risk_score"] >= 60]
223
- risk_before = (len(high_risk_recent) / len(recent)) * 100 if len(recent) else 0
224
- candidate_high_risk = compute_risk_score(inputs) >= 60
225
- risk_after = ((len(high_risk_recent) + (1 if candidate_high_risk else 0)) / (len(recent) + 1)) * 100
226
 
227
- bottleneck = "No immediate bottleneck detected"
228
- if projected_util >= 90:
229
- bottleneck = "Critical staffing contention across platform and data engineering"
230
- elif projected_util >= 80:
231
- bottleneck = "Moderate contention in solution architecture and QA"
232
- elif inputs["dependencies"] >= 4:
233
- bottleneck = "Dependency management likely to become portfolio constraint"
 
 
 
 
 
 
 
 
 
234
 
 
 
 
 
235
  return {
236
- "org_capacity_slots": org_capacity,
237
- "current_committed_slots": current_committed,
238
- "projected_committed_slots": projected_committed,
239
- "current_utilization_pct": round(current_util, 1),
240
- "projected_utilization_pct": round(projected_util, 1),
241
- "utilization_delta_pct": round(projected_util - current_util, 1),
242
- "risk_concentration_before_pct": round(risk_before, 1),
243
- "risk_concentration_after_pct": round(risk_after, 1),
244
- "risk_concentration_delta_pct": round(risk_after - risk_before, 1),
245
- "portfolio_bottleneck": bottleneck,
 
 
246
  }
247
 
248
 
@@ -260,8 +282,7 @@ def compute_similarity_distance(inputs: Dict[str, Any], row: pd.Series) -> float
260
  def find_similar_projects(inputs: Dict[str, Any], historical_df: pd.DataFrame, top_n: int = 5) -> pd.DataFrame:
261
  df = historical_df.copy()
262
  df["similarity_distance"] = df.apply(lambda row: compute_similarity_distance(inputs, row), axis=1)
263
- df = df.sort_values("similarity_distance", ascending=True).head(top_n)
264
- show_cols = [
265
  "project_id",
266
  "name",
267
  "scope_complexity",
@@ -278,70 +299,102 @@ def find_similar_projects(inputs: Dict[str, Any], historical_df: pd.DataFrame, t
278
  "year",
279
  "similarity_distance",
280
  ]
281
- return pd.DataFrame(df[show_cols])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
282
 
283
 
284
- def build_gemini_prompt(inputs: Dict[str, Any], scenario_df: pd.DataFrame, capacity: Dict[str, Any], similar: pd.DataFrame) -> str:
285
- scenario_lines = []
286
  for _, row in scenario_df.iterrows():
287
- scenario_lines.append(
288
- f"- {row['Scenario']}: margin={row['Projected Margin %']}%, success={row['Success Probability %']}%, "
289
- f"risk={row['Delivery Risk']} ({row['Risk Score']}), timeline={row['Projected Timeline (weeks)']} weeks"
290
  )
291
- similar_lines = []
292
- for _, row in similar.iterrows():
293
- similar_lines.append(
294
- f"- {row['name']} ({int(row['year'])}): margin={row['actual_margin_pct']}%, success={row['success_score']}, "
295
- f"risk={row['delivery_risk_score']}, outcome={row['outcome']}, distance={round(float(row['similarity_distance']), 3)}"
296
  )
297
- prompt = f"""
298
- You are an enterprise deal desk and PMO strategy advisor.
299
- Evaluate the candidate project and return practical recommendations.
300
- Use concise business language with actionable bullets.
301
-
302
- Candidate project:
303
- - Name: {inputs['project_name']}
304
- - Scope complexity: {inputs['scope_complexity']}
305
- - Budget: ${inputs['budget']:,.0f}
306
- - Team size: {inputs['team_size']}
307
- - Timeline: {inputs['timeline_weeks']} weeks
308
- - Technology risk: {inputs['tech_risk']}
309
- - Client tier: {inputs['client_tier']}
310
- - Dependencies: {inputs['dependencies']}
 
 
 
311
 
312
  Scenarios:
313
- {chr(10).join(scenario_lines)}
314
 
315
  Capacity context:
316
  - Current utilization: {capacity['current_utilization_pct']}%
317
  - Projected utilization: {capacity['projected_utilization_pct']}%
318
- - Risk concentration after add: {capacity['risk_concentration_after_pct']}%
319
- - Bottleneck: {capacity['portfolio_bottleneck']}
320
 
321
- Nearest historical projects:
322
- {chr(10).join(similar_lines)}
323
-
324
- Provide only these sections:
325
- 1) Recommended Path (3 bullets)
326
- 2) Scope/Pricing Adjustments (3 bullets)
327
- 3) Risk Mitigations and Phasing (3 bullets)
328
- 4) Executive Call (single sentence)
329
  """.strip()
330
- return prompt
331
 
332
 
333
  def call_gemini(prompt: str, api_key: Optional[str]) -> Optional[str]:
334
  if not api_key:
335
  return None
336
  try:
337
- response = requests.post(
338
  f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key={api_key}",
339
  json={"contents": [{"parts": [{"text": prompt}]}]},
340
- timeout=25,
341
  )
342
- if response.status_code != 200:
343
  return None
344
- payload = response.json()
345
  candidates = payload.get("candidates")
346
  if not candidates:
347
  return None
@@ -354,226 +407,484 @@ def call_gemini(prompt: str, api_key: Optional[str]) -> Optional[str]:
354
  return None
355
 
356
 
357
- def build_heuristic_recommendations(
358
- inputs: Dict[str, Any], scenario_df: pd.DataFrame, capacity: Dict[str, Any], similar: pd.DataFrame
359
- ) -> List[str]:
360
- baseline = scenario_df[scenario_df["Scenario"] == "Baseline"].iloc[0].to_dict()
361
- recs: List[str] = []
362
- if baseline["Risk Score"] >= 70:
363
- recs.append("Phase delivery into two releases, isolating highest-uncertainty integrations in release one.")
364
- elif baseline["Risk Score"] >= 52:
365
- recs.append("Gate scope through milestone acceptance and hold dependency owners to weekly commitments.")
366
- else:
367
- recs.append("Current structure is feasible; preserve core scope and avoid uncontrolled feature growth.")
 
 
 
 
 
 
 
 
 
368
 
369
- if baseline["Projected Margin %"] < 16:
370
- recs.append("Reprice by 8-12% or reduce non-core features to protect delivery margin above 18%.")
371
- elif baseline["Projected Margin %"] > 30:
372
- recs.append("Keep current pricing and include a value-based change-order framework for optional add-ons.")
373
- else:
374
- recs.append("Use baseline pricing with explicit assumptions tied to external dependency availability.")
375
 
376
- util = capacity["projected_utilization_pct"]
377
- if util >= 90:
378
- recs.append("Delay mobilization by 2-4 weeks or pre-book specialist contractors to avoid a capacity breach.")
379
- elif util >= 80:
380
- recs.append("Reserve architecture and QA pods now to prevent portfolio contention.")
 
 
 
381
  else:
382
- recs.append("Capacity impact is manageable; prioritize fast kickoff with fixed governance cadence.")
383
-
384
- completed_ratio = (similar["outcome"] == "completed").sum() / len(similar) if len(similar) else 0
385
- if completed_ratio < 0.5:
386
- recs.append("Similar projects underperformed historically; increase steering oversight and tighten acceptance criteria.")
 
 
 
 
 
 
 
 
 
 
387
  else:
388
- recs.append("Comparable projects show positive precedent; proceed with disciplined execution controls.")
389
-
390
- if inputs["dependencies"] >= 4:
391
- recs.append("Add a dedicated dependency manager and pre-negotiate escalation SLAs with upstream teams.")
392
- return recs
393
-
394
-
395
- def parse_ai_to_bullets(text: str) -> List[str]:
396
- lines = [line.strip() for line in text.splitlines() if line.strip()]
397
- bullets: List[str] = []
398
- for line in lines:
399
- if line.startswith("-"):
400
- bullets.append(line[1:].strip())
401
- elif line[0].isdigit() and ")" in line[:4]:
402
- bullets.append(line)
403
- elif line.lower().startswith("executive call"):
404
- bullets.append(line)
405
- return bullets[:12] if bullets else lines[:12]
406
-
407
-
408
- def enforce_rate_limit(max_requests: int = 8, window_seconds: int = 60) -> Tuple[bool, int]:
409
- now_ts = datetime.utcnow().timestamp()
410
- existing = st.session_state.get("request_timestamps", [])
411
- active = [ts for ts in existing if now_ts - ts <= window_seconds]
412
- if len(active) >= max_requests:
413
- st.session_state.request_timestamps = active
414
- return False, 0
415
- active.append(now_ts)
416
- st.session_state.request_timestamps = active
417
- return True, max_requests - len(active)
418
-
419
-
420
- def run_simulation(historical_df: pd.DataFrame) -> None:
421
- allowed, remaining = enforce_rate_limit(max_requests=8, window_seconds=60)
422
- if not allowed:
423
- st.warning("Rate limit reached: max 8 simulations per 60 seconds. Please wait and retry.")
424
- return
425
 
426
- inputs = get_inputs_from_state()
427
- scenario_df, model_summary = simulate_scenarios(inputs)
428
- capacity = compute_capacity_impact(inputs, historical_df)
429
- similar = find_similar_projects(inputs, historical_df, top_n=5)
430
 
 
 
 
431
  api_key = safe_get_api_key()
432
- ai_response = None
433
  if api_key:
434
- prompt = build_gemini_prompt(inputs, scenario_df, capacity, similar)
435
- ai_response = call_gemini(prompt, api_key)
436
-
437
- if ai_response:
438
- recommendations = parse_ai_to_bullets(ai_response)
439
- recommendation_source = "Gemini AI"
440
- else:
441
- recommendations = build_heuristic_recommendations(inputs, scenario_df, capacity, similar)
442
- recommendation_source = "Deterministic Heuristic"
443
-
444
- st.session_state.simulation_result = {
445
- "inputs": inputs,
446
- "scenario_df": scenario_df,
447
- "model_summary": model_summary,
448
- "capacity": capacity,
449
- "similar": similar,
450
- "recommendations": recommendations,
451
- "recommendation_source": recommendation_source,
452
- "remaining_quota": remaining,
453
- "ran_at": datetime.utcnow().isoformat(),
454
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
455
 
456
 
457
- def render_header() -> None:
458
- st.title("Simulation & Prescriptive Analysis Engine")
459
  st.caption(
460
- "What-if scenario simulator for enterprise projects/deals with multi-scenario outcomes, "
461
- "capacity impact analysis, and prescriptive recommendations."
462
  )
463
 
464
 
465
- def render_left_panel() -> bool:
466
- st.subheader("Project Inputs")
467
- st.text_input("Project name", key="project_name", placeholder="e.g., Northstar CRM + Data Platform Rollout")
468
- st.selectbox("Scope complexity", options=["Low", "Medium", "High", "Critical"], key="scope_complexity")
469
- st.slider("Estimated budget ($)", min_value=50000, max_value=2000000, step=10000, key="budget")
470
- st.slider("Team size required", min_value=2, max_value=30, step=1, key="team_size")
471
- st.slider("Timeline weeks", min_value=4, max_value=52, step=1, key="timeline_weeks")
472
- st.selectbox("Technology risk", options=["Low", "Medium", "High"], key="tech_risk")
473
- st.selectbox("Client tier", options=["Enterprise", "Mid-Market", "SMB"], key="client_tier")
474
- st.slider("Dependencies on in-flight projects", min_value=0, max_value=5, step=1, key="dependencies")
475
- c1, c2 = st.columns(2)
476
- with c1:
477
- st.button("Load Example", use_container_width=True, on_click=_load_example_callback)
478
- with c2:
479
- run_clicked = st.button("Run Simulation", type="primary", use_container_width=True)
480
- return run_clicked
481
-
482
-
483
- def render_scenario_tab(result: Dict[str, Any]) -> None:
484
- scenario_df = result["scenario_df"]
485
- baseline = scenario_df[scenario_df["Scenario"] == "Baseline"].iloc[0]
486
- k1, k2, k3, k4 = st.columns(4)
487
- k1.metric("Baseline Margin", f"{baseline['Projected Margin %']}%")
488
- k2.metric("Baseline Success", f"{baseline['Success Probability %']}%")
489
- k3.metric("Baseline Risk", f"{baseline['Delivery Risk']} ({baseline['Risk Score']})")
490
- k4.metric("Baseline Timeline", f"{int(baseline['Projected Timeline (weeks)'])} weeks")
491
- styled = scenario_df.copy()
492
- styled["Projected Margin %"] = styled["Projected Margin %"].map(lambda x: f"{x}%")
493
- styled["Success Probability %"] = styled["Success Probability %"].map(lambda x: f"{x}%")
494
- st.dataframe(styled, use_container_width=True, hide_index=True)
495
- st.caption("Conservative adds schedule buffer. Baseline uses entered assumptions. Aggressive trims timeline.")
496
-
497
-
498
- def render_capacity_tab(result: Dict[str, Any]) -> None:
499
- capacity = result["capacity"]
500
  c1, c2, c3 = st.columns(3)
501
- c1.metric("Current Utilization", f"{capacity['current_utilization_pct']}%")
502
- c2.metric("Projected Utilization", f"{capacity['projected_utilization_pct']}%", f"+{capacity['utilization_delta_pct']}%")
503
- c3.metric("Risk Concentration", f"{capacity['risk_concentration_after_pct']}%", f"+{capacity['risk_concentration_delta_pct']}%")
504
- st.progress(min(capacity["projected_utilization_pct"] / 100, 1.0))
505
- st.write(
506
- f"Portfolio capacity slots: **{capacity['org_capacity_slots']}** | "
507
- f"Committed after project: **{capacity['projected_committed_slots']}**"
 
 
 
 
 
 
 
 
 
 
 
508
  )
509
- st.info(f"Potential bottleneck: {capacity['portfolio_bottleneck']}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
510
 
511
 
512
- def render_recommendation_tab(result: Dict[str, Any]) -> None:
513
- st.write(f"Recommendation source: **{result['recommendation_source']}**")
514
- for rec in result["recommendations"]:
515
- st.write(f"- {rec}")
 
 
 
 
 
 
 
 
516
 
517
 
518
- def render_historical_tab(result: Dict[str, Any]) -> None:
519
- similar = result["similar"].copy()
520
- show = similar.copy()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
521
  show["budget"] = show["budget"].map(lambda x: f"${x:,.0f}")
522
  show["actual_margin_pct"] = show["actual_margin_pct"].map(lambda x: f"{x}%")
523
  show["similarity_distance"] = show["similarity_distance"].map(lambda x: round(float(x), 3))
524
  st.dataframe(show, use_container_width=True, hide_index=True)
525
- completed = (similar["outcome"] == "completed").sum()
526
- avg_margin = float(similar["actual_margin_pct"].mean()) if len(similar) else 0
527
- avg_success = float(similar["success_score"].mean()) if len(similar) else 0
528
- st.caption(
529
- f"Top matches: {len(similar)} | Completed: {completed} | Avg historical margin: {avg_margin:.1f}% | "
530
- f"Avg success score: {avg_success:.1f}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
531
  )
532
-
533
-
534
- def render_right_panel(result: Optional[Dict[str, Any]]) -> None:
535
- st.subheader("Simulation Output")
536
- if not result:
537
- st.info("Run simulation to view scenario analysis, capacity impact, recommendations, and historical comparisons.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
538
  return
539
- st.caption(f"Last run: {result['ran_at']} UTC | Remaining quota in rolling window: {result['remaining_quota']}")
540
- tab1, tab2, tab3, tab4 = st.tabs(
541
- ["Scenario Analysis", "Capacity Impact", "Prescriptive Recommendations", "Historical Comparisons"]
 
 
542
  )
543
- with tab1:
544
- render_scenario_tab(result)
545
- with tab2:
546
- render_capacity_tab(result)
547
- with tab3:
548
- render_recommendation_tab(result)
549
- with tab4:
550
- render_historical_tab(result)
551
-
552
-
553
- def render_dataset_section(df: pd.DataFrame) -> None:
554
- with st.expander("Sample Dataset", expanded=False):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
555
  st.dataframe(df, use_container_width=True, hide_index=True)
556
- csv_bytes = df.to_csv(index=False).encode("utf-8")
557
- st.download_button(
558
- label="Download historical_projects.csv",
559
- data=csv_bytes,
560
- file_name="historical_projects.csv",
561
- mime="text/csv",
562
- )
563
 
564
 
565
  def main() -> None:
566
  initialize_state()
567
  historical_df = load_historical_data()
568
- render_header()
569
- left, right = st.columns([1, 1.7], gap="large")
570
- with left:
571
- run_clicked = render_left_panel()
572
- if run_clicked:
573
- run_simulation(historical_df)
574
- with right:
575
- render_right_panel(st.session_state.simulation_result)
576
- render_dataset_section(historical_df)
577
 
578
 
579
  if __name__ == "__main__":
 
1
+ import json
2
  import os
3
  from datetime import datetime
4
  from typing import Any, Dict, List, Optional, Tuple
 
7
  import requests
8
  import streamlit as st
9
 
10
+ st.set_page_config(page_title="Simulation & Prescriptive Analysis Engine", page_icon="πŸ“ˆ", layout="wide")
 
 
 
 
11
 
12
  COMPLEXITY_FACTORS = {"Low": 0.85, "Medium": 1.0, "High": 1.25, "Critical": 1.55}
13
  TECH_RISK_FACTORS = {"Low": 0.8, "Medium": 1.0, "High": 1.3}
14
  CLIENT_TIER_FACTORS = {"SMB": 0.95, "Mid-Market": 1.0, "Enterprise": 1.08}
15
+ COMPLEXITY_OPTIONS = ["Low", "Medium", "High", "Critical"]
16
+ TECH_RISK_OPTIONS = ["Low", "Medium", "High"]
17
+ CLIENT_TIER_OPTIONS = ["SMB", "Mid-Market", "Enterprise"]
18
+ SAMPLE = {
19
+ "project_description": "Replatform fragmented order lifecycle workflows into a unified commerce operations platform across finance, fulfillment, and support.",
20
+ "budget": 880000,
21
+ "team_size": 14,
22
+ "timeline_weeks": 30,
23
+ "scope_complexity": "High",
24
+ "tech_risk": "Medium",
25
+ "client_tier": "Enterprise",
26
+ "dependencies": 3,
27
+ }
28
 
29
 
30
  def clamp(value: float, min_value: float, max_value: float) -> float:
 
33
 
34
  def safe_get_api_key() -> Optional[str]:
35
  try:
36
+ key = st.secrets.get("GEMINI_API_KEY")
37
+ if key:
38
+ return key
39
  except Exception:
40
  pass
41
  env_key = os.getenv("GEMINI_API_KEY")
 
45
  @st.cache_data
46
  def load_historical_data() -> pd.DataFrame:
47
  df = pd.read_csv("data/historical_projects.csv")
48
+ for col in [
49
  "budget",
50
  "team_size",
51
  "timeline_weeks",
 
54
  "success_score",
55
  "delivery_risk_score",
56
  "year",
57
+ ]:
 
58
  df[col] = pd.to_numeric(df[col], errors="coerce")
59
  return df
60
 
61
 
62
  def initialize_state() -> None:
63
  defaults = {
64
+ "unlocked_step": 1,
 
 
 
 
 
 
 
65
  "request_timestamps": [],
66
+ "base_inputs": None,
67
+ "scenario_snapshot": None,
68
+ "recommendations": None,
69
+ "report": None,
70
+ "custom_scenario_enabled": False,
71
  }
72
+ for k, v in defaults.items():
73
+ if k not in st.session_state:
74
+ st.session_state[k] = v
75
 
76
 
77
+ def reset_all() -> None:
78
+ keep = {"request_timestamps"}
79
+ for k in list(st.session_state.keys()):
80
+ if k not in keep:
81
+ del st.session_state[k]
82
+ initialize_state()
 
 
 
 
83
 
84
 
85
+ def load_sample() -> None:
86
+ for k, v in SAMPLE.items():
87
+ st.session_state[k] = v
88
+
89
+
90
+ def rate_limiter(max_requests: int = 8, window_seconds: int = 60) -> Tuple[bool, int]:
91
+ now_ts = datetime.utcnow().timestamp()
92
+ active = [ts for ts in st.session_state.get("request_timestamps", []) if now_ts - ts <= window_seconds]
93
+ if len(active) >= max_requests:
94
+ st.session_state["request_timestamps"] = active
95
+ return False, 0
96
+ active.append(now_ts)
97
+ st.session_state["request_timestamps"] = active
98
+ return True, max_requests - len(active)
99
 
100
 
101
  def timeline_pressure_score(inputs: Dict[str, Any]) -> float:
 
113
  tier_factor = CLIENT_TIER_FACTORS[inputs["client_tier"]]
114
  budget_scale = min(inputs["budget"] / 1000000, 2.4)
115
  team_density = inputs["team_size"] / max(inputs["budget"] / 100000, 1.0)
116
+ pressure = timeline_pressure_score(inputs)
 
117
  base_margin = 23.5
118
  size_bonus = budget_scale * 2.8
119
  complexity_drag = (complexity - 1.0) * 9.5
120
  tech_drag = (tech_factor - 1.0) * 8.2
121
  staffing_drag = max(0, (team_density - 1.55) * 4.2)
122
+ pressure_drag = max(0, pressure) * 0.09
 
123
  margin = (base_margin + size_bonus - complexity_drag - tech_drag - staffing_drag - pressure_drag) * tier_factor
124
  return clamp(margin, 3.0, 48.0)
125
 
 
129
  tech_weight = {"Low": 7, "Medium": 16, "High": 30}[inputs["tech_risk"]]
130
  dependency_weight = inputs["dependencies"] * 7.5
131
  pressure_weight = max(0, timeline_pressure_score(inputs)) * 0.65
132
+ raw = complexity_weight + tech_weight + dependency_weight + pressure_weight
133
  if inputs["client_tier"] == "Enterprise":
134
+ raw += 4.5
135
  if inputs["team_size"] < 4 and inputs["scope_complexity"] in {"High", "Critical"}:
136
+ raw += 9
137
+ return clamp(raw, 6, 97)
138
 
139
 
140
  def compute_success_probability(inputs: Dict[str, Any], margin: float, risk_score: float) -> float:
 
160
  return "Critical"
161
 
162
 
163
+ def normalize_inputs(
164
+ project_description: str,
165
+ budget: int,
166
+ team_size: int,
167
+ timeline_weeks: int,
168
+ scope_complexity: str,
169
+ tech_risk: str,
170
+ client_tier: str,
171
+ dependencies: int,
172
+ ) -> Dict[str, Any]:
173
+ description = project_description.strip()
174
+ return {
175
+ "project_description": description,
176
+ "project_name": description[:80] if description else "Untitled Simulation",
177
+ "budget": float(budget),
178
+ "team_size": int(team_size),
179
+ "timeline_weeks": int(timeline_weeks),
180
+ "scope_complexity": scope_complexity,
181
+ "tech_risk": tech_risk,
182
+ "client_tier": client_tier,
183
+ "dependencies": int(dependencies),
184
+ }
185
+
186
+
187
+ def quick_preview(inputs: Dict[str, Any]) -> Dict[str, Any]:
188
  margin = compute_margin_estimate(inputs)
189
  risk = compute_risk_score(inputs)
190
+ pressure = timeline_pressure_score(inputs)
191
+ pressure_label = "Low" if pressure < 8 else "Moderate" if pressure < 20 else "High"
192
+ return {
193
+ "margin": round(margin, 1),
194
+ "risk_score": round(risk, 1),
195
+ "risk_label": risk_level_label(risk),
196
+ "pressure": round(pressure, 1),
197
+ "pressure_label": pressure_label,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
198
  }
 
199
 
200
 
201
+ def scenario_defaults(slug: str) -> Dict[str, Any]:
202
+ defaults = {
203
+ "conservative": {
204
+ "team_delta": 2,
205
+ "timeline_delta": 4,
206
+ "budget_delta_pct": 5,
207
+ "dependency_delta": 0,
208
+ "complexity_override": "Same as project",
209
+ "tech_override": "Same as project",
210
+ "client_override": "Same as project",
211
+ },
212
+ "baseline": {
213
+ "team_delta": 0,
214
+ "timeline_delta": 0,
215
+ "budget_delta_pct": 0,
216
+ "dependency_delta": 0,
217
+ "complexity_override": "Same as project",
218
+ "tech_override": "Same as project",
219
+ "client_override": "Same as project",
220
+ },
221
+ "aggressive": {
222
+ "team_delta": -1,
223
+ "timeline_delta": -4,
224
+ "budget_delta_pct": -3,
225
+ "dependency_delta": 1,
226
+ "complexity_override": "Same as project",
227
+ "tech_override": "Same as project",
228
+ "client_override": "Same as project",
229
+ },
230
+ }
231
+ return defaults[slug]
232
 
 
 
 
 
233
 
234
+ def apply_adjustments(base_inputs: Dict[str, Any], adjustments: Dict[str, Any]) -> Dict[str, Any]:
235
+ complexity = base_inputs["scope_complexity"] if adjustments["complexity_override"] == "Same as project" else adjustments["complexity_override"]
236
+ tech = base_inputs["tech_risk"] if adjustments["tech_override"] == "Same as project" else adjustments["tech_override"]
237
+ tier = base_inputs["client_tier"] if adjustments["client_override"] == "Same as project" else adjustments["client_override"]
238
+ return {
239
+ "project_description": base_inputs["project_description"],
240
+ "project_name": base_inputs["project_name"],
241
+ "budget": float(clamp(base_inputs["budget"] * (1 + adjustments["budget_delta_pct"] / 100), 50000, 2000000)),
242
+ "team_size": int(clamp(base_inputs["team_size"] + adjustments["team_delta"], 2, 30)),
243
+ "timeline_weeks": int(clamp(base_inputs["timeline_weeks"] + adjustments["timeline_delta"], 4, 52)),
244
+ "scope_complexity": complexity,
245
+ "tech_risk": tech,
246
+ "client_tier": tier,
247
+ "dependencies": int(clamp(base_inputs["dependencies"] + adjustments["dependency_delta"], 0, 5)),
248
+ }
249
+
250
 
251
+ def scenario_metrics(inputs: Dict[str, Any], name: str) -> Dict[str, Any]:
252
+ margin = compute_margin_estimate(inputs)
253
+ risk = compute_risk_score(inputs)
254
+ success = compute_success_probability(inputs, margin, risk)
255
  return {
256
+ "Scenario": name,
257
+ "Projected Margin %": round(margin, 1),
258
+ "Success Probability %": round(success, 1),
259
+ "Delivery Risk": risk_level_label(risk),
260
+ "Risk Score": round(risk, 1),
261
+ "Projected Timeline (weeks)": int(inputs["timeline_weeks"]),
262
+ "Team Size": int(inputs["team_size"]),
263
+ "Budget": float(inputs["budget"]),
264
+ "Dependencies": int(inputs["dependencies"]),
265
+ "Complexity": inputs["scope_complexity"],
266
+ "Tech Risk": inputs["tech_risk"],
267
+ "Client Tier": inputs["client_tier"],
268
  }
269
 
270
 
 
282
  def find_similar_projects(inputs: Dict[str, Any], historical_df: pd.DataFrame, top_n: int = 5) -> pd.DataFrame:
283
  df = historical_df.copy()
284
  df["similarity_distance"] = df.apply(lambda row: compute_similarity_distance(inputs, row), axis=1)
285
+ cols = [
 
286
  "project_id",
287
  "name",
288
  "scope_complexity",
 
299
  "year",
300
  "similarity_distance",
301
  ]
302
+ return pd.DataFrame(df.sort_values("similarity_distance", ascending=True).head(top_n)[cols])
303
+
304
+
305
+ def compute_capacity_impact(inputs: Dict[str, Any], historical_df: pd.DataFrame) -> Dict[str, Any]:
306
+ recent = historical_df[historical_df["year"] >= 2023].copy()
307
+ if recent.empty:
308
+ recent = historical_df.copy()
309
+ avg_team = float(recent["team_size"].mean())
310
+ active_ref = max(5, int(round(len(recent) * 0.45)))
311
+ org_capacity = max(40, int(round(avg_team * active_ref * 1.42)))
312
+ current_committed = int(round(avg_team * active_ref * 0.88))
313
+ projected_committed = current_committed + inputs["team_size"]
314
+ current_util = (current_committed / org_capacity) * 100
315
+ projected_util = (projected_committed / org_capacity) * 100
316
+ high_risk_recent = recent[recent["delivery_risk_score"] >= 60]
317
+ risk_before = (len(high_risk_recent) / len(recent)) * 100 if len(recent) else 0
318
+ candidate_high_risk = compute_risk_score(inputs) >= 60
319
+ risk_after = ((len(high_risk_recent) + (1 if candidate_high_risk else 0)) / (len(recent) + 1)) * 100
320
+ bottleneck = "No immediate bottleneck detected"
321
+ driver = "Balanced utilization across key disciplines"
322
+ if projected_util >= 90:
323
+ bottleneck, driver = "Critical staffing contention", "Platform and data engineering exceed safe portfolio headroom"
324
+ elif projected_util >= 80:
325
+ bottleneck, driver = "Moderate specialist contention", "Solution architecture and QA become schedule constraints"
326
+ elif inputs["dependencies"] >= 4:
327
+ bottleneck, driver = "Dependency orchestration risk", "Cross-team sequencing overhead likely to slow throughput"
328
+ return {
329
+ "org_capacity_slots": org_capacity,
330
+ "current_committed_slots": current_committed,
331
+ "projected_committed_slots": projected_committed,
332
+ "current_utilization_pct": round(current_util, 1),
333
+ "projected_utilization_pct": round(projected_util, 1),
334
+ "utilization_delta_pct": round(projected_util - current_util, 1),
335
+ "risk_concentration_before_pct": round(risk_before, 1),
336
+ "risk_concentration_after_pct": round(risk_after, 1),
337
+ "risk_concentration_delta_pct": round(risk_after - risk_before, 1),
338
+ "portfolio_bottleneck": bottleneck,
339
+ "portfolio_bottleneck_driver": driver,
340
+ }
341
 
342
 
343
+ def build_gemini_prompt(base_inputs: Dict[str, Any], scenario_df: pd.DataFrame, capacity: Dict[str, Any], similar_df: pd.DataFrame) -> str:
344
+ scenarios = []
345
  for _, row in scenario_df.iterrows():
346
+ scenarios.append(
347
+ f"- {row['Scenario']}: margin={row['Projected Margin %']}%, success={row['Success Probability %']}%, risk={row['Delivery Risk']} ({row['Risk Score']}), timeline={row['Projected Timeline (weeks)']}w"
 
348
  )
349
+ similars = []
350
+ for _, row in similar_df.iterrows():
351
+ similars.append(
352
+ f"- {row['name']} ({int(row['year'])}): margin={row['actual_margin_pct']}%, success={row['success_score']}, risk={row['delivery_risk_score']}, outcome={row['outcome']}, distance={round(float(row['similarity_distance']), 3)}"
 
353
  )
354
+ return f"""
355
+ You are a portfolio strategy advisor.
356
+ Return only strict JSON with keys:
357
+ - recommended_path: 3 bullets
358
+ - scope_adjustments: 3 bullets
359
+ - risk_mitigations: 3 bullets
360
+ - executive_call: one sentence
361
+
362
+ Project:
363
+ - Description: {base_inputs['project_description']}
364
+ - Budget: ${base_inputs['budget']:,.0f}
365
+ - Team size: {base_inputs['team_size']}
366
+ - Timeline: {base_inputs['timeline_weeks']} weeks
367
+ - Complexity: {base_inputs['scope_complexity']}
368
+ - Tech risk: {base_inputs['tech_risk']}
369
+ - Client tier: {base_inputs['client_tier']}
370
+ - Dependencies: {base_inputs['dependencies']}
371
 
372
  Scenarios:
373
+ {chr(10).join(scenarios)}
374
 
375
  Capacity context:
376
  - Current utilization: {capacity['current_utilization_pct']}%
377
  - Projected utilization: {capacity['projected_utilization_pct']}%
378
+ - Risk concentration delta: {capacity['risk_concentration_delta_pct']}%
379
+ - Bottleneck: {capacity['portfolio_bottleneck']} ({capacity['portfolio_bottleneck_driver']})
380
 
381
+ Closest historical projects:
382
+ {chr(10).join(similars)}
 
 
 
 
 
 
383
  """.strip()
 
384
 
385
 
386
  def call_gemini(prompt: str, api_key: Optional[str]) -> Optional[str]:
387
  if not api_key:
388
  return None
389
  try:
390
+ res = requests.post(
391
  f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key={api_key}",
392
  json={"contents": [{"parts": [{"text": prompt}]}]},
393
+ timeout=30,
394
  )
395
+ if res.status_code != 200:
396
  return None
397
+ payload = res.json()
398
  candidates = payload.get("candidates")
399
  if not candidates:
400
  return None
 
407
  return None
408
 
409
 
410
+ def parse_gemini_output(text: str) -> Optional[Dict[str, Any]]:
411
+ cleaned = text.strip().replace("```json", "").replace("```", "").strip()
412
+ try:
413
+ parsed = json.loads(cleaned)
414
+ except Exception:
415
+ return None
416
+ keys = ["recommended_path", "scope_adjustments", "risk_mitigations", "executive_call"]
417
+ if not all(k in parsed for k in keys):
418
+ return None
419
+ rec_path = [str(x).strip() for x in parsed["recommended_path"] if str(x).strip()][:3]
420
+ scope_adj = [str(x).strip() for x in parsed["scope_adjustments"] if str(x).strip()][:3]
421
+ mitigations = [str(x).strip() for x in parsed["risk_mitigations"] if str(x).strip()][:3]
422
+ if min(len(rec_path), len(scope_adj), len(mitigations)) < 3:
423
+ return None
424
+ return {
425
+ "recommended_path": rec_path,
426
+ "scope_adjustments": scope_adj,
427
+ "risk_mitigations": mitigations,
428
+ "executive_call": str(parsed["executive_call"]).strip(),
429
+ }
430
 
 
 
 
 
 
 
431
 
432
+ def heuristic_recommendations(base_inputs: Dict[str, Any], scenario_df: pd.DataFrame, capacity: Dict[str, Any], similar_df: pd.DataFrame) -> Dict[str, Any]:
433
+ baseline = scenario_df[scenario_df["Scenario"] == "Baseline"].iloc[0].to_dict()
434
+ best = scenario_df.sort_values(["Success Probability %", "Projected Margin %"], ascending=False).iloc[0].to_dict()
435
+ rec_path = []
436
+ if best["Scenario"] == "Conservative":
437
+ rec_path.append("Lead with the Conservative posture to absorb integration volatility and protect confidence.")
438
+ elif best["Scenario"] == "Aggressive":
439
+ rec_path.append("Use the Aggressive posture only with strict dependency governance and weekly executive unblockers.")
440
  else:
441
+ rec_path.append("Run with Baseline posture and lock milestone decisions around delivery gates.")
442
+ rec_path.append("Phase high-uncertainty interfaces into early waves with dedicated integration ownership.")
443
+ rec_path.append(
444
+ "Protect economics with scope discipline and change-order controls." if baseline["Projected Margin %"] >= 18 else "Reprice or reduce non-core scope to restore margin above 18%."
445
+ )
446
+ scope_adj = []
447
+ scope_adj.append("Move dependency-heavy workstreams behind readiness gates.") if base_inputs["dependencies"] >= 4 else scope_adj.append("Defer low-value enhancements into an optional tranche.")
448
+ scope_adj.append("Reduce acceptance complexity for compressed timelines.") if baseline["Projected Timeline (weeks)"] < base_inputs["timeline_weeks"] else scope_adj.append("Keep timeline and remove low-value edge cases to reduce QA spread.")
449
+ completion_rate = float((similar_df["outcome"] == "completed").sum()) / float(len(similar_df)) if len(similar_df) else 0
450
+ scope_adj.append("Tie commercial milestones to value slices due weaker historical completion patterns.") if completion_rate < 0.5 else scope_adj.append("Replicate staffing and sequencing from strongest historical analogs.")
451
+ mitigations = []
452
+ if capacity["projected_utilization_pct"] >= 90:
453
+ mitigations.append("Pre-book contract specialists to avoid critical utilization breaches.")
454
+ elif capacity["projected_utilization_pct"] >= 80:
455
+ mitigations.append("Reserve architecture and QA pods now to prevent contention.")
456
  else:
457
+ mitigations.append("Maintain weekly allocation checks to preserve portfolio headroom.")
458
+ mitigations.append("Assign a dependency manager with blocker SLA escalation to steering committee.")
459
+ mitigations.append("Add launch readiness gates with rollback criteria.") if baseline["Risk Score"] >= 60 else mitigations.append("Run monthly steering checkpoints with strict change qualification.")
460
+ return {
461
+ "recommended_path": rec_path[:3],
462
+ "scope_adjustments": scope_adj[:3],
463
+ "risk_mitigations": mitigations[:3],
464
+ "executive_call": "Proceed on the path that keeps risk below critical, margin above 18%, and utilization below 90%.",
465
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
466
 
 
 
 
 
467
 
468
+ def generate_recommendations(base_inputs: Dict[str, Any], scenario_df: pd.DataFrame, capacity: Dict[str, Any], similar_df: pd.DataFrame) -> Dict[str, Any]:
469
+ source = "Deterministic Heuristic"
470
+ body = None
471
  api_key = safe_get_api_key()
 
472
  if api_key:
473
+ prompt = build_gemini_prompt(base_inputs, scenario_df, capacity, similar_df)
474
+ text = call_gemini(prompt, api_key)
475
+ if text:
476
+ parsed = parse_gemini_output(text)
477
+ if parsed:
478
+ body = parsed
479
+ source = "Gemini 2.5 Flash"
480
+ if not body:
481
+ body = heuristic_recommendations(base_inputs, scenario_df, capacity, similar_df)
482
+ return {"source": source, "generated_at": datetime.utcnow().isoformat(), **body}
483
+
484
+
485
+ def apply_style(unlocked_step: int) -> None:
486
+ lock_start = unlocked_step + 1
487
+ lock_css = ""
488
+ if lock_start <= 4:
489
+ lock_css = f"div[role='tablist'] button:nth-child(n+{lock_start}){{opacity:.38!important;filter:grayscale(1)!important;pointer-events:none!important;}}"
490
+ st.markdown(
491
+ f"""
492
+ <style>
493
+ :root{{--bg:#0f141d;--panel:#162032;--line:#324762;--text:#edf3ff;--muted:#9eb1cf;--accent:#6fd8bc;}}
494
+ .stApp{{background:radial-gradient(circle at 7% 5%,rgba(111,216,188,.18),transparent 33%),radial-gradient(circle at 93% 0,rgba(128,160,227,.16),transparent 30%),linear-gradient(180deg,#0b1017 0%,#101824 100%);color:var(--text);}}
495
+ [data-testid='stHeader']{{background:transparent;}}
496
+ [data-testid='stAppViewContainer']{{background:transparent;}}
497
+ div[role='tablist']{{gap:.45rem;}}
498
+ div[role='tablist'] button{{background:rgba(18,27,42,.92)!important;border:1px solid rgba(94,124,166,.52)!important;border-radius:.7rem!important;color:var(--text)!important;}}
499
+ .banner{{background:linear-gradient(90deg,rgba(111,216,188,.17),rgba(111,216,188,.02));border:1px solid rgba(111,216,188,.26);padding:.78rem .95rem;border-radius:.75rem;margin-bottom:.75rem;}}
500
+ .quick{{background:linear-gradient(180deg,rgba(23,34,51,.95),rgba(17,26,38,.96));border:1px solid rgba(83,111,147,.5);border-radius:.85rem;padding:.8rem .9rem;min-height:106px;}}
501
+ .quick .k{{color:var(--muted);font-size:.79rem;text-transform:uppercase;letter-spacing:.06em;}}
502
+ .quick .v{{font-size:1.33rem;font-weight:650;margin-top:.16rem;}}
503
+ .quick .s{{font-size:.8rem;color:var(--accent);margin-top:.17rem;}}
504
+ .scenario-chip{{border:1px solid rgba(111,216,188,.23);background:linear-gradient(180deg,rgba(21,31,48,.95),rgba(15,23,34,.96));border-radius:.8rem;padding:.58rem .74rem;margin-bottom:.65rem;}}
505
+ .mini-link button{{padding:0!important;min-height:0!important;color:var(--accent)!important;text-decoration:underline!important;border:none!important;background:transparent!important;}}
506
+ {lock_css}
507
+ </style>
508
+ """,
509
+ unsafe_allow_html=True,
510
+ )
511
 
512
 
513
+ def show_header() -> None:
514
+ st.title("Simulation and Prescriptive Analysis Engine")
515
  st.caption(
516
+ "An AI engine that simulates custom work and recommends optimal paths, projecting delivery complexity, margin impact, and likelihood of success while factoring in all other projects in flight."
 
517
  )
518
 
519
 
520
+ def section_banner(step: int) -> None:
521
+ lines = {
522
+ 1: "Define project assumptions and watch live margin/risk/timeline pressure update instantly.",
523
+ 2: "Tune Conservative, Baseline, Aggressive, and optional Custom scenarios with inline controls.",
524
+ 3: "Review prescriptive recommendations, capture ratings, and validate capacity and bottlenecks.",
525
+ 4: "Generate the executive report with scenario comparison, recommendations, ratings, and export.",
526
+ }
527
+ st.markdown(f"<div class='banner'>{lines[step]}</div>", unsafe_allow_html=True)
528
+
529
+
530
+ def show_quick_cards(preview: Dict[str, Any]) -> None:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
531
  c1, c2, c3 = st.columns(3)
532
+ c1.markdown(f"<div class='quick'><div class='k'>Projected Margin</div><div class='v'>{preview['margin']}%</div><div class='s'>Live estimate</div></div>", unsafe_allow_html=True)
533
+ c2.markdown(f"<div class='quick'><div class='k'>Risk Level</div><div class='v'>{preview['risk_label']}</div><div class='s'>Score {preview['risk_score']}</div></div>", unsafe_allow_html=True)
534
+ c3.markdown(f"<div class='quick'><div class='k'>Timeline Pressure</div><div class='v'>{preview['pressure_label']}</div><div class='s'>{preview['pressure']} points</div></div>", unsafe_allow_html=True)
535
+
536
+
537
+ def render_step1() -> None:
538
+ section_banner(1)
539
+ st.markdown("<div class='mini-link'>", unsafe_allow_html=True)
540
+ sample_btn = st.button("Try with sample", type="tertiary", key="sample_btn")
541
+ st.markdown("</div>", unsafe_allow_html=True)
542
+ if sample_btn:
543
+ load_sample()
544
+ st.rerun()
545
+ description = st.text_area(
546
+ "Describe the project or deal you want to simulate",
547
+ key="project_description",
548
+ height=118,
549
+ placeholder="e.g., Consolidate billing, customer service, and analytics workflows into a single cloud-native operating model.",
550
  )
551
+ c1, c2, c3 = st.columns(3)
552
+ with c1:
553
+ budget = st.slider("Budget ($)", 50000, 2000000, 350000, 10000, key="budget")
554
+ team_size = st.slider("Team size", 2, 30, 8, 1, key="team_size")
555
+ timeline_weeks = st.slider("Timeline (weeks)", 4, 52, 20, 1, key="timeline_weeks")
556
+ with c2:
557
+ complexity = st.selectbox("Complexity", COMPLEXITY_OPTIONS, index=1, key="scope_complexity")
558
+ tech_risk = st.selectbox("Tech risk", TECH_RISK_OPTIONS, index=1, key="tech_risk")
559
+ client_tier = st.selectbox("Client tier", CLIENT_TIER_OPTIONS, index=1, key="client_tier")
560
+ with c3:
561
+ dependencies = st.slider("Dependencies in flight", 0, 5, 1, 1, key="dependencies")
562
+ st.caption("Quick estimate cards update in real-time while sliders move.")
563
+ base_inputs = normalize_inputs(description, budget, team_size, timeline_weeks, complexity, tech_risk, client_tier, dependencies)
564
+ show_quick_cards(quick_preview(base_inputs))
565
+ run_btn = st.button("Run Baseline Simulation β†’", type="primary", use_container_width=True)
566
+ if run_btn:
567
+ allowed, remaining = rate_limiter(8, 60)
568
+ if not allowed:
569
+ st.warning("Rate limit reached: max 8 actions per 60 seconds.")
570
+ return
571
+ st.session_state["base_inputs"] = base_inputs
572
+ st.session_state["scenario_snapshot"] = None
573
+ st.session_state["recommendations"] = None
574
+ st.session_state["report"] = None
575
+ st.session_state["custom_scenario_enabled"] = False
576
+ st.session_state["unlocked_step"] = max(st.session_state.get("unlocked_step", 1), 2)
577
+ st.success(f"Baseline simulation ready. Remaining quota in rolling window: {remaining}")
578
+
579
+
580
+ def scenario_adjustment_widgets(slug: str) -> Dict[str, Any]:
581
+ d = scenario_defaults(slug)
582
+ team_delta = st.slider("Team change", -6, 6, d["team_delta"], 1, key=f"{slug}_team_delta")
583
+ timeline_delta = st.slider("Timeline shift (weeks)", -12, 12, d["timeline_delta"], 1, key=f"{slug}_timeline_delta")
584
+ budget_delta_pct = st.slider("Budget change (%)", -25, 25, d["budget_delta_pct"], 1, key=f"{slug}_budget_delta")
585
+ dependency_delta = st.slider("Dependency shift", -2, 2, d["dependency_delta"], 1, key=f"{slug}_dep_delta")
586
+ complexity_override = st.selectbox("Complexity override", ["Same as project", *COMPLEXITY_OPTIONS], index=0, key=f"{slug}_complexity")
587
+ tech_override = st.selectbox("Tech risk override", ["Same as project", *TECH_RISK_OPTIONS], index=0, key=f"{slug}_tech")
588
+ client_override = st.selectbox("Client tier override", ["Same as project", *CLIENT_TIER_OPTIONS], index=0, key=f"{slug}_tier")
589
+ return {
590
+ "team_delta": int(team_delta),
591
+ "timeline_delta": int(timeline_delta),
592
+ "budget_delta_pct": int(budget_delta_pct),
593
+ "dependency_delta": int(dependency_delta),
594
+ "complexity_override": complexity_override,
595
+ "tech_override": tech_override,
596
+ "client_override": client_override,
597
+ }
598
 
599
 
600
+ def render_scenario_card(base_inputs: Dict[str, Any], slug: str, title: str) -> Tuple[Dict[str, Any], Dict[str, Any]]:
601
+ st.markdown(f"<div class='scenario-chip'><strong>{title}</strong></div>", unsafe_allow_html=True)
602
+ adjustments = scenario_adjustment_widgets(slug)
603
+ scenario_inputs = apply_adjustments(base_inputs, adjustments)
604
+ metrics = scenario_metrics(scenario_inputs, title)
605
+ m1, m2, m3, m4 = st.columns(4)
606
+ m1.metric("Margin", f"{metrics['Projected Margin %']}%")
607
+ m2.metric("Success", f"{metrics['Success Probability %']}%")
608
+ m3.metric("Risk", f"{metrics['Delivery Risk']} ({metrics['Risk Score']})")
609
+ m4.metric("Timeline", f"{metrics['Projected Timeline (weeks)']}w")
610
+ st.caption("Inline what-if controls are live: add people, compress timeline, shift budget, or adjust risk profile.")
611
+ return metrics, scenario_inputs
612
 
613
 
614
+ def render_custom_scenario() -> Tuple[Dict[str, Any], Dict[str, Any]]:
615
+ st.markdown("<div class='scenario-chip'><strong>Custom</strong></div>", unsafe_allow_html=True)
616
+ label = st.text_input("Scenario label", "Custom", key="custom_label")
617
+ c1, c2, c3 = st.columns(3)
618
+ with c1:
619
+ budget = st.slider("Custom budget ($)", 50000, 2000000, 420000, 10000, key="custom_budget")
620
+ team = st.slider("Custom team size", 2, 30, 8, 1, key="custom_team")
621
+ with c2:
622
+ timeline = st.slider("Custom timeline (weeks)", 4, 52, 18, 1, key="custom_timeline")
623
+ deps = st.slider("Custom dependencies", 0, 5, 1, 1, key="custom_deps")
624
+ with c3:
625
+ complexity = st.selectbox("Custom complexity", COMPLEXITY_OPTIONS, index=1, key="custom_complexity")
626
+ tech = st.selectbox("Custom tech risk", TECH_RISK_OPTIONS, index=1, key="custom_tech")
627
+ tier = st.selectbox("Custom client tier", CLIENT_TIER_OPTIONS, index=1, key="custom_tier")
628
+ custom_inputs = {
629
+ "project_description": f"{label.strip()} scenario",
630
+ "project_name": label.strip() or "Custom",
631
+ "budget": float(budget),
632
+ "team_size": int(team),
633
+ "timeline_weeks": int(timeline),
634
+ "scope_complexity": complexity,
635
+ "tech_risk": tech,
636
+ "client_tier": tier,
637
+ "dependencies": int(deps),
638
+ }
639
+ metrics = scenario_metrics(custom_inputs, "Custom")
640
+ m1, m2, m3, m4 = st.columns(4)
641
+ m1.metric("Margin", f"{metrics['Projected Margin %']}%")
642
+ m2.metric("Success", f"{metrics['Success Probability %']}%")
643
+ m3.metric("Risk", f"{metrics['Delivery Risk']} ({metrics['Risk Score']})")
644
+ m4.metric("Timeline", f"{metrics['Projected Timeline (weeks)']}w")
645
+ return metrics, custom_inputs
646
+
647
+
648
+ def render_step2(historical_df: pd.DataFrame) -> None:
649
+ section_banner(2)
650
+ base_inputs = st.session_state.get("base_inputs")
651
+ if not base_inputs:
652
+ st.info("Complete Step 1 and run baseline simulation to unlock scenario planning.")
653
+ return
654
+ rows: List[Dict[str, Any]] = []
655
+ inputs_map: Dict[str, Dict[str, Any]] = {}
656
+ a, b, c = st.columns(3)
657
+ with a:
658
+ r, i = render_scenario_card(base_inputs, "conservative", "Conservative")
659
+ rows.append(r)
660
+ inputs_map["Conservative"] = i
661
+ with b:
662
+ r, i = render_scenario_card(base_inputs, "baseline", "Baseline")
663
+ rows.append(r)
664
+ inputs_map["Baseline"] = i
665
+ with c:
666
+ r, i = render_scenario_card(base_inputs, "aggressive", "Aggressive")
667
+ rows.append(r)
668
+ inputs_map["Aggressive"] = i
669
+ if not st.session_state.get("custom_scenario_enabled", False):
670
+ custom_btn = st.button("+ Custom Scenario", key="add_custom")
671
+ if custom_btn:
672
+ st.session_state["custom_scenario_enabled"] = True
673
+ st.rerun()
674
+ else:
675
+ left, right = st.columns([5, 1])
676
+ with left:
677
+ r, i = render_custom_scenario()
678
+ rows.append(r)
679
+ inputs_map["Custom"] = i
680
+ with right:
681
+ remove_btn = st.button("Remove", key="remove_custom")
682
+ if remove_btn:
683
+ st.session_state["custom_scenario_enabled"] = False
684
+ st.rerun()
685
+ order = {"Conservative": 0, "Baseline": 1, "Aggressive": 2, "Custom": 3}
686
+ scenario_df = pd.DataFrame(sorted(rows, key=lambda row: order.get(row["Scenario"], 9)))
687
+ baseline_inputs = inputs_map["Baseline"]
688
+ capacity = compute_capacity_impact(baseline_inputs, historical_df)
689
+ similar_df = find_similar_projects(baseline_inputs, historical_df, top_n=5)
690
+ st.markdown("#### Similar historical projects")
691
+ show = similar_df.copy()
692
  show["budget"] = show["budget"].map(lambda x: f"${x:,.0f}")
693
  show["actual_margin_pct"] = show["actual_margin_pct"].map(lambda x: f"{x}%")
694
  show["similarity_distance"] = show["similarity_distance"].map(lambda x: round(float(x), 3))
695
  st.dataframe(show, use_container_width=True, hide_index=True)
696
+ get_recs = st.button("Get Recommendations β†’", type="primary", use_container_width=True)
697
+ if get_recs:
698
+ allowed, remaining = rate_limiter(8, 60)
699
+ if not allowed:
700
+ st.warning("Rate limit reached: max 8 actions per 60 seconds.")
701
+ return
702
+ recs = generate_recommendations(baseline_inputs, scenario_df, capacity, similar_df)
703
+ st.session_state["scenario_snapshot"] = {
704
+ "baseline_inputs": baseline_inputs,
705
+ "scenario_df": scenario_df,
706
+ "scenario_inputs_map": inputs_map,
707
+ "capacity": capacity,
708
+ "similar_df": similar_df,
709
+ "generated_at": datetime.utcnow().isoformat(),
710
+ "remaining_quota": remaining,
711
+ }
712
+ st.session_state["recommendations"] = recs
713
+ st.session_state["report"] = None
714
+ st.session_state["unlocked_step"] = max(st.session_state.get("unlocked_step", 1), 3)
715
+ st.success(f"Recommendations generated with {recs['source']}. Remaining quota: {remaining}")
716
+
717
+
718
+ def recommendation_rows(recs: Dict[str, Any]) -> List[Tuple[str, str, str]]:
719
+ rows: List[Tuple[str, str, str]] = []
720
+ for key, section in [
721
+ ("recommended_path", "Recommended Path"),
722
+ ("scope_adjustments", "Scope Adjustments"),
723
+ ("risk_mitigations", "Risk Mitigations"),
724
+ ]:
725
+ for idx, line in enumerate(recs.get(key, []), start=1):
726
+ rows.append((key, section, f"{idx}. {line}"))
727
+ return rows
728
+
729
+
730
+ def render_recommendations_panel(recs: Dict[str, Any]) -> None:
731
+ st.caption(f"Source: {recs['source']} | Generated: {recs['generated_at']} UTC")
732
+ st.markdown("#### Recommended Path")
733
+ for x in recs["recommended_path"]:
734
+ st.write(f"- {x}")
735
+ st.markdown("#### Scope Adjustments")
736
+ for x in recs["scope_adjustments"]:
737
+ st.write(f"- {x}")
738
+ st.markdown("#### Risk Mitigations")
739
+ for x in recs["risk_mitigations"]:
740
+ st.write(f"- {x}")
741
+ st.info(recs["executive_call"])
742
+
743
+
744
+ def render_capacity_panel(capacity: Dict[str, Any]) -> None:
745
+ c1, c2, c3 = st.columns(3)
746
+ c1.metric("Current utilization", f"{capacity['current_utilization_pct']}%")
747
+ c2.metric("Projected utilization", f"{capacity['projected_utilization_pct']}%", f"+{capacity['utilization_delta_pct']}%")
748
+ c3.metric("Risk concentration", f"{capacity['risk_concentration_after_pct']}%", f"+{capacity['risk_concentration_delta_pct']}%")
749
+ st.progress(min(capacity["current_utilization_pct"] / 100, 1.0), text="Current")
750
+ st.progress(min(capacity["projected_utilization_pct"] / 100, 1.0), text="Projected")
751
+ st.write(
752
+ f"Current committed slots: **{capacity['current_committed_slots']}** / **{capacity['org_capacity_slots']}** | "
753
+ f"Projected committed slots: **{capacity['projected_committed_slots']}**"
754
  )
755
+ st.markdown("#### Portfolio bottleneck analysis")
756
+ st.warning(f"{capacity['portfolio_bottleneck']}: {capacity['portfolio_bottleneck_driver']}")
757
+
758
+
759
+ def gather_feedback(recs: Dict[str, Any]) -> List[Dict[str, Any]]:
760
+ items = []
761
+ for section_key, section, line in recommendation_rows(recs):
762
+ rid = f"{section_key}_{abs(hash(line))}"
763
+ a, b, c = st.columns([5, 1.5, 3])
764
+ with a:
765
+ st.write(line)
766
+ with b:
767
+ rating = st.radio("Rate", ["--", "πŸ‘", "πŸ‘Ž"], index=0, horizontal=True, key=f"rating_{rid}", label_visibility="collapsed")
768
+ with c:
769
+ note = st.text_input("Note", key=f"note_{rid}", placeholder="Optional note", label_visibility="collapsed")
770
+ items.append({"section_key": section_key, "section": section, "recommendation": line, "rating": rating, "note": note.strip()})
771
+ return items
772
+
773
+
774
+ def render_step3() -> None:
775
+ section_banner(3)
776
+ snapshot = st.session_state.get("scenario_snapshot")
777
+ recs = st.session_state.get("recommendations")
778
+ if not snapshot or not recs:
779
+ st.info("Complete Step 2 and generate recommendations to unlock this step.")
780
+ return
781
+ left, right = st.columns([1.3, 1])
782
+ with left:
783
+ render_recommendations_panel(recs)
784
+ with right:
785
+ render_capacity_panel(snapshot["capacity"])
786
+ st.markdown("#### Rate each recommendation and add notes")
787
+ feedback = gather_feedback(recs)
788
+ report_btn = st.button("Generate Report β†’", type="primary", use_container_width=True)
789
+ if report_btn:
790
+ report = {
791
+ "generated_at": datetime.utcnow().isoformat(),
792
+ "base_inputs": snapshot["baseline_inputs"],
793
+ "scenario_table": snapshot["scenario_df"].to_dict(orient="records"),
794
+ "recommendations": {
795
+ "source": recs["source"],
796
+ "recommended_path": recs["recommended_path"],
797
+ "scope_adjustments": recs["scope_adjustments"],
798
+ "risk_mitigations": recs["risk_mitigations"],
799
+ "executive_call": recs["executive_call"],
800
+ },
801
+ "feedback": feedback,
802
+ "capacity": snapshot["capacity"],
803
+ "similar_projects": snapshot["similar_df"].to_dict(orient="records"),
804
+ }
805
+ st.session_state["report"] = report
806
+ st.session_state["unlocked_step"] = max(st.session_state.get("unlocked_step", 1), 4)
807
+ st.success("Executive report generated.")
808
+
809
+
810
+ def render_step4() -> None:
811
+ section_banner(4)
812
+ report = st.session_state.get("report")
813
+ if not report:
814
+ st.info("Generate report in Step 3 to unlock executive output.")
815
  return
816
+ st.markdown("### Executive Summary")
817
+ b = report["base_inputs"]
818
+ st.write(
819
+ f"Simulation summary for **{b['project_name']}**: budget **${b['budget']:,.0f}**, team **{b['team_size']}**, "
820
+ f"timeline **{b['timeline_weeks']} weeks**, complexity **{b['scope_complexity']}**, dependencies **{b['dependencies']}**."
821
  )
822
+ st.markdown("### Scenario Comparison")
823
+ table = pd.DataFrame(report["scenario_table"]).copy()
824
+ table["Budget"] = table["Budget"].map(lambda x: f"${x:,.0f}")
825
+ table["Projected Margin %"] = table["Projected Margin %"].map(lambda x: f"{x}%")
826
+ table["Success Probability %"] = table["Success Probability %"].map(lambda x: f"{x}%")
827
+ st.dataframe(table, use_container_width=True, hide_index=True)
828
+ st.markdown("### Recommendations with Ratings")
829
+ ratings = pd.DataFrame(report["feedback"]).rename(columns={"recommendation": "Recommendation", "rating": "Rating", "note": "Note"})
830
+ st.dataframe(ratings[["section", "Recommendation", "Rating", "Note"]], use_container_width=True, hide_index=True)
831
+ cap = report["capacity"]
832
+ c1, c2, c3 = st.columns(3)
833
+ c1.metric("Current util.", f"{cap['current_utilization_pct']}%")
834
+ c2.metric("Projected util.", f"{cap['projected_utilization_pct']}%")
835
+ c3.metric("Risk concentration", f"{cap['risk_concentration_after_pct']}%")
836
+ st.info(f"Capacity impact: {cap['portfolio_bottleneck']} | {cap['portfolio_bottleneck_driver']}")
837
+ st.download_button(
838
+ "Download Report JSON",
839
+ data=json.dumps(report, indent=2, default=str).encode("utf-8"),
840
+ file_name="simulation_executive_report.json",
841
+ mime="application/json",
842
+ )
843
+ st.button("Start New Simulation", on_click=reset_all)
844
+
845
+
846
+ def locked_notice(step: int) -> None:
847
+ msg = {
848
+ 2: "Step 2 unlocks after running baseline simulation in Step 1.",
849
+ 3: "Step 3 unlocks after generating recommendations in Step 2.",
850
+ 4: "Step 4 unlocks after generating report in Step 3.",
851
+ }
852
+ st.info(msg[step])
853
+
854
+
855
+ def render_workflow(historical_df: pd.DataFrame) -> None:
856
+ t1, t2, t3, t4 = st.tabs(["1. Define Project", "2. Scenarios", "3. Recommendations", "4. Report"])
857
+ with t1:
858
+ render_step1()
859
+ with t2:
860
+ if st.session_state.get("unlocked_step", 1) < 2:
861
+ locked_notice(2)
862
+ else:
863
+ render_step2(historical_df)
864
+ with t3:
865
+ if st.session_state.get("unlocked_step", 1) < 3:
866
+ locked_notice(3)
867
+ else:
868
+ render_step3()
869
+ with t4:
870
+ if st.session_state.get("unlocked_step", 1) < 4:
871
+ locked_notice(4)
872
+ else:
873
+ render_step4()
874
+
875
+
876
+ def render_dataset(df: pd.DataFrame) -> None:
877
+ with st.expander("Historical dataset: data/historical_projects.csv", expanded=False):
878
  st.dataframe(df, use_container_width=True, hide_index=True)
 
 
 
 
 
 
 
879
 
880
 
881
  def main() -> None:
882
  initialize_state()
883
  historical_df = load_historical_data()
884
+ apply_style(st.session_state.get("unlocked_step", 1))
885
+ show_header()
886
+ render_workflow(historical_df)
887
+ render_dataset(historical_df)
 
 
 
 
 
888
 
889
 
890
  if __name__ == "__main__":