Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -6,6 +6,7 @@ import yaml
|
|
| 6 |
import json
|
| 7 |
from tools.final_answer import FinalAnswerTool
|
| 8 |
from tools.web_search import DuckDuckGoSearchTool
|
|
|
|
| 9 |
from duckduckgo_search import DDGS
|
| 10 |
import re
|
| 11 |
from typing import List, Dict, Any, Optional
|
|
@@ -30,42 +31,39 @@ def get_healthy_cheat_meal(diet_type: str) -> List[Dict[str, Any]]:
|
|
| 30 |
- source: URL of the recipe source
|
| 31 |
"""
|
| 32 |
query = f"healthy {diet_type} sweet dish recipe"
|
| 33 |
-
|
| 34 |
try:
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
search_response = search_tool.run(query)
|
| 40 |
-
if not search_response:
|
| 41 |
return [{"error": "No recipes found. Try a different diet type or check your query."}]
|
| 42 |
-
|
| 43 |
recipes = []
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
for result in search_response[:5]: # Limit to 5 recipes
|
| 47 |
try:
|
| 48 |
-
title = result
|
| 49 |
-
url = result
|
| 50 |
-
|
| 51 |
-
#
|
|
|
|
|
|
|
| 52 |
response = requests.get(url, timeout=10, headers={
|
| 53 |
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
|
| 54 |
})
|
| 55 |
-
|
| 56 |
if response.status_code == 200:
|
| 57 |
soup = BeautifulSoup(response.text, 'html.parser')
|
| 58 |
-
|
| 59 |
-
# Extract basic recipe information
|
| 60 |
ingredients = []
|
| 61 |
for ingredient in soup.select('.recipe-ingredients li, .ingredients li'):
|
| 62 |
ingredients.append(ingredient.get_text().strip())
|
| 63 |
-
|
| 64 |
instructions = []
|
| 65 |
for step in soup.select('.recipe-instructions li, .instructions li'):
|
| 66 |
instructions.append(step.get_text().strip())
|
| 67 |
-
|
| 68 |
-
# Create formatted recipe entry
|
| 69 |
recipe = {
|
| 70 |
"recipe_name": title,
|
| 71 |
"ingredients": ingredients[:10] if ingredients else ["Please check source for ingredients"],
|
|
@@ -74,28 +72,32 @@ def get_healthy_cheat_meal(diet_type: str) -> List[Dict[str, Any]]:
|
|
| 74 |
"adaptations": f"This recipe is suitable for {diet_type} diet. Adjust sweeteners and ingredients according to your specific dietary needs.",
|
| 75 |
"source": url
|
| 76 |
}
|
| 77 |
-
|
| 78 |
recipes.append(recipe)
|
| 79 |
-
|
| 80 |
except Exception as e:
|
|
|
|
| 81 |
continue # Skip this recipe if there's an error
|
| 82 |
-
|
|
|
|
|
|
|
| 83 |
if not recipes:
|
| 84 |
# Fallback with basic information if web scraping fails
|
| 85 |
-
for result in
|
| 86 |
recipes.append({
|
| 87 |
-
"recipe_name": result
|
| 88 |
"ingredients": ["Please check source for full ingredients list"],
|
| 89 |
"instructions": ["Please check source for detailed instructions"],
|
| 90 |
"nutritional_benefits": f"This {diet_type} recipe is designed to be a healthier alternative to traditional sweet dishes.",
|
| 91 |
"adaptations": f"This recipe is suitable for {diet_type} diet. Adjust sweeteners and ingredients according to your specific dietary needs.",
|
| 92 |
-
"source": result
|
| 93 |
})
|
| 94 |
-
|
| 95 |
return recipes if recipes else [{"error": "Unable to process recipes. Please try again."}]
|
| 96 |
-
|
| 97 |
except Exception as e:
|
| 98 |
return [{"error": f"An error occurred while searching: {str(e)}"}]
|
|
|
|
| 99 |
# def get_healthy_cheat_meal(diet_type: str) -> List[Dict[str, Any]]:
|
| 100 |
# """Search for healthy sweet dish alternatives based on specific diet types.
|
| 101 |
|
|
@@ -145,7 +147,7 @@ def get_healthy_cheat_meal(diet_type: str) -> List[Dict[str, Any]]:
|
|
| 145 |
|
| 146 |
# Initialize tools
|
| 147 |
final_answer = FinalAnswerTool()
|
| 148 |
-
web_search_tool = DuckDuckGoSearchTool()
|
| 149 |
|
| 150 |
# 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:
|
| 151 |
# model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud'
|
|
@@ -167,7 +169,7 @@ with open("prompts.yaml", 'r') as stream:
|
|
| 167 |
|
| 168 |
agent = CodeAgent(
|
| 169 |
model=model,
|
| 170 |
-
tools=[final_answer,
|
| 171 |
max_steps=6,
|
| 172 |
verbosity_level=1,
|
| 173 |
grammar=None,
|
|
|
|
| 6 |
import json
|
| 7 |
from tools.final_answer import FinalAnswerTool
|
| 8 |
from tools.web_search import DuckDuckGoSearchTool
|
| 9 |
+
from bs4 import BeautifulSoup
|
| 10 |
from duckduckgo_search import DDGS
|
| 11 |
import re
|
| 12 |
from typing import List, Dict, Any, Optional
|
|
|
|
| 31 |
- source: URL of the recipe source
|
| 32 |
"""
|
| 33 |
query = f"healthy {diet_type} sweet dish recipe"
|
| 34 |
+
|
| 35 |
try:
|
| 36 |
+
ddgs = DDGS() # Initialize DDGS here
|
| 37 |
+
search_results = ddgs.text(query, region="us-en", safesearch="moderate", max_results=5)
|
| 38 |
+
|
| 39 |
+
if not search_results:
|
|
|
|
|
|
|
| 40 |
return [{"error": "No recipes found. Try a different diet type or check your query."}]
|
| 41 |
+
|
| 42 |
recipes = []
|
| 43 |
+
|
| 44 |
+
for result in search_results:
|
|
|
|
| 45 |
try:
|
| 46 |
+
title = result.get('title', '').split(' - ')[0].strip() # Use get and handle missing keys
|
| 47 |
+
url = result.get('href', '') # Use get and handle missing keys
|
| 48 |
+
|
| 49 |
+
if not url: # If URL is missing, skip the result
|
| 50 |
+
continue
|
| 51 |
+
|
| 52 |
response = requests.get(url, timeout=10, headers={
|
| 53 |
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
|
| 54 |
})
|
| 55 |
+
|
| 56 |
if response.status_code == 200:
|
| 57 |
soup = BeautifulSoup(response.text, 'html.parser')
|
| 58 |
+
|
|
|
|
| 59 |
ingredients = []
|
| 60 |
for ingredient in soup.select('.recipe-ingredients li, .ingredients li'):
|
| 61 |
ingredients.append(ingredient.get_text().strip())
|
| 62 |
+
|
| 63 |
instructions = []
|
| 64 |
for step in soup.select('.recipe-instructions li, .instructions li'):
|
| 65 |
instructions.append(step.get_text().strip())
|
| 66 |
+
|
|
|
|
| 67 |
recipe = {
|
| 68 |
"recipe_name": title,
|
| 69 |
"ingredients": ingredients[:10] if ingredients else ["Please check source for ingredients"],
|
|
|
|
| 72 |
"adaptations": f"This recipe is suitable for {diet_type} diet. Adjust sweeteners and ingredients according to your specific dietary needs.",
|
| 73 |
"source": url
|
| 74 |
}
|
| 75 |
+
|
| 76 |
recipes.append(recipe)
|
| 77 |
+
|
| 78 |
except Exception as e:
|
| 79 |
+
print(f"Error processing a recipe: {e}") # Print the error for debugging
|
| 80 |
continue # Skip this recipe if there's an error
|
| 81 |
+
time.sleep(1) # Added a small delay to respect rate limits
|
| 82 |
+
|
| 83 |
+
|
| 84 |
if not recipes:
|
| 85 |
# Fallback with basic information if web scraping fails
|
| 86 |
+
for result in search_results:
|
| 87 |
recipes.append({
|
| 88 |
+
"recipe_name": result.get('title', '').split(' - ')[0].strip(), # Use get and handle missing keys
|
| 89 |
"ingredients": ["Please check source for full ingredients list"],
|
| 90 |
"instructions": ["Please check source for detailed instructions"],
|
| 91 |
"nutritional_benefits": f"This {diet_type} recipe is designed to be a healthier alternative to traditional sweet dishes.",
|
| 92 |
"adaptations": f"This recipe is suitable for {diet_type} diet. Adjust sweeteners and ingredients according to your specific dietary needs.",
|
| 93 |
+
"source": result.get('href', '') # Use get and handle missing keys
|
| 94 |
})
|
| 95 |
+
|
| 96 |
return recipes if recipes else [{"error": "Unable to process recipes. Please try again."}]
|
| 97 |
+
|
| 98 |
except Exception as e:
|
| 99 |
return [{"error": f"An error occurred while searching: {str(e)}"}]
|
| 100 |
+
|
| 101 |
# def get_healthy_cheat_meal(diet_type: str) -> List[Dict[str, Any]]:
|
| 102 |
# """Search for healthy sweet dish alternatives based on specific diet types.
|
| 103 |
|
|
|
|
| 147 |
|
| 148 |
# Initialize tools
|
| 149 |
final_answer = FinalAnswerTool()
|
| 150 |
+
#web_search_tool = DuckDuckGoSearchTool()
|
| 151 |
|
| 152 |
# 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:
|
| 153 |
# model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud'
|
|
|
|
| 169 |
|
| 170 |
agent = CodeAgent(
|
| 171 |
model=model,
|
| 172 |
+
tools=[final_answer,get_healthy_cheat_meal], ## add your tools here (don't remove final answer)
|
| 173 |
max_steps=6,
|
| 174 |
verbosity_level=1,
|
| 175 |
grammar=None,
|