mohamedelfeky-mo commited on
Commit
3d56892
·
verified ·
1 Parent(s): 7af577f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +82 -143
app.py CHANGED
@@ -1,84 +1,44 @@
1
- from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool
 
2
  import datetime
3
- import requests
4
  import pytz
5
  import yaml
6
- from tools.final_answer import FinalAnswerTool
7
- from tools.visit_webpage import VisitWebpageTool
8
- #from tools.web_shearch import DuckDuckGoSearchTool
9
- from smolagents import GradioUI
10
  import tempfile
11
  import gradio as gr
12
  import os
13
- from tools.create_presentation import create_presentation
14
 
 
 
 
15
 
16
- '''
17
- # Below is an example of a tool that does nothing. Amaze us with your creativity !
18
- @tool
19
- def my_custom_tool(x:str, y:int)-> int: #it's import to specify the return type
20
- #Keep this format for the description / args / args description but feel free to modify the tool
21
- """A tool that does nothing yet
22
- Args:
23
- arg1: the first argument
24
- arg2: the second argument
25
- """
26
- return "What magic will you build ?"
27
-
28
- @tool
29
- def get_current_time_in_timezone(timezone: str) -> str:
30
- """A tool that fetches the current local time in a specified timezone.
31
- Args:
32
- timezone: A string representing a valid timezone (e.g., 'America/New_York').
33
- """
34
- try:
35
- # Create timezone object
36
- tz = pytz.timezone(timezone)
37
- # Get current time in that timezone
38
- local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
39
- return f"The current local time in {timezone} is: {local_time}"
40
- except Exception as e:
41
- return f"Error fetching time for timezone '{timezone}': {str(e)}"
42
 
43
- '''
 
 
44
  @tool
45
  def create_document(text: str, format: str = "docx") -> str:
46
- """Creates a document with the provided text and allows download.
47
-
48
- Args:
49
- text: The text content to write to the document
50
- format: The output format, either 'docx' or 'pdf'
51
- """
52
  try:
53
  import docx
54
  from docx.shared import Pt
55
-
56
- # Create a temp directory to store files
57
  temp_dir = tempfile.mkdtemp()
58
-
59
- # Create a new document
60
  doc = docx.Document()
61
-
62
- # Add a heading
63
- doc.add_heading('Generated Document', 0)
64
-
65
- # Set font style for regular text
66
- style = doc.styles['Normal']
67
  font = style.font
68
- font.name = 'Calibri'
69
  font.size = Pt(11)
70
-
71
- # Add paragraphs from the input text
72
- # Split by newlines to maintain paragraph structure
73
- for paragraph in text.split('\n'):
74
- if paragraph.strip(): # Skip empty paragraphs
75
  doc.add_paragraph(paragraph)
76
-
77
- # Save the document
78
  docx_path = os.path.join(temp_dir, "generated_document.docx")
79
  doc.save(docx_path)
80
-
81
- # Convert to PDF if requested
82
  if format.lower() == "pdf":
83
  try:
84
  from docx2pdf import convert
@@ -86,124 +46,103 @@ def create_document(text: str, format: str = "docx") -> str:
86
  convert(docx_path, pdf_path)
87
  return pdf_path
88
  except ImportError:
89
- return f"PDF conversion requires docx2pdf package. Document saved as DOCX instead at: {docx_path}"
90
-
91
  return docx_path
92
-
93
  except Exception as e:
94
  return f"Error creating document: {str(e)}"
95
 
96
- # Custom file download tool to help with file handling
97
- @tool
98
- def get_file_download_link(file_path: str) -> str:
99
- """Creates a download link for a file.
100
-
101
- Args:
102
- file_path: Path to the file that should be made available for download
103
- """
104
- if not os.path.exists(file_path):
105
- return f"Error: File not found at {file_path}"
106
-
107
- # Get file extension and set up appropriate mime type
108
- _, file_extension = os.path.splitext(file_path)
109
- mime_types = {
110
- '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
111
- '.pdf': 'application/pdf',
112
- }
113
- mime_type = mime_types.get(file_extension.lower(), 'application/octet-stream')
114
-
115
- # Return information that can be used by the agent to instruct the user
116
- return f"File ready for download: {os.path.basename(file_path)} ({mime_type})"
117
-
118
 
 
 
 
119
  final_answer = FinalAnswerTool()
120
- #web_search=DuckDuckGoSearchTool()
121
- visit_webpage=VisitWebpageTool()
122
-
123
- # If the agent does not answer, the model is overloaded, please use another model or the following Hugging Face Endpoint that also contains qwen2.5 coder:
124
- # model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud'
125
 
126
- # Load LLM
127
  model = HfApiModel(
128
  max_tokens=2096,
129
  temperature=0.5,
130
- model_id='Qwen/Qwen3-235B-A22B', # it is possible that this model may be overloaded
131
- custom_role_conversions=None,
132
  )
133
 
134
-
135
- # Import tool from Hub
136
- image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
137
-
138
- with open("prompts.yaml", 'r') as stream:
139
  prompt_templates = yaml.safe_load(stream)
140
 
141
- #,web_search
142
-
143
  agent = CodeAgent(
144
  model=model,
145
- tools=[final_answer,visit_webpage,create_document,get_file_download_link,create_presentation,], ## add your tools here (don't remove final answer)
 
 
 
 
 
146
  max_steps=6,
147
- verbosity_level=1,
148
- grammar=None,
149
- planning_interval=None,
150
- name=None,
151
- description=None,
152
- prompt_templates=prompt_templates
153
  )
154
 
155
- # Custom Gradio UI with file download capability
 
 
 
156
  class CustomGradioUI(GradioUI):
157
  def build_interface(self):
158
  with gr.Blocks() as interface:
159
- with gr.Row():
160
- with gr.Column(scale=1):
161
- gr.Markdown("# AI Assistant")
162
-
163
  chatbot = gr.Chatbot(height=600)
164
  msg = gr.Textbox(
165
- placeholder="Ask me anything...",
166
  container=False,
167
- scale=7,
168
  )
169
-
170
- # Add a file download component
171
- download_btn = gr.Button("Download File", visible=False)
172
- file_output = gr.File(label="Generated Document", visible=False)
173
-
174
- # Store the latest file path
175
  self._latest_file_path = None
176
-
177
  def respond(message, chat_history):
178
  agent_response = self.agent.run(message)
179
  chat_history.append((message, agent_response))
180
-
181
- # Check if response contains a file path
182
- import re
183
- file_paths = re.findall(r'File ready for download: .+ \((application/[\w.+-]+)\)', agent_response)
184
-
185
- show_download = False
186
  self._latest_file_path = None
187
-
188
- # Look for generated file paths in the response
189
- paths = re.findall(r'/tmp/\w+/generated_document\.(docx|pdf)', agent_response)
190
- if paths:
191
- self._latest_file_path = paths[0]
 
 
 
 
 
192
  show_download = True
193
-
194
- return chat_history, gr.Button.update(visible=show_download), gr.File.update(visible=False)
195
-
 
 
 
 
196
  def prepare_download():
197
- if self._latest_file_path:
198
- return gr.File.update(value=self._latest_file_path, visible=True)
 
 
 
199
  return gr.File.update(visible=False)
200
-
201
- # Connect the components
202
  msg.submit(respond, [msg, chatbot], [chatbot, download_btn, file_output])
203
  download_btn.click(prepare_download, [], [file_output])
204
-
205
- gr.Markdown("Powered by smolagents and Qwen")
206
-
207
  return interface
208
 
209
- CustomGradioUI(agent).launch()
 
 
 
 
 
 
1
+ from smolagents import CodeAgent, HfApiModel, load_tool, tool
2
+ from smolagents import GradioUI
3
  import datetime
 
4
  import pytz
5
  import yaml
 
 
 
 
6
  import tempfile
7
  import gradio as gr
8
  import os
9
+ import re
10
 
11
+ from tools.final_answer import FinalAnswerTool
12
+ from tools.visit_webpage import VisitWebpageTool
13
+ from tools.create_presentation import create_presentation
14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
+ # =========================
17
+ # DOCUMENT CREATION TOOL
18
+ # =========================
19
  @tool
20
  def create_document(text: str, format: str = "docx") -> str:
21
+ """Creates a document with the provided text and allows download."""
 
 
 
 
 
22
  try:
23
  import docx
24
  from docx.shared import Pt
25
+
 
26
  temp_dir = tempfile.mkdtemp()
 
 
27
  doc = docx.Document()
28
+ doc.add_heading("Generated Document", 0)
29
+
30
+ style = doc.styles["Normal"]
 
 
 
31
  font = style.font
32
+ font.name = "Calibri"
33
  font.size = Pt(11)
34
+
35
+ for paragraph in text.split("\n"):
36
+ if paragraph.strip():
 
 
37
  doc.add_paragraph(paragraph)
38
+
 
39
  docx_path = os.path.join(temp_dir, "generated_document.docx")
40
  doc.save(docx_path)
41
+
 
42
  if format.lower() == "pdf":
43
  try:
44
  from docx2pdf import convert
 
46
  convert(docx_path, pdf_path)
47
  return pdf_path
48
  except ImportError:
49
+ return docx_path
50
+
51
  return docx_path
52
+
53
  except Exception as e:
54
  return f"Error creating document: {str(e)}"
55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
 
57
+ # =========================
58
+ # AGENT SETUP
59
+ # =========================
60
  final_answer = FinalAnswerTool()
61
+ visit_webpage = VisitWebpageTool()
 
 
 
 
62
 
 
63
  model = HfApiModel(
64
  max_tokens=2096,
65
  temperature=0.5,
66
+ model_id="Qwen/Qwen3-235B-A22B",
 
67
  )
68
 
69
+ with open("prompts.yaml", "r") as stream:
 
 
 
 
70
  prompt_templates = yaml.safe_load(stream)
71
 
 
 
72
  agent = CodeAgent(
73
  model=model,
74
+ tools=[
75
+ final_answer,
76
+ visit_webpage,
77
+ create_document,
78
+ create_presentation, # ✅ PPTX tool
79
+ ],
80
  max_steps=6,
81
+ verbosity_level=0,
82
+ prompt_templates=prompt_templates,
 
 
 
 
83
  )
84
 
85
+
86
+ # =========================
87
+ # CUSTOM GRADIO UI
88
+ # =========================
89
  class CustomGradioUI(GradioUI):
90
  def build_interface(self):
91
  with gr.Blocks() as interface:
92
+ gr.Markdown("# AI Assistant")
93
+
 
 
94
  chatbot = gr.Chatbot(height=600)
95
  msg = gr.Textbox(
96
+ placeholder="Ask me anything and press Enter…",
97
  container=False,
 
98
  )
99
+
100
+ download_btn = gr.Button("⬇️ Download File", visible=False)
101
+ file_output = gr.File(label="Generated File", visible=False)
102
+
 
 
103
  self._latest_file_path = None
104
+
105
  def respond(message, chat_history):
106
  agent_response = self.agent.run(message)
107
  chat_history.append((message, agent_response))
108
+
 
 
 
 
 
109
  self._latest_file_path = None
110
+ show_download = False
111
+
112
+ # Detect ANY generated file (docx, pdf, pptx)
113
+ match = re.search(
114
+ r"(/tmp/.+?/generated_[\w-]+\.(docx|pdf|pptx))",
115
+ agent_response,
116
+ )
117
+
118
+ if match:
119
+ self._latest_file_path = match.group(1)
120
  show_download = True
121
+
122
+ return (
123
+ chat_history,
124
+ gr.Button.update(visible=show_download),
125
+ gr.File.update(visible=False),
126
+ )
127
+
128
  def prepare_download():
129
+ if self._latest_file_path and os.path.exists(self._latest_file_path):
130
+ return gr.File.update(
131
+ value=self._latest_file_path,
132
+ visible=True,
133
+ )
134
  return gr.File.update(visible=False)
135
+
 
136
  msg.submit(respond, [msg, chatbot], [chatbot, download_btn, file_output])
137
  download_btn.click(prepare_download, [], [file_output])
138
+
139
+ gr.Markdown("Powered by smolagents + Qwen")
140
+
141
  return interface
142
 
143
+
144
+ # =========================
145
+ # 🚀 ENTRY POINT (CRITICAL)
146
+ # =========================
147
+ if __name__ == "__main__":
148
+ CustomGradioUI(agent).launch()