Update app.py
Browse files
app.py
CHANGED
|
@@ -2,163 +2,180 @@ import gradio as gr
|
|
| 2 |
import subprocess
|
| 3 |
import os
|
| 4 |
import sys
|
| 5 |
-
import
|
| 6 |
-
from
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
#
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
"""
|
| 15 |
-
|
| 16 |
-
|
|
|
|
|
|
|
| 17 |
"""
|
| 18 |
-
print("---
|
| 19 |
|
| 20 |
-
#
|
| 21 |
-
if
|
| 22 |
-
print(
|
| 23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
else:
|
| 25 |
print("Repositório SeedVR já existe.")
|
| 26 |
-
|
| 27 |
-
# Mudando para o diretório do projeto para os próximos comandos
|
| 28 |
-
os.chdir(SEEDVR_DIR)
|
| 29 |
|
| 30 |
-
#
|
| 31 |
-
print("
|
| 32 |
-
subprocess.run([sys.executable, "-m", "pip", "install", "flash_attn==2.5.9.post1", "--no-build-isolation"], check=True)
|
| 33 |
|
| 34 |
-
#
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
cache_dir = os.path.join(save_dir, "cache")
|
| 46 |
-
|
| 47 |
-
if not os.path.exists(os.path.join(save_dir, "README.md")): # Checa se o download já foi feito
|
| 48 |
-
print(f"Baixando o modelo '{repo_id}' para '{save_dir}'...")
|
| 49 |
-
snapshot_download(
|
| 50 |
-
cache_dir=cache_dir,
|
| 51 |
-
local_dir=save_dir,
|
| 52 |
-
repo_id=repo_id,
|
| 53 |
-
local_dir_use_symlinks=False,
|
| 54 |
-
resume_download=True,
|
| 55 |
-
allow_patterns=["*.json", "*.safetensors", "*.pth", "*.bin", "*.py", "*.md", "*.txt"],
|
| 56 |
-
)
|
| 57 |
-
else:
|
| 58 |
-
print("Modelo já foi baixado.")
|
| 59 |
|
| 60 |
-
print("--- Configuração do ambiente concluída ---")
|
| 61 |
-
# Retornar ao diretório raiz original
|
| 62 |
-
os.chdir("..")
|
| 63 |
|
| 64 |
-
#
|
| 65 |
-
|
|
|
|
| 66 |
|
| 67 |
-
#
|
|
|
|
| 68 |
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
|
| 76 |
-
input_folder = os.path.dirname(video_path.name)
|
| 77 |
output_folder = "outputs"
|
| 78 |
os.makedirs(output_folder, exist_ok=True)
|
| 79 |
|
| 80 |
-
#
|
| 81 |
-
|
| 82 |
-
|
| 83 |
command = [
|
| 84 |
-
"torchrun",
|
| 85 |
-
f"--nproc-per-node={num_gpus}",
|
| 86 |
"projects/inference_seedvr2_3b.py",
|
| 87 |
-
"--video_path", input_folder,
|
| 88 |
-
"--output_dir", f"../{output_folder}",
|
| 89 |
-
"--seed", str(
|
| 90 |
-
"--res_h",
|
| 91 |
-
"--res_w",
|
| 92 |
-
"--sp_size",
|
| 93 |
]
|
| 94 |
|
| 95 |
-
log_output = ""
|
|
|
|
| 96 |
try:
|
| 97 |
-
print(f"Executando comando: {' '.join(command)}")
|
| 98 |
-
# Executar o comando dentro do diretório SeedVR
|
| 99 |
process = subprocess.Popen(
|
| 100 |
command,
|
| 101 |
-
cwd=
|
| 102 |
stdout=subprocess.PIPE,
|
| 103 |
stderr=subprocess.STDOUT,
|
| 104 |
text=True,
|
| 105 |
encoding='utf-8'
|
| 106 |
)
|
| 107 |
|
| 108 |
-
# Capturar e exibir a saída em tempo real
|
| 109 |
while True:
|
| 110 |
line = process.stdout.readline()
|
| 111 |
if not line:
|
| 112 |
break
|
| 113 |
log_output += line
|
| 114 |
-
print(line
|
| 115 |
yield None, log_output
|
| 116 |
|
| 117 |
process.wait()
|
| 118 |
|
| 119 |
if process.returncode != 0:
|
| 120 |
-
raise
|
| 121 |
|
| 122 |
-
#
|
| 123 |
-
result_files = [os.path.join(output_folder, f) for f in os.listdir(output_folder) if f.endswith(
|
| 124 |
-
|
| 125 |
if not result_files:
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
return result_files, log_output
|
| 129 |
|
| 130 |
-
except
|
| 131 |
-
error_message = f"
|
| 132 |
print(error_message)
|
| 133 |
return None, error_message
|
| 134 |
-
except Exception as e:
|
| 135 |
-
return None, f"Ocorreu um erro inesperado: {str(e)}"
|
| 136 |
|
| 137 |
-
# --- 3. INTERFACE
|
| 138 |
|
| 139 |
with gr.Blocks() as demo:
|
| 140 |
-
gr.Markdown("#
|
| 141 |
-
gr.Markdown("
|
| 142 |
|
| 143 |
with gr.Row():
|
| 144 |
with gr.Column(scale=1):
|
| 145 |
-
video_input = gr.File(label="Vídeo de Entrada
|
| 146 |
-
seed_input = gr.Number(label="Seed", value=
|
| 147 |
-
res_h_input = gr.Number(label="Altura da Saída (res_h)", value=320)
|
| 148 |
-
res_w_input = gr.Number(label="Largura da Saída (res_w)", value=512)
|
| 149 |
-
sp_size_input = gr.Number(label="Tamanho do passo espacial (sp_size)", value=1)
|
| 150 |
-
|
| 151 |
run_button = gr.Button("Gerar Vídeo", variant="primary")
|
| 152 |
|
| 153 |
with gr.Column(scale=2):
|
| 154 |
-
gallery_output = gr.Gallery(label="Vídeo
|
| 155 |
-
log_display = gr.Textbox(label="Logs de Execução", lines=15, interactive=False)
|
| 156 |
-
|
| 157 |
run_button.click(
|
| 158 |
-
fn=
|
| 159 |
-
inputs=[video_input, seed_input
|
| 160 |
outputs=[gallery_output, log_display]
|
| 161 |
)
|
| 162 |
|
| 163 |
-
|
| 164 |
-
demo.launch()
|
|
|
|
| 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 |
+
# --- 1. CONFIGURAÇÃO E INSTALAÇÃO AUTOMÁTICA ---
|
| 10 |
+
# Esta parte do código é executada apenas uma vez quando o Space inicia.
|
| 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 |
+
# Salva o arquivo de entrada em uma pasta temporária
|
| 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 |
+
with open(input_video_path, "wb") as f_out, open(video_file.name, "rb") as f_in:
|
| 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 do SeedVR
|
| 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", f"../{input_folder}",
|
| 115 |
+
"--output_dir", f"../{output_folder}",
|
| 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"
|
| 123 |
+
|
| 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,
|
| 131 |
encoding='utf-8'
|
| 132 |
)
|
| 133 |
|
|
|
|
| 134 |
while True:
|
| 135 |
line = process.stdout.readline()
|
| 136 |
if not line:
|
| 137 |
break
|
| 138 |
log_output += line
|
| 139 |
+
print(line.strip()) # Imprime no console do Space para debug
|
| 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("# 🚀 Automação de Inferência para SeedVR2")
|
| 163 |
+
gr.Markdown("Envie um vídeo, clique em 'Gerar' e o processo de instalação e inferência será executado.")
|
| 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=42)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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)
|
| 174 |
+
|
| 175 |
run_button.click(
|
| 176 |
+
fn=run_inference_app,
|
| 177 |
+
inputs=[video_input, seed_input],
|
| 178 |
outputs=[gallery_output, log_display]
|
| 179 |
)
|
| 180 |
|
| 181 |
+
demo.launch()
|
|
|