Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -8,7 +8,7 @@ from huggingface_hub import InferenceClient
|
|
| 8 |
app = Flask(__name__)
|
| 9 |
|
| 10 |
# =============================
|
| 11 |
-
# Inicialização
|
| 12 |
# =============================
|
| 13 |
firebase_key = os.getenv("FIREBASE_KEY")
|
| 14 |
if not firebase_key:
|
|
@@ -35,114 +35,109 @@ if not HF_TOKEN:
|
|
| 35 |
client = InferenceClient(token=HF_TOKEN)
|
| 36 |
|
| 37 |
# =============================
|
| 38 |
-
#
|
| 39 |
# =============================
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
}
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
"
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
"neutro": "Você parece tranquilo no momento."
|
| 60 |
-
}
|
| 61 |
|
| 62 |
# =============================
|
| 63 |
-
#
|
| 64 |
# =============================
|
| 65 |
-
def
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
|
| 73 |
# =============================
|
| 74 |
-
# Rota
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
# =============================
|
| 76 |
@app.route("/analyze", methods=["POST"])
|
| 77 |
def analyze():
|
| 78 |
try:
|
| 79 |
data = request.get_json()
|
| 80 |
if not data or "text" not in data:
|
| 81 |
-
return jsonify({"
|
| 82 |
|
| 83 |
text = data["text"]
|
| 84 |
|
| 85 |
-
#
|
| 86 |
response = client.text_classification(
|
| 87 |
text,
|
| 88 |
-
model="
|
| 89 |
)
|
| 90 |
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
probabilidades = {}
|
| 94 |
-
for item in results:
|
| 95 |
-
label = item["label"].lower()
|
| 96 |
-
score = round(item["score"], 4)
|
| 97 |
-
|
| 98 |
-
# Conversão e agrupamento manual
|
| 99 |
-
if label in ["sadness", "grief", "hopelessness"]:
|
| 100 |
-
label = "depression"
|
| 101 |
-
elif label == "anger":
|
| 102 |
-
label = "anger"
|
| 103 |
-
elif label == "joy":
|
| 104 |
-
label = "joy"
|
| 105 |
|
| 106 |
-
|
| 107 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
|
| 109 |
-
#
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
# Define principal emoção
|
| 114 |
-
principal = max(probabilidades, key=probabilidades.get)
|
| 115 |
-
sugestao = SUGESTOES.get(principal, "Mantenha o equilíbrio emocional.")
|
| 116 |
|
| 117 |
result = {
|
| 118 |
"status": "ok",
|
| 119 |
-
"emotion":
|
| 120 |
-
"emode":
|
| 121 |
-
"probabilities":
|
| 122 |
-
"suggestion":
|
| 123 |
}
|
| 124 |
|
| 125 |
-
#
|
| 126 |
if db:
|
| 127 |
db.collection("emotions").add({
|
| 128 |
"text": text,
|
| 129 |
-
"emotion":
|
| 130 |
-
"probabilities":
|
| 131 |
})
|
| 132 |
|
| 133 |
return jsonify(result)
|
| 134 |
|
| 135 |
except Exception as e:
|
| 136 |
print(f"❌ Erro na rota /analyze: {e}")
|
| 137 |
-
return jsonify({
|
| 138 |
-
"status": "fallback",
|
| 139 |
-
"emotion": "neutro",
|
| 140 |
-
"emode": ["neutro"],
|
| 141 |
-
"suggestion": "Falha na análise. Fallback ativado.",
|
| 142 |
-
"debug": str(e)
|
| 143 |
-
}), 500
|
| 144 |
-
|
| 145 |
|
|
|
|
|
|
|
|
|
|
| 146 |
if __name__ == "__main__":
|
| 147 |
port = int(os.environ.get("PORT", 7860))
|
| 148 |
app.run(host="0.0.0.0", port=port, debug=False)
|
|
|
|
| 8 |
app = Flask(__name__)
|
| 9 |
|
| 10 |
# =============================
|
| 11 |
+
# Inicialização do Firebase
|
| 12 |
# =============================
|
| 13 |
firebase_key = os.getenv("FIREBASE_KEY")
|
| 14 |
if not firebase_key:
|
|
|
|
| 35 |
client = InferenceClient(token=HF_TOKEN)
|
| 36 |
|
| 37 |
# =============================
|
| 38 |
+
# Função de mapeamento de emoções
|
| 39 |
# =============================
|
| 40 |
+
def map_emotion(label, score):
|
| 41 |
+
mapping = {
|
| 42 |
+
"joy": "alegria",
|
| 43 |
+
"sadness": "tristeza",
|
| 44 |
+
"anger": "raiva",
|
| 45 |
+
"fear": "medo",
|
| 46 |
+
"disgust": "nojo",
|
| 47 |
+
"surprise": "surpresa",
|
| 48 |
+
"neutral": "neutro",
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
# Mapeia para português
|
| 52 |
+
emotion_pt = mapping.get(label.lower(), "neutro")
|
| 53 |
+
|
| 54 |
+
# Identifica "depressão" quando tristeza for alta
|
| 55 |
+
if emotion_pt == "tristeza" and score >= 0.60:
|
| 56 |
+
emotion_pt = "depressão"
|
| 57 |
+
|
| 58 |
+
return emotion_pt
|
|
|
|
|
|
|
| 59 |
|
| 60 |
# =============================
|
| 61 |
+
# Sugestões baseadas na emoção
|
| 62 |
# =============================
|
| 63 |
+
def get_suggestion(emotion):
|
| 64 |
+
suggestions = {
|
| 65 |
+
"alegria": "Continue aproveitando esse momento positivo! 😊",
|
| 66 |
+
"tristeza": "Tente conversar com alguém de confiança. 💬",
|
| 67 |
+
"depressão": "Você não está sozinho. Procure apoio emocional ou profissional. 💙",
|
| 68 |
+
"raiva": "Respire fundo e tente relaxar antes de reagir. 😤",
|
| 69 |
+
"medo": "Procure entender o que te causa medo e fale sobre isso. 💭",
|
| 70 |
+
"nojo": "Afaste-se do que está te incomodando e busque se acalmar. 🌿",
|
| 71 |
+
"surpresa": "Às vezes a vida nos surpreende de formas boas e ruins — reflita com calma. 🤔",
|
| 72 |
+
"neutro": "Você parece tranquilo no momento. 🌼",
|
| 73 |
+
}
|
| 74 |
+
return suggestions.get(emotion, "Cuide de você mesmo hoje. ❤️")
|
| 75 |
|
| 76 |
# =============================
|
| 77 |
+
# Rota de teste
|
| 78 |
+
# =============================
|
| 79 |
+
@app.route("/")
|
| 80 |
+
def index():
|
| 81 |
+
return jsonify({"status": "online", "message": "API Flask funcionando com pysentimiento!"})
|
| 82 |
+
|
| 83 |
+
# =============================
|
| 84 |
+
# Rota principal de análise
|
| 85 |
# =============================
|
| 86 |
@app.route("/analyze", methods=["POST"])
|
| 87 |
def analyze():
|
| 88 |
try:
|
| 89 |
data = request.get_json()
|
| 90 |
if not data or "text" not in data:
|
| 91 |
+
return jsonify({"error": "Campo 'text' é obrigatório"}), 400
|
| 92 |
|
| 93 |
text = data["text"]
|
| 94 |
|
| 95 |
+
# Chama o modelo de emoção do Hugging Face
|
| 96 |
response = client.text_classification(
|
| 97 |
text,
|
| 98 |
+
model="pysentimiento/robertuito-emotion-analysis"
|
| 99 |
)
|
| 100 |
|
| 101 |
+
if not response or len(response) == 0:
|
| 102 |
+
raise ValueError("Resposta vazia da API do Hugging Face")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
|
| 104 |
+
# Mapeia e organiza as probabilidades
|
| 105 |
+
probabilities = {}
|
| 106 |
+
for item in response:
|
| 107 |
+
label = item["label"]
|
| 108 |
+
score = round(float(item["score"]), 4)
|
| 109 |
+
emotion_pt = map_emotion(label, score)
|
| 110 |
+
probabilities[emotion_pt] = score
|
| 111 |
|
| 112 |
+
# Identifica a emoção dominante
|
| 113 |
+
dominant_emotion = max(probabilities, key=probabilities.get)
|
| 114 |
+
suggestion = get_suggestion(dominant_emotion)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
|
| 116 |
result = {
|
| 117 |
"status": "ok",
|
| 118 |
+
"emotion": dominant_emotion,
|
| 119 |
+
"emode": list(probabilities.keys()),
|
| 120 |
+
"probabilities": probabilities,
|
| 121 |
+
"suggestion": suggestion,
|
| 122 |
}
|
| 123 |
|
| 124 |
+
# Armazena no Firestore
|
| 125 |
if db:
|
| 126 |
db.collection("emotions").add({
|
| 127 |
"text": text,
|
| 128 |
+
"emotion": dominant_emotion,
|
| 129 |
+
"probabilities": probabilities
|
| 130 |
})
|
| 131 |
|
| 132 |
return jsonify(result)
|
| 133 |
|
| 134 |
except Exception as e:
|
| 135 |
print(f"❌ Erro na rota /analyze: {e}")
|
| 136 |
+
return jsonify({"error": str(e)}), 500
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 137 |
|
| 138 |
+
# =============================
|
| 139 |
+
# Inicialização do servidor
|
| 140 |
+
# =============================
|
| 141 |
if __name__ == "__main__":
|
| 142 |
port = int(os.environ.get("PORT", 7860))
|
| 143 |
app.run(host="0.0.0.0", port=port, debug=False)
|