Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -32,20 +32,23 @@ DEFAULT_SUGGESTION = "Tente respirar fundo e escrever seus sentimentos."
|
|
| 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 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
|
|
|
|
|
|
|
|
|
| 44 |
|
| 45 |
# Tradução (PT → EN)
|
| 46 |
async def translate_to_english(text: str) -> str:
|
| 47 |
result = await query_inference(TRANSLATION_MODEL, {"inputs": text})
|
| 48 |
-
if isinstance(result, list) and "translation_text" in result[0]:
|
| 49 |
return result[0]["translation_text"]
|
| 50 |
return text
|
| 51 |
|
|
@@ -54,12 +57,12 @@ async def classify_emotion(text: str) -> dict:
|
|
| 54 |
result = await query_inference(EMOTION_MODEL, {"inputs": text})
|
| 55 |
|
| 56 |
if isinstance(result, dict) and "error" in result:
|
| 57 |
-
return {"emotion": "unknown", "suggestion": "Não foi possível analisar a emoção."}
|
| 58 |
|
| 59 |
if isinstance(result, list) and len(result) > 0:
|
| 60 |
top_label = result[0]["label"].lower()
|
| 61 |
suggestion = EMOTION_SUGGESTIONS.get(top_label, DEFAULT_SUGGESTION)
|
| 62 |
-
return {"emotion": top_label, "suggestion": suggestion}
|
| 63 |
|
| 64 |
return {"emotion": "unknown", "suggestion": "Não foi possível analisar a emoção."}
|
| 65 |
|
|
@@ -67,10 +70,13 @@ async def classify_emotion(text: str) -> dict:
|
|
| 67 |
@app.post("/analyze")
|
| 68 |
async def analyze_text(input: TextInput):
|
| 69 |
text = input.text.strip()
|
|
|
|
|
|
|
| 70 |
if any(c in text for c in "áéíóúãõâêôçà"):
|
| 71 |
text_en = await translate_to_english(text)
|
| 72 |
else:
|
| 73 |
text_en = text
|
|
|
|
| 74 |
return await classify_emotion(text_en)
|
| 75 |
|
| 76 |
# Endpoint simples para verificar se está rodando
|
|
@@ -79,4 +85,4 @@ async def root():
|
|
| 79 |
return {"status": "ok", "message": "API de análise emocional rodando 🚀"}
|
| 80 |
|
| 81 |
if __name__ == "__main__":
|
| 82 |
-
uvicorn.run("app:app", host="0.0.0.0", port=7860)
|
|
|
|
| 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(
|
| 38 |
+
f"https://api-inference.huggingface.co/models/{model}",
|
| 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)
|
| 49 |
async def translate_to_english(text: str) -> str:
|
| 50 |
result = await query_inference(TRANSLATION_MODEL, {"inputs": text})
|
| 51 |
+
if isinstance(result, list) and len(result) > 0 and "translation_text" in result[0]:
|
| 52 |
return result[0]["translation_text"]
|
| 53 |
return text
|
| 54 |
|
|
|
|
| 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 |
|
|
|
|
| 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
|
|
|
|
| 85 |
return {"status": "ok", "message": "API de análise emocional rodando 🚀"}
|
| 86 |
|
| 87 |
if __name__ == "__main__":
|
| 88 |
+
uvicorn.run("app:app", host="0.0.0.0", port=7860)
|