Debian Codegraph @

emoji/core.py

raw
1 """
2 emoji.core
3 ~~~~~~~~~~
4
5 Core components for emoji.
6
7 """
8
9 import re
10 import unicodedata
11 from typing import Any, Callable, Dict, Iterator, List, Literal, Match, Optional, Tuple, TypedDict, Union
12
13 from emoji import unicode_codes
14 from emoji.tokenizer import (
15 Token,
16 EmojiMatch,
17 EmojiMatchZWJ,
18 EmojiMatchZWJNonRGI,
19 tokenize,
20 filter_tokens,
21 )
22
23 __all__ = [
24 'emojize',
25 'demojize',
26 'analyze',
27 'config',
28 'emoji_list',
29 'distinct_emoji_list',
30 'emoji_count',
31 'replace_emoji',
32 'is_emoji',
33 'purely_emoji',
34 'version',
35 'Token',
36 'EmojiMatch',
37 'EmojiMatchZWJ',
38 'EmojiMatchZWJNonRGI',
39 ]
40
41 _DEFAULT_DELIMITER = ':'
42 # In Arabic language, the unicode character "\u0655" should be kept so we add it to the pattern below
43 _EMOJI_NAME_PATTERN = '\\w\\-&.’”“()!#*+,/«»\u0300\u0301\u0302\u0303\u0306\u0308\u030a\u0327\u064b\u064e\u064f\u0650\u0653\u0654\u3099\u30fb\u309a\u0655'
44
45
46 class _EmojiListReturn(TypedDict):
47 emoji: str
48 match_start: int
49 match_end: int
50
51
52 class config:
53 """Module-wide configuration"""
54
55 demojize_keep_zwj = True
56 """Change the behavior of :func:`emoji.demojize()` regarding
57 zero-width-joiners (ZWJ/``\\u200D``) in emoji that are not
58 "recommended for general interchange" (non-RGI).
59 It has no effect on RGI emoji.
60
61 For example this family emoji with different skin tones "👨‍👩🏿‍👧🏻‍👦🏾" contains four
62 person emoji that are joined together by three ZWJ characters:
63 ``👨\\u200D👩🏿\\u200D👧🏻\\u200D👦🏾``
64
65 If ``True``, the zero-width-joiners will be kept and :func:`emoji.emojize()` can
66 reverse the :func:`emoji.demojize()` operation:
67 ``emoji.emojize(emoji.demojize(s)) == s``
68
69 The example emoji would be converted to
70 ``:man:\\u200d:woman_dark_skin_tone:\\u200d:girl_light_skin_tone:\\u200d:boy_medium-dark_skin_tone:``
71
72 If ``False``, the zero-width-joiners will be removed and :func:`emoji.emojize()`
73 can only reverse the individual emoji: ``emoji.emojize(emoji.demojize(s)) != s``
74
75 The example emoji would be converted to
76 ``:man::woman_dark_skin_tone::girl_light_skin_tone::boy_medium-dark_skin_tone:``
77 """
78
79 replace_emoji_keep_zwj = False
80 """Change the behavior of :func:`emoji.replace_emoji()` regarding
81 zero-width-joiners (ZWJ/``\\u200D``) in emoji that are not
82 "recommended for general interchange" (non-RGI).
83 It has no effect on RGI emoji.
84
85 See :attr:`config.demojize_keep_zwj` for more information.
86 """
87
88 @staticmethod
89 def load_language(language: Union[List[str], str, None] = None):
90 """Load one or multiple languages into memory.
91 If no language is specified, all languages will be loaded.
92
93 This makes language data accessible in the :data:`EMOJI_DATA` dict.
94 For example to access a French emoji name, first load French with
95
96 ``emoji.config.load_language('fr')``
97
98 and then access it with
99
100 ``emoji.EMOJI_DATA['🏄']['fr']``
101
102 Available languages are listed in :data:`LANGUAGES`"""
103
104 languages = (
105 [language]
106 if isinstance(language, str)
107 else language
108 if language
109 else unicode_codes.LANGUAGES
110 )
111
112 for lang in languages:
113 unicode_codes.load_from_json(lang)
114
115
116 def emojize(
117 string: str,
118 delimiters: Tuple[str, str] = (_DEFAULT_DELIMITER, _DEFAULT_DELIMITER),
119 variant: Optional[Literal['text_type', 'emoji_type']] = None,
120 language: str = 'en',
121 version: Optional[float] = None,
122 handle_version: Optional[Union[str, Callable[[str, Dict[str, str]], str]]] = None,
123 ) -> str:
124 """
125 Replace emoji names in a string with Unicode codes.
126 >>> import emoji
127 >>> print(emoji.emojize("Python is fun :thumbsup:", language='alias'))
128 Python is fun 👍
129 >>> print(emoji.emojize("Python is fun :thumbs_up:"))
130 Python is fun 👍
131 >>> print(emoji.emojize("Python is fun {thumbs_up}", delimiters = ("{", "}")))
132 Python is fun 👍
133 >>> print(emoji.emojize("Python is fun :red_heart:", variant="text_type"))
134 Python is fun ❤
135 >>> print(emoji.emojize("Python is fun :red_heart:", variant="emoji_type"))
136 Python is fun ❤️ # red heart, not black heart
137
138 :param string: String contains emoji names.
139 :param delimiters: (optional) Use delimiters other than _DEFAULT_DELIMITER. Each delimiter
140 should contain at least one character that is not part of a-zA-Z0-9 and ``_-&.()!?#*+,``.
141 See ``emoji.core._EMOJI_NAME_PATTERN`` for the regular expression of unsafe characters.
142 :param variant: (optional) Choose variation selector between "base"(None), VS-15 ("text_type") and VS-16 ("emoji_type")
143 :param language: Choose language of emoji name: language code 'es', 'de', etc. or 'alias'
144 to use English aliases
145 :param version: (optional) Max version. If set to an Emoji Version,
146 all emoji above this version will be ignored.
147 :param handle_version: (optional) Replace the emoji above ``version``
148 instead of ignoring it. handle_version can be either a string or a
149 callable; If it is a callable, it's passed the Unicode emoji and the
150 data dict from :data:`EMOJI_DATA` and must return a replacement string
151 to be used::
152
153 handle_version('\\U0001F6EB', {
154 'en' : ':airplane_departure:',
155 'status' : fully_qualified,
156 'E' : 1,
157 'alias' : [':flight_departure:'],
158 'de': ':abflug:',
159 'es': ':avión_despegando:',
160 ...
161 })
162
163 :raises ValueError: if ``variant`` is neither None, 'text_type' or 'emoji_type'
164
165 """
166
167 unicode_codes.load_from_json(language)
168
169 pattern = re.compile(
170 '(%s[%s]+%s)'
171 % (re.escape(delimiters[0]), _EMOJI_NAME_PATTERN, re.escape(delimiters[1]))
172 )
173
174 def replace(match: Match[str]) -> str:
175 name = match.group(1)[len(delimiters[0]) : -len(delimiters[1])]
176 emj = unicode_codes.get_emoji_by_name(
177 _DEFAULT_DELIMITER
178 + unicodedata.normalize('NFKC', name)
179 + _DEFAULT_DELIMITER,
180 language,
181 )
182
183 if emj is None:
184 return match.group(1)
185
186 if version is not None and unicode_codes.EMOJI_DATA[emj]['E'] > version:
187 if callable(handle_version):
188 emj_data = unicode_codes.EMOJI_DATA[emj].copy()
189 emj_data['match_start'] = match.start()
190 emj_data['match_end'] = match.end()
191 return handle_version(emj, emj_data)
192
193 elif handle_version is not None:
194 return str(handle_version)
195 else:
196 return ''
197
198 if variant is None or 'variant' not in unicode_codes.EMOJI_DATA[emj]:
199 return emj
200
201 if emj[-1] == '\ufe0e' or emj[-1] == '\ufe0f':
202 # Remove an existing variant
203 emj = emj[0:-1]
204 if variant == 'text_type':
205 return emj + '\ufe0e'
206 elif variant == 'emoji_type':
207 return emj + '\ufe0f'
208 else:
209 raise ValueError(
210 "Parameter 'variant' must be either None, 'text_type' or 'emoji_type'"
211 )
212
213 return pattern.sub(replace, string)
214
215
216 def analyze(
217 string: str, non_emoji: bool = False, join_emoji: bool = True
218 ) -> Iterator[Token]:
219 """
220 Find unicode emoji in a string. Yield each emoji as a named tuple
221 :class:`Token` ``(chars, EmojiMatch)`` or :class:`Token` ``(chars, EmojiMatchZWJNonRGI)``.
222 If ``non_emoji`` is True, also yield all other characters as
223 :class:`Token` ``(char, char)`` .
224
225 :param string: String to analyze
226 :param non_emoji: If True also yield all non-emoji characters as Token(char, char)
227 :param join_emoji: If True, multiple EmojiMatch are merged into a single
228 EmojiMatchZWJNonRGI if they are separated only by a ZWJ.
229 """
230
231 return filter_tokens(
232 tokenize(string, keep_zwj=True), emoji_only=not non_emoji, join_emoji=join_emoji
233 )
234
235
236 def demojize(
237 string: str,
238 delimiters: Tuple[str, str] = (_DEFAULT_DELIMITER, _DEFAULT_DELIMITER),
239 language: str = 'en',
240 version: Optional[float] = None,
241 handle_version: Optional[Union[str, Callable[[str, Dict[str, str]], str]]] = None,
242 ) -> str:
243 """
244 Replace Unicode emoji in a string with emoji shortcodes. Useful for storage.
245 >>> import emoji
246 >>> print(emoji.emojize("Python is fun :thumbs_up:"))
247 Python is fun 👍
248 >>> print(emoji.demojize("Python is fun 👍"))
249 Python is fun :thumbs_up:
250 >>> print(emoji.demojize("icode is tricky 😯", delimiters=("__", "__")))
251 Unicode is tricky __hushed_face__
252
253 :param string: String contains Unicode characters. MUST BE UNICODE.
254 :param delimiters: (optional) User delimiters other than ``_DEFAULT_DELIMITER``
255 :param language: Choose language of emoji name: language code 'es', 'de', etc. or 'alias'
256 to use English aliases
257 :param version: (optional) Max version. If set to an Emoji Version,
258 all emoji above this version will be removed.
259 :param handle_version: (optional) Replace the emoji above ``version``
260 instead of removing it. handle_version can be either a string or a
261 callable ``handle_version(emj: str, data: dict) -> str``; If it is
262 a callable, it's passed the Unicode emoji and the data dict from
263 :data:`EMOJI_DATA` and must return a replacement string to be used.
264 The passed data is in the form of::
265
266 handle_version('\\U0001F6EB', {
267 'en' : ':airplane_departure:',
268 'status' : fully_qualified,
269 'E' : 1,
270 'alias' : [':flight_departure:'],
271 'de': ':abflug:',
272 'es': ':avión_despegando:',
273 ...
274 })
275
276 """
277
278 if language == 'alias':
279 language = 'en'
280 _use_aliases = True
281 else:
282 _use_aliases = False
283
284 unicode_codes.load_from_json(language)
285
286 def handle(emoji_match: EmojiMatch) -> str:
287 assert emoji_match.data is not None
288 if version is not None and emoji_match.data['E'] > version:
289 if callable(handle_version):
290 return handle_version(emoji_match.emoji, emoji_match.data_copy())
291 elif handle_version is not None:
292 return handle_version
293 else:
294 return ''
295 elif language in emoji_match.data:
296 if _use_aliases and 'alias' in emoji_match.data:
297 return (
298 delimiters[0] + emoji_match.data['alias'][0][1:-1] + delimiters[1]
299 )
300 else:
301 return delimiters[0] + emoji_match.data[language][1:-1] + delimiters[1]
302 else:
303 # The emoji exists, but it is not translated, so we keep the emoji
304 return emoji_match.emoji
305
306 matches = tokenize(string, keep_zwj=config.demojize_keep_zwj)
307 return ''.join(
308 str(handle(token.value)) if isinstance(token.value, EmojiMatch) else token.value
309 for token in matches
310 )
311
312
313 def replace_emoji(
314 string: str,
315 replace: Union[str, Callable[[str, Dict[str, str]], str]] = '',
316 version: float = -1,
317 ) -> str:
318 """
319 Replace Unicode emoji in a customizable string.
320
321 :param string: String contains Unicode characters. MUST BE UNICODE.
322 :param replace: (optional) replace can be either a string or a callable;
323 If it is a callable, it's passed the Unicode emoji and the data dict from
324 :data:`EMOJI_DATA` and must return a replacement string to be used.
325 replace(str, dict) -> str
326 :param version: (optional) Max version. If set to an Emoji Version,
327 only emoji above this version will be replaced.
328 """
329
330 def handle(emoji_match: EmojiMatch) -> str:
331 if version > -1:
332 assert emoji_match.data is not None
333 if emoji_match.data['E'] > version:
334 if callable(replace):
335 return replace(emoji_match.emoji, emoji_match.data_copy())
336 else:
337 return str(replace)
338 elif callable(replace):
339 return replace(emoji_match.emoji, emoji_match.data_copy())
340 elif replace is not None: # type: ignore
341 return replace
342 return emoji_match.emoji
343
344 matches = tokenize(string, keep_zwj=config.replace_emoji_keep_zwj)
345 if config.replace_emoji_keep_zwj:
346 matches = filter_tokens(matches, emoji_only=False, join_emoji=True)
347 return ''.join(
348 str(handle(m.value)) if isinstance(m.value, EmojiMatch) else m.value
349 for m in matches
350 )
351
352
353 def emoji_list(string: str) -> List[_EmojiListReturn]:
354 """
355 Returns the location and emoji in list of dict format.
356 >>> emoji.emoji_list("Hi, I am fine. 😁")
357 [{'match_start': 15, 'match_end': 16, 'emoji': '😁'}]
358 """
359
360 return [
361 {
362 'match_start': m.value.start,
363 'match_end': m.value.end,
364 'emoji': m.value.emoji,
365 }
366 for m in tokenize(string, keep_zwj=False)
367 if isinstance(m.value, EmojiMatch)
368 ]
369
370
371 def distinct_emoji_list(string: str) -> List[str]:
372 """Returns distinct list of emojis from the string."""
373 distinct_list = list({e['emoji'] for e in emoji_list(string)})
374 return distinct_list
375
376
377 def emoji_count(string: str, unique: bool = False) -> int:
378 """
379 Returns the count of emojis in a string.
380
381 :param unique: (optional) True if count only unique emojis
382 """
383 if unique:
384 return len(distinct_emoji_list(string))
385 return len(emoji_list(string))
386
387
388 def is_emoji(string: str) -> bool:
389 """
390 Returns True if the string is a single emoji, and it is "recommended for
391 general interchange" by Unicode.org.
392 """
393 return string in unicode_codes.EMOJI_DATA
394
395
396 def purely_emoji(string: str) -> bool:
397 """
398 Returns True if the string contains only emojis.
399 This might not imply that `is_emoji` for all the characters, for example,
400 if the string contains variation selectors.
401 """
402 return all(isinstance(m.value, EmojiMatch) for m in analyze(string, non_emoji=True))
403
404
405 def version(string: str) -> float:
406 """
407 Returns the Emoji Version of the emoji.
408
409 See https://www.unicode.org/reports/tr51/#Versioning for more information.
410 >>> emoji.version("😁")
411 0.6
412 >>> emoji.version(":butterfly:")
413 3
414
415 :param string: An emoji or a text containing an emoji
416 :raises ValueError: if ``string`` does not contain an emoji
417 """
418 # Try dictionary lookup
419 if string in unicode_codes.EMOJI_DATA:
420 return unicode_codes.EMOJI_DATA[string]['E']
421
422 # Try name lookup
423 emj_code = unicode_codes.get_emoji_by_name(string, 'en')
424 if emj_code and emj_code in unicode_codes.EMOJI_DATA:
425 return unicode_codes.EMOJI_DATA[emj_code]['E']
426
427 # Try to find first emoji in string
428 version: List[float] = []
429
430 def f(e: str, emoji_data: Dict[str, Any]) -> str:
431 version.append(emoji_data['E'])
432 return ''
433
434 replace_emoji(string, replace=f, version=-1)
435 if version:
436 return version[0]
437 emojize(string, language='alias', version=-1, handle_version=f)
438 if version:
439 return version[0]
440 for lang_code in unicode_codes.LANGUAGES:
441 emojize(string, language=lang_code, version=-1, handle_version=f)
442 if version:
443 return version[0]
444
445 raise ValueError('No emoji found in string')