2017-04-15 11:05:15 +00:00
|
|
|
|
# coding: utf8
|
2017-05-09 16:45:18 +00:00
|
|
|
|
# cython: infer_types=True
|
|
|
|
|
# cython: bounds_check=False
|
2017-04-15 11:05:15 +00:00
|
|
|
|
from __future__ import unicode_literals
|
2015-07-13 17:58:26 +00:00
|
|
|
|
|
2017-04-15 11:05:15 +00:00
|
|
|
|
cimport cython
|
|
|
|
|
cimport numpy as np
|
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
|
2017-05-09 16:11:34 +00:00
|
|
|
|
import dill
|
2015-07-13 17:58:26 +00:00
|
|
|
|
|
2017-04-15 11:05:15 +00:00
|
|
|
|
from libc.string cimport memcpy, memset
|
|
|
|
|
from libc.stdint cimport uint32_t
|
|
|
|
|
from libc.math cimport sqrt
|
|
|
|
|
|
|
|
|
|
from .span cimport Span
|
|
|
|
|
from .token cimport Token
|
2017-05-13 11:04:40 +00:00
|
|
|
|
from .span cimport Span
|
|
|
|
|
from .token cimport Token
|
|
|
|
|
from .printers import parse_tree
|
|
|
|
|
from ..lexeme cimport Lexeme, 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
|
2017-05-09 16:11:34 +00:00
|
|
|
|
from ..attrs cimport LENGTH, POS, LEMMA, TAG, DEP, HEAD, SPACY, ENT_IOB, ENT_TYPE
|
2017-05-13 11:04:40 +00:00
|
|
|
|
from ..parts_of_speech cimport CCONJ, PUNCT, NOUN, univ_pos_t
|
2016-05-02 12:25:10 +00:00
|
|
|
|
from ..syntax.iterators import CHUNKERS
|
2017-05-13 11:04:40 +00:00
|
|
|
|
from ..util import normalize_slice
|
2017-04-15 11:05:15 +00:00
|
|
|
|
from ..compat import is_config
|
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:
|
|
|
|
|
"""
|
2017-02-26 21:27:11 +00:00
|
|
|
|
A sequence of `Token` objects. Access sentences and named entities,
|
|
|
|
|
export annotations to numpy arrays, losslessly serialize to compressed
|
2016-09-28 09:15:13 +00:00
|
|
|
|
binary strings.
|
|
|
|
|
|
|
|
|
|
Aside: Internals
|
2017-02-26 21:27:11 +00:00
|
|
|
|
The `Doc` object holds an array of `TokenC` structs.
|
|
|
|
|
The Python-level `Token` and `Span` objects are views of this
|
2016-09-28 09:15:13 +00:00
|
|
|
|
array, i.e. they don't own the data themselves.
|
|
|
|
|
|
|
|
|
|
Code: Construction 1
|
|
|
|
|
doc = nlp.tokenizer(u'Some text')
|
|
|
|
|
|
|
|
|
|
Code: Construction 2
|
|
|
|
|
doc = Doc(nlp.vocab, orths_and_spaces=[(u'Some', True), (u'text', True)])
|
|
|
|
|
|
2015-07-13 17:58:26 +00:00
|
|
|
|
"""
|
2016-10-16 16:13:03 +00:00
|
|
|
|
def __init__(self, Vocab vocab, words=None, spaces=None, orths_and_spaces=None):
|
2017-04-15 11:05:15 +00:00
|
|
|
|
"""
|
2016-09-28 09:15:13 +00:00
|
|
|
|
Create a Doc object.
|
|
|
|
|
|
|
|
|
|
Arguments:
|
|
|
|
|
vocab:
|
2017-02-26 21:27:11 +00:00
|
|
|
|
A Vocabulary object, which must match any models you want to
|
2016-09-28 09:15:13 +00:00
|
|
|
|
use (e.g. tokenizer, parser, entity recognizer).
|
|
|
|
|
|
2016-10-17 00:42:51 +00:00
|
|
|
|
words:
|
|
|
|
|
A list of unicode strings to add to the document as words. If None,
|
|
|
|
|
defaults to empty list.
|
|
|
|
|
|
|
|
|
|
spaces:
|
|
|
|
|
A list of boolean values, of the same length as words. True
|
|
|
|
|
means that the word is followed by a space, False means it is not.
|
|
|
|
|
If None, defaults to [True]*len(words)
|
2017-04-15 11:05:15 +00:00
|
|
|
|
"""
|
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
|
2016-10-19 18:54:03 +00:00
|
|
|
|
self.sentiment = 0.0
|
2016-10-19 19:15:16 +00:00
|
|
|
|
self.user_hooks = {}
|
|
|
|
|
self.user_token_hooks = {}
|
|
|
|
|
self.user_span_hooks = {}
|
2016-10-17 13:23:47 +00:00
|
|
|
|
self.tensor = numpy.zeros((0,), dtype='float32')
|
2016-10-17 09:43:22 +00:00
|
|
|
|
self.user_data = {}
|
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)
|
2016-09-21 12:52:05 +00:00
|
|
|
|
cdef unicode orth
|
|
|
|
|
cdef bint has_space
|
2016-10-16 16:13:03 +00:00
|
|
|
|
if orths_and_spaces is None and words is not None:
|
|
|
|
|
if spaces is None:
|
|
|
|
|
spaces = [True] * len(words)
|
2016-10-16 16:16:42 +00:00
|
|
|
|
elif len(spaces) != len(words):
|
|
|
|
|
raise ValueError(
|
|
|
|
|
"Arguments 'words' and 'spaces' should be sequences of the "
|
|
|
|
|
"same length, or 'spaces' should be left default at None. "
|
|
|
|
|
"spaces should be a sequence of booleans, with True meaning "
|
|
|
|
|
"that the word owns a ' ' character following it.")
|
2016-10-16 16:13:03 +00:00
|
|
|
|
orths_and_spaces = zip(words, spaces)
|
2016-09-21 12:52:05 +00:00
|
|
|
|
if orths_and_spaces is not None:
|
|
|
|
|
for orth_space in orths_and_spaces:
|
|
|
|
|
if isinstance(orth_space, unicode):
|
|
|
|
|
orth = orth_space
|
|
|
|
|
has_space = True
|
|
|
|
|
elif isinstance(orth_space, bytes):
|
|
|
|
|
raise ValueError(
|
|
|
|
|
"orths_and_spaces expects either List(unicode) or "
|
|
|
|
|
"List((unicode, bool)). Got bytes instance: %s" % (str(orth_space)))
|
|
|
|
|
else:
|
|
|
|
|
orth, has_space = orth_space
|
|
|
|
|
# Note that we pass self.mem here --- we have ownership, if LexemeC
|
|
|
|
|
# must be created.
|
|
|
|
|
self.push_back(
|
|
|
|
|
<const LexemeC*>self.vocab.get(self.mem, orth), has_space)
|
2016-11-02 22:47:46 +00:00
|
|
|
|
# Tough to decide on policy for this. Is an empty doc tagged and parsed?
|
|
|
|
|
# There's no information we'd like to add to it, so I guess so?
|
|
|
|
|
if self.length == 0:
|
|
|
|
|
self.is_tagged = True
|
|
|
|
|
self.is_parsed = True
|
2017-02-26 21:27:11 +00:00
|
|
|
|
|
2015-07-13 17:58:26 +00:00
|
|
|
|
def __getitem__(self, object i):
|
2017-04-15 11:05:15 +00:00
|
|
|
|
"""
|
2016-09-28 09:15:13 +00:00
|
|
|
|
doc[i]
|
2017-02-26 21:27:11 +00:00
|
|
|
|
Get the Token object at position i, where i is an integer.
|
|
|
|
|
Negative indexing is supported, and follows the usual Python
|
2016-09-28 09:15:13 +00:00
|
|
|
|
semantics, i.e. doc[-2] is doc[len(doc) - 2].
|
|
|
|
|
doc[start : end]]
|
|
|
|
|
Get a `Span` object, starting at position `start`
|
|
|
|
|
and ending at position `end`, where `start` and
|
|
|
|
|
`end` are token indices. For instance,
|
2017-02-26 21:27:11 +00:00
|
|
|
|
`doc[2:5]` produces a span consisting of
|
|
|
|
|
tokens 2, 3 and 4. Stepped slices (e.g. `doc[start : end : step]`)
|
2016-09-28 09:15:13 +00:00
|
|
|
|
are not supported, as `Span` objects must be contiguous (cannot have gaps).
|
|
|
|
|
You can use negative indices and open-ended ranges, which have their
|
|
|
|
|
normal Python semantics.
|
2017-04-15 11:05:15 +00:00
|
|
|
|
"""
|
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):
|
2017-04-15 11:05:15 +00:00
|
|
|
|
"""
|
2016-09-28 09:15:13 +00:00
|
|
|
|
for token in doc
|
2017-02-26 21:27:11 +00:00
|
|
|
|
Iterate over `Token` objects, from which the annotations can
|
|
|
|
|
be easily accessed. This is the main way of accessing Token
|
|
|
|
|
objects, which are the main way annotations are accessed from
|
|
|
|
|
Python. If faster-than-Python speeds are required, you can
|
|
|
|
|
instead access the annotations as a numpy array, or access the
|
2016-09-28 09:15:13 +00:00
|
|
|
|
underlying C data directly from Cython.
|
2017-04-15 11:05:15 +00:00
|
|
|
|
"""
|
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):
|
2017-04-15 11:05:15 +00:00
|
|
|
|
"""
|
2016-09-28 09:15:13 +00:00
|
|
|
|
len(doc)
|
|
|
|
|
The number of tokens in the document.
|
2017-04-15 11:05:15 +00:00
|
|
|
|
"""
|
2015-07-13 17:58:26 +00:00
|
|
|
|
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):
|
2017-04-15 11:05:15 +00:00
|
|
|
|
if is_config(python3=True):
|
2015-11-02 18:22:18 +00:00
|
|
|
|
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
|
|
|
|
|
2016-11-24 10:47:20 +00:00
|
|
|
|
@property
|
|
|
|
|
def doc(self):
|
|
|
|
|
return self
|
|
|
|
|
|
2015-09-14 07:49:58 +00:00
|
|
|
|
def similarity(self, other):
|
2017-04-15 11:05:15 +00:00
|
|
|
|
"""
|
|
|
|
|
Make a semantic similarity estimate. The default estimate is cosine
|
2016-11-01 11:25:36 +00:00
|
|
|
|
similarity using an average of word vectors.
|
|
|
|
|
|
|
|
|
|
Arguments:
|
|
|
|
|
other (object): The object to compare with. By default, accepts Doc,
|
|
|
|
|
Span, Token and Lexeme objects.
|
|
|
|
|
|
|
|
|
|
Return:
|
|
|
|
|
score (float): A scalar similarity score. Higher is more similar.
|
2017-04-15 11:05:15 +00:00
|
|
|
|
"""
|
2016-10-19 18:54:03 +00:00
|
|
|
|
if 'similarity' in self.user_hooks:
|
|
|
|
|
return self.user_hooks['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)
|
|
|
|
|
|
2016-05-09 10:36:14 +00:00
|
|
|
|
property has_vector:
|
2017-04-15 11:05:15 +00:00
|
|
|
|
"""
|
2016-11-01 11:25:36 +00:00
|
|
|
|
A boolean value indicating whether a word vector is associated with the object.
|
2017-04-15 11:05:15 +00:00
|
|
|
|
"""
|
2016-05-09 10:36:14 +00:00
|
|
|
|
def __get__(self):
|
2016-10-19 18:54:03 +00:00
|
|
|
|
if 'has_vector' in self.user_hooks:
|
|
|
|
|
return self.user_hooks['has_vector'](self)
|
2017-02-26 21:27:11 +00:00
|
|
|
|
|
2016-05-09 10:36:14 +00:00
|
|
|
|
return any(token.has_vector for token in self)
|
|
|
|
|
|
2015-09-14 07:49:58 +00:00
|
|
|
|
property vector:
|
2017-04-15 11:05:15 +00:00
|
|
|
|
"""
|
2016-11-01 11:25:36 +00:00
|
|
|
|
A real-valued meaning representation. Defaults to an average of the token vectors.
|
2017-02-26 21:27:11 +00:00
|
|
|
|
|
2016-11-01 11:25:36 +00:00
|
|
|
|
Type: numpy.ndarray[ndim=1, dtype='float32']
|
2017-04-15 11:05:15 +00:00
|
|
|
|
"""
|
2015-09-14 07:49:58 +00:00
|
|
|
|
def __get__(self):
|
2016-10-19 18:54:03 +00:00
|
|
|
|
if 'vector' in self.user_hooks:
|
|
|
|
|
return self.user_hooks['vector'](self)
|
2015-09-17 01:50:11 +00:00
|
|
|
|
if self._vector is None:
|
2016-09-28 09:15:13 +00:00
|
|
|
|
if len(self):
|
|
|
|
|
self._vector = sum(t.vector for t in self) / len(self)
|
|
|
|
|
else:
|
|
|
|
|
return numpy.zeros((self.vocab.vectors_length,), dtype='float32')
|
2015-09-17 01:50:11 +00:00
|
|
|
|
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):
|
2016-10-19 18:54:03 +00:00
|
|
|
|
if 'vector_norm' in self.user_hooks:
|
|
|
|
|
return self.user_hooks['vector_norm'](self)
|
2015-09-17 01:50:11 +00:00
|
|
|
|
cdef float value
|
2016-10-23 12:49:31 +00:00
|
|
|
|
cdef double norm = 0
|
2015-09-17 01:50:11 +00:00
|
|
|
|
if self._vector_norm is None:
|
2016-10-23 12:49:31 +00:00
|
|
|
|
norm = 0.0
|
2015-09-17 01:50:11 +00:00
|
|
|
|
for value in self.vector:
|
2016-10-23 12:49:31 +00:00
|
|
|
|
norm += value * value
|
|
|
|
|
self._vector_norm = sqrt(norm) if norm != 0 else 0
|
2015-09-17 01:50:11 +00:00
|
|
|
|
return self._vector_norm
|
2017-02-26 21:27:11 +00:00
|
|
|
|
|
2015-09-17 01:50:11 +00:00
|
|
|
|
def __set__(self, value):
|
2017-02-26 21:27:11 +00:00
|
|
|
|
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-05-04 09:02:16 +00:00
|
|
|
|
return self.text
|
2017-02-26 21:27:11 +00:00
|
|
|
|
|
2016-11-01 12:27:32 +00:00
|
|
|
|
property text:
|
2017-04-15 11:05:15 +00:00
|
|
|
|
"""
|
|
|
|
|
A unicode representation of the document text.
|
|
|
|
|
"""
|
2016-11-01 11:25:36 +00:00
|
|
|
|
def __get__(self):
|
|
|
|
|
return u''.join(t.text_with_ws for t in self)
|
2015-07-13 17:58:26 +00:00
|
|
|
|
|
2016-11-01 11:25:36 +00:00
|
|
|
|
property text_with_ws:
|
2017-04-15 11:05:15 +00:00
|
|
|
|
"""
|
|
|
|
|
An alias of Doc.text, provided for duck-type compatibility with Span and Token.
|
|
|
|
|
"""
|
2016-11-01 11:25:36 +00:00
|
|
|
|
def __get__(self):
|
|
|
|
|
return self.text
|
2015-09-13 00:27:42 +00:00
|
|
|
|
|
2015-08-05 22:35:40 +00:00
|
|
|
|
property ents:
|
2017-04-15 11:05:15 +00:00
|
|
|
|
"""
|
2016-09-28 09:15:13 +00:00
|
|
|
|
Yields named-entity `Span` objects, if the entity recognizer
|
2017-02-26 21:27:11 +00:00
|
|
|
|
has been applied to the document. Iterate over the span to get
|
2016-09-28 09:15:13 +00:00
|
|
|
|
individual Token objects, or access the label:
|
|
|
|
|
|
|
|
|
|
Example:
|
|
|
|
|
from spacy.en import English
|
|
|
|
|
nlp = English()
|
|
|
|
|
tokens = nlp(u'Mr. Best flew to New York on Saturday morning.')
|
|
|
|
|
ents = list(tokens.ents)
|
|
|
|
|
assert ents[0].label == 346
|
|
|
|
|
assert ents[0].label_ == 'PERSON'
|
|
|
|
|
assert ents[0].orth_ == 'Best'
|
|
|
|
|
assert ents[0].text == 'Mr. Best'
|
2017-04-15 11:05:15 +00:00
|
|
|
|
"""
|
2015-08-05 22:35:40 +00:00
|
|
|
|
def __get__(self):
|
|
|
|
|
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
|
2017-02-26 21:27:11 +00:00
|
|
|
|
# At this point we don't know whether the NER has run over the
|
2016-10-26 11:13:56 +00:00
|
|
|
|
# Doc. If the ent_iob is missing, leave it missing.
|
|
|
|
|
if self.c[i].ent_iob != 0:
|
|
|
|
|
self.c[i].ent_iob = 2 # Means O. Non-O are set from ents.
|
2015-08-05 22:35:40 +00:00
|
|
|
|
cdef attr_t ent_type
|
|
|
|
|
cdef int start, end
|
2016-09-23 23:17:43 +00:00
|
|
|
|
for ent_info in ents:
|
|
|
|
|
if isinstance(ent_info, Span):
|
|
|
|
|
ent_id = ent_info.ent_id
|
|
|
|
|
ent_type = ent_info.label
|
|
|
|
|
start = ent_info.start
|
|
|
|
|
end = ent_info.end
|
|
|
|
|
elif len(ent_info) == 3:
|
|
|
|
|
ent_type, start, end = ent_info
|
|
|
|
|
else:
|
|
|
|
|
ent_id, ent_type, start, end = ent_info
|
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-09-28 09:39:49 +00:00
|
|
|
|
property noun_chunks:
|
2017-04-15 11:05:15 +00:00
|
|
|
|
"""
|
2016-09-28 09:15:13 +00:00
|
|
|
|
Yields base noun-phrase #[code Span] objects, if the document
|
2017-02-26 21:27:11 +00:00
|
|
|
|
has been syntactically parsed. A base noun phrase, or
|
|
|
|
|
'NP chunk', is a noun phrase that does not permit other NPs to
|
|
|
|
|
be nested within it – so no NP-level coordination, no prepositional
|
2017-04-15 11:05:15 +00:00
|
|
|
|
phrases, and no relative clauses.
|
|
|
|
|
"""
|
2016-09-28 09:15:13 +00:00
|
|
|
|
def __get__(self):
|
|
|
|
|
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: "
|
2017-04-01 08:19:32 +00:00
|
|
|
|
"\npython -m spacy download %s\n"
|
2016-09-28 09:15:13 +00:00
|
|
|
|
"to install the data" % self.vocab.lang)
|
|
|
|
|
# Accumulate the result before beginning to iterate over it. This prevents
|
|
|
|
|
# the tokenisation from being changed out from under us during the iteration.
|
|
|
|
|
# The tricky thing here is that Span accepts its tokenisation changing,
|
|
|
|
|
# so it's okay once we have the Span objects. See Issue #375
|
|
|
|
|
spans = []
|
|
|
|
|
for start, end, label in self.noun_chunks_iterator(self):
|
|
|
|
|
spans.append(Span(self, start, end, label=label))
|
|
|
|
|
for span in spans:
|
|
|
|
|
yield span
|
|
|
|
|
|
|
|
|
|
property sents:
|
2015-07-13 17:58:26 +00:00
|
|
|
|
"""
|
2016-09-28 09:15:13 +00:00
|
|
|
|
Yields sentence `Span` objects. Sentence spans have no label.
|
|
|
|
|
To improve accuracy on informal texts, spaCy calculates sentence
|
|
|
|
|
boundaries from the syntactic dependency parse. If the parser is disabled,
|
|
|
|
|
`sents` iterator will be unavailable.
|
|
|
|
|
|
|
|
|
|
Example:
|
|
|
|
|
from spacy.en import English
|
|
|
|
|
nlp = English()
|
|
|
|
|
doc = nlp("This is a sentence. Here's another...")
|
|
|
|
|
assert [s.root.orth_ for s in doc.sents] == ["is", "'s"]
|
2015-07-13 17:58:26 +00:00
|
|
|
|
"""
|
2016-09-28 09:15:13 +00:00
|
|
|
|
def __get__(self):
|
2016-10-19 18:54:03 +00:00
|
|
|
|
if 'sents' in self.user_hooks:
|
|
|
|
|
return self.user_hooks['sents'](self)
|
2017-02-26 21:27:11 +00:00
|
|
|
|
|
2016-09-28 09:15:13 +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: "
|
2017-04-01 08:19:32 +00:00
|
|
|
|
"\npython -m spacy download %s\n"
|
2016-09-28 09:15:13 +00:00
|
|
|
|
"to install the data" % self.vocab.lang)
|
|
|
|
|
cdef int i
|
|
|
|
|
start = 0
|
|
|
|
|
for i in range(1, self.length):
|
|
|
|
|
if self.c[i].sent_start:
|
|
|
|
|
yield Span(self, start, i)
|
|
|
|
|
start = i
|
|
|
|
|
if start != self.length:
|
|
|
|
|
yield Span(self, start, self.length)
|
2015-07-13 17:58:26 +00:00
|
|
|
|
|
2015-07-13 19:46:02 +00:00
|
|
|
|
cdef int push_back(self, LexemeOrToken lex_or_tok, bint has_space) except -1:
|
2016-11-02 22:47:46 +00:00
|
|
|
|
if self.length == 0:
|
|
|
|
|
# Flip these to false when we see the first token.
|
|
|
|
|
self.is_tagged = False
|
|
|
|
|
self.is_parsed = False
|
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):
|
2016-09-28 09:15:13 +00:00
|
|
|
|
"""
|
2017-02-26 21:27:11 +00:00
|
|
|
|
Given a list of M attribute IDs, export the tokens to a numpy
|
|
|
|
|
`ndarray` of shape (N, M), where `N` is the length
|
2016-09-28 09:15:13 +00:00
|
|
|
|
of the document. The values will be 32-bit integers.
|
|
|
|
|
|
|
|
|
|
Example:
|
|
|
|
|
from spacy import attrs
|
|
|
|
|
doc = nlp(text)
|
|
|
|
|
# All strings mapped to integers, for easy export to numpy
|
|
|
|
|
np_array = doc.to_array([attrs.LOWER, attrs.POS, attrs.ENT_TYPE, attrs.IS_ALPHA])
|
2017-02-26 21:27:11 +00:00
|
|
|
|
|
2015-07-13 17:58:26 +00:00
|
|
|
|
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):
|
2017-04-15 11:05:15 +00:00
|
|
|
|
"""
|
|
|
|
|
Produce a dict of {attribute (int): count (ints)} frequencies, keyed
|
2015-07-13 17:58:26 +00:00
|
|
|
|
by the values of the given attribute ID.
|
|
|
|
|
|
2016-09-28 09:15:13 +00:00
|
|
|
|
Example:
|
2017-01-31 16:18:45 +00:00
|
|
|
|
from spacy.en import English
|
|
|
|
|
from spacy import attrs
|
2016-09-28 09:15:13 +00:00
|
|
|
|
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]])
|
|
|
|
|
|
|
|
|
|
Arguments:
|
|
|
|
|
attr_id
|
|
|
|
|
int
|
|
|
|
|
The attribute ID to key the counts.
|
2015-07-13 17:58:26 +00:00
|
|
|
|
"""
|
|
|
|
|
cdef int i
|
|
|
|
|
cdef attr_t attr
|
|
|
|
|
cdef size_t count
|
2017-02-26 21:27:11 +00:00
|
|
|
|
|
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
|
|
|
|
|
2017-05-09 16:45:18 +00:00
|
|
|
|
def from_array(self, attrs, int[:, :] array):
|
2017-04-15 11:05:15 +00:00
|
|
|
|
"""
|
|
|
|
|
Write to a `Doc` object, from an `(M, N)` array of attributes.
|
|
|
|
|
"""
|
2015-07-22 02:53:01 +00:00
|
|
|
|
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)
|
2017-05-09 16:45:18 +00:00
|
|
|
|
# Get set up for fast loading
|
|
|
|
|
cdef Pool mem = Pool()
|
|
|
|
|
cdef int n_attrs = len(attrs)
|
|
|
|
|
attr_ids = <attr_id_t*>mem.alloc(n_attrs, sizeof(attr_id_t))
|
|
|
|
|
for i, attr_id in enumerate(attrs):
|
|
|
|
|
attr_ids[i] = attr_id
|
|
|
|
|
# Now load the data
|
|
|
|
|
for i in range(self.length):
|
|
|
|
|
token = &self.c[i]
|
|
|
|
|
for j in range(n_attrs):
|
|
|
|
|
Token.set_struct_attr(token, attr_ids[j], array[i, j])
|
|
|
|
|
# Auxiliary loading logic
|
2017-02-26 21:27:11 +00:00
|
|
|
|
for col, attr_id in enumerate(attrs):
|
2017-05-09 16:45:18 +00:00
|
|
|
|
if attr_id == TAG:
|
2015-07-22 02:53:01 +00:00
|
|
|
|
for i in range(length):
|
2017-05-09 16:45:18 +00:00
|
|
|
|
if array[i, col] != 0:
|
|
|
|
|
self.vocab.morphology.assign_tag(&tokens[i], array[i, col])
|
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):
|
2017-04-15 11:05:15 +00:00
|
|
|
|
"""
|
|
|
|
|
Serialize, producing a byte string.
|
|
|
|
|
"""
|
2017-05-09 16:11:34 +00:00
|
|
|
|
return dill.dumps(
|
|
|
|
|
(self.text,
|
|
|
|
|
self.to_array([LENGTH,SPACY,TAG,LEMMA,HEAD,DEP,ENT_IOB,ENT_TYPE]),
|
|
|
|
|
self.sentiment,
|
|
|
|
|
self.tensor,
|
|
|
|
|
self.noun_chunks_iterator,
|
|
|
|
|
self.user_data,
|
|
|
|
|
(self.user_hooks, self.user_token_hooks, self.user_span_hooks)),
|
|
|
|
|
protocol=-1)
|
2015-07-22 02:53:01 +00:00
|
|
|
|
|
2015-07-24 02:54:13 +00:00
|
|
|
|
def from_bytes(self, data):
|
2017-04-15 11:05:15 +00:00
|
|
|
|
"""
|
|
|
|
|
Deserialize, loading from bytes.
|
|
|
|
|
"""
|
2017-05-09 16:11:34 +00:00
|
|
|
|
if self.length != 0:
|
|
|
|
|
raise ValueError("Cannot load into non-empty Doc")
|
|
|
|
|
cdef int[:, :] attrs
|
|
|
|
|
cdef int i, start, end, has_space
|
|
|
|
|
fields = dill.loads(data)
|
|
|
|
|
text, attrs = fields[:2]
|
|
|
|
|
self.sentiment, self.tensor = fields[2:4]
|
|
|
|
|
self.noun_chunks_iterator, self.user_data = fields[4:6]
|
|
|
|
|
self.user_hooks, self.user_token_hooks, self.user_span_hooks = fields[6]
|
|
|
|
|
|
|
|
|
|
start = 0
|
|
|
|
|
cdef const LexemeC* lex
|
|
|
|
|
cdef unicode orth_
|
|
|
|
|
for i in range(attrs.shape[0]):
|
|
|
|
|
end = start + attrs[i, 0]
|
|
|
|
|
has_space = attrs[i, 1]
|
|
|
|
|
orth_ = text[start:end]
|
|
|
|
|
lex = self.vocab.get(self.mem, orth_)
|
|
|
|
|
self.push_back(lex, has_space)
|
2017-05-13 10:32:06 +00:00
|
|
|
|
|
2017-05-09 16:11:34 +00:00
|
|
|
|
start = end + has_space
|
2017-05-09 16:45:18 +00:00
|
|
|
|
self.from_array([TAG,LEMMA,HEAD,DEP,ENT_IOB,ENT_TYPE],
|
|
|
|
|
attrs[:, 2:])
|
|
|
|
|
return self
|
2015-07-22 02:53:01 +00:00
|
|
|
|
|
2016-10-17 12:02:13 +00:00
|
|
|
|
def merge(self, int start_idx, int end_idx, *args, **attributes):
|
2017-04-15 11:05:15 +00:00
|
|
|
|
"""
|
|
|
|
|
Retokenize the document, such that the span at doc.text[start_idx : end_idx]
|
2016-11-01 11:25:36 +00:00
|
|
|
|
is merged into a single token. If start_idx and end_idx do not mark start
|
|
|
|
|
and end token boundaries, the document remains unchanged.
|
|
|
|
|
|
|
|
|
|
Arguments:
|
|
|
|
|
start_idx (int): The character index of the start of the slice to merge.
|
|
|
|
|
end_idx (int): The character index after the end of the slice to merge.
|
|
|
|
|
**attributes:
|
|
|
|
|
Attributes to assign to the merged token. By default, attributes
|
|
|
|
|
are inherited from the syntactic root token of the span.
|
|
|
|
|
Returns:
|
|
|
|
|
token (Token):
|
|
|
|
|
The newly merged token, or None if the start and end indices did
|
|
|
|
|
not fall at token boundaries.
|
|
|
|
|
"""
|
2016-10-17 12:02:13 +00:00
|
|
|
|
cdef unicode tag, lemma, ent_type
|
|
|
|
|
if len(args) == 3:
|
|
|
|
|
# TODO: Warn deprecation
|
|
|
|
|
tag, lemma, ent_type = args
|
2016-10-17 13:23:47 +00:00
|
|
|
|
attributes[TAG] = self.vocab.strings[tag]
|
|
|
|
|
attributes[LEMMA] = self.vocab.strings[lemma]
|
|
|
|
|
attributes[ENT_TYPE] = self.vocab.strings[ent_type]
|
2017-03-29 06:35:03 +00:00
|
|
|
|
elif not args:
|
2017-03-31 11:59:58 +00:00
|
|
|
|
# TODO: This code makes little sense overall. We're still
|
|
|
|
|
# ignoring most of the attributes?
|
|
|
|
|
if "label" in attributes and 'ent_type' not in attributes:
|
2017-03-29 06:35:03 +00:00
|
|
|
|
if type(attributes["label"]) == int:
|
|
|
|
|
attributes[ENT_TYPE] = attributes["label"]
|
|
|
|
|
else:
|
|
|
|
|
attributes[ENT_TYPE] = self.vocab.strings[attributes["label"]]
|
2017-03-31 11:59:58 +00:00
|
|
|
|
if 'ent_type' in attributes:
|
|
|
|
|
attributes[ENT_TYPE] = attributes['ent_type']
|
2016-10-17 12:02:13 +00:00
|
|
|
|
elif args:
|
|
|
|
|
raise ValueError(
|
|
|
|
|
"Doc.merge received %d non-keyword arguments. "
|
|
|
|
|
"Expected either 3 arguments (deprecated), or 0 (use keyword arguments). "
|
|
|
|
|
"Arguments supplied:\n%s\n"
|
|
|
|
|
"Keyword arguments:%s\n" % (len(args), repr(args), repr(attributes)))
|
2017-02-26 21:27:11 +00:00
|
|
|
|
|
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]
|
2016-10-17 13:23:47 +00:00
|
|
|
|
tag = self.vocab.strings[attributes.get(TAG, span.root.tag)]
|
|
|
|
|
lemma = self.vocab.strings[attributes.get(LEMMA, span.root.lemma)]
|
|
|
|
|
ent_type = self.vocab.strings[attributes.get(ENT_TYPE, span.root.ent_type)]
|
2017-03-31 11:59:58 +00:00
|
|
|
|
ent_id = attributes.get('ent_id', span.root.ent_id)
|
2017-03-31 17:32:01 +00:00
|
|
|
|
if isinstance(ent_id, basestring):
|
2017-03-31 11:59:58 +00:00
|
|
|
|
ent_id = self.vocab.strings[ent_id]
|
2016-10-17 12:02:13 +00:00
|
|
|
|
|
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:
|
2016-09-30 18:11:15 +00:00
|
|
|
|
token.tag = self.vocab.strings[tag]
|
|
|
|
|
token.lemma = self.vocab.strings[lemma]
|
2015-07-13 17:58:26 +00:00
|
|
|
|
if ent_type == 'O':
|
|
|
|
|
token.ent_iob = 2
|
|
|
|
|
token.ent_type = 0
|
|
|
|
|
else:
|
|
|
|
|
token.ent_iob = 3
|
2016-09-30 18:11:15 +00:00
|
|
|
|
token.ent_type = self.vocab.strings[ent_type]
|
2017-03-31 11:59:58 +00:00
|
|
|
|
token.ent_id = ent_id
|
2015-07-13 17:58:26 +00:00
|
|
|
|
# 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
|
|
|
|
|
2016-12-30 17:19:18 +00:00
|
|
|
|
def print_tree(self, light=False, flat=False):
|
|
|
|
|
"""Returns the parse trees in the JSON (Dict) format."""
|
|
|
|
|
return parse_tree(self, light=light, flat=flat)
|
|
|
|
|
|
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
|
2017-02-26 21:27:11 +00:00
|
|
|
|
|
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
|
2017-02-26 21:27:11 +00:00
|
|
|
|
|