Debian Codegraph @

emoji/tokenizer.py

raw
1 """
2 emoji.tokenizer
3 ~~~~~~~~~~~~~~~
4
5 Components for detecting and tokenizing emoji in strings.
6
7 """
8
9 from typing import List, NamedTuple, Dict, Union, Iterator, Any
10 from emoji import unicode_codes
11
12
13 __all__ = [
14 'EmojiMatch',
15 'EmojiMatchZWJ',
16 'EmojiMatchZWJNonRGI',
17 'Token',
18 'tokenize',
19 'filter_tokens',
20 ]
21
22 _ZWJ = '\u200d'
23 _SEARCH_TREE: Dict[str, Any] = {}
24
25
26 class EmojiMatch:
27 """
28 Represents a match of a "recommended for general interchange" (RGI)
29 emoji in a string.
30 """
31
32 __slots__ = ('emoji', 'start', 'end', 'data')
33
34 def __init__(
35 self, emoji: str, start: int, end: int, data: Union[Dict[str, Any], None]
36 ):
37 self.emoji = emoji
38 """The emoji substring"""
39
40 self.start = start
41 """The start index of the match in the string"""
42
43 self.end = end
44 """The end index of the match in the string"""
45
46 self.data = data
47 """The entry from :data:`EMOJI_DATA` for this emoji or ``None`` if the emoji is non-RGI"""
48
49 def data_copy(self) -> Dict[str, Any]:
50 """
51 Returns a copy of the data from :data:`EMOJI_DATA` for this match
52 with the additional keys ``match_start`` and ``match_end``.
53 """
54 if self.data:
55 emj_data = self.data.copy()
56 emj_data['match_start'] = self.start
57 emj_data['match_end'] = self.end
58 return emj_data
59 else:
60 return {'match_start': self.start, 'match_end': self.end}
61
62 def is_zwj(self) -> bool:
63 """
64 Checks if this is a ZWJ-emoji.
65
66 :returns: True if this is a ZWJ-emoji, False otherwise
67 """
68
69 return _ZWJ in self.emoji
70
71 def split(self) -> Union['EmojiMatchZWJ', 'EmojiMatch']:
72 """
73 Splits a ZWJ-emoji into its constituents.
74
75 :returns: An :class:`EmojiMatchZWJ` containing the "sub-emoji" if this is a ZWJ-emoji, otherwise self
76 """
77
78 if self.is_zwj():
79 return EmojiMatchZWJ(self)
80 else:
81 return self
82
83 def __repr__(self) -> str:
84 return f'{self.__class__.__name__}({self.emoji}, {self.start}:{self.end})'
85
86
87 class EmojiMatchZWJ(EmojiMatch):
88 """
89 Represents a match of multiple emoji in a string that were joined by
90 zero-width-joiners (ZWJ/``\\u200D``)."""
91
92 __slots__ = ('emojis',)
93
94 def __init__(self, match: EmojiMatch):
95 super().__init__(match.emoji, match.start, match.end, match.data)
96
97 self.emojis: List[EmojiMatch] = []
98 """List of sub emoji as EmojiMatch objects"""
99
100 i = match.start
101 for e in match.emoji.split(_ZWJ):
102 m = EmojiMatch(e, i, i + len(e), unicode_codes.EMOJI_DATA.get(e, None))
103 self.emojis.append(m)
104 i += len(e) + 1
105
106 def join(self) -> str:
107 """
108 Joins a ZWJ-emoji into a string
109 """
110
111 return _ZWJ.join(e.emoji for e in self.emojis)
112
113 def is_zwj(self) -> bool:
114 return True
115
116 def split(self) -> 'EmojiMatchZWJ':
117 return self
118
119 def __repr__(self) -> str:
120 return f'{self.__class__.__name__}({self.join()}, {self.start}:{self.end})'
121
122
123 class EmojiMatchZWJNonRGI(EmojiMatchZWJ):
124 """
125 Represents a match of multiple emoji in a string that were joined by
126 zero-width-joiners (ZWJ/``\\u200D``). This class is only used for emoji
127 that are not "recommended for general interchange" (non-RGI) by Unicode.org.
128 The data property of this class is always None.
129 """
130
131 def __init__(self, first_emoji_match: EmojiMatch, second_emoji_match: EmojiMatch):
132 self.emojis = [first_emoji_match, second_emoji_match]
133 """List of sub emoji as EmojiMatch objects"""
134
135 self._update()
136
137 def _update(self):
138 self.emoji = _ZWJ.join(e.emoji for e in self.emojis)
139 self.start = self.emojis[0].start
140 self.end = self.emojis[-1].end
141 self.data = None
142
143 def _add(self, next_emoji_match: EmojiMatch):
144 self.emojis.append(next_emoji_match)
145 self._update()
146
147
148 class Token(NamedTuple):
149 """
150 A named tuple containing the matched string and its :class:`EmojiMatch` object if it is an emoji
151 or a single character that is not a unicode emoji.
152 """
153
154 chars: str
155 value: Union[str, EmojiMatch]
156
157
158 def tokenize(string: str, keep_zwj: bool) -> Iterator[Token]:
159 """
160 Finds unicode emoji in a string. Yields all normal characters as a named
161 tuple :class:`Token` ``(char, char)`` and all emoji as :class:`Token` ``(chars, EmojiMatch)``.
162
163 :param string: String contains unicode characters. MUST BE UNICODE.
164 :param keep_zwj: Should ZWJ-characters (``\\u200D``) that join non-RGI emoji be
165 skipped or should be yielded as normal characters
166 :return: An iterable of tuples :class:`Token` ``(char, char)`` or :class:`Token` ``(chars, EmojiMatch)``
167 """
168
169 tree = get_search_tree()
170 EMOJI_DATA = unicode_codes.EMOJI_DATA
171 # result: [ Token(oldsubstring0, EmojiMatch), Token(char1, char1), ... ]
172 result: List[Token] = []
173 i = 0
174 length = len(string)
175 ignore: List[
176 int
177 ] = [] # index of chars in string that are skipped, i.e. the ZWJ-char in non-RGI-ZWJ-sequences
178 while i < length:
179 consumed = False
180 char = string[i]
181 if i in ignore:
182 i += 1
183 if char == _ZWJ and keep_zwj:
184 result.append(Token(char, char))
185 continue
186
187 elif char in tree:
188 j = i + 1
189 sub_tree = tree[char]
190 while j < length and string[j] in sub_tree:
191 if j in ignore:
192 break
193 sub_tree = sub_tree[string[j]]
194 j += 1
195 if 'data' in sub_tree:
196 emj_data = sub_tree['data']
197 code_points = string[i:j]
198
199 # We cannot yield the result here, we need to defer
200 # the call until we are sure that the emoji is finished
201 # i.e. we're not inside an ongoing ZWJ-sequence
202 match_obj = EmojiMatch(code_points, i, j, emj_data)
203
204 i = j - 1
205 consumed = True
206 result.append(Token(code_points, match_obj))
207
208 elif (
209 char == _ZWJ
210 and result
211 and result[-1].chars in EMOJI_DATA
212 and i > 0
213 and string[i - 1] in tree
214 ):
215 # the current char is ZWJ and the last match was an emoji
216 ignore.append(i)
217 if (
218 EMOJI_DATA[result[-1].chars]['status']
219 == unicode_codes.STATUS['component']
220 ):
221 # last match was a component, it could be ZWJ+EMOJI+COMPONENT
222 # or ZWJ+COMPONENT
223 i = i - sum(len(t.chars) for t in result[-2:])
224 if string[i] == _ZWJ:
225 # It's ZWJ+COMPONENT, move one back
226 i += 1
227 del result[-1]
228 else:
229 # It's ZWJ+EMOJI+COMPONENT, move two back
230 del result[-2:]
231 else:
232 # last match result[-1] was a normal emoji, move cursor
233 # before the emoji
234 i = i - len(result[-1].chars)
235 del result[-1]
236 continue
237
238 elif result:
239 yield from result
240 result = []
241
242 if not consumed and char != '\ufe0e' and char != '\ufe0f':
243 result.append(Token(char, char))
244 i += 1
245
246 yield from result
247
248
249 def filter_tokens(
250 matches: Iterator[Token], emoji_only: bool, join_emoji: bool
251 ) -> Iterator[Token]:
252 """
253 Filters the output of `tokenize()`
254
255 :param matches: An iterable of tuples of the form ``(match_str, result)``
256 where ``result`` is either an EmojiMatch or a string.
257 :param emoji_only: If True, only EmojiMatch are returned in the output.
258 If False all characters are returned
259 :param join_emoji: If True, multiple EmojiMatch are merged into
260 a single :class:`EmojiMatchZWJNonRGI` if they are separated only by a ZWJ.
261
262 :return: An iterable of tuples :class:`Token` ``(char, char)``,
263 :class:`Token` ``(chars, EmojiMatch)`` or :class:`Token` ``(chars, EmojiMatchZWJNonRGI)``
264 """
265
266 if not join_emoji and not emoji_only:
267 yield from matches
268 return
269
270 if not join_emoji:
271 for token in matches:
272 if token.chars != _ZWJ:
273 yield token
274 return
275
276 # Combine multiple EmojiMatch that are separated by ZWJs into
277 # a single EmojiMatchZWJNonRGI
278 previous_is_emoji = False
279 previous_is_zwj = False
280 pre_previous_is_emoji = False
281 accumulator: List[Token] = []
282 for token in matches:
283 pre_previous_is_emoji = previous_is_emoji
284 if previous_is_emoji and token.value == _ZWJ:
285 previous_is_zwj = True
286 elif isinstance(token.value, EmojiMatch):
287 if pre_previous_is_emoji and previous_is_zwj:
288 if isinstance(accumulator[-1].value, EmojiMatchZWJNonRGI):
289 accumulator[-1].value._add(token.value) # pyright: ignore [reportPrivateUsage]
290 accumulator[-1] = Token(
291 accumulator[-1].chars + _ZWJ + token.chars,
292 accumulator[-1].value,
293 )
294 else:
295 prev = accumulator.pop()
296 assert isinstance(prev.value, EmojiMatch)
297 accumulator.append(
298 Token(
299 prev.chars + _ZWJ + token.chars,
300 EmojiMatchZWJNonRGI(prev.value, token.value),
301 )
302 )
303 else:
304 accumulator.append(token)
305 previous_is_emoji = True
306 previous_is_zwj = False
307 else:
308 # Other character, not an emoji
309 previous_is_emoji = False
310 previous_is_zwj = False
311 yield from accumulator
312 if not emoji_only:
313 yield token
314 accumulator = []
315 yield from accumulator
316
317
318 def get_search_tree() -> Dict[str, Any]:
319 """
320 Generate a search tree for demojize().
321 Example of a search tree::
322
323 EMOJI_DATA =
324 {'a': {'en': ':Apple:'},
325 'b': {'en': ':Bus:'},
326 'ba': {'en': ':Bat:'},
327 'band': {'en': ':Beatles:'},
328 'bandit': {'en': ':Outlaw:'},
329 'bank': {'en': ':BankOfEngland:'},
330 'bb': {'en': ':BB-gun:'},
331 'c': {'en': ':Car:'}}
332
333 _SEARCH_TREE =
334 {'a': {'data': {'en': ':Apple:'}},
335 'b': {'a': {'data': {'en': ':Bat:'},
336 'n': {'d': {'data': {'en': ':Beatles:'},
337 'i': {'t': {'data': {'en': ':Outlaw:'}}}},
338 'k': {'data': {'en': ':BankOfEngland:'}}}},
339 'b': {'data': {'en': ':BB-gun:'}},
340 'data': {'en': ':Bus:'}},
341 'c': {'data': {'en': ':Car:'}}}
342
343 _SEARCH_TREE
344 / | ⧵
345 / | ⧵
346 a b c
347 | / | ⧵ |
348 | / | ⧵ |
349 :Apple: ba :Bus: bb :Car:
350 / ⧵ |
351 / ⧵ |
352 :Bat: ban :BB-gun:
353 / ⧵
354 / ⧵
355 band bank
356 / ⧵ |
357 / ⧵ |
358 bandi :Beatles: :BankOfEngland:
359 |
360 bandit
361 |
362 :Outlaw:
363
364
365 """
366 if not _SEARCH_TREE:
367 for emj in unicode_codes.EMOJI_DATA:
368 sub_tree = _SEARCH_TREE
369 lastidx = len(emj) - 1
370 for i, char in enumerate(emj):
371 if char not in sub_tree:
372 sub_tree[char] = {}
373 sub_tree = sub_tree[char]
374 if i == lastidx:
375 sub_tree['data'] = unicode_codes.EMOJI_DATA[emj]
376 return _SEARCH_TREE