Update src/streamlit_app.py
Browse files22 unmodified lines2324252627282929303131323332333435363738394041424344454647484950515253543955565758594460614662636465108 unmodified lines17417517616117717816317918018118210 unmodified lines19319419518019619719819926 unmodified lines22622722821322923023123246 unmodified lines279280281282283267268269270271272273274275276277278279280281282283284285286287288289290291292293284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313266 unmodified lines5805815825835845855865 unmodified lines5925935945955965975981 unmodified line600601602603584604605606607146 unmodified lines75475575675775875976076176217 unmodified lines78078178276078378478578614 unmodified lines80180280378180480580680712 unmodified lines8208218228008238248258267 unmodified lines83483583681483783883984084181984284382184484584684784882582682782882984985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988083283388188288388488588688788888989089183683783883984084184289289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592622 unmodified lines# SHAPimport shap
# -------------------------# Config & paths# -------------------------st.set_page_config(page_title="AI Feature Universe Explorer β Advanced + SHAP", layout="wide")st.set_page_config(page_title="Steel Authority of India Limited (MODEX)", layout="wide")
# Use Hugging Face persistent path if availablePERSISTENT_DIR = "/data" if os.path.exists("/data") else "./data"DATA_DIR = os.getenv("DATA_DIR", PERSISTENT_DIR)# Base ephemeral paths (no Hugging Face data mount)BASE_DIR = "./"
LOG_DIR = os.path.join(BASE_DIR, "logs")DATA_DIR = os.path.join(LOG_DIR, "data_ephemeral")os.makedirs(DATA_DIR, exist_ok=True)os.makedirs(LOG_DIR, exist_ok=True)
# Timestamped log filetimestamp = datetime.now().strftime("%Y%m%d_%H%M%S")LOG_PATH = os.path.join(LOG_DIR, f"run_{timestamp}.log")
def log(msg: str): """Log message with timestamp to /logs/ for ephemeral HF runs.""" with open(LOG_PATH, "a", encoding="utf-8") as f: f.write(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] {msg}\n") print(msg)
log(" Streamlit session started.")log(f"Python PID={os.getpid()} | Time={datetime.now().isoformat()}")log(f"Data Dir = {DATA_DIR} | Log Dir = {LOG_DIR}")CSV_PATH = os.path.join(DATA_DIR, "flatfile_universe_advanced.csv")META_PATH = os.path.join(DATA_DIR, "feature_metadata_advanced.json")PDF_PATH = os.path.join(DATA_DIR, "annotated_bibliography.pdf")ENSEMBLE_ARTIFACT = os.path.join(DATA_DIR, "ensemble_models.joblib")
# Confirm storage mountif os.path.exists("/data"): st.sidebar.success(f"β
Using persistent storage: {DATA_DIR}") st.sidebar.success(f" Using persistent storage: {DATA_DIR}")else: st.sidebar.warning(f"β οΈ Using ephemeral storage: {DATA_DIR}. Data will be lost on rebuild.") st.sidebar.warning(f" Using ephemeral storage: {DATA_DIR}. Data will be lost on rebuild.")
# -------------------------108 unmodified lines
# timestamps & metadata start = pd.Timestamp("2025-01-01T00:00:00") df["timestamp"] = pd.date_range(start, periods=n_rows, freq="T") df["timestamp"] = pd.date_range(start, periods=n_rows, freq="min") df["cycle_minute"] = np.mod(np.arange(n_rows), 80) df["meta_plant_name"] = np.random.choice(["Rourkela","Jamshedpur","VSP","Bokaro","Kalinganagar","Salem"], n_rows) df["meta_plant_name"] = np.random.choice(["Rourkela","Bhilai","Durgapur","Bokaro","Burnpur","Salem"], n_rows) df["meta_country"] = "India"
# --- synthetic features: physics informed proxies10 unmodified lines if rc in df.columns: df[f"{rc}_roll_mean_3"] = df[rc].rolling(3, min_periods=1).mean() df[f"{rc}_roll_std_5"] = df[rc].rolling(5, min_periods=1).std().fillna(0) df[f"{rc}_lag1"] = df[rc].shift(1).fillna(method="bfill") df[f"{rc}_lag1"] = df[rc].shift(1).bfill() df[f"{rc}_roc_1"] = df[rc].diff().fillna(0)
# interaction & polynomial-lite26 unmodified lines
# surrogate models surrogate_df = df.copy() surrogate_df["furnace_temp_next"] = surrogate_df["furnace_temp"].shift(-1).fillna(method="ffill") surrogate_df["furnace_temp_next"] = surrogate_df["furnace_temp"].shift(-1).ffill() features_for_surrogate = [c for c in ["furnace_temp","arc_power","o2_probe_pct","offgas_co","offgas_co2"] if c in df.columns] if len(features_for_surrogate) >= 2: X = surrogate_df[features_for_surrogate].fillna(0)46 unmodified lines with open(META_PATH, "w") as f: json.dump(meta, f, indent=2)
PDF_PATH = None # annotated bibliography try: from fpdf import FPDF pdf = FPDF('P','mm','A4') pdf.add_page() pdf.set_font("Helvetica","B",14) pdf.cell(0,8,"Annotated Bibliography - Metallurgical AI (Selected Papers)", ln=True) pdf.ln(2) pdf.set_font("Helvetica","",10) pdf.cell(0,6,"Generated: " + datetime.utcnow().strftime("%Y-%m-%d %H:%M UTC"), ln=True) pdf.ln(4) bib_items = [ ("A Survey of Data-Driven Soft Sensing in Ironmaking Systems","Yan et al. (2024)","Review of soft-sensors; supports gas proxies, lags, PCA."), ("Optimisation of Oxygen Blowing Process using RL","Ojeda Roldan et al. (2022)","RL for oxygen control; motivates surrogate predicted states & safety indices."), ("Analyzing the Energy Efficiency of Electric Arc Furnace","Zhuo et al. (2024)","Energy KPIs (kWh/t) motivate power_density & energy_efficiency features."), ("BOF/Endpoint prediction techniques","Springer (2024)","Endpoint prediction; supports temporal lags and cycle encoding."), ("Dynamic EAF modeling & slag foaming","MacRosty et al.","Physics priors for slag_foaming_index and refractory health modeling.") ] for title, auth, note in bib_items: pdf.set_font("Helvetica","B",11) pdf.multi_cell(0,6, f"{title} β {auth}") pdf.set_font("Helvetica","",10) pdf.multi_cell(0,5, f"Notes: {note}") pdf.ln(2) pdf.output(PDF_PATH) except Exception as e: with open(PDF_PATH.replace(".pdf",".txt"), "w") as tf: tf.write("Annotated bibliography generated. Install fpdf for PDF output.\n") # try: # from fpdf import FPDF # pdf = FPDF('P','mm','A4') # pdf.add_page() # pdf.set_font("Helvetica","B",14) # pdf.cell(0,8,"Annotated Bibliography - Metallurgical AI (Selected Papers)", ln=True) # pdf.ln(2) # pdf.set_font("Helvetica","",10) # pdf.cell(0,6,"Generated: " + datetime.utcnow().strftime("%Y-%m-%d %H:%M UTC"), ln=True) # pdf.ln(4) # bib_items = [ # ("A Survey of Data-Driven Soft Sensing in Ironmaking Systems","Yan et al. (2024)","Review of soft-sensors; supports gas proxies, lags, PCA."), # ("Optimisation of Oxygen Blowing Process using RL","Ojeda Roldan et al. (2022)","RL for oxygen control; motivates surrogate predicted states & safety indices."), # ("Analyzing the Energy Efficiency of Electric Arc Furnace","Zhuo et al. (2024)","Energy KPIs (kWh/t) motivate power_density & energy_efficiency features."), # ("BOF/Endpoint prediction techniques","Springer (2024)","Endpoint prediction; supports temporal lags and cycle encoding."), # ("Dynamic EAF modeling & slag foaming","MacRosty et al.","Physics priors for slag_foaming_index and refractory health modeling.") # ] # for title, auth, note in bib_items: # pdf.set_font("Helvetica","B",11) # pdf.multi_cell(0,6, f"{title} β {auth}") # pdf.set_font("Helvetica","",10) # pdf.multi_cell(0,5, f"Notes: {note}") # pdf.ln(2) # pdf.output(PDF_PATH) # except Exception as e: # with open(PDF_PATH.replace(".pdf",".txt"), "w") as tf: # tf.write("Annotated bibliography generated. Install fpdf for PDF output.\n")
return CSV_PATH, META_PATH, PDF_PATH
266 unmodified lines # --- Run tuning across available families (user triggered) --- run_btn = st.button(" Run expanded AutoML + Stacking") if run_btn: log("AutoML + Stacking initiated.") with st.spinner("Tuning multiple families (this may take a while depending on choices)..."): families_to_try = ["RandomForest", "ExtraTrees", "MLP"] if allow_advanced:5 unmodified lines
tuned_results = [] for fam in families_to_try: log(f"Tuning family: {fam}") st.caption(f"Tuning family: {fam}") res = tune_family(fam, X, y, n_trials=max_trials) # res can be dict or single-run result; ensure consistent format1 unmodified line tuned_results.append(res) else: st.warning(f"Family {fam} returned unexpected tune result: {res}") log("All families tuned successfully.")
# build leaderboard DataFrame lb = pd.DataFrame([{"family": r["family"], "cv_r2": r["cv_score"], "params": r["best_params"]} for r in tuned_results]) lb = lb.sort_values("cv_r2", ascending=False).reset_index(drop=True)146 unmodified lines # Final evaluation final_r2 = r2_score(y_val, y_meta_pred) final_rmse = mean_squared_error(y_val, y_meta_pred, squared=False) st.success("AutoML + Stacking complete β metrics, artifacts, and SHAP ready.") log(f"Completed stacking. Final R2={final_r2:.4f}, RMSE={final_rmse:.4f}")
c1, c2 = st.columns(2) c1.metric("Stacked Ensemble RΒ² (holdout)", f"{final_r2:.4f}")17 unmodified lines "target": target, } joblib.dump(to_save, stack_artifact) st.caption(f"β
Stacked ensemble saved: {stack_artifact}") st.caption(f" Stacked ensemble saved: {stack_artifact}") # Explainability st.markdown("### Explainability (approximate)")14 unmodified lines except Exception as e: st.warning(f"SHAP computation skipped: {e}") st.success("β
AutoML + Stacking complete β metrics, artifacts, and SHAP ready.") st.success(" AutoML + Stacking complete β metrics, artifacts, and SHAP ready.")
12 unmodified lines ["Inventory & Yield Optimization", "yield_ratio (output/input)", "Linked to WIP and process yield", "βΉ1 Cr+/year"], ["Refractory & Cooling Loss Prediction", "lining_thickness / heat_loss_rate", "Predict wear for planned maintenance", "βΉ40 L/year downtime savings"]], columns=["Use Case", "Target Variable", "Why Itβs Ideal", "Business Leverage"])
st.dataframe(target_table, use_container_width=True) st.dataframe(target_table, width="stretch")
st.markdown("---") st.subheader("Business Framing for Clients")7 unmodified lines ["Yield loss", "2 %", "βΉ50 L β βΉ1 Cr"], ], columns=["Metric", "Typical Value (EAF India)", "5 % Improvement β Annual βΉ Value"])
st.dataframe(business_table, use_container_width=True) st.dataframe(business_table, width="stretch") st.info("These numbers are indicative averages; actual benefits depend on plant capacity and process efficiency.")
# ----- Bibliography tab with tabs[6]: st.subheader("Annotated Bibliography & Feature Justification") st.subheader("Annotated Bibliography β Justification for Target Variables") st.markdown("""This section summarizes published research supporting the feature design and modeling choices.These papers justify the chosen target variables (temperature, yield, efficiency, refractory wear)in metallurgical AI modeling. Click any title to open the official paper. """)
bib_data = [ ("A Survey of Data-Driven Soft Sensing in Ironmaking Systems", "Yan et al. (2024)", "Supports gas proxies, lags, PCA for off-gas and temperature correlation."), ("Optimisation of Oxygen Blowing Process using RL", "Ojeda Roldan et al. (2022)", "Reinforcement learning for oxygen control; motivates surrogate predicted states & safety indices."), ("Analyzing the Energy Efficiency of Electric Arc Furnace", "Zhuo et al. (2024)", "Energy KPIs (kWh/t) motivate power_density & energy_efficiency features."), ("BOF/Endpoint Prediction Techniques", "Springer (2024)", "Endpoint prediction; supports temporal lags and cycle encoding."), ("Dynamic EAF Modeling & Slag Foaming", "MacRosty et al.", "Physics priors for slag_foaming_index and refractory health modeling."), { "title": "A Survey of Data-Driven Soft Sensing in Ironmaking Systems", "authors": "Yan et al. (2024)", "notes": "Soft sensors for furnace and tap temperature; validates `furnace_temp` and `tap_temp` targets.", "url": "https://doi.org/10.1021/acsomega.4c01254" }, { "title": "Optimisation of Operator Support Systems through Artificial Intelligence for the Cast Steel Industry", "authors": "Ojeda RoldΓ‘n et al. (2022)", "notes": "Reinforcement learning for oxygen blowing and endpoint control; supports temperature and carbon targets.", "url": "https://doi.org/10.3390/jmmp6020034" }, { "title": "Analyzing the Energy Efficiency of Electric Arc Furnace Steelmaking", "authors": "Zhuo et al. (2024)", "notes": "Links arc power, temperature, and energy KPIs β validates `energy_efficiency` and `power_density`.", "url": "https://doi.org/10.3390/met15010113" }, { "title": "Dynamic EAF Modeling and Slag Foaming Index Prediction", "authors": "MacRosty et al.", "notes": "Supports refractory and heat-flux-based wear prediction β validates `lining_thickness` target.", "url": "https://www.sciencedirect.com/science/article/pii/S0921883123004019" }, { "title": "Machine Learning for Yield Optimization in Continuous Casting", "authors": "Springer (2023)", "notes": "ML for yield ratio and defect minimization; supports `yield_ratio` target.", "url": "https://link.springer.com/article/10.1007/s40964-023-00592-7" } ]
bib_df = pd.DataFrame(bib_data, columns=["Paper Title", "Authors / Year", "Relevance to Feature Engineering"]) st.dataframe(bib_df, use_container_width=True) bib_df = pd.DataFrame(bib_data) bib_df["Paper Title"] = bib_df.apply(lambda x: f"[{x['title']}]({x['url']})", axis=1)
st.dataframe( bib_df[["Paper Title", "authors", "notes"]] .rename(columns={"authors": "Authors / Year", "notes": "Relevance"}), width="stretch", hide_index=True )
st.markdown("""**Feature-to-Research Mapping Summary:**- Gas probes & soft-sensing β `carbon_proxy`, `oxygen_utilization`- Power & energy proxies β `power_density`, `energy_efficiency`- Temporal features β rolling means, lags, cycle progress indicators- Surrogate features β `pred_temp_30s`, `pred_carbon_5min`- PCA / clustering β operating mode compression""")**Feature β Target Justification**- `furnace_temp`, `tap_temp` β Process temperature (Yan 2024, Ojeda 2022) - `yield_ratio` β Production yield (Springer 2023) - `energy_efficiency`, `power_density` β Energy KPIs (Zhuo 2024) - `lining_thickness`, `slag_foaming_index` β Refractory & process health (MacRosty et al.) """)
st.info("Click any paper title above to open it in a new tab.") log("Bibliography tab rendered successfully.")
# -------------------------# Footer / Notes# -------------------------st.markdown("---")st.markdown("**Notes:** This dataset is synthetic and for demo/prototyping. Real plant integration requires NDA, data on-boarding, sensor mapping, and plant safety checks before any control actions.")# ----- Logs tabtabs.append("View Logs")with tabs[-1]: st.subheader("π Session & Model Logs") st.markdown("Each run creates a timestamped log file in `/logs/` inside this Space. Use this panel to review run progress and debug output.")
log_files = sorted( [f for f in os.listdir(LOG_DIR) if f.endswith(".log")], reverse=True )
if not log_files: st.info("No logs yet. Run an AutoML job first.") else: latest = st.selectbox("Select log file", log_files, index=0) path = os.path.join(LOG_DIR, latest) with open(path, "r", encoding="utf-8") as f: content = f.read() st.text_area("Log Output", content, height=400) st.download_button("β¬οΈ Download Log", content, file_name=latest)src/streamlit_app.py+138-59