Spaces:
Runtime error
Runtime error
Update generator.py
Browse files- generator.py +136 -0
generator.py
CHANGED
|
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# generator.py
|
| 2 |
+
import os, random, json
|
| 3 |
+
from datetime import datetime
|
| 4 |
+
from gtts import gTTS
|
| 5 |
+
from moviepy.editor import AudioFileClip, ImageClip, CompositeVideoClip, TextClip, CompositeAudioClip
|
| 6 |
+
from PIL import Image, ImageDraw, ImageFilter, ImageFont
|
| 7 |
+
|
| 8 |
+
# Folders (ensure these exist in repo)
|
| 9 |
+
OUTPUT_IMAGES = "outputs/images"
|
| 10 |
+
OUTPUT_AUDIO = "outputs/audio"
|
| 11 |
+
OUTPUT_VIDEOS = "outputs/videos"
|
| 12 |
+
BG_DIR = "backgrounds"
|
| 13 |
+
MUSIC_DIR = "music"
|
| 14 |
+
|
| 15 |
+
for d in (OUTPUT_IMAGES, OUTPUT_AUDIO, OUTPUT_VIDEOS, BG_DIR, MUSIC_DIR):
|
| 16 |
+
os.makedirs(d, exist_ok=True)
|
| 17 |
+
|
| 18 |
+
# helpers
|
| 19 |
+
def next_index(folder, prefix, ext):
|
| 20 |
+
files = [f for f in os.listdir(folder) if f.startswith(prefix) and f.endswith(ext)]
|
| 21 |
+
if not files: return 1
|
| 22 |
+
nums = []
|
| 23 |
+
for f in files:
|
| 24 |
+
try:
|
| 25 |
+
# expects prefix_N.ext
|
| 26 |
+
part = f[len(prefix) + 1: -len(ext)]
|
| 27 |
+
nums.append(int(part))
|
| 28 |
+
except:
|
| 29 |
+
pass
|
| 30 |
+
return max(nums, default=0) + 1
|
| 31 |
+
|
| 32 |
+
def generate_placeholder_image(prompt, out_path, size=(720,1280)):
|
| 33 |
+
h = abs(hash(prompt))
|
| 34 |
+
r = 90 + (h % 120)
|
| 35 |
+
g = 70 + ((h >> 8) % 140)
|
| 36 |
+
b = 100 + ((h >> 16) % 120)
|
| 37 |
+
img = Image.new("RGB", size, (r, g, b))
|
| 38 |
+
draw = ImageDraw.Draw(img)
|
| 39 |
+
# soft shapes
|
| 40 |
+
for i in range(5):
|
| 41 |
+
shape_color = ((r + i*10) % 256, (g + i*15) % 256, (b + i*20) % 256)
|
| 42 |
+
xy = [(random.randint(0,size[0]), random.randint(0,size[1])) for _ in range(3)]
|
| 43 |
+
draw.polygon(xy, fill=shape_color)
|
| 44 |
+
img = img.filter(ImageFilter.GaussianBlur(radius=6))
|
| 45 |
+
try:
|
| 46 |
+
font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 28)
|
| 47 |
+
except:
|
| 48 |
+
font = ImageFont.load_default()
|
| 49 |
+
caption = prompt if len(prompt) <= 60 else prompt[:57] + "..."
|
| 50 |
+
w,h_text = draw.textsize(caption, font=font)
|
| 51 |
+
draw.text(((size[0]-w)/2, size[1]*0.85), caption, font=font, fill=(255,255,255))
|
| 52 |
+
img.save(out_path)
|
| 53 |
+
return out_path
|
| 54 |
+
|
| 55 |
+
def create_tts(text, lang="en"):
|
| 56 |
+
idx = next_index(OUTPUT_AUDIO, "voice", ".mp3")
|
| 57 |
+
out = os.path.join(OUTPUT_AUDIO, f"voice_{idx}.mp3")
|
| 58 |
+
tts = gTTS(text=text, lang=lang)
|
| 59 |
+
tts.save(out)
|
| 60 |
+
return out
|
| 61 |
+
|
| 62 |
+
def pick_random_background():
|
| 63 |
+
files = [f for f in os.listdir(BG_DIR) if f.lower().endswith((".jpg", ".jpeg", ".png"))]
|
| 64 |
+
if not files: return None
|
| 65 |
+
return os.path.join(BG_DIR, random.choice(files))
|
| 66 |
+
|
| 67 |
+
def pick_random_music():
|
| 68 |
+
files = [f for f in os.listdir(MUSIC_DIR) if f.lower().endswith(".mp3")]
|
| 69 |
+
if not files: return None
|
| 70 |
+
return os.path.join(MUSIC_DIR, random.choice(files))
|
| 71 |
+
|
| 72 |
+
def add_looping_music(narration_path, music_path):
|
| 73 |
+
narration = AudioFileClip(narration_path)
|
| 74 |
+
if not music_path or not os.path.exists(music_path):
|
| 75 |
+
return narration
|
| 76 |
+
music = AudioFileClip(music_path).volumex(0.25)
|
| 77 |
+
reps = int(narration.duration // music.duration) + 2
|
| 78 |
+
# create one long clip by concatenation
|
| 79 |
+
clips = [music] * reps
|
| 80 |
+
# MoviePy: CompositeAudioClip won't concatenate; we use CompositeAudioClip of differently-started tracks
|
| 81 |
+
from moviepy.audio.AudioClip import concatenate_audioclips
|
| 82 |
+
looped = concatenate_audioclips(clips).subclip(0, narration.duration)
|
| 83 |
+
looped = looped.audio_fadeout(2)
|
| 84 |
+
final = CompositeAudioClip([looped, narration.set_start(0)])
|
| 85 |
+
return final
|
| 86 |
+
|
| 87 |
+
def build_vertical_video(text, image_path, narration_path, music_path, size=(720,1280)):
|
| 88 |
+
narration = AudioFileClip(narration_path)
|
| 89 |
+
audio_final = add_looping_music(narration_path, music_path)
|
| 90 |
+
|
| 91 |
+
dur = narration.duration
|
| 92 |
+
bg = ImageClip(image_path).set_duration(dur).resize(size)
|
| 93 |
+
|
| 94 |
+
txt = TextClip(text, fontsize=36, color='white', method='caption', size=(int(size[0]*0.85), None)).set_duration(dur).set_position(('center','center'))
|
| 95 |
+
|
| 96 |
+
video = CompositeVideoClip([bg, txt])
|
| 97 |
+
video = video.set_audio(audio_final)
|
| 98 |
+
|
| 99 |
+
vid_idx = next_index(OUTPUT_VIDEOS, "affirmation", ".mp4")
|
| 100 |
+
out = os.path.join(OUTPUT_VIDEOS, f"affirmation_{vid_idx}.mp4")
|
| 101 |
+
video.write_videofile(out, fps=24, codec='libx264', audio_codec='aac')
|
| 102 |
+
return out
|
| 103 |
+
|
| 104 |
+
def generate_one(text, prompt=None, chosen_bg=None, chosen_music=None, lang='en'):
|
| 105 |
+
# pick or create image
|
| 106 |
+
if chosen_bg and os.path.exists(chosen_bg):
|
| 107 |
+
img_path = chosen_bg
|
| 108 |
+
else:
|
| 109 |
+
bg = pick_random_background()
|
| 110 |
+
if bg:
|
| 111 |
+
img_path = bg
|
| 112 |
+
else:
|
| 113 |
+
idx = next_index(OUTPUT_IMAGES, "bg", ".png")
|
| 114 |
+
img_path = os.path.join(OUTPUT_IMAGES, f"bg_{idx}.png")
|
| 115 |
+
generate_placeholder_image(prompt or text, img_path, size=(720,1280))
|
| 116 |
+
|
| 117 |
+
voice_path = create_tts(text, lang)
|
| 118 |
+
# pick music priority: chosen_music path > random > None
|
| 119 |
+
music_path = chosen_music if (chosen_music and os.path.exists(chosen_music)) else pick_random_music()
|
| 120 |
+
|
| 121 |
+
print(f"🎨 Background used: {img_path}")
|
| 122 |
+
print(f"🎵 Music used: {music_path}")
|
| 123 |
+
|
| 124 |
+
video_path = build_vertical_video(text, img_path, voice_path, music_path)
|
| 125 |
+
# return paths
|
| 126 |
+
return {
|
| 127 |
+
"video": video_path,
|
| 128 |
+
"audio": voice_path,
|
| 129 |
+
"image": img_path,
|
| 130 |
+
"music": music_path,
|
| 131 |
+
"timestamp": datetime.now().isoformat()
|
| 132 |
+
}
|
| 133 |
+
|
| 134 |
+
# quick test (uncomment to run quick test)
|
| 135 |
+
# if __name__ == '__main__':
|
| 136 |
+
# print(generate_one("You are capable of amazing things", prompt="sunrise over mountains"))
|