Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,81 +1,120 @@
|
|
| 1 |
import os
|
| 2 |
import json
|
| 3 |
-
import traceback
|
| 4 |
import firebase_admin
|
| 5 |
from firebase_admin import credentials, firestore
|
| 6 |
from flask import Flask, request, jsonify
|
| 7 |
-
import
|
| 8 |
|
|
|
|
| 9 |
app = Flask(__name__)
|
| 10 |
|
|
|
|
| 11 |
try:
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
|
|
|
| 21 |
except Exception as e:
|
| 22 |
print(f"❌ Erro ao inicializar Firebase: {e}")
|
| 23 |
|
|
|
|
| 24 |
HF_TOKEN = os.getenv("HF_TOKEN")
|
|
|
|
| 25 |
if not HF_TOKEN:
|
| 26 |
raise RuntimeError("❌ HF_TOKEN não encontrado nos Secrets do Space.")
|
| 27 |
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
@app.route("/analyze", methods=["POST"])
|
| 32 |
def analyze():
|
| 33 |
try:
|
| 34 |
data = request.get_json()
|
| 35 |
if not data or "text" not in data:
|
| 36 |
-
return jsonify({"error": "Campo 'text'
|
| 37 |
|
| 38 |
text = data["text"]
|
| 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 |
-
suggestion = suggestions.get(emotion, "Sem sugestão disponível.")
|
| 68 |
-
|
| 69 |
-
return jsonify({
|
| 70 |
-
"status": "ok",
|
| 71 |
-
"emotion": emotion,
|
| 72 |
-
"emode": [emotion],
|
| 73 |
-
"suggestion": suggestion
|
| 74 |
-
})
|
| 75 |
|
| 76 |
except Exception as e:
|
| 77 |
-
|
| 78 |
-
return jsonify({"status": "fallback", "error": str(e)}), 500
|
| 79 |
|
|
|
|
| 80 |
if __name__ == "__main__":
|
| 81 |
app.run(host="0.0.0.0", port=7860)
|
|
|
|
| 1 |
import os
|
| 2 |
import json
|
|
|
|
| 3 |
import firebase_admin
|
| 4 |
from firebase_admin import credentials, firestore
|
| 5 |
from flask import Flask, request, jsonify
|
| 6 |
+
from huggingface_hub import InferenceClient
|
| 7 |
|
| 8 |
+
# Inicialização do Flask
|
| 9 |
app = Flask(__name__)
|
| 10 |
|
| 11 |
+
# ====== CONFIGURAÇÃO FIREBASE ======
|
| 12 |
try:
|
| 13 |
+
firebase_key = os.getenv("FIREBASE_KEY")
|
| 14 |
+
|
| 15 |
+
if firebase_key:
|
| 16 |
+
cred_dict = json.loads(firebase_key)
|
| 17 |
+
cred = credentials.Certificate(cred_dict)
|
| 18 |
+
firebase_admin.initialize_app(cred)
|
| 19 |
+
db = firestore.client()
|
| 20 |
+
print("✅ Firebase conectado com sucesso.")
|
| 21 |
+
else:
|
| 22 |
+
print("⚠️ FIREBASE_KEY não encontrada nos secrets do Space.")
|
| 23 |
except Exception as e:
|
| 24 |
print(f"❌ Erro ao inicializar Firebase: {e}")
|
| 25 |
|
| 26 |
+
# ====== CONFIGURAÇÃO HUGGING FACE ======
|
| 27 |
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 28 |
+
|
| 29 |
if not HF_TOKEN:
|
| 30 |
raise RuntimeError("❌ HF_TOKEN não encontrado nos Secrets do Space.")
|
| 31 |
|
| 32 |
+
client = InferenceClient(token=HF_TOKEN)
|
| 33 |
+
|
| 34 |
+
# ====== MAPEAMENTO DE EMOÇÕES SUPORTADAS ======
|
| 35 |
+
emotion_map = {
|
| 36 |
+
"tristeza": ["triste", "desanimado", "desmotivado", "abatido", "deprimido"],
|
| 37 |
+
"ansiedade": ["ansioso", "preocupado", "tenso", "nervoso", "agitado"],
|
| 38 |
+
"insegurança": ["inseguro", "incerto", "duvidoso", "receoso", "medo"],
|
| 39 |
+
"raiva": ["irritado", "zangado", "revoltado", "bravo", "raiva"],
|
| 40 |
+
"alegria": ["feliz", "contente", "animado", "satisfeito", "positivo"]
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
# ====== FUNÇÃO DE FALLBACK LOCAL ======
|
| 44 |
+
def fallback_emotion(text):
|
| 45 |
+
text_lower = text.lower()
|
| 46 |
+
for emotion, keywords in emotion_map.items():
|
| 47 |
+
for word in keywords:
|
| 48 |
+
if word in text_lower:
|
| 49 |
+
return {
|
| 50 |
+
"status": "fallback",
|
| 51 |
+
"emotion": emotion,
|
| 52 |
+
"emode": [emotion],
|
| 53 |
+
"suggestion": gerar_sugestao(emotion)
|
| 54 |
+
}
|
| 55 |
+
return {
|
| 56 |
+
"status": "fallback",
|
| 57 |
+
"emotion": "desconhecido",
|
| 58 |
+
"emode": ["desconhecido"],
|
| 59 |
+
"suggestion": "Emoção não identificada com precisão."
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
# ====== GERAR SUGESTÃO CONFORME EMOÇÃO ======
|
| 63 |
+
def gerar_sugestao(emotion):
|
| 64 |
+
sugestoes = {
|
| 65 |
+
"tristeza": "Procure fazer algo que te acalme e traga conforto emocional.",
|
| 66 |
+
"ansiedade": "Respire fundo e faça pausas para relaxar. Técnicas de respiração podem ajudar.",
|
| 67 |
+
"insegurança": "Acredite no seu valor. Lembre-se das suas conquistas.",
|
| 68 |
+
"raiva": "Afaste-se um pouco da situação e respire antes de reagir.",
|
| 69 |
+
"alegria": "Continue aproveitando esse momento positivo e compartilhe com os outros!",
|
| 70 |
+
"desconhecido": "Emoção não identificada com precisão."
|
| 71 |
+
}
|
| 72 |
+
return sugestoes.get(emotion, "Mantenha o equilíbrio emocional e cuide de você mesmo.")
|
| 73 |
+
|
| 74 |
+
# ====== ROTA PRINCIPAL DE TESTE ======
|
| 75 |
+
@app.route("/")
|
| 76 |
+
def home():
|
| 77 |
+
return jsonify({"message": "API Flask funcionando no Space!", "status": "online"})
|
| 78 |
+
|
| 79 |
+
# ====== ROTA DE ANÁLISE ======
|
| 80 |
@app.route("/analyze", methods=["POST"])
|
| 81 |
def analyze():
|
| 82 |
try:
|
| 83 |
data = request.get_json()
|
| 84 |
if not data or "text" not in data:
|
| 85 |
+
return jsonify({"error": "Campo 'text' é obrigatório."}), 400
|
| 86 |
|
| 87 |
text = data["text"]
|
| 88 |
+
|
| 89 |
+
# Tenta IA do Hugging Face
|
| 90 |
+
try:
|
| 91 |
+
result = client.text_classification(text)
|
| 92 |
+
if result and isinstance(result, list) and len(result) > 0:
|
| 93 |
+
label = result[0].get("label", "").lower()
|
| 94 |
+
|
| 95 |
+
# Mapeamento IA → emoções suportadas
|
| 96 |
+
if label in emotion_map.keys():
|
| 97 |
+
emotion = label
|
| 98 |
+
else:
|
| 99 |
+
emotion = "desconhecido"
|
| 100 |
+
|
| 101 |
+
return jsonify({
|
| 102 |
+
"status": "ok",
|
| 103 |
+
"emotion": emotion,
|
| 104 |
+
"emode": [emotion],
|
| 105 |
+
"suggestion": gerar_sugestao(emotion)
|
| 106 |
+
})
|
| 107 |
+
else:
|
| 108 |
+
# Fallback local
|
| 109 |
+
return jsonify(fallback_emotion(text))
|
| 110 |
+
|
| 111 |
+
except Exception as e:
|
| 112 |
+
print(f"⚠️ Erro na IA principal: {e}")
|
| 113 |
+
return jsonify(fallback_emotion(text))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
|
| 115 |
except Exception as e:
|
| 116 |
+
return jsonify({"error": str(e)}), 500
|
|
|
|
| 117 |
|
| 118 |
+
# ====== EXECUÇÃO LOCAL (porta 7860) ======
|
| 119 |
if __name__ == "__main__":
|
| 120 |
app.run(host="0.0.0.0", port=7860)
|