Update generate.py
Browse files- generate.py +3 -55
generate.py
CHANGED
|
@@ -4,8 +4,8 @@ import re
|
|
| 4 |
import textwrap
|
| 5 |
import numpy as np
|
| 6 |
import requests
|
| 7 |
-
from PIL import Image, ImageDraw, ImageFont
|
| 8 |
-
from moviepy.editor import ImageClip, concatenate_videoclips, AudioFileClip
|
| 9 |
from io import BytesIO
|
| 10 |
import upload
|
| 11 |
|
|
@@ -15,7 +15,6 @@ DURATION_PER_LINE = 3
|
|
| 15 |
PEXELS_API_KEY = os.environ.get('PEXELS_API_KEY', '')
|
| 16 |
|
| 17 |
def get_background_image(keyword):
|
| 18 |
-
"""Fetch background image from Pexels"""
|
| 19 |
try:
|
| 20 |
headers = {'Authorization': PEXELS_API_KEY}
|
| 21 |
r = requests.get(
|
|
@@ -28,7 +27,6 @@ def get_background_image(keyword):
|
|
| 28 |
img_response = requests.get(photo_url, timeout=15)
|
| 29 |
img = Image.open(BytesIO(img_response.content)).convert('RGB')
|
| 30 |
img = img.resize((WIDTH, HEIGHT))
|
| 31 |
-
# Darken image for text readability
|
| 32 |
overlay = Image.new('RGB', (WIDTH, HEIGHT), (0, 0, 0))
|
| 33 |
img = Image.blend(img, overlay, 0.55)
|
| 34 |
return img
|
|
@@ -37,41 +35,29 @@ def get_background_image(keyword):
|
|
| 37 |
return None
|
| 38 |
|
| 39 |
def make_text_frame(text, bg_image=None):
|
| 40 |
-
"""Create frame with background image and text"""
|
| 41 |
if bg_image:
|
| 42 |
img = bg_image.copy()
|
| 43 |
else:
|
| 44 |
img = Image.new('RGB', (WIDTH, HEIGHT), color=(15, 15, 25))
|
| 45 |
-
|
| 46 |
draw = ImageDraw.Draw(img)
|
| 47 |
-
|
| 48 |
try:
|
| 49 |
font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 65)
|
| 50 |
except:
|
| 51 |
font = ImageFont.load_default()
|
| 52 |
-
|
| 53 |
-
# Draw accent lines
|
| 54 |
draw.rectangle([60, 180, WIDTH-60, 193], fill=(255, 80, 80))
|
| 55 |
draw.rectangle([60, HEIGHT-193, WIDTH-60, HEIGHT-180], fill=(255, 80, 80))
|
| 56 |
-
|
| 57 |
-
# Wrap text
|
| 58 |
lines = textwrap.wrap(text, width=22)
|
| 59 |
y = HEIGHT // 2 - (len(lines) * 85) // 2
|
| 60 |
-
|
| 61 |
for line in lines:
|
| 62 |
bbox = draw.textbbox((0, 0), line, font=font)
|
| 63 |
w = bbox[2] - bbox[0]
|
| 64 |
x = (WIDTH - w) // 2
|
| 65 |
-
# Shadow
|
| 66 |
draw.text((x+4, y+4), line, font=font, fill=(0, 0, 0))
|
| 67 |
-
# Text
|
| 68 |
draw.text((x, y), line, font=font, fill=(255, 255, 255))
|
| 69 |
y += 90
|
| 70 |
-
|
| 71 |
return np.array(img)
|
| 72 |
|
| 73 |
def generate_tts(text, output_path):
|
| 74 |
-
"""Generate voiceover using Google TTS"""
|
| 75 |
try:
|
| 76 |
from gtts import gTTS
|
| 77 |
tts = gTTS(text=text, lang='en', slow=False)
|
|
@@ -84,37 +70,22 @@ def generate_tts(text, output_path):
|
|
| 84 |
def generate_video(script, title, description):
|
| 85 |
print("Starting video generation...")
|
| 86 |
print(f"Script received: {script[:100]}")
|
| 87 |
-
|
| 88 |
-
# Split script into sentences
|
| 89 |
sentences = re.split(r'[.!?\n]', script)
|
| 90 |
sentences = [s.strip() for s in sentences if len(s.strip()) > 5]
|
| 91 |
-
|
| 92 |
if not sentences:
|
| 93 |
words = script.split()
|
| 94 |
sentences = [' '.join(words[i:i+8]) for i in range(0, len(words), 8)]
|
| 95 |
-
|
| 96 |
sentences = sentences[:15]
|
| 97 |
print(f"Total clips: {len(sentences)}")
|
| 98 |
-
|
| 99 |
-
# Get background image from Pexels
|
| 100 |
keyword = title.replace('#shorts', '').replace('Facts', '').strip()
|
| 101 |
print(f"Fetching background for: {keyword}")
|
| 102 |
bg_image = get_background_image(keyword)
|
| 103 |
-
|
| 104 |
clips = []
|
| 105 |
-
audio_clips = []
|
| 106 |
-
|
| 107 |
for i, sentence in enumerate(sentences):
|
| 108 |
print(f"Creating clip {i+1}/{len(sentences)}")
|
| 109 |
-
|
| 110 |
-
# Generate TTS audio
|
| 111 |
audio_path = f'/app/audio_{i}.mp3'
|
| 112 |
has_audio = generate_tts(sentence, audio_path)
|
| 113 |
-
|
| 114 |
-
# Create video frame
|
| 115 |
frame = make_text_frame(sentence, bg_image)
|
| 116 |
-
|
| 117 |
-
# Get audio duration
|
| 118 |
if has_audio and os.path.exists(audio_path):
|
| 119 |
audio = AudioFileClip(audio_path)
|
| 120 |
duration = max(audio.duration + 0.5, DURATION_PER_LINE)
|
|
@@ -122,17 +93,13 @@ def generate_video(script, title, description):
|
|
| 122 |
clip = clip.set_audio(audio)
|
| 123 |
else:
|
| 124 |
clip = ImageClip(frame, duration=DURATION_PER_LINE)
|
| 125 |
-
|
| 126 |
clip = clip.fadein(0.3).fadeout(0.3)
|
| 127 |
clips.append(clip)
|
| 128 |
-
|
| 129 |
if not clips:
|
| 130 |
print("No clips generated!")
|
| 131 |
return False
|
| 132 |
-
|
| 133 |
print("Combining clips...")
|
| 134 |
final = concatenate_videoclips(clips, method="compose")
|
| 135 |
-
|
| 136 |
output_path = '/app/video.mp4'
|
| 137 |
print("Writing video...")
|
| 138 |
final.write_videofile(
|
|
@@ -143,14 +110,11 @@ def generate_video(script, title, description):
|
|
| 143 |
verbose=False,
|
| 144 |
logger=None
|
| 145 |
)
|
| 146 |
-
|
| 147 |
-
# Cleanup audio files
|
| 148 |
for i in range(len(sentences)):
|
| 149 |
try:
|
| 150 |
os.remove(f'/app/audio_{i}.mp3')
|
| 151 |
except:
|
| 152 |
pass
|
| 153 |
-
|
| 154 |
print("Video generated successfully!")
|
| 155 |
return True
|
| 156 |
|
|
@@ -164,20 +128,4 @@ if __name__ == '__main__':
|
|
| 164 |
video_id = upload.upload_video(title, description)
|
| 165 |
print(f"SUCCESS: https://youtube.com/shorts/{video_id}")
|
| 166 |
else:
|
| 167 |
-
print("Video generation failed!")
|
| 168 |
-
```
|
| 169 |
-
|
| 170 |
-
---
|
| 171 |
-
|
| 172 |
-
## Step 4 — Update `requirements.txt`:
|
| 173 |
-
```
|
| 174 |
-
moviepy==1.0.3
|
| 175 |
-
Pillow
|
| 176 |
-
numpy
|
| 177 |
-
imageio
|
| 178 |
-
imageio-ffmpeg
|
| 179 |
-
gtts
|
| 180 |
-
requests
|
| 181 |
-
google-api-python-client
|
| 182 |
-
google-auth
|
| 183 |
-
google-auth-httplib2
|
|
|
|
| 4 |
import textwrap
|
| 5 |
import numpy as np
|
| 6 |
import requests
|
| 7 |
+
from PIL import Image, ImageDraw, ImageFont
|
| 8 |
+
from moviepy.editor import ImageClip, concatenate_videoclips, AudioFileClip
|
| 9 |
from io import BytesIO
|
| 10 |
import upload
|
| 11 |
|
|
|
|
| 15 |
PEXELS_API_KEY = os.environ.get('PEXELS_API_KEY', '')
|
| 16 |
|
| 17 |
def get_background_image(keyword):
|
|
|
|
| 18 |
try:
|
| 19 |
headers = {'Authorization': PEXELS_API_KEY}
|
| 20 |
r = requests.get(
|
|
|
|
| 27 |
img_response = requests.get(photo_url, timeout=15)
|
| 28 |
img = Image.open(BytesIO(img_response.content)).convert('RGB')
|
| 29 |
img = img.resize((WIDTH, HEIGHT))
|
|
|
|
| 30 |
overlay = Image.new('RGB', (WIDTH, HEIGHT), (0, 0, 0))
|
| 31 |
img = Image.blend(img, overlay, 0.55)
|
| 32 |
return img
|
|
|
|
| 35 |
return None
|
| 36 |
|
| 37 |
def make_text_frame(text, bg_image=None):
|
|
|
|
| 38 |
if bg_image:
|
| 39 |
img = bg_image.copy()
|
| 40 |
else:
|
| 41 |
img = Image.new('RGB', (WIDTH, HEIGHT), color=(15, 15, 25))
|
|
|
|
| 42 |
draw = ImageDraw.Draw(img)
|
|
|
|
| 43 |
try:
|
| 44 |
font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 65)
|
| 45 |
except:
|
| 46 |
font = ImageFont.load_default()
|
|
|
|
|
|
|
| 47 |
draw.rectangle([60, 180, WIDTH-60, 193], fill=(255, 80, 80))
|
| 48 |
draw.rectangle([60, HEIGHT-193, WIDTH-60, HEIGHT-180], fill=(255, 80, 80))
|
|
|
|
|
|
|
| 49 |
lines = textwrap.wrap(text, width=22)
|
| 50 |
y = HEIGHT // 2 - (len(lines) * 85) // 2
|
|
|
|
| 51 |
for line in lines:
|
| 52 |
bbox = draw.textbbox((0, 0), line, font=font)
|
| 53 |
w = bbox[2] - bbox[0]
|
| 54 |
x = (WIDTH - w) // 2
|
|
|
|
| 55 |
draw.text((x+4, y+4), line, font=font, fill=(0, 0, 0))
|
|
|
|
| 56 |
draw.text((x, y), line, font=font, fill=(255, 255, 255))
|
| 57 |
y += 90
|
|
|
|
| 58 |
return np.array(img)
|
| 59 |
|
| 60 |
def generate_tts(text, output_path):
|
|
|
|
| 61 |
try:
|
| 62 |
from gtts import gTTS
|
| 63 |
tts = gTTS(text=text, lang='en', slow=False)
|
|
|
|
| 70 |
def generate_video(script, title, description):
|
| 71 |
print("Starting video generation...")
|
| 72 |
print(f"Script received: {script[:100]}")
|
|
|
|
|
|
|
| 73 |
sentences = re.split(r'[.!?\n]', script)
|
| 74 |
sentences = [s.strip() for s in sentences if len(s.strip()) > 5]
|
|
|
|
| 75 |
if not sentences:
|
| 76 |
words = script.split()
|
| 77 |
sentences = [' '.join(words[i:i+8]) for i in range(0, len(words), 8)]
|
|
|
|
| 78 |
sentences = sentences[:15]
|
| 79 |
print(f"Total clips: {len(sentences)}")
|
|
|
|
|
|
|
| 80 |
keyword = title.replace('#shorts', '').replace('Facts', '').strip()
|
| 81 |
print(f"Fetching background for: {keyword}")
|
| 82 |
bg_image = get_background_image(keyword)
|
|
|
|
| 83 |
clips = []
|
|
|
|
|
|
|
| 84 |
for i, sentence in enumerate(sentences):
|
| 85 |
print(f"Creating clip {i+1}/{len(sentences)}")
|
|
|
|
|
|
|
| 86 |
audio_path = f'/app/audio_{i}.mp3'
|
| 87 |
has_audio = generate_tts(sentence, audio_path)
|
|
|
|
|
|
|
| 88 |
frame = make_text_frame(sentence, bg_image)
|
|
|
|
|
|
|
| 89 |
if has_audio and os.path.exists(audio_path):
|
| 90 |
audio = AudioFileClip(audio_path)
|
| 91 |
duration = max(audio.duration + 0.5, DURATION_PER_LINE)
|
|
|
|
| 93 |
clip = clip.set_audio(audio)
|
| 94 |
else:
|
| 95 |
clip = ImageClip(frame, duration=DURATION_PER_LINE)
|
|
|
|
| 96 |
clip = clip.fadein(0.3).fadeout(0.3)
|
| 97 |
clips.append(clip)
|
|
|
|
| 98 |
if not clips:
|
| 99 |
print("No clips generated!")
|
| 100 |
return False
|
|
|
|
| 101 |
print("Combining clips...")
|
| 102 |
final = concatenate_videoclips(clips, method="compose")
|
|
|
|
| 103 |
output_path = '/app/video.mp4'
|
| 104 |
print("Writing video...")
|
| 105 |
final.write_videofile(
|
|
|
|
| 110 |
verbose=False,
|
| 111 |
logger=None
|
| 112 |
)
|
|
|
|
|
|
|
| 113 |
for i in range(len(sentences)):
|
| 114 |
try:
|
| 115 |
os.remove(f'/app/audio_{i}.mp3')
|
| 116 |
except:
|
| 117 |
pass
|
|
|
|
| 118 |
print("Video generated successfully!")
|
| 119 |
return True
|
| 120 |
|
|
|
|
| 128 |
video_id = upload.upload_video(title, description)
|
| 129 |
print(f"SUCCESS: https://youtube.com/shorts/{video_id}")
|
| 130 |
else:
|
| 131 |
+
print("Video generation failed!")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|