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b53d4f
 
 
 
 
 
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
# coding: utf-8

"""
The entrance of the gradio
"""

import tyro
import gradio as gr
import os.path as osp
from src.utils.helper import load_description
from src.gradio_pipeline import GradioPipeline
from src.config.crop_config import CropConfig
from src.config.argument_config import ArgumentConfig
from src.config.inference_config import InferenceConfig
import spaces
import cv2
import torch


#์ถ”๊ฐ€
from elevenlabs_utils import ElevenLabsPipeline
from setup_environment import initialize_environment
from src.utils.video import extract_audio
#from flux_dev import create_flux_tab
from flux_schnell import create_flux_tab
# from diffusers import FluxPipeline

# import gdown
# folder_url = f"https://drive.google.com/drive/folders/1UtKgzKjFAOmZkhNK-OYT0caJ_w2XAnib"
# gdown.download_folder(url=folder_url, output="pretrained_weights", quiet=False)



# #========================= # FLUX ๋ชจ๋ธ ๋กœ๋“œ ์„ค์ •
# flux_pipe = FluxPipeline.from_pretrained("black-forest-labs/FLUX.1-schnell", torch_dtype=torch.bfloat16)
# flux_pipe.enable_sequential_cpu_offload()
# flux_pipe.vae.enable_slicing()
# flux_pipe.vae.enable_tiling()
# flux_pipe.to(torch.float16)


# @spaces.GPU(duration=120)
# def generate_image(prompt, guidance_scale, width, height):
#     # ์ด๋ฏธ์ง€๋ฅผ ์ƒ์„ฑํ•˜๋Š” ํ•จ์ˆ˜
#     output_image = flux_pipe(
#         prompt=prompt,
#         guidance_scale=guidance_scale,
#         height=height,
#         width=width,
#         num_inference_steps=4,
#         max_sequence_length=256,
#     ).images[0]

#     # ๊ฒฐ๊ณผ ํด๋” ์ƒ์„ฑ
#     result_folder = "/tmp/flux/"
#     os.makedirs(result_folder, exist_ok=True)

#     # ํŒŒ์ผ ์ด๋ฆ„ ์ƒ์„ฑ
#     timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
#     #filename = f"{prompt.replace(' ', '_')}_{timestamp}.png"
#     filename = f"{'_'.join(prompt.split()[:3])}_{timestamp}.png"
#     output_path = os.path.join(result_folder, filename)

#     # # ์ด๋ฏธ์ง€๋ฅผ ์ €์žฅ
#     # output_image.save(output_path)

#     return output_image, output_path  # ๋‘ ๊ฐœ์˜ ์ถœ๋ ฅ ๋ฐ˜ํ™˜

# def flux_tab(): #image_input):  # image_input์„ ์ธ์ž๋กœ ๋ฐ›์Šต๋‹ˆ๋‹ค.
#     with gr.Tab("FLUX ์ด๋ฏธ์ง€ ์ƒ์„ฑ"):
#         with gr.Row():
#             with gr.Column():
#                 # ์‚ฌ์šฉ์ž ์ž…๋ ฅ ์„ค์ •
#                 prompt = gr.Textbox(label="Prompt", value="A cat holding a sign that says hello world")
#                 guidance_scale = gr.Slider(label="Guidance Scale", minimum=0.0, maximum=20.0, value=3.5, step=0.1)
#                 width = gr.Slider(label="Width", minimum=256, maximum=2048, value=512, step=64)
#                 height = gr.Slider(label="Height", minimum=256, maximum=2048, value=512, step=64)

#             with gr.Column():
#                 # ์ถœ๋ ฅ ์ด๋ฏธ์ง€์™€ ๋‹ค์šด๋กœ๋“œ ๋ฒ„ํŠผ
#                 output_image = gr.Image(type="pil", label="Output")
#                 download_button = gr.File(label="Download")
#                 generate_button = gr.Button("์ด๋ฏธ์ง€ ์ƒ์„ฑ")
#                 #use_in_text2lipsync_button = gr.Button("์ด ์ด๋ฏธ์ง€๋ฅผ Text2Lipsync์—์„œ ์‚ฌ์šฉํ•˜๊ธฐ")  # ์ƒˆ๋กœ์šด ๋ฒ„ํŠผ ์ถ”๊ฐ€

#                 # ํด๋ฆญ ์ด๋ฒคํŠธ๋ฅผ ์ •์˜
#                 generate_button.click(
#                     fn=generate_image,
#                     inputs=[prompt, guidance_scale, width, height],
#                     outputs=[output_image, download_button]
#                 )

#                 # # ์ƒˆ๋กœ์šด ๋ฒ„ํŠผ ํด๋ฆญ ์ด๋ฒคํŠธ ์ •์˜
#                 # use_in_text2lipsync_button.click(
#                 #     fn=lambda img: img,  # ๊ฐ„๋‹จํ•œ ๋žŒ๋‹ค ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์ด๋ฏธ์ง€๋ฅผ ๊ทธ๋Œ€๋กœ ์ „๋‹ฌ
#                 #     inputs=[output_image],  # ์ƒ์„ฑ๋œ ์ด๋ฏธ์ง€๋ฅผ ์ž…๋ ฅ์œผ๋กœ ์‚ฌ์šฉ
#                 #     outputs=[image_input]  # Text to LipSync ํƒญ์˜ image_input์„ ์—…๋ฐ์ดํŠธ
#                 # )

# #========================= # FLUX ๋ชจ๋ธ ๋กœ๋“œ ์„ค์ •
    
initialize_environment()

import sys
sys.path.append('/home/user/.local/lib/python3.10/site-packages')
sys.path.append('/home/user/.local/lib/python3.10/site-packages/stf_alternative/src/stf_alternative')
sys.path.append('/home/user/.local/lib/python3.10/site-packages/stf_tools/src/stf_tools')
sys.path.append('/home/user/app/')
sys.path.append('/home/user/app/stf/')
sys.path.append('/home/user/app/stf/stf_alternative/')
sys.path.append('/home/user/app/stf/stf_alternative/src/stf_alternative')
sys.path.append('/home/user/app/stf/stf_tools')
sys.path.append('/home/user/app/stf/stf_tools/src/stf_tools')


import os
# CUDA ๊ฒฝ๋กœ๋ฅผ ํ™˜๊ฒฝ ๋ณ€์ˆ˜๋กœ ์„ค์ •
os.environ['PATH'] = '/usr/local/cuda/bin:' + os.environ.get('PATH', '')
os.environ['LD_LIBRARY_PATH'] = '/usr/local/cuda/lib64:' + os.environ.get('LD_LIBRARY_PATH', '')
# ํ™•์ธ์šฉ ์ถœ๋ ฅ
print("PATH:", os.environ['PATH'])
print("LD_LIBRARY_PATH:", os.environ['LD_LIBRARY_PATH'])

from stf_utils import STFPipeline



# audio_path="assets/examples/driving/test_aud.mp3"
#audio_path_component = gr.Textbox(label="Input", value="assets/examples/driving/test_aud.mp3")

# @spaces.GPU(duration=120)
# def gpu_wrapped_stf_pipeline_execute(audio_path):
#     return stf_pipeline.execute(audio_path)

    
# ###### ํ…Œ์ŠคํŠธ์ค‘ ######
    

# stf_pipeline = STFPipeline()
# driving_video_path=gr.Video()

# # set tyro theme
# tyro.extras.set_accent_color("bright_cyan")
# args = tyro.cli(ArgumentConfig)

# with gr.Blocks(theme=gr.themes.Soft()) as demo:
#     with gr.Row():
#         audio_path_component = gr.Textbox(label="Input", value="assets/examples/driving/test_aud.mp3")
#         stf_button = gr.Button("stf test", variant="primary")
#         stf_button.click(
#                     fn=gpu_wrapped_stf_pipeline_execute,
#                     inputs=[
#                         audio_path_component
#                     ],
#                     outputs=[driving_video_path]
#                 )
#     with gr.Row():
#         driving_video_path.render()

#     with gr.Row():
#         create_flux_tab()  # image_input์„ flux_tab์— ์ „๋‹ฌํ•ฉ๋‹ˆ๋‹ค.

# ###### ํ…Œ์ŠคํŠธ์ค‘ ######


def partial_fields(target_class, kwargs):
    return target_class(**{k: v for k, v in kwargs.items() if hasattr(target_class, k)})

# set tyro theme
tyro.extras.set_accent_color("bright_cyan")
args = tyro.cli(ArgumentConfig)

# specify configs for inference
inference_cfg = partial_fields(InferenceConfig, args.__dict__)  # use attribute of args to initial InferenceConfig
crop_cfg = partial_fields(CropConfig, args.__dict__)  # use attribute of args to initial CropConfig

gradio_pipeline = GradioPipeline(
    inference_cfg=inference_cfg,
    crop_cfg=crop_cfg,
    args=args
)

# ์ถ”๊ฐ€ ์ •์˜
elevenlabs_pipeline = ElevenLabsPipeline()
stf_pipeline = STFPipeline()
driving_video_path=gr.Video()

@spaces.GPU(duration=120)
def gpu_wrapped_stf_pipeline_execute(audio_path):
    return stf_pipeline.execute(audio_path)


@spaces.GPU(duration=200)
def gpu_wrapped_elevenlabs_pipeline_generate_voice(text, voice):
    return elevenlabs_pipeline.generate_voice(text, voice)



@spaces.GPU(duration=240)
def gpu_wrapped_execute_video(*args, **kwargs):
    return gradio_pipeline.execute_video(*args, **kwargs)

@spaces.GPU(duration=240)
def gpu_wrapped_execute_image(*args, **kwargs):
    return gradio_pipeline.execute_image(*args, **kwargs)

def is_square_video(video_path):
    video = cv2.VideoCapture(video_path)

    width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH))
    height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))

    video.release()
    if width != height:
        raise gr.Error("Error: the video does not have a square aspect ratio. We currently only support square videos")

    return gr.update(visible=True)

def txt_to_driving_video(text):
    audio_path = gpu_wrapped_elevenlabs_pipeline_generate_voice(text)
    driving_video_path = gpu_wrapped_stf_pipeline_execute(audio_path)
    return driving_video_path

# assets
title_md = "assets/gradio_title.md"
example_portrait_dir = "assets/examples/source"
example_video_dir = "assets/examples/driving"
data_examples = [
    [osp.join(example_portrait_dir, "s9.jpg"), osp.join(example_video_dir, "d0.mp4"), True, True, True, True],
    [osp.join(example_portrait_dir, "s6.jpg"), osp.join(example_video_dir, "d0.mp4"), True, True, True, True],
    [osp.join(example_portrait_dir, "s10.jpg"), osp.join(example_video_dir, "d0.mp4"), True, True, True, True],
    [osp.join(example_portrait_dir, "s5.jpg"), osp.join(example_video_dir, "d18.mp4"), True, True, True, True],
    [osp.join(example_portrait_dir, "s7.jpg"), osp.join(example_video_dir, "d19.mp4"), True, True, True, True],
    [osp.join(example_portrait_dir, "s22.jpg"), osp.join(example_video_dir, "d0.mp4"), True, True, True, True],
]
#################### interface logic ####################

# Define components first
eye_retargeting_slider = gr.Slider(minimum=0, maximum=0.8, step=0.01, label="target eyes-open ratio")
lip_retargeting_slider = gr.Slider(minimum=0, maximum=0.8, step=0.01, label="target lip-open ratio")
retargeting_input_image = gr.Image(type="filepath")
output_image = gr.Image(type="numpy")
output_image_paste_back = gr.Image(type="numpy")
output_video = gr.Video()
output_video_concat = gr.Video()

video_input = gr.Video()


with gr.Blocks(theme=gr.themes.Soft()) as demo:
    #gr.HTML(load_description(title_md))

    with gr.Tabs():
        with gr.Tab("Text to LipSync"):
            gr.Markdown("# Text to LipSync")
            with gr.Row():
                with gr.Column():
                    script_txt = gr.Text()
                with gr.Column():
                    txt2video_gen_button = gr.Button("txt2video generation", variant="primary")

                # with gr.Column():
                #     audio_gen_button = gr.Button("Audio generation", variant="primary")
            # with gr.Row():
            #         video_input = gr.Audio(label="Generated video", type="filepath")
                
            gr.Markdown(load_description("assets/gradio_description_upload.md"))
            with gr.Row():
                with gr.Accordion(open=True, label="Source Portrait"):
                    image_input = gr.Image(type="filepath")
                    gr.Examples(
                        examples=[
                            [osp.join(example_portrait_dir, "s9.jpg")],
                            [osp.join(example_portrait_dir, "s6.jpg")],
                            [osp.join(example_portrait_dir, "s10.jpg")],
                            [osp.join(example_portrait_dir, "s5.jpg")],
                            [osp.join(example_portrait_dir, "s7.jpg")],
                            [osp.join(example_portrait_dir, "s12.jpg")],
                            [osp.join(example_portrait_dir, "s22.jpg")],
                        ],
                        inputs=[image_input],
                        cache_examples=False,
                    )
                with gr.Accordion(open=True, label="Driving Video"):
                    #video_input = gr.Video()
                    gr.Examples(
                        examples=[
                            [osp.join(example_video_dir, "d0.mp4")],
                            [osp.join(example_video_dir, "d18.mp4")],
                            [osp.join(example_video_dir, "d19.mp4")],
                            [osp.join(example_video_dir, "d14_trim.mp4")],
                            [osp.join(example_video_dir, "d6_trim.mp4")],
                        ],
                        inputs=[video_input],
                        cache_examples=False,
                    )
            with gr.Row():
                with gr.Accordion(open=False, label="Animation Instructions and Options"):
                    gr.Markdown(load_description("assets/gradio_description_animation.md"))
                    with gr.Row():
                        flag_relative_input = gr.Checkbox(value=True, label="relative motion")
                        flag_do_crop_input = gr.Checkbox(value=True, label="do crop")
                        flag_remap_input = gr.Checkbox(value=True, label="paste-back")
            gr.Markdown(load_description("assets/gradio_description_animate_clear.md"))
            with gr.Row():
                with gr.Column():
                    process_button_animation = gr.Button("๐Ÿš€ Animate", variant="primary")
                with gr.Column():
                    process_button_reset = gr.ClearButton([image_input, video_input, output_video, output_video_concat], value="๐Ÿงน Clear")
            with gr.Row():
                with gr.Column():
                    with gr.Accordion(open=True, label="The animated video in the original image space"):
                        output_video.render()
                with gr.Column():
                    with gr.Accordion(open=True, label="The animated video"):
                        output_video_concat.render()
            with gr.Row():
                # Examples
                gr.Markdown("## You could also choose the examples below by one click โฌ‡๏ธ")
            with gr.Row():
                gr.Examples(
                    examples=data_examples,
                    fn=gpu_wrapped_execute_video,
                    inputs=[
                        image_input,
                        video_input,
                        flag_relative_input,
                        flag_do_crop_input,
                        flag_remap_input
                    ],
                    outputs=[output_image, output_image_paste_back],
                    examples_per_page=6,
                    cache_examples=False,
                )
        
            process_button_animation.click(
                fn=gpu_wrapped_execute_video,
                inputs=[
                    image_input,
                    video_input,
                    flag_relative_input,
                    flag_do_crop_input,
                    flag_remap_input
                ],
                outputs=[output_video, output_video_concat],
                show_progress=True
            )
            txt2video_gen_button.click(
                fn=txt_to_driving_video,
                inputs=[
                    script_txt
                ],
                outputs=[video_input],
                show_progress=True
            )


            
            # image_input.change(
            #     fn=gradio_pipeline.prepare_retargeting,
            #     inputs=image_input,
            #     outputs=[eye_retargeting_slider, lip_retargeting_slider, retargeting_input_image]
            # )
            video_input.upload(
                fn=is_square_video,
                inputs=video_input,
                outputs=video_input
            )
        
        # ์„ธ ๋ฒˆ์งธ ํƒญ: Flux ๊ฐœ๋ฐœ์šฉ ํƒญ
        with gr.Tab("FLUX Image"):
            flux_demo = create_flux_tab(image_input)  # Flux ๊ฐœ๋ฐœ์šฉ ํƒญ ์ƒ์„ฑ

demo.launch(
    server_port=args.server_port,
    share=args.share,
    server_name=args.server_name
)