In [1]:
from yummly import Client
import json
import requests
import pandas as pd
import numpy as np 
import re

In [2]:
# API call for the first 500 BB recipes labeled as such only!
header= {'X-Yummly-App-ID':'79663a75', 'X-Yummly-App-Key':'02b233108f476f3110e0f65437c4d6dd'}
url='http://api.yummly.com/v1/api/recipes?'
parameters={
            'allowedCourse[]':'course^course-Salads',
            'excludedCourse[]': ['course^course-Main Dishes','course^course-Appetizers', 'course^course-Soups', 'course^course-Lunch',
                                'course^course-Side Dishes','course^course-Desserts','course^course-Breads',
                                 'course^course-Breakfast and Brunch', 'course^course-Beverages', 'course^course-Condiments and Sauces',
                                'course^course-Cocktails', 'course^course-Snacks'],
            'maxResult': 500,
            'start': 1000
            }

response=requests.get(url, headers = header, params = parameters)

In [3]:
response.status_code


Out[3]:
200

In [4]:
SLD=response.json()
print type(SLD)
print SLD.keys()


<type 'dict'>
[u'matches', u'totalMatchCount', u'attribution', u'facetCounts', u'criteria']

In [5]:
#only interrested in the information under matches. 
print len(SLD['matches'])
print type(SLD['matches'])
print SLD['matches'][0].keys()


500
<type 'list'>
[u'flavors', u'rating', u'totalTimeInSeconds', u'ingredients', u'smallImageUrls', u'sourceDisplayName', u'recipeName', u'attributes', u'id', u'imageUrlsBySize']

In [6]:
#checkout one recipe
SLD_matches=SLD['matches']
SLD_matches[499]


Out[6]:
{u'attributes': {u'course': [u'Salads'], u'holiday': [u'Summer']},
 u'flavors': {u'bitter': 0.16666666666666666,
  u'meaty': 0.16666666666666666,
  u'piquant': 0.0,
  u'salty': 0.16666666666666666,
  u'sour': 0.8333333333333334,
  u'sweet': 0.5},
 u'id': u'Watermelon-Salad-1631724',
 u'imageUrlsBySize': {u'90': u'https://lh3.googleusercontent.com/6UxyAd3dnxVOZvbIetkwmoG4Fz0tFpea3SzxAsarv02n3gYgR-SVuv_7Le4-vGrgjjFZrz2Qce14fSZNwYwu=s90-c'},
 u'ingredients': [u'watermelon',
  u'arugula',
  u'crumbled blue cheese',
  u'roasted sunflower seeds',
  u'raspberry vinaigrette',
  u'salt',
  u'pepper'],
 u'rating': 4,
 u'recipeName': u'Watermelon Salad',
 u'smallImageUrls': [u'https://lh3.googleusercontent.com/vLmESP1jZHa-UgMEFDUpFVxn_cRQONTbTERJHtdyT_CF91JTUlcR2Ye2lNDN6QnatqRIuWEZqpc-ngmh9GOBDA=s90'],
 u'sourceDisplayName': u'Add a Pinch',
 u'totalTimeInSeconds': 600}

In [7]:
#import previous list of recipes collected
df=pd.read_csv('SLD_main.csv')
df1=pd.read_csv('SLD_main_1.csv')
SLD_ids=df.id
SLD1_ids=df1.id
print SLD_ids[0]
print SLD1_ids[0]
SLD2_ids=[]
for recipe in SLD_matches:
    SLD2_ids.append(recipe['id'])
print SLD2_ids[0]
#check if there are dupplicate recipes
[i for i, j in zip(SLD_ids, SLD2_ids) if i == j]
[i for i, j in zip(SLD1_ids, SLD2_ids) if i == j]


Greek-Pasta-Salad-1712241
Apple-Coleslaw-1680966
Lemony-Coleslaw-with-Apples-1700377
Out[7]:
[]

In [8]:
#forming lists to create dataframes of the features we want. 
main_list = []
ingredients_list = []
attributes_list = []


for food in SLD_matches:

    _d1 = {}
    _d1['id'] = food['id']
    _d1['rating'] = food['rating']
    _d1['recipeName'] = food['recipeName']
    _d1['sourceDisplayName'] = food['sourceDisplayName']
    main_list.append(_d1)
    
    _d2 = {}
    _d2['id'] = food['id']
    _d2['course'] = 'Breakfast and Brunch' 
    _d2['ingredient_list'] =  food['ingredients']
    for i in food['ingredients']:
        i = i.lower() # additional code to convert to lowercase
        i = re.sub(r'\d+%\s', '', i) # additional code to remove 1%, 2%, etc
        i = re.sub(r'\xae', '', i) # remove '\xae' characters
        i = re.sub(r'shredded\s', '', i)
        i = re.sub(r'chopped\s', '', i)
        i = re.sub(r'diced\s', '', i)
        i = re.sub(r'crumbled\s', '', i)
        i = re.sub(r'fresh\s', '', i)
        i = re.sub(r'grated\s', '', i)
        i = re.sub(r'fat free\s', '', i)
        i = re.sub(r'boneless\s', '', i)
        i = re.sub(r'boneless skinless\s', '', i)
        i = re.sub(r'minced\s', '', i)
        i = re.sub(r'sliced\s', '', i)
        i = re.sub(r'(?!ground beef)ground ', '', i)
        i = re.sub(r'^dried\s', '', i)
        i = re.sub(r'^cooked\s', '', i)
        
        _d2[i] = 1
    ingredients_list.append(_d2)

    _d3 = {}
    _d3['id'] = food['id']
    for k, v in food['attributes'].items():
        for i in v:
            _d3[i] = 1
    attributes_list.append(_d3)

flavors_dict = {}

for food in SLD_matches:
    flavors_dict[food.get('id')] = food.get('flavors')

In [9]:
# read in csv for cuisine and create list of possible values 
cuisine_df = pd.read_csv('/Users/bruktawitabebe/Desktop/Yummly/cuisine_headers.csv', names=['cuisine'])
cuisine_list= cuisine_df.cuisine

In [10]:
#create dictionary of cuisine and course for each recipe

cuisine_dict={}
for food in SLD_matches:
    cuisine_dict[food.get('id')]= food['attributes'].get('cuisine')
            
_cuisines= {}       

for k, v in cuisine_dict.iteritems():
    cuisine_val = {}
    for course in cuisine_list:
        try:
            if course in v :
                cuisine_val[course] = 1
            else:
                cuisine_val[course] = 0
        except TypeError:
            cuisine_val[course] = 0
    
        _cuisines[k] = cuisine_val

In [11]:
#get list of recipe ids
recipe_ids=[]
for recipe in SLD_matches:
    recipe_ids.append(recipe['id'])

In [12]:
# second api call to get other features for each recipe
key_id= '_app_id=79663a75&_app_key=02b233108f476f3110e0f65437c4d6dd'
url='http://api.yummly.com/v1/api/recipe/'

In [13]:
# retrieve other features for all recipes

def get_recipe(_id):
    response = requests.get(url + _id + '?' + key_id)
    return response.json()

recipes=[]
for _id in recipe_ids :
    recipes.append(get_recipe(_id))

In [14]:
response.status_code


Out[14]:
200

In [15]:
print len(recipes)
print recipes[1].keys()


500
[u'totalTime', u'ingredientLines', u'attribution', u'name', u'rating', u'numberOfServings', u'yield', u'nutritionEstimates', u'source', u'flavors', u'images', u'attributes', u'id', u'totalTimeInSeconds']

In [16]:
#for each recipe create a new dictionary of selected attributes and append into a list

recipe_details=[]
for recipe in recipes:
    _dict={}
    #import pdb; pdb.set_trace()
    _dict['id']=recipe['id']
    _dict['ingredientCount'] = len(recipe['ingredientLines'])
    _dict['numberOfServings'] = recipe['numberOfServings']
    _dict['prepTimeInSeconds'] = recipe.get('prepTimeInSeconds')
    _dict['cookTimeInSeconds'] = recipe.get('cookTimeInSeconds')
    _dict['totalTimeInSeconds'] = recipe.get('totalTimeInSeconds')
    
    recipe_details.append(_dict)

In [17]:
#create dataframes, arrange column index and save into csv
df_main = pd.DataFrame(main_list)
df_main.to_csv('SLD_main_2.csv', encoding ='utf-8')

df_ingredients = pd.DataFrame(ingredients_list)
df_ingredients = df_ingredients.fillna(0)
cols = list(df_ingredients)
cols.insert(0, cols.pop(cols.index('id')))
cols.insert(1, cols.pop(cols.index('course')))
df_ingredients= df_ingredients.ix[:,cols]
df_ingredients.to_csv('SLD_ingredients_2.csv', encoding ='utf-8')

df_attributes = pd.DataFrame(attributes_list)
df_attributes = df_attributes.fillna(0)
cols = list(df_attributes)
cols.insert(0, cols.pop(cols.index('id')))
df_attributes = df_attributes.ix[:,cols]
df_attributes.to_csv('SLD_attributes_2.csv')

df_flavors = pd.DataFrame(flavors_dict).transpose()
df_flavors.reset_index(level=0, inplace=True)
df_flavors.to_csv('SLD_flavors_2.csv')

df_cuisines = pd.DataFrame(_cuisines).transpose()
df_cuisines.reset_index(level=0, inplace=True)
df_cuisines.to_csv('SLD_cuisines_2.csv')

df_details=pd.DataFrame(recipe_details)
cols = list(df_details)
cols.insert(0, cols.pop(cols.index('id')))
df_details=df_details.ix[:,cols]
df_details.to_csv('SLD_details_2.csv')