Debian Codegraph @

tests/test_data_languages.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 #
3 # Copyright 2022 Google LLC All Rights Reserved.
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS-IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16 #
17 from collections import defaultdict, Counter
18 import regex
19 import unicodedata
20
21 from gflanguages import (
22 LoadLanguages,
23 languages_public_pb2,
24 LoadScripts,
25 LoadRegions,
26 parse,
27 )
28 import pytest
29 import youseedee
30
31
32 LANGUAGES = LoadLanguages()
33 SCRIPTS = LoadScripts()
34 REGIONS = LoadRegions()
35
36 CLDR_SCRIPT_TO_UCD_SCRIPT = {
37 "Bangla": "Bengali",
38 "Traditional Han": "Han",
39 "Simplified Han": "Han",
40 "Korean": "Hangul",
41 "Odia": "Oriya",
42 "Makasar": "Buginese",
43 "Lanna": "Tai Tham",
44 "Unified Canadian Aboriginal Syllabics": "Canadian Aboriginal",
45 "S-A Cuneiform": "Cuneiform",
46 "Pollard Phonetic": "Miao",
47 "Egyptian hieroglyphs": "Egyptian Hieroglyphs",
48 "Zanabazar": "Zanabazar Square",
49 "Nüshu": "Nushu",
50 "Mandaean": "Mandaic",
51 "N’Ko": "Nko",
52 "Varang Kshiti": "Warang Citi",
53 "Mende": "Mende Kikakui",
54 "Phags-pa": "Phags Pa",
55 "Fraser": "Lisu",
56 "Georgian Khutsuri": "Georgian",
57 "Orkhon": "Old Turkic",
58 }
59
60 SKIP_EXEMPLARS = {
61 "ja_Jpan": "Contains multiple scripts",
62 "aii_Cyrl": "Does indeed use Latin glyphs while writing Cyrillic",
63 "sel_Cyrl": "Does indeed use Latin glyphs while writing Cyrillic",
64 "ykg_Cyrl": "Does indeed use Latin glyphs (w) while writing Cyrillic",
65 "ady_Cyrl": "Does indeed use Latin glyphs (w) while writing Cyrillic",
66 "sla_Latn": "Does indeed use Cyrillic glyphs (ь) when written in Latin",
67 "coo_Latn": "Does indeed use Greek glyphs while writing Latin",
68 "hur_Latn": "Does indeed use Greek glyphs while writing Latin",
69 "kwk_Latn": "Does indeed use Greek glyphs while writing Latin",
70 "thp_Latn": "Does indeed use Greek glyphs while writing Latin",
71 "dnj_Latn": "Does use future Unicode 16 Latin glyphs",
72 "gov_Latn": "Does use future Unicode 16 Latin glyphs",
73 }
74
75 SKIP_REGION = {
76 "cpf_Latn": "French-based creole languages is a group of languages.",
77 "gem_Latn": "Germanic languages is a group of languages.",
78 "sla_Latn": "Slavic languages is a group of languages.",
79 "hmn_Latn": "Homnic languages is a group of languages.",
80 "ie_Latn": "Interlingue is an artifical language.",
81 "io_Latn": "Ido is an artifical language.",
82 "jbo_Latn": "Lobjan is an artifical language.",
83 "tlh_Latn": "Klingon is an artifical language.",
84 }
85
86 LANGUAGE_NAME_REGEX = regex.compile(
87 r"^[-'’ʼ\p{L} ]+(, [-'’ʼ\p{L}/ ]+)?( [(][-'’ʼ\p{L} ]+[)])?$"
88 )
89 # Some scripts have abbreviated names for reference in language names that are
90 # sufficient in context. If an alternate is listed here, it should be used
91 # universally and consistently across all language names.
92 ALTERNATE_SCRIPT_NAMES = {
93 "Dupl": "Duployan",
94 "Hans": "Simplified",
95 "Hant": "Traditional",
96 }
97
98
99 @pytest.mark.parametrize("lang_code", LANGUAGES)
100 @pytest.mark.parametrize(
101 "exemplar_name", ["base", "auxiliary", "marks", "numerals", "punctuation", "index"]
102 )
103 def test_languages_exemplars_canonical_duplicates(lang_code, exemplar_name):
104 lang = LANGUAGES[lang_code]
105 exemplar = getattr(lang.exemplar_chars, exemplar_name).split()
106 normalized = defaultdict(set)
107
108 for g in exemplar:
109 if g[0] == "{" and g[-1] == "}":
110 g = g.lstrip("{").rstrip("}")
111 normalized[unicodedata.normalize("NFC", g)].add(g)
112
113 result = [(len(gs), n) for n, gs in normalized.items()]
114 expected = [(1, n) for n, _ in normalized.items()]
115 assert result == expected
116
117
118 @pytest.mark.parametrize("lang_code", LANGUAGES)
119 @pytest.mark.parametrize(
120 "exemplar_name", ["base", "auxiliary", "marks", "numerals", "punctuation", "index"]
121 )
122 def test_languages_exemplars_duplicates(lang_code, exemplar_name):
123 lang = LANGUAGES[lang_code]
124 exemplar = getattr(lang.exemplar_chars, exemplar_name).split()
125 counter = Counter(exemplar)
126 counts = sorted(counter.most_common(), key=lambda pair: exemplar.index(pair[0]))
127 assert counts == [(v, 1) for v in exemplar]
128
129
130 @pytest.mark.parametrize("lang_code", LANGUAGES.keys())
131 @pytest.mark.parametrize(
132 "exemplar_name", ["base", "auxiliary", "numerals", "punctuation", "index"]
133 )
134 def test_exemplars_bracketed_sequences(lang_code, exemplar_name):
135 lang = LANGUAGES[lang_code]
136 if lang.script != "Latn":
137 return
138 exemplar = getattr(lang.exemplar_chars, exemplar_name).split()
139 for chars in exemplar:
140 if len(chars) > 1:
141 assert chars.startswith("{") and chars.endswith("}")
142 assert len(chars[1:-1]) > 1
143
144
145 @pytest.mark.parametrize("lang_code", LANGUAGES)
146 def test_languages_exemplars_marks_in_base(lang_code):
147 lang = LANGUAGES[lang_code]
148 bases = lang.exemplar_chars.base
149 problems = []
150 for chars in bases.split():
151 if len(chars) > 1:
152 chars = chars.lstrip("{").rstrip("}")
153 if unicodedata.category(chars[0]) == "Mn":
154 problems.append("\u25CC" + chars)
155 if "\u25CC" in chars:
156 problems.append(chars)
157 assert not problems, f"Found marks in base: {problems}"
158
159
160 SampleText = languages_public_pb2.SampleTextProto().DESCRIPTOR
161 ExemplarChars = languages_public_pb2.ExemplarCharsProto().DESCRIPTOR
162
163
164 @pytest.mark.parametrize("lang_code", LANGUAGES.keys())
165 def test_language_samples(lang_code):
166 # Although marked as optional in the protobuf file, all
167 # SampleText fields (except note) are required, so make
168 # sure they are present.
169 lang = LANGUAGES[lang_code]
170 if not lang.sample_text.ListFields():
171 pytest.skip("No sample text for language " + lang_code)
172 return
173
174 for field in SampleText.fields:
175 if field.name == "note":
176 continue
177 assert getattr(lang.sample_text, field.name)
178
179
180 @pytest.mark.parametrize("lang_code", LANGUAGES.keys())
181 def test_script_is_known(lang_code):
182 lang = LANGUAGES[lang_code]
183 script = lang.script
184 assert script in SCRIPTS, f"{lang_code} used unknown script {lang.script}"
185
186
187 @pytest.mark.parametrize("lang_code", LANGUAGES)
188 def test_region_is_known(lang_code):
189 lang = LANGUAGES[lang_code]
190 if lang.id in SKIP_REGION:
191 pytest.skip(SKIP_REGION[lang.id])
192 return
193 regions = lang.region
194 for region in regions:
195 assert region in REGIONS.keys()
196
197
198 @pytest.mark.parametrize("lang_code", LANGUAGES.keys())
199 def test_exemplars_are_in_script(lang_code):
200 lang = LANGUAGES[lang_code]
201 script_name = SCRIPTS[lang.script].name
202 script_name = CLDR_SCRIPT_TO_UCD_SCRIPT.get(script_name, script_name)
203 if not lang.exemplar_chars.ListFields():
204 pytest.skip("No exemplars for language " + lang_code)
205 return
206 if lang.id in SKIP_EXEMPLARS:
207 pytest.skip(SKIP_EXEMPLARS[lang.id])
208 return
209 out_of_script = {}
210 for field in ExemplarChars.fields:
211 if field.name == "auxiliary" or field.name == "index":
212 continue
213 exemplars = getattr(lang.exemplar_chars, field.name)
214 group_of_chars = regex.findall(r"(\{[^}]+\}|\S+)", exemplars)
215 for chars in group_of_chars:
216 for char in chars:
217 char_script = youseedee.ucd_data(ord(char)).get("Script")
218 if char_script == "Common" or char_script == "Inherited":
219 continue
220 char_script = char_script.replace("_", " ")
221 if char_script != script_name:
222 out_of_script[chars] = char_script
223 break
224 assert not out_of_script, (
225 f"{lang_code} exemplars contained out-of-script characters"
226 f": {', '.join(out_of_script.keys())}"
227 f" from scripts {', '.join(set(out_of_script.values()))}"
228 )
229
230
231 @pytest.mark.parametrize("lang_code", LANGUAGES.keys())
232 def test_sample_texts_are_in_script(lang_code):
233 if lang_code in [
234 "mak_Maka",
235 "orv_Cyrl",
236 "cu_Cyrl",
237 "ff_Adlm",
238 "idu_Latn",
239 "ban_Bali",
240 ]:
241 pytest.xfail("These languages have known issues with their sample text")
242 return
243 lang = LANGUAGES[lang_code]
244 script_name = SCRIPTS[lang.script].name
245 script_name = CLDR_SCRIPT_TO_UCD_SCRIPT.get(script_name, script_name)
246 if not lang.sample_text.ListFields():
247 pytest.skip("No sample text for language " + lang_code)
248 return
249 if lang.id in SKIP_EXEMPLARS:
250 pytest.skip(SKIP_EXEMPLARS[lang.id])
251 return
252 out_of_script = defaultdict(set)
253 for field in SampleText.fields:
254 if field.name == "note":
255 continue
256 samples = getattr(lang.sample_text, field.name)
257 chars = set(samples)
258 for char in chars:
259 char_script = (
260 youseedee.ucd_data(ord(char)).get("Script", "").replace("_", " ")
261 )
262 if char_script == "Common" or char_script == "Inherited":
263 continue
264 if char_script != script_name:
265 extensions = (
266 youseedee.ucd_data(ord(char))
267 .get("Script_Extensions", "")
268 .split(" ")
269 )
270 if any(ext == lang.script for ext in extensions):
271 continue
272 out_of_script[char_script].add(char)
273 break
274 msg = []
275 for script, chars in out_of_script.items():
276 msg.append(f"'{''.join(chars)}' ({script} != {script_name})")
277 assert not out_of_script, (
278 f"{lang_code} sample text contained out-of-script characters"
279 f": {', '.join(msg)}"
280 )
281
282
283 def test_exemplar_parser():
284 bases = "a A ā Ā {a̍} {A̍} {kl}"
285 parsed_bases = parse(bases)
286 assert parsed_bases == {
287 "a",
288 "A",
289 "ā",
290 "Ā",
291 "k",
292 "l",
293 "̍",
294 }
295
296
297 def test_language_uniqueness():
298 names = Counter([])
299 for lang in LANGUAGES.values():
300 if lang.preferred_name:
301 names[lang.preferred_name] += 1
302 else:
303 names[lang.name] += 1
304 if any(count > 1 for count in names.values()):
305 duplicates = {name: count for name, count in names.items() if count > 1}
306 pytest.fail(f"Duplicate language names: {duplicates}")
307
308
309 def test_language_name_structure():
310 languages_with_bad_name_structure = {}
311 for lang in LANGUAGES.values():
312 script_name = (
313 SCRIPTS[lang.script].name
314 if lang.script not in ALTERNATE_SCRIPT_NAMES
315 else ALTERNATE_SCRIPT_NAMES[lang.script]
316 )
317 names = [["name", lang.name]]
318 if lang.preferred_name:
319 names += [["preferred_name", lang.preferred_name]]
320 bad_names = []
321 for type, name in names:
322 bad_structure = not regex.match(LANGUAGE_NAME_REGEX, name)
323 bad_script_suffix = name.endswith(")") and not name.endswith(
324 f"({script_name})"
325 )
326 if bad_structure or bad_script_suffix:
327 bad_names.append(type)
328 if len(bad_names) > 0:
329 languages_with_bad_name_structure[lang.id] = bad_names
330 if len(languages_with_bad_name_structure) > 0:
331 misstructured_language_names = [
332 f"{language_id}" if len(types) == 1 else f"{language_id}: {types}"
333 for language_id, types in languages_with_bad_name_structure.items()
334 if len(types) > 0
335 ]
336 pytest.fail(
337 f'Languages names without expected structure ("LANGUAGE, MODIFIER (SCRIPT)"): {misstructured_language_names}'
338 )
339
340
341 @pytest.mark.parametrize("lang_code", LANGUAGES)
342 def test_id_well_formed(lang_code):
343 if lang_code in ["tw_akuapem_Latn"]:
344 pytest.xfail("Well we need to have a conversation about that")
345 return
346 lang = LANGUAGES[lang_code]
347 assert lang.id.startswith(lang.language + "_" + lang.script)