import gradio as gr
import yaml
import json
import os
import traceback
import matplotlib.pyplot as plt
import numpy as np
from engine.loader import load_persona
from engine.drift import apply_context_shift
from engine.responder import generate_response, generate_response_local
from engine.utils import safe_log
from engine.logger import log_interaction
# Paths
persona_dir = "./personas"
contexts_path = "./contexts/scenarios.json"
error_log_path = "./ot_simulator_errors.log"
# Load available personas
def get_persona_choices():
return [f for f in os.listdir(persona_dir) if f.endswith(".yml")]
# Load available contextual scenarios
def get_scenario_choices():
try:
with open(contexts_path, "r") as f:
scenarios = json.load(f)
return [s["scenario"] for s in scenarios]
except Exception as e:
safe_log("Scenarios load error", str(e))
return []
# Generate radar chart for character emotional state
def plot_state(state, persona_name):
if persona_name == "Jack":
metrics = ["anxiety", "trust", "openness", "physical_discomfort"]
labels = ["Intensity", "Openness", "Candor", "Physical State"]
colors = ["#e74c3c", "#3498db", "#2ecc71", "#f39c12"]
elif persona_name == "Maya":
metrics = ["anxiety", "trust", "creative_engagement", "occupational_balance"]
labels = ["Intensity", "Openness", "Creativity", "Balance"]
colors = ["#e74c3c", "#3498db", "#9b59b6", "#1abc9c"]
else:
metrics = ["anxiety", "trust", "openness"]
labels = ["Intensity", "Openness", "Candor"]
colors = ["#e74c3c", "#3498db", "#2ecc71"]
values = [state.get(m, 0.0) for m in metrics]
angles = np.linspace(0, 2 * np.pi, len(metrics), endpoint=False).tolist()
values += values[:1]
angles += angles[:1]
fig, ax = plt.subplots(figsize=(5, 5), subplot_kw=dict(polar=True))
ax.plot(angles, values, color=colors[0], linewidth=2)
ax.fill(angles, values, color=colors[0], alpha=0.25)
ax.set_xticks(angles[:-1])
ax.set_xticklabels(labels)
ax.set_ylim(0, 1)
ax.set_yticklabels(['0.0', '0.2', '0.4', '0.6', '0.8', '1.0'])
ax.set_title(f"{persona_name}'s Character State", fontsize=14, pad=20)
ax.grid(True)
fig.tight_layout()
chart_path = f"./state_chart_{persona_name}.png"
fig.savefig(chart_path, dpi=100, bbox_inches='tight')
plt.close(fig)
return chart_path
# Generate interaction history visualization
def plot_interaction_history(history):
if not history or len(history) < 2:
return None
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 6))
interactions = list(range(1, len(history) + 1))
anxiety_vals = [h.get('anxiety', 0) for h in history]
trust_vals = [h.get('trust', 0) for h in history]
ax1.plot(interactions, anxiety_vals, marker='o', color='#e74c3c', linewidth=2, label='Emotional Intensity')
ax1.set_ylabel('Intensity Level', fontsize=10)
ax1.set_ylim(0, 1)
ax1.grid(True, alpha=0.3)
ax1.legend(loc='upper right')
ax2.plot(interactions, trust_vals, marker='o', color='#3498db', linewidth=2, label='Openness')
ax2.set_xlabel('Interaction Number', fontsize=10)
ax2.set_ylabel('Openness Level', fontsize=10)
ax2.set_ylim(0, 1)
ax2.grid(True, alpha=0.3)
ax2.legend(loc='upper right')
fig.suptitle('Character Engagement Over Time', fontsize=14)
fig.tight_layout()
history_path = "./interaction_history.png"
fig.savefig(history_path, dpi=100, bbox_inches='tight')
plt.close(fig)
return history_path
# Download session transcript
def download_session(conversation_history, state_history, selected_persona_file):
"""Generate downloadable transcript file."""
if not conversation_history:
return None
try:
persona_path = os.path.join(persona_dir, selected_persona_file)
persona = load_persona(persona_path)
from datetime import datetime
timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
name = persona.get("persona_name", "Character")
# Header
transcript = f"""================================================================
LIT DIGITAL TWIN - INTERACTION TRANSCRIPT
================================================================
Character: {name}
Date: {timestamp}
Number of Turns: {len(conversation_history)}
================================================================
CONVERSATION
================================================================
"""
# Conversation history
for i, turn in enumerate(conversation_history, 1):
transcript += f"\n[Turn {i}]\n"
if 'scenario' in turn:
transcript += f"Scenario: {turn['scenario']}\n\n"
transcript += f"Interviewer: {turn.get('student', '')}\n\n"
transcript += f"{name}: {turn.get('client', '')}\n\n"
transcript += "-" * 63 + "\n"
# State progression
if state_history:
transcript += f"""================================================================
STATE PROGRESSION
================================================================
Initial State:
Anxiety: {state_history[0].get('anxiety', 0):.2f}
Trust: {state_history[0].get('trust', 0):.2f}
Openness: {state_history[0].get('openness', 0):.2f}
Final State:
Anxiety: {state_history[-1].get('anxiety', 0):.2f}
Trust: {state_history[-1].get('trust', 0):.2f}
Openness: {state_history[-1].get('openness', 0):.2f}
Change:
Anxiety: {state_history[-1].get('anxiety', 0) - state_history[0].get('anxiety', 0):+.2f}
Trust: {state_history[-1].get('trust', 0) - state_history[0].get('trust', 0):+.2f}
Openness: {state_history[-1].get('openness', 0) - state_history[0].get('openness', 0):+.2f}
================================================================
"""
# Save to file
filename = f"{name}_{timestamp}.txt"
filepath = os.path.join("lit_transcripts", filename)
os.makedirs("lit_transcripts", exist_ok=True)
with open(filepath, "w", encoding="utf-8") as f:
f.write(transcript)
return filepath
except Exception as e:
safe_log("Download error", str(e))
return None
def simulate(prompt, selected_event, selected_persona_file, ai_mode,
conversation_history, state_history, use_fast_mode):
try:
# Normalize inputs
if hasattr(prompt, 'value'):
prompt = prompt.value
prompt = str(prompt) if prompt else ""
if hasattr(selected_event, 'value'):
selected_event = selected_event.value
if hasattr(selected_persona_file, 'value'):
selected_persona_file = selected_persona_file.value
if hasattr(ai_mode, 'value'):
ai_mode = ai_mode.value
# Initialize histories
conversation_history = conversation_history or []
state_history = state_history or []
# Load persona
persona_path = os.path.join(persona_dir, selected_persona_file)
persona = load_persona(persona_path)
# Load contextual scenario
with open(contexts_path, "r") as f:
scenarios = json.load(f)
scenario = next((s for s in scenarios if s["scenario"] == selected_event), None)
if scenario:
persona = apply_context_shift(persona, scenario)
context_note = f"**Context:** {scenario.get('description', selected_event)}\n\n"
else:
context_note = ""
# Generate response
# Note: ai_mode selects which backend to use (HF API vs local model)
# It should NOT be passed as force_mode (which controls emotional state)
response, updated_state, teaching_note = generate_response(
prompt,
persona,
conversation_history,
force_mode=None, # Let the system determine emotional mode naturally
use_fast_mode=use_fast_mode
)
# Update histories
conversation_history.append({
"student": prompt,
"client": response,
"scenario": selected_event
})
state_history.append(updated_state.copy())
# Conversation display with modern styling
conversation_display = ""
for i, turn in enumerate(conversation_history, 1):
# Turn number with gradient badge
conversation_display += f"""
Turn {i}
\n\n"""
# Scenario context if present
if 'scenario' in turn:
conversation_display += f"""
📖 Scene: {turn['scenario']}
\n\n"""
# Student question with modern styling
conversation_display += f"""
👤 YOU ASKED:
{turn['student']}
\n\n"""
# Character response with modern styling
conversation_display += f"""
🎭 {persona['persona_name'].upper()} REPLIED:
{turn['client']}
\n\n"""
conversation_display += "
\n\n"
# Visualizations
state_yaml = yaml.dump(updated_state, sort_keys=False)
current_chart = plot_state(updated_state, persona['persona_name'])
history_chart = plot_interaction_history(state_history)
# Teaching feedback - clean, educational format with better contrast
teaching_feedback = f"""
📊 Character's Current State
"""
# Add literary analysis of character state
intensity = updated_state.get('anxiety', 0)
openness = updated_state.get('trust', 0)
candor = updated_state.get('openness', 0)
mode = updated_state.get('mode', 'baseline')
if intensity > 0.7:
teaching_feedback += " • High Tension: Character is at a crisis point - authors use these moments to reveal core fears and motivations. What does this reveal about their inner conflict?
\n"
elif intensity > 0.4:
teaching_feedback += " • Moderate Tension: Character is emotionally engaged but controlled. Good opportunity to explore the gap between what they say and what they feel (subtext).
\n"
else:
teaching_feedback += " • Calm State: Character is composed. Authors often use calm moments to establish baseline personality before introducing conflict.
\n"
if openness > 0.6:
teaching_feedback += " • Revealing Moment: Character is sharing deeply - this is when backstory, trauma, and hidden desires surface. Pay attention to what they choose to reveal.
\n"
elif openness > 0.4:
teaching_feedback += " • Cautiously Engaged: Character is balancing self-protection with honesty. Notice what they avoid - often as revealing as what they share.
\n"
else:
teaching_feedback += " • Guarded/Defensive: Character is protecting themselves. In literature, walls characters build often point to their deepest wounds. What are they protecting?
\n"
if mode == "trusting":
teaching_feedback += " • ✨ Breakthrough! You've reached the character's authentic self - this is where theme emerges. How does their truth connect to the story's larger meaning?
\n"
elif mode == "triggered":
teaching_feedback += " • ⚠️ Resistance: Character is defensive. In literary analysis, resistance often signals proximity to truth. What nerve did you touch?
\n"
elif mode == "decompensating":
teaching_feedback += " • 🔥 Crisis Point: Character breakdown reveals theme. Joyce, Hemingway, etc. use these moments to expose the forces crushing their characters. Analyze what's collapsing and why.
\n"
teaching_feedback += """
"""
# Log interaction
transcript_path = log_interaction(
persona,
prompt,
selected_event,
response,
updated_state,
teaching_note,
)
return (
conversation_display,
teaching_feedback,
state_yaml,
current_chart,
history_chart,
conversation_history,
state_history
)
except Exception as e:
error_msg = traceback.format_exc()
safe_log("Simulation error", error_msg)
print(f"ERROR: {error_msg}")
return (
"[ERROR] Simulation failed. Check logs.",
"Error occurred",
"",
None,
None,
conversation_history,
state_history
)
# Custom CSS for modern, engaging design
custom_css = """
.gradio-container {
max-width: 1400px !important;
}
.header-banner {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border-radius: 20px;
padding: 2.5rem;
text-align: center;
margin-bottom: 2rem;
box-shadow: 0 10px 30px rgba(102, 126, 234, 0.3);
}
.character-selector {
background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
border-radius: 15px;
padding: 1.5rem;
color: white;
}
.conversation-display {
background: #f8f9fa;
border-radius: 15px;
padding: 1.5rem;
min-height: 450px;
box-shadow: 0 4px 12px rgba(0,0,0,0.08);
}
.feedback-card {
background: linear-gradient(135deg, #84fab0 0%, #8fd3f4 100%);
border-radius: 15px;
padding: 1.5rem;
}
button.primary {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
border: none !important;
color: white !important;
font-weight: 600 !important;
font-size: 1.1rem !important;
padding: 0.8rem 2rem !important;
border-radius: 10px !important;
transition: all 0.3s ease !important;
}
button.primary:hover {
transform: translateY(-2px);
box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4) !important;
}
.chart-container {
background: white;
border-radius: 15px;
padding: 1rem;
box-shadow: 0 4px 12px rgba(0,0,0,0.08);
}
.feedback-box {
border-radius: 12px !important;
padding: 0 !important;
box-shadow: none !important;
background: transparent !important;
}
"""
with gr.Blocks(
title="📚 Literary Character Simulator",
theme=gr.themes.Soft(
primary_hue="purple",
secondary_hue="pink",
neutral_hue="slate",
font=gr.themes.GoogleFont("Inter")
),
css=custom_css
) as ui:
# Modern Header
gr.HTML("""
📚 Literary Character Simulator
Step into the minds of iconic characters from classic literature
An Interface Studio Production
""")
# Info Banner
gr.Markdown(
"""
✨ How It Works
Select a character, choose a scene, and ask questions to explore their story,
motivations, and inner conflicts
"""
)
# State management
conversation_state = gr.State([])
state_history = gr.State([])
# Main row: left column (selectors + info + mode) and right column (conversation)
with gr.Row():
with gr.Column(scale=1, min_width=300):
# Character Selection Card
gr.HTML("""
🎭 Character Selection
""")
persona_files = get_persona_choices()
default_persona = persona_files[0] if persona_files else None
persona_selector = gr.Dropdown(
label="Choose Your Character",
choices=persona_files,
value=default_persona,
allow_custom_value=False,
info="🎭 Select which literary character to engage with",
elem_classes=["dropdown-modern"]
)
scenario_choices = get_scenario_choices()
scenario_selector = gr.Dropdown(
label="Scene Context",
choices=scenario_choices,
value=scenario_choices[0] if scenario_choices else None,
info="📖 Choose the narrative moment",
elem_classes=["dropdown-modern"]
)
gr.HTML("")
with gr.Accordion("📚 Character Library", open=False):
gr.HTML("""
📚 HAMLET by William Shakespeare
👑 Hamlet (23)
Prince of Denmark. Consumed by grief, betrayal, and existential doubt. Philosophical and volatile, struggling to avenge his father's murder.
👸 Gertrude (45)
Queen of Denmark. Married Claudius shortly after King Hamlet's death. Caught between husband and son, loving both, blind to the poison around her.
👑 Claudius (55)
King of Denmark. Murdered his brother, married Gertrude. Smooth politician haunted by guilt. Kingly authority masking desperation and fear of exposure.
🌸 Ophelia (19)
Young noblewoman. Caught between father's commands and Hamlet's madness. Descends into grief-stricken insanity after Polonius's death, drowns tragically.
⚔️ Laertes (25)
Ophelia's brother. Returns from France to avenge father Polonius's murder. Passionate and impulsive, manipulated by Claudius into killing Hamlet.
🏛️ OEDIPUS REX by Sophocles
👑 Oedipus (28)
King of Thebes. Saved city from Sphinx, now investigating King Laius's murder. Confident seeker of truth, unwittingly investigating himself.
👸 Jocasta (45)
Queen of Thebes. Married Oedipus after King Laius's death, unknowingly her own son. Realizes the truth and takes her own life.
👁️ Creon (50)
Brother-in-law to Oedipus. Rational and loyal advisor, wrongly accused of conspiracy. Represents justice and restraint, becomes ruler after Oedipus's fall.
🔮 Tiresias (65)
Blind prophet. Knows the truth about Oedipus but speaks in riddles. Angrily reveals Oedipus is the plague's cause when pressed.
🐑 Shepherd (60)
Former servant. Pitied baby Oedipus and gave him to Corinthian shepherd. His testimony reveals the tragic truth to Oedipus.
📖 CLASSIC SHORT STORIES
🌊 Eveline (29)
Eveline by James Joyce. Ten years after freezing at the dock and not leaving with Frank the sailor. Lives alone after father's death, wondering if she made right choice.
✍️ Jane (30)
The Yellow Wallpaper by Charlotte Perkins Gilman. Confined under rest cure for postpartum depression. Perceptive and imaginative, descending into madness while observing wallpaper patterns.
👨⚕️ John (35)
The Yellow Wallpaper by Charlotte Perkins Gilman. Physician husband who prescribes rest cure, forbids wife from writing. Paternalistic and dismissive, calls her "little girl." Faints when he sees her madness.
🎖️ Harold Krebs (25)
Soldier's Home by Ernest Hemingway. WWI veteran emotionally numb and disconnected from postwar Oklahoma. Struggles with reintegration and societal expectations.
💔 Louise Mallard (28)
The Story of an Hour by Kate Chopin. Hears husband died, feels guilty joy at freedom. Heart condition. Dies when husband returns alive - "joy that kills."
🏛️ Uncle Ben (50)
Uncle Ben's Choice by Chinua Achebe. Civil servant navigating moral compromise in postcolonial Nigeria. Pragmatic and ethically conflicted, chooses silence over confrontation.
🌊 MYSTIC RIVER by Dennis Lehane
📖 Jimmy Markum (38)
Corner store owner and ex-convict driven by grief and vengeance after daughter Katie's murder. Uses street-level intuition and intimidation outside the law.
🎭 Sean Devine (38)
Homicide detective torn between duty and personal history. Methodical and guarded, investigating the case that haunts his childhood friendships.
🔪 Dave Boyle (38)
Childhood friend abducted as child, never recovered. Haunted and suspect in Katie's murder. Tragic victim of misplaced vengeance.
💍 Brendan Harris (19)
Katie's secret boyfriend. Plans to elope with her. Devastated by her death, wrongly suspected by both police and Jimmy.
🚔 JOHN KEEGAN MYSTERIES by John Misak
🚔 John Keegan (52)
Ghosts of Days Gone By (Book #8). NYPD Deputy Inspector. Russian mob calls him "Okhotnik" (bogeyman). Haunted by killing Boris Yigevny, separated from wife Pauline, star of TV show "Dark Justice". Investigating Alice Duncan's murder in Central Park.
👮♀️ Pauline McCrory-Keegan (48)
To The Bone (Pauline Series #1). NYPD officer on leave from work and marriage, staying in St. Michaels. Struggling with identity outside John's shadow. Investigating missing 12-year-old Melissa Carver to feel useful again.
🕵️ Karl Lavin (58)
Ghosts of Days Gone By. NYPD Lieutenant, Keegan's partner and best friend. Shot by Russians 15 years ago. Known for crude humor, loyalty, and ball-busting. Planning retirement to Tennessee.
🔍 Arianna Nunez (32)
Ghosts of Days Gone By. NYPD Detective. Works with Keegan and Lavin. Sharp, witty, pop-culture savvy. Keegan calls her "Millennial". Ambitious and digitally fluent investigator.
🎮 THE LAST OF US by Naughty Dog
🎮 Joel (50)
Survivor hardened by daughter Sarah's death. Saved Ellie from Fireflies, lied about it. Morally complex protector struggling with guilt and love.
🎮 Ellie (14-19)
Survivor immune to infection. Lost friend Riley, bonded with Joel as father figure. Tough exterior hiding vulnerability and survivor's guilt.
""")
gr.HTML("""
⚙️ Settings
""")
ai_mode_selector = gr.Radio(
label="Response Mode",
choices=["AI (HuggingFace)", "Templates (Local)"],
value="AI (HuggingFace)",
info="🤖 Choose how responses are generated"
)
use_fast_mode_toggle = gr.Checkbox(
label="⚡ Fast Mode (Local AI)",
value=True,
info="Uses API if HF_TOKEN/ANTHROPIC_API_KEY set, otherwise local TinyLlama (~15-20s)",
visible=False # Hide since API tokens take priority anyway
)
with gr.Column(scale=2):
gr.HTML("""
💬 Conversation
""")
conversation_display = gr.HTML(
label="",
value="""
🎭 Ready to Begin!
Select a character and ask your first question to start exploring
""",
elem_classes=["conversation-display"]
)
# User input row with modern styling
with gr.Row():
with gr.Column():
gr.HTML("""
✍️ Ask Your Question
""")
student_prompt = gr.Textbox(
label="",
lines=3,
placeholder="💭 Example: How did that moment change you? What were you thinking when...?",
value="",
elem_classes=["input-box"]
)
# Buttons row with modern gradients
with gr.Row():
with gr.Column(scale=1):
send_btn = gr.Button(
"🚀 Send Question",
variant="primary",
size="lg",
elem_classes=["btn-primary"]
)
with gr.Column(scale=1):
download_btn = gr.Button(
"💾 Download Session",
variant="secondary",
size="lg"
)
with gr.Column(scale=1):
reset_btn = gr.Button(
"🔄 New Conversation",
variant="secondary",
size="lg"
)
# Feedback + technical state row with gradient card
with gr.Row():
with gr.Column():
gr.HTML("""
📝 Learning Feedback
""")
teaching_output = gr.HTML(
label="",
elem_classes=["feedback-box"]
)
with gr.Column():
state_output = gr.Textbox(
label="Technical State (for debugging)",
lines=8,
visible=False
)
# Charts row with cards
gr.HTML("""
📊 Character Analysis
""")
with gr.Row():
with gr.Column():
gr.HTML("""
Current Emotional State
""")
current_state_chart = gr.Image(
label="",
elem_classes=["chart-container"]
)
with gr.Column():
gr.HTML("""
Engagement Over Time
""")
history_chart = gr.Image(
label="",
elem_classes=["chart-container"]
)
# Hidden file output for downloads
download_file = gr.File(
label="Your session transcript (right-click to save)",
visible=True
)
# Instructor guide with modern styling
with gr.Accordion("👨🏫 Instructor Guide", open=False):
gr.HTML("""
📚 How to Use This Tool
This simulator enables students to engage with literary characters through
interactive dialogue, fostering deeper understanding of narrative and character development.
Learning Objectives:
- ✅ Practice close reading and character analysis
- ✅ Explore narrative perspectives and authentic voice
- ✅ Understand character psychology and emotional depth
- ✅ Develop critical thinking about literary texts
- ✅ Learn effective questioning techniques for analysis
Features:
- 📊 Real-time Feedback: Students receive immediate guidance on their questions
- 📈 Emotional Tracking: Visualizations show how characters respond emotionally
- 💾 Session Transcripts: Download conversations for review and reflection
- ⚡ Fast AI Responses: Local model provides quick, authentic character interactions
💡 Tip: Encourage students to ask open-ended questions that
explore motivations, conflicts, and character development rather than simple
factual questions about plot.
""")
# Button actions
send_btn.click(
fn=simulate,
inputs=[
student_prompt,
scenario_selector,
persona_selector,
ai_mode_selector,
conversation_state,
state_history,
use_fast_mode_toggle
],
outputs=[
conversation_display,
teaching_output,
state_output,
current_state_chart,
history_chart,
conversation_state,
state_history
]
)
download_btn.click(
fn=download_session,
inputs=[
conversation_state,
state_history,
persona_selector
],
outputs=download_file
)
def reset_conversation():
return (
"*Conversation will appear here...*",
"",
"",
None,
None,
[],
[]
)
reset_btn.click(
fn=reset_conversation,
inputs=[],
outputs=[
conversation_display,
teaching_output,
state_output,
current_state_chart,
history_chart,
conversation_state,
state_history
]
)
if __name__ == "__main__":
os.makedirs("personas", exist_ok=True)
os.makedirs("contexts", exist_ok=True)
os.makedirs("transcripts", exist_ok=True)
os.makedirs("engine", exist_ok=True)
ui.launch(share=True, server_name="0.0.0.0", server_port=7860)