hrlima commited on
Commit
fb59f46
·
verified ·
1 Parent(s): 2674a49

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +67 -90
app.py CHANGED
@@ -1,96 +1,73 @@
1
- from fastapi import FastAPI
2
- from pydantic import BaseModel
3
- import httpx
4
  import os
5
-
6
- app = FastAPI()
7
-
8
- # Garante que a chave existe
9
- HF_API_KEY = os.getenv("HF_API_KEY", "").strip()
10
- if not HF_API_KEY:
11
- print("⚠️ Aviso: Variável HF_API_KEY não configurada. A API pode não funcionar.")
12
-
13
- TRANSLATION_MODEL = "Helsinki-NLP/opus-mt-pt-en"
14
- EMOTION_MODEL = "j-hartmann/emotion-english-distilroberta-base"
15
-
16
-
17
- class TextInput(BaseModel):
18
- text: str
19
-
20
-
21
- EMOTION_SUGGESTIONS = {
22
- "joy": "Ótimo! Continue aproveitando esses momentos positivos!",
23
- "anger": "Respire fundo e tente se acalmar antes de reagir.",
24
- "sadness": "Permita-se sentir, e tente falar ou escrever sobre isso.",
25
- "fear": "Tente identificar o que causa medo e enfrente aos poucos.",
26
- "surprise": "Que surpresa interessante! Observe como se sente.",
27
- "disgust": "Tente refletir sobre o que causou esse sentimento.",
28
- "neutral": "Mantenha-se atento aos seus sentimentos e observe-os.",
29
- "love": "Aproveite esses sentimentos positivos e compartilhe-os!",
30
- }
31
- DEFAULT_SUGGESTION = "Tente respirar fundo e escrever seus sentimentos."
32
-
33
-
34
- async def query_inference(model: str, payload: dict):
35
- """Consulta à HuggingFace Inference API"""
36
- if not HF_API_KEY:
37
- return {"error": "HF_API_KEY não configurada no ambiente"}
38
-
39
- headers = {"Authorization": f"Bearer {HF_API_KEY}"}
 
 
 
 
 
 
 
 
40
  try:
41
- async with httpx.AsyncClient(timeout=60) as client:
42
- response = await client.post(
43
- f"https://api-inference.huggingface.co/models/{model}",
44
- headers=headers,
45
- json=payload,
46
- )
47
- if response.status_code != 200:
48
- return {"error": f"Erro {response.status_code}: {response.text}"}
49
- return response.json()
 
 
 
 
 
 
 
 
 
 
 
50
  except Exception as e:
51
- return {"error": f"Falha ao conectar com a Inference API: {str(e)}"}
52
-
53
-
54
- async def translate_to_english(text: str) -> str:
55
- """Traduz PT -> EN se necessário"""
56
- result = await query_inference(TRANSLATION_MODEL, {"inputs": text})
57
- if isinstance(result, list) and result and "translation_text" in result[0]:
58
- return result[0]["translation_text"]
59
- return text
60
-
61
-
62
- async def classify_emotion(text: str) -> dict:
63
- """Classifica emoção e retorna sugestão"""
64
- result = await query_inference(EMOTION_MODEL, {"inputs": text})
65
-
66
- if isinstance(result, dict) and "error" in result:
67
- return {
68
- "emotion": "unknown",
69
- "suggestion": "Não foi possível analisar a emoção.",
70
- "debug": result,
71
- }
72
-
73
- if isinstance(result, list) and result:
74
- top_label = result[0]["label"].lower()
75
- suggestion = EMOTION_SUGGESTIONS.get(top_label, DEFAULT_SUGGESTION)
76
- return {"emotion": top_label, "suggestion": suggestion, "raw": result}
77
-
78
- return {"emotion": "unknown", "suggestion": "Não foi possível analisar a emoção."}
79
-
80
 
81
- @app.post("/analyze")
82
- async def analyze_text(input: TextInput):
83
- """Endpoint principal de análise"""
84
- text = input.text.strip()
85
- # Heurística simples para decidir se traduz
86
- if any(c in text for c in "áéíóúãõâêôçà"):
87
- text_en = await translate_to_english(text)
88
- else:
89
- text_en = text
90
- return await classify_emotion(text_en)
91
 
 
 
 
92
 
93
- @app.get("/")
94
- async def root():
95
- """Endpoint de saúde"""
96
- return {"status": "ok", "message": "API de análise emocional rodando 🚀"}
 
 
 
 
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