Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -22,44 +22,50 @@ try:
|
|
| 22 |
except Exception as e:
|
| 23 |
print(f"❌ Erro ao inicializar Firebase: {e}")
|
| 24 |
|
| 25 |
-
# ======
|
|
|
|
| 26 |
try:
|
| 27 |
-
|
| 28 |
-
emotion_pipeline = pipeline(
|
| 29 |
-
"text-classification",
|
| 30 |
-
model="pysentimiento/robertuito-emotion-analysis",
|
| 31 |
-
top_k=None
|
| 32 |
-
)
|
| 33 |
print("✅ Modelo carregado com sucesso!")
|
| 34 |
except Exception as e:
|
| 35 |
-
print(f"❌ Erro ao carregar modelo
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
# ====== EMOÇÕES
|
| 39 |
-
|
| 40 |
-
"
|
| 41 |
-
"
|
| 42 |
-
"
|
| 43 |
-
"
|
| 44 |
-
"
|
| 45 |
-
"
|
|
|
|
| 46 |
}
|
| 47 |
|
| 48 |
-
# ======
|
| 49 |
-
def gerar_sugestao(
|
| 50 |
sugestoes = {
|
| 51 |
-
"tristeza": "
|
| 52 |
-
"
|
| 53 |
-
"alegria": "
|
| 54 |
-
"
|
| 55 |
-
"
|
| 56 |
-
"
|
|
|
|
|
|
|
| 57 |
"desconhecido": "Emoção não identificada com precisão."
|
| 58 |
}
|
| 59 |
-
return sugestoes.get(
|
| 60 |
|
| 61 |
# ====== FALLBACK LOCAL ======
|
| 62 |
def fallback_emotion(text):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
text_lower = text.lower()
|
| 64 |
for emotion, keywords in emotion_map.items():
|
| 65 |
for word in keywords:
|
|
@@ -68,7 +74,7 @@ def fallback_emotion(text):
|
|
| 68 |
"status": "fallback",
|
| 69 |
"emotion": emotion,
|
| 70 |
"emode": [emotion],
|
| 71 |
-
"confidence": 0.
|
| 72 |
"suggestion": gerar_sugestao(emotion)
|
| 73 |
}
|
| 74 |
return {
|
|
@@ -82,7 +88,7 @@ def fallback_emotion(text):
|
|
| 82 |
# ====== ROTA PRINCIPAL ======
|
| 83 |
@app.route("/")
|
| 84 |
def home():
|
| 85 |
-
return jsonify({"message": "API Flask
|
| 86 |
|
| 87 |
# ====== ROTA DE ANÁLISE ======
|
| 88 |
@app.route("/analyze", methods=["POST"])
|
|
@@ -93,45 +99,47 @@ def analyze():
|
|
| 93 |
return jsonify({"error": "Campo 'text' é obrigatório."}), 400
|
| 94 |
|
| 95 |
text = data["text"]
|
| 96 |
-
print(f"\n🧠 Texto recebido: {text}
|
| 97 |
|
| 98 |
-
if not
|
| 99 |
-
print("⚠️ Modelo
|
| 100 |
return jsonify(fallback_emotion(text))
|
| 101 |
|
| 102 |
-
#
|
| 103 |
-
result =
|
|
|
|
|
|
|
| 104 |
|
| 105 |
-
#
|
| 106 |
-
|
| 107 |
-
|
|
|
|
| 108 |
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
return jsonify(fallback_emotion(text))
|
| 112 |
|
| 113 |
-
#
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
confidence = round(scores[emotion], 3)
|
| 117 |
|
|
|
|
| 118 |
response = {
|
| 119 |
"status": "ok",
|
| 120 |
-
"emotion":
|
| 121 |
-
"emode": [
|
| 122 |
-
"probabilities": {k: round(v, 3) for k, v in scores.items()},
|
| 123 |
"confidence": confidence,
|
| 124 |
-
"
|
|
|
|
| 125 |
}
|
| 126 |
|
| 127 |
-
print(f"✅
|
| 128 |
return jsonify(response)
|
| 129 |
|
| 130 |
except Exception as e:
|
| 131 |
print(f"❌ Erro na rota /analyze: {e}")
|
| 132 |
-
return jsonify(
|
| 133 |
-
|
| 134 |
|
| 135 |
# ====== EXECUÇÃO ======
|
| 136 |
if __name__ == "__main__":
|
| 137 |
app.run(host="0.0.0.0", port=7860)
|
|
|
|
|
|
| 22 |
except Exception as e:
|
| 23 |
print(f"❌ Erro ao inicializar Firebase: {e}")
|
| 24 |
|
| 25 |
+
# ====== CONFIGURAÇÃO DO MODELO ======
|
| 26 |
+
print("🔄 Carregando modelo local pysentimiento/robertuito-emotion-analysis...")
|
| 27 |
try:
|
| 28 |
+
model_pipeline = pipeline("text-classification", model="pysentimiento/robertuito-emotion-analysis")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
print("✅ Modelo carregado com sucesso!")
|
| 30 |
except Exception as e:
|
| 31 |
+
print(f"❌ Erro ao carregar modelo: {e}")
|
| 32 |
+
model_pipeline = None
|
| 33 |
+
|
| 34 |
+
# ====== MAPEAMENTO DE EMOÇÕES ======
|
| 35 |
+
emotion_labels = {
|
| 36 |
+
"sadness": "tristeza",
|
| 37 |
+
"joy": "alegria",
|
| 38 |
+
"anger": "raiva",
|
| 39 |
+
"fear": "medo",
|
| 40 |
+
"disgust": "repulsa",
|
| 41 |
+
"surprise": "surpresa",
|
| 42 |
+
"others": "neutro"
|
| 43 |
}
|
| 44 |
|
| 45 |
+
# ====== SUGESTÕES PERSONALIZADAS ======
|
| 46 |
+
def gerar_sugestao(emotion_pt):
|
| 47 |
sugestoes = {
|
| 48 |
+
"tristeza": "Procure fazer algo que te acalme e traga conforto emocional.",
|
| 49 |
+
"depressão": "Você não está sozinho. Considere conversar com alguém de confiança ou buscar apoio profissional.",
|
| 50 |
+
"alegria": "Continue aproveitando esse momento positivo e compartilhe boas energias!",
|
| 51 |
+
"raiva": "Afaste-se da situação e respire antes de reagir. Canalize essa energia em algo produtivo.",
|
| 52 |
+
"medo": "Tente identificar o que está te causando insegurança e dê pequenos passos para enfrentá-lo.",
|
| 53 |
+
"repulsa": "Evite focar em situações desagradáveis. Redirecione sua atenção para algo positivo.",
|
| 54 |
+
"surpresa": "Abrace o inesperado! Às vezes, surpresas podem trazer aprendizados valiosos.",
|
| 55 |
+
"neutro": "Mantenha o equilíbrio emocional e cuide de si mesmo.",
|
| 56 |
"desconhecido": "Emoção não identificada com precisão."
|
| 57 |
}
|
| 58 |
+
return sugestoes.get(emotion_pt, "Mantenha o equilíbrio emocional e cuide de você mesmo.")
|
| 59 |
|
| 60 |
# ====== FALLBACK LOCAL ======
|
| 61 |
def fallback_emotion(text):
|
| 62 |
+
emotion_map = {
|
| 63 |
+
"tristeza": ["triste", "desanimado", "deprimido"],
|
| 64 |
+
"ansiedade": ["ansioso", "preocupado", "tenso"],
|
| 65 |
+
"insegurança": ["inseguro", "incerto", "receoso"],
|
| 66 |
+
"raiva": ["irritado", "zangado", "revoltado"],
|
| 67 |
+
"alegria": ["feliz", "animado", "contente"]
|
| 68 |
+
}
|
| 69 |
text_lower = text.lower()
|
| 70 |
for emotion, keywords in emotion_map.items():
|
| 71 |
for word in keywords:
|
|
|
|
| 74 |
"status": "fallback",
|
| 75 |
"emotion": emotion,
|
| 76 |
"emode": [emotion],
|
| 77 |
+
"confidence": 0.0,
|
| 78 |
"suggestion": gerar_sugestao(emotion)
|
| 79 |
}
|
| 80 |
return {
|
|
|
|
| 88 |
# ====== ROTA PRINCIPAL ======
|
| 89 |
@app.route("/")
|
| 90 |
def home():
|
| 91 |
+
return jsonify({"message": "API Flask funcionando no Space!", "status": "online"})
|
| 92 |
|
| 93 |
# ====== ROTA DE ANÁLISE ======
|
| 94 |
@app.route("/analyze", methods=["POST"])
|
|
|
|
| 99 |
return jsonify({"error": "Campo 'text' é obrigatório."}), 400
|
| 100 |
|
| 101 |
text = data["text"]
|
| 102 |
+
print(f"\n🧠 Texto recebido: {text}")
|
| 103 |
|
| 104 |
+
if not model_pipeline:
|
| 105 |
+
print("⚠️ Modelo indisponível, usando fallback local.")
|
| 106 |
return jsonify(fallback_emotion(text))
|
| 107 |
|
| 108 |
+
# Execução do modelo
|
| 109 |
+
result = model_pipeline(text, return_all_scores=True)
|
| 110 |
+
if not result or len(result) == 0:
|
| 111 |
+
return jsonify(fallback_emotion(text))
|
| 112 |
|
| 113 |
+
# Extraindo probabilidades
|
| 114 |
+
scores = {r["label"]: r["score"] for r in result[0]}
|
| 115 |
+
top_label = max(scores, key=scores.get)
|
| 116 |
+
confidence = round(scores[top_label], 2)
|
| 117 |
|
| 118 |
+
# Tradução
|
| 119 |
+
emotion_pt = emotion_labels.get(top_label, "desconhecido")
|
|
|
|
| 120 |
|
| 121 |
+
# Regra extra: tristeza intensa -> depressão
|
| 122 |
+
if emotion_pt == "tristeza" and confidence >= 0.9:
|
| 123 |
+
emotion_pt = "depressão"
|
|
|
|
| 124 |
|
| 125 |
+
# Geração de resposta
|
| 126 |
response = {
|
| 127 |
"status": "ok",
|
| 128 |
+
"emotion": emotion_pt,
|
| 129 |
+
"emode": [emotion_pt],
|
|
|
|
| 130 |
"confidence": confidence,
|
| 131 |
+
"probabilities": {emotion_labels.get(k, k): round(v, 3) for k, v in scores.items()},
|
| 132 |
+
"suggestion": gerar_sugestao(emotion_pt)
|
| 133 |
}
|
| 134 |
|
| 135 |
+
print(f"✅ Análise concluída: {response}")
|
| 136 |
return jsonify(response)
|
| 137 |
|
| 138 |
except Exception as e:
|
| 139 |
print(f"❌ Erro na rota /analyze: {e}")
|
| 140 |
+
return jsonify({"error": str(e)}), 500
|
|
|
|
| 141 |
|
| 142 |
# ====== EXECUÇÃO ======
|
| 143 |
if __name__ == "__main__":
|
| 144 |
app.run(host="0.0.0.0", port=7860)
|
| 145 |
+
|