Spaces:
Sleeping
Sleeping
ali sakour commited on
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,43 +1,220 @@
|
|
| 1 |
-
|
| 2 |
import gradio as gr
|
| 3 |
-
import
|
|
|
|
|
|
|
|
|
|
| 4 |
import numpy as np
|
|
|
|
|
|
|
|
|
|
| 5 |
import tensorflow as tf
|
| 6 |
-
|
| 7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
MODEL_PATH = 'best_resnet_model.keras'
|
| 12 |
|
|
|
|
| 13 |
try:
|
| 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 |
-
description="An AI model to detect tumors in kidney CT scans. (Proof of concept for a university project).",
|
| 39 |
-
examples=['example_1.jpg', 'example_2.jpg', 'example_3.jpg', 'example_4.jpg', 'example_5.jpg'] # إدراج قائمة أسماء الملفات هنا
|
| 40 |
-
)
|
| 41 |
|
|
|
|
| 42 |
if __name__ == "__main__":
|
| 43 |
-
demo.launch()
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import timm
|
| 5 |
+
import cv2
|
| 6 |
import numpy as np
|
| 7 |
+
import joblib
|
| 8 |
+
import json
|
| 9 |
+
import shap
|
| 10 |
import tensorflow as tf
|
| 11 |
+
import matplotlib.pyplot as plt
|
| 12 |
+
import io
|
| 13 |
+
from PIL import Image
|
| 14 |
+
|
| 15 |
+
print("🚀 Initializing Final AI Interface (Hugging Face Mode)...")
|
| 16 |
+
|
| 17 |
+
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
| 18 |
+
classes = ["Normal", "Cyst", "Tumor"]
|
| 19 |
+
|
| 20 |
+
# ==========================================
|
| 21 |
+
# 1. إعداد المسارات (المسارات المحلية في Hugging Face)
|
| 22 |
+
# ==========================================
|
| 23 |
+
VIT_MODEL_PATH = 'best_vit_model.pth'
|
| 24 |
+
FUSION_MODEL_PATH = 'best_vit_fusion_model.h5'
|
| 25 |
+
SCALER_PATH = 'clinical_scaler.pkl'
|
| 26 |
+
SHAP_BG_PATH = 'shap_background_100.npy'
|
| 27 |
+
JSON_CASES_PATH = 'clinical_data.json'
|
| 28 |
+
|
| 29 |
+
# ==========================================
|
| 30 |
+
# 2. تحميل النماذج والملفات المرجعية
|
| 31 |
+
# ==========================================
|
| 32 |
+
print("📦 Loading Models and Assets...")
|
| 33 |
+
|
| 34 |
+
# أ- تحميل نموذج ViT
|
| 35 |
+
vit_model = timm.create_model('vit_base_patch16_224', pretrained=False, num_classes=3)
|
| 36 |
+
vit_model.load_state_dict(torch.load(VIT_MODEL_PATH, map_location=device))
|
| 37 |
+
vit_model.head = nn.Identity()
|
| 38 |
+
vit_model.to(device)
|
| 39 |
+
vit_model.eval()
|
| 40 |
+
|
| 41 |
+
# ب- تحميل نموذج الدمج (Fusion)
|
| 42 |
+
fusion_model = tf.keras.models.load_model(FUSION_MODEL_PATH)
|
| 43 |
|
| 44 |
+
# ج- تحميل مُقيس البيانات السريرية (Scaler)
|
| 45 |
+
scaler = joblib.load(SCALER_PATH)
|
|
|
|
| 46 |
|
| 47 |
+
# د- تحميل عينات SHAP
|
| 48 |
try:
|
| 49 |
+
background_data = np.load(SHAP_BG_PATH)
|
| 50 |
+
explainer = shap.DeepExplainer(fusion_model, background_data)
|
| 51 |
+
print("✅ SHAP Initialized with Saved Background.")
|
| 52 |
+
except FileNotFoundError:
|
| 53 |
+
print(f"❌ Error: Could not find {SHAP_BG_PATH}. Please generate and upload it first.")
|
| 54 |
+
|
| 55 |
+
# ==========================================
|
| 56 |
+
# 3. تحميل العينات الجاهزة للواجهة (Examples)
|
| 57 |
+
# ==========================================
|
| 58 |
+
try:
|
| 59 |
+
with open(JSON_CASES_PATH, 'r') as f:
|
| 60 |
+
saved_cases = json.load(f)
|
| 61 |
+
|
| 62 |
+
examples_img_only = [[c["image_path"]] for c in saved_cases]
|
| 63 |
+
|
| 64 |
+
examples_fusion = [[
|
| 65 |
+
c["image_path"], c["age"], c["bmi"], c["rad_size"],
|
| 66 |
+
c["gender"], c["smoking"], c["alcohol"], c["egfr"], c["ckd"], c["diabetes"]
|
| 67 |
+
] for c in saved_cases]
|
| 68 |
+
print(f"✅ Loaded {len(saved_cases)} examples for UI.")
|
| 69 |
+
except FileNotFoundError:
|
| 70 |
+
print(f"⚠️ Warning: Could not find JSON file at {JSON_CASES_PATH}. Examples won't be shown.")
|
| 71 |
+
examples_img_only = []
|
| 72 |
+
examples_fusion = []
|
| 73 |
+
|
| 74 |
+
# ==========================================
|
| 75 |
+
# 4. دوال التوقع والتفسير
|
| 76 |
+
# ==========================================
|
| 77 |
+
def fig_to_img(fig):
|
| 78 |
+
buf = io.BytesIO()
|
| 79 |
+
fig.savefig(buf, format='png', bbox_inches='tight', dpi=100)
|
| 80 |
+
buf.seek(0)
|
| 81 |
+
img = Image.open(buf)
|
| 82 |
+
plt.close(fig)
|
| 83 |
+
return img
|
| 84 |
+
|
| 85 |
+
def predict_image_only(image):
|
| 86 |
+
if image is None: return None
|
| 87 |
+
|
| 88 |
+
img_resized = cv2.resize(image, (224, 224))
|
| 89 |
+
img_normalized = img_resized.astype(np.float32) / 255.0
|
| 90 |
+
mean = np.array([0.485, 0.456, 0.406]); std = np.array([0.229, 0.224, 0.225])
|
| 91 |
+
img_tensor = (img_normalized - mean) / std
|
| 92 |
+
img_tensor = torch.tensor(np.transpose(img_tensor, (2, 0, 1)), dtype=torch.float32).unsqueeze(0).to(device)
|
| 93 |
+
|
| 94 |
+
with torch.no_grad():
|
| 95 |
+
img_features = vit_model(img_tensor).cpu().numpy()
|
| 96 |
+
|
| 97 |
+
dummy_clinical = np.zeros((1, 10))
|
| 98 |
+
X_fusion = np.concatenate([img_features, dummy_clinical], axis=1)
|
| 99 |
+
|
| 100 |
+
preds = fusion_model.predict(X_fusion, verbose=0)[0]
|
| 101 |
+
return {classes[i]: float(preds[i]) for i in range(3)}
|
| 102 |
+
|
| 103 |
|
| 104 |
+
def predict_fusion(image, age, bmi, rad_size, gender, smoking, alcohol, egfr, ckd, diabetes):
|
| 105 |
+
if image is None: return None, None, None
|
| 106 |
|
| 107 |
+
img_resized = cv2.resize(image, (224, 224))
|
| 108 |
+
img_normalized = img_resized.astype(np.float32) / 255.0
|
| 109 |
+
mean = np.array([0.485, 0.456, 0.406]); std = np.array([0.229, 0.224, 0.225])
|
| 110 |
+
img_tensor = (img_normalized - mean) / std
|
| 111 |
+
img_tensor = torch.tensor(np.transpose(img_tensor, (2, 0, 1)), dtype=torch.float32).unsqueeze(0).to(device)
|
| 112 |
+
|
| 113 |
+
with torch.no_grad():
|
| 114 |
+
img_features = vit_model(img_tensor).cpu().numpy()
|
| 115 |
+
|
| 116 |
+
g_map = {"Male": 0, "Female": 1, "Other": 2}
|
| 117 |
+
s_map = {"Never": 0, "Previous Smoker": 1, "Current Smoker": 2}
|
| 118 |
+
a_map = {"None": 0, "Moderate": 1, "Heavy": 2}
|
| 119 |
+
comorb_score = int(ckd) + int(diabetes)
|
| 120 |
+
|
| 121 |
+
clin_data = np.array([[age, bmi, rad_size, g_map[gender], s_map[smoking], a_map[alcohol], egfr, int(ckd), int(diabetes), comorb_score]])
|
| 122 |
+
clin_scaled = scaler.transform(clin_data)
|
| 123 |
+
|
| 124 |
+
X_fusion = np.concatenate([img_features, clin_scaled], axis=1)
|
| 125 |
+
preds = fusion_model.predict(X_fusion, verbose=0)[0]
|
| 126 |
+
pred_class = np.argmax(preds)
|
| 127 |
+
result_dict = {classes[i]: float(preds[i]) for i in range(3)}
|
| 128 |
|
| 129 |
+
shap_vals = explainer.shap_values(X_fusion)
|
| 130 |
+
if isinstance(shap_vals, list):
|
| 131 |
+
shap_patient = shap_vals[pred_class][0]
|
| 132 |
+
elif len(shap_vals.shape) == 3:
|
| 133 |
+
shap_patient = shap_vals[0, :, pred_class]
|
| 134 |
+
else:
|
| 135 |
+
shap_patient = shap_vals[0]
|
| 136 |
+
|
| 137 |
+
img_shap_sum = np.sum(np.abs(shap_patient[:768]))
|
| 138 |
+
clin_shap_sum = np.sum(np.abs(shap_patient[768:]))
|
| 139 |
+
total_shap = img_shap_sum + clin_shap_sum
|
| 140 |
|
| 141 |
+
img_pct = (img_shap_sum / total_shap) * 100 if total_shap > 0 else 0
|
| 142 |
+
clin_pct = (clin_shap_sum / total_shap) * 100 if total_shap > 0 else 0
|
| 143 |
+
|
| 144 |
+
fig_pie, ax_pie = plt.subplots(figsize=(4, 4))
|
| 145 |
+
ax_pie.pie([img_pct, clin_pct], labels=['Image (ViT)', 'Clinical'], autopct='%1.1f%%', colors=['#ff9999', '#66b3ff'], explode=(0.1, 0), shadow=True, startangle=140)
|
| 146 |
+
ax_pie.set_title("Modality Contribution")
|
| 147 |
+
img_pie = fig_to_img(fig_pie)
|
| 148 |
+
|
| 149 |
+
clin_names = np.array(['Age', 'BMI', 'Rad Size', 'Gender', 'Smoking', 'Alcohol', 'eGFR', 'CKD', 'Diabetes', 'Comorb Score'])
|
| 150 |
+
clin_impact = np.abs(shap_patient[768:])
|
| 151 |
+
sorted_idx = np.argsort(clin_impact)[-5:]
|
| 152 |
+
|
| 153 |
+
fig_bar, ax_bar = plt.subplots(figsize=(5, 4))
|
| 154 |
+
ax_bar.barh(clin_names[sorted_idx], clin_impact[sorted_idx], color='#66b3ff', edgecolor='black')
|
| 155 |
+
ax_bar.set_title(f"Top Clinical Factors for {classes[pred_class]}")
|
| 156 |
+
ax_bar.set_xlabel("Absolute SHAP Impact")
|
| 157 |
+
plt.tight_layout()
|
| 158 |
+
img_bar = fig_to_img(fig_bar)
|
| 159 |
+
|
| 160 |
+
return result_dict, img_pie, img_bar
|
| 161 |
+
|
| 162 |
+
# ==========================================
|
| 163 |
+
# 5. واجهة المستخدم (UI)
|
| 164 |
+
# ==========================================
|
| 165 |
+
print("🌐 Launching Gradio Interface...")
|
| 166 |
+
|
| 167 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 168 |
+
gr.Markdown("<h1 style='text-align: center;'>🩺 AI Kidney Tumor Diagnosis System</h1>")
|
| 169 |
|
| 170 |
+
with gr.Tabs():
|
| 171 |
+
with gr.TabItem("🖼️ Scenario 1: Image Only"):
|
| 172 |
+
with gr.Row():
|
| 173 |
+
with gr.Column():
|
| 174 |
+
img_only_in = gr.Image(label="Upload CT Scan", type="numpy")
|
| 175 |
+
btn_only = gr.Button("Analyze Image", variant="primary")
|
| 176 |
+
if examples_img_only:
|
| 177 |
+
gr.Examples(examples=examples_img_only, inputs=img_only_in)
|
| 178 |
+
with gr.Column():
|
| 179 |
+
out_only_label = gr.Label(label="Prediction (Ignoring Clinical Data)")
|
| 180 |
+
btn_only.click(predict_image_only, inputs=img_only_in, outputs=out_only_label)
|
| 181 |
+
|
| 182 |
+
with gr.TabItem("🧬 Scenario 2: Image + Clinical Fusion"):
|
| 183 |
+
with gr.Row():
|
| 184 |
+
with gr.Column():
|
| 185 |
+
img_fusion_in = gr.Image(label="CT Scan", type="numpy")
|
| 186 |
+
with gr.Row():
|
| 187 |
+
age_in = gr.Number(label="Age", value=50)
|
| 188 |
+
bmi_in = gr.Number(label="BMI", value=25.0)
|
| 189 |
+
with gr.Row():
|
| 190 |
+
rad_size_in = gr.Number(label="Radiographic Size (cm)", value=3.5)
|
| 191 |
+
egfr_in = gr.Number(label="eGFR (Kidney Function)", value=90.0)
|
| 192 |
+
|
| 193 |
+
gender_in = gr.Radio(["Male", "Female", "Other"], label="Gender", value="Male")
|
| 194 |
+
smoking_in = gr.Radio(["Never", "Previous Smoker", "Current Smoker"], label="Smoking", value="Never")
|
| 195 |
+
alcohol_in = gr.Radio(["None", "Moderate", "Heavy"], label="Alcohol Use", value="None")
|
| 196 |
+
|
| 197 |
+
with gr.Row():
|
| 198 |
+
ckd_in = gr.Checkbox(label="Chronic Kidney Disease (CKD)")
|
| 199 |
+
diabetes_in = gr.Checkbox(label="Diabetes")
|
| 200 |
+
|
| 201 |
+
btn_fusion = gr.Button("Analyze Fusion Data", variant="primary")
|
| 202 |
+
if examples_fusion:
|
| 203 |
+
gr.Examples(examples=examples_fusion, inputs=[img_fusion_in, age_in, bmi_in, rad_size_in, gender_in, smoking_in, alcohol_in, egfr_in, ckd_in, diabetes_in])
|
| 204 |
+
|
| 205 |
+
with gr.Column():
|
| 206 |
+
out_fusion_label = gr.Label(label="Final AI Diagnosis")
|
| 207 |
+
gr.Markdown("### 🔍 AI Explainability (Why did the model decide this?)")
|
| 208 |
+
with gr.Row():
|
| 209 |
+
out_pie = gr.Image(label="Modality Impact")
|
| 210 |
+
out_bar = gr.Image(label="Top Clinical Factors")
|
| 211 |
|
| 212 |
+
btn_fusion.click(
|
| 213 |
+
fn=predict_fusion,
|
| 214 |
+
inputs=[img_fusion_in, age_in, bmi_in, rad_size_in, gender_in, smoking_in, alcohol_in, egfr_in, ckd_in, diabetes_in],
|
| 215 |
+
outputs=[out_fusion_label, out_pie, out_bar]
|
| 216 |
+
)
|
|
|
|
|
|
|
|
|
|
| 217 |
|
| 218 |
+
# تشغيل الواجهة
|
| 219 |
if __name__ == "__main__":
|
| 220 |
+
demo.launch()
|