2015-07-13 17:58:26 +00:00
|
|
|
cimport cython
|
|
|
|
from libc.string cimport memcpy, memset
|
2015-07-27 20:57:22 +00:00
|
|
|
from libc.stdint cimport uint32_t
|
2015-07-13 17:58:26 +00:00
|
|
|
|
|
|
|
import numpy
|
2015-09-14 07:49:58 +00:00
|
|
|
import numpy.linalg
|
2015-07-19 13:18:17 +00:00
|
|
|
import struct
|
2015-09-14 07:49:58 +00:00
|
|
|
cimport numpy as np
|
2015-09-17 01:50:11 +00:00
|
|
|
import math
|
2015-11-02 18:22:18 +00:00
|
|
|
import six
|
2016-03-10 12:01:34 +00:00
|
|
|
import warnings
|
2015-07-13 17:58:26 +00:00
|
|
|
|
2015-09-06 17:45:15 +00:00
|
|
|
from ..lexeme cimport Lexeme
|
2015-07-13 17:58:26 +00:00
|
|
|
from ..lexeme cimport EMPTY_LEXEME
|
2015-07-16 09:21:44 +00:00
|
|
|
from ..typedefs cimport attr_t, flags_t
|
|
|
|
from ..attrs cimport attr_id_t
|
2015-07-15 23:15:34 +00:00
|
|
|
from ..attrs cimport ID, ORTH, NORM, LOWER, SHAPE, PREFIX, SUFFIX, LENGTH, CLUSTER
|
|
|
|
from ..attrs cimport POS, LEMMA, TAG, DEP, HEAD, SPACY, ENT_IOB, ENT_TYPE
|
2015-07-30 00:29:49 +00:00
|
|
|
from ..parts_of_speech cimport CONJ, PUNCT, NOUN
|
2015-09-06 02:13:03 +00:00
|
|
|
from ..parts_of_speech cimport univ_pos_t
|
2015-08-23 18:49:18 +00:00
|
|
|
from ..lexeme cimport Lexeme
|
2015-11-03 12:51:05 +00:00
|
|
|
from .span cimport Span
|
2015-07-13 17:58:26 +00:00
|
|
|
from .token cimport Token
|
2015-07-19 13:18:17 +00:00
|
|
|
from ..serialize.bits cimport BitArray
|
2015-10-07 08:25:35 +00:00
|
|
|
from ..util import normalize_slice
|
2016-05-02 12:25:10 +00:00
|
|
|
from ..syntax.iterators import CHUNKERS
|
2015-07-13 17:58:26 +00:00
|
|
|
|
|
|
|
|
|
|
|
DEF PADDING = 5
|
|
|
|
|
|
|
|
|
|
|
|
cdef int bounds_check(int i, int length, int padding) except -1:
|
|
|
|
if (i + padding) < 0:
|
|
|
|
raise IndexError
|
|
|
|
if (i - padding) >= length:
|
|
|
|
raise IndexError
|
|
|
|
|
|
|
|
|
|
|
|
cdef attr_t get_token_attr(const TokenC* token, attr_id_t feat_name) nogil:
|
|
|
|
if feat_name == LEMMA:
|
|
|
|
return token.lemma
|
|
|
|
elif feat_name == POS:
|
|
|
|
return token.pos
|
|
|
|
elif feat_name == TAG:
|
|
|
|
return token.tag
|
|
|
|
elif feat_name == DEP:
|
|
|
|
return token.dep
|
2015-07-15 23:15:34 +00:00
|
|
|
elif feat_name == HEAD:
|
|
|
|
return token.head
|
|
|
|
elif feat_name == SPACY:
|
|
|
|
return token.spacy
|
|
|
|
elif feat_name == ENT_IOB:
|
|
|
|
return token.ent_iob
|
|
|
|
elif feat_name == ENT_TYPE:
|
|
|
|
return token.ent_type
|
2015-07-13 17:58:26 +00:00
|
|
|
else:
|
2015-09-06 17:45:15 +00:00
|
|
|
return Lexeme.get_struct_attr(token.lex, feat_name)
|
2015-07-13 17:58:26 +00:00
|
|
|
|
|
|
|
|
|
|
|
cdef class Doc:
|
|
|
|
"""
|
|
|
|
Container class for annotated text. Constructed via English.__call__ or
|
|
|
|
Tokenizer.__call__.
|
|
|
|
"""
|
2015-07-19 13:18:17 +00:00
|
|
|
def __init__(self, Vocab vocab, orths_and_spaces=None):
|
2015-07-13 17:58:26 +00:00
|
|
|
self.vocab = vocab
|
|
|
|
size = 20
|
|
|
|
self.mem = Pool()
|
|
|
|
# Guarantee self.lex[i-x], for any i >= 0 and x < padding is in bounds
|
|
|
|
# However, we need to remember the true starting places, so that we can
|
|
|
|
# realloc.
|
|
|
|
data_start = <TokenC*>self.mem.alloc(size + (PADDING*2), sizeof(TokenC))
|
|
|
|
cdef int i
|
|
|
|
for i in range(size + (PADDING*2)):
|
|
|
|
data_start[i].lex = &EMPTY_LEXEME
|
2015-09-09 01:39:46 +00:00
|
|
|
data_start[i].l_edge = i
|
|
|
|
data_start[i].r_edge = i
|
2015-11-03 13:15:14 +00:00
|
|
|
self.c = data_start + PADDING
|
2015-07-13 17:58:26 +00:00
|
|
|
self.max_length = size
|
|
|
|
self.length = 0
|
|
|
|
self.is_tagged = False
|
|
|
|
self.is_parsed = False
|
2015-07-13 20:28:10 +00:00
|
|
|
self._py_tokens = []
|
2015-09-17 01:50:11 +00:00
|
|
|
self._vector = None
|
2016-05-02 12:25:10 +00:00
|
|
|
self.noun_chunks_iterator = CHUNKERS.get(self.vocab.lang)
|
2015-07-17 14:39:54 +00:00
|
|
|
|
2015-07-13 17:58:26 +00:00
|
|
|
def __getitem__(self, object i):
|
2015-10-07 08:27:28 +00:00
|
|
|
"""Get a Token or a Span from the Doc.
|
2015-07-13 17:58:26 +00:00
|
|
|
|
|
|
|
Returns:
|
2015-10-07 08:27:28 +00:00
|
|
|
token (Token) or span (Span):
|
2015-07-13 17:58:26 +00:00
|
|
|
"""
|
|
|
|
if isinstance(i, slice):
|
2015-10-07 08:25:35 +00:00
|
|
|
start, stop = normalize_slice(len(self), i.start, i.stop, i.step)
|
|
|
|
return Span(self, start, stop, label=0)
|
2015-07-13 17:58:26 +00:00
|
|
|
|
|
|
|
if i < 0:
|
|
|
|
i = self.length + i
|
|
|
|
bounds_check(i, self.length, PADDING)
|
2015-07-13 22:10:11 +00:00
|
|
|
if self._py_tokens[i] is not None:
|
|
|
|
return self._py_tokens[i]
|
|
|
|
else:
|
2015-11-03 13:15:14 +00:00
|
|
|
return Token.cinit(self.vocab, &self.c[i], i, self)
|
2015-07-13 17:58:26 +00:00
|
|
|
|
|
|
|
def __iter__(self):
|
|
|
|
"""Iterate over the tokens.
|
|
|
|
|
|
|
|
Yields:
|
|
|
|
token (Token):
|
|
|
|
"""
|
2015-07-18 02:10:53 +00:00
|
|
|
cdef int i
|
2015-07-13 17:58:26 +00:00
|
|
|
for i in range(self.length):
|
2015-07-18 02:10:53 +00:00
|
|
|
if self._py_tokens[i] is not None:
|
|
|
|
yield self._py_tokens[i]
|
|
|
|
else:
|
2015-11-03 13:15:14 +00:00
|
|
|
yield Token.cinit(self.vocab, &self.c[i], i, self)
|
2015-07-13 17:58:26 +00:00
|
|
|
|
|
|
|
def __len__(self):
|
|
|
|
return self.length
|
|
|
|
|
|
|
|
def __unicode__(self):
|
2016-01-16 16:13:50 +00:00
|
|
|
return u''.join([t.text_with_ws for t in self])
|
2015-07-13 17:58:26 +00:00
|
|
|
|
2015-11-02 18:22:18 +00:00
|
|
|
def __bytes__(self):
|
2016-01-16 16:13:50 +00:00
|
|
|
return u''.join([t.text_with_ws for t in self]).encode('utf-8')
|
2015-11-02 18:22:18 +00:00
|
|
|
|
2015-07-24 01:49:30 +00:00
|
|
|
def __str__(self):
|
2015-11-02 18:22:18 +00:00
|
|
|
if six.PY3:
|
|
|
|
return self.__unicode__()
|
|
|
|
return self.__bytes__()
|
2015-07-24 01:49:30 +00:00
|
|
|
|
2015-10-21 11:11:46 +00:00
|
|
|
def __repr__(self):
|
2015-11-02 18:22:18 +00:00
|
|
|
return self.__str__()
|
2015-10-21 11:11:46 +00:00
|
|
|
|
2015-09-14 07:49:58 +00:00
|
|
|
def similarity(self, other):
|
2015-09-22 00:10:01 +00:00
|
|
|
if self.vector_norm == 0 or other.vector_norm == 0:
|
|
|
|
return 0.0
|
2015-09-14 07:49:58 +00:00
|
|
|
return numpy.dot(self.vector, other.vector) / (self.vector_norm * other.vector_norm)
|
|
|
|
|
|
|
|
property vector:
|
|
|
|
def __get__(self):
|
2015-09-17 01:50:11 +00:00
|
|
|
if self._vector is None:
|
|
|
|
self._vector = sum(t.vector for t in self) / len(self)
|
|
|
|
return self._vector
|
2015-09-14 07:49:58 +00:00
|
|
|
|
2015-09-17 01:50:11 +00:00
|
|
|
def __set__(self, value):
|
|
|
|
self._vector = value
|
2015-09-14 07:49:58 +00:00
|
|
|
|
|
|
|
property vector_norm:
|
|
|
|
def __get__(self):
|
2015-09-17 01:50:11 +00:00
|
|
|
cdef float value
|
|
|
|
if self._vector_norm is None:
|
|
|
|
self._vector_norm = 1e-20
|
|
|
|
for value in self.vector:
|
|
|
|
self._vector_norm += value * value
|
|
|
|
self._vector_norm = math.sqrt(self._vector_norm)
|
|
|
|
return self._vector_norm
|
|
|
|
|
|
|
|
def __set__(self, value):
|
|
|
|
self._vector_norm = value
|
2015-09-14 07:49:58 +00:00
|
|
|
|
2015-07-13 17:58:26 +00:00
|
|
|
@property
|
|
|
|
def string(self):
|
2016-01-16 16:13:50 +00:00
|
|
|
return self.text_with_ws
|
2015-07-13 17:58:26 +00:00
|
|
|
|
2015-09-13 00:27:42 +00:00
|
|
|
@property
|
2016-01-16 16:13:50 +00:00
|
|
|
def text_with_ws(self):
|
2015-09-13 00:27:42 +00:00
|
|
|
return u''.join([t.text_with_ws for t in self])
|
|
|
|
|
|
|
|
@property
|
|
|
|
def text(self):
|
2016-03-29 02:02:42 +00:00
|
|
|
return u''.join(t.text for t in self)
|
2015-09-13 00:27:42 +00:00
|
|
|
|
2015-08-05 22:35:40 +00:00
|
|
|
property ents:
|
|
|
|
def __get__(self):
|
|
|
|
"""Yields named-entity Span objects.
|
2015-07-13 17:58:26 +00:00
|
|
|
|
2015-08-05 22:35:40 +00:00
|
|
|
Iterate over the span to get individual Token objects, or access the label:
|
|
|
|
|
|
|
|
>>> from spacy.en import English
|
|
|
|
>>> nlp = English()
|
|
|
|
>>> tokens = nlp(u'Mr. Best flew to New York on Saturday morning.')
|
|
|
|
>>> ents = list(tokens.ents)
|
|
|
|
>>> ents[0].label, ents[0].label_, ''.join(t.orth_ for t in ents[0])
|
|
|
|
(112504, u'PERSON', u'Best ')
|
|
|
|
"""
|
|
|
|
cdef int i
|
|
|
|
cdef const TokenC* token
|
|
|
|
cdef int start = -1
|
|
|
|
cdef int label = 0
|
|
|
|
output = []
|
|
|
|
for i in range(self.length):
|
2015-11-03 13:15:14 +00:00
|
|
|
token = &self.c[i]
|
2015-08-05 22:35:40 +00:00
|
|
|
if token.ent_iob == 1:
|
|
|
|
assert start != -1
|
|
|
|
elif token.ent_iob == 2 or token.ent_iob == 0:
|
|
|
|
if start != -1:
|
|
|
|
output.append(Span(self, start, i, label=label))
|
|
|
|
start = -1
|
|
|
|
label = 0
|
|
|
|
elif token.ent_iob == 3:
|
|
|
|
if start != -1:
|
|
|
|
output.append(Span(self, start, i, label=label))
|
|
|
|
start = i
|
|
|
|
label = token.ent_type
|
|
|
|
if start != -1:
|
|
|
|
output.append(Span(self, start, self.length, label=label))
|
|
|
|
return tuple(output)
|
|
|
|
|
|
|
|
def __set__(self, ents):
|
|
|
|
# TODO:
|
|
|
|
# 1. Allow negative matches
|
|
|
|
# 2. Ensure pre-set NERs are not over-written during statistical prediction
|
|
|
|
# 3. Test basic data-driven ORTH gazetteer
|
|
|
|
# 4. Test more nuanced date and currency regex
|
|
|
|
cdef int i
|
|
|
|
for i in range(self.length):
|
2015-11-03 13:15:14 +00:00
|
|
|
self.c[i].ent_type = 0
|
|
|
|
self.c[i].ent_iob = 0
|
2015-08-05 22:35:40 +00:00
|
|
|
cdef attr_t ent_type
|
|
|
|
cdef int start, end
|
|
|
|
for ent_type, start, end in ents:
|
2015-08-06 15:28:43 +00:00
|
|
|
if ent_type is None or ent_type < 0:
|
2015-08-05 22:35:40 +00:00
|
|
|
# Mark as O
|
|
|
|
for i in range(start, end):
|
2015-11-03 13:15:14 +00:00
|
|
|
self.c[i].ent_type = 0
|
|
|
|
self.c[i].ent_iob = 2
|
2015-08-05 22:35:40 +00:00
|
|
|
else:
|
|
|
|
# Mark (inside) as I
|
|
|
|
for i in range(start, end):
|
2015-11-03 13:15:14 +00:00
|
|
|
self.c[i].ent_type = ent_type
|
|
|
|
self.c[i].ent_iob = 1
|
2015-08-05 22:35:40 +00:00
|
|
|
# Set start as B
|
2015-11-03 13:15:14 +00:00
|
|
|
self.c[start].ent_iob = 3
|
2015-07-13 17:58:26 +00:00
|
|
|
|
2016-03-10 12:01:34 +00:00
|
|
|
|
2016-05-02 12:25:10 +00:00
|
|
|
@property
|
|
|
|
def noun_chunks(self):
|
|
|
|
"""Yield spans for base noun phrases."""
|
|
|
|
if not self.is_parsed:
|
|
|
|
raise ValueError(
|
|
|
|
"noun_chunks requires the dependency parse, which "
|
|
|
|
"requires data to be installed. If you haven't done so, run: "
|
|
|
|
"\npython -m spacy.%s.download all\n"
|
|
|
|
"to install the data" % self.vocab.lang)
|
|
|
|
for start, end, label in self.noun_chunks_iterator(self):
|
|
|
|
yield Span(self, start, end, label=label)
|
2015-07-30 00:29:49 +00:00
|
|
|
|
2015-07-13 17:58:26 +00:00
|
|
|
@property
|
|
|
|
def sents(self):
|
|
|
|
"""
|
|
|
|
Yield a list of sentence Span objects, calculated from the dependency parse.
|
|
|
|
"""
|
2015-09-21 08:35:40 +00:00
|
|
|
if not self.is_parsed:
|
|
|
|
raise ValueError(
|
|
|
|
"sentence boundary detection requires the dependency parse, which "
|
|
|
|
"requires data to be installed. If you haven't done so, run: "
|
2016-03-24 10:47:09 +00:00
|
|
|
"\npython -m spacy.%s.download all\n"
|
|
|
|
"to install the data" % self.vocab.lang)
|
2015-07-13 17:58:26 +00:00
|
|
|
cdef int i
|
|
|
|
start = 0
|
|
|
|
for i in range(1, self.length):
|
2015-11-03 13:15:14 +00:00
|
|
|
if self.c[i].sent_start:
|
2015-07-13 17:58:26 +00:00
|
|
|
yield Span(self, start, i)
|
|
|
|
start = i
|
|
|
|
yield Span(self, start, self.length)
|
|
|
|
|
2015-07-13 19:46:02 +00:00
|
|
|
cdef int push_back(self, LexemeOrToken lex_or_tok, bint has_space) except -1:
|
2015-07-13 17:58:26 +00:00
|
|
|
if self.length == self.max_length:
|
|
|
|
self._realloc(self.length * 2)
|
2015-11-03 13:15:14 +00:00
|
|
|
cdef TokenC* t = &self.c[self.length]
|
2015-08-28 00:02:33 +00:00
|
|
|
if LexemeOrToken is const_TokenC_ptr:
|
2015-07-13 17:58:26 +00:00
|
|
|
t[0] = lex_or_tok[0]
|
|
|
|
else:
|
|
|
|
t.lex = lex_or_tok
|
2015-07-13 19:46:02 +00:00
|
|
|
if self.length == 0:
|
|
|
|
t.idx = 0
|
|
|
|
else:
|
|
|
|
t.idx = (t-1).idx + (t-1).lex.length + (t-1).spacy
|
2015-09-09 01:39:46 +00:00
|
|
|
t.l_edge = self.length
|
|
|
|
t.r_edge = self.length
|
2015-08-23 18:49:18 +00:00
|
|
|
assert t.lex.orth != 0
|
2015-07-13 19:46:02 +00:00
|
|
|
t.spacy = has_space
|
2015-07-13 17:58:26 +00:00
|
|
|
self.length += 1
|
2015-07-13 20:28:10 +00:00
|
|
|
self._py_tokens.append(None)
|
2015-07-13 19:46:02 +00:00
|
|
|
return t.idx + t.lex.length + t.spacy
|
2015-07-13 17:58:26 +00:00
|
|
|
|
|
|
|
@cython.boundscheck(False)
|
|
|
|
cpdef np.ndarray to_array(self, object py_attr_ids):
|
|
|
|
"""Given a list of M attribute IDs, export the tokens to a numpy ndarray
|
|
|
|
of shape N*M, where N is the length of the sentence.
|
|
|
|
|
|
|
|
Arguments:
|
|
|
|
attr_ids (list[int]): A list of attribute ID ints.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
feat_array (numpy.ndarray[long, ndim=2]):
|
|
|
|
A feature matrix, with one row per word, and one column per attribute
|
|
|
|
indicated in the input attr_ids.
|
|
|
|
"""
|
|
|
|
cdef int i, j
|
|
|
|
cdef attr_id_t feature
|
2015-07-17 19:20:48 +00:00
|
|
|
cdef np.ndarray[attr_t, ndim=2] output
|
2015-07-13 17:58:26 +00:00
|
|
|
# Make an array from the attributes --- otherwise our inner loop is Python
|
|
|
|
# dict iteration.
|
2015-07-17 19:20:48 +00:00
|
|
|
cdef np.ndarray[attr_t, ndim=1] attr_ids = numpy.asarray(py_attr_ids, dtype=numpy.int32)
|
|
|
|
output = numpy.ndarray(shape=(self.length, len(attr_ids)), dtype=numpy.int32)
|
2015-07-13 17:58:26 +00:00
|
|
|
for i in range(self.length):
|
|
|
|
for j, feature in enumerate(attr_ids):
|
2015-11-03 13:15:14 +00:00
|
|
|
output[i, j] = get_token_attr(&self.c[i], feature)
|
2015-07-13 17:58:26 +00:00
|
|
|
return output
|
|
|
|
|
2015-07-14 01:20:09 +00:00
|
|
|
def count_by(self, attr_id_t attr_id, exclude=None, PreshCounter counts=None):
|
2015-07-13 17:58:26 +00:00
|
|
|
"""Produce a dict of {attribute (int): count (ints)} frequencies, keyed
|
|
|
|
by the values of the given attribute ID.
|
|
|
|
|
2015-07-22 02:53:01 +00:00
|
|
|
>>> from spacy.en import English, attrs
|
|
|
|
>>> nlp = English()
|
|
|
|
>>> tokens = nlp(u'apple apple orange banana')
|
|
|
|
>>> tokens.count_by(attrs.ORTH)
|
|
|
|
{12800L: 1, 11880L: 2, 7561L: 1}
|
|
|
|
>>> tokens.to_array([attrs.ORTH])
|
|
|
|
array([[11880],
|
|
|
|
[11880],
|
|
|
|
[ 7561],
|
|
|
|
[12800]])
|
2015-07-13 17:58:26 +00:00
|
|
|
"""
|
|
|
|
cdef int i
|
|
|
|
cdef attr_t attr
|
|
|
|
cdef size_t count
|
2015-07-14 01:20:09 +00:00
|
|
|
|
|
|
|
if counts is None:
|
2015-09-17 01:50:11 +00:00
|
|
|
counts = PreshCounter()
|
2015-07-14 01:20:09 +00:00
|
|
|
output_dict = True
|
|
|
|
else:
|
|
|
|
output_dict = False
|
|
|
|
# Take this check out of the loop, for a bit of extra speed
|
|
|
|
if exclude is None:
|
|
|
|
for i in range(self.length):
|
2015-11-03 13:15:14 +00:00
|
|
|
counts.inc(get_token_attr(&self.c[i], attr_id), 1)
|
2015-07-14 01:20:09 +00:00
|
|
|
else:
|
|
|
|
for i in range(self.length):
|
|
|
|
if not exclude(self[i]):
|
2015-11-03 13:15:14 +00:00
|
|
|
attr = get_token_attr(&self.c[i], attr_id)
|
2015-07-14 01:20:09 +00:00
|
|
|
counts.inc(attr, 1)
|
|
|
|
if output_dict:
|
|
|
|
return dict(counts)
|
2015-07-13 17:58:26 +00:00
|
|
|
|
|
|
|
def _realloc(self, new_size):
|
|
|
|
self.max_length = new_size
|
|
|
|
n = new_size + (PADDING * 2)
|
|
|
|
# What we're storing is a "padded" array. We've jumped forward PADDING
|
|
|
|
# places, and are storing the pointer to that. This way, we can access
|
|
|
|
# words out-of-bounds, and get out-of-bounds markers.
|
|
|
|
# Now that we want to realloc, we need the address of the true start,
|
|
|
|
# so we jump the pointer back PADDING places.
|
2015-11-03 13:15:14 +00:00
|
|
|
cdef TokenC* data_start = self.c - PADDING
|
2015-07-13 17:58:26 +00:00
|
|
|
data_start = <TokenC*>self.mem.realloc(data_start, n * sizeof(TokenC))
|
2015-11-03 13:15:14 +00:00
|
|
|
self.c = data_start + PADDING
|
2015-07-13 17:58:26 +00:00
|
|
|
cdef int i
|
|
|
|
for i in range(self.length, self.max_length + PADDING):
|
2015-11-03 13:15:14 +00:00
|
|
|
self.c[i].lex = &EMPTY_LEXEME
|
2015-07-13 17:58:26 +00:00
|
|
|
|
2016-01-30 19:27:52 +00:00
|
|
|
cdef void set_parse(self, const TokenC* parsed) nogil:
|
2015-07-15 23:16:33 +00:00
|
|
|
# TODO: This method is fairly misleading atm. It's used by Parser
|
2015-07-13 17:58:26 +00:00
|
|
|
# to actually apply the parse calculated. Need to rethink this.
|
2015-07-22 02:53:01 +00:00
|
|
|
|
|
|
|
# Probably we should use from_array?
|
2015-07-13 17:58:26 +00:00
|
|
|
self.is_parsed = True
|
|
|
|
for i in range(self.length):
|
2015-11-03 13:15:14 +00:00
|
|
|
self.c[i] = parsed[i]
|
2015-07-13 17:58:26 +00:00
|
|
|
|
2015-07-22 02:53:01 +00:00
|
|
|
def from_array(self, attrs, array):
|
|
|
|
cdef int i, col
|
|
|
|
cdef attr_id_t attr_id
|
2015-11-03 13:15:14 +00:00
|
|
|
cdef TokenC* tokens = self.c
|
2015-07-22 02:53:01 +00:00
|
|
|
cdef int length = len(array)
|
2015-07-27 20:57:22 +00:00
|
|
|
cdef attr_t[:] values
|
2015-07-22 02:53:01 +00:00
|
|
|
for col, attr_id in enumerate(attrs):
|
|
|
|
values = array[:, col]
|
|
|
|
if attr_id == HEAD:
|
|
|
|
for i in range(length):
|
|
|
|
tokens[i].head = values[i]
|
2015-07-28 19:03:18 +00:00
|
|
|
if values[i] >= 1:
|
|
|
|
tokens[i + values[i]].l_kids += 1
|
|
|
|
elif values[i] < 0:
|
|
|
|
tokens[i + values[i]].r_kids += 1
|
2015-07-22 02:53:01 +00:00
|
|
|
elif attr_id == TAG:
|
|
|
|
for i in range(length):
|
2016-05-02 14:07:50 +00:00
|
|
|
if values[i] != 0:
|
|
|
|
self.vocab.morphology.assign_tag(&tokens[i],
|
|
|
|
self.vocab.morphology.reverse_index[values[i]])
|
2015-09-06 02:13:03 +00:00
|
|
|
elif attr_id == POS:
|
|
|
|
for i in range(length):
|
|
|
|
tokens[i].pos = <univ_pos_t>values[i]
|
2015-07-22 02:53:01 +00:00
|
|
|
elif attr_id == DEP:
|
|
|
|
for i in range(length):
|
|
|
|
tokens[i].dep = values[i]
|
|
|
|
elif attr_id == ENT_IOB:
|
|
|
|
for i in range(length):
|
|
|
|
tokens[i].ent_iob = values[i]
|
|
|
|
elif attr_id == ENT_TYPE:
|
|
|
|
for i in range(length):
|
|
|
|
tokens[i].ent_type = values[i]
|
2015-11-03 06:56:50 +00:00
|
|
|
else:
|
|
|
|
raise ValueError("Unknown attribute ID: %d" % attr_id)
|
2015-11-03 13:15:14 +00:00
|
|
|
set_children_from_heads(self.c, self.length)
|
2016-02-06 13:44:35 +00:00
|
|
|
self.is_parsed = bool(HEAD in attrs or DEP in attrs)
|
|
|
|
self.is_tagged = bool(TAG in attrs or POS in attrs)
|
|
|
|
|
2015-07-22 02:53:01 +00:00
|
|
|
return self
|
|
|
|
|
|
|
|
def to_bytes(self):
|
2015-07-22 23:14:45 +00:00
|
|
|
byte_string = self.vocab.serializer.pack(self)
|
2015-07-27 20:57:22 +00:00
|
|
|
cdef uint32_t length = len(byte_string)
|
|
|
|
return struct.pack('I', length) + byte_string
|
2015-07-22 02:53:01 +00:00
|
|
|
|
2015-07-24 02:54:13 +00:00
|
|
|
def from_bytes(self, data):
|
2015-07-22 23:14:45 +00:00
|
|
|
self.vocab.serializer.unpack_into(data[4:], self)
|
2015-07-22 02:53:01 +00:00
|
|
|
return self
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def read_bytes(file_):
|
|
|
|
keep_reading = True
|
|
|
|
while keep_reading:
|
|
|
|
try:
|
2015-07-22 23:14:45 +00:00
|
|
|
n_bytes_str = file_.read(4)
|
|
|
|
if len(n_bytes_str) < 4:
|
2015-07-22 02:53:01 +00:00
|
|
|
break
|
2015-07-22 23:14:45 +00:00
|
|
|
n_bytes = struct.unpack('I', n_bytes_str)[0]
|
2015-07-22 02:53:01 +00:00
|
|
|
data = file_.read(n_bytes)
|
|
|
|
except StopIteration:
|
|
|
|
keep_reading = False
|
2015-07-22 23:14:45 +00:00
|
|
|
yield n_bytes_str + data
|
2015-07-22 02:53:01 +00:00
|
|
|
|
2015-11-05 15:28:08 +00:00
|
|
|
def merge(self, int start_idx, int end_idx, unicode tag, unicode lemma,
|
|
|
|
unicode ent_type):
|
|
|
|
"""Merge a multi-word expression into a single token. Currently
|
|
|
|
experimental; API is likely to change."""
|
2015-11-06 21:55:34 +00:00
|
|
|
cdef int start = token_by_start(self.c, self.length, start_idx)
|
|
|
|
if start == -1:
|
2015-11-05 15:28:08 +00:00
|
|
|
return None
|
2015-11-06 21:55:34 +00:00
|
|
|
cdef int end = token_by_end(self.c, self.length, end_idx)
|
|
|
|
if end == -1:
|
|
|
|
return None
|
|
|
|
# Currently we have the token index, we want the range-end index
|
|
|
|
end += 1
|
|
|
|
|
2015-07-30 00:29:49 +00:00
|
|
|
cdef Span span = self[start:end]
|
2015-07-13 17:58:26 +00:00
|
|
|
# Get LexemeC for newly merged token
|
2015-10-18 06:17:27 +00:00
|
|
|
new_orth = ''.join([t.text_with_ws for t in span])
|
2015-10-19 04:47:04 +00:00
|
|
|
if span[-1].whitespace_:
|
|
|
|
new_orth = new_orth[:-len(span[-1].whitespace_)]
|
2015-07-22 02:53:01 +00:00
|
|
|
cdef const LexemeC* lex = self.vocab.get(self.mem, new_orth)
|
2015-07-13 17:58:26 +00:00
|
|
|
# House the new merged token where it starts
|
2015-11-03 13:15:14 +00:00
|
|
|
cdef TokenC* token = &self.c[start]
|
|
|
|
token.spacy = self.c[end-1].spacy
|
2015-11-03 07:14:53 +00:00
|
|
|
if tag in self.vocab.morphology.tag_map:
|
2015-11-03 08:07:02 +00:00
|
|
|
self.vocab.morphology.assign_tag(token, tag)
|
2015-11-03 07:14:53 +00:00
|
|
|
else:
|
|
|
|
token.tag = self.vocab.strings[tag]
|
2015-07-13 17:58:26 +00:00
|
|
|
token.lemma = self.vocab.strings[lemma]
|
|
|
|
if ent_type == 'O':
|
|
|
|
token.ent_iob = 2
|
|
|
|
token.ent_type = 0
|
|
|
|
else:
|
|
|
|
token.ent_iob = 3
|
|
|
|
token.ent_type = self.vocab.strings[ent_type]
|
|
|
|
# Begin by setting all the head indices to absolute token positions
|
|
|
|
# This is easier to work with for now than the offsets
|
2015-07-30 00:29:49 +00:00
|
|
|
# Before thinking of something simpler, beware the case where a dependency
|
|
|
|
# bridges over the entity. Here the alignment of the tokens changes.
|
|
|
|
span_root = span.root.i
|
2015-07-31 22:33:24 +00:00
|
|
|
token.dep = span.root.dep
|
2015-11-05 15:28:08 +00:00
|
|
|
# We update token.lex after keeping span root and dep, since
|
|
|
|
# setting token.lex will change span.start and span.end properties
|
|
|
|
# as it modifies the character offsets in the doc
|
|
|
|
token.lex = lex
|
2015-07-13 17:58:26 +00:00
|
|
|
for i in range(self.length):
|
2015-11-03 13:15:14 +00:00
|
|
|
self.c[i].head += i
|
2015-07-30 00:29:49 +00:00
|
|
|
# Set the head of the merged token, and its dep relation, from the Span
|
2015-11-03 13:15:14 +00:00
|
|
|
token.head = self.c[span_root].head
|
2015-07-13 17:58:26 +00:00
|
|
|
# Adjust deps before shrinking tokens
|
|
|
|
# Tokens which point into the merged token should now point to it
|
|
|
|
# Subtract the offset from all tokens which point to >= end
|
|
|
|
offset = (end - start) - 1
|
|
|
|
for i in range(self.length):
|
2015-11-03 13:15:14 +00:00
|
|
|
head_idx = self.c[i].head
|
2015-07-13 17:58:26 +00:00
|
|
|
if start <= head_idx < end:
|
2015-11-03 13:15:14 +00:00
|
|
|
self.c[i].head = start
|
2015-07-13 17:58:26 +00:00
|
|
|
elif head_idx >= end:
|
2015-11-03 13:15:14 +00:00
|
|
|
self.c[i].head -= offset
|
2015-07-13 17:58:26 +00:00
|
|
|
# Now compress the token array
|
|
|
|
for i in range(end, self.length):
|
2015-11-03 13:15:14 +00:00
|
|
|
self.c[i - offset] = self.c[i]
|
2015-07-13 17:58:26 +00:00
|
|
|
for i in range(self.length - offset, self.length):
|
2015-11-03 13:15:14 +00:00
|
|
|
memset(&self.c[i], 0, sizeof(TokenC))
|
|
|
|
self.c[i].lex = &EMPTY_LEXEME
|
2015-07-13 17:58:26 +00:00
|
|
|
self.length -= offset
|
|
|
|
for i in range(self.length):
|
|
|
|
# ...And, set heads back to a relative position
|
2015-11-03 13:15:14 +00:00
|
|
|
self.c[i].head -= i
|
2015-07-30 00:29:49 +00:00
|
|
|
# Set the left/right children, left/right edges
|
2015-11-03 13:15:14 +00:00
|
|
|
set_children_from_heads(self.c, self.length)
|
2015-07-30 00:29:49 +00:00
|
|
|
# Clear the cached Python objects
|
|
|
|
self._py_tokens = [None] * self.length
|
2015-07-13 17:58:26 +00:00
|
|
|
# Return the merged Python object
|
|
|
|
return self[start]
|
2015-07-30 00:29:49 +00:00
|
|
|
|
|
|
|
|
2015-11-06 21:55:34 +00:00
|
|
|
cdef int token_by_start(const TokenC* tokens, int length, int start_char) except -2:
|
|
|
|
cdef int i
|
|
|
|
for i in range(length):
|
2015-11-06 21:56:49 +00:00
|
|
|
if tokens[i].idx == start_char:
|
2015-11-06 21:55:34 +00:00
|
|
|
return i
|
|
|
|
else:
|
|
|
|
return -1
|
|
|
|
|
|
|
|
|
|
|
|
cdef int token_by_end(const TokenC* tokens, int length, int end_char) except -2:
|
|
|
|
cdef int i
|
|
|
|
for i in range(length):
|
|
|
|
if tokens[i].idx + tokens[i].lex.length == end_char:
|
|
|
|
return i
|
|
|
|
else:
|
|
|
|
return -1
|
|
|
|
|
|
|
|
|
2015-07-30 00:29:49 +00:00
|
|
|
cdef int set_children_from_heads(TokenC* tokens, int length) except -1:
|
|
|
|
cdef TokenC* head
|
|
|
|
cdef TokenC* child
|
|
|
|
cdef int i
|
2015-10-18 06:17:27 +00:00
|
|
|
# Set number of left/right children to 0. We'll increment it in the loops.
|
|
|
|
for i in range(length):
|
|
|
|
tokens[i].l_kids = 0
|
|
|
|
tokens[i].r_kids = 0
|
|
|
|
tokens[i].l_edge = i
|
|
|
|
tokens[i].r_edge = i
|
2015-07-30 00:29:49 +00:00
|
|
|
# Set left edges
|
|
|
|
for i in range(length):
|
|
|
|
child = &tokens[i]
|
|
|
|
head = &tokens[i + child.head]
|
2015-10-18 06:17:27 +00:00
|
|
|
if child < head:
|
|
|
|
if child.l_edge < head.l_edge:
|
|
|
|
head.l_edge = child.l_edge
|
|
|
|
head.l_kids += 1
|
|
|
|
|
2015-07-30 00:29:49 +00:00
|
|
|
# Set right edges --- same as above, but iterate in reverse
|
|
|
|
for i in range(length-1, -1, -1):
|
|
|
|
child = &tokens[i]
|
|
|
|
head = &tokens[i + child.head]
|
2015-10-18 06:17:27 +00:00
|
|
|
if child > head:
|
|
|
|
if child.r_edge > head.r_edge:
|
|
|
|
head.r_edge = child.r_edge
|
|
|
|
head.r_kids += 1
|
2015-11-03 07:14:53 +00:00
|
|
|
|
|
|
|
# Set sentence starts
|
|
|
|
for i in range(length):
|
|
|
|
if tokens[i].head == 0 and tokens[i].dep != 0:
|
|
|
|
tokens[tokens[i].l_edge].sent_start = True
|
|
|
|
|