jarguello76 commited on
Commit
6e46110
·
verified ·
1 Parent(s): 8232071

Update tools.py

Browse files
Files changed (1) hide show
  1. tools.py +358 -17
tools.py CHANGED
@@ -1,17 +1,22 @@
1
- #Tools
2
- from smolagents import DuckDuckGoSearchTool
3
  from smolagents import Tool
4
  import random
5
  from huggingface_hub import list_models
6
-
 
 
 
 
 
 
 
 
7
 
8
  # Initialize the DuckDuckGo search tool
9
- #search_tool = DuckDuckGoSearchTool()
10
-
11
 
12
  class WeatherInfoTool(Tool):
13
  name = "weather_info"
14
- description = "Fetches dummy weather information for a given location."
15
  inputs = {
16
  "location": {
17
  "type": "string",
@@ -21,15 +26,20 @@ class WeatherInfoTool(Tool):
21
  output_type = "string"
22
 
23
  def forward(self, location: str):
24
- # Dummy weather data
25
- weather_conditions = [
26
- {"condition": "Rainy", "temp_c": 15},
27
- {"condition": "Clear", "temp_c": 25},
28
- {"condition": "Windy", "temp_c": 20}
29
- ]
30
- # Randomly select a weather condition
31
- data = random.choice(weather_conditions)
32
- return f"Weather in {location}: {data['condition']}, {data['temp_c']}°C"
 
 
 
 
 
33
 
34
  class HubStatsTool(Tool):
35
  name = "hub_stats"
@@ -46,11 +56,342 @@ class HubStatsTool(Tool):
46
  try:
47
  # List models from the specified author, sorted by downloads
48
  models = list(list_models(author=author, sort="downloads", direction=-1, limit=1))
49
-
50
  if models:
51
  model = models[0]
52
  return f"The most downloaded model by {author} is {model.id} with {model.downloads:,} downloads."
53
  else:
54
  return f"No models found for author {author}."
55
  except Exception as e:
56
- return f"Error fetching models for {author}: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  from smolagents import Tool
2
  import random
3
  from huggingface_hub import list_models
4
+ import requests
5
+ import os
6
+ import sqlite3
7
+ from googletrans import Translator
8
+ from gtts import gTTS
9
+ import speech_recognition as sr
10
+ import cv2
11
+ import numpy as np
12
+ from textblob import TextBlob
13
 
14
  # Initialize the DuckDuckGo search tool
15
+ # search_tool = DuckDuckGoSearchTool()
 
16
 
17
  class WeatherInfoTool(Tool):
18
  name = "weather_info"
19
+ description = "Fetches weather information for a given location."
20
  inputs = {
21
  "location": {
22
  "type": "string",
 
26
  output_type = "string"
27
 
28
  def forward(self, location: str):
29
+ # Use a real weather API here
30
+ api_key = os.getenv("WEATHER_API_KEY")
31
+ if not api_key:
32
+ return "Weather API key not found."
33
+
34
+ try:
35
+ response = requests.get(f"http://api.weatherapi.com/v1/current.json?key={api_key}&q={location}")
36
+ response.raise_for_status()
37
+ data = response.json()
38
+ condition = data["current"]["condition"]["text"]
39
+ temp_c = data["current"]["temp_c"]
40
+ return f"Weather in {location}: {condition}, {temp_c}°C"
41
+ except Exception as e:
42
+ return f"Error fetching weather for {location}: {str(e)}"
43
 
44
  class HubStatsTool(Tool):
45
  name = "hub_stats"
 
56
  try:
57
  # List models from the specified author, sorted by downloads
58
  models = list(list_models(author=author, sort="downloads", direction=-1, limit=1))
59
+
60
  if models:
61
  model = models[0]
62
  return f"The most downloaded model by {author} is {model.id} with {model.downloads:,} downloads."
63
  else:
64
  return f"No models found for author {author}."
65
  except Exception as e:
66
+ return f"Error fetching models for {author}: {str(e)}"
67
+
68
+ class CalculatorTool(Tool):
69
+ name = "calculator"
70
+ description = "Performs mathematical calculations."
71
+ inputs = {
72
+ "expression": {
73
+ "type": "string",
74
+ "description": "The mathematical expression to evaluate."
75
+ }
76
+ }
77
+ output_type = "string"
78
+
79
+ def forward(self, expression: str):
80
+ try:
81
+ result = eval(expression)
82
+ return f"The result of the expression '{expression}' is {result}."
83
+ except Exception as e:
84
+ return f"Error evaluating expression: {str(e)}"
85
+
86
+ class CalendarTool(Tool):
87
+ name = "calendar"
88
+ description = "Manages and retrieves information about dates and events."
89
+ inputs = {
90
+ "action": {
91
+ "type": "string",
92
+ "description": "The action to perform (e.g., 'add', 'get', 'delete')."
93
+ },
94
+ "date": {
95
+ "type": "string",
96
+ "description": "The date of the event (format: YYYY-MM-DD)."
97
+ },
98
+ "event": {
99
+ "type": "string",
100
+ "description": "The event description."
101
+ }
102
+ }
103
+ output_type = "string"
104
+
105
+ def __init__(self):
106
+ self.events = {}
107
+
108
+ def forward(self, action: str, date: str, event: str = None):
109
+ if action == "add":
110
+ self.events[date] = event
111
+ return f"Event '{event}' added to {date}."
112
+ elif action == "get":
113
+ return f"Event on {date}: {self.events.get(date, 'No event found.')}"
114
+ elif action == "delete":
115
+ if date in self.events:
116
+ del self.events[date]
117
+ return f"Event on {date} deleted."
118
+ else:
119
+ return f"No event found on {date}."
120
+ else:
121
+ return "Invalid action."
122
+
123
+ class EmailTool(Tool):
124
+ name = "email"
125
+ description = "Sends and receives emails."
126
+ inputs = {
127
+ "action": {
128
+ "type": "string",
129
+ "description": "The action to perform (e.g., 'send')."
130
+ },
131
+ "to": {
132
+ "type": "string",
133
+ "description": "The recipient's email address."
134
+ },
135
+ "subject": {
136
+ "type": "string",
137
+ "description": "The subject of the email."
138
+ },
139
+ "body": {
140
+ "type": "string",
141
+ "description": "The body of the email."
142
+ }
143
+ }
144
+ output_type = "string"
145
+
146
+ def __init__(self, smtp_server, smtp_port, email, password):
147
+ self.smtp_server = smtp_server
148
+ self.smtp_port = smtp_port
149
+ self.email = email
150
+ self.password = password
151
+
152
+ def forward(self, action: str, to: str, subject: str, body: str):
153
+ if action == "send":
154
+ try:
155
+ msg = MIMEText(body)
156
+ msg['Subject'] = subject
157
+ msg['From'] = self.email
158
+ msg['To'] = to
159
+
160
+ with smtplib.SMTP(self.smtp_server, self.smtp_port) as server:
161
+ server.starttls()
162
+ server.login(self.email, self.password)
163
+ server.sendmail(self.email, [to], msg.as_string())
164
+
165
+ return f"Email sent to {to}."
166
+ except Exception as e:
167
+ return f"Error sending email: {str(e)}"
168
+ else:
169
+ return "Invalid action."
170
+
171
+ class FileManagementTool(Tool):
172
+ name = "file_management"
173
+ description = "Handles file operations like reading, writing, and managing files."
174
+ inputs = {
175
+ "action": {
176
+ "type": "string",
177
+ "description": "The action to perform (e.g., 'read', 'write', 'delete')."
178
+ },
179
+ "file_path": {
180
+ "type": "string",
181
+ "description": "The path of the file."
182
+ },
183
+ "content": {
184
+ "type": "string",
185
+ "description": "The content to write to the file."
186
+ }
187
+ }
188
+ output_type = "string"
189
+
190
+ def forward(self, action: str, file_path: str, content: str = None):
191
+ if action == "read":
192
+ try:
193
+ with open(file_path, 'r') as file:
194
+ content = file.read()
195
+ return f"Content of {file_path}: {content}"
196
+ except Exception as e:
197
+ return f"Error reading file: {str(e)}"
198
+ elif action == "write":
199
+ try:
200
+ with open(file_path, 'w') as file:
201
+ file.write(content)
202
+ return f"Content written to {file_path}."
203
+ except Exception as e:
204
+ return f"Error writing to file: {str(e)}"
205
+ elif action == "delete":
206
+ try:
207
+ os.remove(file_path)
208
+ return f"File {file_path} deleted."
209
+ except Exception as e:
210
+ return f"Error deleting file: {str(e)}"
211
+ else:
212
+ return "Invalid action."
213
+
214
+ class DatabaseQueryTool(Tool):
215
+ name = "database_query"
216
+ description = "Interacts with databases for storing and retrieving information."
217
+ inputs = {
218
+ "action": {
219
+ "type": "string",
220
+ "description": "The action to perform (e.g., 'query', 'insert')."
221
+ },
222
+ "query": {
223
+ "type": "string",
224
+ "description": "The SQL query to execute."
225
+ }
226
+ }
227
+ output_type = "string"
228
+
229
+ def __init__(self, db_path):
230
+ self.db_path = db_path
231
+
232
+ def forward(self, action: str, query: str):
233
+ try:
234
+ conn = sqlite3.connect(self.db_path)
235
+ cursor = conn.cursor()
236
+
237
+ if action == "query":
238
+ cursor.execute(query)
239
+ results = cursor.fetchall()
240
+ return f"Query results: {results}"
241
+ elif action == "insert":
242
+ cursor.execute(query)
243
+ conn.commit()
244
+ return "Data inserted successfully."
245
+ else:
246
+ return "Invalid action."
247
+
248
+ except Exception as e:
249
+ return f"Error executing query: {str(e)}"
250
+ finally:
251
+ conn.close()
252
+
253
+ class TranslationTool(Tool):
254
+ name = "translation"
255
+ description = "Translates text between different languages."
256
+ inputs = {
257
+ "text": {
258
+ "type": "string",
259
+ "description": "The text to translate."
260
+ },
261
+ "src_lang": {
262
+ "type": "string",
263
+ "description": "The source language code."
264
+ },
265
+ "dest_lang": {
266
+ "type": "string",
267
+ "description": "The destination language code."
268
+ }
269
+ }
270
+ output_type = "string"
271
+
272
+ def forward(self, text: str, src_lang: str, dest_lang: str):
273
+ try:
274
+ translator = Translator()
275
+ translation = translator.translate(text, src=src_lang, dest=dest_lang)
276
+ return f"Translated text: {translation.text}"
277
+ except Exception as e:
278
+ return f"Error translating text: {str(e)}"
279
+
280
+ class TextToSpeechTool(Tool):
281
+ name = "text_to_speech"
282
+ description = "Converts text to speech."
283
+ inputs = {
284
+ "text": {
285
+ "type": "string",
286
+ "description": "The text to convert to speech."
287
+ }
288
+ }
289
+ output_type = "string"
290
+
291
+ def forward(self, text: str):
292
+ try:
293
+ tts = gTTS(text=text, lang='en')
294
+ tts.save("output.mp3")
295
+ return "Text converted to speech and saved as output.mp3."
296
+ except Exception as e:
297
+ return f"Error converting text to speech: {str(e)}"
298
+
299
+ class SpeechToTextTool(Tool):
300
+ name = "speech_to_text"
301
+ description = "Converts speech to text."
302
+ inputs = {
303
+ "audio_file": {
304
+ "type": "string",
305
+ "description": "The path to the audio file to convert to text."
306
+ }
307
+ }
308
+ output_type = "string"
309
+
310
+ def forward(self, audio_file: str):
311
+ try:
312
+ recognizer = sr.Recognizer()
313
+ with sr.AudioFile(audio_file) as source:
314
+ audio = recognizer.record(source)
315
+ text = recognizer.recognize_google(audio)
316
+ return f"Converted speech to text: {text}"
317
+ except Exception as e:
318
+ return f"Error converting speech to text: {str(e)}"
319
+
320
+ class ImageRecognitionTool(Tool):
321
+ name = "image_recognition"
322
+ description = "Analyzes and interprets images."
323
+ inputs = {
324
+ "image_path": {
325
+ "type": "string",
326
+ "description": "The path to the image to analyze."
327
+ }
328
+ }
329
+ output_type = "string"
330
+
331
+ def forward(self, image_path: str):
332
+ try:
333
+ image = cv2.imread(image_path)
334
+ gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
335
+ faces = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml').detectMultiScale(gray, 1.3, 5)
336
+ return f"Found {len(faces)} faces in the image."
337
+ except Exception as e:
338
+ return f"Error analyzing image: {str(e)}"
339
+
340
+ class NLPTool(Tool):
341
+ name = "nlp"
342
+ description = "Performs advanced text processing tasks like sentiment analysis, named entity recognition, etc."
343
+ inputs = {
344
+ "text": {
345
+ "type": "string",
346
+ "description": "The text to analyze."
347
+ },
348
+ "task": {
349
+ "type": "string",
350
+ "description": "The NLP task to perform (e.g., 'sentiment', 'entities')."
351
+ }
352
+ }
353
+ output_type = "string"
354
+
355
+ def forward(self, text: str, task: str):
356
+ blob = TextBlob(text)
357
+ if task == "sentiment":
358
+ sentiment = blob.sentiment
359
+ return f"Sentiment analysis: Polarity={sentiment.polarity}, Subjectivity={sentiment.subjectivity}"
360
+ elif task == "entities":
361
+ entities = blob.noun_phrases
362
+ return f"Named entities: {entities}"
363
+ else:
364
+ return "Invalid task."
365
+
366
+ class APIIntegrationTool(Tool):
367
+ name = "api_integration"
368
+ description = "Interacts with various external APIs for fetching or sending data."
369
+ inputs = {
370
+ "api_url": {
371
+ "type": "string",
372
+ "description": "The URL of the API endpoint."
373
+ },
374
+ "method": {
375
+ "type": "string",
376
+ "description": "The HTTP method to use (e.g., 'GET', 'POST')."
377
+ },
378
+ "data": {
379
+ "type": "string",
380
+ "description": "The data to send with the request."
381
+ }
382
+ }
383
+ output_type = "string"
384
+
385
+ def forward(self, api_url: str, method: str, data: str = None):
386
+ try:
387
+ if method == "GET":
388
+ response = requests.get(api_url)
389
+ elif method == "POST":
390
+ response = requests.post(api_url, json=data)
391
+ else:
392
+ return "Invalid method."
393
+
394
+ response.raise_for_status()
395
+ return f"API response: {response.json()}"
396
+ except Exception as e:
397
+ return f"Error interacting with API: {str(e)}"