fix: 🐛 Bug in ffmpeg when generating videos for some posts

pull/2058/head
Mohamed Moataz 1 year ago
parent a9690bdaca
commit f51148bcdb

@ -53,14 +53,14 @@ def main(POST_ID=None) -> None:
global redditid, reddit_object global redditid, reddit_object
reddit_object = get_subreddit_threads(POST_ID) reddit_object = get_subreddit_threads(POST_ID)
redditid = id(reddit_object) redditid = id(reddit_object)
if not (settings.config["settings"]["debug"]["reuse_images"] and
settings.config["settings"]["debug"]["reuse_separate_mp3s"]):
reddit_object['thread_post'] = proofread_post(reddit_object['thread_post'])
post_text = ' '.join(reddit_object['thread_post']) post_text = ' '.join(reddit_object['thread_post'])
print(reddit_object['thread_post'])
print("================================================================")
print(post_text)
if not os.path.exists(f"./assets/temp/{reddit_object['thread_id']}/"): if not os.path.exists(f"./assets/temp/{reddit_object['thread_id']}/"):
for key in settings.config["settings"]["debug"].keys(): for key in settings.config["settings"]["debug"].keys():
if key != "debug": if key != "debug" and key != "no_youtube":
settings.config["settings"]["debug"][key] = False settings.config["settings"]["debug"][key] = False
length, number_of_comments = save_text_to_mp3(reddit_object) length, number_of_comments = save_text_to_mp3(reddit_object)
@ -68,14 +68,21 @@ def main(POST_ID=None) -> None:
reel = length <= 60 reel = length <= 60
get_screenshots_of_reddit_posts(reddit_object, number_of_comments, reel) get_screenshots_of_reddit_posts(reddit_object, number_of_comments, reel)
bg_config = { if not settings.config["settings"]["debug"]["reuse_background"]:
"video": get_background_config("video"), bg_config = {
"audio": get_background_config("audio"), "video": get_background_config("video"),
} "audio": get_background_config("audio"),
download_background_video(bg_config["video"]) }
download_background_audio(bg_config["audio"]) download_background_video(bg_config["video"])
chop_background(bg_config, length, reddit_object) download_background_audio(bg_config["audio"])
chop_background(bg_config, length, reddit_object)
else:
bg_config = {
"video": ["debug mode", "debug mode", "debug mode"],
"audio": ["debug mode", "debug mode", "debug mode"],
}
video_path = make_final_video(number_of_comments, length, reddit_object, bg_config, reel) video_path = make_final_video(number_of_comments, length, reddit_object, bg_config, reel)
if not video_path: return False
video_path = compress_video(video_path) video_path = compress_video(video_path)
video_data, thumbnail_text = get_video_data(post_text, bg_config) video_data, thumbnail_text = get_video_data(post_text, bg_config)
@ -90,10 +97,12 @@ def main(POST_ID=None) -> None:
save_path=f"./assets/temp/{reddit_object['thread_id']}/thumbnail.png" save_path=f"./assets/temp/{reddit_object['thread_id']}/thumbnail.png"
) )
print("Thumbnail generated successfully at:", thumbnail) print("Thumbnail generated successfully at:", thumbnail)
upload_video_to_youtube(video_path, video_data, thumbnail) if not settings.config["settings"]["debug"]["no_youtube"]:
upload_video_to_youtube(video_path, video_data, thumbnail)
if not settings.config["settings"]["debug"]["debug"]: if not settings.config["settings"]["debug"]["debug"]:
shutil.rmtree(f"./assets/temp/{reddit_object['thread_id']}/") shutil.rmtree(f"./assets/temp/{reddit_object['thread_id']}/")
return True
def run_many(times) -> None: def run_many(times) -> None:
@ -122,10 +131,13 @@ def run():
) )
main(post_id) main(post_id)
Popen("cls" if name == "nt" else "clear", shell=True).wait() Popen("cls" if name == "nt" else "clear", shell=True).wait()
elif config["settings"]["times_to_run"]: # elif config["settings"]["times_to_run"]:
run_many(config["settings"]["times_to_run"]) # run_many(config["settings"]["times_to_run"])
else: else:
main() while True:
status = main()
print("Status:", status)
if status: break
print_substep("The video was created successfully! 🎉", style="bold green") print_substep("The video was created successfully! 🎉", style="bold green")
print_substep( print_substep(
@ -149,7 +161,10 @@ if __name__ == "__main__":
from video_data_generation.gemini import get_video_data from video_data_generation.gemini import get_video_data
from video_data_generation.image_generation import generate_image, add_text from video_data_generation.image_generation import generate_image, add_text
from utils.youtube_uploader import upload_video_to_youtube from utils.proofreading import proofread_post
if not settings.config["settings"]["debug"]["no_youtube"]:
from utils.youtube_uploader import upload_video_to_youtube
if ( if (
not settings.config["settings"]["tts"]["tiktok_sessionid"] not settings.config["settings"]["tts"]["tiktok_sessionid"]

@ -42,6 +42,7 @@ reuse_mp3 = { optional = false, type = "bool", default = false, example = false,
reuse_images = { optional = false, type = "bool", default = false, example = false, options = [true, false, ], explanation = "Use images from temp data" } reuse_images = { optional = false, type = "bool", default = false, example = false, options = [true, false, ], explanation = "Use images from temp data" }
reuse_background = { optional = false, type = "bool", default = false, example = false, options = [true, false, ], explanation = "Use previously generated background audio & video." } reuse_background = { optional = false, type = "bool", default = false, example = false, options = [true, false, ], explanation = "Use previously generated background audio & video." }
reuse_video = { optional = false, type = "bool", default = false, example = false, options = [true, false, ], explanation = "Use already generated video" } reuse_video = { optional = false, type = "bool", default = false, example = false, options = [true, false, ], explanation = "Use already generated video" }
no_youtube = { optional = false, type = "bool", default = false, example = false, options = [true, false, ], explanation = "Upload to youtube" }
[settings.background] [settings.background]
background_video = { optional = true, default = "mudrunner", example = "granny-remake", explanation = "Sets the background for the video based on game name" } background_video = { optional = true, default = "mudrunner", example = "granny-remake", explanation = "Sets the background for the video based on game name" }

@ -3,26 +3,26 @@
"haunted_forest":[ "haunted_forest":[
"https://www.youtube.com/watch?v=Yb5XQ9i-gtI", "https://www.youtube.com/watch?v=Yb5XQ9i-gtI",
"haunted_forest.mp3", "haunted_forest.mp3",
"@RPGAmbientSounds" "RPGAmbientSounds"
], ],
"scary_forest":[ "scary_forest":[
"https://www.youtube.com/watch?v=BzYPUjtEVqs", "https://www.youtube.com/watch?v=BzYPUjtEVqs",
"scary_forest.mp3", "scary_forest.mp3",
"@GravitySound" "GravitySound"
], ],
"night_of_the_dead":[ "night_of_the_dead":[
"https://www.youtube.com/watch?v=tmlZeYnfw7g", "https://www.youtube.com/watch?v=tmlZeYnfw7g",
"night_of_the_dead.mp3", "night_of_the_dead.mp3",
"@MysticalSoundscapes" "MysticalSoundscapes"
], ],
"hades":[ "hades":[
"https://www.youtube.com/watch?v=fBR1Qp3njCM", "https://www.youtube.com/watch?v=fBR1Qp3njCM",
"hades.mp3", "hades.mp3",
"@restforthewicked6842" "restforthewicked6842"
], ],
"forest_at_night":[ "forest_at_night":[
"https://www.youtube.com/watch?v=3TNK916Pjto", "https://www.youtube.com/watch?v=3TNK916Pjto",
"forest_at_night.mp3", "forest_at_night.mp3",
"@HawaiiASMRNatureRelaxation" "HawaiiASMRNatureRelaxation"
] ]
} }

@ -3,13 +3,13 @@
"mudrunner": [ "mudrunner": [
"https://www.youtube.com/watch?v=YsfkZoXv4s8", "https://www.youtube.com/watch?v=YsfkZoXv4s8",
"mudrunner.mp4", "mudrunner.mp4",
"@joel.gameplays", "joel.gameplays",
"center" "center"
], ],
"granny-remake": [ "granny-remake": [
"https://www.youtube.com/watch?v=Ynjc1EcRExk", "https://www.youtube.com/watch?v=Ynjc1EcRExk",
"granny.mp4", "granny.mp4",
"@DopeGameplays", "DopeGameplays",
"center" "center"
] ]
} }

@ -86,6 +86,8 @@ def name_normalize(name: str) -> str:
def prepare_background(reddit_id: str, W: int, H: int) -> str: def prepare_background(reddit_id: str, W: int, H: int) -> str:
output_path = f"assets/temp/{reddit_id}/background_noaudio.mp4" output_path = f"assets/temp/{reddit_id}/background_noaudio.mp4"
if settings.config["settings"]["debug"]["reuse_background"]:
return output_path
output = ( output = (
ffmpeg.input(f"assets/temp/{reddit_id}/background.mp4") ffmpeg.input(f"assets/temp/{reddit_id}/background.mp4")
.filter("crop", f"ih*({W}/{H})", "ih") .filter("crop", f"ih*({W}/{H})", "ih")
@ -224,11 +226,12 @@ def make_final_video(
# louder_audio = audio + 10 # louder_audio = audio + 10
# louder_audio.export(f"assets/temp/{reddit_id}/audio.mp3", format='mp3') # louder_audio.export(f"assets/temp/{reddit_id}/audio.mp3", format='mp3')
print("Merging background audio...")
audio = ffmpeg.input(f"assets/temp/{reddit_id}/audio.mp3") audio = ffmpeg.input(f"assets/temp/{reddit_id}/audio.mp3")
final_audio = merge_background_audio(audio, reddit_id) final_audio = merge_background_audio(audio, reddit_id)
image_clips = list() image_clips = list()
print("Adding image clips...")
image_clips.insert( image_clips.insert(
0, 0,
ffmpeg.input(f"assets/temp/{reddit_id}/png/title.png")["v"].filter( ffmpeg.input(f"assets/temp/{reddit_id}/png/title.png")["v"].filter(
@ -322,6 +325,7 @@ def make_final_video(
) )
current_time += audio_clips_durations[i] current_time += audio_clips_durations[i]
print("Added clips successfully.")
title = re.sub(r"[^\w\s-]", "", reddit_obj["thread_title"]) title = re.sub(r"[^\w\s-]", "", reddit_obj["thread_title"])
idx = re.sub(r"[^\w\s-]", "", reddit_obj["thread_id"]) idx = re.sub(r"[^\w\s-]", "", reddit_obj["thread_id"])
title_thumb = reddit_obj["thread_title"] title_thumb = reddit_obj["thread_title"]
@ -373,6 +377,7 @@ def make_final_video(
print_substep(f"Thumbnail - Building Thumbnail in assets/temp/{reddit_id}/thumbnail.png") print_substep(f"Thumbnail - Building Thumbnail in assets/temp/{reddit_id}/thumbnail.png")
text = f"Background by {background_config['video'][2]}" text = f"Background by {background_config['video'][2]}"
print("Drawing text:", text)
background_clip = ffmpeg.drawtext( background_clip = ffmpeg.drawtext(
background_clip, background_clip,
text=text, text=text,
@ -395,11 +400,12 @@ def make_final_video(
defaultPath = f"results/{subreddit}" defaultPath = f"results/{subreddit}"
with ProgressFfmpeg(length, on_update_example) as progress: with ProgressFfmpeg(length, on_update_example) as progress:
path = defaultPath + f"/{filename}" path = defaultPath + f"/{filename[:15]}"
path = ( path = (
path[:251] + ".mp4" path[:120] + ".mp4"
) # Prevent a error by limiting the path length, do not change this. ) # Prevent a error by limiting the path length, do not change this.
try: try:
print(" DEBUG PATH:", path)
ffmpeg.output( ffmpeg.output(
background_clip, background_clip,
final_audio, final_audio,
@ -417,9 +423,9 @@ def make_final_video(
capture_stdout=False, capture_stdout=False,
capture_stderr=False, capture_stderr=False,
) )
except ffmpeg.Error as e: except:
print(e.stderr.decode("utf8")) save_data(subreddit, filename + ".mp4", title, idx, background_config["video"][2])
exit(1) return False
old_percentage = pbar.n old_percentage = pbar.n
pbar.update(100 - old_percentage) pbar.update(100 - old_percentage)
if allowOnlyTTSFolder: if allowOnlyTTSFolder:

@ -54,8 +54,8 @@ def get_credits(bg_config):
video_credits = bg_config['video'][-2] video_credits = bg_config['video'][-2]
credits_template = f""" credits_template = f"""
Background audio by - {audio_credits} Background audio by - @{audio_credits}
Background video by - {video_credits} Background video by - @{video_credits}
""" """
return credits_template return credits_template

Loading…
Cancel
Save