summaryrefslogtreecommitdiffhomepage
path: root/libs/trakit/converters/country.py
blob: 5bfd6908dc61df12727f9bbb046088fd2211cd2f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import typing

from babelfish import Country, CountryReverseConverter, CountryReverseError
from babelfish.converters import CaseInsensitiveDict


class GuessCountryConverter(CountryReverseConverter):
    def __init__(self, config: typing.Mapping[str, str]):
        self.synonyms = CaseInsensitiveDict(config)

    def convert(self, alpha2):
        return str(Country(alpha2))

    def reverse(self, name: str):
        try:
            return self.synonyms[name]
        except KeyError:
            pass

        if name.isupper() and len(name) == 2:
            try:
                return Country(name).alpha2
            except ValueError:
                pass

        for conv in (Country.fromname,):
            try:
                return conv(name).alpha2
            except CountryReverseError:
                pass

        raise CountryReverseError(name)