Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -5,14 +5,19 @@ import os
|
|
| 5 |
|
| 6 |
app = FastAPI()
|
| 7 |
|
| 8 |
-
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
TRANSLATION_MODEL = "Helsinki-NLP/opus-mt-pt-en"
|
| 11 |
EMOTION_MODEL = "j-hartmann/emotion-english-distilroberta-base"
|
| 12 |
|
|
|
|
| 13 |
class TextInput(BaseModel):
|
| 14 |
text: str
|
| 15 |
|
|
|
|
| 16 |
EMOTION_SUGGESTIONS = {
|
| 17 |
"joy": "Ótimo! Continue aproveitando esses momentos positivos!",
|
| 18 |
"anger": "Respire fundo e tente se acalmar antes de reagir.",
|
|
@@ -25,14 +30,19 @@ EMOTION_SUGGESTIONS = {
|
|
| 25 |
}
|
| 26 |
DEFAULT_SUGGESTION = "Tente respirar fundo e escrever seus sentimentos."
|
| 27 |
|
|
|
|
| 28 |
async def query_inference(model: str, payload: dict):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
headers = {"Authorization": f"Bearer {HF_API_KEY}"}
|
| 30 |
try:
|
| 31 |
async with httpx.AsyncClient(timeout=60) as client:
|
| 32 |
response = await client.post(
|
| 33 |
f"https://api-inference.huggingface.co/models/{model}",
|
| 34 |
headers=headers,
|
| 35 |
-
json=payload
|
| 36 |
)
|
| 37 |
if response.status_code != 200:
|
| 38 |
return {"error": f"Erro {response.status_code}: {response.text}"}
|
|
@@ -40,34 +50,47 @@ async def query_inference(model: str, payload: dict):
|
|
| 40 |
except Exception as e:
|
| 41 |
return {"error": f"Falha ao conectar com a Inference API: {str(e)}"}
|
| 42 |
|
|
|
|
| 43 |
async def translate_to_english(text: str) -> str:
|
|
|
|
| 44 |
result = await query_inference(TRANSLATION_MODEL, {"inputs": text})
|
| 45 |
-
if isinstance(result, list) and
|
| 46 |
return result[0]["translation_text"]
|
| 47 |
return text
|
| 48 |
|
|
|
|
| 49 |
async def classify_emotion(text: str) -> dict:
|
|
|
|
| 50 |
result = await query_inference(EMOTION_MODEL, {"inputs": text})
|
| 51 |
|
| 52 |
if isinstance(result, dict) and "error" in result:
|
| 53 |
-
return {
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
|
| 55 |
-
if isinstance(result, list) and
|
| 56 |
top_label = result[0]["label"].lower()
|
| 57 |
suggestion = EMOTION_SUGGESTIONS.get(top_label, DEFAULT_SUGGESTION)
|
| 58 |
return {"emotion": top_label, "suggestion": suggestion, "raw": result}
|
| 59 |
|
| 60 |
return {"emotion": "unknown", "suggestion": "Não foi possível analisar a emoção."}
|
| 61 |
|
|
|
|
| 62 |
@app.post("/analyze")
|
| 63 |
async def analyze_text(input: TextInput):
|
|
|
|
| 64 |
text = input.text.strip()
|
|
|
|
| 65 |
if any(c in text for c in "áéíóúãõâêôçà"):
|
| 66 |
text_en = await translate_to_english(text)
|
| 67 |
else:
|
| 68 |
text_en = text
|
| 69 |
return await classify_emotion(text_en)
|
| 70 |
|
|
|
|
| 71 |
@app.get("/")
|
| 72 |
async def root():
|
|
|
|
| 73 |
return {"status": "ok", "message": "API de análise emocional rodando 🚀"}
|
|
|
|
| 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.",
|
|
|
|
| 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}"}
|
|
|
|
| 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 🚀"}
|