From 6b9caa8bd6fb74a4702dfc22cc22a75d7269fa02 Mon Sep 17 00:00:00 2001 From: pankaj-basnet <165250380+pankaj-basnet@users.noreply.github.com> Date: Thu, 28 May 2026 01:08:57 +0545 Subject: [PATCH 1/3] feat(api): add similar/duplicate exercise name validation Resolves #2357. Implemented duplicate detection in the serialization layer to prevent variations like 'pull ups' and 'pull-ups' from cluttering the database. - Uses regex normalization to catch exact structural variants. - Uses PostgreSQL TrigramSimilarity for fuzzy semantic matching. - Added logic to ensure users can still safely edit existing exercises without triggering false-positive validation errors against themselves. --- wger/exercises/api/serializers.py | 59 ++++++++++++++++++++++++++++++- 1 file changed, 58 insertions(+), 1 deletion(-) diff --git a/wger/exercises/api/serializers.py b/wger/exercises/api/serializers.py index 9971e3deb..62d9098d7 100644 --- a/wger/exercises/api/serializers.py +++ b/wger/exercises/api/serializers.py @@ -13,16 +13,21 @@ # You should have received a copy of the GNU Affero General Public License # Standard Library +import re import uuid # Django from django.conf import settings +from django.contrib.postgres.search import TrigramSimilarity from django.core.cache import cache from django.db import ( models, transaction, ) -from django.db.models import Q +from django.db.models import ( + Length, + Q, +) # Third Party from actstream import action as actstream_action @@ -49,6 +54,10 @@ from wger.utils.constants import CC_BY_SA_4_LICENSE_ID from wger.utils.url import make_absolute_url +# Configuration threshold +SIMILARITY_THRESHOLD = 0.85 + + def _log_action_creation(serializer, instance): """ Emit an actstream ``created`` event for a freshly-created instance. @@ -66,6 +75,42 @@ def _log_action_creation(serializer, instance): ) +def _normalise_name(name: str) -> str: + """ + Regex: matches space, hyphen and underscore, and replaces with an empty string. + """ + return re.sub(r'[\s\-_]+', '', name.strip().lower()) + + +def _check_duplicates(name, language, exclude_pk=None): + base_qs = Translation.objects.filter(language=language) + if exclude_pk: + base_qs = base_qs.exclude(pk=exclude_pk) + + norm_new = _normalise_name(name) + input_len = len(name) + + # Filter by length for exact match + candidates = base_qs.annotate(n_len=Length('name')).filter( + n_len__gte=input_len - 4, n_len__lte=input_len + 4 + ) + + for candidate in candidates: + if _normalise_name(candidate.name) == norm_new: + return candidate.name + + # Trigram Similarity + hit = ( + base_qs.annotate(similarity=TrigramSimilarity('name', name)) + .filter(similarity__gte=SIMILARITY_THRESHOLD) + .order_by('-similarity') + .values_list('name', flat=True) + .first() + ) + + return hit + + class ExerciseSerializer(serializers.ModelSerializer): """ Exercise serializer @@ -437,6 +482,18 @@ class ExerciseTranslationSerializer(serializers.ModelSerializer): if description and language: validate_language_matches(description, language, 'description') + # Check for duplicates + name = value.get('name') + if name and language: + exclude_pk = self.instance.pk if self.instance else None + duplicate_hit = _check_duplicates(name, language, exclude_pk=exclude_pk) + if duplicate_hit: + raise serializers.ValidationError( + { + 'name': f'The name "{name}" is too similar to the existing exercise "{duplicate_hit}". Please choose a more distinct name or submit a variation instead.' + } + ) + return super().validate(value) From d71b0428fa37c493d77830eeae044175056fb9fa Mon Sep 17 00:00:00 2001 From: pankaj-basnet <165250380+pankaj-basnet@users.noreply.github.com> Date: Thu, 28 May 2026 18:40:40 +0545 Subject: [PATCH 2/3] add unit tests, and add fuzzy/structural name duplicate detection for sqlite as well - Implements cross-database (Postgres/SQLite) duplicate checking for exercise names. - Uses pg_trgm for Postgres and difflib.SequenceMatcher for fallback. - Added validation tests for POST and PATCH scenarios including self-edit exclusion. --- wger/exercises/api/serializers.py | 34 +++-- .../tests/test_exercise_translation.py | 133 ++++++++++++++++++ 2 files changed, 153 insertions(+), 14 deletions(-) diff --git a/wger/exercises/api/serializers.py b/wger/exercises/api/serializers.py index 62d9098d7..82def8b3b 100644 --- a/wger/exercises/api/serializers.py +++ b/wger/exercises/api/serializers.py @@ -15,6 +15,7 @@ # Standard Library import re import uuid +from difflib import SequenceMatcher # Django from django.conf import settings @@ -24,10 +25,8 @@ from django.db import ( models, transaction, ) -from django.db.models import ( - Length, - Q, -) +from django.db.models import Q +from django.db.models.functions import Length # Third Party from actstream import action as actstream_action @@ -51,6 +50,7 @@ from wger.exercises.models import ( from wger.exercises.views.helper import StreamVerbs from wger.utils.cache import CacheKeyMapper from wger.utils.constants import CC_BY_SA_4_LICENSE_ID +from wger.utils.db import is_postgres_db from wger.utils.url import make_absolute_url @@ -87,6 +87,16 @@ def _check_duplicates(name, language, exclude_pk=None): if exclude_pk: base_qs = base_qs.exclude(pk=exclude_pk) + # Trigram Similarity + if is_postgres_db(): + return ( + base_qs.annotate(similarity=TrigramSimilarity('name', name)) + .filter(similarity__gte=SIMILARITY_THRESHOLD) + .order_by('-similarity') + .values_list('name', flat=True) + .first() + ) + norm_new = _normalise_name(name) input_len = len(name) @@ -95,20 +105,16 @@ def _check_duplicates(name, language, exclude_pk=None): n_len__gte=input_len - 4, n_len__lte=input_len + 4 ) + # SequenceMatcher for candidate in candidates: if _normalise_name(candidate.name) == norm_new: return candidate.name - # Trigram Similarity - hit = ( - base_qs.annotate(similarity=TrigramSimilarity('name', name)) - .filter(similarity__gte=SIMILARITY_THRESHOLD) - .order_by('-similarity') - .values_list('name', flat=True) - .first() - ) - - return hit + if ( + SequenceMatcher(None, norm_new, _normalise_name(candidate.name)).ratio() + >= SIMILARITY_THRESHOLD + ): + return candidate.name class ExerciseSerializer(serializers.ModelSerializer): diff --git a/wger/exercises/tests/test_exercise_translation.py b/wger/exercises/tests/test_exercise_translation.py index d42b962e2..9f5aab65c 100644 --- a/wger/exercises/tests/test_exercise_translation.py +++ b/wger/exercises/tests/test_exercise_translation.py @@ -361,3 +361,136 @@ class ExerciseTranslationCustomApiTestCase(ActstreamApiMixin, ExerciseCrudApiTes response = self.client.patch(self.url_detail, data={'language': 3}) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) self.assertTrue(response.data['non_field_errors']) + + def test_post_rejects_structural_duplicate_name(self): + """ + Test that submitting a name structurally identical (ignoring spaces/hyphens) + to an existing exercise in the same language is rejected. + """ + + # wger + from wger.exercises.models import ExerciseCategory + + category = ExerciseCategory.objects.first() + + exercise_a = Exercise.objects.create( + category=category, + license_id=2, + license_author='test', + ) + Translation.objects.create( + exercise=exercise_a, + language_id=2, + name='Pull ups', + description_source='A base description for the duplicate name seed translation.', + ) + + exercise_b = Exercise.objects.create( + category=category, + license_id=2, + license_author='test', + ) + + payload = { + 'name': 'Pull-ups', + 'description_source': 'A new description for the pullups duplicate test.', + 'exercise': exercise_b.pk, + 'language': 2, + } + + self.authenticate('trainer1') + response = self.client.post(self.url, data=payload) + + self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) + self.assertIn('name', response.json()) + self.assertIn('too similar', response.json()['name'][0]) + + def test_post_rejects_fuzzy_duplicate_name(self): + """ + Test that submitting a name semantically similar (trigram) + to an existing exercise in the same language is rejected. + """ + # wger + from wger.exercises.models import ExerciseCategory + + category = ExerciseCategory.objects.first() + + exercise_a = Exercise.objects.create( + category=category, + license_id=2, + license_author='test', + ) + Translation.objects.create( + exercise=exercise_a, + language_id=2, + name='Bench Press', + description_source='A base description for the bench press seed translation.', + ) + + exercise_b = Exercise.objects.create( + category=category, + license_id=2, + license_author='test', + ) + + payload = { + 'name': 'Benchpress', # fuzzy duplicate + 'description_source': 'A new description for the benchpress duplicate test.', + 'exercise': exercise_b.pk, + 'language': 2, + } + + self.authenticate('trainer1') + response = self.client.post(self.url, data=payload) + + self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) + self.assertIn('name', response.json()) + self.assertIn('too similar', response.json()['name'][0]) + + def test_patch_allows_self_edit_with_same_name(self): + """ + Test that editing an existing translation without changing its name + (or submitting the exact same name) does not trigger a duplicate error, + validating the `exclude_pk` logic. + """ + translation = Translation.objects.get(pk=self.pk) + original_name = translation.name + + self.authenticate('trainer1') + # passing the same name back + response = self.client.patch( + self.url_detail, + data={'description_source': 'Updating the description only', 'name': original_name}, + ) + + self.assertEqual(response.status_code, status.HTTP_200_OK) + + def test_patch_rejects_conflict_with_other_name(self): + """ + Test that editing an existing translation's name to collide with + a DIFFERENT existing translation's name is rejected. + """ + + # wger + from wger.exercises.models import ExerciseCategory + + other_exercise = Exercise.objects.create( + category=ExerciseCategory.objects.first(), + license_id=2, + license_author='test', + ) + Translation.objects.create( + exercise=other_exercise, + language_id=2, + name='Barbell Squat', + description_source='Base description for barbell squat test.', + ) + + self.authenticate('trainer1') + response = self.client.patch( + self.url_detail, + data={'name': 'Barbell-Squat'}, # Structural duplicate + ) + + self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) + self.assertIn('name', response.json()) From 52e6a185e9935f3c3b031b442ccef1a7dfad409d Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Thu, 2 Jul 2026 12:36:26 +0200 Subject: [PATCH 3/3] Small cleanups --- wger/exercises/api/serializers.py | 12 +++- .../tests/api/test_create_throttle.py | 8 ++- .../tests/test_exercise_translation.py | 69 ++++++++++++++----- 3 files changed, 65 insertions(+), 24 deletions(-) diff --git a/wger/exercises/api/serializers.py b/wger/exercises/api/serializers.py index 9d4efd197..9a72c17a0 100644 --- a/wger/exercises/api/serializers.py +++ b/wger/exercises/api/serializers.py @@ -508,15 +508,21 @@ class ExerciseTranslationSerializer(serializers.ModelSerializer): if description and language: validate_language_matches(description, language, 'description') - # Check for duplicates + # Check for duplicates, but only when the name is actually being + # changed since there are possibly near-duplicates in the existing db name = value.get('name') - if name and language: + name_changed = not self.instance or _normalise_name(name or '') != _normalise_name( + self.instance.name + ) + if name and language and name_changed: exclude_pk = self.instance.pk if self.instance else None duplicate_hit = _check_duplicates(name, language, exclude_pk=exclude_pk) if duplicate_hit: raise serializers.ValidationError( { - 'name': f'The name "{name}" is too similar to the existing exercise "{duplicate_hit}". Please choose a more distinct name or submit a variation instead.' + 'name': f'The name "{name}" is too similar to the existing exercise ' + f'"{duplicate_hit}". Please choose a more distinct name or submit ' + f'a variation instead.' } ) diff --git a/wger/exercises/tests/api/test_create_throttle.py b/wger/exercises/tests/api/test_create_throttle.py index b4edac8cb..c771d59e7 100644 --- a/wger/exercises/tests/api/test_create_throttle.py +++ b/wger/exercises/tests/api/test_create_throttle.py @@ -41,14 +41,14 @@ class ExerciseCreateThrottleTestCase(BaseTestCase, ApiBaseTestCase): """ @staticmethod - def get_payload(): + def get_payload(name='Throttle Test Exercise'): return { 'category': 3, 'license': 5, 'license_author': 'tester', 'translations': [ { - 'name': 'Throttle Test Exercise', + 'name': name, 'description_source': ( 'A sufficiently long English description so the language ' 'detector recognises it and the minimum length passes.' @@ -97,7 +97,9 @@ class ExerciseCreateThrottleTestCase(BaseTestCase, ApiBaseTestCase): with mock.patch.dict(api_settings.DEFAULT_THROTTLE_RATES, {'exercise_create': '1/min'}): first = self.client.post(url, data=self.get_payload()) - second = self.client.post(url, data=self.get_payload()) + # A distinct name, otherwise the duplicate-name check would reject + # the second submission before the throttle exemption is exercised. + second = self.client.post(url, data=self.get_payload('Completely Different Movement')) self.assertEqual(first.status_code, status.HTTP_201_CREATED) self.assertEqual(second.status_code, status.HTTP_201_CREATED) diff --git a/wger/exercises/tests/test_exercise_translation.py b/wger/exercises/tests/test_exercise_translation.py index 6f208c418..ec7d3779c 100644 --- a/wger/exercises/tests/test_exercise_translation.py +++ b/wger/exercises/tests/test_exercise_translation.py @@ -21,6 +21,7 @@ from wger.core.tests.api_base_test import ExerciseCrudApiTestCase from wger.core.tests.base_testcase import WgerTestCase from wger.exercises.models import ( Exercise, + ExerciseCategory, Muscle, Translation, ) @@ -404,10 +405,6 @@ class ExerciseTranslationCustomApiTestCase(ActstreamApiMixin, ExerciseCrudApiTes Test that submitting a name structurally identical (ignoring spaces/hyphens) to an existing exercise in the same language is rejected. """ - - # wger - from wger.exercises.models import ExerciseCategory - category = ExerciseCategory.objects.first() exercise_a = Exercise.objects.create( @@ -444,12 +441,11 @@ class ExerciseTranslationCustomApiTestCase(ActstreamApiMixin, ExerciseCrudApiTes def test_post_rejects_fuzzy_duplicate_name(self): """ - Test that submitting a name semantically similar (trigram) - to an existing exercise in the same language is rejected. + Test that submitting a name that is only fuzzily similar to an existing + one in the same language is rejected. The names differ even after + normalisation (stripping spaces/hyphens leaves the trailing "s"), so + this exercises the similarity fallback rather than exact matching. """ - # wger - from wger.exercises.models import ExerciseCategory - category = ExerciseCategory.objects.first() exercise_a = Exercise.objects.create( @@ -460,8 +456,8 @@ class ExerciseTranslationCustomApiTestCase(ActstreamApiMixin, ExerciseCrudApiTes Translation.objects.create( exercise=exercise_a, language_id=2, - name='Bench Press', - description_source='A base description for the bench press seed translation.', + name='Deadlift', + description_source='A base description for the deadlift seed translation.', ) exercise_b = Exercise.objects.create( @@ -471,8 +467,8 @@ class ExerciseTranslationCustomApiTestCase(ActstreamApiMixin, ExerciseCrudApiTes ) payload = { - 'name': 'Benchpress', # fuzzy duplicate - 'description_source': 'A new description for the benchpress duplicate test.', + 'name': 'Deadlifts', # fuzzy duplicate (plural variant) + 'description_source': 'A new description for the deadlifts duplicate test.', 'exercise': exercise_b.pk, 'language': 2, } @@ -497,7 +493,13 @@ class ExerciseTranslationCustomApiTestCase(ActstreamApiMixin, ExerciseCrudApiTes # passing the same name back response = self.client.patch( self.url_detail, - data={'description_source': 'Updating the description only', 'name': original_name}, + data={ + 'description_source': ( + 'A sufficiently long English description so the language ' + 'detector can reliably recognise it as English.' + ), + 'name': original_name, + }, ) self.assertEqual(response.status_code, status.HTTP_200_OK) @@ -507,10 +509,6 @@ class ExerciseTranslationCustomApiTestCase(ActstreamApiMixin, ExerciseCrudApiTes Test that editing an existing translation's name to collide with a DIFFERENT existing translation's name is rejected. """ - - # wger - from wger.exercises.models import ExerciseCategory - other_exercise = Exercise.objects.create( category=ExerciseCategory.objects.first(), license_id=2, @@ -531,3 +529,38 @@ class ExerciseTranslationCustomApiTestCase(ActstreamApiMixin, ExerciseCrudApiTes self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) self.assertIn('name', response.json()) + + def test_patch_allows_edit_when_unchanged_name_collides_with_existing(self): + """ + Test that editing a translation without changing its name succeeds even + when another, pre-existing near-duplicate already lives in the database + """ + translation = Translation.objects.get(pk=self.pk) + + # Seed a near-duplicate of the edited translation in the same language + twin_exercise = Exercise.objects.create( + category=ExerciseCategory.objects.first(), + license_id=2, + license_author='test', + ) + Translation.objects.create( + exercise=twin_exercise, + language_id=translation.language_id, + name=translation.name.replace(' ', '-'), + description_source='Base description for the pre-existing near-duplicate.', + ) + + self.authenticate('trainer1') + # Resubmit the unchanged name together with a new description + response = self.client.patch( + self.url_detail, + data={ + 'name': translation.name, + 'description_source': ( + 'A sufficiently long English description so the language ' + 'detector can reliably recognise it as English.' + ), + }, + ) + + self.assertEqual(response.status_code, status.HTTP_200_OK)