seawolf2357 commited on
Commit
4cb1b23
ยท
verified ยท
1 Parent(s): 5c708d4

Upload app (8).py

Browse files
Files changed (1) hide show
  1. app (8).py +148 -0
app (8).py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import spaces
2
+ import gradio as gr
3
+ import os
4
+ import sys
5
+ import argparse
6
+ import random
7
+ import time
8
+ from omegaconf import OmegaConf
9
+ import torch
10
+ import torchvision
11
+ from pytorch_lightning import seed_everything
12
+ from huggingface_hub import hf_hub_download
13
+ from einops import repeat
14
+ import torchvision.transforms as transforms
15
+ from utils.utils import instantiate_from_config
16
+ sys.path.insert(0, "scripts/evaluation")
17
+ from funcs import (
18
+ batch_ddim_sampling,
19
+ load_model_checkpoint,
20
+ get_latent_z,
21
+ save_videos
22
+ )
23
+ from transformers import pipeline
24
+
25
+ def download_model():
26
+ REPO_ID = 'Doubiiu/DynamiCrafter_1024'
27
+ filename_list = ['model.ckpt']
28
+ if not os.path.exists('./checkpoints/dynamicrafter_1024_v1/'):
29
+ os.makedirs('./checkpoints/dynamicrafter_1024_v1/')
30
+ for filename in filename_list:
31
+ local_file = os.path.join('./checkpoints/dynamicrafter_1024_v1/', filename)
32
+ if not os.path.exists(local_file):
33
+ hf_hub_download(repo_id=REPO_ID, filename=filename, local_dir='./checkpoints/dynamicrafter_1024_v1/', force_download=True)
34
+
35
+ download_model()
36
+ ckpt_path='checkpoints/dynamicrafter_1024_v1/model.ckpt'
37
+ config_file='configs/inference_1024_v1.0.yaml'
38
+ config = OmegaConf.load(config_file)
39
+ model_config = config.pop("model", OmegaConf.create())
40
+ model_config['params']['unet_config']['params']['use_checkpoint']=False
41
+ model = instantiate_from_config(model_config)
42
+ assert os.path.exists(ckpt_path), "Error: checkpoint Not Found!"
43
+ model = load_model_checkpoint(model, ckpt_path)
44
+ model.eval()
45
+ model = model.cuda()
46
+
47
+ # ๋ฒˆ์—ญ ๋ชจ๋ธ ์ดˆ๊ธฐํ™”
48
+ translator = pipeline("translation", model="Helsinki-NLP/opus-mt-ko-en")
49
+
50
+ @spaces.GPU(duration=300)
51
+ def infer(image, prompt, steps=50, cfg_scale=7.5, eta=1.0, fs=3, seed=123, video_length=2):
52
+ # ํ•œ๊ธ€ ์ž…๋ ฅ ๊ฐ์ง€ ๋ฐ ๋ฒˆ์—ญ
53
+ if any('\u3131' <= char <= '\u318E' or '\uAC00' <= char <= '\uD7A3' for char in prompt):
54
+ translated = translator(prompt, max_length=512)[0]['translation_text']
55
+ prompt = translated
56
+ print(f"Translated prompt: {prompt}")
57
+
58
+ resolution = (576, 1024)
59
+ save_fps = 8
60
+ seed_everything(seed)
61
+ transform = transforms.Compose([
62
+ transforms.Resize(min(resolution)),
63
+ transforms.CenterCrop(resolution),
64
+ ])
65
+ torch.cuda.empty_cache()
66
+ print('start:', prompt, time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
67
+ start = time.time()
68
+ if steps > 60:
69
+ steps = 60
70
+
71
+ batch_size=1
72
+ channels = model.model.diffusion_model.out_channels
73
+ frames = int(video_length * save_fps) # ๋น„๋””์˜ค ๊ธธ์ด์— ๋”ฐ๋ฅธ ํ”„๋ ˆ์ž„ ์ˆ˜ ๊ณ„์‚ฐ
74
+ h, w = resolution[0] // 8, resolution[1] // 8
75
+ noise_shape = [batch_size, channels, frames, h, w]
76
+
77
+ # text cond
78
+ with torch.no_grad(), torch.cuda.amp.autocast():
79
+ text_emb = model.get_learned_conditioning([prompt])
80
+
81
+ # img cond
82
+ img_tensor = torch.from_numpy(image).permute(2, 0, 1).float().to(model.device)
83
+ img_tensor = (img_tensor / 255. - 0.5) * 2
84
+
85
+ image_tensor_resized = transform(img_tensor) #3,256,256
86
+ videos = image_tensor_resized.unsqueeze(0) # bchw
87
+
88
+ z = get_latent_z(model, videos.unsqueeze(2)) #bc,1,hw
89
+
90
+ img_tensor_repeat = repeat(z, 'b c t h w -> b c (repeat t) h w', repeat=frames)
91
+
92
+ cond_images = model.embedder(img_tensor.unsqueeze(0)) ## blc
93
+ img_emb = model.image_proj_model(cond_images)
94
+
95
+ imtext_cond = torch.cat([text_emb, img_emb], dim=1)
96
+
97
+ fs = torch.tensor([fs], dtype=torch.long, device=model.device)
98
+ cond = {"c_crossattn": [imtext_cond], "fs": fs, "c_concat": [img_tensor_repeat]}
99
+
100
+ ## inference
101
+ batch_samples = batch_ddim_sampling(model, cond, noise_shape, n_samples=1, ddim_steps=steps, ddim_eta=eta, cfg_scale=cfg_scale)
102
+ ## b,samples,c,t,h,w
103
+
104
+ video_path = './output.mp4'
105
+ save_videos(batch_samples, './', filenames=['output'], fps=save_fps)
106
+ return video_path
107
+
108
+ i2v_examples = [
109
+ ['prompts/1024/astronaut04.png', 'a man in an astronaut suit playing a guitar', 30, 7.5, 1.0, 6, 123, 2],
110
+ ]
111
+
112
+ css = """#input_img {max-width: 1024px !important} #output_vid {max-width: 1024px; max-height: 576px}"""
113
+
114
+ with gr.Blocks(analytics_enabled=False, css=css) as dynamicrafter_iface:
115
+ gr.Markdown("์ด๋ฏธ์ง€๋กœ ์˜์ƒ ์ƒ์„ฑ ํ…Œ์ŠคํŠธ (ํ•œ๊ธ€ ํ”„๋กฌํ”„ํŠธ ์ง€์›)")
116
+ with gr.Tab(label='ImageAnimation_576x1024'):
117
+ with gr.Column():
118
+ with gr.Row():
119
+ with gr.Column():
120
+ with gr.Row():
121
+ i2v_input_image = gr.Image(label="Input Image",elem_id="input_img")
122
+ with gr.Row():
123
+ i2v_input_text = gr.Text(label='Prompts')
124
+ with gr.Row():
125
+ i2v_seed = gr.Slider(label='Random Seed', minimum=0, maximum=10000, step=1, value=123)
126
+ i2v_eta = gr.Slider(minimum=0.0, maximum=1.0, step=0.1, label='ETA', value=1.0, elem_id="i2v_eta")
127
+ i2v_cfg_scale = gr.Slider(minimum=1.0, maximum=15.0, step=0.5, label='CFG Scale', value=7.5, elem_id="i2v_cfg_scale")
128
+ with gr.Row():
129
+ i2v_steps = gr.Slider(minimum=1, maximum=50, step=1, elem_id="i2v_steps", label="Sampling steps", value=30)
130
+ i2v_motion = gr.Slider(minimum=5, maximum=20, step=1, elem_id="i2v_motion", label="FPS", value=8)
131
+ with gr.Row():
132
+ i2v_video_length = gr.Slider(minimum=2, maximum=8, step=1, elem_id="i2v_video_length", label="Video Length (seconds)", value=2)
133
+ i2v_end_btn = gr.Button("Generate")
134
+ with gr.Row():
135
+ i2v_output_video = gr.Video(label="Generated Video",elem_id="output_vid",autoplay=True,show_share_button=True)
136
+
137
+ gr.Examples(examples=i2v_examples,
138
+ inputs=[i2v_input_image, i2v_input_text, i2v_steps, i2v_cfg_scale, i2v_eta, i2v_motion, i2v_seed, i2v_video_length],
139
+ outputs=[i2v_output_video],
140
+ fn = infer,
141
+ cache_examples=True,
142
+ )
143
+ 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],
144
+ outputs=[i2v_output_video],
145
+ fn = infer
146
+ )
147
+
148
+ dynamicrafter_iface.queue(max_size=12).launch(show_api=True)