Spaces:
Running
Running
File size: 13,635 Bytes
ca65aec |
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 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 |
# # servers/emotion_server.py
# from fastmcp import FastMCP, tool
# import re
# app = FastMCP("emotion-server")
# _PATTERNS = {
# "happy": r"\b(happy|grateful|excited|joy|delighted|content|optimistic)\b",
# "sad": r"\b(sad|down|depressed|cry|lonely|upset|miserable)\b",
# "angry": r"\b(angry|mad|furious|irritated|pissed|annoyed|resentful)\b",
# "anxious": r"\b(worried|anxious|nervous|stressed|overwhelmed|scared)\b",
# "tired": r"\b(tired|exhausted|drained|burnt|sleepy|fatigued)\b",
# "love": r"\b(love|affection|caring|fond|admire|cherish)\b",
# "fear": r"\b(afraid|fear|terrified|panicked|shaken)\b",
# }
# _TONES = {"happy":"light","love":"light","sad":"gentle","fear":"gentle",
# "angry":"calming","anxious":"calming","tired":"gentle"}
# def _analyze(text: str) -> dict:
# t = text.lower()
# found = [k for k,pat in _PATTERNS.items() if re.search(pat, t)]
# valence = 0.0
# if "happy" in found or "love" in found: valence += 0.6
# if "sad" in found or "fear" in found: valence -= 0.6
# if "angry" in found: valence -= 0.4
# if "anxious" in found: valence -= 0.3
# if "tired" in found: valence -= 0.2
# arousal = 0.5 + (0.3 if ("angry" in found or "anxious" in found) else 0) - (0.2 if "tired" in found else 0)
# tone = "neutral"
# for e in found:
# if e in _TONES: tone = _TONES[e]; break
# return {
# "labels": found or ["neutral"],
# "valence": max(-1, min(1, round(valence, 2))),
# "arousal": max(0, min(1, round(arousal, 2))),
# "tone": tone,
# }
# @tool
# def analyze(text: str) -> dict:
# """
# Analyze user text for emotion.
# Args:
# text: str - user message
# Returns: dict {labels, valence, arousal, tone}
# """
# return _analyze(text)
# if __name__ == "__main__":
# app.run() # serves MCP over stdio
# servers/emotion_server.py
from __future__ import annotations
# ---- FastMCP import shim (works across versions) ----
# Ensures: FastMCP is imported and `@tool` is ALWAYS a callable decorator.
from typing import Callable, Any
try:
from fastmcp import FastMCP # present across versions
except Exception as e:
raise ImportError(f"FastMCP missing: {e}")
_tool_candidate: Any = None
# Try common locations
try:
from fastmcp import tool as _tool_candidate # newer API: function
except Exception:
try:
from fastmcp.tools import tool as _tool_candidate # older API: function
except Exception:
_tool_candidate = None
# If we somehow got a module instead of a function, try attribute
if _tool_candidate is not None and not callable(_tool_candidate):
try:
_tool_candidate = _tool_candidate.tool # some builds expose module.tools.tool
except Exception:
_tool_candidate = None
def tool(*dargs, **dkwargs):
"""
Wrapper that behaves correctly in both usages:
@tool
@tool(...)
If real decorator exists, delegate. Otherwise:
- If called as @tool (i.e., first arg is fn), return fn (no-op).
- If called as @tool(...), return a decorator that returns fn (no-op).
"""
if callable(_tool_candidate):
return _tool_candidate(*dargs, **dkwargs)
# No real decorator available β provide no-op behavior.
if dargs and callable(dargs[0]) and not dkwargs:
# Used as @tool
fn = dargs[0]
return fn
# Used as @tool(...)
def _noop_decorator(fn):
return fn
return _noop_decorator
# ---- end shim ----
import re, math, time
from typing import Dict, List, Tuple, Optional
app = FastMCP("emotion-server")
# ---------------------------
# Lexicons & heuristics
# ---------------------------
EMO_LEX = {
"happy": r"\b(happy|grateful|excited|joy(?:ful)?|delighted|content|optimistic|glad|thrilled|yay)\b",
"sad": r"\b(sad|down|depress(?:ed|ing)|cry(?:ing)?|lonely|upset|miserable|heartbroken)\b",
"angry": r"\b(angry|mad|furious|irritated|pissed|annoyed|resentful|rage|hate)\b",
"anxious": r"\b(worried|anxious|nervous|stressed|overwhelmed|scared|uneasy|tense|on edge)\b",
"tired": r"\b(tired|exhaust(?:ed|ing)|drained|burnt(?:\s*out)?|sleepy|fatigued|worn out)\b",
"love": r"\b(love|affection|caring|fond|admire|cherish|adore)\b",
"fear": r"\b(afraid|fear|terrified|panic(?:ky|ked)?|panicked|shaken|petrified)\b",
}
# Emojis contribute signals even without words
EMOJI_SIGNAL = {
"happy": ["π","π","π","π","π","π₯³","β¨"],
"sad": ["π’","π","π","π","βΉοΈ"],
"angry": ["π ","π‘","π€¬","π’"],
"anxious":["π°","π±","π¬","π","π§"],
"tired": ["π₯±","πͺ","π΄"],
"love": ["β€οΈ","π","π","π","π€","π","π","π"],
"fear": ["π«£","π¨","π±","π"],
}
NEGATORS = r"\b(no|not|never|hardly|barely|scarcely|isn['β]t|aren['β]t|can['β]t|don['β]t|doesn['β]t|won['β]t|without)\b"
INTENSIFIERS = {
r"\b(very|really|super|so|extremely|incredibly|totally|absolutely)\b": 1.35,
r"\b(kinda|kind of|somewhat|slightly|a bit|a little)\b": 0.75,
}
SARCASM_CUES = [
r"\byeah right\b", r"\bsure\b", r"\".+\"", r"/s\b", r"\bokayyy+\b", r"\blol\b(?!\w)"
]
# Tone map by quadrant
# arousal high/low Γ valence pos/neg
def quad_tone(valence: float, arousal: float) -> str:
if arousal >= 0.6 and valence >= 0.1: return "excited"
if arousal >= 0.6 and valence < -0.1: return "concerned"
if arousal < 0.6 and valence < -0.1: return "gentle"
if arousal < 0.6 and valence >= 0.1: return "calm"
return "neutral"
# ---------------------------
# Utilities
# ---------------------------
_compiled = {k: re.compile(p, re.I) for k, p in EMO_LEX.items()}
_neg_pat = re.compile(NEGATORS, re.I)
_int_pats = [(re.compile(p, re.I), w) for p, w in INTENSIFIERS.items()]
_sarcasm = [re.compile(p, re.I) for p in SARCASM_CUES]
def _emoji_hits(text: str) -> Dict[str, int]:
hits = {k: 0 for k in EMO_LEX}
for emo, arr in EMOJI_SIGNAL.items():
for e in arr:
hits[emo] += text.count(e)
return hits
def _intensity_multiplier(text: str) -> float:
mult = 1.0
for pat, w in _int_pats:
if pat.search(text):
mult *= w
# Exclamation marks increase arousal a bit (cap effect)
bangs = min(text.count("!"), 5)
mult *= (1.0 + 0.04 * bangs)
# ALL CAPS word run nudges intensity
if re.search(r"\b[A-Z]{3,}\b", text):
mult *= 1.08
return max(0.5, min(1.8, mult))
def _negation_factor(text: str, span_start: int) -> float:
"""
Look 5 words (~40 chars) backwards for a negator.
If present, invert or dampen signal.
"""
window_start = max(0, span_start - 40)
window = text[window_start:span_start]
if _neg_pat.search(window):
return -0.7 # invert and dampen
return 1.0
def _sarcasm_penalty(text: str) -> float:
return 0.85 if any(p.search(text) for p in _sarcasm) else 1.0
def _softmax(d: Dict[str, float]) -> Dict[str, float]:
xs = list(d.values())
if not xs: return d
m = max(xs)
exps = [math.exp(x - m) for x in xs]
s = sum(exps) or 1.0
return {k: exps[i] / s for i, k in enumerate(d.keys())}
# ---------------------------
# Per-user calibration (in-memory)
# ---------------------------
CALIBRATION: Dict[str, Dict[str, float]] = {} # user_id -> {bias_emo: float, arousal_bias: float, valence_bias: float}
def _apply_calibration(user_id: Optional[str], emo_scores: Dict[str, float], valence: float, arousal: float):
if not user_id or user_id not in CALIBRATION:
return emo_scores, valence, arousal
calib = CALIBRATION[user_id]
# shift emotions
for k, bias in calib.items():
if k in emo_scores:
emo_scores[k] += bias * 0.2
# dedicated valence/arousal bias keys if present
valence += calib.get("valence_bias", 0.0) * 0.15
arousal += calib.get("arousal_bias", 0.0) * 0.15
return emo_scores, valence, arousal
# ---------------------------
# Core analysis
# ---------------------------
def _analyze(text: str, user_id: Optional[str] = None) -> dict:
t = text or ""
tl = t.lower()
# Base scores from lexicon hits
emo_scores: Dict[str, float] = {k: 0.0 for k in EMO_LEX}
spans: Dict[str, List[Tuple[int, int, str]]] = {k: [] for k in EMO_LEX}
for emo, pat in _compiled.items():
for m in pat.finditer(tl):
factor = _negation_factor(tl, m.start())
emo_scores[emo] += 1.0 * factor
spans[emo].append((m.start(), m.end(), tl[m.start():m.end()]))
# Emoji contributions
e_hits = _emoji_hits(t)
for emo, c in e_hits.items():
if c:
emo_scores[emo] += 0.6 * c
# Intensifiers / sarcasm / punctuation adjustments (global)
intensity = _intensity_multiplier(t)
sarcasm_mult = _sarcasm_penalty(t)
for emo in emo_scores:
emo_scores[emo] *= intensity * sarcasm_mult
# Map to valence/arousal
pos = emo_scores["happy"] + emo_scores["love"]
neg = emo_scores["sad"] + emo_scores["fear"] + 0.9 * emo_scores["angry"] + 0.6 * emo_scores["anxious"]
valence = max(-1.0, min(1.0, round((pos - neg) * 0.4, 3)))
base_arousal = 0.5
arousal = base_arousal \
+ 0.12 * (emo_scores["angry"] > 0) \
+ 0.08 * (emo_scores["anxious"] > 0) \
- 0.10 * (emo_scores["tired"] > 0) \
+ 0.02 * min(t.count("!"), 5)
arousal = max(0.0, min(1.0, round(arousal, 3)))
# Confidence: count signals + consistency
hits = sum(1 for v in emo_scores.values() if abs(v) > 0.01) + sum(e_hits.values())
consistency = 0.0
if hits:
top2 = sorted(emo_scores.items(), key=lambda kv: kv[1], reverse=True)[:2]
if len(top2) == 2 and top2[1][1] > 0:
ratio = top2[0][1] / (top2[1][1] + 1e-6)
consistency = max(0.0, min(1.0, (ratio - 1) / 3)) # >1 means some separation
elif len(top2) == 1:
consistency = 0.6
conf = max(0.0, min(1.0, 0.25 + 0.1 * hits + 0.5 * consistency))
# downweight very short texts
if len(t.strip()) < 6:
conf *= 0.6
# Normalize emotions to pseudo-probs (softmax over positive scores)
pos_scores = {k: max(0.0, v) for k, v in emo_scores.items()}
probs = _softmax(pos_scores)
# Apply per-user calibration
probs, valence, arousal = _apply_calibration(user_id, probs, valence, arousal)
# Tone
tone = quad_tone(valence, arousal)
# Explanations
reasons = []
if intensity > 1.0: reasons.append(f"intensifiers x{intensity:.2f}")
if sarcasm_mult < 1.0: reasons.append("sarcasm cues detected")
if any(_neg_pat.search(tl[max(0,s-40):s]) for emo, spans_ in spans.items() for (s,_,_) in spans_):
reasons.append("negation near emotion tokens")
if any(e_hits.values()): reasons.append("emoji signals")
labels_sorted = sorted(probs.items(), key=lambda kv: kv[1], reverse=True)
top_labels = [k for k, v in labels_sorted[:3] if v > 0.05] or ["neutral"]
return {
"labels": top_labels,
"scores": {k: round(v, 3) for k, v in probs.items()},
"valence": round(valence, 3),
"arousal": round(arousal, 3),
"tone": tone,
"confidence": round(conf, 3),
"reasons": reasons,
"spans": {k: spans[k] for k in top_labels if spans.get(k)},
"ts": time.time(),
"user_id": user_id,
}
# ---------------------------
# MCP tools
# ---------------------------
@app.tool()
def analyze(text: str, user_id: Optional[str] = None) -> dict:
"""
Analyze text for emotion.
Args:
text: user message
user_id: optional user key for calibration
Returns:
dict with labels, scores (per emotion), valence [-1..1], arousal [0..1],
tone (calm/neutral/excited/concerned/gentle), confidence, reasons, spans.
"""
return _analyze(text, user_id=user_id)
@app.tool()
def batch_analyze(messages: List[str], user_id: Optional[str] = None) -> List[dict]:
"""
Batch analyze a list of messages.
"""
return [_analyze(m or "", user_id=user_id) for m in messages]
@app.tool()
def calibrate(user_id: str, bias: Dict[str, float] = None, arousal_bias: float = 0.0, valence_bias: float = 0.0) -> dict:
"""
Adjust per-user calibration.
- bias: e.g. {"anxious": -0.1, "love": 0.1}
- arousal_bias/valence_bias: small nudges (-1..1) applied after scoring.
"""
if user_id not in CALIBRATION:
CALIBRATION[user_id] = {}
if bias:
for k, v in bias.items():
CALIBRATION[user_id][k] = float(v)
if arousal_bias:
CALIBRATION[user_id]["arousal_bias"] = float(arousal_bias)
if valence_bias:
CALIBRATION[user_id]["valence_bias"] = float(valence_bias)
return {"ok": True, "calibration": CALIBRATION[user_id]}
@app.tool()
def reset_calibration(user_id: str) -> dict:
"""Remove per-user calibration."""
CALIBRATION.pop(user_id, None)
return {"ok": True}
@app.tool()
def health() -> dict:
"""Simple health check for MCP status chips."""
return {"status": "ok", "version": "1.2.0", "time": time.time()}
@app.tool()
def version() -> dict:
"""Return server version & feature flags."""
return {
"name": "emotion-server",
"version": "1.2.0",
"features": ["negation", "intensifiers", "emoji", "sarcasm", "confidence", "batch", "calibration"],
"emotions": list(EMO_LEX.keys()),
}
if __name__ == "__main__":
app.run() # serves MCP over stdio
|