def search(search_terms): TIMEOUT = 5.0 RETRIES = 0 API_ID = 'c819bcc2' API_KEY = 'ad115aa1ff83ff347a2b40c3091a6cf0' client = Client(api_id=API_ID, api_key=API_KEY, timeout=TIMEOUT, retries=RETRIES) query = 'allrecipes+'+search_terms params = { 'q': query, 'maxResult': 5 } search = client.search(**params) matches = search.matches urls = [] for match in matches: recipe = client.recipe(match.id) recipe_source = recipe['source'] recipe_img = recipe['images'] url = (recipe.name, recipe_source['sourceRecipeUrl'], recipe.ingredientLines, recipe_img[0].hostedLargeUrl, recipe.totalTime, recipe.yields) urls.append(url) return urls
def search_recipes(recipe_query_parameters): # passed in partial recipe parameters object #if "ignore user preferences" option is not selected, calculate nutritional requirements if not recipe_query_parameters.ignore_user_preferences: # call calculator to figure out desired meals calc = CalorieCalc(recipe_query_parameters) # calculate max calories for meal recipe_query_parameters.max_calories = calc.get_calories() - recipe_query_parameters.calories_consumed if recipe_query_parameters.meals_left > 0: recipe_query_parameters.max_calories /= recipe_query_parameters.meals_left #diabetic info if recipe_query_parameters.diabetic: recipe_query_parameters.max_carbs = 65 recipe_query_parameters.min_carbs = 45 recipe_query_parameters.max_sodium = 0.4 # have yummly driver query data client = Client(api_id=YummlyApiInfo.Id, api_key=YummlyApiInfo.Key) recipe_query_parameters.q = recipe_query_parameters.allowed_ingredients[0] return_dictionary = recipe_query_parameters.to_dictionary() return client.search(**return_dictionary)
class YummlyClient(object): TIMEOUT = 5.0 RETRIES = 0 def __init__(self, api_id, api_key): self.client = Client(api_id=api_id, api_key=api_key, timeout=self.TIMEOUT, retries=self.RETRIES) def find_consensus(self, query): results = SearchResults(self.client.search(query).matches) return results.core_ingredients(), results
def main(): # default option values TIMEOUT = 5.0 RETRIES = 0 client = Client(api_id="2ecbff5a", api_key="a9e2794b097d6dfc3fef2e3afd81123e", timeout=TIMEOUT, retries=RETRIES) keywords = { 'japanese': 100, 'drink': 100, 'oven roasted': 50, 'fruit': 30, 'salad': 30, 'russian': 30, 'gameday': 10, 'chinese': 100, 'italian': 100, 'indian': 100, 'chicken': 100, 'pork': 100, 'beef': 100, 'soup': 100, 'roasted': 50, 'healthy': 50, 'grilled': 50, 'desert': 100, 'cake': 100, 'breakfast': 250, 'lunch': 250, 'dinner': 250, 'side': 250 } z = 0 print len(keywords.keys()) for keyword in keywords.keys(): print keyword z += 1 print z results = client.search(keyword, maxResults=keywords[keyword]) for match in results.matches: if match.sourceDisplayName== "AllRecipes": recipe = client.recipe(match.id) import pprint pprint.pformat(recipe, indent = 4) print "Processing" process(recipe)
def main(query): """Collect recipes that match your search query """ TIMEOUT = 10.0 RETRIES = 0 client = Client(api_id='d9efc743', api_key='bbb0c1439402e1181312a67278a37342', timeout=TIMEOUT, retries=RETRIES) try: search = client.search(q) l = len(search) for m in range(1): print m match = search.matches[m] #print match recipe = client.recipe(match.id) try: split(recipe) except: print "error when using split" except: "there were no recipes fitting that descripton"
def results(request): """ Results page for the search from the user """ context_dict = {} # If requested (if the submit button has been clicked) if request.method == "POST": # var to hold the ingredients entered into the form on the search page; split each ingredient by # a comma and a space search_list = request.POST["ingredients"].split(", ") # var to hold the api id and key client = Client(api_id=local_settings.api_id_code, api_key=local_settings.api_key_code, timeout=5.0, retries=0) # Params for searches params = { 'q': search_list, 'start': 0, # 'maxResult': 40, # 'requirePicutres': True, # 'allowedIngredient[]': ['salt', 'pepper'], # 'excludedIngredient[]': ['cumin', 'paprika'], 'maxTotalTimeInSeconds': 3600, # 'facetField[]': ['ingredient', 'diet'], # 'flavor.meaty.min': 0.5, # 'flavor.meaty.max': 1, # 'flavor.sweet.min': 0, # 'flavor.sweet.max': 0.5, # 'nutrition.FAT.min': 0, # 'nutrition.FAT.max': 15, } # var results to hold the client search parameters; **params to hold as many or as few as it needs results = client.search(**params) # var context_dict to hold a dictionary of each result match with the key "results" context_dict = {"results": results.matches} # print(results) return render(request, "cupboard_app/results.html", context_dict)
}, "cuisine": { "type": "string" } } } } } clt = Client(api_id="6aa3b3c5", api_key="98f091eede210875e3db43249b670de4", timeout=5.0, retries=0) maxRes = 100 search = clt.search(q, maxResult=maxRes) host = "https://search-pantry2pan-7smzvxcni52n7uhnvtrwzrhj2q.us-east-1.es.amazonaws.com" es = Elasticsearch(host) idx_name = "yummly_idx" es.indices.create(index=idx_name, body=mapping, ignore=400) for i in range(0, maxRes): try: match = search.matches[i] recipe = clt.recipe(match.id) if (recipe.attributes['cuisine']): r = recipe.attributes['cuisine']
from yummly import Client TIMEOUT = 5. RETRIES = 0 API_ID = '2bbb4000' API_KEY = 'c154389b9e106d521c1c443349f2fbf7' client = Client(api_id=API_ID, api_key=API_KEY, timeout=TIMEOUT, retries=RETRIES) search = client.search('green eggs and ham') match = search.matches[0] recipe = client.recipe(match.id)
def main(search_term, num_per_page=1, max_recipes=10): # default option values TIMEOUT = 5.0 RETRIES = 0 key, ID = load_credentials() client = Client(api_id=ID, api_key=key, timeout=TIMEOUT, retries=RETRIES) search = client.search(search_term) total_possible_matches = search.totalMatchCount max_recipes = min(max_recipes, total_possible_matches) page_num = 1 fail_count = 0 num_matches, num_skips = 0, 0 allRecipes = pd.DataFrame() while num_matches < max_recipes and fail_count < max_recipes: search_results = client.search(search_term, maxResults=num_per_page, start=page_num) try: for match in search_results.matches: num_matches += 1 current_ingredients = [] try: # Due to dumb fraction errors recipe = client.recipe(match.id) data = parseIngredientList(recipe['ingredientLines']) quantities = [] for item in data: assert item['name'] != '', "An item needs a name." # Divide by number of servings (if possible) if item['qty'] != '' and isnumeric( recipe['numberOfServings']): try: # amount = float(Fraction(item['qty'])) amount = sum([ float(Fraction(f)) for f in item['qty'].split() ]) quantities.append(amount / recipe['numberOfServings']) # amount = str(amount/recipe['numberOfServings']) + ' ' + item['unit'] except: # quantities.append('unit') quantities.append(1) else: # quantities.append('unit') quantities.append(1) item['name'] = item['name'].lower() # Kludges item['name'] = ingredientKludges(item['name']) current_ingredients.append(item['name']) # Make a data frame from the current recipe counter = " {0}/{1}\n".format(allRecipes.shape[0], max_recipes) print('\n*************************' + counter + recipe['name']) DF = pd.DataFrame(np.array(quantities).reshape( (1, len(current_ingredients))), columns=current_ingredients) DF.insert(0, 'Rating', recipe['rating']) DF.insert(0, 'Salty', recipe['flavors']['salty']) DF.insert(0, 'Sweet', recipe['flavors']['sweet']) DF.insert(0, 'Bitter', recipe['flavors']['bitter']) print(DF) DF.insert(0, 'RecipeID', match.id) DF.insert(0, 'URL', recipe['attribution']['url']) DF.insert(0, 'Title', recipe['name']) allRecipes = pd.concat([allRecipes, DF], axis=0, ignore_index=True) # Continually wite to the .csv file allRecipes.to_csv("allRecipes.csv", mode='w', na_rep=0) except: print('\n-------------------------\n') print((sys.exc_info()[0], sys.exc_info()[1])) # print(data) # for item in data: # print(item['input']) num_skips += 1 # print('--------------------\n' + recipe['name']) if allRecipes.shape[0] > max_recipes: break page_num += num_per_page print( "\nYou downloaded {0} recipes in total and skipped {1}, i.e. {2} skip rate. You saved {3} recipes." .format(num_matches, num_skips, num_skips / float(num_matches), allRecipes.shape[0])) allRecipes.to_csv("allRecipes.csv", mode='w', na_rep=0) except: fail_count += 1 pass
'maxResult': 40, 'requirePicutres': True, 'allowedIngredient[]': ['salt', 'pepper'], 'excludedIngredient[]': ['cumin', 'paprika'], 'maxTotalTimeInSeconds': 3600, 'facetField[]': ['ingredient', 'diet'], 'flavor.meaty.min': 0.5, 'flavor.meaty.max': 1, 'flavor.sweet.min': 0, 'flavor.sweet.max': 0.5, 'nutrition.FAT.min': 0, 'nutrition.FAT.max': 15, } # The var results holds each parameter the user specifies results = client.search(**params) # Formats the raw json data of all matching recipes print(json.dumps(results.matches, indent=4, sort_keys=True)) # print(results.matches) # prints the total matches, the recipe id, ingredients, etc. by grabbing the data print('Total Matches:', results.totalMatchCount) for match in results.matches: print('Recipe ID:', match.id) print('Recipe:', match.recipeName) print('Ingredients:') for x in match.ingredients: print('\t' + x) print('Recipe:', match.recipeName) print('Rating:', match.rating)
def get_recipe(request): '''This function calls the yummly API and retrieves recipe data''' client = Client(api_id='3d16b896', api_key='ad2bc866586798e1e659e988442cafb3') if request.method == 'POST': form = RecipeForm(request.POST) # pylint: disable=E1120 #print form.errors if form.is_valid(): # pylint: disable=E1101 recipe_name = request.POST.get('q', "") allowed_ingredients = request.POST.get('AllowedIngredients', "") excluded_ingredients = request.POST.get('ExcludedIngredients', "") allowed_cuisine = request.POST.get('allowedCuisine', "") allowed_course = request.POST.get('allowedCourse', "") options = { 'q': recipe_name, 'start': 0, 'maxResult': 5, 'requirePicutres': True, 'allowedIngredient[]': [allowed_ingredients], 'excludedIngredient[]': [excluded_ingredients], 'allowedCuisine[]': [allowed_cuisine], 'allowedCourse[]' : [allowed_course], 'maxTotalTimeInSeconds': 3600, 'facetField[]': ['ingredient', 'diet'], 'flavor.sweet.min': 0, 'flavor.sweet.max': 0.5, 'nutrition.FAT.min': 0, 'nutrition.FAT.max': 15 } results2 = client.search(**options) # pylint: disable=W0142 for match in results2.matches: #displaying 5 options in the terminal print 'Recipe ID:', match.id print 'Recipe:', match.recipeName print 'Rating:', match.rating for i in match.ingredients: print 'Ingredients:', i match = results2.matches[0] match1 = results2.matches[1] recipe = client.recipe(match.id) #1st recipe recipe1 = client.recipe(match1.id) #2nd recipe print recipe response_dict = {} response_dict.update({'id': recipe.id}) response_dict.update({'name': recipe.name}) response_dict.update({'totalTime': recipe.totalTime}) response_dict.update({'Ingredients': recipe.ingredientLines}) response_dict.update({'url': recipe.attribution.url}) response_dict.update({'Rating': recipe.rating}) response_dict.update({'id1': recipe1.id}) response_dict.update({'name1': recipe1.name}) response_dict.update({'totalTime1': recipe1.totalTime}) response_dict.update({'Ingredients1': recipe1.ingredientLines}) response_dict.update({'url1': recipe1.attribution.url}) response_dict.update({'Rating1': recipe1.rating}) return HttpResponse(json.dumps(response_dict), content_type='application/javascript') else: return HttpResponse("not valid form") else: form_recipe = RecipeForm() # pylint: disable=E1120 ctx = {'form': form_recipe} return render_to_response('recipe_form.html', ctx, context_instance=RequestContext(request), )
def handle(self, *args, **options): self.stdout.write('success') params = { 'q': '', 'maxResult': options.get('max_results'), 'start': options.get('start'), 'requirePictures': 'true' } # course = 'Main Dishes' # course = 'course^course-{}'.format(course) # params.update({'allowedCourse[]': course}) current_date = datetime.date.today() current_date = current_date.strftime('%Y%m%d') key = 'syncrecipe::%s' % current_date c = Client( api_id=settings.YUMMLY_APP_KEY, api_key=settings.YUMMLY_API_KEY ) ctr = 1 res = c.search(**params) for item in res.matches: ctr = cache.get(key, 1) if Recipe.objects.filter(recipe_source_id=item.id).first(): print 'recipe already stored ', item.id continue if ctr > 480: print 'Exiting: Yummly quota limit' return recipe = c.recipe(item.id) recipe_info = { 'recipe_source_id': item.id, 'name': item.recipeName, 'ingredients': list(recipe.ingredientLines), 'attribution_text': recipe.attribution.text, 'attribution_url': recipe.source.sourceSiteUrl, 'source_text': item.sourceDisplayName, 'source_url': recipe.source.sourceSiteUrl, 'large_image': recipe.images[0]['hostedLargeUrl'], 'small_image': recipe.images[0]['hostedSmallUrl'], 'url': recipe.source.sourceRecipeUrl, 'preparation_time': recipe.totalTimeInSeconds if recipe.totalTimeInSeconds else 1, 'servings': recipe.numberOfServings if recipe.numberOfServings else 1, 'json_response': recipe } recipe = Recipe.objects.get_or_create(**recipe_info)[0] try: if item.attributes.get('holiday', None): print 'holiday', item.attributes for attr in item.attributes.get('holiday'): recipe_holiday = Holiday.objects.get(name=attr) recipe.holidays.add(recipe_holiday) except ObjectDoesNotExist as e: print 'holiday err: ', e.message, item.id, attr except IntegrityError as e: print 'holiday err: ', e.message, item.id finally: print 'done holiday' try: if item.attributes.get('course', None): for attr in item.attributes.get('course'): recipe_course = Course.objects.get(name=attr) recipe.courses.add(recipe_course) except ObjectDoesNotExist as e: print 'course err: ', e.message, item.id, attr except IntegrityError as e: print 'course err: ', e.message, item.id, attr finally: print 'done course' try: if item.attributes.get('cuisine', None): for attr in item.attributes.get('cuisine'): recipe_cuisine = Cuisine.objects.get(name=attr) recipe.cuisines.add(recipe_cuisine) except ObjectDoesNotExist as e: print 'cuisine err: ', e.message, item.id, attr except IntegrityError as e: print 'cuisine err: ', e.message, item.id, attr finally: print 'done cuisine' cache.set(key, ctr + 1) print "total recipes", res.totalMatchCount call_command('index_recipes', verbosity=3, interactive=False)
def removeMeasurement(group, measurement): clean = "" for k in re.findall('\w+', group): if k in meaSet: continue clean += k + " " return clean """ Testing Data - Comment back out when done """ TIMEOUT = 5.0 RETRIES = 0 client = Client(api_id=API_ID, api_key=API_KEY, timeout=TIMEOUT, retries=RETRIES) search = client.search('red curry paste') match = search.matches[0] recipe = client.recipe(match.id) #print recipe if __name__ == '__main__': split(recipe)