hrlima commited on
Commit
017fb9a
·
verified ·
1 Parent(s): 87261ee

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +14 -22
app.py CHANGED
@@ -6,8 +6,8 @@ import os
6
 
7
  app = FastAPI()
8
 
9
- # Pegamos o token da variável de ambiente do Space
10
- HF_API_KEY = os.getenv("HF_API_KEY")
11
 
12
  # Modelos públicos via Inference API
13
  TRANSLATION_MODEL = "Helsinki-NLP/opus-mt-pt-en"
@@ -16,7 +16,6 @@ EMOTION_MODEL = "j-hartmann/emotion-english-distilroberta-base"
16
  class TextInput(BaseModel):
17
  text: str
18
 
19
- # Sugestões de resposta
20
  EMOTION_SUGGESTIONS = {
21
  "joy": "Ótimo! Continue aproveitando esses momentos positivos!",
22
  "anger": "Respire fundo e tente se acalmar antes de reagir.",
@@ -29,9 +28,10 @@ EMOTION_SUGGESTIONS = {
29
  }
30
  DEFAULT_SUGGESTION = "Tente respirar fundo e escrever seus sentimentos."
31
 
32
- # Chamada segura à API do Hugging Face
33
  async def query_inference(model: str, payload: dict):
34
  headers = {"Authorization": f"Bearer {HF_API_KEY}"}
 
35
  try:
36
  async with httpx.AsyncClient(timeout=60) as client:
37
  response = await client.post(
@@ -39,10 +39,13 @@ async def query_inference(model: str, payload: dict):
39
  headers=headers,
40
  json=payload
41
  )
 
 
42
  if response.status_code != 200:
43
  return {"error": f"Erro {response.status_code}: {response.text}"}
44
  return response.json()
45
  except Exception as e:
 
46
  return {"error": f"Falha ao conectar com a Inference API: {str(e)}"}
47
 
48
  # Tradução (PT → EN)
@@ -55,38 +58,27 @@ async def translate_to_english(text: str) -> str:
55
  # Classificação de emoção
56
  async def classify_emotion(text: str) -> dict:
57
  result = await query_inference(EMOTION_MODEL, {"inputs": text})
58
-
59
  if isinstance(result, dict) and "error" in result:
60
  return {"emotion": "unknown", "suggestion": "Não foi possível analisar a emoção.", "debug": result}
61
-
62
  if isinstance(result, list) and len(result) > 0:
63
  top_label = result[0]["label"].lower()
64
  suggestion = EMOTION_SUGGESTIONS.get(top_label, DEFAULT_SUGGESTION)
65
  return {"emotion": top_label, "suggestion": suggestion, "raw": result}
66
-
67
  return {"emotion": "unknown", "suggestion": "Não foi possível analisar a emoção."}
68
 
69
- # Endpoint para o Flutter
70
  @app.post("/analyze")
71
  async def analyze_text(input: TextInput):
72
  text = input.text.strip()
 
 
 
 
 
73
 
74
- # Se tiver acentos, traduz para inglês antes
75
- if any(c in text for c in "áéíóúãõâêôçà"):
76
- text_en = await translate_to_english(text)
77
- else:
78
- text_en = text
79
-
80
- return await classify_emotion(text_en)
81
-
82
- # Endpoint simples para verificar se está rodando
83
  @app.get("/")
84
  async def root():
85
  return {"status": "ok", "message": "API de análise emocional rodando 🚀"}
86
- print("Payload enviado:", payload)
87
- print("Status code:", response.status_code)
88
- print("Response:", response.text)
89
-
90
 
91
  if __name__ == "__main__":
92
- uvicorn.run("app:app", host="0.0.0.0", port=7860)
 
 
6
 
7
  app = FastAPI()
8
 
9
+ # Token da variável de ambiente do Space
10
+ HF_API_KEY = os.getenv("HF_API_KEY", "SEU_TOKEN_AQUI")
11
 
12
  # Modelos públicos via Inference API
13
  TRANSLATION_MODEL = "Helsinki-NLP/opus-mt-pt-en"
 
16
  class TextInput(BaseModel):
17
  text: str
18
 
 
19
  EMOTION_SUGGESTIONS = {
20
  "joy": "Ótimo! Continue aproveitando esses momentos positivos!",
21
  "anger": "Respire fundo e tente se acalmar antes de reagir.",
 
28
  }
29
  DEFAULT_SUGGESTION = "Tente respirar fundo e escrever seus sentimentos."
30
 
31
+ # Função de requisição à Hugging Face com logs detalhados
32
  async def query_inference(model: str, payload: dict):
33
  headers = {"Authorization": f"Bearer {HF_API_KEY}"}
34
+ print(f"\n=== REQUISIÇÃO INFERENCE ===\nModelo: {model}\nPayload: {payload}\n")
35
  try:
36
  async with httpx.AsyncClient(timeout=60) as client:
37
  response = await client.post(
 
39
  headers=headers,
40
  json=payload
41
  )
42
+ print(f"Status code: {response.status_code}")
43
+ print(f"Response: {response.text}\n")
44
  if response.status_code != 200:
45
  return {"error": f"Erro {response.status_code}: {response.text}"}
46
  return response.json()
47
  except Exception as e:
48
+ print(f"ERRO na chamada HTTP: {str(e)}\n")
49
  return {"error": f"Falha ao conectar com a Inference API: {str(e)}"}
50
 
51
  # Tradução (PT → EN)
 
58
  # Classificação de emoção
59
  async def classify_emotion(text: str) -> dict:
60
  result = await query_inference(EMOTION_MODEL, {"inputs": text})
 
61
  if isinstance(result, dict) and "error" in result:
62
  return {"emotion": "unknown", "suggestion": "Não foi possível analisar a emoção.", "debug": result}
 
63
  if isinstance(result, list) and len(result) > 0:
64
  top_label = result[0]["label"].lower()
65
  suggestion = EMOTION_SUGGESTIONS.get(top_label, DEFAULT_SUGGESTION)
66
  return {"emotion": top_label, "suggestion": suggestion, "raw": result}
 
67
  return {"emotion": "unknown", "suggestion": "Não foi possível analisar a emoção."}
68
 
 
69
  @app.post("/analyze")
70
  async def analyze_text(input: TextInput):
71
  text = input.text.strip()
72
+ # Detecta acentos para tradução automática
73
+ text_en = await translate_to_english(text) if any(c in text for c in "áéíóúãõâêôçà") else text
74
+ result = await classify_emotion(text_en)
75
+ print(f"=== RESULTADO FINAL ===\nInput: {text}\nTexto para IA: {text_en}\nResultado: {result}\n")
76
+ return result
77
 
 
 
 
 
 
 
 
 
 
78
  @app.get("/")
79
  async def root():
80
  return {"status": "ok", "message": "API de análise emocional rodando 🚀"}
 
 
 
 
81
 
82
  if __name__ == "__main__":
83
+ uvicorn.run("app:app", host="0.0.0.0", port=7860, log_level="info")
84
+