Update app.py
Browse files7 unmodified lines891011121352 unmodified lines666768697071727374757677787980811 unmodified line8384858687888932 unmodified lines1221231241251261271281291301311321331341354 unmodified lines1401411421431441451461471481493 unmodified lines1531541551561571581592 unmodified lines1621631641651661671681691701711724 unmodified lines17717817918018118218314 unmodified lines19819920020120220320454 unmodified lines2592602612622632642652662672682692702712722732747 unmodified linesimport requestsimport numpy as npfrom PIL import Image, ImageDraw, ImageFontimport gradio as gr# ---------- Constants ----------52 unmodified linesawait edge_tts.Communicate(text, voice).save(path)def generate_audio(text, voice_key):# Sanitize text: remove problematic characters, ensure minimum lengthtext = re.sub(r'[“”‘’]', '"', text) # replace smart quotestext = re.sub(r'[^\x00-\x7F]+', ' ', text) # remove non-ASCIItext = 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 IDvoice_id = EDGE_VOICES.get(voice_key)if not voice_id:print(f"[TTS] Unknown voice key '{voice_key}', using default '{DEFAULT_VOICE}'")1 unmodified lineprint(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 failsfor 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 linesurl = file["link"]breakelse:# fallback to any portraitfor file in vid.get("video_files", []):if file.get("width", 0) < file.get("height", 0):url = file["link"]breakelse:continue# downloadr = requests.get(url, stream=True)out = tempfile.mktemp(suffix=".mp4")with open(out, "wb") as f:4 unmodified linesprint(f"Pexels error: {e}")return None# ---------- Create final video (background loop + outro) ----------def create_reel(sentences, audio_path, bg_video_path, logo_path, outro_path):import moviepy.editor as mpefrom moviepy.video.fx import loopW, H = VIDEO_W, VIDEO_Haudio = mpe.AudioFileClip(audio_path)3 unmodified lines# Backgroundif bg_video_path and os.path.exists(bg_video_path):bg = mpe.VideoFileClip(bg_video_path)# Resize to cover 720x1280if bg.w / bg.h > W / H:bg = bg.resize(height=H)else:2 unmodified linesif 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 readabilitydark = mpe.ColorClip((W, H), color=(0,0,0)).set_opacity(0.3).set_duration(total_dur)bg_layer = mpe.CompositeVideoClip([bg, dark])else:# gradient fallbackframe = 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 linesimg = Image.new("RGBA", (W, H), (0,0,0,0))draw = ImageDraw.Draw(img)font = get_font(60)# wrapwords = text.split()lines = []cur = []14 unmodified linesx = (W - (bbox[2]-bbox[0]))//2draw.text((x, y), line, font=font, fill=(255,255,255))y += line_h# logo overlay if providedif logo_path and os.path.exists(logo_path):try:logo = Image.open(logo_path).convert("RGBA")54 unmodified linesreturn 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 Pexelsbg_video = Noneif pexels_key:# simple keyword from first sentencekw = re.sub(r'[^\w\s]', '', sentences[0]).split()[:3]kw = " ".join(kw) if kw else "news"print(f"[Pexels] Searching for: {kw}")7 unmodified lines891011121314151617181952 unmodified lines7273747576777879808182838485861 unmodified line88899091929332 unmodified lines1261271281291301311321331341351361374 unmodified lines1421431441451461471481491503 unmodified lines1541551561571581592 unmodified lines1621631641651661671681691704 unmodified lines17517617717817918014 unmodified lines19519619719819920054 unmodified lines2552562572582592602612622632642652662677 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.LANCZOSimport gradio as gr# ---------- Constants ----------52 unmodified linesawait edge_tts.Communicate(text, voice).save(path)def generate_audio(text, voice_key):# Sanitize texttext = 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]}...")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 lineprint(f"[TTS] Using voice ID: {voice_id} (key: {voice_key})")out = tempfile.mktemp(suffix=".mp3")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 linesurl = file["link"]breakelse:for file in vid.get("video_files", []):if file.get("width", 0) < file.get("height", 0):url = file["link"]breakelse:continuer = requests.get(url, stream=True)out = tempfile.mktemp(suffix=".mp4")with open(out, "wb") as f:4 unmodified linesprint(f"Pexels error: {e}")return None# ---------- Create final video ----------def create_reel(sentences, audio_path, bg_video_path, logo_path, outro_path):import moviepy.editor as mpeW, H = VIDEO_W, VIDEO_Haudio = mpe.AudioFileClip(audio_path)3 unmodified lines# Backgroundif bg_video_path and os.path.exists(bg_video_path):bg = mpe.VideoFileClip(bg_video_path)if bg.w / bg.h > W / H:bg = bg.resize(height=H)else:2 unmodified linesif bg.duration < total_dur:bg = mpe.concatenate_videoclips([bg] * int(np.ceil(total_dur / bg.duration)))bg = bg.subclip(0, total_dur)dark = mpe.ColorClip((W, H), color=(0,0,0)).set_opacity(0.3).set_duration(total_dur)bg_layer = mpe.CompositeVideoClip([bg, dark])else: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 linesimg = Image.new("RGBA", (W, H), (0,0,0,0))draw = ImageDraw.Draw(img)font = get_font(60)words = text.split()lines = []cur = []14 unmodified linesx = (W - (bbox[2]-bbox[0]))//2draw.text((x, y), line, font=font, fill=(255,255,255))y += line_hif logo_path and os.path.exists(logo_path):try:logo = Image.open(logo_path).convert("RGBA")54 unmodified linesreturn None, "❌ No script"full_script = " ".join(sentences)try:audio_path = generate_audio(full_script, voice_key)except Exception as e:return None, f"❌ Audio generation failed: {str(e)}"bg_video = Noneif pexels_key: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