Update app.py
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481493 unmodified lines1531541551561571581591601611621631641651661671681691701711721731741751761771781792 unmodified lines18218318418518618718818919019119219319419519619719819920020120220320411 unmodified lines2162172182192202212222232242252262272282292302312322332342352362372382392402412 unmodified lines2442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752765 unmodified lines282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341"""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 Pathimport gradio as grimport numpy as npimport requestsfrom PIL import Image, ImageDraw, ImageFont, ImageFilterprint("✓ imports done", flush=True)# ConstantsVIDEO_W = 720VIDEO_H = 1280FPS = 24FONT_BOLD_URL = "https://github.com/google/fonts/raw/main/ofl/montserrat/Montserrat-Bold.ttf"FONT_BOLD_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)"# 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 = Nonedef get_font(size=64):global _fontif _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# Scrape URLdef scrape_url(url):try:import trafilaturatext = trafilatura.extract(trafilatura.fetch_url(url))return text.strip() if text else ""except Exception as e:print(f"[scrape] {e}")return ""# Generate script with Groqdef generate_script(content, groq_key, reel_type, num_points):from groq import Groqclient = Groq(api_key=groq_key.strip())prompt = REEL_PROMPTS.get(reel_type, DEFAULT_PROMPT).format(n=num_points)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,max_tokens=700,)lines = [l.strip() for l in resp.choices[0].message.content.strip().split("\n") if l.strip()]return lines[:num_points]# Edge TTS (with voice selection)async def _edge_save(text, voice, path):import edge_ttsawait 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])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))finally:loop.close()return out# Fetch ONE background video from Pexels (loop it later)def fetch_pexels_video(query, api_key):if not api_key:print("[Pexels] No API key")return Nonetry:resp = requests.get("https://api.pexels.com/videos/search",headers={"Authorization": api_key},params={"query": query, "per_page": 5, "orientation": "portrait"},timeout=15,)data = resp.json()videos = data.get("videos", [])if not videos:print(f"[Pexels] No videos for '{query}'")return None# pick first portrait videofor 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"]breakelse:# fallback to any portraitfor f in files:if f.get("width", 0) < f.get("height", 0):url = f["link"]breakelse:continue3 unmodified lineswith 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 main reel (single background video looped, then append outro)def create_reel(sentences, audio_path, bg_video_path, logo_path, accent_hex, outro_path):import moviepy.editor as mpefrom moviepy.video.fx import loop, resizeW, H = VIDEO_W, VIDEO_H# Load audioaudio = mpe.AudioFileClip(audio_path)total_dur = audio.durationdur_each = total_dur / len(sentences)# Background video (loop if shorter)if bg_video_path and os.path.exists(bg_video_path):bg = mpe.VideoFileClip(bg_video_path)# Resize to fit 720x1280 (cover)if bg.w / bg.h > W / H:bg = bg.resize(height=H)else:2 unmodified linesif bg.duration < total_dur:bg = mpe.concatenate_videoclips([bg] * int(np.ceil(total_dur / bg.duration)))bg = bg.subclip(0, total_dur)# Darken a bitdark = 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)]bg_layer = mpe.ImageClip(frame).set_duration(total_dur)# Text clips (no background, no shadow)def make_text_clip(sentence, start, duration):img = Image.new("RGBA", (W, H), (0,0,0,0))draw = ImageDraw.Draw(img)font = get_font(60)# word wrapwords = sentence.split()lines = []cur = []for w in words:11 unmodified linesfor line in lines:bbox = draw.textbbox((0,0), line, font=font)x = (W - (bbox[2]-bbox[0]))//2draw.text((x, y), line, font=font, fill=(255,255,255,255))y += line_h# Load logo if anyif 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 cliptext_clips = [make_text_clip(s, i*dur_each, dur_each) for i, s in enumerate(sentences)]final = mpe.CompositeVideoClip([bg_layer] + text_clips).set_audio(audio)# Append outro if providedif outro_path and os.path.exists(outro_path):outro = mpe.VideoFileClip(outro_path)# resize to same dimensionsif outro.w / outro.h > W / H:outro = outro.resize(height=H)else:2 unmodified linesfinal = 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)return out# Gradio pipelinedef generate_script_only(url_or_text, groq_key, reel_type, 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"raw = url_or_text.strip()if raw.startswith("http"):content = scrape_url(raw)if not content:return "", "❌ Could not extract text from URL"else:content = rawif len(content) < 20:return "", "❌ Please enter a valid URL or topic"sentences = generate_script(content, groq_key, reel_type, int(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()):if not groq_key:groq_key = os.getenv("GROQ_API_KEY", "")if not groq_key:5 unmodified linesif not sentences:return None, "❌ No script"full_script = " ".join(sentences)# Generate audioif tts_engine == "Edge TTS":audio_path = generate_audio(full_script, edge_voice)else:# Kokoro fallback to Edgeaudio_path = generate_audio(full_script, edge_voice)# Get background video from Pexelsbg_video = Noneif pexels_key:# Extract keyword from first sentencekw = 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)video_path = create_reel(sentences, audio_path, bg_video, logo_path, accent_hex, 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 UIwith 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()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])demo.launch()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021033 unmodified lines1071081091101111121131141151161171181191201211221231241251261271281291301312 unmodified lines13413513613713813914014114214314414514614714814915015115215315415515611 unmodified lines1681691701711721731741751761771781791801811821831841851861871881891901912 unmodified lines1941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232245 unmodified lines230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273import syssys.stdout.reconfigure(line_buffering=True)import osimport reimport tempfileimport asyncioimport requestsimport numpy as npfrom PIL import Image, ImageDraw, ImageFontimport gradio as gr# ---------- Constants ----------VIDEO_W, VIDEO_H, FPS = 720, 1280, 24FONT_URL = "https://github.com/google/fonts/raw/main/ofl/montserrat/Montserrat-Bold.ttf"FONT_PATH = "/tmp/Montserrat-Bold.ttf"EDGE_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",}DEFAULT_VOICE = "Aria (US Female)"# ---------- Font ----------def get_font(size=64):if not os.path.exists(FONT_PATH):import urllib.requesturllib.request.urlretrieve(FONT_URL, FONT_PATH)return ImageFont.truetype(FONT_PATH, size)# ---------- Scrape ----------def scrape_url(url):try:import trafilaturatext = trafilatura.extract(trafilatura.fetch_url(url))return text.strip() if text else ""except Exception as e:print(f"Scrape error: {e}")return ""# ---------- Script Generation (Groq) ----------def generate_script(content, groq_key, num_points=8):from groq import Groqclient = Groq(api_key=groq_key.strip())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.7,max_tokens=700,)lines = [l.strip() for l in resp.choices[0].message.content.split("\n") if l.strip()]return lines[:num_points]# ---------- Edge TTS ----------async def _tts(text, voice, path):import edge_ttsawait edge_tts.Communicate(text, voice).save(path)def generate_audio(text, voice_key):voice_id = EDGE_VOICES.get(voice_key, EDGE_VOICES[DEFAULT_VOICE])out = tempfile.mktemp(suffix=".mp3")loop = asyncio.new_event_loop()try:loop.run_until_complete(_tts(text, voice_id, out))finally:loop.close()return out# ---------- Pexels: fetch one portrait video ----------def fetch_pexels_video(query, api_key):if not api_key:return Nonetry:resp = requests.get("https://api.pexels.com/videos/search",headers={"Authorization": api_key},params={"query": query, "per_page": 5, "orientation": "portrait"},timeout=10)data = resp.json()videos = data.get("videos", [])for vid in videos:for file in vid.get("video_files", []):if file.get("height") == VIDEO_H and file.get("width") == VIDEO_W:url = file["link"]breakelse:# fallback to any portraitfor file in vid.get("video_files", []):if file.get("width", 0) < file.get("height", 0):url = file["link"]breakelse:continue3 unmodified lineswith 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 (background loop + outro) ----------def create_reel(sentences, audio_path, bg_video_path, logo_path, outro_path):import moviepy.editor as mpefrom moviepy.video.fx import loopW, H = VIDEO_W, VIDEO_Haudio = mpe.AudioFileClip(audio_path)total_dur = audio.durationseg_dur = total_dur / len(sentences)# Backgroundif bg_video_path and os.path.exists(bg_video_path):bg = mpe.VideoFileClip(bg_video_path)# Resize to cover 720x1280if bg.w / bg.h > W / H:bg = bg.resize(height=H)else:2 unmodified linesif bg.duration < total_dur:bg = mpe.concatenate_videoclips([bg] * int(np.ceil(total_dur / bg.duration)))bg = bg.subclip(0, total_dur)# darken for text readabilitydark = 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)]bg_layer = mpe.ImageClip(frame).set_duration(total_dur)# 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)# wrapwords = text.split()lines = []cur = []for w in words:11 unmodified linesfor line in lines:bbox = draw.textbbox((0,0), line, font=font)x = (W - (bbox[2]-bbox[0]))//2draw.text((x, y), line, font=font, fill=(255,255,255))y += line_h# logo overlay if providedif 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 error: {e}")return mpe.ImageClip(np.array(img)).set_start(start).set_duration(duration)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 outroif outro_path and os.path.exists(outro_path):outro = mpe.VideoFileClip(outro_path)if outro.w / outro.h > W / H:outro = outro.resize(height=H)else:2 unmodified linesfinal = mpe.concatenate_videoclips([final, outro])out = tempfile.mktemp(suffix=".mp4")final.write_videofile(out, codec="libx264", audio_codec="aac", fps=FPS, preset="medium", logger=None)return out# ---------- 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 required"raw = url_or_text.strip()if raw.startswith("http"):content = scrape_url(raw)if not content:return "", "❌ Could not extract content from URL"else:content = rawsentences = 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, 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 linesif not sentences:return None, "❌ No script"full_script = " ".join(sentences)# generate audioaudio_path = generate_audio(full_script, voice_key)# fetch background video from Pexelsbg_video = Noneif pexels_key:# simple keyword from first sentencekw = re.sub(r'[^\w\s]', '', sentences[0]).split()[:3]kw = " ".join(kw) if kw else "news"bg_video = fetch_pexels_video(kw, pexels_key)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)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}"# ---------- UI ----------with gr.Blocks(title="AI Reels Maker") as demo: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()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