eyad-ai commited on
Commit
c5a5fb2
·
verified ·
1 Parent(s): 29e5f8c

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +64 -0
app.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ import torch.nn as nn
4
+ from transformers import AutoImageProcessor, AutoModel
5
+ from peft import PeftModel
6
+ from huggingface_hub import hf_hub_download
7
+ from PIL import Image
8
+
9
+ REPO_ID = "eyad-ai/SmartChestXRay"
10
+ CLASSES = ["COVID", "Lung_Opacity", "Normal", "Viral Pneumonia"]
11
+
12
+ print("⏳ جاري تحميل النموذج على الـ Space...")
13
+ processor = AutoImageProcessor.from_pretrained("microsoft/rad-dino")
14
+ base_backbone = AutoModel.from_pretrained("microsoft/rad-dino")
15
+ peft_model = PeftModel.from_pretrained(base_backbone, REPO_ID)
16
+ merged_backbone = peft_model.merge_and_unload()
17
+ hidden_size = merged_backbone.config.hidden_size
18
+
19
+ class ChestXRayModel(nn.Module):
20
+ def __init__(self, backbone, hidden_size, num_classes):
21
+ super().__init__()
22
+ self.backbone = backbone
23
+ self.classifier = nn.Sequential(
24
+ nn.Dropout(0.0),
25
+ nn.Linear(hidden_size, num_classes)
26
+ )
27
+
28
+ def forward(self, pixel_values):
29
+ outputs = self.backbone(pixel_values=pixel_values)
30
+ pooled = outputs.pooler_output if getattr(outputs, "pooler_output", None) is not None else outputs.last_hidden_state[:, 0, :]
31
+ return self.classifier(pooled)
32
+
33
+ model = ChestXRayModel(merged_backbone, hidden_size, len(CLASSES))
34
+
35
+ head_path = hf_hub_download(repo_id=REPO_ID, filename="disease_head.pt")
36
+ state_dict = torch.load(head_path, map_location="cpu")
37
+ with torch.no_grad():
38
+ model.classifier[1].weight.copy_(state_dict["1.weight"])
39
+ model.classifier[1].bias.copy_(state_dict["1.bias"])
40
+
41
+ model.eval()
42
+
43
+ def predict(image):
44
+ if image is None:
45
+ return "الرجاء رفع صورة"
46
+
47
+ image = image.convert("RGB")
48
+ inputs = processor(images=image, return_tensors="pt")
49
+
50
+ with torch.no_grad():
51
+ outputs = model(**inputs)
52
+ probs = torch.nn.functional.softmax(outputs, dim=-1)[0]
53
+
54
+ return {CLASSES[i]: float(probs[i]) for i in range(len(CLASSES))}
55
+
56
+ demo = gr.Interface(
57
+ fn=predict,
58
+ inputs=gr.Image(type="pil"),
59
+ outputs=gr.Label(num_top_classes=4),
60
+ title="Smart Chest X-Ray Classification"
61
+ )
62
+
63
+ if __name__ == "__main__":
64
+ demo.launch()