"""Sci-Fi Shorts Studio - Gradio demo of the n8n YouTube Shorts pipeline. Topic -> original twist story (LLM) -> storyboard + consistent character -> FLUX images -> optional Sarvam narration -> Ken Burns 9:16 video with burned-in captions. Billing: signed-in visitors run inference on their own Hugging Face account (OAuth); otherwise the Space owner's HF_TOKEN secret is used if set. """ import os import gradio as gr import documentary import pipeline import research # ZeroGPU: load FLUX at startup (must happen at import time, see gpu_images.py) ZERO = pipeline.use_zerogpu() gpu_fn = None if ZERO: import gpu_images gpu_fn = gpu_images.generate_images SPEAKERS = ["shubh", "aditya", "rahul", "kabir", "ritu", "priya", "neha", "simran"] LANGUAGES = [("Hindi + English words (Sarvam style, most natural voice)", "Hindi"), ("Hinglish (Roman script)", "Hinglish"), ("English", "English")] MODES = [("History documentary (researched, fact-checked)", "documentary"), ("Sci-fi story (fiction)", "story")] DOC_EXAMPLES = ["Sinking of the Titanic", "Chernobyl disaster", "Apollo 11 Moon landing", "Partition of India", "Fall of Constantinople 1453", "Construction of the Taj Mahal"] EXAMPLES = [ ["time travel", "a message from my future self", "Hindi"], ["AI story", "an AI assistant that remembers a life you never lived", "Hindi"], ["parallel universe", "a lift that opens onto a different version of your floor", "English"], ["robots", "the last robot caregiver on a flooded Earth", "English"], ] def generate(mode, genre, topic, language, seconds, max_scenes, voice, speaker, pace, tone, audience, oauth_token: gr.OAuthToken | None, progress=gr.Progress()): token = oauth_token.token if oauth_token else os.getenv("HF_TOKEN") if not token: raise gr.Error("Sign in with Hugging Face first (inference runs on your account's free credits).") try: video, thumb, images, story, board, log, _, _, warning = pipeline.run( token, genre, topic.strip(), language, int(seconds), int(max_scenes), voice, speaker, progress=lambda f, d="": progress(f, desc=d), gpu_fn=gpu_fn, pace=float(pace), mode=mode, tone=tone, audience=audience) except Exception as exc: # surface a readable message instead of a stack trace print("GENERATION FAILED:", repr(exc), flush=True) # shows up in the Space logs raise gr.Error(f"Generation failed: {str(exc)[:500]}", duration=None) from exc if warning: gr.Warning(warning, duration=None) if story.get("mode") == "documentary": story_md = documentary_md(story) else: story_md = (f"### {story['title']}\n\n**Hook:** {story.get('hook', '')}\n\n{story['story']}\n\n" f"**Twist:** {story.get('twist', '')}\n\n" f"**Title options:** {' · '.join(story.get('title_options', [])[:5])}\n\n" f"{' '.join(story.get('hashtags', []))}") gallery = [(p, f"Scene {i}") for i, p in enumerate(images, start=1)] return video, story_md, gallery, board, thumb, log def documentary_md(story): bp, rs = story.get("blueprint") or {}, story.get("research_status") or {} lines = [f"### {story['title']}", f"**Core question:** {bp.get('core_question', '')} \n**Premise:** {bp.get('premise', '')} \n" f"**Period:** {bp.get('period', '')} · **Locations:** {', '.join(bp.get('locations') or [])}", "", "**Script**"] for c in story.get("chunks", []): lines.append(f"{c['chunk']:02d} · *{c['story_function']}* — {c['narration']}") def block(name, items): if items: lines.extend(["", f"**{name}**"] + [f"- {i}" for i in items]) block("Verified facts", rs.get("verified_facts")) block("Facts requiring verification", rs.get("requiring_verification")) block("Historical reconstructions", rs.get("reconstructions")) block("Important uncertainties", rs.get("uncertainties")) block("Fact-check corrections", [f"chunk {i.get('chunk')}: {i.get('problem', '')}" for i in story.get("fact_check_issues") or []]) lines.extend(["", "**Sources:** " + " · ".join(f"[{s['title']}]({s['url']})" for s in story.get("sources", [])), "", f"**Title options:** {' · '.join(story.get('title_options', [])[:5])}", "", story.get("description", ""), "", " ".join(story.get("hashtags", []))]) return "\n".join(lines) def suggest(): try: picks = research.suggest_topics(6) except research.ResearchError: picks = [] picks = picks or DOC_EXAMPLES return gr.update(value=picks[0]), gr.update(choices=picks, value=None, visible=True) def on_mode(mode): doc = mode == "documentary" return (gr.update(visible=not doc), gr.update(visible=doc), gr.update(visible=doc), gr.update(value=pipeline.DOC_PACE if doc else pipeline.SARVAM_PACE), gr.update(label="Documentary subject" if doc else "Topic / 'what if' (optional)", placeholder="Sinking of the Titanic" if doc else "a message from my future self")) with gr.Blocks(title="Sci-Fi Shorts Studio") as demo: gr.Markdown( "# 🎬 Shorts Studio\n" "**History documentary:** researches the subject on Wikipedia first, writes a chronological, fact-based " "script only from those sources, fact-checks it, then films it with 4K cinematic photoreal images. " "**Sci-fi story:** an original twist-ending micro story. Both render a narrated, captioned vertical Short.\n\n" + ("Images are generated on **ZeroGPU** and use your daily GPU time (sign in: 5 min/day free). " "The story text uses a tiny amount of your Inference credits." if ZERO else "Sign in so the images and text run on your own Hugging Face credits.") + " A 6-scene video takes about 2–4 minutes.") gr.LoginButton() with gr.Row(): with gr.Column(scale=1): mode = gr.Radio(MODES, value="documentary", label="Mode") genre = gr.Dropdown(["random"] + pipeline.GENRES, value="random", label="Genre", visible=False) topic = gr.Textbox(label="Documentary subject", placeholder="Sinking of the Titanic") with gr.Row(visible=True) as doc_row: suggest_btn = gr.Button("Suggest a topic (On this day)", size="sm") tone = gr.Dropdown(documentary.TONES, value="Cinematic & Dramatic", label="Tone") audience = gr.Dropdown(documentary.AUDIENCES, value="YouTube General Audience", label="Audience") suggestions = gr.Radio([], label="Real events on this date (Wikipedia)", visible=False) language = gr.Radio(LANGUAGES, value="Hindi", label="Language") with gr.Row(): seconds = gr.Slider(20, 60, value=35, step=5, label="Target length (s)") max_scenes = gr.Slider(4, 10, value=8, step=1, label="Max scenes") has_key = bool(os.getenv("SARVAM_API_KEY", "").strip()) voice = gr.Checkbox(label="Sarvam narration" + ("" if has_key else " - SARVAM_API_KEY secret is NOT set, video will be silent"), value=has_key) with gr.Row(): speaker = gr.Dropdown(SPEAKERS, value="shubh", label="Voice (bulbul:v3)") pace = gr.Slider(0.8, 1.3, value=pipeline.DOC_PACE, step=0.01, label="Voice speed") go = gr.Button("Generate Short", variant="primary") with gr.Column(visible=True) as doc_examples: gr.Examples([[t] for t in DOC_EXAMPLES], [topic], label="Documentary subjects") with gr.Column(visible=False) as story_examples: gr.Examples(EXAMPLES, [genre, topic, language], label="Story ideas") with gr.Column(scale=1): video = gr.Video(label="Short (9:16)", height=640) story_md = gr.Markdown() with gr.Accordion("Storyboard, images and details", open=False): gallery = gr.Gallery(label="Scene images", columns=4, height=420) with gr.Row(): thumb = gr.Image(label="Thumbnail", height=360) board = gr.JSON(label="Storyboard JSON") log = gr.Textbox(label="Run log", lines=6) mode.change(on_mode, mode, [genre, doc_row, doc_examples, pace, topic]).then( lambda m: gr.update(visible=m == "story"), mode, story_examples) suggest_btn.click(suggest, None, [topic, suggestions]) suggestions.change(lambda v: gr.update(value=v) if v else gr.update(), suggestions, topic) go.click(generate, [mode, genre, topic, language, seconds, max_scenes, voice, speaker, pace, tone, audience], [video, story_md, gallery, board, thumb, log], concurrency_limit=1) demo.queue(max_size=8) if __name__ == "__main__": demo.launch()