hrlima commited on
Commit
40e3c4e
·
verified ·
1 Parent(s): fb59f46

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -43
app.py CHANGED
@@ -1,73 +1,80 @@
1
  import os
2
- import requests
3
- from flask import Flask, request, jsonify
4
- from flask_cors import CORS
5
  import firebase_admin
6
  from firebase_admin import credentials, firestore
 
7
  from dotenv import load_dotenv
 
8
 
9
- # Carregar variáveis de ambiente
10
  load_dotenv()
11
 
12
  app = Flask(__name__)
13
- CORS(app)
14
 
15
- # -----------------------------
16
- # Firebase Setup
17
- # -----------------------------
18
  if not firebase_admin._apps:
19
- cred = credentials.Certificate("firebase_key.json") # coloque a chave no container
20
- firebase_admin.initialize_app(cred)
 
 
21
 
22
- db = firestore.client()
 
 
 
 
 
 
 
 
23
 
24
- # -----------------------------
25
- # HuggingFace API
26
- # -----------------------------
27
- HF_API_URL = os.getenv("HF_API_URL", "https://api-inference.huggingface.co/models/YOUR_MODEL")
28
- HF_API_KEY = os.getenv("HF_API_KEY")
29
 
30
- headers = {"Authorization": f"Bearer {HF_API_KEY}"}
31
 
 
32
  @app.route("/")
33
- def home():
34
- return jsonify({"status": "ok", "message": "MindVoice API online!"})
35
 
 
36
  @app.route("/analyze", methods=["POST"])
37
  def analyze():
38
- """
39
- Recebe um áudio ou texto e envia para HuggingFace.
40
- Exemplo de payload:
41
- {
42
- "text": "Estou feliz hoje"
43
- }
44
- """
45
  try:
46
  data = request.get_json()
47
- if not data:
48
- return jsonify({"error": "Payload vazio"}), 400
49
 
50
- # Caso seja texto
51
- if "text" in data:
52
- payload = {"inputs": data["text"]}
53
- else:
54
- return jsonify({"error": "Faltando campo 'text'"}), 400
55
 
56
- response = requests.post(HF_API_URL, headers=headers, json=payload, timeout=60)
57
- result = response.json()
 
 
 
58
 
59
- # Salvar no Firestore
60
- db.collection("insights").add({
61
- "text": data["text"],
62
- "result": result,
63
- })
 
 
 
 
 
64
 
65
- return jsonify({"analysis": result})
66
  except Exception as e:
 
67
  return jsonify({"error": str(e)}), 500
68
 
69
 
70
  if __name__ == "__main__":
71
- port = int(os.getenv("PORT", 8080))
72
- app.run(host="0.0.0.0", port=port, debug=True)
 
 
73
 
 
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 dotenv import load_dotenv
7
+ from huggingface_hub import InferenceClient
8
 
9
+ # Carregar variáveis do .env
10
  load_dotenv()
11
 
12
  app = Flask(__name__)
 
13
 
14
+ # === Inicialização segura do Firebase ===
 
 
15
  if not firebase_admin._apps:
16
+ firebase_key = os.getenv("FIREBASE_KEY")
17
+
18
+ if not firebase_key:
19
+ raise RuntimeError("❌ Variável FIREBASE_KEY não encontrada no ambiente.")
20
 
21
+ try:
22
+ cred_dict = json.loads(firebase_key)
23
+ cred = credentials.Certificate(cred_dict)
24
+ firebase_admin.initialize_app(cred)
25
+ db = firestore.client()
26
+ print("✅ Firebase conectado com sucesso.")
27
+ except Exception as e:
28
+ print(f"❌ Erro ao inicializar Firebase: {e}")
29
+ db = None
30
 
31
+ # === Configuração do modelo da Hugging Face ===
32
+ HF_TOKEN = os.getenv("HF_TOKEN")
33
+ if not HF_TOKEN:
34
+ raise RuntimeError(" Variável HF_TOKEN não encontrada no ambiente.")
 
35
 
36
+ client = InferenceClient(token=HF_TOKEN)
37
 
38
+ # === Rota de teste ===
39
  @app.route("/")
40
+ def index():
41
+ return jsonify({"status": "online", "message": "API Flask funcionando!"})
42
 
43
+ # === Rota principal de análise de emoção ===
44
  @app.route("/analyze", methods=["POST"])
45
  def analyze():
 
 
 
 
 
 
 
46
  try:
47
  data = request.get_json()
48
+ if not data or "text" not in data:
49
+ return jsonify({"error": "Campo 'text' é obrigatório"}), 400
50
 
51
+ text = data["text"]
 
 
 
 
52
 
53
+ # Envia texto para Hugging Face
54
+ response = client.text_classification(
55
+ model="SamLowe/roberta-base-go_emotions",
56
+ inputs=text,
57
+ )
58
 
59
+ emotion = response[0]["label"]
60
+ score = round(response[0]["score"], 4)
61
+
62
+ result = {"emotion": emotion, "score": score}
63
+
64
+ # Armazena no Firestore
65
+ if db:
66
+ db.collection("emotions").add(result)
67
+
68
+ return jsonify(result)
69
 
 
70
  except Exception as e:
71
+ print(f"❌ Erro na rota /analyze: {e}")
72
  return jsonify({"error": str(e)}), 500
73
 
74
 
75
  if __name__ == "__main__":
76
+ port = int(os.environ.get("PORT", 8080))
77
+ # Importante: host='0.0.0.0' para acessível no container
78
+ app.run(host="0.0.0.0", port=port, debug=False)
79
+
80