Aduc-sdr commited on
Commit
b685d92
·
verified ·
1 Parent(s): 4a0885c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -67
app.py CHANGED
@@ -11,22 +11,10 @@
11
  # // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
  # // See the License for the specific language governing permissions and
13
  # // limitations under the License.
14
-
15
- import torch
16
- import torch.distributed as dist
17
  import os
18
- import gc
19
- import logging
20
  import sys
21
- import subprocess
22
- from pathlib import Path
23
- from urllib.parse import urlparse
24
- from torch.hub import download_url_to_file
25
- import gradio as gr
26
- import mediapy
27
- from einops import rearrange
28
- import shutil
29
- from omegaconf import OmegaConf
30
 
31
  # --- ETAPA 1: Preparação do Ambiente ---
32
  # Clonar o repositório para garantir que todas as pastas de código (data, common, etc.) existam.
@@ -34,7 +22,6 @@ from omegaconf import OmegaConf
34
  repo_dir_name = "SeedVR2-3B"
35
  if not os.path.exists(repo_dir_name):
36
  print(f"Clonando o repositório {repo_dir_name} para obter todo o código-fonte...")
37
- # Usamos --depth 1 para um clone mais rápido, já que não precisamos do histórico
38
  subprocess.run(f"git clone --depth 1 https://huggingface.co/spaces/ByteDance-Seed/{repo_dir_name}", shell=True, check=True)
39
 
40
  # --- ETAPA 2: Configuração dos Caminhos ---
@@ -45,31 +32,62 @@ print(f"Diretório de trabalho alterado para: {os.getcwd()}")
45
  sys.path.insert(0, os.path.abspath('.'))
46
  print(f"Diretório atual adicionado ao sys.path para importações.")
47
 
48
- # --- ETAPA 3: Instalação de Dependências e Download de Modelos ---
49
- # Agora que estamos no diretório correto, podemos prosseguir.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  import torch
52
  from pathlib import Path
53
  from urllib.parse import urlparse
54
  from torch.hub import download_url_to_file, get_dir
55
 
56
- # Função de download do original
57
  def load_file_from_url(url, model_dir=None, progress=True, file_name=None):
58
  if model_dir is None:
59
- hub_dir = get_dir()
60
- model_dir = os.path.join(hub_dir, 'checkpoints')
61
  os.makedirs(model_dir, exist_ok=True)
62
- parts = urlparse(url)
63
- filename = os.path.basename(parts.path)
64
- if file_name is not None:
65
- filename = file_name
66
  cached_file = os.path.abspath(os.path.join(model_dir, filename))
67
  if not os.path.exists(cached_file):
68
  print(f'Baixando: "{url}" para {cached_file}\n')
69
  download_url_to_file(url, cached_file, hash_prefix=None, progress=progress)
70
  return cached_file
71
 
72
- # URLs dos modelos
73
  pretrain_model_url = {
74
  'vae': 'https://huggingface.co/ByteDance-Seed/SeedVR-7B/resolve/main/ema_vae.pth',
75
  'dit': 'https://huggingface.co/ByteDance-Seed/SeedVR-7B/resolve/main/seedvr_ema_7b.pth',
@@ -78,40 +96,18 @@ pretrain_model_url = {
78
  'apex': 'https://huggingface.co/ByteDance-Seed/SeedVR2-3B/resolve/main/apex-0.1-cp310-cp310-linux_x86_64.whl'
79
  }
80
 
81
-
82
- # Criar diretório de checkpoints e baixar modelos
83
- ckpt_dir = Path('./ckpts')
84
- ckpt_dir.mkdir(exist_ok=True)
85
  for key, url in pretrain_model_url.items():
86
  filename = os.path.basename(url)
87
  model_dir = './ckpts' if key in ['vae', 'dit'] else '.'
88
- target_path = os.path.join(model_dir, filename)
89
- if not os.path.exists(target_path):
90
  load_file_from_url(url=url, model_dir=model_dir, progress=True, file_name=filename)
91
 
92
- # Baixar vídeos de exemplo
93
  torch.hub.download_url_to_file('https://huggingface.co/datasets/Iceclear/SeedVR_VideoDemos/resolve/main/seedvr_videos_crf23/aigc1k/23_1_lq.mp4', '01.mp4')
94
  torch.hub.download_url_to_file('https://huggingface.co/datasets/Iceclear/SeedVR_VideoDemos/resolve/main/seedvr_videos_crf23/aigc1k/28_1_lq.mp4', '02.mp4')
95
  torch.hub.download_url_to_file('https://huggingface.co/datasets/Iceclear/SeedVR_VideoDemos/resolve/main/seedvr_videos_crf23/aigc1k/2_1_lq.mp4', '03.mp4')
 
96
 
97
- # --- REFINAMENTO: Compilar dependências do zero para a GPU L40S (Ada Lovelace) ---
98
- python_executable = sys.executable
99
-
100
- print("Instalando flash-attn compilando do zero...")
101
- # Força a reinstalação a partir do zero para garantir que seja compilado para a GPU atual
102
- subprocess.run([python_executable, "-m", "pip", "install", "--force-reinstall", "--no-cache-dir", "flash-attn"], check=True)
103
-
104
- print("Clonando e compilando o Apex do zero...")
105
- if not os.path.exists("apex"):
106
- subprocess.run("git clone https://github.com/NVIDIA/apex", shell=True, check=True)
107
-
108
- # Instala o Apex a partir da fonte clonada, o que força a compilação para a GPU L40S
109
- # As flags --cpp_ext e --cuda_ext são essenciais para a compilação
110
- subprocess.run(
111
- [python_executable, "-m", "pip", "install", "-v", "--disable-pip-version-check", "--no-cache-dir", "--global-option=--cpp_ext", "--global-option=--cuda_ext", "./apex"],
112
- check=True
113
- )
114
- print("✅ Configuração do Apex concluída.")
115
 
116
  # --- ETAPA 4: Execução do Código Principal da Aplicação ---
117
  import mediapy
@@ -143,7 +139,6 @@ os.environ["MASTER_ADDR"] = "127.0.0.1"
143
  os.environ["MASTER_PORT"] = "12355"
144
  os.environ["RANK"] = str(0)
145
  os.environ["WORLD_SIZE"] = str(1)
146
- # Adiciona uma variável de ambiente que pode ajudar o PyTorch a debugar erros de CUDA
147
  os.environ["CUDA_LAUNCH_BLOCKING"] = "1"
148
 
149
  if os.path.exists("projects/video_diffusion_sr/color_fix.py"):
@@ -229,10 +224,8 @@ def generation_loop(video_path, seed=666, fps_out=24, batch_size=1, cfg_scale=1.
229
 
230
  with gr.Blocks(title="SeedVR2: Restauração de Vídeo em Um Passo") as demo:
231
  gr.HTML(f"""
232
-
233
- <p>
234
  <a href='https://github.com/ByteDance-Seed/SeedVR' target='_blank'>
235
- <b>SeedVR2 7B: One-Step Video Restoration via Diffusion Adversarial Post-Training</b></a>.<br>
236
  🔥 <b>SeedVR2</b> é um algoritmo de restauração de imagem e vídeo em um passo para conteúdo do mundo real e AIGC.
237
  </p>
238
  """)
@@ -255,17 +248,5 @@ with gr.Blocks(title="SeedVR2: Restauração de Vídeo em Um Passo") as demo:
255
  ],
256
  inputs=[input_file, seed, fps]
257
  )
258
- gr.HTML("""
259
- <hr>
260
- <p>Se você achou o SeedVR útil, por favor ⭐ o
261
- <a href='https://github.com/ByteDance-Seed/SeedVR' target='_blank'>repositório no GitHub</a>:</p>
262
- <a href="https://github.com/ByteDance-Seed/SeedVR" target="_blank">
263
- <img src="https://img.shields.io/github/stars/ByteDance-Seed/SeedVR?style=social" alt="GitHub Stars">
264
- </a>
265
- <h4>Aviso</h4>
266
- <p>Esta demonstração suporta até <b>720p e 121 frames para vídeos ou imagens 2k</b>.
267
- Para outros casos de uso, verifique o <a href='https://github.com/ByteDance-Seed/SeedVR' target='_blank'>repositório no GitHub</a>.</p>
268
- <h4>Limitações</h4>
269
- <p>Pode falhar em degradações pesadas ou em clipes AIGC com pouco movimento, causando excesso de nitidez ou restauração inadequada.</p>
270
- """)
271
  demo.queue().launch(share=True)
 
11
  # // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
  # // See the License for the specific language governing permissions and
13
  # // limitations under the License.
14
+ import spaces
15
+ import subprocess
 
16
  import os
 
 
17
  import sys
 
 
 
 
 
 
 
 
 
18
 
19
  # --- ETAPA 1: Preparação do Ambiente ---
20
  # Clonar o repositório para garantir que todas as pastas de código (data, common, etc.) existam.
 
22
  repo_dir_name = "SeedVR2-3B"
23
  if not os.path.exists(repo_dir_name):
24
  print(f"Clonando o repositório {repo_dir_name} para obter todo o código-fonte...")
 
25
  subprocess.run(f"git clone --depth 1 https://huggingface.co/spaces/ByteDance-Seed/{repo_dir_name}", shell=True, check=True)
26
 
27
  # --- ETAPA 2: Configuração dos Caminhos ---
 
32
  sys.path.insert(0, os.path.abspath('.'))
33
  print(f"Diretório atual adicionado ao sys.path para importações.")
34
 
35
+ # --- ETAPA 3: Instalação de Dependências (NA ORDEM CORRETA E COM A FLAG CORRETA) ---
36
+
37
+ python_executable = sys.executable
38
+
39
+ # **PASSO 3.1: Instalar requisitos PRIMEIRO para ter o PyTorch disponível**
40
+ print("Instalando dependências a partir do requirements.txt (isso inclui o PyTorch)...")
41
+ subprocess.run([python_executable, "-m", "pip", "install", "-r", "requirements.txt"], check=True)
42
+ print("✅ Dependências básicas (incluindo PyTorch) instaladas.")
43
+
44
+
45
+ # **PASSO 3.2: Compilar dependências otimizadas para a GPU**
46
+ print("Instalando flash-attn compilando do zero...")
47
+ subprocess.run([python_executable, "-m", "pip", "install", "--force-reinstall", "--no-cache-dir", "flash-attn"], check=True)
48
+
49
+ print("Clonando e compilando o Apex do zero (isso pode demorar um pouco)...")
50
+ if not os.path.exists("apex"):
51
+ subprocess.run("git clone https://github.com/NVIDIA/apex", shell=True, check=True)
52
 
53
+ # **CORREÇÃO FINAL: Adicionar a flag --no-build-isolation**
54
+ # Isso força o build a usar o ambiente atual (onde o torch já foi instalado)
55
+ # em vez de criar um ambiente isolado e vazio.
56
+ print("Compilando e instalando o Apex...")
57
+ subprocess.run(
58
+ [
59
+ python_executable, "-m", "pip", "install",
60
+ "--no-build-isolation", # A FLAG CRÍTICA QUE RESOLVE O PROBLEMA
61
+ "-v",
62
+ "--disable-pip-version-check",
63
+ "--no-cache-dir",
64
+ "--global-option=--cpp_ext",
65
+ "--global-option=--cuda_ext",
66
+ "./apex"
67
+ ],
68
+ check=True
69
+ )
70
+ print("✅ Configuração do Apex concluída.")
71
+
72
+
73
+ # **PASSO 3.3: Download dos modelos e dados de exemplo**
74
  import torch
75
  from pathlib import Path
76
  from urllib.parse import urlparse
77
  from torch.hub import download_url_to_file, get_dir
78
 
 
79
  def load_file_from_url(url, model_dir=None, progress=True, file_name=None):
80
  if model_dir is None:
81
+ hub_dir = get_dir(); model_dir = os.path.join(hub_dir, 'checkpoints')
 
82
  os.makedirs(model_dir, exist_ok=True)
83
+ parts = urlparse(url); filename = os.path.basename(parts.path)
84
+ if file_name is not None: filename = file_name
 
 
85
  cached_file = os.path.abspath(os.path.join(model_dir, filename))
86
  if not os.path.exists(cached_file):
87
  print(f'Baixando: "{url}" para {cached_file}\n')
88
  download_url_to_file(url, cached_file, hash_prefix=None, progress=progress)
89
  return cached_file
90
 
 
91
  pretrain_model_url = {
92
  'vae': 'https://huggingface.co/ByteDance-Seed/SeedVR-7B/resolve/main/ema_vae.pth',
93
  'dit': 'https://huggingface.co/ByteDance-Seed/SeedVR-7B/resolve/main/seedvr_ema_7b.pth',
 
96
  'apex': 'https://huggingface.co/ByteDance-Seed/SeedVR2-3B/resolve/main/apex-0.1-cp310-cp310-linux_x86_64.whl'
97
  }
98
 
99
+ ckpt_dir = Path('./ckpts'); ckpt_dir.mkdir(exist_ok=True)
 
 
 
100
  for key, url in pretrain_model_url.items():
101
  filename = os.path.basename(url)
102
  model_dir = './ckpts' if key in ['vae', 'dit'] else '.'
103
+ if not os.path.exists(os.path.join(model_dir, filename)):
 
104
  load_file_from_url(url=url, model_dir=model_dir, progress=True, file_name=filename)
105
 
 
106
  torch.hub.download_url_to_file('https://huggingface.co/datasets/Iceclear/SeedVR_VideoDemos/resolve/main/seedvr_videos_crf23/aigc1k/23_1_lq.mp4', '01.mp4')
107
  torch.hub.download_url_to_file('https://huggingface.co/datasets/Iceclear/SeedVR_VideoDemos/resolve/main/seedvr_videos_crf23/aigc1k/28_1_lq.mp4', '02.mp4')
108
  torch.hub.download_url_to_file('https://huggingface.co/datasets/Iceclear/SeedVR_VideoDemos/resolve/main/seedvr_videos_crf23/aigc1k/2_1_lq.mp4', '03.mp4')
109
+ print("✅ Modelos e dados de exemplo baixados.")
110
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
111
 
112
  # --- ETAPA 4: Execução do Código Principal da Aplicação ---
113
  import mediapy
 
139
  os.environ["MASTER_PORT"] = "12355"
140
  os.environ["RANK"] = str(0)
141
  os.environ["WORLD_SIZE"] = str(1)
 
142
  os.environ["CUDA_LAUNCH_BLOCKING"] = "1"
143
 
144
  if os.path.exists("projects/video_diffusion_sr/color_fix.py"):
 
224
 
225
  with gr.Blocks(title="SeedVR2: Restauração de Vídeo em Um Passo") as demo:
226
  gr.HTML(f"""
 
 
227
  <a href='https://github.com/ByteDance-Seed/SeedVR' target='_blank'>
228
+ <b>SeedVR2 7b: One-Step Video Restoration via Diffusion Adversarial Post-Training</b></a>.<br>
229
  🔥 <b>SeedVR2</b> é um algoritmo de restauração de imagem e vídeo em um passo para conteúdo do mundo real e AIGC.
230
  </p>
231
  """)
 
248
  ],
249
  inputs=[input_file, seed, fps]
250
  )
251
+
 
 
 
 
 
 
 
 
 
 
 
 
252
  demo.queue().launch(share=True)