Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -15,7 +15,6 @@ if not firebase_key:
|
|
| 15 |
raise RuntimeError("❌ FIREBASE_KEY não encontrado nos Secrets do Space.")
|
| 16 |
|
| 17 |
try:
|
| 18 |
-
# Garante que o JSON da chave seja carregado corretamente
|
| 19 |
cred_dict = json.loads(firebase_key)
|
| 20 |
cred = credentials.Certificate(cred_dict)
|
| 21 |
if not firebase_admin._apps:
|
|
@@ -35,49 +34,113 @@ if not HF_TOKEN:
|
|
| 35 |
|
| 36 |
client = InferenceClient(token=HF_TOKEN)
|
| 37 |
|
| 38 |
-
#
|
| 39 |
-
|
| 40 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
@app.route("/")
|
| 42 |
def index():
|
| 43 |
-
return jsonify({"status": "online", "message": "API Flask funcionando
|
| 44 |
|
| 45 |
# =============================
|
| 46 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
# =============================
|
| 48 |
@app.route("/analyze", methods=["POST"])
|
| 49 |
def analyze():
|
| 50 |
try:
|
| 51 |
data = request.get_json()
|
| 52 |
if not data or "text" not in data:
|
| 53 |
-
return jsonify({"error": "Campo 'text' é obrigatório"}), 400
|
| 54 |
|
| 55 |
text = data["text"]
|
| 56 |
|
| 57 |
-
#
|
| 58 |
response = client.text_classification(
|
| 59 |
text,
|
| 60 |
model="SamLowe/roberta-base-go_emotions"
|
| 61 |
)
|
| 62 |
|
| 63 |
-
|
| 64 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
|
| 66 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
|
| 68 |
# Armazena no Firestore
|
| 69 |
if db:
|
| 70 |
-
db.collection("emotions").add(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
|
| 72 |
return jsonify(result)
|
| 73 |
|
| 74 |
except Exception as e:
|
| 75 |
print(f"❌ Erro na rota /analyze: {e}")
|
| 76 |
-
return jsonify({
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
|
| 78 |
-
# =============================
|
| 79 |
-
# Inicialização do servidor
|
| 80 |
-
# =============================
|
| 81 |
if __name__ == "__main__":
|
| 82 |
port = int(os.environ.get("PORT", 7860))
|
| 83 |
app.run(host="0.0.0.0", port=port, debug=False)
|
|
|
|
|
|
| 15 |
raise RuntimeError("❌ FIREBASE_KEY não encontrado nos Secrets do Space.")
|
| 16 |
|
| 17 |
try:
|
|
|
|
| 18 |
cred_dict = json.loads(firebase_key)
|
| 19 |
cred = credentials.Certificate(cred_dict)
|
| 20 |
if not firebase_admin._apps:
|
|
|
|
| 34 |
|
| 35 |
client = InferenceClient(token=HF_TOKEN)
|
| 36 |
|
| 37 |
+
# Mapeamento de emoções em português
|
| 38 |
+
EMOTION_MAP = {
|
| 39 |
+
"joy": "alegria",
|
| 40 |
+
"sadness": "tristeza",
|
| 41 |
+
"anger": "raiva",
|
| 42 |
+
"fear": "medo",
|
| 43 |
+
"surprise": "surpresa",
|
| 44 |
+
"disgust": "desgosto",
|
| 45 |
+
"neutral": "neutro",
|
| 46 |
+
"depression": "depressão" # nova emoção
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
# Sugestões simples conforme emoção
|
| 50 |
+
SUGESTOES = {
|
| 51 |
+
"alegria": "Continue fazendo o que te faz bem!",
|
| 52 |
+
"tristeza": "Tente conversar com alguém de confiança.",
|
| 53 |
+
"raiva": "Respire fundo e dê um tempo antes de reagir.",
|
| 54 |
+
"medo": "Procure entender a origem do seu medo.",
|
| 55 |
+
"surpresa": "Nem tudo é previsível — abrace o inesperado.",
|
| 56 |
+
"desgosto": "Tente mudar o foco e procurar algo positivo.",
|
| 57 |
+
"depressão": "Considere buscar apoio emocional ou psicológico.",
|
| 58 |
+
"neutro": "Você parece equilibrado no momento."
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
@app.route("/")
|
| 62 |
def index():
|
| 63 |
+
return jsonify({"status": "online", "message": "API Flask funcionando!"})
|
| 64 |
|
| 65 |
# =============================
|
| 66 |
+
# Função de normalização
|
| 67 |
+
# =============================
|
| 68 |
+
def normalizar_probabilidades(results):
|
| 69 |
+
total = sum([r["score"] for r in results])
|
| 70 |
+
if total == 0:
|
| 71 |
+
return results
|
| 72 |
+
for r in results:
|
| 73 |
+
r["score"] = r["score"] / total
|
| 74 |
+
return results
|
| 75 |
+
|
| 76 |
+
# =============================
|
| 77 |
+
# Rota principal /analyze
|
| 78 |
# =============================
|
| 79 |
@app.route("/analyze", methods=["POST"])
|
| 80 |
def analyze():
|
| 81 |
try:
|
| 82 |
data = request.get_json()
|
| 83 |
if not data or "text" not in data:
|
| 84 |
+
return jsonify({"status": "error", "error": "Campo 'text' é obrigatório"}), 400
|
| 85 |
|
| 86 |
text = data["text"]
|
| 87 |
|
| 88 |
+
# Chama modelo HF
|
| 89 |
response = client.text_classification(
|
| 90 |
text,
|
| 91 |
model="SamLowe/roberta-base-go_emotions"
|
| 92 |
)
|
| 93 |
|
| 94 |
+
# Normaliza scores
|
| 95 |
+
results = normalizar_probabilidades(response)
|
| 96 |
+
|
| 97 |
+
# Monta dicionário de probabilidades traduzidas
|
| 98 |
+
probabilidades = {}
|
| 99 |
+
for item in results:
|
| 100 |
+
label = item["label"].lower()
|
| 101 |
+
score = round(item["score"], 4)
|
| 102 |
|
| 103 |
+
# Regra adicional para identificar "depressão"
|
| 104 |
+
if label in ["sadness", "grief", "hopelessness"]:
|
| 105 |
+
label = "depression"
|
| 106 |
+
|
| 107 |
+
label_pt = EMOTION_MAP.get(label, "neutro")
|
| 108 |
+
probabilidades[label_pt] = score
|
| 109 |
+
|
| 110 |
+
# Define emoção principal
|
| 111 |
+
principal = max(probabilidades, key=probabilidades.get)
|
| 112 |
+
sugestao = SUGESTOES.get(principal, "Mantenha o equilíbrio emocional.")
|
| 113 |
+
|
| 114 |
+
result = {
|
| 115 |
+
"status": "ok",
|
| 116 |
+
"emotion": principal,
|
| 117 |
+
"emode": [principal],
|
| 118 |
+
"probabilities": probabilidades,
|
| 119 |
+
"suggestion": sugestao
|
| 120 |
+
}
|
| 121 |
|
| 122 |
# Armazena no Firestore
|
| 123 |
if db:
|
| 124 |
+
db.collection("emotions").add({
|
| 125 |
+
"text": text,
|
| 126 |
+
"emotion": principal,
|
| 127 |
+
"probabilities": probabilidades
|
| 128 |
+
})
|
| 129 |
|
| 130 |
return jsonify(result)
|
| 131 |
|
| 132 |
except Exception as e:
|
| 133 |
print(f"❌ Erro na rota /analyze: {e}")
|
| 134 |
+
return jsonify({
|
| 135 |
+
"status": "fallback",
|
| 136 |
+
"emotion": "neutro",
|
| 137 |
+
"emode": ["neutro"],
|
| 138 |
+
"suggestion": "Não foi possível usar a API. Fallback ativado.",
|
| 139 |
+
"debug": str(e)
|
| 140 |
+
}), 500
|
| 141 |
+
|
| 142 |
|
|
|
|
|
|
|
|
|
|
| 143 |
if __name__ == "__main__":
|
| 144 |
port = int(os.environ.get("PORT", 7860))
|
| 145 |
app.run(host="0.0.0.0", port=port, debug=False)
|
| 146 |
+
|