Update app.py
Browse files
app.py
CHANGED
|
@@ -1,122 +1,34 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
import subprocess
|
| 3 |
import os
|
| 4 |
-
import sys
|
| 5 |
-
import time
|
| 6 |
-
from threading import Thread
|
| 7 |
-
from queue import Queue, Empty
|
| 8 |
|
| 9 |
-
#
|
| 10 |
-
#
|
| 11 |
-
|
| 12 |
-
INSTALLATION_FLAG = ".installation_complete"
|
| 13 |
-
SEEDVR_REPO_DIR = "SeedVR"
|
| 14 |
-
|
| 15 |
-
def run_subprocess(command, cwd=None):
|
| 16 |
-
"""Executa um comando de subprocesso e imprime a saída em tempo real."""
|
| 17 |
-
print(f"Executando comando: {' '.join(command)}")
|
| 18 |
-
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, cwd=cwd)
|
| 19 |
-
while True:
|
| 20 |
-
output = process.stdout.readline()
|
| 21 |
-
if output == '' and process.poll() is not None:
|
| 22 |
-
break
|
| 23 |
-
if output:
|
| 24 |
-
print(output.strip())
|
| 25 |
-
rc = process.poll()
|
| 26 |
-
if rc != 0:
|
| 27 |
-
raise RuntimeError(f"Comando falhou com código de saída {rc}: {' '.join(command)}")
|
| 28 |
-
|
| 29 |
-
def setup_environment():
|
| 30 |
-
"""
|
| 31 |
-
Traduz os comandos do manual do SeedVR para o ambiente do Hugging Face Spaces.
|
| 32 |
-
1. Clona o repositório.
|
| 33 |
-
2. Instala dependências especiais.
|
| 34 |
-
3. Cria um "flag" para não repetir a instalação.
|
| 35 |
-
"""
|
| 36 |
-
print("--- Verificando o ambiente de instalação ---")
|
| 37 |
-
|
| 38 |
-
# Se a instalação já foi feita, não faz nada.
|
| 39 |
-
if os.path.exists(INSTALLATION_FLAG):
|
| 40 |
-
print("Ambiente já configurado. Pulando a instalação.")
|
| 41 |
-
return
|
| 42 |
-
|
| 43 |
-
print("--- Iniciando configuração pela primeira vez ---")
|
| 44 |
-
|
| 45 |
-
# Comando 1: git clone ...
|
| 46 |
-
if not os.path.exists(SEEDVR_REPO_DIR):
|
| 47 |
-
run_subprocess(["git", "clone", "https://github.com/bytedance-seed/SeedVR.git"])
|
| 48 |
-
else:
|
| 49 |
-
print("Repositório SeedVR já existe.")
|
| 50 |
-
|
| 51 |
-
# Comandos 2 e 3: conda create/activate (substituído pelo `python_version: 3.10` no README.md)
|
| 52 |
-
print("Versão do Python já definida pelo Hugging Face Spaces.")
|
| 53 |
-
|
| 54 |
-
# Comando 4: pip install -r requirements.txt (já foi executado pelo Hugging Face)
|
| 55 |
-
print("Dependências do requirements.txt já instaladas.")
|
| 56 |
-
|
| 57 |
-
# Comando 5: pip install flash_attn... (instalação especial)
|
| 58 |
-
print("Instalando flash_attn com flags especiais...")
|
| 59 |
-
# Usamos sys.executable para garantir que estamos usando o pip do ambiente correto
|
| 60 |
-
flash_attn_command = [
|
| 61 |
-
sys.executable, "-m", "pip", "install",
|
| 62 |
-
"flash_attn==2.5.9.post1", "--no-build-isolation"
|
| 63 |
-
]
|
| 64 |
-
run_subprocess(flash_attn_command)
|
| 65 |
-
|
| 66 |
-
print("--- Configuração do ambiente concluída com sucesso! ---")
|
| 67 |
-
|
| 68 |
-
# Cria o arquivo de flag para indicar que a instalação foi concluída
|
| 69 |
-
with open(INSTALLATION_FLAG, "w") as f:
|
| 70 |
-
f.write("OK")
|
| 71 |
-
|
| 72 |
-
# Executa a função de configuração
|
| 73 |
-
setup_environment()
|
| 74 |
-
|
| 75 |
-
# O restante do código do app (interface Gradio, download do modelo, inferência)
|
| 76 |
-
# continuaria aqui, como na resposta anterior.
|
| 77 |
-
from huggingface_hub import snapshot_download
|
| 78 |
-
|
| 79 |
-
# --- 2. LÓGICA DA APLICAÇÃO (DOWNLOAD DO MODELO E INFERÊNCIA) ---
|
| 80 |
-
|
| 81 |
-
# Baixar o modelo (fora da função de inferência para não baixar toda vez)
|
| 82 |
-
CKPTS_DIR = os.path.join(SEEDVR_REPO_DIR, "ckpts")
|
| 83 |
-
if not os.path.exists(os.path.join(CKPTS_DIR, "README.md")):
|
| 84 |
-
print("Baixando o modelo SeedVR2-3B...")
|
| 85 |
-
snapshot_download(
|
| 86 |
-
repo_id="ByteDance-Seed/SeedVR2-3B",
|
| 87 |
-
local_dir=CKPTS_DIR,
|
| 88 |
-
local_dir_use_symlinks=False,
|
| 89 |
-
resume_download=True,
|
| 90 |
-
allow_patterns=["*.json", "*.safetensors", "*.pth", "*.bin", "*.py", "*.md", "*.txt"],
|
| 91 |
-
)
|
| 92 |
-
else:
|
| 93 |
-
print("Modelo já foi baixado.")
|
| 94 |
|
| 95 |
def run_inference_app(video_file, seed_num):
|
| 96 |
if video_file is None:
|
| 97 |
return None, "Por favor, envie um arquivo de vídeo."
|
| 98 |
|
| 99 |
-
#
|
| 100 |
input_folder = "inputs"
|
| 101 |
os.makedirs(input_folder, exist_ok=True)
|
|
|
|
|
|
|
| 102 |
input_video_path = os.path.join(input_folder, os.path.basename(video_file.name))
|
| 103 |
-
|
| 104 |
-
f_out.write(f_in.read())
|
| 105 |
|
| 106 |
output_folder = "outputs"
|
| 107 |
os.makedirs(output_folder, exist_ok=True)
|
| 108 |
|
| 109 |
-
# Comando de inferência
|
| 110 |
-
# Usando 4 GPUs, como especificado no hardware 4xL40s
|
| 111 |
command = [
|
| 112 |
"torchrun", "--nproc-per-node=4",
|
| 113 |
"projects/inference_seedvr2_3b.py",
|
| 114 |
-
"--video_path",
|
| 115 |
-
"--output_dir",
|
| 116 |
"--seed", str(seed_num),
|
| 117 |
"--res_h", "320",
|
| 118 |
"--res_w", "512",
|
| 119 |
-
"--sp_size", "1"
|
| 120 |
]
|
| 121 |
|
| 122 |
log_output = "Iniciando a inferência...\n" + ' '.join(command) + "\n\n"
|
|
@@ -124,7 +36,6 @@ def run_inference_app(video_file, seed_num):
|
|
| 124 |
try:
|
| 125 |
process = subprocess.Popen(
|
| 126 |
command,
|
| 127 |
-
cwd=SEEDVR_REPO_DIR, # Executa o comando de dentro do diretório do repositório
|
| 128 |
stdout=subprocess.PIPE,
|
| 129 |
stderr=subprocess.STDOUT,
|
| 130 |
text=True,
|
|
@@ -136,38 +47,33 @@ def run_inference_app(video_file, seed_num):
|
|
| 136 |
if not line:
|
| 137 |
break
|
| 138 |
log_output += line
|
| 139 |
-
print(line.strip())
|
| 140 |
yield None, log_output
|
| 141 |
|
| 142 |
process.wait()
|
| 143 |
|
| 144 |
if process.returncode != 0:
|
| 145 |
-
raise RuntimeError("O script de inferência falhou.")
|
| 146 |
|
| 147 |
-
# Encontra o vídeo gerado
|
| 148 |
result_files = [os.path.join(output_folder, f) for f in os.listdir(output_folder) if f.endswith('.mp4')]
|
| 149 |
if not result_files:
|
| 150 |
-
return None, log_output + "\nERRO: Nenhum vídeo foi gerado."
|
| 151 |
|
| 152 |
return result_files, log_output + "\n\nInferência concluída com sucesso!"
|
| 153 |
|
| 154 |
except Exception as e:
|
| 155 |
error_message = f"{log_output}\n\nOcorreu um erro: {str(e)}"
|
| 156 |
-
print(error_message)
|
| 157 |
return None, error_message
|
| 158 |
|
| 159 |
-
# --- 3. INTERFACE GRÁFICA (GRADIO) ---
|
| 160 |
-
|
| 161 |
with gr.Blocks() as demo:
|
| 162 |
-
gr.Markdown("# 🚀
|
| 163 |
-
gr.Markdown("
|
| 164 |
|
| 165 |
with gr.Row():
|
| 166 |
with gr.Column(scale=1):
|
| 167 |
video_input = gr.File(label="Vídeo de Entrada")
|
| 168 |
-
seed_input = gr.Number(label="Seed", value=
|
| 169 |
run_button = gr.Button("Gerar Vídeo", variant="primary")
|
| 170 |
-
|
| 171 |
with gr.Column(scale=2):
|
| 172 |
gallery_output = gr.Gallery(label="Vídeo de Saída", show_label=True)
|
| 173 |
log_display = gr.Textbox(label="Logs de Execução", lines=15, interactive=False, autoscroll=True)
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import subprocess
|
| 3 |
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
+
# Não precisamos mais de nenhuma função de setup, clone ou pip install aqui!
|
| 6 |
+
# O Dockerfile já cuidou de tudo.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
def run_inference_app(video_file, seed_num):
|
| 9 |
if video_file is None:
|
| 10 |
return None, "Por favor, envie um arquivo de vídeo."
|
| 11 |
|
| 12 |
+
# O app roda de dentro do diretório /app/SeedVR, então os caminhos são relativos
|
| 13 |
input_folder = "inputs"
|
| 14 |
os.makedirs(input_folder, exist_ok=True)
|
| 15 |
+
|
| 16 |
+
# O Gradio nos dá um caminho temporário, vamos movê-lo para um local conhecido
|
| 17 |
input_video_path = os.path.join(input_folder, os.path.basename(video_file.name))
|
| 18 |
+
os.rename(video_file.name, input_video_path)
|
|
|
|
| 19 |
|
| 20 |
output_folder = "outputs"
|
| 21 |
os.makedirs(output_folder, exist_ok=True)
|
| 22 |
|
| 23 |
+
# Comando de inferência. O ambiente conda já está "ativado" graças ao Dockerfile.
|
|
|
|
| 24 |
command = [
|
| 25 |
"torchrun", "--nproc-per-node=4",
|
| 26 |
"projects/inference_seedvr2_3b.py",
|
| 27 |
+
"--video_path", input_folder,
|
| 28 |
+
"--output_dir", output_folder,
|
| 29 |
"--seed", str(seed_num),
|
| 30 |
"--res_h", "320",
|
| 31 |
"--res_w", "512",
|
|
|
|
| 32 |
]
|
| 33 |
|
| 34 |
log_output = "Iniciando a inferência...\n" + ' '.join(command) + "\n\n"
|
|
|
|
| 36 |
try:
|
| 37 |
process = subprocess.Popen(
|
| 38 |
command,
|
|
|
|
| 39 |
stdout=subprocess.PIPE,
|
| 40 |
stderr=subprocess.STDOUT,
|
| 41 |
text=True,
|
|
|
|
| 47 |
if not line:
|
| 48 |
break
|
| 49 |
log_output += line
|
| 50 |
+
print(line.strip())
|
| 51 |
yield None, log_output
|
| 52 |
|
| 53 |
process.wait()
|
| 54 |
|
| 55 |
if process.returncode != 0:
|
| 56 |
+
raise RuntimeError("O script de inferência falhou. Verifique os logs.")
|
| 57 |
|
|
|
|
| 58 |
result_files = [os.path.join(output_folder, f) for f in os.listdir(output_folder) if f.endswith('.mp4')]
|
| 59 |
if not result_files:
|
| 60 |
+
return None, log_output + "\n\nERRO: Nenhum vídeo foi gerado."
|
| 61 |
|
| 62 |
return result_files, log_output + "\n\nInferência concluída com sucesso!"
|
| 63 |
|
| 64 |
except Exception as e:
|
| 65 |
error_message = f"{log_output}\n\nOcorreu um erro: {str(e)}"
|
|
|
|
| 66 |
return None, error_message
|
| 67 |
|
|
|
|
|
|
|
| 68 |
with gr.Blocks() as demo:
|
| 69 |
+
gr.Markdown("# 🚀 Inferência SeedVR2 com Ambiente Conda")
|
| 70 |
+
gr.Markdown("Este ambiente foi construído com Conda usando um Dockerfile para máxima estabilidade.")
|
| 71 |
|
| 72 |
with gr.Row():
|
| 73 |
with gr.Column(scale=1):
|
| 74 |
video_input = gr.File(label="Vídeo de Entrada")
|
| 75 |
+
seed_input = gr.Number(label="Seed", value=123)
|
| 76 |
run_button = gr.Button("Gerar Vídeo", variant="primary")
|
|
|
|
| 77 |
with gr.Column(scale=2):
|
| 78 |
gallery_output = gr.Gallery(label="Vídeo de Saída", show_label=True)
|
| 79 |
log_display = gr.Textbox(label="Logs de Execução", lines=15, interactive=False, autoscroll=True)
|