File size: 3,179 Bytes
8bd49c3
 
cf2462a
 
 
8bd49c3
 
cf2462a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8bd49c3
 
 
 
 
 
 
 
 
 
 
cf2462a
8bd49c3
 
 
cf2462a
8bd49c3
 
cf2462a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8bd49c3
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
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()