Spaces:
Sleeping
Sleeping
File size: 8,072 Bytes
4f98c07 f2302fc 0a13e0b f2302fc 0a13e0b 14e95ac 0a13e0b 4f98c07 0a13e0b 67abe4f 4f98c07 f2302fc 67abe4f aefd0c0 67abe4f f2302fc 4f98c07 f2302fc 4f98c07 0a13e0b f2302fc 4f98c07 f2302fc 0a13e0b f2302fc 4f98c07 0a13e0b 4f98c07 f2302fc 629f8df 4f98c07 0a13e0b f2302fc 0a13e0b 4f98c07 0a13e0b 4f98c07 0a13e0b 06b2426 4f98c07 0a13e0b 67abe4f aefd0c0 f2302fc 06b2426 4f98c07 67abe4f 4f98c07 f2302fc 4f98c07 0a13e0b 4f98c07 06b2426 4f98c07 0a13e0b 4f98c07 f2302fc 06b2426 f2302fc 0a13e0b 67abe4f 06b2426 67abe4f 4f98c07 67abe4f 06b2426 67abe4f 4f98c07 06b2426 4f98c07 67abe4f f2302fc 4f98c07 f2302fc 0a13e0b 06b2426 4f98c07 0a13e0b 4f98c07 0a13e0b 4f98c07 06b2426 4f98c07 0a13e0b 4f98c07 f2302fc 06b2426 f2302fc 0a13e0b f2302fc 06b2426 0a13e0b 4f98c07 0a13e0b 4f98c07 f2302fc 4f98c07 06b2426 4f98c07 f2302fc 06b2426 f2302fc 0a13e0b 06b2426 0a13e0b 4f98c07 f2302fc 4f98c07 06b2426 97fec9a 06b2426 c9c4aaf 0a13e0b 06b2426 f2302fc 06b2426 0a13e0b 06b2426 a1db08b 06b2426 f2302fc 4f98c07 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 | import os
import json
import traceback
import joblib
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import shap
import gradio as gr
# ============================================================
# PATCH: Fix gradio_client boolean JSON-schema crash
# ============================================================
try:
import gradio_client.utils as _gcu
if hasattr(_gcu, "_json_schema_to_python_type"):
_orig = _gcu._json_schema_to_python_type
def _patched(schema, defs=None):
# JSON Schema allows boolean schemas (True / False)
if isinstance(schema, bool):
return "Any"
return _orig(schema, defs)
_gcu._json_schema_to_python_type = _patched
except Exception:
pass
# ============================================================
# Artifacts
# ============================================================
MODEL_PATH = "model_extratrees_ds4.joblib"
FEATS_PATH = "feature_names.json"
model = joblib.load(MODEL_PATH)
with open(FEATS_PATH) as f:
FEATURES = json.load(f)
LABEL_NAME = {0: "Benign", 1: "Pathogenic"}
THRESHOLD = 0.7
ID_CANDIDATES = [
"#Uploaded_Variation", "#Uploaded_variation", "uploaded_variation",
"Uploaded_Variation", "Uploaded_variation", "variant_id",
"Variant_ID", "variation_id", "Variant", "ID", "HGVSc", "HGVSp"
]
# ============================================================
# Helpers
# ============================================================
def _clean_headers(df):
df.columns = (
df.columns.astype(str)
.str.replace(r"[\u200b\ufeff]", "", regex=True)
.str.strip()
)
return df
def _read_table(file):
name = getattr(file, "name", str(file))
if name.lower().endswith((".xlsx", ".xls")):
df = pd.read_excel(name, engine="openpyxl")
else:
df = pd.read_csv(
name,
engine="python",
sep=None,
dtype=str,
na_values=["", "NA", "N/A"],
quoting=3,
on_bad_lines="skip",
encoding_errors="ignore",
)
return _clean_headers(df)
def _coerce_numeric(df):
for c in df.columns:
df[c] = pd.to_numeric(df[c], errors="coerce")
return df
def _prepare(df):
for c in FEATURES:
if c not in df.columns:
df[c] = np.nan
return _coerce_numeric(df[FEATURES].copy())
def _validate_columns(df):
return [c for c in FEATURES if c not in df.columns]
def _pick_id_series(df):
norm = {c.lower(): c for c in df.columns}
for cand in ID_CANDIDATES:
if cand.lower() in norm:
col = norm[cand.lower()]
return df[col].astype(str)
return pd.Series(df.index, name="row_index")
# ============================================================
# Prediction
# ============================================================
def predict_csv(file):
try:
if file is None:
return None, "โ No file uploaded."
df = _read_table(file)
missing = _validate_columns(df)
if missing:
return None, f"โ Missing {len(missing)} features. Example: {missing[:10]}"
X = _prepare(df)
proba = model.predict_proba(X)[:, 1]
pred = (proba > THRESHOLD).astype(int)
ids = _pick_id_series(df)
out = pd.DataFrame({
"Variant ID": ids,
"Predicted probability (pathogenic)": proba,
"Predicted class": np.where(
pred == 1, "๐ด Pathogenic", "๐ข Benign"
),
})
summary = (
f"โ
Processed {len(out)} variants \n"
f"๐ด Pathogenic: {(pred == 1).sum()} | "
f"๐ข Benign: {(pred == 0).sum()} \n"
f"Threshold = {THRESHOLD}"
)
return out, summary
except Exception:
return None, "โ ERROR:\n```" + traceback.format_exc() + "```"
# ============================================================
# SHAP Explanation
# ============================================================
def explain_first_row(file):
try:
if file is None:
return None, "โ No file uploaded."
df = _read_table(file)
missing = _validate_columns(df)
if missing:
return None, "โ Missing required features for explanation."
X = _prepare(df)
if len(X) == 0:
return None, "โ No rows found."
explainer = shap.Explainer(model.predict_proba, X)
shap_values = explainer(X.iloc[[0]])
vals = shap_values.values[0, :, 1]
s = pd.Series(vals, index=FEATURES).sort_values(
key=np.abs, ascending=False
).head(15)
fig = plt.figure(figsize=(7, 5))
s.iloc[::-1].plot(kind="barh")
plt.title("Top feature contributions (Sample #1)")
plt.tight_layout()
return fig, (
"๐ **Why this prediction?** \n"
"Positive bars increase the probability of pathogenicity; "
"negative bars decrease it. \n"
"These signals are *supportive only* and must be interpreted "
"within ACMG/AMP guidelines."
)
except Exception:
return None, "โ ERROR:\n```" + traceback.format_exc() + "```"
# ============================================================
# UI
# ============================================================
with gr.Blocks(
title="Pathogenicity Predictor",
theme=gr.themes.Soft(primary_hue="rose", secondary_hue="slate"),
) as demo:
gr.Markdown("""
# ๐งฌ Pathogenicity Predictor
**Research prototype for variant pathogenicity assessment**
Upload a CSV or Excel file containing the trained feature columns.
This tool provides *supportive* predictions and explanations.
""")
with gr.Row():
with gr.Column(scale=1):
gr.Markdown("### ๐ Input")
inp = gr.File(
label="Upload CSV / XLSX",
file_types=[".csv", ".xlsx", ".xls"]
)
gr.Markdown("""
**Requirements**
- One row = one variant
- Must include all trained feature columns
- Results are **not** clinical diagnoses
""")
with gr.Column(scale=2):
gr.Markdown("### ๐ Results")
with gr.Row():
btn_pred = gr.Button("๐ฎ Predict", variant="primary")
btn_expl = gr.Button("๐ Explain first variant")
out_df = gr.Dataframe(
label="Predictions",
interactive=False,
wrap=True,
)
out_txt = gr.Markdown()
gr.Markdown("### ๐ฌ Why this prediction?")
out_plot = gr.Plot(label="Feature contribution (SHAP)")
btn_pred.click(predict_csv, inp, [out_df, out_txt], show_progress=True)
btn_expl.click(explain_first_row, inp, [out_plot, out_txt])
# ========================================================
# Feedback section (email)
# ========================================================
gr.Markdown("""
---
### ๐ฌ Feedback
We would love to hear your thoughts, suggestions, or bug reports.
๐ง **[Send feedback via email](mailto:dr.rahafahmad@gmail.com?subject=Pathogenicity%20Predictor%20Feedback)**
Click on the link or email us directly at **dr.rahafahmad@gmail.com, 700039113@uaeu.ac.ae, bassam.ali@uaeu.ac.ae**
""")
gr.Markdown("""
---
โ ๏ธ **Research prototype**
This tool is for research and educational use only.
Not intended for clinical diagnosis or medical decision-making.
ยฉ 2026
""")
# ============================================================
# Launch (Spaces-safe)
# ============================================================
if __name__ == "__main__":
port = int(os.environ.get("PORT", 7860))
demo.queue()
demo.launch(server_name="0.0.0.0", server_port=port, debug=True)
|