| 1 |
# /// script |
| 2 |
# requires-python = ">=3.10" |
| 3 |
# dependencies = [ |
| 4 |
# "lxml<7", |
| 5 |
# ] |
| 6 |
# /// |
| 7 |
|
| 8 |
"""sort_terms.py |
| 9 |
|
| 10 |
Utility for sorting and normalizing CSL locale XML files. |
| 11 |
|
| 12 |
This script parses CSL locale files (XML) and sorts <term> elements |
| 13 |
according to the canonical ordering derived from `locales-en-US.xml`, and |
| 14 |
rewrites the files preserving comments and structure. It also provides |
| 15 |
helpers to parse the terms into a dictionary (`get_terms_dict`) to ensure the |
| 16 |
script is semantics-preserving: running the sorter and then reparsing the file |
| 17 |
should produce the same terms dictionary. |
| 18 |
|
| 19 |
Typical usage (from the repository root): |
| 20 |
python util/sort_terms.py [-a] [locales-xx-YY.xml ...] |
| 21 |
|
| 22 |
""" |
| 23 |
|
| 24 |
import argparse |
| 25 |
import re |
| 26 |
from copy import deepcopy |
| 27 |
from dataclasses import dataclass |
| 28 |
from datetime import datetime, timezone |
| 29 |
from pathlib import Path |
| 30 |
from typing import Any |
| 31 |
|
| 32 |
from lxml import etree |
| 33 |
|
| 34 |
CSL_NAMESPACE = {"cs": "http://purl.org/net/xbiblio/csl"} |
| 35 |
|
| 36 |
GENDER_FORM_ORDER: dict[str, int] = {"": 0, "masculine": 1, "feminine": 2} |
| 37 |
|
| 38 |
|
| 39 |
@dataclass |
| 40 |
class Section: |
| 41 |
term_names: set[str] |
| 42 |
form: str |
| 43 |
|
| 44 |
|
| 45 |
def is_section_title(node) -> bool: |
| 46 |
if not isinstance(node, etree._Comment): |
| 47 |
return False |
| 48 |
previous = node.getprevious() |
| 49 |
if previous is not None and "\n" not in (previous.tail or ""): |
| 50 |
return False |
| 51 |
text = node.text if isinstance(node.text, str) else "" |
| 52 |
return text.isupper() |
| 53 |
|
| 54 |
|
| 55 |
def get_en_us_sections() -> dict[str, Section]: |
| 56 |
tree = etree.parse("locales-en-US.xml") |
| 57 |
terms = tree.getroot().find(".//cs:terms", namespaces=CSL_NAMESPACE) |
| 58 |
assert terms is not None |
| 59 |
|
| 60 |
sections: dict[str, Section] = {} |
| 61 |
|
| 62 |
category: str = "" |
| 63 |
|
| 64 |
section: str = "" |
| 65 |
term_names: set[str] = set() |
| 66 |
term_forms: set[str] = set() |
| 67 |
|
| 68 |
for node in terms: |
| 69 |
if is_section_title(node): |
| 70 |
title = str(node.text).strip() |
| 71 |
if section: |
| 72 |
assert term_names |
| 73 |
assert len(term_forms) == 1 |
| 74 |
form = term_forms.pop() |
| 75 |
if form == "": # section of long forms |
| 76 |
sections[section] = Section(term_names=set(term_names), form=form) |
| 77 |
term_names = set() |
| 78 |
term_forms = set() |
| 79 |
category = section |
| 80 |
else: |
| 81 |
sections[section] = Section( |
| 82 |
term_names=set(sections[category].term_names).union(term_names), |
| 83 |
form=form, |
| 84 |
) |
| 85 |
section = title |
| 86 |
elif isinstance(node.tag, str): |
| 87 |
name: str = node.attrib.get("name", "") |
| 88 |
assert name |
| 89 |
form: str = node.attrib.get("form", "") |
| 90 |
|
| 91 |
term_names.add(name) |
| 92 |
term_forms.add(form) |
| 93 |
|
| 94 |
if section: |
| 95 |
assert term_names |
| 96 |
assert len(term_forms) == 1 |
| 97 |
form = term_forms.pop() |
| 98 |
if form == "": |
| 99 |
sections[section] = Section(term_names=set(term_names), form=form) |
| 100 |
else: |
| 101 |
sections[section] = Section( |
| 102 |
term_names=set(sections[category].term_names), form=form |
| 103 |
) |
| 104 |
return sections |
| 105 |
|
| 106 |
|
| 107 |
def sort_locale_terms(path: Path, sections: dict[str, Section]) -> None: |
| 108 |
print(str(path)) |
| 109 |
|
| 110 |
original_text = path.read_text(encoding="utf-8") |
| 111 |
|
| 112 |
tree = etree.parse(str(path)) |
| 113 |
terms = tree.getroot().find(".//cs:terms", namespaces=CSL_NAMESPACE) |
| 114 |
assert terms is not None |
| 115 |
|
| 116 |
grouped_terms = group_by_section(sections, terms) |
| 117 |
new_terms = flatten(grouped_terms) |
| 118 |
|
| 119 |
terms[:] = new_terms |
| 120 |
|
| 121 |
text = etree.tostring(tree, encoding="utf-8", xml_declaration=True).decode("utf-8") |
| 122 |
text = re.sub(r"[ \t]+\n", "\n", text) + "\n" |
| 123 |
text = text.replace("'", '"', 4) |
| 124 |
text = text.replace(" ", " ") |
| 125 |
text = text.replace("‑", "‑") |
| 126 |
text = text.replace("—", "—") |
| 127 |
|
| 128 |
if text != original_text: |
| 129 |
now = datetime.now().astimezone(timezone.utc).isoformat(timespec="seconds") |
| 130 |
text = re.sub(r"<updated>.*?</updated>", f"<updated>{now}</updated>", text) |
| 131 |
path.write_text(text, encoding="utf-8") |
| 132 |
|
| 133 |
|
| 134 |
@dataclass |
| 135 |
class TermContent: |
| 136 |
name: str |
| 137 |
sort_key: tuple[int, str, str] |
| 138 |
elements: list[etree._Element] # May include comments following the term |
| 139 |
|
| 140 |
|
| 141 |
def group_by_section( |
| 142 |
sections: dict[str, Section], terms: etree._Element |
| 143 |
) -> dict[str, list[TermContent]]: |
| 144 |
grouped_terms: dict[str, list[TermContent]] = {section: [] for section in sections} |
| 145 |
|
| 146 |
term_content: TermContent | None = None |
| 147 |
other_terms: list[TermContent] = [] |
| 148 |
tmp_comments: list[etree._Comment] = [] # Comments before any term |
| 149 |
|
| 150 |
gender_form_order = GENDER_FORM_ORDER.copy() |
| 151 |
|
| 152 |
for term in terms.iterchildren(tag=etree.Element): |
| 153 |
gender_form = term.attrib.get("gender-form") |
| 154 |
if gender_form: |
| 155 |
if gender_form == "feminine": |
| 156 |
gender_form_order["masculine"] = 2 |
| 157 |
gender_form_order["feminine"] = 1 |
| 158 |
break |
| 159 |
|
| 160 |
for node in terms: |
| 161 |
if isinstance(node, etree._Comment): |
| 162 |
text = node.text.strip() if isinstance(node.text, str) else "" |
| 163 |
if text in sections or is_section_title(node): |
| 164 |
term_content = None |
| 165 |
continue |
| 166 |
|
| 167 |
tail = "" |
| 168 |
previous = node.getprevious() |
| 169 |
if previous is not None: |
| 170 |
tail = previous.tail or "" |
| 171 |
|
| 172 |
if "\n" not in tail and term_content: |
| 173 |
term_content.elements.append(deepcopy(node)) |
| 174 |
else: |
| 175 |
tmp_comments.append(deepcopy(node)) |
| 176 |
|
| 177 |
elif isinstance(node.tag, str): |
| 178 |
term = node |
| 179 |
name: str = term.attrib.get("name", "") |
| 180 |
assert name |
| 181 |
form = term.attrib.get("form", "") |
| 182 |
gender_form = term.attrib.get("gender-form", "") |
| 183 |
|
| 184 |
for section_name, section in sections.items(): |
| 185 |
if (name in section.term_names and form == section.form) or ( |
| 186 |
(name == "ordinal" or name.startswith("ordinal-")) |
| 187 |
and section_name == "ORDINALS" |
| 188 |
): |
| 189 |
new_term = deepcopy(term) |
| 190 |
# new_term.tail = "\n " |
| 191 |
term_content = TermContent( |
| 192 |
name=name, |
| 193 |
sort_key=( |
| 194 |
gender_form_order.get(gender_form, 0), |
| 195 |
"editor-translator" if name == "editortranslator" else name, |
| 196 |
name, |
| 197 |
), |
| 198 |
elements=[*tmp_comments, new_term], |
| 199 |
) |
| 200 |
tmp_comments = [] |
| 201 |
grouped_terms[section_name].append(term_content) |
| 202 |
|
| 203 |
break |
| 204 |
else: |
| 205 |
term_content = TermContent( |
| 206 |
name=name, sort_key=(0, name, ""), elements=[deepcopy(term)] |
| 207 |
) |
| 208 |
other_terms.append(term_content) |
| 209 |
|
| 210 |
if other_terms: |
| 211 |
grouped_terms["REMAINDERS"] = other_terms |
| 212 |
|
| 213 |
return grouped_terms |
| 214 |
|
| 215 |
|
| 216 |
def flatten(grouped_terms: dict[str, list[TermContent]]) -> list[etree._Element]: |
| 217 |
new_terms: list[etree._Element] = [] |
| 218 |
for section_name, section_terms in grouped_terms.items(): |
| 219 |
# print(section_name) |
| 220 |
if new_terms: |
| 221 |
new_terms[-1].tail = "\n\n " |
| 222 |
section_title = etree.Comment(f" {section_name} ") |
| 223 |
section_title.tail = "\n " |
| 224 |
new_terms.append(section_title) |
| 225 |
|
| 226 |
if section_name not in {"PUNCTUATION", "REMAINDERS"}: |
| 227 |
section_terms = sorted(section_terms, key=lambda x: x.sort_key) |
| 228 |
for term_content in section_terms: |
| 229 |
new_terms.extend(term_content.elements) |
| 230 |
new_terms[-1].tail = "\n " |
| 231 |
if new_terms: |
| 232 |
new_terms[-1].tail = "\n " |
| 233 |
return new_terms |
| 234 |
|
| 235 |
|
| 236 |
# The parsed form is based on `src/util_locale.js` of `Juris-M/citeproc-js`. |
| 237 |
# <https://github.com/Juris-M/citeproc-js/blob/f88a47e6d143ace8a79569388534ff8ad9205da0/src/util_locale.js#L86> |
| 238 |
def get_terms_dict(path: Path) -> dict[str, Any]: |
| 239 |
tree = etree.parse(str(path)) |
| 240 |
terms = tree.getroot().find(".//cs:terms", namespaces=CSL_NAMESPACE) |
| 241 |
assert terms is not None |
| 242 |
|
| 243 |
term_dict = { |
| 244 |
"terms": {}, |
| 245 |
"ord": {}, |
| 246 |
"noun-genders": {}, |
| 247 |
} |
| 248 |
term_dict["ord"]["1.0.1"] = None |
| 249 |
term_dict["ord"]["keys"] = {} |
| 250 |
ordinals_101 = {"last-digit": {}, "last-two-digits": {}, "whole-number": {}} |
| 251 |
ordinals101_toggle = False |
| 252 |
genderized_terms: dict[str, bool] = {} |
| 253 |
|
| 254 |
for term in terms.iterchildren(tag=etree.Element): |
| 255 |
name = term.attrib.get("name", "") |
| 256 |
if name == "issue": |
| 257 |
pass |
| 258 |
assert name |
| 259 |
if name == "sub verbo": |
| 260 |
name = "sub-verbo" |
| 261 |
|
| 262 |
if name == "ordinal" or name.startswith("ordinal-"): |
| 263 |
if name == "ordinal": |
| 264 |
ordinals101_toggle = True |
| 265 |
else: |
| 266 |
match = term.attrib.get("match", "") |
| 267 |
term_stub = name[8:] |
| 268 |
gender_form = term.attrib.get("gender-form", "neuter") |
| 269 |
if not match: |
| 270 |
match = "last-two-digits" |
| 271 |
if term_stub[:1] == "0": |
| 272 |
match = "last-digit" |
| 273 |
if term_stub[:1] == "0": |
| 274 |
term_stub = term_stub[1:] |
| 275 |
if term_stub not in ordinals_101[match]: |
| 276 |
ordinals_101[match][term_stub] = {} |
| 277 |
ordinals_101[match][term_stub][gender_form] = name |
| 278 |
term_dict["ord"]["keys"][name] = True |
| 279 |
|
| 280 |
if name not in term_dict["terms"]: |
| 281 |
term_dict["terms"][name] = {} |
| 282 |
|
| 283 |
form = term.attrib.get("form", "long") |
| 284 |
gender_form = term.attrib.get("gender-form", "") |
| 285 |
gender = term.attrib.get("gender", "") |
| 286 |
|
| 287 |
if gender: |
| 288 |
term_dict["noun-genders"][name] = gender |
| 289 |
|
| 290 |
if gender_form: |
| 291 |
term_dict["terms"][name][gender_form] = {} |
| 292 |
term_dict["terms"][name][gender_form][form] = [] |
| 293 |
target = term_dict["terms"][name][gender_form] |
| 294 |
genderized_terms[name] = True |
| 295 |
else: |
| 296 |
term_dict["terms"][name][form] = [] |
| 297 |
target = term_dict["terms"][name] |
| 298 |
|
| 299 |
multiple = term.find("cs:multiple", namespaces=CSL_NAMESPACE) |
| 300 |
if multiple is not None: |
| 301 |
single = term.find("cs:single", namespaces=CSL_NAMESPACE) |
| 302 |
assert single is not None |
| 303 |
target[form].append(single.text or "") |
| 304 |
target[form].append(multiple.text or "") |
| 305 |
else: |
| 306 |
target[form] = term.text or "" |
| 307 |
|
| 308 |
if ordinals101_toggle: |
| 309 |
for ikey in genderized_terms: |
| 310 |
gender_segments = {} |
| 311 |
form_segments = 0 |
| 312 |
for jkey in term_dict["terms"][ikey]: |
| 313 |
if jkey in {"masculine", "feminine"}: |
| 314 |
gender_segments[jkey] = term_dict["terms"][ikey][jkey] |
| 315 |
else: |
| 316 |
form_segments += 1 |
| 317 |
if not form_segments: |
| 318 |
if "feminine" in gender_segments: |
| 319 |
for jkey in gender_segments["feminine"]: |
| 320 |
term_dict["terms"][ikey][jkey] = gender_segments["feminine"][ |
| 321 |
jkey |
| 322 |
] |
| 323 |
elif "masculine" in gender_segments: |
| 324 |
for jkey in gender_segments["masculine"]: |
| 325 |
term_dict["terms"][ikey][jkey] = gender_segments["masculine"][ |
| 326 |
jkey |
| 327 |
] |
| 328 |
|
| 329 |
term_dict["ord"]["1.0.1"] = ordinals_101 |
| 330 |
|
| 331 |
return term_dict |
| 332 |
|
| 333 |
|
| 334 |
def main(): |
| 335 |
parser = argparse.ArgumentParser() |
| 336 |
parser.add_argument("-a", "--all", action="store_true") |
| 337 |
parser.add_argument("files", nargs="*") |
| 338 |
args = parser.parse_args() |
| 339 |
|
| 340 |
paths = [Path(path) for path in args.files] |
| 341 |
if args.all or not paths: |
| 342 |
paths = sorted(Path().glob("locales-*.xml")) |
| 343 |
|
| 344 |
sections = get_en_us_sections() |
| 345 |
|
| 346 |
for path in paths: |
| 347 |
original_terms_dict = get_terms_dict(path) |
| 348 |
# pprint(original_terms_dict) |
| 349 |
sort_locale_terms(path, sections) |
| 350 |
terms_dict = get_terms_dict(path) |
| 351 |
# Path("original-terms-dict.json").write_text( |
| 352 |
# json.dumps( |
| 353 |
# original_terms_dict, ensure_ascii=False, indent="\t", sort_keys=True |
| 354 |
# ) |
| 355 |
# ) |
| 356 |
# Path("terms-dict.json").write_text( |
| 357 |
# json.dumps(terms_dict, ensure_ascii=False, indent="\t", sort_keys=True) |
| 358 |
# ) |
| 359 |
assert terms_dict == original_terms_dict |
| 360 |
|
| 361 |
|
| 362 |
if __name__ == "__main__": |
| 363 |
main() |