Giter VIP home page Giter VIP logo

menu_del_dia's Introduction

Meal Planning Service for Every Day

Project Description

This project is a service for creating a daily meal plan. The main idea is to help users plan their diet by providing them with a list of dishes and recipes for the next day. This can be implemented through a Telegram bot or email newsletter.

Concept

Survey and Personalization

  • The user starts by taking a survey (after successful testing of the MVP), where they provide the following information:
    • Number of people the meal plan is for (or number of servings).
    • Preferences for food items: meat, mushrooms, poultry, seafood (shrimp, mussels), white fish, red fish.
    • Preferred dishes for lunch and dinner: salad, soup, main course.

Concept

  • In the first message (before the start of the 7-day period), the user will receive:
    • A list of dishes for each day of the week.
    • A list of necessary ingredients and their quantities.
  • Every evening, the user receives a message with:
    • A list of dishes for breakfast, lunch, and dinner for the next day.
    • Recipes for these dishes.
    • A list of necessary ingredients and their quantities for cooking the dishes.

Disclaimer

  • The user is solely responsible for their health and well-being, especially if they have allergies or intolerances to certain foods. Before using the daily meal planning service, it is recommended to carefully assess dietary restrictions and consult a medical professional if necessary. Note that your personal food preferences and restrictions should be considered when choosing dishes from the provided recipes.
  • Naturally, I used someone else's recipes as a base, but all of them have been adapted to suit the taste of our family.
  • The recipe database will be kept private.

Feedback

  • Users can provide feedback and suggestions through:
    • A Google form for constructive criticism with a predefined structure.
    • The bot or email.

CRON jobs

0 10 * * 0 /path/to/python /path/to/menu_generator.py
1 10 * * 0 /path/to/python /path/to/weekly_message_sender.py
0 18 * * * /path/to/python /path/to/daily_message_sender.py

Motivation (Manifesto)

  1. This project solves my problem and is aimed at satisfying my needs for meal planning.

  2. I am creating this service because I want it to meet my requirements:

    • Inclusion of only tried and tested dishes in the database.
    • Interface through a Telegram bot.
    • Minimalistic recipe text.
    • Ability to create a grocery shopping list for the week ahead.

Сервис по составлению меню питания на каждый день

Описание проекта

Этот проект представляет собой сервис для составления меню питания на каждый день. Главная идея заключается в том, чтобы помочь пользователям планировать свой рацион, предоставляя им список блюд и рецептов на следующий день. Это может быть реализовано через телеграм-бота или email-рассылку.

Концепция

Опрос и персонализация

  • Пользователь начинает с прохождения опроса (после успешного тестирования MVP), где указывает следующую информацию:
    • Количество человек, на которых рассчитан рацион (или количество порций).
    • Предпочтения по продуктам: мясо, грибы, мясо птицы, морепродукты (креветки, мидии), рыба белая, красная.
    • Предпочитаемые блюда на обед и ужин: салат, суп, горячее (второе).

Концепция

  • В первом сообщении (перед началом 7-дневного периода) будет отправлено на ознакомление:
    • Список блюд на каждый день недели.
    • Список необходимых продуктов и их количество.
  • Каждый вечер пользователь получает сообщение с:
    • Списком блюд на завтрак, обед и ужин на следующий день.
    • Рецептами для этих блюд.
    • Списком необходимых продуктов и их количеством для приготовления блюд.

Дисклеймер

  • Пользователь самостоятельно несет ответственность за свое здоровье и благополучие, особенно если у него есть аллергии или непереносимость определенных продуктов. Перед началом использования сервиса по составлению меню питания на каждый день, рекомендуется внимательно оценить свои диетические ограничения и консультироваться с медицинским специалистом при необходимости. Учтите, что ваши личные пищевые предпочтения и ограничения должны быть учтены при выборе блюд из предоставляемых рецептов.
  • Естественно, я брал за основу чьи-то рецепты, но все они были переработаны под вкус нашей семьи.
  • База данных рецептов будет скрыта.

Обратная связь

  • Пользователи могут отправлять отзывы и предложения через:
    • Google-форму для конструктивной критики с заранее заданной структурой.
    • Бота или почту.

Мотивация (манифест)

  1. Этот проект решает мою проблему и ориентирован на удовлетворение моих потребностей в планировании рациона питания.

  2. Я создаю этот сервис, потому что хочу, чтобы он соответствовал моим требованиям:

    • Включение в базу только проверенных и опробованных мною блюд.
    • Интерфейс через телеграм-бота.
    • Минималистичный текст с рецепта.
    • Возможность составления списка покупок на неделю вперед.

menu_del_dia's People

Contributors

mxteen avatar

Stargazers

 avatar

Watchers

 avatar

menu_del_dia's Issues

Likes and dislikes

Это позволит

  • чаще присылать рецепты из списка избранных;
  • в последствии на основе лайков и дизлайков можно сделать простенькую рекомендательную систему

Сбор обратной связи

придумать обратную связь - отправляешь ему рецепт, группа тестирования проверяет рецепт, дает оценки, рекомендации по изменению и запускается в работу с тегами - типа #обед #что-то-еще ))

Lunch and breaksfast ID should not duplicate

При многократном запуске этого кода всегда есть пересечения в кортежах с ID обедов и ужинов.

"""python

import sqlite3
N_DAYS = 7
DB_PATH = '..\data\recipes.db'
meal_types = ['breakfast', 'lunch', 'dinner']
meal_types_ru = ['Завтрак', 'Обед', 'Ужин']
days_of_week = ['Понедельник', 'Вторник', 'Среда', 'Четверг',
'Пятница', 'Суббота', 'Воскресенье']

def lst_to_str(lst: list) -> str:
"""
Convert a list of elements to a string representation.

Args:
    lst (list): The list of elements to be converted to a string.

Returns:
    str: A string representation of the input list with elements enclosed 
         in parentheses and separated by commas.

Examples:
    >>> lst_to_str([40, 41, 31, 43, 20, 23, 38])
    '(40, 41, 31, 43, 20, 23, 38)'
    >>> lst_to_str(['apple', 'banana', 'cherry'])
    "('apple', 'banana', 'cherry')"
    >>> lst_to_str([])
    '()'

Note:
    - If the input list is empty, an empty string with parentheses '()' 
      will be returned.
    - Elements in the list will be converted to their string 
      representations using the str() function.
"""
return '(' + ', '.join(map(str, lst)) + ')'

def read_menu(path):
# Read menu from JSON file
with open(path, 'r') as file:
menu = json.load(file)
return menu

Define SQLite query

GET_RANDOM_RECIPES = """
SELECT r.recipe_id
FROM recipe r
JOIN meal_type m ON r.meal_type_id = m.meal_type_id
WHERE {}
ORDER BY RANDOM() LIMIT ?
"""

def generate_weekly_menu():
"""
Generate a weekly menu by selecting random recipes for each meal type.

This function queries the database to retrieve random recipe IDs for each
meal type (breakfast, lunch, and dinner) based on specified conditions.
The conditions ensure that for breakfast, only breakfast recipes are
selected, while for lunch and dinner, recipes can be chosen from a broader
category. Additionally, dinner recipes that have already been selected for
lunch in the week are excluded.

Returns:
    dict: A dictionary containing meal types as keys and lists of recipe
          IDs as values. Each list represents the selected recipes for
          the corresponding meal type. The dictionary also includes a
          'week_number' key, indicating the number of the current week
          in the year, and a 'year' key, indicating the current year.


Example usage:
    menu = generate_weekly_menu()
    logging.info(menu)
"""
menu = dict()
recipe_ids = list()
# Meal types and corresponding conditions
where_conditions = [
    "m.meal_type_name = 'Завтрак'",
    "m.meal_type_name = 'Обед или ужин'",
    "m.meal_type_name = 'Обед или ужин'" +\
          f"AND r.recipe_id NOT IN {lst_to_str(recipe_ids)}"
]

for meal_type, condition in zip(meal_types, where_conditions):
    # Execute SQL query to fetch random recipe IDs
    query = GET_RANDOM_RECIPES.format(condition)
    # Fetch recipe_ids and extract IDs from tuples
    print(query, lst_to_str(recipe_ids))
    recipe_ids = [
        id[0] for id in cursor.execute(query, (N_DAYS,)).fetchall()]
    # Store the selected recipe IDs for the current meal type
    print(recipe_ids)
    menu[meal_type] = recipe_ids

# Get the current week number and year
# current_date = datetime.now()
# week_number = current_date.isocalendar()[1]
# year = current_date.year

# Add week number and year to the menu dictionary
# menu['week_number'] = week_number
# menu['year'] = year
# TODO: Add user Id to the output dictionary
return menu

with sqlite3.connect(DB_PATH) as connection:
cursor = connection.cursor()
menu = generate_weekly_menu()
print(menu)
print(set(menu['lunch']).intersection(set(menu['dinner'])))

"""

Correct database: add ingredients, decrease tomato paste qty

  • в завтраке нет в списке продуктов масла, которое далее есть в описании приготовления; это Оладьи без яиц и Омлет
  • вт обед: посолить, поперчить. Добавить перец. (Может добавить балгарсеий перец). А так понятно, в принципе.
  • уменьшить количество томатной пасты в рецепте "Горшочки с мясом и картофелем"

Соблюсти очередность блюд в еженедельном сообщении

  1. В еженедельном сообщении (отправляется по воскресеньям) порядок блюд в перечислении должен соответствовать их последующему порядку.
  2. Добавить нумерацию блюд для каждой из категорий: для 7 дней готовки нумерация от 1 до 7.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.