Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,81 +1,248 @@
|
|
| 1 |
# app.py
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
from fastapi import FastAPI
|
| 3 |
-
from fastapi.responses import HTMLResponse
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
@app.get("/ping")
|
| 80 |
-
async def
|
| 81 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
# app.py
|
| 2 |
+
import html
|
| 3 |
+
import os
|
| 4 |
+
import subprocess
|
| 5 |
+
import sys
|
| 6 |
+
import threading
|
| 7 |
+
import time
|
| 8 |
+
from datetime import datetime, timezone
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from contextlib import asynccontextmanager
|
| 11 |
+
|
| 12 |
from fastapi import FastAPI
|
| 13 |
+
from fastapi.responses import HTMLResponse, JSONResponse, PlainTextResponse
|
| 14 |
+
|
| 15 |
+
BASE_DIR = Path(__file__).resolve().parent
|
| 16 |
+
LOGS_DIR = BASE_DIR / "logs"
|
| 17 |
+
RUNTIME_DIR = BASE_DIR / "runtime"
|
| 18 |
+
BOT_LOG = LOGS_DIR / "bot.log"
|
| 19 |
+
WEB_LOG = LOGS_DIR / "web.log"
|
| 20 |
+
CREATOR_HANDLE = os.getenv("CREATOR_HANDLE", "@Sasuke286")
|
| 21 |
+
PORT = int(os.getenv("PORT", "7860"))
|
| 22 |
+
AUTO_RESTART_BOT = os.getenv("AUTO_RESTART_BOT", "true").lower() in {"1", "true", "yes", "on"}
|
| 23 |
+
|
| 24 |
+
# Variables globales
|
| 25 |
+
_bot_process = None
|
| 26 |
+
_bot_log_handle = None
|
| 27 |
+
_monitor_started = False
|
| 28 |
+
_last_ping = None
|
| 29 |
+
_last_missing_env = None
|
| 30 |
+
_process_lock = threading.Lock()
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def now_iso() -> str:
|
| 34 |
+
return datetime.now(timezone.utc).astimezone().strftime("%Y-%m-%d %H:%M:%S %Z")
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def ensure_dirs() -> None:
|
| 38 |
+
LOGS_DIR.mkdir(parents=True, exist_ok=True)
|
| 39 |
+
RUNTIME_DIR.mkdir(parents=True, exist_ok=True)
|
| 40 |
+
BOT_LOG.touch(exist_ok=True)
|
| 41 |
+
WEB_LOG.touch(exist_ok=True)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def append_web_log(message: str) -> None:
|
| 45 |
+
ensure_dirs()
|
| 46 |
+
with WEB_LOG.open("a", encoding="utf-8") as fh:
|
| 47 |
+
fh.write(f"[{now_iso()}] {message}\n")
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def tail_file(path: Path, lines: int = 120) -> str:
|
| 51 |
+
if not path.exists():
|
| 52 |
+
return ""
|
| 53 |
+
with path.open("r", encoding="utf-8", errors="replace") as fh:
|
| 54 |
+
data = fh.readlines()[-lines:]
|
| 55 |
+
return "".join(data)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def missing_bot_env() -> list[str]:
|
| 59 |
+
required = ["API_ID", "API_HASH", "BOT_TOKEN"]
|
| 60 |
+
return [name for name in required if not os.getenv(name)]
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def bot_status() -> dict:
|
| 64 |
+
running = _bot_process is not None and _bot_process.poll() is None
|
| 65 |
+
return {
|
| 66 |
+
"running": running,
|
| 67 |
+
"pid": _bot_process.pid if running else None,
|
| 68 |
+
"last_ping": _last_ping,
|
| 69 |
+
"missing_env": missing_bot_env(),
|
| 70 |
+
"creator": CREATOR_HANDLE,
|
| 71 |
+
"space_id": os.getenv("SPACE_ID", "local"),
|
| 72 |
+
"space_host": os.getenv("SPACE_HOST", "local"),
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def ensure_bot_started() -> dict:
|
| 77 |
+
global _bot_process, _bot_log_handle, _last_missing_env
|
| 78 |
+
with _process_lock:
|
| 79 |
+
if _bot_process is not None and _bot_process.poll() is None:
|
| 80 |
+
return bot_status()
|
| 81 |
+
|
| 82 |
+
missing = missing_bot_env()
|
| 83 |
+
if missing:
|
| 84 |
+
signature = ",".join(missing)
|
| 85 |
+
if _last_missing_env != signature:
|
| 86 |
+
append_web_log(
|
| 87 |
+
"Bot no iniciado: faltan secrets -> " + ", ".join(missing)
|
| 88 |
+
)
|
| 89 |
+
_last_missing_env = signature
|
| 90 |
+
return bot_status()
|
| 91 |
+
|
| 92 |
+
_last_missing_env = None
|
| 93 |
+
|
| 94 |
+
ensure_dirs()
|
| 95 |
+
_bot_log_handle = BOT_LOG.open("a", encoding="utf-8", buffering=1)
|
| 96 |
+
env = os.environ.copy()
|
| 97 |
+
env["PYTHONUNBUFFERED"] = "1"
|
| 98 |
+
_bot_process = subprocess.Popen(
|
| 99 |
+
[sys.executable, "-u", "main.py"], # Cambia al nombre de tu archivo
|
| 100 |
+
cwd=BASE_DIR,
|
| 101 |
+
stdout=_bot_log_handle,
|
| 102 |
+
stderr=subprocess.STDOUT,
|
| 103 |
+
env=env,
|
| 104 |
+
)
|
| 105 |
+
append_web_log(f"Bot iniciado automáticamente | pid={_bot_process.pid}")
|
| 106 |
+
return bot_status()
|
| 107 |
|
| 108 |
+
|
| 109 |
+
def monitor_bot() -> None:
|
| 110 |
+
global _bot_process
|
| 111 |
+
while True:
|
| 112 |
+
time.sleep(5)
|
| 113 |
+
with _process_lock:
|
| 114 |
+
if _bot_process is None:
|
| 115 |
+
pass
|
| 116 |
+
elif _bot_process.poll() is None:
|
| 117 |
+
continue
|
| 118 |
+
else:
|
| 119 |
+
code = _bot_process.returncode
|
| 120 |
+
append_web_log(f"Bot detenido | exit_code={code}")
|
| 121 |
+
_bot_process = None
|
| 122 |
+
if AUTO_RESTART_BOT:
|
| 123 |
+
ensure_bot_started()
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
@asynccontextmanager
|
| 127 |
+
async def lifespan(application: FastAPI):
|
| 128 |
+
"""Ciclo de vida de FastAPI"""
|
| 129 |
+
global _monitor_started
|
| 130 |
+
ensure_dirs()
|
| 131 |
+
append_web_log("Web mínima iniciada para cronjob/logs")
|
| 132 |
+
ensure_bot_started()
|
| 133 |
+
if not _monitor_started:
|
| 134 |
+
threading.Thread(target=monitor_bot, daemon=True).start()
|
| 135 |
+
_monitor_started = True
|
| 136 |
+
|
| 137 |
+
yield # FastAPI sirve peticiones aquí
|
| 138 |
+
|
| 139 |
+
# No detenemos el bot, solo cerramos logs
|
| 140 |
+
append_web_log("Web deteniéndose... (bot sigue corriendo)")
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
app = FastAPI(
|
| 144 |
+
title="sas Space Control",
|
| 145 |
+
description="Panel mínimo para Hugging Face Space",
|
| 146 |
+
version="1.0",
|
| 147 |
+
lifespan=lifespan,
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
@app.get("/", response_class=HTMLResponse)
|
| 152 |
+
async def index():
|
| 153 |
+
status = bot_status()
|
| 154 |
+
missing = "<br>".join(status["missing_env"]) or "ninguno"
|
| 155 |
+
running_badge = "EN LÍNEA" if status["running"] else "DETENIDO"
|
| 156 |
+
page = f"""
|
| 157 |
+
<!doctype html>
|
| 158 |
+
<html lang="es">
|
| 159 |
+
<head>
|
| 160 |
+
<meta charset="utf-8">
|
| 161 |
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
| 162 |
+
<title>sas Space Control</title>
|
| 163 |
+
<style>
|
| 164 |
+
:root {{ color-scheme: dark; }}
|
| 165 |
+
body {{ margin: 0; font-family: Inter, Arial, sans-serif; background: #0b1020; color: #eef2ff; }}
|
| 166 |
+
.wrap {{ max-width: 980px; margin: 0 auto; padding: 24px; }}
|
| 167 |
+
.card {{ background: #121a31; border: 1px solid #263255; border-radius: 18px; padding: 18px; margin-bottom: 16px; box-shadow: 0 10px 30px rgba(0,0,0,.25); }}
|
| 168 |
+
.grid {{ display: grid; grid-template-columns: repeat(auto-fit, minmax(230px, 1fr)); gap: 14px; }}
|
| 169 |
+
.ok {{ color: #67e8a5; }}
|
| 170 |
+
.bad {{ color: #fca5a5; }}
|
| 171 |
+
a {{ color: #93c5fd; text-decoration: none; }}
|
| 172 |
+
pre {{ background: #070b16; border: 1px solid #1f2a44; border-radius: 14px; padding: 14px; overflow: auto; min-height: 380px; white-space: pre-wrap; }}
|
| 173 |
+
.pill {{ display: inline-block; padding: 6px 10px; border-radius: 999px; background: #1d2846; border: 1px solid #32406b; }}
|
| 174 |
+
code {{ color: #c4b5fd; }}
|
| 175 |
+
</style>
|
| 176 |
+
</head>
|
| 177 |
+
<body>
|
| 178 |
+
<div class="wrap">
|
| 179 |
+
<div class="card">
|
| 180 |
+
<h1 style="margin:0 0 6px;">sas Space Control</h1>
|
| 181 |
+
<div class="pill">Bot: <strong class="{'ok' if status['running'] else 'bad'}">{running_badge}</strong></div>
|
| 182 |
+
<p>Panel mínimo para Hugging Face Space. La web arranca y el bot intenta iniciar automáticamente.</p>
|
| 183 |
+
<p><strong>Creador:</strong> {html.escape(CREATOR_HANDLE)}</p>
|
| 184 |
+
</div>
|
| 185 |
+
|
| 186 |
+
<div class="grid">
|
| 187 |
+
<div class="card"><strong>PID del bot</strong><br><code>{status['pid'] or 'sin proceso'}</code></div>
|
| 188 |
+
<div class="card"><strong>Último ping cron</strong><br><code>{html.escape(status['last_ping'] or 'sin ping todavía')}</code></div>
|
| 189 |
+
<div class="card"><strong>Secrets faltantes</strong><br><code>{html.escape(missing)}</code></div>
|
| 190 |
+
<div class="card"><strong>Endpoints</strong><br><a href="/healthz">/healthz</a><br><a href="/cron/ping">/cron/ping</a><br><a href="/api/status">/api/status</a><br><a href="/api/logs">/api/logs</a></div>
|
| 191 |
+
</div>
|
| 192 |
+
|
| 193 |
+
<div class="card">
|
| 194 |
+
<strong>Logs</strong>
|
| 195 |
+
<pre id="logs">cargando...</pre>
|
| 196 |
+
</div>
|
| 197 |
+
</div>
|
| 198 |
+
|
| 199 |
+
<script>
|
| 200 |
+
async function refresh() {{
|
| 201 |
+
const res = await fetch('/api/logs');
|
| 202 |
+
document.getElementById('logs').textContent = await res.text();
|
| 203 |
+
}}
|
| 204 |
+
refresh();
|
| 205 |
+
setInterval(refresh, 4000);
|
| 206 |
+
</script>
|
| 207 |
+
</body>
|
| 208 |
+
</html>
|
| 209 |
+
"""
|
| 210 |
+
return page
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
@app.get("/healthz")
|
| 214 |
+
async def healthz():
|
| 215 |
+
ensure_bot_started()
|
| 216 |
+
return JSONResponse(bot_status())
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
@app.get("/cron/ping")
|
| 220 |
@app.get("/ping")
|
| 221 |
+
async def cron_ping():
|
| 222 |
+
global _last_ping
|
| 223 |
+
_last_ping = now_iso()
|
| 224 |
+
append_web_log("Ping de cronjob recibido")
|
| 225 |
+
ensure_bot_started()
|
| 226 |
+
return JSONResponse({"ok": True, **bot_status()})
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
@app.get("/api/status")
|
| 230 |
+
async def api_status():
|
| 231 |
+
ensure_bot_started()
|
| 232 |
+
return JSONResponse(bot_status())
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
@app.get("/api/logs")
|
| 236 |
+
async def api_logs():
|
| 237 |
+
content = (
|
| 238 |
+
"===== WEB LOG =====\n"
|
| 239 |
+
+ tail_file(WEB_LOG)
|
| 240 |
+
+ "\n===== BOT LOG =====\n"
|
| 241 |
+
+ tail_file(BOT_LOG)
|
| 242 |
+
)
|
| 243 |
+
return PlainTextResponse(content)
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
if __name__ == "__main__":
|
| 247 |
+
import uvicorn
|
| 248 |
+
uvicorn.run(app, host="0.0.0.0", port=PORT)
|