Roleplay-Chat-Box / app_fixed.py
ButterM40's picture
Fix: Simplified Gradio interface for v3.x compatibility
cad5bb4
import gradio as gr
import os
import sys
import asyncio
from typing import List, Tuple
# Add backend to path for imports
backend_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'backend')
sys.path.insert(0, backend_path)
from backend.models.character_manager import CharacterManager
class RoleplayChatApp:
def __init__(self):
"""Initialize the Roleplay Chat App"""
self.character_manager = None
def initialize_models(self):
"""Initialize the character manager synchronously"""
try:
print("πŸ”„ Initializing character manager...")
self.character_manager = CharacterManager()
# Use sync initialization
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(self.character_manager.initialize())
loop.close()
print("βœ… Models loaded successfully!")
return "βœ… Models loaded successfully!"
except Exception as e:
print(f"❌ Failed to load models: {str(e)}")
return f"❌ Failed to load models: {str(e)}"
def chat_fn(self, message, character_id, history):
"""Handle chat functionality"""
if not message.strip():
return history, ""
if not self.character_manager:
self.initialize_models()
try:
# Convert history for context
conversation_history = []
for user_msg, bot_msg in history[-3:]:
conversation_history.append({"role": "user", "content": user_msg})
if bot_msg:
conversation_history.append({"role": "assistant", "content": bot_msg})
# Generate response
response = self.character_manager.generate_response(
character_id=character_id,
user_message=message,
conversation_history=conversation_history
)
# Update history
history.append((message, response))
return history, ""
except Exception as e:
error_msg = f"❌ Error: {str(e)}"
history.append((message, error_msg))
return history, ""
def create_interface():
"""Create a simple Gradio interface"""
app = RoleplayChatApp()
# Simple function-based interface
def chat_with_character(message, character, history):
return app.chat_fn(message, character, history)
def clear_chat():
return []
# Create simple interface
with gr.Blocks() as demo:
gr.Markdown("# 🎭 Roleplay Chat Box")
gr.Markdown("Chat with AI characters!")
# Character selector
character_selector = gr.Radio(
choices=[
"moses",
"samsung_employee",
"jinx"
],
value="moses",
label="Choose Character"
)
# Chat interface
chatbot = gr.Chatbot()
msg = gr.Textbox(label="Your Message", placeholder="Type here...")
clear = gr.Button("Clear Chat")
# Setup interactions
msg.submit(
chat_with_character,
[msg, character_selector, chatbot],
[chatbot, msg]
)
clear.click(clear_chat, outputs=chatbot)
return demo
if __name__ == "__main__":
demo = create_interface()
demo.launch()