Update app.py
Browse files
app.py
CHANGED
@@ -1,4 +1,47 @@
|
|
1 |
# Install required packages
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
import gradio as gr
|
3 |
import json
|
4 |
import cv2
|
@@ -7,10 +50,14 @@ from deepface import DeepFace
|
|
7 |
import matplotlib.pyplot as plt
|
8 |
from PIL import Image
|
9 |
import tempfile
|
10 |
-
import os
|
11 |
import pandas as pd
|
12 |
import shutil
|
13 |
|
|
|
|
|
|
|
|
|
|
|
14 |
def verify_faces(img1, img2, threshold=0.70, model="VGG-Face"):
|
15 |
temp_dir = tempfile.mkdtemp()
|
16 |
img1_path = os.path.join(temp_dir, "image1.jpg")
|
@@ -88,14 +135,23 @@ def find_faces(query_img, db_folder, threshold=0.70, model="VGG-Face"):
|
|
88 |
else:
|
89 |
query_img.save(query_path)
|
90 |
|
|
|
91 |
if isinstance(db_folder, str):
|
92 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
93 |
else:
|
|
|
94 |
db_path = os.path.join(temp_dir, "db")
|
95 |
os.makedirs(db_path, exist_ok=True)
|
96 |
|
97 |
for i, file in enumerate(db_folder):
|
98 |
-
orig_filename = file.orig_name
|
99 |
file_ext = os.path.splitext(orig_filename)[1]
|
100 |
new_filename = f"image_{i}{file_ext}"
|
101 |
shutil.copy(file.name, os.path.join(db_path, new_filename))
|
@@ -107,7 +163,7 @@ def find_faces(query_img, db_folder, threshold=0.70, model="VGG-Face"):
|
|
107 |
model_name=model,
|
108 |
distance_metric="cosine",
|
109 |
threshold=threshold,
|
110 |
-
silent=True
|
111 |
)
|
112 |
|
113 |
if isinstance(dfs, list):
|
@@ -131,23 +187,34 @@ def find_faces(query_img, db_folder, threshold=0.70, model="VGG-Face"):
|
|
131 |
axes[0].set_title("Query Image")
|
132 |
axes[0].axis("off")
|
133 |
|
|
|
134 |
for i in range(num_matches):
|
|
|
|
|
|
|
135 |
match_path = df.iloc[i]["identity"]
|
136 |
if not os.path.exists(match_path):
|
137 |
-
continue
|
138 |
|
139 |
distance = df.iloc[i]["distance"]
|
140 |
confidence = round((1 - distance) * 100, 2)
|
141 |
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
151 |
|
152 |
plt.suptitle(f"Found {len(df)} matching faces", fontsize=16, fontweight='bold')
|
153 |
plt.tight_layout()
|
@@ -238,7 +305,7 @@ def analyze_face(img, actions=['age', 'gender', 'race', 'emotion']):
|
|
238 |
emotion_conf = f"{conf:.1f}%"
|
239 |
break
|
240 |
|
241 |
-
ax = plt.subplot2grid((2, 4), (0 if i < 2 else 1, 2 + (i % 2))
|
242 |
|
243 |
text = (
|
244 |
f"Face #{i+1}\n\n"
|
@@ -297,7 +364,7 @@ with gr.Blocks(title="Complete Face Recognition Tool", theme=gr.themes.Soft()) a
|
|
297 |
|
298 |
This tool provides three face recognition features:
|
299 |
- **Verify Faces**: Compare two specific images to check if they contain the same person
|
300 |
-
- **Find Faces**: Search for matching faces in a database/folder
|
301 |
- **Analyze Face**: Determine age, gender, race, and emotion from a facial image
|
302 |
""")
|
303 |
|
@@ -320,18 +387,13 @@ with gr.Blocks(title="Complete Face Recognition Tool", theme=gr.themes.Soft()) a
|
|
320 |
|
321 |
verify_result_plot = gr.Plot(label="Verification Result")
|
322 |
verify_json = gr.JSON(label="Technical Details")
|
323 |
-
|
324 |
-
verify_button.click(
|
325 |
-
verify_faces,
|
326 |
-
inputs=[img1_input, img2_input, verify_threshold, verify_model],
|
327 |
-
outputs=[verify_result_plot, verify_json]
|
328 |
-
)
|
329 |
-
|
330 |
-
gr.Markdown("""... (keep existing markdown) ...""")
|
331 |
-
|
332 |
with gr.TabItem("Find Faces"):
|
333 |
query_img = gr.Image(label="Query Image (Face to find)", type="pil")
|
334 |
-
db_path_input = gr.Textbox(
|
|
|
|
|
|
|
335 |
db_files_input = gr.File(label="Or upload images for database", file_count="multiple")
|
336 |
|
337 |
with gr.Row():
|
@@ -347,21 +409,7 @@ with gr.Blocks(title="Complete Face Recognition Tool", theme=gr.themes.Soft()) a
|
|
347 |
|
348 |
find_result_plot = gr.Plot(label="Search Results")
|
349 |
find_results_table = gr.JSON(label="Detailed Results")
|
350 |
-
|
351 |
-
find_button.click(
|
352 |
-
find_faces,
|
353 |
-
inputs=[query_img, db_path_input, find_threshold, find_model],
|
354 |
-
outputs=[find_result_plot, find_results_table]
|
355 |
-
)
|
356 |
-
|
357 |
-
db_files_input.change(
|
358 |
-
lambda x: "",
|
359 |
-
inputs=db_files_input,
|
360 |
-
outputs=db_path_input
|
361 |
-
)
|
362 |
-
|
363 |
-
gr.Markdown("""... (keep existing markdown) ...""")
|
364 |
-
|
365 |
with gr.TabItem("Analyze Face"):
|
366 |
analyze_img = gr.Image(label="Upload Image for Analysis", type="pil")
|
367 |
actions_checkboxes = gr.CheckboxGroup(
|
@@ -374,14 +422,31 @@ with gr.Blocks(title="Complete Face Recognition Tool", theme=gr.themes.Soft()) a
|
|
374 |
|
375 |
analyze_result_plot = gr.Plot(label="Analysis Results")
|
376 |
analyze_json = gr.JSON(label="Detailed Analysis")
|
377 |
-
|
378 |
-
|
379 |
-
|
380 |
-
|
381 |
-
|
382 |
-
|
383 |
-
|
384 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
385 |
|
386 |
# Launch the app
|
387 |
demo.launch()
|
|
|
1 |
# Install required packages
|
2 |
+
import os
|
3 |
+
import subprocess
|
4 |
+
import sys
|
5 |
+
import importlib
|
6 |
+
import pkg_resources
|
7 |
+
|
8 |
+
def install_package(package, version=None):
|
9 |
+
package_spec = f"{package}=={version}" if version else package
|
10 |
+
print(f"Installing {package_spec}...")
|
11 |
+
try:
|
12 |
+
subprocess.check_call([sys.executable, "-m", "pip", "install", "--no-cache-dir", package_spec])
|
13 |
+
except subprocess.CalledProcessError as e:
|
14 |
+
print(f"Failed to install {package_spec}: {e}")
|
15 |
+
raise
|
16 |
+
|
17 |
+
def ensure_package(package, version=None):
|
18 |
+
try:
|
19 |
+
if version:
|
20 |
+
pkg_resources.require(f"{package}=={version}")
|
21 |
+
else:
|
22 |
+
importlib.import_module(package)
|
23 |
+
print(f"{package} is already installed with the correct version.")
|
24 |
+
except (ImportError, pkg_resources.VersionConflict, pkg_resources.DistributionNotFound) as e:
|
25 |
+
print(f"Package requirement failed: {e}")
|
26 |
+
install_package(package, version)
|
27 |
+
|
28 |
+
# Check environment and install dependencies
|
29 |
+
if not os.path.exists("/.dockerenv") and not os.path.exists("/kaggle"):
|
30 |
+
print("Setting up environment...")
|
31 |
+
|
32 |
+
# Install core dependencies
|
33 |
+
ensure_package("numpy", "1.23.5")
|
34 |
+
ensure_package("protobuf", "3.20.3")
|
35 |
+
ensure_package("tensorflow", "2.10.0")
|
36 |
+
ensure_package("opencv-python-headless", "4.7.0.72") # Fix for cv2 error
|
37 |
+
ensure_package("deepface", "0.0.79")
|
38 |
+
ensure_package("gradio", "3.50.2")
|
39 |
+
|
40 |
+
# Install additional required packages
|
41 |
+
for pkg in ["matplotlib", "pillow", "pandas"]:
|
42 |
+
ensure_package(pkg)
|
43 |
+
|
44 |
+
# Now import the required modules
|
45 |
import gradio as gr
|
46 |
import json
|
47 |
import cv2
|
|
|
50 |
import matplotlib.pyplot as plt
|
51 |
from PIL import Image
|
52 |
import tempfile
|
|
|
53 |
import pandas as pd
|
54 |
import shutil
|
55 |
|
56 |
+
# Google Drive integration (for Colab users)
|
57 |
+
if 'google.colab' in sys.modules:
|
58 |
+
from google.colab import drive
|
59 |
+
drive.mount('/content/drive')
|
60 |
+
|
61 |
def verify_faces(img1, img2, threshold=0.70, model="VGG-Face"):
|
62 |
temp_dir = tempfile.mkdtemp()
|
63 |
img1_path = os.path.join(temp_dir, "image1.jpg")
|
|
|
135 |
else:
|
136 |
query_img.save(query_path)
|
137 |
|
138 |
+
# Handle cloud storage paths and uploaded files
|
139 |
if isinstance(db_folder, str):
|
140 |
+
# Check if it's a Google Drive path
|
141 |
+
if db_folder.startswith("/content/drive"):
|
142 |
+
db_path = db_folder
|
143 |
+
else:
|
144 |
+
# Handle regular path
|
145 |
+
db_path = os.path.abspath(db_folder)
|
146 |
+
if not os.path.exists(db_path):
|
147 |
+
return None, "Invalid database path - directory does not exist"
|
148 |
else:
|
149 |
+
# Handle uploaded files
|
150 |
db_path = os.path.join(temp_dir, "db")
|
151 |
os.makedirs(db_path, exist_ok=True)
|
152 |
|
153 |
for i, file in enumerate(db_folder):
|
154 |
+
orig_filename = file.orig_name
|
155 |
file_ext = os.path.splitext(orig_filename)[1]
|
156 |
new_filename = f"image_{i}{file_ext}"
|
157 |
shutil.copy(file.name, os.path.join(db_path, new_filename))
|
|
|
163 |
model_name=model,
|
164 |
distance_metric="cosine",
|
165 |
threshold=threshold,
|
166 |
+
silent=True
|
167 |
)
|
168 |
|
169 |
if isinstance(dfs, list):
|
|
|
187 |
axes[0].set_title("Query Image")
|
188 |
axes[0].axis("off")
|
189 |
|
190 |
+
valid_matches = 0
|
191 |
for i in range(num_matches):
|
192 |
+
if i >= len(df):
|
193 |
+
break
|
194 |
+
|
195 |
match_path = df.iloc[i]["identity"]
|
196 |
if not os.path.exists(match_path):
|
197 |
+
continue
|
198 |
|
199 |
distance = df.iloc[i]["distance"]
|
200 |
confidence = round((1 - distance) * 100, 2)
|
201 |
|
202 |
+
try:
|
203 |
+
match_img = cv2.imread(match_path)
|
204 |
+
if match_img is None:
|
205 |
+
continue
|
206 |
+
|
207 |
+
match_img = cv2.cvtColor(match_img, cv2.COLOR_BGR2RGB)
|
208 |
+
axes[valid_matches+1].imshow(match_img)
|
209 |
+
axes[valid_matches+1].set_title(f"Match #{valid_matches+1}\nConfidence: {confidence}%")
|
210 |
+
axes[valid_matches+1].axis("off")
|
211 |
+
valid_matches += 1
|
212 |
+
except:
|
213 |
+
continue
|
214 |
+
|
215 |
+
# Hide empty axes
|
216 |
+
for j in range(valid_matches+1, num_matches+1):
|
217 |
+
axes[j].axis("off")
|
218 |
|
219 |
plt.suptitle(f"Found {len(df)} matching faces", fontsize=16, fontweight='bold')
|
220 |
plt.tight_layout()
|
|
|
305 |
emotion_conf = f"{conf:.1f}%"
|
306 |
break
|
307 |
|
308 |
+
ax = plt.subplot2grid((2, 4), (0 if i < 2 else 1, 2 + (i % 2))
|
309 |
|
310 |
text = (
|
311 |
f"Face #{i+1}\n\n"
|
|
|
364 |
|
365 |
This tool provides three face recognition features:
|
366 |
- **Verify Faces**: Compare two specific images to check if they contain the same person
|
367 |
+
- **Find Faces**: Search for matching faces in a database/folder (supports Google Drive paths in Colab)
|
368 |
- **Analyze Face**: Determine age, gender, race, and emotion from a facial image
|
369 |
""")
|
370 |
|
|
|
387 |
|
388 |
verify_result_plot = gr.Plot(label="Verification Result")
|
389 |
verify_json = gr.JSON(label="Technical Details")
|
390 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
391 |
with gr.TabItem("Find Faces"):
|
392 |
query_img = gr.Image(label="Query Image (Face to find)", type="pil")
|
393 |
+
db_path_input = gr.Textbox(
|
394 |
+
label="Database Path (folder path or Google Drive path in Colab)",
|
395 |
+
placeholder="/content/drive/MyDrive/your_folder"
|
396 |
+
)
|
397 |
db_files_input = gr.File(label="Or upload images for database", file_count="multiple")
|
398 |
|
399 |
with gr.Row():
|
|
|
409 |
|
410 |
find_result_plot = gr.Plot(label="Search Results")
|
411 |
find_results_table = gr.JSON(label="Detailed Results")
|
412 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
413 |
with gr.TabItem("Analyze Face"):
|
414 |
analyze_img = gr.Image(label="Upload Image for Analysis", type="pil")
|
415 |
actions_checkboxes = gr.CheckboxGroup(
|
|
|
422 |
|
423 |
analyze_result_plot = gr.Plot(label="Analysis Results")
|
424 |
analyze_json = gr.JSON(label="Detailed Analysis")
|
425 |
+
|
426 |
+
# Setup all button clicks
|
427 |
+
verify_button.click(
|
428 |
+
verify_faces,
|
429 |
+
inputs=[img1_input, img2_input, verify_threshold, verify_model],
|
430 |
+
outputs=[verify_result_plot, verify_json]
|
431 |
+
)
|
432 |
+
|
433 |
+
find_button.click(
|
434 |
+
find_faces,
|
435 |
+
inputs=[query_img, db_path_input, find_threshold, find_model],
|
436 |
+
outputs=[find_result_plot, find_results_table]
|
437 |
+
)
|
438 |
+
|
439 |
+
db_files_input.change(
|
440 |
+
lambda x: "",
|
441 |
+
inputs=db_files_input,
|
442 |
+
outputs=db_path_input
|
443 |
+
)
|
444 |
+
|
445 |
+
analyze_button.click(
|
446 |
+
analyze_face,
|
447 |
+
inputs=[analyze_img, actions_checkboxes],
|
448 |
+
outputs=[analyze_result_plot, analyze_json]
|
449 |
+
)
|
450 |
|
451 |
# Launch the app
|
452 |
demo.launch()
|