import gradio as gr import json import os from dotenv import load_dotenv from datetime import datetime from engine import ( RPGEngine, generate_full_setup, generate_from_image_setup, generate_character_from_prompt, stream_literary_chapter, GENRE_CHOICES, DEFAULT_GENRE, ) load_dotenv() OPENROUTER_API_KEY = os.getenv("OPENROUTER_KEY", "") # --- UI LOGIC FORMATTERS --- def format_output(steps, max_steps=8): """ Render the simulation history into Markdown for display. Only the last `max_steps` entries are shown to keep the UI responsive, especially on mobile devices. """ if not steps: return "Simulation results will appear here..." # Only show the last `max_steps` steps to avoid huge Markdown blocks visible_steps = steps[-max_steps:] # Numbering is relative to the visible window (1..max_steps) output = [] for i, step in enumerate(visible_steps, 1): if step.get("error"): output.append(f"\nāŒ **Step {i}: Error**\n> {step['error']}") continue stype = step.get("type", "character_action") if stype == "gm_opening": output.append(f"\n{'='*60}\nšŸŽ² **Step {i} | OPENING SCENE**\n\n{step.get('gm_narration', '')}") elif stype == "system_reflection": output.append(f"\n{'='*60}\nšŸ”„ **Step {i} | SYSTEM REFLECTION**\n> {step.get('gm_narration')}") elif stype == "gm_directed": output.append(f"\n{'='*60}\n⚔ **Step {i} | GM / DIRECTOR EVENT**\n> {step.get('gm_narration')}") elif stype == "player_action": output.append(f"\n{'='*60}\nšŸ§‘ **Step {i} | PLAYER ACTION**\n> {step.get('gm_narration')}") elif stype == "world_event": output.append(f"\n{'='*60}\nšŸŒ **Step {i} | WORLD EVENT**\n> {step.get('gm_narration')}") else: name = step.get('character_name', '???') thinking = step.get('thinking', '') action = step.get('action', '') speech = step.get('speech', '') gm_narration = step.get('gm_narration', '') world_state = step.get('world_state', '') block = [f"\n{'='*60}", f"šŸ”¹ **Step {i}** | šŸŽ­ Actor: `{name}`"] if thinking: block.append(f"šŸ’­ _Thinking_: _{thinking}_") if action: block.append(f"šŸŽ¬ _Attempting_: *{action}*") if speech: block.append(f"šŸ’¬ **Speech**: \"{speech}\"") if gm_narration: block.append(f"\nšŸŽ² **Game Master (GM)**: {gm_narration}") if world_state: block.append(f"šŸŒ _Hidden World State_: _{world_state}_") output.append("\n".join(block)) return "\n".join(output) def update_preview(char_list): if not char_list: return "
šŸ”¹ Character list is empty. Add at least one!
", gr.update(choices=[], value=None) html = "
" choices = [] for i, c in enumerate(char_list): name = c.get('name', f'Character {i+1}') core = str(c.get('core_identity', '')).replace('\n', '
') pers = str(c.get('personality', '')).replace('\n', '
') agd = str(c.get('agenda', '')).replace('\n', '
') inv = str(c.get('inventory', '')).replace('\n', '
') rel = str(c.get('relationships', '')).replace('\n', '
') card = f'''
{i+1}. {name}

🧬 Core Identity: {core}

šŸŽ­ Personality/Mood: {pers}

šŸŽÆ Agenda: {agd}

šŸŽ’ Inventory: {inv}

šŸ¤ Relationships: {rel}

''' html += card choices.append(f"{i}: {name}") html += "
" return html, gr.update(choices=choices) def update_dynamic_ui(engine): if not engine: return gr.update(), gr.update(), gr.update(), gr.update() agent_names = engine.agent_names ws = engine.world_state return ( gr.update(choices=["[Auto GM Choice]"] + agent_names, value="[Auto GM Choice]"), gr.update(choices=agent_names, value=agent_names[0] if agent_names else None), gr.update(value=ws), gr.update(choices=agent_names, value=agent_names[0] if agent_names else None) ) # --- ENGINE WRAPPERS FOR GRADIO --- def start_engine_ui(world_setting, public_lore, char_list, model, api_key, gm_vibe, custom_vibe_instr, story_arc, steps, memory_len, reflection_int, use_jailbreak): if not api_key.strip() or not world_setting.strip() or not char_list or len(char_list) < 1: yield "āŒ Input missing", "", None, gr.update(interactive=False), gr.update(interactive=False) return clean_chars = [c for c in char_list if c.get('name', '').strip()] engine = RPGEngine( world_setting=world_setting, public_lore=public_lore, agents=clean_chars, model_name=model, api_key=api_key, gm_vibe=gm_vibe, memory_length=memory_len, reflection_interval=reflection_int, custom_vibe_instructions=custom_vibe_instr, story_arc=story_arc, use_jailbreak=use_jailbreak ) current_actor = "" for is_final, data, actor_name in engine.run_steps_generator(steps): current_actor = actor_name if not is_final: live_text = format_output(engine.history) + "\n\n" + data yield f"ā³ Running... ({actor_name})", live_text, engine, gr.update(), gr.update() else: yield f"ā³ Finished step. Next: {actor_name}", format_output(engine.history), engine, gr.update(), gr.update() yield f"āœ… Paused. Next: {current_actor}", format_output(engine.history), engine, gr.update(interactive=True), gr.update(interactive=True) def continue_engine_ui(engine, add_steps, force_actor_name): if not engine: yield "āŒ Start simulation first", "", engine, gr.update(), gr.update() return if force_actor_name and force_actor_name != "[Auto GM Choice]" and force_actor_name in engine.agent_names: engine.current_actor_idx = engine.agent_names.index(force_actor_name) current_actor = "" for is_final, step_data, actor_name in engine.run_steps_generator(add_steps): current_actor = actor_name if not is_final: live_text = format_output(engine.history) + "\n\n" + step_data yield f"ā³ Continuing... ({actor_name})", live_text, engine, gr.update(), gr.update() else: yield f"ā³ Finished step. Next: {actor_name}", format_output(engine.history), engine, gr.update(), gr.update() yield f"āœ… Paused. Next: {current_actor}", format_output(engine.history), engine, gr.update(interactive=True), gr.update(interactive=True) def run_directed_event_ui(engine, instruction): if not engine or not instruction.strip(): yield "āŒ Invalid input", "", engine, gr.update(), gr.update() return current_actor = "" for is_final, step_data, actor_name in engine.run_directed_event_generator(instruction): current_actor = actor_name if not is_final: live_text = format_output(engine.history) + "\n\n" + step_data yield f"ā³ Executing Director's Event...", live_text, engine, gr.update(), gr.update() else: yield f"ā³ Finished event. Next: {actor_name}", format_output(engine.history), engine, gr.update(), gr.update() yield f"āœ… Event Completed. Next: {current_actor}", format_output(engine.history), engine, gr.update(interactive=True), gr.update(interactive=True) # --- MID-GAME EDITING FUNCTIONS --- def undo_last_step(engine): if not engine or not engine.history: return "āŒ Session/History empty", gr.update(), engine popped_step = engine.history.pop() stype = popped_step.get("type", "") if stype not in ["system_reflection", "gm_directed", "gm_opening", "player_action", "world_event"]: char_name = popped_step.get("character_name") if char_name in engine.agent_names: engine.current_actor_idx = engine.agent_names.index(char_name) engine.world_state = engine.history[-1].get("world_state", engine.world_setting) if engine.history else engine.world_setting engine.steps_since_reflection = max(0, engine.steps_since_reflection - 1) return f"āŖ Undo successful.", format_output(engine.history), engine def update_world_state_manual(engine, new_state): if not engine: return "āŒ Start simulation first", engine engine.world_state = new_state.strip() return "āœ… World State Overwritten", engine def load_active_character_info(engine, char_name): if not engine or not char_name: return "", "", "", "", "" for a in engine.agents: if a["name"] == char_name: return a.get("core_identity", ""), a.get("personality", ""), a.get("agenda", ""), a.get("inventory", ""), a.get("relationships", "") return "", "", "", "", "" def save_active_character_info(engine, char_name, new_core, new_pers, new_agenda, new_inv, new_rel): if not engine or not char_name: return "āŒ Error", engine for a in engine.agents: if a["name"] == char_name: a["core_identity"] = new_core a["personality"] = new_pers a["agenda"] = new_agenda a["inventory"] = new_inv a["relationships"] = new_rel return f"āœ… {char_name} updated!", engine return "āŒ Character not found", engine def set_secret_whisper(engine, char_name, whisper_text): if not engine or not char_name: return "āŒ Error", engine engine.whispers[char_name] = whisper_text.strip() return f"āœ… Whisper set for {char_name}.", engine def inject_player_action(engine, action_text): if not engine or not action_text.strip(): return "āŒ Error", gr.update(), engine step_data = {"type": "player_action", "gm_narration": f"*{action_text.strip()}*", "world_state": engine.world_state} engine.history.append(step_data) return f"āœ… Action Injected", format_output(engine.history), engine def inject_world_event(engine, event_text): if not engine or not event_text.strip(): return "āŒ Error", gr.update(), engine engine.world_state += f" SUDDEN EVENT: {event_text.strip()}" step_data = {"type": "world_event", "gm_narration": f"āš ļø **World Event**: {event_text.strip()}", "world_state": engine.world_state} engine.history.append(step_data) return f"āœ… Injected Event", format_output(engine.history), engine # --- I/O EXPORT/IMPORT --- def export_session(engine): if not engine: return None filename = f"rpg_log_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json" with open(filename, "w", encoding="utf-8") as f: json.dump(engine.to_dict(), f, ensure_ascii=False, indent=2) return filename def load_session(file_obj, api_key): if not file_obj: return (None, "āŒ No file selected", gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update()) try: with open(file_obj.name, "r", encoding="utf-8") as f: data = json.load(f) # Hydrate object directly engine = RPGEngine.from_dict(data, api_key) # Normalize gm_vibe: support old str format and new list format raw_vibe = engine.gm_vibe vibe_value = raw_vibe if isinstance(raw_vibe, list) else ([raw_vibe] if raw_vibe else ["Neutral Realism"]) p_html, p_drop = update_preview(engine.agents) return ( engine, "āœ… Save loaded successfully!", gr.update(value=engine.world_setting), gr.update(value=engine.public_lore), gr.update(value=vibe_value), gr.update(value=engine.custom_vibe_instructions), gr.update(value=getattr(engine, 'story_arc', '')), gr.update(value=engine.model_name), engine.agents, p_html, p_drop, format_output(engine.history), gr.update(value=engine.memory_length), gr.update(value=engine.reflection_interval), gr.update(value=getattr(engine, 'use_jailbreak', False)), gr.update(interactive=True), gr.update(interactive=True) ) except Exception as e: return (None, f"āŒ Load error: {str(e)}", gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update()) # --- GENERATORS WRAPPERS --- def gen_full_wrapper(prompt, genre, api_key, model, current_chars, gm_vibe, use_jailbreak): w_set, w_lore, new_chars, status = generate_full_setup(prompt, genre, api_key, model, gm_vibe=gm_vibe, use_jailbreak=use_jailbreak) combined = (current_chars or []) + new_chars return w_set, w_lore, combined, status, status def gen_img_wrapper(img_files, extra_instr, genre, api_key, current_chars, gm_vibe, use_jailbreak, img_model): if not img_files: return "", "", current_chars or [], "āŒ No images uploaded", "āŒ No images uploaded" paths = [f.name if hasattr(f, "name") else f["name"] if isinstance(f, dict) else f for f in img_files] w_set, w_lore, new_chars, status = generate_from_image_setup(paths, extra_instr, genre, api_key, model=img_model, gm_vibe=gm_vibe, use_jailbreak=use_jailbreak) combined = (current_chars or []) + new_chars return w_set, w_lore, combined, status, status def gen_char_wrapper(prompt, api_key, model, current_chars, use_jailbreak): char, status = generate_character_from_prompt(prompt, api_key, model, use_jailbreak=use_jailbreak) if char: combined = (current_chars or []) + [char] return combined, status return current_chars, status def stream_chapter_wrapper(engine, api_key, model, use_jailbreak): if not engine: yield "āŒ No active session.", gr.update(visible=False) return story_content = "" for chunk in stream_literary_chapter(engine.history, api_key, model, use_jailbreak=use_jailbreak): story_content = chunk yield story_content, gr.update(visible=False) filename = f"rpg_story_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt" with open(filename, "w", encoding="utf-8") as f: f.write(story_content) yield story_content, gr.update(value=filename, visible=True) # --- MAIN UI BLOCK --- with gr.Blocks(title="šŸŽ² AI RPG Engine", theme=gr.themes.Soft()) as demo: gr.Markdown("# šŸŽ² AI RPG Engine\n_Multi-agent simulation orchestrated by an AI Game Master_") # NOW WE STORE THE ACTUAL RPGEngine INSTANCE! session_state = gr.State(None) characters_state = gr.State([]) with gr.Tabs(): with gr.TabItem("āš™ļø Setup"): with gr.Accordion("šŸ“‚ Load Session", open=False): load_file = gr.File(label="Upload JSON History File", file_types=[".json"]) load_status = gr.Textbox(label="Load Status", interactive=False) with gr.Row(): with gr.Column(scale=2): with gr.Group(): gr.Markdown("#### šŸŒ World Configuration") world_setting = gr.Textbox(label="GM Secrets & Initial Situation", lines=3, value="The abandoned space station 'Icarus'. The airlock is jammed intentionally by a traitor.") public_lore = gr.Textbox(label="Public Lore & Genre Rules", lines=3, value="Sci-Fi horror. Everyone knows they have 2 hours of oxygen left. Characters should act paranoid.") with gr.Row(): model = gr.Dropdown(label="šŸ¤– Model", choices=["deepseek/deepseek-v3.2", "meta-llama/llama-3.3-70b-instruct:free", "openrouter/hunter-alpha", "arcee-ai/trinity-large-preview:free"], value="deepseek/deepseek-v3.2", allow_custom_value=True) gm_vibe = gr.CheckboxGroup( label="šŸŽ­ GM Vibe (select one or more)", choices=[ "Neutral Realism", "Gritty Survival", "Slice of Life", "Fluffy Romance", "Comedy", "Dark Comedy", "Psychological Horror", "Epic High Drama", "Cozy Mystery", "Action Adventure", "Political Intrigue", "Mythic Folklore", "Philosophical Slow Burn", "── ā¤ļøā€šŸ”„ Adult / NSFW ──", "Sensual Intimacy", "Slow Burn to Explicit", "Explicit NSFW", "Dominant & Submissive", "Rough & Primal", "Forbidden Desire", "Monster Romance", "Harem Dynamics" ], value=["Gritty Survival"] ) custom_vibe_instr = gr.Textbox(label="āœļø Custom Vibe Instructions (optional)", lines=2, placeholder="Add your own instructions to complement the selected vibe, e.g.: 'Use lots of sarcasm' or 'Write in a Victorian style'") story_arc = gr.Textbox(label="šŸŽÆ Global Story Arc Goal (optional)", lines=2, placeholder="e.g. 'The traitor must be exposed before the station loses power' — GM will steer the narrative toward this goal.") api_key = gr.Textbox(label="šŸ”‘ OpenRouter Key", type="password", value=OPENROUTER_API_KEY) with gr.Accordion("āš™ļø Engine Settings", open=False): memory_length = gr.Slider(5, 100, value=30, step=5, label="🧠 Memory Depth (Turns)") reflection_interval = gr.Slider(2, 20, value=5, step=1, label="šŸ”„ System Reflection Interval") use_jailbreak = gr.Checkbox(label="šŸ”“ Enable Jailbreak (Bypass Filters)", value=False) with gr.Column(scale=1): gr.Markdown("### šŸ‘„ Characters") with gr.Group(): gr.Markdown("#### šŸŒ Quick Generate World & Cast") with gr.Tabs(): with gr.TabItem("šŸ“ Text Prompt"): gen_setting_genre = gr.Dropdown( label="Setting Genre Template", choices=GENRE_CHOICES, value=DEFAULT_GENRE, ) full_prompt = gr.Textbox(label="Idea / Scenario", lines=2, placeholder="A normal house party...") btn_gen_full = gr.Button("šŸŽ¬ Generate World & Cast from Text", variant="primary", size="sm") full_status = gr.Textbox(label="Status", interactive=False) with gr.TabItem("šŸ–¼ļø Image Prompt"): img_upload = gr.File(label="Upload Image(s)", file_types=["image"], file_count="multiple") img_model = gr.Dropdown( label="šŸ¤– Image Model", choices=["moonshotai/kimi-k2.5", "openrouter/healer-alpha"], value="moonshotai/kimi-k2.5", allow_custom_value=True ) img_genre = gr.Dropdown( label="Setting Genre Template", choices=GENRE_CHOICES, value=DEFAULT_GENRE, ) extra_instr = gr.Textbox(label="Additional Instructions (context, specific requests)", lines=2, placeholder="There's a hidden monster in the shadows.") btn_gen_img = gr.Button("šŸ–¼ļø Generate World & Cast from Image(s)", variant="primary", size="sm") img_status = gr.Textbox(label="Status", interactive=False) with gr.Group(): char_prompt = gr.Textbox(label="Add character by description", lines=1) btn_gen_char = gr.Button("✨ Generate Character", variant="secondary", size="sm") with gr.Group(): gr.Markdown("#### āœļø Character Roster") with gr.Row(): btn_add = gr.Button("āž• Add Empty Character", size="sm") char_preview = gr.HTML("
šŸ”¹ Character list is empty
") with gr.Group(): gr.Markdown("#### āœļø Character Editor") with gr.Row(): edit_select = gr.Dropdown(label="Select Character to Edit / Remove", choices=[], scale=3) btn_remove = gr.Button("šŸ—‘ļø Remove Selected", size="sm", scale=1, variant="stop") with gr.Row(): edit_name = gr.Textbox(label="Name", scale=2) edit_core = gr.Textbox(label="🧬 Core Identity", lines=2) edit_pers = gr.Textbox(label="šŸŽ­ Personality/Mood", lines=1) edit_agenda = gr.Textbox(label="šŸŽÆ Agenda", lines=1) edit_inv = gr.Textbox(label="šŸŽ’ Inventory", lines=1) edit_rel = gr.Textbox(label="šŸ¤ Relationships", lines=1) with gr.Row(): btn_update = gr.Button("šŸ’¾ Save Character Changes", variant="primary") edit_status = gr.Markdown("") with gr.Row(): steps_init = gr.Slider(1, 50, value=3, step=1, label="šŸ”¢ Steps to start") btn_start = gr.Button("šŸš€ Start RPG Simulation", variant="primary", scale=1) status = gr.Textbox(label="šŸ“Š Status", interactive=False) with gr.TabItem("šŸŽ¬ Story (Log)"): with gr.Group(): gr.Markdown("### šŸ•¹ļø Control Panel") with gr.Row(): steps_cont = gr.Slider(1, 50, value=2, step=1, label="āž• Turns to Generate") force_actor = gr.Dropdown(label="šŸŽÆ Force Next Actor", choices=["[Auto GM Choice]"], value="[Auto GM Choice]") with gr.Row(): btn_cont = gr.Button("ā–¶ļø Continue", variant="primary", interactive=False) btn_stop = gr.Button("šŸ›‘ Stop", variant="stop") btn_undo = gr.Button("āŖ Undo Last Turn") btn_exp = gr.Button("šŸ“„ Download JSON", interactive=False) output_md = gr.Markdown("_Waiting for simulation to start..._") gr.Markdown("### šŸ”§ Mid-Game Injections & Director Tools") with gr.Row(): with gr.Column(): with gr.Accordion("šŸŽ¬ Directed GM Event (Director Mode)", open=False): dir_instruction = gr.Textbox(label="Director's Instruction", lines=2) btn_dir_event = gr.Button("Trigger Directed Event", variant="primary") with gr.Accordion("🤫 Secret Whisper (To Character)", open=False): whisper_char = gr.Dropdown(label="Target Character") whisper_text = gr.Textbox(label="Secret Whisper", lines=2) btn_set_whisper = gr.Button("Set Whisper", variant="secondary") with gr.Accordion("šŸŒ World State Editor", open=False): world_state_edit = gr.Textbox(label="Current World State", lines=3) btn_update_ws = gr.Button("šŸ’¾ Force Update State", variant="secondary") with gr.Column(): with gr.Accordion("šŸŽ­ Active Character Editor", open=False): active_char_dropdown = gr.Dropdown(label="Select Character") active_char_core = gr.Textbox(label="🧬 Core Identity", lines=1) active_char_pers = gr.Textbox(label="šŸŽ­ Personality", lines=1) active_char_agenda = gr.Textbox(label="šŸŽÆ Agenda", lines=1) active_char_inv = gr.Textbox(label="šŸŽ’ Inventory", lines=1) active_char_rel = gr.Textbox(label="šŸ¤ Relationships", lines=1) btn_update_active_char = gr.Button("šŸ’¾ Save Character Changes", variant="secondary") with gr.Accordion("šŸ§‘ Player Action Injection", open=False): inj_player = gr.Textbox(label="External/Player Action", lines=2) btn_inject_player = gr.Button("Inject Action", variant="secondary") with gr.Accordion("⚔ Simple World Event Injection", open=False): inj_event = gr.Textbox(label="Event Description", lines=2) btn_inject_event = gr.Button("Inject Event", variant="secondary") with gr.Accordion("šŸ“– Generate Book Chapter", open=False): btn_story = gr.Button("✨ Generate Chapter", variant="primary") story_output = gr.Markdown("_Your story will appear here..._") story_file = gr.File(label="Download Chapter", visible=False) file_out = gr.File(label="JSON Log Download", visible=False) # --- UI LOGIC BINDINGS --- # Setup Generators btn_gen_full.click( gen_full_wrapper, inputs=[full_prompt, gen_setting_genre, api_key, model, characters_state, gm_vibe, use_jailbreak], outputs=[world_setting, public_lore, characters_state, full_status, full_status] ).then(update_preview, inputs=[characters_state], outputs=[char_preview, edit_select]) btn_gen_img.click( gen_img_wrapper, inputs=[img_upload, extra_instr, img_genre, api_key, characters_state, gm_vibe, use_jailbreak, img_model], outputs=[world_setting, public_lore, characters_state, img_status, img_status] ).then(update_preview, inputs=[characters_state], outputs=[char_preview, edit_select]) btn_gen_char.click( gen_char_wrapper, inputs=[char_prompt, api_key, model, characters_state, use_jailbreak], outputs=[characters_state, full_status] ).then(update_preview, inputs=[characters_state], outputs=[char_preview, edit_select]) # Character List Management def add_char(cl): cl = cl or [] new_cl = cl + [{"name": f"Character {len(cl) + 1}", "core_identity": "", "personality": "", "agenda": "", "inventory": "", "relationships": ""}] p_html, p_drop = update_preview(new_cl) return new_cl, p_html, p_drop btn_add.click(add_char, inputs=[characters_state], outputs=[characters_state, char_preview, edit_select]) def rem_char(cl, selected_str): if not selected_str or not cl: p_html, p_drop = update_preview(cl) return cl, p_html, p_drop try: idx = int(selected_str.split(":")[0]) new_cl = cl[:idx] + cl[idx+1:] except: new_cl = cl p_html, p_drop = update_preview(new_cl) return new_cl, p_html, p_drop btn_remove.click(rem_char, inputs=[characters_state, edit_select], outputs=[characters_state, char_preview, edit_select]) def load_edit_data(cl, selected_str): if not selected_str or not cl: return "", "", "", "", "", "", "" try: idx = int(selected_str.split(":")[0]) c = cl[idx] return c.get('name',''), c.get('core_identity',''), c.get('personality',''), c.get('agenda',''), c.get('inventory',''), c.get('relationships',''), "" except: return "", "", "", "", "", "", "" edit_select.change(load_edit_data, inputs=[characters_state, edit_select], outputs=[edit_name, edit_core, edit_pers, edit_agenda, edit_inv, edit_rel, edit_status]) def apply_edit(cl, selected_str, name, core, pers, agenda, inv, rel): if cl and selected_str: try: idx = int(selected_str.split(":")[0]) cl[idx].update({"name": name, "core_identity": core, "personality": pers, "agenda": agenda, "inventory": inv, "relationships": rel}) p_html, p_drop = update_preview(cl) p_drop["value"] = f"{idx}: {name}" return cl, p_html, p_drop, "āœ… Character Updated!" except: pass p_html, p_drop = update_preview(cl) return cl, p_html, p_drop, "" btn_update.click(apply_edit, inputs=[characters_state, edit_select, edit_name, edit_core, edit_pers, edit_agenda, edit_inv, edit_rel], outputs=[characters_state, char_preview, edit_select, edit_status]) # Load Session load_file.upload( load_session, inputs=[load_file, api_key], outputs=[ session_state, load_status, world_setting, public_lore, gm_vibe, custom_vibe_instr, story_arc, model, characters_state, char_preview, edit_select, output_md, memory_length, reflection_interval, use_jailbreak, btn_cont, btn_exp ] ).then(update_dynamic_ui, inputs=[session_state], outputs=[force_actor, active_char_dropdown, world_state_edit, whisper_char]) # Core Engine Start & Continue start_event = btn_start.click( start_engine_ui, inputs=[world_setting, public_lore, characters_state, model, api_key, gm_vibe, custom_vibe_instr, story_arc, steps_init, memory_length, reflection_interval, use_jailbreak], outputs=[status, output_md, session_state, btn_cont, btn_exp] ) start_event.then(update_dynamic_ui, inputs=[session_state], outputs=[force_actor, active_char_dropdown, world_state_edit, whisper_char]) cont_event = btn_cont.click( continue_engine_ui, inputs=[session_state, steps_cont, force_actor], outputs=[status, output_md, session_state, btn_cont, btn_exp] ) cont_event.then(update_dynamic_ui, inputs=[session_state], outputs=[force_actor, active_char_dropdown, world_state_edit, whisper_char]) dir_event = btn_dir_event.click( run_directed_event_ui, inputs=[session_state, dir_instruction], outputs=[status, output_md, session_state, btn_cont, btn_exp] ) dir_event.then(update_dynamic_ui, inputs=[session_state], outputs=[force_actor, active_char_dropdown, world_state_edit, whisper_char]) btn_stop.click(fn=None, inputs=None, outputs=None, cancels=[start_event, cont_event, dir_event]) # Undo Logic btn_undo.click(undo_last_step, inputs=[session_state], outputs=[status, output_md, session_state]).then(update_dynamic_ui, inputs=[session_state], outputs=[force_actor, active_char_dropdown, world_state_edit, whisper_char]) btn_exp.click(export_session, inputs=[session_state], outputs=[file_out]).then(lambda: gr.update(visible=True), outputs=[file_out]) # Injections & Whispers btn_set_whisper.click(set_secret_whisper, inputs=[session_state, whisper_char, whisper_text], outputs=[status, session_state]) btn_inject_player.click(inject_player_action, inputs=[session_state, inj_player], outputs=[status, output_md, session_state]) btn_inject_event.click(inject_world_event, inputs=[session_state, inj_event], outputs=[status, output_md, session_state]) # Mid-game editors btn_update_ws.click(update_world_state_manual, inputs=[session_state, world_state_edit], outputs=[status, session_state]) active_char_dropdown.change(load_active_character_info, inputs=[session_state, active_char_dropdown], outputs=[active_char_core, active_char_pers, active_char_agenda, active_char_inv, active_char_rel]) btn_update_active_char.click(save_active_character_info, inputs=[session_state, active_char_dropdown, active_char_core, active_char_pers, active_char_agenda, active_char_inv, active_char_rel], outputs=[status, session_state]) # Story Gen btn_story.click(stream_chapter_wrapper, inputs=[session_state, api_key, model, use_jailbreak], outputs=[story_output, story_file]) if __name__ == "__main__": demo.launch()