Spaces:
Paused
Paused
Update app.py
Browse files123413 unmodified lines1819202122232425262728292 unmodified lines323334353637383940414220 unmodified lines636465666768697081 unmodified lines15215315415515615715822 unmodified lines181182183184185186187188189190191192193171 unmodified lines36536636736836937037118 unmodified lines3903913923933943953966 unmodified lines4034044054064074084092 unmodified lines41241341441541641741875 unmodified lines49449549649749849950086 unmodified lines5875885895905915925931 unmodified line59559659759859960060160260361 unmodified lines66566666766866967067167267367467567690 unmodified lines7677687697707717727739 unmodified lines78378478578678778878953 unmodified lines8438448458468478488498508518525 unmodified lines858859860861862863864# app.py — ST_Sonic_Ts (Shear Slowness Ts)import io, json, os, base64, mathfrom pathlib import Path13 unmodified linesfrom sklearn.metrics import mean_squared_error, mean_absolute_error# =========================# Constants (Ts variant)# =========================APP_NAME = "ST_Log_Sonic (Ts)"TAGLINE = "Real-Time Shear Slowness (Ts) Prediction"# Defaults (overridden by ts_meta.json if present)FEATURES = ["WOB (klbf)","Torque (kft.lbf)",2 unmodified lines"ROP (ft/h)","Flow Rate (gpm)",]TARGET = "Ts (us/ft_Actual)"PRED_COL = "Ts_Pred"MODELS_DIR = Path("models")DEFAULT_MODEL = MODELS_DIR / "ts_model.joblib"MODEL_FALLBACKS = [MODELS_DIR / "model.joblib", MODELS_DIR / "model.pkl"]COLORS = {"pred": "#1f77b4", "actual": "#f2b702", "ref": "#5a5a5a"}20 unmodified lines.st-message-box.st-success { background-color: #d4edda; color: #155724; border-color: #c3e6cb; }.st-message-box.st-warning { background-color: #fff3cd; color: #856404; border-color: #ffeeba; }.st-message-box.st-error { background-color: #f8d7da; color: #721c24; border-color: #f5c6cb; }.main .block-container { overflow: unset !important; }div[data-testid="stVerticalBlock"] { overflow: unset !important; }div[data-testid="stExpander"] > details > summary {position: sticky; top: 0; z-index: 10; background: #fff; border-bottom: 1px solid #eee;}81 unmodified linesdef _build_alias_map(canonical_features: list[str], target_name: str) -> dict:"""Map common header variants -> the *canonical* names in canonical_features.Whatever appears in canonical_features (from ts_meta.json) wins."""def pick(expected_list, variants):for v in variants:22 unmodified lines# Depth (plot only)"Depth (ft)": can_DEPTH, "Depth, ft": can_DEPTH, "Depth(ft)": can_DEPTH, "DEPTH, ft": can_DEPTH,# Target family"Ts (us/ft_Actual)": target_name,"Ts,us/ft_Actual": target_name,"Ts, us/ft_Actual": target_name,"Ts": target_name,"TS_Actual": target_name,"Ts (us/ft)_Actual": target_name,}return alias171 unmodified linesif do_autofit:_excel_autofit(writer, sheet, df)bio.seek(0)fname = f"TS_Export_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"return bio.getvalue(), fname, order# --------- SIMPLE export UI ----------18 unmodified linesst.download_button(label="⬇️ Export Excel",data=b"",file_name="TS_Export.xlsx",mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",disabled=True,key=f"download_{phase_key}",6 unmodified linesst.download_button("⬇️ Export Excel",data=(data or b""),file_name=(fname or "TS_Export.xlsx"),mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",disabled=(data is None),key=f"download_{phase_key}",2 unmodified lines# =========================# Cross plot (Matplotlib)# =========================def cross_plot_static(actual, pred, xlabel="Actual Ts (µs/ft)", ylabel="Predicted Ts (µs/ft)"):a = pd.Series(actual, dtype=float)p = pd.Series(pred, dtype=float)75 unmodified lineslegend_title_text="")fig.update_xaxes(title_text="Ts (μs/ft)",title_font=dict(size=20, family=BOLD_FONT, color="#000"),tickfont=dict(size=15, family=BOLD_FONT, color="#000"),side="top", range=[xmin, xmax],86 unmodified linesmpath = ensure_model()if not mpath:st.error("Model not found. Upload models/ts_model.joblib (or set MODEL_URL).")st.stop()try:model = load_model(str(mpath))1 unmodified linest.error(f"Failed to load model: {e}")st.stop()# Load meta (prefer Ts-specific)meta = {}meta_candidates = [MODELS_DIR / "ts_meta.json", MODELS_DIR / "meta.json", MODELS_DIR / "ym_meta.json"]meta_path = next((p for p in meta_candidates if p.exists()), None)if meta_path:try:61 unmodified lines# =========================if st.session_state.app_step == "intro":st.header("Welcome!")st.markdown("This software is developed by *Smart Thinking AI-Solutions Team* to estimate **Shear Slowness (Ts)** from drilling data.")st.subheader("How It Works")st.markdown("1) **Upload your data to build the case and preview the model performance.** \n""2) Click **Run Model** to compute metrics and plots. \n""3) **Proceed to Validation** (with actual Ts) or **Proceed to Prediction** (no Ts).")if st.button("Start Showcase", type="primary"):st.session_state.app_step = "dev"; st.rerun()90 unmodified linesrender_export_button(phase_key="dev")# =========================# VALIDATION (with actual Ts)# =========================if st.session_state.app_step == "validate":st.sidebar.header("Validate the Model")9 unmodified linesif st.sidebar.button("⬅ Back to Case Building", use_container_width=True): st.session_state.app_step="dev"; st.rerun()if st.sidebar.button("Proceed to Prediction ▶", use_container_width=True): st.session_state.app_step="predict"; st.rerun()sticky_header("Validate the Model", "Upload a dataset with the same **features** and **Ts** to evaluate performance.")if go_btn and up is not None:book = read_book_bytes(up.getvalue())53 unmodified linesdf_centered_rounded(st.session_state.results["oor_tbl"])# =========================# PREDICTION (no actual Ts)# =========================if st.session_state.app_step == "predict":st.sidebar.header("Prediction (No Actual Ts)")up = st.sidebar.file_uploader("Upload Prediction Excel", type=["xlsx","xls"])if up is not None:book = read_book_bytes(up.getvalue())5 unmodified linesgo_btn = st.sidebar.button("Predict", type="primary", use_container_width=True)if st.sidebar.button("⬅ Back to Case Building", use_container_width=True): st.session_state.app_step="dev"; st.rerun()sticky_header("Prediction", "Upload a dataset with the feature columns (no **Ts**).")if go_btn and up is not None:book = read_book_bytes(up.getvalue()); name = list(book.keys())[0]123413 unmodified lines1819202122232425262728292 unmodified lines323334353637383940414220 unmodified lines636465666768697081 unmodified lines15215315415515615715822 unmodified lines181182183184185186187188189190191192193171 unmodified lines36536636736836937037118 unmodified lines3903913923933943953966 unmodified lines4034044054064074084092 unmodified lines41241341441541641741875 unmodified lines49449549649749849950086 unmodified lines5875885895905915925931 unmodified line59559659759859960060160260361 unmodified lines66566666766866967067167267367467567690 unmodified lines7677687697707717727739 unmodified lines78378478578678778878953 unmodified lines8438448458468478488498508518525 unmodified lines858859860861862863864# app_tc.py — ST_Sonic_Tc (Compressional Slowness Tc)import io, json, os, base64, mathfrom pathlib import Path13 unmodified linesfrom sklearn.metrics import mean_squared_error, mean_absolute_error# =========================# Constants (Tc variant)# =========================APP_NAME = "ST_Log_Sonic (Tc)"TAGLINE = "Real-Time Compressional Slowness (Tc) Prediction"# Defaults (overridden by tc_meta.json if present)FEATURES = ["WOB (klbf)","Torque (kft.lbf)",2 unmodified lines"ROP (ft/h)","Flow Rate (gpm)",]TARGET = "Tc (us/ft_Actual)"PRED_COL = "Tc_Pred"MODELS_DIR = Path("models")DEFAULT_MODEL = MODELS_DIR / "tc_model.joblib"MODEL_FALLBACKS = [MODELS_DIR / "model.joblib", MODELS_DIR / "model.pkl"]COLORS = {"pred": "#1f77b4", "actual": "#f2b702", "ref": "#5a5a5a"}20 unmodified lines.st-message-box.st-success { background-color: #d4edda; color: #155724; border-color: #c3e6cb; }.st-message-box.st-warning { background-color: #fff3cd; color: #856404; border-color: #ffeeba; }.st-message-box.st-error { background-color: #f8d7da; color: #721c24; border-color: #f5c6cb; }.main .block-container { overflow: unset !IMPORTANT; }div[data-testid="stVerticalBlock"] { overflow: unset !IMPORTANT; }div[data-testid="stExpander"] > details > summary {position: sticky; top: 0; z-index: 10; background: #fff; border-bottom: 1px solid #eee;}81 unmodified linesdef _build_alias_map(canonical_features: list[str], target_name: str) -> dict:"""Map common header variants -> the *canonical* names in canonical_features.Whatever appears in canonical_features (from tc_meta.json) wins."""def pick(expected_list, variants):for v in variants:22 unmodified lines# Depth (plot only)"Depth (ft)": can_DEPTH, "Depth, ft": can_DEPTH, "Depth(ft)": can_DEPTH, "DEPTH, ft": can_DEPTH,# Target family (Tc)"Tc (us/ft_Actual)": target_name,"Tc,us/ft_Actual": target_name,"Tc, us/ft_Actual": target_name,"Tc": target_name,"TC_Actual": target_name,"Tc (us/ft)_Actual": target_name,}return alias171 unmodified linesif do_autofit:_excel_autofit(writer, sheet, df)bio.seek(0)fname = f"TC_Export_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"return bio.getvalue(), fname, order# --------- SIMPLE export UI ----------18 unmodified linesst.download_button(label="⬇️ Export Excel",data=b"",file_name="TC_Export.xlsx",mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",disabled=True,key=f"download_{phase_key}",6 unmodified linesst.download_button("⬇️ Export Excel",data=(data or b""),file_name=(fname or "TC_Export.xlsx"),mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",disabled=(data is None),key=f"download_{phase_key}",2 unmodified lines# =========================# Cross plot (Matplotlib)# =========================def cross_plot_static(actual, pred, xlabel="Actual Tc (µs/ft)", ylabel="Predicted Tc (µs/ft)"):a = pd.Series(actual, dtype=float)p = pd.Series(pred, dtype=float)75 unmodified lineslegend_title_text="")fig.update_xaxes(title_text="Tc (μs/ft)",title_font=dict(size=20, family=BOLD_FONT, color="#000"),tickfont=dict(size=15, family=BOLD_FONT, color="#000"),side="top", range=[xmin, xmax],86 unmodified linesmpath = ensure_model()if not mpath:st.error("Model not found. Upload models/tc_model.joblib (or set MODEL_URL).")st.stop()try:model = load_model(str(mpath))1 unmodified linest.error(f"Failed to load model: {e}")st.stop()# Load meta (prefer Tc-specific)meta = {}meta_candidates = [MODELS_DIR / "tc_meta.json", MODELS_DIR / "meta.json"]meta_path = next((p for p in meta_candidates if p.exists()), None)if meta_path:try:61 unmodified lines# =========================if st.session_state.app_step == "intro":st.header("Welcome!")st.markdown("This software is developed by *Smart Thinking AI-Solutions Team* to estimate **Compressional Slowness (Tc)** from drilling data.")st.subheader("How It Works")st.markdown("1) **Upload your data to build the case and preview the model performance.** \n""2) Click **Run Model** to compute metrics and plots. \n""3) **Proceed to Validation** (with actual Tc) or **Proceed to Prediction** (no Tc).")if st.button("Start Showcase", type="primary"):st.session_state.app_step = "dev"; st.rerun()90 unmodified linesrender_export_button(phase_key="dev")# =========================# VALIDATION (with actual Tc)# =========================if st.session_state.app_step == "validate":st.sidebar.header("Validate the Model")9 unmodified linesif st.sidebar.button("⬅ Back to Case Building", use_container_width=True): st.session_state.app_step="dev"; st.rerun()if st.sidebar.button("Proceed to Prediction ▶", use_container_width=True): st.session_state.app_step="predict"; st.rerun()sticky_header("Validate the Model", "Upload a dataset with the same **features** and **Tc** to evaluate performance.")if go_btn and up is not None:book = read_book_bytes(up.getvalue())53 unmodified linesdf_centered_rounded(st.session_state.results["oor_tbl"])# =========================# PREDICTION (no actual Tc)# =========================if st.session_state.app_step == "predict":st.sidebar.header("Prediction (No Actual Tc)")up = st.sidebar.file_uploader("Upload Prediction Excel", type=["xlsx","xls"])if up is not None:book = read_book_bytes(up.getvalue())5 unmodified linesgo_btn = st.sidebar.button("Predict", type="primary", use_container_width=True)if st.sidebar.button("⬅ Back to Case Building", use_container_width=True): st.session_state.app_step="dev"; st.rerun()sticky_header("Prediction", "Upload a dataset with the feature columns (no **Tc**).")if go_btn and up is not None:book = read_book_bytes(up.getvalue()); name = list(book.keys())[0]
app.py+33-33