2014-12-19 20:54:49 +00:00
|
|
|
# cython: embedsignature=True
|
|
|
|
from __future__ import unicode_literals
|
|
|
|
|
2014-12-21 20:25:43 +00:00
|
|
|
import re
|
2016-09-24 13:42:01 +00:00
|
|
|
import pathlib
|
2014-12-20 18:36:29 +00:00
|
|
|
|
2014-12-19 20:54:49 +00:00
|
|
|
from cython.operator cimport dereference as deref
|
|
|
|
from cython.operator cimport preincrement as preinc
|
2015-07-22 02:49:39 +00:00
|
|
|
from cpython cimport Py_UNICODE_ISSPACE
|
2014-12-19 20:54:49 +00:00
|
|
|
|
2016-09-24 13:42:01 +00:00
|
|
|
|
|
|
|
try:
|
|
|
|
import ujson as json
|
|
|
|
except ImportError:
|
|
|
|
import json
|
|
|
|
|
|
|
|
|
2014-12-19 20:54:49 +00:00
|
|
|
from cymem.cymem cimport Pool
|
|
|
|
from preshed.maps cimport PreshMap
|
|
|
|
|
2015-07-22 02:49:39 +00:00
|
|
|
from .strings cimport hash_string
|
|
|
|
cimport cython
|
2014-12-19 20:54:49 +00:00
|
|
|
|
|
|
|
from . import util
|
2015-07-13 18:20:58 +00:00
|
|
|
from .tokens.doc cimport Doc
|
2014-12-19 20:54:49 +00:00
|
|
|
|
|
|
|
|
|
|
|
cdef class Tokenizer:
|
2016-09-24 13:42:01 +00:00
|
|
|
@classmethod
|
|
|
|
def load(cls, path, Vocab vocab, rules=None, prefix_search=None, suffix_search=None,
|
|
|
|
infix_finditer=None):
|
|
|
|
'''Load a Tokenizer, reading unsupplied components from the path.
|
|
|
|
|
|
|
|
Arguments:
|
|
|
|
path pathlib.Path (or string, or Path-like)
|
|
|
|
vocab Vocab
|
|
|
|
rules dict
|
|
|
|
prefix_search callable -- Signature of re.compile(string).search
|
|
|
|
suffix_search callable -- Signature of re.compile(string).search
|
|
|
|
infix_finditer callable -- Signature of re.compile(string).finditer
|
|
|
|
'''
|
|
|
|
if isinstance(path, basestring):
|
|
|
|
path = pathlib.Path(path)
|
|
|
|
|
|
|
|
if rules is None:
|
2016-10-20 23:44:20 +00:00
|
|
|
with (path / 'tokenizer' / 'specials.json').open('r', encoding='utf8') as file_:
|
2016-09-24 13:42:01 +00:00
|
|
|
rules = json.load(file_)
|
2016-09-25 12:49:53 +00:00
|
|
|
if prefix_search in (None, True):
|
|
|
|
with (path / 'tokenizer' / 'prefix.txt').open() as file_:
|
|
|
|
entries = file_.read().split('\n')
|
|
|
|
prefix_search = util.compile_prefix_regex(entries).search
|
|
|
|
if suffix_search in (None, True):
|
|
|
|
with (path / 'tokenizer' / 'suffix.txt').open() as file_:
|
|
|
|
entries = file_.read().split('\n')
|
|
|
|
suffix_search = util.compile_suffix_regex(entries).search
|
|
|
|
if infix_finditer in (None, True):
|
|
|
|
with (path / 'tokenizer' / 'infix.txt').open() as file_:
|
|
|
|
entries = file_.read().split('\n')
|
|
|
|
infix_finditer = util.compile_infix_regex(entries).finditer
|
2016-09-24 13:42:01 +00:00
|
|
|
return cls(vocab, rules, prefix_search, suffix_search, infix_finditer)
|
|
|
|
|
|
|
|
|
|
|
|
def __init__(self, Vocab vocab, rules, prefix_search, suffix_search, infix_finditer):
|
|
|
|
'''Create a Tokenizer, to create Doc objects given unicode text.
|
|
|
|
|
|
|
|
Arguments:
|
|
|
|
vocab Vocab
|
|
|
|
rules dict
|
|
|
|
prefix_search callable -- Signature of re.compile(string).search
|
|
|
|
suffix_search callable -- Signature of re.compile(string).search
|
|
|
|
infix_finditer callable -- Signature of re.compile(string).finditer
|
|
|
|
'''
|
2014-12-19 20:54:49 +00:00
|
|
|
self.mem = Pool()
|
|
|
|
self._cache = PreshMap()
|
|
|
|
self._specials = PreshMap()
|
2016-09-24 13:42:01 +00:00
|
|
|
self.prefix_search = prefix_search
|
|
|
|
self.suffix_search = suffix_search
|
|
|
|
self.infix_finditer = infix_finditer
|
2014-12-21 20:25:43 +00:00
|
|
|
self.vocab = vocab
|
2016-04-13 08:38:26 +00:00
|
|
|
self._rules = {}
|
|
|
|
for chunk, substrings in sorted(rules.items()):
|
|
|
|
self.add_special_case(chunk, substrings)
|
2015-10-24 05:18:47 +00:00
|
|
|
|
|
|
|
def __reduce__(self):
|
2016-09-25 12:49:53 +00:00
|
|
|
args = (self.vocab,
|
|
|
|
self._rules,
|
2015-10-24 05:18:47 +00:00
|
|
|
self._prefix_re,
|
|
|
|
self._suffix_re,
|
|
|
|
self._infix_re)
|
|
|
|
|
|
|
|
return (self.__class__, args, None, None)
|
2016-09-24 13:42:01 +00:00
|
|
|
|
2015-07-08 16:53:00 +00:00
|
|
|
cpdef Doc tokens_from_list(self, list strings):
|
2015-07-13 19:46:02 +00:00
|
|
|
cdef Doc tokens = Doc(self.vocab)
|
|
|
|
if sum([len(s) for s in strings]) == 0:
|
2014-12-19 20:54:49 +00:00
|
|
|
return tokens
|
|
|
|
cdef unicode py_string
|
|
|
|
cdef int idx = 0
|
|
|
|
for i, py_string in enumerate(strings):
|
2015-07-13 19:46:02 +00:00
|
|
|
# Note that we pass tokens.mem here --- the Doc object has ownership
|
|
|
|
tokens.push_back(
|
2015-07-22 02:49:39 +00:00
|
|
|
<const LexemeC*>self.vocab.get(tokens.mem, py_string), True)
|
2014-12-19 20:54:49 +00:00
|
|
|
idx += len(py_string) + 1
|
|
|
|
return tokens
|
|
|
|
|
2015-07-22 02:49:39 +00:00
|
|
|
@cython.boundscheck(False)
|
2015-01-17 05:21:17 +00:00
|
|
|
def __call__(self, unicode string):
|
2014-12-19 20:54:49 +00:00
|
|
|
"""Tokenize a string.
|
|
|
|
|
|
|
|
The tokenization rules are defined in three places:
|
|
|
|
|
|
|
|
* The data/<lang>/tokenization table, which handles special cases like contractions;
|
|
|
|
* The data/<lang>/prefix file, used to build a regex to split off prefixes;
|
|
|
|
* The data/<lang>/suffix file, used to build a regex to split off suffixes.
|
|
|
|
|
|
|
|
The string is first split on whitespace. To tokenize a whitespace-delimited
|
|
|
|
chunk, we first try to look it up in the special-cases. If it's not found,
|
|
|
|
we split off a prefix, and then try again. If it's still not found, we
|
|
|
|
split off a suffix, and repeat.
|
|
|
|
|
|
|
|
Args:
|
2015-04-19 08:31:31 +00:00
|
|
|
string (unicode): The string to be tokenized.
|
2014-12-19 20:54:49 +00:00
|
|
|
|
|
|
|
Returns:
|
2015-07-08 16:53:00 +00:00
|
|
|
tokens (Doc): A Doc object, giving access to a sequence of LexemeCs.
|
2014-12-19 20:54:49 +00:00
|
|
|
"""
|
2015-10-15 17:54:16 +00:00
|
|
|
if len(string) >= (2 ** 30):
|
|
|
|
raise ValueError(
|
|
|
|
"String is too long: %d characters. Max is 2**30." % len(string)
|
|
|
|
)
|
2014-12-19 20:54:49 +00:00
|
|
|
cdef int length = len(string)
|
2015-07-13 19:46:02 +00:00
|
|
|
cdef Doc tokens = Doc(self.vocab)
|
2014-12-19 20:54:49 +00:00
|
|
|
if length == 0:
|
|
|
|
return tokens
|
|
|
|
cdef int i = 0
|
|
|
|
cdef int start = 0
|
|
|
|
cdef bint cache_hit
|
2016-05-04 13:53:36 +00:00
|
|
|
cdef bint in_ws = string[0].isspace()
|
2015-07-22 02:49:39 +00:00
|
|
|
cdef unicode span
|
|
|
|
# The task here is much like string.split, but not quite
|
|
|
|
# We find spans of whitespace and non-space characters, and ignore
|
|
|
|
# spans that are exactly ' '. So, our sequences will all be separated
|
|
|
|
# by either ' ' or nothing.
|
2015-07-28 12:45:37 +00:00
|
|
|
for uc in string:
|
|
|
|
if uc.isspace() != in_ws:
|
2014-12-19 20:54:49 +00:00
|
|
|
if start < i:
|
2015-07-28 12:45:37 +00:00
|
|
|
# When we want to make this fast, get the data buffer once
|
|
|
|
# with PyUnicode_AS_DATA, and then maintain a start_byte
|
|
|
|
# and end_byte, so we can call hash64 directly. That way
|
|
|
|
# we don't have to create the slice when we hit the cache.
|
|
|
|
span = string[start:i]
|
|
|
|
key = hash_string(span)
|
2015-07-22 02:49:39 +00:00
|
|
|
cache_hit = self._try_cache(key, tokens)
|
2014-12-19 20:54:49 +00:00
|
|
|
if not cache_hit:
|
2015-07-28 12:45:37 +00:00
|
|
|
self._tokenize(tokens, span, key)
|
2015-07-22 11:38:45 +00:00
|
|
|
if uc == ' ':
|
2015-11-03 13:15:14 +00:00
|
|
|
tokens.c[tokens.length - 1].spacy = True
|
2015-07-22 11:38:45 +00:00
|
|
|
start = i + 1
|
|
|
|
else:
|
|
|
|
start = i
|
2016-05-04 13:53:36 +00:00
|
|
|
in_ws = not in_ws
|
2015-07-28 12:45:37 +00:00
|
|
|
i += 1
|
2014-12-19 20:54:49 +00:00
|
|
|
i += 1
|
|
|
|
if start < i:
|
2015-07-28 12:45:37 +00:00
|
|
|
span = string[start:]
|
|
|
|
key = hash_string(span)
|
2015-07-22 02:49:39 +00:00
|
|
|
cache_hit = self._try_cache(key, tokens)
|
2014-12-19 20:54:49 +00:00
|
|
|
if not cache_hit:
|
2015-07-28 12:45:37 +00:00
|
|
|
self._tokenize(tokens, span, key)
|
2016-01-16 16:08:59 +00:00
|
|
|
tokens.c[tokens.length - 1].spacy = string[-1] == ' ' and not in_ws
|
2014-12-19 20:54:49 +00:00
|
|
|
return tokens
|
|
|
|
|
2016-02-03 01:32:37 +00:00
|
|
|
def pipe(self, texts, batch_size=1000, n_threads=2):
|
|
|
|
for text in texts:
|
|
|
|
yield self(text)
|
|
|
|
|
2015-07-13 19:46:02 +00:00
|
|
|
cdef int _try_cache(self, hash_t key, Doc tokens) except -1:
|
2014-12-19 20:54:49 +00:00
|
|
|
cached = <_Cached*>self._cache.get(key)
|
|
|
|
if cached == NULL:
|
|
|
|
return False
|
|
|
|
cdef int i
|
|
|
|
if cached.is_lex:
|
2015-07-13 22:10:51 +00:00
|
|
|
for i in range(cached.length):
|
2015-07-13 19:46:02 +00:00
|
|
|
tokens.push_back(cached.data.lexemes[i], False)
|
2014-12-19 20:54:49 +00:00
|
|
|
else:
|
2015-07-13 22:10:51 +00:00
|
|
|
for i in range(cached.length):
|
2015-07-13 19:46:02 +00:00
|
|
|
tokens.push_back(&cached.data.tokens[i], False)
|
2014-12-19 20:54:49 +00:00
|
|
|
return True
|
|
|
|
|
2015-07-22 02:49:39 +00:00
|
|
|
cdef int _tokenize(self, Doc tokens, unicode span, hash_t orig_key) except -1:
|
2015-01-11 23:26:22 +00:00
|
|
|
cdef vector[LexemeC*] prefixes
|
|
|
|
cdef vector[LexemeC*] suffixes
|
2014-12-19 20:54:49 +00:00
|
|
|
cdef int orig_size
|
|
|
|
orig_size = tokens.length
|
2016-02-21 23:17:47 +00:00
|
|
|
span = self._split_affixes(tokens.mem, span, &prefixes, &suffixes)
|
2015-07-22 02:49:39 +00:00
|
|
|
self._attach_tokens(tokens, span, &prefixes, &suffixes)
|
2015-11-03 13:15:14 +00:00
|
|
|
self._save_cached(&tokens.c[orig_size], orig_key, tokens.length - orig_size)
|
2014-12-19 20:54:49 +00:00
|
|
|
|
2016-04-13 08:38:26 +00:00
|
|
|
cdef unicode _split_affixes(self, Pool mem, unicode string,
|
|
|
|
vector[const LexemeC*] *prefixes,
|
2015-07-22 02:49:39 +00:00
|
|
|
vector[const LexemeC*] *suffixes):
|
2014-12-19 20:54:49 +00:00
|
|
|
cdef size_t i
|
2015-07-22 02:49:39 +00:00
|
|
|
cdef unicode prefix
|
|
|
|
cdef unicode suffix
|
|
|
|
cdef unicode minus_pre
|
|
|
|
cdef unicode minus_suf
|
2014-12-19 20:54:49 +00:00
|
|
|
cdef size_t last_size = 0
|
2015-07-22 02:49:39 +00:00
|
|
|
while string and len(string) != last_size:
|
|
|
|
last_size = len(string)
|
|
|
|
pre_len = self.find_prefix(string)
|
2014-12-19 20:54:49 +00:00
|
|
|
if pre_len != 0:
|
2015-07-22 02:49:39 +00:00
|
|
|
prefix = string[:pre_len]
|
|
|
|
minus_pre = string[pre_len:]
|
2014-12-19 20:54:49 +00:00
|
|
|
# Check whether we've hit a special-case
|
2015-07-22 02:49:39 +00:00
|
|
|
if minus_pre and self._specials.get(hash_string(minus_pre)) != NULL:
|
|
|
|
string = minus_pre
|
2016-02-21 23:17:47 +00:00
|
|
|
prefixes.push_back(self.vocab.get(mem, prefix))
|
2014-12-19 20:54:49 +00:00
|
|
|
break
|
2015-07-22 02:49:39 +00:00
|
|
|
suf_len = self.find_suffix(string)
|
2014-12-19 20:54:49 +00:00
|
|
|
if suf_len != 0:
|
2015-07-22 02:49:39 +00:00
|
|
|
suffix = string[-suf_len:]
|
|
|
|
minus_suf = string[:-suf_len]
|
2014-12-19 20:54:49 +00:00
|
|
|
# Check whether we've hit a special-case
|
2015-07-22 02:49:39 +00:00
|
|
|
if minus_suf and (self._specials.get(hash_string(minus_suf)) != NULL):
|
|
|
|
string = minus_suf
|
2016-02-21 23:17:47 +00:00
|
|
|
suffixes.push_back(self.vocab.get(mem, suffix))
|
2014-12-19 20:54:49 +00:00
|
|
|
break
|
2015-07-22 02:49:39 +00:00
|
|
|
if pre_len and suf_len and (pre_len + suf_len) <= len(string):
|
|
|
|
string = string[pre_len:-suf_len]
|
2016-02-21 23:17:47 +00:00
|
|
|
prefixes.push_back(self.vocab.get(mem, prefix))
|
|
|
|
suffixes.push_back(self.vocab.get(mem, suffix))
|
2014-12-19 20:54:49 +00:00
|
|
|
elif pre_len:
|
2015-07-22 02:49:39 +00:00
|
|
|
string = minus_pre
|
2016-02-21 23:17:47 +00:00
|
|
|
prefixes.push_back(self.vocab.get(mem, prefix))
|
2014-12-19 20:54:49 +00:00
|
|
|
elif suf_len:
|
2015-07-22 02:49:39 +00:00
|
|
|
string = minus_suf
|
2016-02-21 23:17:47 +00:00
|
|
|
suffixes.push_back(self.vocab.get(mem, suffix))
|
2015-07-22 02:49:39 +00:00
|
|
|
if string and (self._specials.get(hash_string(string)) != NULL):
|
2014-12-19 20:54:49 +00:00
|
|
|
break
|
|
|
|
return string
|
|
|
|
|
2015-07-22 02:49:39 +00:00
|
|
|
cdef int _attach_tokens(self, Doc tokens, unicode string,
|
2015-01-11 23:26:22 +00:00
|
|
|
vector[const LexemeC*] *prefixes,
|
|
|
|
vector[const LexemeC*] *suffixes) except -1:
|
2014-12-19 20:54:49 +00:00
|
|
|
cdef bint cache_hit
|
2015-07-18 20:45:00 +00:00
|
|
|
cdef int split, end
|
2015-01-11 23:26:22 +00:00
|
|
|
cdef const LexemeC* const* lexemes
|
2015-07-13 19:46:02 +00:00
|
|
|
cdef const LexemeC* lexeme
|
2015-07-22 02:49:39 +00:00
|
|
|
cdef unicode span
|
2014-12-19 20:54:49 +00:00
|
|
|
cdef int i
|
|
|
|
if prefixes.size():
|
|
|
|
for i in range(prefixes.size()):
|
2015-07-13 19:46:02 +00:00
|
|
|
tokens.push_back(prefixes[0][i], False)
|
2015-07-22 02:49:39 +00:00
|
|
|
if string:
|
|
|
|
cache_hit = self._try_cache(hash_string(string), tokens)
|
2015-08-28 00:02:33 +00:00
|
|
|
if not cache_hit:
|
2016-04-13 08:38:26 +00:00
|
|
|
matches = self.find_infix(string)
|
|
|
|
if not matches:
|
2015-07-13 19:46:02 +00:00
|
|
|
tokens.push_back(self.vocab.get(tokens.mem, string), False)
|
2014-12-19 20:54:49 +00:00
|
|
|
else:
|
2016-04-13 08:38:26 +00:00
|
|
|
# let's say we have dyn-o-mite-dave
|
|
|
|
# the regex finds the start and end positions of the hyphens
|
|
|
|
start = 0
|
|
|
|
for match in matches:
|
|
|
|
infix_start = match.start()
|
|
|
|
infix_end = match.end()
|
2016-05-09 11:23:47 +00:00
|
|
|
if infix_start == start:
|
|
|
|
continue
|
2016-11-02 19:35:48 +00:00
|
|
|
if infix_start == infix_end:
|
|
|
|
msg = ("Tokenizer found a zero-width 'infix' token.\n"
|
|
|
|
"If you're using a built-in tokenizer, please\n"
|
|
|
|
"report this bug. If you're using a tokenizer\n"
|
|
|
|
"you developed, check your TOKENIZER_INFIXES\n"
|
|
|
|
"tuple.\n"
|
|
|
|
"String being matched: {string}\n"
|
|
|
|
"Language: {lang}")
|
|
|
|
raise ValueError(msg.format(string=string, lang=self.vocab.lang))
|
|
|
|
|
2016-04-13 08:38:26 +00:00
|
|
|
span = string[start:infix_start]
|
|
|
|
tokens.push_back(self.vocab.get(tokens.mem, span), False)
|
2015-07-18 20:45:00 +00:00
|
|
|
|
2016-04-13 08:38:26 +00:00
|
|
|
infix_span = string[infix_start:infix_end]
|
|
|
|
tokens.push_back(self.vocab.get(tokens.mem, infix_span), False)
|
|
|
|
start = infix_end
|
|
|
|
span = string[start:]
|
2015-07-22 02:49:39 +00:00
|
|
|
tokens.push_back(self.vocab.get(tokens.mem, span), False)
|
2015-01-11 23:26:22 +00:00
|
|
|
cdef vector[const LexemeC*].reverse_iterator it = suffixes.rbegin()
|
2014-12-19 20:54:49 +00:00
|
|
|
while it != suffixes.rend():
|
2015-07-13 19:46:02 +00:00
|
|
|
lexeme = deref(it)
|
2014-12-19 20:54:49 +00:00
|
|
|
preinc(it)
|
2015-07-13 19:46:02 +00:00
|
|
|
tokens.push_back(lexeme, False)
|
2014-12-19 20:54:49 +00:00
|
|
|
|
|
|
|
cdef int _save_cached(self, const TokenC* tokens, hash_t key, int n) except -1:
|
|
|
|
cdef int i
|
|
|
|
for i in range(n):
|
2015-07-18 20:45:28 +00:00
|
|
|
if tokens[i].lex.id == 0:
|
2014-12-19 20:54:49 +00:00
|
|
|
return 0
|
|
|
|
cached = <_Cached*>self.mem.alloc(1, sizeof(_Cached))
|
|
|
|
cached.length = n
|
|
|
|
cached.is_lex = True
|
2015-01-11 23:26:22 +00:00
|
|
|
lexemes = <const LexemeC**>self.mem.alloc(n, sizeof(LexemeC**))
|
2014-12-19 20:54:49 +00:00
|
|
|
for i in range(n):
|
|
|
|
lexemes[i] = tokens[i].lex
|
2015-01-11 23:26:22 +00:00
|
|
|
cached.data.lexemes = <const LexemeC* const*>lexemes
|
2014-12-19 20:54:49 +00:00
|
|
|
self._cache.set(key, cached)
|
|
|
|
|
2015-07-22 02:49:39 +00:00
|
|
|
def find_infix(self, unicode string):
|
2016-11-02 19:35:48 +00:00
|
|
|
if self.infix_finditer is None:
|
|
|
|
return 0
|
2016-09-24 13:42:01 +00:00
|
|
|
return list(self.infix_finditer(string))
|
2015-04-19 08:31:31 +00:00
|
|
|
|
2015-07-22 02:49:39 +00:00
|
|
|
def find_prefix(self, unicode string):
|
2016-11-02 19:35:48 +00:00
|
|
|
if self.prefix_search is None:
|
|
|
|
return 0
|
2016-09-24 13:42:01 +00:00
|
|
|
match = self.prefix_search(string)
|
2014-12-19 20:54:49 +00:00
|
|
|
return (match.end() - match.start()) if match is not None else 0
|
|
|
|
|
2015-07-22 02:49:39 +00:00
|
|
|
def find_suffix(self, unicode string):
|
2016-11-02 19:35:48 +00:00
|
|
|
if self.suffix_search is None:
|
|
|
|
return 0
|
2016-09-24 13:42:01 +00:00
|
|
|
match = self.suffix_search(string)
|
2014-12-19 20:54:49 +00:00
|
|
|
return (match.end() - match.start()) if match is not None else 0
|
|
|
|
|
2015-08-26 17:20:11 +00:00
|
|
|
def _load_special_tokenization(self, special_cases):
|
2016-04-13 08:38:26 +00:00
|
|
|
'''Add special-case tokenization rules.
|
2014-12-19 20:54:49 +00:00
|
|
|
'''
|
2015-08-26 17:20:11 +00:00
|
|
|
for chunk, substrings in sorted(special_cases.items()):
|
2016-04-13 08:38:26 +00:00
|
|
|
self.add_special_case(chunk, substrings)
|
|
|
|
|
|
|
|
def add_special_case(self, unicode chunk, substrings):
|
|
|
|
'''Add a special-case tokenization rule.
|
|
|
|
|
|
|
|
For instance, "don't" is special-cased to tokenize into
|
|
|
|
["do", "n't"]. The split tokens can have lemmas and part-of-speech
|
|
|
|
tags.
|
|
|
|
'''
|
|
|
|
substrings = list(substrings)
|
|
|
|
cached = <_Cached*>self.mem.alloc(1, sizeof(_Cached))
|
|
|
|
cached.length = len(substrings)
|
|
|
|
cached.is_lex = False
|
|
|
|
cached.data.tokens = self.vocab.make_fused_token(substrings)
|
|
|
|
key = hash_string(chunk)
|
|
|
|
self._specials.set(key, cached)
|
|
|
|
self._cache.set(key, cached)
|
|
|
|
self._rules[chunk] = substrings
|