Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Added serving_size import from OFF.

OTijmenc57d71193e03
diff --git a/wger/nutrition/dataclasses.py b/wger/nutrition/dataclasses.py
index e2e02635e..48b553cc4 100644
--- a/wger/nutrition/dataclasses.py
+++ b/wger/nutrition/dataclasses.py
@@ -52,6 +52,9 @@ class IngredientData:
license_author_url: str = ''
is_vegan: Optional[bool] = None
is_vegetarian: Optional[bool] = None
+ serving_size_gram: Optional[int] = None
+ serving_size_unit: Optional[str] = None
+ serving_size_amount: Optional[float] = None
def sanity_checks(self):
if not self.name:
@@ -78,7 +81,11 @@ class IngredientData:
raise ValueError('Total of carbohydrates, protein and fat is greater than 100!')
def dict(self):
- return asdict(self)
+ data = asdict(self)
+ data.pop('serving_size_gram', None)
+ data.pop('serving_size_unit', None)
+ data.pop('serving_size_amount', None)
+ return data
def clean_name(self):
self.name = remove_problematic_characters(self.name)
diff --git a/wger/nutrition/extract_info/off.py b/wger/nutrition/extract_info/off.py
index 3c81d314f..683abe550 100644
--- a/wger/nutrition/extract_info/off.py
+++ b/wger/nutrition/extract_info/off.py
@@ -13,6 +13,9 @@
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
+# Standard Library
+import re
+
# wger
from wger.nutrition.consts import KJ_PER_KCAL
from wger.nutrition.dataclasses import IngredientData
@@ -31,6 +34,50 @@ OFF_REQUIRED_NUTRIMENTS = [
'fat_100g',
]
+GRAM_PATTERN = re.compile(r'(?P<gram>\d+(?:[\.,]\d+)?)\s*g\b', re.IGNORECASE)
+AMOUNT_AND_UNIT_PATTERN = re.compile(
+ r'^\s*(?P<amount>\d+(?:[\.,]\d+)?)\s*(?P<unit>[^\d\(\),;\|][^\(\),;\|]*)$'
+)
+
+
+def extract_serving_size_data(serving_size: str) -> tuple[int | None, str | None, float | None]:
+ if not serving_size:
+ return None, None, None
+
+ gram_match = GRAM_PATTERN.search(serving_size)
+ if not gram_match:
+ return None, None, None
+
+ gram_value = float(gram_match.group('gram').replace(',', '.'))
+ if gram_value <= 0:
+ return None, None, None
+
+ gram = int(round(gram_value))
+
+ # If only grams are provided (e.g. "30 g"), expose a generic serving unit.
+ amount = 1.0
+ unit = 'Serving'
+
+ no_parentheses = re.sub(r'\([^\)]*\)', '', serving_size)
+ no_grams = GRAM_PATTERN.sub('', no_parentheses)
+ candidate = re.sub(r'\s+', ' ', no_grams).strip(' ,;-/').strip()
+
+ if candidate:
+ parsed = AMOUNT_AND_UNIT_PATTERN.match(candidate)
+ if parsed:
+ amount = float(parsed.group('amount').replace(',', '.'))
+ unit = parsed.group('unit').strip()
+ else:
+ unit = candidate
+
+ if amount <= 0:
+ amount = 1.0
+
+ if not unit:
+ unit = 'Serving'
+
+ return gram, unit[:200], amount
+
def extract_info_from_off(product_data: dict, language: int) -> IngredientData:
if not all(req in product_data for req in OFF_REQUIRED_TOP_LEVEL):
@@ -62,6 +109,11 @@ def extract_info_from_off(product_data: dict, language: int) -> IngredientData:
sugars = product_data['nutriments'].get('sugars_100g', None)
fiber = product_data['nutriments'].get('fiber_100g', None)
brand = product_data.get('brands', '')
+ serving_size = product_data.get('serving_size', '')
+
+ serving_size_gram, serving_size_unit, serving_size_amount = extract_serving_size_data(
+ serving_size
+ )
# Dietary properties from OFF ingredients analysis
is_vegan = None
@@ -115,6 +167,9 @@ def extract_info_from_off(product_data: dict, language: int) -> IngredientData:
license_object_url=object_url,
is_vegan=is_vegan,
is_vegetarian=is_vegetarian,
+ serving_size_gram=serving_size_gram,
+ serving_size_unit=serving_size_unit,
+ serving_size_amount=serving_size_amount,
)
ingredient_data.sanity_checks()
return ingredient_data
diff --git a/wger/nutrition/management/products.py b/wger/nutrition/management/products.py
index 4ad50e6a9..4530b1407 100644
--- a/wger/nutrition/management/products.py
+++ b/wger/nutrition/management/products.py
@@ -135,6 +135,7 @@ class ImportProductCommand(BaseCommand):
remote_id=ingredient_data.remote_id,
defaults=ingredient_data.dict(),
)
+ obj.update_or_create_serving_unit_from_off(ingredient_data)
if created:
self.counter['new'] += 1
diff --git a/wger/nutrition/models/ingredient.py b/wger/nutrition/models/ingredient.py
index 40f92b637..dd6909eda 100644
--- a/wger/nutrition/models/ingredient.py
+++ b/wger/nutrition/models/ingredient.py
@@ -17,6 +17,7 @@
# Standard Library
import logging
import uuid as uuid
+from decimal import ROUND_HALF_UP
from decimal import Decimal
from json import JSONDecodeError
@@ -445,6 +446,46 @@ class Ingredient(AbstractLicenseModel, models.Model):
fetch_ingredient_image_task.delay(self.pk)
+ def update_or_create_serving_unit_from_off(self, ingredient_data):
+ if not ingredient_data.serving_size_gram or not ingredient_data.serving_size_unit:
+ return
+
+ # Local imports to avoid model import cycles.
+ from wger.nutrition.models import (
+ IngredientWeightUnit,
+ WeightUnit,
+ )
+
+ unit = WeightUnit.objects.filter(
+ language_id=self.language_id,
+ name__iexact=ingredient_data.serving_size_unit,
+ ).first()
+ if not unit:
+ unit = WeightUnit.objects.create(
+ language_id=self.language_id,
+ name=ingredient_data.serving_size_unit,
+ )
+
+ amount = ingredient_data.serving_size_amount or 1 # if no amount is given, assume 1.
+ amount = Decimal(str(amount)).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
+
+ existing_weight_unit = IngredientWeightUnit.objects.filter(
+ ingredient=self,
+ unit=unit,
+ ).first()
+
+ if existing_weight_unit:
+ existing_weight_unit.gram = ingredient_data.serving_size_gram
+ existing_weight_unit.amount = amount
+ existing_weight_unit.save(update_fields=['gram', 'amount'])
+ else:
+ IngredientWeightUnit.objects.create(
+ ingredient=self,
+ unit=unit,
+ gram=ingredient_data.serving_size_gram,
+ amount=amount,
+ )
+
@classmethod
def fetch_ingredient_from_off(cls, code: str):
"""
@@ -482,5 +523,6 @@ class Ingredient(AbstractLicenseModel, models.Model):
ingredient = cls(**ingredient_data.dict())
ingredient.save()
+ ingredient.update_or_create_serving_unit_from_off(ingredient_data)
logger.info(f'Ingredient found and saved to local database: {ingredient.uuid}')
return ingredient
diff --git a/wger/nutrition/tests/test_ingredient.py b/wger/nutrition/tests/test_ingredient.py
index 83c0cd8a3..5af65f870 100644
--- a/wger/nutrition/tests/test_ingredient.py
+++ b/wger/nutrition/tests/test_ingredient.py
@@ -38,9 +38,12 @@ from wger.core.tests.base_testcase import (
WgerEditTestCase,
WgerTestCase,
)
+from wger.nutrition.extract_info.off import extract_info_from_off
from wger.nutrition.models import (
Ingredient,
+ IngredientWeightUnit,
Meal,
+ WeightUnit,
)
from wger.nutrition.models.image import Image
from wger.utils.constants import NUTRITION_TAB
@@ -531,6 +534,34 @@ class IngredientModelTestCase(WgerTestCase):
self.assertTrue(ingredient.is_vegan)
self.assertTrue(ingredient.is_vegetarian)
+ @patch('openfoodfacts.api.ProductResource.get')
+ def test_fetch_from_off_creates_serving_unit(self, mock_api):
+ self.off_response['serving_size'] = '2 biscuits (30 g)'
+ mock_api.return_value = self.off_response
+
+ ingredient = Ingredient.fetch_ingredient_from_off('1234')
+
+ unit = WeightUnit.objects.get(language=ingredient.language, name='biscuits')
+ ingredient_unit = IngredientWeightUnit.objects.get(ingredient=ingredient, unit=unit)
+ self.assertEqual(ingredient_unit.gram, 30)
+ self.assertEqual(ingredient_unit.amount, Decimal('2.00'))
+
+ @patch('openfoodfacts.api.ProductResource.get')
+ def test_fetch_from_off_updates_existing_serving_unit(self, mock_api):
+ self.off_response['serving_size'] = '2 biscuits (30 g)'
+ mock_api.return_value = self.off_response
+ ingredient = Ingredient.fetch_ingredient_from_off('1234')
+
+ self.off_response['serving_size'] = '2 biscuits (25 g)'
+ ingredient.update_or_create_serving_unit_from_off(
+ extract_info_from_off(self.off_response, ingredient.language_id)
+ )
+
+ unit = WeightUnit.objects.get(language=ingredient.language, name='biscuits')
+ ingredient_unit = IngredientWeightUnit.objects.get(ingredient=ingredient, unit=unit)
+ self.assertEqual(ingredient_unit.gram, 25)
+ self.assertEqual(ingredient_unit.amount, Decimal('2.00'))
+
@patch('openfoodfacts.api.ProductResource.get')
def test_fetch_from_off_success_long_name(self, mock_api):
"""
diff --git a/wger/nutrition/tests/test_off.py b/wger/nutrition/tests/test_off.py
index 61d117e71..0facae5c1 100644
--- a/wger/nutrition/tests/test_off.py
+++ b/wger/nutrition/tests/test_off.py
@@ -200,3 +200,21 @@ class ExtractInfoFromOffTestCase(SimpleTestCase):
)
data.clean_name()
self.assertEqual(data.name, 'Stonebaked Pizza "the american pepperoni"')
+
+ def test_serving_size_parsed(self):
+ self.off_data1['serving_size'] = '2 biscuits (30 g)'
+
+ result = extract_info_from_off(self.off_data1, 1)
+
+ self.assertEqual(result.serving_size_gram, 30)
+ self.assertEqual(result.serving_size_unit, 'biscuits')
+ self.assertEqual(result.serving_size_amount, 2)
+
+ def test_serving_size_only_grams(self):
+ self.off_data1['serving_size'] = '30 g'
+
+ result = extract_info_from_off(self.off_data1, 1)
+
+ self.assertEqual(result.serving_size_gram, 30)
+ self.assertEqual(result.serving_size_unit, 'Serving')
+ self.assertEqual(result.serving_size_amount, 1)