Leonardo commited on
Commit
48fe67a
·
verified ·
1 Parent(s): c6c5ccc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +95 -23
app.py CHANGED
@@ -3,6 +3,9 @@ import os
3
  import re
4
  import shutil
5
  from typing import Optional
 
 
 
6
 
7
  from dotenv import load_dotenv
8
  from huggingface_hub import login
@@ -146,7 +149,7 @@ class ToolRegistry:
146
  def load_web_tools(model, browser, text_limit=20000):
147
  """Initialize and return web-related tools."""
148
  return [
149
- GoogleSearchTool(provider="serper"),
150
  VisitTool(browser),
151
  PageUpTool(browser),
152
  PageDownTool(browser),
@@ -176,8 +179,8 @@ def create_agent():
176
  # Initialize model
177
  model = LiteLLMModel(
178
  custom_role_conversions=custom_role_conversions,
179
- model_id="openrouter/perplexity/r1-1776", # currently serving:
180
- ) # DEEPSEEK = openrouter/perplexity/r1-1776 <--- boss model
181
 
182
  # Initialize tools
183
  text_limit = 30000
@@ -278,6 +281,7 @@ class GradioUI:
278
  for msg in stream_to_gradio(
279
  session_state["agent"], task=prompt, reset_agent_memory=False
280
  ):
 
281
  messages.append(msg)
282
  yield messages # Yield messages after each step
283
  yield messages # Yield messages one last time
@@ -286,6 +290,48 @@ class GradioUI:
286
  print(f"Error in interaction: {str(e)}")
287
  raise
288
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
289
  def upload_file(
290
  self,
291
  file,
@@ -385,30 +431,14 @@ class GradioUI:
385
  # Default case if no clear indicators
386
  return "Desktop"
387
 
388
- def launch(self, **kwargs):
389
- """Launch the Gradio UI with responsive layout."""
390
- with gr.Blocks(theme="ocean", fill_height=True) as demo:
391
- # Different layouts for mobile and computer devices
392
- @gr.render()
393
- def layout(request: gr.Request):
394
- device = self.detect_device(request)
395
- print(f"device - {device}")
396
- # Render layout with sidebar
397
- if device == "Desktop":
398
- return self._create_desktop_layout()
399
- else:
400
- return self._create_mobile_layout()
401
-
402
- demo.queue(max_size=20).launch(
403
- debug=True, **kwargs
404
- ) # Add queue with reasonable size
405
-
406
  def _create_desktop_layout(self):
407
  """Create the desktop layout with sidebar."""
408
  with gr.Blocks(fill_height=True) as sidebar_demo:
409
  with gr.Sidebar():
410
- gr.Markdown("""#OpenDeepResearch - 3theSmolagents!
411
- Model_id: R1-1776""")
 
 
412
  with gr.Group():
413
  gr.Markdown("**What's on your mind mate?**", container=True)
414
  text_input = gr.Textbox(
@@ -432,6 +462,13 @@ class GradioUI:
432
  [upload_status, file_uploads_log],
433
  )
434
 
 
 
 
 
 
 
 
435
  gr.HTML("<br><br><h4><center>Powered by:</center></h4>")
436
  with gr.Row():
437
  gr.HTML(
@@ -514,6 +551,11 @@ class GradioUI:
514
  )
515
  launch_research_btn = gr.Button("Run", variant="primary")
516
 
 
 
 
 
 
517
  self._connect_event_handlers(
518
  text_input,
519
  launch_research_btn,
@@ -577,6 +619,36 @@ class GradioUI:
577
  [text_input, launch_research_btn],
578
  )
579
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
580
 
581
  # ------------------------ Execution ------------------------
582
  def main():
 
3
  import re
4
  import shutil
5
  from typing import Optional
6
+ import io
7
+ import zipfile
8
+ from datetime import datetime
9
 
10
  from dotenv import load_dotenv
11
  from huggingface_hub import login
 
149
  def load_web_tools(model, browser, text_limit=20000):
150
  """Initialize and return web-related tools."""
151
  return [
152
+ GoogleSearchTool(provider="serper"),
153
  VisitTool(browser),
154
  PageUpTool(browser),
155
  PageDownTool(browser),
 
179
  # Initialize model
180
  model = LiteLLMModel(
181
  custom_role_conversions=custom_role_conversions,
182
+ model_id="openrouter/perplexity/r1-1776", # currently serving:
183
+ ) # DEEPSEEK = openrouter/perplexity/r1-1776 <--- boss model
184
 
185
  # Initialize tools
186
  text_limit = 30000
 
281
  for msg in stream_to_gradio(
282
  session_state["agent"], task=prompt, reset_agent_memory=False
283
  ):
284
+ msg = self.track_generated_files(msg, session_state)
285
  messages.append(msg)
286
  yield messages # Yield messages after each step
287
  yield messages # Yield messages one last time
 
290
  print(f"Error in interaction: {str(e)}")
291
  raise
292
 
293
+ def track_generated_files(self, message, session_state):
294
+ """Track file paths in session state for later export"""
295
+ if isinstance(message, gr.ChatMessage) and isinstance(message.content, dict):
296
+ if "image" in message.content:
297
+ file_path = message.content["image"]
298
+ session_state.setdefault("generated_files", []).append(file_path)
299
+ elif "audio" in message.content:
300
+ file_path = message.content["audio"]
301
+ session_state.setdefault("generated_files", []).append(file_path)
302
+ return message
303
+
304
+ def export_chat(self, chat_history):
305
+ """Export conversation history as markdown file"""
306
+ md_content = "# Conversation History\n\n"
307
+ for msg in chat_history:
308
+ role = "User" if msg.role == "user" else "Assistant"
309
+ content = msg.content
310
+ if isinstance(content, dict):
311
+ if "image" in content:
312
+ content = f"![Generated Image]({content['image']})"
313
+ elif "audio" in content:
314
+ content = f"🔊 [Audio File]({content['audio']})"
315
+ md_content += f"**{role}**: {content}\n\n"
316
+
317
+ filename = f"conversation-{datetime.now().strftime('%Y%m%d-%H%M%S')}.md"
318
+ return md_content.encode("utf-8"), filename
319
+
320
+ def export_files(self, session_state):
321
+ """Package generated media files into a zip"""
322
+ if not session_state.get("generated_files"):
323
+ return None
324
+
325
+ zip_buffer = io.BytesIO()
326
+ with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zf:
327
+ for file_path in session_state["generated_files"]:
328
+ if os.path.exists(file_path):
329
+ zf.write(file_path, os.path.basename(file_path))
330
+
331
+ zip_buffer.seek(0)
332
+ filename = f"generated-files-{datetime.now().strftime('%Y%m%d-%H%M%S')}.zip"
333
+ return zip_buffer.getvalue(), filename
334
+
335
  def upload_file(
336
  self,
337
  file,
 
431
  # Default case if no clear indicators
432
  return "Desktop"
433
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
434
  def _create_desktop_layout(self):
435
  """Create the desktop layout with sidebar."""
436
  with gr.Blocks(fill_height=True) as sidebar_demo:
437
  with gr.Sidebar():
438
+ gr.Markdown(
439
+ """#OpenDeepResearch - 3theSmolagents!
440
+ Model_id: R1-1776"""
441
+ )
442
  with gr.Group():
443
  gr.Markdown("**What's on your mind mate?**", container=True)
444
  text_input = gr.Textbox(
 
462
  [upload_status, file_uploads_log],
463
  )
464
 
465
+ # Add download buttons row
466
+ with gr.Row():
467
+ self.chat_download = gr.DownloadButton("💾 Save Chat", visible=True)
468
+ self.file_download = gr.DownloadButton(
469
+ "📦 Export Media", visible=True
470
+ )
471
+
472
  gr.HTML("<br><br><h4><center>Powered by:</center></h4>")
473
  with gr.Row():
474
  gr.HTML(
 
551
  )
552
  launch_research_btn = gr.Button("Run", variant="primary")
553
 
554
+ # Add compact mobile download buttons
555
+ with gr.Row():
556
+ self.chat_download = gr.DownloadButton("💾 Chat", visible=True)
557
+ self.file_download = gr.DownloadButton("📦 Media", visible=True)
558
+
559
  self._connect_event_handlers(
560
  text_input,
561
  launch_research_btn,
 
619
  [text_input, launch_research_btn],
620
  )
621
 
622
+ def launch(self, **kwargs):
623
+ """Launch the Gradio UI with responsive layout."""
624
+ with gr.Blocks(theme="ocean", fill_height=True) as demo:
625
+ # Different layouts for mobile and computer devices
626
+ @gr.render()
627
+ def layout(request: gr.Request):
628
+ device = self.detect_device(request)
629
+ print(f"device - {device}")
630
+ # Render layout with sidebar
631
+ if device == "Desktop":
632
+ return self._create_desktop_layout()
633
+ else:
634
+ return self._create_mobile_layout()
635
+
636
+ # Configure download button click handlers
637
+ self.chat_download.click(
638
+ self.export_chat,
639
+ inputs=[chatbot],
640
+ outputs=gr.File(label="Chat History"),
641
+ )
642
+ self.file_download.click(
643
+ self.export_files,
644
+ inputs=[session_state],
645
+ outputs=gr.File(label="Media Files"),
646
+ )
647
+
648
+ demo.queue(max_size=20).launch(
649
+ debug=True, **kwargs
650
+ ) # Add queue with reasonable size
651
+
652
 
653
  # ------------------------ Execution ------------------------
654
  def main():