Update api/seedvr_server.py
Browse files- api/seedvr_server.py +24 -19
api/seedvr_server.py
CHANGED
|
@@ -6,22 +6,25 @@ import shutil
|
|
| 6 |
import mimetypes
|
| 7 |
import time
|
| 8 |
from pathlib import Path
|
| 9 |
-
from typing import Optional,
|
| 10 |
from types import SimpleNamespace
|
| 11 |
|
| 12 |
from huggingface_hub import hf_hub_download
|
| 13 |
|
| 14 |
-
# Adiciona dinamicamente o caminho do repositório clonado ao sys.path
|
| 15 |
# Isso é crucial para que a importação do 'inference_cli' funcione.
|
| 16 |
SEEDVR_REPO_PATH = Path(os.getenv("SEEDVR_ROOT", "/data/SeedVR"))
|
| 17 |
if str(SEEDVR_REPO_PATH) not in sys.path:
|
|
|
|
| 18 |
sys.path.insert(0, str(SEEDVR_REPO_PATH))
|
| 19 |
|
| 20 |
# Tenta importar as funções necessárias APÓS a modificação do path.
|
|
|
|
| 21 |
try:
|
| 22 |
from inference_cli import run_inference_logic, save_frames_to_video
|
| 23 |
except ImportError as e:
|
| 24 |
-
print(f"ERRO FATAL: Não foi possível importar de 'inference_cli.py'.
|
|
|
|
| 25 |
raise e
|
| 26 |
|
| 27 |
class SeedVRServer:
|
|
@@ -53,6 +56,7 @@ class SeedVRServer:
|
|
| 53 |
""" Clona o repositório do SeedVR se ele não existir. """
|
| 54 |
if not (self.SEEDVR_ROOT / ".git").exists():
|
| 55 |
print(f"[SeedVRServer] Clonando repositório para {self.SEEDVR_ROOT}...")
|
|
|
|
| 56 |
subprocess.run(["git", "clone", "--depth", "1", self.REPO_URL, str(self.SEEDVR_ROOT)], check=True)
|
| 57 |
else:
|
| 58 |
print("[SeedVRServer] Repositório SeedVR já existe.")
|
|
@@ -79,50 +83,51 @@ class SeedVRServer:
|
|
| 79 |
self,
|
| 80 |
file_path: str, *,
|
| 81 |
seed: int, res_h: int, res_w: int, sp_size: int,
|
| 82 |
-
fps: Optional[float] = None, progress=None
|
| 83 |
) -> str:
|
| 84 |
"""
|
| 85 |
Executa a inferência diretamente no mesmo processo e retorna o caminho do arquivo de saída.
|
| 86 |
"""
|
| 87 |
-
|
|
|
|
| 88 |
out_dir.mkdir(parents=True, exist_ok=True)
|
| 89 |
output_filepath = out_dir / f"result_{Path(file_path).stem}.mp4"
|
| 90 |
|
| 91 |
-
# Simula o objeto 'args' que a função de lógica espera
|
|
|
|
| 92 |
args = SimpleNamespace(
|
| 93 |
video_path=file_path,
|
| 94 |
output=str(output_filepath),
|
| 95 |
model_dir=str(self.CKPTS_ROOT),
|
| 96 |
seed=seed,
|
| 97 |
-
resolution=res_h, # O script do SeedVR usa a altura (lado menor) como referência
|
| 98 |
batch_size=sp_size,
|
| 99 |
model="seedvr2_ema_3b_fp16.safetensors",
|
| 100 |
preserve_vram=True,
|
| 101 |
-
debug=True,
|
| 102 |
cuda_device=",".join(map(str, range(self.NUM_GPUS_TOTAL))),
|
| 103 |
skip_first_frames=0,
|
| 104 |
-
load_cap=0
|
|
|
|
| 105 |
)
|
| 106 |
|
| 107 |
try:
|
| 108 |
-
|
| 109 |
-
progress(0.1, desc="Iniciando a lógica de inferência...")
|
| 110 |
-
|
| 111 |
-
# Chama a função importada do script original
|
| 112 |
result_tensor, original_fps, _, _ = run_inference_logic(args, progress_callback=progress)
|
| 113 |
|
| 114 |
if progress:
|
| 115 |
-
progress(0.
|
| 116 |
|
|
|
|
| 117 |
final_fps = fps if fps and fps > 0 else original_fps
|
| 118 |
save_frames_to_video(result_tensor, str(output_filepath), final_fps, args.debug)
|
| 119 |
|
| 120 |
-
print(f"✅
|
| 121 |
|
|
|
|
| 122 |
return str(output_filepath)
|
| 123 |
|
| 124 |
except Exception as e:
|
| 125 |
-
print(f"❌
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
raise # Propaga o erro para a UI do Gradio, que o exibirá.
|
|
|
|
| 6 |
import mimetypes
|
| 7 |
import time
|
| 8 |
from pathlib import Path
|
| 9 |
+
from typing import Optional, Callable
|
| 10 |
from types import SimpleNamespace
|
| 11 |
|
| 12 |
from huggingface_hub import hf_hub_download
|
| 13 |
|
| 14 |
+
# Adiciona dinamicamente o caminho do repositório clonado ao sys.path.
|
| 15 |
# Isso é crucial para que a importação do 'inference_cli' funcione.
|
| 16 |
SEEDVR_REPO_PATH = Path(os.getenv("SEEDVR_ROOT", "/data/SeedVR"))
|
| 17 |
if str(SEEDVR_REPO_PATH) not in sys.path:
|
| 18 |
+
# Insere no início da lista para garantir prioridade de importação.
|
| 19 |
sys.path.insert(0, str(SEEDVR_REPO_PATH))
|
| 20 |
|
| 21 |
# Tenta importar as funções necessárias APÓS a modificação do path.
|
| 22 |
+
# Se falhar, a aplicação não pode continuar.
|
| 23 |
try:
|
| 24 |
from inference_cli import run_inference_logic, save_frames_to_video
|
| 25 |
except ImportError as e:
|
| 26 |
+
print(f"ERRO FATAL: Não foi possível importar de 'inference_cli.py'.")
|
| 27 |
+
print(f"Verifique se o repositório em '{SEEDVR_REPO_PATH}' está correto e completo.")
|
| 28 |
raise e
|
| 29 |
|
| 30 |
class SeedVRServer:
|
|
|
|
| 56 |
""" Clona o repositório do SeedVR se ele não existir. """
|
| 57 |
if not (self.SEEDVR_ROOT / ".git").exists():
|
| 58 |
print(f"[SeedVRServer] Clonando repositório para {self.SEEDVR_ROOT}...")
|
| 59 |
+
# Usamos subprocess.run aqui porque é uma tarefa de inicialização única.
|
| 60 |
subprocess.run(["git", "clone", "--depth", "1", self.REPO_URL, str(self.SEEDVR_ROOT)], check=True)
|
| 61 |
else:
|
| 62 |
print("[SeedVRServer] Repositório SeedVR já existe.")
|
|
|
|
| 83 |
self,
|
| 84 |
file_path: str, *,
|
| 85 |
seed: int, res_h: int, res_w: int, sp_size: int,
|
| 86 |
+
fps: Optional[float] = None, progress: Optional[Callable] = None
|
| 87 |
) -> str:
|
| 88 |
"""
|
| 89 |
Executa a inferência diretamente no mesmo processo e retorna o caminho do arquivo de saída.
|
| 90 |
"""
|
| 91 |
+
# Cria um diretório de saída único para salvar o resultado.
|
| 92 |
+
out_dir = self.OUTPUT_ROOT / f"run_{int(time.time())}_{Path(file_path).stem}"
|
| 93 |
out_dir.mkdir(parents=True, exist_ok=True)
|
| 94 |
output_filepath = out_dir / f"result_{Path(file_path).stem}.mp4"
|
| 95 |
|
| 96 |
+
# Simula o objeto 'args' que a função de lógica do inference_cli espera.
|
| 97 |
+
# Usamos SimpleNamespace para criar um objeto simples com atributos.
|
| 98 |
args = SimpleNamespace(
|
| 99 |
video_path=file_path,
|
| 100 |
output=str(output_filepath),
|
| 101 |
model_dir=str(self.CKPTS_ROOT),
|
| 102 |
seed=seed,
|
| 103 |
+
resolution=res_h, # O script do SeedVR usa a altura (lado menor) como referência.
|
| 104 |
batch_size=sp_size,
|
| 105 |
model="seedvr2_ema_3b_fp16.safetensors",
|
| 106 |
preserve_vram=True,
|
| 107 |
+
debug=True, # Mantém o debug ativo para logs detalhados.
|
| 108 |
cuda_device=",".join(map(str, range(self.NUM_GPUS_TOTAL))),
|
| 109 |
skip_first_frames=0,
|
| 110 |
+
load_cap=0,
|
| 111 |
+
output_format='video' # Garante que sempre gere vídeo
|
| 112 |
)
|
| 113 |
|
| 114 |
try:
|
| 115 |
+
# Chama a função importada do script original, passando o callback de progresso.
|
|
|
|
|
|
|
|
|
|
| 116 |
result_tensor, original_fps, _, _ = run_inference_logic(args, progress_callback=progress)
|
| 117 |
|
| 118 |
if progress:
|
| 119 |
+
progress(0.95, "Saving the final video...")
|
| 120 |
|
| 121 |
+
# Define o FPS final: usa o valor da UI ou o original do vídeo de entrada.
|
| 122 |
final_fps = fps if fps and fps > 0 else original_fps
|
| 123 |
save_frames_to_video(result_tensor, str(output_filepath), final_fps, args.debug)
|
| 124 |
|
| 125 |
+
print(f"✅ Video saved successfully to: {output_filepath}")
|
| 126 |
|
| 127 |
+
# Retorna o caminho do arquivo gerado para a UI.
|
| 128 |
return str(output_filepath)
|
| 129 |
|
| 130 |
except Exception as e:
|
| 131 |
+
print(f"❌ Error during direct inference execution: {e}")
|
| 132 |
+
# Propaga o erro para a UI do Gradio, que o exibirá de forma amigável.
|
| 133 |
+
raise
|
|
|