Alhdrawi commited on
Commit
89f3ba0
·
verified ·
1 Parent(s): d02841f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +51 -29
app.py CHANGED
@@ -1,12 +1,15 @@
1
  import gradio as gr
2
  import torch
3
  import random
4
- import requests
5
- import os
6
  from torchvision import transforms
7
  from PIL import Image
 
 
8
 
 
9
  REPO_ID = "Alhdrawi/x_alhdrawi"
 
 
10
  MODEL_FILES = [
11
  "best_128_0.0002_original_15000_0.859.pt",
12
  "best_128_0.0002_original_8000_0.857.pt",
@@ -20,44 +23,64 @@ MODEL_FILES = [
20
  "best_64_5e-05_original_22000_0.864.pt",
21
  ]
22
 
 
 
 
 
 
 
 
 
23
  diseases = [
24
  "Atelectasis", "Cardiomegaly", "Consolidation", "Edema", "Effusion",
25
  "Emphysema", "Fibrosis", "Hernia", "Infiltration", "Mass", "Nodule",
26
  "Pleural_Thickening", "Pneumonia", "Pneumothorax"
27
  ]
28
 
29
- transform = transforms.Compose([
30
- transforms.Resize((224, 224)),
31
- transforms.ToTensor(),
32
- transforms.Normalize(mean=[0.485], std=[0.229])
33
- ])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
 
35
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
36
  model = None
37
- current_model_path = None
38
 
39
- def download_model_file(filename):
40
- url = f"https://huggingface.co/{REPO_ID}/resolve/main/{filename}"
41
- local_path = f"./{filename}"
 
 
42
  if not os.path.exists(local_path):
43
  print(f"Downloading model from {url}")
44
- response = requests.get(url)
45
- with open(local_path, "wb") as f:
46
- f.write(response.content)
47
- return local_path
48
-
49
- def load_model(_):
50
- global model, current_model_path
51
- selected_model = random.choice(MODEL_FILES)
52
- local_path = download_model_file(selected_model)
53
- model = torch.load(local_path, map_location=device)
54
  model.eval()
55
- current_model_path = selected_model
56
- return f"تم تحميل النموذج العشوائي: {selected_model}"
57
 
58
  def predict(image):
59
  if model is None:
60
- return " الرجاء تحميل نموذج أولاً"
61
  img = transform(image.convert("L")).unsqueeze(0).to(device)
62
  with torch.no_grad():
63
  outputs = model(img)
@@ -65,16 +88,15 @@ def predict(image):
65
  results = {d: round(float(p), 3) for d, p in zip(diseases, probs)}
66
  return results
67
 
 
 
 
68
  with gr.Blocks() as demo:
69
- gr.Markdown("## 🧠 CheXzero | اختر صورة أشعة لتحليلها عبر نموذج يتم تحميله عشوائيًا")
70
- with gr.Row():
71
- load_button = gr.Button("تحميل نموذج عشوائي")
72
- load_status = gr.Textbox(label="الحالة", interactive=False)
73
  with gr.Row():
74
  image_input = gr.Image(type="pil", label="صورة الأشعة")
75
  output = gr.Label(num_top_classes=5)
76
 
77
- load_button.click(fn=load_model, inputs=None, outputs=load_status)
78
  image_input.change(fn=predict, inputs=image_input, outputs=output)
79
 
80
  demo.launch()
 
1
  import gradio as gr
2
  import torch
3
  import random
 
 
4
  from torchvision import transforms
5
  from PIL import Image
6
+ import urllib.request
7
+ import os
8
 
9
+ # اسم الريبو الخاص بك على Hugging Face
10
  REPO_ID = "Alhdrawi/x_alhdrawi"
11
+
12
+ # أسماء الملفات المرفوعة
13
  MODEL_FILES = [
14
  "best_128_0.0002_original_15000_0.859.pt",
15
  "best_128_0.0002_original_8000_0.857.pt",
 
23
  "best_64_5e-05_original_22000_0.864.pt",
24
  ]
25
 
26
+ # نفس المعالجة المستخدمة
27
+ transform = transforms.Compose([
28
+ transforms.Resize((224, 224)),
29
+ transforms.ToTensor(),
30
+ transforms.Normalize(mean=[0.485], std=[0.229])
31
+ ])
32
+
33
+ # الأمراض اللي يشخصها
34
  diseases = [
35
  "Atelectasis", "Cardiomegaly", "Consolidation", "Edema", "Effusion",
36
  "Emphysema", "Fibrosis", "Hernia", "Infiltration", "Mass", "Nodule",
37
  "Pleural_Thickening", "Pneumonia", "Pneumothorax"
38
  ]
39
 
40
+ # تعرّف كلاس النموذج - لازم تعدله حسب المعمارية
41
+ import torch.nn as nn
42
+
43
+ class SimpleCNN(nn.Module): # عدل هذا الكلاس حسب اللي دربت عليه
44
+ def __init__(self, num_classes=14):
45
+ super(SimpleCNN, self).__init__()
46
+ self.features = nn.Sequential(
47
+ nn.Conv2d(1, 32, kernel_size=3, padding=1),
48
+ nn.ReLU(inplace=True),
49
+ nn.MaxPool2d(kernel_size=2),
50
+ nn.Conv2d(32, 64, kernel_size=3, padding=1),
51
+ nn.ReLU(inplace=True),
52
+ nn.AdaptiveAvgPool2d((1, 1))
53
+ )
54
+ self.classifier = nn.Linear(64, num_classes)
55
+
56
+ def forward(self, x):
57
+ x = self.features(x)
58
+ x = x.view(x.size(0), -1)
59
+ x = self.classifier(x)
60
+ return x
61
 
62
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
63
  model = None
64
+ selected_model_file = random.choice(MODEL_FILES)
65
 
66
+ def download_and_load_model():
67
+ global model
68
+ url = f"https://huggingface.co/{REPO_ID}/resolve/main/{selected_model_file}"
69
+ local_path = f"/tmp/{selected_model_file}"
70
+
71
  if not os.path.exists(local_path):
72
  print(f"Downloading model from {url}")
73
+ urllib.request.urlretrieve(url, local_path)
74
+
75
+ model = SimpleCNN(num_classes=len(diseases)).to(device)
76
+ state_dict = torch.load(local_path, map_location=device)
77
+ model.load_state_dict(state_dict)
 
 
 
 
 
78
  model.eval()
79
+ print(f"✅ Model loaded: {selected_model_file}")
 
80
 
81
  def predict(image):
82
  if model is None:
83
+ return "النموذج غير محمّل"
84
  img = transform(image.convert("L")).unsqueeze(0).to(device)
85
  with torch.no_grad():
86
  outputs = model(img)
 
88
  results = {d: round(float(p), 3) for d, p in zip(diseases, probs)}
89
  return results
90
 
91
+ # تحميل النموذج تلقائيًا عند بداية التشغيل
92
+ download_and_load_model()
93
+
94
  with gr.Blocks() as demo:
95
+ gr.Markdown(f"## 🧠 CheXzero | النموذج العشوائي المحمّل: `{selected_model_file}`")
 
 
 
96
  with gr.Row():
97
  image_input = gr.Image(type="pil", label="صورة الأشعة")
98
  output = gr.Label(num_top_classes=5)
99
 
 
100
  image_input.change(fn=predict, inputs=image_input, outputs=output)
101
 
102
  demo.launch()