ButterM40 commited on
Commit
cad5bb4
ยท
1 Parent(s): e981624

Fix: Simplified Gradio interface for v3.x compatibility

Browse files
Files changed (3) hide show
  1. app.py +69 -196
  2. app_fixed.py +113 -0
  3. requirements.txt +2 -2
app.py CHANGED
@@ -1,239 +1,112 @@
1
  import gradio as gr
2
- import requests
3
- import json
4
- import time
5
  import os
6
  import sys
7
- from typing import List, Tuple
8
 
9
  # Add backend to path for imports
10
  backend_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'backend')
11
  sys.path.insert(0, backend_path)
12
 
13
  from backend.models.character_manager import CharacterManager
14
- from backend.config import settings
15
 
16
- class RoleplayChatInterface:
17
  def __init__(self):
18
- """Initialize the Roleplay Chat Interface"""
19
  self.character_manager = None
20
- self.available_characters = ["moses", "samsung_employee", "jinx"]
21
- self.character_info = {
22
- "moses": {
23
- "name": "Moses",
24
- "description": "๐Ÿ“š Wise biblical figure offering guidance and wisdom",
25
- "avatar": "๐Ÿ‘จโ€๐Ÿซ"
26
- },
27
- "samsung_employee": {
28
- "name": "Samsung Employee",
29
- "description": "๐Ÿ’ผ Professional tech support specialist",
30
- "avatar": "๐Ÿ‘จโ€๐Ÿ’ผ"
31
- },
32
- "jinx": {
33
- "name": "Jinx",
34
- "description": "๐ŸŽญ Chaotic and energetic character from Arcane",
35
- "avatar": "๐Ÿ”ฎ"
36
- }
37
- }
38
 
39
- async def initialize_models(self):
40
- """Initialize the character manager"""
41
  try:
 
42
  self.character_manager = CharacterManager()
43
- await self.character_manager.initialize()
44
- return "โœ… Models loaded successfully!"
45
- except Exception as e:
46
- return f"โŒ Failed to load models: {str(e)}"
47
-
48
- def initialize_models_sync(self):
49
- """Synchronous wrapper for model initialization"""
50
- import asyncio
51
- try:
52
  loop = asyncio.new_event_loop()
53
  asyncio.set_event_loop(loop)
54
- result = loop.run_until_complete(self.initialize_models())
55
  loop.close()
56
- return result
 
 
57
  except Exception as e:
 
58
  return f"โŒ Failed to load models: {str(e)}"
59
 
60
- def get_character_response(self, message: str, character_id: str, history: List[Tuple[str, str]]) -> Tuple[List[Tuple[str, str]], str]:
61
- """Generate character response and update chat history"""
62
- if not self.character_manager:
63
- return history + [(message, "โš ๏ธ Models are still loading. Please try again in a moment...")], ""
64
-
65
  if not message.strip():
66
  return history, ""
67
 
 
 
 
68
  try:
69
- # Convert Gradio history to conversation format
70
  conversation_history = []
71
- for user_msg, assistant_msg in history[-3:]: # Last 3 exchanges for context
72
  conversation_history.append({"role": "user", "content": user_msg})
73
- if assistant_msg:
74
- conversation_history.append({"role": "assistant", "content": assistant_msg})
75
 
76
- # Generate response using character manager (correct method signature)
77
  response = self.character_manager.generate_response(
78
  character_id=character_id,
79
  user_message=message,
80
  conversation_history=conversation_history
81
  )
82
 
83
- # Update chat history
84
- new_history = history + [(message, response)]
85
- return new_history, ""
86
 
87
  except Exception as e:
88
- error_response = f"โŒ Error generating response: {str(e)}"
89
- new_history = history + [(message, error_response)]
90
- return new_history, ""
 
 
 
 
91
 
92
- def get_character_options(self):
93
- """Get character dropdown options"""
94
- options = []
95
- for char_id in self.available_characters:
96
- info = self.character_info[char_id]
97
- label = f"{info['avatar']} {info['name']}"
98
- options.append((label, char_id))
99
- return options
100
 
101
- def create_interface(self):
102
- """Create the Gradio interface"""
 
 
 
 
 
103
 
104
- with gr.Blocks(
105
- title="๐ŸŽญ Roleplay Chat Box",
106
- theme=gr.themes.Soft(primary_hue="purple"),
107
- css="""
108
- .character-info {
109
- background: linear-gradient(45deg, #667eea 0%, #764ba2 100%);
110
- color: white;
111
- padding: 1rem;
112
- border-radius: 10px;
113
- margin-bottom: 1rem;
114
- }
115
- .chat-container {
116
- max-height: 500px;
117
- overflow-y: auto;
118
- }
119
- """) as iface:
120
-
121
- gr.Markdown("# ๐ŸŽญ Roleplay Chat Box")
122
- gr.Markdown("Chat with different AI characters, each with unique personalities and expertise!")
123
-
124
- with gr.Row():
125
- with gr.Column(scale=1):
126
- # Character Selection
127
- gr.Markdown("## ๐Ÿ‘ฅ Choose Your Character")
128
- character_dropdown = gr.Dropdown(
129
- choices=self.get_character_options(),
130
- value="moses",
131
- label="Select Character",
132
- interactive=True
133
- )
134
-
135
- # Character Info Display
136
- character_info_display = gr.HTML(
137
- value=self._get_character_info_html("moses"),
138
- elem_classes=["character-info"]
139
- )
140
-
141
- # Update character info when dropdown changes
142
- def update_character_info(character_id):
143
- return self._get_character_info_html(character_id)
144
-
145
- character_dropdown.change(
146
- fn=update_character_info,
147
- inputs=[character_dropdown],
148
- outputs=[character_info_display]
149
- )
150
-
151
- with gr.Column(scale=2):
152
- # Chat Interface
153
- gr.Markdown("## ๐Ÿ’ฌ Chat")
154
- chatbot = gr.Chatbot(
155
- height=400,
156
- show_label=False,
157
- container=True,
158
- elem_classes=["chat-container"]
159
- )
160
-
161
- with gr.Row():
162
- msg_input = gr.Textbox(
163
- placeholder="Type your message here...",
164
- show_label=False,
165
- scale=4,
166
- lines=1
167
- )
168
- send_btn = gr.Button("Send ๐Ÿ“จ", scale=1, variant="primary")
169
- clear_btn = gr.Button("Clear ๐Ÿ—‘๏ธ", scale=1)
170
-
171
- # Initialize models on startup
172
- gr.Markdown("### ๐Ÿ”„ Status")
173
- status_display = gr.Textbox(value="Loading models...", label="System Status", interactive=False)
174
-
175
- # Chat functionality
176
- def respond_and_clear(message, character_id, history):
177
- new_history, _ = self.get_character_response(message, character_id, history)
178
- return new_history, ""
179
-
180
- # Send message on button click or Enter
181
- send_btn.click(
182
- fn=respond_and_clear,
183
- inputs=[msg_input, character_dropdown, chatbot],
184
- outputs=[chatbot, msg_input]
185
- )
186
-
187
- msg_input.submit(
188
- fn=respond_and_clear,
189
- inputs=[msg_input, character_dropdown, chatbot],
190
- outputs=[chatbot, msg_input]
191
- )
192
-
193
- # Clear chat
194
- clear_btn.click(
195
- fn=lambda: ([], "Chat cleared!"),
196
- outputs=[chatbot, status_display]
197
- )
198
-
199
- # Initialize models when interface loads
200
- def init_models():
201
- if not self.character_manager:
202
- return self.initialize_models_sync()
203
- else:
204
- return "โœ… Models already loaded!"
205
-
206
- iface.load(
207
- fn=init_models,
208
- outputs=[status_display]
209
- )
210
 
211
- return iface
212
-
213
- def _get_character_info_html(self, character_id: str) -> str:
214
- """Generate HTML for character information"""
215
- if character_id not in self.character_info:
216
- return "<div>Character not found</div>"
217
 
218
- info = self.character_info[character_id]
219
- return f"""
220
- <div style="text-align: center;">
221
- <div style="font-size: 3rem; margin-bottom: 0.5rem;">{info['avatar']}</div>
222
- <h3 style="margin: 0.5rem 0; color: white;">{info['name']}</h3>
223
- <p style="margin: 0; opacity: 0.9;">{info['description']}</p>
224
- </div>
225
- """
226
-
227
- # Create and launch the interface
228
- def create_demo():
229
- chat_interface = RoleplayChatInterface()
230
- return chat_interface.create_interface()
231
 
232
- # For Hugging Face Spaces
233
  if __name__ == "__main__":
234
- demo = create_demo()
235
- demo.launch(
236
- server_name="0.0.0.0",
237
- server_port=7860,
238
- share=False # Not supported on Hugging Face Spaces
239
- )
 
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()
 
 
 
 
app_fixed.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import sys
4
+ import asyncio
5
+ from typing import List, Tuple
6
+
7
+ # Add backend to path for imports
8
+ backend_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'backend')
9
+ sys.path.insert(0, backend_path)
10
+
11
+ from backend.models.character_manager import CharacterManager
12
+
13
+ class RoleplayChatApp:
14
+ def __init__(self):
15
+ """Initialize the Roleplay Chat App"""
16
+ self.character_manager = None
17
+
18
+ def initialize_models(self):
19
+ """Initialize the character manager synchronously"""
20
+ try:
21
+ print("๐Ÿ”„ Initializing character manager...")
22
+ self.character_manager = CharacterManager()
23
+
24
+ # Use sync initialization
25
+ loop = asyncio.new_event_loop()
26
+ asyncio.set_event_loop(loop)
27
+ loop.run_until_complete(self.character_manager.initialize())
28
+ loop.close()
29
+
30
+ print("โœ… Models loaded successfully!")
31
+ return "โœ… Models loaded successfully!"
32
+ except Exception as e:
33
+ print(f"โŒ Failed to load models: {str(e)}")
34
+ return f"โŒ Failed to load models: {str(e)}"
35
+
36
+ def chat_fn(self, message, character_id, history):
37
+ """Handle chat functionality"""
38
+ if not message.strip():
39
+ return history, ""
40
+
41
+ if not self.character_manager:
42
+ self.initialize_models()
43
+
44
+ try:
45
+ # Convert history for context
46
+ conversation_history = []
47
+ for user_msg, bot_msg in history[-3:]:
48
+ conversation_history.append({"role": "user", "content": user_msg})
49
+ if bot_msg:
50
+ conversation_history.append({"role": "assistant", "content": bot_msg})
51
+
52
+ # Generate response
53
+ response = self.character_manager.generate_response(
54
+ character_id=character_id,
55
+ user_message=message,
56
+ conversation_history=conversation_history
57
+ )
58
+
59
+ # Update history
60
+ history.append((message, response))
61
+ return history, ""
62
+
63
+ except Exception as e:
64
+ error_msg = f"โŒ Error: {str(e)}"
65
+ history.append((message, error_msg))
66
+ return history, ""
67
+
68
+ def create_interface():
69
+ """Create a simple Gradio interface"""
70
+ app = RoleplayChatApp()
71
+
72
+ # Simple function-based interface
73
+ def chat_with_character(message, character, history):
74
+ return app.chat_fn(message, character, history)
75
+
76
+ def clear_chat():
77
+ return []
78
+
79
+ # Create simple interface
80
+ with gr.Blocks() as demo:
81
+ gr.Markdown("# ๐ŸŽญ Roleplay Chat Box")
82
+ gr.Markdown("Chat with AI characters!")
83
+
84
+ # Character selector
85
+ character_selector = gr.Radio(
86
+ choices=[
87
+ "moses",
88
+ "samsung_employee",
89
+ "jinx"
90
+ ],
91
+ value="moses",
92
+ label="Choose Character"
93
+ )
94
+
95
+ # Chat interface
96
+ chatbot = gr.Chatbot()
97
+ msg = gr.Textbox(label="Your Message", placeholder="Type here...")
98
+ clear = gr.Button("Clear Chat")
99
+
100
+ # Setup interactions
101
+ msg.submit(
102
+ chat_with_character,
103
+ [msg, character_selector, chatbot],
104
+ [chatbot, msg]
105
+ )
106
+
107
+ clear.click(clear_chat, outputs=chatbot)
108
+
109
+ return demo
110
+
111
+ if __name__ == "__main__":
112
+ demo = create_interface()
113
+ demo.launch()
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 - use older stable version to avoid schema bugs
11
- gradio==4.20.0
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 - use much older stable version
11
+ gradio==3.50.0
12
 
13
  # Backend API
14
  fastapi>=0.104.0