Update app.py
Browse files8 unmodified lines91011121314151649 unmodified lines666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141152 unmodified lines1181191201211221238 unmodified lines13213313413513613713813914014114214314414519 unmodified lines1651661671681691704 unmodified lines17517617717817918014 unmodified lines19519619719819920057 unmodified lines2582592602612622632642 unmodified lines2672682692702712722731 unmodified line2752762772782792802818 unmodified linesimport 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.LANCZOS49 unmodified lineslines = [l.strip() for l in resp.choices[0].message.content.split("\n") if l.strip()]return lines[:num_points]# ---------- Edge TTS (fixed) ----------async def _tts(text, voice, path):import edge_ttsawait 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}'")voice_id = EDGE_VOICES[DEFAULT_VOICE]print(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}")try:loop = asyncio.new_event_loop()try:loop.run_until_complete(_tts(text, try_voice, out))finally:loop.close()print("[TTS] Audio generated successfully.")return outexcept Exception as e:print(f"[TTS] Attempt {attempt+1} failed: {e}")if attempt == 0:continueelse:raise RuntimeError(f"Edge TTS failed after retries. Last error: {e}")raise RuntimeError("Edge TTS failed to generate audio.")# ---------- Pexels: fetch one portrait video ----------def fetch_pexels_video(query, api_key):if not api_key:return Nonetry:resp = requests.get(2 unmodified linesparams={"query": query, "per_page": 5, "orientation": "portrait"},timeout=10)data = resp.json()videos = data.get("videos", [])for vid in videos:8 unmodified linesbreakelse:continuer = requests.get(url, stream=True)out = tempfile.mktemp(suffix=".mp4")with open(out, "wb") as f:for chunk in r.iter_content(32768):f.write(chunk)return outexcept Exception as e:print(f"Pexels error: {e}")return None# ---------- Create final video ----------19 unmodified linesdark = 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")57 unmodified linestry: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:2 unmodified linesprint(f"[Pexels] Searching for: {kw}")bg_video = fetch_pexels_video(kw, pexels_key)if not bg_video:print("[Pexels] No video found, using gradient")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 linetry: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)}"md = "\n\n".join(f"**{i+1}.** {s}" for i,s in enumerate(sentences))return video_path, f"## Reel Ready!\n\n{md}"8 unmodified lines910111213141549 unmodified lines65666768697071727374757677787980818283848586878889909192939495969798991001011021031041051062 unmodified lines1091101111121131141151161171188 unmodified lines12712812913013113213313413513613713813914014114214319 unmodified lines1631641651661671681694 unmodified lines17417517617717817918014 unmodified lines19519619719819920020157 unmodified lines2592602612622632642652 unmodified lines2682692702712722732741 unmodified line2762772782792802812828 unmodified linesimport numpy as npfrom PIL import Image, ImageDraw, ImageFont# ---------- Pillow compatibility (fixes ANTIALIAS) ----------if not hasattr(Image, 'ANTIALIAS'):Image.ANTIALIAS = Image.LANCZOS49 unmodified lineslines = [l.strip() for l in resp.choices[0].message.content.split("\n") if l.strip()]return lines[:num_points]# ---------- Edge TTS (robust) ----------async def _tts(text, voice, path):import edge_ttsawait edge_tts.Communicate(text, voice).save(path)def generate_audio(text, voice_key):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: '{text}'")print(f"[TTS] Text snippet: {text[:200]}...")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: {try_voice}")try:loop = asyncio.new_event_loop()try:loop.run_until_complete(_tts(text, try_voice, out))finally:loop.close()print("[TTS] Success.")return outexcept Exception as e:print(f"[TTS] Attempt {attempt+1} failed: {e}")raise RuntimeError("Edge TTS failed after retries.")# ---------- Pexels: fetch one video (with 404 handling) ----------def fetch_pexels_video(query, api_key):if not api_key:print("[Pexels] No API key")return Nonetry:resp = requests.get(2 unmodified linesparams={"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 Noneresp.raise_for_status()data = resp.json()videos = data.get("videos", [])for vid in videos:8 unmodified linesbreakelse:continue# Downloadr = 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 outexcept Exception as e:print(f"[Pexels] Error: {e}")return None# ---------- Create final video ----------19 unmodified linesdark = 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)# Word 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 overlayif logo_path and os.path.exists(logo_path):try:logo = Image.open(logo_path).convert("RGBA")57 unmodified linestry:audio_path = generate_audio(full_script, voice_key)except Exception as e:return None, f"β Audio error: {str(e)}"bg_video = Noneif pexels_key:2 unmodified linesprint(f"[Pexels] Searching for: {kw}")bg_video = fetch_pexels_video(kw, pexels_key)if not bg_video: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 linetry:video_path = create_reel(sentences, audio_path, bg_video, logo_path, outro_path)except Exception as 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