hd-hg commited on
Commit
fcbe53d
·
verified ·
1 Parent(s): ae7a494

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +107 -18
app.py CHANGED
@@ -4,34 +4,123 @@ import requests
4
  import pytz
5
  import yaml
6
  from tools.final_answer import FinalAnswerTool
7
-
 
 
 
 
8
  from Gradio_UI import GradioUI
9
 
10
- # Below is an example of a tool that does nothing. Amaze us with your creativity !
 
 
11
  @tool
12
- def my_custom_tool(arg1:str, arg2:int)-> str: #it's import to specify the return type
13
- #Keep this format for the description / args / args description but feel free to modify the tool
14
- """A tool that does nothing yet
 
15
  Args:
16
- arg1: the first argument
17
- arg2: the second argument
 
 
18
  """
19
- return "What magic will you build ?"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
  @tool
22
- def get_current_time_in_timezone(timezone: str) -> str:
23
- """A tool that fetches the current local time in a specified timezone.
 
 
24
  Args:
25
- timezone: A string representing a valid timezone (e.g., 'America/New_York').
 
 
 
26
  """
 
 
27
  try:
28
- # Create timezone object
29
- tz = pytz.timezone(timezone)
30
- # Get current time in that timezone
31
- local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
32
- return f"The current local time in {timezone} is: {local_time}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  except Exception as e:
34
- return f"Error fetching time for timezone '{timezone}': {str(e)}"
35
 
36
 
37
  final_answer = FinalAnswerTool()
@@ -48,7 +137,7 @@ custom_role_conversions=None,
48
 
49
 
50
  # Import tool from Hub
51
- image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
52
 
53
  with open("prompts.yaml", 'r') as stream:
54
  prompt_templates = yaml.safe_load(stream)
 
4
  import pytz
5
  import yaml
6
  from tools.final_answer import FinalAnswerTool
7
+ from tools.web_search import DuckDuckGoSearchTool
8
+ import duckduckgo_search
9
+ import requests
10
+ from bs4 import BeautifulSoup
11
+ from typing import List, Dict, Optional
12
  from Gradio_UI import GradioUI
13
 
14
+ Any = typing.Any
15
+
16
+
17
  @tool
18
+ def extract_recipe_details(url: str) -> Dict[str, Any]:
19
+ """
20
+ Extracts ingredients, instructions, and nutritional information from a recipe webpage.
21
+
22
  Args:
23
+ url (str): The URL of the recipe page.
24
+
25
+ Returns:
26
+ Dict[str, Any]: A dictionary containing ingredients, instructions, and nutritional data.
27
  """
28
+ try:
29
+ headers = {"User-Agent": "Mozilla/5.0"}
30
+ response = requests.get(url, headers=headers, timeout=10)
31
+ response.raise_for_status()
32
+
33
+ soup = BeautifulSoup(response.text, "html.parser")
34
+
35
+ # Extract ingredients
36
+ possible_ingredient_selectors = ["ul", "li", ".ingredients", ".recipe-ingredients", ".ingredient-list"]
37
+ ingredients = []
38
+
39
+ for selector in possible_ingredient_selectors:
40
+ for tag in soup.select(selector):
41
+ items = [item.get_text(strip=True) for item in tag.find_all("li")]
42
+ if items:
43
+ ingredients.extend(items)
44
+
45
+ # Extract instructions
46
+ possible_instruction_selectors = ["ol", "li", ".instructions", ".recipe-instructions", ".step", ".method"]
47
+ instructions = []
48
+
49
+ for selector in possible_instruction_selectors:
50
+ for tag in soup.select(selector):
51
+ steps = [step.get_text(strip=True) for step in tag.find_all("li")]
52
+ if steps:
53
+ instructions.extend(steps)
54
+
55
+ # Extract nutritional information (Look for tables or structured text)
56
+ possible_nutrition_selectors = [".nutrition", ".nutritional-info", ".nutrition-facts", "table"]
57
+ nutrition_info = []
58
+
59
+ for selector in possible_nutrition_selectors:
60
+ for tag in soup.select(selector):
61
+ text = tag.get_text(strip=True)
62
+ if text and len(text) > 20:
63
+ nutrition_info.append(text)
64
+
65
+ # Fallback if no nutrition data found
66
+ nutrition_text = nutrition_info[0] if nutrition_info else "Nutritional information not available. Check the source link."
67
+
68
+ return {
69
+ "ingredients": ingredients if ingredients else ["Ingredients not found. Check the source link."],
70
+ "instructions": instructions if instructions else ["Instructions not found. Check the source link."],
71
+ "nutritional_benefits": nutrition_text
72
+ }
73
+
74
+ except Exception as e:
75
+ return {
76
+ "ingredients": [f"Error extracting ingredients: {str(e)}"],
77
+ "instructions": [f"Error extracting instructions: {str(e)}"],
78
+ "nutritional_benefits": f"Error extracting nutritional info: {str(e)}"
79
+ }
80
 
81
  @tool
82
+ def get_healthy_cheat_meal(diet_type: str) -> List[Dict[str, Any]]:
83
+ """
84
+ Searches the internet for healthy sweet dish recipes and extracts ingredients, instructions, and nutrition.
85
+
86
  Args:
87
+ diet_type (str): The diet category (e.g., Keto, Paleo, Vegan, Vegetarian, Non-Vegetarian).
88
+
89
+ Returns:
90
+ List[Dict[str, Any]]: A list of recipe dictionaries.
91
  """
92
+ query = f"healthy {diet_type} sweet dish recipe with ingredients, instructions, and nutrition facts"
93
+
94
  try:
95
+ # Perform web search using DuckDuckGo
96
+ search_results = duckduckgo_search.ddg(query, max_results=5)
97
+
98
+ if not search_results:
99
+ return [{"error": "No recipes found. Try a different diet type or check your query."}]
100
+
101
+ recipes = []
102
+
103
+ for result in search_results:
104
+ url = result.get("href", "")
105
+ recipe_details = extract_recipe_details(url) if url else {
106
+ "ingredients": ["No source available."],
107
+ "instructions": ["No source available."],
108
+ "nutritional_benefits": "No source available."
109
+ }
110
+
111
+ recipes.append({
112
+ "recipe_name": result.get("title", "Unknown Recipe"),
113
+ "ingredients": recipe_details["ingredients"],
114
+ "nutritional_benefits": recipe_details["nutritional_benefits"],
115
+ "adaptations": f"This recipe follows a {diet_type} diet. Some modifications may be needed.",
116
+ "instructions": recipe_details["instructions"],
117
+ "source": url
118
+ })
119
+
120
+ return recipes
121
+
122
  except Exception as e:
123
+ return [{"error": f"An error occurred while searching: {str(e)}"}]
124
 
125
 
126
  final_answer = FinalAnswerTool()
 
137
 
138
 
139
  # Import tool from Hub
140
+ #image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
141
 
142
  with open("prompts.yaml", 'r') as stream:
143
  prompt_templates = yaml.safe_load(stream)