asdfaman commited on
Commit
16d9395
·
verified ·
1 Parent(s): ab97a00

create app,py

Browse files
Files changed (1) hide show
  1. app.py +352 -0
app.py ADDED
@@ -0,0 +1,352 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from ultralytics import YOLO
3
+ import tensorflow as tf # Change this to import TensorFlow
4
+ import numpy as np
5
+ from PIL import Image, ImageOps, ImageDraw, ImageFont
6
+ import pandas as pd
7
+ import time
8
+ from paddleocr import PaddleOCR, draw_ocr
9
+ import re
10
+ import dateparser
11
+ import os
12
+ import matplotlib.pyplot as plt
13
+
14
+ # Initialize PaddleOCR model
15
+ ocr = PaddleOCR(use_angle_cls=True, lang='en')
16
+ # Define the class names based on your dataset
17
+ class_names = [
18
+ 'fresh_apple', 'fresh_banana', 'fresh_bitter_gourd', 'fresh_capsicum',
19
+ 'fresh_orange', 'fresh_tomato', 'stale_apple', 'stale_banana',
20
+ 'stale_bitter_gourd', 'stale_capsicum', 'stale_orange', 'stale_tomato'
21
+ ]
22
+
23
+ # Team details
24
+ team_members = [
25
+ {"name": "Aman Deep", "image": "aman.jpg"}, # Replace with actual paths to images
26
+ {"name": "Abhishek Kumar Choudhary", "image": "myimage.jpg"},
27
+ {"name": "Gaurav Lodhi", "image": "gaurav.jpg"},
28
+ {"name": "Anand Jha", "image": "anandimg.jpg"}
29
+ ]
30
+
31
+ # Function to preprocess the images for the model
32
+ from PIL import Image
33
+ import numpy as np
34
+
35
+ def preprocess_image(image):
36
+ """
37
+ Preprocess the input image for model prediction.
38
+
39
+ Args:
40
+ image (PIL.Image): Input image in PIL format.
41
+
42
+ Returns:
43
+ np.ndarray: Preprocessed image array ready for prediction.
44
+ """
45
+ try:
46
+ # Resize image to match model input size
47
+ img = image.resize((128, 128), Image.LANCZOS) # Using LANCZOS filter for high-quality resizing
48
+
49
+ # Convert image to NumPy array
50
+ img_array = np.array(img)
51
+
52
+ # Check if the image is grayscale and convert to RGB if needed
53
+ if img_array.ndim == 2: # Grayscale image
54
+ img_array = np.stack([img_array] * 3, axis=-1) # Convert to 3-channel RGB
55
+ elif img_array.shape[2] == 1: # Single-channel image
56
+ img_array = np.concatenate([img_array, img_array, img_array], axis=-1) # Convert to RGB
57
+
58
+ # Normalize pixel values to [0, 1] range
59
+ img_array = img_array / 255.0
60
+
61
+ # Add batch dimension
62
+ img_array = np.expand_dims(img_array, axis=0) # Shape: (1, 128, 128, 3)
63
+
64
+ return img_array
65
+
66
+ except Exception as e:
67
+ print(f"Error processing image: {e}")
68
+ return None # Return None if there's an error
69
+
70
+
71
+ # Function to create a high-quality circular mask for an image
72
+ def make_image_circular1(img, size=(256, 256)):
73
+ img = img.resize(size, Image.LANCZOS)
74
+ mask = Image.new("L", size, 0)
75
+ draw = ImageDraw.Draw(mask)
76
+ draw.ellipse((0, 0) + size, fill=255)
77
+ output = ImageOps.fit(img, mask.size, centering=(0.5, 0.5))
78
+ output.putalpha(mask) # Apply the mask as transparency
79
+ return output
80
+ # Function to check if a file exists
81
+ def file_exists(file_path):
82
+ return os.path.isfile(file_path)
83
+
84
+ def make_image_circular(image):
85
+ # Create a circular mask
86
+ mask = Image.new("L", image.size, 0)
87
+ draw = ImageDraw.Draw(mask)
88
+ draw.ellipse((0, 0, image.size[0], image.size[1]), fill=255)
89
+
90
+ # Apply the mask to the image
91
+ circular_image = Image.new("RGB", image.size)
92
+ circular_image.paste(image.convert("RGBA"), (0, 0), mask)
93
+
94
+ return circular_image
95
+
96
+ # Function to extract dates from recognized text using regex
97
+ def extract_dates_with_dateparser(texts, result):
98
+ date_texts = []
99
+ date_boxes = []
100
+ date_scores = []
101
+
102
+ def is_potential_date(text):
103
+ valid_date_pattern = r'^(0[1-9]|[12][0-9]|3[01])[-/.]?(0[1-9]|1[0-2])[-/.]?(\d{2}|\d{4})$|' \
104
+ r'^(0[1-9]|[12][0-9]|3[01])[-/.]?[A-Za-z]{3}[-/.]?(\d{2}|\d{4})$|' \
105
+ r'^(0[1-9]|1[0-2])[-/.]?(\d{2}|\d{4})$|' \
106
+ r'^[A-Za-z]{3}[-/.]?(\d{2}|\d{4})$'
107
+ return bool(re.match(valid_date_pattern, text))
108
+
109
+ dates_found = []
110
+ for i, text in enumerate(texts):
111
+ if is_potential_date(text): # Only process texts that are potential dates
112
+ parsed_date = dateparser.parse(text, settings={'DATE_ORDER': 'DMY'})
113
+ if parsed_date:
114
+ dates_found.append(parsed_date.strftime('%Y-%m-%d')) # Store as 'YYYY-MM-DD'
115
+ date_texts.append(text) # Store the original text
116
+ date_boxes.append(result[0][i][0]) # Store the bounding box
117
+ date_scores.append(result[0][i][1][1]) # Store confidence score
118
+ return dates_found, date_texts, date_boxes, date_scores
119
+
120
+ # Function to display circular images in a matrix format
121
+ def display_images_in_grid(images, max_images_per_row=4):
122
+ num_images = len(images)
123
+ num_rows = (num_images + max_images_per_row - 1) // max_images_per_row # Calculate number of rows
124
+
125
+ for i in range(num_rows):
126
+ cols = st.columns(min(max_images_per_row, num_images - i * max_images_per_row))
127
+ for j, img in enumerate(images[i * max_images_per_row:(i + 1) * max_images_per_row]):
128
+ with cols[j]:
129
+ st.image(img, use_column_width=True)
130
+
131
+ # Function to display team members in circular format
132
+ def display_team_members(members, max_members_per_row=4):
133
+ num_members = len(members)
134
+ num_rows = (num_members + max_members_per_row - 1) // max_members_per_row # Calculate number of rows
135
+
136
+ for i in range(num_rows):
137
+ cols = st.columns(min(max_members_per_row, num_members - i * max_members_per_row))
138
+ for j, member in enumerate(members[i * max_members_per_row:(i + 1) * max_members_per_row]):
139
+ with cols[j]:
140
+ img = Image.open(member["image"]) # Load the image
141
+ circular_img = make_image_circular(img) # Convert to circular format
142
+ st.image(circular_img, use_column_width=True) # Display the circular image
143
+ st.write(member["name"]) # Display the name below the image
144
+
145
+ # Title and description
146
+ st.title("Flipkart GRID 6.0")
147
+ # Team Details with links
148
+ st.sidebar.title("Flipkart Grid 6.0")
149
+ st.sidebar.write("DELHI TECHNOLOGICAL UNIVERSITY")
150
+
151
+ # Navbar with task tabs
152
+ st.sidebar.title("Navigation")
153
+ st.sidebar.write("Team Name: aman.dp121")
154
+ app_mode = st.sidebar.selectbox("Choose the task", ["Welcome","Project Details", "Task 1", "Task 2", "Task 3", "Task 4", "Team Details"])
155
+ if app_mode == "Welcome":
156
+ # Navigation Menu
157
+ st.write("# Welcome to Flipkart GrID 6.0! 🎉")
158
+
159
+ # Example for adding a local video
160
+ # video_file = open('Finalist.mp4', 'rb') # Replace with the path to your video file
161
+ # video_bytes = video_file.read()
162
+ # Embed the video using st.video()
163
+ st.video(video_bytes)
164
+
165
+ # Add a welcome image
166
+ welcome_image = Image.open("grid_banner.jpg") # Replace with the path to your welcome image
167
+ st.image(welcome_image, use_column_width=True) # Display the welcome image
168
+
169
+ elif app_mode=="Project Details":
170
+ st.markdown("""
171
+ ## Navigation
172
+ - [Project Overview](#project-overview)
173
+ - [Proposal Round](#proposal-round)
174
+ - [Problem Statement](#problem-statement)
175
+ - [Proposed Solution](#proposed-solution)
176
+ """)
177
+ # Project Overview
178
+ st.write("## Project Overview:")
179
+ st.write("""
180
+ 1. **OCR to Extract Details** (20%):
181
+ - Use OCR to read brand details, pack size, brand name, etc.
182
+ - Train the model to read details from various products, including FMCG, OTC items, health supplements, personal care, and household items.
183
+
184
+ 2. **Using OCR for Expiry Date Details** (10%):
185
+ - Validate expiry dates using OCR to read expiry and MRP details printed on items.
186
+
187
+ 3. **Image Recognition for Brand Recognition and Counting** (30%):
188
+ - Use machine learning to recognize brands and count product quantities from images.
189
+
190
+ 4. **Detecting Freshness of Fresh Produce** (40%):
191
+ - Assess the freshness of fruits and vegetables by analyzing various visual cues and patterns.
192
+ """)
193
+
194
+ st.write("""
195
+ Our project aims to leverage OCR and image recognition to enhance product packaging analysis and freshness detection.
196
+ """)
197
+
198
+ # Proposal Round
199
+ st.write("## Proposal Round:")
200
+ st.write("""
201
+ **Format:** Use Case Submission & Code Review
202
+ - Selected teams will submit detailed use case scenarios they plan to solve.
203
+ - The submission should include a proposal outlining their approach and the code developed so far.
204
+ - The GRID team will provide a set of images for testing the model.
205
+ - Since this is an elimination stage, participants are encouraged to submit a video simulation of their solution on the image set provided to them, ensuring they can clearly articulate what they have solved.
206
+ - Teams working on detecting the freshness of produce may choose any fresh fruit/vegetable/bread, etc., and submit the freshness index based on the model.
207
+ - The video will help demonstrate the effectiveness of their approach and provide a visual representation of their solution.
208
+
209
+ Teams with the most comprehensive and innovative proposals will proceed to the final stage.
210
+ """)
211
+
212
+ # Problem Statement
213
+ st.write("## Problem Statement:")
214
+ st.write("""
215
+ In today’s fast-paced retail environment, ensuring product quality and freshness is crucial for customer satisfaction. The Flipkart GrID 6.0 Challenge aims to address this issue by leveraging technology to enhance product packaging analysis and freshness detection.
216
+
217
+ Traditional methods of checking freshness often involve manual inspection, which can be time-consuming and prone to human error. Furthermore, with the increasing variety of products available, a more automated and reliable solution is needed to streamline this process.
218
+
219
+ Our project focuses on developing an advanced system that utilizes Optical Character Recognition (OCR) and image recognition techniques to automate the extraction of product details from packaging. This will not only improve accuracy but also increase efficiency in assessing product freshness.
220
+ """)
221
+
222
+ # Proposed Solution
223
+ st.write("## Proposed Solution:")
224
+ st.write("""
225
+ Our solution is designed to tackle the problem by implementing the following key components:
226
+
227
+ ### 1. OCR for Product Detail Extraction
228
+ We will use OCR technology to accurately extract critical information from product packaging, including:
229
+ - Brand name
230
+ - Pack size
231
+ - Expiry date
232
+ - MRP details
233
+
234
+ This will allow for real-time analysis of product information, ensuring that customers receive accurate data about their purchases.
235
+
236
+ ### 2. Freshness Detection using Image Recognition
237
+ In conjunction with OCR, our model will utilize image recognition to assess the freshness of fruits, vegetables, and other perishable items. The model will be trained to classify products based on their appearance, detecting signs of spoilage and degradation.
238
+
239
+ ### 3. Data Validation and Reporting
240
+ Our system will not only extract data but also validate expiry dates against the current date to ensure product safety. The results will be compiled into a user-friendly report that can be easily interpreted by retail staff.
241
+
242
+ ### 4. Video Simulation
243
+ To effectively demonstrate our solution, we will create a video simulation showcasing the functionality of our system. This will include real-time examples of how our model processes images and extracts relevant information.
244
+
245
+ ### 5. Proposal Submission
246
+ As part of the proposal round, we will provide a comprehensive submission outlining our approach, methodology, and the code developed thus far. This submission will highlight the effectiveness of our solution and our readiness to proceed to the final stage of the challenge.
247
+
248
+ Our team is committed to delivering a robust solution that not only meets but exceeds the expectations of the Flipkart GrID 6.0 Challenge.
249
+ """)
250
+
251
+ elif app_mode == "Team Details":
252
+ st.write("## Meet Our Team:")
253
+ display_team_members(team_members)
254
+ st.write("Delhi Technological University")
255
+
256
+ elif app_mode == "Task 1":
257
+ st.write("## Task 1: 🖼️ OCR to Extract Details 📄")
258
+ st.write("Using OCR to extract details from product packaging material, including brand name and pack size.")
259
+
260
+ # File uploader for images (supports multiple files)
261
+ uploaded_files = st.file_uploader("Upload images of products", type=["jpeg", "png", "jpg"], accept_multiple_files=True)
262
+
263
+ if uploaded_files:
264
+ st.write("### Uploaded Images in Circular Format:")
265
+ circular_images = []
266
+
267
+ for uploaded_file in uploaded_files:
268
+ img = Image.open(uploaded_file)
269
+ circular_img = make_image_circular(img) # Create circular images
270
+ circular_images.append(circular_img)
271
+
272
+ # Display the circular images in a matrix/grid format
273
+ display_images_in_grid(circular_images, max_images_per_row=4)
274
+
275
+ # Function to simulate loading process with a progress bar
276
+ def simulate_progress():
277
+ progress_bar = st.progress(0)
278
+ for percent_complete in range(100):
279
+ time.sleep(0.02)
280
+ progress_bar.progress(percent_complete + 1)
281
+ # Function to remove gibberish using regex (removes non-alphanumeric chars, filters out very short text)
282
+ def clean_text(text):
283
+ # Keep text with letters, digits, and spaces, and remove short/irrelevant text
284
+ return re.sub(r'[^a-zA-Z0-9\s]', '', text).strip()
285
+
286
+ # Function to extract the most prominent text (product name) and other details
287
+ def extract_product_info(results):
288
+ product_name = ""
289
+ product_details = ""
290
+ largest_text_size = 0
291
+
292
+ for line in results:
293
+ for box in line:
294
+ text, confidence = box[1][0], box[1][1]
295
+ text_size = box[0][2][1] - box[0][0][1] # Calculate height of the text box
296
+
297
+ # Clean the text to avoid gibberish
298
+ clean_text_line = clean_text(text)
299
+
300
+ if confidence > 0.7 and len(clean_text_line) > 2: # Only consider confident, meaningful text
301
+ if text_size > largest_text_size: # Assume the largest text is the product name
302
+ largest_text_size = text_size
303
+ product_name = clean_text_line
304
+ else:
305
+ product_details += clean_text_line + " "
306
+
307
+ return product_name, product_details.strip()
308
+ if st.button("Start Analysis"):
309
+ simulate_progress()
310
+ # Loop through each uploaded image and process them
311
+ for uploaded_image in uploaded_files:
312
+ # Load the uploaded image
313
+ image = Image.open(uploaded_image)
314
+ # st.image(image, caption=f'Uploaded Image: {uploaded_image.name}', use_column_width=True)
315
+
316
+ # Convert image to numpy array for OCR processing
317
+ img_array = np.array(image)
318
+
319
+ # Perform OCR on the image
320
+ st.write(f"Extracting details from {uploaded_image.name}...")
321
+ result = ocr.ocr(img_array, cls=True)
322
+
323
+ # Process the OCR result to extract product name and properties
324
+ product_name, product_details = extract_product_info(result)
325
+
326
+ # UI display for single image product details
327
+ st.markdown("---")
328
+ st.markdown(f"### **Product Name:** `{product_name}`")
329
+ st.write(f"**Product Properties:** {product_details}")
330
+ st.markdown("---")
331
+
332
+ else:
333
+ st.write("Please upload images to extract product details.")
334
+
335
+ # Footer with animation
336
+ st.markdown("""
337
+ <style>
338
+ @keyframes fade-in {
339
+ from { opacity: 0; }
340
+ to { opacity: 1;}
341
+ }
342
+ .footer {
343
+ text-align: center;
344
+ font-size: 1.1em;
345
+ animation: fade-in 2s;
346
+ padding-top: 2rem;
347
+ }
348
+ </style>
349
+ <div class="footer">
350
+ <p>© 2024 Flipkart GRiD 6.0 Challenge. All rights reserved.</p>
351
+ </div>
352
+ """, unsafe_allow_html=True)