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