From b8b9244fc84ff2db339f3edde9160f5353653498 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20P=C3=A9ters?= Date: Tue, 26 May 2020 15:21:31 +0200 Subject: [PATCH] misc: add filter to detect language (#43335) --- debian/control | 1 + tests/test_templates.py | 13 +++++++++++++ tox.ini | 1 + wcs/qommon/templatetags/qommon.py | 16 ++++++++++++++++ 4 files changed, 31 insertions(+) diff --git a/debian/control b/debian/control index 4fde2df15..82acea38e 100644 --- a/debian/control +++ b/debian/control @@ -30,6 +30,7 @@ Recommends: libreoffice-writer-nogui | libreoffice-writer, poppler-utils, python3-dns, python3-docutils, + python3-langdetect, python3-magic, python3-qrcode, python3-xlwt diff --git a/tests/test_templates.py b/tests/test_templates.py index baf8dc7ba..7a298a233 100644 --- a/tests/test_templates.py +++ b/tests/test_templates.py @@ -4,6 +4,11 @@ import datetime import pytest import string +try: + import langdetect +except ImportError: + langdetect = None + from django.test import override_settings from quixote import cleanup from wcs.qommon.substitution import CompatibilityNamesDict @@ -604,3 +609,11 @@ def test_phonenumber_fr(): assert t.render({'number': None}) == 'None' t = Template('{{ number|decimal|phonenumber_fr }}') assert t.render({'number': '1,33'}) == '1.33' + + +@pytest.mark.skipif('langdetect is None') +def test_language_detect(): + t = Template('{{ plop|language_detect }}') + assert t.render({'plop': 'Good morning world'}) == 'en' + assert t.render({'plop': 'Bonjour tout le monde'}) == 'fr' + assert t.render({'plop': '2132133'}) == '' diff --git a/tox.ini b/tox.ini index dfd7c5acc..6668574b1 100644 --- a/tox.ini +++ b/tox.ini @@ -32,6 +32,7 @@ deps = Pillow python-magic docutils + langdetect git+https://git.entrouvert.org/debian/django-ckeditor.git django111: django>=1.11,<1.12 django22: django>=2.2,<2.3 diff --git a/wcs/qommon/templatetags/qommon.py b/wcs/qommon/templatetags/qommon.py index 462759a79..b1ef3ed54 100644 --- a/wcs/qommon/templatetags/qommon.py +++ b/wcs/qommon/templatetags/qommon.py @@ -26,6 +26,12 @@ import random import pyproj from pyproj import Geod +try: + import langdetect + from langdetect.lang_detect_exception import LangDetectException +except ImportError: + langdetect = None + from django import template from django.template import defaultfilters from django.utils import dateparse @@ -440,6 +446,16 @@ def has_role(user, role_name): return False +@register.filter +def language_detect(value): + if langdetect is None: + return '' + try: + return langdetect.detect(str(value)) + except LangDetectException: + return '' + + @register.filter(is_safe=False) def phonenumber_fr(value, separator=' '): DROMS = ('262', '508', '590', '594', '596')