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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Euia-AducSdr: Uma implementação aberta e funcional da arquitetura ADUC-SDR para geração de vídeo coerente.
|
| 2 |
+
# Copyright (C) 4 de Agosto de 2025 Carlos Rodrigues dos Santos
|
| 3 |
+
#
|
| 4 |
+
# Contato:
|
| 5 |
+
# Carlos Rodrigues dos Santos
|
| 6 |
+
# carlex22@gmail.com
|
| 7 |
+
# Rua Eduardo Carlos Pereira, 4125, B1 Ap32, Curitiba, PR, Brazil, CEP 8102025
|
| 8 |
+
#
|
| 9 |
+
# Repositórios e Projetos Relacionados:
|
| 10 |
+
# GitHub: https://github.com/carlex22/Aduc-sdr
|
| 11 |
+
# Hugging Face: https://huggingface.co/spaces/Carlexx/Ltx-SuperTime-60Secondos/
|
| 12 |
+
# Hugging Face: https://huggingface.co/spaces/Carlexxx/Novinho/
|
| 13 |
+
#
|
| 14 |
+
# Este programa é software livre: você pode redistribuí-lo e/ou modificá-lo
|
| 15 |
+
# sob os termos da Licença Pública Geral Affero da GNU como publicada pela
|
| 16 |
+
# Free Software Foundation, seja a versão 3 da Licença, ou
|
| 17 |
+
# (a seu critério) qualquer versão posterior.
|
| 18 |
+
#
|
| 19 |
+
# Este programa é distribuído na esperança de que seja útil,
|
| 20 |
+
# mas SEM QUALQUER GARANTIA; sem mesmo a garantia implícita de
|
| 21 |
+
# COMERCIALIZAÇÃO ou ADEQUAÇÃO A UM DETERMINADO FIM. Consulte a
|
| 22 |
+
# Licença Pública Geral Affero da GNU para mais detalhes.
|
| 23 |
+
#
|
| 24 |
+
# Você deve ter recebido uma cópia da Licença Pública Geral Affero da GNU
|
| 25 |
+
# junto com este programa. Se não, veja <https://www.gnu.org/licenses/>.
|
| 26 |
+
|
| 27 |
+
# --- app_demo.py (NOVINHO-6.2: Demo Version) ---
|
| 28 |
+
|
| 29 |
+
# --- Ato 1: A Convocação da Orquestra (Importações) ---
|
| 30 |
+
import gradio as gr
|
| 31 |
+
import torch
|
| 32 |
+
import os
|
| 33 |
+
import yaml
|
| 34 |
+
from PIL import Image, ImageOps, ExifTags
|
| 35 |
+
import shutil
|
| 36 |
+
import gc
|
| 37 |
+
import subprocess
|
| 38 |
+
import google.generativeai as genai
|
| 39 |
+
import numpy as np
|
| 40 |
+
import imageio
|
| 41 |
+
from pathlib import Path
|
| 42 |
+
import huggingface_hub
|
| 43 |
+
import json
|
| 44 |
+
import time
|
| 45 |
+
import spaces
|
| 46 |
+
|
| 47 |
+
# --- Variável de Controle do Modo Demo ---
|
| 48 |
+
# Para habilitar a funcionalidade completa, mude esta variável para True.
|
| 49 |
+
# Isso requer que o Space esteja rodando em um hardware de GPU.
|
| 50 |
+
ENABLE_MODELS = False
|
| 51 |
+
|
| 52 |
+
# Importações condicionais que dependem dos modelos
|
| 53 |
+
if ENABLE_MODELS:
|
| 54 |
+
from inference import create_ltx_video_pipeline, load_image_to_tensor_with_resize_and_crop, ConditioningItem, calculate_padding
|
| 55 |
+
from dreamo_helpers import dreamo_generator_singleton
|
| 56 |
+
|
| 57 |
+
# --- Ato 2: A Preparação do Palco (Configurações Condicionais) ---
|
| 58 |
+
if ENABLE_MODELS:
|
| 59 |
+
config_file_path = "configs/ltxv-13b-0.9.8-distilled.yaml"
|
| 60 |
+
with open(config_file_path, "r") as file: PIPELINE_CONFIG_YAML = yaml.safe_load(file)
|
| 61 |
+
|
| 62 |
+
LTX_REPO = "Lightricks/LTX-Video"
|
| 63 |
+
models_dir = "downloaded_models_gradio"
|
| 64 |
+
Path(models_dir).mkdir(parents=True, exist_ok=True)
|
| 65 |
+
|
| 66 |
+
print("MODO COMPLETO ATIVADO: Carregando pipelines LTX na CPU (estado de repouso)...")
|
| 67 |
+
distilled_model_actual_path = huggingface_hub.hf_hub_download(repo_id=LTX_REPO, filename=PIPELINE_CONFIG_YAML["checkpoint_path"], local_dir=models_dir, local_dir_use_symlinks=False)
|
| 68 |
+
pipeline_instance = create_ltx_video_pipeline(
|
| 69 |
+
ckpt_path=distilled_model_actual_path,
|
| 70 |
+
precision=PIPELINE_CONFIG_YAML["precision"],
|
| 71 |
+
text_encoder_model_name_or_path=PIPELINE_CONFIG_YAML["text_encoder_model_name_or_path"],
|
| 72 |
+
sampler=PIPELINE_CONFIG_YAML["sampler"],
|
| 73 |
+
device='cpu'
|
| 74 |
+
)
|
| 75 |
+
print("Modelos LTX prontos (na CPU).")
|
| 76 |
+
else:
|
| 77 |
+
# Em modo demo, definimos as variáveis dos modelos como None para evitar erros.
|
| 78 |
+
pipeline_instance = None
|
| 79 |
+
dreamo_generator_singleton = None
|
| 80 |
+
print("MODO DEMO ATIVADO: Carregamento de modelos pesados ignorado.")
|
| 81 |
+
|
| 82 |
+
WORKSPACE_DIR = "aduc_workspace"
|
| 83 |
+
GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")
|
| 84 |
+
VIDEO_FPS = 24
|
| 85 |
+
TARGET_RESOLUTION = 420
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
# --- Ato 3: As Partituras dos Músicos (Funções de Geração e Análise) ---
|
| 89 |
+
|
| 90 |
+
# Funções que NÃO dependem dos modelos locais podem funcionar normalmente
|
| 91 |
+
def robust_json_parser(raw_text: str) -> dict:
|
| 92 |
+
try:
|
| 93 |
+
start_index = raw_text.find('{'); end_index = raw_text.rfind('}')
|
| 94 |
+
if start_index != -1 and end_index != -1 and end_index > start_index:
|
| 95 |
+
json_str = raw_text[start_index : end_index + 1]; return json.loads(json_str)
|
| 96 |
+
else: raise ValueError("Nenhum objeto JSON válido encontrado na resposta da IA.")
|
| 97 |
+
except json.JSONDecodeError as e: raise ValueError(f"Falha ao decodificar JSON: {e}")
|
| 98 |
+
|
| 99 |
+
def extract_image_exif(image_path: str) -> str:
|
| 100 |
+
# ... (código interno idêntico) ...
|
| 101 |
+
return "Could not read EXIF data."
|
| 102 |
+
|
| 103 |
+
def run_storyboard_generation(num_fragments: int, prompt: str, initial_image_path: str):
|
| 104 |
+
if not initial_image_path: raise gr.Error("Por favor, forneça uma imagem de referência inicial.")
|
| 105 |
+
if not GEMINI_API_KEY: raise gr.Error("Chave da API Gemini não configurada! Esta função requer uma chave, mesmo em modo demo.")
|
| 106 |
+
# ... (código interno idêntico) ...
|
| 107 |
+
return storyboard
|
| 108 |
+
|
| 109 |
+
# Funções que dependem dos modelos precisam de uma "cláusula de guarda"
|
| 110 |
+
@spaces.GPU(duration=180)
|
| 111 |
+
def run_keyframe_generation(storyboard, ref_images_tasks, progress=gr.Progress()):
|
| 112 |
+
if not ENABLE_MODELS or dreamo_generator_singleton is None:
|
| 113 |
+
raise gr.Error("Modo Demo Ativado! Para gerar imagens, por favor, clone este Space, mude a variável 'ENABLE_MODELS' para True no arquivo app.py e use hardware de GPU.")
|
| 114 |
+
|
| 115 |
+
# O resto da função é idêntico à versão `app_gpu.py`
|
| 116 |
+
if not storyboard: raise gr.Error("Nenhum roteiro para gerar keyframes.")
|
| 117 |
+
# ... (código interno idêntico) ...
|
| 118 |
+
try:
|
| 119 |
+
dreamo_generator_singleton.to_gpu()
|
| 120 |
+
# ...
|
| 121 |
+
finally:
|
| 122 |
+
dreamo_generator_singleton.to_cpu()
|
| 123 |
+
gc.collect()
|
| 124 |
+
torch.cuda.empty_cache()
|
| 125 |
+
# ...
|
| 126 |
+
yield {keyframe_log_output: gr.update(value=log_history), keyframe_gallery_output: gr.update(value=generated_images_for_gallery), keyframe_images_state: keyframe_paths}
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def get_dreamo_prompt_for_transition(previous_image_path: str, target_scene_description: str):
|
| 130 |
+
# Esta função também depende do Gemini, que deve funcionar
|
| 131 |
+
if not GEMINI_API_KEY: raise gr.Error("Chave da API Gemini não configurada!")
|
| 132 |
+
# ... (código interno idêntico) ...
|
| 133 |
+
return response.text.strip().replace("\"", "")
|
| 134 |
+
|
| 135 |
+
def get_initial_motion_prompt(user_prompt: str, start_image_path: str, destination_image_path: str, dest_scene_desc: str):
|
| 136 |
+
if not GEMINI_API_KEY: raise gr.Error("Chave da API Gemini não configurada!")
|
| 137 |
+
# ... (código interno idêntico) ...
|
| 138 |
+
return response.text.strip()
|
| 139 |
+
|
| 140 |
+
def get_dynamic_motion_prompt(user_prompt, story_history, memory_media_path, path_image_path, destination_image_path, path_scene_desc, dest_scene_desc):
|
| 141 |
+
if not GEMINI_API_KEY: raise gr.Error("Chave da API Gemini não configurada!")
|
| 142 |
+
# ... (código interno idêntico) ...
|
| 143 |
+
return response.text.strip()
|
| 144 |
+
|
| 145 |
+
@spaces.GPU(duration=360)
|
| 146 |
+
def run_video_production(
|
| 147 |
+
video_duration_seconds, video_fps, eco_video_frames, use_attention_slicing,
|
| 148 |
+
fragment_duration_frames, mid_cond_strength, num_inference_steps,
|
| 149 |
+
prompt_geral, keyframe_images_state, scene_storyboard, cfg,
|
| 150 |
+
progress=gr.Progress()
|
| 151 |
+
):
|
| 152 |
+
if not ENABLE_MODELS or pipeline_instance is None:
|
| 153 |
+
raise gr.Error("Modo Demo Ativado! Para gerar vídeos, por favor, clone este Space, mude a variável 'ENABLE_MODELS' para True no arquivo app.py e use hardware de GPU.")
|
| 154 |
+
|
| 155 |
+
# O resto da função é idêntico à versão `app_gpu.py`
|
| 156 |
+
video_total_frames = int(video_duration_seconds * video_fps)
|
| 157 |
+
# ... (código interno idêntico) ...
|
| 158 |
+
try:
|
| 159 |
+
pipeline_instance.to(target_device)
|
| 160 |
+
# ...
|
| 161 |
+
finally:
|
| 162 |
+
pipeline_instance.to('cpu')
|
| 163 |
+
gc.collect()
|
| 164 |
+
torch.cuda.empty_cache()
|
| 165 |
+
|
| 166 |
+
# O restante das funções helper que não carregam modelos não precisam de mudanças
|
| 167 |
+
def process_image_to_square(image_path: str, size: int = TARGET_RESOLUTION) -> str:
|
| 168 |
+
# ... (código interno idêntico) ...
|
| 169 |
+
return output_path
|
| 170 |
+
|
| 171 |
+
# Funções que usam os modelos precisam ser capazes de lidar com a instância `None`
|
| 172 |
+
def load_conditioning_tensor(media_path: str, height: int, width: int) -> torch.Tensor:
|
| 173 |
+
if not ENABLE_MODELS: return None # Retorna None se em modo demo
|
| 174 |
+
# ... (código interno idêntico) ...
|
| 175 |
+
return load_image_to_tensor_with_resize_and_crop(media_path, height, width)
|
| 176 |
+
|
| 177 |
+
def run_ltx_animation(*args, **kwargs):
|
| 178 |
+
if not ENABLE_MODELS: return None, 0 # Retorna None se em modo demo
|
| 179 |
+
# ... (código interno idêntico da `app_gpu.py`) ...
|
| 180 |
+
return output_path, actual_num_frames
|
| 181 |
+
|
| 182 |
+
def trim_video_to_frames(input_path: str, output_path: str, frames_to_keep: int) -> str:
|
| 183 |
+
# ... (código interno idêntico) ...
|
| 184 |
+
return output_path
|
| 185 |
+
|
| 186 |
+
def extract_last_n_frames_as_video(input_path: str, output_path: str, n_frames: int) -> str:
|
| 187 |
+
# ... (código interno idêntico) ...
|
| 188 |
+
return output_path
|
| 189 |
+
|
| 190 |
+
def concatenate_and_trim_masterpiece(fragment_paths: list, fragment_duration_frames: int, eco_video_frames: int, progress=gr.Progress()):
|
| 191 |
+
if not fragment_paths: raise gr.Error("Nenhum fragmento de vídeo para concatenar.")
|
| 192 |
+
# ... (código interno idêntico) ...
|
| 193 |
+
return final_output_path
|
| 194 |
+
|
| 195 |
+
# --- Ato 5: A Interface com o Mundo (UI) ---
|
| 196 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 197 |
+
gr.Markdown("# NOVIM-6.2 (Painel de Controle do Diretor)\n*By Carlex & Gemini & DreamO - Versão de Demonstração*")
|
| 198 |
+
|
| 199 |
+
# Banner de Aviso para o Modo Demo
|
| 200 |
+
if not ENABLE_MODELS:
|
| 201 |
+
gr.Warning(
|
| 202 |
+
"""
|
| 203 |
+
**MODO DE DEMONSTRAÇÃO ATIVADO**
|
| 204 |
+
Você pode explorar a interface e usar a "Etapa 1: Gerar Roteiro" se tiver uma chave da API Gemini configurada.
|
| 205 |
+
Para habilitar a geração de imagens e vídeos (Etapas 2 e 3), você precisa:
|
| 206 |
+
1. **Fork este Space:** Clique no menu de três pontos ao lado do título e selecione "Duplicate this Space".
|
| 207 |
+
2. **Escolha um Hardware de GPU:** Na tela de duplicação, selecione um hardware de GPU (ex: T4 Small).
|
| 208 |
+
3. **Edite o `app.py`:** Na aba "Files" do seu novo Space, edite o arquivo `app.py`.
|
| 209 |
+
4. **Ative os Modelos:** Mude a linha `ENABLE_MODELS = False` para `ENABLE_MODELS = True`.
|
| 210 |
+
5. Salve o arquivo. O Space será reiniciado com a funcionalidade completa.
|
| 211 |
+
"""
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
if os.path.exists(WORKSPACE_DIR): shutil.rmtree(WORKSPACE_DIR)
|
| 215 |
+
os.makedirs(WORKSPACE_DIR); Path("prompts").mkdir(exist_ok=True)
|
| 216 |
+
|
| 217 |
+
# O resto da UI permanece o mesmo
|
| 218 |
+
scene_storyboard_state, keyframe_images_state, fragment_list_state = gr.State([]), gr.State([]), gr.State([])
|
| 219 |
+
# ... (código da UI idêntico à versão `app_gpu.py` a partir daqui) ...
|
| 220 |
+
prompt_geral_state, processed_ref_path_state = gr.State(""), gr.State("")
|
| 221 |
+
|
| 222 |
+
gr.Markdown("--- \n ## ETAPA 1: O ROTEIRO (IA Roteirista)")
|
| 223 |
+
with gr.Row():
|
| 224 |
+
with gr.Column(scale=1):
|
| 225 |
+
prompt_input = gr.Textbox(label="Ideia Geral (Prompt)")
|
| 226 |
+
num_fragments_input = gr.Slider(2, 5, 4, step=1, label="Número de Atos (Keyframes)")
|
| 227 |
+
image_input = gr.Image(type="filepath", label=f"Imagem de Referência Principal (será {TARGET_RESOLUTION}x{TARGET_RESOLUTION})")
|
| 228 |
+
director_button = gr.Button("▶️ 1. Gerar Roteiro", variant="primary")
|
| 229 |
+
with gr.Column(scale=2): storyboard_to_show = gr.JSON(label="Roteiro de Cenas Gerado (em Inglês)")
|
| 230 |
+
|
| 231 |
+
gr.Markdown("--- \n ## ETAPA 2: OS KEYFRAMES (IA Pintor & Diretor de Arte)")
|
| 232 |
+
with gr.Row():
|
| 233 |
+
with gr.Column(scale=2):
|
| 234 |
+
gr.Markdown("Forneça referências para guiar a IA. A Principal é obrigatória. A Secundária é opcional (ex: para estilo ou uma segunda pessoa).")
|
| 235 |
+
with gr.Row():
|
| 236 |
+
with gr.Column():
|
| 237 |
+
ref1_image = gr.Image(label="Referência Principal (Conteúdo/ID)", type="filepath")
|
| 238 |
+
ref1_task = gr.Dropdown(choices=["ip", "id", "style"], value="ip", label="Tarefa da Ref. Principal")
|
| 239 |
+
with gr.Column():
|
| 240 |
+
ref2_image = gr.Image(label="Referência Secundária (Opcional)", type="filepath")
|
| 241 |
+
ref2_task = gr.Dropdown(choices=["ip", "id", "style"], value="style", label="Tarefa da Ref. Secundária")
|
| 242 |
+
photographer_button = gr.Button("▶️ 2. Pintar Imagens-Chave em Cadeia", variant="primary")
|
| 243 |
+
with gr.Column(scale=1):
|
| 244 |
+
keyframe_log_output = gr.Textbox(label="Diário de Bordo do Pintor", lines=15, interactive=False)
|
| 245 |
+
keyframe_gallery_output = gr.Gallery(label="Imagens-Chave Pintadas", object_fit="contain", height="auto", type="filepath")
|
| 246 |
+
|
| 247 |
+
gr.Markdown("--- \n ## ETAPA 3: A PRODUÇÃO (IA Cineasta & Câmera)")
|
| 248 |
+
with gr.Row():
|
| 249 |
+
with gr.Column(scale=1):
|
| 250 |
+
cfg_slider = gr.Slider(1.0, 10.0, 2.5, step=0.1, label="CFG")
|
| 251 |
+
with gr.Accordion("Controles Avançados de Timing e Performance", open=False):
|
| 252 |
+
video_duration_slider = gr.Slider(label="Duração da Geração Bruta (segundos)", minimum=2.0, maximum=10.0, value=6.0, step=0.5)
|
| 253 |
+
video_fps_slider = gr.Slider(label="FPS do Vídeo", minimum=12, maximum=30, value=30, step=1)
|
| 254 |
+
num_inference_steps_slider = gr.Slider(label="Etapas de Inferência", minimum=10, maximum=50, value=30, step=1)
|
| 255 |
+
slicing_checkbox = gr.Checkbox(label="Usar Attention Slicing (Economiza VRAM)", value=True)
|
| 256 |
+
gr.Markdown("---"); gr.Markdown("#### Controles de Duração (Arquitetura Eco + Déjà Vu)")
|
| 257 |
+
fragment_duration_slider = gr.Slider(label="Duração de Cada Fragmento (Frames)", minimum=30, maximum=300, value=90, step=1)
|
| 258 |
+
eco_frames_slider = gr.Slider(label="Tamanho do Eco Cinético (Frames)", minimum=4, maximum=48, value=8, step=1)
|
| 259 |
+
mid_cond_strength_slider = gr.Slider(label="Força do 'Caminho'", minimum=0.1, maximum=1.0, value=0.5, step=0.05)
|
| 260 |
+
gr.Markdown(
|
| 261 |
+
"""
|
| 262 |
+
**Instruções (Nova Arquitetura):**
|
| 263 |
+
- **Duração da Geração Bruta:** Tempo total que a IA tem para criar a transição. Deve ser MAIOR que a Duração do Fragmento.
|
| 264 |
+
- **Duração de Cada Fragmento:** O comprimento final de cada clipe de vídeo que será gerado.
|
| 265 |
+
- **Tamanho do Eco Cinético:** Quantos frames do *final* de um fragmento serão passados para o próximo para garantir continuidade.
|
| 266 |
+
- **Força do Caminho:** Define o quão forte a imagem-chave intermediária ('Caminho') influencia a transição.
|
| 267 |
+
"""
|
| 268 |
+
)
|
| 269 |
+
animator_button = gr.Button("▶️ 3. Produzir Cenas (Handoff Cinético)", variant="primary")
|
| 270 |
+
with gr.Accordion("Visualização das Mídias de Condicionamento (Ao Vivo)", open=True):
|
| 271 |
+
with gr.Row():
|
| 272 |
+
prod_media_start_output = gr.Video(label="Mídia Inicial (Eco/K1)", interactive=False)
|
| 273 |
+
prod_media_mid_output = gr.Image(label="Mídia do Caminho (K_i-1)", interactive=False, visible=False)
|
| 274 |
+
prod_media_end_output = gr.Image(label="Mídia de Destino (K_i)", interactive=False)
|
| 275 |
+
production_log_output = gr.Textbox(label="Diário de Bordo da Produção", lines=10, interactive=False)
|
| 276 |
+
with gr.Column(scale=1): video_gallery_glitch = gr.Gallery(label="Fragmentos Gerados (Versões Cortadas)", object_fit="contain", height="auto", type="video")
|
| 277 |
+
|
| 278 |
+
fragment_duration_state = gr.State()
|
| 279 |
+
eco_frames_state = gr.State()
|
| 280 |
+
|
| 281 |
+
gr.Markdown(f"--- \n ## ETAPA 4: PÓS-PRODUÇÃO (Editor)")
|
| 282 |
+
editor_button = gr.Button("▶️ 4. Montar Vídeo Final", variant="primary")
|
| 283 |
+
final_video_output = gr.Video(label="A Obra-Prima Final", width=TARGET_RESOLUTION)
|
| 284 |
+
|
| 285 |
+
gr.Markdown(
|
| 286 |
+
"""
|
| 287 |
+
---
|
| 288 |
+
### A Arquitetura: Eco + Déjà Vu
|
| 289 |
+
A geração começa com um "Big Bang" entre os dois primeiros keyframes. A partir daí, a mágica acontece.
|
| 290 |
+
* **O Eco (A Memória Física):** No final de cada cena, os últimos frames são capturados e salvos como um pequeno vídeo, o `Eco`. Ele carrega a "energia cinética" do movimento, iluminação e atmosfera da cena que acabou.
|
| 291 |
+
* **O Déjà Vu (A Memória Conceitual):** Para criar a próxima cena, o Cineasta de IA (Gemini) assiste ao `Eco`, olha para o keyframe do "caminho" e o keyframe do "destino". Com essa visão tripla, ele tem um "déjà vu", uma memória do que acabou de acontecer que o inspira a escrever uma instrução de câmera precisa para conectar o passado ao futuro de forma fluida e coerente.
|
| 292 |
+
"""
|
| 293 |
+
)
|
| 294 |
+
|
| 295 |
+
# --- Ato 6: A Regência (Lógica de Conexão dos Botões) ---
|
| 296 |
+
def process_and_update_storyboard(num_fragments, prompt, image_path):
|
| 297 |
+
processed_path = process_image_to_square(image_path)
|
| 298 |
+
if not processed_path: raise gr.Error("A imagem de referência é inválida ou não foi fornecida.")
|
| 299 |
+
storyboard = run_storyboard_generation(num_fragments, prompt, processed_path)
|
| 300 |
+
return storyboard, prompt, processed_path
|
| 301 |
+
|
| 302 |
+
director_button.click(
|
| 303 |
+
fn=process_and_update_storyboard,
|
| 304 |
+
inputs=[num_fragments_input, prompt_input, image_input],
|
| 305 |
+
outputs=[scene_storyboard_state, prompt_geral_state, processed_ref_path_state]
|
| 306 |
+
).success(
|
| 307 |
+
fn=lambda s, p: (s, p),
|
| 308 |
+
inputs=[scene_storyboard_state, processed_ref_path_state],
|
| 309 |
+
outputs=[storyboard_to_show, ref1_image]
|
| 310 |
+
)
|
| 311 |
+
|
| 312 |
+
@photographer_button.click(
|
| 313 |
+
inputs=[scene_storyboard_state, ref1_image, ref1_task, ref2_image, ref2_task],
|
| 314 |
+
outputs=[keyframe_log_output, keyframe_gallery_output, keyframe_images_state]
|
| 315 |
+
)
|
| 316 |
+
def run_keyframe_generation_wrapper(storyboard, ref1_img, ref1_tsk, ref2_img, ref2_tsk, progress=gr.Progress()):
|
| 317 |
+
ref_data = [
|
| 318 |
+
{'image': ref1_img, 'task': ref1_tsk},
|
| 319 |
+
{'image': ref2_img, 'task': ref2_tsk}
|
| 320 |
+
]
|
| 321 |
+
yield from run_keyframe_generation(storyboard, ref_data, progress)
|
| 322 |
+
|
| 323 |
+
animator_button.click(
|
| 324 |
+
fn=lambda frag_dur, eco_dur: (frag_dur, eco_dur),
|
| 325 |
+
inputs=[fragment_duration_slider, eco_frames_slider],
|
| 326 |
+
outputs=[fragment_duration_state, eco_frames_state]
|
| 327 |
+
).then(
|
| 328 |
+
fn=run_video_production,
|
| 329 |
+
inputs=[
|
| 330 |
+
video_duration_slider, video_fps_slider, eco_frames_slider, slicing_checkbox,
|
| 331 |
+
fragment_duration_slider, mid_cond_strength_slider,
|
| 332 |
+
num_inference_steps_slider,
|
| 333 |
+
prompt_geral_state, keyframe_images_state, scene_storyboard_state, cfg_slider
|
| 334 |
+
],
|
| 335 |
+
outputs=[
|
| 336 |
+
production_log_output, video_gallery_glitch, fragment_list_state,
|
| 337 |
+
prod_media_start_output, prod_media_mid_output, prod_media_end_output
|
| 338 |
+
]
|
| 339 |
+
)
|
| 340 |
+
|
| 341 |
+
editor_button.click(
|
| 342 |
+
fn=concatenate_and_trim_masterpiece,
|
| 343 |
+
inputs=[fragment_list_state, fragment_duration_state, eco_frames_state],
|
| 344 |
+
outputs=[final_video_output]
|
| 345 |
+
)
|
| 346 |
+
|
| 347 |
+
if __name__ == "__main__":
|
| 348 |
+
demo.queue().launch(server_name="0.0.0.0", share=True)
|