GotThatData commited on
Commit
8ee319e
·
verified ·
1 Parent(s): 4f13b31

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +229 -50
app.py CHANGED
@@ -5,19 +5,164 @@ import gradio as gr
5
  from datasets import load_dataset, Dataset
6
  import pandas as pd
7
  from PIL import Image
8
- import shutil
 
 
 
 
 
9
  from tqdm import tqdm
10
  import logging
 
11
 
12
  # Set up logging
13
  logging.basicConfig(level=logging.INFO)
14
  logger = logging.getLogger(__name__)
15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  class DatasetManager:
17
  def __init__(self, local_images_dir="downloaded_cards"):
18
  self.local_images_dir = local_images_dir
19
  self.drive = None
20
  self.dataset_name = "GotThatData/sports-cards"
 
21
 
22
  # Create local directory if it doesn't exist
23
  os.makedirs(local_images_dir, exist_ok=True)
@@ -32,8 +177,41 @@ class DatasetManager:
32
  except Exception as e:
33
  return False, f"Authentication failed: {str(e)}"
34
 
35
- def download_and_rename_files(self, drive_folder_id, naming_convention):
36
- """Download files from Google Drive and rename them"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  if not self.drive:
38
  return False, "Google Drive not authenticated", []
39
 
@@ -43,56 +221,52 @@ class DatasetManager:
43
  file_list = self.drive.ListFile({'q': query}).GetList()
44
 
45
  if not file_list:
46
- # Try to get single file if folder is empty
47
  file = self.drive.CreateFile({'id': drive_folder_id})
48
  if file:
49
  file_list = [file]
50
  else:
51
  return False, "No files found with the specified ID", []
52
 
53
- renamed_files = []
54
- existing_dataset = None
55
- try:
56
- existing_dataset = load_dataset(self.dataset_name)
57
- logger.info(f"Loaded existing dataset: {self.dataset_name}")
58
- # Get the current count of images to continue numbering
59
- start_index = len(existing_dataset['train']) if 'train' in existing_dataset else 0
60
- except Exception as e:
61
- logger.info(f"No existing dataset found, starting fresh: {str(e)}")
62
- start_index = 0
63
-
64
- for i, file in enumerate(tqdm(file_list, desc="Downloading files")):
65
  if file['mimeType'].startswith('image/'):
66
- new_filename = f"{naming_convention}_{start_index + i + 1}.jpg"
67
- file_path = os.path.join(self.local_images_dir, new_filename)
68
 
69
  # Download file
70
- file.GetContentFile(file_path)
71
 
72
- # Verify the image can be opened
73
- try:
74
- with Image.open(file_path) as img:
75
- img.verify()
76
- renamed_files.append({
77
- 'file_path': file_path,
 
 
 
 
 
 
 
78
  'original_name': file['title'],
79
  'new_name': new_filename,
80
- 'image': file_path # Adding image column for dataset
 
 
 
81
  })
82
- except Exception as e:
83
- logger.error(f"Error processing image {file['title']}: {str(e)}")
84
- if os.path.exists(file_path):
85
- os.remove(file_path)
86
 
87
- return True, f"Successfully processed {len(renamed_files)} images", renamed_files
88
  except Exception as e:
89
- return False, f"Error downloading files: {str(e)}", []
90
 
91
- def update_huggingface_dataset(self, renamed_files):
92
- """Update the sports-cards dataset with new images"""
93
  try:
94
  # Create a DataFrame with the file information
95
- df = pd.DataFrame(renamed_files)
96
 
97
  # Create a Hugging Face Dataset from the new files
98
  new_dataset = Dataset.from_pandas(df)
@@ -109,11 +283,11 @@ class DatasetManager:
109
  # Push to Hugging Face Hub
110
  new_dataset.push_to_hub(self.dataset_name, split="train")
111
 
112
- return True, f"Successfully updated dataset '{self.dataset_name}' with {len(renamed_files)} new images"
113
  except Exception as e:
114
  return False, f"Error updating Hugging Face dataset: {str(e)}"
115
 
116
- def process_pipeline(folder_id, naming_convention):
117
  """Main pipeline to process images and update dataset"""
118
  manager = DatasetManager()
119
 
@@ -122,14 +296,24 @@ def process_pipeline(folder_id, naming_convention):
122
  if not auth_success:
123
  return auth_message
124
 
125
- # Step 2: Download and rename files
126
- success, message, renamed_files = manager.download_and_rename_files(folder_id, naming_convention)
127
  if not success:
128
  return message
129
 
130
  # Step 3: Update Hugging Face dataset
131
- success, hf_message = manager.update_huggingface_dataset(renamed_files)
132
- return f"{message}\n{hf_message}"
 
 
 
 
 
 
 
 
 
 
133
 
134
  # Gradio interface
135
  demo = gr.Interface(
@@ -138,17 +322,12 @@ demo = gr.Interface(
138
  gr.Textbox(
139
  label="Google Drive File/Folder ID",
140
  placeholder="Enter the ID from your Google Drive URL",
141
- value="151VOxPO91mg0C3ORiioGUd4hogzP1ujm" # Pre-filled with provided ID
142
- ),
143
- gr.Textbox(
144
- label="Naming Convention",
145
- placeholder="e.g., card",
146
- value="sports_card"
147
  )
148
  ],
149
- outputs=gr.Textbox(label="Status"),
150
- title="Sports Cards Dataset Processor",
151
- description="Download card images from Google Drive and add them to the sports-cards dataset"
152
  )
153
 
154
  if __name__ == "__main__":
 
5
  from datasets import load_dataset, Dataset
6
  import pandas as pd
7
  from PIL import Image
8
+ import pytesseract
9
+ import cv2
10
+ import numpy as np
11
+ import tensorflow as tf
12
+ from transformers import LayoutLMv2Processor, LayoutLMv2ForSequenceClassification
13
+ import torch
14
  from tqdm import tqdm
15
  import logging
16
+ import re
17
 
18
  # Set up logging
19
  logging.basicConfig(level=logging.INFO)
20
  logger = logging.getLogger(__name__)
21
 
22
+ class CardPreprocessor:
23
+ def __init__(self):
24
+ # Initialize OCR and models
25
+ self.processor = LayoutLMv2Processor.from_pretrained("microsoft/layoutlmv2-base-uncased")
26
+ self.ocr_threshold = 0.5
27
+
28
+ def extract_text_regions(self, image):
29
+ """Extract text regions from the image using OCR"""
30
+ try:
31
+ # Convert PIL Image to cv2 format
32
+ img_cv = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
33
+
34
+ # Preprocess image for better OCR
35
+ gray = cv2.cvtColor(img_cv, cv2.COLOR_BGR2GRAY)
36
+ blurred = cv2.GaussianBlur(gray, (5, 5), 0)
37
+ thresh = cv2.threshold(blurred, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
38
+
39
+ # Perform OCR
40
+ text = pytesseract.image_to_data(thresh, output_type=pytesseract.Output.DICT)
41
+
42
+ # Extract relevant information
43
+ extracted_info = {
44
+ 'player_name': None,
45
+ 'team': None,
46
+ 'year': None,
47
+ 'card_number': None,
48
+ 'brand': None,
49
+ 'stats': []
50
+ }
51
+
52
+ # Process OCR results
53
+ for i, word in enumerate(text['text']):
54
+ if word.strip():
55
+ conf = int(text['conf'][i])
56
+ if conf > 50: # Filter low-confidence detections
57
+ # Try to identify year
58
+ year_match = re.search(r'19[0-9]{2}|20[0-2][0-9]', word)
59
+ if year_match:
60
+ extracted_info['year'] = year_match.group()
61
+
62
+ # Try to identify card number
63
+ card_num_match = re.search(r'#\d+|\d+/\d+', word)
64
+ if card_num_match:
65
+ extracted_info['card_number'] = card_num_match.group()
66
+
67
+ # Look for common card brands
68
+ brands = ['topps', 'upper deck', 'panini', 'fleer', 'bowman']
69
+ if word.lower() in brands:
70
+ extracted_info['brand'] = word.lower()
71
+
72
+ # Look for statistics (numbers with common sports stats patterns)
73
+ stats_match = re.search(r'\d+\s*(?:HR|RBI|AVG|YDS|TD)', word)
74
+ if stats_match:
75
+ extracted_info['stats'].append(stats_match.group())
76
+
77
+ return extracted_info
78
+
79
+ except Exception as e:
80
+ logger.error(f"Error in OCR processing: {str(e)}")
81
+ return None
82
+
83
+ def analyze_card_condition(self, image):
84
+ """Analyze the physical condition of the card"""
85
+ try:
86
+ # Convert PIL Image to cv2 format
87
+ img_cv = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
88
+
89
+ # Edge detection for corner and edge analysis
90
+ edges = cv2.Canny(img_cv, 100, 200)
91
+
92
+ # Analyze corners
93
+ corner_regions = {
94
+ 'top_left': edges[0:50, 0:50],
95
+ 'top_right': edges[0:50, -50:],
96
+ 'bottom_left': edges[-50:, 0:50],
97
+ 'bottom_right': edges[-50:, -50:]
98
+ }
99
+
100
+ corner_scores = {k: np.mean(v) for k, v in corner_regions.items()}
101
+
102
+ # Analyze centering
103
+ height, width = img_cv.shape[:2]
104
+ center_x = width // 2
105
+ center_y = height // 2
106
+
107
+ # Calculate centering score
108
+ centering_score = self.calculate_centering(img_cv, center_x, center_y)
109
+
110
+ condition_info = {
111
+ 'corner_scores': corner_scores,
112
+ 'centering_score': centering_score,
113
+ 'overall_condition': self.calculate_overall_condition(corner_scores, centering_score)
114
+ }
115
+
116
+ return condition_info
117
+
118
+ except Exception as e:
119
+ logger.error(f"Error in condition analysis: {str(e)}")
120
+ return None
121
+
122
+ def calculate_centering(self, image, center_x, center_y):
123
+ """Calculate the centering score of the card"""
124
+ try:
125
+ gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
126
+ edges = cv2.Canny(gray, 50, 150)
127
+
128
+ # Find contours
129
+ contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
130
+
131
+ if contours:
132
+ # Find the largest contour (assumed to be the card)
133
+ main_contour = max(contours, key=cv2.contourArea)
134
+ x, y, w, h = cv2.boundingRect(main_contour)
135
+
136
+ # Calculate centering scores
137
+ x_score = abs(0.5 - (x + w/2) / image.shape[1])
138
+ y_score = abs(0.5 - (y + h/2) / image.shape[0])
139
+
140
+ return 1 - (x_score + y_score) / 2
141
+
142
+ return None
143
+
144
+ except Exception as e:
145
+ logger.error(f"Error in centering calculation: {str(e)}")
146
+ return None
147
+
148
+ def calculate_overall_condition(self, corner_scores, centering_score):
149
+ """Calculate overall condition score"""
150
+ if corner_scores and centering_score:
151
+ corner_avg = sum(corner_scores.values()) / len(corner_scores)
152
+ return (corner_avg + centering_score) / 2
153
+ return None
154
+
155
+ def detect_orientation(self, image):
156
+ """Detect if the card is portrait or landscape"""
157
+ width, height = image.size
158
+ return 'portrait' if height > width else 'landscape'
159
+
160
  class DatasetManager:
161
  def __init__(self, local_images_dir="downloaded_cards"):
162
  self.local_images_dir = local_images_dir
163
  self.drive = None
164
  self.dataset_name = "GotThatData/sports-cards"
165
+ self.preprocessor = CardPreprocessor()
166
 
167
  # Create local directory if it doesn't exist
168
  os.makedirs(local_images_dir, exist_ok=True)
 
177
  except Exception as e:
178
  return False, f"Authentication failed: {str(e)}"
179
 
180
+ def process_image(self, image_path):
181
+ """Process a single image and extract information"""
182
+ try:
183
+ with Image.open(image_path) as img:
184
+ # Extract text information
185
+ text_info = self.preprocessor.extract_text_regions(img)
186
+
187
+ # Analyze card condition
188
+ condition_info = self.preprocessor.analyze_card_condition(img)
189
+
190
+ # Get orientation
191
+ orientation = self.preprocessor.detect_orientation(img)
192
+
193
+ return {
194
+ 'text_info': text_info,
195
+ 'condition_info': condition_info,
196
+ 'orientation': orientation
197
+ }
198
+ except Exception as e:
199
+ logger.error(f"Error processing image {image_path}: {str(e)}")
200
+ return None
201
+
202
+ def generate_filename(self, info):
203
+ """Generate filename based on extracted information"""
204
+ year = info['text_info'].get('year', 'unknown_year')
205
+ brand = info['text_info'].get('brand', 'unknown_brand')
206
+ number = info['text_info'].get('card_number', '').replace('#', '').replace('/', '_')
207
+
208
+ if not number:
209
+ number = 'unknown_number'
210
+
211
+ return f"sports_card_{year}_{brand}_{number}"
212
+
213
+ def download_and_rename_files(self, drive_folder_id):
214
+ """Download files from Google Drive and process them"""
215
  if not self.drive:
216
  return False, "Google Drive not authenticated", []
217
 
 
221
  file_list = self.drive.ListFile({'q': query}).GetList()
222
 
223
  if not file_list:
 
224
  file = self.drive.CreateFile({'id': drive_folder_id})
225
  if file:
226
  file_list = [file]
227
  else:
228
  return False, "No files found with the specified ID", []
229
 
230
+ processed_files = []
231
+ for i, file in enumerate(tqdm(file_list, desc="Processing files")):
 
 
 
 
 
 
 
 
 
 
232
  if file['mimeType'].startswith('image/'):
233
+ temp_path = os.path.join(self.local_images_dir, f"temp_{i}.jpg")
 
234
 
235
  # Download file
236
+ file.GetContentFile(temp_path)
237
 
238
+ # Process image
239
+ info = self.process_image(temp_path)
240
+ if info:
241
+ # Generate filename based on extracted info
242
+ base_filename = self.generate_filename(info)
243
+ new_filename = f"{base_filename}.jpg"
244
+ final_path = os.path.join(self.local_images_dir, new_filename)
245
+
246
+ # Rename file
247
+ os.rename(temp_path, final_path)
248
+
249
+ processed_files.append({
250
+ 'file_path': final_path,
251
  'original_name': file['title'],
252
  'new_name': new_filename,
253
+ 'image': final_path,
254
+ 'extracted_info': info['text_info'],
255
+ 'condition': info['condition_info'],
256
+ 'orientation': info['orientation']
257
  })
258
+ else:
259
+ os.remove(temp_path)
 
 
260
 
261
+ return True, f"Successfully processed {len(processed_files)} images", processed_files
262
  except Exception as e:
263
+ return False, f"Error processing files: {str(e)}", []
264
 
265
+ def update_huggingface_dataset(self, processed_files):
266
+ """Update the sports-cards dataset with processed images"""
267
  try:
268
  # Create a DataFrame with the file information
269
+ df = pd.DataFrame(processed_files)
270
 
271
  # Create a Hugging Face Dataset from the new files
272
  new_dataset = Dataset.from_pandas(df)
 
283
  # Push to Hugging Face Hub
284
  new_dataset.push_to_hub(self.dataset_name, split="train")
285
 
286
+ return True, f"Successfully updated dataset '{self.dataset_name}' with {len(processed_files)} processed images"
287
  except Exception as e:
288
  return False, f"Error updating Hugging Face dataset: {str(e)}"
289
 
290
+ def process_pipeline(folder_id):
291
  """Main pipeline to process images and update dataset"""
292
  manager = DatasetManager()
293
 
 
296
  if not auth_success:
297
  return auth_message
298
 
299
+ # Step 2: Download and process files
300
+ success, message, processed_files = manager.download_and_rename_files(folder_id)
301
  if not success:
302
  return message
303
 
304
  # Step 3: Update Hugging Face dataset
305
+ success, hf_message = manager.update_huggingface_dataset(processed_files)
306
+
307
+ # Create detailed report
308
+ report = f"{message}\n{hf_message}\n\nDetailed Processing Report:\n"
309
+ for file in processed_files:
310
+ report += f"\nFile: {file['new_name']}\n"
311
+ report += f"Extracted Info: {file['extracted_info']}\n"
312
+ report += f"Condition Score: {file['condition']['overall_condition']:.2f}\n"
313
+ report += f"Orientation: {file['orientation']}\n"
314
+ report += "-" * 50
315
+
316
+ return report
317
 
318
  # Gradio interface
319
  demo = gr.Interface(
 
322
  gr.Textbox(
323
  label="Google Drive File/Folder ID",
324
  placeholder="Enter the ID from your Google Drive URL",
325
+ value="151VOxPO91mg0C3ORiioGUd4hogzP1ujm"
 
 
 
 
 
326
  )
327
  ],
328
+ outputs=gr.Textbox(label="Processing Report"),
329
+ title="AI-Powered Sports Cards Processor",
330
+ description="Upload card images to automatically extract information, analyze condition, and add to dataset"
331
  )
332
 
333
  if __name__ == "__main__":