Update app.py
Browse files12234567891045678910111226 unmodified lines3940414342434445187 unmodified lines2332342352372362372382395 unmodified lines24524624724824925025125125225325425525425625725825825926026126237 unmodified lines30030130230230330430530630741 unmodified lines34935035135235035335435535617 unmodified lines37437537637737837938037437537638138238338438538638738138838939039139239339439539628 unmodified lines4254264274164284294304311 unmodified line4334344354364244374384394404414424434444454324464474484491 unmodified line45145245344044144244344444544644744844945045145445545645345745545845945745845946046146246346466 unmodified lines5315325335345325355365375384 unmodified lines54354454554354654754854912 unmodified lines562563564562565566567568310 unmodified lines879880881879882883884885"""AI Reels Maker β HuggingFace Space v3.1AI Reels Maker β HuggingFace Space v3.3=========================================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- 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# VOICE CONFIGS (plain ASCII keys)# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββEDGE_VOICES = { "Aria (US Female)" : "en-US-AriaNeural",187 unmodified lines return lines[:num_points]
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# AUDIO β Edge TTS (improved with retry and fallback)# AUDIO β Edge TTS (with voice selection debug)# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββasync def _edge_tts_save(text: str, voice: str, path: str) -> None: import edge_tts5 unmodified lines if len(text.strip()) < 5: raise ValueError(f"Text too short: '{text}'")
# Get voice ID from key; if not found, use default voice = EDGE_VOICES.get(voice_key) if voice is None: print(f"[TTS] Unknown voice key '{voice_key}', using default '{DEFAULT_VOICE_KEY}'") 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] 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 voice # Try selected voice first, then fallback to default voice if it fails for 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 lines if _kokoro_pipeline is None: from kokoro import KPipeline _kokoro_pipeline = KPipeline(lang_code="a") voice = KOKORO_VOICES.get(voice_key, "af_heart") 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 lines timeout=20, ) resp.raise_for_status() data = resp.json() for vid in resp.json().get("videos", []): for vid in data.get("videos", []): vid_id = vid.get("id") if vid_id in used_ids: continue17 unmodified lines return None
def 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) queries = _extract_queries(sentences, count=count) used_ids = set() paths = [] 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) print(f"[pexels] Fetched {len(paths)}/{count} videos", flush=True) if len(paths) >= count: break if 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 lines return out
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# TEXT FRAME RENDERER# TEXT FRAME RENDERER (NO background, NO shadow)# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef render_text_frame( text: str, width: int, height: int,1 unmodified line logo_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)) img = Image.new("RGBA", (width, height), (0, 0, 0, 0)) # fully transparent draw = 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.84 and cur: if bbox[2] - bbox[0] > width * 0.90 and cur: lines.append(" ".join(cur)) cur = [word] else:1 unmodified line if cur: lines.append(" ".join(cur))
line_h = 76 total_text_h = len(lines) * line_h pad_v, pad_h = 44, 24 box_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) line_h = 72 y = (height - (len(lines) * line_h)) // 2
y = box_y1 + pad_v for line in lines: bbox = draw.textbbox((0, 0), line, font=font) bbox = draw.textbbox((0, 0), line, font=font) text_w = bbox[2] - bbox[0] x = (width - text_w) // 2 for 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)) x = (width - text_w) // 2 # Draw text directly, no shadow, no background draw.text((x, y), line, font=font, fill=(255, 255, 255, 255)) y += line_h
66 unmodified lines loops = int(np.ceil(seg_dur / bg.duration)) + 1 bg = 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 lighter dark = mpe.ColorClip((W, H), color=[0, 0, 0]).set_opacity(0.42).set_duration(seg_dur) dark = 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 lines
bg_layer = mpe.CompositeVideoClip(bg_segs, size=(W, H)).set_duration(total_dur)
# Text overlays # 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 lines return out
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# NEWS ANCHOR MODE (simplified, kept from previous working version)# 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 lines logo_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") show_caption_bg = gr.Checkbox(label="Show caption background", value=False, info="Unchecked = no background/shadow (clean text)", visible=False) # hidden because we removed background 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)")app.py+46-43