Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Refactor image generation

Roland Geider5e715da9f19a
diff --git a/wger/exercises/migrations/0035_add_is_ai_generated.py b/wger/exercises/migrations/0035_add_is_ai_generated.py
index 45c0cfe2b..dd629ec54 100644
--- a/wger/exercises/migrations/0035_add_is_ai_generated.py
+++ b/wger/exercises/migrations/0035_add_is_ai_generated.py
@@ -1,10 +1,9 @@
-# Generated manually
+# Generated manually
from django.db import migrations, models
class Migration(migrations.Migration):
-
dependencies = [
('exercises', '0034_add_exercise_image_dimensions'),
]
diff --git a/wger/exercises/models/image.py b/wger/exercises/models/image.py
index da5f594c8..aa9067bbe 100644
--- a/wger/exercises/models/image.py
+++ b/wger/exercises/models/image.py
@@ -27,7 +27,7 @@ from simple_history.models import HistoricalRecords
# wger
from wger.exercises.models import Exercise
from wger.utils.cache import reset_exercise_api_cache
-from wger.utils.helpers import BaseImage
+from wger.utils.helpers import BaseImageMixin
from wger.utils.images import validate_image_static_no_animation
from wger.utils.models import (
AbstractHistoryMixin,
@@ -43,7 +43,7 @@ def exercise_image_upload_dir(instance, filename):
return f'exercise-images/{instance.exercise.id}/{instance.uuid}{ext}'
-class ExerciseImage(AbstractLicenseModel, AbstractHistoryMixin, models.Model, BaseImage):
+class ExerciseImage(AbstractLicenseModel, AbstractHistoryMixin, models.Model, BaseImageMixin):
"""
Model for an exercise image
"""
@@ -207,24 +207,20 @@ class ExerciseImage(AbstractLicenseModel, AbstractHistoryMixin, models.Model, Ba
retrieved_image,
json_data: dict,
generate_uuid: bool = False,
+ save_to_db: bool = True,
):
- image: cls = super().from_json(
+ image = super().from_json(
connect_to,
retrieved_image,
json_data,
generate_uuid,
+ has_license_information=True,
)
image.exercise = connect_to
image.is_main = json_data['is_main']
+ image.is_ai_generated = json_data.get('is_ai_generated', False)
- image.license_id = json_data['license']
- image.license_title = json_data['license_title']
- image.license_object_url = json_data['license_object_url']
- image.license_author = json_data['license_author']
- image.license_author_url = json_data['license_author_url']
- image.license_derivative_source_url = json_data['license_derivative_source_url']
-
- image.save_image(retrieved_image, json_data)
-
- image.save()
+ if save_to_db:
+ image.save_image(retrieved_image, json_data)
+ image.save()
return image
diff --git a/wger/exercises/tests/test_exercise_images.py b/wger/exercises/tests/test_exercise_images.py
index 9aea7a501..0a55b0822 100644
--- a/wger/exercises/tests/test_exercise_images.py
+++ b/wger/exercises/tests/test_exercise_images.py
@@ -14,6 +14,7 @@
# Django
from django.core.files import File
+from django.test import SimpleTestCase
# wger
from wger.core.tests import api_base_test
@@ -127,6 +128,59 @@ class MainImageTestCase(WgerTestCase):
self.assertTrue(image.is_ai_generated)
+
+class ExerciseImageFromJsonSimpleTests(SimpleTestCase):
+ def test_from_json_sets_fields_when_generate_uuid_false(self):
+ json_data = {
+ 'uuid': '11111111-2222-3333-4444-555555555555',
+ 'license_title': 'CC-BY',
+ 'license_object_url': 'https://license.example/',
+ 'license_author': 'Author Name',
+ 'license_author_url': 'https://author.example/',
+ 'license_derivative_source_url': 'https://source.example/',
+ 'is_main': True,
+ 'is_ai_generated': True,
+ }
+
+ img = ExerciseImage.from_json(
+ connect_to=None,
+ retrieved_image=None,
+ json_data=json_data,
+ generate_uuid=False,
+ save_to_db=False,
+ )
+
+ self.assertIsInstance(img, ExerciseImage)
+ self.assertEqual(str(img.uuid), json_data['uuid'])
+ self.assertTrue(img.is_main)
+ self.assertTrue(img.is_ai_generated)
+ self.assertEqual(img.license_title, json_data['license_title'])
+ self.assertEqual(img.license_author, json_data['license_author'])
+
+ def test_from_json_generate_uuid_true_uses_model_default(self):
+ json_data = {
+ 'uuid': 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee',
+ 'license_title': 'CC-BY',
+ 'license_object_url': 'https://license.example/',
+ 'license_author': 'Author Name',
+ 'license_author_url': 'https://author.example/',
+ 'license_derivative_source_url': 'https://source.example/',
+ 'is_main': False,
+ }
+
+ img = ExerciseImage.from_json(
+ connect_to=None,
+ retrieved_image=None,
+ json_data=json_data,
+ generate_uuid=True,
+ save_to_db=False,
+ )
+
+ self.assertIsInstance(img, ExerciseImage)
+ self.assertNotEqual(str(img.uuid), json_data['uuid'])
+ self.assertFalse(img.is_main)
+
+
# TODO: add POST and DELETE tests
class ExerciseImagesApiTestCase(
api_base_test.BaseTestCase,
diff --git a/wger/nutrition/migrations/0013_ingredient_image.py b/wger/nutrition/migrations/0013_ingredient_image.py
index 17adbd26f..1bdf8cd7d 100644
--- a/wger/nutrition/migrations/0013_ingredient_image.py
+++ b/wger/nutrition/migrations/0013_ingredient_image.py
@@ -108,7 +108,7 @@ class Migration(migrations.Migration):
options={
'abstract': False,
},
- bases=(models.Model, wger.utils.helpers.BaseImage),
+ bases=(models.Model, wger.utils.helpers.BaseImageMixin),
),
migrations.RunPython(generate_uuids, reverse_code=noop),
migrations.AlterField(
diff --git a/wger/nutrition/models/image.py b/wger/nutrition/models/image.py
index a2bad9beb..da2044f54 100644
--- a/wger/nutrition/models/image.py
+++ b/wger/nutrition/models/image.py
@@ -22,9 +22,12 @@ import uuid
from django.db import models
# wger
-from wger.utils.helpers import BaseImage
+from wger.utils.helpers import BaseImageMixin
from wger.utils.models import AbstractLicenseModel
+# Local
+from .ingredient import Ingredient
+
def ingredient_image_upload_dir(instance, filename):
"""
@@ -34,7 +37,7 @@ def ingredient_image_upload_dir(instance, filename):
return f'ingredients/{instance.ingredient.pk}/{instance.uuid}{ext}'
-class Image(AbstractLicenseModel, models.Model, BaseImage):
+class Image(AbstractLicenseModel, models.Model, BaseImageMixin):
"""
Model for an ingredient image
"""
@@ -81,26 +84,25 @@ class Image(AbstractLicenseModel, models.Model, BaseImage):
@classmethod
def from_json(
cls,
- connect_to,
+ connect_to: Ingredient,
retrieved_image,
json_data: dict,
generate_uuid: bool = False,
+ save_to_db: bool = True,
):
- image: cls = super().from_json(connect_to, retrieved_image, json_data, generate_uuid)
+ image = super().from_json(
+ connect_to,
+ retrieved_image,
+ json_data,
+ generate_uuid,
+ has_license_information=True,
+ )
image.ingredient = connect_to
- image.license_id = json_data['license']
- image.license_title = json_data['license_title']
- image.license_object_url = json_data['license_object_url']
- image.license_author = json_data['license_author']
- image.license_author_url = json_data['license_author_url']
- image.license_derivative_source_url = json_data['license_derivative_source_url']
image.size = json_data['size']
- image.save_image(retrieved_image, json_data)
-
- image.save()
+ if save_to_db:
+ image.save_image(retrieved_image, json_data)
+ image.save()
- connect_to.image = image
- connect_to.save()
return image
diff --git a/wger/nutrition/tests/test_ingredient.py b/wger/nutrition/tests/test_ingredient.py
index bce6535a9..fb3206aee 100644
--- a/wger/nutrition/tests/test_ingredient.py
+++ b/wger/nutrition/tests/test_ingredient.py
@@ -21,6 +21,7 @@ from unittest.mock import patch
# Django
from django.core.exceptions import ValidationError
+from django.test import SimpleTestCase
from django.urls import reverse
# Third Party
@@ -41,6 +42,7 @@ from wger.nutrition.models import (
Ingredient,
Meal,
)
+from wger.nutrition.models.image import Image
from wger.utils.constants import NUTRITION_TAB
@@ -594,3 +596,52 @@ class IngredientApiCodeSearch(BaseTestCase, ApiBaseTestCase):
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data['count'], 0)
+
+
+class ImageFromJsonSimpleTests(SimpleTestCase):
+ def test_from_json_sets_uuid_size_and_license_when_generate_uuid_false(self):
+ json_data = {
+ 'uuid': '123e4567-e89b-12d3-a456-426614174000',
+ 'license_title': 'CC0',
+ 'license_object_url': 'https://license.example/',
+ 'license_author': 'Author Name',
+ 'license_author_url': 'https://author.example/',
+ 'license_derivative_source_url': 'https://source.example/',
+ 'size': 12345,
+ }
+
+ img = Image.from_json(
+ connect_to=None,
+ retrieved_image=None,
+ json_data=json_data,
+ generate_uuid=False,
+ save_to_db=False,
+ )
+
+ self.assertIsInstance(img, Image)
+ self.assertEqual(str(img.uuid), json_data['uuid'])
+ self.assertEqual(img.size, 12345)
+ self.assertEqual(img.license_title, json_data['license_title'])
+
+ def test_from_json_generate_uuid_true_uses_model_default_uuid(self):
+ json_data = {
+ 'uuid': '123e4567-e89b-12d3-a456-426614174001',
+ 'license_title': 'CC0',
+ 'license_object_url': 'https://license.example/',
+ 'license_author': 'Author Name',
+ 'license_author_url': 'https://author.example/',
+ 'license_derivative_source_url': 'https://source.example/',
+ 'size': 54321,
+ }
+
+ img = Image.from_json(
+ connect_to=None,
+ retrieved_image=None,
+ json_data=json_data,
+ generate_uuid=True,
+ save_to_db=False,
+ )
+
+ self.assertIsInstance(img, Image)
+ self.assertNotEqual(str(img.uuid), json_data['uuid'])
+ self.assertEqual(img.size, 54321)
diff --git a/wger/utils/helpers.py b/wger/utils/helpers.py
index a44caa03e..837ca6787 100644
--- a/wger/utils/helpers.py
+++ b/wger/utils/helpers.py
@@ -25,6 +25,7 @@ import re
import string
from decimal import Decimal
from functools import wraps
+from typing import Any
# Django
from django.contrib.auth.models import User
@@ -171,7 +172,7 @@ def random_string(length=32):
return ''.join(random.choice(string.ascii_uppercase) for i in range(length))
-class BaseImage:
+class BaseImageMixin:
def save_image(self, retrieved_image, json_data: dict):
# Save the downloaded image
# http://stackoverflow.com/questions/1308386/programmatically-saving-image-to
@@ -188,10 +189,24 @@ class BaseImage:
)
@classmethod
- def from_json(cls, connect_to, retrieved_image, json_data: dict, generate_uuid: bool = False):
- image: cls = cls()
+ def from_json(
+ cls,
+ connect_to: Any,
+ retrieved_image,
+ json_data: dict,
+ generate_uuid: bool = False,
+ has_license_information: bool = True,
+ ):
+ image = cls()
if not generate_uuid:
image.uuid = json_data['uuid']
+
+ if has_license_information:
+ image.license_title = json_data['license_title']
+ image.license_object_url = json_data['license_object_url']
+ image.license_author = json_data['license_author']
+ image.license_author_url = json_data['license_author_url']
+ image.license_derivative_source_url = json_data['license_derivative_source_url']
return image
diff --git a/wger/utils/tests/test_imagemixin.py b/wger/utils/tests/test_imagemixin.py
new file mode 100644
index 000000000..d73136672
--- /dev/null
+++ b/wger/utils/tests/test_imagemixin.py
@@ -0,0 +1,57 @@
+# Django
+from django.test import SimpleTestCase
+
+# wger
+from wger.utils.helpers import BaseImageMixin
+
+
+class ImageMixinTestCase(SimpleTestCase):
+ def test_from_json_sets_uuid_and_license(self):
+ json_data = {
+ 'uuid': '123e4567-e89b-12d3-a456-426614174000',
+ 'license_title': 'CC0',
+ 'license_object_url': 'https://license.example/',
+ 'license_author': 'Author Name',
+ 'license_author_url': 'https://author.example/',
+ 'license_derivative_source_url': 'https://source.example/',
+ }
+
+ img = BaseImageMixin.from_json(
+ connect_to=None,
+ retrieved_image=None,
+ json_data=json_data,
+ generate_uuid=False,
+ has_license_information=True,
+ )
+
+ self.assertIsInstance(img, BaseImageMixin)
+ self.assertEqual(getattr(img, 'uuid'), json_data['uuid'])
+ self.assertEqual(img.license_title, json_data['license_title'])
+ self.assertEqual(img.license_object_url, json_data['license_object_url'])
+ self.assertEqual(img.license_author, json_data['license_author'])
+ self.assertEqual(img.license_author_url, json_data['license_author_url'])
+ self.assertEqual(
+ img.license_derivative_source_url, json_data['license_derivative_source_url']
+ )
+
+ def test_from_json_skips_uuid_and_license_when_requested(self):
+ json_data = {
+ 'uuid': 'unused-uuid',
+ 'license_title': 'Should be skipped',
+ }
+
+ img = BaseImageMixin.from_json(
+ connect_to=None,
+ retrieved_image=None,
+ json_data=json_data,
+ generate_uuid=True,
+ has_license_information=False,
+ )
+
+ self.assertIsInstance(img, BaseImageMixin)
+ self.assertFalse(hasattr(img, 'uuid'))
+ self.assertFalse(hasattr(img, 'license_title'))
+ self.assertFalse(hasattr(img, 'license_object_url'))
+ self.assertFalse(hasattr(img, 'license_author'))
+ self.assertFalse(hasattr(img, 'license_author_url'))
+ self.assertFalse(hasattr(img, 'license_derivative_source_url'))