Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Move generator logic to dummy-generator-nutrition.py

Roland Geiderfc0e4e6ede01
diff --git a/extras/dummy_generator/generator.py b/extras/dummy_generator/generator.py
index 9307e736c..99e5e729c 100644
--- a/extras/dummy_generator/generator.py
+++ b/extras/dummy_generator/generator.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
# This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
@@ -16,7 +14,6 @@
# Standard Library
import argparse
-import csv
import datetime
import os
import random
@@ -26,9 +23,10 @@ import uuid
# Django
import django
from django.db import IntegrityError
-from django.utils import timezone
from django.utils.text import slugify
+import csv
+
sys.path.insert(0, os.path.join('..', '..'))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings')
django.setup()
@@ -40,7 +38,6 @@ from django.contrib.auth.models import User
# wger
from wger.core.models import (
DaysOfWeek,
- Language,
)
from wger.exercises.models import Exercise
from wger.gym.models import (
@@ -61,13 +58,6 @@ from wger.measurements.models import (
Category,
Measurement,
)
-from wger.nutrition.models import (
- Ingredient,
- LogItem,
- Meal,
- MealItem,
- NutritionPlan,
-)
from wger.weight.models import WeightEntry
parser = argparse.ArgumentParser(description='Data generator. Please consult the documentation')
@@ -566,89 +556,10 @@ if hasattr(args, 'number_measurement'):
# Nutrition Generator
#
if hasattr(args, 'number_nutrition_plans'):
- print("** Generating {0} nutrition plan(s) per user".format(args.number_nutrition_plans))
-
- if args.add_to_user:
- userlist = [User.objects.get(pk=args.add_to_user)]
- else:
- userlist = User.objects.all()
-
- # Load all ingredients to a list
- ingredient_list = [i for i in Ingredient.objects.order_by('?').all()[:100]]
-
- # Total meals per plan
- TOTAL_MEALS = 4
-
- for user in userlist:
- print(' - generating for {0}'.format(user.username))
-
- # Add nutrition plan
- for i in range(0, args.number_nutrition_plans):
- uid = str(uuid.uuid4()).split('-')
- start_date = datetime.date.today() - datetime.timedelta(days=random.randint(0, 100))
- nutrition_plan = NutritionPlan(
- language=Language.objects.all()[1],
- description='Dummy nutrition plan - {0}'.format(uid[1]),
- creation_date=start_date,
- )
- nutrition_plan.user = user
-
- nutrition_plan.save()
-
- # Add meals to plan
- order = 1
- for j in range(0, TOTAL_MEALS):
- meal = Meal(
- plan=nutrition_plan,
- order=order,
- time=datetime.time(hour=random.randint(0, 23), minute=random.randint(0, 59))
- )
- meal.save()
- for k in range(0, random.randint(1, 5)):
- ingredient = random.choice(ingredient_list)
- meal_item = MealItem(
- meal=meal,
- ingredient=ingredient,
- weight_unit=None,
- order=order,
- amount=random.randint(10, 250)
- )
- meal_item.save()
- order = order + 1
+ print("*** Please use 'python manage.py dummy-generator-nutrition' instead")
#
# Nutrition diary Generator
#
if hasattr(args, 'number_nutrition_logs'):
- print("** Generating {0} nutrition diary entries per user".format(args.number_nutrition_logs))
-
- if args.add_to_user:
- userlist = [User.objects.get(pk=args.add_to_user)]
- else:
- userlist = User.objects.all()
-
- # Load all ingredients to a list
- ingredient_list = [i for i in Ingredient.objects.order_by('?').all()[:100]]
-
- for user in userlist:
- plan_list = NutritionPlan.objects.order_by('?').filter(user=user)
- print(' - generating for {0}'.format(user.username))
-
- # Add diary entries
- for plan in NutritionPlan.objects.filter(user=user):
- for i in range(0, args.number_diary_dates):
- date = timezone.now() - datetime.timedelta(
- days=random.randint(0, 100),
- hours=random.randint(0, 12),
- minutes=random.randint(0, 59)
- )
- for j in range(0, args.number_nutrition_logs):
- ingredient = random.choice(ingredient_list)
- log = LogItem(
- plan=plan,
- datetime=date,
- ingredient=ingredient,
- weight_unit=None,
- amount=random.randint(10, 300)
- )
- log.save()
+ print("*** Please use 'python manage.py dummy-generator-nutrition' instead")
diff --git a/wger/nutrition/management/commands/download-off-ingredient-images.py b/wger/nutrition/management/commands/download-off-ingredient-images.py
deleted file mode 100644
index 29fc19e50..000000000
--- a/wger/nutrition/management/commands/download-off-ingredient-images.py
+++ /dev/null
@@ -1,70 +0,0 @@
-# This file is part of wger Workout Manager.
-#
-# wger Workout Manager is free software: you can redistribute it and/or modify
-# it under the terms of the GNU Affero General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-#
-# wger Workout Manager is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU Affero General Public License
-
-# Standard Library
-import logging
-
-# Django
-from django.conf import settings
-from django.core.management.base import BaseCommand
-
-# wger
-from wger.nutrition.models import MealItem
-from wger.nutrition.tasks import fetch_ingredient_image_task
-
-
-logger = logging.getLogger(__name__)
-
-
-class Command(BaseCommand):
- """
- One off script
-
- This is intended to download all images from Open Food Facts for the all
- currently used ingredients
- """
-
- help = 'Download images of all Open Food Facts ingredients that are used in a nutritional plan'
-
- def handle(self, **options):
- if not settings.WGER_SETTINGS['USE_CELERY']:
- self.stdout.write('Celery deactivated. Exiting...')
- return
-
- # Make sure off downloads are enabled
- if not settings.WGER_SETTINGS['DOWNLOAD_INGREDIENTS_FROM']:
- self.stdout.write('DOWNLOAD_INGREDIENTS_FROM not set. Exiting...')
- return
-
- # Since each MealItem is linked to a NutritionPlan via a Meal we can skip accessing
- # NutritionPlan and Meal itself and fetch all MealItems directly instead.
- meal_items = MealItem.objects.all()
- meal_item_counter = 0
- download_counter = 0
- for meal_item in meal_items:
- if meal_item.ingredient:
- fetch_ingredient_image_task.delay(meal_item.ingredient.pk)
- download_counter += 1
- meal_item_counter += 1
-
- if meal_item_counter % 10 == 0:
- self.stdout.write(
- f'Processed {meal_item_counter} meal items, '
- f'downloaded {download_counter} images'
- )
-
- self.stdout.write(
- f'Processed {meal_item_counter} meal items, downloaded {download_counter} images'
- )
- self.stdout.write(f'Done')
diff --git a/wger/nutrition/management/commands/dummy-generator-nutrition.py b/wger/nutrition/management/commands/dummy-generator-nutrition.py
new file mode 100644
index 000000000..b13c1215d
--- /dev/null
+++ b/wger/nutrition/management/commands/dummy-generator-nutrition.py
@@ -0,0 +1,157 @@
+# This file is part of wger Workout Manager.
+#
+# wger Workout Manager is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# wger Workout Manager is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+
+# Standard Library
+import datetime
+import logging
+from random import (
+ choice,
+ randint,
+)
+from uuid import uuid4
+
+# Django
+from django.contrib.auth.models import User
+from django.core.management.base import BaseCommand
+from django.utils import timezone
+
+# wger
+from wger.core.models import Language
+from wger.nutrition.models import (
+ Ingredient,
+ LogItem,
+ Meal,
+ MealItem,
+ NutritionPlan,
+)
+
+logger = logging.getLogger(__name__)
+
+
+class Command(BaseCommand):
+ """
+ One off script
+
+ This is intended to download all images from Open Food Facts for the all
+ currently used ingredients
+ """
+
+ help = 'Download images of all Open Food Facts ingredients that are used in a nutritional plan'
+
+ def add_arguments(self, parser):
+
+ parser.add_argument(
+ '--number-plans',
+ action='store',
+ default=10,
+ dest='nr_plans',
+ type=int,
+ help='The number of nutritional plans to create per user (default: 10)'
+ )
+ parser.add_argument(
+ '--number-diary-entries',
+ action='store',
+ default=30,
+ dest='nr_diary_entries',
+ type=int,
+ help='The number of nutrition logs to create per day (default: 30)'
+ )
+ parser.add_argument(
+ '--number-diary-dates',
+ action='store',
+ default=30,
+ dest='nr_diary_dates',
+ type=int,
+ help='Number of dates in which to create logs (default: 30)',
+ )
+ parser.add_argument(
+ '--user-id',
+ action='store',
+ dest='user_id',
+ type=int,
+ help='Add only to the specified user-ID (default: all users)',
+ )
+
+ def handle(self, **options):
+ self.stdout.write(
+ f"** Generating {options['nr_plans']} dummy nutritional plan(s) per user"
+ )
+
+ users = [User.objects.get(pk=options['user_id'])
+ ] if options['user_id'] else User.objects.all()
+ ingredients = [i for i in Ingredient.objects.order_by('?').all()[:100]]
+ meals_per_plan = 4
+
+ for user in users:
+ diary_entries = []
+ self.stdout.write(f'- processing user {user.username}')
+
+ # Add plan
+ for _ in range(0, options['nr_plans']):
+ uid = str(uuid4()).split('-')
+ start_date = datetime.date.today() - datetime.timedelta(days=randint(0, 100))
+ plan = NutritionPlan(
+ language=Language.objects.all()[1],
+ description=f'Dummy nutritional plan - {uid[1]}',
+ creation_date=start_date,
+ user=user
+ )
+ plan.save()
+
+ if int(options['verbosity']) >= 2:
+ self.stdout.write(f' created plan {plan.description}')
+
+ # Add meals
+ for _ in range(0, meals_per_plan):
+ order = 1
+ meal = Meal(
+ plan=plan,
+ order=order,
+ time=datetime.time(hour=randint(0, 23), minute=randint(0, 59))
+ )
+ meal.save()
+
+ # Add meal items
+ for _ in range(0, randint(1, 5)):
+ meal_item = MealItem(
+ meal=meal,
+ ingredient=choice(ingredients),
+ weight_unit=None,
+ order=order,
+ amount=randint(10, 250)
+ )
+ meal_item.save()
+ order = order + 1
+
+ # Add diary entries
+ for _ in range(0, options['nr_diary_dates']):
+ date = timezone.now() - datetime.timedelta(
+ days=randint(0, 100),
+ hours=randint(0, 12),
+ minutes=randint(0, 59),
+ )
+ for _ in range(0, options['nr_diary_entries']):
+ log = LogItem(
+ plan=plan,
+ datetime=date,
+ ingredient=choice(ingredients),
+ weight_unit=None,
+ amount=randint(10, 300)
+ )
+ diary_entries.append(log)
+
+ if int(options['verbosity']) >= 2:
+ self.stdout.write(f" created {options['nr_diary_dates']} diary entries")
+
+ LogItem.objects.bulk_create(diary_entries)