Update app.py
Browse files8 unmodified lines9101112131213141549 unmodified lines6566676968697071727375747576778081787980848586878881828384858693878889909192931009495969710410510610710898991101001011021031041051062 unmodified lines1091101111121131141151161171188 unmodified lines12712812913013113213313413513613713813914214014114214319 unmodified lines1631641651661671681694 unmodified lines17417517617717817918014 unmodified lines19519619719819920020157 unmodified lines2592602612612622632642652 unmodified lines2682692702702712722732741 unmodified line2762772782782792802812828 unmodified linesimport numpy as npfrom PIL import Image, ImageDraw, ImageFont
# ---------- PILLOW COMPATIBILITY FIX ----------# MoviePy uses Image.ANTIALIAS which was removed in Pillow 10+# ---------- Pillow compatibility (fixes ANTIALIAS) ----------if not hasattr(Image, 'ANTIALIAS'): Image.ANTIALIAS = Image.LANCZOS
49 unmodified lines lines = [l.strip() for l in resp.choices[0].message.content.split("\n") if l.strip()] return lines[:num_points]
# ---------- Edge TTS (fixed) ----------# ---------- Edge TTS (robust) ----------async def _tts(text, voice, path): import edge_tts await edge_tts.Communicate(text, voice).save(path)
def generate_audio(text, voice_key): # 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") raise ValueError(f"Text too short: '{text}'") 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}'") voice_id = EDGE_VOICES[DEFAULT_VOICE] print(f"[TTS] Using voice ID: {voice_id} (key: {voice_key})") voice_id = EDGE_VOICES.get(voice_key, EDGE_VOICES[DEFAULT_VOICE]) print(f"[TTS] Using voice: {voice_id}")
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}") print(f"[TTS] Retry with fallback: {try_voice}") try: loop = asyncio.new_event_loop() try: loop.run_until_complete(_tts(text, try_voice, out)) finally: loop.close() print("[TTS] Audio generated successfully.") print("[TTS] Success.") return out except Exception as e: print(f"[TTS] Attempt {attempt+1} failed: {e}") if attempt == 0: continue else: raise RuntimeError(f"Edge TTS failed after retries. Last error: {e}") raise RuntimeError("Edge TTS failed to generate audio.") raise RuntimeError("Edge TTS failed after retries.")
# ---------- Pexels: fetch one portrait video ----------# ---------- Pexels: fetch one video (with 404 handling) ----------def fetch_pexels_video(query, api_key): if not api_key: print("[Pexels] No API key") return None try: resp = requests.get(2 unmodified lines params={"query": query, "per_page": 5, "orientation": "portrait"}, timeout=10 ) if resp.status_code == 404: print("[Pexels] 404 β Invalid API key or endpoint. Check your Pexels API key.") return None resp.raise_for_status() data = resp.json() videos = data.get("videos", []) for vid in videos:8 unmodified lines break else: continue # Download r = requests.get(url, stream=True) r.raise_for_status() out = tempfile.mktemp(suffix=".mp4") with open(out, "wb") as f: for chunk in r.iter_content(32768): f.write(chunk) print(f"[Pexels] Downloaded: {out}") return out except Exception as e: print(f"Pexels error: {e}") print(f"[Pexels] Error: {e}") return None
# ---------- Create final video ----------19 unmodified lines 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) # Word 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 logo_path and os.path.exists(logo_path): try: logo = Image.open(logo_path).convert("RGBA")57 unmodified lines try: audio_path = generate_audio(full_script, voice_key) except Exception as e: return None, f"β Audio generation failed: {str(e)}" return None, f"β Audio error: {str(e)}"
bg_video = None if pexels_key:2 unmodified lines print(f"[Pexels] Searching for: {kw}") bg_video = fetch_pexels_video(kw, pexels_key) if not bg_video: print("[Pexels] No video found, using gradient") print("[Pexels] No video found, using gradient background")
logo_path = logo_file if isinstance(logo_file, str) else (logo_file.name if logo_file else None) outro_path = outro_file if isinstance(outro_file, str) else (outro_file.name if outro_file else None)1 unmodified line try: video_path = create_reel(sentences, audio_path, bg_video, logo_path, outro_path) except Exception as e: return None, f"β Video creation failed: {str(e)}" return None, f"β Video error: {str(e)}"
md = "\n\n".join(f"**{i+1}.** {s}" for i,s in enumerate(sentences)) return video_path, f"## Reel Ready!\n\n{md}"app.py+24-23