"""Ask Anything Lab — TEDx presentation Gradio app. Two modes from one URL: - Presenter: clicker-controlled stage demo with hardcoded data, zero API calls. - Audience: prompt input, three parallel Claude calls, study data to Supabase. Run locally: `python app.py` """ import html as _html import os import uuid # Load .env before any service module reads os.environ try: from dotenv import load_dotenv load_dotenv() except ImportError: pass import gradio as gr from data.demo import PROMPT, REFLECT_QUOTE, RESPONSE from components.landing import LANDING_HTML from components.embed_viz import render_embed_step, render_audience_embed from components.source_list import render_sources from components.typewriter import typewriter_html from components.study import SURPRISING_OPTIONS, study_intro_html, thanks_html from services.claude_api import process_prompt_parallel from services.supabase_client import save_study # ============================================================ # Presenter-mode stage rendering # ============================================================ # Top-level stages: 0=Input, 1=Embed (6 sub-steps), 2=Retrieve, 3=Synthesize, 4=Reflect EMBED_SUBSTEPS = 6 def render_presenter_stage(stage: int, embed_step: int) -> str: if stage == 0: return _render_input_stage() if stage == 1: return render_embed_step(embed_step) if stage == 2: return render_sources(label="Step 3 \u00b7 Retrieve") if stage == 3: return typewriter_html(RESPONSE) if stage == 4: return _render_reflect_stage() return _render_input_stage() def _render_input_stage() -> str: escaped = _html.escape(PROMPT) return f"""
Step 1 · Input
Imagine you just typed this into ChatGPT.
“{escaped}”
Press → to watch what happens next.
""" def _render_reflect_stage() -> str: return f"""
Step 5 · Reflect
“{_html.escape(REFLECT_QUOTE)}”
— Ask Anything
""" # ============================================================ # Presenter state machine # ============================================================ def advance(stage: int, embed_step: int): if stage == 0: return 1, 0 if stage == 1: if embed_step < EMBED_SUBSTEPS - 1: return 1, embed_step + 1 return 2, 0 if stage == 2: return 3, 0 if stage == 3: return 4, 0 return 4, 0 def retreat(stage: int, embed_step: int): if stage == 0: return 0, 0 if stage == 1: if embed_step > 0: return 1, embed_step - 1 return 0, 0 if stage == 2: # Going back from Retrieve returns to the LAST embed sub-step, not the first. return 1, EMBED_SUBSTEPS - 1 if stage == 3: return 2, 0 if stage == 4: return 3, 0 return 0, 0 def on_forward(stage: int, embed_step: int): new_stage, new_step = advance(stage, embed_step) return new_stage, new_step, render_presenter_stage(new_stage, new_step) def on_back(stage: int, embed_step: int): new_stage, new_step = retreat(stage, embed_step) return new_stage, new_step, render_presenter_stage(new_stage, new_step) # ============================================================ # Mode switching # ============================================================ def enter_presenter(): return ( gr.update(visible=False), # landing_view gr.update(visible=True), # presenter_view gr.update(visible=False), # audience_input_group gr.update(visible=False), # audience_viz_group gr.update(visible=False), # study_group gr.update(visible=False), # thanks_group 0, 0, # stage, embed_step render_presenter_stage(0, 0), ) def enter_audience(): return ( gr.update(visible=False), # landing_view gr.update(visible=False), # presenter_view gr.update(visible=True), # audience_input_group gr.update(visible=False), # audience_viz_group gr.update(visible=False), # study_group gr.update(visible=False), # thanks_group "", # prompt_box reset 0, # audience_stage reset ) def go_home(): return ( gr.update(visible=True), # landing_view gr.update(visible=False), # presenter_view gr.update(visible=False), # audience_input_group gr.update(visible=False), # audience_viz_group gr.update(visible=False), # study_group gr.update(visible=False), # thanks_group 0, 0, # stage, embed_step ) # ============================================================ # Audience-mode handlers # ============================================================ def _loading_html(msg: str) -> str: return f"""
{_html.escape(msg)}
Claude is processing your prompt in parallel across three calls…
""" def handle_audience_submit(prompt): """Generator: shows loading state, fires 3 parallel API calls, then renders embed viz.""" if not prompt or not prompt.strip(): yield ( gr.update(), # audience_input_group (no change) gr.update(), # audience_viz_group (no change) "", # audience_display 0, # audience_stage "", # prompt_state {}, {}, "", # embeddings/sources/response "", # session_id gr.update(value="**Please enter a prompt first.**", visible=True), ) return prompt = prompt.strip() session_id = str(uuid.uuid4()) # 1) Loading state yield ( gr.update(visible=False), # hide input gr.update(visible=True), # show viz _loading_html("Embedding your words\u2026"), 0, prompt, {}, {}, "", session_id, gr.update(value="", visible=False), ) # 2) Fire the three calls in parallel embeddings, sources, response = process_prompt_parallel(prompt) # 3) Render the first audience viz stage (embed) yield ( gr.update(visible=False), gr.update(visible=True), render_audience_embed(prompt, embeddings), 1, # audience_stage = 1 means embed is showing, next is retrieve prompt, embeddings, sources, response, session_id, gr.update(value="", visible=False), ) def handle_audience_continue(audience_stage, prompt, embeddings, sources, response): """Advance through audience stages: 1=embed showing -> 2=retrieve, 2=retrieve -> 3=synthesize, 3=synthesize -> 4=study.""" print(f"[audience] handle_audience_continue called with audience_stage={audience_stage!r}", flush=True) if audience_stage == 1: srcs = (sources or {}).get("sources") if isinstance(sources, dict) else None return ( gr.update(visible=True), gr.update(visible=False), render_sources(srcs, label="Step 3 \u00b7 Retrieve"), 2, ) if audience_stage == 2: return ( gr.update(visible=True), gr.update(visible=False), typewriter_html(response or "(no response)"), 3, ) if audience_stage == 3: return ( gr.update(visible=False, elem_classes=["aal-force-hide"]), gr.update(visible=True, elem_classes=["aal-force-show"]), gr.update(), # leave audience_display as-is 4, ) return gr.update(), gr.update(), gr.update(), audience_stage def handle_study_submit(session_id, prompt, q1, q2, q3): if not q1: return ( gr.update(), gr.update(), gr.update(value="**Please answer question 1 before submitting.**", visible=True), ) save_study(session_id, prompt, q1, q2, q3) return ( gr.update(visible=False, elem_classes=["aal-force-hide"]), # hide study gr.update(visible=True, elem_classes=["aal-force-show"]), # show thanks gr.update(value="", visible=False), ) # ============================================================ # Gradio UI # ============================================================ KEYBOARD_JS = """ () => { if (window._tedxKbSetup) return; window._tedxKbSetup = true; document.addEventListener('keydown', (e) => { const ae = document.activeElement; const tag = ae ? ae.tagName : ''; if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'BUTTON' || tag === 'SELECT') return; const pv = document.querySelector('#presenter_view'); if (!pv || pv.offsetParent === null) return; // only active when presenter mode is visible const forward = ['ArrowRight', ' ', 'PageDown', 'ArrowDown', 'Enter']; const back = ['ArrowLeft', 'PageUp', 'ArrowUp', 'Backspace']; if (forward.includes(e.key)) { e.preventDefault(); const fb = document.querySelector('#forward_btn button') || document.querySelector('#forward_btn'); if (fb) fb.click(); } else if (back.includes(e.key)) { e.preventDefault(); const bb = document.querySelector('#back_btn button') || document.querySelector('#back_btn'); if (bb) bb.click(); } }); } """ def _load_css(): path = os.path.join(os.path.dirname(__file__), "static", "style.css") try: with open(path, "r") as f: return f.read() except FileNotFoundError: return "" with gr.Blocks(title="Ask Anything Lab") as demo: # -- State -- stage = gr.State(0) embed_step = gr.State(0) audience_stage = gr.State(0) prompt_state = gr.State("") embeddings_state = gr.State({}) sources_state = gr.State({}) response_state = gr.State("") session_id_state = gr.State("") # ============================================================ # Landing view # ============================================================ with gr.Column(visible=True, elem_id="landing_view") as landing_view: gr.HTML(LANDING_HTML) with gr.Row(elem_classes=["tedx-cta"]): with gr.Column(scale=1): pass with gr.Column(scale=2): go_presenter_btn = gr.Button("Presenter Demo", variant="primary") with gr.Column(scale=2): go_audience_btn = gr.Button("Try It Yourself", variant="secondary") with gr.Column(scale=1): pass gr.HTML("""
TEDx · May 1, 2026 · thatrandomagency.com
""") # ============================================================ # Presenter view # ============================================================ with gr.Column(visible=False, elem_id="presenter_view") as presenter_view: presenter_display = gr.HTML(value=render_presenter_stage(0, 0)) with gr.Row(): with gr.Column(scale=1): home_btn_p = gr.Button("\u2190 Home", size="sm") with gr.Column(scale=4): pass # Hidden keyboard-proxy buttons (styled off-screen by CSS) forward_btn = gr.Button("forward", elem_id="forward_btn") back_btn = gr.Button("back", elem_id="back_btn") # ============================================================ # Audience view — top-level sibling groups to avoid Gradio 6 nested # visibility cascading issues. Each view is an independent top-level # Column that can be toggled cleanly. # ============================================================ # -- audience input group (first screen of audience mode) -- with gr.Column(visible=False, elem_id="audience_input_view") as audience_input_group: gr.HTML("""
Ask anything

Type a prompt. We’ll show you what the AI does next.

Your words will travel through embedding → retrieval → synthesis — the same pipeline ChatGPT runs on every request.

""") with gr.Row(): with gr.Column(scale=1): pass with gr.Column(scale=3): prompt_box = gr.Textbox( label="Your prompt", placeholder="Ask me anything\u2026", lines=3, autofocus=True, ) prompt_err = gr.Markdown(value="", visible=False) submit_btn = gr.Button("Process my prompt \u2192", variant="primary") with gr.Column(scale=1): pass # -- audience viz group (embed/retrieve/synthesize display) -- with gr.Column(visible=False, elem_id="audience_viz_view") as audience_viz_group: audience_display = gr.HTML(value="") with gr.Row(): with gr.Column(scale=1): pass with gr.Column(scale=2): continue_btn = gr.Button("Continue \u2192", variant="primary") with gr.Column(scale=1): pass # -- study questions group -- with gr.Column(visible=False, elem_id="study_view") as study_group: gr.HTML(study_intro_html()) with gr.Row(): with gr.Column(scale=1): pass with gr.Column(scale=3): q1 = gr.Radio( choices=[(label, value) for value, label in SURPRISING_OPTIONS], label="1. Which stage surprised you most?", ) q2 = gr.Slider( minimum=1, maximum=5, step=1, value=3, label="2. Before seeing this, how much did you trust AI answers? (1 = not at all, 5 = completely)", ) q3 = gr.Slider( minimum=1, maximum=5, step=1, value=3, label="3. After seeing how it works, how much do you trust AI answers? (1 = not at all, 5 = completely)", ) study_err = gr.Markdown(value="", visible=False) study_submit_btn = gr.Button("Submit", variant="primary") with gr.Column(scale=1): pass # -- thanks group -- with gr.Column(visible=False, elem_id="thanks_view") as thanks_group: gr.HTML(thanks_html()) with gr.Row(): with gr.Column(scale=2): pass with gr.Column(scale=1): home_btn_a = gr.Button("\u2190 Back to start", size="sm") with gr.Column(scale=2): pass # ============================================================ # Event wiring # ============================================================ go_presenter_btn.click( enter_presenter, outputs=[ landing_view, presenter_view, audience_input_group, audience_viz_group, study_group, thanks_group, stage, embed_step, presenter_display, ], ) go_audience_btn.click( enter_audience, outputs=[ landing_view, presenter_view, audience_input_group, audience_viz_group, study_group, thanks_group, prompt_box, audience_stage, ], ) home_btn_p.click( go_home, outputs=[ landing_view, presenter_view, audience_input_group, audience_viz_group, study_group, thanks_group, stage, embed_step, ], ) home_btn_a.click( go_home, outputs=[ landing_view, presenter_view, audience_input_group, audience_viz_group, study_group, thanks_group, stage, embed_step, ], ) forward_btn.click( on_forward, inputs=[stage, embed_step], outputs=[stage, embed_step, presenter_display], ) back_btn.click( on_back, inputs=[stage, embed_step], outputs=[stage, embed_step, presenter_display], ) submit_btn.click( handle_audience_submit, inputs=[prompt_box], outputs=[ audience_input_group, audience_viz_group, audience_display, audience_stage, prompt_state, embeddings_state, sources_state, response_state, session_id_state, prompt_err, ], ) continue_btn.click( handle_audience_continue, inputs=[audience_stage, prompt_state, embeddings_state, sources_state, response_state], outputs=[audience_viz_group, study_group, audience_display, audience_stage], ) study_submit_btn.click( handle_study_submit, inputs=[session_id_state, prompt_state, q1, q2, q3], outputs=[study_group, thanks_group, study_err], ) # Install keyboard listener on page load (Gradio 6: js= must go on .load()) demo.load(fn=None, inputs=None, outputs=None, js=KEYBOARD_JS) if __name__ == "__main__": demo.launch( server_name="0.0.0.0", server_port=7860, show_error=True, theme=gr.themes.Base(primary_hue="blue", neutral_hue="slate"), css=_load_css(), )