From a8f5aa5edce5ed65e1bb4970ac7a413145497357 Mon Sep 17 00:00:00 2001 From: Satyam Kumar Date: Sat, 16 May 2020 03:52:30 +0530 Subject: [PATCH 1/7] Address #18 - More unified language support --- requirements.txt | 2 +- src/zimscraperlib/i18n.py | 135 +++++++++++++++++++++++++------------- tests/i18n/test_i18n.py | 113 +++++++++++++++++-------------- 3 files changed, 154 insertions(+), 96 deletions(-) diff --git a/requirements.txt b/requirements.txt index f40c0bc9..218e3dc0 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,4 @@ -iso639==0.1.4 +iso-639==0.4.5 requests>=2.22,<3.0 colorthief==0.2.1 python-resize-image==1.1.19 diff --git a/src/zimscraperlib/i18n.py b/src/zimscraperlib/i18n.py index 40e7a84c..635bfb51 100644 --- a/src/zimscraperlib/i18n.py +++ b/src/zimscraperlib/i18n.py @@ -4,8 +4,10 @@ import locale import gettext +import re -import iso639 +from iso639 import languages +from . import logger class Locale: @@ -48,51 +50,90 @@ def setlocale(root_dir, locale_name): return Locale.setup(root_dir / "locale", locale_name) -def get_language_details(iso_639_3): - """ dict container iso639-2, name and native name for an iso-639-3 code """ - non_iso_langs = { - "zh-Hans": { - "code": "zh-Hans", - "iso-639-1": "zh", - "english": "Simplified Chinese", - "native": "简化字", - }, - "zh-Hant": { - "code": "zh-Hant", - "iso-639-1": "zh", - "english": "Traditional Chinese", - "native": "正體字", - }, - "iw": {"code": "iw", "iso-639-1": "he", "english": "Hebrew", "native": "עברית"}, - "es-419": { - "code": "es-419", - "iso-639-1": "es-419", - "english": "Spanish", - "native": "Español", - }, - "multi": { - "code": "mul", - "iso-639-1": "en", - "english": "Multiple Languages", - "native": "Multiple Languages", - }, - } - - try: - return ( - non_iso_langs.get(iso_639_3) - if iso_639_3 in non_iso_langs.keys() - else { - "code": iso_639_3, - "iso-639-1": iso639.to_iso639_1(iso_639_3), - "english": iso639.to_name(iso_639_3), - "native": iso639.to_native(iso_639_3), - } - ) - except iso639.NonExistentLanguageError: +def get_language_details(query): + """returns language details if query is a language or a locale otherwise returns None""" + + def get_iso_lang_data(lang): + """return details if lang is a valid iso language else raises exception""" + + iso_types = [] + try: + languages.get(part1=lang) + iso_types.append("part1") + except KeyError: + logger.debug("Not a valid iso-639-1") + try: + languages.get(part2b=lang) + iso_types.append("part2b") + except KeyError: + logger.debug("Not a valid iso-639-2b") + try: + languages.get(part2t=lang) + iso_types.append("part2t") + except KeyError: + logger.debug("Not a valid iso-639-2t") + try: + languages.get(part3=lang) + iso_types.append("part3") + except KeyError: + logger.debug("Not a valid iso-639-3") + try: + languages.get(part5=lang) + iso_types.append("part5") + except KeyError: + logger.debug("Not a valid iso-639-5") + try: + languages.get(name=lang) + iso_types.append("name") + except KeyError: + logger.debug("Not a valid iso language name") + + if not iso_types: + raise Exception("Not a valid iso language name/code") + + res = languages.get(**{iso_types[0]: lang}) + return { - "code": iso_639_3, - "iso-639-1": iso_639_3, - "english": iso_639_3, - "native": iso_639_3, + "iso-639-1": res.part1, + "iso-639-2b": res.part2b, + "iso-639-2t": res.part2t, + "iso-639-3": res.part3, + "iso-639-5": res.part5, + "english": res.name, + "iso_types": iso_types, } + + if query.isalpha() and (2 <= len(query) <= 3): + # possibility of iso-639 code + try: + iso_data = get_iso_lang_data(query) + iso_data["querytype"] = "purecode" + except Exception as exc: + logger.error(str(exc)) + return None + + elif all(x.isalpha() or x == "-" or x == "_" for x in query) and ( + query.count("_") + query.count("-") == 1 + ): + # possibility of locale + query_parts = re.split("-|_", query) + try: + iso_data = get_iso_lang_data(query_parts[0]) + iso_data["querytype"] = "locale" + except Exception as exc: + logger.error(str(exc)) + return None + + else: + # possibility of iso language name + try: + iso_data = get_iso_lang_data( + query.title().replace("Languages", "languages") + ) + iso_data["querytype"] = "languagename" + except Exception as exc: + logger.error(str(exc)) + return None + + iso_data["query"] = query + return iso_data diff --git a/tests/i18n/test_i18n.py b/tests/i18n/test_i18n.py index 8933aa6e..8cf3cbc6 100644 --- a/tests/i18n/test_i18n.py +++ b/tests/i18n/test_i18n.py @@ -24,83 +24,100 @@ def test_selocale_unsupported(tmp_path): @pytest.mark.parametrize( - "iso_639_3,expected", + "query,expected", [ ( "zh-Hans", { - "code": "zh-Hans", "iso-639-1": "zh", - "english": "Simplified Chinese", - "native": "简化字", + "iso-639-2b": "chi", + "iso-639-2t": "zho", + "iso-639-3": "zho", + "iso-639-5": "", + "english": "Chinese", + "iso_types": ["part1"], + "querytype": "locale", + "query": "zh-Hans", }, ), ( - "zh-Hant", + "hi", { - "code": "zh-Hant", - "iso-639-1": "zh", - "english": "Traditional Chinese", - "native": "正體字", + "iso-639-1": "hi", + "iso-639-2b": "hin", + "iso-639-2t": "hin", + "iso-639-3": "hin", + "iso-639-5": "", + "english": "Hindi", + "iso_types": ["part1"], + "querytype": "purecode", + "query": "hi", }, ), ( - "iw", - {"code": "iw", "iso-639-1": "he", "english": "Hebrew", "native": "עברית"}, - ), - ( - "es-419", + "hin", { - "code": "es-419", - "iso-639-1": "es-419", - "english": "Spanish", - "native": "Español", + "iso-639-1": "hi", + "iso-639-2b": "hin", + "iso-639-2t": "hin", + "iso-639-3": "hin", + "iso-639-5": "", + "english": "Hindi", + "iso_types": ["part2b", "part2t", "part3"], + "querytype": "purecode", + "query": "hin", }, ), ( - "multi", + "Japanese", { - "code": "mul", - "iso-639-1": "en", - "english": "Multiple Languages", - "native": "Multiple Languages", + "iso-639-1": "ja", + "iso-639-2b": "jpn", + "iso-639-2t": "jpn", + "iso-639-3": "jpn", + "iso-639-5": "", + "english": "Japanese", + "iso_types": ["name"], + "querytype": "languagename", + "query": "Japanese", }, ), ( - "fra", + "afa", { - "code": "fra", - "english": "French", - "iso-639-1": "fr", - "native": "français; langue française", + "iso-639-1": "", + "iso-639-2b": "afa", + "iso-639-2t": "afa", + "iso-639-3": "", + "iso-639-5": "afa", + "english": "Afro-Asiatic languages", + "iso_types": ["part2b", "part2t", "part5"], + "querytype": "purecode", + "query": "afa", }, ), ( - "bam", + "afro-asiatic languages", { - "code": "bam", - "english": "Bambara", - "iso-639-1": "bm", - "native": "bamanankan", + "iso-639-1": "", + "iso-639-2b": "afa", + "iso-639-2t": "afa", + "iso-639-3": "", + "iso-639-5": "afa", + "english": "Afro-Asiatic languages", + "iso_types": ["name"], + "querytype": "languagename", + "query": "afro-asiatic languages", }, ), - ( - "ara", - { - "code": "ara", - "english": "Arabic", - "iso-639-1": "ar", - "native": "العربية", - }, - ), - ( - "fake", - {"code": "fake", "english": "fake", "iso-639-1": "fake", "native": "fake"}, - ), + ("fake-lang", None,), + ("fake", None,), + ("C#", None,), + ("fks", None,), ], ) -def test_lang_details(iso_639_3, expected): - assert get_language_details(iso_639_3) == expected +def test_lang_details(query, expected): + assert get_language_details(query) == expected @pytest.mark.parametrize( From 95f402eaa197c93864321e24e5bc66f70771ca26 Mon Sep 17 00:00:00 2001 From: Satyam Kumar Date: Tue, 19 May 2020 14:34:03 +0530 Subject: [PATCH 2/7] Address #18 - Get info from macrolanguage also --- src/zimscraperlib/i18n.py | 15 +++++++++++++-- tests/i18n/test_i18n.py | 14 ++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/src/zimscraperlib/i18n.py b/src/zimscraperlib/i18n.py index 635bfb51..654aa4d5 100644 --- a/src/zimscraperlib/i18n.py +++ b/src/zimscraperlib/i18n.py @@ -51,10 +51,10 @@ def setlocale(root_dir, locale_name): def get_language_details(query): - """returns language details if query is a language or a locale otherwise returns None""" + """ returns language details if query is a language or a locale otherwise returns None """ def get_iso_lang_data(lang): - """return details if lang is a valid iso language else raises exception""" + """ return details if lang is a valid iso language else raises exception """ iso_types = [] try: @@ -92,6 +92,17 @@ def get_iso_lang_data(lang): raise Exception("Not a valid iso language name/code") res = languages.get(**{iso_types[0]: lang}) + if res.macro: + macro_data = get_iso_lang_data(res.macro) + return { + "iso-639-1": res.part1 if res.part1 else macro_data["iso-639-1"], + "iso-639-2b": res.part2b if res.part2b else macro_data["iso-639-2b"], + "iso-639-2t": res.part2t if res.part2t else macro_data["iso-639-2t"], + "iso-639-3": res.part3 if res.part3 else macro_data["iso-639-3"], + "iso-639-5": res.part5 if res.part5 else macro_data["iso-639-5"], + "english": res.name, + "iso_types": iso_types, + } return { "iso-639-1": res.part1, diff --git a/tests/i18n/test_i18n.py b/tests/i18n/test_i18n.py index 8cf3cbc6..bc880272 100644 --- a/tests/i18n/test_i18n.py +++ b/tests/i18n/test_i18n.py @@ -110,6 +110,20 @@ def test_selocale_unsupported(tmp_path): "query": "afro-asiatic languages", }, ), + ( + "cmn", + { + "iso-639-1": "zh", + "iso-639-2b": "chi", + "iso-639-2t": "zho", + "iso-639-3": "cmn", + "iso-639-5": "", + "english": "Mandarin Chinese", + "iso_types": ["part3"], + "querytype": "purecode", + "query": "cmn", + }, + ), ("fake-lang", None,), ("fake", None,), ("C#", None,), From 7fff4df50b9b6b2d4a541a6022fcfb4d6220662c Mon Sep 17 00:00:00 2001 From: Satyam Kumar Date: Wed, 20 May 2020 19:38:27 +0530 Subject: [PATCH 3/7] Address #18 - Refactored code, add native name support --- requirements.txt | 1 + src/zimscraperlib/i18n.py | 109 ++++++++++++++++++++++---------------- tests/i18n/test_i18n.py | 37 +++++++++++++ 3 files changed, 101 insertions(+), 46 deletions(-) diff --git a/requirements.txt b/requirements.txt index a49086e2..6c29203d 100644 --- a/requirements.txt +++ b/requirements.txt @@ -2,3 +2,4 @@ iso-639==0.4.5 requests>=2.22,<3.0 colorthief==0.2.1 python-resize-image==1.1.* +Babel==2.8 diff --git a/src/zimscraperlib/i18n.py b/src/zimscraperlib/i18n.py index 654aa4d5..05d4cf0b 100644 --- a/src/zimscraperlib/i18n.py +++ b/src/zimscraperlib/i18n.py @@ -5,6 +5,7 @@ import locale import gettext import re +import babel from iso639 import languages from . import logger @@ -56,55 +57,21 @@ def get_language_details(query): def get_iso_lang_data(lang): """ return details if lang is a valid iso language else raises exception """ + code_types = ["part1", "part2b", "part2t", "part3", "part5", "name"] iso_types = [] - try: - languages.get(part1=lang) - iso_types.append("part1") - except KeyError: - logger.debug("Not a valid iso-639-1") - try: - languages.get(part2b=lang) - iso_types.append("part2b") - except KeyError: - logger.debug("Not a valid iso-639-2b") - try: - languages.get(part2t=lang) - iso_types.append("part2t") - except KeyError: - logger.debug("Not a valid iso-639-2t") - try: - languages.get(part3=lang) - iso_types.append("part3") - except KeyError: - logger.debug("Not a valid iso-639-3") - try: - languages.get(part5=lang) - iso_types.append("part5") - except KeyError: - logger.debug("Not a valid iso-639-5") - try: - languages.get(name=lang) - iso_types.append("name") - except KeyError: - logger.debug("Not a valid iso language name") + + for code_type in code_types: + try: + languages.get(**{code_type: lang}) + iso_types.append(code_type) + except KeyError: + logger.debug(f"Not a valid {code_type}") if not iso_types: raise Exception("Not a valid iso language name/code") res = languages.get(**{iso_types[0]: lang}) - if res.macro: - macro_data = get_iso_lang_data(res.macro) - return { - "iso-639-1": res.part1 if res.part1 else macro_data["iso-639-1"], - "iso-639-2b": res.part2b if res.part2b else macro_data["iso-639-2b"], - "iso-639-2t": res.part2t if res.part2t else macro_data["iso-639-2t"], - "iso-639-3": res.part3 if res.part3 else macro_data["iso-639-3"], - "iso-639-5": res.part5 if res.part5 else macro_data["iso-639-5"], - "english": res.name, - "iso_types": iso_types, - } - - return { + lang_data = { "iso-639-1": res.part1, "iso-639-2b": res.part2b, "iso-639-2t": res.part2t, @@ -113,11 +80,55 @@ def get_iso_lang_data(lang): "english": res.name, "iso_types": iso_types, } + if res.macro: + return ( + lang_data, + get_iso_lang_data(res.macro)[0], + ) # first item in the returned tuple + return lang_data, None + + def find_native_name(query, lang_data, macro_data): + try: + return babel.Locale.parse(query).get_display_name() + except (babel.UnknownLocaleError, TypeError, ValueError): + logger.debug("Can't find native name from exact query") + code_types = ["iso-639-5", "iso-639-3", "iso-639-2t", "iso-639-2b", "iso-639-1"] + for code_type in code_types: + try: + return babel.Locale.parse(lang_data[code_type]).get_display_name() + except (babel.UnknownLocaleError, TypeError, ValueError): + logger.debug(f"Can't find native name from {code_type} of language") + if macro_data: + logger.debug("Trying the macrolanguage to find native name") + for code_type in code_types: + try: + return babel.Locale.parse(macro_data[code_type]).get_display_name() + except (babel.UnknownLocaleError, TypeError, ValueError): + logger.debug(f"Can't find native name from {code_type} of language") + return lang_data["english"] + else: + return lang_data["english"] + + def combine_lang_and_macro_data(lang_data, macro_data): + if macro_data: + code_types = [ + "iso-639-1", + "iso-639-2b", + "iso-639-2t", + "iso-639-3", + "iso-639-5", + ] + for code_type in code_types: + if not lang_data[code_type]: + lang_data[code_type] = macro_data[code_type] + return lang_data if query.isalpha() and (2 <= len(query) <= 3): # possibility of iso-639 code try: - iso_data = get_iso_lang_data(query) + lang_data, macro_data = get_iso_lang_data(query) + iso_data = combine_lang_and_macro_data(lang_data, macro_data) + iso_data["native"] = find_native_name(query, lang_data, macro_data) iso_data["querytype"] = "purecode" except Exception as exc: logger.error(str(exc)) @@ -129,7 +140,11 @@ def get_iso_lang_data(lang): # possibility of locale query_parts = re.split("-|_", query) try: - iso_data = get_iso_lang_data(query_parts[0]) + lang_data, macro_data = get_iso_lang_data(query_parts[0]) + iso_data = combine_lang_and_macro_data(lang_data, macro_data) + iso_data["native"] = find_native_name( + query.replace("-", "_"), lang_data, macro_data + ) iso_data["querytype"] = "locale" except Exception as exc: logger.error(str(exc)) @@ -138,9 +153,11 @@ def get_iso_lang_data(lang): else: # possibility of iso language name try: - iso_data = get_iso_lang_data( + lang_data, macro_data = get_iso_lang_data( query.title().replace("Languages", "languages") ) + iso_data = combine_lang_and_macro_data(lang_data, macro_data) + iso_data["native"] = find_native_name(query, lang_data, macro_data) iso_data["querytype"] = "languagename" except Exception as exc: logger.error(str(exc)) diff --git a/tests/i18n/test_i18n.py b/tests/i18n/test_i18n.py index bc880272..4f6ad527 100644 --- a/tests/i18n/test_i18n.py +++ b/tests/i18n/test_i18n.py @@ -38,6 +38,7 @@ def test_selocale_unsupported(tmp_path): "iso_types": ["part1"], "querytype": "locale", "query": "zh-Hans", + "native": "中文 (简体)", }, ), ( @@ -52,6 +53,7 @@ def test_selocale_unsupported(tmp_path): "iso_types": ["part1"], "querytype": "purecode", "query": "hi", + "native": "हिन्दी", }, ), ( @@ -66,6 +68,7 @@ def test_selocale_unsupported(tmp_path): "iso_types": ["part2b", "part2t", "part3"], "querytype": "purecode", "query": "hin", + "native": "हिन्दी (भारत)", }, ), ( @@ -80,6 +83,7 @@ def test_selocale_unsupported(tmp_path): "iso_types": ["name"], "querytype": "languagename", "query": "Japanese", + "native": "日本語 (日本)", }, ), ( @@ -94,6 +98,7 @@ def test_selocale_unsupported(tmp_path): "iso_types": ["part2b", "part2t", "part5"], "querytype": "purecode", "query": "afa", + "native": "Afro-Asiatic languages", }, ), ( @@ -108,6 +113,7 @@ def test_selocale_unsupported(tmp_path): "iso_types": ["name"], "querytype": "languagename", "query": "afro-asiatic languages", + "native": "Afro-Asiatic languages", }, ), ( @@ -122,12 +128,43 @@ def test_selocale_unsupported(tmp_path): "iso_types": ["part3"], "querytype": "purecode", "query": "cmn", + "native": "中文 (简体, 中国)", }, ), ("fake-lang", None,), ("fake", None,), ("C#", None,), ("fks", None,), + ( + "arq", + { + "iso-639-1": "ar", + "iso-639-2b": "ara", + "iso-639-2t": "ara", + "iso-639-3": "arq", + "iso-639-5": "", + "english": "Algerian Arabic", + "iso_types": ["part3"], + "native": "العربية (مصر)", + "querytype": "purecode", + "query": "arq", + }, + ), + ( + "ar-ma", + { + "iso-639-1": "ar", + "iso-639-2b": "ara", + "iso-639-2t": "ara", + "iso-639-3": "ara", + "iso-639-5": "", + "english": "Arabic", + "iso_types": ["part1"], + "native": "العربية (المغرب)", + "querytype": "locale", + "query": "ar-ma", + }, + ), ], ) def test_lang_details(query, expected): From 609a4e906e073c195fc852d183a4ce0e7ee72fda Mon Sep 17 00:00:00 2001 From: Satyam Kumar Date: Wed, 20 May 2020 20:11:30 +0530 Subject: [PATCH 4/7] Address #18 - Fix code for coverage --- src/zimscraperlib/i18n.py | 32 ++++++++++++++++++-------------- 1 file changed, 18 insertions(+), 14 deletions(-) diff --git a/src/zimscraperlib/i18n.py b/src/zimscraperlib/i18n.py index 05d4cf0b..04aedc10 100644 --- a/src/zimscraperlib/i18n.py +++ b/src/zimscraperlib/i18n.py @@ -105,9 +105,7 @@ def find_native_name(query, lang_data, macro_data): return babel.Locale.parse(macro_data[code_type]).get_display_name() except (babel.UnknownLocaleError, TypeError, ValueError): logger.debug(f"Can't find native name from {code_type} of language") - return lang_data["english"] - else: - return lang_data["english"] + return lang_data["english"] def combine_lang_and_macro_data(lang_data, macro_data): if macro_data: @@ -127,9 +125,11 @@ def combine_lang_and_macro_data(lang_data, macro_data): # possibility of iso-639 code try: lang_data, macro_data = get_iso_lang_data(query) - iso_data = combine_lang_and_macro_data(lang_data, macro_data) - iso_data["native"] = find_native_name(query, lang_data, macro_data) - iso_data["querytype"] = "purecode" + iso_data = { + "native": find_native_name(query, lang_data, macro_data), + "querytype": "purecode", + } + iso_data.update(combine_lang_and_macro_data(lang_data, macro_data)) except Exception as exc: logger.error(str(exc)) return None @@ -141,11 +141,13 @@ def combine_lang_and_macro_data(lang_data, macro_data): query_parts = re.split("-|_", query) try: lang_data, macro_data = get_iso_lang_data(query_parts[0]) - iso_data = combine_lang_and_macro_data(lang_data, macro_data) - iso_data["native"] = find_native_name( - query.replace("-", "_"), lang_data, macro_data - ) - iso_data["querytype"] = "locale" + iso_data = { + "native": find_native_name( + query.replace("-", "_"), lang_data, macro_data + ), + "querytype": "locale", + } + iso_data.update(combine_lang_and_macro_data(lang_data, macro_data)) except Exception as exc: logger.error(str(exc)) return None @@ -156,9 +158,11 @@ def combine_lang_and_macro_data(lang_data, macro_data): lang_data, macro_data = get_iso_lang_data( query.title().replace("Languages", "languages") ) - iso_data = combine_lang_and_macro_data(lang_data, macro_data) - iso_data["native"] = find_native_name(query, lang_data, macro_data) - iso_data["querytype"] = "languagename" + iso_data = { + "native": find_native_name(query, lang_data, macro_data), + "querytype": "languagename", + } + iso_data.update(combine_lang_and_macro_data(lang_data, macro_data)) except Exception as exc: logger.error(str(exc)) return None From 9212328f6f11e8c7e559368f7c943103821eba48 Mon Sep 17 00:00:00 2001 From: renaud gaudin Date: Thu, 21 May 2020 15:57:44 +0000 Subject: [PATCH 5/7] refactored i18n get_language_details - fixed imports ordering - changed iso639's import local name to avoid confusion - added a global `ISO_LEVELS` var to avoid duplicating `part` and `iso-639-` strings - added custom NotFound exception - exposed all sub-functions of get_language_details - fixed docstrings - refactored to simplify code: - find_native now uses only query and optionnaly lang_data - combine_lang_and_macro_data was renamed and simplifieg (using inspection) - get_iso_lang_data was simplified using ISO_LEVELS - get_language_details was refactored to share what can be between conditions - added `failsafe` param to get_language_details --- src/zimscraperlib/i18n.py | 203 +++++++++++++++++++------------------- tests/i18n/test_i18n.py | 9 +- 2 files changed, 107 insertions(+), 105 deletions(-) diff --git a/src/zimscraperlib/i18n.py b/src/zimscraperlib/i18n.py index 04aedc10..f46df592 100644 --- a/src/zimscraperlib/i18n.py +++ b/src/zimscraperlib/i18n.py @@ -2,13 +2,18 @@ # -*- coding: utf-8 -*- # vim: ai ts=4 sts=4 et sw=4 nu +import re import locale import gettext -import re + import babel +from iso639 import languages as iso639_languages + +ISO_LEVELS = ["1", "2b", "2t", "3", "5"] -from iso639 import languages -from . import logger + +class NotFound(ValueError): + pass class Locale: @@ -51,121 +56,113 @@ def setlocale(root_dir, locale_name): return Locale.setup(root_dir / "locale", locale_name) -def get_language_details(query): - """ returns language details if query is a language or a locale otherwise returns None """ +def get_iso_lang_data(lang): + """ ISO-639-x languages details for lang. Raises NotFound + + Included keys: iso-639-1, iso-639-2b, iso-639-2t, iso-639-3, iso-639-5 + english, iso_types - def get_iso_lang_data(lang): - """ return details if lang is a valid iso language else raises exception """ + See get_language_details() for details """ - code_types = ["part1", "part2b", "part2t", "part3", "part5", "name"] - iso_types = [] + iso_types = [] - for code_type in code_types: - try: - languages.get(**{code_type: lang}) - iso_types.append(code_type) - except KeyError: - logger.debug(f"Not a valid {code_type}") + for code_type in [f"part{l}" for l in ISO_LEVELS] + ["name"]: + try: + iso639_languages.get(**{code_type: lang}) + iso_types.append(code_type) + except KeyError: + pass - if not iso_types: - raise Exception("Not a valid iso language name/code") + if not iso_types: + raise NotFound("Not a valid iso language name/code") - res = languages.get(**{iso_types[0]: lang}) - lang_data = { - "iso-639-1": res.part1, - "iso-639-2b": res.part2b, - "iso-639-2t": res.part2t, - "iso-639-3": res.part3, - "iso-639-5": res.part5, - "english": res.name, - "iso_types": iso_types, - } - if res.macro: - return ( - lang_data, - get_iso_lang_data(res.macro)[0], - ) # first item in the returned tuple - return lang_data, None - - def find_native_name(query, lang_data, macro_data): + language = iso639_languages.get(**{iso_types[0]: lang}) + + lang_data = {f"iso-639-{l}": getattr(language, f"part{l}") for l in ISO_LEVELS} + lang_data.update({"english": language.name, "iso_types": iso_types}) + + if language.macro: + return ( + lang_data, + get_iso_lang_data(language.macro)[0], + ) # first item in the returned tuple + return lang_data, None + + +def find_native_name(query, lang_data={}): + """ native-language name for lang in query with help from language_details dict + + Falls back to English name if available or query if not """ + try: + return babel.Locale.parse(query).get_display_name() + except (babel.UnknownLocaleError, TypeError, ValueError): + pass + + # ISO code lookup order matters (most qualified first)! + for iso_level in [f"iso-639-{l}" for l in reversed(ISO_LEVELS)]: try: - return babel.Locale.parse(query).get_display_name() + return babel.Locale.parse(lang_data.get(iso_level)).get_display_name() except (babel.UnknownLocaleError, TypeError, ValueError): - logger.debug("Can't find native name from exact query") - code_types = ["iso-639-5", "iso-639-3", "iso-639-2t", "iso-639-2b", "iso-639-1"] - for code_type in code_types: - try: - return babel.Locale.parse(lang_data[code_type]).get_display_name() - except (babel.UnknownLocaleError, TypeError, ValueError): - logger.debug(f"Can't find native name from {code_type} of language") - if macro_data: - logger.debug("Trying the macrolanguage to find native name") - for code_type in code_types: - try: - return babel.Locale.parse(macro_data[code_type]).get_display_name() - except (babel.UnknownLocaleError, TypeError, ValueError): - logger.debug(f"Can't find native name from {code_type} of language") - return lang_data["english"] - - def combine_lang_and_macro_data(lang_data, macro_data): - if macro_data: - code_types = [ - "iso-639-1", - "iso-639-2b", - "iso-639-2t", - "iso-639-3", - "iso-639-5", - ] - for code_type in code_types: - if not lang_data[code_type]: - lang_data[code_type] = macro_data[code_type] - return lang_data + pass + return lang_data.get("english", query) + + +def update_with_macro(lang_data, macro_data): + """ update empty keys from lang_data with ones of macro_data """ + if macro_data: + for key, value in macro_data.items(): + if key in lang_data and not lang_data[key]: + lang_data[key] = value + return lang_data + + +def get_language_details(query, failsafe=False): + """ language details dict from query. + + Raises NotFound or return `und` language details if failsafe + + iso-639-1: str ISO-639-1 language code + iso-639-2b: str ISO-639-2b language code + iso-639-2t: str ISO-639-2t language code + iso-639-3: str ISO-639-3 language code + iso-639-5: str ISO-639-5 language code + english: str language name in English + native: str language name in is native language + iso_types: [str] list of supported iso types + + """ if query.isalpha() and (2 <= len(query) <= 3): # possibility of iso-639 code - try: - lang_data, macro_data = get_iso_lang_data(query) - iso_data = { - "native": find_native_name(query, lang_data, macro_data), - "querytype": "purecode", - } - iso_data.update(combine_lang_and_macro_data(lang_data, macro_data)) - except Exception as exc: - logger.error(str(exc)) - return None - + adjusted_query = query + native_query = query + query_type = "purecode" elif all(x.isalpha() or x == "-" or x == "_" for x in query) and ( query.count("_") + query.count("-") == 1 ): # possibility of locale - query_parts = re.split("-|_", query) - try: - lang_data, macro_data = get_iso_lang_data(query_parts[0]) - iso_data = { - "native": find_native_name( - query.replace("-", "_"), lang_data, macro_data - ), - "querytype": "locale", - } - iso_data.update(combine_lang_and_macro_data(lang_data, macro_data)) - except Exception as exc: - logger.error(str(exc)) - return None - + adjusted_query = re.split("-|_", query)[0] + native_query = query.replace("-", "_") + query_type = "locale" else: # possibility of iso language name - try: - lang_data, macro_data = get_iso_lang_data( - query.title().replace("Languages", "languages") - ) - iso_data = { - "native": find_native_name(query, lang_data, macro_data), - "querytype": "languagename", - } - iso_data.update(combine_lang_and_macro_data(lang_data, macro_data)) - except Exception as exc: - logger.error(str(exc)) + adjusted_query = query.title().replace("Languages", "languages") + native_query = query + query_type = "languagename" + + try: + lang_data, macro_data = get_iso_lang_data(adjusted_query) + except NotFound as exc: + if failsafe: return None - - iso_data["query"] = query + raise exc + + iso_data = update_with_macro(lang_data, macro_data) + iso_data.update( + { + "native": find_native_name(native_query, iso_data), + "querytype": query_type, + "query": query, + } + ) return iso_data diff --git a/tests/i18n/test_i18n.py b/tests/i18n/test_i18n.py index 4f6ad527..12265ec2 100644 --- a/tests/i18n/test_i18n.py +++ b/tests/i18n/test_i18n.py @@ -7,7 +7,7 @@ import pytest -from zimscraperlib.i18n import setlocale, get_language_details, _ +from zimscraperlib.i18n import setlocale, get_language_details, _, NotFound @pytest.mark.parametrize( @@ -168,7 +168,12 @@ def test_selocale_unsupported(tmp_path): ], ) def test_lang_details(query, expected): - assert get_language_details(query) == expected + if expected is None: + assert get_language_details(query, failsafe=True) == expected + with pytest.raises(NotFound): + get_language_details(query) + else: + assert get_language_details(query) == expected @pytest.mark.parametrize( From 99a81e75699a8749d68b56b10daa1fbaa65e4bf6 Mon Sep 17 00:00:00 2001 From: renaud gaudin Date: Thu, 21 May 2020 16:11:40 +0000 Subject: [PATCH 6/7] removing unused import --- src/zimscraperlib/zim.py | 1 - 1 file changed, 1 deletion(-) diff --git a/src/zimscraperlib/zim.py b/src/zimscraperlib/zim.py index be5fe3e6..5395b091 100644 --- a/src/zimscraperlib/zim.py +++ b/src/zimscraperlib/zim.py @@ -5,7 +5,6 @@ """ zimwriterfs abstraction via ZimInfo """ -import os import subprocess from . import logger From c23c714f324c8a33e31970f2331708b58d83e757 Mon Sep 17 00:00:00 2001 From: renaud gaudin Date: Thu, 21 May 2020 16:12:14 +0000 Subject: [PATCH 7/7] using english names from babel babel's english names seems of better quality than those of iso639 use babel's version whenever it's present updated tests according to new (babel's) expected values --- src/zimscraperlib/i18n.py | 17 +++++++++++------ tests/i18n/test_i18n.py | 12 ++++++------ 2 files changed, 17 insertions(+), 12 deletions(-) diff --git a/src/zimscraperlib/i18n.py b/src/zimscraperlib/i18n.py index f46df592..20359448 100644 --- a/src/zimscraperlib/i18n.py +++ b/src/zimscraperlib/i18n.py @@ -89,22 +89,25 @@ def get_iso_lang_data(lang): return lang_data, None -def find_native_name(query, lang_data={}): - """ native-language name for lang in query with help from language_details dict +def find_language_names(query, lang_data={}): + """ (native, english) language names for lang with help from language_details dict Falls back to English name if available or query if not """ try: - return babel.Locale.parse(query).get_display_name() + query_locale = babel.Locale.parse(query) + return query_locale.get_display_name(), query_locale.get_display_name("en") except (babel.UnknownLocaleError, TypeError, ValueError): pass # ISO code lookup order matters (most qualified first)! for iso_level in [f"iso-639-{l}" for l in reversed(ISO_LEVELS)]: try: - return babel.Locale.parse(lang_data.get(iso_level)).get_display_name() + query_locale = babel.Locale.parse(lang_data.get(iso_level)) + return query_locale.get_display_name(), query_locale.get_display_name("en") except (babel.UnknownLocaleError, TypeError, ValueError): pass - return lang_data.get("english", query) + default = lang_data.get("english", query) + return default, default def update_with_macro(lang_data, macro_data): @@ -158,9 +161,11 @@ def get_language_details(query, failsafe=False): raise exc iso_data = update_with_macro(lang_data, macro_data) + native_name, english_name = find_language_names(native_query, iso_data) iso_data.update( { - "native": find_native_name(native_query, iso_data), + "english": english_name, + "native": native_name, "querytype": query_type, "query": query, } diff --git a/tests/i18n/test_i18n.py b/tests/i18n/test_i18n.py index 12265ec2..011d2801 100644 --- a/tests/i18n/test_i18n.py +++ b/tests/i18n/test_i18n.py @@ -34,7 +34,7 @@ def test_selocale_unsupported(tmp_path): "iso-639-2t": "zho", "iso-639-3": "zho", "iso-639-5": "", - "english": "Chinese", + "english": "Chinese (Simplified)", "iso_types": ["part1"], "querytype": "locale", "query": "zh-Hans", @@ -64,7 +64,7 @@ def test_selocale_unsupported(tmp_path): "iso-639-2t": "hin", "iso-639-3": "hin", "iso-639-5": "", - "english": "Hindi", + "english": "Hindi (India)", "iso_types": ["part2b", "part2t", "part3"], "querytype": "purecode", "query": "hin", @@ -79,7 +79,7 @@ def test_selocale_unsupported(tmp_path): "iso-639-2t": "jpn", "iso-639-3": "jpn", "iso-639-5": "", - "english": "Japanese", + "english": "Japanese (Japan)", "iso_types": ["name"], "querytype": "languagename", "query": "Japanese", @@ -124,7 +124,7 @@ def test_selocale_unsupported(tmp_path): "iso-639-2t": "zho", "iso-639-3": "cmn", "iso-639-5": "", - "english": "Mandarin Chinese", + "english": "Chinese (Simplified, China)", "iso_types": ["part3"], "querytype": "purecode", "query": "cmn", @@ -143,7 +143,7 @@ def test_selocale_unsupported(tmp_path): "iso-639-2t": "ara", "iso-639-3": "arq", "iso-639-5": "", - "english": "Algerian Arabic", + "english": "Arabic (Egypt)", "iso_types": ["part3"], "native": "العربية (مصر)", "querytype": "purecode", @@ -158,7 +158,7 @@ def test_selocale_unsupported(tmp_path): "iso-639-2t": "ara", "iso-639-3": "ara", "iso-639-5": "", - "english": "Arabic", + "english": "Arabic (Morocco)", "iso_types": ["part1"], "native": "العربية (المغرب)", "querytype": "locale",