Matan Kriel commited on
Commit
2277fc2
Β·
1 Parent(s): 72e2859

added new parquet file

Browse files
app.py CHANGED
@@ -27,6 +27,8 @@ else:
27
  if DB_PATH:
28
  print(f"πŸ“‚ Loaded Knowledge Base: {DB_PATH}")
29
  df_db = pd.read_parquet(DB_PATH)
 
 
30
  # Convert embedding column to a clean numpy matrix for fast math
31
  DB_VECTORS = np.stack(df_db['embedding'].values)
32
 
@@ -34,6 +36,20 @@ if DB_PATH:
34
  # e.g. "famous_faces_GhostFaceNet.parquet" -> "GhostFaceNet"
35
  MODEL_NAME = DB_PATH.split("_")[-1].replace(".parquet", "")
36
  print(f"βš™οΈ Model configured: {MODEL_NAME}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  else:
38
  print("❌ CRITICAL: No Parquet file found! Please run the Model Battle step.")
39
  DB_VECTORS = None
@@ -41,49 +57,87 @@ else:
41
 
42
  # --- 2. Helper function to load images with fallbacks ---
43
  def load_image_with_fallback(image_path, name):
44
- """Try to load image from various possible locations, or create placeholder"""
45
- # Try original path
 
 
 
 
 
 
 
46
  if os.path.exists(image_path):
47
  try:
48
- return Image.open(image_path)
49
- except:
50
- pass
 
 
51
 
52
- # Try just the filename in current directory
53
  filename = os.path.basename(image_path)
54
  if os.path.exists(filename):
55
  try:
56
- return Image.open(filename)
57
- except:
58
- pass
 
 
 
 
 
 
 
 
 
 
59
 
60
- # Try in my_dataset directory
61
- dataset_path = os.path.join("my_dataset", filename)
62
  if os.path.exists(dataset_path):
63
  try:
64
- return Image.open(dataset_path)
65
- except:
66
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
 
68
- # Create a placeholder image if nothing found
69
  placeholder = Image.new('RGB', (200, 200), color=(220, 220, 220))
70
  from PIL import ImageDraw, ImageFont
71
  draw = ImageDraw.Draw(placeholder)
72
  # Try to use default font, fallback to basic if not available
73
  try:
74
- font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 20)
75
  except:
76
  font = ImageFont.load_default()
77
 
78
- # Draw text in center
79
- text = f"Image\nNot Found"
80
- bbox = draw.textbbox((0, 0), text, font=font)
81
- text_width = bbox[2] - bbox[0]
82
- text_height = bbox[3] - bbox[1]
83
- position = ((200 - text_width) // 2, (200 - text_height) // 2)
84
- draw.text(position, text, fill=(100, 100, 100), font=font)
 
 
85
 
86
- return placeholder
 
87
 
88
  # --- 3. Define the Search Logic ---
89
  def find_best_matches(user_image):
@@ -121,18 +175,59 @@ def find_best_matches(user_image):
121
  display_name = f"{row['name']} (Match: {int(score*100)}%)"
122
  result_text += f"### #{i}: {display_name}\n\n"
123
 
124
- # Load Image with fallback - always add to gallery (with placeholder if needed)
125
  try:
126
- img = load_image_with_fallback(row['image_path'], row['name'])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
127
  gallery_images.append((img, display_name))
128
- # Check if we used a placeholder
129
- if not os.path.exists(row['image_path']) and not os.path.exists(os.path.basename(row['image_path'])):
130
- result_text += f"⚠️ Image not found at: {row['image_path']} (showing placeholder)\n\n"
 
 
 
 
 
 
131
  except Exception as img_error:
132
  # Even if loading fails, create placeholder
133
  placeholder = Image.new('RGB', (200, 200), color=(220, 220, 220))
134
  gallery_images.append((placeholder, display_name))
135
- result_text += f"⚠️ Could not load image: {str(img_error)}\n\n"
136
 
137
  # Don't pad with None - Gallery can't handle None images
138
  # Just return what we have
 
27
  if DB_PATH:
28
  print(f"πŸ“‚ Loaded Knowledge Base: {DB_PATH}")
29
  df_db = pd.read_parquet(DB_PATH)
30
+ print(f"πŸ“Š Database columns: {df_db.columns.tolist()}")
31
+ print(f"πŸ“Š Database shape: {df_db.shape}")
32
  # Convert embedding column to a clean numpy matrix for fast math
33
  DB_VECTORS = np.stack(df_db['embedding'].values)
34
 
 
36
  # e.g. "famous_faces_GhostFaceNet.parquet" -> "GhostFaceNet"
37
  MODEL_NAME = DB_PATH.split("_")[-1].replace(".parquet", "")
38
  print(f"βš™οΈ Model configured: {MODEL_NAME}")
39
+
40
+ # Debug: Check what directories exist
41
+ print(f"πŸ” Checking available directories...")
42
+ if os.path.exists("my_dataset"):
43
+ files_in_dataset = os.listdir("my_dataset")[:5] # Show first 5
44
+ print(f" Found 'my_dataset' directory with {len(os.listdir('my_dataset'))} files")
45
+ print(f" Sample files: {files_in_dataset}")
46
+ else:
47
+ print(f" 'my_dataset' directory not found")
48
+
49
+ # Debug: Show sample image paths from database
50
+ if 'image_path' in df_db.columns:
51
+ sample_paths = df_db['image_path'].head(3).tolist()
52
+ print(f"πŸ“· Sample image paths from DB: {sample_paths}")
53
  else:
54
  print("❌ CRITICAL: No Parquet file found! Please run the Model Battle step.")
55
  DB_VECTORS = None
 
57
 
58
  # --- 2. Helper function to load images with fallbacks ---
59
  def load_image_with_fallback(image_path, name):
60
+ """
61
+ Try to load image from various possible locations, or create placeholder.
62
+
63
+ The parquet file stores image_path (e.g., 'my_dataset/Sahar_Milis.png'),
64
+ but we need to find where the actual image files are located.
65
+ """
66
+ tried_paths = []
67
+
68
+ # Strategy 1: Try original path as-is
69
  if os.path.exists(image_path):
70
  try:
71
+ return Image.open(image_path), image_path
72
+ except Exception as e:
73
+ tried_paths.append(f"{image_path} (error: {e})")
74
+ else:
75
+ tried_paths.append(f"{image_path} (not found)")
76
 
77
+ # Strategy 2: Try just the filename in current directory
78
  filename = os.path.basename(image_path)
79
  if os.path.exists(filename):
80
  try:
81
+ return Image.open(filename), filename
82
+ except Exception as e:
83
+ tried_paths.append(f"{filename} (error: {e})")
84
+ else:
85
+ tried_paths.append(f"{filename} (not found)")
86
+
87
+ # Strategy 3: Try in my_dataset directory (remove my_dataset/ prefix if present)
88
+ if image_path.startswith("my_dataset/"):
89
+ # Already has prefix, try as-is
90
+ dataset_path = image_path
91
+ else:
92
+ # Add prefix
93
+ dataset_path = os.path.join("my_dataset", filename)
94
 
 
 
95
  if os.path.exists(dataset_path):
96
  try:
97
+ return Image.open(dataset_path), dataset_path
98
+ except Exception as e:
99
+ tried_paths.append(f"{dataset_path} (error: {e})")
100
+ else:
101
+ tried_paths.append(f"{dataset_path} (not found)")
102
+
103
+ # Strategy 4: Try searching in current directory recursively
104
+ import glob
105
+ search_patterns = [
106
+ f"**/{filename}",
107
+ f"**/*{filename}",
108
+ f"**/{name.replace(' ', '_')}*",
109
+ f"**/{name.replace(' ', '-')}*",
110
+ ]
111
+ for pattern in search_patterns:
112
+ matches = glob.glob(pattern, recursive=True)
113
+ if matches:
114
+ try:
115
+ return Image.open(matches[0]), matches[0]
116
+ except:
117
+ continue
118
 
119
+ # Strategy 5: Create a placeholder image with name
120
  placeholder = Image.new('RGB', (200, 200), color=(220, 220, 220))
121
  from PIL import ImageDraw, ImageFont
122
  draw = ImageDraw.Draw(placeholder)
123
  # Try to use default font, fallback to basic if not available
124
  try:
125
+ font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 16)
126
  except:
127
  font = ImageFont.load_default()
128
 
129
+ # Draw name and "Not Found" text
130
+ text_lines = [name[:15], "Image", "Not Found"]
131
+ y_offset = 50
132
+ for line in text_lines:
133
+ bbox = draw.textbbox((0, 0), line, font=font)
134
+ text_width = bbox[2] - bbox[0]
135
+ position = ((200 - text_width) // 2, y_offset)
136
+ draw.text(position, line, fill=(100, 100, 100), font=font)
137
+ y_offset += 30
138
 
139
+ print(f"⚠️ Could not find image for {name}. Tried: {tried_paths[:3]}")
140
+ return placeholder, None
141
 
142
  # --- 3. Define the Search Logic ---
143
  def find_best_matches(user_image):
 
175
  display_name = f"{row['name']} (Match: {int(score*100)}%)"
176
  result_text += f"### #{i}: {display_name}\n\n"
177
 
178
+ # Load Image - prioritize bytes from parquet, then try file paths
179
  try:
180
+ img = None
181
+ found_path = None
182
+
183
+ # Strategy 1: Check if image is stored as bytes in parquet (BEST - self-contained)
184
+ if 'image_bytes' in df_db.columns and row.get('image_bytes') is not None:
185
+ try:
186
+ import io
187
+ img = Image.open(io.BytesIO(row['image_bytes']))
188
+ found_path = "parquet (embedded)"
189
+ except Exception as e:
190
+ print(f"⚠️ Could not load image bytes for {row['name']}: {e}")
191
+
192
+ # Strategy 2: Try loading from file path (fallback)
193
+ if img is None and 'image_path' in df_db.columns:
194
+ img, found_path = load_image_with_fallback(row['image_path'], row['name'])
195
+
196
+ # Strategy 3: Create placeholder if still no image
197
+ if img is None:
198
+ placeholder = Image.new('RGB', (200, 200), color=(220, 220, 220))
199
+ from PIL import ImageDraw, ImageFont
200
+ draw = ImageDraw.Draw(placeholder)
201
+ try:
202
+ font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 16)
203
+ except:
204
+ font = ImageFont.load_default()
205
+ text_lines = [row['name'][:15], "Image", "Not Found"]
206
+ y_offset = 50
207
+ for line in text_lines:
208
+ bbox = draw.textbbox((0, 0), line, font=font)
209
+ text_width = bbox[2] - bbox[0]
210
+ position = ((200 - text_width) // 2, y_offset)
211
+ draw.text(position, line, fill=(100, 100, 100), font=font)
212
+ y_offset += 30
213
+ img = placeholder
214
+ found_path = None
215
+
216
  gallery_images.append((img, display_name))
217
+
218
+ # Add status message
219
+ if found_path == "parquet (embedded)":
220
+ result_text += f"βœ“ Image loaded from parquet\n\n"
221
+ elif found_path:
222
+ result_text += f"βœ“ Found image at: {found_path}\n\n"
223
+ else:
224
+ result_text += f"⚠️ Image not found for {row['name']}\n\n"
225
+
226
  except Exception as img_error:
227
  # Even if loading fails, create placeholder
228
  placeholder = Image.new('RGB', (200, 200), color=(220, 220, 220))
229
  gallery_images.append((placeholder, display_name))
230
+ result_text += f"⚠️ Error loading image: {str(img_error)}\n\n"
231
 
232
  # Don't pad with None - Gallery can't handle None images
233
  # Just return what we have
famous_faces_GhostFaceNet.parquet β†’ famous_faces_ArcFace_standalone.parquet RENAMED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:2683e1a44df3c686cd25fc73b922b46628702947e8c2ddef27083342e16c8beb
3
- size 3625095
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f5e212ec446c3014d737f327a5788deb262fcadd0bcee7c6052dda8a356727c4
3
+ size 12055699