Update app.py
Browse files
app.py
CHANGED
@@ -40,31 +40,52 @@ def extract_feature(signal: np.ndarray, sr: int) -> np.ndarray:
|
|
40 |
|
41 |
# --- 4. 三種預測函式 ---
|
42 |
|
43 |
-
def predict_face(img
|
44 |
-
|
45 |
-
|
|
|
|
|
|
|
|
|
|
|
46 |
try:
|
47 |
-
|
48 |
-
|
49 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
50 |
return emo
|
51 |
except Exception as e:
|
52 |
print("DeepFace.analyze error:", e)
|
53 |
-
|
|
|
54 |
|
55 |
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
68 |
|
69 |
|
70 |
|
|
|
40 |
|
41 |
# --- 4. 三種預測函式 ---
|
42 |
|
43 |
+
def predict_face(img):
|
44 |
+
global _last_time, _last_result
|
45 |
+
if img is None:
|
46 |
+
return {}
|
47 |
+
now = time.time()
|
48 |
+
# 限频: 每 0.5 秒最多分析一次
|
49 |
+
if now - _last_time < 0.5 and _last_result:
|
50 |
+
return _last_result
|
51 |
try:
|
52 |
+
res = DeepFace.analyze(img, actions=["emotion"], detector_backend="opencv")
|
53 |
+
# 处理返回类型
|
54 |
+
if isinstance(res, list):
|
55 |
+
first = res[0] if len(res) > 0 else {}
|
56 |
+
emo = first.get("emotion", {}) if isinstance(first, dict) else {}
|
57 |
+
elif isinstance(res, dict):
|
58 |
+
emo = res.get("emotion", {})
|
59 |
+
else:
|
60 |
+
emo = {}
|
61 |
+
_last_result = emo
|
62 |
+
_last_time = now
|
63 |
+
print("predict_face result:", emo)
|
64 |
return emo
|
65 |
except Exception as e:
|
66 |
print("DeepFace.analyze error:", e)
|
67 |
+
# 出错时返回上次有效结果或空
|
68 |
+
return _last_result if _last_result else {}
|
69 |
|
70 |
|
71 |
+
|
72 |
+
def predict_voice(audio_path: str):
|
73 |
+
# 如果没有录音文件路径,直接返回空字典或提示
|
74 |
+
if not audio_path:
|
75 |
+
# 可打印日志,帮助调试
|
76 |
+
print("predict_voice: 收到 None 或空 audio_path,跳過分析")
|
77 |
+
return {}
|
78 |
+
try:
|
79 |
+
signal, sr = librosa.load(audio_path, sr=None)
|
80 |
+
# 提取特征
|
81 |
+
feat = extract_feature(signal, sr) # 你的特征提取函数
|
82 |
+
probs = svm_model.predict_proba([feat])[0]
|
83 |
+
labels = svm_model.classes_
|
84 |
+
return {labels[i]: float(probs[i]) for i in range(len(labels))}
|
85 |
+
except Exception as e:
|
86 |
+
print("predict_voice error:", e)
|
87 |
+
return {}
|
88 |
+
|
89 |
|
90 |
|
91 |
|