File size: 11,710 Bytes
4795176
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81f02dd
 
 
8445179
81f02dd
 
 
 
4795176
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81f02dd
 
 
 
 
4795176
 
 
 
 
 
 
 
 
 
 
 
 
81f02dd
 
 
 
 
 
 
 
 
 
 
4795176
 
 
81f02dd
 
 
 
 
 
8445179
4795176
 
 
 
 
 
 
8445179
 
6460e33
4795176
 
81f02dd
6460e33
4795176
 
 
 
 
81f02dd
 
 
4795176
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81f02dd
 
 
4795176
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81f02dd
 
4795176
 
 
 
 
 
 
81f02dd
 
 
8445179
81f02dd
 
2a60c75
4795176
 
 
 
 
2a60c75
 
 
 
d36ef68
 
 
 
2a60c75
 
4795176
 
 
 
2a60c75
81f02dd
4795176
6460e33
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
# import cv2
# import numpy as np
# from PIL import Image
# import torch
# from torchvision import models, transforms
# from ultralytics import YOLO
# import gradio as gr
# import torch.nn as nn

# # Initialize device
# device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

# # Load models
# yolo_model = YOLO('best.pt')  # Make sure this file is uploaded
# resnet = models.resnet50(pretrained=False)
# resnet.fc = nn.Linear(resnet.fc.in_features, 3)
# resnet.load_state_dict(torch.load('rice_resnet_model.pth', map_location=device))
# resnet = resnet.to(device)
# resnet.eval()

# # Class labels
# class_labels = ["c9", "kant", "superf"]

# # Image transformations
# transform = transforms.Compose([
#     transforms.Resize((224, 224)),
#     transforms.ToTensor(),
#     transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
# ])

# def classify_crop(crop_img):
#     """ایک چاول کے دانے کو درجہ بند کریں"""
#     image = transform(crop_img).unsqueeze(0).to(device)
#     with torch.no_grad():
#         output = resnet(image)
#         _, predicted = torch.max(output, 1)
#     return class_labels[predicted.item()]

# def detect_and_classify(input_image):
#     """تصویر پر کارروائی کریں اور ہر دانے کو شناخت کریں"""
#     image = np.array(input_image)
#     image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)

#     results = yolo_model(image)[0]
#     boxes = results.boxes.xyxy.cpu().numpy()

#     for box in boxes:
#         x1, y1, x2, y2 = map(int, box[:4])
#         crop = image[y1:y2, x1:x2]
#         crop_pil = Image.fromarray(cv2.cvtColor(crop, cv2.COLOR_BGR2RGB))
#         predicted_label = classify_crop(crop_pil)

#         cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 2)
#         cv2.putText(image, 
#                    predicted_label, 
#                    (x1, y1-10), 
#                    cv2.FONT_HERSHEY_SIMPLEX, 
#                    0.9, 
#                    (36, 255, 12), 
#                    2)

#     return Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))

# with gr.Blocks(title="چاول کی اقسام کی درجہ بندی") as demo:
#     gr.Markdown("""
#     ## 🍚 چاول کی اقسام کی شناخت کا نظام  
#     ایک تصویر اپ لوڈ کریں جس میں چاول کے دانے ہوں۔  
#     سسٹم ہر دانے کو شناخت اور درجہ بند کرے گا۔
#     """)
    
#     with gr.Row():
#         with gr.Column():
#             image_input = gr.Image(type="pil", label="چاول کی تصویر اپ لوڈ کریں")
#             submit_btn = gr.Button("تجزیہ شروع کریں", variant="primary")
#         with gr.Column():
#             output_image = gr.Image(label="نتائج", interactive=False)
    
#     submit_btn.click(
#         fn=detect_and_classify,
#         inputs=image_input,
#         outputs=output_image
#     )
    
#     # ✅ Move this block inside the `with gr.Blocks(...)` scope
#     gr.Examples(
#         examples=[
#             "samples/rice1.jpg",
#             "samples/rice2.jpg",
#             "samples/rice3.jpg",
#             "samples/rice4.jpg",
#             "samples/rice5.jpg",
#             "samples/rice6.jpg"
#         ],
#         inputs=image_input,
#         label="مثال تصاویر"
#     )
#     gr.Markdown("""
# ### ℹ️ ہدایات:
# - ✅ واضح اور الگ الگ چاول کے دانے والی تصویر اپ لوڈ کریں۔
# - ⚠️ اگر دانے آپس میں جُڑے ہوں یا ایک دوسرے پر چڑھے ہوں، تو نتائج متاثر ہو سکتے ہیں۔
# - 📸 بہتر پہچان کے لیے تصویر کا پس منظر صاف اور دانے منتشر (پھیلے ہوئے) ہونے چاہئیں۔
# - 🖼️ آپ اوپر دی گئی مثال تصاویر کو بھی دیکھ سکتے ہیں۔
# """)



# demo.launch()







import cv2
import numpy as np
from PIL import Image
import torch
from torchvision import models, transforms
from ultralytics import YOLO
import gradio as gr
import torch.nn as nn
import os 

# --- DOCUMENTATION STRINGS (English and Urdu) ---

USAGE_GUIDELINES = """
## 1. Quick Start Guide: Run Instructions

**English:**
1. **Upload:** Click the 'Upload Rice Image' box and select your image (JPG or PNG).
2. **Run:** Click the **"Run Analysis"** button.
3. **Review:** The output image will show each detected rice grain marked with its predicted class label.

**Urdu (اردو):**
## 1. فوری استعمال کی ہدایات: تجزیہ شروع کریں
1. **تصویر اپ لوڈ کریں:** 'چاول کی تصویر اپ لوڈ کریں' کے باکس پر کلک کریں اور اپنی تصویر (JPG یا PNG) منتخب کریں۔
2. **چلائیں:** **"تجزیہ شروع کریں"** بٹن پر کلک کریں۔
3. **نتائج دیکھیں:** آؤٹ پٹ تصویر ہر شناخت شدہ چاول کے دانے کو اس کی پیش گوئی کردہ قسم کے لیبل کے ساتھ دکھائے گی۔
"""

INPUT_EXPLANATION = """
## 2. Expected Inputs / متوقع ان پٹ

| Input Field (ان پٹ فیلڈ) | Purpose (مقصد) | Requirement (ضرورت) |
| :--- | :--- | :--- |
| **Upload Image** / تصویر اپ لوڈ کریں | The image containing the rice grains for analysis. | Must be a single image file (JPG, PNG). The input should preferably contain clear, separated rice grains. |

**Important Note (اہم نوٹ):** For the best detection and classification accuracy, ensure the rice grains are scattered (not heavily overlapping) and the background is simple.
"""

OUTPUT_EXPLANATION = """
## 3. Expected Outputs (Detection and Classification) / متوقع آؤٹ پٹ

The output is the original image overlayed with results from the two-stage AI model:

*   **Bounding Boxes:** Each individual rice grain detected by the YOLO model is enclosed in a **Green rectangle**.
*   **Labels:** Above each rectangle, the predicted class label is displayed:
    *   **c9** (A specific rice variety)
    *   **kant** (Another specific rice variety)
    *   **superf** (A third specific rice variety)

**Urdu (اردو):**
آؤٹ پٹ اصل تصویر ہوگی جس پر دو مراحل پر مشتمل AI ماڈل کے نتائج لگائے گئے ہیں:
*   **نشان زد ڈبے:** YOLO ماڈل سے تلاش کیے گئے ہر چاول کے دانے کے گرد **سبز رنگ کا مستطیل** لگایا جائے گا۔
*   **لیبلز:** ہر مستطیل کے اوپر اس کی پیش گوئی کردہ قسم کا لیبل درج ہوگا: c9، kant، یا superf۔
"""

# --- CORE LOGIC (KEPT AS IS) ---

# Initialize device
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

# Load models
# NOTE: These paths (best.pt, rice_resnet_model.pth) must exist in the execution directory.
try:
    yolo_model = YOLO('best.pt') 
    resnet = models.resnet50(weights=None) # Use weights=None since we are loading custom weights
    resnet.fc = nn.Linear(resnet.fc.in_features, 3)
    resnet.load_state_dict(torch.load('rice_resnet_model.pth', map_location=device))
    resnet = resnet.to(device)
    resnet.eval()
except Exception as e:
    print(f"Error loading models: {e}. Ensure 'best.pt' and 'rice_resnet_model.pth' are present.")
    yolo_model = None
    resnet = None
    
# Class labels
class_labels = ["c9", "kant", "superf"]

# Image transformations
transform = transforms.Compose([
    transforms.Resize((224, 224)),
    transforms.ToTensor(),
    transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])

def classify_crop(crop_img):
    """Classify a single rice grain crop"""
    if resnet is None:
        return "Error"
    image = transform(crop_img).unsqueeze(0).to(device)
    with torch.no_grad():
        output = resnet(image)
        _, predicted = torch.max(output, 1)
    return class_labels[predicted.item()]

def detect_and_classify(input_image):
    """Process the image and classify each grain"""
    if yolo_model is None or resnet is None:
        raise gr.Error("Models failed to load. Cannot proceed with analysis.")
        
    if input_image is None:
        raise gr.Error("Please upload an image or select an example.")
        
    image = np.array(input_image)
    image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)

    # YOLO Detection
    results = yolo_model(image, verbose=False)[0]
    boxes = results.boxes.xyxy.cpu().numpy()

    if len(boxes) == 0:
        gr.Warning("No rice grains detected in the image.")
        return Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))


    for box in boxes:
        x1, y1, x2, y2 = map(int, box[:4])
        crop = image[y1:y2, x1:x2]
        
        # Check if crop is valid
        if crop.shape[0] > 0 and crop.shape[1] > 0:
            crop_pil = Image.fromarray(cv2.cvtColor(crop, cv2.COLOR_BGR2RGB))
            predicted_label = classify_crop(crop_pil)
    
            # Draw results
            cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 2) # Green box
            cv2.putText(image, 
                       predicted_label, 
                       (x1, y1-10), 
                       cv2.FONT_HERSHEY_SIMPLEX, 
                       0.9, 
                       (36, 255, 12), 
                       2) # Green text

    return Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))

# --- GRADIO UI (Single Tab) ---

with gr.Blocks(title="Rice Variety Classification") as demo:
    
    gr.Markdown(
        """
        # Rice Variety Classification System / چاول کی اقسام کی شناخت کا نظام
        Upload an image containing rice grains. The system will detect and classify each grain using a two-stage AI pipeline (YOLO for detection, ResNet for classification).
        """
    )
    
    # 1. GUIDELINES SECTION
    with gr.Accordion(" Tips & Guidelines (ہدایات)", open=False):
        gr.Markdown(USAGE_GUIDELINES)
        gr.Markdown("---")
        gr.Markdown(INPUT_EXPLANATION)
        gr.Markdown("---")
        gr.Markdown(OUTPUT_EXPLANATION)
        
    gr.Markdown("---")

    # 2. APPLICATION INTERFACE
    gr.Markdown("## Start Analysis / تجزیہ شروع کریں")
    
    with gr.Row():
        with gr.Column(scale=1):
            gr.Markdown("## Step 1: Upload an Image of Rice /  چاول کی تصویر اپ لوڈ کریں")
            image_input = gr.Image(type="pil")
            gr.Markdown("## Step 2: Click Run Analysis /تجزیہ شروع کریں  ")
            submit_btn = gr.Button("Run Analysis / تجزیہ شروع کریں", variant="primary")
            gr.Markdown("## Outputs / نتائج ")
            output_image = gr.Image(scale=2, interactive=True)
    
    submit_btn.click(
        fn=detect_and_classify,
        inputs=image_input,
        outputs=output_image
    )
    
    gr.Markdown("---")

    # 3. EXAMPLES SECTION
    gr.Markdown("## Example Images / مثال تصاویر")
    # Ensure "samples/" directory exists and contains these images
    gr.Examples(
        examples=[
            "samples/rice1.jpg",
            "samples/rice2.jpg",
            "samples/rice3.jpg",
            "samples/rice4.jpg",
            "samples/rice5.jpg",
            "samples/rice6.jpg"
        ],
        inputs=image_input,
        outputs=output_image, # Required for proper caching and execution
        fn=detect_and_classify, # Required for proper caching and execution
        cache_examples=True,
        label="Click to load and run a sample image / نمونہ تصویر لوڈ اور رن کرنے کے لیے کلک کریں"
    )

demo.queue()
demo.launch()