hd-hg commited on
Commit
95b536e
·
verified ·
1 Parent(s): c7dcb0c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +34 -24
app.py CHANGED
@@ -40,13 +40,17 @@ def get_healthy_cheat_meal(diet_type: str) -> List[Dict[str, Any]]:
40
 
41
  # Fetch recipe details
42
  details = visit_webpage(url)
43
- if details:
44
- recipes.append({
45
- "recipe_name": title,
46
- "url": url,
47
- "ingredients": details.get("ingredients", "Ingredients not found"),
48
- "instructions": details.get("instructions", "Instructions not found")
49
- })
 
 
 
 
50
 
51
  return recipes if recipes else [{"error": "No valid recipes found"}]
52
 
@@ -61,37 +65,43 @@ def visit_webpage(url: str) -> Dict[str, Any]:
61
  url: The recipe URL.
62
 
63
  Returns:
64
- A dictionary containing 'ingredients' and 'instructions'.
65
  """
66
  try:
 
 
 
 
67
  response = requests.get(url, timeout=10, headers={
68
  'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
69
  })
70
- response.raise_for_status()
71
 
72
  soup = BeautifulSoup(response.content, 'html.parser')
73
 
74
- # Extract ingredients and instructions using common patterns
75
- ingredients = []
76
- instructions = []
 
77
 
78
- for ingredient_tag in soup.select('ul li, .ingredient'):
79
- text = ingredient_tag.get_text(strip=True)
80
- if text:
81
- ingredients.append(text)
82
-
83
- for instruction_tag in soup.select('ol li, .instruction, .step'):
84
- text = instruction_tag.get_text(strip=True)
85
- if text:
86
- instructions.append(text)
87
 
88
  return {
89
- "ingredients": ingredients if ingredients else "Ingredients not found",
90
- "instructions": instructions if instructions else "Instructions not found"
91
  }
92
 
 
 
 
 
 
 
93
  except Exception as e:
94
- return {"error": f"Failed to scrape {url}: {e}"}
95
 
96
  # Initialize tools
97
  final_answer = FinalAnswerTool()
 
40
 
41
  # Fetch recipe details
42
  details = visit_webpage(url)
43
+
44
+ # Skip recipes with errors
45
+ if "error" in details:
46
+ continue
47
+
48
+ recipes.append({
49
+ "recipe_name": title,
50
+ "url": url,
51
+ "ingredients": details.get("ingredients", []),
52
+ "instructions": details.get("instructions", [])
53
+ })
54
 
55
  return recipes if recipes else [{"error": "No valid recipes found"}]
56
 
 
65
  url: The recipe URL.
66
 
67
  Returns:
68
+ A dictionary containing 'ingredients' and 'instructions', or an error message if the URL is invalid.
69
  """
70
  try:
71
+ # Validate URL format before making a request
72
+ if not url.startswith("http"):
73
+ return {"error": f"Invalid URL format: {url}"}
74
+
75
  response = requests.get(url, timeout=10, headers={
76
  'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
77
  })
78
+ response.raise_for_status() # Raise an error for 404, 403, etc.
79
 
80
  soup = BeautifulSoup(response.content, 'html.parser')
81
 
82
+ # Extract ingredients
83
+ ingredients = [tag.get_text(strip=True) for tag in soup.select('ul li, .ingredient')]
84
+ if not ingredients:
85
+ ingredients = [tag.get_text(strip=True) for tag in soup.find_all('li') if "ingredient" in tag.get_text(strip=True).lower()]
86
 
87
+ # Extract instructions
88
+ instructions = [tag.get_text(strip=True) for tag in soup.select('ol li, .instruction, .step')]
89
+ if not instructions:
90
+ instructions = [tag.get_text(strip=True) for tag in soup.find_all('p') if "step" in tag.get_text(strip=True).lower()]
 
 
 
 
 
91
 
92
  return {
93
+ "ingredients": ingredients if ingredients else [],
94
+ "instructions": instructions if instructions else []
95
  }
96
 
97
+ except requests.exceptions.HTTPError as http_err:
98
+ return {"error": f"HTTP error {response.status_code}: {http_err}"}
99
+
100
+ except requests.exceptions.RequestException as req_err:
101
+ return {"error": f"Request failed: {req_err}"}
102
+
103
  except Exception as e:
104
+ return {"error": f"Failed to scrape {url}: {str(e)}"}
105
 
106
  # Initialize tools
107
  final_answer = FinalAnswerTool()