diff --git a/README.md b/README.md index e649d46..bdc5a8b 100644 --- a/README.md +++ b/README.md @@ -1,16 +1,18 @@ -# ComfyUI Sequential Batcher (v1.3.1) +# ComfyUI Sequential Batcher (v1.4.0) Una suite altamente especializada de nodos personalizados para ComfyUI diseñada para el **Auto-Encolado Recursivo (Recursive Self-Queuing)** y el procesamiento secuencial autónomo. Esta arquitectura minimiza el uso de VRAM procesando tareas pesadas (como la generación de vídeo) de forma secuencial, lote por lote, orquestadas completamente desde dentro del propio grafo. > **Read in English:** [README_EN.md](README_EN.md) -## La Arquitectura "Motor de Fórmula 1" +## La Arquitectura Híbrida de Identidad -A partir de la versión 1.0.0, este repositorio ha pivotado exclusivamente hacia la arquitectura de bucles secuenciales autónomos y memoria global. Toda la deuda técnica de los antiguos nodos (lotes, secuencias, depuración) ha sido eliminada, dejando un código base limpio y fácil de mantener enfocado en los 6 fantásticos. +A partir de la versión 1.4.0, hemos dado un paso más allá implementando la **Arquitectura Híbrida de Identidad**. Toda la deuda técnica de los antiguos cargadores acoplados ha sido eliminada. Ahora, el procesamiento de video se divide en tres roles lógicos principales: -En la **v1.3.1**, hemos implementado el **"Ciclo Explorador"**. Hemos eliminado la dependencia externa del número de frames originales en el calculador, utilizando una "Evaluación Perezosa" (Lazy Evaluation). En el Ciclo 0, el calculador dispara a ciegas las intenciones del usuario mientras el cargador de vídeo intercepta el total de frames directamente del nodo VHS, calculando automáticamente y al vuelo el total de bucles para el resto de la automatización. Esto mantiene el JSON limpio para integraciones API (n8n). +1. **El Explorador (`VideoAnalyzerWithAudio`)**: Un nuevo nodo que utiliza OpenCV para escanear el vídeo de entrada (en el Ciclo 0) en busca de rostros nítidos y frontales, extrayendo también la pista de audio de forma íntegra. +2. **El Cerebro (`AutoLoopCalculator`)**: Recibe la lista de frames seguros del Explorador y planifica cortes asimétricos e inteligentes. En lugar de dividir el video matemáticamente de forma ciega, prioriza realizar cortes en frames donde el rostro es nítido, manteniendo la coherencia de identidad entre bucles. +3. **El Obrero (`VHS_LoadVideo`)**: El nodo estándar de VideoHelperSuite de ComfyUI ahora se encarga exclusivamente del trabajo pesado: extraer los tensores de vídeo exactos según las órdenes del Cerebro. -## Los 6 Nodos Principales +## Los Nodos Principales El sistema se construye alrededor de tres categorías principales: @@ -26,33 +28,35 @@ El sistema se construye alrededor de tres categorías principales: - **💾 Guardado de Keyframes (¡Nuevo en v1.1.0!):** Ahora recibe el índice actual y realiza un volcado de seguridad en el disco duro, guardando progresivamente `keyframe_XXX.png` en cada ciclo para prevenir pérdidas de datos. ### 🎞️ Video (Ensamblaje y Validación) -5. **📊 Auto Loop Calculator (`AutoLoopCalculator`)**: Es el "Cerebro" obligatorio de la máquina. En el Ciclo 0 actúa como explorador sin conocer la longitud del vídeo original. En ciclos posteriores, calcula y reparte proporcionalmente los lotes de frames (incluso cuando usas salto de frames con `select_every_nth`), evitando caídas de VRAM. Todo fluye gracias a su integración automática mediante variables fantasma. -6. **🎞️ Incremental Auto-Stitcher (`IncrementalVideoStitcher`)**: Archiva progresivamente los tensores generados en el disco duro y los ensambla de forma segura al final de todos los ciclos. - - **🧠 Cero OOM (¡Nuevo!):** Sustituye las acumulaciones en memoria por guardados temporales en disco (`.pt`), borrando la RAM de inmediato para poder procesar vídeos infinitos sin colapsar el sistema. Al desactivar `INPUT_IS_LIST`, maneja tensores puros eficientemente. - - **🎵 Passthrough de Audio (¡Nuevo!):** Alimenta directamente el audio original hacia el archivo ensamblado en el último ciclo (devolviendo `None` en los ciclos intermedios para ahorrar recursos). -7. **🎥 Load Video + Source Audio (`LoadVideoWithSourceAudio`)**: (¡Nuevo!) Este nodo **hereda directamente de la clase original de VHS (`VHS_LoadVideo`)**. Funciona exactamente igual (incluyendo validaciones, vista previa en la UI y el botón de subida), pero extrae y expone de manera segura la pista de audio original **completa** y sin recortes para asegurar que viaja inalterada a lo largo del proceso secuencial. +5. **🕵️ Video Analyzer + Audio (`VideoAnalyzerWithAudio`)**: Es el "Explorador" de la máquina. Escanea el vídeo usando OpenCV para detectar frames con rostros nítidos y extrae la pista de audio íntegra de forma pura mediante Torchaudio. +6. **📊 Auto Loop Calculator (`AutoLoopCalculator`)**: Es el "Cerebro". Recibe la información del Explorador y calcula los cortes de los frames (chunk, skip) de forma asimétrica. Si se le pasa la lista de `safe_faces_list`, forzará los cortes en fotogramas donde haya rostros reconocibles para no romper la fluidez. +7. **🎞️ Incremental Auto-Stitcher (`IncrementalVideoStitcher`)**: Archiva progresivamente los tensores generados en el disco duro y los ensambla de forma segura al final de todos los ciclos. + - **🧠 Cero OOM:** Sustituye las acumulaciones en memoria por guardados temporales en disco (`.pt`), borrando la RAM de inmediato para poder procesar vídeos infinitos sin colapsar el sistema. + - **🎵 Passthrough de Audio:** Alimenta directamente el audio original hacia el archivo ensamblado en el último ciclo (devolviendo `None` en los ciclos intermedios para ahorrar recursos). ## Configuración y Uso ### Prerrequisitos -- **VideoHelperSuite (VHS)**: **Obligatorio** para que el nodo `Load Video + Source Audio` funcione. Al heredar de su clase base, si VHS no está instalado en tu entorno de ComfyUI, este nodo no se cargará. +- **VideoHelperSuite (VHS)**: **Recomendado/Estándar** para el nodo "Obrero" de extracción (`VHS_LoadVideo`). +- **OpenCV (`opencv-python`)**: Necesario para que el Explorador (`VideoAnalyzerWithAudio`) escanee rostros nítidos. Si no está instalado, la detección de rostros se desactivará de forma segura. - **FFmpeg**: Debe estar instalado y disponible en el PATH del sistema para manejar procesos subyacentes de vídeo. -- **Torchaudio**: (Generalmente incluido en los entornos ComfyUI) es necesario para extraer la pista de audio fuente original de forma pura. +- **Torchaudio**: (Generalmente incluido en los entornos ComfyUI) es necesario para extraer la pista de audio fuente original de forma pura en el nodo Explorador. ### Instalación 1. Ve a la carpeta `custom_nodes` de ComfyUI. 2. Clona este repositorio: `git clone https://github.com/your-repo/ComfyUI-Sequential-Batcher.git` -3. Reinicia ComfyUI. +3. Instala los requerimientos adicionales si es necesario (ej. `pip install opencv-python`). +4. Reinicia ComfyUI. -### Cómo Conectar tu Nueva Máquina Autónoma -1. **El Inicio:** Añade el nodo `🏁 Loop Start (Index)` y el nodo `📊 Auto Loop Calculator`. - - El calculador ya no necesita el cable de entrada de `source_frame_count`. Solo define cuántos frames quieres por lote en `target_frames_per_loop` y el `select_every_nth`. - - Conecta la salida `current_loop_index` del `Loop Start` al calculador y a los nodos de Imagen y Video (Receiver, Sender, Stitcher). *¡No olvides conectar el Sender para el guardado de los keyframes!* - - Asegúrate de que su interruptor `reset_loop` del Loop Start está en `False`. - - Lleva las salidas `chunk_frames`, `skip_frames` y `select_every_nth` del calculador hacia tu cargador/generador de vídeo. -2. **Conectando el Audio (Opcional):** Si tu flujo tiene sonido, saca un cable de la salida de audio de tu nodo inicial (ej. `VHS_LoadVideo`) y conéctalo al puerto `audio` azul de tu `Incremental Auto-Stitcher`. -3. **El Final:** Añade el nodo `🚀 Loop Trigger (Auto-Queue)`. Crucial: Conecta la salida de imagen o audio de tu `Incremental Auto-Stitcher` en la entrada `trigger_dependency`. Esto obliga al trigger a esperar a que el vídeo se haya guardado físicamente en disco temporal antes de disparar. (Nota: gracias a la memoria global fantasma, el Trigger ya sabe cuántos bucles hacer sin necesitar cables extras). -4. **Ejecución:** **Ya no tienes que marcar la casilla "Auto Queue" nunca más.** Pulsa "Queue Prompt" **1 sola vez**. El lote 0 arranca y, al llegar al final, el nodo `Trigger` envía una señal invisible al servidor. Gracias a la Inyección Anti-Caché, la caché se destruye en cada iteración y el progreso fluye hasta completar tu vídeo perfectamente repartido. +### Cómo Conectar la Arquitectura Híbrida de Identidad +1. **El Explorador (`🕵️ Video Analyzer + Audio`)**: Coloca este nodo al principio de tu flujo. Sube tu vídeo aquí. +2. **El Cerebro (`📊 Auto Loop Calculator`)**: Conecta la salida `total_frames` del Explorador a la entrada `source_frame_count` del Cerebro. Conecta también la salida `safe_faces_list`. Conecta el `current_loop_index` desde el nodo `🏁 Loop Start`. +3. **El Obrero (`VHS_LoadVideo`)**: Haz clic derecho sobre este nodo estándar de ComfyUI y selecciona **Convert Widget to Input -> video**. + - Conecta la salida `video_name` del Explorador a la nueva entrada `video` del Obrero. + - Conecta las salidas `chunk_frames`, `skip_frames` y `select_every_nth` del Cerebro al Obrero. +4. **Conectando el Audio:** Saca un cable de la salida `source_audio` del Explorador y conéctalo directamente al puerto `audio` azul de tu `🎞️ Incremental Auto-Stitcher`. +5. **El Final:** Añade el nodo `🚀 Loop Trigger (Auto-Queue)` al final. Conecta la salida de imagen o audio de tu `Incremental Auto-Stitcher` en la entrada `trigger_dependency`. +6. **Ejecución:** Pulsa "Queue Prompt" **1 sola vez** (no marques la casilla Auto Queue). El lote 0 arranca, el Explorador analiza el vídeo una vez, pasa los cortes al Cerebro, y el Obrero ejecuta los tensores iterativamente mientras la Inyección Anti-Caché fluye ciclo tras ciclo. --- *Creado para llevar los límites de la automatización en ComfyUI un paso más allá.* \ No newline at end of file diff --git a/README_EN.md b/README_EN.md index f2a18f1..33826fe 100644 --- a/README_EN.md +++ b/README_EN.md @@ -1,16 +1,18 @@ -# ComfyUI Sequential Batcher (v1.3.1) +# ComfyUI Sequential Batcher (v1.4.0) A highly specialized suite of custom nodes for ComfyUI designed for **Recursive Self-Queuing** and autonomous sequential processing. This architecture minimizes VRAM usage by processing heavy tasks (like video generation) sequentially, batch-by-batch, orchestrated entirely from within the graph. > **Leer en Español:** [README.md](README.md) -## The "Formula 1" Engine Architecture +## The Hybrid Identity Architecture -Starting with v1.0.0, this repository has pivoted exclusively to the autonomous sequential loops and global memory architecture. All legacy technical debt (deprecated batch/sequence/debug nodes) has been pruned, leaving a clean, highly maintainable codebase focused on 6 core nodes. +Starting with version 1.4.0, we have taken a step further by implementing the **Hybrid Identity Architecture**. All technical debt from older coupled loaders has been eliminated. Now, video processing is divided into three main logical roles: -In **v1.3.1**, we implemented the **"Explorer Cycle 0"**. We eliminated the external dependency on the total original frame count in the calculator by adopting a "Lazy Evaluation". In Cycle 0, the calculator blindly fires the user's intended target, while the video loader dynamically intercepts the true frame count directly from the VHS payload, dynamically calculating the total required loops for the rest of the generation. This removes unnecessary metadata nodes and keeps JSON layouts perfectly clean for n8n API integrations. +1. **The Explorer (`VideoAnalyzerWithAudio`)**: A new node that utilizes OpenCV to scan the input video (in Cycle 0) for sharp, frontal faces, while also cleanly extracting the entire audio track. +2. **The Brain (`AutoLoopCalculator`)**: Receives the safe frames list from the Explorer and plans asymmetric, intelligent cuts. Instead of blindly dividing the video mathematically, it prioritizes making cuts on frames where the face is sharp, thereby maintaining identity coherence between loops. +3. **The Worker (`VHS_LoadVideo`)**: The standard ComfyUI VideoHelperSuite node is now solely responsible for the heavy lifting: extracting the exact video tensors according to the Brain's orders. -## The 6 Core Nodes +## The Core Nodes The system is built around three major categories: @@ -26,33 +28,35 @@ The system is built around three major categories: - **💾 Keyframe Dumping (New in v1.1.0!):** Now receives the current index and performs a safety dump to the hard drive, progressively saving `keyframe_XXX.png` every cycle to prevent data loss. ### 🎞️ Video (Assembly and Validation) -5. **📊 Auto Loop Calculator (`AutoLoopCalculator`)**: The mandatory "Brain" of the machine. In Cycle 0, it operates as an explorer without knowing the total duration of the original video. In subsequent cycles, it proportionally calculates and distributes batches of frames (even when using frame skipping with `select_every_nth`), preventing VRAM spikes. Everything flows smoothly with integration via ghost variables. -6. **🎞️ Incremental Auto-Stitcher (`IncrementalVideoStitcher`)**: Progressively archives generated tensors directly to the hard drive and safely assembles them at the end of all cycles. - - **🧠 Zero OOM (New!):** Replaces RAM accumulation with progressive temporary disk saves (`.pt`), clearing system memory immediately to enable infinite video processing without crashing the system. By disabling `INPUT_IS_LIST`, it handles raw tensors efficiently. - - **🎵 Audio Passthrough (New!):** Feeds the original pure audio straight to the assembled output during the final loop iteration (returning `None` during intermediate loops to save resources). -7. **🎥 Load Video + Source Audio (`LoadVideoWithSourceAudio`)**: (New!) This node **inherits directly from the original VHS class (`VHS_LoadVideo`)**. It functions exactly the same (including validations, UI preview widget, and upload button), but extracts and safely exposes the **complete**, uncropped original audio track to ensure it travels unaltered throughout the sequential process. +5. **🕵️ Video Analyzer + Audio (`VideoAnalyzerWithAudio`)**: The "Explorer" of the machine. Scans the video using OpenCV to detect frames with sharp faces and extracts the pure, intact audio track using Torchaudio. +6. **📊 Auto Loop Calculator (`AutoLoopCalculator`)**: The "Brain". Receives information from the Explorer and calculates frame cuts (chunk, skip) asymmetrically. If provided with a `safe_faces_list`, it forces cuts on frames with recognizable faces to maintain fluid continuity. +7. **🎞️ Incremental Auto-Stitcher (`IncrementalVideoStitcher`)**: Progressively archives generated tensors directly to the hard drive and safely assembles them at the end of all cycles. + - **🧠 Zero OOM:** Replaces RAM accumulation with progressive temporary disk saves (`.pt`), clearing system memory immediately to enable infinite video processing without crashing the system. + - **🎵 Audio Passthrough:** Feeds the original pure audio straight to the assembled output during the final loop iteration (returning `None` during intermediate loops to save resources). ## Setup & Usage ### Prerequisites -- **VideoHelperSuite (VHS)**: **Mandatory** for the `Load Video + Source Audio` node to function. Since it inherits from its base class, if VHS is not installed in your ComfyUI environment, this node will not load. +- **VideoHelperSuite (VHS)**: **Recommended/Standard** for the "Worker" extraction node (`VHS_LoadVideo`). +- **OpenCV (`opencv-python`)**: Required for the Explorer (`VideoAnalyzerWithAudio`) to scan for sharp faces. If not installed, face detection will safely be disabled. - **FFmpeg**: Must be installed and available in your system's PATH to manage underlying video operations. -- **Torchaudio**: (Usually included in ComfyUI environments) is required to extract the original pure audio track from the source. +- **Torchaudio**: (Usually included in ComfyUI environments) is required for the Explorer node to extract the original pure audio track from the source. ### Installation 1. Navigate to your ComfyUI `custom_nodes` folder. 2. Clone this repository: `git clone https://github.com/your-repo/ComfyUI-Sequential-Batcher.git` -3. Restart ComfyUI. +3. Install the required dependencies if necessary (e.g., `pip install opencv-python`). +4. Restart ComfyUI. -### How to use the Autonomous Machine -1. **The Start:** Add the `🏁 Loop Start (Index)` and the `📊 Auto Loop Calculator` nodes. - - The calculator no longer requires the `source_frame_count` input. Simply define how many frames you want per loop in `target_frames_per_loop` and the `select_every_nth`. - - Connect the `current_loop_index` output of `Loop Start` to the calculator, and to your Image and Video nodes (Receiver, Sender, Stitcher). *Don't forget the Sender for keyframe saving!* - - Ensure the `reset_loop` toggle on the Loop Start is set to `False`. - - Wire the `chunk_frames`, `skip_frames`, and `select_every_nth` outputs from the calculator into your video loader/generator. -2. **Connecting Audio (Optional):** If your workflow has sound, pull a cable from your initial node's audio output (e.g., `VHS_LoadVideo`) and connect it to the blue `audio` port on your `Incremental Auto-Stitcher`. -3. **The End:** Add the `🚀 Loop Trigger (Auto-Queue)` node. Crucially, connect the image or audio output from your `Incremental Auto-Stitcher` into the `trigger_dependency` input. This forces the trigger to wait until the video is physically saved to the temporary disk before firing. (Note: thanks to the global ghost memory, the Trigger already knows how many loops to execute without needing extra cables). -4. **Execution:** **You no longer need to check "Auto Queue".** Just press "Queue Prompt" **once**. Batch 0 starts, and upon finishing, the trigger invisibly signals the server. Thanks to Anti-Cache Injection, cache is destroyed on every iteration, and progress flows until your video is perfectly distributed and complete. +### How to Connect the Hybrid Identity Architecture +1. **The Explorer (`🕵️ Video Analyzer + Audio`)**: Place this node at the very beginning of your workflow. Upload your video here. +2. **The Brain (`📊 Auto Loop Calculator`)**: Connect the `total_frames` output from the Explorer to the `source_frame_count` input of the Brain. Connect the `safe_faces_list` as well. Connect the `current_loop_index` from the `🏁 Loop Start` node. +3. **The Worker (`VHS_LoadVideo`)**: Right-click on this standard ComfyUI node and select **Convert Widget to Input -> video**. + - Connect the `video_name` output from the Explorer to the new `video` input on the Worker. + - Connect the `chunk_frames`, `skip_frames`, and `select_every_nth` outputs from the Brain to the Worker. +4. **Connecting Audio:** Pull a cable from the `source_audio` output of the Explorer and connect it directly to the blue `audio` port on your `🎞️ Incremental Auto-Stitcher`. +5. **The End:** Add the `🚀 Loop Trigger (Auto-Queue)` node at the end. Connect the image or audio output from your `Incremental Auto-Stitcher` into the `trigger_dependency` input. +6. **Execution:** Press "Queue Prompt" **once** (do not check Auto Queue). Batch 0 begins, the Explorer analyzes the video once, passes the cuts to the Brain, and the Worker iteratively extracts the tensors as the Anti-Cache Injection drives each successive cycle. --- *Created to push the boundaries of ComfyUI automation.* \ No newline at end of file