Upload 12 files
Browse files- Dockerfile +127 -0
- LICENSE +25 -0
- NOTICE.md +76 -0
- README.md +208 -6
- app.py +194 -0
- builder.sh +346 -0
- compose.yaml +39 -0
- entrypoint.sh +44 -0
- info.sh +154 -0
- requirements.txt +60 -0
- setup.py +174 -0
- start.sh +88 -0
Dockerfile
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# =============================================================================
|
| 2 |
+
# ADUC-SDR Video Suite — Dockerfile Otimizado
|
| 3 |
+
# Preserva a estrutura de instalação original para alta performance.
|
| 4 |
+
# CUDA 12.8 | PyTorch 2.8.0+cu128 | Ubuntu 22.04
|
| 5 |
+
# =============================================================================
|
| 6 |
+
FROM nvidia/cuda:12.8.0-devel-ubuntu22.04
|
| 7 |
+
|
| 8 |
+
LABEL maintainer="Carlos Rodrigues dos Santos"
|
| 9 |
+
LABEL description="ADUC-SDR: High-performance Diffusers stack for 8x NVIDIA L40S with LTX-Video and SeedVR"
|
| 10 |
+
LABEL version="5.0.0"
|
| 11 |
+
LABEL cuda_version="12.8.0"
|
| 12 |
+
LABEL python_version="3.10"
|
| 13 |
+
LABEL pytorch_version="2.8.0+cu128"
|
| 14 |
+
LABEL gpu_optimized_for="8x_NVIDIA_L40S"
|
| 15 |
+
|
| 16 |
+
# =============================================================================
|
| 17 |
+
# 1. Variáveis de Ambiente e Configuração de Paths
|
| 18 |
+
# =============================================================================
|
| 19 |
+
ENV DEBIAN_FRONTEND=noninteractive TZ=UTC LANG=C.UTF-8 LC_ALL=C.UTF-8 \
|
| 20 |
+
PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1 \
|
| 21 |
+
PIP_NO_CACHE_DIR=0 PIP_DISABLE_PIP_VERSION_CHECK=1
|
| 22 |
+
|
| 23 |
+
# --- Configurações de GPU e Computação ---
|
| 24 |
+
ENV NVIDIA_VISIBLE_DEVICES=all \
|
| 25 |
+
TORCH_CUDA_ARCH_LIST="8.9" \
|
| 26 |
+
CUDA_DEVICE_ORDER=PCI_BUS_ID \
|
| 27 |
+
CUDA_DEVICE_MAX_CONNECTIONS=32
|
| 28 |
+
|
| 29 |
+
# --- Configurações de Threads ---
|
| 30 |
+
ENV OMP_NUM_THREADS=8 MKL_NUM_THREADS=8 MAX_JOBS=160
|
| 31 |
+
|
| 32 |
+
# --- Configurações de Alocador de Memória e Caches de GPU ---
|
| 33 |
+
ENV PYTORCH_CUDA_ALLOC_CONF=max_split_size_mb:512,garbage_collection_threshold:0.8 \
|
| 34 |
+
CUDA_LAUNCH_BLOCKING=0 CUDA_CACHE_MAXSIZE=2147483648 CUDA_CACHE_DISABLE=0
|
| 35 |
+
|
| 36 |
+
# --- Paths da Aplicação e Dados Persistentes ---
|
| 37 |
+
ENV APP_HOME=/app \
|
| 38 |
+
HF_HOME=/data/.cache/huggingface \
|
| 39 |
+
TORCH_HOME=/data/.cache/torch \
|
| 40 |
+
HF_DATASETS_CACHE=/data/.cache/datasets \
|
| 41 |
+
TRANSFORMERS_CACHE=/data/.cache/transformers \
|
| 42 |
+
DIFFUSERS_CACHE=/data/.cache/diffusers \
|
| 43 |
+
HF_HUB_ENABLE_HF_TRANSFER=1 \
|
| 44 |
+
TOKENIZERS_PARALLELISM=false
|
| 45 |
+
|
| 46 |
+
WORKDIR $APP_HOME
|
| 47 |
+
|
| 48 |
+
# =============================================================================
|
| 49 |
+
# 2. Setup de Usuário e Sistema
|
| 50 |
+
# =============================================================================
|
| 51 |
+
# Cria usuário não-root e diretórios de dados/app.
|
| 52 |
+
# As permissões finais serão aplicadas no final.
|
| 53 |
+
RUN useradd -m -u 1000 -s /bin/bash appuser && \
|
| 54 |
+
mkdir -p /data $APP_HOME /app/output
|
| 55 |
+
|
| 56 |
+
# --- Instalação de Pacotes de Sistema e Python ---
|
| 57 |
+
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 58 |
+
build-essential gosu tree cmake git git-lfs curl wget ffmpeg ninja-build \
|
| 59 |
+
python3.10 python3.10-dev python3.10-distutils python3-pip \
|
| 60 |
+
ca-certificates libglib2.0-0 libgl1 \
|
| 61 |
+
&& apt-get clean && rm -rf /var/lib/apt/lists/*
|
| 62 |
+
|
| 63 |
+
RUN ln -sf /usr/bin/python3.10 /usr/bin/python && \
|
| 64 |
+
python3 -m pip install --upgrade pip
|
| 65 |
+
|
| 66 |
+
# =============================================================================
|
| 67 |
+
# 3. Instalação da Toolchain de Machine Learning (Mantida 100% Original)
|
| 68 |
+
# =============================================================================
|
| 69 |
+
|
| 70 |
+
# --- PyTorch para CUDA 12.8 ---
|
| 71 |
+
RUN pip install --index-url https://download.pytorch.org/whl/cu128 \
|
| 72 |
+
torch>=2.8.0+cu128 torchvision>=0.23.0+cu128 torchaudio>=2.8.0+cu128
|
| 73 |
+
|
| 74 |
+
# --- Ferramentas de Compilação, Triton e FlashAttention ---
|
| 75 |
+
RUN pip install packaging ninja cmake pybind11 scikit-build cython hf_transfer "numpy>=1.24.4"
|
| 76 |
+
|
| 77 |
+
# --- Triton 3.x ---
|
| 78 |
+
RUN pip uninstall -y triton || true && \
|
| 79 |
+
pip install -v --no-build-isolation triton==3.4.0
|
| 80 |
+
|
| 81 |
+
# --- FlashAttention 2.8.x ---
|
| 82 |
+
|
| 83 |
+
# =============================================================================
|
| 84 |
+
# 4. Instalação das Dependências da Aplicação
|
| 85 |
+
# =============================================================================
|
| 86 |
+
# Copia e instala requirements.txt primeiro para otimizar o cache de camadas do Docker.
|
| 87 |
+
COPY --chown=appuser:appuser requirements.txt ./requirements.txt
|
| 88 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 89 |
+
|
| 90 |
+
# --- Instalação de bitsandbytes e Wheels Customizados (Mantido 100% Original) ---
|
| 91 |
+
RUN pip install --upgrade bitsandbytes
|
| 92 |
+
|
| 93 |
+
# Instala wheels customizados (Apex, etc.)
|
| 94 |
+
# Instala q8_kernels
|
| 95 |
+
RUN pip install --no-cache-dir \
|
| 96 |
+
"https://huggingface.co/euIaxs22/Aduc-sdr/resolve/main/q8_kernels-0.0.5-cp310-cp310-linux_x86_64.whl"
|
| 97 |
+
|
| 98 |
+
RUN echo "Installing custom wheels..." && \
|
| 99 |
+
pip install --no-cache-dir \
|
| 100 |
+
"https://huggingface.co/euIaxs22/Aduc-sdr/resolve/main/apex-0.1-cp310-cp310-linux_x86_64.whl" \
|
| 101 |
+
"https://huggingface.co/euIaxs22/Aduc-sdr/resolve/main/dropout_layer_norm-0.1-cp310-cp310-linux_x86_64.whl"
|
| 102 |
+
|
| 103 |
+
# =============================================================================
|
| 104 |
+
# 5. Cópia do Código-Fonte e Configuração Final
|
| 105 |
+
# =============================================================================
|
| 106 |
+
# Copia o restante do código-fonte da aplicação por último.
|
| 107 |
+
COPY --chown=appuser:appuser . .
|
| 108 |
+
|
| 109 |
+
# Garante que todos os scripts de inicialização sejam executáveis
|
| 110 |
+
# e que o usuário 'appuser' seja o dono de todos os arquivos.
|
| 111 |
+
RUN chown -R appuser:appuser $APP_HOME /data && \
|
| 112 |
+
chmod +x /app/entrypoint.sh /app/start.sh /app/info.sh /app/builder.sh
|
| 113 |
+
|
| 114 |
+
# =============================================================================
|
| 115 |
+
# 6. Ponto de Entrada
|
| 116 |
+
# =============================================================================
|
| 117 |
+
# Expõe o diretório /data para ser montado como um volume persistente.
|
| 118 |
+
VOLUME /data
|
| 119 |
+
|
| 120 |
+
# Define o usuário padrão para a execução do contêiner.
|
| 121 |
+
USER appuser
|
| 122 |
+
|
| 123 |
+
# Define o script que será executado na inicialização do contêiner.
|
| 124 |
+
ENTRYPOINT ["/app/entrypoint.sh"]
|
| 125 |
+
|
| 126 |
+
# Define o comando padrão a ser executado pelo entrypoint.
|
| 127 |
+
CMD ["/app/start.sh"]
|
LICENSE
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Euia-AducSdr: Uma implementação aberta e funcional da arquitetura ADUC-SDR para geração de vídeo coerente.
|
| 2 |
+
# Copyright (C) 4 de Agosto de 2025 Carlos Rodrigues dos Santos
|
| 3 |
+
#
|
| 4 |
+
# Contato:
|
| 5 |
+
# Carlos Rodrigues dos Santos
|
| 6 | |
| 7 |
+
# Rua Eduardo Carlos Pereira, 4125, B1 Ap32, Curitiba, PR, Brazil, CEP 8102025
|
| 8 |
+
#
|
| 9 |
+
# Repositórios e Projetos Relacionados:
|
| 10 |
+
# GitHub: https://github.com/carlex22/Aduc-sdr
|
| 11 |
+
# Hugging Face (Ltx-SuperTime-60Secondos): https://huggingface.co/spaces/Carlexx/Ltx-SuperTime-60Secondos/
|
| 12 |
+
# Hugging Face (Novinho): https://huggingface.co/spaces/Carlexxx/Novinho/
|
| 13 |
+
#
|
| 14 |
+
# This program is free software: you can redistribute it and/or modify
|
| 15 |
+
# it under the terms of the GNU Affero General Public License as published by
|
| 16 |
+
# the Free Software Foundation, either version 3 of the License, or
|
| 17 |
+
# (at your option) any later version.
|
| 18 |
+
#
|
| 19 |
+
# This program is distributed in the hope that it will be useful,
|
| 20 |
+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
| 21 |
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
| 22 |
+
# GNU Affero General Public License for more details.
|
| 23 |
+
#
|
| 24 |
+
# You should have received a copy of the GNU Affero General Public License
|
| 25 |
+
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
NOTICE.md
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# NOTICE
|
| 2 |
+
|
| 3 |
+
Copyright (C) 2025 Carlos Rodrigues dos Santos. All rights reserved.
|
| 4 |
+
|
| 5 |
+
---
|
| 6 |
+
|
| 7 |
+
## Aviso de Propriedade Intelectual e Licenciamento
|
| 8 |
+
|
| 9 |
+
### **Processo de Patenteamento em Andamento (EM PORTUGUÊS):**
|
| 10 |
+
|
| 11 |
+
O método e o sistema de orquestração de prompts denominados **ADUC (Automated Discovery and Orchestration of Complex tasks)**, conforme descritos neste documento e implementados neste software, estão atualmente em processo de patenteamento.
|
| 12 |
+
|
| 13 |
+
O titular dos direitos, Carlos Rodrigues dos Santos, está buscando proteção legal para as inovações chave da arquitetura ADUC, incluindo, mas não se limitando a:
|
| 14 |
+
|
| 15 |
+
* Fragmentação e escalonamento de solicitações que excedem limites de contexto de modelos de IA.
|
| 16 |
+
* Distribuição inteligente de sub-tarefas para especialistas heterogêneos.
|
| 17 |
+
* Gerenciamento de estado persistido com avaliação iterativa e realimentação para o planejamento de próximas etapas.
|
| 18 |
+
* Planejamento e roteamento sensível a custo, latência e requisitos de qualidade.
|
| 19 |
+
* O uso de "tokens universais" para comunicação agnóstica a modelos.
|
| 20 |
+
|
| 21 |
+
### **Reconhecimento e Implicações (EM PORTUGUÊS):**
|
| 22 |
+
|
| 23 |
+
Ao acessar ou utilizar este software e a arquitetura ADUC aqui implementada, você reconhece:
|
| 24 |
+
|
| 25 |
+
1. A natureza inovadora e a importância da arquitetura ADUC no campo da orquestração de prompts para IA.
|
| 26 |
+
2. Que a essência desta arquitetura, ou suas implementações derivadas, podem estar sujeitas a direitos de propriedade intelectual, incluindo patentes.
|
| 27 |
+
3. Que o uso comercial, a reprodução da lógica central da ADUC em sistemas independentes, ou a exploração direta da invenção sem o devido licenciamento podem infringir os direitos de patente pendente.
|
| 28 |
+
|
| 29 |
+
---
|
| 30 |
+
|
| 31 |
+
### **Patent Pending (IN ENGLISH):**
|
| 32 |
+
|
| 33 |
+
The method and system for prompt orchestration named **ADUC (Automated Discovery and Orchestration of Complex tasks)**, as described herein and implemented in this software, are currently in the process of being patented.
|
| 34 |
+
|
| 35 |
+
The rights holder, Carlos Rodrigues dos Santos, is seeking legal protection for the key innovations of the ADUC architecture, including, but not limited to:
|
| 36 |
+
|
| 37 |
+
* Fragmentation and scaling of requests exceeding AI model context limits.
|
| 38 |
+
* Intelligent distribution of sub-tasks to heterogeneous specialists.
|
| 39 |
+
* Persistent state management with iterative evaluation and feedback for planning subsequent steps.
|
| 40 |
+
* Cost, latency, and quality-aware planning and routing.
|
| 41 |
+
* The use of "universal tokens" for model-agnostic communication.
|
| 42 |
+
|
| 43 |
+
### **Acknowledgement and Implications (IN ENGLISH):**
|
| 44 |
+
|
| 45 |
+
By accessing or using this software and the ADUC architecture implemented herein, you acknowledge:
|
| 46 |
+
|
| 47 |
+
1. The innovative nature and significance of the ADUC architecture in the field of AI prompt orchestration.
|
| 48 |
+
2. That the essence of this architecture, or its derivative implementations, may be subject to intellectual property rights, including patents.
|
| 49 |
+
3. That commercial use, reproduction of ADUC's core logic in independent systems, or direct exploitation of the invention without proper licensing may infringe upon pending patent rights.
|
| 50 |
+
|
| 51 |
+
---
|
| 52 |
+
|
| 53 |
+
## Licença AGPLv3
|
| 54 |
+
|
| 55 |
+
This program is free software: you can redistribute it and/or modify
|
| 56 |
+
it under the terms of the GNU Affero General Public License as published by
|
| 57 |
+
the Free Software Foundation, either version 3 of the License, or
|
| 58 |
+
(at your option) any later version.
|
| 59 |
+
|
| 60 |
+
This program is distributed in the hope that it will be useful,
|
| 61 |
+
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
| 62 |
+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
| 63 |
+
GNU Affero General Public License for more details.
|
| 64 |
+
|
| 65 |
+
You should have received a copy of the GNU Affero General Public License
|
| 66 |
+
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
| 67 |
+
|
| 68 |
+
---
|
| 69 |
+
|
| 70 |
+
**Contato para Consultas:**
|
| 71 |
+
|
| 72 |
+
Para mais informações sobre a arquitetura ADUC, o status do patenteamento, ou para discutir licenciamento para usos comerciais ou não conformes com a AGPLv3, por favor, entre em contato:
|
| 73 |
+
|
| 74 |
+
Carlos Rodrigues dos Santos
|
| 75 | |
| 76 |
+
Rua Eduardo Carlos Pereira, 4125, B1 Ap32, Curitiba, PR, Brazil, CEP 8102025
|
README.md
CHANGED
|
@@ -1,10 +1,212 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: docker
|
| 7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
---
|
| 9 |
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: Euia-AducSdr
|
| 3 |
+
emoji: 🎥
|
| 4 |
+
colorFrom: indigo
|
| 5 |
+
colorTo: purple
|
| 6 |
sdk: docker
|
| 7 |
+
app_file: app.py
|
| 8 |
+
pinned: true
|
| 9 |
+
license: agpl-3.0
|
| 10 |
+
setup_file: setup.sh
|
| 11 |
+
short_description: Uma implementação aberta e funcional da arquitetura ADUC-SDR
|
| 12 |
---
|
| 13 |
|
| 14 |
+
|
| 15 |
+
### 🇧🇷 Português
|
| 16 |
+
|
| 17 |
+
Uma implementação aberta e funcional da arquitetura ADUC-SDR (Arquitetura de Unificação Compositiva - Escala Dinâmica e Resiliente), projetada para a geração de vídeo coerente de longa duração. Este projeto materializa os princípios de fragmentação, navegação geométrica e um mecanismo de "eco causal 4bits memoria" para garantir a continuidade física e narrativa em sequências de vídeo geradas por múltiplos modelos de IA.
|
| 18 |
+
|
| 19 |
+
**Licença:** Este projeto é licenciado sob os termos da **GNU Affero General Public License v3.0**. Isto significa que se você usar este software (ou qualquer trabalho derivado) para fornecer um serviço através de uma rede, você é **obrigado a disponibilizar o código-fonte completo** da sua versão para os usuários desse serviço.
|
| 20 |
+
|
| 21 |
+
- **Copyright (C) 4 de Agosto de 2025, Carlos Rodrigues dos Santos**
|
| 22 |
+
- Uma cópia completa da licença pode ser encontrada no arquivo [LICENSE](LICENSE).
|
| 23 |
+
|
| 24 |
+
---
|
| 25 |
+
|
| 26 |
+
### 🇬🇧 English
|
| 27 |
+
|
| 28 |
+
An open and functional implementation of the ADUC-SDR (Architecture for Compositive Unification - Dynamic and Resilient Scaling) architecture, designed for long-form coherent video generation. This project materializes the principles of fragmentation, geometric navigation, and a "causal echo 4bits memori" mechanism to ensure physical and narrative continuity in video sequences generated by multiple AI models.
|
| 29 |
+
|
| 30 |
+
**License:** This project is licensed under the terms of the **GNU Affero General Public License v3.0**. This means that if you use this software (or any derivative work) to provide a service over a network, you are **required to make the complete source code** of your version available to the users of that service.
|
| 31 |
+
|
| 32 |
+
- **Copyright (C) August 4, 2025, Carlos Rodrigues dos Santos**
|
| 33 |
+
- A full copy of the license can be found in the [LICENSE](LICENSE) file.
|
| 34 |
+
|
| 35 |
+
---
|
| 36 |
+
|
| 37 |
+
## **Aviso de Propriedade Intelectual e Patenteamento**
|
| 38 |
+
|
| 39 |
+
### **Processo de Patenteamento em Andamento (EM PORTUGUÊS):**
|
| 40 |
+
|
| 41 |
+
A arquitetura e o método **ADUC (Automated Discovery and Orchestration of Complex tasks)**, conforme descritos neste projeto e nas reivindicações associadas, estão **atualmente em processo de patenteamento**.
|
| 42 |
+
|
| 43 |
+
O titular dos direitos, Carlos Rodrigues dos Santos, está buscando proteção legal para as inovações chave da arquitetura ADUC, que incluem, mas não se limitam a:
|
| 44 |
+
|
| 45 |
+
* Fragmentação e escalonamento de solicitações que excedem limites de contexto de modelos de IA.
|
| 46 |
+
* Distribuição inteligente de sub-tarefas para especialistas heterogêneos.
|
| 47 |
+
* Gerenciamento de estado persistido com avaliação iterativa e realimentação para o planejamento de próximas etapas.
|
| 48 |
+
* Planejamento e roteamento sensível a custo, latência e requisitos de qualidade.
|
| 49 |
+
* O uso de "tokens universais" para comunicação agnóstica a modelos.
|
| 50 |
+
|
| 51 |
+
Ao utilizar este software e a arquitetura ADUC aqui implementada, você reconhece a natureza inovadora desta arquitetura e que a **reprodução ou exploração da lógica central da ADUC em sistemas independentes pode infringir direitos de patente pendente.**
|
| 52 |
+
|
| 53 |
+
---
|
| 54 |
+
|
| 55 |
+
### **Patent Pending (IN ENGLISH):**
|
| 56 |
+
|
| 57 |
+
The **ADUC (Automated Discovery and Orchestration of Complex tasks)** architecture and method, as described in this project and its associated claims, are **currently in the process of being patented.**
|
| 58 |
+
|
| 59 |
+
The rights holder, Carlos Rodrigues dos Santos, is seeking legal protection for the key innovations of the ADUC architecture, including, but not limited to:
|
| 60 |
+
|
| 61 |
+
* Fragmentation and scaling of requests exceeding AI model context limits.
|
| 62 |
+
* Intelligent distribution of sub-tasks to heterogeneous specialists.
|
| 63 |
+
* Persistent state management with iterative evaluation and feedback for planning subsequent steps.
|
| 64 |
+
* Cost, latency, and quality-aware planning and routing.
|
| 65 |
+
* The use of "universal tokens" for model-agnostic communication.
|
| 66 |
+
|
| 67 |
+
By using this software and the ADUC architecture implemented herein, you acknowledge the innovative nature of this architecture and that **the reproduction or exploitation of ADUC's core logic in independent systems may infringe upon pending patent rights.**
|
| 68 |
+
|
| 69 |
+
---
|
| 70 |
+
|
| 71 |
+
### Detalhes Técnicos e Reivindicações da ADUC
|
| 72 |
+
|
| 73 |
+
#### 🇧🇷 Definição Curta (para Tese e Patente)
|
| 74 |
+
|
| 75 |
+
**ADUC** é um *framework pré-input* e *intermediário* de **gerenciamento de prompts** que:
|
| 76 |
+
|
| 77 |
+
1. **fragmenta** solicitações acima do limite de contexto de qualquer modelo,
|
| 78 |
+
2. **escala linearmente** (processo sequencial com memória persistida),
|
| 79 |
+
3. **distribui** sub-tarefas a **especialistas** (modelos/ferramentas heterogêneos), e
|
| 80 |
+
4. **realimenta** a próxima etapa com avaliação do que foi feito/esperado (LLM diretor).
|
| 81 |
+
|
| 82 |
+
Não é um modelo; é uma **camada orquestradora** plugável antes do input de modelos existentes (texto, imagem, áudio, vídeo), usando *tokens universais* e a tecnologia atual.
|
| 83 |
+
|
| 84 |
+
#### 🇬🇧 Short Definition (for Thesis and Patent)
|
| 85 |
+
|
| 86 |
+
**ADUC** is a *pre-input* and *intermediate* **prompt management framework** that:
|
| 87 |
+
|
| 88 |
+
1. **fragments** requests exceeding any model's context limit,
|
| 89 |
+
2. **scales linearly** (sequential process with persisted memory),
|
| 90 |
+
3. **distributes** sub-tasks to **specialists** (heterogeneous models/tools), and
|
| 91 |
+
4. **feeds back** to the next step with an evaluation of what was done/expected (director LLM).
|
| 92 |
+
|
| 93 |
+
It is not a model; it is a pluggable **orchestration layer** before the input of existing models (text, image, audio, video), using *universal tokens* and current technology.
|
| 94 |
+
|
| 95 |
+
---
|
| 96 |
+
|
| 97 |
+
#### 🇧🇷 Elementos Essenciais (Telegráfico)
|
| 98 |
+
|
| 99 |
+
* **Agnóstico a modelos:** opera com qualquer LLM/difusor/API.
|
| 100 |
+
* **Pré-input manager:** recebe pedido do usuário, **divide** em blocos ≤ limite de tokens, **prioriza**, **agenda** e **roteia**.
|
| 101 |
+
* **Memória persistida:** resultados/latentes/“eco” viram **estado compartilhado** para o próximo bloco (nada é ignorado).
|
| 102 |
+
* **Especialistas:** *routers* decidem quem faz o quê (ex.: “descrição → LLM-A”, “keyframe → Img-B”, “vídeo → Vid-C”).
|
| 103 |
+
* **Controle de qualidade:** LLM diretor compara *o que fez* × *o que deveria* × *o que falta* e **regenera objetivos** do próximo fragmento.
|
| 104 |
+
* **Custo/latência-aware:** planeja pela **VRAM/tempo/custo**, não tenta “abraçar tudo de uma vez”.
|
| 105 |
+
|
| 106 |
+
#### 🇬🇧 Essential Elements (Telegraphic)
|
| 107 |
+
|
| 108 |
+
* **Model-agnostic:** operates with any LLM/diffuser/API.
|
| 109 |
+
* **Pre-input manager:** receives user request, **divides** into blocks ≤ token limit, **prioritizes**, **schedules**, and **routes**.
|
| 110 |
+
* **Persisted memory:** results/latents/“echo” become **shared state** for the next block (nothing is ignored).
|
| 111 |
+
* **Specialists:** *routers* decide who does what (e.g., “description → LLM-A”, “keyframe → Img-B”, “video → Vid-C”).
|
| 112 |
+
* **Quality control:** director LLM compares *what was done* × *what should be done* × *what is missing* and **regenerates objectives** for the next fragment.
|
| 113 |
+
* **Cost/latency-aware:** plans by **VRAM/time/cost**, does not try to “embrace everything at once”.
|
| 114 |
+
|
| 115 |
+
---
|
| 116 |
+
|
| 117 |
+
#### 🇧🇷 Reivindicações Independentes (Método e Sistema)
|
| 118 |
+
|
| 119 |
+
**Reivindicação Independente (Método) — Versão Enxuta:**
|
| 120 |
+
|
| 121 |
+
1. **Método** de **orquestração de prompts** para execução de tarefas acima do limite de contexto de modelos de IA, compreendendo:
|
| 122 |
+
(a) **receber** uma solicitação que excede um limite de tokens;
|
| 123 |
+
(b) **analisar** a solicitação por um **LLM diretor** e **fragmentá-la** em sub-tarefas ≤ limite;
|
| 124 |
+
(c) **selecionar** especialistas de execução para cada sub-tarefa com base em capacidades declaradas;
|
| 125 |
+
(d) **gerar** prompts específicos por sub-tarefa em **tokens universais**, incluindo referências ao **estado persistido** de execuções anteriores;
|
| 126 |
+
(e) **executar sequencialmente** as sub-tarefas e **persistir** suas saídas como memória (incluindo latentes/eco/artefatos);
|
| 127 |
+
(f) **avaliar** automaticamente a saída versus metas declaradas e **regenerar objetivos** do próximo fragmento;
|
| 128 |
+
(g) **iterar** (b)–(f) até que os critérios de completude sejam atendidos, produzindo o resultado agregado;
|
| 129 |
+
em que o framework **escala linearmente** no tempo e armazenamento físico, **independente** da janela de contexto dos modelos subjacentes.
|
| 130 |
+
|
| 131 |
+
**Reivindicação Independente (Sistema):**
|
| 132 |
+
|
| 133 |
+
2. **Sistema** de orquestração de prompts, compreendendo: um **planejador LLM diretor**; um **roteador de especialistas**; um **banco de estado persistido** (incl. memória cinética para vídeo); um **gerador de prompts universais**; e um **módulo de avaliação/realimentação**, acoplados por uma **API pré-input** a modelos heterogêneos.
|
| 134 |
+
|
| 135 |
+
#### 🇬🇧 Independent Claims (Method and System)
|
| 136 |
+
|
| 137 |
+
**Independent Claim (Method) — Concise Version:**
|
| 138 |
+
|
| 139 |
+
1. A **method** for **prompt orchestration** for executing tasks exceeding AI model context limits, comprising:
|
| 140 |
+
(a) **receiving** a request that exceeds a token limit;
|
| 141 |
+
(b) **analyzing** the request by a **director LLM** and **fragmenting it** into sub-tasks ≤ the limit;
|
| 142 |
+
(c) **selecting** execution specialists for each sub-task based on declared capabilities;
|
| 143 |
+
(d) **generating** specific prompts per sub-task in **universal tokens**, including references to the **persisted state** of previous executions;
|
| 144 |
+
(e) **sequentially executing** the sub-tasks and **persisting** their outputs as memory (including latents/echo/artifacts);
|
| 145 |
+
(f) **automatically evaluating** the output against declared goals and **regenerating objectives** for the next fragment;
|
| 146 |
+
(g) **iterating** (b)–(f) until completion criteria are met, producing the aggregated result;
|
| 147 |
+
wherein the framework **scales linearly** in time and physical storage, **independent** of the context window of the underlying models.
|
| 148 |
+
|
| 149 |
+
**Independent Claim (System):**
|
| 150 |
+
|
| 151 |
+
2. A prompt orchestration **system**, comprising: a **director LLM planner**; a **specialist router**; a **persisted state bank** (incl. kinetic memory for video); a **universal prompt generator**; and an **evaluation/feedback module**, coupled via a **pre-input API** to heterogeneous models.
|
| 152 |
+
|
| 153 |
+
---
|
| 154 |
+
|
| 155 |
+
#### 🇧🇷 Dependentes Úteis
|
| 156 |
+
|
| 157 |
+
* (3) Onde o roteamento considera **custo/latência/VRAM** e metas de qualidade.
|
| 158 |
+
* (4) Onde o banco de estado inclui **eco cinético** para vídeo (últimos *n* frames/latentes/fluxo).
|
| 159 |
+
* (5) Onde a avaliação usa métricas específicas por domínio (Lflow, consistência semântica, etc.).
|
| 160 |
+
* (6) Onde *tokens universais* padronizam instruções entre especialistas.
|
| 161 |
+
* (7) Onde a orquestração decide **cut vs continuous** e **corte regenerativo** (Déjà-Vu) ao editar vídeo.
|
| 162 |
+
* (8) Onde o sistema **nunca descarta** conteúdo excedente: **reagenda** em novos fragmentos.
|
| 163 |
+
|
| 164 |
+
#### 🇬🇧 Useful Dependents
|
| 165 |
+
|
| 166 |
+
* (3) Wherein routing considers **cost/latency/VRAM** and quality goals.
|
| 167 |
+
* (4) Wherein the state bank includes **kinetic echo** for video (last *n* frames/latents/flow).
|
| 168 |
+
* (5) Wherein evaluation uses domain-specific metrics (Lflow, semantic consistency, etc.).
|
| 169 |
+
* (6) Wherein *universal tokens* standardize instructions between specialists.
|
| 170 |
+
* (7) Wherein orchestration decides **cut vs continuous** and **regenerative cut** (Déjà-Vu) when editing video.
|
| 171 |
+
* (8) Wherein the system **never discards** excess content: it **reschedules** it in new fragments.
|
| 172 |
+
|
| 173 |
+
---
|
| 174 |
+
|
| 175 |
+
#### 🇧🇷 Como isso conversa com SDR (Vídeo)
|
| 176 |
+
|
| 177 |
+
* **Eco Cinético**: é um **tipo de estado persistido** consumido pelo próximo passo.
|
| 178 |
+
* **Déjà-Vu (Corte Regenerativo)**: é **uma política de orquestração** aplicada quando há edição; ADUC decide, monta os prompts certos e chama o especialista de vídeo.
|
| 179 |
+
* **Cut vs Continuous**: decisão do **diretor** com base em estado + metas; ADUC roteia e garante a sobreposição/remoção final.
|
| 180 |
+
|
| 181 |
+
#### 🇬🇧 How this Converses with SDR (Video)
|
| 182 |
+
|
| 183 |
+
* **Kinetic Echo**: is a **type of persisted state** consumed by the next step.
|
| 184 |
+
* **Déjà-Vu (Regenerative Cut)**: is an **orchestration policy** applied during editing; ADUC decides, crafts the right prompts, and calls the video specialist.
|
| 185 |
+
* **Cut vs Continuous**: decision made by the **director** based on state + goals; ADUC routes and ensures the final overlap/removal.
|
| 186 |
+
|
| 187 |
+
---
|
| 188 |
+
|
| 189 |
+
#### 🇧🇷 Mensagem Clara ao Usuário (Experiência)
|
| 190 |
+
|
| 191 |
+
> “Seu pedido excede o limite X do modelo Y. Em vez de truncar silenciosamente, o **ADUC** dividirá e **entregará 100%** do conteúdo por etapas coordenadas.”
|
| 192 |
+
|
| 193 |
+
Isso é diferencial prático e jurídico: **não-obviedade** por transformar limite de contexto em **pipeline controlado**, com **persistência de estado** e **avaliação iterativa**.
|
| 194 |
+
|
| 195 |
+
#### 🇬🇧 Clear User Message (Experience)
|
| 196 |
+
|
| 197 |
+
> "Your request exceeds model Y's limit X. Instead of silently truncating, **ADUC** will divide and **deliver 100%** of the content through coordinated steps."
|
| 198 |
+
|
| 199 |
+
This is a practical and legal differentiator: **non-obviousness** by transforming context limits into a **controlled pipeline**, with **state persistence** and **iterative evaluation**.
|
| 200 |
+
|
| 201 |
+
---
|
| 202 |
+
|
| 203 |
+
### Contact / Contato / Contacto
|
| 204 |
+
|
| 205 |
+
- **Author / Autor:** Carlos Rodrigues dos Santos
|
| 206 |
+
- **Email:** [email protected]
|
| 207 |
+
- **GitHub:** [https://github.com/carlex22/Aduc-sdr](https://github.com/carlex22/Aduc-sdr)
|
| 208 |
+
- **Hugging Face Spaces:**
|
| 209 |
+
- [Ltx-SuperTime-60Secondos](https://huggingface.co/spaces/Carlexx/Ltx-SuperTime-60Secondos/)
|
| 210 |
+
- [Novinho](https://huggingface.co/spaces/Carlexxx/Novinho/)
|
| 211 |
+
|
| 212 |
+
---
|
app.py
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
# app_refactored_with_postprod.py (FINAL VERSION with LTX Refinement)
|
| 3 |
+
|
| 4 |
+
import gradio as gr
|
| 5 |
+
import os
|
| 6 |
+
import sys
|
| 7 |
+
import traceback
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
import torch
|
| 10 |
+
import numpy as np
|
| 11 |
+
from PIL import Image
|
| 12 |
+
|
| 13 |
+
# --- Import dos Serviços de Backend ---
|
| 14 |
+
|
| 15 |
+
# Serviço LTX para geração de vídeo base e refinamento de textura
|
| 16 |
+
from api.ltx_server_refactored import video_generation_service
|
| 17 |
+
|
| 18 |
+
# Serviço SeedVR para upscaling de alta qualidade
|
| 19 |
+
from api.seedvr_server import SeedVRServer
|
| 20 |
+
|
| 21 |
+
# Inicializa o servidor SeedVR uma vez, se disponível
|
| 22 |
+
seedvr_inference_server = SeedVRServer() if SeedVRServer else None
|
| 23 |
+
|
| 24 |
+
# --- ESTADO DA SESSÃO ---
|
| 25 |
+
def create_initial_state():
|
| 26 |
+
return {
|
| 27 |
+
"low_res_video": None,
|
| 28 |
+
"low_res_latents": None,
|
| 29 |
+
"refined_video_ltx": None,
|
| 30 |
+
"refined_latents_ltx": None,
|
| 31 |
+
"used_seed": None
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
# --- FUNÇÕES WRAPPER PARA A UI ---
|
| 35 |
+
|
| 36 |
+
def run_generate_low(prompt, neg_prompt, start_img, height, width, duration, cfg, seed, randomize_seed, progress=gr.Progress(track_tqdm=True)):
|
| 37 |
+
"""Executa a primeira etapa: geração de um vídeo base em baixa resolução."""
|
| 38 |
+
print("UI: Chamando generate_low")
|
| 39 |
+
if True:
|
| 40 |
+
|
| 41 |
+
conditioning_items = []
|
| 42 |
+
if start_img:
|
| 43 |
+
num_frames_estimate = int(duration * 24)
|
| 44 |
+
items_list = [[start_img, 0, 1.0]]
|
| 45 |
+
conditioning_items = video_generation_service._prepare_condition_items(items_list, height, width, num_frames_estimate)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
used_seed = None if randomize_seed else seed
|
| 49 |
+
|
| 50 |
+
video_path, tensor_path, final_seed = video_generation_service.generate_low_resolution(
|
| 51 |
+
prompt=prompt, negative_prompt=neg_prompt,
|
| 52 |
+
height=height, width=width, duration_secs=duration,
|
| 53 |
+
guidance_scale=cfg, seed=used_seed,
|
| 54 |
+
conditioning_items=conditioning_items
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
new_state = {
|
| 58 |
+
"low_res_video": video_path,
|
| 59 |
+
"low_res_latents": tensor_path,
|
| 60 |
+
"refined_video_ltx": None,
|
| 61 |
+
"refined_latents_ltx": None,
|
| 62 |
+
"used_seed": final_seed
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
return video_path, new_state, gr.update(visible=True)
|
| 66 |
+
|
| 67 |
+
def run_ltx_refinement(state, prompt, neg_prompt, cfg, progress=gr.Progress(track_tqdm=True)):
|
| 68 |
+
"""Executa o processo de refinamento e upscaling de textura com o pipeline LTX."""
|
| 69 |
+
print("UI: Chamando run_ltx_refinement (generate_upscale_denoise)")
|
| 70 |
+
|
| 71 |
+
if True:
|
| 72 |
+
video_path, tensor_path = video_generation_service.generate_upscale_denoise(
|
| 73 |
+
latents_path=state["low_res_latents"],
|
| 74 |
+
prompt=prompt,
|
| 75 |
+
negative_prompt=neg_prompt,
|
| 76 |
+
guidance_scale=cfg,
|
| 77 |
+
seed=state["used_seed"]
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
# Atualiza o estado com os novos artefatos refinados
|
| 81 |
+
state["refined_video_ltx"] = video_path
|
| 82 |
+
state["refined_latents_ltx"] = tensor_path
|
| 83 |
+
|
| 84 |
+
return video_path, state
|
| 85 |
+
|
| 86 |
+
def run_seedvr_upscaling(state, seed, resolution, batch_size, fps, progress=gr.Progress(track_tqdm=True)):
|
| 87 |
+
"""Executa o processo de upscaling com SeedVR."""
|
| 88 |
+
|
| 89 |
+
video_path = state["low_res_video"]
|
| 90 |
+
print(f"▶️ Iniciando processo de upscaling SeedVR para o vídeo: {video_path}")
|
| 91 |
+
|
| 92 |
+
if True:
|
| 93 |
+
def progress_wrapper(p, desc=""):
|
| 94 |
+
progress(p, desc=desc)
|
| 95 |
+
output_filepath = seedvr_inference_server.run_inference(
|
| 96 |
+
file_path=video_path, seed=seed, resolution=resolution,
|
| 97 |
+
batch_size=batch_size, fps=fps, progress=progress_wrapper
|
| 98 |
+
)
|
| 99 |
+
final_message = f"✅ Processo SeedVR concluído!\nVídeo salvo em: {output_filepath}"
|
| 100 |
+
return gr.update(value=output_filepath, interactive=True), gr.update(value=final_message, interactive=False)
|
| 101 |
+
|
| 102 |
+
# --- DEFINIÇÃO DA INTERFACE GRADIO ---
|
| 103 |
+
with gr.Blocks() as demo:
|
| 104 |
+
gr.Markdown("# LTX Video - Geração e Pós-Produção por Etapas")
|
| 105 |
+
|
| 106 |
+
app_state = gr.State(value=create_initial_state())
|
| 107 |
+
|
| 108 |
+
# --- ETAPA 1: Geração Base ---
|
| 109 |
+
with gr.Row():
|
| 110 |
+
with gr.Column(scale=1):
|
| 111 |
+
gr.Markdown("### Etapa 1: Configurações de Geração")
|
| 112 |
+
prompt_input = gr.Textbox(label="Prompt", value="A majestic dragon flying over a medieval castle", lines=3)
|
| 113 |
+
neg_prompt_input = gr.Textbox(visible=False, label="Negative Prompt", value="worst quality, blurry, low quality, jittery", lines=2)
|
| 114 |
+
start_image = gr.Image(label="Imagem de Início (Opcional)", type="filepath", sources=["upload", "clipboard"])
|
| 115 |
+
|
| 116 |
+
with gr.Accordion("Parâmetros Avançados", open=False):
|
| 117 |
+
height_input = gr.Slider(label="Height", value=512, step=64, minimum=256, maximum=1024)
|
| 118 |
+
width_input = gr.Slider(label="Width", value=512, step=64, minimum=256, maximum=1024)
|
| 119 |
+
duration_input = gr.Slider(label="Duração (s)", value=8, step=0.5, minimum=1, maximum=16)
|
| 120 |
+
cfg_input = gr.Slider(label="Guidance Scale (CFG)", value=5.0, step=1, minimum=1, maximum=10.0)
|
| 121 |
+
seed_input = gr.Number(label="Seed", value=42, precision=0)
|
| 122 |
+
randomize_seed = gr.Checkbox(label="Randomize Seed", value=True)
|
| 123 |
+
|
| 124 |
+
generate_low_btn = gr.Button("1. Gerar Vídeo Base (Low-Res)", variant="primary")
|
| 125 |
+
|
| 126 |
+
with gr.Column(scale=1):
|
| 127 |
+
gr.Markdown("### Vídeo Base Gerado")
|
| 128 |
+
low_res_video_output = gr.Video(label="O resultado da Etapa 1 aparecerá aqui", interactive=False)
|
| 129 |
+
|
| 130 |
+
# --- ETAPA 2: Pós-Produção (no rodapé, em abas) ---
|
| 131 |
+
with gr.Group(visible=False) as post_prod_group:
|
| 132 |
+
gr.Markdown("<hr style='margin-top: 20px; margin-bottom: 20px;'>")
|
| 133 |
+
gr.Markdown("## Etapa 2: Pós-Produção")
|
| 134 |
+
gr.Markdown("Use o vídeo gerado acima como entrada para as ferramentas abaixo. **O prompt e a CFG da Etapa 1 serão reutilizados.**")
|
| 135 |
+
|
| 136 |
+
with gr.Tabs():
|
| 137 |
+
# --- ABA LTX REFINEMENT (AGORA FUNCIONAL) ---
|
| 138 |
+
with gr.TabItem("🚀 Upscaler Textura (LTX)"):
|
| 139 |
+
with gr.Row():
|
| 140 |
+
with gr.Column(scale=1):
|
| 141 |
+
gr.Markdown("### Parâmetros de Refinamento")
|
| 142 |
+
gr.Markdown("Esta etapa reutiliza o prompt, o prompt negativo e a CFG da Etapa 1 para manter a consistência.")
|
| 143 |
+
ltx_refine_btn = gr.Button("Aplicar Refinamento de Textura LTX", variant="primary")
|
| 144 |
+
with gr.Column(scale=1):
|
| 145 |
+
gr.Markdown("### Resultado do Refinamento")
|
| 146 |
+
ltx_refined_video_output = gr.Video(label="Vídeo com Textura Refinada (LTX)", interactive=False)
|
| 147 |
+
|
| 148 |
+
# --- ABA SEEDVR UPSCALER ---
|
| 149 |
+
with gr.TabItem("✨ Upscaler SeedVR"):
|
| 150 |
+
with gr.Row():
|
| 151 |
+
with gr.Column(scale=1):
|
| 152 |
+
gr.Markdown("### Parâmetros do SeedVR")
|
| 153 |
+
seedvr_seed = gr.Slider(minimum=0, maximum=999999, value=42, step=1, label="Seed")
|
| 154 |
+
seedvr_resolution = gr.Slider(minimum=720, maximum=1440, value=1072, step=8, label="Resolução Vertical (Altura)")
|
| 155 |
+
seedvr_batch_size = gr.Slider(minimum=1, maximum=16, value=4, step=1, label="Batch Size por GPU")
|
| 156 |
+
seedvr_fps_output = gr.Number(label="FPS de Saída (0 = original)", value=0)
|
| 157 |
+
run_seedvr_button = gr.Button("Iniciar Upscaling SeedVR", variant="primary", interactive=(seedvr_inference_server is not None))
|
| 158 |
+
if not seedvr_inference_server:
|
| 159 |
+
gr.Markdown("<p style='color: red;'>Serviço SeedVR não disponível.</p>")
|
| 160 |
+
with gr.Column(scale=1):
|
| 161 |
+
gr.Markdown("### Resultado do Upscaling")
|
| 162 |
+
seedvr_video_output = gr.Video(label="Vídeo com Upscale SeedVR", interactive=False)
|
| 163 |
+
seedvr_status_box = gr.Textbox(label="Status do Processamento", value="Aguardando...", lines=3, interactive=False)
|
| 164 |
+
|
| 165 |
+
# --- ABA MM-AUDIO ---
|
| 166 |
+
with gr.TabItem("🔊 Áudio (MM-Audio)"):
|
| 167 |
+
gr.Markdown("*(Funcionalidade futura para adicionar som aos vídeos)*")
|
| 168 |
+
|
| 169 |
+
# --- LÓGICA DE EVENTOS DA UI ---
|
| 170 |
+
|
| 171 |
+
# Botão da Etapa 1
|
| 172 |
+
generate_low_btn.click(
|
| 173 |
+
fn=run_generate_low,
|
| 174 |
+
inputs=[prompt_input, neg_prompt_input, start_image, height_input, width_input, duration_input, cfg_input, seed_input, randomize_seed],
|
| 175 |
+
outputs=[low_res_video_output, app_state, post_prod_group]
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
# Botão da Aba LTX Refinement
|
| 179 |
+
ltx_refine_btn.click(
|
| 180 |
+
fn=run_ltx_refinement,
|
| 181 |
+
inputs=[app_state, prompt_input, neg_prompt_input, cfg_input],
|
| 182 |
+
outputs=[ltx_refined_video_output, app_state]
|
| 183 |
+
)
|
| 184 |
+
|
| 185 |
+
# Botão da Aba SeedVR
|
| 186 |
+
run_seedvr_button.click(
|
| 187 |
+
fn=run_seedvr_upscaling,
|
| 188 |
+
inputs=[app_state, seedvr_seed, seedvr_resolution, seedvr_batch_size, seedvr_fps_output],
|
| 189 |
+
outputs=[seedvr_video_output, seedvr_status_box]
|
| 190 |
+
)
|
| 191 |
+
|
| 192 |
+
if __name__ == "__main__":
|
| 193 |
+
demo.queue().launch(server_name="0.0.0.0", server_port=7860, debug=True, show_error=True)
|
| 194 |
+
|
builder.sh
ADDED
|
@@ -0,0 +1,346 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
|
| 4 |
+
echo "🚀 Builder (FlashAttn LayerNorm extra + Apex + Q8) — runtime com GPU visível"
|
| 5 |
+
|
| 6 |
+
# ===== Config e diretórios =====
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
mkdir -p /app/wheels /app/cuda_cache /app/wheels/src
|
| 10 |
+
chmod -R 777 /app/wheels || true
|
| 11 |
+
export CUDA_CACHE_PATH="/app/cuda_cache"
|
| 12 |
+
|
| 13 |
+
# Preserva licença NGC (se existir)
|
| 14 |
+
if [ -f "/NGC-DL-CONTAINER-LICENSE" ]; then
|
| 15 |
+
cp -f /NGC-DL-CONTAINER-LICENSE /app/wheels/NGC-DL-CONTAINER-LICENSE || true
|
| 16 |
+
fi
|
| 17 |
+
|
| 18 |
+
# ===== Dependências mínimas =====
|
| 19 |
+
python -m pip install -v -U pip build setuptools wheel hatchling hatch-vcs scikit-build-core cmake ninja packaging "huggingface_hub[hf_transfer]" || true
|
| 20 |
+
|
| 21 |
+
# ===== Tags de ambiente (Python/CUDA/Torch) =====
|
| 22 |
+
PY_TAG="$(python -c 'import sys; print(f"cp{sys.version_info[0]}{sys.version_info[1]}")' 2>/dev/null || echo cp310)"
|
| 23 |
+
TORCH_VER="$(python - <<'PY'
|
| 24 |
+
try:
|
| 25 |
+
import torch, re
|
| 26 |
+
v = torch.__version__
|
| 27 |
+
print(re.sub(r'\+.*$', '', v))
|
| 28 |
+
except Exception:
|
| 29 |
+
print("unknown")
|
| 30 |
+
PY
|
| 31 |
+
)"
|
| 32 |
+
CU_TAG="$(python - <<'PY'
|
| 33 |
+
try:
|
| 34 |
+
import torch
|
| 35 |
+
cu = getattr(torch.version, "cuda", None)
|
| 36 |
+
print("cu"+cu.replace(".","")) if cu else print("")
|
| 37 |
+
except Exception:
|
| 38 |
+
print("")
|
| 39 |
+
PY
|
| 40 |
+
)"
|
| 41 |
+
echo "[env] PY_TAG=${PY_TAG} TORCH_VER=${TORCH_VER} CU_TAG=${CU_TAG}"
|
| 42 |
+
|
| 43 |
+
# ============================================================================
|
| 44 |
+
# CHECKERS
|
| 45 |
+
# ============================================================================
|
| 46 |
+
|
| 47 |
+
# Checa especificamente o módulo nativo requerido pelo layer_norm (sem checar 'flash-attn' geral)
|
| 48 |
+
check_flash_layer_norm_bin () {
|
| 49 |
+
python - <<'PY'
|
| 50 |
+
import importlib
|
| 51 |
+
ok = False
|
| 52 |
+
# extensões conhecidas produzidas por csrc/layer_norm
|
| 53 |
+
for name in [
|
| 54 |
+
"dropout_layer_norm", # nome do módulo nativo
|
| 55 |
+
"flash_attn.ops.layer_norm", # wrapper python que usa o nativo
|
| 56 |
+
"flash_attn.ops.rms_norm", # pode depender do mesmo backend em alguns empacotamentos
|
| 57 |
+
]:
|
| 58 |
+
try:
|
| 59 |
+
importlib.import_module(name)
|
| 60 |
+
ok = True
|
| 61 |
+
break
|
| 62 |
+
except Exception:
|
| 63 |
+
pass
|
| 64 |
+
raise SystemExit(0 if ok else 1)
|
| 65 |
+
PY
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
check_apex () {
|
| 69 |
+
python - <<'PY'
|
| 70 |
+
try:
|
| 71 |
+
from apex.normalization import FusedLayerNorm
|
| 72 |
+
import importlib; importlib.import_module("fused_layer_norm_cuda")
|
| 73 |
+
ok = True
|
| 74 |
+
except Exception:
|
| 75 |
+
ok = False
|
| 76 |
+
raise SystemExit(0 if ok else 1)
|
| 77 |
+
PY
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
check_q8 () {
|
| 81 |
+
python - <<'PY'
|
| 82 |
+
import importlib.util
|
| 83 |
+
spec = importlib.util.find_spec("ltx_q8_kernels") or importlib.util.find_spec("q8_kernels")
|
| 84 |
+
raise SystemExit(0 if spec else 1)
|
| 85 |
+
PY
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
# ============================================================================
|
| 89 |
+
# DOWNLOAD DO HUB (GENÉRICO)
|
| 90 |
+
# ============================================================================
|
| 91 |
+
|
| 92 |
+
# Instala uma wheel do HF por prefixo simples (ex.: apex-, q8_kernels-)
|
| 93 |
+
install_from_hf_by_prefix () {
|
| 94 |
+
local PREFIX="$1"
|
| 95 |
+
echo "[hub] Procurando wheels '${PREFIX}-*.whl' em ${SELF_HF_REPO_ID} com tags ${PY_TAG}/${CU_TAG}"
|
| 96 |
+
python - "$PREFIX" "$PY_TAG" "$CU_TAG" <<'PY' || exit 0
|
| 97 |
+
import os, sys
|
| 98 |
+
from huggingface_hub import HfApi, hf_hub_download, HfFolder
|
| 99 |
+
|
| 100 |
+
prefix, py_tag, cu_tag = sys.argv[1], sys.argv[2], sys.argv[3]
|
| 101 |
+
repo = os.environ.get("SELF_HF_REPO_ID","euIaxs22/Aduc-sdr")
|
| 102 |
+
api = HfApi(token=os.getenv("HF_TOKEN") or HfFolder.get_token())
|
| 103 |
+
try:
|
| 104 |
+
files = api.list_repo_files(repo_id=repo, repo_type="model")
|
| 105 |
+
except Exception:
|
| 106 |
+
raise SystemExit(0)
|
| 107 |
+
|
| 108 |
+
def match(name: str) -> bool:
|
| 109 |
+
return name.endswith(".whl") and name.rsplit("/",1)[-1].startswith(prefix + "-") and (py_tag in name)
|
| 110 |
+
|
| 111 |
+
cands = [f for f in files if match(f)]
|
| 112 |
+
pref = [f for f in cands if cu_tag and cu_tag in f] or cands
|
| 113 |
+
if not pref:
|
| 114 |
+
raise SystemExit(0)
|
| 115 |
+
|
| 116 |
+
target = sorted(pref, reverse=True)[0]
|
| 117 |
+
print(target)
|
| 118 |
+
path = hf_hub_download(repo_id=repo, filename=target, repo_type="model", local_dir="/app/wheels")
|
| 119 |
+
print(path)
|
| 120 |
+
PY
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
# Instala wheels do submódulo layer_norm aceitando variantes de nome
|
| 124 |
+
install_flash_layer_norm_from_hf () {
|
| 125 |
+
echo "[hub] Procurando wheels FlashAttention LayerNorm em ${SELF_HF_REPO_ID}"
|
| 126 |
+
python - "$PY_TAG" "$CU_TAG" <<'PY' || exit 0
|
| 127 |
+
import os, sys, re
|
| 128 |
+
from huggingface_hub import HfApi, hf_hub_download, HfFolder
|
| 129 |
+
|
| 130 |
+
py_tag, cu_tag = sys.argv[1], sys.argv[2]
|
| 131 |
+
repo = os.environ.get("SELF_HF_REPO_ID","euIaxs22/Aduc-sdr")
|
| 132 |
+
api = HfApi(token=os.getenv("HF_TOKEN") or HfFolder.get_token())
|
| 133 |
+
try:
|
| 134 |
+
files = api.list_repo_files(repo_id=repo, repo_type="model")
|
| 135 |
+
except Exception:
|
| 136 |
+
raise SystemExit(0)
|
| 137 |
+
|
| 138 |
+
pats = [
|
| 139 |
+
r"^flash[_-]?attn[_-]?.*layer[_-]?norm-.*\.whl$",
|
| 140 |
+
r"^dropout[_-]?layer[_-]?norm-.*\.whl$",
|
| 141 |
+
]
|
| 142 |
+
def ok(fn: str) -> bool:
|
| 143 |
+
name = fn.rsplit("/",1)[-1]
|
| 144 |
+
if py_tag not in name: return False
|
| 145 |
+
return any(re.search(p, name, flags=re.I) for p in pats)
|
| 146 |
+
|
| 147 |
+
cands = [f for f in files if ok(f)]
|
| 148 |
+
pref = [f for f in cands if cu_tag and cu_tag in f] or cands
|
| 149 |
+
if not pref:
|
| 150 |
+
raise SystemExit(0)
|
| 151 |
+
|
| 152 |
+
target = sorted(pref, reverse=True)[0]
|
| 153 |
+
print(target)
|
| 154 |
+
path = hf_hub_download(repo_id=repo, filename=target, repo_type="model", local_dir="/app/wheels")
|
| 155 |
+
print(path)
|
| 156 |
+
PY
|
| 157 |
+
}
|
| 158 |
+
|
| 159 |
+
# ============================================================================
|
| 160 |
+
# BUILDERS
|
| 161 |
+
# ============================================================================
|
| 162 |
+
|
| 163 |
+
# Passo extra: SIEMPRE tenta instalar o submódulo layer_norm via wheel do HF;
|
| 164 |
+
# se não houver wheel compatível, compila a partir de csrc/layer_norm e gera wheel.
|
| 165 |
+
build_or_install_flash_layer_norm () {
|
| 166 |
+
echo "[flow] === FlashAttn LayerNorm (passo extra) ==="
|
| 167 |
+
|
| 168 |
+
# 1) Tentar instalar wheel do HF primeiro (evita recompilar)
|
| 169 |
+
HF_OUT="$(install_flash_layer_norm_from_hf || true)"
|
| 170 |
+
if [ -n "${HF_OUT:-}" ]; then
|
| 171 |
+
WHEEL_PATH="$(printf "%s\n" "${HF_OUT}" | tail -n1)"
|
| 172 |
+
echo "[hub] Baixado: ${WHEEL_PATH}"
|
| 173 |
+
python -m pip install -v -U --no-build-isolation --no-deps "${WHEEL_PATH}" || true
|
| 174 |
+
if check_flash_layer_norm_bin; then
|
| 175 |
+
echo "[flow] FlashAttn LayerNorm: OK via wheel do Hub"
|
| 176 |
+
return 0
|
| 177 |
+
fi
|
| 178 |
+
echo "[flow] Wheel do Hub não resolveu import; seguirá com build"
|
| 179 |
+
else
|
| 180 |
+
echo "[hub] Nenhuma wheel compatível encontrada para FlashAttn LayerNorm"
|
| 181 |
+
fi
|
| 182 |
+
|
| 183 |
+
# 2) Build from source do submódulo csrc/layer_norm -> wheel
|
| 184 |
+
local SRC="/app/wheels/src/flash-attn"
|
| 185 |
+
echo "[build] Preparando fonte FlashAttention (layer_norm) em ${SRC}"
|
| 186 |
+
if [ -d "$SRC/.git" ]; then
|
| 187 |
+
git -C "$SRC" fetch --all -p || true
|
| 188 |
+
git -C "$SRC" reset --hard origin/main || true
|
| 189 |
+
git -C "$SRC" clean -fdx || true
|
| 190 |
+
else
|
| 191 |
+
rm -rf "$SRC"
|
| 192 |
+
git clone --depth 1 https://github.com/Dao-AILab/flash-attention "$SRC"
|
| 193 |
+
fi
|
| 194 |
+
|
| 195 |
+
# Define CC alvo a partir da GPU ativa (reduz tempo/ruído de build)
|
| 196 |
+
export TORCH_CUDA_ARCH_LIST="$(python - <<'PY'
|
| 197 |
+
import torch
|
| 198 |
+
try:
|
| 199 |
+
cc = "%d.%d" % torch.cuda.get_device_capability(0)
|
| 200 |
+
print(cc)
|
| 201 |
+
except Exception:
|
| 202 |
+
print("8.9") # fallback p/ Ada (L40S) caso build sem GPU visível
|
| 203 |
+
PY
|
| 204 |
+
)"
|
| 205 |
+
echo "[build] TORCH_CUDA_ARCH_LIST=${TORCH_CUDA_ARCH_LIST}"
|
| 206 |
+
|
| 207 |
+
pushd "$SRC/csrc/layer_norm" >/dev/null
|
| 208 |
+
export MAX_JOBS="${MAX_JOBS:-90}"
|
| 209 |
+
# Gera wheel reutilizável
|
| 210 |
+
python -m pip wheel -v --no-build-isolation --no-deps . -w /app/wheels || true
|
| 211 |
+
popd >/dev/null
|
| 212 |
+
|
| 213 |
+
# Instala a wheel gerada
|
| 214 |
+
local W="$(ls -t /app/wheels/*flash*attn*layer*norm*-*.whl 2>/dev/null | head -n1 || true)"
|
| 215 |
+
if [ -z "${W}" ]; then
|
| 216 |
+
W="$(ls -t /app/wheels/*dropout*layer*norm*-*.whl 2>/dev/null | head -n1 || true)"
|
| 217 |
+
fi
|
| 218 |
+
if [ -z "${W}" ]; then
|
| 219 |
+
# fallback para qualquer .whl recém gerado
|
| 220 |
+
W="$(ls -t /app/wheels/*.whl 2>/dev/null | head -n1 || true)"
|
| 221 |
+
fi
|
| 222 |
+
|
| 223 |
+
if [ -n "${W}" ]; then
|
| 224 |
+
python -m pip install -v -U --no-deps "${W}" || true
|
| 225 |
+
echo "[build] FlashAttn LayerNorm instalado da wheel: ${W}"
|
| 226 |
+
else
|
| 227 |
+
echo "[build] Nenhuma wheel gerada; instalando direto do source (último recurso)"
|
| 228 |
+
python -m pip install -v --no-build-isolation "$SRC/csrc/layer_norm" || true
|
| 229 |
+
fi
|
| 230 |
+
|
| 231 |
+
# Checagem final do binário
|
| 232 |
+
if check_flash_layer_norm_bin; then
|
| 233 |
+
echo "[flow] FlashAttn LayerNorm: import OK após build"
|
| 234 |
+
return 0
|
| 235 |
+
fi
|
| 236 |
+
echo "[flow] FlashAttn LayerNorm: falhou import após build"
|
| 237 |
+
return 1
|
| 238 |
+
}
|
| 239 |
+
|
| 240 |
+
build_apex () {
|
| 241 |
+
local SRC="/app/wheels/src/apex"
|
| 242 |
+
echo "[build] Preparando fonte Apex em ${SRC}"
|
| 243 |
+
if [ -d "$SRC/.git" ]; then
|
| 244 |
+
git -C "$SRC" fetch --all -p || true
|
| 245 |
+
git -C "$SRC" reset --hard HEAD || true
|
| 246 |
+
git -C "$SRC" clean -fdx || true
|
| 247 |
+
else
|
| 248 |
+
rm -rf "$SRC"
|
| 249 |
+
git clone --depth 1 https://github.com/NVIDIA/apex "$SRC"
|
| 250 |
+
fi
|
| 251 |
+
echo "[build] Compilando Apex -> wheel"
|
| 252 |
+
export APEX_CPP_EXT=1 APEX_CUDA_EXT=1 APEX_ALL_CONTRIB_EXT=0
|
| 253 |
+
python -m pip wheel -v --no-build-isolation --no-deps "$SRC" -w /app/wheels || true
|
| 254 |
+
local W="$(ls -t /app/wheels/apex-*.whl 2>/dev/null | head -n1 || true)"
|
| 255 |
+
if [ -n "${W}" ]; then
|
| 256 |
+
python -m pip install -v -U --no-deps "${W}" || true
|
| 257 |
+
echo "[build] Apex instalado da wheel recém-compilada: ${W}"
|
| 258 |
+
else
|
| 259 |
+
echo "[build] Nenhuma wheel Apex gerada; instalando do source"
|
| 260 |
+
python -m pip install -v --no-build-isolation "$SRC" || true
|
| 261 |
+
fi
|
| 262 |
+
}
|
| 263 |
+
|
| 264 |
+
Q8_REPO="${Q8_REPO:-https://github.com/Lightricks/LTX-Video-Q8-Kernels}"
|
| 265 |
+
Q8_COMMIT="${Q8_COMMIT:-f3066edea210082799ca5a2bbf9ef0321c5dd8fc}"
|
| 266 |
+
build_q8 () {
|
| 267 |
+
local SRC="/app/wheels/src/q8_kernels"
|
| 268 |
+
rm -rf "$SRC"
|
| 269 |
+
git clone --filter=blob:none "$Q8_REPO" "$SRC"
|
| 270 |
+
git -C "$SRC" checkout "$Q8_COMMIT"
|
| 271 |
+
git -C "$SRC" submodule update --init --recursive
|
| 272 |
+
echo "[build] Compilando Q8 Kernels -> wheel"
|
| 273 |
+
python -m pip wheel -v --no-build-isolation "$SRC" -w /app/wheels || true
|
| 274 |
+
local W="$(ls -t /app/wheels/q8_kernels-*.whl 2>/dev/null | head -n1 || true)"
|
| 275 |
+
if [ -n "${W}" ]; then
|
| 276 |
+
python -m pip install -v -U --no-deps "${W}" || true
|
| 277 |
+
echo "[build] Q8 instalado da wheel recém-compilada: ${W}"
|
| 278 |
+
else
|
| 279 |
+
echo "[build] Nenhuma wheel q8_kernels gerada; instalando do source"
|
| 280 |
+
python -m pip install -v --no-build-isolation "$SRC" || true
|
| 281 |
+
fi
|
| 282 |
+
}
|
| 283 |
+
|
| 284 |
+
# ============================================================================
|
| 285 |
+
# EXECUÇÃO
|
| 286 |
+
# ============================================================================
|
| 287 |
+
|
| 288 |
+
# Passo adicional SEM depender de "flash-attn" já instalado: trata somente o layer_norm
|
| 289 |
+
#build_q8 || true
|
| 290 |
+
|
| 291 |
+
# Apex (mantido)
|
| 292 |
+
# Tenta primeiro via wheel no HF e, se não houver, compila e instala em wheel
|
| 293 |
+
#echo "[flow] === apex ==="
|
| 294 |
+
#HF_OUT="$(install_from_hf_by_prefix "apex" || true)"
|
| 295 |
+
#if [ -n "${HF_OUT:-}" ]; then
|
| 296 |
+
# WHEEL_PATH="$(printf "%s\n" "${HF_OUT}" | tail -n1)"
|
| 297 |
+
# echo "[hub] Baixado: ${WHEEL_PATH}"
|
| 298 |
+
# python -m pip install -v -U --no-build-isolation "${WHEEL_PATH}" || true
|
| 299 |
+
# if ! check_apex; then
|
| 300 |
+
# echo "[flow] apex: import falhou após wheel; compilando"
|
| 301 |
+
# #build_apex || true
|
| 302 |
+
# fi
|
| 303 |
+
#else
|
| 304 |
+
# echo "[hub] Nenhuma wheel apex compatível; compilando"
|
| 305 |
+
# build_apex || true
|
| 306 |
+
#fi
|
| 307 |
+
|
| 308 |
+
#Q8 (opcional)
|
| 309 |
+
echo "[flow] === q8_kernels ==="
|
| 310 |
+
HF_OUT="$(install_from_hf_by_prefix "q8_kernels" || true)"
|
| 311 |
+
if [ -n "${HF_OUT:-}" ]; then
|
| 312 |
+
WHEEL_PATH="$(printf "%s\n" "${HF_OUT}" | tail -n1)"
|
| 313 |
+
echo "[hub] Baixado: ${WHEEL_PATH}"
|
| 314 |
+
python -m pip install -v -U --no-build-isolation "${WHEEL_PATH}" || true
|
| 315 |
+
if ! check_q8; then
|
| 316 |
+
echo "[flow] q8_kernels: import falhou após wheel; compilando"
|
| 317 |
+
build_q8 || true
|
| 318 |
+
fi
|
| 319 |
+
else
|
| 320 |
+
echo "[hub] Nenhuma wheel q8_kernels compatível; compilando"
|
| 321 |
+
build_q8 || true
|
| 322 |
+
fi
|
| 323 |
+
|
| 324 |
+
# Upload de wheels produzidas para o HF (cache cross-restarts)
|
| 325 |
+
python - <<'PY'
|
| 326 |
+
import os
|
| 327 |
+
from huggingface_hub import HfApi, HfFolder
|
| 328 |
+
|
| 329 |
+
repo = os.environ.get("SELF_HF_REPO_ID","euIaxs22/Aduc-sdr")
|
| 330 |
+
token = os.getenv("HF_TOKEN") or HfFolder.get_token()
|
| 331 |
+
if not token:
|
| 332 |
+
raise SystemExit("HF_TOKEN ausente; upload desabilitado")
|
| 333 |
+
|
| 334 |
+
api = HfApi(token=token)
|
| 335 |
+
api.upload_folder(
|
| 336 |
+
folder_path="/app/wheels",
|
| 337 |
+
repo_id=repo,
|
| 338 |
+
repo_type="model",
|
| 339 |
+
allow_patterns=["*.whl","NGC-DL-CONTAINER-LICENSE"],
|
| 340 |
+
ignore_patterns=["**/src/**","**/*.log","**/logs/**",".git/**"],
|
| 341 |
+
)
|
| 342 |
+
print("Upload concluído (wheels + licença).")
|
| 343 |
+
PY
|
| 344 |
+
|
| 345 |
+
chmod -R 777 /app/wheels || true
|
| 346 |
+
echo "✅ Builder finalizado."
|
compose.yaml
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# compose.yaml (Versão com VINCIE)
|
| 2 |
+
version: '3.8'
|
| 3 |
+
|
| 4 |
+
services:
|
| 5 |
+
aduc-sdr-app:
|
| 6 |
+
build: .
|
| 7 |
+
environment:
|
| 8 |
+
ADUC_LOG_LEVEL: "DEBUG"
|
| 9 |
+
image: aduc-sdr-videosuite:latest
|
| 10 |
+
# (deploy, resources... mantidos como antes)
|
| 11 |
+
ports:
|
| 12 |
+
- "7860:7860" # Porta para a UI principal (LTX + SeedVR)
|
| 13 |
+
- "7861:7861" # Porta para a nova UI do VINCIE
|
| 14 |
+
volumes:
|
| 15 |
+
# O volume 'aduc_data' agora armazena tudo: cache, modelos e repos.
|
| 16 |
+
- aduc_data:/data
|
| 17 |
+
- ./output:/app/output
|
| 18 |
+
# O entrypoint cuidará do setup na inicialização.
|
| 19 |
+
# O CMD padrão iniciará a UI principal. Para VINCIE, usaremos um comando diferente.
|
| 20 |
+
|
| 21 |
+
# Novo serviço para a interface do VINCIE
|
| 22 |
+
vince-ui:
|
| 23 |
+
image: aduc-sdr-videosuite:latest # Usa a mesma imagem já construída
|
| 24 |
+
command: python3 /app/app_vince.py # Sobrescreve o CMD padrão para iniciar a UI do VINCIE
|
| 25 |
+
deploy:
|
| 26 |
+
resources:
|
| 27 |
+
reservations:
|
| 28 |
+
devices:
|
| 29 |
+
- driver: nvidia
|
| 30 |
+
count: all
|
| 31 |
+
capabilities: [gpu]
|
| 32 |
+
ports:
|
| 33 |
+
- "7861:7861"
|
| 34 |
+
volumes:
|
| 35 |
+
- aduc_data:/data
|
| 36 |
+
- ./output:/app/output
|
| 37 |
+
|
| 38 |
+
volumes:
|
| 39 |
+
aduc_data:
|
entrypoint.sh
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
set -e
|
| 3 |
+
|
| 4 |
+
echo "🚀 ADUC-SDR Entrypoint: Configurando o ambiente de execução..."
|
| 5 |
+
|
| 6 |
+
# --- Configuração de Performance (CPU & GPU) ---
|
| 7 |
+
NUM_VCPUS=$(nproc)
|
| 8 |
+
NUM_GPUS=$(nvidia-smi --query-gpu=count --format=csv,noheader | head -n 1 || echo 0)
|
| 9 |
+
echo " > Hardware: ${NUM_VCPUS} vCPUs, ${NUM_GPUS} GPUs"
|
| 10 |
+
if [[ ${NUM_GPUS} -gt 0 ]]; then
|
| 11 |
+
VCPUS_PER_GPU=$((NUM_VCPUS / NUM_GPUS))
|
| 12 |
+
THREADS_PER_PROCESS=$((VCPUS_PER_GPU / 2))
|
| 13 |
+
else
|
| 14 |
+
THREADS_PER_PROCESS=$((NUM_VCPUS / 2))
|
| 15 |
+
fi
|
| 16 |
+
MIN_THREADS=4; MAX_THREADS=16
|
| 17 |
+
if [[ ${THREADS_PER_PROCESS} -lt ${MIN_THREADS} ]]; then THREADS_PER_PROCESS=${MIN_THREADS}; fi
|
| 18 |
+
if [[ ${THREADS_PER_PROCESS} -gt ${MAX_THREADS} ]]; then THREADS_PER_PROCESS=${MAX_THREADS}; fi
|
| 19 |
+
export OMP_NUM_THREADS=${OMP_NUM_THREADS:-${THREADS_PER_PROCESS}}
|
| 20 |
+
export MKL_NUM_THREADS=${MKL_NUM_THREADS:-${THREADS_PER_PROCESS}}
|
| 21 |
+
export MAX_JOBS=${MAX_JOBS:-${NUM_VCPUS}}
|
| 22 |
+
export PYTORCH_CUDA_ALLOC_CONF=${PYTORCH_CUDA_ALLOC_CONF:-"max_split_size_mb:512"}
|
| 23 |
+
export NVIDIA_TF32_OVERRIDE=${NVIDIA_TF32_OVERRIDE:-1}
|
| 24 |
+
|
| 25 |
+
# --- Configuração de Depuração e Logging ---
|
| 26 |
+
export ADUC_LOG_LEVEL=${ADUC_LOG_LEVEL:-"INFO"}
|
| 27 |
+
export CUDA_LAUNCH_BLOCKING=${CUDA_LAUNCH_BLOCKING:-0}
|
| 28 |
+
export PYTHONFAULTHANDLER=1
|
| 29 |
+
export GRADIO_DEBUG=${GRADIO_DEBUG:-"False"}
|
| 30 |
+
|
| 31 |
+
echo " > Performance: OMP_NUM_THREADS=${OMP_NUM_THREADS}, MKL_NUM_THREADS=${MKL_NUM_THREADS}"
|
| 32 |
+
echo " > Depuração: ADUC_LOG_LEVEL=${ADUC_LOG_LEVEL}, CUDA_LAUNCH_BLOCKING=${CUDA_LAUNCH_BLOCKING}"
|
| 33 |
+
echo ""
|
| 34 |
+
echo ""
|
| 35 |
+
|
| 36 |
+
#/bin/bash /app/info.sh
|
| 37 |
+
|
| 38 |
+
# --- Setup de Dependências ---
|
| 39 |
+
echo " > Verificando dependências com setup.py..."
|
| 40 |
+
python3 /app/setup.py
|
| 41 |
+
|
| 42 |
+
echo "---------------------------------------------------------"
|
| 43 |
+
echo "🔥 Ambiente configurado. Iniciando o comando principal: $@"
|
| 44 |
+
exec "$@"
|
info.sh
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
|
| 3 |
+
set -euo pipefail
|
| 4 |
+
|
| 5 |
+
echo "================= RUNTIME CAPABILITIES ================="
|
| 6 |
+
date
|
| 7 |
+
|
| 8 |
+
echo
|
| 9 |
+
if command -v nvidia-smi >/dev/null 2>&1; then
|
| 10 |
+
nvidia-smi
|
| 11 |
+
else
|
| 12 |
+
echo "nvidia-smi: not available"
|
| 13 |
+
fi
|
| 14 |
+
echo
|
| 15 |
+
|
| 16 |
+
echo "CUDA_HOME: ${CUDA_HOME:-/usr/local/cuda}"
|
| 17 |
+
if command -v nvcc >/dev/null 2>&1; then
|
| 18 |
+
nvcc --version || true
|
| 19 |
+
else
|
| 20 |
+
echo "nvcc: not available"
|
| 21 |
+
fi
|
| 22 |
+
echo
|
| 23 |
+
|
| 24 |
+
echo "[PyTorch / CUDA backend]"
|
| 25 |
+
python3 - <<'PY'
|
| 26 |
+
import json, os, torch, inspect
|
| 27 |
+
|
| 28 |
+
def to_bool(x):
|
| 29 |
+
try:
|
| 30 |
+
if callable(x):
|
| 31 |
+
try:
|
| 32 |
+
sig = inspect.signature(x)
|
| 33 |
+
if len(sig.parameters)==0:
|
| 34 |
+
return bool(x())
|
| 35 |
+
except Exception:
|
| 36 |
+
pass
|
| 37 |
+
return True
|
| 38 |
+
return bool(x)
|
| 39 |
+
except Exception:
|
| 40 |
+
return None
|
| 41 |
+
|
| 42 |
+
info = {
|
| 43 |
+
"torch": getattr(torch, "__version__", None),
|
| 44 |
+
"cuda_available": torch.cuda.is_available(),
|
| 45 |
+
"cuda_device_count": torch.cuda.device_count(),
|
| 46 |
+
"cuda_runtime_version": getattr(torch.version, "cuda", None),
|
| 47 |
+
"cudnn_version": torch.backends.cudnn.version() if torch.backends.cudnn.is_available() else None,
|
| 48 |
+
"tf32": (torch.backends.cuda.matmul.allow_tf32 if torch.cuda.is_available() else None),
|
| 49 |
+
"flash_sdp": (to_bool(getattr(torch.backends.cuda, "enable_flash_sdp", None)) if torch.cuda.is_available() else None),
|
| 50 |
+
"mem_efficient_sdp": (to_bool(getattr(torch.backends.cuda, "enable_mem_efficient_sdp", None)) if torch.cuda.is_available() else None),
|
| 51 |
+
"math_sdp": (to_bool(getattr(torch.backends.cuda, "enable_math_sdp", None)) if torch.cuda.is_available() else None),
|
| 52 |
+
}
|
| 53 |
+
print(json.dumps(info, indent=2))
|
| 54 |
+
for i in range(min(torch.cuda.device_count(), 16)):
|
| 55 |
+
print(f"GPU {i}: {torch.cuda.get_device_name(i)}")
|
| 56 |
+
PY
|
| 57 |
+
echo
|
| 58 |
+
|
| 59 |
+
echo "[Apex (FusedLayerNorm/RMSNorm)]"
|
| 60 |
+
python3 - <<'PY'
|
| 61 |
+
try:
|
| 62 |
+
from apex.normalization import FusedLayerNorm, FusedRMSNorm
|
| 63 |
+
import importlib; importlib.import_module("fused_layer_norm_cuda")
|
| 64 |
+
print("apex.normalization: OK")
|
| 65 |
+
except Exception as e:
|
| 66 |
+
print("apex.normalization: FAIL ->", e)
|
| 67 |
+
PY
|
| 68 |
+
echo
|
| 69 |
+
|
| 70 |
+
echo "[FlashAttention (CUDA/Triton/RMSNorm)]"
|
| 71 |
+
python3 - <<'PY'
|
| 72 |
+
import importlib
|
| 73 |
+
mods = [
|
| 74 |
+
'flash_attn', 'flash_attn_2_cuda',
|
| 75 |
+
'flash_attn.ops.rms_norm', 'flash_attn.ops.layer_norm',
|
| 76 |
+
'flash_attn.layers.layer_norm'
|
| 77 |
+
]
|
| 78 |
+
for m in mods:
|
| 79 |
+
try:
|
| 80 |
+
importlib.import_module(m)
|
| 81 |
+
print(f"{m}: OK")
|
| 82 |
+
except Exception as e:
|
| 83 |
+
print(f"{m}: FAIL -> {e}")
|
| 84 |
+
PY
|
| 85 |
+
echo
|
| 86 |
+
|
| 87 |
+
echo "[FlashAttention versão/details]"
|
| 88 |
+
python3 - <<'PY'
|
| 89 |
+
try:
|
| 90 |
+
import flash_attn
|
| 91 |
+
fa_ver = getattr(flash_attn, "__version__", None)
|
| 92 |
+
print(f"flash_attn: {fa_ver}")
|
| 93 |
+
except Exception:
|
| 94 |
+
print("flash_attn: not importable.")
|
| 95 |
+
try:
|
| 96 |
+
import torch
|
| 97 |
+
print(f"torch: {torch.__version__} | cuda: {getattr(torch.version, 'cuda', None)}")
|
| 98 |
+
except Exception:
|
| 99 |
+
pass
|
| 100 |
+
PY
|
| 101 |
+
echo
|
| 102 |
+
|
| 103 |
+
echo "[Triton]"
|
| 104 |
+
python3 - <<'PY'
|
| 105 |
+
try:
|
| 106 |
+
import triton
|
| 107 |
+
print("triton:", triton.__version__)
|
| 108 |
+
try:
|
| 109 |
+
import triton.ops as _; print("triton.ops: OK")
|
| 110 |
+
except Exception:
|
| 111 |
+
print("triton.ops: not present (ok on Triton>=3.x)")
|
| 112 |
+
except Exception as e:
|
| 113 |
+
print("triton: FAIL ->", e)
|
| 114 |
+
PY
|
| 115 |
+
echo
|
| 116 |
+
|
| 117 |
+
echo "[BitsAndBytes (Q8/Q4)]"
|
| 118 |
+
python3 - <<'PY'
|
| 119 |
+
try:
|
| 120 |
+
import bitsandbytes as bnb
|
| 121 |
+
print("bitsandbytes:", bnb.__version__)
|
| 122 |
+
try:
|
| 123 |
+
from bitsandbytes.triton import _custom_ops as _; print("bnb.triton._custom_ops: OK")
|
| 124 |
+
except Exception as e:
|
| 125 |
+
print("bnb.triton: partial ->", e)
|
| 126 |
+
except Exception as e:
|
| 127 |
+
print("bitsandbytes: FAIL ->", e)
|
| 128 |
+
PY
|
| 129 |
+
echo
|
| 130 |
+
|
| 131 |
+
echo "[Transformers / Diffusers / XFormers / EcoML]"
|
| 132 |
+
python3 - <<'PY'
|
| 133 |
+
def _v(m):
|
| 134 |
+
try:
|
| 135 |
+
mod = __import__(m)
|
| 136 |
+
print(f"{m}: {getattr(mod, '__version__', 'unknown')}")
|
| 137 |
+
except Exception as e:
|
| 138 |
+
print(f"{m}: FAIL -> {e}")
|
| 139 |
+
for m in ("transformers", "diffusers", "xformers", "ecuml", "mlx", "ecobase"):
|
| 140 |
+
_v(m)
|
| 141 |
+
PY
|
| 142 |
+
echo
|
| 143 |
+
|
| 144 |
+
echo "[Distribuído / NCCL Env]"
|
| 145 |
+
env | grep -E '^(CUDA_VISIBLE_DEVICES|NCCL_|TORCH_|ENABLE_.*SDP|HF_HUB_.*|CUDA_|NV_.*NCCL.*|PYTORCH_CUDA_ALLOC_CONF)=' | sort
|
| 146 |
+
echo
|
| 147 |
+
|
| 148 |
+
echo "[Output dir/perms]"
|
| 149 |
+
OUT="/app/outputs"
|
| 150 |
+
echo "OUT dir: $OUT"
|
| 151 |
+
mkdir -p "$OUT"
|
| 152 |
+
ls -la "$OUT" || true
|
| 153 |
+
|
| 154 |
+
echo "================= END CAPABILITIES ================="
|
requirements.txt
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
accelerate
|
| 2 |
+
transformers
|
| 3 |
+
sentencepiece
|
| 4 |
+
pillow
|
| 5 |
+
numpy
|
| 6 |
+
torchvision
|
| 7 |
+
huggingface_hub
|
| 8 |
+
spaces
|
| 9 |
+
opencv-python
|
| 10 |
+
imageio
|
| 11 |
+
imageio-ffmpeg
|
| 12 |
+
einops
|
| 13 |
+
timm
|
| 14 |
+
av
|
| 15 |
+
#flash-attn-3@https://huggingface.co/alexnasa/flash-attn-3/resolve/main/128/flash_attn_3-3.0.0b1-cp39-abi3-linux_x86_64.whl
|
| 16 |
+
git+https://github.com/huggingface/diffusers.git@main
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
Common
|
| 20 |
+
# Configuration system.
|
| 21 |
+
lpips>=0.1.4 # LPIPS model for VAE training
|
| 22 |
+
|
| 23 |
+
# Dataloading
|
| 24 |
+
bson>=0.5.10 # bson for Image dataloading
|
| 25 |
+
tensorflow>=2.16.1 # Video dataloading
|
| 26 |
+
opencv-python>=4.9.0.80 # OpenCV
|
| 27 |
+
sentencepiece>=0.2.0 # For Text Encoder
|
| 28 |
+
|
| 29 |
+
# Modeling
|
| 30 |
+
rotary-embedding-torch>=0.5.3 # Rotary positional embedding
|
| 31 |
+
transformers>=4.38.2 # Transformers
|
| 32 |
+
torchvision>=0.19.0 # Torchvision
|
| 33 |
+
tiktoken>=0.7.0 # Tiktoken for generation
|
| 34 |
+
transformers_stream_generator>=0.0.5 #LLM generation support
|
| 35 |
+
|
| 36 |
+
# Metrics
|
| 37 |
+
torchmetrics>=1.3.2 # Core module for metric
|
| 38 |
+
pycocotools>=2.0.7 # COCO-related
|
| 39 |
+
torch-fidelity>=0.3.0 # FID-related
|
| 40 |
+
|
| 41 |
+
# Experiment Tracking
|
| 42 |
+
moviepy>=1.0.3 # WandB Logging Image & Video
|
| 43 |
+
imageio>=2.34.0 # WandB Logging Image & Video
|
| 44 |
+
tabulate>=0.9.0 # Logging Table
|
| 45 |
+
deepdiff>=7.0.1 # Find difference of config
|
| 46 |
+
|
| 47 |
+
# Testing
|
| 48 |
+
parameterized>=0.9.0 # Define multiple tests through decorators.
|
| 49 |
+
|
| 50 |
+
# Notebook
|
| 51 |
+
mediapy>=1.2.0 # Notebook Visualization
|
| 52 |
+
|
| 53 |
+
# DevOPs
|
| 54 |
+
black >= 24 # Code formatting
|
| 55 |
+
flake8 >= 7 # Code style
|
| 56 |
+
isort >= 5 # Import sorting
|
| 57 |
+
pre-commit>=3.7.0 # Pre-commit hooks
|
| 58 |
+
expecttest>=0.2.1 # Pytorch dist tests
|
| 59 |
+
hypothesis>=6.100.1 # Fix randomness
|
| 60 |
+
av>=12.0.0
|
setup.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# setup.py
|
| 2 |
+
#
|
| 3 |
+
# Copyright (C) August 4, 2025 Carlos Rodrigues dos Santos
|
| 4 |
+
#
|
| 5 |
+
# Versão 3.1.0 (Setup Unificado com LTX, SeedVR e VINCIE com Cache Robusto)
|
| 6 |
+
# - Orquestra a instalação de todos os repositórios e modelos para a suíte ADUC-SDR.
|
| 7 |
+
# - Usa snapshot_download para baixar dependências de forma eficiente e correta.
|
| 8 |
+
|
| 9 |
+
import os
|
| 10 |
+
import subprocess
|
| 11 |
+
import sys
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
import yaml
|
| 14 |
+
from huggingface_hub import hf_hub_download, snapshot_download
|
| 15 |
+
|
| 16 |
+
# ==============================================================================
|
| 17 |
+
# --- CONFIGURAÇÃO DE PATHS E CACHE ---
|
| 18 |
+
# ==============================================================================
|
| 19 |
+
# Assume que /data é um volume persistente montado no contêiner.
|
| 20 |
+
DEPS_DIR = Path("/data")
|
| 21 |
+
CACHE_DIR = DEPS_DIR / ".cache" / "huggingface"
|
| 22 |
+
|
| 23 |
+
# --- Paths dos Módulos da Aplicação ---
|
| 24 |
+
LTX_VIDEO_REPO_DIR = DEPS_DIR / "LTX-Video"
|
| 25 |
+
SEEDVR_MODELS_DIR = DEPS_DIR / "models" / "SeedVR"
|
| 26 |
+
VINCIE_REPO_DIR = DEPS_DIR / "VINCIE"
|
| 27 |
+
VINCIE_CKPT_DIR = DEPS_DIR / "ckpt" / "VINCIE-3B"
|
| 28 |
+
|
| 29 |
+
# --- Repositórios Git para Clonar ---
|
| 30 |
+
REPOS_TO_CLONE = {
|
| 31 |
+
"LTX-Video": "https://huggingface.co/spaces/Lightricks/ltx-video-distilled",
|
| 32 |
+
"SeedVR": "https://github.com/numz/ComfyUI-SeedVR2_VideoUpscaler",
|
| 33 |
+
"VINCIE": "https://github.com/ByteDance-Seed/VINCIE",
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
# ==============================================================================
|
| 37 |
+
# --- FUNÇÕES AUXILIARES ---
|
| 38 |
+
# ==============================================================================
|
| 39 |
+
|
| 40 |
+
def run_command(command, cwd=None):
|
| 41 |
+
"""Executa um comando no terminal de forma segura e com logs claros."""
|
| 42 |
+
print(f"Executando: {' '.join(command)}")
|
| 43 |
+
try:
|
| 44 |
+
subprocess.run(
|
| 45 |
+
command, check=True, cwd=cwd,
|
| 46 |
+
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
|
| 47 |
+
)
|
| 48 |
+
except subprocess.CalledProcessError as e:
|
| 49 |
+
print(f"ERRO: O comando falhou com o código {e.returncode}\nStderr:\n{e.stderr.strip()}")
|
| 50 |
+
sys.exit(1)
|
| 51 |
+
except FileNotFoundError:
|
| 52 |
+
print(f"ERRO: Comando '{command[0]}' não encontrado. Verifique se o git está instalado.")
|
| 53 |
+
sys.exit(1)
|
| 54 |
+
|
| 55 |
+
def _load_ltx_config():
|
| 56 |
+
"""Carrega o arquivo de configuração YAML do LTX-Video."""
|
| 57 |
+
print("--- Carregando Configuração do LTX-Video ---")
|
| 58 |
+
config_file = LTX_VIDEO_REPO_DIR / "configs" / "ltxv-13b-0.9.8-distilled-fp8.yaml"
|
| 59 |
+
if not config_file.exists():
|
| 60 |
+
print(f"ERRO: Arquivo de configuração do LTX não encontrado em '{config_file}'")
|
| 61 |
+
return None
|
| 62 |
+
print(f"Configuração LTX encontrada: {config_file}")
|
| 63 |
+
with open(config_file, "r") as file:
|
| 64 |
+
return yaml.safe_load(file)
|
| 65 |
+
|
| 66 |
+
def _ensure_hf_model(repo_id, filenames=None, allow_patterns=None, local_dir=None):
|
| 67 |
+
"""Função genérica para baixar um ou mais arquivos (hf_hub_download) ou um snapshot (snapshot_download)."""
|
| 68 |
+
if not repo_id: return
|
| 69 |
+
|
| 70 |
+
print(f"Verificando/Baixando modelo do repositório: '{repo_id}'...")
|
| 71 |
+
try:
|
| 72 |
+
if filenames: # Baixa arquivos específicos
|
| 73 |
+
for filename in filenames:
|
| 74 |
+
if not filename: continue
|
| 75 |
+
hf_hub_download(
|
| 76 |
+
repo_id=repo_id, filename=filename, cache_dir=str(CACHE_DIR),
|
| 77 |
+
local_dir=str(local_dir) if local_dir else None,
|
| 78 |
+
#local_dir_use_symlinks=False,
|
| 79 |
+
token=os.getenv("HF_TOKEN"),
|
| 80 |
+
)
|
| 81 |
+
else: # Baixa um snapshot (partes de um repositório)
|
| 82 |
+
snapshot_download(
|
| 83 |
+
repo_id=repo_id, cache_dir=str(CACHE_DIR),
|
| 84 |
+
local_dir=str(local_dir) if local_dir else None,
|
| 85 |
+
allow_patterns=allow_patterns,
|
| 86 |
+
token=os.getenv("HF_TOKEN"),
|
| 87 |
+
)
|
| 88 |
+
print(f"-> Modelo '{repo_id}' está disponível.")
|
| 89 |
+
except Exception as e:
|
| 90 |
+
print(f"ERRO CRÍTICO ao baixar o modelo '{repo_id}': {e}")
|
| 91 |
+
sys.exit(1)
|
| 92 |
+
|
| 93 |
+
# ==============================================================================
|
| 94 |
+
# --- FUNÇÃO PRINCIPAL DE SETUP ---
|
| 95 |
+
# ==============================================================================
|
| 96 |
+
|
| 97 |
+
def main():
|
| 98 |
+
"""Orquestra todo o processo de setup do ambiente."""
|
| 99 |
+
print("--- Iniciando Setup do Ambiente ADUC-SDR (LTX + SeedVR + VINCIE) ---")
|
| 100 |
+
DEPS_DIR.mkdir(exist_ok=True)
|
| 101 |
+
CACHE_DIR.mkdir(parents=True, exist_ok=True)
|
| 102 |
+
|
| 103 |
+
# --- ETAPA 1: Clonar Repositórios ---
|
| 104 |
+
print("\n--- ETAPA 1: Verificando Repositórios Git ---")
|
| 105 |
+
for repo_name, repo_url in REPOS_TO_CLONE.items():
|
| 106 |
+
repo_path = DEPS_DIR / repo_name
|
| 107 |
+
if repo_path.is_dir():
|
| 108 |
+
print(f"Repositório '{repo_name}' já existe em '{repo_path}'. Pulando.")
|
| 109 |
+
else:
|
| 110 |
+
print(f"Clonando '{repo_name}' de {repo_url}...")
|
| 111 |
+
run_command(["git", "clone", "--depth", "1", repo_url, str(repo_path)])
|
| 112 |
+
print(f"-> '{repo_name}' clonado com sucesso.")
|
| 113 |
+
|
| 114 |
+
# --- ETAPA 2: Baixar Modelos LTX-Video e Dependências ---
|
| 115 |
+
print("\n--- ETAPA 2: Verificando Modelos LTX-Video e Dependências ---")
|
| 116 |
+
ltx_config = _load_ltx_config()
|
| 117 |
+
if not ltx_config:
|
| 118 |
+
print("ERRO: Não foi possível carregar a configuração do LTX-Video. Abortando.")
|
| 119 |
+
sys.exit(1)
|
| 120 |
+
|
| 121 |
+
_ensure_hf_model(
|
| 122 |
+
repo_id="Lightricks/LTX-Video",
|
| 123 |
+
filenames=[
|
| 124 |
+
ltx_config.get("checkpoint_path"),
|
| 125 |
+
ltx_config.get("spatial_upscaler_model_path") # <-- Adicione esta linha
|
| 126 |
+
]
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
_ensure_hf_model(
|
| 130 |
+
repo_id=ltx_config.get("text_encoder_model_name_or_path"),
|
| 131 |
+
allow_patterns=["*.json", "*.safetensors"]
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
enhancer_repos = [
|
| 135 |
+
ltx_config.get("prompt_enhancer_image_caption_model_name_or_path"),
|
| 136 |
+
ltx_config.get("prompt_enhancer_llm_model_name_or_path"),
|
| 137 |
+
]
|
| 138 |
+
for repo_id in filter(None, enhancer_repos):
|
| 139 |
+
_ensure_hf_model(repo_id=repo_id, allow_patterns=["*.json", "*.safetensors", "*.bin"])
|
| 140 |
+
|
| 141 |
+
# --- ETAPA 3: Baixar Modelos SeedVR ---
|
| 142 |
+
print("\n--- ETAPA 3: Verificando Modelos SeedVR ---")
|
| 143 |
+
SEEDVR_MODELS_DIR.mkdir(parents=True, exist_ok=True)
|
| 144 |
+
seedvr_files = {
|
| 145 |
+
"seedvr2_ema_7b_fp16.safetensors": "MonsterMMORPG/SeedVR2_SECourses",
|
| 146 |
+
"seedvr2_ema_7b_sharp_fp16.safetensors": "MonsterMMORPG/SeedVR2_SECourses",
|
| 147 |
+
"ema_vae_fp16.safetensors": "MonsterMMORPG/SeedVR2_SECourses",
|
| 148 |
+
}
|
| 149 |
+
for filename, repo_id in seedvr_files.items():
|
| 150 |
+
if not (SEEDVR_MODELS_DIR / filename).is_file():
|
| 151 |
+
_ensure_hf_model(repo_id=repo_id, filenames=[filename], local_dir=SEEDVR_MODELS_DIR)
|
| 152 |
+
else:
|
| 153 |
+
print(f"Arquivo SeedVR '{filename}' já existe. Pulando.")
|
| 154 |
+
|
| 155 |
+
# --- ETAPA 4: Baixar Modelos VINCIE ---
|
| 156 |
+
print("\n--- ETAPA 4: Verificando Modelos VINCIE ---")
|
| 157 |
+
VINCIE_CKPT_DIR.mkdir(parents=True, exist_ok=True)
|
| 158 |
+
_ensure_hf_model(repo_id="ByteDance-Seed/VINCIE-3B", local_dir=VINCIE_CKPT_DIR)
|
| 159 |
+
|
| 160 |
+
# Cria o symlink de compatibilidade, se necessário
|
| 161 |
+
repo_ckpt_dir = VINCIE_REPO_DIR / "ckpt"
|
| 162 |
+
repo_ckpt_dir.mkdir(parents=True, exist_ok=True)
|
| 163 |
+
link = repo_ckpt_dir / "VINCIE-3B"
|
| 164 |
+
if not link.exists():
|
| 165 |
+
link.symlink_to(VINCIE_CKPT_DIR.resolve(), target_is_directory=True)
|
| 166 |
+
print(f"-> Symlink de compatibilidade VINCIE criado: '{link}' -> '{VINCIE_CKPT_DIR.resolve()}'")
|
| 167 |
+
else:
|
| 168 |
+
print(f"-> Symlink de compatibilidade VINCIE já existe.")
|
| 169 |
+
|
| 170 |
+
print("\n\n--- ✅ Setup Completo do Ambiente ADUC-SDR Concluído com Sucesso! ---")
|
| 171 |
+
print("Todos os repositórios e modelos foram verificados e estão prontos para uso.")
|
| 172 |
+
|
| 173 |
+
if __name__ == "__main__":
|
| 174 |
+
main()
|
start.sh
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
cp /app/LTX-Video/. /data/LTX-Video -rdfv
|
| 5 |
+
|
| 6 |
+
tree -L 6 /data
|
| 7 |
+
|
| 8 |
+
# ==============================================================================
|
| 9 |
+
# GERENCIAMENTO DE LOGS NA INICIALIZAÇÃO
|
| 10 |
+
# ==============================================================================
|
| 11 |
+
mkdir /data/logs
|
| 12 |
+
LOG_FILE="/data/logs/session.log"
|
| 13 |
+
|
| 14 |
+
# Verifica se o arquivo de log da sessão anterior existe e não está vazio
|
| 15 |
+
if [ -f "$LOG_FILE" ] && [ -s "$LOG_FILE" ]; then
|
| 16 |
+
echo "[STARTUP] Log da sessão anterior encontrado. Preparando para upload."
|
| 17 |
+
|
| 18 |
+
# Cria um nome de arquivo com timestamp para o upload
|
| 19 |
+
TODAY=$(date +%Y-%m-%d)
|
| 20 |
+
TIMESTAMP=$(date +%H-%M-%S)
|
| 21 |
+
UPLOAD_FILENAME="log-${TIMESTAMP}.txt"
|
| 22 |
+
export REPO_PATH="logs/${TODAY}/${UPLOAD_FILENAME}"
|
| 23 |
+
|
| 24 |
+
# Move o log antigo para um local temporário para evitar que a aplicação comece a escrever nele
|
| 25 |
+
TEMP_LOG_PATH="/data/previous_session.log"
|
| 26 |
+
mv "$LOG_FILE" "$TEMP_LOG_PATH"
|
| 27 |
+
|
| 28 |
+
echo "[STARTUP] Fazendo upload de '$TEMP_LOG_PATH' para o repositório em '$REPO_PATH'..."
|
| 29 |
+
|
| 30 |
+
# Executa o script de upload do Python em segundo plano para não bloquear a inicialização
|
| 31 |
+
# O token HF_TOKEN deve estar definido como uma variável de ambiente no seu contêiner
|
| 32 |
+
python - <<'PY' &
|
| 33 |
+
import os
|
| 34 |
+
import time
|
| 35 |
+
from huggingface_hub import HfApi, HfFolder
|
| 36 |
+
|
| 37 |
+
# Adiciona uma pequena espera para garantir que a rede esteja pronta
|
| 38 |
+
time.sleep(5)
|
| 39 |
+
|
| 40 |
+
repo = os.environ.get("SELF_HF_REPO_ID", "eeuuia/Tmp")
|
| 41 |
+
token = os.getenv("HF_TOKEN")
|
| 42 |
+
log_to_upload = "/data/previous_session.log"
|
| 43 |
+
repo_path = os.getenv("REPO_PATH",'logs/log.log')
|
| 44 |
+
|
| 45 |
+
if not token:
|
| 46 |
+
print("[UPLOAD_SCRIPT] AVISO: HF_TOKEN ausente; upload do log desabilitado.")
|
| 47 |
+
# Limpa o arquivo temporário mesmo assim
|
| 48 |
+
if os.path.exists(log_to_upload):
|
| 49 |
+
os.remove(log_to_upload)
|
| 50 |
+
exit()
|
| 51 |
+
|
| 52 |
+
if not repo_path:
|
| 53 |
+
print("[UPLOAD_SCRIPT] ERRO: REPO_PATH não definido.")
|
| 54 |
+
exit()
|
| 55 |
+
|
| 56 |
+
try:
|
| 57 |
+
print(f"[UPLOAD_SCRIPT] Iniciando upload para {repo}...")
|
| 58 |
+
api = HfApi(token=token)
|
| 59 |
+
api.upload_file(
|
| 60 |
+
path_or_fileobj=log_to_upload,
|
| 61 |
+
path_in_repo=repo_path,
|
| 62 |
+
repo_id=repo,
|
| 63 |
+
repo_type="model",
|
| 64 |
+
)
|
| 65 |
+
print(f"[UPLOAD_SCRIPT] Upload de log concluído com sucesso para: {repo_path}")
|
| 66 |
+
finally:
|
| 67 |
+
# Garante que o arquivo de log temporário seja sempre removido após a tentativa de upload
|
| 68 |
+
if os.path.exists(log_to_upload):
|
| 69 |
+
os.remove(log_to_upload)
|
| 70 |
+
print("[UPLOAD_SCRIPT] Arquivo de log temporário limpo.")
|
| 71 |
+
PY
|
| 72 |
+
|
| 73 |
+
else
|
| 74 |
+
echo "[STARTUP] Nenhum log da sessão anterior encontrado. Iniciando com um log limpo."
|
| 75 |
+
fi
|
| 76 |
+
|
| 77 |
+
# ==============================================================================
|
| 78 |
+
# INICIALIZAÇÃO DA APLICAÇÃO PRINCIPAL
|
| 79 |
+
# ==============================================================================
|
| 80 |
+
echo "[STARTUP] Iniciando a aplicação principal Gradio (app.py)..."
|
| 81 |
+
|
| 82 |
+
# Executa o setup.py primeiro para garantir que as dependências estão prontas
|
| 83 |
+
python /app/setup.py
|
| 84 |
+
|
| 85 |
+
# Inicia a aplicação Gradio
|
| 86 |
+
# O `exec` substitui o processo do shell pelo processo do python,
|
| 87 |
+
# o que é uma boa prática para scripts de inicialização de contêineres.
|
| 88 |
+
exec python /app/app.py
|