Spaces:
Sleeping
Sleeping
Commit
·
d0cc95b
1
Parent(s):
ae7a494
Added image generation and translator tool
Browse files- app.py +178 -2
- requirements.txt +1 -0
app.py
CHANGED
|
@@ -33,6 +33,181 @@ def get_current_time_in_timezone(timezone: str) -> str:
|
|
| 33 |
except Exception as e:
|
| 34 |
return f"Error fetching time for timezone '{timezone}': {str(e)}"
|
| 35 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
final_answer = FinalAnswerTool()
|
| 38 |
|
|
@@ -42,7 +217,8 @@ final_answer = FinalAnswerTool()
|
|
| 42 |
model = HfApiModel(
|
| 43 |
max_tokens=2096,
|
| 44 |
temperature=0.5,
|
| 45 |
-
model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may be overloaded
|
|
|
|
| 46 |
custom_role_conversions=None,
|
| 47 |
)
|
| 48 |
|
|
@@ -55,7 +231,7 @@ with open("prompts.yaml", 'r') as stream:
|
|
| 55 |
|
| 56 |
agent = CodeAgent(
|
| 57 |
model=model,
|
| 58 |
-
tools=[final_answer], ## add your tools here (don't remove final answer)
|
| 59 |
max_steps=6,
|
| 60 |
verbosity_level=1,
|
| 61 |
grammar=None,
|
|
|
|
| 33 |
except Exception as e:
|
| 34 |
return f"Error fetching time for timezone '{timezone}': {str(e)}"
|
| 35 |
|
| 36 |
+
@tool
|
| 37 |
+
def image_generator(prompt: str) -> str:
|
| 38 |
+
"""A tool that generates an image based on a text prompt.
|
| 39 |
+
Args:
|
| 40 |
+
prompt: A text description of the image to generate.
|
| 41 |
+
"""
|
| 42 |
+
try:
|
| 43 |
+
# Use the imported image generation tool
|
| 44 |
+
image_path = image_generation_tool(prompt=prompt)
|
| 45 |
+
return image_path
|
| 46 |
+
except Exception as e:
|
| 47 |
+
return f"Error generating image: {str(e)}"
|
| 48 |
+
|
| 49 |
+
@tool
|
| 50 |
+
def translator(question: str, src_lang: str, tgt_lang: str) -> str:
|
| 51 |
+
"""A tool that translates text from one language to another.
|
| 52 |
+
Args:
|
| 53 |
+
question: The text to translate.
|
| 54 |
+
src_lang: The source language of the text.
|
| 55 |
+
tgt_lang: The target language to translate to.
|
| 56 |
+
"""
|
| 57 |
+
try:
|
| 58 |
+
# Import the deep_translator library
|
| 59 |
+
from deep_translator import GoogleTranslator
|
| 60 |
+
|
| 61 |
+
# Map common language names to language codes if needed
|
| 62 |
+
language_map = {
|
| 63 |
+
"english": "en", "french": "fr", "spanish": "es", "german": "de",
|
| 64 |
+
"italian": "it", "portuguese": "pt", "russian": "ru", "japanese": "ja",
|
| 65 |
+
"chinese": "zh-CN", "korean": "ko", "arabic": "ar", "hindi": "hi"
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
# Convert language names to codes if necessary
|
| 69 |
+
src = language_map.get(src_lang.lower(), src_lang.lower())
|
| 70 |
+
tgt = language_map.get(tgt_lang.lower(), tgt_lang.lower())
|
| 71 |
+
|
| 72 |
+
# Perform the translation
|
| 73 |
+
translated = GoogleTranslator(source=src, target=tgt).translate(question)
|
| 74 |
+
|
| 75 |
+
return translated
|
| 76 |
+
except Exception as e:
|
| 77 |
+
return f"Error translating text: {str(e)}"
|
| 78 |
+
|
| 79 |
+
@tool
|
| 80 |
+
def search(query: str) -> str:
|
| 81 |
+
"""A tool that searches the web for information and returns a list of relevant pages.
|
| 82 |
+
Args:
|
| 83 |
+
query: The search query.
|
| 84 |
+
"""
|
| 85 |
+
try:
|
| 86 |
+
# Use DuckDuckGo search tool that's already imported
|
| 87 |
+
search_tool = DuckDuckGoSearchTool()
|
| 88 |
+
results = search_tool(query)
|
| 89 |
+
|
| 90 |
+
# Check if results is empty
|
| 91 |
+
if not results:
|
| 92 |
+
return f"No result found for query \"{query}\"."
|
| 93 |
+
|
| 94 |
+
# Handle different return formats
|
| 95 |
+
formatted_results = []
|
| 96 |
+
|
| 97 |
+
# Check if results is a list of strings or objects
|
| 98 |
+
if isinstance(results, list):
|
| 99 |
+
if results and isinstance(results[0], str):
|
| 100 |
+
# Handle list of strings
|
| 101 |
+
formatted_results = results[:5] # Limit to top 5 results
|
| 102 |
+
else:
|
| 103 |
+
# Try to handle objects with title/url attributes
|
| 104 |
+
for result in results[:5]:
|
| 105 |
+
try:
|
| 106 |
+
if hasattr(result, 'title') and hasattr(result, 'url'):
|
| 107 |
+
formatted_results.append(f"[{result.title}]({result.url})")
|
| 108 |
+
elif isinstance(result, dict) and 'title' in result and 'url' in result:
|
| 109 |
+
formatted_results.append(f"[{result['title']}]({result['url']})")
|
| 110 |
+
else:
|
| 111 |
+
formatted_results.append(str(result))
|
| 112 |
+
except:
|
| 113 |
+
formatted_results.append(str(result))
|
| 114 |
+
elif isinstance(results, str):
|
| 115 |
+
# Handle string result
|
| 116 |
+
return results
|
| 117 |
+
|
| 118 |
+
return f"Found {len(formatted_results)} pages:\n" + "\n".join(formatted_results)
|
| 119 |
+
except Exception as e:
|
| 120 |
+
return f"Error searching the web: {str(e)}"
|
| 121 |
+
|
| 122 |
+
@tool
|
| 123 |
+
def web_search(query: str) -> str:
|
| 124 |
+
"""A tool that searches the web for information and returns detailed results.
|
| 125 |
+
Args:
|
| 126 |
+
query: The search query.
|
| 127 |
+
"""
|
| 128 |
+
try:
|
| 129 |
+
# Use DuckDuckGo search tool that's already imported
|
| 130 |
+
search_tool = DuckDuckGoSearchTool()
|
| 131 |
+
results = search_tool(query)
|
| 132 |
+
|
| 133 |
+
# Check if results is empty
|
| 134 |
+
if not results:
|
| 135 |
+
return f"No results found for query \"{query}\"."
|
| 136 |
+
|
| 137 |
+
# Handle different return formats
|
| 138 |
+
if isinstance(results, str):
|
| 139 |
+
return results
|
| 140 |
+
|
| 141 |
+
combined_info = ""
|
| 142 |
+
|
| 143 |
+
# Process up to 3 results
|
| 144 |
+
count = 0
|
| 145 |
+
for result in results:
|
| 146 |
+
if count >= 3:
|
| 147 |
+
break
|
| 148 |
+
|
| 149 |
+
try:
|
| 150 |
+
if hasattr(result, 'snippet'):
|
| 151 |
+
combined_info += f"Result {count+1}: {result.snippet}\n\n"
|
| 152 |
+
elif isinstance(result, dict) and 'snippet' in result:
|
| 153 |
+
combined_info += f"Result {count+1}: {result['snippet']}\n\n"
|
| 154 |
+
elif hasattr(result, 'title'):
|
| 155 |
+
combined_info += f"Result {count+1}: {result.title}\n\n"
|
| 156 |
+
elif isinstance(result, dict) and 'title' in result:
|
| 157 |
+
combined_info += f"Result {count+1}: {result['title']}\n\n"
|
| 158 |
+
else:
|
| 159 |
+
combined_info += f"Result {count+1}: {str(result)}\n\n"
|
| 160 |
+
count += 1
|
| 161 |
+
except:
|
| 162 |
+
combined_info += f"Result {count+1}: {str(result)}\n\n"
|
| 163 |
+
count += 1
|
| 164 |
+
|
| 165 |
+
return combined_info.strip() if combined_info else "No detailed information found."
|
| 166 |
+
except Exception as e:
|
| 167 |
+
return f"Error searching the web: {str(e)}"
|
| 168 |
+
|
| 169 |
+
@tool
|
| 170 |
+
def visit_webpage(url: str) -> str:
|
| 171 |
+
"""A tool that visits a webpage and returns its content.
|
| 172 |
+
Args:
|
| 173 |
+
url: The URL of the webpage to visit.
|
| 174 |
+
"""
|
| 175 |
+
try:
|
| 176 |
+
# Add headers to mimic a browser request
|
| 177 |
+
headers = {
|
| 178 |
+
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36'
|
| 179 |
+
}
|
| 180 |
+
|
| 181 |
+
# Make the request
|
| 182 |
+
response = requests.get(url, headers=headers, timeout=10)
|
| 183 |
+
response.raise_for_status()
|
| 184 |
+
|
| 185 |
+
# Try to extract main content using a simple approach
|
| 186 |
+
from bs4 import BeautifulSoup
|
| 187 |
+
soup = BeautifulSoup(response.text, 'html.parser')
|
| 188 |
+
|
| 189 |
+
# Remove script and style elements
|
| 190 |
+
for script in soup(["script", "style"]):
|
| 191 |
+
script.extract()
|
| 192 |
+
|
| 193 |
+
# Get text
|
| 194 |
+
text = soup.get_text()
|
| 195 |
+
|
| 196 |
+
# Break into lines and remove leading and trailing space on each
|
| 197 |
+
lines = (line.strip() for line in text.splitlines())
|
| 198 |
+
# Break multi-headlines into a line each
|
| 199 |
+
chunks = (phrase.strip() for line in lines for phrase in line.split(" "))
|
| 200 |
+
# Remove blank lines
|
| 201 |
+
text = '\n'.join(chunk for chunk in chunks if chunk)
|
| 202 |
+
|
| 203 |
+
# Limit the length of the response
|
| 204 |
+
max_length = 5000
|
| 205 |
+
if len(text) > max_length:
|
| 206 |
+
text = text[:max_length] + "... (content truncated)"
|
| 207 |
+
|
| 208 |
+
return text
|
| 209 |
+
except Exception as e:
|
| 210 |
+
return f"Error visiting webpage: {str(e)}"
|
| 211 |
|
| 212 |
final_answer = FinalAnswerTool()
|
| 213 |
|
|
|
|
| 217 |
model = HfApiModel(
|
| 218 |
max_tokens=2096,
|
| 219 |
temperature=0.5,
|
| 220 |
+
#model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may be overloaded
|
| 221 |
+
model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud',
|
| 222 |
custom_role_conversions=None,
|
| 223 |
)
|
| 224 |
|
|
|
|
| 231 |
|
| 232 |
agent = CodeAgent(
|
| 233 |
model=model,
|
| 234 |
+
tools=[final_answer, image_generator, translator, get_current_time_in_timezone, search, web_search, visit_webpage], ## add your tools here (don't remove final answer)
|
| 235 |
max_steps=6,
|
| 236 |
verbosity_level=1,
|
| 237 |
grammar=None,
|
requirements.txt
CHANGED
|
@@ -3,3 +3,4 @@ smolagents
|
|
| 3 |
requests
|
| 4 |
duckduckgo_search
|
| 5 |
pandas
|
|
|
|
|
|
| 3 |
requests
|
| 4 |
duckduckgo_search
|
| 5 |
pandas
|
| 6 |
+
deep_translator
|