muhammadhamza-stack commited on
Commit
8038115
·
1 Parent(s): b53d31e

initial commit

Browse files
.DS_Store ADDED
Binary file (6.15 kB). View file
 
app.py ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+ from PIL import Image
4
+ import torch
5
+ from torchvision import models, transforms
6
+ from ultralytics import YOLO
7
+ import gradio as gr
8
+ import torch.nn as nn
9
+ import os
10
+ from datetime import datetime
11
+ import json
12
+
13
+ # ============================================
14
+ # RICE ANALYZER PRO - Advanced Analytics Dashboard
15
+ # A professional grain analysis platform with statistics and batch processing
16
+ # ============================================
17
+
18
+ # --- SYSTEM CONFIGURATION ---
19
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
20
+
21
+ # Model initialization
22
+ try:
23
+ detection_model = YOLO('best.pt')
24
+ classifier_network = models.resnet50(weights=None)
25
+ classifier_network.fc = nn.Linear(classifier_network.fc.in_features, 3)
26
+ classifier_network.load_state_dict(torch.load('rice_resnet_model.pth', map_location=device))
27
+ classifier_network = classifier_network.to(device)
28
+ classifier_network.eval()
29
+ models_loaded = True
30
+ except Exception as e:
31
+ print(f" Model initialization failed: {e}")
32
+ detection_model = None
33
+ classifier_network = None
34
+ models_loaded = False
35
+
36
+ # Variety definitions
37
+ VARIETY_MAP = {
38
+ 0: "C9 Premium",
39
+ 1: "Kant Special",
40
+ 2: "Superfine Grade"
41
+ }
42
+
43
+ VARIETY_COLORS = {
44
+ "C9 Premium": (255, 100, 100), # Red
45
+ "Kant Special": (100, 100, 255), # Blue
46
+ "Superfine Grade": (100, 255, 100) # Green
47
+ }
48
+
49
+ # Data preprocessing pipeline
50
+ image_preprocessor = transforms.Compose([
51
+ transforms.Resize((224, 224)),
52
+ transforms.ToTensor(),
53
+ transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
54
+ ])
55
+
56
+ # --- ANALYTICS FUNCTIONS ---
57
+
58
+ def analyze_single_grain(grain_image):
59
+ """Perform classification on an individual grain"""
60
+ if not models_loaded:
61
+ return "System Error"
62
+
63
+ tensor_input = image_preprocessor(grain_image).unsqueeze(0).to(device)
64
+ with torch.no_grad():
65
+ prediction = classifier_network(tensor_input)
66
+ class_idx = torch.argmax(prediction, dim=1).item()
67
+ return VARIETY_MAP[class_idx]
68
+
69
+ def compute_distribution_stats(variety_counts):
70
+ """Generate statistical summary of grain distribution"""
71
+ total = sum(variety_counts.values())
72
+ if total == 0:
73
+ return "No grains detected for analysis."
74
+
75
+ stats = [" **Distribution Analysis**\n"]
76
+ stats.append(f" Total Grains Detected: **{total}**\n")
77
+ stats.append("\n**Breakdown by Variety:**\n")
78
+
79
+ for variety, count in sorted(variety_counts.items(), key=lambda x: x[1], reverse=True):
80
+ percentage = (count / total) * 100
81
+ bar_length = int(percentage / 5)
82
+ bar = "█" * bar_length + "░" * (20 - bar_length)
83
+ stats.append(f"- {variety}: {count} grains ({percentage:.1f}%) {bar}\n")
84
+
85
+ # Dominant variety
86
+ dominant = max(variety_counts.items(), key=lambda x: x[1])
87
+ stats.append(f"\n **Dominant Variety:** {dominant[0]}")
88
+
89
+ return "".join(stats)
90
+
91
+ def execute_batch_analysis(input_img):
92
+ """Main processing pipeline with analytics"""
93
+ if not models_loaded:
94
+ raise gr.Error(" Analysis engine unavailable. Please check model files.")
95
+
96
+ if input_img is None:
97
+ raise gr.Error(" Please upload an image to begin analysis.")
98
+
99
+ # Convert and prepare image
100
+ img_array = np.array(input_img)
101
+ img_bgr = cv2.cvtColor(img_array, cv2.COLOR_RGB2BGR)
102
+
103
+ # Detection phase
104
+ detection_results = detection_model(img_bgr, verbose=False)[0]
105
+ bounding_boxes = detection_results.boxes.xyxy.cpu().numpy()
106
+
107
+ if len(bounding_boxes) == 0:
108
+ gr.Warning("⚠️ No rice grains found. Try a clearer image.")
109
+ return (
110
+ Image.fromarray(cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)),
111
+ "No grains detected in the provided image."
112
+ )
113
+
114
+ # Classification phase with tracking
115
+ variety_counter = {v: 0 for v in VARIETY_MAP.values()}
116
+
117
+ for box in bounding_boxes:
118
+ x1, y1, x2, y2 = map(int, box[:4])
119
+ grain_crop = img_bgr[y1:y2, x1:x2]
120
+
121
+ if grain_crop.shape[0] > 0 and grain_crop.shape[1] > 0:
122
+ grain_pil = Image.fromarray(cv2.cvtColor(grain_crop, cv2.COLOR_BGR2RGB))
123
+ variety_label = analyze_single_grain(grain_pil)
124
+ variety_counter[variety_label] += 1
125
+
126
+ # Visualization with color coding
127
+ color = VARIETY_COLORS[variety_label]
128
+ cv2.rectangle(img_bgr, (x1, y1), (x2, y2), color, 3)
129
+
130
+ # Label with background
131
+ label_text = variety_label
132
+ (text_w, text_h), _ = cv2.getTextSize(label_text, cv2.FONT_HERSHEY_SIMPLEX, 0.7, 2)
133
+ cv2.rectangle(img_bgr, (x1, y1-text_h-10), (x1+text_w, y1), color, -1)
134
+ cv2.putText(img_bgr, label_text, (x1, y1-5),
135
+ cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2)
136
+
137
+ # Generate analytics
138
+ statistics_report = compute_distribution_stats(variety_counter)
139
+
140
+ return (
141
+ Image.fromarray(cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)),
142
+ statistics_report
143
+ )
144
+
145
+ # --- GRADIO INTERFACE ---
146
+
147
+ custom_css = """
148
+ .gradio-container {
149
+ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
150
+ }
151
+ .header-box {
152
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
153
+ padding: 30px;
154
+ border-radius: 15px;
155
+ color: white;
156
+ text-align: center;
157
+ margin-bottom: 20px;
158
+ }
159
+ .stat-box {
160
+ background: #f8f9fa;
161
+ border-left: 4px solid #667eea;
162
+ padding: 15px;
163
+ border-radius: 8px;
164
+ margin: 10px 0;
165
+ }
166
+ """
167
+
168
+ with gr.Blocks(css=custom_css, title="Rice Analyzer Pro") as app:
169
+
170
+ gr.HTML("""
171
+ <div class="header-box">
172
+ <h1>🌾 Rice Analyzer Pro</h1>
173
+ <p style="font-size: 18px; margin-top: 10px;">
174
+ Advanced Grain Analytics Platform | Professional Quality Assessment
175
+ </p>
176
+ </div>
177
+ """)
178
+
179
+ with gr.Tabs():
180
+ # Main Analysis Tab
181
+ with gr.Tab("Analysis app"):
182
+ gr.Markdown("""
183
+ ### How It Works
184
+ 1. **Upload** your rice sample image (clear photos work best)
185
+ 2. **Analyze** Click on "Start Analysis" and let Our AI model detect and classify each grain
186
+ 3. **Review** detailed statistics and visual results
187
+
188
+ **Color Coding:** 🔵 C9 Premium | 🔴 Kant Special | 🟢 Superfine Grade
189
+ """)
190
+
191
+ with gr.Row():
192
+ with gr.Column(scale=1):
193
+ image_upload = gr.Image(type="pil", label="📸 Sample Image")
194
+ analyze_button = gr.Button(" Start Analysis", variant="primary", size="lg")
195
+
196
+ with gr.Column(scale=1):
197
+ output_visualization = gr.Image(label=" Annotated Results")
198
+
199
+ with gr.Row():
200
+ statistics_output = gr.Markdown(label=" Statistical Report")
201
+
202
+ analyze_button.click(
203
+ fn=execute_batch_analysis,
204
+ inputs=image_upload,
205
+ outputs=[output_visualization, statistics_output]
206
+ )
207
+
208
+ # Documentation Tab
209
+ with gr.Tab(" Documentation"):
210
+ gr.Markdown("""
211
+ ## System Overview
212
+
213
+ **Rice Analyzer Pro** uses a two-stage deep learning pipeline:
214
+ - **Stage 1:** YOLO-based grain detection
215
+ - **Stage 2:** ResNet50 variety classification
216
+
217
+ ### Supported Varieties
218
+ | Variety | Description | Market Grade |
219
+ |---------|-------------|--------------|
220
+ | C9 Premium | High-quality long grain | Premium |
221
+ | Kant Special | Medium grain specialty | Standard |
222
+ | Superfine Grade | Ultra-refined grain | Super Fine |
223
+
224
+ ### Best Practices
225
+ - Use well-lit images with minimal shadows
226
+ - Ensure grains are separated (not clumped)
227
+ - Plain backgrounds yield better results
228
+ - Recommended resolution: 1024x1024 or higher
229
+
230
+ ### Technical Specifications
231
+ - Detection Model: YOLOv8
232
+ - Classification: ResNet50 (Fine-tuned)
233
+ - Processing: GPU-accelerated (when available)
234
+ """)
235
+
236
+ gr.Markdown("---")
237
+ gr.Markdown("### Sample Gallery")
238
+
239
+ gr.Examples(
240
+ examples=[
241
+ "samples/rice1.jpg",
242
+ "samples/rice2.jpg",
243
+ "samples/rice4.jpg",
244
+ "samples/rice5.jpg"
245
+ ],
246
+ inputs=image_upload,
247
+ outputs=[output_visualization, statistics_output],
248
+ fn=execute_batch_analysis,
249
+ label="Click any sample to run instant analysis"
250
+ )
251
+
252
+ if __name__ == "__main__":
253
+ app.queue()
254
+ app.launch()
best.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:517d391d3ea5a490c9ef00112d735d85086449a1e8e30840a58183997bec6e48
3
+ size 5520595
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ numpy<2
2
+ Pillow>=9.0.0
3
+ gradio==3.50.2
4
+ gradio-client==0.6.1
5
+ torch>=2.0.0
6
+ torchvision>=0.15.0
7
+ ultralytics>=8.0.0
8
+ opencv-python-headless>=4.7.0
rice_resnet_model.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:789b26cc9b71852782ba037086806ef006c83f931ccd9a37e7ee65eb28ce5575
3
+ size 94377562
samples/.DS_Store ADDED
Binary file (6.15 kB). View file
 
samples/rice1.jpg ADDED

Git LFS Details

  • SHA256: 8dce00a91fec8e32019b2398a2b6927252bfa595ef082a9d4a28737f27524d14
  • Pointer size: 131 Bytes
  • Size of remote file: 621 kB
samples/rice2.jpg ADDED

Git LFS Details

  • SHA256: 93ee55674a7579f3513d3a92ea37b5d0598f1e2e143805fa1fdd1b3fcd492b73
  • Pointer size: 131 Bytes
  • Size of remote file: 849 kB
samples/rice4.jpg ADDED

Git LFS Details

  • SHA256: 0383e7978dbdadcebb413b9434ce77d326b0baa6d5a465e45526a262cb56ac13
  • Pointer size: 131 Bytes
  • Size of remote file: 695 kB
samples/rice5.jpg ADDED

Git LFS Details

  • SHA256: 2ab5f2d1a508f5296081533fef359c7b94db7bc005c0bbd2098bd9097f76b87d
  • Pointer size: 131 Bytes
  • Size of remote file: 913 kB