Spaces:
Sleeping

FamDLike / app.py
yucelmehmet's picture
Update the title in app.py
e0865d5 verified
Raw History Blame Contribute Delete
9.19 kB
import os
from pathlib import Path
os.environ.setdefault("FAMLIKE_DATA_PATH", str(Path(__file__).resolve().parent))
import streamlit as st
import pandas as pd
from main import PredictDrugLikeness
import plotly.express as px
import plotly.graph_objects as go
import re
from rdkit import Chem
from rdkit.Chem import Draw
svg_config = {
'toImageButtonOptions': {
'format': 'svg', # one of png, svg, jpeg, webp
'filename': 'famlike_custom_plot',
'height': 500,
'width': 700,
'scale': 1
}
}
def create_style_boxplot(df, columns, title, short_names_dict):
fig = go.Figure()
palette = px.colors.qualitative.Dark24
unique_fams = list(short_names_dict.values())
color_map = {fam: palette[i % len(palette)] for i, fam in enumerate(unique_fams)}
bg_color = "rgba(245, 247, 250, 0.5)"
for col in columns:
raw_family = col
# 1. Clean suffixes (e.g., "Oxidoreductase_DrugLikeness_Score" -> "Oxidoreductase")
raw_family = re.sub(r'_druglikeness_score', '', raw_family, flags=re.IGNORECASE)
raw_family = re.sub(r'_desirability', '', raw_family, flags=re.IGNORECASE)
raw_family = re.sub(r'_gam_prob', '', raw_family, flags=re.IGNORECASE)
# Remove prefix smoothly
raw_family = re.sub(r'ensemble_prob_', '', raw_family, flags=re.IGNORECASE)
display_name = short_names_dict.get(raw_family, raw_family)
assigned_col = color_map.get(display_name, "#3A506B")
fig.add_trace(
go.Box(
y=df[col],
name=display_name,
boxpoints="outliers",
marker=dict(color=assigned_col, size=4),
fillcolor = assigned_col,
line= dict(color=assigned_col, width=1.5),
showlegend=False
)
)
fig.update_layout(
title=dict(text=title, font=dict(size=18, family = "Helvetica Neue, sans-serif", color="#1C2541"), x=0),
margin=dict(l=50, r=30, t=60, b=60),
height = 420,
plot_bgcolor=bg_color,
paper_bgcolor="rgba(0,0,0,0)",
yaxis=dict(gridcolor='white', gridwidth=2, zeroline=False, tickfont=dict(color="#4A5568", size=12)),
xaxis=dict(
tickfont=dict(color="#4A5568", size=12, family="Helvetica Neue", weight="bold"),
tickangle=-30)
)
return fig
st.set_page_config(page_title="FamDLike", page_icon="πŸ§ͺ", layout="wide")
st.title("πŸ§ͺ FamDLike β€” Family Druglikeness Scorer")
st.caption("Target Family Specific Druglikeness Score using Desirability Functions (ADS), GAMs, and Tree Models")
@st.cache_resource(show_spinner="Loading models (one-time)...")
def get_warm_predictor(use_tree, use_gams):
dummy = pd.DataFrame({"SMILES": ["CC(=O)Nc1ccc(O)cc1"]})
return PredictDrugLikeness(
df=dummy,
calc_desc=False,
tree_models=use_tree,
use_gams=use_gams
)
short_names = {
"Kinase": "Kinase",
"Monoamine_GPCR": "Mono.GPCR",
"Lipid_GPCR": "Lipid GPCR",
"Nuclear_Rec": "Nuclear",
"Nucleotid_GPCR": "Nucl.GPCR",
"Peptide_GPCR": "Pep.GPCR",
"Protease": "Protease",
"Epigenetic_Reg": "Epigenetic Reg.",
"Voltage_Ion": "Volt.Ion",
"Ligand_Ion": "Lig.Ion",
"Hydrolase_Viral":"Hydrolase (Viral)",
'Oxidoreductase': "Oxidoreductase",
}
with st.sidebar:
st.header("Settings")
use_desirability = st.checkbox("Family Desirability functions", value=True)
use_tree = st.checkbox("Tree models (RF + XGBoost)", value=True)
use_gams = st.checkbox("GAM models", value=True)
visualize_FamLike = st.checkbox("Visualize FamLike Score distribution", value=True)
visualize_ADS_Prob = st.checkbox("Visualize Family Desirability Scores (FDS)", value=True)
visualize_Tree_Prob = st.checkbox("Visualize Tree model probabilities", value=True)
visualize_GAM_Prob = st.checkbox("Visualize GAM model probabilities", value=True)
n_cores = st.slider("CPU cores (descriptor calc)", 1, 8, 2)
input_mode = st.radio("Input method", ["Single SMILES", "Upload CSV"])
df_in = None
smi = ""
if input_mode == "Single SMILES":
smi = st.text_input("Enter SMILES", "CC(=O)Oc1ccccc1C(=O)O")
if smi.strip():
mol = Chem.MolFromSmiles(smi.strip())
if mol is None:
st.error("⚠️ Invalid SMILES β€” please check your input")
else:
df_in = pd.DataFrame({"SMILES": [smi.strip()]})
st.image(Draw.MolToImage(mol, size=(300, 300)), caption="Input molecule")
else: # Upload CSV
uploaded = st.file_uploader("Upload CSV (must contain \"SMILES\" column)", type="csv")
if uploaded:
df_in = pd.read_csv(uploaded)
st.write(f"Loaded {len(df_in)} rows")
if len(df_in) > 50:
st.info(f"Processing {len(df_in)} molecules β€” this may take a moment...")
st.dataframe(df_in.head())
if st.button("Predict", type="primary") and df_in is not None:
warm = get_warm_predictor(use_tree, use_gams)
# Reuse loaded models, swap in user data
warm.df = df_in.copy()
warm.calc_desc = True
warm.n_cores = n_cores
with st.spinner("Calculating descriptors and running models..."):
try:
results = warm.predict()
st.success(f"Done β€” {len(results)} molecules processed")
# Show score columns prominently
score_cols = [c for c in results.columns if "DrugLikeness_Score" in c]
if score_cols and len(results) == 1:
best_fam = results[score_cols].iloc[0].idxmax()
best_score = results[score_cols].iloc[0].max()
clean_name = best_fam.replace("_DrugLikeness_Score", "")
st.metric(
"🎯 Best Target Family",
short_names.get(clean_name, clean_name),
f"Score: {best_score:.3f}"
)
if score_cols:
st.subheader("Druglikeness Scores")
display_cols = (
[c for c in results.columns if c.lower() in ("smiles", "canonical_smiles")]
+ score_cols
)
st.dataframe(
results[display_cols].style.background_gradient(
subset=score_cols, cmap="RdYlGn", vmin=0, vmax=1
).format({col: "{:.3f}" for col in score_cols})
)
if len(results) == 1 and score_cols:
values = results[score_cols].iloc[0].values
labels = [short_names.get(c.replace("_DrugLikeness_Score",""), c) for c in score_cols]
fig = go.Figure(go.Scatterpolar(r=values, theta=labels, fill='toself'))
fig.update_layout(polar=dict(radialaxis=dict(range=[0,1])), title="Family Profile")
st.plotly_chart(fig)
with st.expander("Full results (all columns)"):
st.dataframe(results)
# 1. Drug-likeness Scores Distribution
if visualize_FamLike:
score_cols = [c for c in results.columns if "DrugLikeness_Score" in c]
if score_cols:
st.subheader("Distribution of FamLike Scores")
fig = create_style_boxplot(results, score_cols, "FamLike Scores", short_names)
st.plotly_chart(fig,config=svg_config, width='stretch')
# 2. Desirability Scores
if visualize_ADS_Prob:
ads_cols = [c for c in results.columns if "Desirability" in c]
if ads_cols:
st.subheader("Desirability Scores")
fig = create_style_boxplot(results, ads_cols, "Desirability Scores (ADS)", short_names)
st.plotly_chart(fig,config=svg_config, width='stretch')
# 3. Tree Model Probabilities
if visualize_Tree_Prob and use_tree:
tree_cols = [c for c in results.columns if "Ensemble_Prob" in c]
if tree_cols:
st.subheader("Tree Model Probabilities")
fig = create_style_boxplot(results, tree_cols, "Tree Model Target Probabilities", short_names)
st.plotly_chart(fig,config=svg_config, width='stretch')
# 4. GAM Model Probabilities
if visualize_GAM_Prob and use_gams:
gam_cols = [c for c in results.columns if "GAM_Prob" in c]
if gam_cols:
st.subheader("GAM Model Probabilities")
fig = create_style_boxplot(results, gam_cols, "GAM Model Target Probabilities", short_names)
st.plotly_chart(fig,config=svg_config, width='stretch')
st.download_button(
"πŸ“₯ Download results CSV",
results.to_csv(index=False).encode(),
"famlike_scores.csv",
"text/csv",
)
except Exception as e:
st.error(f"Prediction failed: {e}")
elif df_in is None:
st.info("Provide a SMILES or upload a CSV to begin.")