diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 95a58084..ab6b8bff 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -70,9 +70,9 @@ repos: name: "\u2705 Check code for common misspellings" language: system types: [text] - # Station corrections hold names, tags and URLs in many languages, - # not English prose: "Cadena SER" is a name, not a typo. - exclude: ^(poetry\.lock|src/radios/corrections/.+\.json)$ + # Station corrections and country names are data in many languages, + # not English prose: "Cadena SER" is a name, and "FO" a country code. + exclude: ^(poetry\.lock|src/radios/corrections/.+\.json|src/radios/country_names\.py)$ entry: poetry run codespell - id: detect-private-key name: "\U0001F575\uFE0F Detect Private Keys" diff --git a/AGENTS.md b/AGENTS.md index 7a8cf7e8..546b76d2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -26,8 +26,10 @@ manager exits. | ` const.py` | Enums, supported orders, and language flags | | ` exceptions.py` | `RadioBrowserError` and its connection subclasses | | ` corrections/` | Station corrections: loader, schema, data per country | +| ` country_names.py` | Country names by code, generated from the Unicode CLDR | | `tests/` | pytest suite; each test has a one-line docstring | | `examples/` | Runnable example against the live API | +| `scripts/` | Maintenance scripts, like the country names generator | ## Commands @@ -90,8 +92,9 @@ See [AI_POLICY.md](AI_POLICY.md) for the contribution policy around AI tooling. that is what the API expects. - The API returns countries as ISO 3166-1 alpha-2 codes, and lists a few of them twice, once in lowercase. `countries()` fetches the whole list, merges - those, resolves the codes to names with `pycountry` (with a special case for - Kosovo, `XK`), and sorts and pages locally. + those, resolves the codes to names with `COUNTRY_NAMES`, and sorts and pages + locally. `country_names.py` is generated from the Unicode CLDR by + `scripts/update_country_names.py`; do not edit it by hand. - The API uses names of its own for countries in some places, like "The Netherlands" for states. `states()` looks those up from a country code. - Not every endpoint can sort by every `Order`. `LIST_ORDERS` and diff --git a/poetry.lock b/poetry.lock index ab599668..9689cb60 100644 --- a/poetry.lock +++ b/poetry.lock @@ -1326,14 +1326,14 @@ idna = ["idna (>=2.1)"] [[package]] name = "pycountry" -version = "26.2.16" +version = "24.6.1" description = "ISO country, subdivision, language, currency and script definitions and their translations" optional = false -python-versions = ">=3.10" -groups = ["main"] +python-versions = ">=3.8" +groups = ["dev"] files = [ - {file = "pycountry-26.2.16-py3-none-any.whl", hash = "sha256:115c4baf7cceaa30f59a4694d79483c9167dbce7a9de4d3d571c5f3ea77c305a"}, - {file = "pycountry-26.2.16.tar.gz", hash = "sha256:5b6027d453fcd6060112b951dd010f01f168b51b4bf8a1f1fc8c95c8d94a0801"}, + {file = "pycountry-24.6.1-py3-none-any.whl", hash = "sha256:f1a4fb391cd7214f8eefd39556d740adcc233c778a27f8942c8dca351d6ce06f"}, + {file = "pycountry-24.6.1.tar.gz", hash = "sha256:b61b3faccea67f87d10c1f2b0fc0be714409e8fcdcc1315613174f6466c10221"}, ] [[package]] @@ -1834,4 +1834,4 @@ files = [ [metadata] lock-version = "2.1" python-versions = ">=3.12" -content-hash = "5a60383b79b33c5742161760226262b787b0f26ba0865775dc4b90eda5b8aa80" +content-hash = "9aa84ef8566f8c498b764ad836d22bcfd3d5c901b1c30c8c8d1e0d1444fab5e0" diff --git a/pyproject.toml b/pyproject.toml index 336ef987..64e6ff04 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ version = "0.0.0" description = "Asynchronous Python client for the Radio Browser API." authors = [{ name = "Franck Nijhof", email = "opensource@frenck.dev" }] maintainers = [{ name = "Franck Nijhof", email = "opensource@frenck.dev" }] -license = "MIT" +license = "MIT AND Unicode-3.0" requires-python = ">=3.12" readme = "README.md" keywords = [ @@ -41,7 +41,6 @@ dependencies = [ 'orjson (>=3.9.8)', 'probatio (>=0.13.0)', 'pycares (>=5.0.0)', - 'pycountry (>=24.0.0)', 'yarl (>=1.6.0)', ] @@ -71,6 +70,7 @@ syrupy = "6.1.1" ty = "0.0.84" yamllint = "1.38.0" zizmor = "1.30.1" +pycountry = "24.6.1" [tool.coverage.run] plugins = ["covdefaults"] @@ -127,6 +127,9 @@ ignore = [ "FBT001", # Boolean positional args are idiomatic in parametrized tests "FBT002", # Boolean defaults are idiomatic in parametrized tests ] +"scripts/*.py" = [ + "INP001", # Standalone scripts, run by hand, not a package +] [tool.ruff.lint.flake8-pytest-style] mark-parentheses = false diff --git a/scripts/update_country_names.py b/scripts/update_country_names.py new file mode 100644 index 00000000..c1730246 --- /dev/null +++ b/scripts/update_country_names.py @@ -0,0 +1,82 @@ +"""Generate src/radios/country_names.py from the Unicode CLDR. + +The country names come from the English locale of the Unicode Common Locale +Data Repository (CLDR), the data browsers and operating systems use too. The +codes are the ISO 3166-1 alpha-2 codes pycountry knows, plus Kosovo, which has +a user-assigned code the Radio Browser API uses. + +Run it with `poetry run python scripts/update_country_names.py`. +""" + +import json +import pathlib +import urllib.request + +import pycountry + +CLDR_VERSION = "48.2.3" +CLDR_BASE = f"https://raw.githubusercontent.com/unicode-org/cldr-json/{CLDR_VERSION}" +CLDR_URL = f"{CLDR_BASE}/cldr-json/cldr-localenames-full/main/en/territories.json" +LICENSE_URL = f"{CLDR_BASE}/LICENSE" +OUTPUT = pathlib.Path(__file__).parent.parent / "src" / "radios" / "country_names.py" + +# Where the CLDR default name reads awkwardly in a list of stations, the short +# or variant name CLDR also has is used instead. +ALTERNATIVES = { + "CD": "CD-alt-variant", # Congo (DRC), instead of Congo - Kinshasa + "CG": "CG-alt-variant", # Congo (Republic), instead of Congo - Brazzaville + "HK": "HK-alt-short", # Hong Kong, instead of Hong Kong SAR China + "MM": "MM-alt-short", # Myanmar, instead of Myanmar (Burma) + "MO": "MO-alt-short", # Macao, instead of Macao SAR China + "PS": "PS-alt-short", # Palestine, instead of Palestinian Territories +} + + +def main() -> None: + """Fetch the country names, and write them out as a Python module.""" + with urllib.request.urlopen(CLDR_URL, timeout=30) as response: # noqa: S310 + territories = json.load(response)["main"]["en"]["localeDisplayNames"][ + "territories" + ] + + # The Unicode license asks for its notice to come with every copy of the + # data, so it goes into the generated file. + with urllib.request.urlopen(LICENSE_URL, timeout=30) as response: # noqa: S310 + notice = response.read().decode().strip() + + codes = sorted({country.alpha_2 for country in pycountry.countries} | {"XK"}) + # CLDR uses a typographic apostrophe (U+2019), like in Côte d'Ivoire. A + # plain one is what people type when they search or sort. + names = { + code: territories[ALTERNATIVES.get(code, code)].replace("\u2019", "'") + for code in codes + } + + license_comment = "\n".join(f"# {line}".rstrip() for line in notice.splitlines()) + + # A JSON string is a valid Python string, in the double quotes ruff wants. + body = "\n".join( + f" {json.dumps(code)}: {json.dumps(name, ensure_ascii=False)}," + for code, name in names.items() + ) + OUTPUT.write_text( + f'''"""English names of countries, by ISO 3166-1 alpha-2 code. + +Generated by scripts/update_country_names.py from the Unicode CLDR +{CLDR_VERSION}. Do not edit this file by hand, run that script instead. + +The names are data from the Unicode CLDR, under the Unicode License V3: +""" + +{license_comment} + +COUNTRY_NAMES: dict[str, str] = {{ +{body} +}} +''', + encoding="utf-8", + ) + + +if __name__ == "__main__": + main() diff --git a/src/radios/country_names.py b/src/radios/country_names.py new file mode 100644 index 00000000..86a35c45 --- /dev/null +++ b/src/radios/country_names.py @@ -0,0 +1,302 @@ +"""English names of countries, by ISO 3166-1 alpha-2 code. + +Generated by scripts/update_country_names.py from the Unicode CLDR +48.2.3. Do not edit this file by hand, run that script instead. + +The names are data from the Unicode CLDR, under the Unicode License V3: +""" + +# UNICODE LICENSE V3 +# +# COPYRIGHT AND PERMISSION NOTICE +# +# Copyright © 2015-2024 Unicode, Inc. +# +# NOTICE TO USER: Carefully read the following legal agreement. BY +# DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING DATA FILES, AND/OR +# SOFTWARE, YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE +# TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT +# DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE. +# +# Permission is hereby granted, free of charge, to any person obtaining a +# copy of data files and any associated documentation (the "Data Files") or +# software and any associated documentation (the "Software") to deal in the +# Data Files or Software without restriction, including without limitation +# the rights to use, copy, modify, merge, publish, distribute, and/or sell +# copies of the Data Files or Software, and to permit persons to whom the +# Data Files or Software are furnished to do so, provided that either (a) +# this copyright and permission notice appear with all copies of the Data +# Files or Software, or (b) this copyright and permission notice appear in +# associated Documentation. +# +# THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY +# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF +# THIRD PARTY RIGHTS. +# +# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE +# BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, +# OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +# ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA +# FILES OR SOFTWARE. +# +# Except as contained in this notice, the name of a copyright holder shall +# not be used in advertising or otherwise to promote the sale, use or other +# dealings in these Data Files or Software without prior written +# authorization of the copyright holder. +# +# SPDX-License-Identifier: Unicode-3.0 + +COUNTRY_NAMES: dict[str, str] = { + "AD": "Andorra", + "AE": "United Arab Emirates", + "AF": "Afghanistan", + "AG": "Antigua & Barbuda", + "AI": "Anguilla", + "AL": "Albania", + "AM": "Armenia", + "AO": "Angola", + "AQ": "Antarctica", + "AR": "Argentina", + "AS": "American Samoa", + "AT": "Austria", + "AU": "Australia", + "AW": "Aruba", + "AX": "Åland Islands", + "AZ": "Azerbaijan", + "BA": "Bosnia & Herzegovina", + "BB": "Barbados", + "BD": "Bangladesh", + "BE": "Belgium", + "BF": "Burkina Faso", + "BG": "Bulgaria", + "BH": "Bahrain", + "BI": "Burundi", + "BJ": "Benin", + "BL": "St. Barthélemy", + "BM": "Bermuda", + "BN": "Brunei", + "BO": "Bolivia", + "BQ": "Caribbean Netherlands", + "BR": "Brazil", + "BS": "Bahamas", + "BT": "Bhutan", + "BV": "Bouvet Island", + "BW": "Botswana", + "BY": "Belarus", + "BZ": "Belize", + "CA": "Canada", + "CC": "Cocos (Keeling) Islands", + "CD": "Congo (DRC)", + "CF": "Central African Republic", + "CG": "Congo (Republic)", + "CH": "Switzerland", + "CI": "Côte d'Ivoire", + "CK": "Cook Islands", + "CL": "Chile", + "CM": "Cameroon", + "CN": "China", + "CO": "Colombia", + "CR": "Costa Rica", + "CU": "Cuba", + "CV": "Cape Verde", + "CW": "Curaçao", + "CX": "Christmas Island", + "CY": "Cyprus", + "CZ": "Czechia", + "DE": "Germany", + "DJ": "Djibouti", + "DK": "Denmark", + "DM": "Dominica", + "DO": "Dominican Republic", + "DZ": "Algeria", + "EC": "Ecuador", + "EE": "Estonia", + "EG": "Egypt", + "EH": "Western Sahara", + "ER": "Eritrea", + "ES": "Spain", + "ET": "Ethiopia", + "FI": "Finland", + "FJ": "Fiji", + "FK": "Falkland Islands", + "FM": "Micronesia", + "FO": "Faroe Islands", + "FR": "France", + "GA": "Gabon", + "GB": "United Kingdom", + "GD": "Grenada", + "GE": "Georgia", + "GF": "French Guiana", + "GG": "Guernsey", + "GH": "Ghana", + "GI": "Gibraltar", + "GL": "Greenland", + "GM": "Gambia", + "GN": "Guinea", + "GP": "Guadeloupe", + "GQ": "Equatorial Guinea", + "GR": "Greece", + "GS": "South Georgia & South Sandwich Islands", + "GT": "Guatemala", + "GU": "Guam", + "GW": "Guinea-Bissau", + "GY": "Guyana", + "HK": "Hong Kong", + "HM": "Heard & McDonald Islands", + "HN": "Honduras", + "HR": "Croatia", + "HT": "Haiti", + "HU": "Hungary", + "ID": "Indonesia", + "IE": "Ireland", + "IL": "Israel", + "IM": "Isle of Man", + "IN": "India", + "IO": "British Indian Ocean Territory", + "IQ": "Iraq", + "IR": "Iran", + "IS": "Iceland", + "IT": "Italy", + "JE": "Jersey", + "JM": "Jamaica", + "JO": "Jordan", + "JP": "Japan", + "KE": "Kenya", + "KG": "Kyrgyzstan", + "KH": "Cambodia", + "KI": "Kiribati", + "KM": "Comoros", + "KN": "St. Kitts & Nevis", + "KP": "North Korea", + "KR": "South Korea", + "KW": "Kuwait", + "KY": "Cayman Islands", + "KZ": "Kazakhstan", + "LA": "Laos", + "LB": "Lebanon", + "LC": "St. Lucia", + "LI": "Liechtenstein", + "LK": "Sri Lanka", + "LR": "Liberia", + "LS": "Lesotho", + "LT": "Lithuania", + "LU": "Luxembourg", + "LV": "Latvia", + "LY": "Libya", + "MA": "Morocco", + "MC": "Monaco", + "MD": "Moldova", + "ME": "Montenegro", + "MF": "St. Martin", + "MG": "Madagascar", + "MH": "Marshall Islands", + "MK": "North Macedonia", + "ML": "Mali", + "MM": "Myanmar", + "MN": "Mongolia", + "MO": "Macao", + "MP": "Northern Mariana Islands", + "MQ": "Martinique", + "MR": "Mauritania", + "MS": "Montserrat", + "MT": "Malta", + "MU": "Mauritius", + "MV": "Maldives", + "MW": "Malawi", + "MX": "Mexico", + "MY": "Malaysia", + "MZ": "Mozambique", + "NA": "Namibia", + "NC": "New Caledonia", + "NE": "Niger", + "NF": "Norfolk Island", + "NG": "Nigeria", + "NI": "Nicaragua", + "NL": "Netherlands", + "NO": "Norway", + "NP": "Nepal", + "NR": "Nauru", + "NU": "Niue", + "NZ": "New Zealand", + "OM": "Oman", + "PA": "Panama", + "PE": "Peru", + "PF": "French Polynesia", + "PG": "Papua New Guinea", + "PH": "Philippines", + "PK": "Pakistan", + "PL": "Poland", + "PM": "St. Pierre & Miquelon", + "PN": "Pitcairn Islands", + "PR": "Puerto Rico", + "PS": "Palestine", + "PT": "Portugal", + "PW": "Palau", + "PY": "Paraguay", + "QA": "Qatar", + "RE": "Réunion", + "RO": "Romania", + "RS": "Serbia", + "RU": "Russia", + "RW": "Rwanda", + "SA": "Saudi Arabia", + "SB": "Solomon Islands", + "SC": "Seychelles", + "SD": "Sudan", + "SE": "Sweden", + "SG": "Singapore", + "SH": "St. Helena", + "SI": "Slovenia", + "SJ": "Svalbard & Jan Mayen", + "SK": "Slovakia", + "SL": "Sierra Leone", + "SM": "San Marino", + "SN": "Senegal", + "SO": "Somalia", + "SR": "Suriname", + "SS": "South Sudan", + "ST": "São Tomé & Príncipe", + "SV": "El Salvador", + "SX": "Sint Maarten", + "SY": "Syria", + "SZ": "Eswatini", + "TC": "Turks & Caicos Islands", + "TD": "Chad", + "TF": "French Southern Territories", + "TG": "Togo", + "TH": "Thailand", + "TJ": "Tajikistan", + "TK": "Tokelau", + "TL": "Timor-Leste", + "TM": "Turkmenistan", + "TN": "Tunisia", + "TO": "Tonga", + "TR": "Türkiye", + "TT": "Trinidad & Tobago", + "TV": "Tuvalu", + "TW": "Taiwan", + "TZ": "Tanzania", + "UA": "Ukraine", + "UG": "Uganda", + "UM": "U.S. Outlying Islands", + "US": "United States", + "UY": "Uruguay", + "UZ": "Uzbekistan", + "VA": "Vatican City", + "VC": "St. Vincent & Grenadines", + "VE": "Venezuela", + "VG": "British Virgin Islands", + "VI": "U.S. Virgin Islands", + "VN": "Vietnam", + "VU": "Vanuatu", + "WF": "Wallis & Futuna", + "WS": "Samoa", + "XK": "Kosovo", + "YE": "Yemen", + "YT": "Mayotte", + "ZA": "South Africa", + "ZM": "Zambia", + "ZW": "Zimbabwe", +} diff --git a/src/radios/models.py b/src/radios/models.py index 2c59542d..92c65f71 100644 --- a/src/radios/models.py +++ b/src/radios/models.py @@ -6,13 +6,13 @@ from dataclasses import dataclass, field from datetime import datetime -import pycountry from awesomeversion import AwesomeVersion from mashumaro import field_options from mashumaro.mixins.orjson import DataClassORJSONMixin from mashumaro.types import SerializationStrategy from .const import LANGUAGE_FLAGS +from .country_names import COUNTRY_NAMES def country_name(country_code: str) -> str | None: @@ -27,15 +27,7 @@ def country_name(country_code: str) -> str | None: The country name, or None if the code is unknown. """ - # Kosovo has a user-assigned code that is not part of ISO 3166-1, so - # pycountry does not know it. https://github.com/frenck/python-radios/issues/19 - if country_code.upper() == "XK": - return "Kosovo" - - if country := pycountry.countries.get(alpha_2=country_code): - return country.name # type: ignore[return-value] - - return None + return COUNTRY_NAMES.get(country_code.upper()) class CommaSeparatedString(SerializationStrategy): diff --git a/tests/test_country_names.py b/tests/test_country_names.py new file mode 100644 index 00000000..c1c56e41 --- /dev/null +++ b/tests/test_country_names.py @@ -0,0 +1,37 @@ +"""Tests for the country names the library ships.""" + +import pycountry +import pytest + +from radios.country_names import COUNTRY_NAMES +from radios.models import country_name + + +def test_every_country_has_a_name() -> None: + """Test every ISO 3166-1 country, and Kosovo, has a name, and nothing else.""" + iso_codes = {country.alpha_2 for country in pycountry.countries} + + assert set(COUNTRY_NAMES) == iso_codes | {"XK"} + assert all(COUNTRY_NAMES.values()) + + +@pytest.mark.parametrize( + ("code", "name"), + [ + ("NL", "Netherlands"), + ("KR", "South Korea"), + ("CI", "Côte d'Ivoire"), + ("HK", "Hong Kong"), + ("CD", "Congo (DRC)"), + ("XK", "Kosovo"), + ], +) +def test_country_name(code: str, name: str) -> None: + """Test a country code resolves to its common English name.""" + assert country_name(code) == name + assert country_name(code.lower()) == name + + +def test_unknown_country_name() -> None: + """Test an unknown country code has no name.""" + assert country_name("ZZ") is None diff --git a/tests/test_lists.py b/tests/test_lists.py index 388ec177..0374a692 100644 --- a/tests/test_lists.py +++ b/tests/test_lists.py @@ -39,7 +39,7 @@ async def test_countries( countries = await radios.countries() assert countries == snapshot - # Kosovo is not in pycountry, and unknown codes keep their code as name. + # Kosovo has a user-assigned code, and unknown codes keep their code as name. assert [country.name for country in countries] == [ "Germany", "Kosovo", diff --git a/tests/test_models.py b/tests/test_models.py index 8b94471f..f60cec5e 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -25,7 +25,7 @@ def test_station_country() -> None: def test_station_country_kosovo() -> None: - """Test a station in Kosovo resolves its country, which pycountry lacks.""" + """Test a station in Kosovo resolves its country, a user-assigned code.""" station, _, _ = _stations() station.country_code = "XK"