Upload 2 files
Browse files- ai_studio_code (20).txt +29 -0
- ai_studio_code (6).py +164 -0
ai_studio_code (20).txt
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Dependências do SeedVR
|
| 2 |
+
torch==2.1.0
|
| 3 |
+
torchvision==0.16.0
|
| 4 |
+
torchaudio==2.1.0
|
| 5 |
+
accelerate==0.24.1
|
| 6 |
+
av==11.0.0
|
| 7 |
+
beautifulsoup4==4.12.2
|
| 8 |
+
einops==0.7.0
|
| 9 |
+
gradio
|
| 10 |
+
huggingface_hub
|
| 11 |
+
iopath==0.1.10
|
| 12 |
+
ipython==8.17.2
|
| 13 |
+
omegaconf==2.3.0
|
| 14 |
+
pandas==2.1.3
|
| 15 |
+
pytorch-lightning==2.1.0
|
| 16 |
+
pytorchvideo==0.1.5
|
| 17 |
+
ftfy==6.1.1
|
| 18 |
+
regex==2023.10.3
|
| 19 |
+
timm==0.9.10
|
| 20 |
+
transformers==4.35.2
|
| 21 |
+
tqdm==4.66.1
|
| 22 |
+
webdataset==0.2.70
|
| 23 |
+
diffusers==0.26.3
|
| 24 |
+
controlnet_aux==0.0.7
|
| 25 |
+
opencv-python
|
| 26 |
+
scikit-image
|
| 27 |
+
xformers==0.0.22.post7
|
| 28 |
+
# Dependência com instalação especial (tratada no app.py)
|
| 29 |
+
# flash_attn==2.5.9.post1 --no-build-isolation
|
ai_studio_code (6).py
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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O INICIAL (Executa apenas uma vez) ---
|
| 9 |
+
|
| 10 |
+
# Diretório base para o projeto SeedVR
|
| 11 |
+
SEEDVR_DIR = "SeedVR"
|
| 12 |
+
|
| 13 |
+
def setup():
|
| 14 |
+
"""
|
| 15 |
+
Clona o repositório, instala dependências especiais e baixa o modelo.
|
| 16 |
+
Esta função é executada uma vez quando o Space é iniciado.
|
| 17 |
+
"""
|
| 18 |
+
print("--- Iniciando configuração do ambiente ---")
|
| 19 |
+
|
| 20 |
+
# Etapa 1: Clonar o repositório SeedVR se ainda não existir
|
| 21 |
+
if not os.path.exists(SEEDVR_DIR):
|
| 22 |
+
print(f"Clonando o repositório SeedVR de https://github.com/bytedance-seed/SeedVR.git...")
|
| 23 |
+
subprocess.run(["git", "clone", "https://github.com/bytedance-seed/SeedVR.git"], check=True)
|
| 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 |
+
# Etapa 2: Instalar dependências que exigem comandos específicos
|
| 31 |
+
print("Instalando flash_attn...")
|
| 32 |
+
subprocess.run([sys.executable, "-m", "pip", "install", "flash_attn==2.5.9.post1", "--no-build-isolation"], check=True)
|
| 33 |
+
|
| 34 |
+
# Nota sobre o Apex: O arquivo .whl precisa estar no seu repositório Hugging Face
|
| 35 |
+
apex_whl_path = "apex-0.1-cp310-cp310-linux_x86_64.whl"
|
| 36 |
+
if os.path.exists(apex_whl_path):
|
| 37 |
+
print(f"Instalando {apex_whl_path}...")
|
| 38 |
+
subprocess.run([sys.executable, "-m", "pip", "install", apex_whl_path], check=True)
|
| 39 |
+
else:
|
| 40 |
+
print(f"AVISO: Arquivo '{apex_whl_path}' não encontrado. A instalação do Apex foi pulada. Por favor, adicione este arquivo ao seu repositório.")
|
| 41 |
+
|
| 42 |
+
# Etapa 3: Baixar o modelo do Hugging Face Hub
|
| 43 |
+
save_dir = "ckpts/"
|
| 44 |
+
repo_id = "ByteDance-Seed/SeedVR2-3B"
|
| 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 |
+
# Executa a configuração
|
| 65 |
+
setup()
|
| 66 |
+
|
| 67 |
+
# --- 2. LÓGICA DA INFERÊNCIA ---
|
| 68 |
+
|
| 69 |
+
def run_inference(video_path, seed, res_h, res_w, sp_size, progress=gr.Progress(track_tqdm=True)):
|
| 70 |
+
"""
|
| 71 |
+
Executa o script de inferência do SeedVR usando torchrun.
|
| 72 |
+
"""
|
| 73 |
+
if video_path is None:
|
| 74 |
+
return None, "Por favor, faça o upload de um arquivo de vídeo de entrada."
|
| 75 |
+
|
| 76 |
+
input_folder = os.path.dirname(video_path.name)
|
| 77 |
+
output_folder = "outputs"
|
| 78 |
+
os.makedirs(output_folder, exist_ok=True)
|
| 79 |
+
|
| 80 |
+
# Determinar o número de GPUs disponíveis. Para 4xL40s, será 4.
|
| 81 |
+
num_gpus = 4
|
| 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}", # Navega para fora do dir SeedVR
|
| 89 |
+
"--seed", str(seed),
|
| 90 |
+
"--res_h", str(res_h),
|
| 91 |
+
"--res_w", str(res_w),
|
| 92 |
+
"--sp_size", str(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=SEEDVR_DIR,
|
| 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, end='')
|
| 115 |
+
yield None, log_output
|
| 116 |
+
|
| 117 |
+
process.wait()
|
| 118 |
+
|
| 119 |
+
if process.returncode != 0:
|
| 120 |
+
raise subprocess.CalledProcessError(process.returncode, command, output=log_output)
|
| 121 |
+
|
| 122 |
+
# Encontrar os arquivos de vídeo gerados
|
| 123 |
+
result_files = [os.path.join(output_folder, f) for f in os.listdir(output_folder) if f.endswith(('.mp4', '.avi', '.mov'))]
|
| 124 |
+
|
| 125 |
+
if not result_files:
|
| 126 |
+
return None, log_output + "\n\nERRO: Nenhum arquivo de vídeo foi gerado."
|
| 127 |
+
|
| 128 |
+
return result_files, log_output
|
| 129 |
+
|
| 130 |
+
except subprocess.CalledProcessError as e:
|
| 131 |
+
error_message = f"Erro ao executar a inferência.\nOutput:\n{e.output}"
|
| 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 GRAPHEMICA (GRADIO) ---
|
| 138 |
+
|
| 139 |
+
with gr.Blocks() as demo:
|
| 140 |
+
gr.Markdown("# 🎥 Interface de Inferência para SeedVR2")
|
| 141 |
+
gr.Markdown("Faça o upload de um vídeo, ajuste os parâmetros e clique em 'Gerar Vídeo' para iniciar a inferência.")
|
| 142 |
+
|
| 143 |
+
with gr.Row():
|
| 144 |
+
with gr.Column(scale=1):
|
| 145 |
+
video_input = gr.File(label="Vídeo de Entrada (.mp4, .mov, etc.)")
|
| 146 |
+
seed_input = gr.Number(label="Seed", value=123)
|
| 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 Gerado", show_label=True, elem_id="gallery")
|
| 155 |
+
log_display = gr.Textbox(label="Logs de Execução", lines=15, interactive=False)
|
| 156 |
+
|
| 157 |
+
run_button.click(
|
| 158 |
+
fn=run_inference,
|
| 159 |
+
inputs=[video_input, seed_input, res_h_input, res_w_input, sp_size_input],
|
| 160 |
+
outputs=[gallery_output, log_display]
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
if __name__ == "__main__":
|
| 164 |
+
demo.launch()
|