Spaces:
Sleeping

Prayag80 commited on
Commit
2143bab
·
0 Parent(s):

Initial Gradio API for mobile app

Browse files
Files changed (3) hide show
  1. README.md +89 -0
  2. app.py +215 -0
  3. requirements.txt +7 -0
README.md ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Diabetic Retinopathy API
3
+ emoji: 🩺
4
+ colorFrom: blue
5
+ colorTo: green
6
+ sdk: gradio
7
+ sdk_version: 4.0.0
8
+ app_file: app.py
9
+ pinned: false
10
+ ---
11
+
12
+ # Diabetic Retinopathy Detection API
13
+
14
+ API endpoint for mobile app integration. Detects diabetic retinopathy severity from retinal fundus images.
15
+
16
+ ## Model Performance
17
+
18
+ - **QWK:** 93.6%
19
+ - **Accuracy:** 89%
20
+ - **Severe/Proliferative Detection:** 99%+
21
+
22
+ ## API Usage
23
+
24
+ ### Endpoint
25
+ ```
26
+ POST https://YOUR-SPACE-NAME.hf.space/api/predict
27
+ ```
28
+
29
+ ### Request (JavaScript/React Native)
30
+ ```javascript
31
+ const formData = new FormData();
32
+ formData.append('data', {
33
+ uri: imageUri,
34
+ type: 'image/jpeg',
35
+ name: 'retinal.jpg'
36
+ });
37
+
38
+ const response = await fetch(
39
+ 'https://YOUR-SPACE-NAME.hf.space/api/predict',
40
+ {
41
+ method: 'POST',
42
+ body: formData
43
+ }
44
+ );
45
+
46
+ const result = await response.json();
47
+ ```
48
+
49
+ ### Response
50
+ ```json
51
+ {
52
+ "data": [
53
+ {
54
+ "label": "Severe",
55
+ "confidences": [
56
+ {"label": "No_DR", "confidence": 0.001},
57
+ {"label": "Mild", "confidence": 0.002},
58
+ {"label": "Moderate", "confidence": 0.005},
59
+ {"label": "Severe", "confidence": 0.992},
60
+ {"label": "Proliferative_DR", "confidence": 0.000}
61
+ ]
62
+ }
63
+ ]
64
+ }
65
+ ```
66
+
67
+ ## Classes
68
+
69
+ | Class | Description |
70
+ |-------|-------------|
71
+ | No_DR | No Diabetic Retinopathy |
72
+ | Mild | Mild Non-Proliferative DR |
73
+ | Moderate | Moderate Non-Proliferative DR |
74
+ | Severe | Severe Non-Proliferative DR |
75
+ | Proliferative_DR | Proliferative Diabetic Retinopathy |
76
+
77
+ ## Model
78
+
79
+ - **Architecture:** MobileNet V3 Large
80
+ - **Training Data:** 35,000 balanced retinal images
81
+ - **Model Weights:** [Prayag80/diabetic_retinopathy](https://huggingface.co/Prayag80/diabetic_retinopathy)
82
+
83
+ ## Disclaimer
84
+
85
+ ⚠️ This is a research tool, not a medical diagnostic device. Always consult qualified healthcare professionals for medical diagnosis.
86
+
87
+ ## License
88
+
89
+ MIT
app.py ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Gradio API for Diabetic Retinopathy Detection
3
+ Provides a simple API endpoint for mobile app integration
4
+ """
5
+
6
+ import gradio as gr
7
+ import torch
8
+ import torch.nn as nn
9
+ import torchvision.models as models
10
+ import cv2
11
+ import numpy as np
12
+ from PIL import Image
13
+ from huggingface_hub import hf_hub_download
14
+
15
+ # Model configuration
16
+ CLASS_NAMES = ['No_DR', 'Mild', 'Moderate', 'Severe', 'Proliferative_DR']
17
+ IMAGE_SIZE = 224
18
+ DEVICE = 'cpu' # Hugging Face Spaces use CPU
19
+
20
+ # Model architecture (must match training)
21
+ class MobileNet_V3_Large(nn.Module):
22
+ def __init__(self, num_classes=5):
23
+ super(MobileNet_V3_Large, self).__init__()
24
+ self.model = models.mobilenet_v3_large(weights=None)
25
+ self.model.classifier[-1] = nn.Linear(
26
+ self.model.classifier[-1].in_features,
27
+ num_classes,
28
+ bias=True
29
+ )
30
+
31
+ def forward(self, x):
32
+ return self.model(x)
33
+
34
+ # Download and load model
35
+ print("Downloading model from Hugging Face...")
36
+ model_path = hf_hub_download(
37
+ repo_id="Prayag80/diabetic_retinopathy",
38
+ filename="best_train_loss.pt"
39
+ )
40
+
41
+ print(f"Loading model from: {model_path}")
42
+ model = MobileNet_V3_Large(num_classes=5)
43
+ model.load_state_dict(torch.load(model_path, map_location=DEVICE))
44
+ model.to(DEVICE)
45
+ model.eval()
46
+ print("Model loaded successfully!")
47
+
48
+ def remove_black_borders(img, black_th=5):
49
+ """Remove black borders from retinal images"""
50
+ img_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
51
+
52
+ # x axis
53
+ centre_y = img_gray.shape[1] // 2
54
+ black_list = img_gray[:, centre_y]
55
+ black_list = np.where(black_list >= black_th)[0]
56
+
57
+ if len(black_list) > 1:
58
+ first_non_black = black_list[0]
59
+ reverse_first_non_black = black_list[-1] + 1
60
+ img = img[first_non_black:reverse_first_non_black, :, :]
61
+
62
+ # y axis
63
+ centre_x = img_gray.shape[0] // 2
64
+ black_list = img_gray[centre_x, :]
65
+ black_list = np.where(black_list >= black_th)[0]
66
+
67
+ if len(black_list) > 1:
68
+ first_non_black_y = black_list[0]
69
+ reverse_first_non_black_y = black_list[-1] + 1
70
+ img = img[:, first_non_black_y:reverse_first_non_black_y, :]
71
+
72
+ return img
73
+
74
+ def preprocess_image(image):
75
+ """Preprocess image for model inference"""
76
+ # Convert PIL to numpy
77
+ if isinstance(image, Image.Image):
78
+ image = np.array(image)
79
+
80
+ # Ensure RGB
81
+ if len(image.shape) == 2: # Grayscale
82
+ image = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB)
83
+ elif image.shape[2] == 4: # RGBA
84
+ image = cv2.cvtColor(image, cv2.COLOR_RGBA2RGB)
85
+
86
+ # Remove black borders
87
+ image = remove_black_borders(image)
88
+
89
+ # Pad to square
90
+ height, width, _ = image.shape
91
+ if height > width:
92
+ pad = (height - width) // 2
93
+ image = cv2.copyMakeBorder(image, 0, 0, pad, pad, cv2.BORDER_CONSTANT)
94
+ elif width > height:
95
+ pad = (width - height) // 2
96
+ image = cv2.copyMakeBorder(image, pad, pad, 0, 0, cv2.BORDER_CONSTANT)
97
+
98
+ # Resize
99
+ image = cv2.resize(image, (IMAGE_SIZE, IMAGE_SIZE))
100
+
101
+ # Normalize
102
+ image = image / 255.0
103
+
104
+ # Transpose to CHW format
105
+ image = np.transpose(image, (2, 0, 1))
106
+
107
+ return image
108
+
109
+ def predict_dr(image):
110
+ """
111
+ Predict diabetic retinopathy severity from retinal image
112
+
113
+ Args:
114
+ image: PIL Image or numpy array
115
+
116
+ Returns:
117
+ dict: Prediction results with label and confidences
118
+ """
119
+ try:
120
+ # Preprocess
121
+ processed = preprocess_image(image)
122
+
123
+ # Convert to tensor
124
+ tensor = torch.tensor(processed, dtype=torch.float32).unsqueeze(0).to(DEVICE)
125
+
126
+ # Predict
127
+ with torch.no_grad():
128
+ output = model(tensor)
129
+ probabilities = torch.softmax(output, dim=1).cpu().numpy()[0]
130
+
131
+ # Get predicted class
132
+ predicted_class = int(np.argmax(probabilities))
133
+ predicted_label = CLASS_NAMES[predicted_class]
134
+
135
+ # Build confidences dict for Gradio
136
+ confidences = {
137
+ name: float(prob)
138
+ for name, prob in zip(CLASS_NAMES, probabilities)
139
+ }
140
+
141
+ return confidences
142
+
143
+ except Exception as e:
144
+ print(f"Error during prediction: {str(e)}")
145
+ raise gr.Error(f"Prediction failed: {str(e)}")
146
+
147
+ # Severity information for UI
148
+ severity_info = {
149
+ "No_DR": "✅ No Diabetic Retinopathy detected. Continue regular checkups.",
150
+ "Mild": "⚠️ Mild DR detected. Consult ophthalmologist within 6-12 months.",
151
+ "Moderate": "⚠️ Moderate DR. Schedule appointment within 3-6 months.",
152
+ "Severe": "🚨 Severe DR. Urgent consultation needed within weeks.",
153
+ "Proliferative_DR": "🚨 Proliferative DR. Critical - seek immediate medical attention."
154
+ }
155
+
156
+ # Create Gradio interface
157
+ title = "🩺 Diabetic Retinopathy Detection API"
158
+ description = """
159
+ Upload a retinal fundus image to detect diabetic retinopathy severity.
160
+ This model classifies images into 5 categories: No_DR, Mild, Moderate, Severe, and Proliferative_DR.
161
+
162
+ **Model Performance:**
163
+ - Quadratic Weighted Kappa: 93.6%
164
+ - Overall Accuracy: 89%
165
+ - Severe/Proliferative Detection: 99%+
166
+
167
+ **For Mobile App API:**
168
+ - Endpoint: `/api/predict`
169
+ - Method: POST
170
+ - Returns: JSON with predictions
171
+ """
172
+
173
+ article = """
174
+ ### About
175
+ Fine-tuned MobileNet V3 Large model trained on 35,000 balanced retinal images.
176
+
177
+ ### API Usage (Mobile Apps)
178
+ ```javascript
179
+ const formData = new FormData();
180
+ formData.append('data', imageFile);
181
+
182
+ const response = await fetch('YOUR-SPACE-URL/api/predict', {
183
+ method: 'POST',
184
+ body: formData
185
+ });
186
+
187
+ const result = await response.json();
188
+ console.log(result.data[0]); // Prediction with confidences
189
+ ```
190
+
191
+ ### Important
192
+ ⚠️ This is a screening tool, not a diagnostic device. Always consult healthcare professionals.
193
+
194
+ **Created by:** Prayag Adage
195
+ **Model:** [Prayag80/diabetic_retinopathy](https://huggingface.co/Prayag80/diabetic_retinopathy)
196
+ """
197
+
198
+ # Create interface
199
+ demo = gr.Interface(
200
+ fn=predict_dr,
201
+ inputs=gr.Image(type="pil", label="Upload Retinal Image"),
202
+ outputs=gr.Label(num_top_classes=5, label="Prediction Results"),
203
+ title=title,
204
+ description=description,
205
+ article=article,
206
+ examples=[
207
+ # You can add example images here if desired
208
+ ],
209
+ allow_flagging="never",
210
+ analytics_enabled=False
211
+ )
212
+
213
+ # Launch
214
+ if __name__ == "__main__":
215
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ gradio
2
+ torch
3
+ torchvision
4
+ opencv-python-headless
5
+ numpy
6
+ Pillow
7
+ huggingface-hub