File size: 3,569 Bytes
cad5bb4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
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()