def main(): filename = "tags.txt" badTags = [ "no person", "fruit", "food", "nutrition", "confection", "health", "tropical", "bunch", "healthy", "glass", "foam", "alcohol", "pub", "drink", "lager", "sesame", "unhealthy", "fast", "lunch", "mayonnaise", "bird", "poultry", "hen", "animal", "feather", "farm", "nature", "desktop", "wing", "meat", "barbecue", "fillet", "dinner", "vegetable", "pastry", "delicious", "refreshment", "delicious", "homemade", "citrus", "juice", "juicy", "isolated", "desktop", "meal", "plate", "bowl", "cuisine", "cooking", "person", "calcium", "cream", "glass", "cold", "closeup", "diet", "epicure", "close", "skin", "texture", "breakfast", "half", "moon", "grow", "one", "old", "wood", "stick" ] f0 = open(filename) lines = [line.rstrip('\n') for line in f0] f0.close #print(lines) #remove bad tags from the list goodList = [x for x in lines if x not in badTags] consumerkey = "916c5699f1614b4bb2b939a76df609b1" consumersecret = "ec94e8fc8be7483f810a81f7cba32c14" fs = Fatsecret(consumerkey, consumersecret) #print(goodList) try: foods = fs.foods_search(goodList[0], 0, 1) except Exception: print("titty tats") foods = str(fs.foods_search("chicken tenders", 0, 1)[0]) pass if isinstance(foods, list): stringFood = str(foods[0]) #first entry else: stringFood = str(foods) s = stringFood.replace("u'", "\"") #strip u' 's s2 = s.replace("\'", "\"") #turn single quotes to double quotes # Open a file to write our shit to fo = open("guac.json", "w") fo.write(s2) # Close opend file fo.close()
def food_search(user_id, search_string): """Searches the specified query in the FS database. :param user_id: BotMother user platform_id. :type user_id: int :param search_string: Search query for FS food search. :type search_string: str """ user = BotUser.objects.get(bot_user_id=user_id) session_token = user.fatsecret_oauth_token, user.fatsecret_oauth_token_secret fs = Fatsecret(settings.CONSUMER_KEY, settings.CONSUMER_SECRET, session_token=session_token) food_names = [] food_ids = [] try: results = fs.foods_search(search_string)[:4] except KeyError: # Found nothing, eg query in Russian return for food_item in results: food_names.append(food_item["food_name"]) food_ids.append(food_item["food_id"]) return {"success": True, "food_names": food_names, "food_ids": food_ids}
def show(food_name): fs = Fatsecret(consumer_key, consumer_secret) foods = fs.foods_search(food_name) #print("Food Search Results: {}".format(len(foods))) #print("{}\n".format(foods)) food_id = str(foods[0]["food_id"]) #print(food_id) f = open('helloworld.html', 'w') message1 = """<!DOCTYPE html > <html> <head> <title>Sample Code</title> <style> body { font-family: Arial; font-size: 12px; } .title{ font-size: 200%; font-weight:bold; margin-bottom:20px; } .holder{ width:300px; margin:0 auto; padding: 10px; } </style> <script src="http://platform.fatsecret.com/js?key=8575eae8dc11485090730817b5c67c94&auto_template=false&theme=none"></script> <script> function doLoad(){ fatsecret.setContainer('container'); fatsecret.setCanvas("food.get", {food_id: """ message2 = """}); } </script> </head> <body onload="doLoad()"> <div class="holder"> <div class="title"><script>fatsecret.writeHolder("foodtitle");</script></div> <script>fatsecret.writeHolder("nutritionpanel");</script> <div id="container"></div> </div> </body> </html>""" f.write(message1 + food_id + message2) f.close() #Change path to reflect file location filename = 'file:///Users/wd4446/Box Sync/Adv_Predictive_Modeling/Image_Recognition/model2.0/demo_test/' + 'helloworld.html' webbrowser.open_new_tab(filename)
class SofiaAPI: def __init__(self, intent_request, session): self.session = session self.fs = Fatsecret(oauth_consumer_key, oauth_secret_key) self.calorie_count = 0 # self.request_date = datetime.strptime(intent_request['timestamp'], "%Y-%m-%dT%H:%M:%SZ") # ------- Interface with the Intents ---------- #def save_exercise(self, exercise_name, duration): #method = "method":"exercises.get" # response = encode([method]) # if response is not None: # exercise_name = response.exercise_types.exercise[0].exercise_name # method = "exercise_entries.commit_day" # #return encode([method, self.auth_token]) def calculate(self, response_type): if self.calorie_count < 500: return "You have eaten way too little today! Only "+ calorie_count + " calories!" elif self.calorie_count < 1000 and calorie_count > 500: return "You are doing well today. You have eaten "+ calorie_count + " calories!" elif self.calorie_count > 1000: return "You have eaten way too much, you fatty!" def add_food(self, food_name): foods = self.fs.foods_search(food_name) if foods is not None: food_description = foods[0]['food_description'] print(food_description) food_id = foods[0]['food_id'] food_name = foods[0]['food_name'] #self.fs.food_entry_create(food_id, food_name, 0, 1, "breakfast", date=None) print(food_description) return self.get_calories(food_description) return "Could not find this food type." def get_calories(self, str): index = str.find("Calories: ") if index != -1: str = str[index+9: index+13] cals = str.strip(' ') self.calorie_count = self.calorie_count + int(cals) return cals else: return 0 def configure_me(self, height, weight, age, gender): return "2000" # self.fs.profile_create(user_id=None) # if weight: # if height: # return self.set_weight(weight, height) # else: # return self.set_weight(weight, 180) def set_weight(self, weight, height): self.fs.weight_update(weight, date=None, weight_type='kg', height_type='cm', goal_weight_kg=None, current_height_cm=None, comment=None)
def food_calorie(): if request.method == "GET": if 'lastSearchedFoodItem' in session.keys(): return render_template('food_calorie.html', food=session['lastSearchedFoodItem'], foodList=enumerate( session['lastSearchedFoodList']), diet=enumerate(session['diet'].items()), summary=totalCalories(session['diet'])) else: return render_template('food_calorie.html', diet=session['diet']) elif request.method == "POST": # Handling the Search Bar if "search" in request.form: print(request.form) foodItem = request.form.get('fooditem') fs = Fatsecret(CONSUMER_KEY, CONSUMER_SECRET) foodItems = fs.foods_search(foodItem) foodList = [] for food in foodItems: foodList.append(record_to_dict(food)) session['lastSearchedFoodList'] = foodList session['lastSearchedFoodItem'] = foodItem session.modified = True return render_template('food_calorie.html', food=foodItem, foodList=enumerate(foodList), diet=enumerate(session['diet'].items()), summary=totalCalories(session['diet'])) # Updation to the Account Page else: # Here we are by default updating the food entries # in terms of each field like Calories and Carbs for id, record in session['diet'].items(): record = updatedQuantityRecord(record) foodItem = Food(name=record['food_name'], quantity=record['quantity'], perServing=record['serving_size'], totalCalorie=record['Calories'], totalCarbs=record['Carbs'], totalFat=record["Fat"], totalProtein=record['Protein'], eatingDate=datetime.now(), foodEater=current_user) db.session.add(foodItem) db.session.commit() session['diet'] = {} return redirect(url_for('account'))
def main(): filename="tags.txt" badTags=["no person", "fruit", "food", "nutrition", "confection", "health", "tropical", "bunch", "healthy", "glass", "foam", "alcohol", "pub", "drink", "lager", "sesame", "unhealthy", "fast", "lunch", "mayonnaise", "bird", "poultry", "hen", "animal", "feather", "farm", "nature", "desktop", "wing", "meat", "barbecue", "fillet", "dinner", "vegetable", "pastry", "delicious", "refreshment", "delicious", "homemade", "citrus", "juice", "juicy", "isolated", "desktop", "meal", "plate", "bowl", "cuisine", "cooking", "person", "calcium", "cream", "glass", "cold"] consumerkey = "916c5699f1614b4bb2b939a76df609b1" consumersecret = "ec94e8fc8be7483f810a81f7cba32c14" #read file tags.txt into a list f0 = open(filename) lines = [line.rstrip('\n') for line in f0] f0.close #print(lines) #remove bad tags from the list goodList = [x for x in lines if x not in badTags] #print(goodList) #write the goodList to a new file tags2.txt f1 = open("tags2.txt", "w") for item in goodList: f1.write("%s\n" % item) f1.close() fs = Fatsecret(consumerkey, consumersecret) foods = fs.foods_search(goodList[0], 0, 1) #print(foods) stringFood = str(foods[0]) #top good tag used here s=stringFood.replace("u'","\"") #strip u' 's s2=s.replace("\'","\"") #turn single quotes to double quotes #print(s2) # Open a file to write our result to, then close it f2 = open("guac.json", "w") f2.write(s2) f2.close()
def create_food_attributes(food, amount=None, measurement=None): consumer_key = '2430c39a9a3545fe95340690808444f7' consumer_secret = '9d60923bee3c4a209b053bcacd8f7159' fs = Fatsecret(consumer_key, consumer_secret) searchResults = fs.foods_search(str(food), max_results=10) finalFood = None for result in searchResults: servingTypes = fs.food_get(result['food_id'])['servings']['serving'] if(not measurement or not amount): finalFood = servingTypes[0] break #endif for serving in servingTypes: if(not isinstance(serving, str) and measurement in serving['measurement_description'] and int(float(serving['number_of_units'])) == 1): finalFood = serving break #endif if(finalFood == None): finalFood = servingTypes[0] #endif # endfor # endfor fs.close() calories = int(int(finalFood['calories']) * (1 if amount == None else (amount/servingSize))) fat = int(round(float(finalFood['fat']) * (1 if amount == None else (amount/servingSize)))) carbs = int(round(float(finalFood['carbohydrate']) * (1 if amount == None else (amount/servingSize)))) protein = int(round(float(finalFood['protein']) * (1 if amount == None else (amount/servingSize)))) return {"carbs": carbs, "protein": protein, "fat": fat, "calories": calories}
from fatsecret import Fatsecret fs = Fatsecret('fd1d348919f0451894bd32b2d3de6e5c', '1a36ce0def3949229b8c638dd5838383') foods = fs.foods_search("Tacos") print(foods)
class Bot(object): def __init__(self, name=None, speech_input=False, facebook_input=False): self.phrases = Phrases() self.speech = Speech() self.knowledge = Knowledge(weather_api_token=weather_api_token) self.name = name self.facebook_input = facebook_input if self.facebook_input: self.facebook_response = list() self.speech_input = speech_input self.witai = Wit("S73IKQDWJ22OJMOSD6AOT4CSJOWXIPX6") self.fs = Fatsecret("90fe184a283449ed8a83e35790c04d65", "054e80b2be154337af191be2c9e11c28") self.translator = Translator() def gr_to_en(self, text): return self.translator.translate(text, 'en', 'el').text def en_to_gr(self, text): return self.translator.translate(text, 'el', 'en').text def start(self): if self.speech_input or self.facebook_input: self.decide_action() else: print("Γεία σου! Πως θα μπορούσα να σε βοηθήσω;") while 1: self.decide_action() def learn_action(self, filename, phraseslist): Knowledge.learn_default_responses(file=filename, phrases=phraseslist) def decide_action(self, facebook_input=None): if self.speech_input or self.facebook_input: if self.speech_input: recognizer, audio = self.speech.listen_for_audio() # received audio data, now we'll recognize it using Google Speech Recognition bot_input = self.speech.google_speech_recognition(recognizer, audio) if self.facebook_input: self.facebook_response[:] = [] bot_input = facebook_input else: bot_input = input() if bot_input is not None: try: resp = self.witai.message(bot_input) entities = None intent = None if 'entities' in resp and 'intent' in resp['entities']: entities = resp['entities'] intent = resp['entities']['intent'][0]["value"] # print('Intent: {intent}'.format(intent=intent)) if intent == 'greeting': self.__text_action(self.phrases.get_phrases('greetings_phrases')) elif intent == 'tutorial': self.__tutorial_action() elif intent == 'name': if self.name is not None: self.__text_action(self.phrases.get_phrases('name_phrases').replace('<name>', self.name)) else: self.__text_action('Οι δημιουργοί μου δεν μου έδωσαν κάποιο όνομα') elif intent == 'swear': self.__text_action(self.phrases.get_phrases('swear_phrases')) elif intent == 'funny': self.__text_action(self.phrases.get_phrases('funny_phrases')) elif intent == 'sex_type': self.__text_action('Λίγο απ\'όλα') elif intent == 'user_joke': self.__text_action('χαχαχα') elif intent == 'personal_status': self.__personal_status() elif intent == 'joke': self.__joke_action() elif intent == 'datetime': # print(resp) self.__datetime_action(entities) elif intent == 'weather': self.__weather_action() elif intent == 'search': self.__search_action(entities) elif intent == 'food_det': self.__food_action(entities) elif intent == 'recipe': self.__recipe_action(entities) elif intent == 'thanksgiving': self.__text_action(self.phrases.get_phrases('thanks_phrases')) elif intent == 'sticker': self.__text_action('Επίσης') else: # No recognized intent # print('Intent not recognized') self.__text_action(self.phrases.get_phrases('unrecognized_intent_phrases')) return except Exception as e: print("Exception occured") print(e) traceback.print_exc() self.__text_action("Έγινε κάποιο λάθος") return def __text_action(self, text=None): if text is not None: if self.speech_input: self.speech.synthesize_text(text) if self.facebook_input: self.facebook_response.append(text) if not (self.facebook_input or self.speech_input): print(text) def __tutorial_action(self): self.__text_action(self.phrases.get_phrases('tutorial_phrases')) def __personal_status(self): self.__text_action(self.phrases.get_phrases('personal_status_phrases')) def __joke_action(self): joke = self.phrases.get_phrases('joke_phrases') self.__text_action(joke) def __datetime_action(self, entities): dt = None if 'date' in entities: dt = entities['date'][0]['value'] print('Datetime: {dt}'.format(dt=dt)) if str(dt) == 'hour': self.__text_action('Η ώρα είναι {time}'.format(time=self.knowledge.get_time())) elif str(dt) == 'day': self.__text_action('Σήμερα είναι {weekday}'.format(weekday=self.knowledge.get_weekday())) elif str(dt) == 'date': self.__text_action('Σήμερα είναι {date}'.format(date=self.knowledge.get_date())) def __weather_action(self): weather_obj = self.knowledge.find_weather() self.__text_action('Η θερμοκρασία είναι ' + str(weather_obj['temperature']) + '° Κελσίου.') def __search_action(self, entities=None): self.__text_action(self.phrases.get_phrases('search_phrases')) if 'wikipedia_search_query' in entities: query = entities['wikipedia_search_query'][0]['value'] # print('wikipedia query: {query}'.format(query=query)) wikipedia.set_lang("el") try: self.__text_action(re.sub(r'\([^)]*\)', '', wikipedia.summary(query, sentences=1))) except wikipedia.PageError as e: print(e) self.__text_action('Δεν βρήκα κάποιο αποτέλεσμα') else: self.__text_action('Δεν μου είπες τί να ψάξω') def __food_action(self, entities): self.__text_action(self.phrases.get_phrases('search_phrases')) inp = self.gr_to_en(entities['wikipedia_search_query'][0]['value']) try: resp = self.fs.foods_search(inp) food = self.fs.food_get(resp[0]['food_id']) if 'nutrient_type' in entities.keys(): self.__text_action( self.en_to_gr( '{type} - 1 {serving}'.format(serving=food['servings']['serving'][0]['measurement_description'], type=resp[0]["food_name"]))) for nutrient in entities['nutrient_type']: self.__text_action(self.en_to_gr('{nutrient}: {value}'.format(nutrient=nutrient['value'], value= food['servings']['serving'][0][ nutrient['value']]))) else: self.__text_action(self.en_to_gr(resp[0]["food_name"] + "\n" + resp[0]["food_description"])) except Exception as e: self.__text_action( "Δεν υπάρχουν διαθέσιμες διατροφικές πληροφορίες για " + entities['wikipedia_search_query'][0]['value']) self.__search_action(entities) def __recipe_action(self, entities): self.__text_action(self.phrases.get_phrases('search_phrases')) inp = self.gr_to_en(entities['wikipedia_search_query'][0]['value']) try: resp = self.fs.recipes_search(inp) recipe = self.fs.recipe_get(resp[0]['recipe_id']) if self.facebook_input: self.__text_action("Μπορείς να δεις την συνταγή στο παρακάτω link:") self.__text_action(recipe['recipe_url']) else: self.__text_action(self.en_to_gr(recipe['recipe_name'] + "\n")) self.__text_action("Οδηγίες") for dir in recipe['directions']['direction']: self.__text_action(self.en_to_gr(dir['direction_description'])) self.__text_action("Συστατικά") for ing in recipe['ingredients']['ingredient']: self.__text_action(self.en_to_gr(ing['ingredient_description'])) except Exception as e: self.__text_action( "Δεν υπάρχει διαθέσιμη συνταγή για " + entities['wikipedia_search_query'][0]['value']) self.__search_action(entities)
from fatsecret import Fatsecret # Be sure to add your own keys consumer_key = None consumer_secret = None fs = Fatsecret(consumer_key, consumer_secret) # Test Calls w/o authentication print("\n\n ---- No Authentication Required ---- \n\n") foods = fs.foods_search("Tacos") print("Food Search Results: {}".format(len(foods))) print("{}\n".format(foods)) food = fs.food_get("1345") print("Food Item 1345") print("{}\n".format(food)) recipes = fs.recipes_search("Tomato Soup") print("Recipe Search Results:") print("{}\n".format(recipes)) recipe = fs.recipe_get("88339") print("Recipe 88339") print("{}\n".format(recipe)) # Test Calls with 3 Legged Oauth
def main(): filename = "tags.txt" badTags = [ "no person", "fruit", "food", "nutrition", "confection", "health", "tropical", "bunch", "healthy", "glass", "foam", "alcohol", "pub", "drink", "lager", "sesame", "unhealthy", "fast", "lunch", "mayonnaise", "bird", "poultry", "hen", "animal", "feather", "farm", "nature", "desktop", "wing", "meat", "barbecue", "fillet", "dinner", "vegetable", "pastry", "delicious", "refreshment", "delicious", "homemade", "citrus", "juice", "juicy", "isolated", "desktop", "meal", "plate", "bowl", "cuisine", "cooking", "person", "calcium", "cream", "glass", "cold", "closeup", "diet", "epicure", "close", "skin", "texture", "breakfast", "half", "moon", "grow", "one", "old", "wood", "stick", ] f0 = open(filename) lines = [line.rstrip("\n") for line in f0] f0.close # print(lines) # remove bad tags from the list goodList = [x for x in lines if x not in badTags] consumerkey = "916c5699f1614b4bb2b939a76df609b1" consumersecret = "ec94e8fc8be7483f810a81f7cba32c14" fs = Fatsecret(consumerkey, consumersecret) # print(goodList) try: foods = fs.foods_search(goodList[0], 0, 1) except Exception: print("titty tats") foods = str(fs.foods_search("chicken tenders", 0, 1)[0]) pass if isinstance(foods, list): stringFood = str(foods[0]) # first entry else: stringFood = str(foods) s = stringFood.replace("u'", '"') # strip u' 's s2 = s.replace("'", '"') # turn single quotes to double quotes # Open a file to write our shit to fo = open("guac.json", "w") fo.write(s2) # Close opend file fo.close()
class Nutrition: def __init__(self): with open('keys.txt', 'r') as f: keys = f.read().splitlines() self.consumer_key = keys[0] self.consumer_secret = keys[1] self.fs = Fatsecret(self.consumer_key, self.consumer_secret) self.ignore = { 'measurement_description', 'metric_serving_amount', 'metric_serving_unit', 'number_of_units', 'serving_description', 'serving_id', 'serving_url' } self.units = { 'calories': 'kcal', 'cholesterol': 'mg', 'sodium': 'mg', 'potassium': 'mg', 'vitamin_d': 'mcg', 'vitamin_a': 'mcg', 'vitamin_c': 'mg', 'calcium': 'mg', 'iron': 'mg' } self.essential = { 'calories', 'carbohydrate', 'protein', 'fat', 'fiber', 'sugar' } def get_nutrition_general(self, food): food_id = self.fs.foods_search(food)[0]['food_id'] detailed = self.fs.food_get(food_id) name = detailed['food_name'].lower() url = detailed['food_url'] # print(type(detailed['servings']['serving'])) if isinstance(detailed['servings']['serving'], dict): serving = detailed['servings']['serving'] else: serving = detailed['servings']['serving'][0] # print(serving) serving_desc = serving['serving_description'] metric = 'g' res = f'In {serving_desc} {name} there are:\n' info = [] for key, val in serving.items(): if key in self.essential: unit = self.units[key] if key in self.units else metric key2 = 'total ' + key if key == 'carbohydrate' or key == 'fat' else key key2 = key2.replace('_', ' ') key2 = key2.split() key2 = map(lambda x: x.upper() if len(x) == 1 else x, key2) key2 = ' '.join(key2) info.append(f'{val}{unit} of {key2}') info[-1] = 'and ' + info[-1] info = ', '.join(info) res += info + '\n' res += f'More information can be found at {url}' return res def get_nutrition_specific(self, field, food): field = field.lower() food_id = self.fs.foods_search(food)[0]['food_id'] detailed = self.fs.food_get(food_id) name = detailed['food_name'].lower() url = detailed['food_url'] if isinstance(detailed['servings']['serving'], dict): serving = detailed['servings']['serving'] else: serving = detailed['servings']['serving'][0] serving_desc = serving['serving_description'] serving_desc = serving_desc.replace(name, '') metric = 'g' keys = list(serving.keys()) keys = [k for k in keys if k not in self.ignore] field = field.replace(' ', '_') most_similar, min_dist = None, None for k in keys: distance = nltk.edit_distance(field, k) if most_similar is None or distance < min_dist: most_similar, min_dist = k, distance res = "" if min_dist >= 4: res += "The field you want information on may not be in my database for this food...\n" desired_val = serving[most_similar] unit = self.units[ most_similar] if most_similar in self.units else metric most_similar = most_similar.replace('_', ' ') most_similar = most_similar.split() most_similar = map(lambda x: x.upper() if len(x) == 1 else x, most_similar) most_similar = ' '.join(most_similar) res += f'In {serving_desc} {name} there is {desired_val}{unit} of {most_similar}' return res