2017-04-15 14:05:15 +03:00
|
|
|
|
# coding: utf8
|
2015-03-26 05:16:40 +03:00
|
|
|
|
from __future__ import unicode_literals
|
|
|
|
|
from collections import defaultdict
|
2017-04-15 14:05:15 +03:00
|
|
|
|
|
|
|
|
|
cimport numpy as np
|
2015-09-14 10:49:58 +03:00
|
|
|
|
import numpy
|
|
|
|
|
import numpy.linalg
|
2016-10-23 15:49:31 +03:00
|
|
|
|
from libc.math cimport sqrt
|
2015-03-26 05:16:40 +03:00
|
|
|
|
|
2017-08-19 13:20:45 +03:00
|
|
|
|
from .doc cimport token_by_start, token_by_end, get_token_attr
|
2015-08-26 20:20:46 +03:00
|
|
|
|
from ..structs cimport TokenC, LexemeC
|
2016-09-23 17:02:28 +03:00
|
|
|
|
from ..typedefs cimport flags_t, attr_t, hash_t
|
2015-07-16 20:55:21 +03:00
|
|
|
|
from ..attrs cimport attr_id_t
|
2015-07-13 21:20:58 +03:00
|
|
|
|
from ..parts_of_speech cimport univ_pos_t
|
2015-10-07 11:25:35 +03:00
|
|
|
|
from ..util import normalize_slice
|
2016-01-18 20:14:09 +03:00
|
|
|
|
from ..attrs cimport IS_PUNCT, IS_SPACE
|
|
|
|
|
from ..lexeme cimport Lexeme
|
2017-04-15 14:05:15 +03:00
|
|
|
|
from ..compat import is_config
|
2017-05-13 14:05:47 +03:00
|
|
|
|
from .. import about
|
2017-10-07 19:56:01 +03:00
|
|
|
|
from .underscore import Underscore
|
2015-07-13 21:20:58 +03:00
|
|
|
|
|
2015-03-26 05:16:40 +03:00
|
|
|
|
|
|
|
|
|
cdef class Span:
|
2017-05-18 23:17:24 +03:00
|
|
|
|
"""A slice from a Doc object."""
|
2017-10-07 19:56:01 +03:00
|
|
|
|
@classmethod
|
|
|
|
|
def set_extension(cls, name, default=None, method=None,
|
|
|
|
|
getter=None, setter=None):
|
2017-10-10 06:00:15 +03:00
|
|
|
|
Underscore.span_extensions[name] = (default, method, getter, setter)
|
2017-10-07 19:56:01 +03:00
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def get_extension(cls, name):
|
|
|
|
|
return Underscore.span_extensions.get(name)
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def has_extension(cls, name):
|
|
|
|
|
return name in Underscore.span_extensions
|
|
|
|
|
|
2017-10-27 16:41:45 +03:00
|
|
|
|
def __cinit__(self, Doc doc, int start, int end, attr_t label=0,
|
|
|
|
|
vector=None, vector_norm=None):
|
2017-05-18 23:17:24 +03:00
|
|
|
|
"""Create a `Span` object from the slice `doc[start : end]`.
|
|
|
|
|
|
|
|
|
|
doc (Doc): The parent document.
|
|
|
|
|
start (int): The index of the first token of the span.
|
|
|
|
|
end (int): The index of the first token after the span.
|
2017-05-28 15:06:40 +03:00
|
|
|
|
label (uint64): A label to attach to the Span, e.g. for named entities.
|
2017-10-27 16:41:45 +03:00
|
|
|
|
vector (ndarray[ndim=1, dtype='float32']): A meaning representation
|
|
|
|
|
of the span.
|
2017-05-18 23:17:24 +03:00
|
|
|
|
RETURNS (Span): The newly constructed object.
|
2017-04-15 14:05:15 +03:00
|
|
|
|
"""
|
2016-11-01 15:27:44 +03:00
|
|
|
|
if not (0 <= start <= end <= len(doc)):
|
2015-10-07 11:25:35 +03:00
|
|
|
|
raise IndexError
|
2015-10-06 11:59:11 +03:00
|
|
|
|
|
2016-11-01 14:25:36 +03:00
|
|
|
|
self.doc = doc
|
2015-11-07 00:55:34 +03:00
|
|
|
|
self.start = start
|
2015-11-07 09:05:16 +03:00
|
|
|
|
self.start_char = self.doc[start].idx if start < self.doc.length else 0
|
2015-11-07 00:55:34 +03:00
|
|
|
|
self.end = end
|
2015-11-07 09:05:16 +03:00
|
|
|
|
if end >= 1:
|
|
|
|
|
self.end_char = self.doc[end - 1].idx + len(self.doc[end - 1])
|
|
|
|
|
else:
|
|
|
|
|
self.end_char = 0
|
2017-05-28 19:09:27 +03:00
|
|
|
|
assert label in doc.vocab.strings, label
|
2015-03-26 05:16:40 +03:00
|
|
|
|
self.label = label
|
2015-09-21 09:50:40 +03:00
|
|
|
|
self._vector = vector
|
|
|
|
|
self._vector_norm = vector_norm
|
2015-03-26 05:16:40 +03:00
|
|
|
|
|
|
|
|
|
def __richcmp__(self, Span other, int op):
|
2018-01-15 17:51:25 +03:00
|
|
|
|
if other is None:
|
|
|
|
|
if op == 0 or op == 1 or op == 2:
|
|
|
|
|
return False
|
|
|
|
|
else:
|
|
|
|
|
return True
|
2015-03-26 05:16:40 +03:00
|
|
|
|
# Eq
|
|
|
|
|
if op == 0:
|
2015-11-07 00:55:34 +03:00
|
|
|
|
return self.start_char < other.start_char
|
2015-03-26 05:16:40 +03:00
|
|
|
|
elif op == 1:
|
2015-11-07 00:55:34 +03:00
|
|
|
|
return self.start_char <= other.start_char
|
2015-03-26 05:16:40 +03:00
|
|
|
|
elif op == 2:
|
2015-11-07 01:54:14 +03:00
|
|
|
|
return self.start_char == other.start_char and self.end_char == other.end_char
|
2015-03-26 05:16:40 +03:00
|
|
|
|
elif op == 3:
|
2015-11-07 00:55:34 +03:00
|
|
|
|
return self.start_char != other.start_char or self.end_char != other.end_char
|
2015-03-26 05:16:40 +03:00
|
|
|
|
elif op == 4:
|
2015-11-07 00:55:34 +03:00
|
|
|
|
return self.start_char > other.start_char
|
2015-03-26 05:16:40 +03:00
|
|
|
|
elif op == 5:
|
2015-11-07 00:55:34 +03:00
|
|
|
|
return self.start_char >= other.start_char
|
2015-03-26 05:16:40 +03:00
|
|
|
|
|
2017-04-26 20:01:05 +03:00
|
|
|
|
def __hash__(self):
|
|
|
|
|
return hash((self.doc, self.label, self.start_char, self.end_char))
|
|
|
|
|
|
2015-03-26 05:16:40 +03:00
|
|
|
|
def __len__(self):
|
2017-05-19 01:31:31 +03:00
|
|
|
|
"""Get the number of tokens in the span.
|
|
|
|
|
|
|
|
|
|
RETURNS (int): The number of tokens in the span.
|
|
|
|
|
"""
|
2015-11-07 00:56:49 +03:00
|
|
|
|
self._recalculate_indices()
|
2015-03-26 05:16:40 +03:00
|
|
|
|
if self.end < self.start:
|
|
|
|
|
return 0
|
|
|
|
|
return self.end - self.start
|
|
|
|
|
|
2015-10-21 14:11:46 +03:00
|
|
|
|
def __repr__(self):
|
2017-04-15 14:05:15 +03:00
|
|
|
|
if is_config(python3=True):
|
2015-11-02 21:22:18 +03:00
|
|
|
|
return self.text
|
|
|
|
|
return self.text.encode('utf-8')
|
2015-10-21 14:11:46 +03:00
|
|
|
|
|
2015-10-06 12:45:49 +03:00
|
|
|
|
def __getitem__(self, object i):
|
2017-05-19 01:31:31 +03:00
|
|
|
|
"""Get a `Token` or a `Span` object
|
|
|
|
|
|
|
|
|
|
i (int or tuple): The index of the token within the span, or slice of
|
|
|
|
|
the span to get.
|
|
|
|
|
RETURNS (Token or Span): The token at `span[i]`.
|
|
|
|
|
|
|
|
|
|
EXAMPLE:
|
|
|
|
|
>>> span[0]
|
|
|
|
|
>>> span[1:3]
|
|
|
|
|
"""
|
2015-11-07 00:56:49 +03:00
|
|
|
|
self._recalculate_indices()
|
2015-10-06 12:45:49 +03:00
|
|
|
|
if isinstance(i, slice):
|
2015-10-07 11:25:35 +03:00
|
|
|
|
start, end = normalize_slice(len(self), i.start, i.stop, i.step)
|
2015-11-07 00:55:34 +03:00
|
|
|
|
return Span(self.doc, start + self.start, end + self.start)
|
2015-07-30 03:30:24 +03:00
|
|
|
|
else:
|
2015-11-07 00:55:34 +03:00
|
|
|
|
if i < 0:
|
2015-11-07 00:56:49 +03:00
|
|
|
|
return self.doc[self.end + i]
|
2015-11-07 00:55:34 +03:00
|
|
|
|
else:
|
2015-11-07 00:56:49 +03:00
|
|
|
|
return self.doc[self.start + i]
|
2015-03-26 05:16:40 +03:00
|
|
|
|
|
|
|
|
|
def __iter__(self):
|
2017-05-19 01:31:31 +03:00
|
|
|
|
"""Iterate over `Token` objects.
|
|
|
|
|
|
|
|
|
|
YIELDS (Token): A `Token` object.
|
|
|
|
|
"""
|
2015-11-07 00:56:49 +03:00
|
|
|
|
self._recalculate_indices()
|
2015-03-26 05:16:40 +03:00
|
|
|
|
for i in range(self.start, self.end):
|
2015-09-29 16:03:55 +03:00
|
|
|
|
yield self.doc[i]
|
2015-03-26 05:16:40 +03:00
|
|
|
|
|
2017-10-07 19:56:01 +03:00
|
|
|
|
@property
|
|
|
|
|
def _(self):
|
2017-10-27 18:07:26 +03:00
|
|
|
|
"""User space for adding custom attribute extensions."""
|
2017-10-07 19:56:01 +03:00
|
|
|
|
return Underscore(Underscore.span_extensions, self,
|
|
|
|
|
start=self.start_char, end=self.end_char)
|
2017-10-23 11:38:06 +03:00
|
|
|
|
|
2017-10-09 00:50:20 +03:00
|
|
|
|
def as_doc(self):
|
2017-10-27 18:07:26 +03:00
|
|
|
|
# TODO: fix
|
|
|
|
|
"""Create a `Doc` object view of the Span's data. This is mostly
|
|
|
|
|
useful for C-typed interfaces.
|
2017-10-09 00:50:20 +03:00
|
|
|
|
|
2017-10-27 18:07:26 +03:00
|
|
|
|
RETURNS (Doc): The `Doc` view of the span.
|
|
|
|
|
"""
|
2017-10-09 00:50:20 +03:00
|
|
|
|
cdef Doc doc = Doc(self.doc.vocab)
|
|
|
|
|
doc.length = self.end-self.start
|
|
|
|
|
doc.c = &self.doc.c[self.start]
|
|
|
|
|
doc.mem = self.doc.mem
|
|
|
|
|
doc.is_parsed = self.doc.is_parsed
|
|
|
|
|
doc.is_tagged = self.doc.is_tagged
|
|
|
|
|
doc.noun_chunks_iterator = self.doc.noun_chunks_iterator
|
|
|
|
|
doc.user_hooks = self.doc.user_hooks
|
|
|
|
|
doc.user_span_hooks = self.doc.user_span_hooks
|
|
|
|
|
doc.user_token_hooks = self.doc.user_token_hooks
|
|
|
|
|
doc.vector = self.vector
|
|
|
|
|
doc.vector_norm = self.vector_norm
|
|
|
|
|
for key, value in self.doc.cats.items():
|
|
|
|
|
if hasattr(key, '__len__') and len(key) == 3:
|
|
|
|
|
cat_start, cat_end, cat_label = key
|
|
|
|
|
if cat_start == self.start_char and cat_end == self.end_char:
|
|
|
|
|
doc.cats[cat_label] = value
|
|
|
|
|
return doc
|
2017-10-07 19:56:01 +03:00
|
|
|
|
|
2016-10-17 15:02:13 +03:00
|
|
|
|
def merge(self, *args, **attributes):
|
2017-05-19 01:31:31 +03:00
|
|
|
|
"""Retokenize the document, such that the span is merged into a single
|
|
|
|
|
token.
|
2017-05-18 23:17:24 +03:00
|
|
|
|
|
|
|
|
|
**attributes: Attributes to assign to the merged token. By default,
|
|
|
|
|
attributes are inherited from the syntactic root token of the span.
|
|
|
|
|
RETURNS (Token): The newly merged token.
|
2016-11-01 14:25:36 +03:00
|
|
|
|
"""
|
2017-10-27 16:41:45 +03:00
|
|
|
|
return self.doc.merge(self.start_char, self.end_char, *args,
|
|
|
|
|
**attributes)
|
2015-07-30 03:30:24 +03:00
|
|
|
|
|
2015-09-14 10:49:58 +03:00
|
|
|
|
def similarity(self, other):
|
2017-05-19 19:47:46 +03:00
|
|
|
|
"""Make a semantic similarity estimate. The default estimate is cosine
|
2016-11-01 14:25:36 +03:00
|
|
|
|
similarity using an average of word vectors.
|
|
|
|
|
|
2017-05-18 23:17:24 +03:00
|
|
|
|
other (object): The object to compare with. By default, accepts `Doc`,
|
|
|
|
|
`Span`, `Token` and `Lexeme` objects.
|
|
|
|
|
RETURNS (float): A scalar similarity score. Higher is more similar.
|
2017-04-15 14:05:15 +03:00
|
|
|
|
"""
|
2016-10-19 21:54:03 +03:00
|
|
|
|
if 'similarity' in self.doc.user_span_hooks:
|
|
|
|
|
self.doc.user_span_hooks['similarity'](self, other)
|
2018-01-15 18:29:48 +03:00
|
|
|
|
if len(self) == 1 and hasattr(other, 'orth'):
|
|
|
|
|
if self[0].orth == other.orth:
|
|
|
|
|
return 1.0
|
|
|
|
|
elif hasattr(other, '__len__') and len(self) == len(other):
|
|
|
|
|
for i in range(len(self)):
|
|
|
|
|
if self[i].orth != getattr(other[i], 'orth', None):
|
|
|
|
|
break
|
|
|
|
|
else:
|
|
|
|
|
return 1.0
|
2015-09-22 03:10:01 +03:00
|
|
|
|
if self.vector_norm == 0.0 or other.vector_norm == 0.0:
|
|
|
|
|
return 0.0
|
2015-09-14 10:49:58 +03:00
|
|
|
|
return numpy.dot(self.vector, other.vector) / (self.vector_norm * other.vector_norm)
|
|
|
|
|
|
2017-10-20 21:28:00 +03:00
|
|
|
|
def get_lca_matrix(self):
|
2017-10-27 16:41:45 +03:00
|
|
|
|
"""Calculates the lowest common ancestor matrix for a given `Span`.
|
|
|
|
|
Returns LCA matrix containing the integer index of the ancestor, or -1
|
|
|
|
|
if no common ancestor is found (ex if span excludes a necessary
|
|
|
|
|
ancestor). Apologies about the recursion, but the impact on
|
|
|
|
|
performance is negligible given the natural limitations on the depth
|
|
|
|
|
of a typical human sentence.
|
|
|
|
|
"""
|
2017-10-20 21:28:00 +03:00
|
|
|
|
def __pairwise_lca(token_j, token_k, lca_matrix, margins):
|
|
|
|
|
offset = margins[0]
|
|
|
|
|
token_k_head = token_k.head if token_k.head.i in range(*margins) else token_k
|
|
|
|
|
token_j_head = token_j.head if token_j.head.i in range(*margins) else token_j
|
|
|
|
|
token_j_i = token_j.i - offset
|
|
|
|
|
token_k_i = token_k.i - offset
|
|
|
|
|
if lca_matrix[token_j_i][token_k_i] != -2:
|
|
|
|
|
return lca_matrix[token_j_i][token_k_i]
|
|
|
|
|
elif token_j == token_k:
|
|
|
|
|
lca_index = token_j_i
|
|
|
|
|
elif token_k_head == token_j:
|
|
|
|
|
lca_index = token_j_i
|
|
|
|
|
elif token_j_head == token_k:
|
|
|
|
|
lca_index = token_k_i
|
|
|
|
|
elif (token_j_head == token_j) and (token_k_head == token_k):
|
|
|
|
|
lca_index = -1
|
|
|
|
|
else:
|
|
|
|
|
lca_index = __pairwise_lca(token_j_head, token_k_head, lca_matrix, margins)
|
|
|
|
|
lca_matrix[token_j_i][token_k_i] = lca_index
|
|
|
|
|
lca_matrix[token_k_i][token_j_i] = lca_index
|
|
|
|
|
return lca_index
|
|
|
|
|
|
|
|
|
|
lca_matrix = numpy.empty((len(self), len(self)), dtype=numpy.int32)
|
|
|
|
|
lca_matrix.fill(-2)
|
|
|
|
|
margins = [self.start, self.end]
|
|
|
|
|
for j in range(len(self)):
|
|
|
|
|
token_j = self[j]
|
|
|
|
|
for k in range(len(self)):
|
|
|
|
|
token_k = self[k]
|
|
|
|
|
lca_matrix[j][k] = __pairwise_lca(token_j, token_k, lca_matrix, margins)
|
|
|
|
|
lca_matrix[k][j] = lca_matrix[j][k]
|
|
|
|
|
return lca_matrix
|
|
|
|
|
|
2017-08-19 13:20:45 +03:00
|
|
|
|
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 document.
|
|
|
|
|
The values will be 32-bit integers.
|
|
|
|
|
|
|
|
|
|
attr_ids (list[int]): A list of attribute ID ints.
|
|
|
|
|
RETURNS (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
|
|
|
|
|
cdef np.ndarray[attr_t, ndim=2] output
|
|
|
|
|
# Make an array from the attributes --- otherwise our inner loop is Python
|
|
|
|
|
# dict iteration.
|
|
|
|
|
cdef np.ndarray[attr_t, ndim=1] attr_ids = numpy.asarray(py_attr_ids, dtype=numpy.uint64)
|
2017-08-19 17:24:28 +03:00
|
|
|
|
cdef int length = self.end - self.start
|
|
|
|
|
output = numpy.ndarray(shape=(length, len(attr_ids)), dtype=numpy.uint64)
|
2017-08-19 13:20:45 +03:00
|
|
|
|
for i in range(self.start, self.end):
|
|
|
|
|
for j, feature in enumerate(attr_ids):
|
2017-08-19 17:24:28 +03:00
|
|
|
|
output[i-self.start, j] = get_token_attr(&self.doc.c[i], feature)
|
2017-08-19 13:20:45 +03:00
|
|
|
|
return output
|
|
|
|
|
|
2015-11-07 00:56:49 +03:00
|
|
|
|
cpdef int _recalculate_indices(self) except -1:
|
2015-11-07 09:05:16 +03:00
|
|
|
|
if self.end > self.doc.length \
|
2015-11-07 00:56:49 +03:00
|
|
|
|
or self.doc.c[self.start].idx != self.start_char \
|
|
|
|
|
or (self.doc.c[self.end-1].idx + self.doc.c[self.end-1].lex.length) != self.end_char:
|
2015-11-07 00:55:34 +03:00
|
|
|
|
start = token_by_start(self.doc.c, self.doc.length, self.start_char)
|
|
|
|
|
if self.start == -1:
|
|
|
|
|
raise IndexError("Error calculating span: Can't find start")
|
2015-11-07 00:56:49 +03:00
|
|
|
|
end = token_by_end(self.doc.c, self.doc.length, self.end_char)
|
2015-11-07 00:55:34 +03:00
|
|
|
|
if end == -1:
|
|
|
|
|
raise IndexError("Error calculating span: Can't find end")
|
2017-04-01 11:19:01 +03:00
|
|
|
|
|
2015-11-07 00:55:34 +03:00
|
|
|
|
self.start = start
|
|
|
|
|
self.end = end + 1
|
2016-05-06 01:17:38 +03:00
|
|
|
|
|
2018-01-14 17:06:30 +03:00
|
|
|
|
property vocab:
|
|
|
|
|
"""RETURNS (Vocab): The Span's Doc's vocab."""
|
|
|
|
|
def __get__(self):
|
|
|
|
|
return self.doc.vocab
|
|
|
|
|
|
2016-05-06 01:17:38 +03:00
|
|
|
|
property sent:
|
2017-10-27 18:07:26 +03:00
|
|
|
|
"""RETURNS (Span): The sentence span that the span is a part of."""
|
2016-05-06 01:17:38 +03:00
|
|
|
|
def __get__(self):
|
2016-10-19 21:54:03 +03:00
|
|
|
|
if 'sent' in self.doc.user_span_hooks:
|
|
|
|
|
return self.doc.user_span_hooks['sent'](self)
|
2018-02-15 00:18:54 +03:00
|
|
|
|
# This should raise if we're not parsed
|
|
|
|
|
# or doesen't have any sbd component :)
|
2016-05-06 01:28:05 +03:00
|
|
|
|
self.doc.sents
|
2018-02-15 00:18:54 +03:00
|
|
|
|
# if doc is parsed we can use the deps to find the sentence
|
|
|
|
|
# otherwise we use the `sent_start` token attribute
|
2016-05-06 01:17:38 +03:00
|
|
|
|
cdef int n = 0
|
2018-02-15 18:58:30 +03:00
|
|
|
|
cdef int i
|
2018-02-15 00:18:54 +03:00
|
|
|
|
if self.doc.is_parsed:
|
|
|
|
|
root = &self.doc.c[self.start]
|
2018-02-28 14:27:09 +03:00
|
|
|
|
n = 0
|
2018-02-15 00:18:54 +03:00
|
|
|
|
while root.head != 0:
|
|
|
|
|
root += root.head
|
|
|
|
|
n += 1
|
|
|
|
|
if n >= self.doc.length:
|
|
|
|
|
raise RuntimeError
|
|
|
|
|
return self.doc[root.l_edge:root.r_edge + 1]
|
2018-02-18 16:16:55 +03:00
|
|
|
|
elif self.doc.is_sentenced:
|
2018-02-15 00:18:54 +03:00
|
|
|
|
# find start of the sentence
|
|
|
|
|
start = self.start
|
2018-02-15 18:58:30 +03:00
|
|
|
|
while self.doc.c[start].sent_start != 1 and start > 0:
|
2018-02-15 00:18:54 +03:00
|
|
|
|
start += -1
|
|
|
|
|
# find end of the sentence
|
|
|
|
|
end = self.end
|
2018-02-28 14:27:09 +03:00
|
|
|
|
n = 0
|
|
|
|
|
while end < self.doc.length and self.doc.c[end].sent_start != 1:
|
2018-02-15 00:18:54 +03:00
|
|
|
|
end += 1
|
2018-02-28 14:27:09 +03:00
|
|
|
|
n += 1
|
2018-02-15 00:18:54 +03:00
|
|
|
|
if n >= self.doc.length:
|
|
|
|
|
break
|
|
|
|
|
#
|
|
|
|
|
return self.doc[start:end]
|
2018-02-18 16:16:55 +03:00
|
|
|
|
else:
|
|
|
|
|
raise ValueError(
|
|
|
|
|
"Access to sentence requires either the dependency parse "
|
|
|
|
|
"or sentence boundaries to be set by setting " +
|
|
|
|
|
"doc[i].is_sent_start = True")
|
2018-02-15 18:58:30 +03:00
|
|
|
|
|
2016-05-09 13:36:14 +03:00
|
|
|
|
property has_vector:
|
2017-10-27 18:07:26 +03:00
|
|
|
|
"""RETURNS (bool): Whether a word vector is associated with the object.
|
2017-05-19 19:47:46 +03:00
|
|
|
|
"""
|
2016-05-09 13:36:14 +03:00
|
|
|
|
def __get__(self):
|
2016-10-19 21:54:03 +03:00
|
|
|
|
if 'has_vector' in self.doc.user_span_hooks:
|
|
|
|
|
return self.doc.user_span_hooks['has_vector'](self)
|
2017-11-03 22:56:33 +03:00
|
|
|
|
elif self.vocab.vectors.data.size > 0:
|
|
|
|
|
return any(token.has_vector for token in self)
|
|
|
|
|
elif self.doc.tensor.size > 0:
|
|
|
|
|
return True
|
|
|
|
|
else:
|
|
|
|
|
return False
|
2017-04-01 11:19:01 +03:00
|
|
|
|
|
2015-09-14 10:49:58 +03:00
|
|
|
|
property vector:
|
2017-05-19 19:47:46 +03:00
|
|
|
|
"""A real-valued meaning representation. Defaults to an average of the
|
|
|
|
|
token vectors.
|
|
|
|
|
|
|
|
|
|
RETURNS (numpy.ndarray[ndim=1, dtype='float32']): A 1D numpy array
|
|
|
|
|
representing the span's semantics.
|
|
|
|
|
"""
|
2015-09-14 10:49:58 +03:00
|
|
|
|
def __get__(self):
|
2016-10-19 21:54:03 +03:00
|
|
|
|
if 'vector' in self.doc.user_span_hooks:
|
|
|
|
|
return self.doc.user_span_hooks['vector'](self)
|
2015-09-17 04:50:11 +03:00
|
|
|
|
if self._vector is None:
|
|
|
|
|
self._vector = sum(t.vector for t in self) / len(self)
|
|
|
|
|
return self._vector
|
|
|
|
|
|
2015-09-14 10:49:58 +03:00
|
|
|
|
property vector_norm:
|
2017-10-27 18:07:26 +03:00
|
|
|
|
"""RETURNS (float): The L2 norm of the vector representation."""
|
2015-09-14 10:49:58 +03:00
|
|
|
|
def __get__(self):
|
2016-10-20 22:58:56 +03:00
|
|
|
|
if 'vector_norm' in self.doc.user_span_hooks:
|
|
|
|
|
return self.doc.user_span_hooks['vector'](self)
|
2015-09-17 04:50:11 +03:00
|
|
|
|
cdef float value
|
2016-10-23 15:49:31 +03:00
|
|
|
|
cdef double norm = 0
|
2015-09-17 04:50:11 +03:00
|
|
|
|
if self._vector_norm is None:
|
2016-10-23 15:49:31 +03:00
|
|
|
|
norm = 0
|
2015-09-17 04:50:11 +03:00
|
|
|
|
for value in self.vector:
|
2016-10-23 15:49:31 +03:00
|
|
|
|
norm += value * value
|
|
|
|
|
self._vector_norm = sqrt(norm) if norm != 0 else 0
|
2015-09-17 04:50:11 +03:00
|
|
|
|
return self._vector_norm
|
2015-09-14 10:49:58 +03:00
|
|
|
|
|
2016-12-02 13:05:50 +03:00
|
|
|
|
property sentiment:
|
2017-10-27 18:07:26 +03:00
|
|
|
|
"""RETURNS (float): A scalar value indicating the positivity or
|
|
|
|
|
negativity of the span.
|
|
|
|
|
"""
|
2016-12-02 13:05:50 +03:00
|
|
|
|
def __get__(self):
|
|
|
|
|
if 'sentiment' in self.doc.user_span_hooks:
|
|
|
|
|
return self.doc.user_span_hooks['sentiment'](self)
|
|
|
|
|
else:
|
|
|
|
|
return sum([token.sentiment for token in self]) / len(self)
|
|
|
|
|
|
2015-09-13 03:27:42 +03:00
|
|
|
|
property text:
|
2017-10-27 18:07:26 +03:00
|
|
|
|
"""RETURNS (unicode): The original verbatim text of the span."""
|
2015-09-13 03:27:42 +03:00
|
|
|
|
def __get__(self):
|
2015-09-17 04:50:11 +03:00
|
|
|
|
text = self.text_with_ws
|
|
|
|
|
if self[-1].whitespace_:
|
|
|
|
|
text = text[:-1]
|
|
|
|
|
return text
|
2015-09-13 03:27:42 +03:00
|
|
|
|
|
|
|
|
|
property text_with_ws:
|
2017-05-19 19:47:46 +03:00
|
|
|
|
"""The text content of the span with a trailing whitespace character if
|
|
|
|
|
the last token has one.
|
|
|
|
|
|
2017-10-27 16:41:45 +03:00
|
|
|
|
RETURNS (unicode): The text content of the span (with trailing
|
|
|
|
|
whitespace).
|
2017-05-19 19:47:46 +03:00
|
|
|
|
"""
|
2015-09-13 03:27:42 +03:00
|
|
|
|
def __get__(self):
|
|
|
|
|
return u''.join([t.text_with_ws for t in self])
|
|
|
|
|
|
2016-11-24 13:47:20 +03:00
|
|
|
|
property noun_chunks:
|
2017-05-18 23:17:24 +03:00
|
|
|
|
"""Yields base noun-phrase `Span` objects, if the document 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
|
2017-10-27 16:41:45 +03:00
|
|
|
|
NP-level coordination, no prepositional phrases, and no relative
|
|
|
|
|
clauses.
|
2017-05-18 23:17:24 +03:00
|
|
|
|
|
|
|
|
|
YIELDS (Span): Base noun-phrase `Span` objects
|
2017-04-15 14:05:15 +03:00
|
|
|
|
"""
|
2016-11-24 13:47:20 +03:00
|
|
|
|
def __get__(self):
|
|
|
|
|
if not self.doc.is_parsed:
|
|
|
|
|
raise ValueError(
|
|
|
|
|
"noun_chunks requires the dependency parse, which "
|
2017-10-27 16:41:45 +03:00
|
|
|
|
"requires a statistical model to be installed and loaded. "
|
|
|
|
|
"For more info, see the "
|
2017-05-13 14:05:47 +03:00
|
|
|
|
"documentation: \n%s\n" % about.__docs_models__)
|
2017-10-27 18:07:26 +03:00
|
|
|
|
# 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
|
2016-11-24 13:47:20 +03:00
|
|
|
|
spans = []
|
2017-05-28 19:09:27 +03:00
|
|
|
|
cdef attr_t label
|
2016-11-24 13:47:20 +03:00
|
|
|
|
for start, end, label in self.doc.noun_chunks_iterator(self):
|
2017-11-18 04:13:13 +03:00
|
|
|
|
spans.append(Span(self.doc, start, end, label=label))
|
2016-11-24 13:47:20 +03:00
|
|
|
|
for span in spans:
|
|
|
|
|
yield span
|
|
|
|
|
|
2015-07-09 18:30:58 +03:00
|
|
|
|
property root:
|
2017-05-18 23:17:24 +03:00
|
|
|
|
"""The token within the span that's highest in the parse tree.
|
|
|
|
|
If there's a tie, the earliest is prefered.
|
2016-11-01 14:25:36 +03:00
|
|
|
|
|
2017-05-18 23:17:24 +03:00
|
|
|
|
RETURNS (Token): The root token.
|
2017-04-01 11:19:01 +03:00
|
|
|
|
|
2017-10-27 16:41:45 +03:00
|
|
|
|
EXAMPLE: The root token has the shortest path to the root of the
|
|
|
|
|
sentence (or is the root itself). If multiple words are equally
|
|
|
|
|
high in the tree, the first word is taken. For example:
|
2017-04-01 11:19:01 +03:00
|
|
|
|
|
2017-05-18 23:17:24 +03:00
|
|
|
|
>>> toks = nlp(u'I like New York in Autumn.')
|
2015-07-09 18:30:58 +03:00
|
|
|
|
|
2017-05-18 23:17:24 +03:00
|
|
|
|
Let's name the indices – easier than writing `toks[4]` etc.
|
2015-07-09 18:30:58 +03:00
|
|
|
|
|
2017-05-18 23:17:24 +03:00
|
|
|
|
>>> i, like, new, york, in_, autumn, dot = range(len(toks))
|
2015-07-09 18:30:58 +03:00
|
|
|
|
|
2017-05-18 23:17:24 +03:00
|
|
|
|
The head of 'new' is 'York', and the head of "York" is "like"
|
2015-07-09 18:30:58 +03:00
|
|
|
|
|
2017-05-19 01:31:31 +03:00
|
|
|
|
>>> toks[new].head.text
|
2017-05-18 23:17:24 +03:00
|
|
|
|
'York'
|
2017-05-19 01:31:31 +03:00
|
|
|
|
>>> toks[york].head.text
|
2017-05-18 23:17:24 +03:00
|
|
|
|
'like'
|
2015-07-09 18:30:58 +03:00
|
|
|
|
|
2017-05-18 23:17:24 +03:00
|
|
|
|
Create a span for "New York". Its root is "York".
|
2015-07-09 18:30:58 +03:00
|
|
|
|
|
2017-05-18 23:17:24 +03:00
|
|
|
|
>>> new_york = toks[new:york+1]
|
2017-05-19 01:31:31 +03:00
|
|
|
|
>>> new_york.root.text
|
2017-05-18 23:17:24 +03:00
|
|
|
|
'York'
|
2015-07-09 18:30:58 +03:00
|
|
|
|
|
2017-05-18 23:17:24 +03:00
|
|
|
|
Here's a more complicated case, raised by issue #214:
|
2016-01-16 17:38:50 +03:00
|
|
|
|
|
2017-05-18 23:17:24 +03:00
|
|
|
|
>>> toks = nlp(u'to, north and south carolina')
|
|
|
|
|
>>> to, north, and_, south, carolina = toks
|
|
|
|
|
>>> south.head.text, carolina.head.text
|
|
|
|
|
('north', 'to')
|
2016-01-16 17:38:50 +03:00
|
|
|
|
|
2017-05-18 23:17:24 +03:00
|
|
|
|
Here "south" is a child of "north", which is a child of "carolina".
|
|
|
|
|
Carolina is the root of the span:
|
2015-07-09 18:30:58 +03:00
|
|
|
|
|
2017-05-18 23:17:24 +03:00
|
|
|
|
>>> south_carolina = toks[-2:]
|
|
|
|
|
>>> south_carolina.root.text
|
|
|
|
|
'carolina'
|
2015-05-13 22:45:19 +03:00
|
|
|
|
"""
|
|
|
|
|
def __get__(self):
|
2015-11-07 00:56:49 +03:00
|
|
|
|
self._recalculate_indices()
|
2016-10-19 21:54:03 +03:00
|
|
|
|
if 'root' in self.doc.user_span_hooks:
|
|
|
|
|
return self.doc.user_span_hooks['root'](self)
|
2015-07-09 18:30:58 +03:00
|
|
|
|
# This should probably be called 'head', and the other one called
|
|
|
|
|
# 'gov'. But we went with 'head' elsehwhere, and now we're stuck =/
|
2016-01-16 17:38:50 +03:00
|
|
|
|
cdef int i
|
2016-01-16 18:17:28 +03:00
|
|
|
|
# First, we scan through the Span, and check whether there's a word
|
|
|
|
|
# with head==0, i.e. a sentence root. If so, we can return it. The
|
|
|
|
|
# longer the span, the more likely it contains a sentence root, and
|
|
|
|
|
# in this case we return in linear time.
|
|
|
|
|
for i in range(self.start, self.end):
|
|
|
|
|
if self.doc.c[i].head == 0:
|
2016-01-18 17:40:28 +03:00
|
|
|
|
return self.doc[i]
|
2016-01-16 18:17:28 +03:00
|
|
|
|
# If we don't have a sentence root, we do something that's not so
|
2017-10-27 16:41:45 +03:00
|
|
|
|
# algorithmically clever, but I think should be quite fast,
|
|
|
|
|
# especially for short spans.
|
2016-01-16 18:17:28 +03:00
|
|
|
|
# For each word, we count the path length, and arg min this measure.
|
2017-10-27 16:41:45 +03:00
|
|
|
|
# We could use better tree logic to save steps here...But I
|
|
|
|
|
# think this should be okay.
|
2016-01-18 20:14:09 +03:00
|
|
|
|
cdef int current_best = self.doc.length
|
|
|
|
|
cdef int root = -1
|
2016-01-16 17:38:50 +03:00
|
|
|
|
for i in range(self.start, self.end):
|
2016-01-18 18:59:38 +03:00
|
|
|
|
if self.start <= (i+self.doc.c[i].head) < self.end:
|
|
|
|
|
continue
|
2016-01-16 17:38:50 +03:00
|
|
|
|
words_to_root = _count_words_to_root(&self.doc.c[i], self.doc.length)
|
|
|
|
|
if words_to_root < current_best:
|
|
|
|
|
current_best = words_to_root
|
|
|
|
|
root = i
|
2016-02-05 21:18:35 +03:00
|
|
|
|
if root == -1:
|
|
|
|
|
return self.doc[self.start]
|
|
|
|
|
else:
|
|
|
|
|
return self.doc[root]
|
2017-04-01 11:19:01 +03:00
|
|
|
|
|
2015-05-13 22:45:19 +03:00
|
|
|
|
property lefts:
|
2017-05-18 23:17:24 +03:00
|
|
|
|
""" Tokens that are to the left of the span, whose head is within the
|
|
|
|
|
`Span`.
|
2017-04-01 11:19:01 +03:00
|
|
|
|
|
2017-05-18 23:17:24 +03:00
|
|
|
|
YIELDS (Token):A left-child of a token of the span.
|
2016-11-01 14:25:36 +03:00
|
|
|
|
"""
|
2015-05-13 22:45:19 +03:00
|
|
|
|
def __get__(self):
|
2017-10-27 18:07:26 +03:00
|
|
|
|
for token in reversed(self): # Reverse, so we get tokens in order
|
2015-05-13 22:45:19 +03:00
|
|
|
|
for left in token.lefts:
|
|
|
|
|
if left.i < self.start:
|
|
|
|
|
yield left
|
|
|
|
|
|
2015-07-11 23:15:04 +03:00
|
|
|
|
property rights:
|
2017-05-18 23:17:24 +03:00
|
|
|
|
"""Tokens that are to the right of the Span, whose head is within the
|
|
|
|
|
`Span`.
|
2017-04-01 11:19:01 +03:00
|
|
|
|
|
2017-05-18 23:17:24 +03:00
|
|
|
|
YIELDS (Token): A right-child of a token of the span.
|
2016-11-01 14:25:36 +03:00
|
|
|
|
"""
|
2015-05-13 22:45:19 +03:00
|
|
|
|
def __get__(self):
|
|
|
|
|
for token in self:
|
|
|
|
|
for right in token.rights:
|
|
|
|
|
if right.i >= self.end:
|
|
|
|
|
yield right
|
|
|
|
|
|
2017-10-27 18:07:26 +03:00
|
|
|
|
property n_lefts:
|
|
|
|
|
"""RETURNS (int): The number of leftward immediate children of the
|
|
|
|
|
span, in the syntactic dependency parse.
|
|
|
|
|
"""
|
2017-10-27 19:09:28 +03:00
|
|
|
|
def __get__(self):
|
2017-11-01 15:25:12 +03:00
|
|
|
|
return len(list(self.lefts))
|
2017-10-27 18:07:26 +03:00
|
|
|
|
|
|
|
|
|
property n_rights:
|
|
|
|
|
"""RETURNS (int): The number of rightward immediate children of the
|
|
|
|
|
span, in the syntactic dependency parse.
|
|
|
|
|
"""
|
2017-10-27 19:09:28 +03:00
|
|
|
|
def __get__(self):
|
2017-11-01 15:25:12 +03:00
|
|
|
|
return len(list(self.rights))
|
2017-10-27 18:07:26 +03:00
|
|
|
|
|
2015-07-09 18:30:58 +03:00
|
|
|
|
property subtree:
|
2017-05-18 23:17:24 +03:00
|
|
|
|
"""Tokens that descend from tokens in the span, but fall outside it.
|
2016-11-01 14:25:36 +03:00
|
|
|
|
|
2017-05-18 23:17:24 +03:00
|
|
|
|
YIELDS (Token): A descendant of a token within the span.
|
2016-11-01 14:25:36 +03:00
|
|
|
|
"""
|
2015-07-09 18:30:58 +03:00
|
|
|
|
def __get__(self):
|
|
|
|
|
for word in self.lefts:
|
|
|
|
|
yield from word.subtree
|
|
|
|
|
yield from self
|
|
|
|
|
for word in self.rights:
|
|
|
|
|
yield from word.subtree
|
|
|
|
|
|
2016-09-21 15:54:55 +03:00
|
|
|
|
property ent_id:
|
2017-10-27 18:07:26 +03:00
|
|
|
|
"""RETURNS (uint64): The entity ID."""
|
2016-09-21 15:54:55 +03:00
|
|
|
|
def __get__(self):
|
|
|
|
|
return self.root.ent_id
|
|
|
|
|
|
|
|
|
|
def __set__(self, hash_t key):
|
|
|
|
|
raise NotImplementedError(
|
2017-10-27 16:41:45 +03:00
|
|
|
|
"Can't yet set ent_id from Span. Vote for this feature on "
|
|
|
|
|
"the issue tracker: http://github.com/explosion/spaCy/issues")
|
2017-05-18 23:17:24 +03:00
|
|
|
|
|
2016-09-21 15:54:55 +03:00
|
|
|
|
property ent_id_:
|
2017-10-27 18:07:26 +03:00
|
|
|
|
"""RETURNS (unicode): The (string) entity ID."""
|
2016-09-21 15:54:55 +03:00
|
|
|
|
def __get__(self):
|
|
|
|
|
return self.root.ent_id_
|
|
|
|
|
|
|
|
|
|
def __set__(self, hash_t key):
|
|
|
|
|
raise NotImplementedError(
|
2017-10-27 16:41:45 +03:00
|
|
|
|
"Can't yet set ent_id_ from Span. Vote for this feature on the "
|
|
|
|
|
"issue tracker: http://github.com/explosion/spaCy/issues")
|
2016-09-21 15:54:55 +03:00
|
|
|
|
|
2015-03-26 05:16:40 +03:00
|
|
|
|
property orth_:
|
2017-10-27 16:41:45 +03:00
|
|
|
|
"""Verbatim text content (identical to Span.text). Exists mostly for
|
|
|
|
|
consistency with other attributes.
|
|
|
|
|
|
|
|
|
|
RETURNS (unicode): The span's text."""
|
2015-03-26 05:16:40 +03:00
|
|
|
|
def __get__(self):
|
2017-11-20 21:04:06 +03:00
|
|
|
|
return self.text
|
2015-03-26 05:16:40 +03:00
|
|
|
|
|
|
|
|
|
property lemma_:
|
2017-10-27 18:07:26 +03:00
|
|
|
|
"""RETURNS (unicode): The span's lemma."""
|
2015-03-26 05:16:40 +03:00
|
|
|
|
def __get__(self):
|
2015-03-26 05:45:11 +03:00
|
|
|
|
return ' '.join([t.lemma_ for t in self]).strip()
|
2017-03-11 03:50:02 +03:00
|
|
|
|
|
|
|
|
|
property upper_:
|
2017-10-27 16:41:45 +03:00
|
|
|
|
"""Deprecated. Use Span.text.upper() instead."""
|
2017-03-11 03:50:02 +03:00
|
|
|
|
def __get__(self):
|
2017-10-27 16:41:45 +03:00
|
|
|
|
return ''.join([t.text_with_ws.upper() for t in self]).strip()
|
2017-03-11 03:50:02 +03:00
|
|
|
|
|
|
|
|
|
property lower_:
|
2017-10-27 16:41:45 +03:00
|
|
|
|
"""Deprecated. Use Span.text.lower() instead."""
|
2017-03-11 03:50:02 +03:00
|
|
|
|
def __get__(self):
|
2017-10-27 16:41:45 +03:00
|
|
|
|
return ''.join([t.text_with_ws.lower() for t in self]).strip()
|
2015-03-26 05:16:40 +03:00
|
|
|
|
|
2015-03-27 19:40:52 +03:00
|
|
|
|
property string:
|
2017-10-27 18:07:26 +03:00
|
|
|
|
"""Deprecated: Use Span.text_with_ws instead."""
|
2015-03-27 19:40:52 +03:00
|
|
|
|
def __get__(self):
|
2017-10-27 16:41:45 +03:00
|
|
|
|
return ''.join([t.text_with_ws for t in self])
|
2015-03-27 19:40:52 +03:00
|
|
|
|
|
2015-03-26 05:16:40 +03:00
|
|
|
|
property label_:
|
2017-10-27 18:07:26 +03:00
|
|
|
|
"""RETURNS (unicode): The span's label."""
|
2015-03-26 05:16:40 +03:00
|
|
|
|
def __get__(self):
|
2015-09-29 16:03:55 +03:00
|
|
|
|
return self.doc.vocab.strings[self.label]
|
2015-03-26 05:16:40 +03:00
|
|
|
|
|
2016-01-16 17:38:50 +03:00
|
|
|
|
|
|
|
|
|
cdef int _count_words_to_root(const TokenC* token, int sent_length) except -1:
|
2016-02-06 15:37:41 +03:00
|
|
|
|
# Don't allow spaces to be the root, if there are
|
|
|
|
|
# better candidates
|
|
|
|
|
if Lexeme.c_check_flag(token.lex, IS_SPACE) and token.l_kids == 0 and token.r_kids == 0:
|
|
|
|
|
return sent_length-1
|
|
|
|
|
if Lexeme.c_check_flag(token.lex, IS_PUNCT) and token.l_kids == 0 and token.r_kids == 0:
|
|
|
|
|
return sent_length-1
|
2016-01-16 17:38:50 +03:00
|
|
|
|
cdef int n = 0
|
|
|
|
|
while token.head != 0:
|
|
|
|
|
token += token.head
|
|
|
|
|
n += 1
|
|
|
|
|
if n >= sent_length:
|
|
|
|
|
raise RuntimeError(
|
2017-10-27 16:41:45 +03:00
|
|
|
|
"Array bounds exceeded while searching for root word. This "
|
|
|
|
|
"likely means the parse tree is in an invalid state. Please "
|
|
|
|
|
"report this issue here: "
|
|
|
|
|
"http://github.com/explosion/spaCy/issues")
|
2016-01-16 17:38:50 +03:00
|
|
|
|
return n
|