Debian Codegraph @

scripts/import_cldr.py

raw
1 #!/usr/bin/env python
2 #
3 # Copyright (C) 2007-2011 Edgewall Software, 2013-2025 the Babel team
4 # All rights reserved.
5 #
6 # This software is licensed as described in the file LICENSE, which
7 # you should have received as part of this distribution. The terms
8 # are also available at https://github.com/python-babel/babel/blob/master/LICENSE.
9 #
10 # This software consists of voluntary contributions made by many
11 # individuals. For the exact contribution history, see the revision
12 # history and logs, available at https://github.com/python-babel/babel/commits/master/.
13
14 import collections
15 import logging
16 import os
17 import pickle
18 import re
19 import sys
20 import warnings
21 from optparse import OptionParser
22 from xml.etree import ElementTree
23
24 # Make sure we're using Babel source, and not some previously installed version
25 CHECKOUT_ROOT = os.path.abspath(os.path.join(
26 os.path.dirname(__file__),
27 '..',
28 ))
29 BABEL_PACKAGE_ROOT = os.path.join(CHECKOUT_ROOT, "babel")
30 sys.path.insert(0, CHECKOUT_ROOT)
31
32 from babel import dates, numbers
33 from babel.dates import split_interval_pattern
34 from babel.localedata import Alias
35 from babel.plural import PluralRule
36
37 parse = ElementTree.parse
38 weekdays = {'mon': 0, 'tue': 1, 'wed': 2, 'thu': 3, 'fri': 4, 'sat': 5,
39 'sun': 6}
40
41
42 def _text(elem):
43 buf = [elem.text or '']
44 for child in elem:
45 buf.append(_text(child))
46 buf.append(elem.tail or '')
47 return ''.join(filter(None, buf)).strip()
48
49
50 NAME_RE = re.compile(r"^\w+$")
51 TYPE_ATTR_RE = re.compile(r"^\w+\[@type='(.*?)'\]$")
52
53 NAME_MAP = {
54 'dateFormats': 'date_formats',
55 'dateTimeFormats': 'datetime_formats',
56 'eraAbbr': 'abbreviated',
57 'eraNames': 'wide',
58 'eraNarrow': 'narrow',
59 'timeFormats': 'time_formats',
60 }
61
62 log = logging.getLogger("import_cldr")
63
64
65 def _translate_alias(ctxt, path):
66 parts = path.split('/')
67 keys = ctxt[:]
68 for part in parts:
69 if part == '..':
70 keys.pop()
71 else:
72 match = TYPE_ATTR_RE.match(part)
73 if match:
74 keys.append(match.group(1))
75 else:
76 assert NAME_RE.match(part)
77 keys.append(NAME_MAP.get(part, part))
78 return keys
79
80
81 def _sibling_alias_type(alias_elem) -> str:
82 """
83 Extract target type from an alias path pointing at a sibling.
84
85 E.g. ``../unit[@type='duration-year']`` -> ``duration-year``.
86 """
87 path_attr = alias_elem.attrib['path']
88 parent, _, leaf = path_attr.rpartition('/')
89 if parent != "..":
90 raise ValueError(f"not a sibling alias: {path_attr}")
91 return TYPE_ATTR_RE.match(leaf).group(1)
92
93
94 def _parse_currency_date(s):
95 if not s:
96 return None
97 parts = s.split('-', 2)
98 return tuple(map(int, parts + [1] * (3 - len(parts))))
99
100
101 def _currency_sort_key(tup):
102 code, start, end, tender = tup
103 return int(not tender), start or (1, 1, 1)
104
105
106 def _extract_plural_rules(file_path):
107 rule_dict = {}
108 prsup = parse(file_path)
109 for elem in prsup.findall('.//plurals/pluralRules'):
110 rules = []
111 for rule in elem.findall('pluralRule'):
112 rules.append((rule.attrib['count'], str(rule.text)))
113 pr = PluralRule(rules)
114 for locale in elem.attrib['locales'].split():
115 rule_dict[locale] = pr
116 return rule_dict
117
118
119 def _time_to_seconds_past_midnight(time_expr):
120 """
121 Parse a time expression to seconds after midnight.
122 :param time_expr: Time expression string (H:M or H:M:S)
123 :rtype: int
124 """
125 if time_expr is None:
126 return None
127 if time_expr.count(":") == 1:
128 time_expr += ":00"
129 hour, minute, second = (int(p, 10) for p in time_expr.split(":"))
130 return hour * 60 * 60 + minute * 60 + second
131
132
133 def _compact_dict(dict):
134 """
135 "Compact" the given dict by removing items whose value is None or False.
136 """
137 out_dict = {}
138 for key, value in dict.items():
139 if value is not None and value is not False:
140 out_dict[key] = value
141 return out_dict
142
143
144 def debug_repr(obj):
145 if isinstance(obj, PluralRule):
146 return obj.abstract
147 return repr(obj)
148
149
150 def write_datafile(path, data, dump_json=False):
151 with open(path, 'wb') as outfile:
152 pickle.dump(data, outfile, 2)
153 if dump_json:
154 import json
155
156 with open(f"{path}.json", "w") as outfile:
157 json.dump(data, outfile, indent=4, default=debug_repr)
158
159
160 def main():
161 parser = OptionParser(usage='%prog path/to/cldr')
162 parser.add_option(
163 '-f', '--force', dest='force', action='store_true', default=False,
164 help='legacy option; conversion is always done',
165 )
166 parser.add_option(
167 '-j', '--json', dest='dump_json', action='store_true', default=False,
168 help='also export debugging JSON dumps of locale data',
169 )
170 parser.add_option(
171 '-q', '--quiet', dest='quiet', action='store_true', default=bool(os.environ.get('BABEL_CLDR_QUIET')),
172 help='quiesce info/warning messages',
173 )
174
175 options, args = parser.parse_args()
176 if len(args) != 1:
177 parser.error('incorrect number of arguments')
178
179 logging.basicConfig(
180 level=(logging.ERROR if options.quiet else logging.INFO),
181 )
182
183 return process_data(
184 srcdir=args[0],
185 destdir=BABEL_PACKAGE_ROOT,
186 dump_json=bool(options.dump_json),
187 )
188
189
190 def process_data(srcdir, destdir, force=True, dump_json=False):
191 if not force:
192 warnings.warn("Setting `force=False` has no effect.", DeprecationWarning, stacklevel=2)
193 sup_filename = os.path.join(srcdir, 'supplemental', 'supplementalData.xml')
194 sup = parse(sup_filename)
195
196 # Import global data from the supplemental files
197 global_path = os.path.join(destdir, 'global.dat')
198 global_data = parse_global(srcdir, sup)
199 write_datafile(global_path, global_data, dump_json=dump_json)
200 _process_local_datas(sup, srcdir, destdir, dump_json=dump_json)
201
202
203 def parse_global(srcdir, sup):
204 global_data = {}
205
206 with open(os.path.join(srcdir, 'dtd', 'ldml.dtd')) as dtd_file:
207 cldr_version_match = re.search(
208 r'<!ATTLIST version cldrVersion CDATA #FIXED "(.+?)"',
209 dtd_file.read(),
210 )
211 if not cldr_version_match:
212 raise ValueError("Could not find CLDR version in DTD file")
213 cldr_version = cldr_version_match.group(1)
214 global_data.setdefault('cldr', {})['version'] = cldr_version
215
216 log.info('Processing CLDR version %s from %s', cldr_version, srcdir)
217
218 sup_dir = os.path.join(srcdir, 'supplemental')
219 territory_zones = global_data.setdefault('territory_zones', {})
220 zone_aliases = global_data.setdefault('zone_aliases', {})
221 zone_territories = global_data.setdefault('zone_territories', {})
222 win_mapping = global_data.setdefault('windows_zone_mapping', {})
223 language_aliases = global_data.setdefault('language_aliases', {})
224 territory_aliases = global_data.setdefault('territory_aliases', {})
225 script_aliases = global_data.setdefault('script_aliases', {})
226 variant_aliases = global_data.setdefault('variant_aliases', {})
227 likely_subtags = global_data.setdefault('likely_subtags', {})
228 territory_currencies = global_data.setdefault('territory_currencies', {})
229 parent_exceptions = global_data.setdefault('parent_exceptions', {})
230 all_currencies = collections.defaultdict(set)
231 currency_fractions = global_data.setdefault('currency_fractions', {})
232 territory_languages = global_data.setdefault('territory_languages', {})
233 bcp47_timezone = parse(os.path.join(srcdir, 'bcp47', 'timezone.xml'))
234 sup_windows_zones = parse(os.path.join(sup_dir, 'windowsZones.xml'))
235 sup_metadata = parse(os.path.join(sup_dir, 'supplementalMetadata.xml'))
236 sup_likely = parse(os.path.join(sup_dir, 'likelySubtags.xml'))
237 # create auxiliary zone->territory map from the windows zones (we don't set
238 # the 'zones_territories' map directly here, because there are some zones
239 # aliases listed and we defer the decision of which ones to choose to the
240 # 'bcp47' data
241 _zone_territory_map = {}
242 for map_zone in sup_windows_zones.findall('.//windowsZones/mapTimezones/mapZone'):
243 if map_zone.attrib.get('territory') == '001':
244 win_mapping[map_zone.attrib['other']] = map_zone.attrib['type'].split()[0]
245 for tzid in str(map_zone.attrib['type']).split():
246 _zone_territory_map[tzid] = str(map_zone.attrib['territory'])
247 for key_elem in bcp47_timezone.findall('.//keyword/key'):
248 if key_elem.attrib['name'] == 'tz':
249 for elem in key_elem.findall('type'):
250 if 'deprecated' in elem.attrib:
251 continue
252 aliases = str(elem.attrib['alias']).split()
253 iana = elem.attrib.get('iana')
254 tzid = iana or aliases[0] # Use the IANA ID if available, otherwise the first alias
255 territory = '001'
256 # The windowsZones map might use an alias to refer to a timezone,
257 # so can't just do a simple dict lookup.
258 for cand in (tzid, *aliases):
259 if cand in _zone_territory_map:
260 territory = _zone_territory_map[cand]
261 break
262 territory_zones.setdefault(territory, []).append(tzid)
263 zone_territories[tzid] = territory
264 for alias in aliases:
265 if alias != tzid:
266 zone_aliases[alias] = tzid
267 break
268
269 # Import Metazone mapping
270 meta_zones = global_data.setdefault('meta_zones', {})
271 tzsup = parse(os.path.join(srcdir, 'supplemental', 'metaZones.xml'))
272 for elem in tzsup.findall('.//timezone'):
273 for child in elem.findall('usesMetazone'):
274 if 'to' not in child.attrib: # FIXME: support old mappings
275 meta_zones[elem.attrib['type']] = child.attrib['mzone']
276
277 # Language aliases
278 for alias in sup_metadata.findall('.//alias/languageAlias'):
279 # We don't have a use for those at the moment. They don't
280 # pass our parser anyways.
281 if '_' in alias.attrib['type']:
282 continue
283 language_aliases[alias.attrib['type']] = alias.attrib['replacement']
284
285 # Territory aliases
286 for alias in sup_metadata.findall('.//alias/territoryAlias'):
287 territory_aliases[alias.attrib['type']] = alias.attrib['replacement'].split()
288
289 # Script aliases
290 for alias in sup_metadata.findall('.//alias/scriptAlias'):
291 script_aliases[alias.attrib['type']] = alias.attrib['replacement']
292
293 # Variant aliases
294 for alias in sup_metadata.findall('.//alias/variantAlias'):
295 repl = alias.attrib.get('replacement')
296 if repl:
297 variant_aliases[alias.attrib['type']] = repl
298
299 # Likely subtags
300 for likely_subtag in sup_likely.findall('.//likelySubtags/likelySubtag'):
301 likely_subtags[likely_subtag.attrib['from']] = likely_subtag.attrib['to']
302
303 # Currencies in territories
304 for region in sup.findall('.//currencyData/region'):
305 region_code = region.attrib['iso3166']
306 region_currencies = []
307 for currency in region.findall('./currency'):
308 cur_code = currency.attrib['iso4217']
309 cur_start = _parse_currency_date(currency.attrib.get('from'))
310 cur_end = _parse_currency_date(currency.attrib.get('to'))
311 cur_tender = currency.attrib.get('tender', 'true') == 'true'
312 # Tie region to currency.
313 region_currencies.append((cur_code, cur_start, cur_end, cur_tender))
314 # Keep a reverse index of currencies to territorie.
315 all_currencies[cur_code].add(region_code)
316 region_currencies.sort(key=_currency_sort_key)
317 territory_currencies[region_code] = region_currencies
318 global_data['all_currencies'] = {
319 currency: tuple(sorted(regions)) for currency, regions in all_currencies.items()}
320
321 # Explicit parent locales
322 # Since CLDR-43, there are multiple <parentLocales> statements, some of them with a `component="collations"` or
323 # `component="segmentations"` attribute; these indicate that only some language aspects should be inherited.
324 # (https://cldr.unicode.org/index/downloads/cldr-43)
325 #
326 # Ignore these for now, as one of them even points to a locale that doesn't have a corresponding XML file (sr_ME)
327 # and we crash trying to load it.
328 # There is no XPath support to test for an absent attribute, so use Python to filter
329 for parentBlock in sup.findall('.//parentLocales'):
330 if parentBlock.attrib.get('component'):
331 # Consider only unqualified parent declarations
332 continue
333
334 for paternity in parentBlock.findall('./parentLocale'):
335 parent = paternity.attrib['parent']
336 if parent == 'root':
337 # Since CLDR-45, the 'root' parent locale uses 'localeRules="nonlikelyScript"' instead of
338 # 'locales'. This special case is handled in babel when loading locale data
339 # (https://cldr.unicode.org/index/downloads/cldr-45#h.5rbkhkncdqi9)
340 continue
341 for child in paternity.attrib['locales'].split():
342 parent_exceptions[child] = parent
343
344 # Currency decimal and rounding digits
345 for fraction in sup.findall('.//currencyData/fractions/info'):
346 cur_code = fraction.attrib['iso4217']
347 cur_digits = int(fraction.attrib['digits'])
348 cur_rounding = int(fraction.attrib['rounding'])
349 cur_cdigits = int(fraction.attrib.get('cashDigits', cur_digits))
350 cur_crounding = int(fraction.attrib.get('cashRounding', cur_rounding))
351 currency_fractions[cur_code] = (cur_digits, cur_rounding, cur_cdigits, cur_crounding)
352
353 # Languages in territories
354 for territory in sup.findall('.//territoryInfo/territory'):
355 languages = {}
356 for language in territory.findall('./languagePopulation'):
357 languages[language.attrib['type']] = {
358 'population_percent': float(language.attrib['populationPercent']),
359 'official_status': language.attrib.get('officialStatus'),
360 }
361 territory_languages[territory.attrib['type']] = languages
362 return global_data
363
364
365 def _process_local_datas(sup, srcdir, destdir, force=True, dump_json=False):
366 if not force:
367 warnings.warn("Setting `force=False` has no effect.", DeprecationWarning, stacklevel=2)
368 day_period_rules = parse_day_period_rules(parse(os.path.join(srcdir, 'supplemental', 'dayPeriods.xml')))
369 # build a territory containment mapping for inheritance
370 regions = {}
371 for elem in sup.findall('.//territoryContainment/group'):
372 regions[elem.attrib['type']] = elem.attrib['contains'].split()
373
374 # Resolve territory containment
375 territory_containment = {}
376 region_items = sorted(regions.items())
377 for group, territory_list in region_items:
378 for territory in territory_list:
379 containers = territory_containment.setdefault(territory, set())
380 if group in territory_containment:
381 containers |= territory_containment[group]
382 containers.add(group)
383
384 # prepare the per-locale plural rules definitions
385 plural_rules = _extract_plural_rules(os.path.join(srcdir, 'supplemental', 'plurals.xml'))
386 ordinal_rules = _extract_plural_rules(os.path.join(srcdir, 'supplemental', 'ordinals.xml'))
387
388 filenames = os.listdir(os.path.join(srcdir, 'main'))
389 filenames.remove('root.xml')
390 filenames.sort(key=len)
391 filenames.insert(0, 'root.xml')
392
393 for filename in filenames:
394 stem, ext = os.path.splitext(filename)
395 if ext != '.xml':
396 continue
397
398 full_filename = os.path.join(srcdir, "main", filename)
399 data_filename = os.path.join(destdir, "locale-data", f"{stem}.dat")
400
401 data = {}
402
403 tree = parse(full_filename)
404
405 language = None
406 elem = tree.find('.//identity/language')
407 if elem is not None:
408 language = elem.attrib['type']
409
410 territory = '001' # world
411 elem = tree.find('.//identity/territory')
412 if elem is not None:
413 territory = elem.attrib['type']
414 regions = territory_containment.get(territory, [])
415
416 log.info(
417 'Processing %s (Language = %s; Territory = %s)',
418 filename, language, territory,
419 )
420
421 locale_id = '_'.join(filter(None, [
422 language,
423 territory != '001' and territory or None,
424 ]))
425
426 data['locale_id'] = locale_id
427 data['unsupported_number_systems'] = set()
428
429 if locale_id in plural_rules:
430 data['plural_form'] = plural_rules[locale_id]
431 if locale_id in ordinal_rules:
432 data['ordinal_form'] = ordinal_rules[locale_id]
433 if locale_id in day_period_rules:
434 data["day_period_rules"] = day_period_rules[locale_id]
435
436 is_global = ("_" not in locale_id)
437 parse_locale_display_names(data, tree, is_global=is_global)
438 parse_list_patterns(data, tree)
439 parse_dates(data, tree, sup, regions, territory)
440
441 for calendar in tree.findall('.//calendars/calendar'):
442 if calendar.attrib['type'] != 'gregorian':
443 # TODO: support other calendar types
444 continue
445
446 parse_calendar_months(data, calendar)
447 parse_calendar_days(data, calendar)
448 parse_calendar_quarters(data, calendar)
449 parse_calendar_eras(data, calendar)
450 parse_calendar_periods(data, calendar)
451 parse_calendar_date_formats(data, calendar)
452 parse_calendar_time_formats(data, calendar)
453 parse_calendar_datetime_skeletons(data, calendar)
454 parse_interval_formats(data, calendar)
455
456 parse_number_symbols(data, tree)
457 parse_numbering_systems(data, tree)
458 parse_decimal_formats(data, tree)
459 parse_scientific_formats(data, tree)
460 parse_percent_formats(data, tree)
461
462 parse_currency_formats(data, tree)
463 parse_currency_unit_patterns(data, tree)
464 parse_currency_names(data, tree)
465 parse_unit_patterns(data, tree)
466 parse_date_fields(data, tree)
467 parse_character_order(data, tree)
468 parse_measurement_systems(data, tree)
469
470 unsupported_number_systems_string = ', '.join(sorted(data.pop('unsupported_number_systems')))
471 if unsupported_number_systems_string:
472 log.warning(
473 f"{locale_id}: unsupported number systems were ignored: "
474 f"{unsupported_number_systems_string}",
475 )
476
477 write_datafile(data_filename, data, dump_json=dump_json)
478
479
480 def _should_skip_number_elem(data, elem):
481 """
482 Figure out whether the numbering-containing element `elem` is in a currently
483 non-supported (i.e. currently non-Latin) numbering system.
484
485 :param data: The root data element, for stashing the warning.
486 :param elem: Element with `numberSystem` key
487 :return: Boolean
488 """
489 number_system = elem.get('numberSystem', 'latn')
490
491 if number_system != 'latn':
492 data['unsupported_number_systems'].add(number_system)
493 return True
494
495 return False
496
497
498 def _should_skip_elem(elem, type=None, dest=None):
499 """
500 Check whether the given element should be skipped.
501
502 Elements are skipped if they are drafts or alternates of data that already exists in `dest`.
503
504 :param elem: XML element
505 :param type: Type string. May be elided if the dest dict is elided.
506 :param dest: Destination dict. May be elided to skip the dict check.
507 :return: skip boolean
508 """
509 if _is_draft_or_alt(elem):
510 if dest is None or type in dest:
511 return True
512
513
514 def _is_draft_or_alt(elem) -> bool:
515 return 'draft' in elem.attrib or 'alt' in elem.attrib
516
517
518 def _import_type_text(dest, elem, type=None, *, allow_variant_and_draft_fallback=True) -> None:
519 """
520 Conditionally import the element's inner text(s) into the `dest` dict.
521
522 If `allow_variant_and_draft_fallback` is True, then the element may be imported
523 if there otherwise isn't a pre-existing element of the same type.
524
525 :param dest: Destination dict
526 :param elem: XML element.
527 :param type: Override type. (By default, the `type` attr of the element.)
528 :param allow_variant_and_draft_fallback: See above.
529 :return: Nothing.
530 """
531 if type is None:
532 type = elem.attrib['type']
533
534 # Already have this, nothing to do.
535 if type in dest:
536 return
537
538 if not allow_variant_and_draft_fallback and _is_draft_or_alt(elem):
539 # Not allowed to use a draft/alternate here.
540 return
541 dest[type] = _text(elem)
542
543
544 def parse_locale_display_names(data, tree, *, is_global: bool):
545 territories = data.setdefault('territories', {})
546 for elem in tree.findall('.//territories/territory'):
547 _import_type_text(territories, elem, allow_variant_and_draft_fallback=is_global)
548 languages = data.setdefault('languages', {})
549 for elem in tree.findall('.//languages/language'):
550 _import_type_text(languages, elem, allow_variant_and_draft_fallback=is_global)
551 variants = data.setdefault('variants', {})
552 for elem in tree.findall('.//variants/variant'):
553 _import_type_text(variants, elem, allow_variant_and_draft_fallback=is_global)
554 scripts = data.setdefault('scripts', {})
555 for elem in tree.findall('.//scripts/script'):
556 _import_type_text(scripts, elem, allow_variant_and_draft_fallback=is_global)
557
558
559 def parse_list_patterns(data, tree):
560 list_patterns = data.setdefault('list_patterns', {})
561 for list_pattern_el in tree.findall('.//listPatterns/listPattern'):
562 pattern_type = list_pattern_el.attrib.get('type', 'standard')
563 for pattern_part_el in list_pattern_el.findall('listPatternPart'):
564 pattern_part_type = pattern_part_el.attrib['type']
565 list_patterns.setdefault(pattern_type, {})[pattern_part_type] = _text(pattern_part_el)
566
567
568 def parse_dates(data, tree, sup, regions, territory):
569 week_data = data.setdefault('week_data', {})
570 supelem = sup.find('.//weekData')
571 for elem in supelem.findall('minDays'):
572 if _should_skip_elem(elem):
573 continue
574 territories = elem.attrib['territories'].split()
575 if territory in territories or any(r in territories for r in regions):
576 week_data['min_days'] = int(elem.attrib['count'])
577 for elem in supelem.findall('firstDay'):
578 if _should_skip_elem(elem):
579 continue
580 territories = elem.attrib['territories'].split()
581 if territory in territories or any(r in territories for r in regions):
582 week_data['first_day'] = weekdays[elem.attrib['day']]
583 for elem in supelem.findall('weekendStart'):
584 if _should_skip_elem(elem):
585 continue
586 territories = elem.attrib['territories'].split()
587 if territory in territories or any(r in territories for r in regions):
588 week_data['weekend_start'] = weekdays[elem.attrib['day']]
589 for elem in supelem.findall('weekendEnd'):
590 if _should_skip_elem(elem):
591 continue
592 territories = elem.attrib['territories'].split()
593 if territory in territories or any(r in territories for r in regions):
594 week_data['weekend_end'] = weekdays[elem.attrib['day']]
595 zone_formats = data.setdefault('zone_formats', {})
596 for elem in tree.findall('.//timeZoneNames/gmtFormat'):
597 if not _should_skip_elem(elem):
598 zone_formats['gmt'] = str(elem.text).replace('{0}', '%s')
599 break
600 for elem in tree.findall('.//timeZoneNames/regionFormat'):
601 if not _should_skip_elem(elem):
602 zone_formats['region'] = str(elem.text).replace('{0}', '%s')
603 break
604 for elem in tree.findall('.//timeZoneNames/fallbackFormat'):
605 if not _should_skip_elem(elem):
606 zone_formats['fallback'] = (
607 str(elem.text).replace('{0}', '%(0)s').replace('{1}', '%(1)s')
608 )
609 break
610 for elem in tree.findall('.//timeZoneNames/fallbackRegionFormat'):
611 if not _should_skip_elem(elem):
612 zone_formats['fallback_region'] = (
613 str(elem.text).replace('{0}', '%(0)s').replace('{1}', '%(1)s')
614 )
615 break
616 time_zones = data.setdefault('time_zones', {})
617 for elem in tree.findall('.//timeZoneNames/zone'):
618 info = {}
619 city = elem.findtext('exemplarCity')
620 if city:
621 info['city'] = str(city)
622 for child in elem.findall('long/*'):
623 info.setdefault('long', {})[child.tag] = str(child.text)
624 for child in elem.findall('short/*'):
625 info.setdefault('short', {})[child.tag] = str(child.text)
626 time_zones[elem.attrib['type']] = info
627 meta_zones = data.setdefault('meta_zones', {})
628 for elem in tree.findall('.//timeZoneNames/metazone'):
629 info = {}
630 city = elem.findtext('exemplarCity')
631 if city:
632 info['city'] = str(city)
633 for child in elem.findall('long/*'):
634 info.setdefault('long', {})[child.tag] = str(child.text)
635 for child in elem.findall('short/*'):
636 info.setdefault('short', {})[child.tag] = str(child.text)
637 meta_zones[elem.attrib['type']] = info
638
639
640 def parse_calendar_months(data, calendar):
641 months = data.setdefault('months', {})
642 for ctxt in calendar.findall('months/monthContext'):
643 ctxt_type = ctxt.attrib['type']
644 ctxts = months.setdefault(ctxt_type, {})
645 for width in ctxt.findall('monthWidth'):
646 width_type = width.attrib['type']
647 widths = ctxts.setdefault(width_type, {})
648 for elem in width:
649 if elem.tag == 'month':
650 _import_type_text(widths, elem, int(elem.attrib['type']))
651 elif elem.tag == 'alias':
652 ctxts[width_type] = Alias(
653 _translate_alias(['months', ctxt_type, width_type],
654 elem.attrib['path']),
655 )
656
657
658 def parse_calendar_days(data, calendar):
659 days = data.setdefault('days', {})
660 for ctxt in calendar.findall('days/dayContext'):
661 ctxt_type = ctxt.attrib['type']
662 ctxts = days.setdefault(ctxt_type, {})
663 for width in ctxt.findall('dayWidth'):
664 width_type = width.attrib['type']
665 widths = ctxts.setdefault(width_type, {})
666 for elem in width:
667 if elem.tag == 'day':
668 _import_type_text(widths, elem, weekdays[elem.attrib['type']])
669 elif elem.tag == 'alias':
670 ctxts[width_type] = Alias(
671 _translate_alias(['days', ctxt_type, width_type],
672 elem.attrib['path']),
673 )
674
675
676 def parse_calendar_quarters(data, calendar):
677 quarters = data.setdefault('quarters', {})
678 for ctxt in calendar.findall('quarters/quarterContext'):
679 ctxt_type = ctxt.attrib['type']
680 ctxts = quarters.setdefault(ctxt.attrib['type'], {})
681 for width in ctxt.findall('quarterWidth'):
682 width_type = width.attrib['type']
683 widths = ctxts.setdefault(width_type, {})
684 for elem in width:
685 if elem.tag == 'quarter':
686 _import_type_text(widths, elem, int(elem.attrib['type']))
687 elif elem.tag == 'alias':
688 ctxts[width_type] = Alias(
689 _translate_alias(['quarters', ctxt_type,
690 width_type],
691 elem.attrib['path']))
692
693
694 def parse_calendar_eras(data, calendar):
695 eras = data.setdefault('eras', {})
696 for width in calendar.findall('eras/*'):
697 width_type = NAME_MAP[width.tag]
698 widths = eras.setdefault(width_type, {})
699 for elem in width:
700 if elem.tag == 'era':
701 _import_type_text(widths, elem, type=int(elem.attrib.get('type')))
702 elif elem.tag == 'alias':
703 eras[width_type] = Alias(
704 _translate_alias(['eras', width_type],
705 elem.attrib['path']),
706 )
707
708
709 def parse_calendar_periods(data, calendar):
710 # Day periods (AM/PM/others)
711 periods = data.setdefault('day_periods', {})
712 for day_period_ctx in calendar.findall('dayPeriods/dayPeriodContext'):
713 ctx_type = day_period_ctx.attrib["type"]
714 for day_period_width in day_period_ctx.findall('dayPeriodWidth'):
715 width_type = day_period_width.attrib["type"]
716 dest_dict = periods.setdefault(ctx_type, {}).setdefault(width_type, {})
717 for day_period in day_period_width.findall('dayPeriod'):
718 period_type = day_period.attrib['type']
719 if 'alt' not in day_period.attrib:
720 dest_dict[period_type] = str(day_period.text)
721
722
723 def parse_calendar_date_formats(data, calendar):
724 date_formats = data.setdefault('date_formats', {})
725 for format in calendar.findall('dateFormats'):
726 for elem in format:
727 if elem.tag == 'dateFormatLength':
728 type = elem.attrib.get('type')
729 if _should_skip_elem(elem, type, date_formats):
730 continue
731 try:
732 date_formats[type] = dates.parse_pattern(
733 str(elem.findtext('dateFormat/pattern')),
734 )
735 except ValueError as e:
736 log.error(e)
737 elif elem.tag == 'alias':
738 date_formats = Alias(_translate_alias(
739 ['date_formats'], elem.attrib['path']),
740 )
741
742
743 def parse_calendar_time_formats(data, calendar):
744 time_formats = data.setdefault('time_formats', {})
745 for format in calendar.findall('timeFormats'):
746 for elem in format:
747 if elem.tag == 'timeFormatLength':
748 type = elem.attrib.get('type')
749 if _should_skip_elem(elem, type, time_formats):
750 continue
751 try:
752 time_formats[type] = dates.parse_pattern(
753 str(elem.findtext('timeFormat/pattern')),
754 )
755 except ValueError as e:
756 log.error(e)
757 elif elem.tag == 'alias':
758 time_formats = Alias(_translate_alias(
759 ['time_formats'], elem.attrib['path']),
760 )
761
762
763 def parse_calendar_datetime_skeletons(data, calendar):
764 datetime_formats = data.setdefault('datetime_formats', {})
765 datetime_skeletons = data.setdefault('datetime_skeletons', {})
766 for format in calendar.findall('dateTimeFormats'):
767 for elem in format:
768 if elem.tag == 'dateTimeFormatLength':
769 type = elem.attrib.get('type')
770 if _should_skip_elem(elem, type, datetime_formats):
771 continue
772 try:
773 datetime_formats[type] = str(elem.findtext('dateTimeFormat/pattern'))
774 except ValueError as e:
775 log.error(e)
776 elif elem.tag == 'alias':
777 datetime_formats = Alias(_translate_alias(
778 ['datetime_formats'], elem.attrib['path']),
779 )
780 elif elem.tag == 'availableFormats':
781 for datetime_skeleton in elem.findall('dateFormatItem'):
782 datetime_skeletons[datetime_skeleton.attrib['id']] = (
783 dates.parse_pattern(str(datetime_skeleton.text))
784 )
785
786
787 def parse_number_symbols(data, tree):
788 number_symbols = data.setdefault('number_symbols', {})
789 for symbol_system_elem in tree.findall('.//numbers/symbols'):
790 number_system = symbol_system_elem.get('numberSystem')
791 if not number_system:
792 continue
793
794 for symbol_element in symbol_system_elem.findall('./*'):
795 if _should_skip_elem(symbol_element):
796 continue
797
798 number_symbols.setdefault(number_system, {})[symbol_element.tag] = str(symbol_element.text)
799
800
801 def parse_numbering_systems(data, tree):
802 default_number_system_node = tree.find('.//numbers/defaultNumberingSystem')
803 if default_number_system_node is not None:
804 data['default_numbering_system'] = default_number_system_node.text
805
806 numbering_systems = data.setdefault('numbering_systems', {})
807 other_numbering_systems_node = tree.find('.//numbers/otherNumberingSystems') or []
808 for system in other_numbering_systems_node:
809 numbering_systems[system.tag] = system.text
810
811
812 def parse_decimal_formats(data, tree):
813 decimal_formats = data.setdefault('decimal_formats', {})
814 for df_elem in tree.findall('.//decimalFormats'):
815 if _should_skip_number_elem(data, df_elem): # TODO: Support other number systems
816 continue
817 for elem in df_elem.findall('./decimalFormatLength'):
818 length_type = elem.attrib.get('type')
819 if _should_skip_elem(elem, length_type, decimal_formats):
820 continue
821 alias_elem = elem.find('./alias')
822 if alias_elem is not None:
823 if alias_elem.attrib['path'] != "../decimalFormatLength[@type='short']":
824 raise ValueError("Unexpected decimal format alias in new CLDR data; this may require hand-holding.")
825 # In particular: if you're reading this, the tribal knowledge below
826 # (that this is compact_decimal_format) needs to be double-checked.
827
828 # `root.xml` aliases `long` to `short`.
829 # The typed lengths only carry compact patterns, so the alias lands in `compact_decimal_formats`.
830 # Only root has this.
831 compact_decimal_formats = data.setdefault('compact_decimal_formats', {})
832 compact_decimal_formats[length_type] = Alias(
833 ('compact_decimal_formats', _sibling_alias_type(alias_elem)),
834 )
835 continue
836 for pattern_el in elem.findall('./decimalFormat/pattern'):
837 pattern_type = pattern_el.attrib.get('type')
838 pattern = numbers.parse_pattern(str(pattern_el.text))
839 if pattern_type:
840 # This is a compact decimal format, see:
841 # https://www.unicode.org/reports/tr35/tr35-45/tr35-numbers.html#Compact_Number_Formats
842
843 # These are mapped into a `compact_decimal_formats` dictionary
844 # with the format {length: {count: {multiplier: pattern}}}.
845 compact_decimal_formats = data.setdefault('compact_decimal_formats', {})
846 length_map = compact_decimal_formats.setdefault(length_type, {})
847 length_count_map = length_map.setdefault(pattern_el.attrib['count'], {})
848 length_count_map[pattern_type] = pattern
849 else:
850 # Regular decimal format.
851 decimal_formats[length_type] = pattern
852
853
854 def parse_scientific_formats(data, tree):
855 scientific_formats = data.setdefault('scientific_formats', {})
856 for sf_elem in tree.findall('.//scientificFormats'):
857 if _should_skip_number_elem(data, sf_elem): # TODO: Support other number systems
858 continue
859 for elem in sf_elem.findall('./scientificFormatLength'):
860 type = elem.attrib.get('type')
861 if _should_skip_elem(elem, type, scientific_formats):
862 continue
863 pattern = str(elem.findtext('scientificFormat/pattern'))
864 scientific_formats[type] = numbers.parse_pattern(pattern)
865
866
867 def parse_percent_formats(data, tree):
868 percent_formats = data.setdefault('percent_formats', {})
869
870 for pf_elem in tree.findall('.//percentFormats'):
871 if _should_skip_number_elem(data, pf_elem): # TODO: Support other number systems
872 continue
873 for elem in pf_elem.findall('.//percentFormatLength'):
874 type = elem.attrib.get('type')
875 if _should_skip_elem(elem, type, percent_formats):
876 continue
877 pattern = str(elem.findtext('percentFormat/pattern'))
878 percent_formats[type] = numbers.parse_pattern(pattern)
879
880
881 def parse_currency_names(data, tree):
882 currency_names = data.setdefault('currency_names', {})
883 currency_names_plural = data.setdefault('currency_names_plural', {})
884 currency_symbols = data.setdefault('currency_symbols', {})
885 for elem in tree.findall('.//currencies/currency'):
886 code = elem.attrib['type']
887 for name in elem.findall('displayName'):
888 if ('draft' in name.attrib) and code in currency_names:
889 continue
890 if 'count' in name.attrib:
891 currency_names_plural.setdefault(code, {})[
892 name.attrib['count']] = str(name.text)
893 else:
894 currency_names[code] = str(name.text)
895 for symbol in elem.findall('symbol'):
896 if 'draft' in symbol.attrib or 'choice' in symbol.attrib: # Skip drafts and choice-patterns
897 continue
898 if symbol.attrib.get('alt'): # Skip alternate forms
899 continue
900 currency_symbols[code] = str(symbol.text)
901
902
903 def parse_unit_patterns(data, tree):
904 unit_patterns = data.setdefault('unit_patterns', {})
905 compound_patterns = data.setdefault('compound_unit_patterns', {})
906 unit_display_names = data.setdefault('unit_display_names', {})
907 # `root.xml` aliases the `long` and `narrow` unit lengths to `short`,
908 # and some units to others (e.g. `duration-day-person` to `duration-day`).
909 # This is keyed unit-first instead of length-first (XML),
910 # so length aliases are expanded into per-unit aliases below.
911 # Only root has aliases.
912 length_aliases = {}
913
914 for elem in tree.findall('.//units/unitLength'):
915 unit_length_type = elem.attrib['type']
916 alias_elem = elem.find('./alias')
917 if alias_elem is not None:
918 length_aliases[unit_length_type] = _sibling_alias_type(alias_elem)
919 continue
920 for unit in elem.findall('unit'):
921 unit_type = unit.attrib['type']
922 alias_elem = unit.find('./alias')
923 if alias_elem is not None:
924 target_unit = _sibling_alias_type(alias_elem)
925 if unit_type.endswith('-person'):
926 # HACK (and this is a mouthful):
927 # The `duration-*-person` units (used for formatting ages) are
928 # aliased to their base units. The alias element only exists
929 # inside `unitLength[short]`, so literal resolution would route
930 # a long/narrow request through the short chain and lose the
931 # requested length ("3 y" where "3 years" was wanted).
932 # ICU considers this a deficiency of the alias data structure
933 # (https://unicode-org.atlassian.net/browse/ICU-20400) and
934 # compensates by stripping the `-person` suffix before lookup
935 # This seems to make sense, so we do that too:
936 # alias the whole unit, preserving the requested length.
937 #
938 # NB: this deliberately bends literal TR35 alias resolution to
939 # match ICU's output. Should CLDR ever gain a length-preserving
940 # alias representation, spec compliance is restored by deleting
941 # this special-case `-person` branch and translating those
942 # aliases as written, as the branch below does..
943 unit_patterns[unit_type] = Alias(('unit_patterns', target_unit))
944 unit_display_names[unit_type] = Alias(('unit_display_names', target_unit))
945 else:
946 # The other aliased units (`graphics-dot*` -> `graphics-pixel*`,
947 # `energy-foodcalorie` -> `energy-kilocalorie`) get no such
948 # compensation in ICU and follow the literal chain: the alias
949 # applies within this length only, and a locale's own data for
950 # the unit at other lengths (plus the length aliases below)
951 # takes precedence over the target unit's.
952 unit_patterns.setdefault(unit_type, {})[unit_length_type] = Alias(
953 ('unit_patterns', target_unit, unit_length_type),
954 )
955 unit_display_names.setdefault(unit_type, {})[unit_length_type] = Alias(
956 ('unit_display_names', target_unit, unit_length_type),
957 )
958 continue
959 unit_and_length_patterns = unit_patterns.setdefault(unit_type, {}).setdefault(unit_length_type, {})
960 for pattern in unit.findall('unitPattern'):
961 if pattern.attrib.get('case', 'nominative') != 'nominative':
962 # Skip non-nominative cases.
963 continue
964 unit_and_length_patterns[pattern.attrib['count']] = _text(pattern)
965
966 per_unit_pat = unit.find('perUnitPattern')
967 if per_unit_pat is not None:
968 unit_and_length_patterns['per'] = _text(per_unit_pat)
969
970 display_name = unit.find('displayName')
971 if display_name is not None:
972 unit_display_names.setdefault(unit_type, {})[unit_length_type] = _text(display_name)
973
974 for unit in elem.findall('compoundUnit'):
975 unit_type = unit.attrib['type']
976 compound_unit_info = {}
977 compound_variations = {}
978 for child in unit:
979 if child.attrib.get('case', 'nominative') != 'nominative':
980 # Skip non-nominative cases.
981 continue
982 if child.tag == "unitPrefixPattern":
983 compound_unit_info['prefix'] = _text(child)
984 elif child.tag == "compoundUnitPattern":
985 compound_variations[None] = _text(child)
986 elif child.tag == "compoundUnitPattern1":
987 compound_variations[child.attrib.get('count')] = _text(child)
988 if compound_variations:
989 compound_variation_values = set(compound_variations.values())
990 if len(compound_variation_values) == 1:
991 # shortcut: if all compound variations are the same, only store one
992 compound_unit_info['compound'] = next(iter(compound_variation_values))
993 else:
994 compound_unit_info['compound_variations'] = compound_variations
995 compound_patterns.setdefault(unit_type, {})[unit_length_type] = compound_unit_info
996
997 for aliased_length, target_length in length_aliases.items():
998 for dict_name, dst in (
999 ('unit_patterns', unit_patterns),
1000 ('compound_unit_patterns', compound_patterns),
1001 ('unit_display_names', unit_display_names),
1002 ):
1003 for unit_type, lengths in dst.items():
1004 if isinstance(lengths, Alias):
1005 # A length-preserving whole-unit alias installed above.
1006 continue
1007 lengths.setdefault(aliased_length, Alias((dict_name, unit_type, target_length)))
1008
1009
1010 def parse_date_fields(data, tree):
1011 date_fields = data.setdefault('date_fields', {})
1012 for elem in tree.findall('.//dates/fields/field'):
1013 field_type = elem.attrib['type']
1014 # `root` aliases `x-narrow` to `x-short` and `x-short` to `x`.
1015 # Locales defining only some length variants inherit these.
1016 # Only root has these.
1017 alias_elem = elem.find('alias')
1018 if alias_elem is not None:
1019 date_fields[field_type] = Alias(
1020 _translate_alias(['date_fields', field_type], alias_elem.attrib['path']),
1021 )
1022 continue
1023 date_fields.setdefault(field_type, {})
1024 for rel_time in elem.findall('relativeTime'):
1025 rel_time_type = rel_time.attrib['type']
1026 for pattern in rel_time.findall('relativeTimePattern'):
1027 type_dict = date_fields[field_type].setdefault(rel_time_type, {})
1028 type_dict[pattern.attrib['count']] = str(pattern.text)
1029
1030
1031 def parse_interval_formats(data, tree):
1032 # https://www.unicode.org/reports/tr35/tr35-dates.html#intervalFormats
1033 interval_formats = data.setdefault("interval_formats", {})
1034 for elem in tree.findall("dateTimeFormats/intervalFormats/*"):
1035 if 'draft' in elem.attrib:
1036 continue
1037 if elem.tag == "intervalFormatFallback":
1038 interval_formats[None] = elem.text
1039 elif elem.tag == "intervalFormatItem":
1040 skel_data = interval_formats.setdefault(elem.attrib["id"], {})
1041 for item_sub in elem:
1042 if item_sub.tag == "greatestDifference":
1043 skel_data[item_sub.attrib["id"]] = split_interval_pattern(item_sub.text)
1044 else:
1045 raise NotImplementedError(f"Not implemented: {item_sub.tag}({item_sub.attrib!r})")
1046
1047
1048 def parse_currency_formats(data, tree):
1049 currency_formats = data.setdefault('currency_formats', {})
1050 for currency_format in tree.findall('.//currencyFormats'):
1051 if _should_skip_number_elem(data, currency_format): # TODO: Support other number systems
1052 continue
1053
1054 for length_elem in currency_format.findall('./currencyFormatLength'):
1055 curr_length_type = length_elem.attrib.get('type')
1056 for elem in length_elem.findall('currencyFormat'):
1057 type = elem.attrib.get('type')
1058 if _should_skip_elem(elem, type, currency_formats):
1059 continue
1060 for child in elem.iter():
1061 if child.tag == 'alias':
1062 currency_formats[type] = Alias(
1063 _translate_alias(['currency_formats', elem.attrib['type']],
1064 child.attrib['path']),
1065 )
1066 elif child.tag == 'pattern':
1067 pattern_type = child.attrib.get('type')
1068 if child.attrib.get('draft') or child.attrib.get('alt'):
1069 # Skip drafts and alternates.
1070 # The `noCurrency` alternate for currencies was added in CLDR 42.
1071 continue
1072 pattern = numbers.parse_pattern(str(child.text))
1073 if pattern_type:
1074 # This is a compact currency format, see:
1075 # https://www.unicode.org/reports/tr35/tr35-45/tr35-numbers.html#Compact_Number_Formats
1076
1077 # These are mapped into a `compact_currency_formats` dictionary
1078 # with the format {length: {count: {multiplier: pattern}}}.
1079 compact_currency_formats = data.setdefault('compact_currency_formats', {})
1080 length_map = compact_currency_formats.setdefault(curr_length_type, {})
1081 length_count_map = length_map.setdefault(child.attrib['count'], {})
1082 length_count_map[pattern_type] = pattern
1083 else:
1084 # Regular currency format
1085 currency_formats[type] = pattern
1086
1087
1088 def parse_currency_unit_patterns(data, tree):
1089 currency_unit_patterns = data.setdefault('currency_unit_patterns', {})
1090 for currency_formats_elem in tree.findall('.//currencyFormats'):
1091 if _should_skip_number_elem(data, currency_formats_elem): # TODO: Support other number systems
1092 continue
1093 for unit_pattern_elem in currency_formats_elem.findall('./unitPattern'):
1094 count = unit_pattern_elem.attrib['count']
1095 pattern = str(unit_pattern_elem.text)
1096 currency_unit_patterns[count] = pattern
1097
1098
1099 def parse_day_period_rules(tree):
1100 """
1101 Parse dayPeriodRule data into a dict.
1102
1103 :param tree: ElementTree
1104 """
1105 day_periods = {}
1106 for ruleset in tree.findall(".//dayPeriodRuleSet"):
1107 ruleset_type = ruleset.attrib.get("type") # None|"selection"
1108 for rules in ruleset.findall("dayPeriodRules"):
1109 locales = rules.attrib["locales"].split()
1110 for rule in rules.findall("dayPeriodRule"):
1111 type = rule.attrib["type"]
1112 if type in ("am", "pm"): # These fixed periods are handled separately by `get_period_id`
1113 continue
1114 rule = _compact_dict({
1115 key: _time_to_seconds_past_midnight(rule.attrib.get(key))
1116 for key in ("after", "at", "before", "from", "to")
1117 })
1118 for locale in locales:
1119 dest_list = day_periods.setdefault(locale, {}).setdefault(ruleset_type, {}).setdefault(type, [])
1120 dest_list.append(rule)
1121 return day_periods
1122
1123
1124 def parse_character_order(data, tree):
1125 for elem in tree.findall('.//layout/orientation/characterOrder'):
1126 data['character_order'] = elem.text
1127
1128
1129 def parse_measurement_systems(data, tree):
1130 measurement_systems = data.setdefault('measurement_systems', {})
1131 for measurement_system in tree.findall('.//measurementSystemNames/measurementSystemName'):
1132 type = measurement_system.attrib['type']
1133 if not _should_skip_elem(measurement_system, type=type, dest=measurement_systems):
1134 _import_type_text(measurement_systems, measurement_system, type=type)
1135
1136
1137 if __name__ == '__main__':
1138 main()