def main(args): config = configparser.ConfigParser() config.read('pibrew.ini') sensor = config.get('Main', 'temp_sensor') heater_gpio = config.getint('Main', 'heater_gpio') beeper_gpio = config.getint('Main', 'beeper_gpio') termometer = SimTermometer(sensor) heater = SimHeater(heater_gpio) beeper = SimBeeper(beeper_gpio) recipe = Recipe(config) x = 0 while x != ord('3'): screen = curses.initscr() curses.cbreak() curses.noecho() curses.curs_set(0) screen.clear() screen.border(0) screen.addstr(2, 2, "Pi-Brew") screen.addstr(4, 2, "Please enter a number...") screen.addstr(6, 4, "1 - Run recept") #screen.addstr(7, 4, "2 - Re-run recept") screen.addstr(7, 4, "3 - Exit") screen.refresh() x = screen.getch() if x == ord('1'): sensor = config.get('Main', 'temp_sensor') heater_gpio = config.getint('Main', 'heater_gpio') beeper_gpio = config.getint('Main', 'beeper_gpio') if not recipe.get_simulation(): from DS18B20Termometer import DS18B20Termometer from ActiveBeeper import ActiveBeeper from RealHeater import RealHeater termometer = DS18B20Termometer(sensor) heater = RealHeater(heater_gpio) beeper = ActiveBeeper(beeper_gpio) atexit.register(cleanupGPIO, heater, beeper) recipe = Recipe(config) show_recept(screen, recipe, termometer, heater, beeper) cleanupGPIO(heater, beeper) #if x == ord('2'): # show_recept(screen, recipe) curses.endwin()
def recipesjump(self, lemons, sugar, ice): recip = Recipe() recip.recipes(lemons, sugar, ice) self.pitcher = recip.pitcher self.lemons -= recip.lemonus self.sugar -= recip.sugaruse self.ice -= recip.iceuse
def parse(url): lang = "en" if "/en/" in url else "el" options = webdriver.ChromeOptions() options.add_argument('headless') driver = webdriver.Chrome(options=options) driver.get(url) title = driver.find_element_by_tag_name('h1').text cat = driver.find_element_by_class_name('recipe-breadcrumb').text.split( "/ ", 1)[1] diet = get_diet(driver) tags = get_tags(driver) times_raw = driver.find_element_by_class_name("new-times").text # print(times_raw) hands_on, hands_off, cook_time, portions, difficulty = extract_times( times_raw, lang) total_time = get_total_time(hands_on, hands_off, cook_time) method = get_method_ingredients_tip(driver, "method") ingredients = get_method_ingredients_tip(driver, "ingredients") tip = get_method_ingredients_tip(driver, "tip") rating_value = driver.find_element_by_name("score").get_attribute("value") rating = 0 if rating_value == '' else float(rating_value) video = get_video(driver) driver.close() return Recipe(url, title, cat, diet, tags, hands_on, hands_off, cook_time, total_time, portions, difficulty, ingredients, method, tip, rating, video).convert_to_json()
def main(): for instance in instances: recipe_node = f'http://api.conceptnet.io/c/en/{instance}?filter=/c/en?offset=0&limit=2500' node = Recipe(recipe_node, instance) node.output_requests_csv() node.filter_requests()
def setRecipeInformation(): global recipeInformation recipe = recipeList[recipeIndex] url = "http://www.cookingalexa.com/api/v1.0/recipes/" + str( recipe['RecipeID']) recipeInformation = Recipe(requests.get(url).json())
def read_file(file_name, recipe): recipe = Recipe() f = open(file_name, 'r') title = remove_non_ascii(f.readline()) print 'Title: {}'.format(title) comp = remove_non_ascii(f.readline()) while comp: print 'comp: {}'.format(comp) cook = re.search(r'Cook\s*time', comp, re.I) prep = re.search(r'Prep\s*time', comp, re.I) total = re.search(r'Total\s*time', comp, re.I) ingr = re.search(r'Ingredients', comp, re.I) if cook: cook_time = next_important_line(comp, f) if prep: prep_time = next_important_line(comp, f) elif total: total_time = next_important_line(comp, f) elif ingr: Ingredients = next_important_line(comp, f) comp = remove_non_ascii(f.readline()) print 'Cook Time: {}'.format(cook_time) print 'Prep Time: {}'.format(prep_time) print 'Total Time: {}'.format(total_time) print 'Ingredients:{}'.format(Ingredients)
def main(): if len(sys.argv) == 2: if sys.argv[1][0:4] != "http": print("Invalid url, missing http") return recipe = Recipe(sys.argv[1]) option = int( input( "Enter 1 for Healthier, 2 for Indian, 3 for Italian, 4 for toVegetarian, 5 for Unhealthier, 6 for fromVegetarian: " )) if option == 1: print(toHealthy(recipe)) elif option == 2: print(MakeIndian(recipe)) elif option == 3: print(MakeItalian(recipe)) elif option == 4: print(toVegetarian(recipe)) elif option == 5: print(toUnhealthy(recipe)) elif option == 6: print(fromVegetarian(recipe)) else: print("invalid input") else: print("wrong number of arguments")
def display_recipes(dietary_recipe_results): recipes = {} recipe_count = 0 partition = f'_________________________________________________________________________________________________________' # Creates formatted recipes from search results and places them in dictionary where: # {'recipe title': recipe_object} # If no instructions are included: recipe is skipped for i in range(len(dietary_recipe_results)): if len(dietary_recipe_results[i]['analyzedInstructions']) > 0: recipe_count += 1 recipe = Recipe(dietary_recipe_results[i]) recipes[recipe.title] = recipe print(f'{partition}\n\n' \ f'{recipe_count}. {recipe.title}\n\n' \ + '{title}: {amount} {unit} per serving ({percentOfDailyNeeds}% of daily needs)\n'.format(**recipe.calories_per_serving) \ + f'Ready in {recipe.ready_in_minutes} minutes\n\n' \ f'Summary: {recipe.summary}\n') print(partition) return recipes
def submitted_form(): recipe_title = request.form['title'] recipe_origin = request.form['origin'] recipe_content = request.form['content'] # process raw input m = hashlib.md5() m.update(recipe_origin.encode('utf-8')) recipe_id = m.hexdigest() recipe_groups = RecipePreprocessor().preprocess(html_input=recipe_content) basic_name, code, confidence, bytesize = detect_language(', '.join(recipe_groups)) recipe_lang = basic_name recipe_lang_pred = float(confidence) tagger = Tagger(lang=code) RecipeStorage().store(recipe=Recipe(id=recipe_id, title=recipe_title, origin=recipe_origin, lang=recipe_lang)) groups_widget, ingredients = tagger.get_group_widget(recipe_groups) return render_template( 'submitted_recipe.html', title= f'{recipe_title} (id: {recipe_id})', origin=recipe_origin, language=recipe_lang, language_pred=recipe_lang_pred, content_html=recipe_content, content=Markup(groups_widget))
def post(self, recipekey, description, devices, frequency, duration): global recipes recipes[recipekey] = Recipe(recipekey, description, devices.split("-"), frequency, duration, dict()) updateRecipePersistance() return json.dumps({'success': True}), 200, { 'ContentType': 'application/json' }
def s(): if request.method == 'POST': query = request.form['query'] new_recipe = Recipe(ingredients=query) json_data = new_recipe.GetRequest_Ingredients() recipe_dict = new_recipe.process_recipe_ID_summary(json_data) recipes = new_recipe.return_results(recipe_dict) return render_template( 'search.html', results=recipes) #the recipes we want to display
def init_recipe(self): 떡볶이 = Recipe('떡볶이') 떡볶이.people = 2 # 1 떡볶이.video = 'youtube.com' # '' 떡볶이.ingrediant = {'물': '100', '떡': '100', '고추장': '100'} # {} self.recipe_list.append(떡볶이) 카레 = Recipe('카레') 카레.ingrediant = {'카레가루': '150', '감자': '100', '당근': '100'} self.recipe_list.append(카레) 파스타 = Recipe('파스타') 파스타.contents = '맛있게 만드세요!' 파스타.ingrediant = {'면': '100', '소스': '200'} self.recipe_list.append(파스타)
def get_recipe_by_id(self, id): connection = sqlite3.connect('recipe.db') connection.row_factory = sqlite3.Row cursor = connection.cursor() cursor.execute("SELECT a.USERNAME, r.ID, r.RECIPE_NAME, r.RECIPE_DESCRIPTION, r.RECIPE_INGREDIENTS \ FROM tbl_recipe r \ JOIN tbl_account a ON a.ID = r.RECIPE_OWNER \ WHERE r.ID = ?", (id,)) rows = cursor.fetchall() connection.close() if len(rows) > 0: return Recipe(rows[0]['ID'], rows[0]['RECIPE_NAME'], rows[0]['RECIPE_DESCRIPTION'], rows[0]['RECIPE_INGREDIENTS'], rows[0]['USERNAME']) return None
def create_recipes(title, cuisine, first_prepare, total_kal, for_how_much_person, main_ingridient): try: new_recipe = Recipe(title=title, cuisine=cuisine, first_prepare=first_prepare, total_kal=total_kal, for_how_much_person=for_how_much_person, main_ingridient=main_ingridient) except ValueError: new_recipe = None pass return new_recipe
def get_recipes_for_user(self, user): connection = sqlite3.connect('recipe.db') connection.row_factory = sqlite3.Row cursor = connection.cursor() cursor.execute("SELECT r.ID, r.RECIPE_NAME, r.RECIPE_DESCRIPTION, r.RECIPE_INGREDIENTS, a.USERNAME \ FROM tbl_recipe r \ JOIN tbl_account a ON a.ID = r.RECIPE_OWNER \ WHERE a.USERNAME = ?", (user,)) rows = cursor.fetchall() connection.close() recipes = [] for row in rows: recipes.append(Recipe(row['ID'], row['RECIPE_NAME'], row['RECIPE_DESCRIPTION'],row["RECIPE_INGREDIENTS"], row['USERNAME'])) return recipes
def add_recipe(self, recipe): """ Takes the given dict recipe, creates a Recipe() from it and adds it to self.recipes also adds all ingredients that aren't yet in self.ingredients to that. The same applies to products. :param recipe: A dictionary for a single recipe """ ingredients = {} for ingredient in recipe['ingredients']: # check if ingredient already exist potential_new_ingredient = self.ingredient_exists(ingredient) if potential_new_ingredient is None: # if ingredient does not already exist create a new Ingredient() from ingredient dictionary # and add it to ingredients ing = Ingredient(ingredient['type'], ingredient['name'], ingredient['amount']) self.ingredients[ingredient['name']] = ing ingredients[ingredient['name']] = ing else: # if ingredient does already exist take that ingredient object and add it to ingredients ingredients[ingredient['name']] = potential_new_ingredient products = {} for product in recipe['products']: # check if product already exist potential_new_product = self.product_exists(product) if potential_new_product is None: # if product does not already exist create a new Product() from product dictionary # and add it to products pro = None if 'amount' in product.keys(): pro = self.products[product['name']] = Product( product['type'], product['name'], amount=product['amount']) else: pro = self.products[product['name']] = Product( product['type'], product['name'], amount_min=product['amount_min'], amount_max=product['amount_max']) self.products[product['name']] = pro products[product['name']] = pro else: # if product does already exist take that product object and add it to products products[product['name']] = potential_new_product # create new Recipe() and add it to self.recipes r_o = Recipe(recipe['name'], ingredients, products, recipe['energy']) self.recipes[recipe['name']] = r_o
def get_recipe(self, user, recipeName): connection = sqlite3.connect('recipe.db') connection.row_factory = sqlite3.Row cursor = connection.cursor() id = self.get_recipe_id_from_user_and_name(cursor, user, recipeName) cursor.execute("SELECT r.ID, a.USERNAME, r.RECIPE_NAME, r.RECIPE_DESCRIPTION, r.RECIPE_INGREDIENTS \ FROM tbl_recipe r \ JOIN tbl_account a ON a.ID = r.RECIPE_OWNER \ WHERE r.ID = ?", (id,)) rows = cursor.fetchall() connection.close() if (len(rows) > 0): return Recipe(rows[0]['ID'], rows[0]['RECIPE_NAME'], rows[0]['RECIPE_DESCRIPTION'], rows[0]["RECIPE_INGREDIENTS"], rows[0]['USERNAME']) return None
def extract_recipes_data(recipes): for recipe_html in recipes: recipe_link = root_url + recipe_html['href'] recipe = Recipe(recipe_link) recipe.get_recipe_steps() print(recipe.get_recipe_name()) print('pour {} personnes\n'.format(recipe.get_nb_person())) print('Ingredients:') for ingredient in recipe.get_ingredients(): print(ingredient['ingredient_quantity'] + ingredient['ingredient_name']) print('\n') for step in recipe.get_recipe_steps(): print('\t- {}'.format(step)) print('\n\n')
def add_recipe(self): # 추가할 레시피 이름 입력 name = input('레시피의 이름을 입력하세요 : ') # 중복 체크 for recipe in self.recipe_list: if name == recipe.name: # 중복되는 레시피가 있으면 중복이라고 표기 print('이미 존재하는 레시피입니다.') return # 빠져 나오기 # 중복되는 레시피가 없으면 추가 # 레시피 생성 new_recipe = Recipe(name) new_recipe.set_recipe() # 레시피 리스트에 생성한 레시피 추가하기 self.recipe_list.append(new_recipe)
def main(): platform = Platform() recipe = Recipe() # Step 0: Preform hard reset to calibrate platform position during startup #platform.hard_Reset() # Step 1: get recipe from user either from onboard gui or android app #sampleRecipe = sys.argv[1] sampleRecipe = "1,19.3,2,19.3,3,19.3,4,19.3,5,19.3,6,19.3,7,19.3,8,19.3,true" # Step 2: split recipe string to a stack of seperate ingredients recipe.initilize_Stack(sampleRecipe) # Step 3: specify the order of the recipe if recipe.isOrdered == True: recipeOrder = recipe.recipeStack else: recipeOrder = platform.get_Shortest_Path(recipe) hbridge.turnOff() time.sleep(.3) # Step 4: interate over each ingredient then move platform for ingred in recipeOrder: print "Getting %rmL of segment %r" %(ingred.mL, ingred.segNum) #segNum is NOT 0 indexed platform.move_To_Segment(platform.segList[ingred.segNum-1].name) time.sleep(WAIT) # Step 5: once platform reached its mark, pour amount hbridge.turnOn() time.sleep(.2) Actuator.actuate(Actuator.actDict[ingred.segNum-1], float(ingred.mL)) hbridge.turnOff() time.sleep(WAIT) # Step 6: repeat step 4 till stack is empty # Step 7: Move platform back to the middle print "Final offset: %r " % Platform.offset platform.reset()
def __init__(self): #reads the information from the CSV file with open('src/dataset/recipes.CSV', newline='') as f: file = csv.reader(f) for line in file: #create new recipe new_recipe = Recipe(line[0], int(line[1]), int(line[2]), int(line[3]), int(line[4])) #add its ingredients for ing in range(5, len(line)): #the following is a little clean up because of the way the CSV file is written if len(line[ing]) > 2: if ing != 5: line[ing] = line[ing][1:] new_recipe.addIngredient(line[ing]) self.recipes.append( new_recipe) # add recipe to list of recipes
def init(self): fh = open("Devices.json", "r") devicesLoaded = json.load(fh) fh.close() for val in devicesLoaded: if val['typ'] == "nozzle": devices[val['name']] = Nozzle(val['name'],val['typ'], val['pins']) elif val['typ'] == "ultrasonic": devices[val['name']] = Ultrasonic(val['name'],val['typ'], val['pins']) elif val['typ'] == "termometer": devices[val['name']] = TermoMeter(val['name'],val['typ'], val['pins']) elif val['typ'] == "humiditymeter": devices[val['name']] = HumidityMeter(val['name'],val['typ'], val['pins']) elif val['typ'] == "terrainhumiditymeter": devices[val['name']] = TerrainHumidityMeter(val['name'],val['typ'], val['pins']) for x in devices: devices[x].init() devices[x].status=3 fh = open("Recipes.json", "r") recipesLoaded = json.load(fh) fh.close() for val in recipesLoaded: connectedDevices = [] for x in val['recipeDevices']: connectedDevices.append(x) checks = dict() for x,y in val['checks'].items(): if y['tp'] == "Threshould" : checks[x] = Threshould(y['valueToTest'],y['operator'],y['value']) elif y['tp'] == "EmergencyThreshould" : checks[x] = EmergencyThreshould(y['valueToTest'],y['operator'],y['value']) elif y['tp'] == "OnceADay" : checks[x] = OnceADay(y['recipeName']) elif y['tp'] == "ActivationTime" : checks[x] = ActivationTime(y['hours'], y['minutes'], y['maxDelta']) elif y['tp'] == "NoActivationPeriod" : checks[x] = NoActivationPeriod(y['starthours'], y['startmin'], y['stophours'], y['stopmin']) recipes[val['name']] = Recipe(val['name'], val['description'], connectedDevices, val['frequency'], val['duration'], checks)
def s(): #if request.method == 'GET': query = request.args.get('query') # query.split() # query = ','.join(query) query = str(query) new_recipe = Recipe(ingredients=query) #print(new_recipe) json_data = new_recipe.GetRequest_Ingredients() #print(json_data) recipe_dict = new_recipe.process_recipe_ID_summary(json_data) recipes = new_recipe.return_results(recipe_dict) instructions = new_recipe.display_instructions(recipe_dict) ingredients = new_recipe.display_ingredients(recipe_dict) print(instructions) return render_template( 'search.html', results=recipes, json_file=json_data, instructions=instructions, ingredients=ingredients) #the recipes we want to display
def get_recipe_by_descriptor(self, recipe_descriptor): match = self._RECIPE_DESCRIPTOR_RE.fullmatch(recipe_descriptor) if match is None: raise Exception("Not a valid recipe descriptor: %s" % (recipe_descriptor)) match = match.groupdict() if match["cardinality"] is None: scalar = 1 elif "/" in match["cardinality"]: # Fraction scalar = fractions.Fraction(match["cardinality"]) else: # Integer or floating point value try: scalar = int(match["cardinality"]) except ValueError: scalar = float(match["cardinality"]) if match["percent"] is not None: scalar /= 100 if match["name_type"] == "#": recipe_index = int(match["name"]) - 1 if (recipe_index < 0) or (recipe_index >= len(self._recipes)): raise Exception( "Invalid recipe number, must be between 1 and %d." % (len(self._recipes))) recipe = self._recipes[recipe_index] elif match["name_type"] == ">": recipe = Recipe((Resource(name=match["name"], count=scalar), ), (Resource(name=Recipe.FINISHED, count=1), ), name="Pseudo-Recipe") scalar = 1 else: recipe = self._recipes_by_name[match["name"]] return recipe * scalar
def CreateRecipes(self): city13 = Recipe('City Roast (13 Minutes)') city13.segments.append( RecipeSegment(200, 250, MAX_FAN_STATE_INDEX, MAX_FAN_STATE_INDEX, 5 * 60, 'Drying', 0, 4)) city13.segments.append( RecipeSegment(250, 415, MAX_FAN_STATE_INDEX, 2, 6 * 60, 'Ramp Up')) city13.segments.append(RecipeSegment(415, 425, 1, 1, 2 * 60, 'Hold')) self.Recipes.append(city13) city9 = Recipe('City Roast (9 Minutes)') city9.segments.append( RecipeSegment(200, 250, MAX_FAN_STATE_INDEX, MAX_FAN_STATE_INDEX, 3 * 60, 'Drying', 0, 4)) city9.segments.append( RecipeSegment(250, 415, MAX_FAN_STATE_INDEX, 2, 4 * 60, 'Ramp Up')) city9.segments.append(RecipeSegment(415, 425, 1, 1, 2 * 60, 'Hold')) self.Recipes.append(city9) cityplus13 = Recipe('City+ (13 minutes)') cityplus13.segments.append( RecipeSegment(200, 250, MAX_FAN_STATE_INDEX, MAX_FAN_STATE_INDEX, 5 * 60, 'Drying', 0, 4)) cityplus13.segments.append( RecipeSegment(250, 425, MAX_FAN_STATE_INDEX - 1, 2, 6 * 60, 'Ramp Up')) cityplus13.segments.append( RecipeSegment(425, 435, 1, 1, 2 * 60, 'Hold')) self.Recipes.append(cityplus13) cityPlus11 = Recipe('City+ (11 minutes)') cityPlus11.segments.append( RecipeSegment(175, 300, MAX_FAN_STATE_INDEX, MAX_FAN_STATE_INDEX, 4 * 60, 'Drying', 0, 4)) cityPlus11.segments.append( RecipeSegment(300, 425, MAX_FAN_STATE_INDEX, 2, 5 * 60, 'Ramp Up')) cityPlus11.segments.append( RecipeSegment(425, 435, 1, 1, 2 * 60, 'Hold')) self.Recipes.append(cityPlus11) cityPlus10 = Recipe('City+ (10 minutes)') cityPlus10.segments.append( RecipeSegment(175, 300, MAX_FAN_STATE_INDEX, MAX_FAN_STATE_INDEX, 4 * 60, 'Drying', 0, 4)) cityPlus10.segments.append( RecipeSegment(300, 425, MAX_FAN_STATE_INDEX, 2, 4 * 60, 'Ramp Up')) cityPlus10.segments.append( RecipeSegment(425, 435, 1, 1, 2 * 60, 'Hold')) self.Recipes.append(cityPlus10) cityPlus9 = Recipe('City+ (9 minutes)') cityPlus9.segments.append( RecipeSegment(175, 300, MAX_FAN_STATE_INDEX, MAX_FAN_STATE_INDEX, 3.5 * 60, 'Drying', 0, 4)) cityPlus9.segments.append( RecipeSegment(300, 425, MAX_FAN_STATE_INDEX, 2, 3.5 * 60, 'Ramp Up')) cityPlus9.segments.append(RecipeSegment(425, 435, 1, 1, 2 * 60, 'Hold')) self.Recipes.append(cityPlus9) cityPlus8 = Recipe('City+ (8 minutes)') cityPlus8.segments.append( RecipeSegment(200, 250, MAX_FAN_STATE_INDEX, MAX_FAN_STATE_INDEX, 2 * 60, 'Drying', 0, 4)) cityPlus8.segments.append( RecipeSegment(250, 425, MAX_FAN_STATE_INDEX - 1, 2, 4 * 60, 'Ramp Up')) cityPlus8.segments.append(RecipeSegment(425, 435, 1, 1, 2 * 60, 'Hold')) self.Recipes.append(cityPlus8) fullCity10 = Recipe('Full City (10 minutes)') fullCity10.segments.append( RecipeSegment(200, 250, MAX_FAN_STATE_INDEX, MAX_FAN_STATE_INDEX, 4 * 60, 'Drying', 0, 4)) fullCity10.segments.append( RecipeSegment(250, 435, MAX_FAN_STATE_INDEX - 1, 2, 4 * 60, 'Ramp Up')) fullCity10.segments.append( RecipeSegment(435, 445, 1, 1, 2 * 60, 'Hold')) self.Recipes.append(fullCity10) fullCity13 = Recipe('Full City (13 minutes)') fullCity13.segments.append( RecipeSegment(200, 250, MAX_FAN_STATE_INDEX, MAX_FAN_STATE_INDEX, 5 * 60, 'Drying', 0, 4)) fullCity13.segments.append( RecipeSegment(250, 435, MAX_FAN_STATE_INDEX - 1, 2, 6 * 60, 'Ramp Up')) fullCity13.segments.append( RecipeSegment(435, 445, 1, 1, 2 * 60, 'Hold')) self.Recipes.append(fullCity13) fullCityPlus13 = Recipe('Full City+ (13 minutes)') fullCityPlus13.segments.append( RecipeSegment(200, 250, MAX_FAN_STATE_INDEX, MAX_FAN_STATE_INDEX, 5 * 60, 'Drying', 0, 4)) fullCityPlus13.segments.append( RecipeSegment(300, 450, MAX_FAN_STATE_INDEX - 1, 2, 5 * 60, 'Ramp Up')) fullCityPlus13.segments.append( RecipeSegment(450, 450, 1, 1, 3 * 60, 'Hold')) self.Recipes.append(fullCityPlus13) frenchRoast12 = Recipe('French Roast (12 Minutes)') frenchRoast12.segments.append( RecipeSegment(200, 250, MAX_FAN_STATE_INDEX, MAX_FAN_STATE_INDEX, 4 * 60, 'Drying', 0, 4)) frenchRoast12.segments.append( RecipeSegment(300, 470, MAX_FAN_STATE_INDEX - 1, 2, 6 * 60, 'Ramp Up')) frenchRoast12.segments.append( RecipeSegment(470, 470, 1, 1, 2 * 60, 'Hold')) self.Recipes.append(frenchRoast12) self.SelectedRecipe = fullCity13 print(self.SelectedRecipe.name)
def scrape_page(page_link): page_reponse = requests.get(page_link) page_soup = BeautifulSoup(page_reponse.text, "html.parser") try: image_url = page_soup.select_one( ".recipeGallerySegment .bigImg img")['src'] if "without-watermark" not in image_url: global recipes_with_watermarks recipes_with_watermarks += 1 return recipe_title = page_soup.select_one( ".recipeTitleSegment h1").text.strip() before_split = page_soup.select_one(".method .info .info").text.strip() recipe_preparation_time = int(re.findall("\d+", before_split)[0]) if "min" in before_split: recipe_preparation_time = int(60 * recipe_preparation_time) elif "val" in before_split: recipe_preparation_time = int(60 * 60 * recipe_preparation_time) recipe_portion_amount = page_soup.select_one(".info").text.strip() if len(recipe_portion_amount) is 0: recipe_portion_amount = int(4) else: recipe_portion_amount = int( re.findall("\d+", recipe_portion_amount)[0]) recipe_description = '' try: recipe_description = page_soup.select_one( ".authorsDescription").text.strip() except AttributeError: recipe_description = '' print('No description') amounts = page_soup.select(".ingredients .infoA table tr") recipe_products = [] for amount in amounts: cells = amount.select("td") if len(cells) is 1: continue quantity = cells[0].text.strip() product_name = cells[1].text.strip()[0:30].strip() new_product = Product(product_name, quantity) recipe_products.append(new_product.__dict__) steps = page_soup.select(".infoA .description") recipe_steps = [] for step in steps: step_text = step.select_one(".text") # print(step_text.text) new_step = Step(step_text.text) recipe_steps.append(new_step.__dict__) recipe_view_count = int(0) recipe_rating = int(0) recipe_votes_count = int(0) image_extension = image_url.split('.')[-1] image_fileName = '' image_name = '' while True: image_name = uuid.uuid4().hex image_fileName = image_name + "." + image_extension if not os.path.isfile("Photos/" + image_fileName): break opener = urllib.request.URLopener() opener.addheader( 'User-Agent', 'Mozilla/5.0 (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Mobile/7B405' ) opener.retrieve(image_url, "Photos/" + image_fileName) # urllib.request.urlretrieve(image_url, "Photos/" + image_fileName) recipe_image = Photo(image_fileName) recipe_images = [] recipe_images.append(recipe_image.__dict__) # Tags recipe_tags = [] temp = Tag("grilio patiekalai") recipe_tags.append(temp.__dict__) tags = page_soup.select(".guidelinesSegment a") for tag in tags: if not "lamaistas" in tag.text: new_tag = Tag(tag.text) recipe_tags.append(new_tag.__dict__) new_recipe = Recipe(recipe_title, recipe_products, recipe_steps, recipe_portion_amount, recipe_preparation_time, recipe_description, recipe_view_count, recipe_rating, recipe_votes_count, recipe_images, recipe_tags) new_recipes.append(new_recipe.__dict__) print("Saved " + page_link + " " + str(len(new_recipes))) except Exception as e: print("Error " + str(e) + " || " + page_link)
import json, codecs from Recipe import Recipe with open("db-recipes.json") as jfile: data = json.load(jfile) RecipeList = list() for key,value in data.items(): RecipeList.append(Recipe(value)) f = codecs.open("mySQL.sql", mode="a", encoding="utf-8") f.write("USE 6Vm97vzJ6U;\n\n") f.write("CREATE TABLE recipes(\nID VARCHAR(50) NOT NULL PRIMARY KEY,\nTitle VARCHAR(50) NOT NULL,\nInstructions TEXT,\nIngredients TEXT,\nTags TEXT,\nCalories INT,\nServings TEXT );\n\n") f.write("INSERT INTO recipes (ID, Title, Instructions, Ingredients, Tags, Calories, Servings)\nVALUES\n") for r in RecipeList: tempr = r.getDict() tempr["instructions"] = tempr["instructions"].replace("[", "") tempr["instructions"] = tempr["instructions"].replace("]", "") tempr["instructions"] = tempr["instructions"].replace("'", "") tempr["instructions"] = tempr["instructions"].replace('"', "") tempr["tags"] = str(tempr["tags"]).replace("[", "") tempr["tags"] = str(tempr["tags"]).replace("]", "") tempr["tags"] = str(tempr["tags"]).replace("'", "") tempr["ingredients"] = str(tempr["ingredients"]).replace("[", "") tempr["ingredients"] = str(tempr["ingredients"]).replace("]", "") tempr["ingredients"] = str(tempr["ingredients"]).replace("'", "") tempr["ingredients"] = str(tempr["ingredients"]).replace('"', "") f.write('\t("%s", "%s", "%s", "%s", "%s", %d, %d),\n' % (tempr["id"], str(tempr["name"]), str(tempr["instructions"]), str(tempr["ingredients"]), str(tempr["tags"]), tempr["calories"], tempr["servings"]))
from Recipe import Recipe import numpy as np #Make a test recipe: tester=Recipe() tester.setCategory("Cider") tester.setName("BrewDevil") tester.setFlavor("Standard Cider, no additional fruit") tester.setYeast("Brew Devil Brand") tester.setGoalABV(0) tester.setOG(0) tester.setFG(0) tester.addIngredient("1.5C Granulated White Sugar") tester.addIngredient("1 Can Brew Devil Cider Concentrate") tester.addIngredient("2 Gallons Water- Chippewa Valley Spring Water") tester.setTasteNotes("Pre-Yeast: Not particularly strong flavor, watery and sweet. low acidiy") tester.setStartDate("2020-10-08") tester.printRecipe() tester.writeRecipe()
def main(): resp = requests.get('https://food.mthai.com/food-recipe/page/3') selector = 'h3.entry-title' html_page = bs4.BeautifulSoup(resp.text, 'html.parser') menu_elm = html_page.select(selector) menus = [] for elm in menu_elm: recipe = Recipe() found_elm = elm.findAll('a', attrs={ 'href': re.compile('^https://'), 'rel': 'bookmark' }) if len(found_elm) > 0 and re.search('^(สูตร|วิธีทำ)', found_elm[0].text): recipe.name = found_elm[0].text.strip() recipe.link = found_elm[0].get('href') recipe.food_ingredients = find_food_ingredients( recipe.name, recipe.link) menus.append(recipe) menu_input = input('Enter menu: ') print('\nProcessing...\n') forecast_prices = find_forecast_items_price() for menu in menus: if menu.name == menu_input.strip(): fixed_prices = read_fixed_price() summary_price = {'avg': 0, 'min': 0, 'max': 0} for recipe in menu.food_ingredients: found_forecase_item = False for key in forecast_prices: if forecast_prices[key]['success'] and re.search( '(เนื้อหมู|เนื้อวัว|เนื้อไก่|นม)', forecast_prices[key]['item']): found_forecase_item = True summary_price['avg'] += (forecast_prices[key]['avg'] * recipe.get_gram()) / 1000 summary_price['min'] += (forecast_prices[key]['min'] * recipe.get_gram()) / 1000 summary_price['max'] += (forecast_prices[key]['max'] * recipe.get_gram()) / 1000 break if forecast_prices[key]['success'] and re.search( 'ไข่', forecast_prices[key]['item']): found_forecase_item = True summary_price['avg'] += forecast_prices[key][ 'avg'] * recipe.quantity summary_price['min'] += forecast_prices[key][ 'min'] * recipe.quantity summary_price['max'] += forecast_prices[key][ 'max'] * recipe.quantity break if found_forecase_item: continue for item, price in fixed_prices: if re.search(rf"{item}", recipe.item): summary_price['avg'] += (price * recipe.get_gram()) / 1000 summary_price['min'] += (price * recipe.get_gram()) / 1000 summary_price['max'] += (price * recipe.get_gram()) / 1000 print('cost average: {}, min: {}, max: {}'.format( round(summary_price['avg'], 2), round(summary_price['min'], 2), round(summary_price['max'], 2))) return None print('Your menu doesn\'t exist')
def run(self): print("Running..") brews = 1 brewcount = 0 # add the pumps hlt_recirc = Pump(Pump.PUMP_BROWN) mlt_recirc = Pump(Pump.PUMP_MARCH) transfer = Pump(Pump.PUMP_MARCH) # This will run forever. while True: # Initially this will just be doing a single batch at a time # but this could allow recipes to be stacked. try: # load the recipe xml recipe = Recipe('step_mash_recipe.xml') # parse the recipe xml recipe.parse() except Exception as e: error_str = "Recipe parsing failed!" self.logger.critical(error_str) print(error_str) print("Mash steps are:") mash_steps = recipe.get_mash_steps() for steps in mash_steps: print(steps.tag, steps.attrib) for step in steps: print(step.tag, step.text) # setup the vessels self.vessel_hlt = VesselHlt(self.logger, self.dbconn) self.vessel_hlt.strike_in_mlt(self.strike_in_mlt) self.vessel_hlt.set_target_strike_time() # UNIX timestamp self.vessel_hlt.add_steps(recipe.get_mash_steps()) self.vessel_mlt = VesselMlt(self.logger, self.dbconn) self.vessel_mlt.strike_in_mlt(self.strike_in_mlt) self.vessel_mlt.add_steps(recipe.get_mash_steps()) self.vessel_ktl = VesselKettle(self.logger, self.dbconn) self.sensor_logger = SensorLogger(self.logger, self.dbconn) self.control = ControlInterface(self.logger, self.dbconn) children = [] # Create forks for each vessel. # from http://www.petercollingridge.co.uk/blog/running-multiple-processes-python start_time = time.time() processes = self.VESSEL_COUNT + 2 # number of vessels plus the logger and webservice threads for process in range(self.VESSEL_COUNT): pid = os.fork() if pid: children.append(pid) else: self.processLauncher(process) os._exit(0) # Wait for all the vessels to complete. for i, child in enumerate(children): os.waitpid(child, 0) brewcount += 1 if (brewcount == brews): print("All batches completed. Exiting.") os._exit(0)