Nils Durner commited on
Commit
7902830
·
1 Parent(s): e7c2e79

file download

Browse files
Files changed (1) hide show
  1. app.py +31 -2
app.py CHANGED
@@ -185,8 +185,8 @@ with gr.Blocks() as demo:
185
  dmp_btn.click(dump, inputs=[chatbot], outputs=[txt_dmp])
186
 
187
  with gr.Accordion("Import/Export", open = False):
188
- import_button = gr.UploadButton("Import")
189
- export_button = gr.Button("Export")
190
  export_button.click(lambda: None, [chatbot], js="""
191
  (chat_history) => {
192
  // Convert the chat history to a JSON string
@@ -204,6 +204,35 @@ with gr.Blocks() as demo:
204
  URL.revokeObjectURL(url);
205
  }
206
  """)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
207
  import_button.upload(import_history, inputs=[chatbot, import_button], outputs=[chatbot])
208
 
209
  txt_msg = txt.submit(add_text, [chatbot, txt], [chatbot, txt], queue=False).then(
 
185
  dmp_btn.click(dump, inputs=[chatbot], outputs=[txt_dmp])
186
 
187
  with gr.Accordion("Import/Export", open = False):
188
+ import_button = gr.UploadButton("History Import")
189
+ export_button = gr.Button("History Export")
190
  export_button.click(lambda: None, [chatbot], js="""
191
  (chat_history) => {
192
  // Convert the chat history to a JSON string
 
204
  URL.revokeObjectURL(url);
205
  }
206
  """)
207
+ dl_button = gr.Button("File download")
208
+ dl_button.click(lambda: None, [chatbot], js="""
209
+ (chat_history) => {
210
+ // Attempt to extract content enclosed in backticks with an optional filename
211
+ const contentRegex = /```(\\S*\\.(\\S+))?\\n?([\\s\\S]*?)```/;
212
+ const match = contentRegex.exec(chat_history[chat_history.length - 1][1]);
213
+ if (match && match[3]) {
214
+ // Extract the content and the file extension
215
+ const content = match[3];
216
+ const fileExtension = match[2] || 'txt'; // Default to .txt if extension is not found
217
+ const filename = match[1] || `download.${fileExtension}`;
218
+ // Create a Blob from the content
219
+ const blob = new Blob([content], {type: `text/${fileExtension}`});
220
+ // Create a download link for the Blob
221
+ const url = URL.createObjectURL(blob);
222
+ const a = document.createElement('a');
223
+ a.href = url;
224
+ // If the filename from the chat history doesn't have an extension, append the default
225
+ a.download = filename.includes('.') ? filename : `${filename}.${fileExtension}`;
226
+ document.body.appendChild(a);
227
+ a.click();
228
+ document.body.removeChild(a);
229
+ URL.revokeObjectURL(url);
230
+ } else {
231
+ // Inform the user if the content is malformed or missing
232
+ alert('Sorry, the file content could not be found or is in an unrecognized format.');
233
+ }
234
+ }
235
+ """)
236
  import_button.upload(import_history, inputs=[chatbot, import_button], outputs=[chatbot])
237
 
238
  txt_msg = txt.submit(add_text, [chatbot, txt], [chatbot, txt], queue=False).then(