File size: 10,143 Bytes
15d6d88
4afdd4d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5c708d4
97f24d6
 
 
391d7c7
 
 
 
 
 
 
 
 
26a1726
4afdd4d
28fb111
4afdd4d
28fb111
 
4afdd4d
28fb111
4afdd4d
28fb111
be0fea4
 
 
 
 
 
 
 
 
 
 
 
 
5c708d4
54bb316
be0fea4
391d7c7
 
 
 
 
 
97f24d6
 
391d7c7
97f24d6
 
 
 
94ffdb9
97f24d6
 
 
 
 
 
 
 
94ffdb9
ba36683
5c708d4
 
 
 
ba36683
5c708d4
28fb111
4afdd4d
 
 
28fb111
 
4afdd4d
 
ba36683
4afdd4d
 
ba36683
4afdd4d
ba36683
4afdd4d
26a1726
28fb111
4afdd4d
 
ba36683
b5d93b2
 
 
 
ba36683
b5d93b2
ba36683
b5d93b2
ba36683
b5d93b2
 
ba36683
b5d93b2
 
 
ba36683
7f31be9
ba36683
b5d93b2
 
4afdd4d
 
ba36683
97f24d6
 
 
 
 
 
 
 
 
 
 
eec49a2
26a1726
eec49a2
4afdd4d
28fb111
4afdd4d
18011ec
 
 
 
 
 
 
4afdd4d
28e12ad
 
18011ec
 
28e12ad
 
 
18011ec
 
 
28e12ad
54bb316
28e12ad
18011ec
 
 
 
 
 
 
 
4afdd4d
 
 
 
 
 
 
 
 
 
 
 
6ef2bdd
26a1726
 
 
4afdd4d
 
 
 
 
26a1726
4afdd4d
 
d9114d9
4afdd4d
26a1726
4afdd4d
 
 
18011ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4afdd4d
97f24d6
 
8631f1e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
import spaces
import gradio as gr
import os
import sys
import argparse
import random
import time
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 FluxPipeline
from PIL import Image
import numpy as np
from huggingface_hub import login

# Hugging Face ํ† ํฐ ์„ค์ • ๋ฐ ๋กœ๊ทธ์ธ
hf_token = os.getenv("HF_TOKEN")
if hf_token:
    login(token=hf_token)
else:
    print("Warning: HF_TOKEN not found in environment variables. You may encounter authentication issues.")


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", device=0)  # GPU ์‚ฌ์šฉ ์„ค์ •

# FLUX ํŒŒ์ดํ”„๋ผ์ธ ์ดˆ๊ธฐํ™” ๋ถ€๋ถ„ ์ˆ˜์ •
flux_pipe = FluxPipeline.from_pretrained(
    "black-forest-labs/FLUX.1-dev",
    torch_dtype=torch.bfloat16,
    use_auth_token=hf_token  # ํ† ํฐ์„ ์‚ฌ์šฉํ•˜์—ฌ ์ธ์ฆ
)
flux_pipe.enable_model_cpu_offload()


def generate_image_from_text(prompt, seed=0):
    generator = torch.Generator("cpu").manual_seed(seed)
    image = flux_pipe(
        prompt,
        height=576,
        width=1024,
        guidance_scale=3.5,
        num_inference_steps=50,
        max_sequence_length=512,
        generator=generator
    ).images[0]
    return image

@spaces.GPU(duration=600)
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]

    # ํ…์ŠคํŠธ ์กฐ๊ฑด ์„ค์ •
    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) * 2
        image_tensor_resized = transform(img_tensor).unsqueeze(0)  # bchw
        
        z = get_latent_z(model, image_tensor_resized.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]}
        
        # ์ถ”๋ก  ์‹คํ–‰
        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_path


@spaces.GPU(duration=300)
def infer_t2v(prompt, video_prompt, steps=50, cfg_scale=7.5, eta=1.0, fs=3, seed=123, video_length=2):
    # ์ด๋ฏธ์ง€ ์ƒ์„ฑ
    image = generate_image_from_text(prompt, seed)
    
    # ์ด๋ฏธ์ง€๋ฅผ numpy ๋ฐฐ์—ด๋กœ ๋ณ€ํ™˜
    image_np = np.array(image)
    
    # ๋น„๋””์˜ค ์ƒ์„ฑ์„ ์œ„ํ•ด ๊ธฐ์กด infer ํ•จ์ˆ˜ ํ˜ธ์ถœ
    return infer(image_np, video_prompt, steps, cfg_scale, eta, fs, seed, video_length)

i2v_examples = [
    ['prompts/1024/astronaut04.png', 'a man in an astronaut suit playing a guitar', 30, 7.5, 1.0, 6, 123, 2],
]

css = """#input_img {max-width: 1024px !important} #output_vid {max-width: 1024px; max-height: 576px}"""

def generate_only_image(prompt, seed=123):
    # ์ด๋ฏธ์ง€ ์ƒ์„ฑ
    image = generate_image_from_text(prompt, seed)

    # PIL ์ด๋ฏธ์ง€๋กœ ๋ณ€ํ™˜ ํ›„ ๋ฐ˜ํ™˜
    return Image.fromarray(np.array(image))

with gr.Blocks(analytics_enabled=False, css=css) as dynamicrafter_iface:
    gr.Markdown("kAI ๋ฌด๋น„ ์ŠคํŠœ๋””์˜ค")


    with gr.Tab(label='Image(+Text) Generation'):
        with gr.Column():
            with gr.Row():
                with gr.Column():
                    img_input_text = gr.Text(label='Image Generation Prompt')
                    img_seed = gr.Slider(label='Random Seed', minimum=0, maximum=10000, step=1, value=123)
                    img_generate_btn = gr.Button("Generate Image")
                with gr.Row():
                    img_output_image = gr.Image(label="Generated Image")

            img_generate_btn.click(
                inputs=[img_input_text, img_seed],
                outputs=[img_output_image],
                fn=generate_only_image
        ) 


    with gr.Tab(label='Image to Video Generation'):
        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=7.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 Generation'):
        with gr.Column():
            with gr.Row():
                with gr.Column():
                    with gr.Row():
                        t2v_video_prompt = gr.Text(label='Video Generation Prompt')
                    with gr.Row():
                        t2v_seed = gr.Slider(label='Random Seed', minimum=0, maximum=10000, step=1, value=123)
                        t2v_eta = gr.Slider(minimum=0.0, maximum=1.0, step=0.1, label='ETA', value=1.0)
                        t2v_cfg_scale = gr.Slider(minimum=1.0, maximum=15.0, step=0.5, label='CFG Scale', value=7.5)
                    with gr.Row():
                        t2v_steps = gr.Slider(minimum=1, maximum=50, step=1, label="Sampling steps", value=30)
                        t2v_motion = gr.Slider(minimum=5, maximum=20, step=1, label="FPS", value=8)
                    with gr.Row():
                        t2v_video_length = gr.Slider(minimum=2, maximum=8, step=1, label="Video Length (seconds)", value=2)
                    t2v_end_btn = gr.Button("Generate")
                with gr.Row():
                    t2v_output_video = gr.Video(label="Generated Video", autoplay=True, show_share_button=True)

        t2v_end_btn.click(
            inputs=[t2v_input_text, t2v_video_prompt, t2v_steps, t2v_cfg_scale, t2v_eta, t2v_motion, t2v_seed, t2v_video_length],
            outputs=[t2v_output_video],
            fn=infer_t2v
        )
    




dynamicrafter_iface.queue(max_size=12).launch(show_api=True)