import json
import os
from PIL import Image, ImageDraw, ImageFont
import imageio
Define your paths here
json_path = 'video_data.json' # Ensure this path is correct
output_dir = 'output_videos'
default_font_path = '/root/mm/vidtext/opensansvar.ttf' # Default font path
Function to generate scene image
def generate_scene_image(scene):
# Load default font
try:
# Attempt to load a specific font; if fails, use default
font_path = scene.get("font_path", default_font_path) # This assumes you may set a font_path in scene
font = ImageFont.truetype(font_path, size=50)
except Exception as e:
print(f"Error loading font: {e}. Using default font.")
font = ImageFont.truetype(default_font_path, size=50)
code
# Generate scene image based on scene data
img = Image.new('RGB', (1920, 1080), color=scene.get("background_color", "black"))
draw = ImageDraw.Draw(img)
# Calculate text position and text size
text = scene["text"]
font_color = scene.get("font_color", "white")
text_width, text_height = draw.textbbox((0, 0), text, font=font)[2:]
position = ((1920 - text_width) // 2, (1080 - text_height) // 2)
# Draw text on the image
draw.text(position, text, font=font, fill=font_color)
# Save the image to a file
image_path = f"{output_dir}/{text.replace(' ', '_')}.png"
img.save(image_path)
return image_path
Function to generate video from scene images
def generate_video(scenes):
# Ensure output directory exists
if not os.path.exists(output_dir):
os.makedirs(output_dir)
code
# Placeholder for images generated
images = []
for scene in scenes:
image_path = generate_scene_image(scene)
images.append(image_path)
# Create video using images
video_output = f"{output_dir}/final_video.mp4"
writer = imageio.get_writer(video_output, fps=24)
for img in images:
frame = imageio.imread(img)
writer.append_data(frame)
writer.close()
print(f"Video generated: {video_output}")
Assistant
Main function to handle video creation
def main(use_precompiled):
# Load scenes from JSON
with open(json_path, 'r') as f:
scenes = json.load(f)
code
# Generate video using the scene data
generate_video(scenes)
if name == "main":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--use-precompiled', action='store_true', help='Use precompiled JSON for scenes')
args = parser.parse_args()
code
main(args.use_precompiled)
What is wrong with this script
The script contains several issues that prevent it from functioning correctly:
Incorrect Calculation of Text Width and Height:
In your generate_scene_image function, you're incorrectly calculating the text_width and text_height. The draw.textbbox method returns a tuple of four coordinates (left, top, right, bottom). However, you're taking the right and bottom values directly as text_width and text_height, which is incorrect because these are coordinates, not dimensions.
This means text_width becomes right and text_height becomes bottom, which doesn't represent the actual width and height of the text.
Solution:
You need to calculate the width and height by subtracting the starting coordinates:
python
left, top, right, bottom = draw.textbbox((0, 0), text, font=font)
text_width = right - left
text_height = bottom - top
This correctly computes the dimensions of the text, allowing you to center it properly on the image.
Font File Path Issues:
The default_font_path is set to an absolute path that is likely not valid on your system:
python
default_font_path = '/root/mm/vidtext/opensansvar.ttf' # Default font path
Issue:
If the font file does not exist at this path, the script will raise an exception when it tries to load the font.
In the exception handling, you attempt to load the same font again, which will fail repeatedly.
Solution:
Provide a valid path to a font file that exists on your system. You can use a relative path or ensure the font file is in the same directory as your script.
Modify your exception handling to handle the case when the default font is also not available. You could use a standard font like Arial or fallback to a default system font.
Example:
python
default_font_path = 'opensansvar.ttf' # Ensure this font file is in your script directory
try:
font_path = scene.get("font_path", default_font_path)
font = ImageFont.truetype(font_path, size=50)
except Exception as e:
print(f"Error loading font '{font_path}': {e}. Attempting to load default font.")
try:
font = ImageFont.truetype(default_font_path, size=50)
except Exception as e:
print(f"Error loading default font '{default_font_path}': {e}. Using system default font.")
font = ImageFont.load_default()
Unused Argument in main Function:
The use_precompiled argument in your main function is not used, making it redundant.
Issue:
python
def main(use_precompiled):
# Load scenes from JSON
with open(json_path, 'r') as f:
scenes = json.load(f)
# Generate video using the scene data
generate_video(scenes)
Solution:
If you intend to use precompiled data, you need to incorporate logic that handles that. If not, you can remove the argument to clean up your code:
python
def main():
# Load scenes from JSON
with open(json_path, 'r') as f:
scenes = json.load(f)
# Generate video using the scene data
generate_video(scenes)
And update your if __name__ == "__main__" block accordingly.
Assumption that video_data.json Exists and Is Correctly Formatted:
The script assumes that the video_data.json file exists in the specified path and contains valid JSON data.
Issue:
If the JSON file does not exist or contains invalid data, the script will crash.
There's no error handling for file not found or JSON parsing errors.
Solution:
Add error handling when reading the JSON file:
python
def main():
# Load scenes from JSON
try:
with open(json_path, 'r') as f:
scenes = json.load(f)
except FileNotFoundError:
print(f"Error: JSON file '{json_path}' not found.")
return
except json.JSONDecodeError as e:
print(f"Error decoding JSON: {e}")
return
# Generate video using the scene data
generate_video(scenes)
Potential Issues with Image Paths:
When saving images, you replace spaces in the text with underscores to create the filename. If the text contains characters that are invalid in filenames (like slashes or colons), this could cause an error.
The script saves images to disk but doesn't delete them after creating the video, which could clutter the output_videos directory.
Solution:
After closing the video writer, delete the temporary images:
python
import os
# At the end of generate_video function
writer.close()
print(f"Video generated: {video_output}")
# Delete temporary images
for img in images:
os.remove(img)
Using imageio Instead of imageio-ffmpeg:
The imageio library requires additional plugins to handle video writing, and in some cases, you might need imageio-ffmpeg installed.
Issue:
If ffmpeg is not installed or imageio can't find it, the script will fail when attempting to write the video.
Solution:
Ensure ffmpeg is installed and imageio-ffmpeg is available. You can install it using:
code
pip install imageio-ffmpeg
Alternatively, you can use other libraries like moviepy for video creation, which can be more straightforward.
Example using moviepy:
python
from moviepy.editor import ImageSequenceClip
def generate_video(scenes):
# Ensure output directory exists
if not os.path.exists(output_dir):
os.makedirs(output_dir)
# Placeholder for images generated
images = []
durations = [] # You might have durations per scene in your JSON
for scene in scenes:
image_path = generate_scene_image(scene)
images.append(image_path)
durations.append(scene.get('duration', 2)) # Default duration 2 seconds
# Create video using MoviePy
video_output = f"{output_dir}/final_video.mp4"
clip = ImageSequenceClip(images, durations=durations)
clip.write_videofile(video_output, fps=24)
print(f"Video generated: {video_output}")
# Delete temporary images
for img in images:
os.remove(img)
Summary:
The main issues with your script are:
Incorrect calculation of text dimensions leading to misalignment.
Invalid font path causing exceptions.
Lack of error handling for missing files and invalid data.
Unused parameters and possible filename issues.
Corrected generate_scene_image Function:
python
def generate_scene_image(scene):
# Load default font
try:
# Attempt to load a specific font; if fails, use default
font_path = scene.get("font_path", default_font_path)
font = ImageFont.truetype(font_path, size=50)
except Exception as e:
print(f"Error loading font '{font_path}': {e}. Attempting to load default font.")
try:
font = ImageFont.truetype(default_font_path, size=50)
except Exception as e:
print(f"Error loading default font '{default_font_path}': {e}. Using system default font.")
font = ImageFont.load_default()
# Generate scene image based on scene data
img = Image.new('RGB', (1920, 1080), color=scene.get("background_color", "black"))
draw = ImageDraw.Draw(img)
# Calculate text position and text size
text = scene["text"]
font_color = scene.get("font_color", "white")
left, top, right, bottom = draw.textbbox((0, 0), text, font=font)
text_width = right - left
text_height = bottom - top
position = ((1920 - text_width) // 2, (1080 - text_height) // 2)
# Draw text on the image
draw.text(position, text, font=font, fill=font_color)
# Save the image to a file
image_filename = sanitize_filename(text) + '.png'
image_path = os.path.join(output_dir, image_filename)
img.save(image_path)
return image_path
By addressing these issues, your script should function correctly and generate the desired video output.