hrlima commited on
Commit
68c5b1b
·
verified ·
1 Parent(s): 4b359bb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -26
app.py CHANGED
@@ -23,11 +23,7 @@ except Exception as e:
23
 
24
  # ====== MODELO ======
25
  try:
26
- model_pipeline = pipeline(
27
- "text-classification",
28
- model="pysentimiento/robertuito-emotion-analysis",
29
- return_all_scores=True
30
- )
31
  print("✅ Modelo carregado com sucesso!")
32
  except Exception as e:
33
  print(f"❌ Erro ao carregar modelo: {e}")
@@ -58,30 +54,58 @@ def gerar_sugestao(emotion_pt):
58
  }
59
  return sugestoes.get(emotion_pt, "Mantenha o equilíbrio emocional e cuide de você mesmo.")
60
 
61
- # ====== FALLBACK APRIMORADO ======
62
- def fallback_emotion(text):
63
- emotion_map = {
64
- "tristeza": ["triste", "desanimado", "melancólico", "chateado", "solitário", "deprimido", "abatido", "infeliz"],
65
- "ansiedade": ["ansioso", "preocupado", "nervoso", "tenso", "inquieto", "aflito", "alarmado", "sobrecarregado"],
66
- "insegurança": ["inseguro", "incerto", "receoso", "hesitante", "duvidoso", "apreensivo", "desconfiado"],
67
- "raiva": ["irritado", "zangado", "raiva", "furioso", "ódio", "revoltado", "frustrado", "indignado"],
68
- "alegria": ["feliz", "animado", "contente", "alegre", "satisfeito", "entusiasmado", "radiante", "orgulhoso"],
69
- "depressão": ["sem esperança", "vazio", "desesperado", "sem vontade", "cansado da vida", "desamparado"],
70
- "neutro": ["ok", "normal", "tranquilo", "indiferente", "equilibrado", "estável"]
71
- }
72
 
 
73
  text_lower = text.lower()
74
- match_counts = {k: sum(1 for w in v if w in text_lower) for k, v in emotion_map.items()}
75
  emotion = max(match_counts, key=match_counts.get)
76
  if match_counts[emotion] == 0:
77
  emotion = "neutro"
78
-
79
  return {
80
  "status": "fallback",
81
  "emotion": emotion,
82
  "emode": [emotion],
83
- "confidence": 0.5 if match_counts[emotion] > 0 else 0.0,
84
- "suggestion": gerar_sugestao(emotion)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
  }
86
 
87
  # ====== ROTA DE ANÁLISE ======
@@ -97,30 +121,32 @@ def analyze():
97
  if not model_pipeline:
98
  return jsonify(fallback_emotion(text))
99
 
100
- result = model_pipeline(text)
101
  if not result or len(result) == 0:
102
  return jsonify(fallback_emotion(text))
103
 
104
- # Extrai probabilidades e identifica maior confiança
105
  scores = {r["label"]: r["score"] for r in result[0]}
106
  top_label = max(scores, key=scores.get)
107
  confidence = round(scores[top_label], 2)
108
  emotion_pt = emotion_labels.get(top_label, "desconhecido")
109
 
110
- # Caso confiança alta em tristeza, considera depressão
111
  if emotion_pt == "tristeza" and confidence >= 0.9:
112
  emotion_pt = "depressão"
113
 
114
- response = {
115
  "status": "ok",
116
  "emotion": emotion_pt,
117
  "emode": [emotion_pt],
118
  "confidence": confidence,
119
- "probabilities": {emotion_labels.get(k, k): round(v, 3) for k, v in scores.items()},
120
  "suggestion": gerar_sugestao(emotion_pt)
121
  }
122
 
123
- return jsonify(response)
 
 
 
124
  except Exception as e:
125
  return jsonify({"error": str(e)}), 500
126
 
 
23
 
24
  # ====== MODELO ======
25
  try:
26
+ model_pipeline = pipeline("text-classification", model="pysentimiento/robertuito-emotion-analysis")
 
 
 
 
27
  print("✅ Modelo carregado com sucesso!")
28
  except Exception as e:
29
  print(f"❌ Erro ao carregar modelo: {e}")
 
54
  }
55
  return sugestoes.get(emotion_pt, "Mantenha o equilíbrio emocional e cuide de você mesmo.")
56
 
57
+ # ====== FALLBACK APRIMORADO COM PALAVRAS-CHAVE ======
58
+ EMOTION_KEYWORDS = {
59
+ "tristeza": ["triste","desanimado","melancólico","chateado","solitário","deprimido","abatido","infeliz","desmotivado"],
60
+ "ansiedade": ["ansioso","preocupado","nervoso","tenso","inquieto","aflito","alarmado","sobrecarregado","inseguro","apreensivo"],
61
+ "insegurança": ["inseguro","incerto","receoso","hesitante","duvidoso","apreensivo","desconfiado"],
62
+ "raiva": ["irritado","zangado","raiva","furioso","ódio","revoltado","frustrado","indignado","hostil","bravo","enfurecido","irado"],
63
+ "alegria": ["feliz","animado","contente","alegre","satisfeito","entusiasmado","radiante","orgulhoso","euforia"],
64
+ "depressão": ["sem esperança","vazio","desesperado","sem vontade","cansado da vida","desamparado"],
65
+ "neutro": ["ok","normal","tranquilo","indiferente","equilibrado","estável"]
66
+ }
 
67
 
68
+ def fallback_emotion(text):
69
  text_lower = text.lower()
70
+ match_counts = {k: sum(1 for w in v if w in text_lower) for k, v in EMOTION_KEYWORDS.items()}
71
  emotion = max(match_counts, key=match_counts.get)
72
  if match_counts[emotion] == 0:
73
  emotion = "neutro"
 
74
  return {
75
  "status": "fallback",
76
  "emotion": emotion,
77
  "emode": [emotion],
78
+ "confidence": 0.6 if match_counts[emotion] > 0 else 0.0,
79
+ "suggestion": gerar_sugestao(emotion),
80
+ "debug": "Fallback ativado"
81
+ }
82
+
83
+ # ====== AJUSTE HÍBRIDO ======
84
+ def hybrid_emotion(text, result):
85
+ text_lower = text.lower()
86
+ detected = result.get("emotion", "neutro")
87
+ max_matches = 0
88
+
89
+ for emo, keywords in EMOTION_KEYWORDS.items():
90
+ matches = sum(2 for w in keywords if w in text_lower)
91
+ if matches > max_matches:
92
+ max_matches = matches
93
+ if emo != detected:
94
+ detected = emo
95
+
96
+ confidence = result.get("confidence", 0.0)
97
+ if detected != result.get("emotion"):
98
+ confidence = 0.7 + max_matches * 0.05
99
+ confidence = min(confidence, 1.0)
100
+
101
+ return {
102
+ "status": "ok",
103
+ "emotion": detected,
104
+ "emode": [detected],
105
+ "confidence": round(confidence, 2),
106
+ "probabilities": result.get("probabilities", {detected: 1.0}),
107
+ "suggestion": result.get("suggestion", gerar_sugestao(detected)),
108
+ "debug": result.get("debug", "Híbrido aplicado")
109
  }
110
 
111
  # ====== ROTA DE ANÁLISE ======
 
121
  if not model_pipeline:
122
  return jsonify(fallback_emotion(text))
123
 
124
+ result = model_pipeline(text, return_all_scores=True)
125
  if not result or len(result) == 0:
126
  return jsonify(fallback_emotion(text))
127
 
 
128
  scores = {r["label"]: r["score"] for r in result[0]}
129
  top_label = max(scores, key=scores.get)
130
  confidence = round(scores[top_label], 2)
131
  emotion_pt = emotion_labels.get(top_label, "desconhecido")
132
 
133
+ # Ajuste especial para "tristeza" muito forte
134
  if emotion_pt == "tristeza" and confidence >= 0.9:
135
  emotion_pt = "depressão"
136
 
137
+ base_result = {
138
  "status": "ok",
139
  "emotion": emotion_pt,
140
  "emode": [emotion_pt],
141
  "confidence": confidence,
142
+ "probabilities": {emotion_labels.get(k, k): round(v,3) for k,v in scores.items()},
143
  "suggestion": gerar_sugestao(emotion_pt)
144
  }
145
 
146
+ # Aplica lógica híbrida com fallback de palavras-chave
147
+ final_result = hybrid_emotion(text, base_result)
148
+ return jsonify(final_result)
149
+
150
  except Exception as e:
151
  return jsonify({"error": str(e)}), 500
152