|
8 | 8 | from typing import Dict, Optional, Tuple, Union
|
9 | 9 |
|
10 | 10 | import babel
|
11 |
| -from iso639 import languages as iso639_languages |
| 11 | +import iso639 |
| 12 | +import iso639.exceptions |
12 | 13 |
|
13 | 14 | ISO_LEVELS = ["1", "2b", "2t", "3", "5"]
|
14 | 15 |
|
@@ -67,27 +68,42 @@ def get_iso_lang_data(lang: str) -> Tuple[Dict, Union[Dict, None]]:
|
67 | 68 |
|
68 | 69 | iso_types = []
|
69 | 70 |
|
70 |
| - for code_type in [f"part{lang_}" for lang_ in ISO_LEVELS] + ["name"]: |
71 |
| - try: |
72 |
| - iso639_languages.get(**{code_type: lang}) |
73 |
| - iso_types.append(code_type) |
74 |
| - except KeyError: |
75 |
| - pass |
76 |
| - |
77 |
| - if not iso_types: |
78 |
| - raise NotFound("Not a valid iso language name/code") |
79 |
| - |
80 |
| - language = iso639_languages.get(**{iso_types[0]: lang}) |
| 71 | + try: |
| 72 | + isolang = iso639.Lang(lang) |
| 73 | + except iso639.exceptions.InvalidLanguageValue as exc: |
| 74 | + raise NotFound("Not a valid iso language name/code") from exc |
| 75 | + |
| 76 | + def replace_types(new_type: str) -> str: |
| 77 | + # convert new iso_types from iso639-lang Pypi package to old iso_types from |
| 78 | + # iso-639 package, since we were returning these values for a long time |
| 79 | + if new_type == "pt1": |
| 80 | + return "part1" |
| 81 | + elif new_type == "pt2b": |
| 82 | + return "part2b" |
| 83 | + elif new_type == "pt2t": |
| 84 | + return "part2t" |
| 85 | + elif new_type == "pt3": |
| 86 | + return "part3" |
| 87 | + elif new_type == "pt5": |
| 88 | + return "part5" |
| 89 | + return new_type |
| 90 | + |
| 91 | + for code_type in [f"pt{lang_}" for lang_ in ISO_LEVELS] + ["name"]: |
| 92 | + # the `if` condition below is a bit hackish but it is the only way to know |
| 93 | + # if the passed value is matching a code type or not with new python-i639 |
| 94 | + # library and we do not expect weird things to happen here |
| 95 | + if str(getattr(isolang, code_type)).lower() == lang.lower(): |
| 96 | + iso_types.append(replace_types(code_type)) |
81 | 97 |
|
82 | 98 | lang_data = {
|
83 |
| - f"iso-639-{lang_}": getattr(language, f"part{lang_}") for lang_ in ISO_LEVELS |
| 99 | + f"iso-639-{lang_}": getattr(isolang, f"pt{lang_}") for lang_ in ISO_LEVELS |
84 | 100 | }
|
85 |
| - lang_data.update({"english": language.name, "iso_types": iso_types}) |
| 101 | + lang_data.update({"english": isolang.name, "iso_types": iso_types}) |
86 | 102 |
|
87 |
| - if language.macro: |
| 103 | + if isolang.macro(): |
88 | 104 | return (
|
89 | 105 | lang_data,
|
90 |
| - get_iso_lang_data(language.macro)[0], |
| 106 | + get_iso_lang_data(isolang.macro().name)[0], |
91 | 107 | ) # first item in the returned tuple
|
92 | 108 | return lang_data, None
|
93 | 109 |
|
|
0 commit comments