Python Forum

Full Version: Script get's really weird error
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,
I am trying to write a Python script to ask the user for a recipe. The script should look up the ingredients needed for the recipe via OpenAI. Then, it should look up the live prices at Albert Heijn, at their site. However, I'm reveiving an error:
Error:
File "<stdin>", line 1 ingredient_prices = get_ingredient_prices(ingredients) IndentationError: unexpected indent >>> total_cost = sum(ingredient_prices.values()) File "<stdin>", line 1 total_cost = sum(ingredient_prices.values()) IndentationError: unexpected indent
It looks good to me tho. Here's the full code:

import requests
from bs4 import BeautifulSoup
import openai

openai.api_key = '*************'

def get_recipe(dish_name):
    prompt = f"Geef me een recept voor {dish_name} inclusief een lijst van ingrediënten."
    response = openai.Completion.create(
        engine="text-davinci-003",
        prompt=prompt,
        max_tokens=150
    )
    return response.choices[0].text.strip()

def search_ingredient_price(ingredient):
    search_url = f"https://www.ah.nl/zoeken?query={ingredient.replace(' ', '%20')}"
    response = requests.get(search_url)
    soup = BeautifulSoup(response.text, 'html.parser')
    
   
    try:
        product = soup.find('div', class_='product-card-portrait')
        if product:
            price = product.find('span', class_='price-amount').text.strip().replace(',', '.').replace('€', '')
            return float(price)
        else:
            return 0.0
    except AttributeError:
        return 0.0

def get_ingredient_prices(ingredients):
    prices = {}
    for ingredient in ingredients:
        prices[ingredient] = search_ingredient_price(ingredient)
    return prices

def main():
    dish_name = input("Voer uw gewenste gerecht in: ")
    recipe = get_recipe(dish_name)
    print("\nRecept voor", dish_name)
    print(recipe)
    

    ingredients = [line.split(' ')[-1] for line in recipe.split('\n') if line.strip()]

    ingredient_prices = get_ingredient_prices(ingredients)
    total_cost = sum(ingredient_prices.values())

    if total_cost < 17:
        print("\nDe geschatte totale kosten voor de ingrediënten zijn €", total_cost)
        for ingredient, price in ingredient_prices.items():
            print(f"{ingredient}: €{price}")
    else:
        print("\nHet totale bedrag voor de ingrediënten overschrijdt €17,-. Probeer een ander gerecht.")

if __name__ == "__main__":
    main()
Please helpppp :)
It shows you where the error is.
Output:
IndentationError: unexpected indent
Yeah, but what is the error exactly?
The error message does not match your code. The line numbers disagree. How are you entering and running this code? I sometimes get an error like this using VSCode and using the run arrow. If "Run Code" is selected, VSCode runs the selected code, or the line containing the cursor. You want to use Run Program.
Thanks for your respond. I currently use Python 3.11 to run the code. Should be the right program, shouldn't it?
How do you run the code? Do you type it into a file and run the file form the command line? Are you using an IDE like VSCode, PyCharm, or, god forbid, IDLE? Do you try to type code in the Python interactive interpreter?
I don't know what openai does, so I skipped that part.

import requests
from bs4 import BeautifulSoup

def search_ingredient_price(ingredient):
    search_url = f"https://www.ah.nl/zoeken?query={ingredient.replace(' ', '%20')}"
    response = requests.get(search_url)
    soup = BeautifulSoup(response.text, 'html.parser')     
    
    try:
        product = soup.find('div', class_='product-card-portrait')
        if product:
            price = product.find('span', class_='price-amount').text.strip().replace(',', '.').replace('€', '')
            return float(price)
        else:
            return 0.0
    except AttributeError:
        return 0.0

def get_ingredient_prices(ingredients):
    prices = {}
    for ingredient in ingredients:
        prices[ingredient] = search_ingredient_price(ingredient)
    return prices
Now try this in Idle:

ingrediënten = ['meel', 'kaas', 'tomaten']
get_ingredient_prices(ingrediënten)
No indent error:

Output:
{'meel': 0.0, 'kaas': 0.0, 'tomaten': 0.0}
Pizza voor het ontbijt!
As you have >>> in error message mean that you run in interactive interpreter.
A common mistake when new to Python and use the not so good IDLE💀.
In IDLE has to do file --> new file then write or paste in code in that Window.
Then do Run --> Run module F5.

Also have to change to response = openai.chat.completions.create to use new openai API.
If i try get 429 Too Many Requests in openai as link suggest or sleep in code or need to increase your rate limits.