The script you've provided has a few issues that prevent it from working as intended. I'll explain what's wrong with the script and suggest libraries and modifications to help you achieve your goal of creating a video from images with variable fonts and scenes.
Issues with the Script
1. Saving Images as MP4 Files Using PIL
The primary issue is that you're trying to save images as an MP4 video using the PIL (Python Imaging Library) Image.save() method:
img.save(output_path, save_all=True, append_images=images, duration=[scene["duration"] * 1000 for scene in data["scenes"]], loop=0)
What's Wrong:
-
PIL Does Not Support MP4 Output: The PIL.Image.save() method does not support saving images directly as MP4 videos. It can save images in formats like JPEG, PNG, and GIF (including animated GIFs using save_all=True), but not MP4.
-
Incorrect Use of img.save(): Even if saving as GIF, the method is misused in this context because img is a single image, and images is a list of images. The append_images parameter should exclude the first image (as img is the first frame), but the way it's used here may cause unexpected results.
2. Handling Variable Fonts with PIL
Another issue is how you're attempting to set the variable font axes:
font = ImageFont.truetype(f"{font_path}[XROT={xrot_value},YROT={yrot_value}]", text_size)
What's Wrong:
-
Variable Font Axes Not Applied: The ImageFont.truetype() method in PIL does not support setting variable font axes by appending axis values to the font path string as shown.
-
No Direct Support for Variable Fonts in PIL: As of now, PIL does not natively support setting variable font axes. This means that even if the font path is correct, the rotation axes (XROT and YROT) won't be applied to the font rendering.
3. Text Size Measurement
w, h = draw.textsize(text, font=font)
What's Wrong:
-
Deprecated Method: The draw.textsize() method is deprecated for obtaining accurate text size with variable fonts or complex scripts.
-
Inaccuracy with Variable Fonts: This method may not return accurate dimensions when dealing with variable fonts or fonts with advanced typographic features.
Suggested Libraries and Solutions
To fix these issues, you can leverage additional libraries and modify your script accordingly.
1. Use MoviePy to Create the MP4 Video
Why MoviePy:
-
Video Creation from Images: MoviePy is a Python library for video editing, which allows you to create video clips from images (static or animated).
-
Supports Different Durations: It can handle varying durations for each image/scene in the video.
-
Easy Integration: MoviePy can be easily integrated into your script to build the final MP4 video.
How to Implement:
-
Install MoviePy:
pip install moviepy
-
Modify the Script to Use MoviePy:
After generating the images, create ImageClip objects for each image and concatenate them into a video.
from moviepy.editor import ImageClip, concatenate_videoclips
# Generate ImageClips with specified durations
clips = []
for idx, scene in enumerate(data["scenes"]):
# Random values for XROT and YROT to create variation
xrot_value = random.randint(-30, 30)
yrot_value = random.randint(-30, 30)
# Generate the scene image
img = create_scene_image(scene["text"], scene["text_color"], scene["background_color"], scene["text_size"], font_path, xrot_value, yrot_value)
# Save image to a temporary file
img_path = f"/tmp/scene_{idx}.png"
img.save(img_path)
# Create an ImageClip
clip = ImageClip(img_path).set_duration(scene["duration"])
clips.append(clip)
# Concatenate clips
final_clip = concatenate_videoclips(clips, method="compose")
# Write the video file
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
output_path = f"/root/mm/var/mp4/{timestamp}.mp4"
final_clip.write_videofile(output_path, fps=24)
print(f"Video saved to {output_path}")
2. Use fontTools to Handle Variable Fonts
Why fontTools:
-
Manipulate Variable Fonts: The fontTools library allows you to access and manipulate OpenType and TrueType fonts, including setting variable font axes.
-
Integration with PIL: Combined with PIL, you can create images that utilize variable font instances.
How to Implement:
-
Install fontTools:
pip install fonttools
-
Create a Function to Load a Variable Font Instance:
from fontTools.ttLib import TTFont
from fontTools.varLib import instantiateVariableFont
import io
def get_variable_font(font_path, axes):
# Load the variable font
var_font = TTFont(font_path)
# Instantiate the font with the specified axes
instantiated_font = instantiateVariableFont(var_font, axes, inplace=False)
# Save the instantiated font to a BytesIO object
font_bytes_io = io.BytesIO()
instantiated_font.save(font_bytes_io)
font_bytes_io.seek(0)
# Load the font into PIL
font = ImageFont.truetype(font_bytes_io, text_size)
return font
-
Modify create_scene_image to Use the Variable Font Instance:
def create_scene_image(text, text_color, background_color, text_size, font_path, xrot_value, yrot_value):
# Create an image with 1024x1024 dimensions
img = Image.new('RGB', (1024, 1024), color=background_color)
draw = ImageDraw.Draw(img)
# Define the axes for the variable font
axes = {'XROT': xrot_value, 'YROT': yrot_value}
# Load the variable font instance
font = get_variable_font(font_path, axes)
# Calculate text position to center it
w, h = draw.textbbox((0, 0), text, font=font)[2:]
position = ((1024 - w) // 2, (1024 - h) // 2)
# Draw the text onto the image
draw.text(position, text, fill=text_color, font=font)
return img
3. Use Accurate Text Measurement Methods
-
Use draw.textbbox() Instead of draw.textsize():
bbox = draw.textbbox((0, 0), text, font=font)
w, h = bbox[2] - bbox[0], bbox[3] - bbox[1]
-
This Provides Accurate Dimensions: The textbbox method returns the bounding box of the text, which is more accurate, especially for variable fonts and complex scripts.
Revised Script
Here's a summary of the revised script incorporating the suggested changes:
import json
import os
import random
from datetime import datetime
from PIL import Image, ImageDraw, ImageFont
from fontTools.ttLib import TTFont
from fontTools.varLib import instantiateVariableFont
import io
from moviepy.editor import ImageClip, concatenate_videoclips
# Predefined color names and their corresponding hex values
COLORS = {
"Red": "#FF0000",
"Green": "#00FF00",
"Blue": "#0000FF",
"Yellow": "#FFFF00",
"Cyan": "#00FFFF",
"Magenta": "#FF00FF",
"Black": "#000000",
"White": "#FFFFFF",
"Orange": "#FFA500",
"Purple": "#800080",
}
# Function to ask user for input with validation (same as before)
def ask_questions():
# [Your existing code for collecting user inputs]
pass # Replace this with the actual function
# Function to load variable font instance
def get_variable_font(font_path, text_size, axes):
# Load the variable font
var_font = TTFont(font_path)
# Instantiate the font with the specified axes
instantiated_font = instantiateVariableFont(var_font, axes, inplace=False)
# Save the instantiated font to a BytesIO object
font_bytes_io = io.BytesIO()
instantiated_font.save(font_bytes_io)
font_bytes_io.seek(0)
# Load the font into PIL
font = ImageFont.truetype(font_bytes_io, text_size)
return font
# Function to create image for each scene
def create_scene_image(text, text_color, background_color, text_size, font_path, xrot_value, yrot_value):
# Create an image with 1024x1024 dimensions
img = Image.new('RGB', (1024, 1024), color=background_color)
draw = ImageDraw.Draw(img)
# Define the axes for the variable font
axes = {'XROT': xrot_value, 'YROT': yrot_value}
# Load the variable font instance
font = get_variable_font(font_path, text_size, axes)
# Calculate text position to center it
bbox = draw.textbbox((0, 0), text, font=font)
w, h = bbox[2] - bbox[0], bbox[3] - bbox[1]
position = ((1024 - w) // 2, (1024 - h) // 2)
# Draw the text onto the image
draw.text(position, text, fill=text_color, font=font)
return img
# Main script logic
def main():
font_path = "/root/mm/var/TiltWarp-Regular-VariableFont_XROT,YROT.ttf"
# Ask the user questions and generate scenes
data = ask_questions()
# Generate images for each scene and save them
clips = []
for idx, scene in enumerate(data["scenes"]):
# Random values for XROT and YROT to create variation
xrot_value = random.randint(-30, 30)
yrot_value = random.randint(-30, 30)
# Generate the scene image
img = create_scene_image(
scene["text"],
scene["text_color"],
scene["background_color"],
scene["text_size"],
font_path,
xrot_value,
yrot_value
)
# Save image to a temporary file
img_path = f"/tmp/scene_{idx}.png"
img.save(img_path)
# Create an ImageClip
clip = ImageClip(img_path).set_duration(scene["duration"])
clips.append(clip)
# Concatenate clips
final_clip = concatenate_videoclips(clips, method="compose")
# Write the video file
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
output_path = f"/root/mm/var/mp4/{timestamp}.mp4"
final_clip.write_videofile(output_path, fps=24)
print(f"Video saved to {output_path}")
if __name__ == "__main__":
main()
Summary of Changes
- Added
MoviePy Integration: To handle video creation from images with specified durations.
- Used
fontTools for Variable Fonts: To properly set the variable font axes (XROT and YROT) when rendering text.
- Improved Text Measurement: Replaced
draw.textsize() with draw.textbbox() for accurate text positioning.
- Temporary Image Files: Saved images to temporary files to be used by
MoviePy.
Additional Notes
-
Temporary Files Management: You may want to add code to clean up the temporary image files after the video is created.
-
Error Handling: It’s good practice to include error handling for file operations and user input.
-
Font File Path: Ensure that the font file at font_path exists and supports the specified axes (XROT and YROT).
-
Permissions: Make sure the script has permission to write to /root/mm/var/mp4/ and /tmp/.
Conclusion
By using MoviePy for video creation and fontTools for handling variable fonts, you can address the issues in the script and achieve the desired functionality. The revised script should help you generate a video where each scene displays text with variable font rotations and durations as specified by the user.