-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathscript_example.py
More file actions
419 lines (349 loc) · 15.1 KB
/
Copy pathscript_example.py
File metadata and controls
419 lines (349 loc) · 15.1 KB
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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
# Copyright 2024 Vikit.ai. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
import argparse
import asyncio
import os
import pandas as pd # type: ignore
from loguru import logger # type: ignore
from vikit.common.context_managers import WorkingFolderContext
from vikit.common.decorators import log_function_params
from vikit.music_building_context import MusicBuildingContext
from vikit.prompt.prompt_factory import PromptFactory
from vikit.video.composite_video import CompositeVideo
from vikit.video.prompt_based_video import PromptBasedVideo
from vikit.video.raw_image_based_video import RawImageBasedVideo
from vikit.video.raw_text_based_video import RawTextBasedVideo
from vikit.video.seine_transition import SeineTransition
from vikit.video.transition import Transition
from vikit.video.video import VideoBuildSettings
@log_function_params
def get_estimated_duration(composite: CompositeVideo) -> float:
"""Get an estimation of a composite video's duration, based on the type of the sub-videos"""
duration_dict = {
"": 4.04,
"vikit": 4.04,
"stabilityai": 4.04,
"stabilityai_image": 4.04,
"videocrafter": 2.0,
"haiper": 4.0,
"transition": 2.0,
}
duration = 0
for video in composite.video_list:
interpolation_factor = 1.9 if video.build_settings.interpolate else 1.0
if isinstance(video, Transition):
duration += duration_dict["transition"] * interpolation_factor
else:
duration += (
duration_dict[video.build_settings.target_model_provider]
* interpolation_factor
)
return duration
async def batch_raw_text_based_prompting(
prompt_file: str, model_provider: str = "stabilityai"
):
# It is strongly recommended to activate interpolate for videocrafter model
to_interpolate = True if model_provider == "videocrafter" else False
prompt_df = pd.read_csv(prompt_file, delimiter=";", header=0)
for _, row in prompt_df.iterrows():
output_file = f"{row.iloc[0]}.mp4"
prompt_content = row.iloc[1]
video_build_settings = VideoBuildSettings(
music_building_context=MusicBuildingContext(
apply_background_music=True,
generate_background_music=True,
expected_music_length=5,
),
interpolate=to_interpolate,
target_model_provider=model_provider,
output_video_file_name=output_file,
test_mode=False,
)
video_build_settings.prompt = await PromptFactory(
ml_gateway=video_build_settings.get_ml_models_gateway()
).create_prompt_from_text(prompt_content)
video = RawTextBasedVideo(prompt_content)
await video.build(build_settings=video_build_settings)
async def composite_textonly_prompting(
prompt_file: str, model_provider: str = "stabilityai"
):
TEST_MODE = False
# It is strongly recommended to activate interpolate for videocrafter model
to_interpolate = True if model_provider == "videocrafter" else False
prompt_df = pd.read_csv(prompt_file, delimiter=";", header=0)
vid_cp_sub = CompositeVideo()
subtitle_total = ""
for i in range(len(prompt_df)):
prompt_content = prompt_df.iloc[i]["prompt"]
subtitle_total += prompt_content
video = RawTextBasedVideo(prompt_content)
video.build_settings = VideoBuildSettings(
interpolate=to_interpolate,
test_mode=TEST_MODE,
target_model_provider=model_provider,
)
# add transitions from time to time
if i >= 1 and i % 2 == 0:
n_videos = len(vid_cp_sub.video_list)
transition_video = SeineTransition(
source_video=vid_cp_sub.video_list[n_videos - 1],
target_video=video,
)
vid_cp_sub.append_video(transition_video)
# Here we prepare the video before asking to build and using a tailored made build-settings
await video.prepare_build(build_settings=video.build_settings)
vid_cp_sub.append_video(video)
# Here we decide to set music only for the global video
total_duration = get_estimated_duration(vid_cp_sub)
composite_build_settings = VideoBuildSettings(
music_building_context=MusicBuildingContext(
apply_background_music=True,
generate_background_music=True,
expected_music_length=total_duration * 1.5,
),
test_mode=TEST_MODE,
target_model_provider=model_provider,
output_video_file_name="Composite.mp4",
expected_length=total_duration,
include_read_aloud_prompt=True,
)
prompt = await PromptFactory(
ml_gateway=composite_build_settings.get_ml_models_gateway()
).create_prompt_from_text(subtitle_total)
composite_build_settings.prompt = prompt
await vid_cp_sub.build(build_settings=composite_build_settings)
async def create_single_image_based_video(
prompt_content,
build_settings=None,
test_mode: bool = False,
output_filename: str = None,
text: str = None,
):
"""text: would be basically used for music generation, if applicable"""
if build_settings is None:
build_settings = VideoBuildSettings(
test_mode=test_mode,
target_model_provider="stabilityai_image",
output_video_file_name=output_filename,
)
image_prompt = PromptFactory(
ml_gateway=build_settings.get_ml_models_gateway()
).create_prompt_from_image(image_path=prompt_content, text=text)
video = RawImageBasedVideo(
raw_image_prompt=image_prompt.image,
)
video.build_settings = build_settings
build_settings.prompt = image_prompt
return video, build_settings
async def batch_image_based_prompting(prompt_file: str):
prompt_df = pd.read_csv(prompt_file, delimiter=";", header=0)
for _, row in prompt_df.iterrows():
prompt_path = row.iloc[1]
output_file = f"{row.iloc[0]}.mp4"
build_settings = VideoBuildSettings(
music_building_context=MusicBuildingContext(
apply_background_music=True,
generate_background_music=True,
expected_music_length=5,
),
target_model_provider="stabilityai_image",
output_video_file_name=output_file,
expected_length=4,
test_mode=False,
)
video, _ = await create_single_image_based_video(
prompt_content=prompt_path,
text="A cool music for picnic",
build_settings=build_settings,
)
await video.build(build_settings=build_settings)
assert video.media_url, "media URL was not updated"
assert os.path.exists(
video.media_url
), f"The generated video {video.media_url} does not exist"
print(f"video saved on {output_file}")
async def composite_imageonly_prompting(prompt_file: str):
TEST_MODE = False
prompt_df = pd.read_csv(prompt_file, delimiter=";", header=0)
single_video_buildsettings = VideoBuildSettings(
test_mode=TEST_MODE,
target_model_provider="stabilityai_image",
)
vid_cp_sub = CompositeVideo()
for i in range(len(prompt_df)):
prompt_content = prompt_df.iloc[i]["prompt"]
video, _ = await create_single_image_based_video(
prompt_content=prompt_content,
build_settings=single_video_buildsettings,
)
# Add transitions from time to time
if i >= 1 and i % 2 == 0:
n_videos = len(vid_cp_sub.video_list)
transition_video = SeineTransition(
source_video=vid_cp_sub.video_list[n_videos - 1],
target_video=video,
)
vid_cp_sub.append_video(transition_video)
await video.prepare_build(build_settings=video.build_settings)
vid_cp_sub.append_video(video)
total_duration = get_estimated_duration(vid_cp_sub)
composite_build_settings = VideoBuildSettings(
music_building_context=MusicBuildingContext(
apply_background_music=True,
generate_background_music=True,
expected_music_length=total_duration * 1.5,
),
test_mode=TEST_MODE,
target_model_provider="stabilityai_image",
output_video_file_name="Composite.mp4",
expected_length=total_duration,
)
# The text is used to generate music, if applicable
composite_build_settings.prompt = await PromptFactory().create_prompt_from_text(
"A happy picnic music!"
)
await vid_cp_sub.build(build_settings=composite_build_settings)
async def composite_mixed_prompting(
prompt_file: str, text_to_video_model_provider: str = "stabilityai"
):
TEST_MODE = False
prompt_df = pd.read_csv(prompt_file, delimiter=";", header=0)
# It is strongly recommended to activate interpolate for videocrafter model
to_interpolate = True if text_to_video_model_provider == "videocrafter" else False
text_based_video_buildsettings = VideoBuildSettings(
test_mode=TEST_MODE,
target_model_provider=text_to_video_model_provider,
interpolate=to_interpolate,
)
vid_cp_sub = CompositeVideo()
for i in range(len(prompt_df)):
prompt_content = prompt_df.iloc[i]["prompt"]
prompt_type = prompt_df.iloc[i]["type"]
if prompt_type == "image":
image_based_video_buildsettings = VideoBuildSettings(
test_mode=TEST_MODE,
target_model_provider="stabilityai_image",
)
video, image_based_video_buildsettings = (
await create_single_image_based_video(
prompt_content=prompt_content,
build_settings=image_based_video_buildsettings,
)
)
elif prompt_type == "text":
video = RawTextBasedVideo(prompt_content)
video.build_settings = text_based_video_buildsettings
else:
logger.debug(f"Error! prompt type {prompt_type} not recognized!")
continue
await video.prepare_build(build_settings=video.build_settings)
# Add transitions from time to time
if i >= 1 and i % 2 == 0:
n_videos = len(vid_cp_sub.video_list)
transition_video = SeineTransition(
source_video=vid_cp_sub.video_list[n_videos - 1],
target_video=video,
)
vid_cp_sub.append_video(transition_video)
vid_cp_sub.append_video(video)
total_duration = get_estimated_duration(vid_cp_sub)
composite_build_settings = VideoBuildSettings(
music_building_context=MusicBuildingContext(
apply_background_music=True,
generate_background_music=True,
expected_music_length=total_duration * 1.5,
),
test_mode=TEST_MODE,
output_video_file_name="Composite.mp4",
expected_length=total_duration,
)
composite_build_settings.prompt = await PromptFactory().create_prompt_from_text(
"A happy Guitar music!"
)
await vid_cp_sub.build(build_settings=composite_build_settings)
async def prompt_based_composite(prompt: str, model_provider="stabilityai"):
# It is strongly recommended to activate interpolate for videocrafter model
to_interpolate = True if model_provider == "videocrafter" else False
video_build_settings = VideoBuildSettings(
music_building_context=MusicBuildingContext(
apply_background_music=True,
generate_background_music=True,
),
include_read_aloud_prompt=True,
target_model_provider=model_provider,
output_video_file_name="Composite.mp4",
interpolate=to_interpolate,
test_mode=False,
)
gw = video_build_settings.get_ml_models_gateway()
prompt = await PromptFactory(ml_gateway=gw).create_prompt_from_text(prompt)
video = PromptBasedVideo(prompt=prompt)
await video.build(build_settings=video_build_settings)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"--example",
default=None,
type=int,
help="choose one of the predefined examples to run",
)
# Parse the command-line arguments
args = parser.parse_args()
run_an_example = args.example
if run_an_example is None:
pass
elif run_an_example == 1:
# Example 1- Create a composite of text-based videos:
with WorkingFolderContext("./examples/inputs/TextOnlyComposite"):
logger.add("log.txt")
asyncio.run(composite_textonly_prompting("./input.csv"))
elif run_an_example == 2:
# Example 2- Create a batch of text-based videos:
with WorkingFolderContext("./examples/inputs/TextOnly"):
logger.add("log.txt")
asyncio.run(batch_raw_text_based_prompting("./input.csv"))
elif run_an_example == 3:
# Example 3 - Create a batch of videos from images
with WorkingFolderContext("./examples/inputs/ImageOnly/"):
logger.add("log.txt")
asyncio.run(
batch_image_based_prompting(
"input.csv",
)
)
elif run_an_example == 4:
# Example 4 - Create a composite of image-based videos:
with WorkingFolderContext("./examples/inputs/ImageOnlyComposite/"):
logger.add("log.txt")
asyncio.run(
composite_imageonly_prompting(
"input.csv",
)
)
elif run_an_example == 5:
# Example 5 - Create a composite of text and image-based videos:
with WorkingFolderContext("./examples/inputs/Mixed/"):
logger.add("log.txt")
asyncio.run(
composite_mixed_prompting(
"input.csv",
)
)
elif run_an_example == 6:
# Example 6 - Create a prompt-based videos
with WorkingFolderContext("./examples/inputs/PromptBased/"):
logger.add("log.txt")
prompt = """Paris, the City of Light, is a global center of art, fashion, and culture, renowned for its iconic landmarks and romantic atmosphere. The Eiffel Tower, Louvre Museum, and Notre-Dame Cathedral are just a few of the city's must-see attractions. Paris is also famous for its charming cafes, chic boutiques, and world-class cuisine, offering visitors a delightful blend of history, elegance, and joie de vivre along the scenic Seine River."""
asyncio.run(prompt_based_composite(prompt=prompt))