text-to-video / app.py
venkatl's picture
Create app.py
6b885dc verified
raw
history blame
1.88 kB
import gradio as gr
from PIL import Image, ImageDraw, ImageFont
from gtts import gTTS
from moviepy.editor import ImageClip, AudioFileClip, concatenate_videoclips
import textwrap
import os
def create_video_from_text(text):
lines = text.split('\n')
clips = []
for line in lines:
# Create an image with text
img = Image.new('RGB', (1920, 1080), color = (73, 109, 137)) # Professional color background
d = ImageDraw.Draw(img)
fnt = ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf', 50)
wrapped_text = textwrap.wrap(line, width=20) # Adjust the width parameter as needed
y_text=50
for line1 in wrapped_text:
bbox = d.textbbox((0, 0), line1, font=fnt)
textwidth, textheight = bbox[2], bbox[3]
x= (img.width - textwidth) /2
d.text((x, y_text), line1, font=fnt, fill=(255, 255, 255)) # White text color
y_text += textheight
img.save('text.png')
# Convert text to speech
speech = gTTS(text=line, lang='en', slow=False)
speech.save("text.mp3")
# Create a video clip from the image
clip = ImageClip('text.png')
# Set the duration of the video clip to the duration of the audio file
audioclip = AudioFileClip('text.mp3')
videoclip = clip.set_duration(audioclip.duration)
# Add audio to the video clip
videoclip = videoclip.set_audio(audioclip)
clips.append(videoclip)
# Concatenate all video clips
final_clip = concatenate_videoclips(clips)
# Write the result to a file
final_clip.write_videofile("text.mp4", codec='libx264',fps=24)
os.remove("text.png")
os.remove("text.mp3")
return "text.mp4"
iface = gr.Interface(fn=create_video_from_text, inputs="text", outputs=gr.Video())
iface.launch()