Skip to content

Instantly share code, notes, and snippets.

@xooxo
Created October 10, 2023 12:04
Show Gist options
  • Save xooxo/3ec4256376a8387498f6189acb49b998 to your computer and use it in GitHub Desktop.
Save xooxo/3ec4256376a8387498f6189acb49b998 to your computer and use it in GitHub Desktop.
A script to create video from randomly selected videos on a folder. It's here for archive. concat function is so slow. There are solutions on the net
import os
import random
import ffmpeg
# Function to apply random color to text surrounded by symbols
def apply_random_color(text, symbol_colors):
result = ""
inside_symbol = False
for char in text:
if char == "#" or char == "/":
inside_symbol = not inside_symbol
color = random.choice(symbol_colors) if inside_symbol else "reset"
result += f"\033[{color}m{char}\033[0m"
else:
result += char
return result
# Function to overlay text on a video clip
def overlay_text(input_clip, output_clip, text1, text2, font_path):
print(input_clip)
ffmpeg.input(input_clip).output(
output_clip,
vf=f"scale=640:360,drawtext=text='{text1}':x=50:y=50:fontfile={font_path},drawtext=text='{text2}':x=100:y=100:fontfile={font_path}"
).run(overwrite_output=True)
# Set up some variables
input_clip_folder = "input_clips"
output_folder = "output_clips"
textlist1_file = "textlist1.txt"
textlist2_file = "textlist2.txt"
font_path = "OpenSans-Bold.ttf"
symbol_colors = ["31", "32", "33", "34", "35"] # ANSI color codes
# Create output folder if it doesn't exist
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# Create a list to store the filtered video clips
filtered_clips = []
# Process 4 clips
for i in range(1, 5):
# Randomly select a video clip
input_clip = ".\\" + os.path.join(input_clip_folder, random.choice(os.listdir(input_clip_folder)))
print(input_clip)
# Randomly select text from text files
with open(textlist1_file, "r") as f1, open(textlist2_file, "r") as f2:
text1 = random.choice(f1.readlines()).strip()
text2 = random.choice(f2.readlines()).strip()
# Apply random colors to text
text1 = apply_random_color(text1, symbol_colors)
text2 = apply_random_color(text2, symbol_colors)
# Generate output file name
output_clip = ".\\" + os.path.join(output_folder, f"output_clip_{i}.mp4")
print(output_clip)
# Overlay text on the video clip
overlay_text(input_clip, output_clip, text1, text2, font_path)
# Add the filtered clip to the list for concatenation
filtered_clips.append(output_clip)
# Concatenate the 4 filtered clips into a final output
concatenated_clips = ffmpeg.concat(*[ffmpeg.input(clip) for clip in filtered_clips])
final_output = "final_output.mp4"
concatenated_clips.output(final_output,movflags="+frag_keyframe+separate_moof+omit_tfhd_offset+empty_moov").run(overwrite_output=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment