Spaces:
Configuration error
Configuration error
| # keepalive.py | |
| """ | |
| Keep-alive para Hugging Face Spaces. | |
| HF duerme los Spaces gratuitos tras 15 min sin tráfico. | |
| Este script se pinga a sí mismo cada 4 minutos para mantenerlo activo. | |
| También hace ping externo a UptimeRobot si se configura UPTIME_URL. | |
| """ | |
| import os | |
| import time | |
| import urllib.request | |
| import urllib.error | |
| from datetime import datetime | |
| # URL del propio Space — HF la inyecta como variable de entorno | |
| # Formato: https://TU_USUARIO-synergix.hf.space | |
| SPACE_URL = os.getenv("SPACE_URL", "http://localhost:7860") | |
| UPTIME_URL = os.getenv("UPTIME_URL", "") # opcional: UptimeRobot webhook | |
| INTERVAL = 240 # 4 minutos (HF duerme tras 15 min sin tráfico) | |
| def ping(url: str, label: str) -> bool: | |
| try: | |
| req = urllib.request.Request( | |
| url, | |
| headers={"User-Agent": "Synergix-Keepalive/2.0"}, | |
| ) | |
| with urllib.request.urlopen(req, timeout=10) as resp: | |
| status = resp.status | |
| print(f"[{datetime.now().strftime('%H:%M:%S')}] ✅ {label} → HTTP {status}", flush=True) | |
| return status == 200 | |
| except Exception as e: | |
| print(f"[{datetime.now().strftime('%H:%M:%S')}] ⚠️ {label} ping falló: {e}", flush=True) | |
| return False | |
| if __name__ == "__main__": | |
| print(f"🔄 Keepalive iniciado → Space: {SPACE_URL} | Intervalo: {INTERVAL}s", flush=True) | |
| time.sleep(15) # Esperar a que el health server arranque | |
| while True: | |
| ping(f"{SPACE_URL}/health", "Self-ping") | |
| if UPTIME_URL: | |
| ping(UPTIME_URL, "UptimeRobot") | |
| time.sleep(INTERVAL) | |