Spaces:
Sleeping
Sleeping
File size: 9,664 Bytes
f447aad 571b6d5 f447aad 571b6d5 f447aad 571b6d5 f447aad 571b6d5 f447aad 571b6d5 f447aad 571b6d5 f447aad 571b6d5 f447aad 571b6d5 f447aad 571b6d5 f447aad 571b6d5 879c749 571b6d5 f447aad 571b6d5 f447aad 571b6d5 f447aad 571b6d5 | 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 | import gradio as gr
import torch
import torch.nn as nn
import timm
import cv2
import numpy as np
import joblib
import json
import shap
import tensorflow as tf
import matplotlib.pyplot as plt
import io
from PIL import Image
print("🚀 Initializing Final AI Interface (Hugging Face Mode)...")
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
classes = ["Normal", "Cyst", "Tumor"]
# ==========================================
# 1. إعداد المسارات (المسارات المحلية في Hugging Face)
# ==========================================
VIT_MODEL_PATH = 'best_vit_model.pth'
FUSION_MODEL_PATH = 'best_vit_fusion_model.h5'
SCALER_PATH = 'clinical_scaler.pkl'
SHAP_BG_PATH = 'shap_background_100.npy'
JSON_CASES_PATH = 'clinical_data.json'
# ==========================================
# 2. تحميل النماذج والملفات المرجعية
# ==========================================
print("📦 Loading Models and Assets...")
# أ- تحميل نموذج ViT
vit_model = timm.create_model('vit_base_patch16_224', pretrained=False, num_classes=3)
vit_model.load_state_dict(torch.load(VIT_MODEL_PATH, map_location=device))
vit_model.head = nn.Identity()
vit_model.to(device)
vit_model.eval()
# ب- تحميل نموذج الدمج (Fusion)
fusion_model = tf.keras.models.load_model(FUSION_MODEL_PATH)
# ج- تحميل مُقيس البيانات السريرية (Scaler)
scaler = joblib.load(SCALER_PATH)
# د- تحميل عينات SHAP
try:
background_data = np.load(SHAP_BG_PATH)
explainer = shap.DeepExplainer(fusion_model, background_data)
print("✅ SHAP Initialized with Saved Background.")
except FileNotFoundError:
print(f"❌ Error: Could not find {SHAP_BG_PATH}. Please generate and upload it first.")
# ==========================================
# 3. تحميل العينات الجاهزة للواجهة (Examples)
# ==========================================
try:
with open(JSON_CASES_PATH, 'r') as f:
saved_cases = json.load(f)
examples_img_only = [[c["image_path"]] for c in saved_cases]
examples_fusion = [[
c["image_path"], c["age"], c["bmi"], c["rad_size"],
c["gender"], c["smoking"], c["alcohol"], c["egfr"], c["ckd"], c["diabetes"]
] for c in saved_cases]
print(f"✅ Loaded {len(saved_cases)} examples for UI.")
except FileNotFoundError:
print(f"⚠️ Warning: Could not find JSON file at {JSON_CASES_PATH}. Examples won't be shown.")
examples_img_only = []
examples_fusion = []
# ==========================================
# 4. دوال التوقع والتفسير
# ==========================================
def fig_to_img(fig):
buf = io.BytesIO()
fig.savefig(buf, format='png', bbox_inches='tight', dpi=100)
buf.seek(0)
img = Image.open(buf)
plt.close(fig)
return img
def predict_image_only(image):
if image is None: return None
img_resized = cv2.resize(image, (224, 224))
img_normalized = img_resized.astype(np.float32) / 255.0
mean = np.array([0.485, 0.456, 0.406]); std = np.array([0.229, 0.224, 0.225])
img_tensor = (img_normalized - mean) / std
img_tensor = torch.tensor(np.transpose(img_tensor, (2, 0, 1)), dtype=torch.float32).unsqueeze(0).to(device)
with torch.no_grad():
img_features = vit_model(img_tensor).cpu().numpy()
dummy_clinical = np.zeros((1, 10))
X_fusion = np.concatenate([img_features, dummy_clinical], axis=1)
preds = fusion_model.predict(X_fusion, verbose=0)[0]
return {classes[i]: float(preds[i]) for i in range(3)}
def predict_fusion(image, age, bmi, rad_size, gender, smoking, alcohol, egfr, ckd, diabetes):
if image is None: return None, None, None
img_resized = cv2.resize(image, (224, 224))
img_normalized = img_resized.astype(np.float32) / 255.0
mean = np.array([0.485, 0.456, 0.406]); std = np.array([0.229, 0.224, 0.225])
img_tensor = (img_normalized - mean) / std
img_tensor = torch.tensor(np.transpose(img_tensor, (2, 0, 1)), dtype=torch.float32).unsqueeze(0).to(device)
with torch.no_grad():
img_features = vit_model(img_tensor).cpu().numpy()
g_map = {"Male": 0, "Female": 1, "Other": 2}
s_map = {"Never": 0, "Previous Smoker": 1, "Current Smoker": 2}
a_map = {"None": 0, "Moderate": 1, "Heavy": 2}
comorb_score = int(ckd) + int(diabetes)
clin_data = np.array([[age, bmi, rad_size, g_map[gender], s_map[smoking], a_map[alcohol], egfr, int(ckd), int(diabetes), comorb_score]])
clin_scaled = scaler.transform(clin_data)
X_fusion = np.concatenate([img_features, clin_scaled], axis=1)
preds = fusion_model.predict(X_fusion, verbose=0)[0]
pred_class = np.argmax(preds)
result_dict = {classes[i]: float(preds[i]) for i in range(3)}
shap_vals = explainer.shap_values(X_fusion)
if isinstance(shap_vals, list):
shap_patient = shap_vals[pred_class][0]
elif len(shap_vals.shape) == 3:
shap_patient = shap_vals[0, :, pred_class]
else:
shap_patient = shap_vals[0]
img_shap_sum = np.sum(np.abs(shap_patient[:768]))
clin_shap_sum = np.sum(np.abs(shap_patient[768:]))
total_shap = img_shap_sum + clin_shap_sum
img_pct = (img_shap_sum / total_shap) * 100 if total_shap > 0 else 0
clin_pct = (clin_shap_sum / total_shap) * 100 if total_shap > 0 else 0
fig_pie, ax_pie = plt.subplots(figsize=(4, 4))
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)
ax_pie.set_title("Modality Contribution")
img_pie = fig_to_img(fig_pie)
clin_names = np.array(['Age', 'BMI', 'Rad Size', 'Gender', 'Smoking', 'Alcohol', 'eGFR', 'CKD', 'Diabetes', 'Comorb Score'])
clin_impact = np.abs(shap_patient[768:])
sorted_idx = np.argsort(clin_impact)[-5:]
fig_bar, ax_bar = plt.subplots(figsize=(5, 4))
ax_bar.barh(clin_names[sorted_idx], clin_impact[sorted_idx], color='#66b3ff', edgecolor='black')
ax_bar.set_title(f"Top Clinical Factors for {classes[pred_class]}")
ax_bar.set_xlabel("Absolute SHAP Impact")
plt.tight_layout()
img_bar = fig_to_img(fig_bar)
return result_dict, img_pie, img_bar
# ==========================================
# 5. واجهة المستخدم (UI)
# ==========================================
print("🌐 Launching Gradio Interface...")
with gr.Blocks(theme=gr.themes.Soft()) as demo:
gr.Markdown("<h1 style='text-align: center;'>🩺 AI Kidney Tumor Diagnosis System</h1>")
gr.Markdown("<p style='text-align: center;'>🩺 إعداد حعفر شهيرة - سالي حليبية - سلاف خدام</p>")
with gr.Tabs():
with gr.TabItem("🖼️ Scenario 1: Image Only"):
with gr.Row():
with gr.Column():
img_only_in = gr.Image(label="Upload CT Scan", type="numpy")
btn_only = gr.Button("Analyze Image", variant="primary")
if examples_img_only:
gr.Examples(examples=examples_img_only, inputs=img_only_in)
with gr.Column():
out_only_label = gr.Label(label="Prediction (Ignoring Clinical Data)")
btn_only.click(predict_image_only, inputs=img_only_in, outputs=out_only_label)
with gr.TabItem("🧬 Scenario 2: Image + Clinical Fusion"):
with gr.Row():
with gr.Column():
img_fusion_in = gr.Image(label="CT Scan", type="numpy")
with gr.Row():
age_in = gr.Number(label="Age", value=50)
bmi_in = gr.Number(label="BMI", value=25.0)
with gr.Row():
rad_size_in = gr.Number(label="Radiographic Size (cm)", value=3.5)
egfr_in = gr.Number(label="eGFR (Kidney Function)", value=90.0)
gender_in = gr.Radio(["Male", "Female", "Other"], label="Gender", value="Male")
smoking_in = gr.Radio(["Never", "Previous Smoker", "Current Smoker"], label="Smoking", value="Never")
alcohol_in = gr.Radio(["None", "Moderate", "Heavy"], label="Alcohol Use", value="None")
with gr.Row():
ckd_in = gr.Checkbox(label="Chronic Kidney Disease (CKD)")
diabetes_in = gr.Checkbox(label="Diabetes")
btn_fusion = gr.Button("Analyze Fusion Data", variant="primary")
if examples_fusion:
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])
with gr.Column():
out_fusion_label = gr.Label(label="Final AI Diagnosis")
gr.Markdown("### 🔍 AI Explainability (Why did the model decide this?)")
with gr.Row():
out_pie = gr.Image(label="Modality Impact")
out_bar = gr.Image(label="Top Clinical Factors")
btn_fusion.click(
fn=predict_fusion,
inputs=[img_fusion_in, age_in, bmi_in, rad_size_in, gender_in, smoking_in, alcohol_in, egfr_in, ckd_in, diabetes_in],
outputs=[out_fusion_label, out_pie, out_bar]
)
# تشغيل الواجهة
if __name__ == "__main__":
demo.launch() |