theangelstudio commited on
Commit
d04e0f5
·
verified ·
1 Parent(s): ad3695b

Upload gradio_demo.py

Browse files
Files changed (1) hide show
  1. Kaggle/gradio_demo.py +343 -0
Kaggle/gradio_demo.py ADDED
@@ -0,0 +1,343 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gc
2
+ import logging
3
+ from argparse import ArgumentParser
4
+ from datetime import datetime
5
+ from fractions import Fraction
6
+ from pathlib import Path
7
+
8
+ import gradio as gr
9
+ import torch
10
+ import torchaudio
11
+
12
+ from mmaudio.eval_utils import (ModelConfig, VideoInfo, all_model_cfg, generate, load_image,
13
+ load_video, make_video, setup_eval_logging)
14
+ from mmaudio.model.flow_matching import FlowMatching
15
+ from mmaudio.model.networks import MMAudio, get_my_mmaudio
16
+ from mmaudio.model.sequence_config import SequenceConfig
17
+ from mmaudio.model.utils.features_utils import FeaturesUtils
18
+
19
+ torch.backends.cuda.matmul.allow_tf32 = True
20
+ torch.backends.cudnn.allow_tf32 = True
21
+
22
+ log = logging.getLogger()
23
+
24
+ device = 'cpu'
25
+ if torch.cuda.is_available():
26
+ device = 'cuda'
27
+ elif torch.backends.mps.is_available():
28
+ device = 'mps'
29
+ else:
30
+ log.warning('CUDA/MPS are not available, running on CPU')
31
+ dtype = torch.bfloat16
32
+
33
+ model: ModelConfig = all_model_cfg['large_44k_v2']
34
+ model.download_if_needed()
35
+ output_dir = Path('./output/gradio')
36
+
37
+ setup_eval_logging()
38
+
39
+
40
+ def get_model() -> tuple[MMAudio, FeaturesUtils, SequenceConfig]:
41
+ seq_cfg = model.seq_cfg
42
+
43
+ net: MMAudio = get_my_mmaudio(model.model_name).to(device, dtype).eval()
44
+ net.load_weights(torch.load(model.model_path, map_location=device, weights_only=True))
45
+ log.info(f'Loaded weights from {model.model_path}')
46
+
47
+ feature_utils = FeaturesUtils(tod_vae_ckpt=model.vae_path,
48
+ synchformer_ckpt=model.synchformer_ckpt,
49
+ enable_conditions=True,
50
+ mode=model.mode,
51
+ bigvgan_vocoder_ckpt=model.bigvgan_16k_path,
52
+ need_vae_encoder=False)
53
+ feature_utils = feature_utils.to(device, dtype).eval()
54
+
55
+ return net, feature_utils, seq_cfg
56
+
57
+
58
+ net, feature_utils, seq_cfg = get_model()
59
+
60
+
61
+ @torch.inference_mode()
62
+ def video_to_audio(video: gr.Video, prompt: str, negative_prompt: str, seed: int, num_steps: int,
63
+ cfg_strength: float, duration: float):
64
+
65
+ rng = torch.Generator(device=device)
66
+ if seed >= 0:
67
+ rng.manual_seed(seed)
68
+ else:
69
+ rng.seed()
70
+ fm = FlowMatching(min_sigma=0, inference_mode='euler', num_steps=num_steps)
71
+
72
+ video_info = load_video(video, duration)
73
+ clip_frames = video_info.clip_frames
74
+ sync_frames = video_info.sync_frames
75
+ duration = video_info.duration_sec
76
+ clip_frames = clip_frames.unsqueeze(0)
77
+ sync_frames = sync_frames.unsqueeze(0)
78
+ seq_cfg.duration = duration
79
+ net.update_seq_lengths(seq_cfg.latent_seq_len, seq_cfg.clip_seq_len, seq_cfg.sync_seq_len)
80
+
81
+ audios = generate(clip_frames,
82
+ sync_frames, [prompt],
83
+ negative_text=[negative_prompt],
84
+ feature_utils=feature_utils,
85
+ net=net,
86
+ fm=fm,
87
+ rng=rng,
88
+ cfg_strength=cfg_strength)
89
+ audio = audios.float().cpu()[0]
90
+
91
+ current_time_string = datetime.now().strftime('%Y%m%d_%H%M%S')
92
+ output_dir.mkdir(exist_ok=True, parents=True)
93
+ video_save_path = output_dir / f'{current_time_string}.mp4'
94
+ make_video(video_info, video_save_path, audio, sampling_rate=seq_cfg.sampling_rate)
95
+ gc.collect()
96
+ return video_save_path
97
+
98
+
99
+ @torch.inference_mode()
100
+ def image_to_audio(image: gr.Image, prompt: str, negative_prompt: str, seed: int, num_steps: int,
101
+ cfg_strength: float, duration: float):
102
+
103
+ rng = torch.Generator(device=device)
104
+ if seed >= 0:
105
+ rng.manual_seed(seed)
106
+ else:
107
+ rng.seed()
108
+ fm = FlowMatching(min_sigma=0, inference_mode='euler', num_steps=num_steps)
109
+
110
+ image_info = load_image(image)
111
+ clip_frames = image_info.clip_frames
112
+ sync_frames = image_info.sync_frames
113
+ clip_frames = clip_frames.unsqueeze(0)
114
+ sync_frames = sync_frames.unsqueeze(0)
115
+ seq_cfg.duration = duration
116
+ net.update_seq_lengths(seq_cfg.latent_seq_len, seq_cfg.clip_seq_len, seq_cfg.sync_seq_len)
117
+
118
+ audios = generate(clip_frames,
119
+ sync_frames, [prompt],
120
+ negative_text=[negative_prompt],
121
+ feature_utils=feature_utils,
122
+ net=net,
123
+ fm=fm,
124
+ rng=rng,
125
+ cfg_strength=cfg_strength,
126
+ image_input=True)
127
+ audio = audios.float().cpu()[0]
128
+
129
+ current_time_string = datetime.now().strftime('%Y%m%d_%H%M%S')
130
+ output_dir.mkdir(exist_ok=True, parents=True)
131
+ video_save_path = output_dir / f'{current_time_string}.mp4'
132
+ video_info = VideoInfo.from_image_info(image_info, duration, fps=Fraction(1))
133
+ make_video(video_info, video_save_path, audio, sampling_rate=seq_cfg.sampling_rate)
134
+ gc.collect()
135
+ return video_save_path
136
+
137
+
138
+ @torch.inference_mode()
139
+ def text_to_audio(prompt: str, negative_prompt: str, seed: int, num_steps: int, cfg_strength: float,
140
+ duration: float):
141
+
142
+ rng = torch.Generator(device=device)
143
+ if seed >= 0:
144
+ rng.manual_seed(seed)
145
+ else:
146
+ rng.seed()
147
+ fm = FlowMatching(min_sigma=0, inference_mode='euler', num_steps=num_steps)
148
+
149
+ clip_frames = sync_frames = None
150
+ seq_cfg.duration = duration
151
+ net.update_seq_lengths(seq_cfg.latent_seq_len, seq_cfg.clip_seq_len, seq_cfg.sync_seq_len)
152
+
153
+ audios = generate(clip_frames,
154
+ sync_frames, [prompt],
155
+ negative_text=[negative_prompt],
156
+ feature_utils=feature_utils,
157
+ net=net,
158
+ fm=fm,
159
+ rng=rng,
160
+ cfg_strength=cfg_strength)
161
+ audio = audios.float().cpu()[0]
162
+
163
+ current_time_string = datetime.now().strftime('%Y%m%d_%H%M%S')
164
+ output_dir.mkdir(exist_ok=True, parents=True)
165
+ audio_save_path = output_dir / f'{current_time_string}.flac'
166
+ torchaudio.save(audio_save_path, audio, seq_cfg.sampling_rate)
167
+ gc.collect()
168
+ return audio_save_path
169
+
170
+
171
+ video_to_audio_tab = gr.Interface(
172
+ fn=video_to_audio,
173
+ description="""
174
+ Project page: <a href="https://hkchengrex.com/MMAudio/">https://hkchengrex.com/MMAudio/</a><br>
175
+ Code: <a href="https://github.com/hkchengrex/MMAudio">https://github.com/hkchengrex/MMAudio</a><br>
176
+
177
+ NOTE: It takes longer to process high-resolution videos (>384 px on the shorter side).
178
+ Doing so does not improve results.
179
+ """,
180
+ inputs=[
181
+ gr.Video(),
182
+ gr.Text(label='Prompt'),
183
+ gr.Text(label='Negative prompt', value='music'),
184
+ gr.Number(label='Seed (-1: random)', value=-1, precision=0, minimum=-1),
185
+ gr.Number(label='Num steps', value=25, precision=0, minimum=1),
186
+ gr.Number(label='Guidance Strength', value=4.5, minimum=1),
187
+ gr.Number(label='Duration (sec)', value=8, minimum=1),
188
+ ],
189
+ outputs='playable_video',
190
+ cache_examples=False,
191
+ title='MMAudio — Video-to-Audio Synthesis',
192
+ examples=[
193
+ [
194
+ 'https://huggingface.co/hkchengrex/MMAudio/resolve/main/examples/sora_beach.mp4',
195
+ 'waves, seagulls',
196
+ '',
197
+ 0,
198
+ 25,
199
+ 4.5,
200
+ 10,
201
+ ],
202
+ [
203
+ 'https://huggingface.co/hkchengrex/MMAudio/resolve/main/examples/sora_serpent.mp4',
204
+ '',
205
+ 'music',
206
+ 0,
207
+ 25,
208
+ 4.5,
209
+ 10,
210
+ ],
211
+ [
212
+ 'https://huggingface.co/hkchengrex/MMAudio/resolve/main/examples/sora_seahorse.mp4',
213
+ 'bubbles',
214
+ '',
215
+ 0,
216
+ 25,
217
+ 4.5,
218
+ 10,
219
+ ],
220
+ [
221
+ 'https://huggingface.co/hkchengrex/MMAudio/resolve/main/examples/sora_india.mp4',
222
+ 'Indian holy music',
223
+ '',
224
+ 0,
225
+ 25,
226
+ 4.5,
227
+ 10,
228
+ ],
229
+ [
230
+ 'https://huggingface.co/hkchengrex/MMAudio/resolve/main/examples/sora_galloping.mp4',
231
+ 'galloping',
232
+ '',
233
+ 0,
234
+ 25,
235
+ 4.5,
236
+ 10,
237
+ ],
238
+ [
239
+ 'https://huggingface.co/hkchengrex/MMAudio/resolve/main/examples/sora_kraken.mp4',
240
+ 'waves, storm',
241
+ '',
242
+ 0,
243
+ 25,
244
+ 4.5,
245
+ 10,
246
+ ],
247
+ [
248
+ 'https://huggingface.co/hkchengrex/MMAudio/resolve/main/examples/mochi_storm.mp4',
249
+ 'storm',
250
+ '',
251
+ 0,
252
+ 25,
253
+ 4.5,
254
+ 10,
255
+ ],
256
+ [
257
+ 'https://huggingface.co/hkchengrex/MMAudio/resolve/main/examples/hunyuan_spring.mp4',
258
+ '',
259
+ '',
260
+ 0,
261
+ 25,
262
+ 4.5,
263
+ 10,
264
+ ],
265
+ [
266
+ 'https://huggingface.co/hkchengrex/MMAudio/resolve/main/examples/hunyuan_typing.mp4',
267
+ 'typing',
268
+ '',
269
+ 0,
270
+ 25,
271
+ 4.5,
272
+ 10,
273
+ ],
274
+ [
275
+ 'https://huggingface.co/hkchengrex/MMAudio/resolve/main/examples/hunyuan_wake_up.mp4',
276
+ '',
277
+ '',
278
+ 0,
279
+ 25,
280
+ 4.5,
281
+ 10,
282
+ ],
283
+ [
284
+ 'https://huggingface.co/hkchengrex/MMAudio/resolve/main/examples/sora_nyc.mp4',
285
+ '',
286
+ '',
287
+ 0,
288
+ 25,
289
+ 4.5,
290
+ 10,
291
+ ],
292
+ ])
293
+
294
+ text_to_audio_tab = gr.Interface(
295
+ fn=text_to_audio,
296
+ description="""
297
+ Project page: <a href="https://hkchengrex.com/MMAudio/">https://hkchengrex.com/MMAudio/</a><br>
298
+ Code: <a href="https://github.com/hkchengrex/MMAudio">https://github.com/hkchengrex/MMAudio</a><br>
299
+ """,
300
+ inputs=[
301
+ gr.Text(label='Prompt'),
302
+ gr.Text(label='Negative prompt'),
303
+ gr.Number(label='Seed (-1: random)', value=-1, precision=0, minimum=-1),
304
+ gr.Number(label='Num steps', value=25, precision=0, minimum=1),
305
+ gr.Number(label='Guidance Strength', value=4.5, minimum=1),
306
+ gr.Number(label='Duration (sec)', value=8, minimum=1),
307
+ ],
308
+ outputs='audio',
309
+ cache_examples=False,
310
+ title='MMAudio — Text-to-Audio Synthesis',
311
+ )
312
+
313
+ image_to_audio_tab = gr.Interface(
314
+ fn=image_to_audio,
315
+ description="""
316
+ Project page: <a href="https://hkchengrex.com/MMAudio/">https://hkchengrex.com/MMAudio/</a><br>
317
+ Code: <a href="https://github.com/hkchengrex/MMAudio">https://github.com/hkchengrex/MMAudio</a><br>
318
+
319
+ NOTE: It takes longer to process high-resolution images (>384 px on the shorter side).
320
+ Doing so does not improve results.
321
+ """,
322
+ inputs=[
323
+ gr.Image(type='filepath'),
324
+ gr.Text(label='Prompt'),
325
+ gr.Text(label='Negative prompt'),
326
+ gr.Number(label='Seed (-1: random)', value=-1, precision=0, minimum=-1),
327
+ gr.Number(label='Num steps', value=25, precision=0, minimum=1),
328
+ gr.Number(label='Guidance Strength', value=4.5, minimum=1),
329
+ gr.Number(label='Duration (sec)', value=8, minimum=1),
330
+ ],
331
+ outputs='playable_video',
332
+ cache_examples=False,
333
+ title='MMAudio — Image-to-Audio Synthesis (experimental)',
334
+ )
335
+
336
+ if __name__ == "__main__":
337
+ parser = ArgumentParser()
338
+ parser.add_argument('--port', type=int, default=7860)
339
+ args = parser.parse_args()
340
+
341
+ gr.TabbedInterface([video_to_audio_tab, text_to_audio_tab, image_to_audio_tab],
342
+ ['Video-to-Audio', 'Text-to-Audio', 'Image-to-Audio (experimental)']).launch(
343
+ server_port=args.port, share=True, allowed_paths=[output_dir])