PeterPinetree commited on
Commit
0c8ac4f
·
verified ·
1 Parent(s): 529ba07

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -64
app.py CHANGED
@@ -124,11 +124,8 @@ def create_story_summary(chat_history):
124
  return None
125
 
126
  story_text = ""
127
- for msg in chat_history:
128
- if msg["role"] == "user":
129
- story_text += f"User: {msg['content']}\n"
130
- else:
131
- story_text += f"Story: {msg['content']}\n\n"
132
 
133
  summary_instruction = {
134
  "role": "system",
@@ -136,8 +133,8 @@ def create_story_summary(chat_history):
136
  }
137
  return summary_instruction
138
 
139
- # Modified function to handle message format
140
- def respond(message: str, chat_history: List[Dict], genre: Optional[str] = None, use_full_memory: bool = True) -> Tuple[str, List[Dict]]:
141
  """Generate a response based on the current message and conversation history."""
142
  if not message.strip():
143
  return "", chat_history
@@ -147,10 +144,13 @@ def respond(message: str, chat_history: List[Dict], genre: Optional[str] = None,
147
  api_messages = [{"role": "system", "content": get_enhanced_system_prompt(genre)}]
148
  logging.debug(f"System Message: {api_messages[0]}")
149
 
150
- # Add chat history - convert to API format
151
  if chat_history and use_full_memory:
152
- for msg in chat_history[-MEMORY_WINDOW*2:]: # Multiply by 2 since we have user and assistant messages
153
- api_messages.append({"role": msg["role"], "content": msg["content"]})
 
 
 
154
  logging.debug(f"Chat History Messages: {api_messages[1:]}")
155
 
156
  # Add current message
@@ -171,20 +171,14 @@ def respond(message: str, chat_history: List[Dict], genre: Optional[str] = None,
171
  bot_message = response.choices[0].message.content
172
  logging.debug(f"Bot Response: {bot_message[:100]}...") # First 100 chars
173
 
174
- # Update history with proper message format
175
- updated_history = chat_history + [
176
- {"role": "user", "content": message},
177
- {"role": "assistant", "content": bot_message}
178
- ]
179
  return "", updated_history
180
 
181
  except Exception as e:
182
  logging.error("Error in respond function", exc_info=True)
183
  error_msg = f"Story magic temporarily interrupted. Please try again. (Error: {str(e)})"
184
- return "", chat_history + [
185
- {"role": "user", "content": message},
186
- {"role": "assistant", "content": error_msg}
187
- ]
188
 
189
  def save_story(chat_history):
190
  """Convert chat history to markdown for download"""
@@ -192,45 +186,17 @@ def save_story(chat_history):
192
  return "No story to save yet!"
193
 
194
  story_text = "# My Interactive Adventure\n\n"
195
- for msg in chat_history:
196
- if msg["role"] == "user":
197
- story_text += f"**Player:** {msg['content']}\n\n"
198
- elif msg["role"] == "assistant":
199
- story_text += f"**Story:** {msg['content']}\n\n---\n\n"
200
 
201
  return story_text
202
 
203
- # Add this function to get SVG for avatar
204
- def get_storyteller_avatar():
205
- """Return SVG for storyteller avatar"""
206
- return """
207
- <svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
208
- <!-- Wizard hat -->
209
- <path d="M50 10 L70 40 L30 40 Z" fill="#4b0082" stroke="#000" stroke-width="1"/>
210
- <!-- Hat band -->
211
- <rect x="30" y="38" width="40" height="5" fill="#ffd700" stroke="#000" stroke-width="1"/>
212
- <!-- Hat stars -->
213
- <path d="M40 25 L42 30 L37 27 L43 27 L38 30 Z" fill="#ffd700"/>
214
- <path d="M60 30 L62 35 L57 32 L63 32 L58 35 Z" fill="#ffd700"/>
215
- <!-- Face -->
216
- <circle cx="50" cy="60" r="20" fill="#fbe8d3" stroke="#000" stroke-width="1"/>
217
- <!-- Eyes -->
218
- <ellipse cx="40" cy="55" rx="3" ry="4" fill="#fff" stroke="#000" stroke-width="1"/>
219
- <ellipse cx="60" cy="55" rx="3" ry="4" fill="#fff" stroke="#000" stroke-width="1"/>
220
- <circle cx="40" cy="55" r="1" fill="#000"/>
221
- <circle cx="60" cy="55" r="1" fill="#000"/>
222
- <!-- Eyebrows -->
223
- <path d="M36 50 Q40 48 44 50" fill="none" stroke="#000" stroke-width="1"/>
224
- <path d="M56 50 Q60 48 64 50" fill="none" stroke="#000" stroke-width="1"/>
225
- <!-- Beard -->
226
- <path d="M30 60 Q50 90 70 60" fill="#7c6e5c" stroke="#000" stroke-width="1"/>
227
- <!-- Mouth -->
228
- <path d="M45 65 Q50 70 55 65" fill="none" stroke="#000" stroke-width="1"/>
229
- <!-- Sparkle -->
230
- <circle cx="75" cy="25" r="3" fill="#ffd700"/>
231
- <path d="M75 20 L75 30 M70 25 L80 25" stroke="#ffd700" stroke-width="1"/>
232
- </svg>
233
- """
234
 
235
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
236
  gr.Markdown("# 🔮 Interactive Story Time")
@@ -238,21 +204,21 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
238
  status_message = gr.Markdown("Ready to begin your adventure...", visible=True)
239
  gr.Markdown("Create a completely unique literary world, one choice at a time. Dare to explore the unknown.")
240
 
241
- wizard_avatar = get_storyteller_avatar()
 
242
 
243
  with gr.Row():
244
  with gr.Column(scale=3):
245
- # Chat window + user input - FIXED MESSAGE FORMAT
246
  chatbot = gr.Chatbot(
247
  height=500,
248
  bubble_full_width=True,
249
  show_copy_button=True,
250
- avatar_images=(None, wizard_avatar), # Added wizard avatar
251
- type="chatbot", # Changed from "messages" to "chatbot"
252
  container=True,
253
  scale=1,
254
  min_width=800,
255
- value=[],
256
  render=True
257
  )
258
  msg = gr.Textbox(
@@ -317,10 +283,7 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
317
 
318
  except Exception as e:
319
  error_msg = f"Story magic temporarily interrupted. Please try again. (Error: {str(e)})"
320
- return "", history + [
321
- {"role": "user", "content": starter_text},
322
- {"role": "assistant", "content": error_msg}
323
- ]
324
 
325
  # Simplified button connections
326
  for starter_button in starter_buttons:
 
124
  return None
125
 
126
  story_text = ""
127
+ for user_msg, bot_msg in chat_history:
128
+ story_text += f"User: {user_msg}\nStory: {bot_msg}\n\n"
 
 
 
129
 
130
  summary_instruction = {
131
  "role": "system",
 
133
  }
134
  return summary_instruction
135
 
136
+ # Modified function for proper Gradio format (tuples)
137
+ def respond(message: str, chat_history: List[Tuple[str, str]], genre: Optional[str] = None, use_full_memory: bool = True) -> Tuple[str, List[Tuple[str, str]]]:
138
  """Generate a response based on the current message and conversation history."""
139
  if not message.strip():
140
  return "", chat_history
 
144
  api_messages = [{"role": "system", "content": get_enhanced_system_prompt(genre)}]
145
  logging.debug(f"System Message: {api_messages[0]}")
146
 
147
+ # Add chat history - convert from tuples to API format
148
  if chat_history and use_full_memory:
149
+ for user_msg, bot_msg in chat_history[-MEMORY_WINDOW:]:
150
+ api_messages.extend([
151
+ {"role": "user", "content": str(user_msg)},
152
+ {"role": "assistant", "content": str(bot_msg)}
153
+ ])
154
  logging.debug(f"Chat History Messages: {api_messages[1:]}")
155
 
156
  # Add current message
 
171
  bot_message = response.choices[0].message.content
172
  logging.debug(f"Bot Response: {bot_message[:100]}...") # First 100 chars
173
 
174
+ # Update history using tuple format (user_msg, bot_msg)
175
+ updated_history = chat_history + [(message, bot_message)]
 
 
 
176
  return "", updated_history
177
 
178
  except Exception as e:
179
  logging.error("Error in respond function", exc_info=True)
180
  error_msg = f"Story magic temporarily interrupted. Please try again. (Error: {str(e)})"
181
+ return "", chat_history + [(message, error_msg)]
 
 
 
182
 
183
  def save_story(chat_history):
184
  """Convert chat history to markdown for download"""
 
186
  return "No story to save yet!"
187
 
188
  story_text = "# My Interactive Adventure\n\n"
189
+ for user_msg, bot_msg in chat_history:
190
+ story_text += f"**Player:** {user_msg}\n\n"
191
+ story_text += f"**Story:** {bot_msg}\n\n---\n\n"
 
 
192
 
193
  return story_text
194
 
195
+ # Add this function to get a custom avatar image URL
196
+ def get_storyteller_avatar_url():
197
+ """Get a URL for the storyteller avatar from a free image service"""
198
+ # Using an external wizard avatar image
199
+ return "https://api.dicebear.com/7.x/bottts/svg?seed=wizard&backgroundColor=b6e3f4&eyes=bulging"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
200
 
201
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
202
  gr.Markdown("# 🔮 Interactive Story Time")
 
204
  status_message = gr.Markdown("Ready to begin your adventure...", visible=True)
205
  gr.Markdown("Create a completely unique literary world, one choice at a time. Dare to explore the unknown.")
206
 
207
+ # Get avatar URL
208
+ wizard_avatar = get_storyteller_avatar_url()
209
 
210
  with gr.Row():
211
  with gr.Column(scale=3):
212
+ # Chat window + user input - USING TUPLES FORMAT
213
  chatbot = gr.Chatbot(
214
  height=500,
215
  bubble_full_width=True,
216
  show_copy_button=True,
217
+ avatar_images=(None, wizard_avatar),
 
218
  container=True,
219
  scale=1,
220
  min_width=800,
221
+ value=[], # Empty list of tuples
222
  render=True
223
  )
224
  msg = gr.Textbox(
 
283
 
284
  except Exception as e:
285
  error_msg = f"Story magic temporarily interrupted. Please try again. (Error: {str(e)})"
286
+ return "", history + [(starter_text, error_msg)]
 
 
 
287
 
288
  # Simplified button connections
289
  for starter_button in starter_buttons: