arcalab's picture
Upload folder using huggingface_hub
fd9b733 verified
Raw History Blame Contribute Delete
41.4 kB
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()