Esempio n. 1
0
def fetch_recipe_nutrition(title, servings, ingredient_list):
    argument = argparser_results()
    DATA_DIR = os.path.abspath(argument['DATA_DIR'])
    config = configparser_results(f'{DATA_DIR}/config.ini')

    app_id = config.get('third_party', 'edamam_id')
    app_key = config.get('third_party', 'edamam_key')

    if not app_id or not app_key:
        return False

    print(f' * Searching for nutrition information on {title}')

    params = {'app_id': app_id, 'app_key': app_key}
    headers = {'Content-Type': 'application/json'}
    ingredient_dict = {
        'title': title,
        'yield': servings,
        'ingr': ingredient_list
    }

    r = requests.post('https://api.edamam.com/api/nutrition-details',
                      params=params,
                      headers=headers,
                      json=ingredient_dict)

    if r.status_code != 200:
        print(
            f" * ERROR: Could not fetch nutrition data. | Code:({r.status_code} Message:{r.json()['error']})"
        )
        return False

    r_json = r.json()

    nutrition_dict = {
        'weight': r_json.get('totalWeight'),
        'nutrients': {
            'calcium': r_json['totalNutrients'].get('CA'),
            'carbs': r_json['totalNutrients'].get('CHOCDF'),
            'cholesterol': r_json['totalNutrients'].get('CHOLE'),
            'energy': r_json['totalNutrients'].get('ENERC_KCAL'),
            'fat': r_json['totalNutrients'].get('FAT'),
            'fiber': r_json['totalNutrients'].get('FIBTG'),
            'folate_equivalent': r_json['totalNutrients'].get('FOLDFE'),
            'folate_food': r_json['totalNutrients'].get('FOLFD'),
            'iron': r_json['totalNutrients'].get('FE'),
            'magnesium': r_json['totalNutrients'].get('MG'),
            'monounsaturated': r_json['totalNutrients'].get('FAMS'),
            'niacin_b3': r_json['totalNutrients'].get('NIA'),
            'phosphorus': r_json['totalNutrients'].get('P'),
            'polyunsaturated': r_json['totalNutrients'].get('FAPU'),
            'potassium': r_json['totalNutrients'].get('K'),
            'protein': r_json['totalNutrients'].get('PROCNT'),
            'riboflavin_b2': r_json['totalNutrients'].get('RIBF'),
            'saturated': r_json['totalNutrients'].get('FASAT'),
            'sodium': r_json['totalNutrients'].get('NA'),
            'sugars': r_json['totalNutrients'].get('SUGAR'),
            'sugars_added': r_json['totalNutrients'].get('SUGAR.added'),
            'thiamin_b1': r_json['totalNutrients'].get('THIA'),
            'trans': r_json['totalNutrients'].get('FATRN'),
            'vitamin_a': r_json['totalNutrients'].get('VITA_RAE'),
            'vitamin_b12': r_json['totalNutrients'].get('VITB12'),
            'vitamin_b6': r_json['totalNutrients'].get('VITB6A'),
            'vitamin_c': r_json['totalNutrients'].get('VITC'),
            'vitamin_d': r_json['totalNutrients'].get('VITD'),
            'vitamin_e': r_json['totalNutrients'].get('TOCPHA'),
            'vitamin_k': r_json['totalNutrients'].get('VITK1')
        },
        'daily': {
            'calcium': r_json['totalDaily'].get('CA'),
            'carbs': r_json['totalDaily'].get('CHOCDF'),
            'cholesterol': r_json['totalDaily'].get('CHOLE'),
            'energy': r_json['totalDaily'].get('ENERC_KCAL'),
            'fat': r_json['totalDaily'].get('FAT'),
            'fiber': r_json['totalDaily'].get('FIBTG'),
            'folate_equivalent': r_json['totalDaily'].get('FOLDFE'),
            'folate_food': r_json['totalDaily'].get('FOLFD'),
            'iron': r_json['totalDaily'].get('FE'),
            'magnesium': r_json['totalDaily'].get('MG'),
            'monounsaturated': r_json['totalDaily'].get('FAMS'),
            'niacin_b3': r_json['totalDaily'].get('NIA'),
            'phosphorus': r_json['totalDaily'].get('P'),
            'polyunsaturated': r_json['totalDaily'].get('FAPU'),
            'potassium': r_json['totalDaily'].get('K'),
            'protein': r_json['totalDaily'].get('PROCNT'),
            'riboflavin_b2': r_json['totalDaily'].get('RIBF'),
            'saturated': r_json['totalDaily'].get('FASAT'),
            'sodium': r_json['totalDaily'].get('NA'),
            'sugars': r_json['totalDaily'].get('SUGAR'),
            'sugars_added': r_json['totalDaily'].get('SUGAR.added'),
            'thiamin_b1': r_json['totalDaily'].get('THIA'),
            'trans': r_json['totalDaily'].get('FATRN'),
            'vitamin_a': r_json['totalDaily'].get('VITA_RAE'),
            'vitamin_b12': r_json['totalDaily'].get('VITB12'),
            'vitamin_b6': r_json['totalDaily'].get('VITB6A'),
            'vitamin_c': r_json['totalDaily'].get('VITC'),
            'vitamin_d': r_json['totalDaily'].get('VITD'),
            'vitamin_e': r_json['totalDaily'].get('TOCPHA'),
            'vitamin_k': r_json['totalDaily'].get('VITK1')
        }
    }

    # Only keep the quantity value for each item
    keys = nutrition_dict['nutrients'].keys()
    for section in ['nutrients', 'daily']:
        for key in keys:
            if nutrition_dict[section][key]:
                nutrition_dict[section][key] = nutrition_dict[section][key][
                    'quantity']

    return nutrition_dict
Esempio n. 2
0
import os
from saltToTaste.argparser_handler import argparser_results

argument = argparser_results()
DATA_DIR = os.path.abspath(argument['DATA_DIR'])

# Create the DATA_DIR if it doesn't exist
if not os.path.exists(DATA_DIR):
    try:
        os.makedirs(DATA_DIR)
    except OSError:
        raise SystemExit(f'Could not create data directory: {DATA_DIR}. Exiting....')
# Make sure the DATA_DIR is writeable
if not os.access(DATA_DIR, os.W_OK):
    raise SystemExit(f'Cannot write to the data directory: {DATA_DIR}. Exiting...')

# Make DATA_DIR subfolders if they don't exist
subfolders = ['_recipes', '_images', 'backups']
for folder in subfolders:
    if not os.path.exists(f'{DATA_DIR}/{folder}'):
        try:
            os.makedirs(f'{DATA_DIR}/{folder}')
        except OSError:
            raise SystemExit(f'Could not create data directory: {DATA_DIR}/{folder}. Exiting....')
    # Make sure the subfolder is writeable
    if not os.access(f'{DATA_DIR}/{folder}', os.W_OK):
        raise SystemExit(f'Cannot write to the data directory: {DATA_DIR}/{folder}. Exiting...')
Esempio n. 3
0
def create_app(config_file='settings.py'):
    argument = argparser_results()
    DATA_DIR = os.path.abspath(argument['DATA_DIR'])

    app = Flask(__name__)
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
    app.config['SQLALCHEMY_ECHO'] = False
    app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{DATA_DIR}/database.db'
    app.config['WHOOSH_INDEX_PATH'] = f'{DATA_DIR}/whooshIndex'
    app.config['WHOOSH_ANALYZER'] = 'StemmingAnalyzer'
    app.config['DATA_DIR'] = DATA_DIR
    app.config['RECIPE_FILES'] = f'{DATA_DIR}/_recipes/'
    app.config['RECIPE_IMAGES'] = f'{DATA_DIR}/_images/'
    app.config['CONFIG_INI'] = f'{DATA_DIR}/config.ini'
    app.jinja_env.filters['capwords'] = capwords

    if not os.path.isfile(app.config['CONFIG_INI']):
        create_default_configfile()

    verify_configfile()
    config = configparser_results(app.config['CONFIG_INI'])

    try:
        app.config['SECRET_KEY'] = config.get('flask', 'secret_key')
    except TypeError:
        print('Error: Could not find Flask secret_key in config.ini.')
        sys.exit()

    # Register blueprints
    app.register_blueprint(main)
    app.register_blueprint(api, url_prefix='/api')

    # Create indexes of database tables
    wa.search_index(app, Recipe)
    wa.search_index(app, Tag)
    wa.search_index(app, Ingredient)
    wa.search_index(app, Direction)
    wa.search_index(app, Note)

    # Initalize and create the DB
    db.init_app(app)
    db.app = app
    db.create_all()

    # Initalize the login manager plugin
    login_manager.init_app(app)
    login_manager.login_view = 'main.login'
    login_manager.login_message_category = 'info'

    @login_manager.user_loader
    def load_user(user_id):
        return User.query.get(user_id)

    # Import phyiscal recipe files
    recipe_list = recipe_importer(app.config['RECIPE_FILES'])

    # Sync physical recipe files with database
    if not Recipe.query.first():
        add_all_recipes(recipe_list)
    else:
        add_new_recipes(recipe_list)
        remove_missing_recipes(recipe_list)
        update_recipes(recipe_list)

    db_cleanup()

    return app