Spaces:
Paused
Paused
Update app.py
Browse files18 unmodified lines19202122232410 unmodified lines3536373839404142434445464748491 unmodified line515253545556575 unmodified lines63646566676869707172737475767778798081821 unmodified line8485868788899091929394959697983 unmodified lines1021031041051061071081091105 unmodified lines1161171181191201211222 unmodified lines1251261271281291301318 unmodified lines14014114214314414518 unmodified linesget_latent_z,save_videos)def download_model():REPO_ID = 'Doubiiu/DynamiCrafter_1024'10 unmodified linesconfig_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']=True # Checkpoint 사용하여 메모리 사용 최적화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()@spaces.GPU(duration=300, gpu_type="h100") # H100 GPU 사용 지정def infer(image, prompt, steps=50, cfg_scale=7.5, eta=1.0, fs=3, seed=123):resolution = (576, 1024)save_fps = 8seed_everything(seed)1 unmodified linetransforms.Resize(min(resolution)),transforms.CenterCrop(resolution),])torch.cuda.empty_cache() # GPU 캐시 메모리 정리print('start:', prompt, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))start = time.time()if steps > 60:5 unmodified linesh, w = resolution[0] // 8, resolution[1] // 8noise_shape = [batch_size, channels, frames, h, w]# 텍스트 조건 생성with torch.no_grad(), torch.cuda.amp.autocast(): # 메모리 사용량 감소 및 연산 속도 개선text_emb = model.get_learned_conditioning([prompt])# 이미지 조건 생성img_tensor = torch.from_numpy(image).permute(2, 0, 1).float().to(model.device)img_tensor = (img_tensor / 255. - 0.5) * 2image_tensor_resized = transform(img_tensor) #3,256,256videos = image_tensor_resized.unsqueeze(0) # bchwz = get_latent_z(model, videos.unsqueeze(2)) #bc,1,hwimg_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)) ## blcimg_emb = model.image_proj_model(cond_images)imtext_cond = torch.cat([text_emb, img_emb], dim=1)1 unmodified linefs = torch.tensor([fs], dtype=torch.long, device=model.device)cond = {"c_crossattn": [imtext_cond], "fs": fs, "c_concat": [img_tensor_repeat]}# 추론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,wvideo_path = './output.mp4'save_videos(batch_samples, './', filenames=['output'], fps=save_fps)return video_pathi2v_examples = [['prompts/1024/astronaut04.png', 'a man in an astronaut suit playing a guitar', 30, 7.5, 1.0, 6, 123],['prompts/1024/bloom01.png', 'time-lapse of a blooming flower with leaves and a stem', 30, 7.5, 1.0, 10, 123],3 unmodified lines['prompts/1024/firework03.png', 'fireworks display', 30, 7.5, 1.0, 10, 123],]css = """#input_img {max-width: 1024px !important} #output_vid {max-width: 1024px; max-height: 576px}"""with gr.Blocks(analytics_enabled=False, css=css) as dynamicrafter_iface:5 unmodified lineswith 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")2 unmodified linesi2v_steps = gr.Slider(minimum=1, maximum=50, step=1, elem_id="i2v_steps", label="Sampling steps", value=50)i2v_motion = gr.Slider(minimum=5, maximum=20, step=1, elem_id="i2v_motion", label="FPS", value=10)i2v_end_btn = gr.Button("Generate")# with gr.Tab(label='Result'):with gr.Row():i2v_output_video = gr.Video(label="Generated Video",elem_id="output_vid",autoplay=True,show_share_button=True)8 unmodified linesfn = infer)# 포트 7890 설정, 대기열 활성화, API 활성화dynamicrafter_iface.launch()18 unmodified lines1920212223242510 unmodified lines36373839404142434445464748495051525354555657581 unmodified line606162636465665 unmodified lines7273747576777879808182838485868788891 unmodified line9192939495969798991001011023 unmodified lines1061071081091101115 unmodified lines1171181191201211221232 unmodified lines1261271281291301318 unmodified lines14014114214318 unmodified linesget_latent_z,save_videos)from transformers import pipelinedef download_model():REPO_ID = 'Doubiiu/DynamiCrafter_1024'10 unmodified linesconfig_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']=Truemodel = 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")@spaces.GPU(duration=300, gpu_type="h100")def infer(image, prompt, steps=50, cfg_scale=7.5, eta=1.0, fs=3, seed=123):# 한글 입력 확인 및 번역if any('\u3131' <= char <= '\u318E' or '\uAC00' <= char <= '\uD7A3' for char in prompt):translated = translator(prompt, max_length=512)prompt = translated[0]['translation_text']resolution = (576, 1024)save_fps = 8seed_everything(seed)1 unmodified linetransforms.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:5 unmodified linesh, w = resolution[0] // 8, resolution[1] // 8noise_shape = [batch_size, channels, frames, h, w]with torch.no_grad(), torch.cuda.amp.autocast():text_emb = model.get_learned_conditioning([prompt])img_tensor = torch.from_numpy(image).permute(2, 0, 1).float().to(model.device)img_tensor = (img_tensor / 255. - 0.5) * 2image_tensor_resized = transform(img_tensor)videos = image_tensor_resized.unsqueeze(0)z = get_latent_z(model, videos.unsqueeze(2))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))img_emb = model.image_proj_model(cond_images)imtext_cond = torch.cat([text_emb, img_emb], dim=1)1 unmodified linefs = torch.tensor([fs], dtype=torch.long, device=model.device)cond = {"c_crossattn": [imtext_cond], "fs": fs, "c_concat": [img_tensor_repeat]}batch_samples = batch_ddim_sampling(model, cond, noise_shape, n_samples=1, ddim_steps=steps, ddim_eta=eta, cfg_scale=cfg_scale)video_path = './output.mp4'save_videos(batch_samples, './', filenames=['output'], fps=save_fps)return video_pathi2v_examples = [['prompts/1024/astronaut04.png', 'a man in an astronaut suit playing a guitar', 30, 7.5, 1.0, 6, 123],['prompts/1024/bloom01.png', 'time-lapse of a blooming flower with leaves and a stem', 30, 7.5, 1.0, 10, 123],3 unmodified lines['prompts/1024/firework03.png', 'fireworks display', 30, 7.5, 1.0, 10, 123],]css = """#input_img {max-width: 1024px !important} #output_vid {max-width: 1024px; max-height: 576px}"""with gr.Blocks(analytics_enabled=False, css=css) as dynamicrafter_iface:5 unmodified lineswith 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")2 unmodified linesi2v_steps = gr.Slider(minimum=1, maximum=50, step=1, elem_id="i2v_steps", label="Sampling steps", value=50)i2v_motion = gr.Slider(minimum=5, maximum=20, step=1, elem_id="i2v_motion", label="FPS", value=10)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)8 unmodified linesfn = infer)dynamicrafter_iface.launch(server_port=7890, server_name="0.0.0.0", share=True)
app.py+19-21