Update app.py
Browse files7 unmodified lines891011121314151617181952 unmodified lines727374697071757677787980818283788485861 unmodified line8889908691929332 unmodified lines1261271281251291301311321331341321351361374 unmodified lines1421431441431451461471461481491503 unmodified lines1541551561561571581592 unmodified lines1621631641651651661671691681691704 unmodified lines17517617718017817918014 unmodified lines19519619720119819920054 unmodified lines2552562572622582592602612622682632642712652662677 unmodified linesimport requestsimport numpy as npfrom PIL import Image, ImageDraw, ImageFont
# ---------- PILLOW COMPATIBILITY FIX ----------# MoviePy uses Image.ANTIALIAS which was removed in Pillow 10+if not hasattr(Image, 'ANTIALIAS'): Image.ANTIALIAS = Image.LANCZOS
import gradio as gr
# ---------- Constants ----------52 unmodified lines await edge_tts.Communicate(text, voice).save(path)
def generate_audio(text, voice_key): # Sanitize text: remove problematic characters, ensure minimum length text = re.sub(r'[ββββ]', '"', text) # replace smart quotes text = re.sub(r'[^\x00-\x7F]+', ' ', text) # remove non-ASCII # Sanitize text text = re.sub(r'[ββββ]', '"', text) text = re.sub(r'[^\x00-\x7F]+', ' ', text) text = re.sub(r'\s+', ' ', text).strip() if len(text) < 10: raise ValueError(f"Text too short ({len(text)} chars): '{text}'") print(f"[TTS] Original text length: {len(text)} chars") print(f"[TTS] Text snippet: {text[:200]}...")
# Get voice ID voice_id = EDGE_VOICES.get(voice_key) if not voice_id: print(f"[TTS] Unknown voice key '{voice_key}', using default '{DEFAULT_VOICE}'")1 unmodified line print(f"[TTS] Using voice ID: {voice_id} (key: {voice_key})")
out = tempfile.mktemp(suffix=".mp3") # Try selected voice, then fallback to default voice if it fails for attempt, try_voice in enumerate([voice_id, EDGE_VOICES[DEFAULT_VOICE]]): if attempt > 0: print(f"[TTS] Retry with fallback voice: {try_voice}")32 unmodified lines url = file["link"] break else: # fallback to any portrait for file in vid.get("video_files", []): if file.get("width", 0) < file.get("height", 0): url = file["link"] break else: continue # download r = requests.get(url, stream=True) out = tempfile.mktemp(suffix=".mp4") with open(out, "wb") as f:4 unmodified lines print(f"Pexels error: {e}") return None
# ---------- Create final video (background loop + outro) ----------# ---------- Create final video ----------def create_reel(sentences, audio_path, bg_video_path, logo_path, outro_path): import moviepy.editor as mpe from moviepy.video.fx import loop
W, H = VIDEO_W, VIDEO_H audio = mpe.AudioFileClip(audio_path)3 unmodified lines # Background if bg_video_path and os.path.exists(bg_video_path): bg = mpe.VideoFileClip(bg_video_path) # Resize to cover 720x1280 if bg.w / bg.h > W / H: bg = bg.resize(height=H) else:2 unmodified lines if bg.duration < total_dur: bg = mpe.concatenate_videoclips([bg] * int(np.ceil(total_dur / bg.duration))) bg = bg.subclip(0, total_dur) # darken for text readability dark = mpe.ColorClip((W, H), color=(0,0,0)).set_opacity(0.3).set_duration(total_dur) bg_layer = mpe.CompositeVideoClip([bg, dark]) else: # gradient fallback frame = np.zeros((H, W, 3), dtype=np.uint8) for i in range(H): frame[i] = [int(30 + i/H*100), int(20 + i/H*50), int(40 + i/H*80)]4 unmodified lines img = Image.new("RGBA", (W, H), (0,0,0,0)) draw = ImageDraw.Draw(img) font = get_font(60) # wrap words = text.split() lines = [] cur = []14 unmodified lines x = (W - (bbox[2]-bbox[0]))//2 draw.text((x, y), line, font=font, fill=(255,255,255)) y += line_h # logo overlay if provided if logo_path and os.path.exists(logo_path): try: logo = Image.open(logo_path).convert("RGBA")54 unmodified lines return None, "β No script" full_script = " ".join(sentences)
# Generate audio (with retry and fallback) try: audio_path = generate_audio(full_script, voice_key) except Exception as e: return None, f"β Audio generation failed: {str(e)}"
# fetch background video from Pexels bg_video = None if pexels_key: # simple keyword from first sentence kw = re.sub(r'[^\w\s]', '', sentences[0]).split()[:3] kw = " ".join(kw) if kw else "news" print(f"[Pexels] Searching for: {kw}")app.py+10-17