Too Boomer for TikTok? Not anymore! The next code is a Python code created through MoviePy and PyGoogle_Image libraries. The code creates a TikTok video given a theme for the video (this is going to be the only input). During the development of this program, I created different TikTok options. These options include creating the TikTok with personal pictures, using Google pictures with different templates, and the one I’m going to showcase, which involves using Google Images. In this option, the template also includes text to display according to the picture’s positionNext, we are going to explain all the steps of the code:
Steps:
- Define the theme of the TikTok.
- The program uses the PyGoogle_Image library to download the images from Google, where the theme input is going to be the Google Images search.
- All the images are going to be saved in a specific path.
- Then the code adds the MP3 audio to the path with the images.
- Next, it will read all the files needed to create the TikTok and save them in a MoviePy format.
- Define the template of the TikTok with a dictionary, where the key will be the photo position, and the value will be the duration of each photo.
- The next step is to select the pictures that will fit best into the TikTok format, using a loop for all the pictures, where:
- If the image size height is more than 550px, it will resize the image to fit a phone screen.
- Then, it will set the duration of the picture according to the position (using the dictionary).
- Add the picture with the duration to a list.
- Set the audio of the TikTok.
- Convert the list with all the images to the TikTok and save it.”
Output:
Code:
# Imports
from PIL import Image
from IPython.display import Video
from moviepy.editor import VideoFileClip, AudioFileClip, concatenate_videoclips
import os
from pygoogle_image import image as pi
from PIL import Image
from moviepy.editor import VideoFileClip, TextClip, CompositeVideoClip
import openai as ai
import shutil
## Choose the theme
theme = "Nature phone wallpaper"
limit = 100
## Generate the pictures
def generar_fotos(theme, limit):
pi.download(theme, limit )
generar_fotos(theme, limit)
### Delet the 2 first bad pics
# Main path
path = r"images_path"
path = path[:-1] + theme.replace(" ", "_")
# Pics name
pic_1_delet = path + "/" + theme + "_1.png"
pic_2_delet = path + "/" + theme + "_2.png"
# Delet pics:
os.remove(pic_1_delet)
os.remove(pic_2_delet)
## ELiminar la carpeta con las fotosuna vez se ha creado el video
### Move audio
source_file = r'path... TIKTOK\Audios\Icantexplain.mp3'
if not os.path.exists(source_file):
print("Source file does not exist.")
else:
# Check if the destination folder exists
if not os.path.exists(path):
print("Destination folder does not exist.")
else:
# Attempt to copy the file
try:
shutil.copy(source_file, os.path.join(path))
print("File copied successfully.")
except PermissionError as e:
print(f"PermissionError: {e}")
# Read content
#25 fotos + audio
def read_files_path(path):
#Contadores
contador_files = 0
contador_files_mp3 = 0
contador_files_vid = 0
contador_files_img = 0
#dicionario output
dic_files = {}
# Get a list of all files in the path
files = os.listdir(path)
# Iterate over each file in the list
for file in files:
# Create the file's absolute path
file_path = os.path.join(path, file)
# Check if the file is a regular file
if os.path.isfile(file_path):
#Obtain the path
extension = file_path[-4:].upper()
#mp3:
if extension == '.MP3':
audio = file_path
#Name dic
name_mp3 = "mp3_file" + str(contador_files_mp3)
#Save dic
#dic_files[name_mp3] = file_path
#Add 1 to counter
contador_files_mp3 = contador_files_mp3 + 1
#Imagen:
if (extension == '.JPG') | (extension == '.PNG') | (extension == 'JPEG'):
#Name dic
name_img = "img_file" + str(contador_files_img)
#Save dic
dic_files[name_img] = file_path
#Add 1 to counter
contador_files_img = contador_files_img +1
#Video:
if (extension == '.MOV') | (extension == '.MP4'):
#Name dic
name_vid = "vid_file" + str(contador_files_vid)
#Save dic
dic_files[name_vid] = file_path
#Add 1 to counter
contador_files_vid = contador_files_vid +1
# Perform operations on the file
print(file_path)
return dic_files, audio
#path = r"" # Path with images.
dic_files, audio = read_files_path(path)
audio = AudioFileClip(audio)
### RESIZE;
def resize(path):
# Open the image file
image = Image.open(path)
# Define the desired resolution (width, height)
desired_width = 480
desired_height = 848
# Calculate the center coordinates for cropping
left = (image.width - desired_width) // 2
upper = (image.height - desired_height) // 2
right = left + desired_width
lower = upper + desired_height
# Crop the image
cropped_image = image.crop((left, upper, right, lower))
# Resize the cropped image to the desired resolution
resized_image = cropped_image.resize((desired_width, desired_height))
# Save the resized image
resized_image.save(path)
# Leer y clasificar files:
###
# Tik tok with text
dicionario_Icantexplain = {
"Amount":13,
0:2.1,
1:2.4,
2:1.2,
3:1.4,
4:0.7,
5:1.4,
6:1,
7:1,
8:1,
9:0.8,
10:0.7,
11:1.1,
12:1,
13:1.2,
14: "I can't explain",
15: "I got a feeling that I just",
16: "I can't erase",
17: "Just a feeling that",
18: "I won't",
19: "Won't leave behind",
20: "Because it's something",
21: "That is on",
22: "It's on my mind",
23: "I guess it goes like",
24:"na-na-na",
25:".",
26:".",
27:".",
28:".",
29:"."
}
dicionario = dicionario_Icantexplain
media_list= []
i = 0
for file_name in dic_files.keys():
# SI ya te el numero de fotos neccesarias parar
if i >= (dicionario["Amount"]+1):
break
# Print Nombre:path
print(dic_files[file_name])
# Get the path name
file_path = dic_files[file_name]
# Abrir imagen y descartar si toca
image = Image.open(file_path)
if (image.size[1]>= 550): #& (( (image.size[0] / image.size[1]) > 0.45 ) & ( (image.size[0] / image.size[1]) < 0.65 ))
try:
#Ajustar Imagen
resize(file_path)
#Read img
video_clip = VideoFileClip(file_path)
video_clip = video_clip.set_duration(dicionario[i])
# Create a TextClip with the desired text
try:
print(dicionario[i+14], dicionario[i])
text_clip = TextClip(dicionario[i+14], fontsize=20, color='white', bg_color ="black")
except:
text_clip = TextClip(",", fontsize=20, color='white', bg_color ="black")
print("good", i )
# Position the text on the video (adjust x and y as needed)
x_position = video_clip.w / 2 - text_clip.w / 2
y_position = video_clip.h / 2 - text_clip.h / 2
text_clip = text_clip.set_position((x_position, y_position)).set_duration(dicionario[i])
# Composite the TextClip on top of the video
composite_clip = CompositeVideoClip([video_clip, text_clip])
#Audio:
media = composite_clip.set_audio(audio)
# Añadir a la lista de fotos a mostrar
media_list.append(media)
i = i +1
except:
print("Error")
pass
else:
print("Imagen pequeña")
name_file = theme.replace(" ","_")
name_file = name_file + ".mp4"
name_file
len(media_list)
# Concatenate the video clips
final_video = concatenate_videoclips(media_list)
# Set the final video's audio to the desired audio
final_video = final_video.set_audio(audio)
# Display the video in Jupyter Notebook or JupyterLab
#Video(final_video)
# Export the final video with changed audio
final_video.write_videofile(name_file)