Update src/streamlit_app.py
Browse files760 unmodified lines761762763764765760 unmodified lineselse:st.info("No logs yet — run AutoML once.")st.markdown("---")st.markdown("**Note:** Synthetic demo dataset for educational use only. Real deployment requires plant data, NDA, and safety validation.")760 unmodified lines761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059760 unmodified lineselse:st.info("No logs yet — run AutoML once.")# ----- Smart Advisor tab (Role-based Insights)with tabs[9]:st.subheader(" Smart Advisor — Role-Based Insights")# -------------------------# 1. Role hierarchy and descriptions# -------------------------roles = {# --- Ground-level ---"Furnace Operator": "Runs daily EAF heats, manages electrodes, slag foaming, and tap timing.","Shift Engineer": "Coordinates furnace, casting, and maintenance operations during the shift.","Process Metallurgist": "Optimizes chemistry, refining, and metallurgical balance across heats.","Maintenance Engineer": "Monitors vibration, bearings, and schedules preventive maintenance.","Quality Engineer": "Tracks billet surface, composition, and defect rates from casting to rolling.",# --- Mid-level / Plant ---"Energy Manager": "Analyzes power, load factor, and energy cost per ton of steel.","Production Head": "Supervises throughput, yield, and adherence to shift-level production targets.","Reliability Manager": "Oversees equipment reliability, predictive maintenance, and downtime prevention.","Chief Process Engineer": "Links metallurgical parameters to standard operating conditions.","Process Optimization Head (PP&C)": "Balances yield, power, and reliability across EAF, caster, and rolling units.","Chief General Manager – PP&C": "Oversees planning, process, and control at plant level — coordinating all shops for optimal energy, yield, and reliability.","Deputy General Manager (Operations)": "Supervises multi-shop coordination, productivity, and manpower scheduling.","Plant Head": "Oversees plant-wide KPIs — production, energy, quality, and modernization progress.",# --- Strategic / Corporate ---"Executive Director (Works)": "Integrates operations, people, and safety across all plants.","Chief Operating Officer (COO)": "Ensures alignment between production efficiency and business goals.","Chief Sustainability Officer (CSO)": "Monitors CO₂ intensity, waste recovery, and environmental compliance.","Chief Financial Officer (CFO)": "Links operational performance to cost efficiency and ROI.","Chief Executive Officer (CEO)": "Focuses on long-term performance, modernization, and shareholder impact."}# -------------------------# 2. Role-specific reasoning prompts for LLM# -------------------------role_prompts = {"Furnace Operator": """You are the EAF furnace operator responsible for maintaining a stable arc and safe melting.Translate model recommendations into clear, actionable controls: electrode movement, oxygen flow,slag foaming, or power adjustment. Focus on operational safety and tap timing.""","Shift Engineer": """You are the shift engineer overseeing melting, casting, and maintenance coordination.Interpret model insights for operational actions — mention if inter-shop coordination is required.""","Process Metallurgist": """You are the process metallurgist. Evaluate the data-driven SHAP patterns to interpret metallurgicalbalance, oxidation behavior, and refining efficiency. Suggest chemistry or process tuning.""","Maintenance Engineer": """You are the maintenance engineer responsible for reliability. Identify potential failure risks(e.g., vibration anomalies, overheating, current imbalance) and propose proactive checks.""","Quality Engineer": """You are the quality engineer monitoring casting and rolling outcomes. Translate process variablesinto expected surface or composition quality impacts and preventive measures.""","Energy Manager": """You are the energy manager. Interpret how SHAP signals influence energy per ton and power factor.Quantify efficiency deviations and suggest scheduling or load adjustments.""","Production Head": """You are the production head tracking yield and throughput. Connect SHAP insights to bottlenecksin productivity, heat timing, or equipment utilization. Suggest optimization steps.""","Reliability Manager": """You are the reliability manager. Evaluate if process trends suggest equipment stress, overheating,or wear. Recommend intervention plans and projected downtime avoidance.""","Chief Process Engineer": """You are the chief process engineer. Convert SHAP outputs into process standardization insights.Flag anomalies that require SOP review and coordinate with metallurgical and control teams.""","Process Optimization Head (PP&C)": """You are the Process Optimization Head in PP&C. Assess SHAP signals across multiple units to improvesystem-level yield, energy, and reliability. Recommend balanced actions and inter-shop alignment.""","Chief General Manager – PP&C": """You are the Chief General Manager (PP&C) responsible for overall plant coordination,planning, process control, and modernization. Interpret model insights as if briefingsenior management and section heads before a shift review.Your response must:- Translate technical terms into operational themes (e.g., “arc instability”)- Identify cross-functional effects (EAF ↔ Caster ↔ Rolling)- Suggest coordination steps (maintenance, power, metallurgist)- Conclude with KPI or strategic impact (yield, energy, reliability)- If any data pattern seems implausible, mention it and propose review.""","Deputy General Manager (Operations)": """You are the DGM (Operations). Summarize SHAP-derived insights into actionable instructionsfor shop heads. Emphasize throughput, manpower planning, and heat plan adherence.""","Plant Head": """You are the Plant Head. Translate technical findings into KPI performance trends and upcomingoperational risks. Recommend cross-departmental actions and expected impact on production targets.""","Executive Director (Works)": """You are the Executive Director (Works). Summarize how the plant is performing overall and whereimmediate leadership attention is required. Use a governance-level tone, referencing key KPIs.""","Chief Operating Officer (COO)": """You are the COO. Interpret model insights at a strategic level — efficiency, tonnage, cost, reliability.Highlight systemic improvements, risk areas, and financial implications across plants.""","Chief Sustainability Officer (CSO)": """You are the CSO. Relate operational insights to environmental impact, carbon efficiency,and sustainability metrics. Quantify potential emission reduction.""","Chief Financial Officer (CFO)": """You are the CFO. Interpret operational SHAP findings in terms of cost efficiency, asset utilization,and ROI. Provide an executive financial perspective on potential savings or risks.""","Chief Executive Officer (CEO)": """You are the CEO of a major integrated steel producer.Provide a concise narrative (2–3 paragraphs) summarizing plant performance trends,operational risks, and opportunities — linking them to strategic goals in the annual report:productivity, sustainability, cost leadership, and modernization."""}# -------------------------# 3. Role selection and contextual info# -------------------------role = st.selectbox("Select Your Role", list(roles.keys()), index=10)st.caption(f" Context: {roles[role]}")if "recs" not in locals() or not isinstance(recs, list) or not recs:st.warning("Please run the AutoML + SHAP step first to generate recommendations.")else:if st.button("Generate Role-Based Advisory"):HF_TOKEN = os.getenv("HF_TOKEN")if not HF_TOKEN:st.error("HF_TOKEN not found. Please set it as an environment variable or in secrets.toml.")else:import requests, textwrapAPI_URL = "https://router.huggingface.co/v1/chat/completions"headers = {"Authorization": f"Bearer {HF_TOKEN}", "Content-Type": "application/json"}# Add CGM-style reasoning context for cross-functional rolesif role in ["Chief General Manager – PP&C", "Process Optimization Head (PP&C)", "Plant Head"]:reasoning_context = """Think like a systems integrator balancing EAF, caster, and rolling mill performance.Evaluate interdependencies and recommend coordinated actions across departments."""elif role in ["COO", "CFO", "CEO"]:reasoning_context = """Think strategically. Connect operational drivers to business KPIs,and quantify financial or sustainability implications."""else:reasoning_context = ""# Build final promptprompt = textwrap.dedent(f"""Role: {role}Use case: {use_case}Target variable: {target}Ensemble model confidence (R²): {final_r2:.3f}{reasoning_context}Model-derived recommendations:{json.dumps(recs, indent=2)}{role_prompts.get(role, "Provide a professional metallurgical advisory summary.")}Your response should cover:1. What’s happening (interpreted simply)2. What should be done3. What outcomes to expect and why""")payload = {"model": "meta-llama/Meta-Llama-3-8B-Instruct","messages": [{"role": "system", "content": "You are a multi-role metallurgical advisor connecting data to human decisions."},{"role": "user", "content": prompt}],"temperature": 0.4,"max_tokens": 350,}with st.spinner(f"Generating role-based advisory for {role}..."):resp = requests.post(API_URL, headers=headers, json=payload, timeout=90)if resp.status_code == 200:data = resp.json()msg = (data.get("choices", [{}])[0].get("message", {}).get("content", "").strip())if msg:st.markdown(f"### Advisory for {role}")st.info(msg)# ---- Dynamic Data-Driven Highlights ----if role in ["Chief General Manager – PP&C", "Plant Head", "Process Optimization Head (PP&C)"]:st.markdown("#### 🔍 Shift Highlights — Data-Driven Summary")try:# 1️⃣ Latest data snapshot (simulates "current shift")latest_df = df.tail(500).copy() # last 500 rows = current shift snapshot# 2️⃣ Basic KPIs computed from live datafurnace_temp_mean = latest_df["furnace_temp"].mean()furnace_temp_std = latest_df["furnace_temp"].std()energy_eff_mean = latest_df["energy_efficiency"].mean()yield_mean = latest_df["yield_ratio"].mean()downtime_proxy = np.mean(latest_df["refractory_limit_flag"]) * 8 # hours/shift (proxy)# 3️⃣ Compare vs historical baseline (previous 500 rows)if len(df) > 1000:prev_df = df.tail(1000).head(500)delta_temp = ((furnace_temp_mean - prev_df["furnace_temp"].mean()) /prev_df["furnace_temp"].mean()) * 100delta_eff = ((energy_eff_mean - prev_df["energy_efficiency"].mean()) /prev_df["energy_efficiency"].mean()) * 100delta_yield = ((yield_mean - prev_df["yield_ratio"].mean()) /prev_df["yield_ratio"].mean()) * 100else:delta_temp, delta_eff, delta_yield = 0, 0, 0# 4️⃣ Qualitative interpretationdef trend_symbol(val):if val > 0.5:return f"↑ +{val:.2f}%"elif val < -0.5:return f"↓ {val:.2f}%"else:return f"→ {val:.2f}%"# 5️⃣ Build structured tablehighlights = pd.DataFrame([["Furnace Temp Stability","Stable" if furnace_temp_std < 50 else "Fluctuating",f"Avg: {furnace_temp_mean:.1f}°C ({trend_symbol(delta_temp)})"],["Energy Efficiency","Improved" if delta_eff > 0 else "Declined",f"{energy_eff_mean:.4f} ({trend_symbol(delta_eff)})"],["Yield Ratio","Nominal" if abs(delta_yield) < 1 else ("↑" if delta_yield > 0 else "↓"),f"{yield_mean*100:.2f}% ({trend_symbol(delta_yield)})"],["Refractory Limit Flag","Within Safe Limit" if downtime_proxy < 1 else "Check Lining",f"Active Alerts: {downtime_proxy:.1f}/shift"]], columns=["Parameter", "Status", "Observation"])st.dataframe(highlights, use_container_width=True)st.caption("Derived from live dataset trends (last 500 vs previous 500 rows).")# 6️⃣ Optional: Link to SHAP recs for validationif isinstance(recs, list) and recs:st.markdown("#### 🧭 Cross-Verification with SHAP Insights")matches = [r for r in recs if any(k in r for k in ["furnace", "energy", "yield", "slag", "power"])]if matches:st.info("Aligned SHAP Recommendations:\n\n- " + "\n- ".join(matches))else:st.warning("No direct SHAP alignment found — potential anomaly or unseen pattern.")except Exception as e:st.warning(f"Shift Highlights unavailable: {e}")else:st.warning(f"Empty response.\nRaw: {data}")else:st.error(f"HF API error {resp.status_code}: {resp.text}")# -------------------------# 4. Optional role-based KPIs# -------------------------if role == "Chief General Manager – PP&C":col1, col2, col3 = st.columns(3)col1.metric("Plant Yield (Rolling 24h)", "96.8%", "↑0.7% vs yesterday")col2.metric("Energy per ton", "4.92 MWh/t", "↓2.3% week-on-week")col3.metric("Unplanned Downtime", "3.1 hrs", "↓1.2 hrs")st.caption("KPIs aligned with PP&C Balanced Scorecard — Yield • Energy • Reliability")elif role in ["CEO", "COO"]:col1, col2, col3 = st.columns(3)col1.metric("EBITDA per ton", "₹7,420", "↑3.1% QoQ")col2.metric("CO₂ Intensity", "1.79 tCO₂/t", "↓2.4% YoY")col3.metric("Modernization CapEx", "₹122 Cr", "On track")st.caption("Strategic alignment: cost leadership • sustainability • modernization")elif role in ["Furnace Operator", "Shift Engineer"]:col1, col2, col3 = st.columns(3)col1.metric("Furnace Temp", f"{df['furnace_temp'].iloc[-1]:.1f} °C")col2.metric("Arc Power", f"{df['arc_power'].iloc[-1]:.0f} kW")col3.metric("Power Factor", f"{df['power_factor'].iloc[-1]:.2f}")st.caption("Live operational parameters — monitor stability and foaming balance.")st.markdown("---")st.markdown("**Note:** Synthetic demo dataset for educational use only. Real deployment requires plant data, NDA, and safety validation.")
src/streamlit_app.py+294