Spaces:
Paused
Paused
Update main.py
Browse files
main.py
CHANGED
|
@@ -24,14 +24,8 @@ logger = logging.getLogger(__name__)
|
|
| 24 |
FLOW_API_URL = os.getenv("FLOW_API_URL")
|
| 25 |
if FLOW_API_URL is None:
|
| 26 |
raise RuntimeError("❌ FLOW_API_URL no está definido. Agregalo en los Secrets de Hugging Face.")
|
| 27 |
-
logger.info(f"✅ FLOW_API_URL configurado: {FLOW_API_URL[:30]}...")
|
| 28 |
|
| 29 |
-
|
| 30 |
-
# CARGA DEL LANGFLOW_API_KEY DESDE SECRETS
|
| 31 |
-
# -------------------------------
|
| 32 |
-
LANGFLOW_API_KEY = os.getenv("LANGFLOW_API_KEY")
|
| 33 |
-
if LANGFLOW_API_KEY is None:
|
| 34 |
-
raise RuntimeError("❌ LANGFLOW_API_KEY no está definido. Agregalo en los Secrets de Hugging Face.")
|
| 35 |
|
| 36 |
# -------------------------------
|
| 37 |
# INICIALIZACIÓN DE LA APP
|
|
@@ -63,9 +57,12 @@ async def serve_logo():
|
|
| 63 |
logo_path = "static/te.png"
|
| 64 |
if os.path.exists(logo_path):
|
| 65 |
return FileResponse(logo_path)
|
| 66 |
-
|
|
|
|
|
|
|
| 67 |
<circle cx="20" cy="20" r="18" fill="#f6ae2d"/>
|
| 68 |
-
|
|
|
|
| 69 |
<path d="M -12 0 Q -6 -6 0 -6 Q 6 -6 12 0 Q 6 6 0 6 Q -6 6 -12 0" fill="#420909" stroke="none"/>
|
| 70 |
<circle cx="0" cy="0" r="5" fill="#f6ae2d"/>
|
| 71 |
<circle cx="0" cy="0" r="3" fill="#420909"/>
|
|
@@ -74,11 +71,11 @@ async def serve_logo():
|
|
| 74 |
<text x="20" y="35" font-family="Arial, sans-serif" font-size="8" font-weight="bold"
|
| 75 |
text-anchor="middle" fill="#420909">TE</text>
|
| 76 |
</svg>'''
|
| 77 |
-
|
| 78 |
-
|
| 79 |
|
| 80 |
# -------------------------------
|
| 81 |
-
# MODELO DE ENTRADA/SALIDA
|
| 82 |
# -------------------------------
|
| 83 |
class AnalyzeRequest(BaseModel):
|
| 84 |
url: str
|
|
@@ -94,19 +91,20 @@ class AnalyzeResponse(BaseModel):
|
|
| 94 |
@app.post("/analyze", response_model=AnalyzeResponse)
|
| 95 |
async def analyze(request: AnalyzeRequest):
|
| 96 |
logger.info(f"📥 Recibida solicitud de análisis para URL: {request.url}")
|
| 97 |
-
payload = {
|
| 98 |
-
"input_value": request.url,
|
| 99 |
-
"output_type": "chat",
|
| 100 |
-
"input_type": "chat",
|
| 101 |
-
"tweaks": {}
|
| 102 |
-
}
|
| 103 |
-
headers = {
|
| 104 |
-
"Content-Type": "application/json",
|
| 105 |
-
"User-Agent": "TrueEye-HuggingFace-Space/1.0",
|
| 106 |
-
"x-api-key": LANGFLOW_API_KEY
|
| 107 |
-
}
|
| 108 |
try:
|
| 109 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
response = requests.post(
|
| 111 |
FLOW_API_URL,
|
| 112 |
json=payload,
|
|
@@ -115,9 +113,11 @@ async def analyze(request: AnalyzeRequest):
|
|
| 115 |
)
|
| 116 |
logger.info(f"📨 Respuesta recibida. Status: {response.status_code}")
|
| 117 |
response.raise_for_status()
|
|
|
|
| 118 |
data = response.json()
|
|
|
|
| 119 |
|
| 120 |
-
#
|
| 121 |
result_text = None
|
| 122 |
if isinstance(data, dict) and "result" in data:
|
| 123 |
result_text = data["result"]
|
|
@@ -125,16 +125,13 @@ async def analyze(request: AnalyzeRequest):
|
|
| 125 |
outputs = data["outputs"]
|
| 126 |
if outputs and isinstance(outputs, list):
|
| 127 |
for node in outputs[0].get("outputs", []):
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
result_text = msg.get("text",
|
| 131 |
-
else:
|
| 132 |
-
result_text = str(msg)
|
| 133 |
-
if result_text:
|
| 134 |
break
|
| 135 |
if not result_text:
|
| 136 |
result_text = _extract_text_from_response(data) or \
|
| 137 |
-
|
| 138 |
|
| 139 |
logger.info("✅ Análisis completado exitosamente")
|
| 140 |
return AnalyzeResponse(result=result_text)
|
|
@@ -142,50 +139,54 @@ async def analyze(request: AnalyzeRequest):
|
|
| 142 |
except requests.exceptions.Timeout:
|
| 143 |
logger.error("⏱️ Timeout en la petición a Langflow")
|
| 144 |
return AnalyzeResponse(
|
| 145 |
-
result="❌ Error:
|
| 146 |
-
success=False,
|
|
|
|
| 147 |
)
|
|
|
|
| 148 |
except requests.exceptions.ConnectionError as e:
|
| 149 |
logger.error(f"🔌 Error de conexión: {e}")
|
| 150 |
return AnalyzeResponse(
|
| 151 |
-
result="❌ Error: No se pudo conectar
|
| 152 |
-
success=False,
|
|
|
|
| 153 |
)
|
|
|
|
| 154 |
except requests.exceptions.HTTPError as e:
|
| 155 |
-
|
|
|
|
|
|
|
|
|
|
| 156 |
return AnalyzeResponse(
|
| 157 |
-
result=f"❌ Error del servidor
|
| 158 |
-
success=False,
|
|
|
|
| 159 |
)
|
|
|
|
| 160 |
except Exception as e:
|
| 161 |
logger.exception(f"💥 Error inesperado: {e}")
|
| 162 |
return AnalyzeResponse(
|
| 163 |
-
result=f"❌ Error inesperado: {e}",
|
| 164 |
-
success=False,
|
|
|
|
| 165 |
)
|
| 166 |
|
| 167 |
def _extract_text_from_response(data):
|
| 168 |
if isinstance(data, str):
|
| 169 |
return data
|
| 170 |
if isinstance(data, dict):
|
| 171 |
-
for key in ['text','message','result','output','content']:
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
return r
|
| 179 |
-
for v in data.values():
|
| 180 |
-
if isinstance(v, (dict, list)):
|
| 181 |
-
r = _extract_text_from_response(v)
|
| 182 |
-
if r:
|
| 183 |
-
return r
|
| 184 |
if isinstance(data, list):
|
| 185 |
for item in data:
|
| 186 |
-
|
| 187 |
-
if
|
| 188 |
-
return
|
| 189 |
return None
|
| 190 |
|
| 191 |
# -------------------------------
|
|
|
|
| 24 |
FLOW_API_URL = os.getenv("FLOW_API_URL")
|
| 25 |
if FLOW_API_URL is None:
|
| 26 |
raise RuntimeError("❌ FLOW_API_URL no está definido. Agregalo en los Secrets de Hugging Face.")
|
|
|
|
| 27 |
|
| 28 |
+
logger.info(f"✅ FLOW_API_URL configurado: {FLOW_API_URL[:30]}...")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
# -------------------------------
|
| 31 |
# INICIALIZACIÓN DE LA APP
|
|
|
|
| 57 |
logo_path = "static/te.png"
|
| 58 |
if os.path.exists(logo_path):
|
| 59 |
return FileResponse(logo_path)
|
| 60 |
+
else:
|
| 61 |
+
svg_content = '''<svg width="40" height="40" viewBox="0 0 40 40" xmlns="http://www.w3.org/2000/svg">
|
| 62 |
+
<!-- Fondo circular -->
|
| 63 |
<circle cx="20" cy="20" r="18" fill="#f6ae2d"/>
|
| 64 |
+
<!-- Ojo estilizado -->
|
| 65 |
+
<g transform="translate(20, 20)">
|
| 66 |
<path d="M -12 0 Q -6 -6 0 -6 Q 6 -6 12 0 Q 6 6 0 6 Q -6 6 -12 0" fill="#420909" stroke="none"/>
|
| 67 |
<circle cx="0" cy="0" r="5" fill="#f6ae2d"/>
|
| 68 |
<circle cx="0" cy="0" r="3" fill="#420909"/>
|
|
|
|
| 71 |
<text x="20" y="35" font-family="Arial, sans-serif" font-size="8" font-weight="bold"
|
| 72 |
text-anchor="middle" fill="#420909">TE</text>
|
| 73 |
</svg>'''
|
| 74 |
+
return Response(content=svg_content, media_type="image/svg+xml",
|
| 75 |
+
headers={"Cache-Control": "public, max-age=3600"})
|
| 76 |
|
| 77 |
# -------------------------------
|
| 78 |
+
# MODELO DE ENTRADA / SALIDA
|
| 79 |
# -------------------------------
|
| 80 |
class AnalyzeRequest(BaseModel):
|
| 81 |
url: str
|
|
|
|
| 91 |
@app.post("/analyze", response_model=AnalyzeResponse)
|
| 92 |
async def analyze(request: AnalyzeRequest):
|
| 93 |
logger.info(f"📥 Recibida solicitud de análisis para URL: {request.url}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
try:
|
| 95 |
+
payload = {
|
| 96 |
+
"input_value": request.url,
|
| 97 |
+
"output_type": "chat",
|
| 98 |
+
"input_type": "chat",
|
| 99 |
+
"tweaks": {}
|
| 100 |
+
}
|
| 101 |
+
headers = {
|
| 102 |
+
"Content-Type": "application/json",
|
| 103 |
+
"User-Agent": "TrueEye-HuggingFace-Space/1.0"
|
| 104 |
+
}
|
| 105 |
+
logger.info("📤 Enviando petición a Langflow...")
|
| 106 |
+
logger.debug(f"Payload: {payload}")
|
| 107 |
+
|
| 108 |
response = requests.post(
|
| 109 |
FLOW_API_URL,
|
| 110 |
json=payload,
|
|
|
|
| 113 |
)
|
| 114 |
logger.info(f"📨 Respuesta recibida. Status: {response.status_code}")
|
| 115 |
response.raise_for_status()
|
| 116 |
+
|
| 117 |
data = response.json()
|
| 118 |
+
logger.debug(f"Respuesta JSON: {data}")
|
| 119 |
|
| 120 |
+
# Extracción de texto
|
| 121 |
result_text = None
|
| 122 |
if isinstance(data, dict) and "result" in data:
|
| 123 |
result_text = data["result"]
|
|
|
|
| 125 |
outputs = data["outputs"]
|
| 126 |
if outputs and isinstance(outputs, list):
|
| 127 |
for node in outputs[0].get("outputs", []):
|
| 128 |
+
if "message" in node:
|
| 129 |
+
msg = node["message"]
|
| 130 |
+
result_text = msg.get("text") if isinstance(msg, dict) else str(msg)
|
|
|
|
|
|
|
|
|
|
| 131 |
break
|
| 132 |
if not result_text:
|
| 133 |
result_text = _extract_text_from_response(data) or \
|
| 134 |
+
"⚠️ Se procesó la solicitud pero no se pudo extraer el resultado."
|
| 135 |
|
| 136 |
logger.info("✅ Análisis completado exitosamente")
|
| 137 |
return AnalyzeResponse(result=result_text)
|
|
|
|
| 139 |
except requests.exceptions.Timeout:
|
| 140 |
logger.error("⏱️ Timeout en la petición a Langflow")
|
| 141 |
return AnalyzeResponse(
|
| 142 |
+
result="❌ Error: La solicitud tardó demasiado tiempo.",
|
| 143 |
+
success=False,
|
| 144 |
+
error="timeout"
|
| 145 |
)
|
| 146 |
+
|
| 147 |
except requests.exceptions.ConnectionError as e:
|
| 148 |
logger.error(f"🔌 Error de conexión: {e}")
|
| 149 |
return AnalyzeResponse(
|
| 150 |
+
result="❌ Error: No se pudo conectar con el servicio de análisis.",
|
| 151 |
+
success=False,
|
| 152 |
+
error="connection"
|
| 153 |
)
|
| 154 |
+
|
| 155 |
except requests.exceptions.HTTPError as e:
|
| 156 |
+
# <-- Aquí mejora el logging para capturar el body del 500 interno
|
| 157 |
+
status = e.response.status_code if e.response else "unknown"
|
| 158 |
+
body = e.response.text if e.response else ""
|
| 159 |
+
logger.error(f"🚫 Error HTTP {status} al llamar al Flow. Body de error:\n{body}")
|
| 160 |
return AnalyzeResponse(
|
| 161 |
+
result=f"❌ Error del servidor (HTTP {status}). Revisa los logs internos.",
|
| 162 |
+
success=False,
|
| 163 |
+
error=f"http_{status}"
|
| 164 |
)
|
| 165 |
+
|
| 166 |
except Exception as e:
|
| 167 |
logger.exception(f"💥 Error inesperado: {e}")
|
| 168 |
return AnalyzeResponse(
|
| 169 |
+
result=f"❌ Error inesperado: {str(e)}",
|
| 170 |
+
success=False,
|
| 171 |
+
error="unknown"
|
| 172 |
)
|
| 173 |
|
| 174 |
def _extract_text_from_response(data):
|
| 175 |
if isinstance(data, str):
|
| 176 |
return data
|
| 177 |
if isinstance(data, dict):
|
| 178 |
+
for key in ['text', 'message', 'result', 'output', 'content']:
|
| 179 |
+
if key in data:
|
| 180 |
+
return _extract_text_from_response(data[key]) if isinstance(data[key], (dict, list)) else data[key]
|
| 181 |
+
for value in data.values():
|
| 182 |
+
txt = _extract_text_from_response(value)
|
| 183 |
+
if txt:
|
| 184 |
+
return txt
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 185 |
if isinstance(data, list):
|
| 186 |
for item in data:
|
| 187 |
+
txt = _extract_text_from_response(item)
|
| 188 |
+
if txt:
|
| 189 |
+
return txt
|
| 190 |
return None
|
| 191 |
|
| 192 |
# -------------------------------
|