2015-07-23 11:24:20 +00:00
|
|
|
from __future__ import unicode_literals
|
|
|
|
|
2014-12-24 06:42:00 +00:00
|
|
|
from libc.string cimport memset
|
2015-07-27 08:58:15 +00:00
|
|
|
from libc.stdint cimport int32_t
|
2016-10-23 12:44:45 +00:00
|
|
|
from libc.math cimport sqrt
|
2014-12-19 19:54:03 +00:00
|
|
|
|
2016-11-10 21:48:48 +00:00
|
|
|
from pathlib import Path
|
2015-01-17 05:21:17 +00:00
|
|
|
import bz2
|
2016-10-20 23:44:50 +00:00
|
|
|
import ujson as json
|
2017-02-16 11:08:07 +00:00
|
|
|
import re
|
2014-12-19 19:54:03 +00:00
|
|
|
|
|
|
|
from .lexeme cimport EMPTY_LEXEME
|
2015-01-17 05:21:17 +00:00
|
|
|
from .lexeme cimport Lexeme
|
2015-01-11 23:26:22 +00:00
|
|
|
from .strings cimport hash_string
|
2015-01-31 05:38:58 +00:00
|
|
|
from .typedefs cimport attr_t
|
2015-07-22 23:18:19 +00:00
|
|
|
from .cfile cimport CFile
|
2015-08-28 00:02:33 +00:00
|
|
|
from .lemmatizer import Lemmatizer
|
2016-11-25 11:43:24 +00:00
|
|
|
from .attrs import intify_attrs
|
|
|
|
from .tokens.token cimport Token
|
2014-12-24 06:42:00 +00:00
|
|
|
|
2015-10-10 06:58:29 +00:00
|
|
|
from . import attrs
|
2015-10-10 11:12:06 +00:00
|
|
|
from . import symbols
|
2015-10-10 06:58:29 +00:00
|
|
|
|
2015-01-17 05:21:17 +00:00
|
|
|
from cymem.cymem cimport Address
|
2015-07-19 13:18:17 +00:00
|
|
|
from .serialize.packer cimport Packer
|
2016-03-16 14:53:35 +00:00
|
|
|
from .attrs cimport PROB, LANG
|
2016-09-25 12:49:53 +00:00
|
|
|
from . import util
|
2015-01-17 05:21:17 +00:00
|
|
|
|
2016-09-24 13:42:01 +00:00
|
|
|
|
2015-10-13 09:04:40 +00:00
|
|
|
try:
|
|
|
|
import copy_reg
|
|
|
|
except ImportError:
|
|
|
|
import copyreg as copy_reg
|
|
|
|
|
2014-12-24 06:42:00 +00:00
|
|
|
|
2015-01-11 23:26:22 +00:00
|
|
|
DEF MAX_VEC_SIZE = 100000
|
2014-12-24 06:42:00 +00:00
|
|
|
|
|
|
|
|
2015-01-11 23:26:22 +00:00
|
|
|
cdef float[MAX_VEC_SIZE] EMPTY_VEC
|
|
|
|
memset(EMPTY_VEC, 0, sizeof(EMPTY_VEC))
|
|
|
|
memset(&EMPTY_LEXEME, 0, sizeof(LexemeC))
|
2015-11-03 12:47:59 +00:00
|
|
|
EMPTY_LEXEME.vector = EMPTY_VEC
|
2015-01-11 23:26:22 +00:00
|
|
|
|
|
|
|
|
2014-12-19 19:54:03 +00:00
|
|
|
cdef class Vocab:
|
2015-01-11 23:26:22 +00:00
|
|
|
'''A map container for a language's LexemeC structs.
|
2014-12-19 19:54:03 +00:00
|
|
|
'''
|
2015-08-26 17:21:46 +00:00
|
|
|
@classmethod
|
2016-10-20 16:27:48 +00:00
|
|
|
def load(cls, path, lex_attr_getters=None, lemmatizer=True,
|
2016-12-21 17:04:41 +00:00
|
|
|
tag_map=True, serializer_freqs=True, oov_prob=True, **deprecated_kwargs):
|
2016-11-01 11:25:36 +00:00
|
|
|
"""
|
|
|
|
Load the vocabulary from a path.
|
|
|
|
|
|
|
|
Arguments:
|
|
|
|
path (Path):
|
|
|
|
The path to load from.
|
|
|
|
lex_attr_getters (dict):
|
|
|
|
A dictionary mapping attribute IDs to functions to compute them.
|
|
|
|
Defaults to None.
|
|
|
|
lemmatizer (object):
|
|
|
|
A lemmatizer. Defaults to None.
|
|
|
|
tag_map (dict):
|
|
|
|
A dictionary mapping fine-grained tags to coarse-grained parts-of-speech,
|
|
|
|
and optionally morphological attributes.
|
|
|
|
oov_prob (float):
|
|
|
|
The default probability for out-of-vocabulary words.
|
|
|
|
Returns:
|
|
|
|
Vocab: The newly constructed vocab object.
|
|
|
|
"""
|
2016-11-10 21:48:48 +00:00
|
|
|
if isinstance(path, basestring):
|
|
|
|
path = Path(path)
|
2016-09-25 12:49:53 +00:00
|
|
|
util.check_renamed_kwargs({'get_lex_attr': 'lex_attr_getters'}, deprecated_kwargs)
|
2016-10-20 16:27:48 +00:00
|
|
|
if 'vectors' in deprecated_kwargs:
|
|
|
|
raise AttributeError(
|
|
|
|
"vectors argument to Vocab.load() deprecated. "
|
|
|
|
"Install vectors after loading.")
|
2016-09-25 12:49:53 +00:00
|
|
|
if tag_map is True and (path / 'vocab' / 'tag_map.json').exists():
|
2016-10-20 19:23:26 +00:00
|
|
|
with (path / 'vocab' / 'tag_map.json').open('r', encoding='utf8') as file_:
|
2016-09-24 18:26:17 +00:00
|
|
|
tag_map = json.load(file_)
|
2016-12-18 15:51:10 +00:00
|
|
|
elif tag_map is True:
|
|
|
|
tag_map = None
|
2016-10-19 21:38:14 +00:00
|
|
|
if lex_attr_getters is not None \
|
|
|
|
and oov_prob is True \
|
|
|
|
and (path / 'vocab' / 'oov_prob').exists():
|
2016-10-20 19:23:26 +00:00
|
|
|
with (path / 'vocab' / 'oov_prob').open('r', encoding='utf8') as file_:
|
2016-10-19 21:38:14 +00:00
|
|
|
oov_prob = float(file_.read())
|
|
|
|
lex_attr_getters[PROB] = lambda text: oov_prob
|
2016-09-24 18:26:17 +00:00
|
|
|
if lemmatizer is True:
|
2016-09-24 13:42:01 +00:00
|
|
|
lemmatizer = Lemmatizer.load(path)
|
2016-09-25 12:49:53 +00:00
|
|
|
if serializer_freqs is True and (path / 'vocab' / 'serializer.json').exists():
|
2016-10-20 19:23:26 +00:00
|
|
|
with (path / 'vocab' / 'serializer.json').open('r', encoding='utf8') as file_:
|
2016-09-24 18:26:17 +00:00
|
|
|
serializer_freqs = json.load(file_)
|
2016-12-21 17:05:23 +00:00
|
|
|
else:
|
|
|
|
serializer_freqs = None
|
2015-12-07 05:01:28 +00:00
|
|
|
|
2016-09-25 12:49:53 +00:00
|
|
|
cdef Vocab self = cls(lex_attr_getters=lex_attr_getters, tag_map=tag_map,
|
2015-09-10 13:22:48 +00:00
|
|
|
lemmatizer=lemmatizer, serializer_freqs=serializer_freqs)
|
2015-08-28 01:44:54 +00:00
|
|
|
|
2016-10-20 19:23:26 +00:00
|
|
|
with (path / 'vocab' / 'strings.json').open('r', encoding='utf8') as file_:
|
2015-12-29 17:00:48 +00:00
|
|
|
self.strings.load(file_)
|
2016-09-24 13:42:01 +00:00
|
|
|
self.load_lexemes(path / 'vocab' / 'lexemes.bin')
|
2015-08-26 17:21:46 +00:00
|
|
|
return self
|
2015-07-22 23:18:19 +00:00
|
|
|
|
2016-09-25 12:49:53 +00:00
|
|
|
def __init__(self, lex_attr_getters=None, tag_map=None, lemmatizer=None,
|
|
|
|
serializer_freqs=None, **deprecated_kwargs):
|
2016-11-01 11:25:36 +00:00
|
|
|
'''Create the vocabulary.
|
|
|
|
|
|
|
|
lex_attr_getters (dict):
|
|
|
|
A dictionary mapping attribute IDs to functions to compute them.
|
|
|
|
Defaults to None.
|
|
|
|
lemmatizer (object):
|
|
|
|
A lemmatizer. Defaults to None.
|
|
|
|
tag_map (dict):
|
|
|
|
A dictionary mapping fine-grained tags to coarse-grained parts-of-speech,
|
|
|
|
and optionally morphological attributes.
|
|
|
|
oov_prob (float):
|
|
|
|
The default probability for out-of-vocabulary words.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
Vocab: The newly constructed vocab object.
|
|
|
|
'''
|
2016-09-25 12:49:53 +00:00
|
|
|
util.check_renamed_kwargs({'get_lex_attr': 'lex_attr_getters'}, deprecated_kwargs)
|
2016-12-21 17:04:41 +00:00
|
|
|
|
2016-09-25 12:49:53 +00:00
|
|
|
lex_attr_getters = lex_attr_getters if lex_attr_getters is not None else {}
|
|
|
|
tag_map = tag_map if tag_map is not None else {}
|
|
|
|
if lemmatizer in (None, True, False):
|
2015-09-10 12:49:10 +00:00
|
|
|
lemmatizer = Lemmatizer({}, {}, {})
|
2016-09-25 12:49:53 +00:00
|
|
|
serializer_freqs = serializer_freqs if serializer_freqs is not None else {}
|
|
|
|
|
2015-09-10 12:49:10 +00:00
|
|
|
self.mem = Pool()
|
|
|
|
self._by_hash = PreshMap()
|
|
|
|
self._by_orth = PreshMap()
|
|
|
|
self.strings = StringStore()
|
2015-10-06 13:39:50 +00:00
|
|
|
# Load strings in a special order, so that we have an onset number for
|
|
|
|
# the vocabulary. This way, when words are added in order, the orth ID
|
|
|
|
# is the frequency rank of the word, plus a certain offset. The structural
|
|
|
|
# strings are loaded first, because the vocab is open-class, and these
|
|
|
|
# symbols are closed class.
|
2016-09-24 13:42:01 +00:00
|
|
|
# TODO: Actually this has turned out to be a pain in the ass...
|
|
|
|
# It means the data is invalidated when we add a symbol :(
|
|
|
|
# Need to rethink this.
|
2015-10-10 11:12:06 +00:00
|
|
|
for name in symbols.NAMES + list(sorted(tag_map.keys())):
|
2015-10-10 07:27:03 +00:00
|
|
|
if name:
|
2016-09-30 18:10:30 +00:00
|
|
|
_ = self.strings[name]
|
2016-09-25 12:49:53 +00:00
|
|
|
self.lex_attr_getters = lex_attr_getters
|
2015-09-10 12:49:10 +00:00
|
|
|
self.morphology = Morphology(self.strings, tag_map, lemmatizer)
|
2015-09-10 13:22:48 +00:00
|
|
|
self.serializer_freqs = serializer_freqs
|
2016-12-21 17:04:41 +00:00
|
|
|
|
2015-09-10 12:49:10 +00:00
|
|
|
self.length = 1
|
|
|
|
self._serializer = None
|
2016-12-21 17:04:41 +00:00
|
|
|
|
2015-07-22 23:18:19 +00:00
|
|
|
property serializer:
|
2016-10-23 15:45:44 +00:00
|
|
|
# Having the serializer live here is super messy :(
|
2015-07-22 23:18:19 +00:00
|
|
|
def __get__(self):
|
|
|
|
if self._serializer is None:
|
2015-09-10 13:22:48 +00:00
|
|
|
self._serializer = Packer(self, self.serializer_freqs)
|
2015-07-22 23:18:19 +00:00
|
|
|
return self._serializer
|
2015-07-19 13:18:17 +00:00
|
|
|
|
2016-03-16 14:53:35 +00:00
|
|
|
property lang:
|
|
|
|
def __get__(self):
|
|
|
|
langfunc = None
|
2016-09-25 12:49:53 +00:00
|
|
|
if self.lex_attr_getters:
|
|
|
|
langfunc = self.lex_attr_getters.get(LANG, None)
|
2016-03-16 14:53:35 +00:00
|
|
|
return langfunc('_') if langfunc else ''
|
|
|
|
|
2014-12-19 19:54:03 +00:00
|
|
|
def __len__(self):
|
2014-12-27 07:45:16 +00:00
|
|
|
"""The current number of lexemes stored."""
|
2015-07-18 20:42:15 +00:00
|
|
|
return self.length
|
2014-12-19 19:54:03 +00:00
|
|
|
|
2016-10-20 23:44:50 +00:00
|
|
|
def resize_vectors(self, int new_size):
|
|
|
|
'''
|
|
|
|
Set vectors_length to a new size, and allocate more memory for the Lexeme
|
|
|
|
vectors if necessary. The memory will be zeroed.
|
2016-11-01 11:25:36 +00:00
|
|
|
|
|
|
|
Arguments:
|
2016-12-21 17:04:41 +00:00
|
|
|
new_size (int): The new size of the vectors.
|
2016-10-20 23:44:50 +00:00
|
|
|
'''
|
|
|
|
cdef hash_t key
|
|
|
|
cdef size_t addr
|
|
|
|
if new_size > self.vectors_length:
|
|
|
|
for key, addr in self._by_hash.items():
|
|
|
|
lex = <LexemeC*>addr
|
|
|
|
lex.vector = <float*>self.mem.realloc(lex.vector,
|
|
|
|
new_size * sizeof(lex.vector[0]))
|
|
|
|
self.vectors_length = new_size
|
|
|
|
|
2016-10-14 10:15:38 +00:00
|
|
|
def add_flag(self, flag_getter, int flag_id=-1):
|
2016-11-01 11:25:36 +00:00
|
|
|
'''Set a new boolean flag to words in the vocabulary.
|
2016-12-21 17:04:41 +00:00
|
|
|
|
2016-11-01 11:25:36 +00:00
|
|
|
The flag_setter function will be called over the words currently in the
|
|
|
|
vocab, and then applied to new words as they occur. You'll then be able
|
|
|
|
to access the flag value on each token, using token.check_flag(flag_id).
|
2016-12-21 17:04:41 +00:00
|
|
|
|
2016-11-01 11:25:36 +00:00
|
|
|
See also:
|
|
|
|
Lexeme.set_flag, Lexeme.check_flag, Token.set_flag, Token.check_flag.
|
2016-10-14 10:15:38 +00:00
|
|
|
|
|
|
|
Arguments:
|
|
|
|
flag_getter:
|
|
|
|
A function f(unicode) -> bool, to get the flag value.
|
|
|
|
|
|
|
|
flag_id (int):
|
|
|
|
An integer between 1 and 63 (inclusive), specifying the bit at which the
|
2016-12-21 17:04:41 +00:00
|
|
|
flag will be stored. If -1, the lowest available bit will be
|
2016-10-14 10:15:38 +00:00
|
|
|
chosen.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
flag_id (int): The integer ID by which the flag value can be checked.
|
|
|
|
'''
|
|
|
|
if flag_id == -1:
|
|
|
|
for bit in range(1, 64):
|
|
|
|
if bit not in self.lex_attr_getters:
|
|
|
|
flag_id = bit
|
|
|
|
break
|
|
|
|
else:
|
|
|
|
raise ValueError(
|
|
|
|
"Cannot find empty bit for new lexical flag. All bits between "
|
|
|
|
"0 and 63 are occupied. You can replace one by specifying the "
|
|
|
|
"flag_id explicitly, e.g. nlp.vocab.add_flag(your_func, flag_id=IS_ALPHA")
|
|
|
|
elif flag_id >= 64 or flag_id < 1:
|
|
|
|
raise ValueError(
|
|
|
|
"Invalid value for flag_id: %d. Flag IDs must be between "
|
|
|
|
"1 and 63 (inclusive)" % flag_id)
|
|
|
|
for lex in self:
|
|
|
|
lex.set_flag(flag_id, flag_getter(lex.orth_))
|
|
|
|
self.lex_attr_getters[flag_id] = flag_getter
|
|
|
|
return flag_id
|
|
|
|
|
2015-07-22 02:49:39 +00:00
|
|
|
cdef const LexemeC* get(self, Pool mem, unicode string) except NULL:
|
2015-01-11 23:26:22 +00:00
|
|
|
'''Get a pointer to a LexemeC from the lexicon, creating a new Lexeme
|
2014-12-19 19:54:03 +00:00
|
|
|
if necessary, using memory acquired from the given pool. If the pool
|
|
|
|
is the lexicon's own memory, the lexeme is saved in the lexicon.'''
|
2015-07-25 22:18:30 +00:00
|
|
|
if string == u'':
|
|
|
|
return &EMPTY_LEXEME
|
2015-01-11 23:26:22 +00:00
|
|
|
cdef LexemeC* lex
|
2015-07-22 02:49:39 +00:00
|
|
|
cdef hash_t key = hash_string(string)
|
|
|
|
lex = <LexemeC*>self._by_hash.get(key)
|
2015-08-23 18:49:18 +00:00
|
|
|
cdef size_t addr
|
2014-12-19 19:54:03 +00:00
|
|
|
if lex != NULL:
|
2016-09-30 18:20:22 +00:00
|
|
|
if lex.orth != self.strings[string]:
|
2015-10-05 23:34:59 +00:00
|
|
|
raise LookupError.mismatched_strings(
|
2015-11-05 13:48:08 +00:00
|
|
|
lex.orth, self.strings[string], self.strings[lex.orth], string)
|
2014-12-19 19:54:03 +00:00
|
|
|
return lex
|
2015-07-19 23:37:34 +00:00
|
|
|
else:
|
2015-08-22 20:04:34 +00:00
|
|
|
return self._new_lexeme(mem, string)
|
2014-12-19 19:54:03 +00:00
|
|
|
|
2015-07-22 23:18:19 +00:00
|
|
|
cdef const LexemeC* get_by_orth(self, Pool mem, attr_t orth) except NULL:
|
|
|
|
'''Get a pointer to a LexemeC from the lexicon, creating a new Lexeme
|
|
|
|
if necessary, using memory acquired from the given pool. If the pool
|
|
|
|
is the lexicon's own memory, the lexeme is saved in the lexicon.'''
|
2015-07-26 17:26:41 +00:00
|
|
|
if orth == 0:
|
2015-07-26 16:39:27 +00:00
|
|
|
return &EMPTY_LEXEME
|
2015-07-22 23:18:19 +00:00
|
|
|
cdef LexemeC* lex
|
|
|
|
lex = <LexemeC*>self._by_orth.get(orth)
|
|
|
|
if lex != NULL:
|
|
|
|
return lex
|
2015-08-22 20:04:34 +00:00
|
|
|
else:
|
2016-09-30 18:10:30 +00:00
|
|
|
return self._new_lexeme(mem, self.strings[orth])
|
2015-08-22 20:04:34 +00:00
|
|
|
|
|
|
|
cdef const LexemeC* _new_lexeme(self, Pool mem, unicode string) except NULL:
|
2015-08-23 18:49:18 +00:00
|
|
|
cdef hash_t key
|
2016-12-27 20:03:45 +00:00
|
|
|
if len(string) < 3 or self.length < 10000:
|
2016-09-30 18:10:30 +00:00
|
|
|
mem = self.mem
|
2016-12-27 20:03:45 +00:00
|
|
|
cdef bint is_oov = mem is not self.mem
|
2016-09-30 18:10:30 +00:00
|
|
|
lex = <LexemeC*>mem.alloc(sizeof(LexemeC), 1)
|
2016-09-30 18:20:22 +00:00
|
|
|
lex.orth = self.strings[string]
|
2015-08-26 17:21:46 +00:00
|
|
|
lex.length = len(string)
|
2015-08-23 18:49:18 +00:00
|
|
|
lex.id = self.length
|
2016-09-30 18:10:30 +00:00
|
|
|
lex.vector = <float*>mem.alloc(self.vectors_length, sizeof(float))
|
2016-09-25 12:49:53 +00:00
|
|
|
if self.lex_attr_getters is not None:
|
|
|
|
for attr, func in self.lex_attr_getters.items():
|
2015-08-23 18:49:18 +00:00
|
|
|
value = func(string)
|
|
|
|
if isinstance(value, unicode):
|
2016-09-30 18:20:22 +00:00
|
|
|
value = self.strings[value]
|
2015-08-26 17:21:46 +00:00
|
|
|
if attr == PROB:
|
|
|
|
lex.prob = value
|
2016-10-09 10:24:24 +00:00
|
|
|
elif value is not None:
|
2015-08-26 17:21:46 +00:00
|
|
|
Lexeme.set_struct_attr(lex, attr, value)
|
2016-09-30 18:10:30 +00:00
|
|
|
if is_oov:
|
2015-07-22 23:18:19 +00:00
|
|
|
lex.id = 0
|
|
|
|
else:
|
2015-08-23 18:49:18 +00:00
|
|
|
key = hash_string(string)
|
2015-08-22 20:04:34 +00:00
|
|
|
self._add_lex_to_vocab(key, lex)
|
|
|
|
assert lex != NULL, string
|
2015-07-22 23:18:19 +00:00
|
|
|
return lex
|
|
|
|
|
2015-01-13 13:03:48 +00:00
|
|
|
cdef int _add_lex_to_vocab(self, hash_t key, const LexemeC* lex) except -1:
|
2015-07-18 20:42:15 +00:00
|
|
|
self._by_hash.set(key, <void*>lex)
|
|
|
|
self._by_orth.set(lex.orth, <void*>lex)
|
|
|
|
self.length += 1
|
|
|
|
|
2016-03-08 15:49:10 +00:00
|
|
|
def __contains__(self, unicode string):
|
2016-11-01 11:25:36 +00:00
|
|
|
'''Check whether the string has an entry in the vocabulary.
|
|
|
|
|
|
|
|
Arguments:
|
|
|
|
string (unicode): The ID string.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
bool Whether the string has an entry in the vocabulary.
|
|
|
|
'''
|
2016-03-08 15:49:10 +00:00
|
|
|
key = hash_string(string)
|
|
|
|
lex = self._by_hash.get(key)
|
2017-01-11 09:18:22 +00:00
|
|
|
return lex is not NULL
|
2016-03-08 15:49:10 +00:00
|
|
|
|
2015-07-18 20:42:15 +00:00
|
|
|
def __iter__(self):
|
2016-11-01 11:25:36 +00:00
|
|
|
'''Iterate over the lexemes in the vocabulary.
|
|
|
|
|
|
|
|
Yields: Lexeme An entry in the vocabulary.
|
|
|
|
'''
|
2015-07-18 20:42:15 +00:00
|
|
|
cdef attr_t orth
|
|
|
|
cdef size_t addr
|
|
|
|
for orth, addr in self._by_orth.items():
|
2015-08-23 18:49:18 +00:00
|
|
|
yield Lexeme(self, orth)
|
2015-01-13 13:03:48 +00:00
|
|
|
|
2014-12-19 19:54:03 +00:00
|
|
|
def __getitem__(self, id_or_string):
|
|
|
|
'''Retrieve a lexeme, given an int ID or a unicode string. If a previously
|
2016-09-30 18:20:22 +00:00
|
|
|
unseen unicode string is given, a new lexeme is created and stored.
|
2014-12-19 19:54:03 +00:00
|
|
|
|
2016-11-01 11:25:36 +00:00
|
|
|
Arguments:
|
2015-01-14 13:33:16 +00:00
|
|
|
id_or_string (int or unicode):
|
2016-11-01 11:25:36 +00:00
|
|
|
The integer ID of a word, or its unicode string.
|
2016-12-21 17:04:41 +00:00
|
|
|
|
2016-11-01 11:25:36 +00:00
|
|
|
If an int >= Lexicon.size, IndexError is raised. If id_or_string
|
|
|
|
is neither an int nor a unicode string, ValueError is raised.
|
2014-12-19 19:54:03 +00:00
|
|
|
|
|
|
|
Returns:
|
2016-11-01 11:25:36 +00:00
|
|
|
lexeme (Lexeme): The lexeme indicated by the given ID.
|
2014-12-19 19:54:03 +00:00
|
|
|
'''
|
2015-07-18 20:42:15 +00:00
|
|
|
cdef attr_t orth
|
2016-09-30 18:10:30 +00:00
|
|
|
if type(id_or_string) == unicode:
|
2016-09-30 18:20:22 +00:00
|
|
|
orth = self.strings[id_or_string]
|
2015-01-14 13:33:16 +00:00
|
|
|
else:
|
2015-08-23 18:49:18 +00:00
|
|
|
orth = id_or_string
|
|
|
|
return Lexeme(self, orth)
|
2014-12-19 19:54:03 +00:00
|
|
|
|
2015-08-28 00:02:33 +00:00
|
|
|
cdef const TokenC* make_fused_token(self, substrings) except NULL:
|
|
|
|
cdef int i
|
|
|
|
tokens = <TokenC*>self.mem.alloc(len(substrings) + 1, sizeof(TokenC))
|
|
|
|
for i, props in enumerate(substrings):
|
2016-11-25 11:43:24 +00:00
|
|
|
props = intify_attrs(props, strings_map=self.strings, _do_deprecated=True)
|
2015-08-28 00:02:33 +00:00
|
|
|
token = &tokens[i]
|
2016-11-25 11:43:24 +00:00
|
|
|
# Set the special tokens up to have arbitrary attributes
|
|
|
|
token.lex = <LexemeC*>self.get_by_orth(self.mem, props[attrs.ORTH])
|
|
|
|
if attrs.TAG in props:
|
|
|
|
self.morphology.assign_tag(token, props[attrs.TAG])
|
|
|
|
for attr_id, value in props.items():
|
|
|
|
Token.set_struct_attr(token, attr_id, value)
|
2015-08-28 00:02:33 +00:00
|
|
|
return tokens
|
2016-12-21 17:04:41 +00:00
|
|
|
|
2014-12-19 19:54:03 +00:00
|
|
|
def dump(self, loc):
|
2016-11-01 11:25:36 +00:00
|
|
|
"""Save the lexemes binary data to the given location.
|
|
|
|
|
|
|
|
Arguments:
|
|
|
|
loc (Path): The path to save to.
|
|
|
|
"""
|
2016-09-24 19:13:15 +00:00
|
|
|
if hasattr(loc, 'as_posix'):
|
|
|
|
loc = loc.as_posix()
|
2014-12-19 19:54:03 +00:00
|
|
|
cdef bytes bytes_loc = loc.encode('utf8') if type(loc) == unicode else loc
|
2015-07-22 23:18:19 +00:00
|
|
|
|
|
|
|
cdef CFile fp = CFile(bytes_loc, 'wb')
|
2015-07-27 08:58:15 +00:00
|
|
|
cdef size_t st
|
2015-07-18 20:42:15 +00:00
|
|
|
cdef size_t addr
|
2014-12-19 19:54:03 +00:00
|
|
|
cdef hash_t key
|
2015-07-27 08:58:15 +00:00
|
|
|
for key, addr in self._by_hash.items():
|
2015-07-18 20:42:15 +00:00
|
|
|
lexeme = <LexemeC*>addr
|
2015-07-27 08:58:15 +00:00
|
|
|
fp.write_from(&lexeme.orth, sizeof(lexeme.orth), 1)
|
2015-09-08 12:23:58 +00:00
|
|
|
fp.write_from(&lexeme.flags, sizeof(lexeme.flags), 1)
|
2015-09-10 12:49:10 +00:00
|
|
|
fp.write_from(&lexeme.id, sizeof(lexeme.id), 1)
|
2015-09-08 12:23:58 +00:00
|
|
|
fp.write_from(&lexeme.length, sizeof(lexeme.length), 1)
|
|
|
|
fp.write_from(&lexeme.orth, sizeof(lexeme.orth), 1)
|
|
|
|
fp.write_from(&lexeme.lower, sizeof(lexeme.lower), 1)
|
|
|
|
fp.write_from(&lexeme.norm, sizeof(lexeme.norm), 1)
|
|
|
|
fp.write_from(&lexeme.shape, sizeof(lexeme.shape), 1)
|
|
|
|
fp.write_from(&lexeme.prefix, sizeof(lexeme.prefix), 1)
|
|
|
|
fp.write_from(&lexeme.suffix, sizeof(lexeme.suffix), 1)
|
|
|
|
fp.write_from(&lexeme.cluster, sizeof(lexeme.cluster), 1)
|
|
|
|
fp.write_from(&lexeme.prob, sizeof(lexeme.prob), 1)
|
|
|
|
fp.write_from(&lexeme.sentiment, sizeof(lexeme.sentiment), 1)
|
|
|
|
fp.write_from(&lexeme.l2_norm, sizeof(lexeme.l2_norm), 1)
|
2016-03-10 12:01:34 +00:00
|
|
|
fp.write_from(&lexeme.lang, sizeof(lexeme.lang), 1)
|
2015-07-22 23:18:19 +00:00
|
|
|
fp.close()
|
2014-12-19 19:54:03 +00:00
|
|
|
|
2015-10-22 10:13:03 +00:00
|
|
|
def load_lexemes(self, loc):
|
2016-11-01 11:25:36 +00:00
|
|
|
'''Load the binary vocabulary data from the given location.
|
|
|
|
|
|
|
|
Arguments:
|
|
|
|
loc (Path): The path to load from.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
None
|
|
|
|
'''
|
2016-09-24 18:26:17 +00:00
|
|
|
fp = CFile(loc, 'rb',
|
|
|
|
on_open_error=lambda: IOError('LexemeCs file not found at %s' % loc))
|
2015-07-27 08:58:15 +00:00
|
|
|
cdef LexemeC* lexeme
|
2014-12-19 19:54:03 +00:00
|
|
|
cdef hash_t key
|
2015-01-31 05:38:58 +00:00
|
|
|
cdef unicode py_str
|
2015-09-09 12:33:26 +00:00
|
|
|
cdef attr_t orth
|
2015-09-09 09:49:51 +00:00
|
|
|
assert sizeof(orth) == sizeof(lexeme.orth)
|
2015-07-27 08:58:15 +00:00
|
|
|
i = 0
|
|
|
|
while True:
|
2015-09-08 12:23:58 +00:00
|
|
|
try:
|
|
|
|
fp.read_into(&orth, 1, sizeof(orth))
|
|
|
|
except IOError:
|
2015-07-27 08:58:15 +00:00
|
|
|
break
|
2015-09-09 12:33:26 +00:00
|
|
|
lexeme = <LexemeC*>self.mem.alloc(sizeof(LexemeC), 1)
|
2015-09-08 12:23:58 +00:00
|
|
|
# Copy data from the file into the lexeme
|
|
|
|
fp.read_into(&lexeme.flags, 1, sizeof(lexeme.flags))
|
|
|
|
fp.read_into(&lexeme.id, 1, sizeof(lexeme.id))
|
|
|
|
fp.read_into(&lexeme.length, 1, sizeof(lexeme.length))
|
|
|
|
fp.read_into(&lexeme.orth, 1, sizeof(lexeme.orth))
|
|
|
|
fp.read_into(&lexeme.lower, 1, sizeof(lexeme.lower))
|
|
|
|
fp.read_into(&lexeme.norm, 1, sizeof(lexeme.norm))
|
|
|
|
fp.read_into(&lexeme.shape, 1, sizeof(lexeme.shape))
|
|
|
|
fp.read_into(&lexeme.prefix, 1, sizeof(lexeme.prefix))
|
|
|
|
fp.read_into(&lexeme.suffix, 1, sizeof(lexeme.suffix))
|
|
|
|
fp.read_into(&lexeme.cluster, 1, sizeof(lexeme.cluster))
|
|
|
|
fp.read_into(&lexeme.prob, 1, sizeof(lexeme.prob))
|
|
|
|
fp.read_into(&lexeme.sentiment, 1, sizeof(lexeme.sentiment))
|
|
|
|
fp.read_into(&lexeme.l2_norm, 1, sizeof(lexeme.l2_norm))
|
2016-03-10 12:01:34 +00:00
|
|
|
fp.read_into(&lexeme.lang, 1, sizeof(lexeme.lang))
|
2015-09-08 12:23:58 +00:00
|
|
|
|
2015-11-03 12:47:59 +00:00
|
|
|
lexeme.vector = EMPTY_VEC
|
2015-09-09 12:33:26 +00:00
|
|
|
py_str = self.strings[lexeme.orth]
|
2015-01-31 05:38:58 +00:00
|
|
|
key = hash_string(py_str)
|
2015-07-27 08:58:15 +00:00
|
|
|
self._by_hash.set(key, lexeme)
|
|
|
|
self._by_orth.set(lexeme.orth, lexeme)
|
|
|
|
self.length += 1
|
|
|
|
i += 1
|
2015-09-08 12:23:58 +00:00
|
|
|
fp.close()
|
2015-04-19 08:31:31 +00:00
|
|
|
|
2015-10-26 01:33:04 +00:00
|
|
|
def dump_vectors(self, out_loc):
|
2016-11-01 11:25:36 +00:00
|
|
|
'''Save the word vectors to a binary file.
|
|
|
|
|
|
|
|
Arguments:
|
|
|
|
loc (Path): The path to save to.
|
|
|
|
Returns:
|
|
|
|
None
|
|
|
|
'''
|
2015-10-26 01:33:04 +00:00
|
|
|
cdef int32_t vec_len = self.vectors_length
|
|
|
|
cdef int32_t word_len
|
|
|
|
cdef bytes word_str
|
|
|
|
cdef char* chars
|
2016-12-21 17:04:41 +00:00
|
|
|
|
2015-10-26 01:33:04 +00:00
|
|
|
cdef Lexeme lexeme
|
|
|
|
cdef CFile out_file = CFile(out_loc, 'wb')
|
|
|
|
for lexeme in self:
|
|
|
|
word_str = lexeme.orth_.encode('utf8')
|
2015-11-03 12:47:59 +00:00
|
|
|
vec = lexeme.c.vector
|
2015-10-26 01:33:04 +00:00
|
|
|
word_len = len(word_str)
|
|
|
|
|
|
|
|
out_file.write_from(&word_len, 1, sizeof(word_len))
|
|
|
|
out_file.write_from(&vec_len, 1, sizeof(vec_len))
|
|
|
|
|
|
|
|
chars = <char*>word_str
|
|
|
|
out_file.write_from(chars, word_len, sizeof(char))
|
|
|
|
out_file.write_from(vec, vec_len, sizeof(float))
|
|
|
|
out_file.close()
|
|
|
|
|
2015-10-11 13:51:43 +00:00
|
|
|
def load_vectors(self, file_):
|
2016-12-21 17:04:41 +00:00
|
|
|
"""Load vectors from a text-based file.
|
2016-11-01 11:25:36 +00:00
|
|
|
|
|
|
|
Arguments:
|
|
|
|
file_ (buffer): The file to read from. Entries should be separated by newlines,
|
|
|
|
and each entry should be whitespace delimited. The first value of the entry
|
|
|
|
should be the word string, and subsequent entries should be the values of the
|
|
|
|
vector.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
vec_len (int): The length of the vectors loaded.
|
|
|
|
"""
|
2015-09-17 02:58:23 +00:00
|
|
|
cdef LexemeC* lexeme
|
|
|
|
cdef attr_t orth
|
2015-09-21 08:03:08 +00:00
|
|
|
cdef int32_t vec_len = -1
|
2016-10-23 12:44:45 +00:00
|
|
|
cdef double norm = 0.0
|
2017-02-16 11:08:07 +00:00
|
|
|
|
|
|
|
whitespace_pattern = re.compile(r'\s')
|
|
|
|
|
2015-10-11 13:51:43 +00:00
|
|
|
for line_num, line in enumerate(file_):
|
2015-09-23 13:51:08 +00:00
|
|
|
pieces = line.split()
|
2017-02-16 11:08:07 +00:00
|
|
|
word_str = " " if whitespace_pattern.match(line) else pieces.pop(0)
|
2015-09-23 13:51:08 +00:00
|
|
|
if vec_len == -1:
|
|
|
|
vec_len = len(pieces)
|
|
|
|
elif vec_len != len(pieces):
|
2015-10-11 13:51:43 +00:00
|
|
|
raise VectorReadError.mismatched_sizes(file_, line_num,
|
2015-09-23 13:51:08 +00:00
|
|
|
vec_len, len(pieces))
|
|
|
|
orth = self.strings[word_str]
|
2016-09-30 18:10:30 +00:00
|
|
|
lexeme = <LexemeC*><void*>self.get_by_orth(self.mem, orth)
|
2016-10-20 16:27:48 +00:00
|
|
|
lexeme.vector = <float*>self.mem.alloc(vec_len, sizeof(float))
|
2015-09-23 13:51:08 +00:00
|
|
|
for i, val_str in enumerate(pieces):
|
2015-11-03 12:47:59 +00:00
|
|
|
lexeme.vector[i] = float(val_str)
|
2016-10-23 12:44:45 +00:00
|
|
|
norm = 0.0
|
|
|
|
for i in range(vec_len):
|
|
|
|
norm += lexeme.vector[i] * lexeme.vector[i]
|
2016-10-23 12:50:50 +00:00
|
|
|
lexeme.l2_norm = sqrt(norm)
|
2016-10-20 16:27:48 +00:00
|
|
|
self.vectors_length = vec_len
|
2015-09-21 08:03:08 +00:00
|
|
|
return vec_len
|
2015-09-17 02:58:23 +00:00
|
|
|
|
2015-09-23 13:51:08 +00:00
|
|
|
def load_vectors_from_bin_loc(self, loc):
|
2016-11-01 11:25:36 +00:00
|
|
|
"""Load vectors from the location of a binary file.
|
|
|
|
|
|
|
|
Arguments:
|
|
|
|
loc (unicode): The path of the binary file to load from.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
vec_len (int): The length of the vectors loaded.
|
|
|
|
"""
|
2015-07-22 23:18:19 +00:00
|
|
|
cdef CFile file_ = CFile(loc, b'rb')
|
2015-01-17 05:21:17 +00:00
|
|
|
cdef int32_t word_len
|
2015-09-21 08:08:32 +00:00
|
|
|
cdef int32_t vec_len = 0
|
2015-06-05 14:26:39 +00:00
|
|
|
cdef int32_t prev_vec_len = 0
|
2015-01-17 05:21:17 +00:00
|
|
|
cdef float* vec
|
|
|
|
cdef Address mem
|
2015-07-18 20:42:15 +00:00
|
|
|
cdef attr_t string_id
|
2015-01-17 05:21:17 +00:00
|
|
|
cdef bytes py_word
|
|
|
|
cdef vector[float*] vectors
|
2015-09-21 08:08:32 +00:00
|
|
|
cdef int line_num = 0
|
2015-07-22 23:18:19 +00:00
|
|
|
cdef Pool tmp_mem = Pool()
|
2015-01-17 05:21:17 +00:00
|
|
|
while True:
|
|
|
|
try:
|
2015-07-22 23:18:19 +00:00
|
|
|
file_.read_into(&word_len, sizeof(word_len), 1)
|
2015-01-17 05:21:17 +00:00
|
|
|
except IOError:
|
|
|
|
break
|
2015-07-22 23:18:19 +00:00
|
|
|
file_.read_into(&vec_len, sizeof(vec_len), 1)
|
2015-06-05 14:26:39 +00:00
|
|
|
if prev_vec_len != 0 and vec_len != prev_vec_len:
|
2015-09-21 08:08:32 +00:00
|
|
|
raise VectorReadError.mismatched_sizes(loc, line_num,
|
|
|
|
vec_len, prev_vec_len)
|
2015-06-05 14:26:39 +00:00
|
|
|
if 0 >= vec_len >= MAX_VEC_SIZE:
|
|
|
|
raise VectorReadError.bad_size(loc, vec_len)
|
2015-01-17 05:21:17 +00:00
|
|
|
|
2015-07-22 23:18:19 +00:00
|
|
|
chars = <char*>file_.alloc_read(tmp_mem, word_len, sizeof(char))
|
|
|
|
vec = <float*>file_.alloc_read(self.mem, vec_len, sizeof(float))
|
2015-01-17 05:21:17 +00:00
|
|
|
|
|
|
|
string_id = self.strings[chars[:word_len]]
|
|
|
|
while string_id >= vectors.size():
|
|
|
|
vectors.push_back(EMPTY_VEC)
|
|
|
|
assert vec != NULL
|
|
|
|
vectors[string_id] = vec
|
2015-09-21 08:08:32 +00:00
|
|
|
line_num += 1
|
2015-01-11 23:26:22 +00:00
|
|
|
cdef LexemeC* lex
|
2015-07-18 20:42:15 +00:00
|
|
|
cdef size_t lex_addr
|
2016-10-23 12:44:45 +00:00
|
|
|
cdef double norm = 0.0
|
2015-09-21 08:08:32 +00:00
|
|
|
cdef int i
|
2015-07-18 20:42:15 +00:00
|
|
|
for orth, lex_addr in self._by_orth.items():
|
|
|
|
lex = <LexemeC*>lex_addr
|
2015-01-23 19:17:03 +00:00
|
|
|
if lex.lower < vectors.size():
|
2015-11-03 12:47:59 +00:00
|
|
|
lex.vector = vectors[lex.lower]
|
2016-10-23 17:40:18 +00:00
|
|
|
norm = 0.0
|
2015-02-07 13:44:42 +00:00
|
|
|
for i in range(vec_len):
|
2016-10-23 12:44:45 +00:00
|
|
|
norm += lex.vector[i] * lex.vector[i]
|
|
|
|
lex.l2_norm = sqrt(norm)
|
2015-01-17 05:21:17 +00:00
|
|
|
else:
|
2015-11-03 12:47:59 +00:00
|
|
|
lex.vector = EMPTY_VEC
|
2016-10-20 16:27:48 +00:00
|
|
|
self.vectors_length = vec_len
|
2015-06-05 14:26:39 +00:00
|
|
|
return vec_len
|
2015-01-17 05:21:17 +00:00
|
|
|
|
|
|
|
|
|
|
|
def write_binary_vectors(in_loc, out_loc):
|
2015-07-22 23:18:19 +00:00
|
|
|
cdef CFile out_file = CFile(out_loc, 'wb')
|
2015-01-17 05:21:17 +00:00
|
|
|
cdef Address mem
|
|
|
|
cdef int32_t word_len
|
|
|
|
cdef int32_t vec_len
|
|
|
|
cdef char* chars
|
|
|
|
with bz2.BZ2File(in_loc, 'r') as file_:
|
|
|
|
for line in file_:
|
|
|
|
pieces = line.split()
|
|
|
|
word = pieces.pop(0)
|
|
|
|
mem = Address(len(pieces), sizeof(float))
|
|
|
|
vec = <float*>mem.ptr
|
|
|
|
for i, val_str in enumerate(pieces):
|
|
|
|
vec[i] = float(val_str)
|
|
|
|
|
|
|
|
word_len = len(word)
|
|
|
|
vec_len = len(pieces)
|
|
|
|
|
2015-07-22 23:18:19 +00:00
|
|
|
out_file.write_from(&word_len, 1, sizeof(word_len))
|
|
|
|
out_file.write_from(&vec_len, 1, sizeof(vec_len))
|
2015-01-17 05:21:17 +00:00
|
|
|
|
|
|
|
chars = <char*>word
|
2015-07-22 23:18:19 +00:00
|
|
|
out_file.write_from(chars, len(word), sizeof(char))
|
|
|
|
out_file.write_from(vec, vec_len, sizeof(float))
|
2015-06-05 14:26:39 +00:00
|
|
|
|
|
|
|
|
2015-10-05 23:34:59 +00:00
|
|
|
class LookupError(Exception):
|
|
|
|
@classmethod
|
|
|
|
def mismatched_strings(cls, id_, id_string, original_string):
|
|
|
|
return cls(
|
|
|
|
"Error fetching a Lexeme from the Vocab. When looking up a string, "
|
|
|
|
"the lexeme returned had an orth ID that did not match the query string. "
|
|
|
|
"This means that the cached lexeme structs are mismatched to the "
|
|
|
|
"string encoding table. The mismatched:\n"
|
|
|
|
"Query string: {query}\n"
|
|
|
|
"Orth cached: {orth_str}\n"
|
|
|
|
"ID of orth: {orth_id}".format(
|
2015-11-05 13:48:08 +00:00
|
|
|
query=repr(original_string), orth_str=repr(id_string), orth_id=id_)
|
2015-10-05 23:34:59 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
|
2015-06-05 14:26:39 +00:00
|
|
|
class VectorReadError(Exception):
|
|
|
|
@classmethod
|
2015-09-21 08:08:32 +00:00
|
|
|
def mismatched_sizes(cls, loc, line_num, prev_size, curr_size):
|
2015-06-05 14:26:39 +00:00
|
|
|
return cls(
|
2015-09-21 08:08:32 +00:00
|
|
|
"Error reading word vectors from %s on line %d.\n"
|
2015-06-05 14:26:39 +00:00
|
|
|
"All vectors must be the same size.\n"
|
|
|
|
"Prev size: %d\n"
|
2015-09-21 08:08:32 +00:00
|
|
|
"Curr size: %d" % (loc, line_num, prev_size, curr_size))
|
2015-06-05 14:26:39 +00:00
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def bad_size(cls, loc, size):
|
|
|
|
return cls(
|
|
|
|
"Error reading word vectors from %s.\n"
|
|
|
|
"Vector size: %d\n"
|
|
|
|
"Max size: %d\n"
|
|
|
|
"Min size: 1\n" % (loc, size, MAX_VEC_SIZE))
|