Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Add check for name similarity

Lydia Xingc1f0eac0e6da
diff --git a/wger/exercises/views/exercises.py b/wger/exercises/views/exercises.py
index 64c7aacae..a56aef899 100644
--- a/wger/exercises/views/exercises.py
+++ b/wger/exercises/views/exercises.py
@@ -26,6 +26,7 @@ from django.contrib.auth.mixins import (
PermissionRequiredMixin
)
from django.core import mail
+from django.core.exceptions import ValidationError
from django.forms import (
CharField,
CheckboxSelectMultiple,
@@ -83,6 +84,8 @@ from wger.utils.language import (
load_item_languages,
load_language
)
+from wger.utils.constants import MIN_EDIT_DISTANCE_THRESHOLD
+from wger.utils.helpers import levenshtein
from wger.utils.widgets import TranslatedSelectMultiple
from wger.weight.helpers import process_log_entries
@@ -157,6 +160,54 @@ def view(request, id, slug=None):
return render(request, 'exercise/view.html', template_data)
+class ExerciseForm(ModelForm):
+ # Redefine some fields here to set some properties
+ # (some of this could be done with a crispy form helper and would be
+ # a cleaner solution)
+ category = ModelChoiceField(queryset=ExerciseCategory.objects.all(),
+ widget=Select())
+ muscles = ModelMultipleChoiceField(queryset=Muscle.objects.all(),
+ widget=CheckboxSelectMultiple(),
+ required=False)
+
+ muscles_secondary = ModelMultipleChoiceField(queryset=Muscle.objects.all(),
+ widget=CheckboxSelectMultiple(),
+ required=False)
+
+ description = CharField(label=_('Description'),
+ widget=Textarea,
+ required=False)
+
+ class Meta:
+ model = Exercise
+ widgets = {'equipment': TranslatedSelectMultiple()}
+ fields = ['name_original',
+ 'category',
+ 'description',
+ 'muscles',
+ 'muscles_secondary',
+ 'equipment',
+ 'license',
+ 'license_author']
+
+ class Media:
+ js = (settings.STATIC_URL + 'yarn/tinymce/tinymce.min.js',)
+
+ def clean_name_original(self):
+ name_original = self.cleaned_data['name_original']
+ languages = load_item_languages(LanguageConfig.SHOW_ITEM_EXERCISES)
+ exercises = Exercise.objects.accepted() \
+ .filter(language__in=languages)
+ for exercise in exercises:
+ exercise_name = str(exercise)
+ if levenshtein(exercise_name.casefold(), name_original.casefold()) < MIN_EDIT_DISTANCE_THRESHOLD:
+ raise ValidationError(
+ _('%(name_original)s is too similar to existing exercise "%(exercise_name)s"'),
+ params={'name_original': name_original, 'exercise_name': exercise_name},
+ )
+ return data
+
+
class ExercisesEditAddView(WgerFormMixin):
"""
Generic view to subclass from for exercise adding and editing, since they
@@ -169,40 +220,6 @@ class ExercisesEditAddView(WgerFormMixin):
clean_html = ('description', )
def get_form_class(self):
-
- class ExerciseForm(ModelForm):
- # Redefine some fields here to set some properties
- # (some of this could be done with a crispy form helper and would be
- # a cleaner solution)
- category = ModelChoiceField(queryset=ExerciseCategory.objects.all(),
- widget=Select())
- muscles = ModelMultipleChoiceField(queryset=Muscle.objects.all(),
- widget=CheckboxSelectMultiple(),
- required=False)
-
- muscles_secondary = ModelMultipleChoiceField(queryset=Muscle.objects.all(),
- widget=CheckboxSelectMultiple(),
- required=False)
-
- description = CharField(label=_('Description'),
- widget=Textarea,
- required=False)
-
- class Meta:
- model = Exercise
- widgets = {'equipment': TranslatedSelectMultiple()}
- fields = ['name_original',
- 'category',
- 'description',
- 'muscles',
- 'muscles_secondary',
- 'equipment',
- 'license',
- 'license_author']
-
- class Media:
- js = (settings.STATIC_URL + 'yarn/tinymce/tinymce.min.js',)
-
return ExerciseForm
def get_form(self, form_class=None):
diff --git a/wger/utils/constants.py b/wger/utils/constants.py
index 6f2407656..81f19390c 100644
--- a/wger/utils/constants.py
+++ b/wger/utils/constants.py
@@ -60,3 +60,7 @@ HTML_STYLES_WHITELIST = ('text-decoration',)
PAGINATION_OBJECTS_PER_PAGE = 25
PAGINATION_MAX_TOTAL_PAGES = 10
PAGINATION_PAGES_AROUND_CURRENT = 5
+
+# Minimum edit distance from all existing exercises for a new exercise submission
+# to be accepted
+MIN_EDIT_DISTANCE_THRESHOLD = 2
diff --git a/wger/utils/helpers.py b/wger/utils/helpers.py
index 627f35aa6..4b3e1389d 100644
--- a/wger/utils/helpers.py
+++ b/wger/utils/helpers.py
@@ -235,3 +235,30 @@ def smart_capitalize(input):
else:
out.append(word)
return ' '.join(out)
+
+def levenshtein(s1, s2):
+ """
+ The Levenshtein distance
+
+ This is used as a string metric for measuring the difference between
+ two sequences. We use this to determine whether or not similar
+ exercises have been added
+
+ Source: Wikipedia
+
+ :param input: two input strings
+ :return: number of characters different between the strings
+ """
+ if len(s1) > len(s2):
+ s1, s2 = s2, s1
+
+ distances = range(len(s1) + 1)
+ for i2, c2 in enumerate(s2):
+ distances_ = [i2+1]
+ for i1, c1 in enumerate(s1):
+ if c1 == c2:
+ distances_.append(distances[i1])
+ else:
+ distances_.append(1 + min((distances[i1], distances[i1 + 1], distances_[-1])))
+ distances = distances_
+ return distances[-1]