import os
import face_recognition
import tkinter as tk
from tkinter import filedialog, messagebox
from PIL import Image, ImageTk
from tkinter import ttk
import threading
import pickle
import time
import datetime
def generate_cache_filename():
"""Generate a unique filename for the cache based on the current date and time."""
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
return os.path.join(os.path.expanduser('~'), 'Documents', f'face_encodings_cache_{timestamp}.pkl')
def load_cache():
"""Load face encodings cache from the cache file."""
global cache
if os.path.exists(cache_file_path):
with open(cache_file_path, 'rb') as cache_file:
cache = pickle.load(cache_file)
def save_cache():
"""Save face encodings cache to the cache file."""
with open(cache_file_path, 'wb') as cache_file:
pickle.dump(cache, cache_file)
def load_face_encoding(image_path):
"""Load and encode faces from an image file, using cache if available."""
if image_path in cache:
return cache[image_path]
code
image = face_recognition.load_image_file(image_path)
encodings = face_recognition.face_encodings(image)
if encodings:
encoding = encodings[0]
cache[image_path] = encoding # Cache the encoding
save_cache() # Save the updated cache
return encoding
return None
def face_matches(search_image_path, client_image_path):
"""Compare two images and return True if the face matches."""
search_encoding = load_face_encoding(search_image_path)
client_encoding = load_face_encoding(client_image_path)
code
if search_encoding is None or client_encoding is None:
return False
# Compare faces
matches = face_recognition.compare_faces([client_encoding], search_encoding)
return matches[0]
def search_client_by_picture(search_picture_path):
"""Search for all clients by comparing the search picture to client pictures."""
global matched_image_paths
matched_image_paths = []
code
Assistant
if not clients_dir:
return "Client folder directory not set."
image_paths = []
for client_folder in os.listdir(clients_dir):
client_path = os.path.join(clients_dir, client_folder)
if os.path.isdir(client_path):
for file in os.listdir(client_path):
if file.endswith(('.jpg', '.jpeg', '.png')):
image_paths.append(os.path.join(client_path, file))
total_images = len(image_paths)
start_time = time.time()
for idx, client_picture in enumerate(image_paths):
if face_matches(search_picture_path, client_picture):
matched_image_paths.append(client_picture)
# Update progress and estimated time remaining
elapsed_time = time.time() - start_time
average_time_per_image = elapsed_time / (idx + 1)
remaining_time = (total_images - (idx + 1)) * average_time_per_image
update_progress_bar(idx + 1, total_images, remaining_time)
return matched_image_paths
def update_progress_bar(current, total, remaining_time):
"""Update the progress bar and show estimated remaining time."""
progress_percent = int((current / total) * 100)
progress_bar['value'] = progress_percent
progress_label.config(text=f"Progress: {progress_percent}% - Estimated time left: {int(remaining_time)} seconds")
def show_results():
"""Show matched images and their folders in a new window."""
result_window = tk.Toplevel(app)
result_window.title("Search Results")
result_window.geometry("600x400")
def start_search():
"""Start the search process in a separate thread."""
def search_thread():
global cache_file_path
cache_file_path = generate_cache_filename() # Generate a unique cache filename for each search
load_cache() # Load the cache for the current search
progress_bar.start()
search_client_by_picture(search_image_path)
progress_bar.stop()
show_results()
save_cache() # Save the cache after the search is completed
code
threading.Thread(target=search_thread).start()
def select_folder():
"""Open a folder dialog to select the directory containing client folders."""
global clients_dir
clients_dir = filedialog.askdirectory()
if clients_dir:
messagebox.showinfo("Directory Selected", f"Clients directory set to:\n{clients_dir}")
def select_image_file():
"""Open a file dialog to select an image file and start search."""
global search_image_path
file_path = filedialog.askopenfilename(filetypes=[("Image Files", ".jpg;.jpeg;*.png")])
if file_path:
search_image_path = file_path
show_thumbnails() # Optionally show thumbnails of the selected image
start_search() # Start search
def show_thumbnails():
"""Show thumbnail of the search image."""
if search_image_path:
search_img = Image.open(search_image_path)
search_img.thumbnail((100, 100))
search_img_tk = ImageTk.PhotoImage(search_img)
هذا الكود هو تطبيق واجهة مستخدم رسومية (GUI) باستخدام مكتبة Tkinter في بايثون، وهو مصمم للبحث عن صور العملاء التي تطابق صورة محددة باستخدام تقنية التعرف على الوجوه من خلال مكتبة face_recognition. إليك تحليلًا مفصلًا للكود:
المكتبات المستخدمة:
os: للتعامل مع نظام التشغيل والملفات والمجلدات.
face_recognition: للتعرف على الوجوه واستخراج التشفيرات الوجهية.
tkinter: لإنشاء الواجهة الرسومية والتعامل مع عناصرها.
تحديث شريط التقدم في الواجهة بناءً على عدد الصور المعالجة والوقت المتبقي.
8. show_results()
عرض النتائج في نافذة جديدة.
إذا كانت هناك صور مطابقة، يتم عرضها مع مسارات مجلداتها.
إذا لم تكن هناك نتائج، يتم عرض رسالة تفيد بعدم وجود تطابق.
9. start_search()
بدء عملية البحث في خيط منفصل حتى لا تتجمد الواجهة.
يقوم بإنشاء ملف التخزين المؤقت وبدء عملية البحث.
10. select_folder()
يفتح نافذة لاختيار مجلد العملاء.
يخزن المسار في المتغير clients_dir.
11. select_image_file()
يفتح نافذة لاختيار صورة البحث.
عند اختيار الصورة، يتم عرضها كصورة مصغرة ويبدأ البحث.
12. show_thumbnails()
عرض صورة البحث كصورة مصغرة في الواجهة.
وصف الواجهة الرسومية:
زر اختيار مجلد العملاء: يتيح للمستخدم تحديد المجلد الذي يحتوي على مجلدات العملاء.
زر اختيار الصورة: يتيح للمستخدم اختيار صورة البحث.
شريط التقدم: يظهر تقدم عملية البحث ونسبة الإنجاز.
ملصق التقدم: يظهر نسبة التقدم والوقت المتبقي المتوقع.
عرض النتائج: يتم في نافذة جديدة بعد انتهاء البحث.
ملاحظات وإمكانيات التحسين:
إدارة الأخطاء:
التحقق من وجود الوجه: إذا لم يتم العثور على وجه في صورة، ينبغي التعامل مع ذلك وتوفير رسالة مناسبة.
التحقق من المسارات: إذا لم يتم تحديد clients_dir أو search_image_path، يجب منع البدء في البحث وتوجيه المستخدم.
تحسين الواجهة:
يمكن تحسين تصميم الواجهة لجعلها أكثر تفاعلية وجاذبية.
إضافة تعليمات أو إرشادات للمستخدم لكيفية استخدام التطبيق.
أداء التطبيق:
إذا كان عدد صور العملاء كبيرًا، قد تستغرق العملية وقتًا طويلاً. يمكن التفكير في تحسينات مثل المعالجة المتوازية (Parallel Processing).
يمكن استخدام تقنيات أكثر كفاءة للتخزين المؤقت مثل قواعد البيانات الخفيفة (SQLite) بدلاً من pickle.
إدارة التخزين المؤقت:
حالياً، يتم إنشاء ملف تخزين مؤقت جديد لكل عملية بحث. يمكن تعديل الكود لاستخدام ملف تخزين مؤقت عام لتقليل زمن البحث في المرات التالية.
إضافة إمكانية تنظيف التخزين المؤقت عند الحاجة.
التوافق والأمان:
التأكد من توافق الكود مع أنظمة التشغيل المختلفة (Windows, macOS, Linux).
التعامل مع صور من صيغ مختلفة وضمان أمان تحميل ومعالجة الملفات.
إضافة ميزات جديدة:
إمكانية حفظ نتائج البحث إلى ملف أو تصديرها.
إضافة خيار لتعديل درجة التشابه المقبولة بين الوجوه.
ختامًا:
هذا الكود يقدم أداة مفيدة للبحث عن العملاء من خلال صور وجوههم، باستخدام تقنيات التعرف على الوجوه. بتطبيق بعض التحسينات المذكورة، يمكن جعله أكثر فعالية واستجابة لاحتياجات المستخدم.