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 post(self): recipeUrl = self.request.get('recipe_url') logging.info("Url Recived: " + recipeUrl) ################################ ## Fetch Recipe ## ################################ recipeObj = Recipe(recipeUrl) measurementParserObj = MeasurementParser() structuredIngredients = measurementParserObj.Parse(recipeObj.ScrapeIngredients()) recipeObj.setStructuredIngredients(structuredIngredients) structuredDirections = recipeObj.InitDirections() structuredIngredientsJsonString = Jsonify.ListToJsonString(structuredIngredients) structuredDirectionsJsonString = Jsonify.ListToJsonString(structuredDirections) template_values = { 'RecipeUrl': recipeUrl, 'title': recipeObj.getTitle(), 'ingredients': structuredIngredientsJsonString, 'directions': structuredDirectionsJsonString, 'nutrition': recipeObj.getNutrition() } template = JINJA_ENVIRONMENT.get_template('RecipeEnginePage.html') self.response.write(template.render(template_values))
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 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 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 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 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 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 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 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 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 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 parseRecipesFromJsonFile(self, file): """Parses the given json-file, creates Recipe-instances and appends the to Recipebook.recipes""" try: data = json.load(open(file)) for dict in data: # Loops through each dictionary in the file self.addRecipe(Recipe.recipeFromJson(dict)) #Inits a recipe, and adds it to the recipebook except (FileNotFoundError, ValueError, KeyError) as e: newFilename = input('File with that name not found or is empty, try another:') self.run(newFilename)
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 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 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 parse_file(cls, filename): rcps = cls() with open(filename) as f: for (lineno, line) in enumerate(f, 1): line = line.rstrip("\r\n") if line.startswith("#") or line.strip() == "": continue try: recipe = Recipe.parse_line(line) except ParseError: raise Exception("Could not parse recipe on line %d." % (lineno)) rcps.add(recipe) return rcps
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 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 parse_soup_epicurious(soup): r = Recipe() r.title = soup.find('h1', {'class': 'fn'}).next.strip() try: r.servings = extract_int_from_string(soup.find('span', {'class': 'yield'}).next) except AttributeError: pass r.ingredients = [i.next.string for i in soup.findAll('li', {'class': 'ingredient'})] par = soup.find('div', {'id': 'at_a_glance'}) r.tags = [t.next.string.lower() for t in par.findAll('a')] r.directions = [p.next.strip().replace('\r\n',' ') for p in soup.findAll('p', {'class': 'instruction'})] try: r.cooking_time = extract_int_from_string(soup.find('span', {'class': 'prepTime'}).next) except AttributeError: pass try: r.prep_time = extract_int_from_string(soup.find('span', {'class': 'duration'}).next) except AttributeError: pass return r
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 _parse_recipes(self): recipes = [] for (recipe_number, recipe) in enumerate(self._def["recipes"], 1): cycle_time = None if self._args.show_rate: if "time" in recipe: cycle_time = NumberTools.str2num(recipe["time"]) elif "rate" in recipe: cycle_time = 60 / NumberTools.str2num(recipe["rate"]) if "name" in recipe: name = "#%d: %s" % (recipe_number, recipe["name"]) else: name = "#%d" % (recipe_number) produced_at = recipe.get("at") recipe = Recipe.from_str(recipe["recipe"], name=name, produced_at=produced_at, cycle_time=cycle_time) recipes.append(recipe) return recipes
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 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"]))
if force or changed_q: self.send_update_clock() def __freq_to_register_value(self,freq,twos_complement=False): """ Returns an integer that can be used to program the 6 byte frequency registers. """ if twos_complement: c1 = float(2**47) else: c1 = float(2**48) return int(freq*(c1/self.__SYSCLK)) def __get_frequency_resolution(self): c1 = float(2**48) return self.__SYSCLK/c1 if __name__ == "__main__": from Recipe import Recipe R = Recipe(r"D:\tmp\bcode.utb") R.start() D = DDS(address=30,refclock=15*10**6,refclock_multiplier=20) reg = Register("1f",D) reg.set(4,0,5) reg.set_bit(5,1) reg.set_bit(6,1) R.end() print reg
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()
sys.exit(1) time.sleep(1) log_file = open(log_file_name, 'a') current_status = s.read_current_status() if current_status: if current_status[:5] == 'ERROR': print current_status else: print 'ERROR: Program already running. Reset the device and try again.' sys.exit(1) else: recipe = Recipe(open(recipe_file_name, 'r').read()) print 'Sending recipe:' print "\n".join(recipe.human_readable()) try: s.write_recipe(recipe) except DeviceSyncError as err: print err sys.exit(1) had_error = False while True: current_status = s.read_current_status() #current_status = 'SPARGING,HEA,0,0,31.00,24.25,40.00,40.00,1000,ON' if current_status == 'PAUSED': if had_error: play_sound('interface/alarm.wav')
def __init__(self, oOm=None, oFd=sys.stdout): Recipe.__init__(self, oOm, oFd) self.__fVersion__ = 1.0 self.sIniFile = 'SMARecipe.ini' self.sFile = __file__
def addRecipeFromJson(self, json): """creates and adds a recipe from json-object the object must be properly formatted with corresponding keys""" recipe = Recipe.recipeFromJson(json) self.addRecipe(recipe)
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)