Update app.py
Browse files123456781231245616171819207822232425262728299101112131431321516173418192021224041234324254546474849505152535455565758596061626326276566676869707172732829303132753334353637383982404142858643444546894748495051529293945354555657585997606162100101636465666768106107108691097071721137374757677118787980121818283848586128878889901321331341359113713813914092939495969714414514698991001011021033 unmodified lines1071081091561101111591121131141621631151161171651181191201681211221711231241731251261271761281291301312 unmodified lines13413513618513713813914018914114214314414514619519614714814915015120020115215315415515611 unmodified lines1681691702191711722211731741751761771781792282292301801811822321831841852351861871882381891901912 unmodified lines1941951962471971981992502512002012022032042552052062072082092602102112122632642652132142152162172182192722732202212222232245 unmodified lines230231232285286287288289290233234235292236237238295239240241298242300301243244304245246306247248249250310251252312313314315316317318319320321322323324325326327328329330331332333334335253254255256257258259260261262263264265266267268269337338339270271272273"""AI Reels Maker — Fixed Version- Single Pexels background video (looped)- Outro video appended at the end- No caption background/shadow- Voice selection works"""
import syssys.stdout.reconfigure(line_buffering=True)
import asyncioimport osimport reimport tempfileimport urllib.requestfrom pathlib import Path
import gradio as grimport numpy as npimport asyncioimport requestsfrom PIL import Image, ImageDraw, ImageFont, ImageFilter
print("✓ imports done", flush=True)
# ConstantsVIDEO_W = 720VIDEO_H = 1280FPS = 24import numpy as npfrom PIL import Image, ImageDraw, ImageFontimport gradio as gr
# ---------- Constants ----------VIDEO_W, VIDEO_H, FPS = 720, 1280, 24FONT_BOLD_URL = "https://github.com/google/fonts/raw/main/ofl/montserrat/Montserrat-Bold.ttf"FONT_BOLD_PATH = "/tmp/Montserrat-Bold.ttf"FONT_URL = "https://github.com/google/fonts/raw/main/ofl/montserrat/Montserrat-Bold.ttf"FONT_PATH = "/tmp/Montserrat-Bold.ttf"
# Voice configsEDGE_VOICES = { "Aria (US Female)": "en-US-AriaNeural", "Davis (US Male)": "en-US-DavisNeural", "Jenny (US Female)": "en-US-JennyNeural", "Guy (US Male)": "en-US-GuyNeural", "Sonia (UK Female)": "en-GB-SoniaNeural", "Ryan (UK Male)": "en-GB-RyanNeural",}DEFAULT_VOICE_KEY = "Aria (US Female)"DEFAULT_VOICE = "Aria (US Female)"
# Prompts (factual + CTA)REEL_TYPES = ["Fact", "Custom Prompt", "Top 5", "Blog to Reel"]REEL_PROMPTS = { "Fact": ( "Create a FACTUAL reel script based STRICTLY on the provided news article.\n" "Do NOT invent facts. Each line: 15-20 words.\n" "The LAST line MUST be a call-to-action with the source domain (e.g., 'Visit ChainStreet.io for the full story').\n" "Output exactly {n} lines, one per line." ), "Custom Prompt": ( "You are a senior financial journalist. Write a FACTUAL script based ONLY on the provided news content.\n" "No speculation. Last line: call-to-action with source domain.\n" "Each line: 15-20 words. Output {n} lines." ),}DEFAULT_PROMPT = REEL_PROMPTS["Fact"]
# Font loader_font = None# ---------- Font ----------def get_font(size=64): global _font if _font is None: try: if not os.path.exists(FONT_BOLD_PATH): urllib.request.urlretrieve(FONT_BOLD_URL, FONT_BOLD_PATH) _font = ImageFont.truetype(FONT_BOLD_PATH, size) except: _font = ImageFont.load_default() return _font if not os.path.exists(FONT_PATH): import urllib.request urllib.request.urlretrieve(FONT_URL, FONT_PATH) return ImageFont.truetype(FONT_PATH, size)
# Scrape URL# ---------- Scrape ----------def scrape_url(url): try: import trafilatura text = trafilatura.extract(trafilatura.fetch_url(url)) return text.strip() if text else "" except Exception as e: print(f"[scrape] {e}") print(f"Scrape error: {e}") return ""
# Generate script with Groqdef generate_script(content, groq_key, reel_type, num_points):# ---------- Script Generation (Groq) ----------def generate_script(content, groq_key, num_points=8): from groq import Groq client = Groq(api_key=groq_key.strip()) prompt = REEL_PROMPTS.get(reel_type, DEFAULT_PROMPT).format(n=num_points) prompt = f"""Create a FACTUAL reel script based STRICTLY on the provided news article.Do NOT invent facts. Each line: 15-20 words.The LAST line MUST be a call-to-action with the source domain (e.g., 'Visit ChainStreet.io for the full story').Output exactly {num_points} lines, one per line.""" resp = client.chat.completions.create( model="llama-3.3-70b-versatile", messages=[{"role": "system", "content": prompt}, {"role": "user", "content": f"Content:\n{content[:4000]}"}], temperature=0.75, messages=[ {"role": "system", "content": prompt}, {"role": "user", "content": f"Content:\n{content[:4000]}"} ], temperature=0.7, max_tokens=700, ) lines = [l.strip() for l in resp.choices[0].message.content.strip().split("\n") if l.strip()] lines = [l.strip() for l in resp.choices[0].message.content.split("\n") if l.strip()] return lines[:num_points]
# Edge TTS (with voice selection)async def _edge_save(text, voice, path):# ---------- Edge TTS ----------async def _tts(text, voice, path): import edge_tts await edge_tts.Communicate(text, voice).save(path)
def generate_audio(text, voice_key): if not text.strip(): raise ValueError("Empty text") voice_id = EDGE_VOICES.get(voice_key, EDGE_VOICES[DEFAULT_VOICE_KEY]) voice_id = EDGE_VOICES.get(voice_key, EDGE_VOICES[DEFAULT_VOICE]) print(f"[TTS] Using voice: {voice_id} (key: {voice_key})") out = tempfile.mktemp(suffix=".mp3") loop = asyncio.new_event_loop() try: loop.run_until_complete(_edge_save(text, voice_id, out)) loop.run_until_complete(_tts(text, voice_id, out)) finally: loop.close() return out
# Fetch ONE background video from Pexels (loop it later)# ---------- Pexels: fetch one portrait video ----------def fetch_pexels_video(query, api_key): if not api_key: print("[Pexels] No API key") return None try: resp = requests.get( "https://api.pexels.com/videos/search", headers={"Authorization": api_key}, params={"query": query, "per_page": 5, "orientation": "portrait"}, timeout=15, timeout=10 ) data = resp.json() videos = data.get("videos", []) if not videos: print(f"[Pexels] No videos for '{query}'") return None # pick first portrait video for vid in videos: files = vid.get("video_files", []) for f in files: if f.get("height") == VIDEO_H and f.get("width") == VIDEO_W: url = f["link"] for file in vid.get("video_files", []): if file.get("height") == VIDEO_H and file.get("width") == VIDEO_W: url = file["link"] break else: # fallback to any portrait for f in files: if f.get("width", 0) < f.get("height", 0): url = f["link"] for file in vid.get("video_files", []): if file.get("width", 0) < file.get("height", 0): url = file["link"] break else: continue3 unmodified lines 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 main reel (single background video looped, then append outro)def create_reel(sentences, audio_path, bg_video_path, logo_path, accent_hex, outro_path):# ---------- Create final video (background loop + outro) ----------def create_reel(sentences, audio_path, bg_video_path, logo_path, outro_path): import moviepy.editor as mpe from moviepy.video.fx import loop, resize from moviepy.video.fx import loop
W, H = VIDEO_W, VIDEO_H # Load audio audio = mpe.AudioFileClip(audio_path) total_dur = audio.duration dur_each = total_dur / len(sentences) seg_dur = total_dur / len(sentences)
# Background video (loop if shorter) # Background if bg_video_path and os.path.exists(bg_video_path): bg = mpe.VideoFileClip(bg_video_path) # Resize to fit 720x1280 (cover) # Resize to cover 720x1280 if bg.w / bg.h > W / H: bg = bg.resize(height=H) else:2 unmodified lines if bg.duration < total_dur: bg = mpe.concatenate_videoclips([bg] * int(np.ceil(total_dur / bg.duration))) bg = bg.subclip(0, total_dur) # Darken a bit # darken for text readability 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 # 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)] bg_layer = mpe.ImageClip(frame).set_duration(total_dur)
# Text clips (no background, no shadow) def make_text_clip(sentence, start, duration): # Text clips (no background) def make_text_clip(text, start, duration): img = Image.new("RGBA", (W, H), (0,0,0,0)) draw = ImageDraw.Draw(img) font = get_font(60) # word wrap words = sentence.split() # wrap words = text.split() lines = [] cur = [] for w in words:11 unmodified lines for line in lines: bbox = draw.textbbox((0,0), line, font=font) x = (W - (bbox[2]-bbox[0]))//2 draw.text((x, y), line, font=font, fill=(255,255,255,255)) draw.text((x, y), line, font=font, fill=(255,255,255)) y += line_h # Load logo if any # logo overlay if provided if logo_path and os.path.exists(logo_path): try: logo = Image.open(logo_path).convert("RGBA") logo = logo.resize((180, int(180*logo.height/logo.width)), Image.LANCZOS) img.paste(logo, (W-180-30, 30), logo) except Exception as e: print(f"[logo] {e}") clip = mpe.ImageClip(np.array(img)).set_start(start).set_duration(duration) return clip print(f"Logo error: {e}") return mpe.ImageClip(np.array(img)).set_start(start).set_duration(duration)
text_clips = [make_text_clip(s, i*dur_each, dur_each) for i, s in enumerate(sentences)] text_clips = [make_text_clip(s, i*seg_dur, seg_dur) for i, s in enumerate(sentences)] final = mpe.CompositeVideoClip([bg_layer] + text_clips).set_audio(audio)
# Append outro if provided # Append outro if outro_path and os.path.exists(outro_path): outro = mpe.VideoFileClip(outro_path) # resize to same dimensions if outro.w / outro.h > W / H: outro = outro.resize(height=H) else:2 unmodified lines final = mpe.concatenate_videoclips([final, outro])
out = tempfile.mktemp(suffix=".mp4") final.write_videofile(out, codec="libx264", audio_codec="aac", fps=FPS, preset="ultrafast", logger=None) final.write_videofile(out, codec="libx264", audio_codec="aac", fps=FPS, preset="medium", logger=None) return out
# Gradio pipelinedef generate_script_only(url_or_text, groq_key, reel_type, num_points, progress=gr.Progress()):# ---------- Gradio pipelines ----------def generate_script_only(url_or_text, groq_key, num_points, progress=gr.Progress()): if not groq_key: groq_key = os.getenv("GROQ_API_KEY", "") if not groq_key: return "", "❌ Groq API key missing" return "", "❌ Groq API key required" raw = url_or_text.strip() if raw.startswith("http"): content = scrape_url(raw) if not content: return "", "❌ Could not extract text from URL" return "", "❌ Could not extract content from URL" else: content = raw if len(content) < 20: return "", "❌ Please enter a valid URL or topic" sentences = generate_script(content, groq_key, reel_type, int(num_points)) sentences = generate_script(content, groq_key, num_points) if not sentences: return "", "❌ Script generation failed" script_text = "\n".join(sentences) md = "\n\n".join(f"**{i+1}.** {s}" for i,s in enumerate(sentences)) return script_text, f"## Script Ready\n\n{md}"
def create_video_from_script(script_text, groq_key, pexels_key, tts_engine, edge_voice, kokoro_voice, logo_file, logo_pos, accent_hex, show_caption_bg, outro_video, progress=gr.Progress()):def create_video_from_script(script_text, groq_key, pexels_key, voice_key, logo_file, outro_file, progress=gr.Progress()): if not groq_key: groq_key = os.getenv("GROQ_API_KEY", "") if not groq_key:5 unmodified lines if not sentences: return None, "❌ No script" full_script = " ".join(sentences) # Generate audio if tts_engine == "Edge TTS": audio_path = generate_audio(full_script, edge_voice) else: # Kokoro fallback to Edge audio_path = generate_audio(full_script, edge_voice) # generate audio audio_path = generate_audio(full_script, voice_key)
# Get background video from Pexels # fetch background video from Pexels bg_video = None if pexels_key: # Extract keyword from first sentence # simple keyword from first sentence kw = re.sub(r'[^\w\s]', '', sentences[0]).split()[:3] kw = " ".join(kw) if kw else "news" 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")
logo_path = logo_file if isinstance(logo_file, str) else (logo_file.name if logo_file else None) outro_path = outro_video if isinstance(outro_video, str) else (outro_video.name if outro_video else None) outro_path = outro_file if isinstance(outro_file, str) else (outro_file.name if outro_file else None)
video_path = create_reel(sentences, audio_path, bg_video, logo_path, accent_hex, outro_path) video_path = create_reel(sentences, audio_path, bg_video, logo_path, outro_path) md = "\n\n".join(f"**{i+1}.** {s}" for i,s in enumerate(sentences)) return video_path, f"## Reel Ready!\n\n{md}"
# Gradio UI# ---------- UI ----------with gr.Blocks(title="AI Reels Maker") as demo: gr.Markdown("# 🎬 AI Reels Maker\nFactual news reels with background video and optional outro") with gr.Tab("Reel Generator"): with gr.Row(): with gr.Column(): url_input = gr.Textbox(label="URL or Topic", lines=3) reel_type = gr.Dropdown(choices=REEL_TYPES, value="Fact") groq_key = gr.Textbox(label="Groq API Key", type="password", placeholder="or set GROQ_API_KEY secret") pexels_key = gr.Textbox(label="Pexels API Key", type="password", placeholder="or set PEXELS_API_KEY secret") with gr.Accordion("Voice"): tts_engine = gr.Radio(["Edge TTS", "Kokoro TTS"], value="Edge TTS") edge_voice = gr.Dropdown(choices=list(EDGE_VOICES.keys()), value=DEFAULT_VOICE_KEY, label="Edge Voice") kokoro_voice = gr.Dropdown(choices=["Heart (US Female)"], value="Heart (US Female)", visible=False) with gr.Accordion("Branding"): logo_file = gr.File(label="Logo (PNG)", type="filepath") logo_pos = gr.Dropdown(["top-right","top-left","bottom-right","bottom-left"], value="top-right") accent_hex = gr.ColorPicker(value="#d4af37", label="Accent Color") outro_video = gr.File(label="Outro Video (optional)", type="filepath") num_points = gr.Slider(6, 10, value=8, step=1, label="Number of sentences") gen_btn = gr.Button("Generate Script") create_btn = gr.Button("Create Video") with gr.Column(): script_editor = gr.TextArea(label="Edit Script", lines=10, interactive=True) video_out = gr.Video(label="Your Reel") status = gr.Markdown() gr.Markdown("# 🎬 AI Reels Maker\nFactual news reels with Pexels background + optional outro") with gr.Row(): with gr.Column(): url_input = gr.Textbox(label="URL or Topic", lines=3) groq_key = gr.Textbox(label="Groq API Key", type="password", placeholder="or set GROQ_API_KEY secret") pexels_key = gr.Textbox(label="Pexels API Key", type="password", placeholder="or set PEXELS_API_KEY secret") voice = gr.Dropdown(choices=list(EDGE_VOICES.keys()), value=DEFAULT_VOICE, label="Voice") logo = gr.File(label="Logo (optional)", type="filepath") outro = gr.File(label="Outro Video (optional)", type="filepath") num_points = gr.Slider(6, 10, value=8, step=1, label="Number of sentences") gen_btn = gr.Button("Generate Script") create_btn = gr.Button("Create Video") with gr.Column(): script_editor = gr.TextArea(label="Edit Script", lines=12, interactive=True) video = gr.Video(label="Your Reel") status = gr.Markdown()
tts_engine.change(lambda e: (gr.update(visible=e=="Edge TTS"), gr.update(visible=e=="Kokoro TTS")), inputs=tts_engine, outputs=[edge_voice, kokoro_voice]) gen_btn.click(generate_script_only, inputs=[url_input, groq_key, reel_type, num_points], outputs=[script_editor, status]) create_btn.click(create_video_from_script, inputs=[script_editor, groq_key, pexels_key, tts_engine, edge_voice, kokoro_voice, logo_file, logo_pos, accent_hex, gr.Checkbox(value=False, visible=False), outro_video], outputs=[video_out, status]) gen_btn.click(generate_script_only, inputs=[url_input, groq_key, num_points], outputs=[script_editor, status]) create_btn.click(create_video_from_script, inputs=[script_editor, groq_key, pexels_key, voice, logo, outro], outputs=[video, status])
demo.launch()app.py+92-160