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)
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)
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(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)
def __init__(self, api_id, api_key): self.client = Client(api_id=api_id, api_key=api_key, timeout=self.TIMEOUT, retries=self.RETRIES)
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
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), )
# limitations under the License. from adapt.intent import IntentBuilder from mycroft.skills.core import MycroftSkill from mycroft.util.log import getLogger from yummly import Client import time __author__ = 'ajwkc' LOGGER = getLogger(__name__) # Preps the Yummly API ID and key client = Client(api_id="578ccc53", api_key="1d102bfd626c6a634b477219350a6233", timeout=5.0, retries=0) class RecipeSkill(MycroftSkill): def __init__(self): super(RecipeSkill, self).__init__(name="RecipeSkill") # Listens for "how do I cook ____________" @intent_handler(IntentBuilder("RecipeIntent").require("Query").require("Cook").require("Food")) def handle_recipe_intent(self, message): # Searches for "Food" and grabs the first result food = message.data.['Food'] search = client.search(food) match = search.matches[0]
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)
# search = "Chicken" # r = requests.get("http://api.yummly.com/v1/api/recipes?_app_id=243f40b9&_app_key=0b99d35c38f2043e163a04a97e9c5476&q&" + # search) # data = r.json() # print(json.dumps(data['matches'], indent=4, sort_keys=True)) ######## TIMEOUT = 5.0 RETRIES = 0 # Access the api using the client api id & key client = Client(api_id="243f40b9", api_key="0b99d35c38f2043e163a04a97e9c5476", timeout=TIMEOUT, retries=RETRIES) # Dict of all search parameters. This will be implemented into Cupboard with replacable data. # Examples: # If a user would like to use pork chops, lemon, and pepper an their dish, it will be included in the "q" param # If a user would like to exclude any ingredients, "excludedIngredient[]" will include those # specifications in an array. # flavor.meaty.min/max: The allowed savoriness of the dish they're searching for. params = { 'q': 'apple', 'start': 0, 'maxResult': 40, 'requirePicutres': True, 'allowedIngredient[]': ['salt', 'pepper'], 'excludedIngredient[]': ['cumin', 'paprika'], 'maxTotalTimeInSeconds': 3600,
"ingredients": { "type": "string" }, "sourceURL": { "type": "string" }, "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:
from mycroft.skills import context import yummly import numpy as np import pandas as pd from yummly import Client __author__ = "aasta" LOGGER = getLogger(__name__) #initialize yummly TIMEOUT = 5.0 RETRIES = 0 client = Client(api_id = "bc03093e" , api_key = "66163b61d9724213d0a76744e93d89db", timeout = TIMEOUT, retries = RETRIES) #max rating from list of recipes def max_rating(matches): mat = matches["Rating"].idxmax() return client.recipe(matches.ix[mat,"ID"]) #min cooking time from list of recipes def min_time(matches): mat = matches["Total Time"].idxmin() return client.recipe(matches.ix[mat,"ID"]) #max serving size from list of recipes def max_servings(matches): mat = matches["Servings"].idxmax() return client.recipe(matches.ix[mat,"ID"])