Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add NEVER_UNIT automation #2432

Merged
merged 119 commits into from
Aug 26, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
119 commits
Select commit Hold shift + click to select a range
689eb42
method for asynchronous generation of meals. start of menu for auto p…
AquaticLava Sep 4, 2022
31f3425
Menu for auto planner, menu sets auto planner settings. delete method…
AquaticLava Jan 5, 2023
785dc15
Merge branch 'TandoorRecipes:develop' into Auto-Planner
AquaticLava Jan 5, 2023
4a390b5
removed logging
AquaticLava Jan 8, 2023
4fb5ce5
Bump bleach from 5.0.1 to 6.0.0
dependabot[bot] May 1, 2023
693b43a
Merge remote-tracking branch 'origin/develop' into Auto-Planner
AquaticLava May 18, 2023
6c9227f
fixed formatting and minor bug causeing the start of the period to al…
AquaticLava May 18, 2023
ee5c7d0
Merge branch 'TandoorRecipes:develop' into Auto-Planner
AquaticLava Jun 22, 2023
ee38d93
Created auto meal plan api endpoint.
AquaticLava Jun 22, 2023
9756b7b
regenerated open api file
AquaticLava Jun 22, 2023
ac17b84
updated auto meal plan to start at the current day, and exclude a mea…
AquaticLava Jun 22, 2023
c2def3e
Bump typescript from 4.9.5 to 5.1.6 in /vue
dependabot[bot] Jul 1, 2023
7bc78e1
Expose food description in food form
titilambert Jul 11, 2023
0f5e535
add NEVER_UNIT automation
smilerz Apr 24, 2023
814f415
create Transpose Words automation
smilerz Apr 24, 2023
6880c0a
filtered automations to tokens present
smilerz Apr 25, 2023
7f33f82
fixed defect in NEVER_UNIT automation
smilerz May 1, 2023
19f1225
make automation parameters case insensitive on search
smilerz May 2, 2023
14a67fd
improved spinner rendering
vabene1111 Jul 20, 2023
cf9d599
fixed sort by rating so that unrated are always last
smilerz Jul 20, 2023
74c86f1
Merge pull request #2541 from titilambert/patch-1
vabene1111 Jul 22, 2023
b30f8c2
added option to set URL on food
vabene1111 Jul 22, 2023
d5ba2e6
improved multi url import
vabene1111 Jul 22, 2023
c18386b
fixed copied ingredients being linked together
vabene1111 Jul 22, 2023
6f1befc
fixed rating sort order and updated tests
smilerz Jul 25, 2023
7853357
fix error when filtering on rating in saved filters
smilerz Jul 25, 2023
f34fb8e
Merge pull request #2563 from smilerz/test_fixes
vabene1111 Jul 26, 2023
9988a61
added version number to system screen
vabene1111 Jul 27, 2023
e77016e
playing around
vabene1111 Jul 27, 2023
2b5a86c
improved system page
vabene1111 Jul 27, 2023
22dfb40
improved system info even more
vabene1111 Jul 27, 2023
6a39148
fixed try catch and added git to permanent dependency
vabene1111 Jul 28, 2023
2fdcdba
base pasth pdf viewer
vabene1111 Jul 29, 2023
0688f46
new version script
vabene1111 Jul 29, 2023
113c40c
changed version command order
vabene1111 Jul 29, 2023
0c2c12d
improved version script
vabene1111 Jul 29, 2023
ca28e52
keep git installed
vabene1111 Jul 29, 2023
f7b60f2
version script improvements
vabene1111 Jul 29, 2023
782dd4c
build stuff
vabene1111 Jul 29, 2023
eac059c
Translated using Weblate (Czech)
daaric-mt Jul 30, 2023
312cd07
Bump eslint from 7.32.0 to 8.46.0 in /vue
dependabot[bot] Aug 1, 2023
7f27419
Bump lxml from 4.9.2 to 4.9.3
dependabot[bot] Aug 1, 2023
cb5b51b
Bump django-auth-ldap from 4.2.0 to 4.4.0
dependabot[bot] Aug 1, 2023
df684f5
added share functionality. changed random recipe selection to prevent…
AquaticLava Aug 1, 2023
2b8c607
Bump cryptography from 41.0.2 to 41.0.3
dependabot[bot] Aug 2, 2023
ecd8280
added auto shopping functionality. fixed bug when there are no matchi…
AquaticLava Aug 2, 2023
baa84cf
Added translation using Weblate (Hebrew)
Churator Aug 2, 2023
fe33adb
Translated using Weblate (Hebrew)
Churator Aug 2, 2023
d876334
Translated using Weblate (Hebrew)
Churator Aug 2, 2023
b8e1ed8
Merge pull request #2570 from TandoorRecipes/dependabot/pip/cryptogra…
vabene1111 Aug 5, 2023
6d84c71
Bump django-cleanup from 7.0.0 to 8.0.0
dependabot[bot] Aug 5, 2023
678963e
more debug in version script
vabene1111 Aug 5, 2023
0c62b80
Merge branch 'develop' of https://github.com/TandoorRecipes/recipes i…
vabene1111 Aug 5, 2023
dae7cbf
version script updates and system page fix
vabene1111 Aug 5, 2023
4b14a09
better logging
vabene1111 Aug 5, 2023
3a8ea4b
fix incorrect variable in apply_transpose_words_automations
smilerz Aug 10, 2023
c0d67db
add NEVER_UNIT automation
smilerz Apr 24, 2023
d83b048
create Transpose Words automation
smilerz Apr 24, 2023
4a93681
filtered automations to tokens present
smilerz Apr 25, 2023
b356545
fixed defect in NEVER_UNIT automation
smilerz May 1, 2023
743fae1
make automation parameters case insensitive on search
smilerz May 2, 2023
6eac486
fix incorrect variable in apply_transpose_words_automations
smilerz Aug 10, 2023
1d29e43
Merge branch 'new_automations' of github.com:smilerz/recipes into new…
smilerz Aug 10, 2023
8bf661c
update migrations
smilerz Aug 10, 2023
640500c
Translated using Weblate (German)
fabjoe91 Aug 12, 2023
714d5e5
Translated using Weblate (German)
Br33ce Aug 12, 2023
64e28fd
Translated using Weblate (German)
fabjoe91 Aug 12, 2023
d7f77a5
Translated using Weblate (Polish)
Klem7ens Aug 12, 2023
fc2ce6e
Translated using Weblate (Slovenian)
Miha-2 Aug 11, 2023
ba361a8
Translated using Weblate (Slovenian)
Miha-2 Aug 11, 2023
3d7e2b1
Translated using Weblate (Dutch)
JohnMoor Aug 14, 2023
c18a77b
Translated using Weblate (Dutch)
JohnMoor Aug 14, 2023
246b9c4
Merge pull request #2569 from TandoorRecipes/dependabot/pip/django-au…
vabene1111 Aug 16, 2023
ef72a07
Merge pull request #2568 from TandoorRecipes/dependabot/pip/lxml-4.9.3
vabene1111 Aug 16, 2023
4a835c3
Merge pull request #2567 from TandoorRecipes/dependabot/pip/django-cl…
vabene1111 Aug 16, 2023
4592cc8
Merge pull request #2566 from TandoorRecipes/dependabot/npm_and_yarn/…
vabene1111 Aug 16, 2023
a8fd703
Merge pull request #2529 from TandoorRecipes/dependabot/npm_and_yarn/…
vabene1111 Aug 16, 2023
ffc9689
Delete recipes.iml
vabene1111 Aug 16, 2023
f07dec6
Merge pull request #2468 from AquaticLava/Auto-Planner
vabene1111 Aug 16, 2023
7169764
fixed pycharm file
vabene1111 Aug 16, 2023
8ff5142
auto meal plan tweaks and improvements
vabene1111 Aug 16, 2023
c4a0df2
Merge pull request #2446 from TandoorRecipes/dependabot/pip/bleach-6.0.0
vabene1111 Aug 16, 2023
1ecb57e
removed dependency and upgraded bleach clean
vabene1111 Aug 16, 2023
f5fb4e5
Changed var-name in env, info in docs and processing in settings
boppy Aug 16, 2023
7561278
Translated using Weblate (French)
Aug 15, 2023
7e9cef6
Translated using Weblate (German)
Aug 15, 2023
db4f2db
Translated using Weblate (French)
Aug 15, 2023
8580aea
Translated using Weblate (Norwegian Bokmål)
IDmedia Aug 19, 2023
835c5a1
Translated using Weblate (Greek)
teogramm Aug 19, 2023
2e606dc
Translated using Weblate (Greek)
teogramm Aug 20, 2023
c010812
Translated using Weblate (Greek)
teogramm Aug 20, 2023
2888b18
Translated using Weblate (Greek)
teogramm Aug 21, 2023
934df3c
Merge pull request from GHSA-66qh-qh47-9w6p
vabene1111 Aug 23, 2023
7163c33
fixed food edit merge/move/automate not working
vabene1111 Aug 23, 2023
0345b77
Merge branch 'develop' of https://github.com/vabene1111/recipes into …
vabene1111 Aug 23, 2023
6785033
Add step-level configuration whether an ingredients table should be s…
srwareham Jul 10, 2023
2f0929e
Merge pull request #2539 from srwareham/hide-step-ingredients
vabene1111 Aug 24, 2023
f255397
added translation
vabene1111 Aug 24, 2023
d819cbc
Merge branch 'develop' of https://github.com/vabene1111/recipes into …
vabene1111 Aug 24, 2023
c1ae4e3
added migration for step ingredient showing
vabene1111 Aug 24, 2023
17fa3c8
fixed serving property calculation
vabene1111 Aug 24, 2023
92d648c
added ability to order property types
vabene1111 Aug 24, 2023
01ce658
fixed step factory
vabene1111 Aug 25, 2023
3d45a06
added share target to web manifest
vabene1111 Aug 25, 2023
cf7cc6c
only url on share target
vabene1111 Aug 25, 2023
87beed4
testing share targets
vabene1111 Aug 25, 2023
5d5eb45
also accept text as a parameter for import url
vabene1111 Aug 25, 2023
8fa0097
add NEVER_UNIT automation
smilerz Apr 24, 2023
479cf1a
create Transpose Words automation
smilerz Apr 24, 2023
8411537
filtered automations to tokens present
smilerz Apr 25, 2023
cde8dd8
fixed defect in NEVER_UNIT automation
smilerz May 1, 2023
9b50ea4
make automation parameters case insensitive on search
smilerz May 2, 2023
2f617aa
fix incorrect variable in apply_transpose_words_automations
smilerz Aug 10, 2023
a7a6abe
add NEVER_UNIT automation
smilerz Apr 24, 2023
1328154
create Transpose Words automation
smilerz Apr 24, 2023
fde4ea8
filtered automations to tokens present
smilerz Apr 25, 2023
0662255
update migrations
smilerz Aug 10, 2023
833ebf8
Merge branch 'new_automations' of github.com:smilerz/recipes into new…
smilerz Aug 25, 2023
6353885
update migrations after rebase
smilerz Aug 25, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion .dockerignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ npm-debug.log
Dockerfile*
docker-compose*
.dockerignore
.git
.gitignore
README.md
LICENSE
Expand Down
8 changes: 5 additions & 3 deletions .env.template
Original file line number Diff line number Diff line change
Expand Up @@ -100,10 +100,12 @@ GUNICORN_MEDIA=0
# prefix used for account related emails (default "[Tandoor Recipes] ")
# ACCOUNT_EMAIL_SUBJECT_PREFIX=

# allow authentication via reverse proxy (e.g. authelia), leave off if you dont know what you are doing
# see docs for more information https://docs.tandoor.dev/features/authentication/
# allow authentication via the REMOTE-USER header (can be used for e.g. authelia).
# ATTENTION: Leave off if you don't know what you are doing! Enabling this without proper configuration will enable anybody
# to login with any username!
# See docs for additional information: https://docs.tandoor.dev/features/authentication/#reverse-proxy-authentication
# when unset: 0 (false)
REVERSE_PROXY_AUTH=0
REMOTE_USER_AUTH=0

# Default settings for spaces, apply per space and can be changed in the admin view
# SPACE_DEFAULT_MAX_RECIPES=0 # 0=unlimited recipes
Expand Down
10 changes: 0 additions & 10 deletions .github/workflows/build-docker-open-data.yml
Original file line number Diff line number Diff line change
Expand Up @@ -34,16 +34,6 @@ jobs:
echo VERSION=develop >> $GITHUB_OUTPUT
fi

# Update Version number
- name: Update version file
uses: DamianReeves/[email protected]
with:
path: recipes/version.py
contents: |
VERSION_NUMBER = '${{ steps.get_version.outputs.VERSION }}-open-data'
BUILD_REF = '${{ github.sha }}'
write-mode: overwrite

# clone open data plugin
- name: clone open data plugin repo
uses: actions/checkout@master
Expand Down
10 changes: 0 additions & 10 deletions .github/workflows/build-docker.yml
Original file line number Diff line number Diff line change
Expand Up @@ -34,16 +34,6 @@ jobs:
echo VERSION=develop >> $GITHUB_OUTPUT
fi

# Update Version number
- name: Update version file
uses: DamianReeves/[email protected]
with:
path: recipes/version.py
contents: |
VERSION_NUMBER = '${{ steps.get_version.outputs.VERSION }}'
BUILD_REF = '${{ github.sha }}'
write-mode: overwrite

# Build Vue frontend
- uses: actions/setup-node@v3
with:
Expand Down
2 changes: 1 addition & 1 deletion .idea/vcs.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 8 additions & 2 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
FROM python:3.10-alpine3.18

#Install all dependencies.
RUN apk add --no-cache postgresql-libs postgresql-client gettext zlib libjpeg libwebp libxml2-dev libxslt-dev openldap
RUN apk add --no-cache postgresql-libs postgresql-client gettext zlib libjpeg libwebp libxml2-dev libxslt-dev openldap git

#Print all logs without buffering it.
ENV PYTHONUNBUFFERED 1
Expand All @@ -19,7 +19,7 @@ RUN \
if [ `apk --print-arch` = "armv7" ]; then \
printf "[global]\nextra-index-url=https://www.piwheels.org/simple\n" > /etc/pip.conf ; \
fi
RUN apk add --no-cache --virtual .build-deps gcc musl-dev postgresql-dev zlib-dev jpeg-dev libwebp-dev openssl-dev libffi-dev cargo openldap-dev python3-dev git && \
RUN apk add --no-cache --virtual .build-deps gcc musl-dev postgresql-dev zlib-dev jpeg-dev libwebp-dev openssl-dev libffi-dev cargo openldap-dev python3-dev && \
echo -n "INPUT ( libldap.so )" > /usr/lib/libldap_r.so && \
python -m venv venv && \
/opt/recipes/venv/bin/python -m pip install --upgrade pip && \
Expand All @@ -30,5 +30,11 @@ RUN apk add --no-cache --virtual .build-deps gcc musl-dev postgresql-dev zlib-de

#Copy project and execute it.
COPY . ./

# collect information from git repositories
RUN /opt/recipes/venv/bin/python version.py
# delete git repositories to reduce image size
RUN find . -type d -name ".git" | xargs rm -rf

RUN chmod +x boot.sh
ENTRYPOINT ["/opt/recipes/boot.sh"]
1 change: 1 addition & 0 deletions cookbook/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -314,6 +314,7 @@ class InviteLinkAdmin(admin.ModelAdmin):

class CookLogAdmin(admin.ModelAdmin):
list_display = ('recipe', 'created_by', 'created_at', 'rating', 'servings')
search_fields = ('recipe__name', 'space__name',)


admin.site.register(CookLog, CookLogAdmin)
Expand Down
7 changes: 5 additions & 2 deletions cookbook/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ class Meta:
fields = (
'default_unit', 'use_fractions', 'use_kj', 'theme', 'nav_color',
'sticky_navbar', 'default_page', 'plan_share', 'ingredient_decimals', 'comments', 'left_handed',
'show_step_ingredients',
)

labels = {
Expand All @@ -60,7 +61,8 @@ class Meta:
'ingredient_decimals': _('Ingredient decimal places'),
'shopping_auto_sync': _('Shopping list auto sync period'),
'comments': _('Comments'),
'left_handed': _('Left-handed mode')
'left_handed': _('Left-handed mode'),
'show_step_ingredients': _('Show step ingredients table')
}

help_texts = {
Expand All @@ -82,7 +84,8 @@ class Meta:
'sticky_navbar': _('Makes the navbar stick to the top of the page.'),
'mealplan_autoadd_shopping': _('Automatically add meal plan ingredients to shopping list.'),
'mealplan_autoexclude_onhand': _('Exclude ingredients that are on hand.'),
'left_handed': _('Will optimize the UI for use with your left hand.')
'left_handed': _('Will optimize the UI for use with your left hand.'),
'show_step_ingredients': _('Add ingredients table next to recipe steps. Applies at creation time for manually created and URL imported recipes. Individual steps can be overridden in the edit recipe view.')
}

widgets = {
Expand Down
125 changes: 108 additions & 17 deletions cookbook/helper/ingredient_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,19 @@
import unicodedata

from django.core.cache import caches
from django.db.models import Q
from django.db.models.functions import Lower

from cookbook.models import Unit, Food, Automation, Ingredient
from cookbook.models import Automation, Food, Ingredient, Unit


class IngredientParser:
request = None
ignore_rules = False
food_aliases = {}
unit_aliases = {}
never_unit = {}
transpose_words = {}

def __init__(self, request, cache_mode, ignore_automations=False):
"""
Expand All @@ -29,7 +33,7 @@ def __init__(self, request, cache_mode, ignore_automations=False):
caches['default'].touch(FOOD_CACHE_KEY, 30)
else:
for a in Automation.objects.filter(space=self.request.space, disabled=False, type=Automation.FOOD_ALIAS).only('param_1', 'param_2').order_by('order').all():
self.food_aliases[a.param_1] = a.param_2
self.food_aliases[a.param_1.lower()] = a.param_2
caches['default'].set(FOOD_CACHE_KEY, self.food_aliases, 30)

UNIT_CACHE_KEY = f'automation_unit_alias_{self.request.space.pk}'
Expand All @@ -38,11 +42,33 @@ def __init__(self, request, cache_mode, ignore_automations=False):
caches['default'].touch(UNIT_CACHE_KEY, 30)
else:
for a in Automation.objects.filter(space=self.request.space, disabled=False, type=Automation.UNIT_ALIAS).only('param_1', 'param_2').order_by('order').all():
self.unit_aliases[a.param_1] = a.param_2
self.unit_aliases[a.param_1.lower()] = a.param_2
caches['default'].set(UNIT_CACHE_KEY, self.unit_aliases, 30)

NEVER_UNIT_CACHE_KEY = f'automation_never_unit_{self.request.space.pk}'
if c := caches['default'].get(NEVER_UNIT_CACHE_KEY, None):
self.never_unit = c
caches['default'].touch(NEVER_UNIT_CACHE_KEY, 30)
else:
for a in Automation.objects.filter(space=self.request.space, disabled=False, type=Automation.NEVER_UNIT).only('param_1', 'param_2').order_by('order').all():
self.never_unit[a.param_1.lower()] = a.param_2
caches['default'].set(NEVER_UNIT_CACHE_KEY, self.never_unit, 30)

TRANSPOSE_WORDS_CACHE_KEY = f'automation_transpose_words_{self.request.space.pk}'
if c := caches['default'].get(TRANSPOSE_WORDS_CACHE_KEY, None):
self.transpose_words = c
caches['default'].touch(TRANSPOSE_WORDS_CACHE_KEY, 30)
else:
i = 0
for a in Automation.objects.filter(space=self.request.space, disabled=False, type=Automation.TRANSPOSE_WORDS).only('param_1', 'param_2').order_by('order').all():
vabene1111 marked this conversation as resolved.
Show resolved Hide resolved
self.transpose_words[i] = [a.param_1.lower(), a.param_2.lower()]
i += 1
caches['default'].set(TRANSPOSE_WORDS_CACHE_KEY, self.transpose_words, 30)
else:
self.food_aliases = {}
self.unit_aliases = {}
self.never_unit = {}
self.transpose_words = {}

def apply_food_automation(self, food):
"""
Expand All @@ -55,11 +81,11 @@ def apply_food_automation(self, food):
else:
if self.food_aliases:
try:
return self.food_aliases[food]
return self.food_aliases[food.lower()]
except KeyError:
return food
else:
if automation := Automation.objects.filter(space=self.request.space, type=Automation.FOOD_ALIAS, param_1=food, disabled=False).order_by('order').first():
if automation := Automation.objects.filter(space=self.request.space, type=Automation.FOOD_ALIAS, param_1__iexact=food, disabled=False).order_by('order').first():
return automation.param_2
return food

Expand All @@ -72,13 +98,13 @@ def apply_unit_automation(self, unit):
if self.ignore_rules:
return unit
else:
if self.unit_aliases:
if self.transpose_words:
try:
return self.unit_aliases[unit]
return self.unit_aliases[unit.lower()]
except KeyError:
return unit
else:
if automation := Automation.objects.filter(space=self.request.space, type=Automation.UNIT_ALIAS, param_1=unit, disabled=False).order_by('order').first():
if automation := Automation.objects.filter(space=self.request.space, type=Automation.UNIT_ALIAS, param_1__iexact=unit, disabled=False).order_by('order').first():
return automation.param_2
return unit

Expand Down Expand Up @@ -133,10 +159,10 @@ def parse_amount(self, x):
end = 0
while (end < len(x) and (x[end] in string.digits
or (
(x[end] == '.' or x[end] == ',' or x[end] == '/')
and end + 1 < len(x)
and x[end + 1] in string.digits
))):
(x[end] == '.' or x[end] == ',' or x[end] == '/')
and end + 1 < len(x)
and x[end + 1] in string.digits
))):
end += 1
if end > 0:
if "/" in x[:end]:
Expand All @@ -160,7 +186,8 @@ def parse_amount(self, x):
if unit is not None and unit.strip() == '':
unit = None

if unit is not None and (unit.startswith('(') or unit.startswith('-')): # i dont know any unit that starts with ( or - so its likely an alternative like 1L (500ml) Water or 2-3
if unit is not None and (unit.startswith('(') or unit.startswith(
'-')): # i dont know any unit that starts with ( or - so its likely an alternative like 1L (500ml) Water or 2-3
unit = None
note = x
return amount, unit, note
Expand Down Expand Up @@ -205,6 +232,67 @@ def parse_food(self, tokens):
food, note = self.parse_food_with_comma(tokens)
return food, note

def apply_never_unit_automations(self, tokens):
"""
Moves a string that should never be treated as a unit to next token and optionally replaced with default unit
e.g. NEVER_UNIT: param1: egg, param2: None would modify ['1', 'egg', 'white'] to ['1', '', 'egg', 'white']
or NEVER_UNIT: param1: egg, param2: pcs would modify ['1', 'egg', 'yolk'] to ['1', 'pcs', 'egg', 'yolk']
:param1 string: string that should never be considered a unit, will be moved to token[2]
:param2 (optional) unit as string: will insert unit string into token[1]
:return: unit as string (possibly changed by automation)
"""

if self.ignore_rules:
return tokens

new_unit = None
alt_unit = self.apply_unit_automation(tokens[1])
never_unit = False
if self.never_unit:
try:
new_unit = self.never_unit[tokens[1].lower()]
never_unit = True
except KeyError:
return tokens

else:
if automation := Automation.objects.annotate(param_1_lower=Lower('param_1')).filter(space=self.request.space, type=Automation.NEVER_UNIT, param_1_lower__in=[
tokens[1].lower(), alt_unit.lower()], disabled=False).order_by('order').first():
new_unit = automation.param_2
never_unit = True

if never_unit:
tokens.insert(1, new_unit)

return tokens

def apply_transpose_words_automations(self, ingredient):
"""
If two words (param_1 & param_2) are detected in sequence, swap their position in the ingredient string
:param 1: first word to detect
:param 2: second word to detect
return: new ingredient string
"""

if self.ignore_rules:
return ingredient

else:
tokens = [x.lower() for x in ingredient.replace(',', ' ').split()]
if self.transpose_words:
filtered_rules = {}
for key, value in self.transpose_words.items():
if value[0] in tokens and value[1] in tokens:
filtered_rules[key] = value
for k, v in filtered_rules.items():
ingredient = re.sub(rf"\b({v[0]})\W*({v[1]})\b", r"\2 \1", ingredient, flags=re.IGNORECASE)
else:
for rule in Automation.objects.filter(space=self.request.space, type=Automation.TRANSPOSE_WORDS, disabled=False) \
.annotate(param_1_lower=Lower('param_1'), param_2_lower=Lower('param_2')) \
.filter(Q(Q(param_1_lower__in=tokens) | Q(param_2_lower__in=tokens))).order_by('order'):
ingredient = re.sub(rf"\b({rule.param_1})\W*({rule.param_1})\b", r"\2 \1", ingredient, flags=re.IGNORECASE)
return ingredient

def parse(self, ingredient):
"""
Main parsing function, takes an ingredient string (e.g. '1 l Water') and extracts amount, unit, food, ...
Expand All @@ -230,21 +318,23 @@ def parse(self, ingredient):

# if the string contains parenthesis early on remove it and place it at the end
# because its likely some kind of note
if re.match('(.){1,6}\s\((.[^\(\)])+\)\s', ingredient):
match = re.search('\((.[^\(])+\)', ingredient)
if re.match('(.){1,6}\\s\\((.[^\\(\\)])+\\)\\s', ingredient):
match = re.search('\\((.[^\\(])+\\)', ingredient)
ingredient = ingredient[:match.start()] + ingredient[match.end():] + ' ' + ingredient[match.start():match.end()]

# leading spaces before commas result in extra tokens, clean them out
ingredient = ingredient.replace(' ,', ',')

# handle "(from) - (to)" amounts by using the minimum amount and adding the range to the description
# "10.5 - 200 g XYZ" => "100 g XYZ (10.5 - 200)"
ingredient = re.sub("^(\d+|\d+[\\.,]\d+) - (\d+|\d+[\\.,]\d+) (.*)", "\\1 \\3 (\\1 - \\2)", ingredient)
ingredient = re.sub("^(\\d+|\\d+[\\.,]\\d+) - (\\d+|\\d+[\\.,]\\d+) (.*)", "\\1 \\3 (\\1 - \\2)", ingredient)

# if amount and unit are connected add space in between
if re.match('([0-9])+([A-z])+\s', ingredient):
if re.match('([0-9])+([A-z])+\\s', ingredient):

Check warning

Code scanning / CodeQL

Overly permissive regular expression range

Suspicious character range that is equivalent to \[A-Z\\[\\\\]^_`a-z\].
ingredient = re.sub(r'(?<=([a-z])|\d)(?=(?(1)\d|[a-z]))', ' ', ingredient)

ingredient = self.apply_transpose_words_automations(ingredient)

tokens = ingredient.split() # split at each space into tokens
if len(tokens) == 1:
# there only is one argument, that must be the food
Expand All @@ -257,6 +347,7 @@ def parse(self, ingredient):
# three arguments if it already has a unit there can't be
# a fraction for the amount
if len(tokens) > 2:
tokens = self.apply_never_unit_automations(tokens)
try:
if unit is not None:
# a unit is already found, no need to try the second argument for a fraction
Expand Down
2 changes: 1 addition & 1 deletion cookbook/helper/property_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def calculate_recipe_properties(self, recipe):
caches['default'].set(CacheHelper(self.space).PROPERTY_TYPE_CACHE_KEY, property_types, 60 * 60) # cache is cleared on property type save signal so long duration is fine

for fpt in property_types:
computed_properties[fpt.id] = {'id': fpt.id, 'name': fpt.name, 'icon': fpt.icon, 'description': fpt.description, 'unit': fpt.unit, 'food_values': {}, 'total_value': 0, 'missing_value': False}
computed_properties[fpt.id] = {'id': fpt.id, 'name': fpt.name, 'icon': fpt.icon, 'description': fpt.description, 'unit': fpt.unit, 'order': fpt.order, 'food_values': {}, 'total_value': 0, 'missing_value': False}

uch = UnitConversionHelper(self.space)

Expand Down
Loading