import spaces import gradio as gr import os import sys import argparse import random import time import numpy as np from omegaconf import OmegaConf import torch import torchvision from pytorch_lightning import seed_everything from huggingface_hub import hf_hub_download from einops import repeat import torchvision.transforms as transforms from utils.utils import instantiate_from_config sys.path.insert(0, "scripts/evaluation") from funcs import ( batch_ddim_sampling, load_model_checkpoint, get_latent_z, save_videos ) from transformers import pipeline from diffusers import DiffusionPipeline # 상수 정의 MAX_SEED = np.iinfo(np.int32).max MAX_IMAGE_SIZE = 2048 # DynamiCrafter 모델 설정 def download_model(): REPO_ID = 'Doubiiu/DynamiCrafter_1024' filename_list = ['model.ckpt'] if not os.path.exists('./checkpoints/dynamicrafter_1024_v1/'): os.makedirs('./checkpoints/dynamicrafter_1024_v1/') for filename in filename_list: local_file = os.path.join('./checkpoints/dynamicrafter_1024_v1/', filename) if not os.path.exists(local_file): hf_hub_download(repo_id=REPO_ID, filename=filename, local_dir='./checkpoints/dynamicrafter_1024_v1/', force_download=True) # 모델 다운로드 실행 download_model() ckpt_path='checkpoints/dynamicrafter_1024_v1/model.ckpt' config_file='configs/inference_1024_v1.0.yaml' config = OmegaConf.load(config_file) model_config = config.pop("model", OmegaConf.create()) model_config['params']['unet_config']['params']['use_checkpoint']=False model = instantiate_from_config(model_config) assert os.path.exists(ckpt_path), "Error: checkpoint Not Found!" model = load_model_checkpoint(model, ckpt_path) model.eval() model = model.cuda() # 번역 모델 초기화 translator = pipeline("translation", model="Helsinki-NLP/opus-mt-ko-en") import torch from diffusers import DiffusionPipeline # FLUX 모델 설정 device = "cuda" if torch.cuda.is_available() else "cpu" dtype = torch.float16 if torch.cuda.is_available() else torch.float32 pipe = DiffusionPipeline.from_pretrained("black-forest-labs/FLUX.1-dev", torch_dtype=torch.float16) pipe.enable_model_cpu_offload() # 메모리 최적화 (GPU 사용 시에만 적용) if torch.cuda.is_available(): pipe.enable_attention_slicing() @spaces.GPU(duration=300) def infer_t2i(prompt, seed=42, randomize_seed=False, width=1024, height=576, guidance_scale=5.0, num_inference_steps=28, progress=gr.Progress(track_tqdm=True)): # 한글 입력 감지 및 번역 if any('\u3131' <= char <= '\u318E' or '\uAC00' <= char <= '\uD7A3' for char in prompt): translated = translator(prompt, max_length=512)[0]['translation_text'] prompt = translated print(f"Translated prompt: {prompt}") if randomize_seed: seed = random.randint(0, MAX_SEED) generator = torch.Generator(device=device).manual_seed(seed) with torch.no_grad(): image = pipe( prompt=prompt, width=width, height=height, num_inference_steps=num_inference_steps, generator=generator, guidance_scale=guidance_scale ).images[0] torch.cuda.empty_cache() return image, seed, prompt # 번역된 프롬프트도 반환 @spaces.GPU(duration=300) def infer(image, prompt, steps=50, cfg_scale=7.5, eta=1.0, fs=3, seed=123, video_length=2): # 한글 입력 감지 및 번역 if any('\u3131' <= char <= '\u318E' or '\uAC00' <= char <= '\uD7A3' for char in prompt): translated = translator(prompt, max_length=512)[0]['translation_text'] prompt = translated print(f"Translated prompt: {prompt}") resolution = (576, 1024) save_fps = 8 seed_everything(seed) transform = transforms.Compose([ transforms.Resize(min(resolution)), transforms.CenterCrop(resolution), ]) torch.cuda.empty_cache() print('start:', prompt, time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))) start = time.time() if steps > 60: steps = 60 batch_size=1 channels = model.model.diffusion_model.out_channels frames = int(video_length * save_fps) # 비디오 길이에 따른 프레임 수 계산 h, w = resolution[0] // 8, resolution[1] // 8 noise_shape = [batch_size, channels, frames, h, w] # text cond with torch.no_grad(), torch.cuda.amp.autocast(): text_emb = model.get_learned_conditioning([prompt]) # img cond img_tensor = torch.from_numpy(image).permute(2, 0, 1).float().to(model.device) img_tensor = (img_tensor / 255. - 0.5) * 2 image_tensor_resized = transform(img_tensor) #3,256,256 videos = image_tensor_resized.unsqueeze(0) # bchw z = get_latent_z(model, videos.unsqueeze(2)) #bc,1,hw img_tensor_repeat = repeat(z, 'b c t h w -> b c (repeat t) h w', repeat=frames) cond_images = model.embedder(img_tensor.unsqueeze(0)) ## blc img_emb = model.image_proj_model(cond_images) imtext_cond = torch.cat([text_emb, img_emb], dim=1) fs = torch.tensor([fs], dtype=torch.long, device=model.device) cond = {"c_crossattn": [imtext_cond], "fs": fs, "c_concat": [img_tensor_repeat]} ## inference batch_samples = batch_ddim_sampling(model, cond, noise_shape, n_samples=1, ddim_steps=steps, ddim_eta=eta, cfg_scale=cfg_scale) ## b,samples,c,t,h,w video_path = './output.mp4' save_videos(batch_samples, './', filenames=['output'], fps=save_fps) return video_path i2v_examples = [ ['prompts/1024/astronaut04.png', 'a man in an astronaut suit playing a guitar', 30, 7.5, 1.0, 6, 123, 2], ] css = """ .tab-nav { border-bottom: 2px solid #ddd; padding: 0; margin-bottom: 20px; } .tab-nav button { background-color: #f8f8f8; border: none; outline: none; cursor: pointer; padding: 10px 20px; transition: 0.3s; font-size: 16px; border-radius: 10px 10px 0 0; margin-right: 5px; } .tab-nav button:hover { background-color: #ddd; } .tab-nav button.selected { background-color: #fff; border: 2px solid #ddd; border-bottom: 2px solid #fff; font-weight: bold; } .tab-content { padding: 20px; border: 2px solid #ddd; border-radius: 0 10px 10px 10px; } /* 탭별 색상 */ .tab-nav button:nth-child(1) { border-top: 3px solid #ff6b6b; } .tab-nav button:nth-child(2) { border-top: 3px solid #4ecdc4; } .tab-nav button:nth-child(3) { border-top: 3px solid #f7b731; } """ # 먼저 text-to-video 함수를 정의합니다. @spaces.GPU(duration=300) def infer_t2v(prompt, seed=42, randomize_seed=False, width=1024, height=576, guidance_scale=5.0, num_inference_steps=28, video_steps=50, video_cfg_scale=7.5, video_eta=1.0, video_fps=3, video_length=2): # 텍스트로 이미지 생성 image, _, translated_prompt = infer_t2i(prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps) # 생성된 이미지로 비디오 생성 video_path = infer(np.array(image), translated_prompt, video_steps, video_cfg_scale, video_eta, video_fps, seed, video_length) return video_path, translated_prompt with gr.Blocks(analytics_enabled=False, css=css) as dynamicrafter_iface: gr.Markdown("숏폼 스튜디오") with gr.Tab(label='Text to Image'): with gr.Column(): with gr.Row(): t2i_input_text = gr.Text(label='Prompt') with gr.Row(): t2i_seed = gr.Slider(label='Seed', minimum=0, maximum=MAX_SEED, step=1, value=123) t2i_randomize_seed = gr.Checkbox(label='Randomize seed', value=False) with gr.Row(): t2i_width = gr.Slider(label='Width', minimum=256, maximum=MAX_IMAGE_SIZE, step=64, value=1024) t2i_height = gr.Slider(label='Height', minimum=256, maximum=MAX_IMAGE_SIZE, step=64, value=576) with gr.Row(): t2i_guidance_scale = gr.Slider(label='Guidance Scale', minimum=1.0, maximum=20.0, step=0.1, value=5.0) t2i_num_inference_steps = gr.Slider(label='Inference Steps', minimum=1, maximum=100, step=1, value=28) # t2i_generate_btn = gr.Button("Generate") # t2i_output_image = gr.Image(label="Generated Image", elem_id="t2i_output_img") # t2i_output_seed = gr.Number(label="Used Seed", elem_id="t2i_output_seed") t2i_generate_btn = gr.Button("Generate") t2i_output_image = gr.Image(label="Generated Image", elem_id="t2i_output_img") t2i_output_seed = gr.Number(label="Used Seed", elem_id="t2i_output_seed") t2i_translated_prompt = gr.Text(label="Translated Prompt (if applicable)", elem_id="t2i_translated_prompt") t2i_generate_btn.click( fn=infer_t2i, inputs=[t2i_input_text, t2i_seed, t2i_randomize_seed, t2i_width, t2i_height, t2i_guidance_scale, t2i_num_inference_steps], outputs=[t2i_output_image, t2i_output_seed, t2i_translated_prompt] ) with gr.Tab(label='Image+Text to Video'): with gr.Column(): with gr.Row(): with gr.Column(): with gr.Row(): i2v_input_image = gr.Image(label="Input Image",elem_id="input_img") with gr.Row(): i2v_input_text = gr.Text(label='Prompts') with gr.Row(): i2v_seed = gr.Slider(label='Random Seed', minimum=0, maximum=10000, step=1, value=123) i2v_eta = gr.Slider(minimum=0.0, maximum=1.0, step=0.1, label='ETA', value=1.0, elem_id="i2v_eta") i2v_cfg_scale = gr.Slider(minimum=1.0, maximum=15.0, step=0.5, label='CFG Scale', value=3.5, elem_id="i2v_cfg_scale") with gr.Row(): i2v_steps = gr.Slider(minimum=1, maximum=50, step=1, elem_id="i2v_steps", label="Sampling steps", value=30) i2v_motion = gr.Slider(minimum=5, maximum=20, step=1, elem_id="i2v_motion", label="FPS", value=8) with gr.Row(): i2v_video_length = gr.Slider(minimum=2, maximum=8, step=1, elem_id="i2v_video_length", label="Video Length (seconds)", value=2) i2v_end_btn = gr.Button("Generate") with gr.Row(): i2v_output_video = gr.Video(label="Generated Video",elem_id="output_vid",autoplay=True,show_share_button=True) gr.Examples(examples=i2v_examples, inputs=[i2v_input_image, i2v_input_text, i2v_steps, i2v_cfg_scale, i2v_eta, i2v_motion, i2v_seed, i2v_video_length], outputs=[i2v_output_video], fn = infer, cache_examples=True, ) i2v_end_btn.click(inputs=[i2v_input_image, i2v_input_text, i2v_steps, i2v_cfg_scale, i2v_eta, i2v_motion, i2v_seed, i2v_video_length], outputs=[i2v_output_video], fn = infer ) with gr.Tab(label='Text to Video'): with gr.Column(): t2v_input_text = gr.Text(label='Prompt') with gr.Row(): t2v_seed = gr.Slider(label='Seed', minimum=0, maximum=MAX_SEED, step=1, value=123) t2v_randomize_seed = gr.Checkbox(label='Randomize seed', value=False) with gr.Row(): t2v_width = gr.Slider(label='Width', minimum=256, maximum=MAX_IMAGE_SIZE, step=64, value=1024) t2v_height = gr.Slider(label='Height', minimum=256, maximum=MAX_IMAGE_SIZE, step=64, value=576) with gr.Row(): t2v_guidance_scale = gr.Slider(label='Image Guidance Scale', minimum=1.0, maximum=20.0, step=0.1, value=4.0) t2v_num_inference_steps = gr.Slider(label='Image Inference Steps', minimum=1, maximum=100, step=1, value=30) with gr.Row(): t2v_video_steps = gr.Slider(label='Video Steps', minimum=1, maximum=50, step=1, value=30) t2v_video_cfg_scale = gr.Slider(label='Video CFG Scale', minimum=1.0, maximum=15.0, step=0.5, value=3.5) with gr.Row(): t2v_video_eta = gr.Slider(label='Video ETA', minimum=0.0, maximum=1.0, step=0.1, value=1.0) t2v_video_fps = gr.Slider(label='Video FPS', minimum=5, maximum=20, step=1, value=8) t2v_video_length = gr.Slider(label='Video Length (seconds)', minimum=2, maximum=8, step=1, value=2) t2v_generate_btn = gr.Button("Generate Video") t2v_output_video = gr.Video(label="Generated Video", elem_id="t2v_output_vid", autoplay=True, show_share_button=True) t2v_translated_prompt = gr.Text(label="Translated Prompt (if applicable)", elem_id="t2v_translated_prompt") t2v_generate_btn.click( fn=infer_t2v, inputs=[t2v_input_text, t2v_seed, t2v_randomize_seed, t2v_width, t2v_height, t2v_guidance_scale, t2v_num_inference_steps, t2v_video_steps, t2v_video_cfg_scale, t2v_video_eta, t2v_video_fps, t2v_video_length], outputs=[t2v_output_video, t2v_translated_prompt] ) dynamicrafter_iface.queue(max_size=12).launch(show_api=True)