rabbydatainsight commited on
Commit
5cfe6ab
·
verified ·
1 Parent(s): 99699a4

Upload 3 files

Browse files
Files changed (3) hide show
  1. app.py +54 -0
  2. best_model_swin.pth +3 -0
  3. requirements.txt +5 -0
app.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py (Use this code for Hugging Face)
2
+ import torch
3
+ import gradio as gr
4
+ from PIL import Image
5
+ from transformers import SwinForImageClassification, ViTImageProcessor
6
+
7
+ # --- 1. Load Model & Processor ---
8
+ MODEL_NAME = "microsoft/swin-tiny-patch4-window7-224"
9
+ MODEL_PATH = "best_model_swin.pth"
10
+ NUM_CLASSES = 3
11
+ CLASS_NAMES = ['COVID19', 'NORMAL', 'PNEUMONIA']
12
+ device = torch.device("cpu") # Use CPU for free-tier hosting
13
+
14
+ processor = ViTImageProcessor.from_pretrained(MODEL_NAME)
15
+ model = SwinForImageClassification.from_pretrained(
16
+ MODEL_NAME,
17
+ num_labels=NUM_CLASSES,
18
+ ignore_mismatched_sizes=True
19
+ )
20
+ model.load_state_dict(torch.load(MODEL_PATH, map_location=device))
21
+ model.to(device)
22
+ model.eval()
23
+
24
+ # --- 2. Define Prediction Function ---
25
+ def classify_image(input_image: Image.Image):
26
+ if input_image is None:
27
+ return "Please upload an image."
28
+ if input_image.mode != "RGB":
29
+ input_image = input_image.convert("RGB")
30
+
31
+ inputs = processor(images=input_image, return_tensors="pt")
32
+ pixel_values = inputs['pixel_values'].to(device)
33
+
34
+ with torch.no_grad():
35
+ outputs = model(pixel_values)
36
+
37
+ probabilities = torch.nn.functional.softmax(outputs.logits, dim=1)
38
+
39
+ # Create a dictionary of {class_name: probability}
40
+ confidences = {CLASS_NAMES[i]: prob.item() for i, prob in enumerate(probabilities[0])}
41
+
42
+ return confidences
43
+
44
+ # --- 3. Create the Gradio Interface ---
45
+ iface = gr.Interface(
46
+ fn=classify_image,
47
+ inputs=gr.Image(type="pil", label="Upload Chest X-Ray"),
48
+ outputs=gr.Label(num_top_classes=3, label="Predictions"),
49
+ title="Swin Transformer Chest X-Ray Classifier",
50
+ description="Upload an X-ray image to classify it as COVID-19, Normal, or Pneumonia."
51
+ )
52
+
53
+ # --- 4. Launch the app ---
54
+ iface.launch()
best_model_swin.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2ac3270d49c78130820f0ef852c827788dafe8780a19abd55deb3f807e4f3a9b
3
+ size 110416869
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # requirements.txt
2
+ torch
3
+ transformers
4
+ gradio
5
+ pillow