Repository navigation
Expand file tree
/
Copy pathemotion_classifier.py
More file actions
74 lines (55 loc) · 2.34 KB
/
Copy pathemotion_classifier.py
File metadata and controls
74 lines (55 loc) · 2.34 KB
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
from __future__ import annotations
import threading
import numpy as np
from typing import NamedTuple
from embedding import encode
try:
from config import EMOTION_LABELS, SHORT_TEXT_MAX_LEN
except ImportError:
EMOTION_LABELS = ["开心", "悲伤", "愤怒", "惊讶", "恐惧", "厌恶", "中性"]
SHORT_TEXT_MAX_LEN = 10
_lock = threading.Lock()
_label_embeddings: list[list[float]] | None = None
class EmotionResult(NamedTuple):
emotion: str
score: float
def _ensure_label_embeddings() -> list[list[float]]:
"""Compute and cache L2-normalized label embeddings once. Thread-safe."""
global _label_embeddings
if _label_embeddings is None:
with _lock:
if _label_embeddings is None:
import numpy as np
emb = encode(EMOTION_LABELS, normalize=True)
_label_embeddings = [emb[i].tolist() for i in range(len(EMOTION_LABELS))]
return _label_embeddings
def classify(text: str) -> EmotionResult:
"""
Classify text into one of the predefined emotions by cosine similarity.
Returns the top-1 emotion label and score.
"""
if not text or not text.strip():
return EmotionResult(emotion=EMOTION_LABELS[-1], score=0.0) # neutral
label_emb = _ensure_label_embeddings()
q = encode([text.strip()], normalize=True) # (1, 768)
C = np.array(label_emb, dtype=np.float64) # (n_classes, 768)
scores = np.dot(q, C.T).ravel() # (n_classes,) cosine already (normalized)
idx = int(np.argmax(scores))
return EmotionResult(emotion=EMOTION_LABELS[idx], score=float(scores[idx]))
def is_ready() -> bool:
"""Return True if label embeddings are cached (model and categories ready)."""
return _label_embeddings is not None
def classify_with_fallback(text: str) -> EmotionResult:
"""
Short text: use rule-based first. Longer text: use embedding when ready, else rule-based.
Return type is EmotionResult so callers get emotion + score in all cases.
"""
from rule_based_emotion import classify_rule_based
stripped = (text or "").strip()
if len(stripped) <= SHORT_TEXT_MAX_LEN:
r = classify_rule_based(text)
return EmotionResult(emotion=r.emotion, score=r.score)
if is_ready():
return classify(text)
r = classify_rule_based(text)
return EmotionResult(emotion=r.emotion, score=r.score)