Spaces:
Running
Running
File size: 8,761 Bytes
3d98fdb | 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 | import gradio as gr
from huggingface_hub import hf_hub_download
import pickle
import numpy as np
import os
REPO_ID = "Umranz/mediscan-symptom-classifier"
def load_models():
files = ["svm.pkl", "logistic.pkl", "random_forest.pkl", "naive_bayes.pkl", "voting_ensemble.pkl", "label_encoder.pkl", "tfidf.pkl"]
loaded = {}
for f in files:
path = hf_hub_download(repo_id=REPO_ID, filename=f)
with open(path, "rb") as file:
loaded[f.replace(".pkl", "")] = pickle.load(file)
return loaded
print("Loading models...")
M = load_models()
tfidf = M["tfidf"]
le = M["label_encoder"]
ensemble = M["voting_ensemble"]
models = {
"SVM" : M["svm"],
"Logistic Reg" : M["logistic"],
"Random Forest" : M["random_forest"],
"Naive Bayes" : M["naive_bayes"],
}
print("β
Models loaded!")
SEVERITY = {
"Fungal infection" : ("π‘", "Mild"),
"Allergy" : ("π‘", "Mild"),
"GERD" : ("π‘", "Mild"),
"Chronic cholestasis" : ("π ", "Moderate"),
"Drug Reaction" : ("π ", "Moderate"),
"Peptic ulcer disease" : ("π ", "Moderate"),
"AIDS" : ("π΄", "Severe"),
"Diabetes" : ("π ", "Moderate"),
"Gastroenteritis" : ("π‘", "Mild"),
"Bronchial Asthma" : ("π ", "Moderate"),
"Hypertension" : ("π΄", "Severe"),
"Migraine" : ("π‘", "Mild"),
"Cervical spondylosis" : ("π‘", "Mild"),
"Paralysis (brain hemorrhage)": ("π΄", "Severe"),
"Jaundice" : ("π ", "Moderate"),
"Malaria" : ("π΄", "Severe"),
"Chicken pox" : ("π‘", "Mild"),
"Dengue" : ("π΄", "Severe"),
"Typhoid" : ("π ", "Moderate"),
"hepatitis A" : ("π ", "Moderate"),
"Hepatitis B" : ("π΄", "Severe"),
"Hepatitis C" : ("π΄", "Severe"),
"Hepatitis D" : ("π΄", "Severe"),
"Hepatitis E" : ("π ", "Moderate"),
"Alcoholic hepatitis" : ("π ", "Moderate"),
"Tuberculosis" : ("π΄", "Severe"),
"Common Cold" : ("π’", "Low"),
"Pneumonia" : ("π΄", "Severe"),
"Dimorphic hemmorhoids(piles)": ("π‘", "Mild"),
"Heart attack" : ("π΄", "Critical"),
"Varicose veins" : ("π‘", "Mild"),
"Hypothyroidism" : ("π ", "Moderate"),
"Hyperthyroidism" : ("π ", "Moderate"),
"Hypoglycemia" : ("π΄", "Severe"),
"Osteoarthristis" : ("π‘", "Mild"),
"Arthritis" : ("π‘", "Mild"),
"Vertigo" : ("π‘", "Mild"),
"Acne" : ("π’", "Low"),
"Urinary tract infection" : ("π‘", "Mild"),
"Psoriasis" : ("π‘", "Mild"),
"Impetigo" : ("π‘", "Mild"),
}
def predict(symptoms, threshold):
if not symptoms.strip():
return (
"β οΈ Please enter your symptoms.",
"",
"",
""
)
vec = tfidf.transform([symptoms])
proba = ensemble.predict_proba(vec)[0]
top3 = np.argsort(proba)[::-1][:3]
top_idx = top3[0]
top_label = le.classes_[top_idx]
top_conf = proba[top_idx] * 100
sev_emoji, sev_label = SEVERITY.get(top_label, ("βͺ", "Unknown"))
if top_conf < threshold:
main_result = (
f"β οΈ **Low Confidence ({top_conf:.1f}%)** β Please provide more specific symptoms.\n\n"
f"Best guess: **{top_label}** but confidence is below your threshold of {threshold}%."
)
return main_result, "", "", ""
else:
main_result = (
f"## {sev_emoji} {top_label}\n"
f"**Confidence:** {top_conf:.1f}%\n\n"
f"**Severity:** {sev_emoji} {sev_label}\n\n"
f"{'β' * int(top_conf // 5)}{'β' * (20 - int(top_conf // 5))} {top_conf:.1f}%"
)
top3_result = "## π Top 3 Predictions\n\n"
for rank, idx in enumerate(top3):
label = le.classes_[idx]
conf = proba[idx] * 100
s_emoji, s_label = SEVERITY.get(label, ("βͺ", "Unknown"))
bar = "β" * int(conf // 5) + "β" * (20 - int(conf // 5))
top3_result += (
f"**{rank+1}. {label}** {s_emoji} {s_label}\n"
f"{bar} {conf:.1f}%\n\n"
)
agreement = "## π€ Model Votes\n\n"
votes = {}
for name, model in models.items():
pred = le.classes_[model.predict(vec)[0]]
votes[name] = pred
match = "β
" if pred == top_label else "π"
agreement += f"{match} **{name}** β {pred}\n\n"
all_agree = len(set(votes.values())) == 1
agreement += (
"\nπ’ **All models agree!**" if all_agree
else "\nπ‘ **Models have different opinions β consider consulting a doctor.**"
)
disclaimer = (
"## β οΈ Medical Disclaimer\n\n"
"This tool is for **educational purposes only** and does **NOT** replace "
"professional medical advice. Always consult a qualified healthcare provider "
"for diagnosis and treatment.\n\n"
"**If you have a medical emergency, call your local emergency number immediately.**"
)
return main_result, top3_result, agreement, disclaimer
EXAMPLES = [
["fever, chills, headache, muscle pain, sweating", 50],
["itching, skin rash, nodal skin eruptions, dischromic patches", 50],
["chest pain, shortness of breath, fatigue, sweating", 50],
["sneezing, runny nose, cough, sore throat, congestion", 50],
["fatigue, weight loss, high fever, night sweats, cough", 50],
]
with gr.Blocks(title="MediScan AI") as demo:
gr.Markdown("""
# π©Ί MediScan AI β Medical Symptom Classifier
**4 ML Models + Voting Ensemble** | DistilBERT-level accuracy with traditional ML
> Enter your symptoms separated by commas for instant multi-model analysis.
""")
with gr.Row():
with gr.Column(scale=2):
symptoms_input = gr.Textbox(
lines=4,
placeholder="e.g. fever, chills, headache, muscle pain, fatigue...",
label="π Describe Your Symptoms",
max_lines=8
)
threshold_slider = gr.Slider(
minimum=10,
maximum=90,
value=50,
step=5,
label="βοΈ Confidence Threshold (%)",
info="Predictions below this % will show a low-confidence warning"
)
analyze_btn = gr.Button(
"π Analyze Symptoms",
variant="primary",
size="lg"
)
with gr.Column(scale=3):
main_output = gr.Markdown(label="Primary Diagnosis")
with gr.Row():
top3_output = gr.Markdown(label="Top 3 Predictions")
agreement_output = gr.Markdown(label="Model Agreement")
disclaimer_output = gr.Markdown()
gr.Examples(
examples=EXAMPLES,
inputs=[symptoms_input, threshold_slider],
label="π‘ Try These Examples"
)
with gr.Accordion("βΉοΈ About MediScan AI", open=False):
gr.Markdown("""
## π§ How It Works
MediScan AI runs your symptoms through **4 independent ML models simultaneously:**
| Model | Strength |
|---|---|
| **SVM** | Best accuracy on text classification |
| **Logistic Regression** | Fast, reliable baseline |
| **Random Forest** | Handles noisy input well |
| **Naive Bayes** | Great for keyword-based symptoms |
A **Soft Voting Ensemble** combines all 4 predictions for the final result.
## π Dataset
- **Source:** Gretel AI Symptom to Diagnosis dataset
- **Diseases:** 24 unique conditions
- **Features:** TF-IDF with bigrams (5000 features)
## π¨βπ» Built By
Umranz β [HuggingFace Profile](https://huggingface.co/Umranz)
""")
analyze_btn.click(
fn=predict,
inputs=[symptoms_input, threshold_slider],
outputs=[main_output, top3_output, agreement_output, disclaimer_output]
)
symptoms_input.submit(
fn=predict,
inputs=[symptoms_input, threshold_slider],
outputs=[main_output, top3_output, agreement_output, disclaimer_output]
)
demo.launch() |