Update app.py
Browse files1234567891011121326 unmodified lines40414243444546187 unmodified lines2342352362372382392405 unmodified lines24624724824925025125225325425525625725825926026137 unmodified lines29930030130230330430541 unmodified lines34734834935035135235317 unmodified lines37137237337437537637737837938038138238338428 unmodified lines4134144154164174184191 unmodified line4214224234244254264274284294304314324334344351 unmodified line43743843944044144244344444544644744844945045145245345445545645745845946046146266 unmodified lines5295305315325335345354 unmodified lines54054154254354454554612 unmodified lines559560561562563564565310 unmodified lines876877878879880881882"""AI Reels Maker β HuggingFace Space v3.1=========================================Professional viral reel generator with:β’ 45-60 second reels (8+ sentences, 15-20 words each)β’ 2-3 stitched background videos from Pexelsβ’ Optional outro video (plays after main reel)β’ Editable script: generate, edit, then renderβ’ Factual, CTAβenforced prompts (no invented data)β’ Robust Edge TTS with retry & fallback"""import sys26 unmodified linesFONT_LIGHT_PATH = "/tmp/Montserrat-Regular.ttf"# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# VOICE CONFIGS# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββEDGE_VOICES = {"Aria (US Female)" : "en-US-AriaNeural",187 unmodified linesreturn lines[:num_points]# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# AUDIO β Edge TTS (improved with retry and fallback)# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββasync def _edge_tts_save(text: str, voice: str, path: str) -> None:import edge_tts5 unmodified linesif len(text.strip()) < 5:raise ValueError(f"Text too short: '{text}'")voice = EDGE_VOICES.get(voice_key)if voice is None:print(f"[TTS] Unknown voice key '{voice_key}', using default '{DEFAULT_VOICE_KEY}'")voice = EDGE_VOICES[DEFAULT_VOICE_KEY]print(f"[TTS] Using voice ID: {voice} (key: {voice_key})")print(f"[TTS] Text snippet: {text[:200]}... (total chars: {len(text)})")out = tempfile.mktemp(suffix=".mp3")# Try selected voice first, then fallback to default voicefor attempt, try_voice in enumerate([voice, EDGE_VOICES[DEFAULT_VOICE_KEY]]):if attempt > 0:print(f"[TTS] Retry with fallback voice: {try_voice}")37 unmodified linesif _kokoro_pipeline is None:from kokoro import KPipeline_kokoro_pipeline = KPipeline(lang_code="a")voice = KOKORO_VOICES.get(voice_key, "af_heart")chunks = [a for _, _, a in _kokoro_pipeline(text, voice=voice, speed=1.05)]out = tempfile.mktemp(suffix=".wav")sf.write(out, np.concatenate(chunks), 24000)41 unmodified linestimeout=20,)resp.raise_for_status()for vid in resp.json().get("videos", []):vid_id = vid.get("id")if vid_id in used_ids:continue17 unmodified linesreturn Nonedef fetch_bg_videos(sentences: list[str], api_key: str, count: int = 3) -> list[str]:queries = _extract_queries(sentences, count=count)used_ids = set()paths = []for q in queries:p = _fetch_one_video(q, api_key, used_ids)if p:paths.append(p)print(f"[pexels] Fetched {len(paths)}/{count} videos", flush=True)return paths# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ28 unmodified linesreturn out# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# TEXT FRAME RENDERER# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef render_text_frame(text: str, width: int, height: int,1 unmodified linelogo_pos: str = "top-right",accent_color: tuple = (124, 58, 237),) -> np.ndarray:img = Image.new("RGBA", (width, height), (0, 0, 0, 0))draw = ImageDraw.Draw(img)font = get_font(60, bold=True)words, lines, cur = text.split(), [], []for word in words:test = " ".join(cur + [word])bbox = draw.textbbox((0, 0), test, font=font)if bbox[2] - bbox[0] > width * 0.84 and cur:lines.append(" ".join(cur))cur = [word]else:1 unmodified lineif cur:lines.append(" ".join(cur))line_h = 76total_text_h = len(lines) * line_hpad_v, pad_h = 44, 24box_y1 = max(pad_h, (height - total_text_h) // 2 - pad_v)box_y2 = min(height - pad_h, box_y1 + total_text_h + pad_v * 2)overlay = Image.new("RGBA", (width, height), (0, 0, 0, 0))od = ImageDraw.Draw(overlay)od.rounded_rectangle([20, box_y1, width - 20, box_y2], radius=22, fill=(6, 6, 20, 190))od.rectangle([20, box_y1, 29, box_y2], fill=(*accent_color, 245))img = Image.alpha_composite(img, overlay)draw = ImageDraw.Draw(img)y = box_y1 + pad_vfor line in lines:bbox = draw.textbbox((0, 0), line, font=font)text_w = bbox[2] - bbox[0]x = (width - text_w) // 2for dx, dy in [(-2, -2), (2, -2), (-2, 2), (2, 2), (0, 3), (3, 0), (-3, 0), (0, -3)]:draw.text((x + dx, y + dy), line, font=font, fill=(0, 0, 0, 170))draw.text((x, y), line, font=font, fill=(255, 255, 255, 255))y += line_h66 unmodified linesloops = int(np.ceil(seg_dur / bg.duration)) + 1bg = mpe.concatenate_videoclips([bg] * loops)bg = bg.subclip(0, seg_dur)dark = mpe.ColorClip((W, H), color=[0, 0, 0]).set_opacity(0.42).set_duration(seg_dur)seg = mpe.CompositeVideoClip([bg, dark]).set_start(start)bg_segs.append(seg)continue4 unmodified linesbg_layer = mpe.CompositeVideoClip(bg_segs, size=(W, H)).set_duration(total_dur)# Text overlaystext_clips = []for i, sentence in enumerate(sentences):arr = render_text_frame(sentence, W, H, logo, logo_pos, accent_color)12 unmodified linesreturn out# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# NEWS ANCHOR MODE (simplified, kept from previous working version)# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef _make_studio_bg(W: int, H: int, dark: bool, accent_color: tuple) -> np.ndarray:frame = np.zeros((H, W, 3), dtype=np.uint8)310 unmodified lineslogo_file = gr.File(label="π€ Upload Logo (PNG/JPG)", file_types=["image"], type="filepath")logo_pos = gr.Dropdown(choices=["top-right","top-left","bottom-right","bottom-left"], value="top-right", label="Logo Position")accent_hex = gr.ColorPicker(value="#d4af37", label="Accent Color")show_caption_bg = gr.Checkbox(label="Show caption background", value=True, info="Toggle semi-transparent card behind text")outro_video = gr.File(label="π¬ Optional Outro Video (plays after the reel)", file_types=["video"], type="filepath")num_points = gr.Slider(6, 10, value=8, step=1, label="π Number of points (8 = ~55s reel)")12345678910111226 unmodified lines39404142434445187 unmodified lines2332342352362372382395 unmodified lines24524624724824925025125225325425525625725825926026126237 unmodified lines30030130230330430530630741 unmodified lines34935035135235335435535617 unmodified lines37437537637737837938038138238338438538638738838939039139239339439539628 unmodified lines4254264274284294304311 unmodified line4334344354364374384394404414424434444454464474484491 unmodified line45145245345445545645745845946046146246346466 unmodified lines5315325335345355365375384 unmodified lines54354454554654754854912 unmodified lines562563564565566567568310 unmodified lines879880881882883884885"""AI Reels Maker β HuggingFace Space v3.3=========================================- Clean captions (no background, no shadow)- Reliable Pexels background videos- Voice selection works (Edge TTS & Kokoro)- Optional outro video- Factual, CTAβenforced prompts- Groq & Pexels API secrets support"""import sys26 unmodified linesFONT_LIGHT_PATH = "/tmp/Montserrat-Regular.ttf"# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# VOICE CONFIGS (plain ASCII keys)# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββEDGE_VOICES = {"Aria (US Female)" : "en-US-AriaNeural",187 unmodified linesreturn lines[:num_points]# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# AUDIO β Edge TTS (with voice selection debug)# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββasync def _edge_tts_save(text: str, voice: str, path: str) -> None:import edge_tts5 unmodified linesif len(text.strip()) < 5:raise ValueError(f"Text too short: '{text}'")# Get voice ID from key; if not found, use defaultvoice = EDGE_VOICES.get(voice_key)if voice is None:print(f"[TTS] WARNING: Voice key '{voice_key}' not found. Using default '{DEFAULT_VOICE_KEY}'")voice = EDGE_VOICES[DEFAULT_VOICE_KEY]else:print(f"[TTS] Using voice: {voice} (key: {voice_key})")print(f"[TTS] Text snippet: {text[:200]}... (total chars: {len(text)})")out = tempfile.mktemp(suffix=".mp3")# Try selected voice first, then fallback to default voice if it failsfor attempt, try_voice in enumerate([voice, EDGE_VOICES[DEFAULT_VOICE_KEY]]):if attempt > 0:print(f"[TTS] Retry with fallback voice: {try_voice}")37 unmodified linesif _kokoro_pipeline is None:from kokoro import KPipeline_kokoro_pipeline = KPipeline(lang_code="a")voice = KOKORO_VOICES.get(voice_key, "af_heart")print(f"[Kokoro] Using voice: {voice}")chunks = [a for _, _, a in _kokoro_pipeline(text, voice=voice, speed=1.05)]out = tempfile.mktemp(suffix=".wav")sf.write(out, np.concatenate(chunks), 24000)41 unmodified linestimeout=20,)resp.raise_for_status()data = resp.json()for vid in data.get("videos", []):vid_id = vid.get("id")if vid_id in used_ids:continue17 unmodified linesreturn Nonedef fetch_bg_videos(sentences: list[str], api_key: str, count: int = 3) -> list[str]:if not api_key:print("[pexels] No API key provided β skipping background videos.")return []queries = _extract_queries(sentences, count=count)print(f"[pexels] Searching for videos with queries: {queries}")used_ids = set()paths = []for q in queries:p = _fetch_one_video(q, api_key, used_ids)if p:paths.append(p)if len(paths) >= count:breakif not paths:print("[pexels] WARNING: No videos found. Using gradient fallback.")else:print(f"[pexels] Successfully fetched {len(paths)} videos: {paths}")return paths# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ28 unmodified linesreturn out# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# TEXT FRAME RENDERER (NO background, NO shadow)# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef render_text_frame(text: str, width: int, height: int,1 unmodified linelogo_pos: str = "top-right",accent_color: tuple = (124, 58, 237),) -> np.ndarray:"""Render text with NO background and NO shadow β just clean text on video."""img = Image.new("RGBA", (width, height), (0, 0, 0, 0)) # fully transparentdraw = ImageDraw.Draw(img)font = get_font(60, bold=True)# Word wrap to fit 90% of width (no background, so more space)words, lines, cur = text.split(), [], []for word in words:test = " ".join(cur + [word])bbox = draw.textbbox((0, 0), test, font=font)if bbox[2] - bbox[0] > width * 0.90 and cur:lines.append(" ".join(cur))cur = [word]else:1 unmodified lineif cur:lines.append(" ".join(cur))line_h = 72y = (height - (len(lines) * line_h)) // 2for line in lines:bbox = draw.textbbox((0, 0), line, font=font)text_w = bbox[2] - bbox[0]x = (width - text_w) // 2# Draw text directly, no shadow, no backgrounddraw.text((x, y), line, font=font, fill=(255, 255, 255, 255))y += line_h66 unmodified linesloops = int(np.ceil(seg_dur / bg.duration)) + 1bg = mpe.concatenate_videoclips([bg] * loops)bg = bg.subclip(0, seg_dur)# Darken only if you want, but now text has no background so we keep it lighterdark = mpe.ColorClip((W, H), color=[0, 0, 0]).set_opacity(0.35).set_duration(seg_dur)seg = mpe.CompositeVideoClip([bg, dark]).set_start(start)bg_segs.append(seg)continue4 unmodified linesbg_layer = mpe.CompositeVideoClip(bg_segs, size=(W, H)).set_duration(total_dur)# Text overlays (clean, no background)text_clips = []for i, sentence in enumerate(sentences):arr = render_text_frame(sentence, W, H, logo, logo_pos, accent_color)12 unmodified linesreturn out# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# NEWS ANCHOR MODE (simplified)# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef _make_studio_bg(W: int, H: int, dark: bool, accent_color: tuple) -> np.ndarray:frame = np.zeros((H, W, 3), dtype=np.uint8)310 unmodified lineslogo_file = gr.File(label="π€ Upload Logo (PNG/JPG)", file_types=["image"], type="filepath")logo_pos = gr.Dropdown(choices=["top-right","top-left","bottom-right","bottom-left"], value="top-right", label="Logo Position")accent_hex = gr.ColorPicker(value="#d4af37", label="Accent Color")show_caption_bg = gr.Checkbox(label="Show caption background", value=False, info="Unchecked = no background/shadow (clean text)", visible=False) # hidden because we removed backgroundoutro_video = gr.File(label="π¬ Optional Outro Video (plays after the reel)", file_types=["video"], type="filepath")num_points = gr.Slider(6, 10, value=8, step=1, label="π Number of points (8 = ~55s reel)")
app.py+46-43