Exemple #1
0
                "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:
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
Exemple #3
0
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),
                             )
Exemple #4
0
# 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]
Exemple #5
0
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)
Exemple #6
0
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"])