Spaces:
Sleeping
Sleeping
Update
Browse files
app.py
CHANGED
@@ -5,164 +5,18 @@ import gradio as gr
|
|
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)
|
@@ -171,47 +25,16 @@ class DatasetManager:
|
|
171 |
"""Authenticate with Google Drive"""
|
172 |
try:
|
173 |
gauth = GoogleAuth()
|
|
|
|
|
174 |
gauth.LocalWebserverAuth()
|
175 |
self.drive = GoogleDrive(gauth)
|
176 |
return True, "Successfully authenticated with Google Drive"
|
177 |
except Exception as e:
|
178 |
return False, f"Authentication failed: {str(e)}"
|
179 |
|
180 |
-
def
|
181 |
-
"""
|
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,54 +44,57 @@ class DatasetManager:
|
|
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 |
-
|
231 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
232 |
if file['mimeType'].startswith('image/'):
|
233 |
-
|
|
|
234 |
|
235 |
# Download file
|
236 |
-
file.GetContentFile(
|
237 |
|
238 |
-
#
|
239 |
-
|
240 |
-
|
241 |
-
|
242 |
-
|
243 |
-
|
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':
|
254 |
-
'extracted_info': info['text_info'],
|
255 |
-
'condition': info['condition_info'],
|
256 |
-
'orientation': info['orientation']
|
257 |
})
|
258 |
-
|
259 |
-
|
|
|
|
|
260 |
|
261 |
-
return True, f"Successfully processed {len(
|
262 |
except Exception as e:
|
263 |
-
return False, f"Error
|
264 |
|
265 |
-
def update_huggingface_dataset(self,
|
266 |
-
"""Update the sports-cards dataset with
|
267 |
try:
|
268 |
# Create a DataFrame with the file information
|
269 |
-
df = pd.DataFrame(
|
270 |
|
271 |
-
# Create a Hugging Face Dataset
|
272 |
new_dataset = Dataset.from_pandas(df)
|
273 |
|
274 |
try:
|
@@ -283,11 +109,11 @@ class DatasetManager:
|
|
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(
|
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,24 +122,14 @@ def process_pipeline(folder_id):
|
|
296 |
if not auth_success:
|
297 |
return auth_message
|
298 |
|
299 |
-
# Step 2: Download and
|
300 |
-
success, message,
|
301 |
if not success:
|
302 |
return message
|
303 |
|
304 |
# Step 3: Update Hugging Face dataset
|
305 |
-
success, hf_message = manager.update_huggingface_dataset(
|
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(
|
@@ -323,11 +139,16 @@ demo = gr.Interface(
|
|
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="
|
329 |
-
title="
|
330 |
-
description="
|
331 |
)
|
332 |
|
333 |
if __name__ == "__main__":
|
|
|
5 |
from datasets import load_dataset, Dataset
|
6 |
import pandas as pd
|
7 |
from PIL import Image
|
|
|
|
|
|
|
|
|
|
|
|
|
8 |
from tqdm import tqdm
|
9 |
import logging
|
|
|
10 |
|
11 |
# Set up logging
|
12 |
logging.basicConfig(level=logging.INFO)
|
13 |
logger = logging.getLogger(__name__)
|
14 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
15 |
class DatasetManager:
|
16 |
def __init__(self, local_images_dir="downloaded_cards"):
|
17 |
self.local_images_dir = local_images_dir
|
18 |
self.drive = None
|
19 |
self.dataset_name = "GotThatData/sports-cards"
|
|
|
20 |
|
21 |
# Create local directory if it doesn't exist
|
22 |
os.makedirs(local_images_dir, exist_ok=True)
|
|
|
25 |
"""Authenticate with Google Drive"""
|
26 |
try:
|
27 |
gauth = GoogleAuth()
|
28 |
+
# Specify the path to client_secrets.json
|
29 |
+
gauth.settings['client_config_file'] = 'client_secrets.json' # Make sure this matches your file path
|
30 |
gauth.LocalWebserverAuth()
|
31 |
self.drive = GoogleDrive(gauth)
|
32 |
return True, "Successfully authenticated with Google Drive"
|
33 |
except Exception as e:
|
34 |
return False, f"Authentication failed: {str(e)}"
|
35 |
|
36 |
+
def download_and_rename_files(self, drive_folder_id, naming_convention):
|
37 |
+
"""Download files from Google Drive and rename them"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
38 |
if not self.drive:
|
39 |
return False, "Google Drive not authenticated", []
|
40 |
|
|
|
44 |
file_list = self.drive.ListFile({'q': query}).GetList()
|
45 |
|
46 |
if not file_list:
|
47 |
+
# Try to get single file if folder is empty
|
48 |
file = self.drive.CreateFile({'id': drive_folder_id})
|
49 |
if file:
|
50 |
file_list = [file]
|
51 |
else:
|
52 |
return False, "No files found with the specified ID", []
|
53 |
|
54 |
+
renamed_files = []
|
55 |
+
existing_dataset = None
|
56 |
+
try:
|
57 |
+
existing_dataset = load_dataset(self.dataset_name)
|
58 |
+
logger.info(f"Loaded existing dataset: {self.dataset_name}")
|
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
|
|
|
|
|
|
|
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
|
98 |
new_dataset = Dataset.from_pandas(df)
|
99 |
|
100 |
try:
|
|
|
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 |
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(
|
|
|
139 |
label="Google Drive File/Folder ID",
|
140 |
placeholder="Enter the ID from your Google Drive URL",
|
141 |
value="151VOxPO91mg0C3ORiioGUd4hogzP1ujm"
|
142 |
+
),
|
143 |
+
gr.Textbox(
|
144 |
+
label="Naming Convention",
|
145 |
+
placeholder="e.g., sports_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__":
|