def create_food_entry(request): """ Creates food entry in the specified user's food diary. :request_field integer user_id: BotMother user platform_id. :request_field string food_id: FS food_id. :request_field string serving_id: FS serving_id. :request_field float number_of_units: FS number_of_units. :response_field string entry_id: FS food_entry_id. :response_field boolean success """ user_id = int(request.POST['user_id']) food_id = str(request.POST['food_id']) serving_id = str(request.POST['serving_id']) number_of_units = float(request.POST['number_of_units']) if number_of_units <= 0: return JsonResponse({"success": False, "error": "Number of units must be positive"}) # Getting parameters for food entry creation 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) # Requesting datetime in my timezone dt = now().astimezone(pytz.timezone(settings.TIME_ZONE)).replace(tzinfo=None) meal = hour_to_meal(dt.hour) entry_name = "{}: {}".format(dt.ctime(), fs.food_get(food_id)['food_name']) # Creating food entry in FS database entry_id_dict = fs.food_entry_create(food_id, entry_name, serving_id, number_of_units, meal) return JsonResponse({"success": True, "entry_id": entry_id_dict["value"]})
def get_serving_for_food_id(request): """ Gets the serving we need for the specified food item. :request_field integer food_id: FS food_id. :response_field string measure: Metric serving unit (g, ml). :response_field string serving_id: Metric serving unit (g, ml). :response_field boolean success """ food_id = str(request.POST['food_id']) fs = Fatsecret(settings.CONSUMER_KEY, settings.CONSUMER_SECRET) servings = fs.food_get(food_id)["servings"]["serving"] if isinstance(servings, dict): needed_serving = servings else: # Branded food, only one serving option, not list of servings needed_serving = servings[-1] measure = needed_serving["metric_serving_unit"] serving_id = needed_serving["serving_id"] return JsonResponse({"success": True, "measure": measure, "serving_id": serving_id})
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}
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)
# 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 print("\n\n ------ OAuth Example ------ \n\n")
# 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 print("\n\n ------ OAuth Example ------ \n\n")
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