countrycodes 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,18 @@
1
+ """Look up ISO 3166-1 country codes."""
2
+
3
+ __all__ = (
4
+ "__version__",
5
+ "Country",
6
+ "Countries",
7
+ "country_name_similarity",
8
+ "get_country",
9
+ "search_countries",
10
+ "list_countries",
11
+ )
12
+
13
+ from importlib import metadata
14
+
15
+ from countrycodes.core import country_name_similarity, get_country, search_countries
16
+ from countrycodes.country import Countries, Country, list_countries
17
+
18
+ __version__ = metadata.version(__name__)
countrycodes/core.py ADDED
@@ -0,0 +1,152 @@
1
+ """ISO 3166-1 country lookup API."""
2
+
3
+ __all__ = ("country_name_similarity", "get_country", "search_countries")
4
+
5
+
6
+ from collections import defaultdict
7
+ from functools import cache, lru_cache
8
+
9
+ from countrycodes.country import Countries, Country, list_countries
10
+
11
+
12
+ def get_country(query: str) -> Country | None:
13
+ """Return the country for a unique exact code, dial code, or display name.
14
+
15
+ Matching ignores case and surrounding or repeated whitespace. Return
16
+ ``None`` when the query has no exact match or matches multiple countries.
17
+ """
18
+ normalized_query = _normalize(query)
19
+ if not normalized_query:
20
+ return None
21
+
22
+ matches = _country_index(list_countries()).get(normalized_query, ())
23
+ return matches[0] if len(matches) == 1 else None
24
+
25
+
26
+ def search_countries(query: str, *, limit: int | None = None) -> Countries:
27
+ """Return exact matches or fuzzy matches ranked by name similarity.
28
+
29
+ Queries match ISO alpha-2, alpha-3, and numeric codes, dial codes, and
30
+ display names (common name, falling back to the source name). Matching
31
+ ignores case and surrounding or repeated whitespace. If there is no exact
32
+ match, countries are ranked by combined word-level and full-name
33
+ similarity against the display name; equal scores are ordered by alpha-2
34
+ code. ``limit`` restricts the number of returned countries; it must be
35
+ positive when provided. An empty query returns an empty tuple.
36
+ """
37
+ if limit is not None and limit < 1:
38
+ raise ValueError("limit must be positive")
39
+
40
+ normalized_query = _normalize(query)
41
+ if not normalized_query:
42
+ return ()
43
+
44
+ countries = list_countries()
45
+ exact_matches = _country_index(countries).get(normalized_query, ())
46
+ if exact_matches:
47
+ matches = exact_matches
48
+ else:
49
+ scored_countries = []
50
+ for country in countries:
51
+ scored_countries.append(
52
+ (_country_name_similarity(normalized_query, country), country)
53
+ )
54
+ matches = tuple(
55
+ country
56
+ for _, country in sorted(
57
+ scored_countries,
58
+ key=lambda match: (
59
+ -match[0],
60
+ match[1].alpha2,
61
+ ),
62
+ )
63
+ )
64
+
65
+ return matches if limit is None else matches[:limit]
66
+
67
+
68
+ def country_name_similarity(query: str, country: Country) -> float:
69
+ """Return the combined word-level and full-name similarity score."""
70
+ normalized_query = _normalize(query)
71
+ if not normalized_query:
72
+ return 0.0
73
+ return _country_name_similarity(normalized_query, country)
74
+
75
+
76
+ def _normalize(value: str) -> str:
77
+ """Return a normalized country query."""
78
+ return " ".join(value.casefold().split())
79
+
80
+
81
+ @cache
82
+ def _country_index(countries: Countries) -> dict[str, Countries]:
83
+ """Return the cached index of country codes and names."""
84
+ index: dict[str, list[Country]] = defaultdict(list)
85
+ for country in countries:
86
+ search_terms = (
87
+ country.alpha2,
88
+ country.alpha3,
89
+ country.numeric,
90
+ country.dial_code,
91
+ country.display_name,
92
+ )
93
+ for value in search_terms:
94
+ if value is not None:
95
+ index[_normalize(value)].append(country)
96
+
97
+ return {key: tuple(matches) for key, matches in index.items()}
98
+
99
+
100
+ def _country_name_similarity(query: str, country: Country) -> float:
101
+ """Return combined word and full-name similarity for the displayed name."""
102
+ word_score, full_name_score = _name_similarity(query, country.display_name)
103
+ return (word_score + full_name_score) / 2
104
+
105
+
106
+ @lru_cache(maxsize=4096)
107
+ def _name_similarity(query: str, name: str) -> tuple[float, float]:
108
+ """Return word-level and full-name similarity scores."""
109
+ normalized_name = _normalize(name)
110
+ full_name_score = _edit_similarity(query, normalized_name)
111
+ if " " in query:
112
+ return full_name_score, full_name_score
113
+
114
+ word_score = max(
115
+ (_edit_similarity(query, word) for word in normalized_name.split()),
116
+ default=full_name_score,
117
+ )
118
+ return word_score, full_name_score
119
+
120
+
121
+ def _edit_similarity(left: str, right: str) -> float:
122
+ """Return normalized edit similarity, counting adjacent transpositions."""
123
+ if not left or not right:
124
+ return float(left == right)
125
+
126
+ distances = [list(range(len(right) + 1)) for _ in range(len(left) + 1)]
127
+ for left_index in range(len(left) + 1):
128
+ distances[left_index][0] = left_index
129
+ for right_index in range(len(right) + 1):
130
+ distances[0][right_index] = right_index
131
+
132
+ for left_index in range(1, len(left) + 1):
133
+ for right_index in range(1, len(right) + 1):
134
+ cost = left[left_index - 1] != right[right_index - 1]
135
+ distances[left_index][right_index] = min(
136
+ distances[left_index - 1][right_index] + 1,
137
+ distances[left_index][right_index - 1] + 1,
138
+ distances[left_index - 1][right_index - 1] + cost,
139
+ )
140
+ if (
141
+ left_index > 1
142
+ and right_index > 1
143
+ and left[left_index - 1] == right[right_index - 2]
144
+ and left[left_index - 2] == right[right_index - 1]
145
+ ):
146
+ distances[left_index][right_index] = min(
147
+ distances[left_index][right_index],
148
+ distances[left_index - 2][right_index - 2] + 1,
149
+ )
150
+
151
+ distance = distances[-1][-1]
152
+ return 1 - distance / max(len(left), len(right))