File size: 1,233 Bytes
357796f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# app.py
import os
# —— 把 DeepFace 缓存目录指向可写的 /tmp/.deepface
os.environ["DEEPFACE_HOME"] = "/tmp/.deepface"
os.makedirs(os.environ["DEEPFACE_HOME"], exist_ok=True)

import gradio as gr
import cv2
import numpy as np
from deepface import DeepFace

def face_emotion(frame: np.ndarray) -> str:
    """
    接收 gr.Camera 给出的 RGB ndarray,
    转成 BGR 后交给 DeepFace 分析情绪。
    """
    # RGB → BGR
    bgr = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
    res = DeepFace.analyze(
        bgr,
        actions=['emotion'],
        enforce_detection=False
    )
    # DeepFace 支持 list 或 dict 返回
    if isinstance(res, list):
        emo = res[0].get('dominant_emotion', 'unknown')
    else:
        emo = res.get('dominant_emotion', 'unknown')
    return emo

# —— Gradio 前端 —— 
with gr.Blocks() as demo:
    gr.Markdown("## 📱 多模態即時情緒分析(示範:即時人臉情緒)")
    camera = gr.Camera(label="請對準鏡頭", type="numpy")
    output = gr.Textbox(label="偵測到的情緒")
    # 实时流:fps 可以调低一点,减轻服务器压力
    camera.stream(face_emotion, camera, output, fps=5)

if __name__ == "__main__":
    demo.launch()