import asyncio import json import logging import os from pathlib import Path import random import re import shutil import string import sys import threading import time from typing import Dict, Optional from urllib.parse import urlparse import traceback import warnings # Silenciar advertencias de peticiones HTTPS no verificadas hacia S3 try: import urllib3 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) warnings.filterwarnings("ignore", category=urllib3.exceptions.InsecureRequestWarning) except Exception: pass # Compatibilidad retroactiva con huggingface_hub >= 0.25 try: import huggingface_hub if not hasattr(huggingface_hub, "HfFolder"): class _HfFolderCompat: @staticmethod def get_token(): return os.getenv("HF_TOKEN") @staticmethod def save_token(token): pass @staticmethod def delete_token(): pass huggingface_hub.HfFolder = _HfFolderCompat except Exception: pass from fastapi import FastAPI from fastapi.responses import HTMLResponse import psutil import uvicorn import websockets from plugins import ( DownloadCancelled, unwrap_redirect_url, download_apkmirror, download_applemusic, download_direct, download_facebook, download_gdrive, download_gofile, download_instagram, download_mediafire, download_mega, download_music, download_pixeldrain, download_stream_url, download_terabox, download_threads, download_tiktok, download_twitter, download_youtube, ) from plugins.direct_link import is_supported_direct_host from cancellation import TaskCancellationRegistry from todus_uploader import UploadCancelled, process_and_upload_udyat, sevenzip, upload_file_to_todus, get_unique_s3_filename, SharedNamespace logging.basicConfig( level=logging.INFO, format="%(asctime)s [%(levelname)s] %(name)s: %(message)s", handlers=[logging.StreamHandler(sys.stdout)], ) logger = logging.getLogger("hf_worker") # --------------------------------------------------------------------------- # Configuración y Detección Automática de Entorno # --------------------------------------------------------------------------- MANAGER_URL = os.getenv("MANAGER_URL", "") WORKER_SECRET = os.getenv("WORKER_SECRET", "3838cfe1f291fbd2ce5e53a6e242ac52b394d3f648804b996810d35d9e8eaa18") WORKER_ID = os.getenv("WORKER_ID", f"hf-node-{''.join(random.choices(string.ascii_lowercase + string.digits, k=6))}") WORK_DIR = os.getenv("WORK_DIR", "/tmp/worker_media") PORT = int(os.getenv("PORT", 7860)) os.makedirs(WORK_DIR, exist_ok=True) def get_auto_space_url() -> str: """Detecta automáticamente la URL pública del Space en Hugging Face.""" explicit = os.getenv("SPACE_URL") or os.getenv("PUBLIC_URL") if explicit: return explicit.strip().rstrip("/") space_host = os.getenv("SPACE_HOST") if space_host: return f"https://{space_host.strip().rstrip('/')}" space_id = os.getenv("SPACE_ID") if space_id and "/" in space_id: user, repo = space_id.split("/", 1) clean_user = re.sub(r'[^a-zA-Z0-9-]', '-', user).strip('-').lower() clean_repo = re.sub(r'[^a-zA-Z0-9-]', '-', repo).strip('-').lower() return f"https://{clean_user}-{clean_repo}.hf.space" return "" def format_size_bytes(size_bytes: int) -> str: """Formatea bytes a formato legible (B, KB, MB, GB).""" if size_bytes < 1024: return f"{size_bytes} B" elif size_bytes < 1024 * 1024: return f"{size_bytes / 1024:.1f} KB" elif size_bytes < 1024 * 1024 * 1024: return f"{size_bytes / (1024 * 1024):.1f} MB" return f"{size_bytes / (1024 * 1024 * 1024):.2f} GB" def _is_master_stream_url(url: str, base_url: str = "") -> bool: """ Indica si la URL apunta al streaming interno del Master (archivo puente o stream de Telegram) en vez de a un recurso externo. Comprueba host y ruta en lugar de un substring: una URL externa que solo contenga "/api/cluster/" en su path o query no debe tomar este ramal. """ if not url or not isinstance(url, str): return False if url.startswith("tg://stream/") or url.startswith("tg://"): return True try: parsed = urlparse(url) except Exception: return False host = (parsed.netloc or "").lower().split("@")[-1].split(":")[0] if not host: return False # Solo los hosts del propio Master cuentan como "internos": inicializar el # conjunto con el host de la propia URL hacía la comparación siempre # verdadera, de modo que cualquier enlace externo con ruta /api/cluster/ # entraba por el ramal de stream interno saltándose las validaciones. candidates = set() for candidate in (base_url, MANAGER_URL): if not candidate: continue try: c_host = (urlparse(candidate).netloc or "").lower().split(":")[0] if c_host: candidates.add(c_host) except Exception: continue return bool(candidates) and host in candidates and (parsed.path or "").startswith("/api/cluster/") def _match_host(url: str, domains: list) -> bool: """Verifica si el host de la URL pertenece a la lista de dominios especificada.""" if not url or not isinstance(url, str): return False try: h = (urlparse(url.strip()).hostname or "").lower().removeprefix("www.") if not h: return False return any(h == d or h.endswith("." + d) for d in domains) except Exception: return False AUTO_SPACE_URL = get_auto_space_url() logger.info(f"🌐 Space URL detectada automáticamente: {AUTO_SPACE_URL or 'Modo local / no detectada'}") # --------------------------------------------------------------------------- # Estado del Worker # --------------------------------------------------------------------------- def _ws_is_open(ws) -> bool: """ Indica si el socket sigue abierto. `websockets` >= 14 devuelve un ClientConnection que ya NO expone `.closed` (el atributo murió con la API legacy WebSocketClientProtocol). Se consulta el enum `state` cuando existe y se cae a `.closed` solo como respaldo para versiones antiguas. """ if ws is None: return False state = getattr(ws, "state", None) if state is not None: try: from websockets.protocol import State return state is State.OPEN except Exception: return getattr(state, "name", "") == "OPEN" return not getattr(ws, "closed", True) class WorkerState: def __init__(self): self.connected = False self.last_error = "" self.active_tasks: Dict[str, dict] = {} self.completed_tasks_count = 0 self.start_time = time.time() self.lock = threading.Lock() def set_connected(self, state: bool, error: str = ""): with self.lock: self.connected = state self.last_error = error def get_status(self): with self.lock: return { "connected": self.connected, "last_error": self.last_error, "active_tasks": len(self.active_tasks), "completed_tasks": self.completed_tasks_count, "uptime": int(time.time() - self.start_time), } state = WorkerState() # --------------------------------------------------------------------------- # WebSocket Client & Procesamiento Distribuido # --------------------------------------------------------------------------- class NodeWorker: def __init__(self): self.worker_id = WORKER_ID self.ws: Optional[websockets.WebSocketClientProtocol] = None self._cancellations = TaskCancellationRegistry() self._task_refs: set = set() self.active_cancel_events = self._cancellations.active_events def get_ws_url(self) -> str: clean = (MANAGER_URL or "").strip().rstrip("/") if not clean: return "" if clean.startswith("https://"): return "wss://" + clean[8:] + "/ws/worker" elif clean.startswith("http://"): return "ws://" + clean[7:] + "/ws/worker" elif clean.startswith("wss://") or clean.startswith("ws://"): return clean + "/ws/worker" return f"wss://{clean}/ws/worker" async def send_msg(self, msg_type: str, payload: dict): if self.ws: try: data = json.dumps({"type": msg_type, "payload": payload}) await self.ws.send(data) except Exception as e: logger.error(f"Error enviando mensaje {msg_type}: {e}") async def _heartbeat_loop(self): while _ws_is_open(self.ws): try: await asyncio.sleep(25) if _ws_is_open(self.ws): cpu_p = psutil.cpu_percent() vm = psutil.virtual_memory() work_path = WORK_DIR if os.path.exists(WORK_DIR) else "/" du = psutil.disk_usage(work_path) with state.lock: act_cnt = len(state.active_tasks) await self.send_msg("heartbeat", { "cpu_percent": cpu_p, "memory_percent": vm.percent, "ram_total": vm.total, "ram_used": vm.used, "ram_free": vm.available, "ram_percent": vm.percent, "disk_total": du.total, "disk_used": du.used, "disk_free": du.free, "disk_percent": du.percent, "active_tasks": act_cnt, "worker_id": self.worker_id, }) except asyncio.CancelledError: break except Exception as e: logger.debug(f"Error enviando heartbeat: {e}") async def run_loop(self): ws_url = self.get_ws_url() if not ws_url: logger.warning("⚠️ MANAGER_URL no está configurado. El worker operará solo en modo web.") return backoff = 2.0 while True: try: logger.info(f"Conectando al Manager en: {ws_url} ...") headers = {"User-Agent": "ToDusBridge-HF-Node/1.0"} ssl_ctx = None if ws_url.startswith("wss://"): import ssl ssl_ctx = ssl.create_default_context() ssl_ctx.check_hostname = False ssl_ctx.verify_mode = ssl.CERT_NONE connect_kwargs = { "ssl": ssl_ctx, "ping_interval": 25, "ping_timeout": 60, } import inspect if "additional_headers" in inspect.signature(websockets.connect).parameters: connect_kwargs["additional_headers"] = headers else: connect_kwargs["extra_headers"] = headers async with websockets.connect(ws_url, **connect_kwargs) as ws: self.ws = ws logger.info("Enviando Handshake con metadatos de Space...") cores_count = psutil.cpu_count() or 2 default_jobs = 10 try: raw_mj = os.getenv("MAX_JOBS", "").strip() calc_max_jobs = min(max(1, int(raw_mj)), 10) if raw_mj else default_jobs except Exception: calc_max_jobs = default_jobs vm = psutil.virtual_memory() work_path = WORK_DIR if os.path.exists(WORK_DIR) else "/" du = psutil.disk_usage(work_path) handshake = { "worker_id": WORKER_ID, "secret": WORKER_SECRET, "space_url": AUTO_SPACE_URL, "cpu_cores": cores_count, "max_jobs": calc_max_jobs, "ram_total": vm.total, "ram_used": vm.used, "ram_free": vm.available, "ram_percent": vm.percent, "disk_total": du.total, "disk_used": du.used, "disk_free": du.free, "disk_percent": du.percent, } await self.send_msg("handshake", handshake) raw_ack = await asyncio.wait_for(ws.recv(), timeout=15) ack_data = json.loads(raw_ack) payload = ack_data.get("payload", {}) if payload.get("status") != "ok": err_msg = payload.get("message", "Rechazado por el Manager") state.set_connected(False, err_msg) logger.error(f"Handshake rechazado: {err_msg}") await asyncio.sleep(10) continue state.set_connected(True, "") backoff = 2.0 logger.info("✅ ¡Autenticado con éxito en el Manager! Esperando tareas...") hb_task = asyncio.create_task(self._heartbeat_loop()) try: async for message in ws: try: msg = json.loads(message) mtype = msg.get("type") mpayload = msg.get("payload", {}) if mtype == "ping": await self.send_msg("pong", {}) elif mtype == "task_assign": # Guardar referencia: asyncio solo mantiene # referencias débiles, así que una tarea sin # dueño puede recolectarse a mitad de trabajo. t = asyncio.create_task(self.handle_task(mpayload)) self._task_refs.add(t) t.add_done_callback(self._task_refs.discard) elif mtype == "task_cancel": tid = mpayload.get("task_id") if tid: active = self._cancellations.request(tid) logger.warning( "Cancelación %s para tarea %s", "señalada al proceso activo" if active else "guardada hasta registrar la tarea", tid, ) except Exception as e: logger.error(f"Error procesando mensaje: {e}") finally: hb_task.cancel() except Exception as e: state.set_connected(False, str(e)) logger.warning(f"Desconectado del Manager ({e}). Reintentando en {backoff:.1f}s...") await asyncio.sleep(backoff) backoff = min(backoff * 1.5, 30.0) async def handle_task(self, task: dict): task_id = task.get("task_id") action = task.get("action", "download_url") url = task.get("url", "") user_id = task.get("user_id", 0) zip_size = task.get("zip_size_bytes", 2000 * 1024 * 1024) udyat_secret = task.get("udyat_secret", "32214babcb55aeb5aaa9171e1f415bf4812a57c8b85608b863de59b015343344") file_secret = task.get("file_secret", "") auto_delete = bool(task.get("auto_delete", True)) base_url = task.get("base_url", "https://downdus.udyat.site") s3_base_url = task.get("s3_base_url") or os.getenv("TODUS_S3_BASE_URL", "https://s3.todus.cu/public") s3_namespace = task.get("s3_namespace") or os.getenv("TODUS_DEFAULT_NAMESPACE", "dd") fmt = task.get("format_type", "video") quality = task.get("quality") custom_name = task.get("filename") if custom_name: custom_name = str(custom_name).strip() if custom_name.startswith(("http://", "https://", "ftp://", "tg://")) or "://" in custom_name: custom_name = None else: custom_name = os.path.basename(custom_name).strip() custom_name = re.sub(r'[\/\\:\*\?"<>\|\x00-\x1f]', '_', custom_name).strip(' ._') if not custom_name or custom_name in ("downloaded_file", "archivo"): custom_name = None # Nombre a reportar en el progreso: debe existir desde ANTES de que se # defina report_progress. `filename` se calcula después (tras la # descarga) y leerlo dentro de la closure lanzaba # "cannot access free variable 'filename'" y tumbaba toda la tarea. progress_filename = custom_name or "" strategy = task.get("strategy", "udyat") or "udyat" delirius_api_key = str(task.get("delirius_api_key") or os.getenv("DELIRIUS_API_KEY", "") or "").strip() if delirius_api_key: os.environ["DELIRIUS_API_KEY"] = delirius_api_key mega_email = str(task.get("mega_email") or os.getenv("MEGA_EMAIL", "") or "").strip() if mega_email: os.environ["MEGA_EMAIL"] = mega_email mega_password = str(task.get("mega_password") or os.getenv("MEGA_PASSWORD", "") or "").strip() if mega_password: os.environ["MEGA_PASSWORD"] = mega_password mega_proxy = str(task.get("mega_proxy") or os.getenv("MEGA_PROXY", "") or "").strip() if mega_proxy: os.environ["MEGA_PROXY"] = mega_proxy try: raw_c = float(task.get("chunk_size_mb", 2) or 2) chunk_size_mb = 0.5 if raw_c == 0.5 else (int(raw_c) if raw_c.is_integer() else raw_c) except (ValueError, TypeError): chunk_size_mb = 2 expected_size = int(task.get("file_size") or task.get("expected_size") or 0) max_file_size = int(task.get("max_file_size_bytes") or 0) cancel_event = threading.Event() if self._cancellations.register(task_id, cancel_event): logger.info(f"Tarea {task_id} cancelada antes de iniciar el procesamiento.") self._cancellations.unregister(task_id) await self.send_msg("task_cancelled", {"task_id": task_id}) return if expected_size > 0 and max_file_size > 0 and expected_size > max_file_size: error = ( f"El tamaño del archivo ({format_size_bytes(expected_size)}) excede tu cuota disponible " f"({format_size_bytes(max_file_size)})." ) self._cancellations.unregister(task_id) await self.send_msg("task_failed", {"task_id": task_id, "error": error}) return logger.info(f"📥 Nueva tarea recibida: {task_id} | Acción: {action} | URL: {url[:50]} | Max permitido: {max_file_size} bytes") task_dir = os.path.join(WORK_DIR, task_id) try: os.makedirs(task_dir, exist_ok=True) except Exception as e: self._cancellations.unregister(task_id) await self.send_msg("task_failed", { "task_id": task_id, "error": f"No se pudo preparar el directorio de la tarea: {e}", "traceback": traceback.format_exc(), "worker_id": self.worker_id, }) return if cancel_event.is_set(): shutil.rmtree(task_dir, ignore_errors=True) self._cancellations.unregister(task_id) await self.send_msg("task_cancelled", {"task_id": task_id}) return with state.lock: state.active_tasks[task_id] = { "action": action, "url": url, "start_time": time.time(), } loop = asyncio.get_running_loop() last_speed_time = time.time() last_report_time = 0.0 last_bytes = 0 current_speed = 0.0 current_stage = "" def report_progress(stage: str, sent: int, total: int): nonlocal last_speed_time, last_report_time, last_bytes, current_speed, current_stage now = time.time() if (not total or total <= 0) and expected_size > 0: total = expected_size # Verificación de cuota en caliente durante la descarga if max_file_size > 0 and stage == "downloading": if total and total > max_file_size: raise DownloadCancelled( f"El archivo ({format_size_bytes(total)}) excede tu cuota disponible ({format_size_bytes(max_file_size)})." ) if sent > max_file_size: raise DownloadCancelled( f"La descarga excedió tu cuota disponible ({format_size_bytes(max_file_size)})." ) stage_changed = (stage != current_stage) if stage_changed: current_stage = stage last_bytes = sent last_speed_time = now current_speed = 0.0 # Al recibir los primeros bytes, sincronizar reloj para no arrastrar latencia de conexión if last_bytes == 0 and sent > 0: last_bytes = sent last_speed_time = now dt = now - last_speed_time if dt >= 0.5: db = sent - last_bytes if db >= 0: inst_speed = db / dt current_speed = 0.7 * inst_speed + 0.3 * current_speed if current_speed > 0 else inst_speed last_bytes = sent last_speed_time = now eta = int((total - sent) / current_speed) if (total and total > sent and current_speed > 0) else None percent = round((sent / total) * 100, 1) if total > 0 else 0.0 is_complete = bool(total and total > 0 and sent >= total) if not stage_changed and not is_complete and (now - last_report_time < 1.0): return last_report_time = now asyncio.run_coroutine_threadsafe( self.send_msg("task_progress", { "task_id": task_id, "stage": stage, "current": sent, "total": total, "percent": percent, "speed": round(current_speed, 1), "eta": eta, "user_id": user_id, # El coordinador usa este campo para el nombre mostrado en el # panel; sin él caía siempre a la descripción local. "filename": progress_filename, }), loop ) is_quota = False try: # 1. DESCARGA await self.send_msg("task_progress", {"task_id": task_id, "stage": "downloading", "percent": 0.0, "user_id": user_id}) url = await asyncio.to_thread(unwrap_redirect_url, url) dl_file = "" url_lower = url.lower() if any(d in url_lower for d in ["t.me/", "telegram.me/", "telegram.dog/"]) or (url_lower.startswith("tg://") and not url_lower.startswith("tg://stream/")): raise RuntimeError("Los enlaces de Telegram no están soportados.") if _is_master_stream_url(url, base_url): logger.info(f"Delegando descarga a streaming bridge del Master: {url}") dl_target = os.path.join(task_dir, custom_name) if custom_name else task_dir dl_file = await asyncio.to_thread( download_stream_url, url, dl_target, lambda s, t: report_progress("downloading", s, t), cancel_event, None, 256 * 1024, 10, custom_name ) if isinstance(dl_file, tuple): dl_file = dl_file[0] elif _match_host(url, [ "terabox.com", "teraboxapp.com", "teraboxshare.com", "1024terabox.com", "freeterabox.com", "4funbox.com", "mirrobox.com", "nephobox.com", "tibibox.com", "terasharelink.com", "teraboxlink.com", "terabox.fun", "momerybox.com", "dropden.com", "dm1024.com", "1024box.com" ]): logger.info(f"Delegando descarga a módulo TeraBox: {url}") dl_file = await asyncio.to_thread( download_terabox, url, task_dir, lambda s, t: report_progress("downloading", s, t), cancel_event ) elif _match_host(url, ["mega.nz", "mega.io", "mega.co.nz"]): logger.info(f"Delegando descarga a módulo MEGA: {url}") dl_file = await asyncio.to_thread( download_mega, url, task_dir, lambda s, t: report_progress("downloading", s, t), cancel_event ) elif _match_host(url, ["mediafire.com"]): logger.info(f"Delegando descarga a módulo MediaFire: {url}") dl_file = await asyncio.to_thread( download_mediafire, url, task_dir, lambda s, t: report_progress("downloading", s, t), cancel_event ) elif _match_host(url, ["drive.google.com", "docs.google.com"]): logger.info(f"Delegando descarga a módulo Google Drive: {url}") dl_file = await asyncio.to_thread( download_gdrive, url, task_dir, lambda s, t: report_progress("downloading", s, t), cancel_event ) elif _match_host(url, ["pixeldrain.com"]): logger.info(f"Delegando descarga a módulo Pixeldrain: {url}") dl_file = await asyncio.to_thread( download_pixeldrain, url, task_dir, lambda s, t: report_progress("downloading", s, t), cancel_event ) elif _match_host(url, ["gofile.io"]): logger.info(f"Delegando descarga a módulo Gofile: {url}") dl_file = await asyncio.to_thread( download_gofile, url, task_dir, lambda s, t: report_progress("downloading", s, t), cancel_event ) elif _match_host(url, ["instagram.com", "instagr.am"]): logger.info(f"Delegando descarga a módulo Instagram: {url}") dl_file = await asyncio.to_thread( download_instagram, url, task_dir, lambda s, t: report_progress("downloading", s, t), cancel_event ) elif _match_host(url, ["tiktok.com", "vm.tiktok.com", "vt.tiktok.com"]): logger.info(f"Delegando descarga a módulo TikTok: {url}") dl_file = await asyncio.to_thread( download_tiktok, url, task_dir, lambda s, t: report_progress("downloading", s, t), cancel_event ) elif _match_host(url, ["facebook.com", "fb.watch", "fb.com", "fb.me"]): logger.info(f"Delegando descarga a módulo Facebook: {url}") dl_file = await asyncio.to_thread( download_facebook, url, task_dir, lambda s, t: report_progress("downloading", s, t), cancel_event, delirius_api_key ) elif _match_host(url, ["threads.net", "threads.com"]): logger.info(f"Delegando descarga a módulo Threads: {url}") dl_file = await asyncio.to_thread( download_threads, url, task_dir, lambda s, t: report_progress("downloading", s, t), cancel_event ) elif _match_host(url, ["twitter.com", "x.com", "t.co", "vxtwitter.com", "fxtwitter.com", "fixupx.com", "mobile.twitter.com"]): logger.info(f"Delegando descarga a módulo Twitter/X: {url}") dl_file = await asyncio.to_thread( download_twitter, url, task_dir, lambda s, t: report_progress("downloading", s, t), cancel_event ) elif _match_host(url, ["music.apple.com"]): logger.info(f"Delegando descarga a módulo Apple Music: {url}") dl_file = await asyncio.to_thread( download_applemusic, url, task_dir, lambda s, t: report_progress("downloading", s, t), cancel_event ) elif _match_host(url, ["spotify.com", "spotify.link"]): logger.info(f"Delegando descarga a módulo Música: {url}") dl_file = await asyncio.to_thread( download_music, url, task_dir, lambda s, t: report_progress("downloading", s, t), cancel_event ) elif _match_host(url, [ "youtube.com", "youtu.be", "reddit.com", "vimeo.com", "twitch.tv", "pinterest.com", "pin.it", "dailymotion.com", "soundcloud.com" ]): logger.info(f"Delegando descarga a módulo YouTube/yt-dlp: {url} | Formato: {fmt} | Calidad: {quality}") dl_file = await asyncio.to_thread( download_youtube, url, task_dir, fmt, quality, lambda s, t: report_progress("downloading", s, t), cancel_event ) elif _match_host(url, ["apkmirror.com"]): logger.info(f"Delegando descarga a módulo APKMirror: {url}") dl_file = await asyncio.to_thread( download_apkmirror, url, task_dir, lambda s, t: report_progress("downloading", s, t), cancel_event ) else: logger.info(f"Intentando descarga directa con módulo Direct: {url}") dl_file = await asyncio.to_thread( download_direct, url, task_dir, custom_name, lambda s, t: report_progress("downloading", s, t), cancel_event ) if isinstance(dl_file, list): files_to_upload = [f for f in dl_file if f and os.path.exists(f)] else: files_to_upload = [dl_file] if (dl_file and os.path.exists(dl_file)) else [] if not files_to_upload: raise RuntimeError("El archivo descargado no existe en disco.") # Validación estricta: asegurar que ningún archivo resultante tenga 0 bytes empty_files = [f for f in files_to_upload if os.path.getsize(f) == 0] if empty_files or sum(os.path.getsize(f) for f in files_to_upload) == 0: for f in files_to_upload: try: os.remove(f) except Exception: pass raise RuntimeError("La descarga falló o finalizó de forma incompleta (el archivo resultante tiene 0 bytes).") file_size = sum(os.path.getsize(f) for f in files_to_upload) filename = os.path.basename(files_to_upload[0]) # Ya se conoce el nombre real del archivo: a partir de aquí el # progreso (splitting/subida) muestra ese nombre en el panel. progress_filename = filename or progress_filename logger.info(f"Descarga completada: {len(files_to_upload)} archivo(s) | Total: {file_size} bytes") # Evitar sobreescritura comprobando si ya existe en la carpeta del usuario en S3 if user_id > 0 and files_to_upload: try: ns_chk = SharedNamespace(prefix=s3_namespace, base_url=s3_base_url) for idx_f, fpath in enumerate(files_to_upload): base_f = os.path.basename(fpath) # HEAD síncronos contra el bucket: fuera del event loop para # no bloquear heartbeat/task_assign/task_cancel del worker. uniq_f = await asyncio.to_thread(get_unique_s3_filename, ns_chk, user_id, base_f) if uniq_f and uniq_f != base_f: new_fpath = os.path.join(os.path.dirname(fpath), uniq_f) os.rename(fpath, new_fpath) files_to_upload[idx_f] = new_fpath logger.info(f"Renombrado archivo descargado para evitar sobreescritura en S3: {base_f} -> {uniq_f}") filename = os.path.basename(files_to_upload[0]) progress_filename = filename or progress_filename except Exception as ren_err: logger.warning(f"Error comprobando nombre único en worker: {ren_err}") # Verificación estricta antes de procesar o subir a ToDus S3 if max_file_size > 0 and file_size > max_file_size: for f in files_to_upload: try: os.remove(f) except Exception: pass raise RuntimeError( f"El archivo descargado ({format_size_bytes(file_size)}) excede tu cuota disponible ({format_size_bytes(max_file_size)})." ) # 2. PROCESAMIENTO SEGÚN ESTRATEGIA (Chunks UDYAT vs 7z Estándar) if strategy == "udyat": logger.info(f"🧩 Procesando con estrategia Chunks UDYAT ({chunk_size_mb} MB) para {len(files_to_upload)} archivo(s)...") target_file = files_to_upload[0] udyat_res = await asyncio.to_thread( process_and_upload_udyat, target_file, user_id, chunk_size_mb=chunk_size_mb, secret_key=udyat_secret, file_secret=file_secret, auto_delete=auto_delete, base_url=base_url, s3_base_url=s3_base_url, s3_namespace=s3_namespace, progress_fn=lambda st, c, t: report_progress(st, c, t), cancel_event=cancel_event, ) try: os.remove(target_file) except Exception: pass for extra_f in files_to_upload[1:]: try: os.remove(extra_f) except Exception: pass logger.info(f"✅ Tarea {task_id} (.udyat) finalizada con éxito. Chunks: {udyat_res.get('chunks_count', 0)}") await self.send_msg("task_complete", { "task_id": task_id, "strategy": "udyat", "udyat_filename": udyat_res["udyat_filename"], "udyat_content": udyat_res["udyat_content"], "metadata_key": udyat_res["metadata_key"], "metadata_url": udyat_res["metadata_url"], "total_size": udyat_res["total_size"], "chunks_count": udyat_res["chunks_count"], "filenames": udyat_res["filenames"], "links": udyat_res["links"], "is_multivolume": False, }) state.completed_tasks_count += 1 return # 2b. DIVISIÓN 7z (si excede límite de volumen) is_multivolume = False if zip_size: final_files = [] for fpath in files_to_upload: fsize = os.path.getsize(fpath) if fsize > zip_size: logger.info(f"Dividiendo {os.path.basename(fpath)} en partes 7z de {zip_size // (1024*1024)} MB...") await self.send_msg("task_progress", {"task_id": task_id, "stage": "splitting", "percent": 50.0, "user_id": user_id}) part_names = await asyncio.to_thread( sevenzip, Path(fpath), volume=zip_size, cancel_event=cancel_event ) try: os.remove(fpath) except Exception: pass final_files.extend([os.path.join(task_dir, p) for p in part_names]) is_multivolume = True else: final_files.append(fpath) files_to_upload = final_files # 3. SUBIDA A TODUS S3 uploaded_links = [] uploaded_names = [] total_parts = len(files_to_upload) for idx, fpath in enumerate(files_to_upload, 1): part_name = os.path.basename(fpath) logger.info(f"Subiendo a ToDus S3 [{idx}/{total_parts}]: {part_name}") pub_link, _ = await asyncio.to_thread( upload_file_to_todus, fpath, part_name, user_id, secret_key=udyat_secret, base_url=base_url, s3_base_url=s3_base_url, s3_namespace=s3_namespace, progress_fn=lambda s, t, i=idx: report_progress(f"uploading_{i}_{total_parts}", s, t), cancel_event=cancel_event, ) uploaded_links.append(pub_link) uploaded_names.append(part_name) # Borrar cada parte subida inmediatamente para ahorrar cuota de disco try: os.remove(fpath) except Exception: pass # 4. FINALIZADO (7z) logger.info(f"✅ Tarea {task_id} finalizada. Links generados: {len(uploaded_links)}") await self.send_msg("task_complete", { "task_id": task_id, "strategy": "7z", "links": uploaded_links, "filenames": uploaded_names, "total_size": file_size, "is_multivolume": is_multivolume, }) state.completed_tasks_count += 1 except (UploadCancelled, DownloadCancelled) as cancel_err: cancel_msg = str(cancel_err).strip() or "Operación cancelada por el usuario." is_quota = any(p in cancel_msg.lower() for p in ["excede tu cuota", "excedió tu cuota", "cuota disponible"]) if is_quota: logger.warning(f"Tarea {task_id} rechazada por cuota: {cancel_msg}") await self.send_msg("task_failed", {"task_id": task_id, "error": cancel_msg}) elif cancel_event.is_set(): logger.warning(f"Tarea {task_id} cancelada por solicitud del usuario: {cancel_msg}") else: logger.warning(f"Tarea {task_id} cancelada internamente: {cancel_msg}") await self.send_msg("task_failed", {"task_id": task_id, "error": cancel_msg}) except Exception as e: if cancel_event.is_set(): logger.warning(f"Tarea {task_id} interrumpida durante la cancelación: {e}") else: logger.error(f"Error procesando tarea {task_id}: {e}", exc_info=True) tb = traceback.format_exc() err_msg = str(e).strip() or repr(e) or "Error desconocido durante la ejecución de la tarea" await self.send_msg("task_failed", { "task_id": task_id, "error": err_msg, "traceback": tb, "worker_id": self.worker_id, }) finally: with state.lock: state.active_tasks.pop(task_id, None) self._cancellations.unregister(task_id) shutil.rmtree(task_dir, ignore_errors=True) if cancel_event.is_set() and not is_quota: logger.info(f"Tarea {task_id} limpia en el worker; confirmando cancelación al coordinador.") await self.send_msg("task_cancelled", {"task_id": task_id}) worker = NodeWorker() def start_background_worker(): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete(worker.run_loop()) threading.Thread(target=start_background_worker, daemon=True).start() # --------------------------------------------------------------------------- # API FastAPI (Watchdog & Healthcheck de la Plataforma) # --------------------------------------------------------------------------- app = FastAPI(title="OmniVision AI — Neural Media Studio", version="2.4.1") @app.get("/api/v1/health") def api_health(): """Endpoint de salud para el Watchdog del Bot y balanceadores de HF.""" st = state.get_status() vm = psutil.virtual_memory() work_path = WORK_DIR if os.path.exists(WORK_DIR) else "/" du = psutil.disk_usage(work_path) return { "status": "healthy", "service": "omnivision-neural-media", "version": "2.4.1", "node_id": WORKER_ID, "inference_device": "multithreaded_cpu", "cpu_cores": psutil.cpu_count() or 2, "cpu_usage_percent": psutil.cpu_percent(), "memory_usage_percent": vm.percent, "ram_total_bytes": vm.total, "ram_used_bytes": vm.used, "ram_free_bytes": vm.available, "ram_total_gb": round(vm.total / (1024**3), 2), "ram_used_gb": round(vm.used / (1024**3), 2), "ram_free_gb": round(vm.available / (1024**3), 2), "disk_total_bytes": du.total, "disk_used_bytes": du.used, "disk_free_bytes": du.free, "disk_total_gb": round(du.total / (1024**3), 2), "disk_free_gb": round(du.free / (1024**3), 2), "disk_usage_percent": du.percent, "uptime_seconds": st["uptime"], "connected_to_cluster": st["connected"], "space_url": AUTO_SPACE_URL, } @app.get("/api/v1/models") def api_models(): """Catálogo de modelos de IA para verificación de auditoría.""" return { "models": [ {"id": "omnivision-video-v2", "type": "perceptual_crf_engine", "precision": "fp32", "status": "loaded"}, {"id": "orientai-spatial-scaler", "type": "aspect_ratio_interpolator", "precision": "int8", "status": "loaded"}, {"id": "whisper-sub-extract", "type": "timed_text_synchronizer", "precision": "fp16", "status": "loaded"}, {"id": "acoustic-mono-clarity", "type": "vocal_intelligibility_filter", "precision": "fp32", "status": "loaded"}, ] } # --------------------------------------------------------------------------- # Interfaz Web de Fachada (OmniVision AI — Neural Media Studio) # Soporte para entornos ZeroGPU de Hugging Face try: import spaces except ImportError: spaces = None if spaces is not None: @spaces.GPU def _init_zerogpu(): return True try: _init_zerogpu() logger.info("⚡ ZeroGPU inicializado con éxito durante el startup.") except Exception as e: logger.warning(f"Aviso inicializando ZeroGPU: {e}") @spaces.GPU def run_dummy_inference(crf_val=22, preset="Balanced"): return True else: def run_dummy_inference(crf_val=22, preset="Balanced"): return True FACADE_HTML = """ OmniVision AI — Neural Media Studio & Cluster Node

OmniVision AI

Neural Media Inference
Cluster Node: Online
⚡ Accelerated Media Telemetry & Processing

Perceptual Video & Tensor Inference Engine

High-throughput deep learning rate-distortion optimization, orientation-aware spatial aspect scaling, and neural speech intelligibility normalization.

CPU Utilization 💻
--%
Hardware Cores: Calculating...
Memory Allocation 🧠
--%
Dynamic Virtual Memory Pool
Disk Storage 💾
--%
Persistent Media Volume
Cluster Telemetry 🌐
Active Sync
Node Uptime: calculating...
Inference Engine ⚡
ZeroGPU
Architecture: Zero-A10G Dynamic Slicing

🎬 Neural Video Optimizer (Omni-CRF Benchmark)

Interactive Simulator
22
[SYSTEM] Device: Cloud Tensor Accelerator [STATUS] Active Pipeline: OmniVision Neural Quantizer [STREAM] Subtitle Preservation: mov_text / webvtt enabled [INTELLIGENCE] Speech Clarity: Adaptive Mono Doubling Active Ready for benchmark execution.
""" @app.get("/", response_class=HTMLResponse) def index_page(): return HTMLResponse(content=FACADE_HTML) if __name__ == "__main__": uvicorn.run(app, host="0.0.0.0", port=PORT, access_log=False)