Commit ·
c7437ae
1
Parent(s): 8855e7f
feat: add browser tts and conversation pacing
Browse files123438 unmodified lines4344454647484930 unmodified lines8081828384858623 unmodified lines1101111121131141155 unmodified lines121122123124125126894 unmodified lines102110221023102410251026511 unmodified lines153815391540154115421543101 unmodified lines1645164616471648164916501651165216531654165516561657165816591660146 unmodified lines18071808180918101811181222 unmodified lines18351836183718381839184033 unmodified lines1874187518761877187818794 unmodified lines18841885188618871888188910 unmodified lines19001901190219031904190519 unmodified lines19251926192719281929193043 unmodified lines19741975197619771978197919809 unmodified lines19901991199219931994199519 unmodified lines20152016201720182019202018 unmodified lines20392040204120422043204488 unmodified lines2133213421352136213721386 unmodified lines21452146214721482149215021 unmodified lines2172217321742175217621772178217921802181218267 unmodified lines22502251225222532254225522568 unmodified lines2265226622672268226922701 unmodified line22722273227422752276227722786 unmodified lines2285228622872288228922901 unmodified line22922293229422952296229722987 unmodified lines2306230723082309231023111 unmodified line23132314231523162317231823197 unmodified lines2327232823292330233123321 unmodified line23342335233623372338233923407 unmodified lines2348234923502351235223531 unmodified line23552356235723582359236023616 unmodified lines23682369237023712372237315 unmodified lines2389239023912392239323944 unmodified lines239924002401240224032404240524062407from html import escapeimport osfrom time import sleep38 unmodified lines</div>"""EMPTY_TRANSCRIPT = "No show yet. The transcript will appear here."EMPTY_AGENT_STATE = "<div class=\"agent-state-empty\">No agents on stage yet.</div>"EMPTY_DIRECTOR_LOG = "No director notes yet."EMPTY_TRACE = "No trace events yet."30 unmodified linesHF_API_MODEL_ID = os.getenv("HF_API_MODEL_ID", DEFAULT_HF_API_MODEL_ID)DEFAULT_MAX_NEW_TOKENS = 120DEFAULT_TEMPERATURE = 0.75PLAYBACK_DELAY_SECONDS = 0.75SHOW_LENGTH_CHOICES = [("Short", "short"),("Standard", "standard"),23 unmodified lines"scroll",]def _prop_dropdown_label(canonical: str) -> str:emoji = PROP_EMOJI.get(canonical.lower(), "🎁")5 unmodified lines(_prop_dropdown_label(name), name) for name in DEFAULT_STAGE_PROPS]CUSTOM_CSS = """body,.gradio-container {894 unmodified linesborder: none !important;box-shadow: none !important;}.agent-state-grid {display: grid;gap: 0.55rem;511 unmodified lines)def render_stage(session: TheaterSession | None) -> str:if session is None:return EMPTY_STAGE101 unmodified linesif session is None:return EMPTY_TRANSCRIPTtranscript_lines = ["Transcript:","No puppet lines yet. The first beat will be added in the next milestone.",]if session.transcript:transcript_lines = ["Transcript:"]for index, beat in enumerate(session.transcript, start=1):transcript_lines.append(f"{index}. {beat.speaker}: {beat.line}")return "\n".join(transcript_lines)def render_agent_state(session: TheaterSession | None) -> str:146 unmodified linesreturn (render_stage(session),render_transcript(session),render_agent_state(session),render_director_log(session),render_trace(session),22 unmodified linesNone,EMPTY_STAGE,"No premise yet. Add a premise to raise the curtain.",EMPTY_AGENT_STATE,EMPTY_DIRECTOR_LOG,EMPTY_TRACE,33 unmodified lines"",EMPTY_STAGE,EMPTY_TRANSCRIPT,EMPTY_AGENT_STATE,EMPTY_DIRECTOR_LOG,EMPTY_TRACE,4 unmodified linesDEFAULT_MAX_NEW_TOKENS,DEFAULT_TEMPERATURE,True,EMPTY_BACKEND,)10 unmodified linesNone,EMPTY_STAGE,"Create a show before running a beat.",EMPTY_AGENT_STATE,EMPTY_DIRECTOR_LOG,EMPTY_TRACE,19 unmodified linesNone,EMPTY_STAGE,"Create a show before running the full act.",EMPTY_AGENT_STATE,EMPTY_DIRECTOR_LOG,EMPTY_TRACE,43 unmodified linessession.director_mode = selected_director_modeyield session, *render_outputs(session)if session.beat_index < session.max_beats:sleep(PLAYBACK_DELAY_SECONDS)def throw_audience_prop(9 unmodified linesNone,EMPTY_STAGE,"Create a show before throwing a prop.",EMPTY_AGENT_STATE,EMPTY_DIRECTOR_LOG,EMPTY_TRACE,19 unmodified linesNone,EMPTY_STAGE,"Create a show before summoning an actor.",EMPTY_AGENT_STATE,EMPTY_DIRECTOR_LOG,EMPTY_TRACE,18 unmodified linesNone,EMPTY_STAGE,"Create a show before requesting a finale.",EMPTY_AGENT_STATE,EMPTY_DIRECTOR_LOG,EMPTY_TRACE,88 unmodified linesreset_button = gr.Button("Reset", elem_classes=["reset-action"])stage_output = gr.HTML(value=EMPTY_STAGE, label="Stage", elem_classes=["stage-output"])with gr.Column(elem_classes=["backstage-stack"]):with gr.Group(elem_classes=["control-panel"]):6 unmodified lines)run_full_button = gr.Button("Run Full Act", elem_classes=["cue-action"])with gr.Group(elem_classes=["control-panel"]):gr.Markdown("### Audience", elem_classes=["audience-title", "panel-heading"])prop_input = gr.Dropdown(21 unmodified lines)with gr.Accordion("Transcript", open=False, elem_classes=["transcript-section"]):transcript_output = gr.Textbox(value=EMPTY_TRANSCRIPT,label="Transcript",lines=7,interactive=False,elem_classes=["transcript-box", "no-field-label"],)with gr.Accordion("Agent State", open=False):67 unmodified lineselem_classes=["no-field-label"],)create_button.click(create_show,inputs=[premise_input,8 unmodified linessession_state,stage_output,transcript_output,agent_state_output,director_output,trace_output,1 unmodified linebackend_output,],)run_one_button.click(advance_one_beat,inputs=[session_state,6 unmodified linessession_state,stage_output,transcript_output,agent_state_output,director_output,trace_output,1 unmodified linebackend_output,],)run_full_button.click(advance_full_act,inputs=[session_state,7 unmodified linessession_state,stage_output,transcript_output,agent_state_output,director_output,trace_output,1 unmodified linebackend_output,],)throw_prop_button.click(throw_audience_prop,inputs=[session_state,7 unmodified linessession_state,stage_output,transcript_output,agent_state_output,director_output,trace_output,1 unmodified linebackend_output,],)summon_actor_button.click(summon_audience_actor,inputs=[session_state,7 unmodified linessession_state,stage_output,transcript_output,agent_state_output,director_output,trace_output,1 unmodified linebackend_output,],)request_finale_button.click(request_audience_finale,inputs=[session_state,6 unmodified linessession_state,stage_output,transcript_output,agent_state_output,director_output,trace_output,15 unmodified linesactor_input,stage_output,transcript_output,agent_state_output,director_output,trace_output,4 unmodified linesmax_new_tokens_input,temperature_input,deterministic_full_act_input,backend_output,],)if __name__ == "__main__":1234538 unmodified lines4445464748495030 unmodified lines8182838485868788899091929394959623 unmodified lines1201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691705 unmodified lines176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224894 unmodified lines111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181511 unmodified lines1693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960101 unmodified lines206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088146 unmodified lines223522362237223822392240224122 unmodified lines226422652266226722682269227033 unmodified lines23042305230623072308230923104 unmodified lines23152316231723182319232023212322232310 unmodified lines233423352336233723382339234019 unmodified lines236023612362236323642365236643 unmodified lines24102411241224132414241524169 unmodified lines242624272428242924302431243219 unmodified lines245224532454245524562457245818 unmodified lines247724782479248024812482248388 unmodified lines25722573257425752576257725786 unmodified lines258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261521 unmodified lines26372638263926402641264226432644264567 unmodified lines27132714271527162717271827198 unmodified lines27282729273027312732273327341 unmodified line27362737273827392740274127426 unmodified lines27492750275127522753275427551 unmodified line27572758275927602761276227637 unmodified lines27712772277327742775277627771 unmodified line27792780278127822783278427857 unmodified lines27932794279527962797279827991 unmodified line28012802280328042805280628077 unmodified lines28152816281728182819282028211 unmodified line28232824282528262827282828296 unmodified lines283628372838283928402841284215 unmodified lines28582859286028612862286328644 unmodified lines2869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031from html import escapeimport jsonimport osfrom time import sleep38 unmodified lines</div>"""EMPTY_TRANSCRIPT = '<div class="conversation-empty">No show yet. The transcript will appear here.</div>'EMPTY_AGENT_STATE = "<div class=\"agent-state-empty\">No agents on stage yet.</div>"EMPTY_DIRECTOR_LOG = "No director notes yet."EMPTY_TRACE = "No trace events yet."30 unmodified linesHF_API_MODEL_ID = os.getenv("HF_API_MODEL_ID", DEFAULT_HF_API_MODEL_ID)DEFAULT_MAX_NEW_TOKENS = 120DEFAULT_TEMPERATURE = 0.75MIN_PLAYBACK_DELAY_SECONDS = 0.55MAX_PLAYBACK_DELAY_SECONDS = 1.85VOICE_MODE_CHOICES = [("Off", "off"),("Browser TTS: Character Voices", "character"),("Browser TTS: Narrator Only", "narrator"),]DEFAULT_VOICE_MODE = "off"EMPTY_TTS_PAYLOAD = "{}"EMPTY_TTS_STATUS = "Voice mode is off."SHOW_LENGTH_CHOICES = [("Short", "short"),("Standard", "standard"),23 unmodified lines"scroll",]VOICE_STYLE_PRESETS = [{"label": "Warm Puppet","pitch": 1.04,"rate": 0.96,"volume": 0.9,"voiceNameHints": ["Google US English", "Samantha", "Jenny", "Aria"],},{"label": "Tiny Mischief","pitch": 1.14,"rate": 0.98,"volume": 0.88,"voiceNameHints": ["Google UK English Female", "Samantha", "Jenny", "Aria"],},{"label": "Grumpy Elder","pitch": 0.92,"rate": 0.9,"volume": 0.9,"voiceNameHints": ["Daniel", "Alex", "Google UK English Male", "Microsoft Guy"],},{"label": "Bright Hero","pitch": 1.02,"rate": 1.02,"volume": 0.9,"voiceNameHints": ["Google US English", "Microsoft David", "Microsoft Mark", "Alex"],},{"label": "Soft Oracle","pitch": 0.98,"rate": 0.86,"volume": 0.82,"voiceNameHints": ["Google UK English Female", "Microsoft Zira", "Samantha", "Aria"],},]NARRATOR_VOICE_STYLE = {"label": "Narrator","pitch": 0.96,"rate": 0.88,"volume": 0.82,"voiceNameHints": ["Daniel", "Alex", "Google UK English Male", "Microsoft Guy", "Google US English"],}def _prop_dropdown_label(canonical: str) -> str:emoji = PROP_EMOJI.get(canonical.lower(), "🎁")5 unmodified lines(_prop_dropdown_label(name), name) for name in DEFAULT_STAGE_PROPS]def voice_style_for_actor(session: TheaterSession, speaker_name: str) -> dict[str, object]:for index, actor in enumerate(session.actors):if actor.name == speaker_name:return dict(VOICE_STYLE_PRESETS[index % len(VOICE_STYLE_PRESETS)])return dict(NARRATOR_VOICE_STYLE)def latest_tts_payload(session: TheaterSession | None) -> str:if session is None or not session.transcript:return EMPTY_TTS_PAYLOADlatest_beat = session.transcript[-1]latest_tool = session.latest_tool_resultif latest_tool is not None and latest_beat.tool_request is not None and latest_tool.actor_name == latest_beat.speaker:payload = {"id": f"{session.session_id}:{len(session.transcript)}:tool:{latest_tool.tool_name}","kind": "tool","speaker": "Stage Oracle","text": latest_tool.result,"style": NARRATOR_VOICE_STYLE,"narratorStyle": NARRATOR_VOICE_STYLE,}else:payload = {"id": f"{session.session_id}:{len(session.transcript)}:actor:{latest_beat.speaker}","kind": "actor","speaker": latest_beat.speaker,"text": latest_beat.line,"style": voice_style_for_actor(session, latest_beat.speaker),"narratorStyle": NARRATOR_VOICE_STYLE,}return json.dumps(payload, ensure_ascii=True)def playback_delay_for_latest_line(session: TheaterSession) -> float:if not session.transcript:return MIN_PLAYBACK_DELAY_SECONDSlatest = session.transcript[-1].lineword_count = len(latest.split())delay = 0.65 + (word_count * 0.28)return max(MIN_PLAYBACK_DELAY_SECONDS, min(4.25, delay))CUSTOM_CSS = """body,.gradio-container {894 unmodified linesborder: none !important;box-shadow: none !important;}.conversation-empty {color: #cbb7a1;font-size: 0.88rem;padding: 0.45rem 0.2rem;}.conversation-transcript {display: grid;gap: 0.38rem;padding: 0.15rem 0;}.conversation-turn {max-width: min(42rem, 84%);}.conversation-turn.speaker-changed {margin-top: 0.42rem;}.conversation-turn.same-speaker {margin-top: 0.04rem;}.conversation-turn:nth-child(even) {justify-self: end;}.conversation-speaker {color: #ffd166;font-size: 0.68rem;font-weight: 800;letter-spacing: 0.07em;margin: 0 0 0.12rem 0.18rem;text-transform: uppercase;}.conversation-bubble {background: rgba(10, 12, 23, 0.88);border: 1px solid rgba(246, 196, 83, 0.24);border-radius: 11px;box-shadow: 0 8px 22px rgba(0, 0, 0, 0.24);color: #f8efe4;font-size: 0.9rem;line-height: 1.38;padding: 0.54rem 0.68rem;overflow-wrap: anywhere;}.conversation-turn.latest .conversation-bubble {background: rgba(246, 196, 83, 0.13);border-color: rgba(246, 196, 83, 0.52);box-shadow:0 0 0 1px rgba(246, 196, 83, 0.14),0 10px 24px rgba(0, 0, 0, 0.28);}.voice-status {color: #cbb7a1;font-size: 0.8rem;min-height: 1.2rem;padding: 0.15rem 0.05rem 0;}.voice-status strong {color: #ffd166;}.agent-state-grid {display: grid;gap: 0.55rem;511 unmodified lines)BROWSER_TTS_JS = r"""async (mode, payloadJson, previewKind = "", options = {}) => {const root = globalThis;const speech = root.speechSynthesis;root.aiPuppetSpeech = root.aiPuppetSpeech || {lastAutoId: null,voices: [],voicesReady: false,queue: [],speaking: false,};root.aiPuppetSpeech.voices = Array.isArray(root.aiPuppetSpeech.voices) ? root.aiPuppetSpeech.voices : [];root.aiPuppetSpeech.queue = Array.isArray(root.aiPuppetSpeech.queue) ? root.aiPuppetSpeech.queue : [];root.aiPuppetSpeech.voicesReady = Boolean(root.aiPuppetSpeech.voicesReady);root.aiPuppetSpeech.speaking = Boolean(root.aiPuppetSpeech.speaking);const escapeHtml = (value) => String(value).replace(/[&<>"']/g, (char) => ({"&": "&","<": "<",">": ">",'"': ""","'": "'",})[char]);if (mode === "off") {if (speech) {root.aiPuppetSpeech.queue = [];root.aiPuppetSpeech.speaking = false;speech.cancel();}return '<div class="voice-status">Voice mode is off.</div>';}if (!("speechSynthesis" in root) || typeof SpeechSynthesisUtterance === "undefined") {return '<div class="voice-status"><strong>Browser TTS unavailable.</strong> The show still works without voice.</div>';}const cleanSpokenText = (value) => {return String(value || "").replace(/\[[^\]]{1,140}\]/g, " ").replace(/\*[^*]{1,140}\*/g, " ").replace(/\([^)]{1,90}\)/g, " ").replace(/[\u{1F000}-\u{1FAFF}\u{2600}-\u{27BF}]/gu, " ").replace(/\s+/g, " ").trim();};const loadVoices = () => new Promise((resolve) => {const current = speech.getVoices ? speech.getVoices() : [];if (current.length > 0) {root.aiPuppetSpeech.voices = current;root.aiPuppetSpeech.voicesReady = true;resolve(current);return;}let settled = false;const finish = () => {if (settled) return;settled = true;const voices = speech.getVoices ? speech.getVoices() : [];root.aiPuppetSpeech.voices = voices;root.aiPuppetSpeech.voicesReady = voices.length > 0;resolve(voices);};speech.onvoiceschanged = () => finish();setTimeout(finish, 700);});const selectVoice = (voices, style) => {if (!voices || voices.length === 0) return null;const hints = (style.voiceNameHints || []).map((hint) => String(hint).toLowerCase());const byHint = voices.find((candidate) => {const name = String(candidate.name || "").toLowerCase();return hints.some((hint) => name.includes(hint) || hint.includes(name));});if (byHint) return byHint;const english = voices.find((candidate) => {const lang = String(candidate.lang || "").toLowerCase();const name = String(candidate.name || "").toLowerCase();return lang.startsWith("en") || name.includes("english");});if (english) return english;const anyVoice = voices[0] || null;if (anyVoice) return anyVoice;if (Number.isInteger(style.voiceIndex) && voices.length > 0) {return voices[Math.abs(style.voiceIndex) % voices.length] || null;}return null;};const payloadFromJson = () => {try {return JSON.parse(payloadJson || "{}");} catch (_error) {return null;}};const buildTask = (payload) => {const narratorStyle = payload.narratorStyle || payload.style || {};const activeStyle = mode === "narrator" || previewKind === "narrator"? narratorStyle: (payload.style || narratorStyle);let text = payload.text;let speaker = payload.speaker ? String(payload.speaker) : "Latest line";if (previewKind === "actor") {text = `Previewing ${activeStyle.label || "character voice"}. The puppet voice is softer now.`;speaker = activeStyle.label || "Actor voice";} else if (previewKind === "narrator") {text = "Previewing narrator voice. The curtain rises, and the scene begins.";speaker = activeStyle.label || "Narrator";} else if (mode === "narrator") {speaker = "Narrator";}text = cleanSpokenText(text);return { id: payload.id || `${Date.now()}:${speaker}`, text, speaker, style: activeStyle };};const updateStatus = (html) => {const status = document.querySelector(".voice-status");if (status) status.outerHTML = html;};const drainQueue = async () => {if (root.aiPuppetSpeech.speaking || root.aiPuppetSpeech.queue.length === 0) return;const task = root.aiPuppetSpeech.queue.shift();try {const voices = await loadVoices();const utterance = new SpeechSynthesisUtterance(task.text);utterance.pitch = Math.max(0.1, Math.min(2, Number(task.style.pitch ?? 1)));utterance.rate = Math.max(0.1, Math.min(2, Number(task.style.rate ?? 1)));utterance.volume = Math.max(0, Math.min(1, Number(task.style.volume ?? 1)));const voice = selectVoice(voices, task.style);if (voice) utterance.voice = voice;const label = task.style.label ? ` (${escapeHtml(task.style.label)})` : "";const statusHtml = `<div class="voice-status">Speaking: <strong>${escapeHtml(task.speaker)}</strong>${label}</div>`;root.aiPuppetSpeech.speaking = true;updateStatus(statusHtml);utterance.onend = () => {root.aiPuppetSpeech.speaking = false;drainQueue();};utterance.onerror = () => {root.aiPuppetSpeech.speaking = false;drainQueue();};speech.speak(utterance);} catch (error) {root.aiPuppetSpeech.speaking = false;updateStatus('<div class="voice-status"><strong>Browser TTS could not start.</strong> Try Speak Latest Line once, then run the show again.</div>');}};const payload = payloadFromJson();if (!payload) {return '<div class="voice-status">No speakable line is ready yet.</div>';}const task = buildTask(payload);if (!task.text) {return '<div class="voice-status">No speakable line is ready yet.</div>';}if (!options.queue) {root.aiPuppetSpeech.queue = [];root.aiPuppetSpeech.speaking = false;speech.cancel();}root.aiPuppetSpeech.queue.push(task);drainQueue();const label = task.style.label ? ` (${escapeHtml(task.style.label)})` : "";const prefix = options.queue && root.aiPuppetSpeech.speaking ? "Queued" : "Speaking";return `<div class="voice-status">${prefix}: <strong>${escapeHtml(task.speaker)}</strong>${label}</div>`;}"""AUTO_BROWSER_TTS_JS = r"""async (mode, autoSpeak, payloadJson) => {const root = globalThis;root.aiPuppetSpeech = root.aiPuppetSpeech || {};root.aiPuppetSpeech.lastAutoId = root.aiPuppetSpeech.lastAutoId || null;root.aiPuppetSpeech.voices = Array.isArray(root.aiPuppetSpeech.voices) ? root.aiPuppetSpeech.voices : [];root.aiPuppetSpeech.queue = Array.isArray(root.aiPuppetSpeech.queue) ? root.aiPuppetSpeech.queue : [];root.aiPuppetSpeech.voicesReady = Boolean(root.aiPuppetSpeech.voicesReady);root.aiPuppetSpeech.speaking = Boolean(root.aiPuppetSpeech.speaking);const speech = root.speechSynthesis;try {if (mode === "off") {if (speech) speech.cancel();return '<div class="voice-status">Voice mode is off.</div>';}if (!autoSpeak) {return '<div class="voice-status">Auto-speak is off. Use Speak Latest Line to replay.</div>';}let payload = {};try {payload = JSON.parse(payloadJson || "{}");} catch (_error) {return '<div class="voice-status">No speakable line is ready yet.</div>';}if (!payload.id || root.aiPuppetSpeech.lastAutoId === payload.id) {return '<div class="voice-status">Browser TTS is ready.</div>';}root.aiPuppetSpeech.lastAutoId = payload.id;const speakLatest = %s;return await speakLatest(mode, payloadJson, "", { queue: true });} catch (error) {const detail = error && error.message ? String(error.message) : String(error || "unknown error");const safeDetail = detail.replace(/[&<>"']/g, (char) => ({"&": "&","<": "<",">": ">",'"': ""","'": "'",})[char]);return `<div class="voice-status"><strong>Auto-speak could not start.</strong> ${safeDetail}</div>`;}}""" % BROWSER_TTS_JSREGISTER_BROWSER_TTS_JS = r"""() => {globalThis.aiPuppetSpeakLatest = %s;if ("speechSynthesis" in globalThis && globalThis.speechSynthesis.getVoices) {globalThis.aiPuppetSpeech = globalThis.aiPuppetSpeech || {};globalThis.aiPuppetSpeech.lastAutoId = globalThis.aiPuppetSpeech.lastAutoId || null;globalThis.aiPuppetSpeech.voices = Array.isArray(globalThis.aiPuppetSpeech.voices) ? globalThis.aiPuppetSpeech.voices : [];globalThis.aiPuppetSpeech.queue = Array.isArray(globalThis.aiPuppetSpeech.queue) ? globalThis.aiPuppetSpeech.queue : [];globalThis.aiPuppetSpeech.voicesReady = Boolean(globalThis.aiPuppetSpeech.voicesReady);globalThis.aiPuppetSpeech.speaking = Boolean(globalThis.aiPuppetSpeech.speaking);const load = () => {const voices = globalThis.speechSynthesis.getVoices();globalThis.aiPuppetSpeech.voices = voices;globalThis.aiPuppetSpeech.voicesReady = voices.length > 0;};globalThis.speechSynthesis.onvoiceschanged = load;load();}globalThis.aiPuppetStopSpeaking = () => {if ("speechSynthesis" in globalThis) {globalThis.aiPuppetSpeech = globalThis.aiPuppetSpeech || {};globalThis.aiPuppetSpeech.queue = [];globalThis.aiPuppetSpeech.speaking = false;globalThis.speechSynthesis.cancel();return '<div class="voice-status">Speech stopped.</div>';}return '<div class="voice-status"><strong>Browser TTS unavailable.</strong> The show still works without voice.</div>';};return '<div class="voice-status">Voice mode is off.</div>';}""" % BROWSER_TTS_JSSTOP_SPEAKING_JS = r"""() => {if (globalThis.aiPuppetStopSpeaking) {return globalThis.aiPuppetStopSpeaking();}if ("speechSynthesis" in globalThis) {globalThis.aiPuppetSpeech = globalThis.aiPuppetSpeech || {};globalThis.aiPuppetSpeech.queue = [];globalThis.aiPuppetSpeech.speaking = false;globalThis.speechSynthesis.cancel();return '<div class="voice-status">Speech stopped.</div>';}return '<div class="voice-status"><strong>Browser TTS unavailable.</strong> The show still works without voice.</div>';}"""def render_stage(session: TheaterSession | None) -> str:if session is None:return EMPTY_STAGE101 unmodified linesif session is None:return EMPTY_TRANSCRIPTif not session.transcript:return '<div class="conversation-empty">No puppet lines yet. Run one beat to start the scene.</div>'turns: list[str] = []previous_speaker: str | None = Nonelatest_index = len(session.transcript)for index, beat in enumerate(session.transcript, start=1):speaker_changed = previous_speaker is not None and previous_speaker != beat.speakergap_class = "speaker-changed" if speaker_changed else "same-speaker"latest_class = " latest" if index == latest_index else ""turns.append(f"""<div class="conversation-turn {gap_class}{latest_class}"><div class="conversation-speaker">{escape(beat.speaker)}</div><div class="conversation-bubble">{escape(beat.line)}</div></div>""")previous_speaker = beat.speakerreturn f'<div class="conversation-transcript">{"".join(turns)}</div>'def render_agent_state(session: TheaterSession | None) -> str:146 unmodified linesreturn (render_stage(session),render_transcript(session),latest_tts_payload(session),render_agent_state(session),render_director_log(session),render_trace(session),22 unmodified linesNone,EMPTY_STAGE,"No premise yet. Add a premise to raise the curtain.",EMPTY_TTS_PAYLOAD,EMPTY_AGENT_STATE,EMPTY_DIRECTOR_LOG,EMPTY_TRACE,33 unmodified lines"",EMPTY_STAGE,EMPTY_TRANSCRIPT,EMPTY_TTS_PAYLOAD,EMPTY_AGENT_STATE,EMPTY_DIRECTOR_LOG,EMPTY_TRACE,4 unmodified linesDEFAULT_MAX_NEW_TOKENS,DEFAULT_TEMPERATURE,True,DEFAULT_VOICE_MODE,True,EMPTY_TTS_STATUS,EMPTY_BACKEND,)10 unmodified linesNone,EMPTY_STAGE,"Create a show before running a beat.",EMPTY_TTS_PAYLOAD,EMPTY_AGENT_STATE,EMPTY_DIRECTOR_LOG,EMPTY_TRACE,19 unmodified linesNone,EMPTY_STAGE,"Create a show before running the full act.",EMPTY_TTS_PAYLOAD,EMPTY_AGENT_STATE,EMPTY_DIRECTOR_LOG,EMPTY_TRACE,43 unmodified linessession.director_mode = selected_director_modeyield session, *render_outputs(session)if session.beat_index < session.max_beats:sleep(playback_delay_for_latest_line(session))def throw_audience_prop(9 unmodified linesNone,EMPTY_STAGE,"Create a show before throwing a prop.",EMPTY_TTS_PAYLOAD,EMPTY_AGENT_STATE,EMPTY_DIRECTOR_LOG,EMPTY_TRACE,19 unmodified linesNone,EMPTY_STAGE,"Create a show before summoning an actor.",EMPTY_TTS_PAYLOAD,EMPTY_AGENT_STATE,EMPTY_DIRECTOR_LOG,EMPTY_TRACE,18 unmodified linesNone,EMPTY_STAGE,"Create a show before requesting a finale.",EMPTY_TTS_PAYLOAD,EMPTY_AGENT_STATE,EMPTY_DIRECTOR_LOG,EMPTY_TRACE,88 unmodified linesreset_button = gr.Button("Reset", elem_classes=["reset-action"])stage_output = gr.HTML(value=EMPTY_STAGE, label="Stage", elem_classes=["stage-output"])latest_tts_payload_output = gr.Textbox(value=EMPTY_TTS_PAYLOAD, visible=False)with gr.Column(elem_classes=["backstage-stack"]):with gr.Group(elem_classes=["control-panel"]):6 unmodified lines)run_full_button = gr.Button("Run Full Act", elem_classes=["cue-action"])with gr.Group(elem_classes=["control-panel"]):gr.Markdown("### Voice", elem_classes=["show-controls-title", "panel-heading"])voice_mode_select = gr.Radio(choices=VOICE_MODE_CHOICES,value=DEFAULT_VOICE_MODE,label="Voice Mode",interactive=True,)auto_speak_checkbox = gr.Checkbox(value=True,label="Auto-speak latest line",interactive=True,)with gr.Row():speak_latest_button = gr.Button("Speak Latest Line", elem_classes=["cue-action"])stop_speaking_button = gr.Button("Stop Speaking", elem_classes=["reset-action"])with gr.Row():preview_actor_voice_button = gr.Button("Preview Actor Voice", elem_classes=["cue-action"])preview_narrator_voice_button = gr.Button("Preview Narrator Voice", elem_classes=["cue-action"])tts_status_output = gr.HTML(value=f'<div class="voice-status">{EMPTY_TTS_STATUS}</div>',label="Voice Status",elem_classes=["no-field-label"],)with gr.Group(elem_classes=["control-panel"]):gr.Markdown("### Audience", elem_classes=["audience-title", "panel-heading"])prop_input = gr.Dropdown(21 unmodified lines)with gr.Accordion("Transcript", open=False, elem_classes=["transcript-section"]):transcript_output = gr.HTML(value=EMPTY_TRANSCRIPT,label="Transcript",elem_classes=["transcript-box", "no-field-label"],)with gr.Accordion("Agent State", open=False):67 unmodified lineselem_classes=["no-field-label"],)create_event = create_button.click(create_show,inputs=[premise_input,8 unmodified linessession_state,stage_output,transcript_output,latest_tts_payload_output,agent_state_output,director_output,trace_output,1 unmodified linebackend_output,],)run_one_event = run_one_button.click(advance_one_beat,inputs=[session_state,6 unmodified linessession_state,stage_output,transcript_output,latest_tts_payload_output,agent_state_output,director_output,trace_output,1 unmodified linebackend_output,],)run_full_event = run_full_button.click(advance_full_act,inputs=[session_state,7 unmodified linessession_state,stage_output,transcript_output,latest_tts_payload_output,agent_state_output,director_output,trace_output,1 unmodified linebackend_output,],)throw_prop_event = throw_prop_button.click(throw_audience_prop,inputs=[session_state,7 unmodified linessession_state,stage_output,transcript_output,latest_tts_payload_output,agent_state_output,director_output,trace_output,1 unmodified linebackend_output,],)summon_actor_event = summon_actor_button.click(summon_audience_actor,inputs=[session_state,7 unmodified linessession_state,stage_output,transcript_output,latest_tts_payload_output,agent_state_output,director_output,trace_output,1 unmodified linebackend_output,],)request_finale_event = request_finale_button.click(request_audience_finale,inputs=[session_state,6 unmodified linessession_state,stage_output,transcript_output,latest_tts_payload_output,agent_state_output,director_output,trace_output,15 unmodified linesactor_input,stage_output,transcript_output,latest_tts_payload_output,agent_state_output,director_output,trace_output,4 unmodified linesmax_new_tokens_input,temperature_input,deterministic_full_act_input,voice_mode_select,auto_speak_checkbox,tts_status_output,backend_output,],)app.load(None,outputs=[tts_status_output],js=REGISTER_BROWSER_TTS_JS,)voice_mode_select.change(None,inputs=[voice_mode_select],outputs=[tts_status_output],js=r"""(mode) => {if (mode !== "off") {if (!("speechSynthesis" in globalThis) || typeof SpeechSynthesisUtterance === "undefined") {return '<div class="voice-status"><strong>Browser TTS unavailable.</strong> The show still works without voice.</div>';}if (globalThis.speechSynthesis.getVoices) globalThis.speechSynthesis.getVoices();try {const unlock = new SpeechSynthesisUtterance(" ");unlock.volume = 0;unlock.rate = 1;globalThis.speechSynthesis.cancel();globalThis.speechSynthesis.speak(unlock);} catch (_error) {// Some browsers ignore silent unlock utterances; normal speaking still works.}const status = mode === "narrator"? '<div class="voice-status">Browser TTS narrator-only mode is ready.</div>': '<div class="voice-status">Browser TTS character voices are ready.</div>';return status;}if ("speechSynthesis" in globalThis) globalThis.speechSynthesis.cancel();return '<div class="voice-status">Voice mode is off.</div>';}""",)auto_speak_checkbox.change(None,inputs=[voice_mode_select, auto_speak_checkbox],outputs=[tts_status_output],js=r"""(mode, autoSpeak) => {if (mode === "off") {return autoSpeak? '<div class="voice-status">Auto-speak is ready, but voice mode is off.</div>': '<div class="voice-status">Auto-speak is off.</div>';}return autoSpeak? '<div class="voice-status">Auto-speak will read each new line.</div>': '<div class="voice-status">Auto-speak is off. Use Speak Latest Line manually.</div>';}""",)speak_latest_button.click(None,inputs=[voice_mode_select, latest_tts_payload_output],outputs=[tts_status_output],js=BROWSER_TTS_JS,)preview_actor_voice_button.click(None,inputs=[voice_mode_select, latest_tts_payload_output],outputs=[tts_status_output],js=r"""(mode, payloadJson) => {const activeMode = mode === "off" ? "character" : mode;const payload = payloadJson && payloadJson !== "{}"? payloadJson: JSON.stringify({speaker: "Warm Puppet",text: "Previewing actor voice.",style: {label: "Warm Puppet",pitch: 1.04,rate: 0.96,volume: 0.9,voiceNameHints: ["Google US English", "Samantha", "Jenny", "Aria"],},narratorStyle: {label: "Narrator",pitch: 0.96,rate: 0.88,volume: 0.82,voiceNameHints: ["Daniel", "Alex", "Google UK English Male", "Microsoft Guy", "Google US English"],},});const speakLatest = %s;return speakLatest(activeMode, payload, "actor");}""" % BROWSER_TTS_JS,)preview_narrator_voice_button.click(None,inputs=[voice_mode_select, latest_tts_payload_output],outputs=[tts_status_output],js=r"""(_mode, payloadJson) => {const payload = payloadJson && payloadJson !== "{}"? payloadJson: JSON.stringify({speaker: "Narrator",text: "Previewing narrator voice.",style: {label: "Warm Puppet",pitch: 1.04,rate: 0.96,volume: 0.9,voiceNameHints: ["Google US English", "Samantha", "Jenny", "Aria"],},narratorStyle: {label: "Narrator",pitch: 0.96,rate: 0.88,volume: 0.82,voiceNameHints: ["Daniel", "Alex", "Google UK English Male", "Microsoft Guy", "Google US English"],},});const speakLatest = %s;return speakLatest("narrator", payload, "narrator");}""" % BROWSER_TTS_JS,)stop_speaking_button.click(None,outputs=[tts_status_output],js=STOP_SPEAKING_JS,)reset_button.click(None,outputs=[tts_status_output],js=STOP_SPEAKING_JS,)latest_tts_payload_output.change(None,inputs=[voice_mode_select, auto_speak_checkbox, latest_tts_payload_output],outputs=[tts_status_output],js=AUTO_BROWSER_TTS_JS,)for event in [create_event,run_one_event,run_full_event,throw_prop_event,summon_actor_event,request_finale_event,]:event.then(None,inputs=[voice_mode_select, auto_speak_checkbox, latest_tts_payload_output],outputs=[tts_status_output],js=AUTO_BROWSER_TTS_JS,)if __name__ == "__main__":
app.py+645-21