ButterM40 commited on
Commit
390f796
Β·
1 Parent(s): d207a2b

Fix Gradio schema error: Use v3.40.1 and simplified interface

Browse files
Files changed (2) hide show
  1. app.py +89 -88
  2. requirements.txt +2 -2
app.py CHANGED
@@ -1,114 +1,115 @@
1
  import gradio as gr
2
  import os
3
  import sys
4
- import asyncio
5
 
6
  # Add backend to path for imports
7
  backend_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'backend')
8
  sys.path.insert(0, backend_path)
9
 
10
  from backend.models.character_manager import CharacterManager
 
11
 
12
- class RoleplayChatApp:
13
- def __init__(self):
14
- """Initialize the Roleplay Chat App"""
15
- self.character_manager = None
16
-
17
- def initialize_models(self):
18
- """Initialize the character manager synchronously"""
19
- try:
20
- print("πŸ”„ Initializing character manager...")
21
- self.character_manager = CharacterManager()
22
-
23
- # Use sync initialization
24
- loop = asyncio.new_event_loop()
25
- asyncio.set_event_loop(loop)
26
- loop.run_until_complete(self.character_manager.initialize())
27
- loop.close()
28
-
29
- print("βœ… Models loaded successfully!")
30
- return "βœ… Models loaded successfully!"
31
- except Exception as e:
32
- print(f"❌ Failed to load models: {str(e)}")
33
- return f"❌ Failed to load models: {str(e)}"
34
 
35
- def chat_fn(self, message, character_id, history):
36
- """Handle chat functionality"""
37
- if not message.strip():
38
- return history, ""
39
-
40
- if not self.character_manager:
41
- self.initialize_models()
42
-
43
- try:
44
- # Convert history for context
45
- conversation_history = []
46
  for user_msg, bot_msg in history[-3:]:
47
- conversation_history.append({"role": "user", "content": user_msg})
 
48
  if bot_msg:
49
  conversation_history.append({"role": "assistant", "content": bot_msg})
50
-
51
- # Generate response
52
- response = self.character_manager.generate_response(
53
- character_id=character_id,
54
- user_message=message,
55
- conversation_history=conversation_history
56
- )
57
-
58
- # Update history
59
- history.append((message, response))
60
- return history, ""
61
-
62
- except Exception as e:
63
- error_msg = f"❌ Error: {str(e)}"
64
- history.append((message, error_msg))
65
- return history, ""
 
 
 
 
66
 
67
- def create_interface():
68
- """Create a simple Gradio interface"""
69
- app = RoleplayChatApp()
 
70
 
71
- # Simple function-based interface
72
- def chat_with_character(message, character, history):
73
- return app.chat_fn(message, character, history)
74
-
75
- def clear_chat():
76
- return []
77
-
78
- # Create simple interface
79
- with gr.Blocks() as demo:
80
- gr.Markdown("# 🎭 Roleplay Chat Box")
81
- gr.Markdown("Chat with AI characters!")
82
-
83
- # Character selector
84
- character_selector = gr.Radio(
85
- choices=[
86
- "moses",
87
- "samsung_employee",
88
- "jinx"
89
- ],
90
  value="moses",
91
  label="Choose Character"
92
  )
93
-
94
- # Chat interface
95
- chatbot = gr.Chatbot()
96
- msg = gr.Textbox(label="Your Message", placeholder="Type here...")
97
- clear = gr.Button("Clear Chat")
98
-
99
- # Setup interactions
100
- msg.submit(
101
- chat_with_character,
102
- [msg, character_selector, chatbot],
103
- [chatbot, msg]
104
  )
105
-
106
- clear.click(clear_chat, outputs=chatbot)
107
 
108
- return demo
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109
 
110
  if __name__ == "__main__":
111
- demo = create_interface()
112
  demo.launch(
113
  share=True,
114
  server_name="0.0.0.0",
 
1
  import gradio as gr
2
  import os
3
  import sys
 
4
 
5
  # Add backend to path for imports
6
  backend_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'backend')
7
  sys.path.insert(0, backend_path)
8
 
9
  from backend.models.character_manager import CharacterManager
10
+ import asyncio
11
 
12
+ # Global character manager
13
+ character_manager = None
14
+
15
+ def initialize_models():
16
+ """Initialize the character manager"""
17
+ global character_manager
18
+ if character_manager is None:
19
+ print("πŸ”„ Initializing character manager...")
20
+ character_manager = CharacterManager()
21
+ loop = asyncio.new_event_loop()
22
+ asyncio.set_event_loop(loop)
23
+ loop.run_until_complete(character_manager.initialize())
24
+ loop.close()
25
+ print("βœ… Models loaded successfully!")
26
+
27
+ def chat_with_character(message, character_id, history):
28
+ """Handle chat with character"""
29
+ if not message or not message.strip():
30
+ return history
 
 
 
31
 
32
+ # Initialize if needed
33
+ if character_manager is None:
34
+ initialize_models()
35
+
36
+ try:
37
+ # Convert history for context
38
+ conversation_history = []
39
+ if history:
 
 
 
40
  for user_msg, bot_msg in history[-3:]:
41
+ if user_msg:
42
+ conversation_history.append({"role": "user", "content": user_msg})
43
  if bot_msg:
44
  conversation_history.append({"role": "assistant", "content": bot_msg})
45
+
46
+ # Generate response
47
+ response = character_manager.generate_response(
48
+ character_id=character_id,
49
+ user_message=message,
50
+ conversation_history=conversation_history
51
+ )
52
+
53
+ # Update history
54
+ if history is None:
55
+ history = []
56
+ history.append((message, response))
57
+ return history
58
+
59
+ except Exception as e:
60
+ error_msg = f"❌ Error: {str(e)}"
61
+ if history is None:
62
+ history = []
63
+ history.append((message, error_msg))
64
+ return history
65
 
66
+ # Create simple interface with gr.Interface (most compatible)
67
+ with gr.Blocks(title="🎭 Roleplay Chat Box") as demo:
68
+ gr.HTML("<h1 style='text-align: center'>🎭 Roleplay Chat Box</h1>")
69
+ gr.HTML("<p style='text-align: center'>Chat with AI characters!</p>")
70
 
71
+ with gr.Row():
72
+ character_dropdown = gr.Dropdown(
73
+ choices=["moses", "samsung_employee", "jinx"],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
  value="moses",
75
  label="Choose Character"
76
  )
77
+
78
+ chatbot = gr.Chatbot(label="Chat")
79
+
80
+ with gr.Row():
81
+ msg = gr.Textbox(
82
+ label="Your Message",
83
+ placeholder="Type your message here...",
84
+ lines=2
 
 
 
85
  )
 
 
86
 
87
+ with gr.Row():
88
+ submit = gr.Button("Send", variant="primary")
89
+ clear = gr.Button("Clear")
90
+
91
+ # Event handlers
92
+ submit.click(
93
+ fn=chat_with_character,
94
+ inputs=[msg, character_dropdown, chatbot],
95
+ outputs=chatbot
96
+ ).then(
97
+ lambda: "",
98
+ outputs=msg
99
+ )
100
+
101
+ msg.submit(
102
+ fn=chat_with_character,
103
+ inputs=[msg, character_dropdown, chatbot],
104
+ outputs=chatbot
105
+ ).then(
106
+ lambda: "",
107
+ outputs=msg
108
+ )
109
+
110
+ clear.click(lambda: None, outputs=chatbot)
111
 
112
  if __name__ == "__main__":
 
113
  demo.launch(
114
  share=True,
115
  server_name="0.0.0.0",
requirements.txt CHANGED
@@ -7,8 +7,8 @@ datasets>=2.14.0
7
  huggingface-hub>=0.19.0
8
  safetensors>=0.4.0
9
 
10
- # Gradio for Hugging Face Spaces - pinned to avoid schema errors
11
- gradio==3.50.2
12
 
13
  # Backend API
14
  fastapi>=0.104.0
 
7
  huggingface-hub>=0.19.0
8
  safetensors>=0.4.0
9
 
10
+ # Gradio for Hugging Face Spaces - using ultra-stable version
11
+ gradio==3.40.1
12
 
13
  # Backend API
14
  fastapi>=0.104.0