deepFaceAPI / app.py
huy00001's picture
Update app.py
cf2462a verified
raw
history blame
3.18 kB
import gradio as gr
from deepface import DeepFace
import os
import uuid
import shutil
import json
# Thư mục lưu ảnh upload
UPLOAD_FOLDER = "uploads"
if not os.path.exists(UPLOAD_FOLDER):
os.makedirs(UPLOAD_FOLDER)
# 1️⃣ API: Push ảnh lên server
def upload_image(image):
try:
image_id = str(uuid.uuid4())
save_path = os.path.join(UPLOAD_FOLDER, f"{image_id}.png")
image.save(save_path) # nếu image là PIL.Image
return f"Ảnh lưu thành công với ID: {image_id}", image_id
except Exception as e:
return f"Lỗi khi upload: {str(e)}", None
# 2️⃣ API: Nhận diện khuôn mặt
def recognize_face(image, image_id):
try:
target_path = os.path.join(UPLOAD_FOLDER, f"{image_id}.png")
if not os.path.exists(target_path):
return "Ảnh ID không tồn tại"
result = DeepFace.verify(img1_path=image, img2_path=target_path)
# result là dict có 'verified': True/False, 'distance': float
output = {
"Verified": result["verified"],
"Khoảng cách": round(result["distance"], 4)
}
return json.dumps(output, ensure_ascii=False, indent=2)
except Exception as e:
return f"Lỗi khi nhận diện: {str(e)}"
# 3️⃣ API: Phân tích khuôn mặt
def analyze_face(image):
try:
result = DeepFace.analyze(
img_path=image,
actions=["age", "gender", "emotion", "race"],
enforce_detection=False
)
info = result[0]
output = {
"Tuổi ước tính": info["age"],
"Giới tính": "Nam" if info["dominant_gender"] == "Man" else "Nữ",
"Cảm xúc chính": info["dominant_emotion"],
"Chủng tộc": info["dominant_race"]
}
return json.dumps(output, ensure_ascii=False, indent=2)
except Exception as e:
return f"Lỗi khi phân tích: {str(e)}"
# Tạo giao diện Gradio
with gr.Blocks() as demo:
gr.Markdown("## 📁 Upload ảnh")
with gr.Row():
upload_input = gr.Image(label="Upload ảnh", type="pil")
upload_btn = gr.Button("Upload")
upload_output = gr.Textbox(label="Kết quả Upload")
image_id_store = gr.State() # lưu image_id
upload_btn.click(upload_image, inputs=upload_input, outputs=[upload_output, image_id_store])
gr.Markdown("## 🆔 Nhận diện khuôn mặt")
with gr.Row():
recognize_input = gr.Image(label="Ảnh cần nhận diện", type="pil")
recognize_btn = gr.Button("Nhận diện")
recognize_output = gr.Textbox(label="Kết quả nhận diện")
recognize_btn.click(recognize_face, inputs=[recognize_input, image_id_store], outputs=recognize_output)
gr.Markdown("## 🔍 Phân tích khuôn mặt")
with gr.Row():
analyze_input = gr.Image(label="Ảnh cần phân tích", type="pil")
analyze_btn = gr.Button("Phân tích")
analyze_output = gr.Textbox(label="Kết quả phân tích")
analyze_btn.click(analyze_face, inputs=analyze_input, outputs=analyze_output)
if __name__ == "__main__":
demo.launch()