Debian Codegraph @

emoji/unicode_codes/__init__.py

raw
1 import sys
2 import importlib.resources
3 import json
4 from functools import lru_cache
5 from warnings import warn
6
7 from typing import IO, Any, Dict, Optional, Set
8
9 from emoji.unicode_codes.data_dict import STATUS, LANGUAGES
10
11 __all__ = [
12 'get_emoji_by_name',
13 'load_from_json',
14 'EMOJI_DATA',
15 'STATUS',
16 'LANGUAGES',
17 ]
18
19 _DEFAULT_KEYS = ('en', 'alias', 'E', 'status') # The keys in emoji.json
20
21 _loaded_keys: Set[str] = set(
22 _DEFAULT_KEYS
23 ) # Keep track of keys already loaded from json files to avoid loading them twice
24
25
26 @lru_cache(maxsize=4000)
27 def get_emoji_by_name(name: str, language: str) -> Optional[str]:
28 """
29 Find emoji by short-name in a specific language.
30 Returns None if not found
31
32 :param name: emoji short code e.g. ":banana:"
33 :param language: language-code e.g. 'es', 'de', etc. or 'alias'
34 """
35
36 fully_qualified = STATUS['fully_qualified']
37
38 if language == 'alias':
39 for emj, data in EMOJI_DATA.items():
40 if name in data.get('alias', []) and data['status'] <= fully_qualified:
41 return emj
42 language = 'en'
43
44 for emj, data in EMOJI_DATA.items():
45 if data.get(language) == name and data['status'] <= fully_qualified:
46 return emj
47
48 return None
49
50
51 class EmojiDataDict(Dict[str, Any]):
52 """Replaces built-in-dict in the values of the EMOJI_DATA dict.
53 Auto loads language data when accessing language data via
54 key-access without prior loading of the language:
55 e.g. EMOJI_DATA['👌']['fr'] will auto load French language and not throw
56 a KeyError.
57 Shows a deprecation warning explainging that `emoji.config.load_language()`
58 should be used."""
59
60 def __missing__(self, key: str) -> str:
61 """Auto load language `key`, raises KeyError if language is no supported."""
62 if key in LANGUAGES and key not in _loaded_keys:
63 load_from_json(key)
64 if key in self:
65 warn(
66 f"""Use emoji.config.load_language('{key}') before accesing EMOJI_DATA[emj]['{key}'].
67 Accessing EMOJI_DATA[emj]['{key}'] without loading the language is deprecated.""",
68 DeprecationWarning,
69 stacklevel=3,
70 )
71 return self[key] # type: ignore
72
73 raise KeyError(key)
74
75
76 EMOJI_DATA: Dict[str, Dict[str, Any]]
77
78
79 def _open_file(name: str) -> IO[bytes]:
80 if sys.version_info >= (3, 9):
81 return importlib.resources.files('emoji.unicode_codes').joinpath(name).open('rb')
82 else:
83 return importlib.resources.open_binary('emoji.unicode_codes', name)
84
85
86 def _load_default_from_json():
87 global EMOJI_DATA
88 global _loaded_keys
89
90 with _open_file('emoji.json') as f:
91 EMOJI_DATA = dict(json.load(f, object_pairs_hook=EmojiDataDict)) # type: ignore
92 _loaded_keys = set(_DEFAULT_KEYS)
93
94
95 def load_from_json(key: str):
96 """Load values from the file 'emoji_{key}.json' into EMOJI_DATA"""
97
98 if key in _loaded_keys:
99 return
100
101 if key not in LANGUAGES:
102 raise NotImplementedError('Language not supported', key)
103
104 with _open_file(f'emoji_{key}.json') as f:
105 for emj, value in json.load(f).items():
106 EMOJI_DATA[emj][key] = value # type: ignore
107
108 _loaded_keys.add(key)
109
110
111 _load_default_from_json()