Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from flask import Flask, request, jsonify, send_file
|
3 |
+
from gtts import gTTS
|
4 |
+
from moviepy.editor import *
|
5 |
+
from PIL import Image, ImageDraw, ImageFont
|
6 |
+
from io import BytesIO
|
7 |
+
|
8 |
+
app = Flask(__name__)
|
9 |
+
|
10 |
+
# Function to create TTS audio
|
11 |
+
def create_tts_audio(text, filename="audio.mp3"):
|
12 |
+
tts = gTTS(text=text, lang='en')
|
13 |
+
tts.save(filename)
|
14 |
+
return filename
|
15 |
+
|
16 |
+
# Function to create an image with text
|
17 |
+
def create_image_with_text(text, filename="image.png"):
|
18 |
+
img = Image.new('RGB', (1920, 1080), color=(255, 255, 255))
|
19 |
+
d = ImageDraw.Draw(img)
|
20 |
+
|
21 |
+
try:
|
22 |
+
font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 100)
|
23 |
+
except IOError:
|
24 |
+
font = ImageFont.load_default()
|
25 |
+
|
26 |
+
bbox = d.textbbox((0, 0), text, font=font)
|
27 |
+
text_width, text_height = bbox[2] - bbox[0], bbox[3] - bbox[1]
|
28 |
+
|
29 |
+
position = ((1920 - text_width) // 2, (1080 - text_height) // 2)
|
30 |
+
d.text(position, text, fill=(0, 0, 0), font=font)
|
31 |
+
|
32 |
+
img.save(filename)
|
33 |
+
return filename
|
34 |
+
|
35 |
+
# Function to create video from text
|
36 |
+
def create_video_from_text(text, video_filename="output_video.mp4"):
|
37 |
+
audio_file = create_tts_audio(text)
|
38 |
+
image_file = create_image_with_text(text)
|
39 |
+
|
40 |
+
clip = ImageClip(image_file, duration=AudioFileClip(audio_file).duration)
|
41 |
+
audio = AudioFileClip(audio_file)
|
42 |
+
|
43 |
+
clip = clip.set_audio(audio)
|
44 |
+
clip.write_videofile(video_filename, fps=24)
|
45 |
+
|
46 |
+
# Clean up temporary files
|
47 |
+
os.remove(image_file)
|
48 |
+
os.remove(audio_file)
|
49 |
+
|
50 |
+
return video_filename
|
51 |
+
|
52 |
+
@app.route('/generate_video', methods=['POST'])
|
53 |
+
def generate_video():
|
54 |
+
text = request.json.get('text')
|
55 |
+
if not text:
|
56 |
+
return jsonify({"error": "No text provided"}), 400
|
57 |
+
|
58 |
+
try:
|
59 |
+
# Generate video from text
|
60 |
+
video_file = create_video_from_text(text)
|
61 |
+
|
62 |
+
# Send the video file back
|
63 |
+
return send_file(video_file, as_attachment=True, download_name="output_video.mp4", mimetype="video/mp4")
|
64 |
+
|
65 |
+
except Exception as e:
|
66 |
+
return jsonify({"error": str(e)}), 500
|
67 |
+
|
68 |
+
if __name__ == '__main__':
|
69 |
+
app.run(host="0.0.0.0", port=5000)
|