shukdevdattaEX commited on
Commit
4a42aed
·
verified ·
1 Parent(s): 7bc10be

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +152 -16
app.py CHANGED
@@ -95,7 +95,7 @@ def save_conversation():
95
  global conversation_history
96
 
97
  if not conversation_history:
98
- return "No conversation to save."
99
 
100
  try:
101
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
@@ -106,9 +106,31 @@ def save_conversation():
106
  }
107
  json.dump(conv_data, f)
108
  f.write("\n")
109
- return "Conversation saved successfully!"
 
 
 
110
  except Exception as e:
111
- return f"Error saving conversation: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
 
113
  # Function to load previous conversations
114
  def load_conversations():
@@ -121,9 +143,10 @@ def load_conversations():
121
  for i, conv in enumerate(conversations):
122
  conv_text += f"\n{'='*50}\nConversation {i + 1}\n{'='*50}\n"
123
  timestamp = conv.get("timestamp", "Unknown time")
124
- conv_text += f"Timestamp: {timestamp}\n\n"
 
125
 
126
- messages = conv.get("messages", conv) # Handle old format
127
  for message in messages:
128
  role = message.get('role', 'unknown')
129
  content = message.get('content', '')
@@ -134,6 +157,72 @@ def load_conversations():
134
  return f"Error loading conversations: {str(e)}"
135
  return "No previous conversations found."
136
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
137
  # Function to clear current conversation
138
  def clear_conversation():
139
  global conversation_history
@@ -145,10 +234,15 @@ def delete_all_conversations():
145
  try:
146
  if os.path.exists("conversations.json"):
147
  os.remove("conversations.json")
148
- return "All conversations deleted successfully!"
149
- return "No conversations to delete."
150
  except Exception as e:
151
- return f"Error deleting conversations: {str(e)}"
 
 
 
 
 
152
 
153
  # Create Gradio interface
154
  with gr.Blocks(title="Chat with Documents 💬 📚") as demo:
@@ -182,7 +276,8 @@ with gr.Blocks(title="Chat with Documents 💬 📚") as demo:
182
  with gr.Column(scale=3):
183
  chatbot = gr.Chatbot(
184
  label="Chat",
185
- height=400
 
186
  )
187
  msg = gr.Textbox(
188
  label="Your Question",
@@ -198,14 +293,38 @@ with gr.Blocks(title="Chat with Documents 💬 📚") as demo:
198
  save_status = gr.Textbox(label="Save Status", interactive=False)
199
 
200
  with gr.Column(scale=1):
201
- gr.Markdown("### Previous Conversations")
202
- load_convs_btn = gr.Button("Load Previous Conversations")
 
 
 
 
203
  convs_display = gr.Textbox(
204
- label="Conversation History",
205
- lines=20,
206
  interactive=False
207
  )
208
- delete_all_btn = gr.Button("Delete All Conversations", variant="stop")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
209
  delete_status = gr.Textbox(label="Delete Status", interactive=False)
210
 
211
  # Event handlers
@@ -234,7 +353,7 @@ with gr.Blocks(title="Chat with Documents 💬 📚") as demo:
234
 
235
  save_btn.click(
236
  fn=save_conversation,
237
- outputs=save_status
238
  )
239
 
240
  load_convs_btn.click(
@@ -242,9 +361,26 @@ with gr.Blocks(title="Chat with Documents 💬 📚") as demo:
242
  outputs=convs_display
243
  )
244
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
245
  delete_all_btn.click(
246
  fn=delete_all_conversations,
247
- outputs=delete_status
248
  )
249
 
250
  if __name__ == "__main__":
 
95
  global conversation_history
96
 
97
  if not conversation_history:
98
+ return "No conversation to save.", gr.update()
99
 
100
  try:
101
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
 
106
  }
107
  json.dump(conv_data, f)
108
  f.write("\n")
109
+
110
+ # Update the dropdown choices
111
+ choices = get_conversation_choices()
112
+ return "Conversation saved successfully!", gr.update(choices=choices)
113
  except Exception as e:
114
+ return f"Error saving conversation: {str(e)}", gr.update()
115
+
116
+ # Function to get conversation choices for dropdown
117
+ def get_conversation_choices():
118
+ if os.path.exists("conversations.json"):
119
+ try:
120
+ with open("conversations.json", "r") as f:
121
+ conversations = [json.loads(line) for line in f]
122
+
123
+ choices = []
124
+ for i, conv in enumerate(conversations):
125
+ timestamp = conv.get("timestamp", "Unknown time")
126
+ # Format: "1. 2024-01-13 14:30:45"
127
+ formatted_time = datetime.strptime(timestamp, "%Y%m%d_%H%M%S").strftime("%Y-%m-%d %H:%M:%S")
128
+ choices.append(f"{i + 1}. {formatted_time}")
129
+
130
+ return choices
131
+ except Exception as e:
132
+ return []
133
+ return []
134
 
135
  # Function to load previous conversations
136
  def load_conversations():
 
143
  for i, conv in enumerate(conversations):
144
  conv_text += f"\n{'='*50}\nConversation {i + 1}\n{'='*50}\n"
145
  timestamp = conv.get("timestamp", "Unknown time")
146
+ formatted_time = datetime.strptime(timestamp, "%Y%m%d_%H%M%S").strftime("%Y-%m-%d %H:%M:%S")
147
+ conv_text += f"Timestamp: {formatted_time}\n\n"
148
 
149
+ messages = conv.get("messages", conv)
150
  for message in messages:
151
  role = message.get('role', 'unknown')
152
  content = message.get('content', '')
 
157
  return f"Error loading conversations: {str(e)}"
158
  return "No previous conversations found."
159
 
160
+ # Function to view selected conversation
161
+ def view_selected_conversation(selection):
162
+ if not selection or selection == "Select a conversation":
163
+ return "Please select a conversation to view."
164
+
165
+ try:
166
+ # Extract conversation number from selection
167
+ conv_number = int(selection.split(".")[0]) - 1
168
+
169
+ if os.path.exists("conversations.json"):
170
+ with open("conversations.json", "r") as f:
171
+ conversations = [json.loads(line) for line in f]
172
+
173
+ if conv_number < len(conversations):
174
+ conv = conversations[conv_number]
175
+ conv_text = f"{'='*50}\n"
176
+ timestamp = conv.get("timestamp", "Unknown time")
177
+ formatted_time = datetime.strptime(timestamp, "%Y%m%d_%H%M%S").strftime("%Y-%m-%d %H:%M:%S")
178
+ conv_text += f"Conversation Timestamp: {formatted_time}\n"
179
+ conv_text += f"{'='*50}\n\n"
180
+
181
+ messages = conv.get("messages", conv)
182
+ for message in messages:
183
+ role = message.get('role', 'unknown')
184
+ content = message.get('content', '')
185
+ conv_text += f"{role.upper()}: {content}\n\n"
186
+
187
+ return conv_text
188
+
189
+ return "Conversation not found."
190
+ except Exception as e:
191
+ return f"Error viewing conversation: {str(e)}"
192
+
193
+ # Function to delete selected conversation
194
+ def delete_selected_conversation(selection):
195
+ if not selection or selection == "Select a conversation":
196
+ return "Please select a conversation to delete.", gr.update()
197
+
198
+ try:
199
+ # Extract conversation number from selection
200
+ conv_number = int(selection.split(".")[0]) - 1
201
+
202
+ if os.path.exists("conversations.json"):
203
+ with open("conversations.json", "r") as f:
204
+ conversations = [json.loads(line) for line in f]
205
+
206
+ if conv_number < len(conversations):
207
+ # Remove the selected conversation
208
+ del conversations[conv_number]
209
+
210
+ # Write back the remaining conversations
211
+ with open("conversations.json", "w") as f:
212
+ for conv in conversations:
213
+ json.dump(conv, f)
214
+ f.write("\n")
215
+
216
+ # Update dropdown choices
217
+ choices = get_conversation_choices()
218
+ return f"Conversation {conv_number + 1} deleted successfully!", gr.update(choices=choices, value="Select a conversation")
219
+ else:
220
+ return "Conversation not found.", gr.update()
221
+
222
+ return "No conversations file found.", gr.update()
223
+ except Exception as e:
224
+ return f"Error deleting conversation: {str(e)}", gr.update()
225
+
226
  # Function to clear current conversation
227
  def clear_conversation():
228
  global conversation_history
 
234
  try:
235
  if os.path.exists("conversations.json"):
236
  os.remove("conversations.json")
237
+ return "All conversations deleted successfully!", gr.update(choices=[], value="Select a conversation")
238
+ return "No conversations to delete.", gr.update()
239
  except Exception as e:
240
+ return f"Error deleting conversations: {str(e)}", gr.update()
241
+
242
+ # Function to refresh dropdown
243
+ def refresh_dropdown():
244
+ choices = get_conversation_choices()
245
+ return gr.update(choices=choices)
246
 
247
  # Create Gradio interface
248
  with gr.Blocks(title="Chat with Documents 💬 📚") as demo:
 
276
  with gr.Column(scale=3):
277
  chatbot = gr.Chatbot(
278
  label="Chat",
279
+ height=400,
280
+ type="messages"
281
  )
282
  msg = gr.Textbox(
283
  label="Your Question",
 
293
  save_status = gr.Textbox(label="Save Status", interactive=False)
294
 
295
  with gr.Column(scale=1):
296
+ gr.Markdown("### Conversation Management")
297
+
298
+ with gr.Row():
299
+ load_convs_btn = gr.Button("Load All Conversations")
300
+ refresh_btn = gr.Button("🔄 Refresh List")
301
+
302
  convs_display = gr.Textbox(
303
+ label="All Conversations",
304
+ lines=10,
305
  interactive=False
306
  )
307
+
308
+ gr.Markdown("### Select & Manage Conversation")
309
+
310
+ conversation_dropdown = gr.Dropdown(
311
+ label="Select Conversation",
312
+ choices=get_conversation_choices(),
313
+ value="Select a conversation",
314
+ interactive=True
315
+ )
316
+
317
+ view_btn = gr.Button("View Selected", variant="secondary")
318
+ selected_conv_display = gr.Textbox(
319
+ label="Selected Conversation",
320
+ lines=10,
321
+ interactive=False
322
+ )
323
+
324
+ with gr.Row():
325
+ delete_selected_btn = gr.Button("Delete Selected", variant="stop")
326
+ delete_all_btn = gr.Button("Delete All", variant="stop")
327
+
328
  delete_status = gr.Textbox(label="Delete Status", interactive=False)
329
 
330
  # Event handlers
 
353
 
354
  save_btn.click(
355
  fn=save_conversation,
356
+ outputs=[save_status, conversation_dropdown]
357
  )
358
 
359
  load_convs_btn.click(
 
361
  outputs=convs_display
362
  )
363
 
364
+ refresh_btn.click(
365
+ fn=refresh_dropdown,
366
+ outputs=conversation_dropdown
367
+ )
368
+
369
+ view_btn.click(
370
+ fn=view_selected_conversation,
371
+ inputs=conversation_dropdown,
372
+ outputs=selected_conv_display
373
+ )
374
+
375
+ delete_selected_btn.click(
376
+ fn=delete_selected_conversation,
377
+ inputs=conversation_dropdown,
378
+ outputs=[delete_status, conversation_dropdown]
379
+ )
380
+
381
  delete_all_btn.click(
382
  fn=delete_all_conversations,
383
+ outputs=[delete_status, conversation_dropdown]
384
  )
385
 
386
  if __name__ == "__main__":