import gradio as gr
import torch
import torch.nn as nn
import torchvision.models as models
import segmentation_models_pytorch as smp
import xgboost as xgb
import joblib
import cv2
import numpy as np
from PIL import Image
import json
import os
# تحديد الجهاز (عادة مساحات Hugging Face المجانية تستخدم CPU)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# 1. تعريف المعماريات
seg_model = smp.Unet(
encoder_name="efficientnet-b4",
encoder_weights=None,
in_channels=3,
classes=2
).to(device)
class MultiModalGlaucomaNet(nn.Module):
def __init__(self, num_tabular_features):
super(MultiModalGlaucomaNet, self).__init__()
resnet = models.resnet50(weights=None)
self.image_extractor = nn.Sequential(*list(resnet.children())[:-1])
self.tabular_extractor = nn.Sequential(
nn.Linear(num_tabular_features, 64), nn.ReLU(), nn.BatchNorm1d(64), nn.Dropout(0.3),
nn.Linear(64, 32), nn.ReLU()
)
self.classifier = nn.Sequential(
nn.Linear(2048 + 32, 256), nn.ReLU(), nn.Dropout(0.4), nn.Linear(256, 1)
)
def forward(self, img, tab):
x_img = self.image_extractor(img).view(img.size(0), -1)
x_tab = self.tabular_extractor(tab)
return self.classifier(torch.cat((x_img, x_tab), dim=1))
cls_model = MultiModalGlaucomaNet(12).to(device)
# 2. تحميل الأوزان
seg_model.load_state_dict(torch.load("best_glaucoma_model_final.pth", map_location=device))
seg_model.eval()
cls_model.load_state_dict(torch.load("Ultimate_Original_Model_Restored.pth", map_location=device))
cls_model.eval()
xgb_model = xgb.XGBClassifier()
xgb_model.load_model("xgb_glaucoma_expert.json")
rf_model = joblib.load("rf_glaucoma_expert.joblib")
with open("blending_config.json", "r") as f:
blend_config = json.load(f)
# 3. دوال المعالجة والتنبؤ
def preprocess_image(image_pil):
img_array = np.array(image_pil.convert("RGB"))
img_resized = cv2.resize(img_array, (256, 256))
img_normalized = (img_resized / 255.0).astype(np.float32)
mean = np.array([0.485, 0.456, 0.406])
std = np.array([0.229, 0.224, 0.225])
img_normalized = (img_normalized - mean) / std
img_tensor = torch.tensor(img_normalized).permute(2, 0, 1).unsqueeze(0).to(device, dtype=torch.float32)
return img_resized, img_tensor
def predict_glaucoma(mode, image, age, gender, iop, cct, rnfl_g, rnfl_s, rnfl_n, rnfl_i, rnfl_t, vf_mean, vf_min, vf_std):
if image is None:
return None, "
Please upload or select a Fundus Image to begin analysis.
", ""
img_original_resized, img_tensor = preprocess_image(image)
output_segmentation_img = None
diagnosis_html = ""
details_str = ""
if mode in ["Full AI Pipeline (Segmentation + Classification)", "Optic Disc & Cup Segmentation Only"]:
with torch.no_grad():
seg_out = torch.sigmoid(seg_model(img_tensor))[0].cpu().numpy()
pred_od = (seg_out[0] > 0.5).astype(np.uint8)
pred_oc = (seg_out[1] > 0.5).astype(np.uint8)
seg_overlay = img_original_resized.copy()
contours_od, _ = cv2.findContours(pred_od, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours_oc, _ = cv2.findContours(pred_oc, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(seg_overlay, contours_od, -1, (0, 255, 0), 2)
cv2.drawContours(seg_overlay, contours_oc, -1, (255, 255, 0), 2)
output_segmentation_img = Image.fromarray(seg_overlay)
if mode in ["Full AI Pipeline (Segmentation + Classification)", "Glaucoma Progression Classification Only"]:
gender_val = 0.0 if gender == "Male" else 1.0
tab_data = np.array([[age, gender_val, iop, cct, rnfl_g, rnfl_s, rnfl_n, rnfl_i, rnfl_t, vf_mean, vf_min, vf_std]], dtype=np.float32)
tab_tensor = torch.tensor(tab_data).to(device)
with torch.no_grad():
out1 = cls_model(img_tensor, tab_tensor)
out2 = cls_model(torch.flip(img_tensor, [3]), tab_tensor)
out3 = cls_model(torch.flip(img_tensor, [2]), tab_tensor)
out4 = cls_model(torch.clamp(img_tensor * 1.1, 0, 1), tab_tensor)
dl_prob = ((torch.sigmoid(out1) + torch.sigmoid(out2) + torch.sigmoid(out3) + torch.sigmoid(out4)) / 4.0).item()
xgb_prob = xgb_model.predict_proba(tab_data)[0][1]
rf_prob = rf_model.predict_proba(tab_data)[0][1]
w_dl = blend_config['dl_weight']
w_xgb = blend_config['xgb_weight']
w_rf = blend_config['rf_weight']
threshold = blend_config['optimal_threshold']
final_prob = (w_dl * dl_prob) + (w_xgb * xgb_prob) + (w_rf * rf_prob)
diagnosis = "Glaucoma Progression Detected" if final_prob >= threshold else "Stable / No Progression"
color = "red" if final_prob >= threshold else "green"
diagnosis_html = f"Diagnosis Result: {diagnosis}
"
details_str = (
f"Final Ensemble Probability: {final_prob*100:.2f}%\n"
f"Classification Threshold : {threshold*100:.2f}%\n\n"
f"--- Individual Model Breakdown ---\n"
f"Deep Learning Model : {dl_prob*100:.2f}% (Weight: {w_dl*100:.0f}%)\n"
f"XGBoost Model : {xgb_prob*100:.2f}% (Weight: {w_xgb*100:.0f}%)\n"
f"Random Forest Model : {rf_prob*100:.2f}% (Weight: {w_rf*100:.0f}%)"
)
else:
diagnosis_html = "Classification Mode Bypassed
"
details_str = "Classification model was not executed as per the selected mode."
if mode == "Glaucoma Progression Classification Only":
output_segmentation_img = image
return output_segmentation_img, diagnosis_html, details_str
# 4. بناء واجهة Gradio
theme = gr.themes.Soft(primary_hue="blue", secondary_hue="indigo")
with gr.Blocks(theme=theme, title="Advanced Glaucoma Multi-Task AI System") as demo:
gr.Markdown("Advanced Multi-Task Glaucoma AI Diagnostic Platform
")
mode_selector = gr.Radio(
choices=["Full AI Pipeline (Segmentation + Classification)", "Optic Disc & Cup Segmentation Only", "Glaucoma Progression Classification Only"],
value="Full AI Pipeline (Segmentation + Classification)",
label="Analysis Mode"
)
with gr.Row():
with gr.Column(scale=1):
gr.Markdown("### 1. Medical Image Input")
img_input = gr.Image(type="pil", label="Fundus Image (CFP / ROI)")
gr.Markdown("### 2. Patient Clinical Parameters")
with gr.Row():
age_in = gr.Number(label="Age", value=46)
gender_in = gr.Radio(choices=["Male", "Female"], label="Gender", value="Female")
with gr.Row():
iop_in = gr.Number(label="IOP (mmHg)", value=14.7)
cct_in = gr.Number(label="CCT (µm)", value=535.0)
gr.Markdown("#### RNFL Thickness (µm)")
with gr.Row():
rnfl_g_in = gr.Number(label="Global", value=113.0)
rnfl_s_in = gr.Number(label="Superior", value=104.0)
with gr.Row():
rnfl_n_in = gr.Number(label="Nasal", value=104.0)
rnfl_i_in = gr.Number(label="Inferior", value=123.0)
rnfl_t_in = gr.Number(label="Temporal", value=120.0)
gr.Markdown("#### Visual Field (VF) Statistical Metrics")
with gr.Row():
vf_mean_in = gr.Number(label="VF Mean Sensitivity", value=19.8)
vf_min_in = gr.Number(label="VF Min Sensitivity", value=13.0)
vf_std_in = gr.Number(label="VF Std Deviation", value=3.5)
submit_btn = gr.Button("Run Selected AI Analysis", variant="primary")
with gr.Column(scale=1):
gr.Markdown("### AI Analysis Results")
diag_output = gr.HTML(label="Diagnostic Status")
img_output = gr.Image(type="pil", label="Optic Disc (Green) & Cup (Yellow) Boundaries")
details_output = gr.Textbox(label="Probabilities & Model Contributions", lines=9)
gr.Markdown("### Clinical Test Samples with Images (Click to Auto-load)")
# فلترة الأمثلة الموجودة فعلياً
available_examples = []
example_data = [
["Full AI Pipeline (Segmentation + Classification)", "1_OD_1.jpg", 46, "Female", 14.7, 535, 113, 104, 104, 123, 120, 19.8, 13.0, 3.5],
["Full AI Pipeline (Segmentation + Classification)", "2_OS_1.jpg", 57, "Male", 15.5, 545, 62, 69, 70, 61, 49, 11.2, 1.0, 8.4],
["Full AI Pipeline (Segmentation + Classification)", "3_OD_1.jpg", 41, "Male", 17.0, 557, 89, 100, 83, 88, 86, 23.5, 14.0, 3.1],
["Full AI Pipeline (Segmentation + Classification)", "4_OS_1.jpg", 58, "Male", 14.7, 487, 103, 140, 93, 122, 57, 21.2, 12.0, 4.2],
["Full AI Pipeline (Segmentation + Classification)", "7_OD_1.jpg", 33, "Female", 19.0, 534, 85, 106, 77, 94, 61, 21.8, 11.0, 4.8]
]
for ex in example_data:
if os.path.exists(ex[1]): available_examples.append(ex)
gr.Examples(
examples=available_examples,
inputs=[mode_selector, img_input, age_in, gender_in, iop_in, cct_in, rnfl_g_in, rnfl_s_in, rnfl_n_in, rnfl_i_in, rnfl_t_in, vf_mean_in, vf_min_in, vf_std_in],
label="Dataset Patient Profiles (Image + Clinical Data)"
)
submit_btn.click(
fn=predict_glaucoma,
inputs=[mode_selector, img_input, age_in, gender_in, iop_in, cct_in, rnfl_g_in, rnfl_s_in, rnfl_n_in, rnfl_i_in, rnfl_t_in, vf_mean_in, vf_min_in, vf_std_in],
outputs=[img_output, diag_output, details_output]
)
demo.launch()