GCLing commited on
Commit
4826bc7
·
verified ·
1 Parent(s): 4eafa91

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +40 -19
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: np.ndarray):
44
- print("predict_face called, img is None?", img is None)
45
- # 你的限频和 DeepFace 分析逻辑...
 
 
 
 
 
46
  try:
47
- result = DeepFace.analyze(img, actions=["emotion"], detector_backend="opencv")
48
- emo = result.get("emotion", {})
49
- print("DeepFace result:", emo)
 
 
 
 
 
 
 
 
 
50
  return emo
51
  except Exception as e:
52
  print("DeepFace.analyze error:", e)
53
- return {}
 
54
 
55
 
56
- def predict_voice(audio):
57
- """
58
- 語音情緒分析:audio 由 Gradio 傳入,形式為暫存檔路徑字串 (str)。
59
- librosa.load 讀取,再提取 MFCC 特徵,最後用 SVM 模型 predict_proba。
60
- 回傳格式為 dict,例如 {"angry":0.1, "happy":0.7, ...}
61
- """
62
- # audio 參數為 Gradio Audio 組件給的檔案路徑
63
- signal, sr = librosa.load(audio, sr=None)
64
- feat = extract_feature(signal, sr)
65
- probs = svm_model.predict_proba([feat])[0]
66
- labels = svm_model.classes_
67
- return {labels[i]: float(probs[i]) for i in range(len(labels))}
 
 
 
 
 
 
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