index
int64
0
731k
package
stringlengths
2
98
name
stringlengths
1
76
docstring
stringlengths
0
281k
code
stringlengths
4
1.07M
signature
stringlengths
2
42.8k
57,315
estnltk_core.layer.layer
__getattr__
null
def __getattr__(self, item): if item in self.__getattribute__('attributes'): return self.__getitem__(item) return self.resolve_attribute(item)
(self, item)
57,316
estnltk_core.layer.base_layer
__getitem__
null
def __getitem__(self, item) -> Union[Span, 'BaseLayer', 'Layer', AmbiguousAttributeTupleList]: if isinstance(item, int): # Expected call: layer[index] # Returns Span return self._span_list[item] if isinstance(item, BaseSpan): # Example call: layer[ parent_layer[0].base_span ] # Returns Span return self._span_list.get(item) if item == [] or item == (): # Unexpected call: layer[[]] raise IndexError('no attributes: ' + str(item)) if isinstance(item, str) or isinstance(item, (list, tuple)) and all(isinstance(s, str) for s in item): # Expected call: layer[attribute] or layer[attributes] # Returns AmbiguousAttributeTupleList if isinstance(item, (list, tuple)): # Separate regular attributes from index attributes attributes = \ [attr for attr in item if attr not in ['start', 'end'] or attr in self.attributes] index_attributes = \ [attr for attr in item if attr in ['start', 'end'] and attr not in self.attributes] return self.attribute_values(attributes, index_attributes=index_attributes) return self.attribute_values(item) if isinstance(item, tuple) and len(item) == 2: # Expected call: layer[indexes, attributes] # Check that the first item specifies an index or a range indexes # Can also be a callable function validating suitable spans first_ok = callable(item[0]) or \ isinstance(item[0], (int, slice)) or \ (isinstance(item[0], (tuple, list)) and all(isinstance(i, int) for i in item[0])) # Check that the second item specifies an attribute or a list of attributes second_ok = isinstance(item[1], str) or \ isinstance(item[1], (list, tuple)) and all(isinstance(i, str) for i in item[1]) if first_ok and second_ok: if isinstance(item[0], int): # Select attribute(s) of a single span # Example: text.morph_analysis[0, ['partofspeech', 'lemma']] # Returns Span -> List return self[item[1]][item[0]] # Select attribute(s) over multiple spans # Example: text.morph_analysis[0:5, ['partofspeech', 'lemma']] # Returns AmbiguousAttributeTupleList return self[item[0]][item[1]] # If not first_ok or not second_ok, then we need to check # if this could be a list call with 2-element list, see below # for details layer = self.__class__(name=self.name, attributes=self.attributes, secondary_attributes=self.secondary_attributes, text_object=self.text_object, parent=self.parent, enveloping=self.enveloping, ambiguous=self.ambiguous, default_values=self.default_values) # keep the span level same layer._span_list = SpanList(span_level=self.span_level) if isinstance(item, slice): # Expected call: layer[start:end] # Returns Layer wrapped = self._span_list.spans.__getitem__(item) layer._span_list.spans = wrapped return layer if isinstance(item, (list, tuple)): if all(isinstance(i, bool) for i in item): # Expected call: layer[list_of_bools] # Returns Layer if len(item) != len(self): warnings.warn('Index boolean list not equal to length of layer: {}!={}'.format(len(item), len(self))) wrapped = [s for s, i in zip(self._span_list.spans, item) if i] layer._span_list.spans = wrapped return layer if all(isinstance(i, int) and not isinstance(i, bool) for i in item): # Expected call: layer[list_of_indexes] # Returns Layer wrapped = [self._span_list.spans.__getitem__(i) for i in item] layer._span_list.spans = wrapped return layer if all(isinstance(i, BaseSpan) for i in item): # Expected call: layer[list_of_base_span] # Returns Layer wrapped = [self._span_list.get(i) for i in item] layer._span_list.spans = wrapped return layer if callable(item): # Expected call: layer[selector_function] # Returns Layer wrapped = [span for span in self._span_list.spans if item(span)] layer._span_list.spans = wrapped return layer raise TypeError('index not supported: ' + str(item))
(self, item) -> Union[estnltk_core.layer.span.Span, ForwardRef('BaseLayer'), ForwardRef('Layer'), estnltk_core.layer.attribute_list.ambiguous_attribute_tuple_list.AmbiguousAttributeTupleList]
57,317
estnltk_core.layer.base_layer
__init__
Initializes a new BaseLayer object based on given configuration. Parameter `name` is mandatory and should be a descriptive name of the layer. It is advisable to use layer names that are legitimate Pyhton attribute names (e.g. 'morphology', 'syntax_layer') and are not attributes of text objects. Otherwise, the layer is accessible only with indexing operator. Parameter `attributes` lists legal attribute names for the layer. If an annotation is added to the layer, only values of legal attributes will be added, and values of illegal attributes will be ignored. Parameter `secondary_attributes` lists names of layer's attributes which will be skipped while comparing two layers. Usually this means that these attributes contain redundant information. Another reason for marking attribute as secondary is avoiding (infinite) recursion in comparison. For instance, attributes referring to parent and children spans in the syntax layer are marked as secondary, because they are recursive and comparing recursive spans is not supported. All secondary attributes must also be present in `attributes`. Parameter `text_object` specifies the Text object of this layer. Note that the Text object becomes fully connected with the layer only after text.add_layer( layer ) has been called. Parameter `parent` is used to specify the name of the parent layer, declaring that each span of this layer has a parent span on the parent layer. For instance, 'morph_analysis' layer takes 'words' layer as a parent, because morphological properties can be described on each word. Parameter `enveloping` specifies the name of the layer this layer envelops, meaning that each span of this layer envelops (wraps around) multiple spans of that layer. For instance, 'sentences' layer is enveloping around 'words' layer, and 'paragraphs' layer is enveloping around 'sentences' layer. Note that `parent` and `enveloping` cannot be set simultaneously -- one of them must be None. If ambiguous is set, then this layer can have multiple annotations on the same location (same span). Parameter `default_values` can be used to specify default values for `attributes` in case they are missing from the annotation. If not specified, missing attributes will obtain None values. Parameter `serialisation_module` specifies name of the serialisation module. If left unspecified, then default serialisation module is used.
def __init__(self, name: str, attributes: Sequence[str] = (), secondary_attributes: Sequence[str] = (), text_object: Union['BaseText','Text']=None, parent: str = None, enveloping: str = None, ambiguous: bool = False, default_values: dict = None, serialisation_module=None ) -> None: """ Initializes a new BaseLayer object based on given configuration. Parameter `name` is mandatory and should be a descriptive name of the layer. It is advisable to use layer names that are legitimate Pyhton attribute names (e.g. 'morphology', 'syntax_layer') and are not attributes of text objects. Otherwise, the layer is accessible only with indexing operator. Parameter `attributes` lists legal attribute names for the layer. If an annotation is added to the layer, only values of legal attributes will be added, and values of illegal attributes will be ignored. Parameter `secondary_attributes` lists names of layer's attributes which will be skipped while comparing two layers. Usually this means that these attributes contain redundant information. Another reason for marking attribute as secondary is avoiding (infinite) recursion in comparison. For instance, attributes referring to parent and children spans in the syntax layer are marked as secondary, because they are recursive and comparing recursive spans is not supported. All secondary attributes must also be present in `attributes`. Parameter `text_object` specifies the Text object of this layer. Note that the Text object becomes fully connected with the layer only after text.add_layer( layer ) has been called. Parameter `parent` is used to specify the name of the parent layer, declaring that each span of this layer has a parent span on the parent layer. For instance, 'morph_analysis' layer takes 'words' layer as a parent, because morphological properties can be described on each word. Parameter `enveloping` specifies the name of the layer this layer envelops, meaning that each span of this layer envelops (wraps around) multiple spans of that layer. For instance, 'sentences' layer is enveloping around 'words' layer, and 'paragraphs' layer is enveloping around 'sentences' layer. Note that `parent` and `enveloping` cannot be set simultaneously -- one of them must be None. If ambiguous is set, then this layer can have multiple annotations on the same location (same span). Parameter `default_values` can be used to specify default values for `attributes` in case they are missing from the annotation. If not specified, missing attributes will obtain None values. Parameter `serialisation_module` specifies name of the serialisation module. If left unspecified, then default serialisation module is used. """ default_values = default_values or {} assert isinstance(default_values, dict) self.default_values = default_values self.attributes = attributes self.secondary_attributes = secondary_attributes # name of the layer assert name is not None and len(name) > 0 and not name.isspace(), \ 'layer name cannot be empty or consist of only whitespaces {!r}'.format(name) self.name = name assert parent is None or enveloping is None, "can't be derived AND enveloping" self.parent = parent self.enveloping = enveloping self._span_list = SpanList() self.ambiguous = ambiguous self.text_object = text_object self.serialisation_module = serialisation_module self.meta = {}
(self, name: str, attributes: Sequence[str] = (), secondary_attributes: Sequence[str] = (), text_object: Union[ForwardRef('BaseText'), ForwardRef('Text')] = None, parent: str = None, enveloping: str = None, ambiguous: bool = False, default_values: dict = None, serialisation_module=None) -> None
57,318
estnltk_core.layer.base_layer
__iter__
null
def __iter__(self): return iter(self._span_list.spans)
(self)
57,319
estnltk_core.layer.base_layer
__len__
null
def __len__(self): return len(self._span_list)
(self)
57,320
estnltk_core.layer.base_layer
__repr__
null
def __repr__(self): return '{classname}(name={self.name!r}, attributes={self.attributes}, spans={self._span_list})'.format(classname=self.__class__.__name__, self=self)
(self)
57,321
estnltk_core.layer.layer
__setattr__
null
def __setattr__(self, key, value): if key == 'attributes': # check attributes: add userwarnings in case of # problematic attribute names attributes = value if isinstance(attributes, (list, tuple)) and all([isinstance(attr,str) for attr in attributes]): # Warn if user wants to use non-identifiers as argument names nonidentifiers = [attr for attr in attributes if not attr.isidentifier()] if nonidentifiers: warnings.warn(('Attribute names {!r} are not valid Python identifiers. '+\ 'This can hinder setting and accessing attribute values.'+\ '').format(nonidentifiers)) # Warn if user wants to use 'text', 'start', 'end' as attribute names overlapping_props = [attr for attr in attributes if attr in ['text', 'start', 'end']] if overlapping_props: warnings.warn(('Attribute names {!r} overlap with Span/Annotation property names. '+\ 'This can hinder setting and accessing attribute values.'+\ '').format(overlapping_props)) super().__setattr__(key, value)
(self, key, value)
57,322
estnltk_core.layer.base_layer
__setitem__
null
def __setitem__(self, key: int, value: Span): self._span_list[key] = value
(self, key: int, value: estnltk_core.layer.span.Span)
57,323
estnltk_core.layer.base_layer
_repr_html_
null
def _repr_html_(self): if self.meta: data = {'key': sorted(self.meta), 'value': [self.meta[k] for k in sorted(self.meta)]} meta_table = pandas.DataFrame(data, columns=['key', 'value']) meta_table = meta_table.to_html(header=False, index=False) meta = '\n'.join(('<h4>Metadata</h4>', meta_table)) else: meta = '' index_attributes = [] if self.text_object is None: text_object = 'No Text object.' else: index_attributes.append('text') text_object = '' if self.print_start_end: index_attributes.extend(['start', 'end']) attributes = self.attributes[:] if not attributes and not index_attributes: index_attributes = ['start', 'end'] table_1 = self.get_overview_dataframe().to_html(index=False, escape=False) table_2 = '' if attributes or index_attributes: table_2 = self.attribute_values(attributes, index_attributes=index_attributes).to_html(index='text') return '\n'.join(('<h4>{}</h4>'.format(self.__class__.__name__), meta, text_object, table_1, table_2))
(self)
57,324
estnltk_core.layer.base_layer
add_annotation
Adds new annotation (from `attribute_dict` / `attribute_kwargs`) to given text location `base_span`. For non-enveloping layer, the location `base_span` can be: * (start, end) -- integer tuple; * ElementaryBaseSpan; * Span; For enveloping layer, the `base_span` can be: * [(start_1, end_1), ... (start_N, end_N)] -- list of integer tuples; * EnvelopingBaseSpan; * EnvelopingSpan; * BaseLayer if the layer is enveloping; `attribute_dict` should contain attribute assignments for the annotation. Example: layer.add_annotation( base_span, {'attr1': ..., 'attr2': ...} ) Missing attributes will be filled in with layer's default_values (None values, if defaults have not been explicitly set). Optionally, you can leave `attribute_dict` unspecified and pass keyword arguments to the method via `attribute_kwargs`, for example: layer.add_annotation( base_span, attr1=..., attr2=... ) While keyword arguments can only be valid Python keywords (excluding the keyword 'base_span'), `attribute_dict` enables to bypass these restrictions while giving the attribute assignments. The priority order in setting value of an attribute is: `attribute_kwargs` > `attribute_dict` > `default attributes` (e.g. if the attribute has a default value, and it is set both in `attribute_dict` and in `attribute_kwargs`, then `attribute_kwargs` will override other assignments). The method returns added annotation. Note 1: you can add two or more annotations to exactly the same `base_span` location only if the layer is ambiguous. however, partially overlapping locations are always allowed. Note 2: in case of an enveloping layer, all basespans must be at the same level. For instance, if you add an enveloping span [(1,2), (2,3)], which corresponds to level 1, you cannot add level 2 span [ [(1,2), (2,3)], [(4,5)]].
def add_annotation(self, base_span, attribute_dict: Dict[str, Any]={}, **attribute_kwargs) -> Annotation: """Adds new annotation (from `attribute_dict` / `attribute_kwargs`) to given text location `base_span`. For non-enveloping layer, the location `base_span` can be: * (start, end) -- integer tuple; * ElementaryBaseSpan; * Span; For enveloping layer, the `base_span` can be: * [(start_1, end_1), ... (start_N, end_N)] -- list of integer tuples; * EnvelopingBaseSpan; * EnvelopingSpan; * BaseLayer if the layer is enveloping; `attribute_dict` should contain attribute assignments for the annotation. Example: layer.add_annotation( base_span, {'attr1': ..., 'attr2': ...} ) Missing attributes will be filled in with layer's default_values (None values, if defaults have not been explicitly set). Optionally, you can leave `attribute_dict` unspecified and pass keyword arguments to the method via `attribute_kwargs`, for example: layer.add_annotation( base_span, attr1=..., attr2=... ) While keyword arguments can only be valid Python keywords (excluding the keyword 'base_span'), `attribute_dict` enables to bypass these restrictions while giving the attribute assignments. The priority order in setting value of an attribute is: `attribute_kwargs` > `attribute_dict` > `default attributes` (e.g. if the attribute has a default value, and it is set both in `attribute_dict` and in `attribute_kwargs`, then `attribute_kwargs` will override other assignments). The method returns added annotation. Note 1: you can add two or more annotations to exactly the same `base_span` location only if the layer is ambiguous. however, partially overlapping locations are always allowed. Note 2: in case of an enveloping layer, all basespans must be at the same level. For instance, if you add an enveloping span [(1,2), (2,3)], which corresponds to level 1, you cannot add level 2 span [ [(1,2), (2,3)], [(4,5)]]. """ base_span = to_base_span(base_span) # Make it clear, if we got non-enveloping or enveloping span properly # (otherwise we may run into obscure error messages later) if self.enveloping is not None and not isinstance(base_span, EnvelopingBaseSpan): raise TypeError('Cannot add {!r} to enveloping layer. Enveloping span is required.'.format(base_span)) elif self.enveloping is None and isinstance(base_span, EnvelopingBaseSpan): # TODO: A tricky situation is when the parent is enveloping -- should allow EnvelopingBaseSpan then? # And how can we get the parent layer if it is not attached to the Text object? raise TypeError('Cannot add {!r} to non-enveloping layer. Elementary span is required.'.format(base_span)) if not isinstance(attribute_dict, dict): raise ValueError('(!) attribute_dict should be an instance of dict, not {}'.format(type(attribute_dict))) attributes = {**self.default_values, \ **{k: v for k, v in attribute_dict.items() if k in self.attributes}, \ **{k: v for k, v in attribute_kwargs.items() if k in self.attributes}} span = self.get(base_span) if self.enveloping is not None: if span is None: # add to new span span = EnvelopingSpan(base_span=base_span, layer=self) annotation = span.add_annotation(Annotation(span, attributes)) self.add_span(span) else: # add to existing span if isinstance(span, EnvelopingSpan): annotation = span.add_annotation(Annotation(span, attributes)) else: # Normally, self.get(base_span) should return EnvelopingSpan for the # enveloping layer. If it returned BaseLayer instead, then we are most # likely in a situation where the level of the base_span mismatches # the level of the layer. assert self.span_level is not None if self.span_level != base_span.level: raise ValueError( ('(!) Mismatching base_span levels: span level of this layer is {}, '+\ 'while level of the new span is {}').format( self.span_level, base_span.level ) ) raise ValueError(('(!) Unexpected base_span {!r}.'+\ ' Unable to find layer span corresponding to this base_span.').format(base_span)) return annotation if self.ambiguous: if span is None: # add to new span span = Span(base_span, self) annotation = span.add_annotation(Annotation(span, attributes)) self.add_span(span) else: # add to existing span assert isinstance(span, Span), span annotation = span.add_annotation(Annotation(span, attributes)) return annotation if span is not None: raise ValueError('the layer is not ambiguous and already contains this span') # add to new span span = Span(base_span=base_span, layer=self) annotation = span.add_annotation(Annotation(span, attributes)) self.add_span(span) return annotation
(self, base_span, attribute_dict: Dict[str, Any] = {}, **attribute_kwargs) -> estnltk_core.layer.annotation.Annotation
57,325
estnltk_core.layer.base_layer
add_span
Adds new Span (or EnvelopingSpan) to this layer. Before adding, span will be validated: * the span must have at least one annotation; * the span must have exactly one annotation (if the layer is not ambiguous); * the span belongs to this layer; * the base_span of the new span matches the span level of this layer; Note that you cannot add two Spans (EnvelopingSpans) that have exactly the same text location (base span); however, partially overlapping spans are allowed.
def add_span(self, span: Span) -> Span: """Adds new Span (or EnvelopingSpan) to this layer. Before adding, span will be validated: * the span must have at least one annotation; * the span must have exactly one annotation (if the layer is not ambiguous); * the span belongs to this layer; * the base_span of the new span matches the span level of this layer; Note that you cannot add two Spans (EnvelopingSpans) that have exactly the same text location (base span); however, partially overlapping spans are allowed. """ assert isinstance(span, Span), str(type(span)) assert len(span.annotations) > 0, span assert self.ambiguous or len(span.annotations) == 1, span assert span.layer is self, span.layer if self.get(span) is not None: raise ValueError('this layer already has a span with the same base span') if self.span_level is not None: # Check that level of the new (base)span matches the span level of this layer # ( all basespans in the layer should be at the same level ) if self.span_level != span.base_span.level: raise ValueError( ('(!) Mismatching base_span levels: span level of this layer is {}, '+\ 'while level of the new span is {}').format( self.span_level, span.base_span.level ) ) self._span_list.add_span(span) return span
(self, span: estnltk_core.layer.span.Span) -> estnltk_core.layer.span.Span
57,326
estnltk_core.layer.layer
ancestor_layers
Finds all layers that given layer depends on (ancestor layers). Returns names of ancestor layers in alphabetical order.
def ancestor_layers(self) -> List[str]: """Finds all layers that given layer depends on (ancestor layers). Returns names of ancestor layers in alphabetical order. """ if self.text_object is None: raise Exception('(!) Cannot find ancestor layers: the layer is detached from Text object.') ancestors = find_layer_dependencies(self.text_object, self.name, reverse=False) return sorted(ancestors)
(self) -> List[str]
57,327
estnltk_core.layer.base_layer
attribute_values
Returns a matrix-like data structure containing all annotations of this layer with the selected attributes. Usage examples: >>> from estnltk import Text >>> text = Text('Kirjule kassile').tag_layer('morph_analysis') >>> # select 'partofspeech' attributes from the 'morph_analysis' layer >>> text['morph_analysis'].attribute_values('partofspeech') [['A'], ['S']] >>> text = Text('Kirjule kassile').tag_layer('morph_analysis') >>> # select 'lemma' & 'partofspeech' attributes from the 'morph_analysis' layer >>> text['morph_analysis'].attribute_values(['lemma', 'partofspeech']) [[['kirju', 'A']], [['kass', 'S']]] Optional parameter `index_attributes` can be a list of span's indexing attributes ('start', 'end', 'text'), which will be prepended to attributes: Example: >>> text = Text('Kirjule kassile').tag_layer('morph_analysis') >>> # select 'partofspeech' from the 'morph_analysis' layer and prepend surface text strings >>> text['morph_analysis'].attribute_values('partofspeech', index_attributes=['text']) [[['Kirjule', 'A']], [['kassile', 'S']]] Note: for a successful selection, you should provide at least one regular or index attribute; a selection without any attributes raises IndexError. Parameters ---------- attributes: Union[str, List[str]] layer's attribute or attributes which values will be selected index_attributes: Union[str, List[str]] layer's indexing attributes ('start', 'end' or 'text') which values will be selected Returns -------- AmbiguousAttributeTupleList * AttributeList -- if the layer is not ambiguous and only one attribute was selected; * AttributeTupleList -- if the layer is not ambiguous and more than one attributes were selected; * AmbiguousAttributeList -- if the layer is ambiguous and only one attribute was selected; * AmbiguousAttributeTupleList -- if the layer is ambiguous and more than one attributes were selected;
def attribute_values(self, attributes, index_attributes=[]): """Returns a matrix-like data structure containing all annotations of this layer with the selected attributes. Usage examples: >>> from estnltk import Text >>> text = Text('Kirjule kassile').tag_layer('morph_analysis') >>> # select 'partofspeech' attributes from the 'morph_analysis' layer >>> text['morph_analysis'].attribute_values('partofspeech') [['A'], ['S']] >>> text = Text('Kirjule kassile').tag_layer('morph_analysis') >>> # select 'lemma' & 'partofspeech' attributes from the 'morph_analysis' layer >>> text['morph_analysis'].attribute_values(['lemma', 'partofspeech']) [[['kirju', 'A']], [['kass', 'S']]] Optional parameter `index_attributes` can be a list of span's indexing attributes ('start', 'end', 'text'), which will be prepended to attributes: Example: >>> text = Text('Kirjule kassile').tag_layer('morph_analysis') >>> # select 'partofspeech' from the 'morph_analysis' layer and prepend surface text strings >>> text['morph_analysis'].attribute_values('partofspeech', index_attributes=['text']) [[['Kirjule', 'A']], [['kassile', 'S']]] Note: for a successful selection, you should provide at least one regular or index attribute; a selection without any attributes raises IndexError. Parameters ---------- attributes: Union[str, List[str]] layer's attribute or attributes which values will be selected index_attributes: Union[str, List[str]] layer's indexing attributes ('start', 'end' or 'text') which values will be selected Returns -------- AmbiguousAttributeTupleList * AttributeList -- if the layer is not ambiguous and only one attribute was selected; * AttributeTupleList -- if the layer is not ambiguous and more than one attributes were selected; * AmbiguousAttributeList -- if the layer is ambiguous and only one attribute was selected; * AmbiguousAttributeTupleList -- if the layer is ambiguous and more than one attributes were selected; """ if not isinstance(attributes, (str, list, tuple)): raise TypeError( 'Unexpected type for attributes:'.format( str(type(attributes)) ) ) if not isinstance(index_attributes, (str, list, tuple)): raise TypeError( 'Unexpected type for index_attributes:'.format( str(type(index_attributes)) ) ) number_of_layer_attrs = \ len(attributes) if isinstance(attributes, (list, tuple)) else (0 if not attributes else 1) number_of_index_attrs = \ len(index_attributes) if isinstance(index_attributes, (list, tuple)) else (0 if not index_attributes else 1) if number_of_layer_attrs + number_of_index_attrs == 0: raise IndexError('no attributes: ' + str(attributes)) if self.ambiguous: if (number_of_layer_attrs + number_of_index_attrs) > 1 or \ isinstance(attributes, (list, tuple)): # selected: more than 1 attributes at total or # at least 1 layer attribute in a list (for backwards compatibility) result = AmbiguousAttributeTupleList(self.spans, attributes, span_index_attributes=index_attributes) elif number_of_layer_attrs + number_of_index_attrs == 1: # only attribute index_attr = index_attributes if len(index_attributes) > 0 else None result = AmbiguousAttributeList(self.spans, attributes, index_attribute_name=index_attr) else: if (number_of_layer_attrs + number_of_index_attrs) > 1 or \ isinstance(attributes, (list, tuple)): # selected: more than 1 attributes at total or # at least 1 layer attribute in a list (for backwards compatibility) result = AttributeTupleList(self.spans, attributes, span_index_attributes=index_attributes) elif number_of_layer_attrs + number_of_index_attrs == 1: # only attribute index_attr = index_attributes if len(index_attributes) > 0 else None result = AttributeList(self.spans, attributes, index_attribute_name=index_attr) return result
(self, attributes, index_attributes=[])
57,328
estnltk_core.layer.base_layer
check_span_consistency
Checks for layer's span consistency. Checks that: * all spans are attached to this layer; * spans of the layer are sorted; * each span has at least one annotation; * each span has at exactly one annotation if the layer is not ambiguous; * all annotations have exactly the same attributes as the layer; Returns None if no inconsistencies were detected; otherwise, returns a string message describing the problem. This method is mainly used by Retagger to validate that changes made in the layer do not break the span consistency.
def check_span_consistency(self) -> Optional[str]: """Checks for layer's span consistency. Checks that: * all spans are attached to this layer; * spans of the layer are sorted; * each span has at least one annotation; * each span has at exactly one annotation if the layer is not ambiguous; * all annotations have exactly the same attributes as the layer; Returns None if no inconsistencies were detected; otherwise, returns a string message describing the problem. This method is mainly used by Retagger to validate that changes made in the layer do not break the span consistency. """ attribute_names = set(self.attributes) last_span = None for span in self: if span.layer is not self: return '{} is not attached to this layer'.format(span) if last_span is not None and not last_span < span: if last_span.base_span == span.base_span: return 'duplicate spans: {!r} and {!r} (both have basespan {})'.format( \ last_span, span, last_span.base_span ) return 'ordering problem: {!r} should precede {!r}'.format(last_span, span) last_span = span annotations = span.annotations if len(annotations) == 0: return '{} has no annotations'.format(span) if not self.ambiguous and len(annotations) > 1: return 'the layer is not ambiguous but {} has {} annotations'.format(span, len(annotations)) for annotation in annotations: if set(annotation) != attribute_names: return '{!r} has redundant annotation attributes: {}, missing annotation attributes: {}'.format( \ span, set(annotation) - attribute_names, attribute_names - set(annotation) ) return None
(self) -> Optional[str]
57,329
estnltk_core.layer.base_layer
clear_spans
Removes all spans (and annotations) from this layer. Note: Clearing preserves the span level of the layer.
def clear_spans(self): """Removes all spans (and annotations) from this layer. Note: Clearing preserves the span level of the layer. """ self._span_list = SpanList(span_level=self.span_level)
(self)
57,330
estnltk_core.layer.layer
count_values
Counts attribute values and returns frequency table (collections.Counter). Note: you can also use 'text' as the attribute name to count corresponding surface text strings.
def count_values(self, attribute: str) -> collections.Counter: """Counts attribute values and returns frequency table (collections.Counter). Note: you can also use 'text' as the attribute name to count corresponding surface text strings. """ if self.ambiguous: return collections.Counter(annotation[attribute] if attribute != 'text' else annotation.text \ for span in self.spans for annotation in span.annotations) return collections.Counter( span.annotations[0][attribute] if attribute != 'text' else span.text \ for span in self.spans)
(self, attribute: str) -> collections.Counter
57,331
estnltk_core.layer.layer
descendant_layers
Finds all layers that are depending on the given layer (descendant layers). Returns names of descendant layers in alphabetical order.
def descendant_layers(self) -> List[str]: """Finds all layers that are depending on the given layer (descendant layers). Returns names of descendant layers in alphabetical order. """ if self.text_object is None: raise Exception('(!) Cannot find descendant layers: the layer is detached from Text object.') descendants = find_layer_dependencies(self.text_object, self.name, reverse=True) return sorted(descendants)
(self) -> List[str]
57,332
estnltk_core.layer.base_layer
diff
Finds differences between this layer and the other layer. Checks that both layers: * are instances of BaseLayer; * have same names and attributes; * have same parent and enveloping layers; * are correspondingly ambiguous or unambiguous; * have same serialisation_module; * have same spans (and annotations); Returns None if no differences were detected (both layers are the same or one is exact copy of another), or a message string describing the difference.
def diff(self, other) -> Optional[str]: """Finds differences between this layer and the other layer. Checks that both layers: * are instances of BaseLayer; * have same names and attributes; * have same parent and enveloping layers; * are correspondingly ambiguous or unambiguous; * have same serialisation_module; * have same spans (and annotations); Returns None if no differences were detected (both layers are the same or one is exact copy of another), or a message string describing the difference. """ if self is other: return None if not isinstance(other, BaseLayer): return 'Other is not a Layer.' if self.name != other.name: return "Layer names are different: {self.name}!={other.name}".format(self=self, other=other) if tuple(self.attributes) != tuple(other.attributes): return "{self.name} layer attributes differ: {self.attributes} != {other.attributes}".format(self=self, other=other) if tuple(self.secondary_attributes) != tuple(other.secondary_attributes): return ("{self.name} layer secondary_attributes differ: {self.secondary_attributes} != {other.secondary_attributes}"+\ "").format(self=self, other=other) if self.ambiguous != other.ambiguous: return "{self.name} layer ambiguous differs: {self.ambiguous} != {other.ambiguous}".format(self=self, other=other) if self.parent != other.parent: return "{self.name} layer parent differs: {self.parent} != {other.parent}".format(self=self, other=other) if self.enveloping != other.enveloping: return "{self.name} layer enveloping differs: {self.enveloping}!={other.enveloping}".format(self=self, other=other) if self.serialisation_module != other.serialisation_module: return "{self.name!r} layer dict converter modules are different: " \ "{self.dict_converter_module!r}!={other.dict_converter_module!r}".format(self=self, other=other) if self._span_list != other._span_list: return "{self.name} layer spans differ".format(self=self) return None
(self, other) -> Optional[str]
57,333
estnltk_core.layer.layer
display
null
def display(self, **kwargs): if check_if_estnltk_is_available(): from estnltk.visualisation import DisplaySpans display_spans = DisplaySpans(**kwargs) display_spans(self) else: raise NotImplementedError("Layer display is not available in estnltk-core. Please use the full EstNLTK package for that.")
(self, **kwargs)
57,334
estnltk_core.layer.base_layer
get
Finds and returns Span (or EnvelopingSpan) corresponding to the given (Base)Span item(s). If this layer is empty, returns None. If the parameter item is a sequence of BaseSpans, then returns a new Layer populated with specified spans and bearing the same configuration as this layer. For instance, if you pass a span of the enveloping layer as item, then you'll get a snapshot layer with all the spans of this layer wrapped by the enveloping span: # get a snapshot words-layer bearing all words of the first sentence text['words'].get( text['sentences'][0] )
def get(self, item): """ Finds and returns Span (or EnvelopingSpan) corresponding to the given (Base)Span item(s). If this layer is empty, returns None. If the parameter item is a sequence of BaseSpans, then returns a new Layer populated with specified spans and bearing the same configuration as this layer. For instance, if you pass a span of the enveloping layer as item, then you'll get a snapshot layer with all the spans of this layer wrapped by the enveloping span: # get a snapshot words-layer bearing all words of the first sentence text['words'].get( text['sentences'][0] ) """ if len(self._span_list) == 0: return if isinstance(item, Span): item = item.base_span if isinstance(item, BaseSpan): if self.span_level == item.level: return self._span_list.get(item) item = item.reduce(self.span_level) if isinstance(item, (list, tuple)): layer = self.__class__(name=self.name, attributes=self.attributes, secondary_attributes=self.secondary_attributes, text_object=self.text_object, parent=self.parent, enveloping=self.enveloping, ambiguous=self.ambiguous, default_values=self.default_values) # keep the span level same layer._span_list = SpanList(span_level=self.span_level) wrapped = [self._span_list.get(i) for i in item] assert all(s is not None for s in wrapped) layer._span_list.spans = wrapped return layer raise ValueError(item)
(self, item)
57,335
estnltk_core.layer.base_layer
get_overview_dataframe
Returns DataFrame giving an overview about layer's configuration (name, attributes, parent etc) and status (span count).
def get_overview_dataframe(self): """ Returns DataFrame giving an overview about layer's configuration (name, attributes, parent etc) and status (span count). """ rec = [{'layer name': self.name, 'attributes': ', '.join(self.attributes), 'parent': str(self.parent), 'enveloping': str(self.enveloping), 'ambiguous': str(self.ambiguous), 'span count': str(len(self._span_list.spans))}] return pandas.DataFrame.from_records(rec, columns=['layer name', 'attributes', 'parent', 'enveloping', 'ambiguous', 'span count'])
(self)
57,336
estnltk_core.layer.layer
groupby
Groups layer by attribute values of annotations or by an enveloping layer. Parameters ----------- by: Union[str, Sequence[str], 'Layer'] specifies basis for grouping, which can be either matching attribute values or containment in an enveloping span. More specifically, the parameter `by` can be:: 1) name of an attribute of this layer, 2) list of attribute names of this layer, 3) name of a Layer enveloping around this layer, or 4) Layer object which is a layer enveloping around this layer. Note: you can also use 'text' as an attribute name; in that case, spans / annotations are grouped by their surface text strings. return_type: str (default: 'spans') specifies layer's units which will be grouped. Possible values: "spans" or "annotations". Returns -------- estnltk_core.layer_operations.GroupBy estnltk_core.layer_operations.GroupBy object.
def groupby(self, by: Union[str, Sequence[str], 'Layer'], return_type: str = 'spans') -> GroupBy: """Groups layer by attribute values of annotations or by an enveloping layer. Parameters ----------- by: Union[str, Sequence[str], 'Layer'] specifies basis for grouping, which can be either matching attribute values or containment in an enveloping span. More specifically, the parameter `by` can be:: 1) name of an attribute of this layer, 2) list of attribute names of this layer, 3) name of a Layer enveloping around this layer, or 4) Layer object which is a layer enveloping around this layer. Note: you can also use 'text' as an attribute name; in that case, spans / annotations are grouped by their surface text strings. return_type: str (default: 'spans') specifies layer's units which will be grouped. Possible values: "spans" or "annotations". Returns -------- estnltk_core.layer_operations.GroupBy estnltk_core.layer_operations.GroupBy object. """ if isinstance(by, str): if by in self.attributes: # Group by a single attribute of this Layer return GroupBy(layer=self, by=[ by ], return_type=return_type) elif self.text_object is not None and by in self.text_object.layers: # Group by a Layer (using given layer name) return GroupBy(layer=self, by = self.text_object[by], return_type=return_type) raise ValueError(by) elif isinstance(by, Sequence) and all(isinstance(b, str) for b in by): # Group by multiple attributes of this Layer return GroupBy(layer=self, by=by, return_type=return_type) elif isinstance(by, Layer): # Group by a Layer return GroupBy(layer=self, by=by, return_type=return_type) raise ValueError( ('Unexpected grouping parameter by={!r}. The parameter '+\ 'should be either an enveloping Layer (layer name or object) '+\ 'or attribute(s) of this layer (a single attribute name '+\ 'or a list of names).').format(by) )
(self, by: Union[str, Sequence[str], estnltk_core.layer.layer.Layer], return_type: str = 'spans') -> estnltk_core.layer_operations.aggregators.groupby.GroupBy
57,337
estnltk_core.layer.base_layer
index
Returns the index of the given span in this layer. Use this to find the location of the span. TODO: this is only used in legacy serialization, so it can also be deprecated/removed if there are no other usages.
def index(self, x, *args) -> int: '''Returns the index of the given span in this layer. Use this to find the location of the span. TODO: this is only used in legacy serialization, so it can also be deprecated/removed if there are no other usages. ''' return self._span_list.index(x, *args)
(self, x, *args) -> int
57,338
estnltk_core.layer.base_layer
remove_span
Removes given span from the layer.
def remove_span(self, span): """Removes given span from the layer. """ self._span_list.remove_span(span)
(self, span)
57,339
estnltk_core.layer.layer
resolve_attribute
Resolves and returns values of foreign attribute `item`. Values of the attribute will be sought from a foreign layer, which must either: a) share the same base spans with this layer (be a parent or a child), or b) share the same base spans with smaller span level, which means that this layer should envelop around the foreign layer. Note: this method relies on a mapping from attribute names to foreign layer names (`attribute_mapping_for_elementary_layers`), which is defined estnltk's `Text` object. If this layer is attached to estnltk-core's `BaseText` instead, then the method always raises AttributeError.
def resolve_attribute(self, item) -> Union[AmbiguousAttributeList, AttributeList]: """Resolves and returns values of foreign attribute `item`. Values of the attribute will be sought from a foreign layer, which must either: a) share the same base spans with this layer (be a parent or a child), or b) share the same base spans with smaller span level, which means that this layer should envelop around the foreign layer. Note: this method relies on a mapping from attribute names to foreign layer names (`attribute_mapping_for_elementary_layers`), which is defined estnltk's `Text` object. If this layer is attached to estnltk-core's `BaseText` instead, then the method always raises AttributeError. """ if len(self) == 0: raise AttributeError(item, 'layer is empty') attribute_mapping = {} if self.text_object is not None: if hasattr(self.text_object, 'attribute_mapping_for_elementary_layers'): # Attribute mapping for elementary layers is only # defined in Text object, it is missing in BaseText if self.span_level == 0: attribute_mapping = self.text_object.attribute_mapping_for_elementary_layers else: attribute_mapping = self.text_object.attribute_mapping_for_enveloping_layers else: raise AttributeError(item, "Foreign attribute resolving is only available "+\ "if the layer is attached to estnltk.text.Text object.") else: raise AttributeError(item, \ "Unable to resolve foreign attribute: the layer is not attached to Text object." ) if item not in attribute_mapping: raise AttributeError(item, \ "Attribute not defined in attribute_mapping_for_elementary_layers.") target_layer = self.text_object[attribute_mapping[item]] if len(target_layer) == 0: return AttributeList([], item) result = [target_layer.get(span.base_span) for span in self] target_level = target_layer.span_level self_level = self.span_level if target_level > self_level: raise AttributeError(item, \ ("Unable to resolve foreign attribute: target layer {!r} has higher "+\ "span level than this layer.").format( target_layer.name ) ) if target_level == self_level and target_layer.ambiguous: assert all([isinstance(s, Span) for s in result]) return AmbiguousAttributeList(result, item) assert all([isinstance(l, BaseLayer) for l in result]) return AttributeList(result, item, index_type='layers')
(self, item) -> Union[estnltk_core.layer.attribute_list.ambiguous_attribute_list.AmbiguousAttributeList, estnltk_core.layer.attribute_list.attribute_list.AttributeList]
57,340
estnltk_core.layer.layer
rolling
Creates an iterable object yielding span sequences from a window rolling over the layer. Parameters ----------- window length of the window (in spans); min_periods the minimal length of the window for borderline cases; allows to shrink the window to meet this minimal length. If not specified, then `min_periods == window`, which means that the shrinking is not allowed, and contexts smaller than the `window` will be discarded. Note: `0 < min_periods <= window` must hold; inside an enveloping layer to be used for constraining the rolling window. The rolling window is applied on each span of the enveloping layer separately, thus ensuring that the window does not exceed boundaries of enveloping spans. For instance, if you create a rolling window over 'words', you can specify inside='sentences', ensuring that the generated word N-grams do not exceed sentence boundaries; Returns -------- estnltk_core.layer_operations.Rolling estnltk_core.layer_operations.Rolling object.
def rolling(self, window: int, min_periods: int = None, inside: str = None) -> Rolling: """Creates an iterable object yielding span sequences from a window rolling over the layer. Parameters ----------- window length of the window (in spans); min_periods the minimal length of the window for borderline cases; allows to shrink the window to meet this minimal length. If not specified, then `min_periods == window`, which means that the shrinking is not allowed, and contexts smaller than the `window` will be discarded. Note: `0 < min_periods <= window` must hold; inside an enveloping layer to be used for constraining the rolling window. The rolling window is applied on each span of the enveloping layer separately, thus ensuring that the window does not exceed boundaries of enveloping spans. For instance, if you create a rolling window over 'words', you can specify inside='sentences', ensuring that the generated word N-grams do not exceed sentence boundaries; Returns -------- estnltk_core.layer_operations.Rolling estnltk_core.layer_operations.Rolling object. """ return Rolling(self, window=window, min_periods=min_periods, inside=inside)
(self, window: int, min_periods: Optional[int] = None, inside: Optional[str] = None) -> estnltk_core.layer_operations.aggregators.rolling.Rolling
57,341
estnltk.helpers.progressbar
Progressbar
null
class Progressbar: def __init__(self, iterable, total, initial, progressbar_type): self.progressbar_type = progressbar_type if progressbar_type is None: self.data_iterator = iterable elif progressbar_type in {'ascii', 'unicode'}: self.data_iterator = tqdm(iterable, total=total, initial=initial, unit='doc', ascii=progressbar_type == 'ascii', smoothing=0) elif progressbar_type == 'notebook': self.data_iterator = notebook_tqdm(iterable, total=total, initial=initial, unit='doc', smoothing=0) else: raise ValueError("unknown progressbar type: {!r}, expected None, 'ascii', 'unicode' or 'notebook'" .format(progressbar_type)) def set_description(self, description, refresh=False): if self.progressbar_type is not None: self.data_iterator.set_description(description, refresh=refresh) def __iter__(self): yield from self.data_iterator
(iterable, total, initial, progressbar_type)
57,342
estnltk.helpers.progressbar
__init__
null
def __init__(self, iterable, total, initial, progressbar_type): self.progressbar_type = progressbar_type if progressbar_type is None: self.data_iterator = iterable elif progressbar_type in {'ascii', 'unicode'}: self.data_iterator = tqdm(iterable, total=total, initial=initial, unit='doc', ascii=progressbar_type == 'ascii', smoothing=0) elif progressbar_type == 'notebook': self.data_iterator = notebook_tqdm(iterable, total=total, initial=initial, unit='doc', smoothing=0) else: raise ValueError("unknown progressbar type: {!r}, expected None, 'ascii', 'unicode' or 'notebook'" .format(progressbar_type))
(self, iterable, total, initial, progressbar_type)
57,343
estnltk.helpers.progressbar
__iter__
null
def __iter__(self): yield from self.data_iterator
(self)
57,344
estnltk.helpers.progressbar
set_description
null
def set_description(self, description, refresh=False): if self.progressbar_type is not None: self.data_iterator.set_description(description, refresh=refresh)
(self, description, refresh=False)
57,345
estnltk.resource_utils
ResourceView
Shows Estnltk's resources in a pretty-printed table. Special filters can be added to show only downloaded resources or only resources that have specific names. This view works both in jupyter notebook and on command line.
class ResourceView: """Shows Estnltk's resources in a pretty-printed table. Special filters can be added to show only downloaded resources or only resources that have specific names. This view works both in jupyter notebook and on command line. """ def __init__(self, name: str="", downloaded: bool=False): """Creates a new ResourceView constrained by given parameters. Parameters ----------- name: str="" Show only resources that have given `name` as a part of their name or alias. Note that the default value ("") is a part of every resource name, so by default, all resources will be shown. downloaded: bool=False Show only resources which have been downloaded. """ assert isinstance(name, str) self._keys = [name.lower()] self._only_downloaded = downloaded def _get_version_constraint_info(self, resource_dict): # Fetches information about EstNLTK's version constraints # of the resource. If no constraints have been imposed, # returns None info = [] for version_tag in [ 'estnltk_core_version', \ 'estnltk_version', \ 'estnltk_neural_version' ]: if version_tag in resource_dict: info.append( version_tag+' '+\ resource_dict[version_tag] ) if info: return \ '(requires: '+('; '.join(info))+')' return None def _get_resource_descriptions(self): # Get normalized resource descriptions res_descriptions = \ _normalized_resource_descriptions(check_existence=True) # Rename 'desc' -> 'description' # Add size information to description (if available) # Add version constraint information (if available) for res_dict in res_descriptions: res_dict['description'] = res_dict.get('desc', '') del res_dict['desc'] size = res_dict.get('size', None) if size: size = _normalize_resource_size( size ) res_dict['description'] += ' ' res_dict['description'] += '(size: {})'.format(size) ver_constraint = self._get_version_constraint_info(res_dict) if ver_constraint is not None: res_dict['description'] += ' ' res_dict['description'] += ver_constraint # Show only downloaded resources if self._only_downloaded: filtered_descriptions = [] for res_dict in res_descriptions: if res_dict.get('downloaded', False): filtered_descriptions.append( res_dict ) res_descriptions = filtered_descriptions # Show only resources with specific keywords or aliases if self._keys: filtered_descriptions = [] for res_dict in res_descriptions: has_name = \ any([k in res_dict['name'] for k in self._keys]) has_alias = \ any([k in a for k in self._keys for a in res_dict['aliases']]) if has_name or has_alias: filtered_descriptions.append( res_dict ) res_descriptions = filtered_descriptions return res_descriptions def __repr__(self): # Get normalized resource descriptions res_descriptions = self._get_resource_descriptions() # Create and output table lengths = { 'name': 20, 'description': 37, 'license': 25, 'downloaded': 10 } table = _pretty_print_resources_table( res_descriptions, lengths ) return '{classname}\n{info_table}'.format( classname=self.__class__.__name__, \ info_table=table ) def _repr_html_(self): import pandas # Get normalized resource descriptions res_descriptions = self._get_resource_descriptions() columns = ['name', 'description', 'license', 'downloaded'] # Create and output HTML table df = pandas.DataFrame.from_records(res_descriptions, columns=columns) return ('<h4>{}</h4>'.format(self.__class__.__name__))+'\n'+df.to_html(index=False)
(name: str = '', downloaded: bool = False)
57,346
estnltk.resource_utils
__init__
Creates a new ResourceView constrained by given parameters. Parameters ----------- name: str="" Show only resources that have given `name` as a part of their name or alias. Note that the default value ("") is a part of every resource name, so by default, all resources will be shown. downloaded: bool=False Show only resources which have been downloaded.
def __init__(self, name: str="", downloaded: bool=False): """Creates a new ResourceView constrained by given parameters. Parameters ----------- name: str="" Show only resources that have given `name` as a part of their name or alias. Note that the default value ("") is a part of every resource name, so by default, all resources will be shown. downloaded: bool=False Show only resources which have been downloaded. """ assert isinstance(name, str) self._keys = [name.lower()] self._only_downloaded = downloaded
(self, name: str = '', downloaded: bool = False)
57,347
estnltk.resource_utils
__repr__
null
def __repr__(self): # Get normalized resource descriptions res_descriptions = self._get_resource_descriptions() # Create and output table lengths = { 'name': 20, 'description': 37, 'license': 25, 'downloaded': 10 } table = _pretty_print_resources_table( res_descriptions, lengths ) return '{classname}\n{info_table}'.format( classname=self.__class__.__name__, \ info_table=table )
(self)
57,348
estnltk.resource_utils
_get_resource_descriptions
null
def _get_resource_descriptions(self): # Get normalized resource descriptions res_descriptions = \ _normalized_resource_descriptions(check_existence=True) # Rename 'desc' -> 'description' # Add size information to description (if available) # Add version constraint information (if available) for res_dict in res_descriptions: res_dict['description'] = res_dict.get('desc', '') del res_dict['desc'] size = res_dict.get('size', None) if size: size = _normalize_resource_size( size ) res_dict['description'] += ' ' res_dict['description'] += '(size: {})'.format(size) ver_constraint = self._get_version_constraint_info(res_dict) if ver_constraint is not None: res_dict['description'] += ' ' res_dict['description'] += ver_constraint # Show only downloaded resources if self._only_downloaded: filtered_descriptions = [] for res_dict in res_descriptions: if res_dict.get('downloaded', False): filtered_descriptions.append( res_dict ) res_descriptions = filtered_descriptions # Show only resources with specific keywords or aliases if self._keys: filtered_descriptions = [] for res_dict in res_descriptions: has_name = \ any([k in res_dict['name'] for k in self._keys]) has_alias = \ any([k in a for k in self._keys for a in res_dict['aliases']]) if has_name or has_alias: filtered_descriptions.append( res_dict ) res_descriptions = filtered_descriptions return res_descriptions
(self)
57,349
estnltk.resource_utils
_get_version_constraint_info
null
def _get_version_constraint_info(self, resource_dict): # Fetches information about EstNLTK's version constraints # of the resource. If no constraints have been imposed, # returns None info = [] for version_tag in [ 'estnltk_core_version', \ 'estnltk_version', \ 'estnltk_neural_version' ]: if version_tag in resource_dict: info.append( version_tag+' '+\ resource_dict[version_tag] ) if info: return \ '(requires: '+('; '.join(info))+')' return None
(self, resource_dict)
57,350
estnltk.resource_utils
_repr_html_
null
def _repr_html_(self): import pandas # Get normalized resource descriptions res_descriptions = self._get_resource_descriptions() columns = ['name', 'description', 'license', 'downloaded'] # Create and output HTML table df = pandas.DataFrame.from_records(res_descriptions, columns=columns) return ('<h4>{}</h4>'.format(self.__class__.__name__))+'\n'+df.to_html(index=False)
(self)
57,351
estnltk_core.taggers.retagger
Retagger
Base class for retaggers. A retagger modifies existing layer. Use this class as a superclass in creating concrete implementations of retaggers. Retagger's derived class needs to set the instance variables: conf_param input_layers output_layer output_attributes ... and implement the following methods: __init__(...) _change_layer(...) Optionally, you can also add implementations of: __copy__ __deepcopy__ Constructor ============= Every subclass of Retagger should have __init__(...) constructor, in which retagger's configuration and instance variables are set. The following instance variables should be set: * input_layers: Sequence[str] -- names of all layers that are needed by the retagger for input; * output_layer: str -- name of the layer modified by the retagger; * output_attributes: Sequence[str] -- (final) attributes of the output_layer; * conf_param: Sequence[str] -- names of all additional attributes of the retagger object, which are set in the constructor. If retagger tries to set an attribute not declared in conf_param, an exception will be raised. Note that instance variables (the configuration of the retagger) can only be set inside the constructor. After the retagger has been initialized, changing values of instance variables is no longer allowed. _change_layer(...) method ========================== The layer is modified inside the _change_layer(...) method, which always returns None, indicating that the method does not produce a new layer, but only changes the target layer. The target layer that will be changed is the output_layer, which should be accessed as layers[self.output_layer] inside the _change_layer(...) method. Retagger can add or remove spans inside the target layer, or change annotations of the spans. In addition, it can also modify attributes of the layer: add new attributes, delete old ones, or change attributes. Changing annotations ==================== This is the most common and simplest layer modification operation. Basically, you can iterate over spans of the layer, remove old annotations and add new ones: for span in layers[self.output_layer]: # remove old annotations span.clear_annotations() # create a dictionary of new annotation new_annotation = ... assert isinstance(new_annotation, dict) # add new annotation span.add_annotation( new_annotation ) Note, however, that the new annotation (a dictionary of attributes and values) should have the same attributes as the layer has. Any attributes of the new annotation that are not present in the layer will be discarded. And if the new annotation misses some of the layer's attributes, these will be replaced by default values (None values, if the layer does not define default values). Adding annotations ================== You can use layer's add_annotation(...) method to add new annotations to the specific (text) locations. The method takes two inputs: the location of the span (start,end), and the dictionary of an annotation (attributes-values), and adds annotations to the layer at the specified location: assert isinstance(annotations, dict) layers[self.output_layer].add_annotation( (start,end), annotations ) If all attribute names are valid Python identifiers, you can also pass annotation as keyword assignments, e.g.: layers[self.output_layer].add_annotation( (start,end), attr1=..., attr2=... ) In case of an ambiguous layer, you can add multiple annotations to the same location via layer.add_annotation(...), but this is not allowed for unambiguous layers. Note #1: if the layer does not define any attributes, you can use layers[self.output_layer].add_annotation( (start,end) ) to create a markup without attributes-values (an empty annotation). Note #2: location of the span can be given as (start,end) only if the output layer is not enveloping. In case of an enveloping layer, a more complex structure should be used, please consult the documentation of BaseSpan (from estnltk_core) for details. Note #3: you cannot add two Spans (or EnvelopingSpan-s) that have exactly the same text location, however, partially overlapping spans are allowed. Removing spans ============== You can delete spans directly via the method remove_span( ... ), which takes the deletable Span or EnvelopingSpan as an input parameter. Be warned, however, that you should not delete spans while iterating over the layer, as this results in inconsistent deleting behaviour. Instead, you can first iterate over the layer and gather the deletable elements into a separate list, and then apply the deletion on the elements of that list: to_delete = [] for span in layers[self.output_layer]: if must_be_deleted(span): to_delete.append(span) for span in to_delete: layers[self.output_layer].remove_span( span ) Alaternatively, you can also delete spans by their index in the layer, using the del function. Example: to_delete = [] for span_id, span in enumerate( layers[self.output_layer] ): if must_be_deleted(span): to_delete.append( span_id ) for span_id in to_delete: del layers[self.output_layer][ span_id ] Adding attributes ================= New attributes can be added in the following way. First, update layer's attributes tuple: layers[self.output_layer].attributes += ('new_attr_1', 'new_attr_2') Note that after this step the old annotations of the layer become partially broken (e.g. you cannot display them) until you've set all the missing attributes, but you can still read and change their data. Second, update all annotations by adding new attributes: for span in layers[self.output_layer]: for annotation in span.annotations: annotation['new_attr_1'] = ... annotation['new_attr_2'] = ... Removing attributes =================== First, update layer's attributes tuple by leaving deletable attributes out: # leave out attributes ('old_attr_1', 'old_attr_2') new_attribs = tuple( a for a in layers[self.output_layer].attributes if a not in ('old_attr_1', 'old_attr_2') ) # update layer's attributes layers[self.output_layer].attributes = new_attribs Second, remove attributes from the annotations of the layer with the help of the delattr function: for span in layers[self.output_layer]: for annotation in span.annotations: delattr(annotation, 'old_attr_1') delattr(annotation, 'old_attr_2') Varia ===== # TODO: text.layers will be Set[str]. Make sure that this does not cause problems
class Retagger(Tagger): """Base class for retaggers. A retagger modifies existing layer. Use this class as a superclass in creating concrete implementations of retaggers. Retagger's derived class needs to set the instance variables: conf_param input_layers output_layer output_attributes ... and implement the following methods: __init__(...) _change_layer(...) Optionally, you can also add implementations of: __copy__ __deepcopy__ Constructor ============= Every subclass of Retagger should have __init__(...) constructor, in which retagger's configuration and instance variables are set. The following instance variables should be set: * input_layers: Sequence[str] -- names of all layers that are needed by the retagger for input; * output_layer: str -- name of the layer modified by the retagger; * output_attributes: Sequence[str] -- (final) attributes of the output_layer; * conf_param: Sequence[str] -- names of all additional attributes of the retagger object, which are set in the constructor. If retagger tries to set an attribute not declared in conf_param, an exception will be raised. Note that instance variables (the configuration of the retagger) can only be set inside the constructor. After the retagger has been initialized, changing values of instance variables is no longer allowed. _change_layer(...) method ========================== The layer is modified inside the _change_layer(...) method, which always returns None, indicating that the method does not produce a new layer, but only changes the target layer. The target layer that will be changed is the output_layer, which should be accessed as layers[self.output_layer] inside the _change_layer(...) method. Retagger can add or remove spans inside the target layer, or change annotations of the spans. In addition, it can also modify attributes of the layer: add new attributes, delete old ones, or change attributes. Changing annotations ==================== This is the most common and simplest layer modification operation. Basically, you can iterate over spans of the layer, remove old annotations and add new ones: for span in layers[self.output_layer]: # remove old annotations span.clear_annotations() # create a dictionary of new annotation new_annotation = ... assert isinstance(new_annotation, dict) # add new annotation span.add_annotation( new_annotation ) Note, however, that the new annotation (a dictionary of attributes and values) should have the same attributes as the layer has. Any attributes of the new annotation that are not present in the layer will be discarded. And if the new annotation misses some of the layer's attributes, these will be replaced by default values (None values, if the layer does not define default values). Adding annotations ================== You can use layer's add_annotation(...) method to add new annotations to the specific (text) locations. The method takes two inputs: the location of the span (start,end), and the dictionary of an annotation (attributes-values), and adds annotations to the layer at the specified location: assert isinstance(annotations, dict) layers[self.output_layer].add_annotation( (start,end), annotations ) If all attribute names are valid Python identifiers, you can also pass annotation as keyword assignments, e.g.: layers[self.output_layer].add_annotation( (start,end), attr1=..., attr2=... ) In case of an ambiguous layer, you can add multiple annotations to the same location via layer.add_annotation(...), but this is not allowed for unambiguous layers. Note #1: if the layer does not define any attributes, you can use layers[self.output_layer].add_annotation( (start,end) ) to create a markup without attributes-values (an empty annotation). Note #2: location of the span can be given as (start,end) only if the output layer is not enveloping. In case of an enveloping layer, a more complex structure should be used, please consult the documentation of BaseSpan (from estnltk_core) for details. Note #3: you cannot add two Spans (or EnvelopingSpan-s) that have exactly the same text location, however, partially overlapping spans are allowed. Removing spans ============== You can delete spans directly via the method remove_span( ... ), which takes the deletable Span or EnvelopingSpan as an input parameter. Be warned, however, that you should not delete spans while iterating over the layer, as this results in inconsistent deleting behaviour. Instead, you can first iterate over the layer and gather the deletable elements into a separate list, and then apply the deletion on the elements of that list: to_delete = [] for span in layers[self.output_layer]: if must_be_deleted(span): to_delete.append(span) for span in to_delete: layers[self.output_layer].remove_span( span ) Alaternatively, you can also delete spans by their index in the layer, using the del function. Example: to_delete = [] for span_id, span in enumerate( layers[self.output_layer] ): if must_be_deleted(span): to_delete.append( span_id ) for span_id in to_delete: del layers[self.output_layer][ span_id ] Adding attributes ================= New attributes can be added in the following way. First, update layer's attributes tuple: layers[self.output_layer].attributes += ('new_attr_1', 'new_attr_2') Note that after this step the old annotations of the layer become partially broken (e.g. you cannot display them) until you've set all the missing attributes, but you can still read and change their data. Second, update all annotations by adding new attributes: for span in layers[self.output_layer]: for annotation in span.annotations: annotation['new_attr_1'] = ... annotation['new_attr_2'] = ... Removing attributes =================== First, update layer's attributes tuple by leaving deletable attributes out: # leave out attributes ('old_attr_1', 'old_attr_2') new_attribs = tuple( a for a in layers[self.output_layer].attributes if a not in ('old_attr_1', 'old_attr_2') ) # update layer's attributes layers[self.output_layer].attributes = new_attribs Second, remove attributes from the annotations of the layer with the help of the delattr function: for span in layers[self.output_layer]: for annotation in span.annotations: delattr(annotation, 'old_attr_1') delattr(annotation, 'old_attr_2') Varia ===== # TODO: text.layers will be Set[str]. Make sure that this does not cause problems """ check_output_consistency=True, """ check_output_consistency: if ``True`` (default), then applies layer's method `check_span_consistency()` after the modification to validate the layer. Do not turn this off unless you know what you are doing! """ def __init__(self): raise NotImplementedError('__init__ method not implemented in ' + self.__class__.__name__) def _change_layer(self, text: Union['BaseText', 'Text'], layers: MutableMapping[str, Layer], status: dict) -> None: """Changes `output_layer` in the given `text`. **This method needs to be implemented in a derived class.** Parameters ---------- text: Union['BaseText', 'Text'] Text object which layer is changed layers: MutableMapping[str, Layer] A mapping from layer names to Layer objects. Layers in the mapping can be detached from the Text object. It can be assumed that `output_layer` is in the mapping and all tagger's `input_layers` are also in the mapping. IMPORTANT: input_layers and output_layer should always be accessed via the layers parameter, and NOT VIA THE TEXT OBJECT, because the Text object is not guaranteed to have them as attached layers at this processing stage. status: dict Dictionary for recording status messages about tagging. Note: the status parameter is **deprecated**. To store any metadata, use ``layer.meta`` instead. Returns ---------- NoneType None """ raise NotImplementedError('_change_layer method not implemented in ' + self.__class__.__name__) def change_layer(self, text: Union['BaseText', 'Text'], layers: Union[MutableMapping[str, Layer], Set[str]], status: dict = None) -> None: """Changes `output_layer` in the given `text`. Note: derived classes **should not override** this method. Parameters ---------- text: Union['BaseText', 'Text'] Text object which layer is changed layers: MutableMapping[str, Layer] A mapping from layer names to Layer objects. Layers in the mapping can be detached from the Text object. It can be assumed that `output_layer` is in the mapping and all tagger's `input_layers` are also in the mapping. IMPORTANT: the output_layer is changed based on input_layers and output_layer in the mapping, and not based on the layers attached to the Text object. status: dict Dictionary with status messages about retagging. Note: the status parameter is **deprecated**. To store/access metadata, use ``layer.meta`` instead. Returns ---------- NoneType None ============================================================================= # QUICK FIXES: layers should be a dictionary of layers but due to the changes in the Text object signature, it is actually a list of layer names which will cause a lot of problems in refactoring. Hence, we convert list of layer names to dictionary of layers. # REFLECTION: Adding layers as a separate argument is justified only if the layer is not present in the text object but then these layers become undocumented input which make the dependency graph useless. The only useful place where layers as separate argument is useful is in text collectons where we cn work with detached layers directly. Hence, it makes sense to rename layers parameter as detached_layers and check that these are indeed detached Also fix some resolving order for the case text[layer] != layers[layer] """ # Quick fix for refactoring problem (does not propagate changes out of the function) if type(layers) == set and (not layers or set(map(type, layers)) == {str}): layers = {layer: text[layer] for layer in layers} # End of fix # In order to change the layer, the layer must already exist assert self.output_layer in layers, \ "output_layer {!r} missing from layers {}".format( self.output_layer, list(layers.keys())) target_layers = {name: layers[name] for name in self.input_layers} # TODO: check that layer is not frozen # Used _change_layer to get the retagged variant of the layer self._change_layer(text, target_layers, status) # Check that the layer exists assert self.output_layer in target_layers, \ "output_layer {!r} missing from layers {}".format( self.output_layer, list(layers.keys())) if self.check_output_consistency: # Validate changed layer: check span consistency error_msg = target_layers[self.output_layer].check_span_consistency() if error_msg is not None: # TODO: should we use ValueErrors (here and elsewere) instead of AssertionError ? raise AssertionError( error_msg ) def retag(self, text: Union['BaseText', 'Text'], status: dict = None ) -> Union['BaseText', 'Text']: """ Modifies output_layer of given Text object. Note: derived classes **should not override** this method. Parameters ---------- text: Text object to be retagged status: dict, default {} This can be used to store metadata on layer modification. Returns ------- Union['BaseText', 'Text'] Input Text object which has a output_layer changed by this retagger. """ # Used change_layer to get the retagged variant of the layer self.change_layer(text, (text.layers).union(text.relation_layers), status) return text def __call__(self, text: Union['BaseText', 'Text'], status: dict = None) -> Union['BaseText', 'Text']: return self.retag(text, status) def _repr_html_(self): import pandas parameters = {'name': self.__class__.__name__, 'output layer': self.output_layer, 'output attributes': str(self.output_attributes), 'input layers': str(self.input_layers)} table = pandas.DataFrame(parameters, columns=['name', 'output layer', 'output attributes', 'input layers'], index=[0]) table = table.to_html(index=False) assert self.__class__.__doc__ is not None, 'No docstring.' description = self.__class__.__doc__.strip().split('\n')[0] table = ['<h4>{self.__class__.__name__}({self.__class__.__base__.__name__})</h4>'.format(self=self), description, table] def to_str(value): value_str = str(value) if len(value_str) < 100: return value_str value_str = value_str[:80] + ' ..., type: ' + str(type(value)) if hasattr(value, '__len__'): value_str += ', length: ' + str(len(value)) return value_str if self.conf_param: conf_vals = [to_str(getattr(self, attr)) for attr in self.conf_param if not attr.startswith('_')] conf_table = pandas.DataFrame(conf_vals, index=[attr for attr in self.conf_param if not attr.startswith('_')]) conf_table = conf_table.to_html(header=False) conf_table = ('<h4>Configuration</h4>', conf_table) else: conf_table = ('No configuration parameters.',) table.extend(conf_table) return '\n'.join(table) def __repr__(self): conf_str = '' if self.conf_param: conf = [attr+'='+str(getattr(self, attr)) for attr in self.conf_param if not attr.startswith('_')] conf_str = ', '.join(conf) return self.__class__.__name__+'('+conf_str+')' def __str__(self): return self.__class__.__name__ + '(' + str(self.input_layers) + '->' + self.output_layer + ')'
(*args, **kwargs)
57,352
estnltk_core.taggers.retagger
__call__
null
def __call__(self, text: Union['BaseText', 'Text'], status: dict = None) -> Union['BaseText', 'Text']: return self.retag(text, status)
(self, text: Union[ForwardRef('BaseText'), ForwardRef('Text')], status: dict = None) -> Union[ForwardRef('BaseText'), ForwardRef('Text')]
57,353
estnltk_core.taggers.tagger
__copy__
null
def __copy__(self): raise NotImplementedError('__copy__ method not implemented in ' + self.__class__.__name__)
(self)
57,354
estnltk_core.taggers.tagger
__deepcopy__
null
def __deepcopy__(self, memo={}): raise NotImplementedError('__deepcopy__ method not implemented in ' + self.__class__.__name__)
(self, memo={})
57,355
estnltk_core.taggers.retagger
__init__
null
def __init__(self): raise NotImplementedError('__init__ method not implemented in ' + self.__class__.__name__)
(self)
57,356
estnltk_core.taggers.tagger
__new__
null
def __new__(cls, *args, **kwargs): instance = super().__new__(cls) object.__setattr__(instance, '_initialized', False) return instance
(cls, *args, **kwargs)
57,357
estnltk_core.taggers.retagger
__repr__
null
def __repr__(self): conf_str = '' if self.conf_param: conf = [attr+'='+str(getattr(self, attr)) for attr in self.conf_param if not attr.startswith('_')] conf_str = ', '.join(conf) return self.__class__.__name__+'('+conf_str+')'
(self)
57,358
estnltk_core.taggers.tagger
__setattr__
null
def __setattr__(self, key, value): if self._initialized: raise AttributeError('changing of the tagger attributes is not allowed: {!r}, {!r}'.format( self.__class__.__name__, key)) assert key in {'conf_param', 'output_layer', 'output_attributes', 'input_layers', '_initialized'} or\ key in self.conf_param,\ 'attribute {!r} not listed in {}.conf_param'.format(key, self.__class__.__name__) super().__setattr__(key, value)
(self, key, value)
57,359
estnltk_core.taggers.retagger
__str__
null
def __str__(self): return self.__class__.__name__ + '(' + str(self.input_layers) + '->' + self.output_layer + ')'
(self)
57,360
estnltk_core.taggers.retagger
_change_layer
Changes `output_layer` in the given `text`. **This method needs to be implemented in a derived class.** Parameters ---------- text: Union['BaseText', 'Text'] Text object which layer is changed layers: MutableMapping[str, Layer] A mapping from layer names to Layer objects. Layers in the mapping can be detached from the Text object. It can be assumed that `output_layer` is in the mapping and all tagger's `input_layers` are also in the mapping. IMPORTANT: input_layers and output_layer should always be accessed via the layers parameter, and NOT VIA THE TEXT OBJECT, because the Text object is not guaranteed to have them as attached layers at this processing stage. status: dict Dictionary for recording status messages about tagging. Note: the status parameter is **deprecated**. To store any metadata, use ``layer.meta`` instead. Returns ---------- NoneType None
def _change_layer(self, text: Union['BaseText', 'Text'], layers: MutableMapping[str, Layer], status: dict) -> None: """Changes `output_layer` in the given `text`. **This method needs to be implemented in a derived class.** Parameters ---------- text: Union['BaseText', 'Text'] Text object which layer is changed layers: MutableMapping[str, Layer] A mapping from layer names to Layer objects. Layers in the mapping can be detached from the Text object. It can be assumed that `output_layer` is in the mapping and all tagger's `input_layers` are also in the mapping. IMPORTANT: input_layers and output_layer should always be accessed via the layers parameter, and NOT VIA THE TEXT OBJECT, because the Text object is not guaranteed to have them as attached layers at this processing stage. status: dict Dictionary for recording status messages about tagging. Note: the status parameter is **deprecated**. To store any metadata, use ``layer.meta`` instead. Returns ---------- NoneType None """ raise NotImplementedError('_change_layer method not implemented in ' + self.__class__.__name__)
(self, text: Union[ForwardRef('BaseText'), ForwardRef('Text')], layers: MutableMapping[str, estnltk_core.layer.layer.Layer], status: dict) -> None
57,361
estnltk_core.taggers.tagger
_make_layer
Creates and returns a new layer, based on the given `text` and its `layers`. **This method needs to be implemented in a derived class.** Parameters ---------- text: Union['BaseText', 'Text'] Text object to be annotated. layers: MutableMapping[str, Layer] A mapping from layer names to corresponding Layer objects. Layers in the mapping can be detached from the Text object. It can be assumed that all tagger's `input_layers` are in the mapping. IMPORTANT: input_layers should always be accessed via the layers parameter, and NOT VIA THE TEXT OBJECT, because the Text object is not guaranteed to have the input layers as attached layers at this processing stage. status: dict Dictionary for recording status messages about tagging. Note: the status parameter is **deprecated**. To store any metadata, use ``layer.meta`` instead. Returns ---------- Layer Created Layer object, which is detached from the Text object.
def _make_layer(self, text: Union['BaseText', 'Text'], layers: MutableMapping[str, Layer], status: dict) -> Layer: """ Creates and returns a new layer, based on the given `text` and its `layers`. **This method needs to be implemented in a derived class.** Parameters ---------- text: Union['BaseText', 'Text'] Text object to be annotated. layers: MutableMapping[str, Layer] A mapping from layer names to corresponding Layer objects. Layers in the mapping can be detached from the Text object. It can be assumed that all tagger's `input_layers` are in the mapping. IMPORTANT: input_layers should always be accessed via the layers parameter, and NOT VIA THE TEXT OBJECT, because the Text object is not guaranteed to have the input layers as attached layers at this processing stage. status: dict Dictionary for recording status messages about tagging. Note: the status parameter is **deprecated**. To store any metadata, use ``layer.meta`` instead. Returns ---------- Layer Created Layer object, which is detached from the Text object. """ raise NotImplementedError('make_layer method not implemented in ' + self.__class__.__name__)
(self, text: Union[ForwardRef('BaseText'), ForwardRef('Text')], layers: MutableMapping[str, estnltk_core.layer.layer.Layer], status: dict) -> estnltk_core.layer.layer.Layer
57,362
estnltk_core.taggers.tagger
_make_layer_template
Returns an empty detached layer that contains all parameters of the output layer. This method needs to be implemented in a derived class.
def _make_layer_template(self) -> Layer: """ Returns an empty detached layer that contains all parameters of the output layer. This method needs to be implemented in a derived class. """ raise NotImplementedError('_make_layer_template method not implemented in ' + self.__class__.__name__)
(self) -> estnltk_core.layer.layer.Layer
57,363
estnltk_core.taggers.tagger
_repr_html
null
def _repr_html(self, heading: str, description: str): import pandas parameters = {'name': self.__class__.__name__, 'output layer': self.output_layer, 'output attributes': str(self.output_attributes), 'input layers': str(self.input_layers)} table = pandas.DataFrame(data=parameters, columns=['name', 'output layer', 'output attributes', 'input layers'], index=[0]) table = table.to_html(index=False) table = ['<h4>{}</h4>'.format(heading), description, table] if self.conf_param: public_param = [p for p in self.conf_param if not p.startswith('_')] conf_values = [to_str(getattr(self, attr)) for attr in public_param] conf_table = pandas.DataFrame(conf_values, index=public_param) conf_table = conf_table.to_html(header=False) conf_table = ('<h4>Configuration</h4>', conf_table) else: conf_table = ('No configuration parameters.',) table.extend(conf_table) return '\n'.join(table)
(self, heading: str, description: str)
57,364
estnltk_core.taggers.retagger
_repr_html_
null
def _repr_html_(self): import pandas parameters = {'name': self.__class__.__name__, 'output layer': self.output_layer, 'output attributes': str(self.output_attributes), 'input layers': str(self.input_layers)} table = pandas.DataFrame(parameters, columns=['name', 'output layer', 'output attributes', 'input layers'], index=[0]) table = table.to_html(index=False) assert self.__class__.__doc__ is not None, 'No docstring.' description = self.__class__.__doc__.strip().split('\n')[0] table = ['<h4>{self.__class__.__name__}({self.__class__.__base__.__name__})</h4>'.format(self=self), description, table] def to_str(value): value_str = str(value) if len(value_str) < 100: return value_str value_str = value_str[:80] + ' ..., type: ' + str(type(value)) if hasattr(value, '__len__'): value_str += ', length: ' + str(len(value)) return value_str if self.conf_param: conf_vals = [to_str(getattr(self, attr)) for attr in self.conf_param if not attr.startswith('_')] conf_table = pandas.DataFrame(conf_vals, index=[attr for attr in self.conf_param if not attr.startswith('_')]) conf_table = conf_table.to_html(header=False) conf_table = ('<h4>Configuration</h4>', conf_table) else: conf_table = ('No configuration parameters.',) table.extend(conf_table) return '\n'.join(table)
(self)
57,365
estnltk_core.taggers.retagger
change_layer
Changes `output_layer` in the given `text`. Note: derived classes **should not override** this method. Parameters ---------- text: Union['BaseText', 'Text'] Text object which layer is changed layers: MutableMapping[str, Layer] A mapping from layer names to Layer objects. Layers in the mapping can be detached from the Text object. It can be assumed that `output_layer` is in the mapping and all tagger's `input_layers` are also in the mapping. IMPORTANT: the output_layer is changed based on input_layers and output_layer in the mapping, and not based on the layers attached to the Text object. status: dict Dictionary with status messages about retagging. Note: the status parameter is **deprecated**. To store/access metadata, use ``layer.meta`` instead. Returns ---------- NoneType None ============================================================================= # QUICK FIXES: layers should be a dictionary of layers but due to the changes in the Text object signature, it is actually a list of layer names which will cause a lot of problems in refactoring. Hence, we convert list of layer names to dictionary of layers. # REFLECTION: Adding layers as a separate argument is justified only if the layer is not present in the text object but then these layers become undocumented input which make the dependency graph useless. The only useful place where layers as separate argument is useful is in text collectons where we cn work with detached layers directly. Hence, it makes sense to rename layers parameter as detached_layers and check that these are indeed detached Also fix some resolving order for the case text[layer] != layers[layer]
def change_layer(self, text: Union['BaseText', 'Text'], layers: Union[MutableMapping[str, Layer], Set[str]], status: dict = None) -> None: """Changes `output_layer` in the given `text`. Note: derived classes **should not override** this method. Parameters ---------- text: Union['BaseText', 'Text'] Text object which layer is changed layers: MutableMapping[str, Layer] A mapping from layer names to Layer objects. Layers in the mapping can be detached from the Text object. It can be assumed that `output_layer` is in the mapping and all tagger's `input_layers` are also in the mapping. IMPORTANT: the output_layer is changed based on input_layers and output_layer in the mapping, and not based on the layers attached to the Text object. status: dict Dictionary with status messages about retagging. Note: the status parameter is **deprecated**. To store/access metadata, use ``layer.meta`` instead. Returns ---------- NoneType None ============================================================================= # QUICK FIXES: layers should be a dictionary of layers but due to the changes in the Text object signature, it is actually a list of layer names which will cause a lot of problems in refactoring. Hence, we convert list of layer names to dictionary of layers. # REFLECTION: Adding layers as a separate argument is justified only if the layer is not present in the text object but then these layers become undocumented input which make the dependency graph useless. The only useful place where layers as separate argument is useful is in text collectons where we cn work with detached layers directly. Hence, it makes sense to rename layers parameter as detached_layers and check that these are indeed detached Also fix some resolving order for the case text[layer] != layers[layer] """ # Quick fix for refactoring problem (does not propagate changes out of the function) if type(layers) == set and (not layers or set(map(type, layers)) == {str}): layers = {layer: text[layer] for layer in layers} # End of fix # In order to change the layer, the layer must already exist assert self.output_layer in layers, \ "output_layer {!r} missing from layers {}".format( self.output_layer, list(layers.keys())) target_layers = {name: layers[name] for name in self.input_layers} # TODO: check that layer is not frozen # Used _change_layer to get the retagged variant of the layer self._change_layer(text, target_layers, status) # Check that the layer exists assert self.output_layer in target_layers, \ "output_layer {!r} missing from layers {}".format( self.output_layer, list(layers.keys())) if self.check_output_consistency: # Validate changed layer: check span consistency error_msg = target_layers[self.output_layer].check_span_consistency() if error_msg is not None: # TODO: should we use ValueErrors (here and elsewere) instead of AssertionError ? raise AssertionError( error_msg )
(self, text: Union[ForwardRef('BaseText'), ForwardRef('Text')], layers: Union[MutableMapping[str, estnltk_core.layer.layer.Layer], Set[str]], status: dict = None) -> None
57,366
estnltk_core.taggers.tagger
get_layer_template
Returns an empty detached layer that contains all parameters of the output layer.
def get_layer_template(self) -> Layer: """ Returns an empty detached layer that contains all parameters of the output layer. """ return self._make_layer_template()
(self) -> estnltk_core.layer.layer.Layer
57,367
estnltk_core.taggers.tagger
make_layer
Creates and returns a new layer, based on the given `text` and its `layers`. Note: derived classes **should not override** this method. Parameters ---------- text: Union['BaseText', 'Text'] Text object to be annotated. layers: MutableMapping[str, Layer] A mapping from layer names to corresponding Layer objects. Layers in the mapping can be detached from the Text object. It is assumed that all tagger's `input_layers` are in the mapping. IMPORTANT: the new layer is created based on input_layers in the mapping, and not based on layers attached to the Text object. status: dict Dictionary with status messages about tagging. Note: the status parameter is **deprecated**. To store/access metadata, use ``layer.meta`` instead. Returns ---------- Layer Created Layer object, which is detached from the Text object. ============================================================================= # QUICK FIXES: layers should be a dictionary of layers but due to the changes in the Text object signature, it is actually a list of layer names which will cause a lot of problems in refactoring. Hence, we convert list of layer names to dictionary of layers. # REFLECTION: Adding layers as a separate argument is justified only if the layer is not present in the text object but then these layers become undocumented input which make the dependency graph useless. The only useful place where layers as separate argument is useful is in text collectons where we cn work with detached layers directly. Hence, it makes sense to rename layers parameter as detached_layers and check that these are indeed detached Also fix some resolving order for the case text[layer] != layers[layer] BUG: The function alters layers if it is specified as variable. This can lead to unexpected results
def make_layer(self, text: Union['BaseText', 'Text'], layers: Union[MutableMapping[str, Layer], Set[str]] = None, status: dict = None) -> Layer: """ Creates and returns a new layer, based on the given `text` and its `layers`. Note: derived classes **should not override** this method. Parameters ---------- text: Union['BaseText', 'Text'] Text object to be annotated. layers: MutableMapping[str, Layer] A mapping from layer names to corresponding Layer objects. Layers in the mapping can be detached from the Text object. It is assumed that all tagger's `input_layers` are in the mapping. IMPORTANT: the new layer is created based on input_layers in the mapping, and not based on layers attached to the Text object. status: dict Dictionary with status messages about tagging. Note: the status parameter is **deprecated**. To store/access metadata, use ``layer.meta`` instead. Returns ---------- Layer Created Layer object, which is detached from the Text object. ============================================================================= # QUICK FIXES: layers should be a dictionary of layers but due to the changes in the Text object signature, it is actually a list of layer names which will cause a lot of problems in refactoring. Hence, we convert list of layer names to dictionary of layers. # REFLECTION: Adding layers as a separate argument is justified only if the layer is not present in the text object but then these layers become undocumented input which make the dependency graph useless. The only useful place where layers as separate argument is useful is in text collectons where we cn work with detached layers directly. Hence, it makes sense to rename layers parameter as detached_layers and check that these are indeed detached Also fix some resolving order for the case text[layer] != layers[layer] BUG: The function alters layers if it is specified as variable. This can lead to unexpected results """ assert status is None or isinstance(status, dict), 'status should be None or dict, not {!r}'.format(type(status)) if status is None: status = {} layers = layers or {} # Quick fix for refactoring problem (does not propagate changes out of the function) if type(layers) == set and (not layers or set(map(type, layers)) == {str}): layers = {layer: text[layer] for layer in layers} # End of fix for layer in self.input_layers: if layer in layers: continue if layer in text.layers: layers[layer] = text[layer] else: raise ValueError('missing input layer: {!r}'.format(layer)) try: layer = self._make_layer(text=text, layers=layers, status=status) except Exception as e: e.args += ('in the {!r}'.format(self.__class__.__name__),) raise assert isinstance(layer, Layer), '{}._make_layer did not return a Layer object, but {!r}'.format( self.__class__.__name__, type(layer)) assert layer.text_object is text, '{}._make_layer returned a layer with incorrect Text object'.format( self.__class__.__name__) assert layer.attributes == self.output_attributes,\ '{}._make_layer returned layer with unexpected attributes: {} != {}'.format( self.__class__.__name__, layer.attributes, self.output_attributes) assert isinstance(layer, Layer), self.__class__.__name__ + '._make_layer must return Layer' assert layer.name == self.output_layer,\ '{}._make_layer returned a layer with incorrect name: {} != {}'.format( self.__class__.__name__, layer.name, self.output_layer) return layer
(self, text: Union[ForwardRef('BaseText'), ForwardRef('Text')], layers: Union[MutableMapping[str, estnltk_core.layer.layer.Layer], Set[str]] = None, status: dict = None) -> estnltk_core.layer.layer.Layer
57,368
estnltk_core.taggers.tagger
parameters
null
def parameters(self): record = {'name': self.__class__.__name__, 'layer': self.output_layer, 'attributes': self.output_attributes, 'depends_on': self.input_layers, 'configuration': [p+'='+str(getattr(self, p)) for p in self.conf_param if not p.startswith('_')] } return record
(self)
57,369
estnltk_core.taggers.retagger
retag
Modifies output_layer of given Text object. Note: derived classes **should not override** this method. Parameters ---------- text: Text object to be retagged status: dict, default {} This can be used to store metadata on layer modification. Returns ------- Union['BaseText', 'Text'] Input Text object which has a output_layer changed by this retagger.
def retag(self, text: Union['BaseText', 'Text'], status: dict = None ) -> Union['BaseText', 'Text']: """ Modifies output_layer of given Text object. Note: derived classes **should not override** this method. Parameters ---------- text: Text object to be retagged status: dict, default {} This can be used to store metadata on layer modification. Returns ------- Union['BaseText', 'Text'] Input Text object which has a output_layer changed by this retagger. """ # Used change_layer to get the retagged variant of the layer self.change_layer(text, (text.layers).union(text.relation_layers), status) return text
(self, text: Union[ForwardRef('BaseText'), ForwardRef('Text')], status: dict = None) -> Union[ForwardRef('BaseText'), ForwardRef('Text')]
57,370
estnltk_core.taggers.tagger
tag
Annotates Text object with this tagger. Note: derived classes **should not override** this method. Parameters ----------- text: Union['BaseText', 'Text'] Text object to be tagged. status: dict, default {} This can be used to store layer creation metadata. Returns ------- Union['BaseText', 'Text'] Input Text object which has a new (attached) layer created by this tagger.
def tag(self, text: Union['BaseText', 'Text'], status: dict = None) -> Union['BaseText', 'Text']: """Annotates Text object with this tagger. Note: derived classes **should not override** this method. Parameters ----------- text: Union['BaseText', 'Text'] Text object to be tagged. status: dict, default {} This can be used to store layer creation metadata. Returns ------- Union['BaseText', 'Text'] Input Text object which has a new (attached) layer created by this tagger. """ text.add_layer(self.make_layer(text=text, layers=(text.layers).union(text.relation_layers), status=status)) return text
(self, text: Union[ForwardRef('BaseText'), ForwardRef('Text')], status: dict = None) -> Union[ForwardRef('BaseText'), ForwardRef('Text')]
57,371
estnltk_core.layer.span
Span
Basic element of an EstNLTK layer. A span is a container for a fragment of text that is meaningful in the analyzed context. There can be several spans in one layer and each span can have many annotations which contain the information about the span. However, if the layer is not ambiguous, a span can have only one annotation. When creating a span, it must be given two arguments: BaseSpan which defines the mandatory attributes for a span (the exact attributes depend which kind of BaseSpan is given but minimally these are start and end of the span) and the layer that the span is attached to. Each annotation can have only one span. Span can exist without annotations. It is the responsibility of a programmer to remove such spans.
class Span: """Basic element of an EstNLTK layer. A span is a container for a fragment of text that is meaningful in the analyzed context. There can be several spans in one layer and each span can have many annotations which contain the information about the span. However, if the layer is not ambiguous, a span can have only one annotation. When creating a span, it must be given two arguments: BaseSpan which defines the mandatory attributes for a span (the exact attributes depend which kind of BaseSpan is given but minimally these are start and end of the span) and the layer that the span is attached to. Each annotation can have only one span. Span can exist without annotations. It is the responsibility of a programmer to remove such spans. """ __slots__ = ['_base_span', '_layer', '_annotations', '_parent'] def __init__(self, base_span: BaseSpan, layer): assert isinstance(base_span, BaseSpan), base_span self._base_span = base_span self._layer = layer # type: Layer self._annotations = [] self._parent = None # type: Span def __deepcopy__(self, memo=None): """ Makes a deep copy from the span. Loosely based on: https://github.com/estnltk/estnltk/blob/5bacff50072f9415814aee4f369c28db0e8d7789/estnltk/layer/span.py#L60 """ memo = memo or {} # Create new valid instance # _base_span: Immutable result = self.__class__(base_span=self.base_span, \ layer=None) # Add self to memo memo[id(self)] = result # _annotations: List[Mutable] for annotation in self._annotations: deepcopy_annotation = deepcopy(annotation, memo) deepcopy_annotation.span = result result._annotations.append( deepcopy_annotation ) # _parent: Mutable result._parent = deepcopy(self._parent, memo) # _layer: Mutable result._layer = deepcopy(self._layer, memo) return result def add_annotation(self, annotation: Union[Dict[str, Any], Annotation]={}, **annotation_kwargs) -> Annotation: """Adds new annotation (from `annotation` / `annotation_kwargs`) to this span. `annotation` can be either an Annotation object initiated with this span. For example:: span.add_annotation(Annotation(span, {'attr1': ..., 'attr2': ...})) Or it can be a dictionary of attributes and values:: span.add_annotation( {'attr1': ..., 'attr2': ...} ) Missing attributes will be filled in with span layer's default_values (None values, if defaults have not been explicitly set). Redundant attributes (attributes not in `span.layer.attributes`) will be discarded. Optionally, you can leave `annotation` unspecified and pass keyword arguments to the method via `annotation_kwargs`, for example:: span.add_annotation( attr1=..., attr2=... ) Note that keyword arguments can only be valid Python keywords (excluding the keyword 'annotation'), and using `annotation` dictionary enables to bypass these restrictions. Note that you cannot pass Annotation object and keyword arguments simultaneously, this will result in TypeError. However, you can pass annotation dictionary and keyword arguments simultaneously. In that case, keyword arguments override annotation dictionary in case of an overlap in attributes. Overall, the priority order in setting value of an attribute is: `annotation_kwargs` > `annotation(dict)` > `default attributes`. The method returns added Annotation object. Note: you can add two or more annotations to this span only if the layer is ambiguous. """ if isinstance(annotation, Annotation): # Annotation object if annotation.span is not self: raise ValueError('the annotation has a different span {}'.format(annotation.span)) if set(annotation) != set(self.layer.attributes): raise ValueError('the annotation has unexpected or missing attributes {}!={}'.format( set(annotation), set(self.layer.attributes))) if len(annotation_kwargs.items()) > 0: # If Annotation object is already provided, cannot add additional keywords raise TypeError(('cannot add keyword arguments {!r} to an existing Annotation object.'+\ 'please pass keywords as a dict instead of Annotation object.').format(annotation_kwargs)) elif isinstance(annotation, dict): # annotation dict annotation_dict = {**self.layer.default_values, \ **{k: v for k, v in annotation.items() if k in self.layer.attributes}, \ **{k: v for k, v in annotation_kwargs.items() if k in self.layer.attributes}} annotation = Annotation(self, annotation_dict) else: raise TypeError('expected Annotation object or dict, but got {}'.format(type(annotation))) if annotation not in self._annotations: if self.layer.ambiguous or len(self._annotations) == 0: self._annotations.append(annotation) return annotation raise ValueError('The layer is not ambiguous and this span already has a different annotation.') def del_annotation(self, idx): """Deletes annotation by index `idx`. """ del self._annotations[idx] def clear_annotations(self): """Removes all annotations from this span. Warning: Span without any annotations is dysfunctional. It is the responsibility of a programmer to either add new annotations to span after clearing it, or to remove the span from the layer altogether. """ self._annotations.clear() @property def annotations(self): return self._annotations def __getitem__(self, item): if isinstance(item, str): if self._layer.ambiguous: return AttributeList(self, item, index_type='annotations') return self._annotations[0][item] if isinstance(item, tuple): if self._layer.ambiguous: return AttributeTupleList(self, item, index_type='annotations') return self._annotations[0][item] raise KeyError(item) @property def parent(self): if self._parent is None: if self._layer is None or self._layer.parent is None: return self._parent text_obj = self._layer.text_object if text_obj is None or self._layer.parent not in text_obj.layers: return self._parent self._parent = self._layer.text_object[self._layer.parent].get(self.base_span) return self._parent @property def layer(self): return self._layer @property def legal_attribute_names(self) -> Sequence[str]: return self._layer.attributes @property def start(self) -> int: return self._base_span.start @property def end(self) -> int: return self._base_span.end @property def base_span(self): return self._base_span @property def base_spans(self): return [(self.start, self.end)] @property def text(self): if self.text_object is None: return text = self.text_object.text base_span = self.base_span if isinstance(base_span, ElementaryBaseSpan): return text[base_span.start:base_span.end] return [text[start:end] for start, end in base_span.flatten()] @property def enclosing_text(self): if self.text_object is None: return return self._layer.text_object.text[self.start:self.end] @property def text_object(self): if self._layer is not None: return self._layer.text_object @property def raw_text(self): return self.text_object.text def __setattr__(self, key, value): if key in {'_base_span', '_layer', '_annotations', '_parent'}: super().__setattr__(key, value) elif key in self.legal_attribute_names: for annotation in self._annotations: setattr(annotation, key, value) else: raise AttributeError(key) def resolve_attribute(self, item): """Resolves and returns values of foreign attribute `item`, or resolves and returns a foreign span from layer `item`. More specifically: 1) If `item` is a name of a foreign attribute which is listed in the mapping from attribute names to foreign layer names (`attribute_mapping_for_elementary_layers`), attempts to find foreign span with the same base span as this span from the foreign layer & returns value(s) of the attribute `item` from that foreign span. (raises KeyError if base span is missing in the foreign layer); Note: this is only available when this span belongs to estnltk's `Text` object. The step will be skipped if the span belongs to `BaseText`; 2) If `item` is a layer attached to span's the text_object, attempts to get & return span with the same base span from that layer (raises KeyError if base span is missing); """ if self.text_object is not None: if hasattr(self.text_object, 'attribute_mapping_for_elementary_layers'): # Attempt to get the foreign attribute of # the same base span of a different attached # layer, based on the mapping of attributes-layers # (only available if we have estnltk.text.Text object) attribute_mapping = self.text_object.attribute_mapping_for_elementary_layers if item in attribute_mapping: return self._layer.text_object[attribute_mapping[item]].get(self.base_span)[item] if item in self.text_object.layers: # Attempt to get the same base span from # a different attached layer # (e.g parent or child span) return self.text_object[item].get(self.base_span) else: raise AttributeError(("Unable to resolve foreign attribute {!r}: "+\ "the layer is not attached to Text object.").format(item) ) raise AttributeError("Unable to resolve foreign attribute {!r}.".format(item)) def __getattr__(self, item): if item in self.__getattribute__('_layer').attributes: return self[item] try: return self.resolve_attribute(item) except KeyError as key_error: raise AttributeError(key_error.args[0]) from key_error def __lt__(self, other: Any) -> bool: return self.base_span < other.base_span def __eq__(self, other: Any) -> bool: return isinstance(other, Span) \ and self.base_span == other.base_span \ and len(self.annotations) == len(other.annotations) \ and all(s in other.annotations for s in self.annotations) @recursive_repr() def __repr__(self): try: text = self.text except: text = None try: attribute_names = self._layer.attributes annotation_strings = [] for annotation in self._annotations: attr_val_repr = _create_attr_val_repr( [(attr, annotation[attr]) for attr in attribute_names] ) annotation_strings.append( attr_val_repr ) annotations = '[{}]'.format(', '.join(annotation_strings)) except: annotations = None return '{class_name}({text!r}, {annotations})'.format(class_name=self.__class__.__name__, text=text, annotations=annotations) def _to_html(self, margin=0) -> str: return '<b>{}</b>\n{}'.format( self.__class__.__name__, html_table(spans=[self], attributes=self._layer.attributes, margin=margin, index=False)) def _repr_html_(self): return self._to_html()
(base_span: estnltk_core.layer.base_span.BaseSpan, layer)
57,375
estnltk_core.layer.span
__getitem__
null
def __getitem__(self, item): if isinstance(item, str): if self._layer.ambiguous: return AttributeList(self, item, index_type='annotations') return self._annotations[0][item] if isinstance(item, tuple): if self._layer.ambiguous: return AttributeTupleList(self, item, index_type='annotations') return self._annotations[0][item] raise KeyError(item)
(self, item)
57,376
estnltk_core.layer.span
__init__
null
def __init__(self, base_span: BaseSpan, layer): assert isinstance(base_span, BaseSpan), base_span self._base_span = base_span self._layer = layer # type: Layer self._annotations = [] self._parent = None # type: Span
(self, base_span: estnltk_core.layer.base_span.BaseSpan, layer)
57,379
estnltk_core.layer.span
__setattr__
null
def __setattr__(self, key, value): if key in {'_base_span', '_layer', '_annotations', '_parent'}: super().__setattr__(key, value) elif key in self.legal_attribute_names: for annotation in self._annotations: setattr(annotation, key, value) else: raise AttributeError(key)
(self, key, value)
57,385
estnltk_core.layer.span
resolve_attribute
Resolves and returns values of foreign attribute `item`, or resolves and returns a foreign span from layer `item`. More specifically: 1) If `item` is a name of a foreign attribute which is listed in the mapping from attribute names to foreign layer names (`attribute_mapping_for_elementary_layers`), attempts to find foreign span with the same base span as this span from the foreign layer & returns value(s) of the attribute `item` from that foreign span. (raises KeyError if base span is missing in the foreign layer); Note: this is only available when this span belongs to estnltk's `Text` object. The step will be skipped if the span belongs to `BaseText`; 2) If `item` is a layer attached to span's the text_object, attempts to get & return span with the same base span from that layer (raises KeyError if base span is missing);
def resolve_attribute(self, item): """Resolves and returns values of foreign attribute `item`, or resolves and returns a foreign span from layer `item`. More specifically: 1) If `item` is a name of a foreign attribute which is listed in the mapping from attribute names to foreign layer names (`attribute_mapping_for_elementary_layers`), attempts to find foreign span with the same base span as this span from the foreign layer & returns value(s) of the attribute `item` from that foreign span. (raises KeyError if base span is missing in the foreign layer); Note: this is only available when this span belongs to estnltk's `Text` object. The step will be skipped if the span belongs to `BaseText`; 2) If `item` is a layer attached to span's the text_object, attempts to get & return span with the same base span from that layer (raises KeyError if base span is missing); """ if self.text_object is not None: if hasattr(self.text_object, 'attribute_mapping_for_elementary_layers'): # Attempt to get the foreign attribute of # the same base span of a different attached # layer, based on the mapping of attributes-layers # (only available if we have estnltk.text.Text object) attribute_mapping = self.text_object.attribute_mapping_for_elementary_layers if item in attribute_mapping: return self._layer.text_object[attribute_mapping[item]].get(self.base_span)[item] if item in self.text_object.layers: # Attempt to get the same base span from # a different attached layer # (e.g parent or child span) return self.text_object[item].get(self.base_span) else: raise AttributeError(("Unable to resolve foreign attribute {!r}: "+\ "the layer is not attached to Text object.").format(item) ) raise AttributeError("Unable to resolve foreign attribute {!r}.".format(item))
(self, item)
57,386
estnltk_core.layer.span_list
SpanList
SpanList is a container of Spans sorted by start indexes. Note: all spans in SpanList must have the same (base span) level, but SpanList itself does not validate that span levels match. It is the responsibility of a programmer to assure that the spanlist is populated with equal-level spans (for more about span levels, see the docstring of BaseSpan from estnltk_core). # TODO replace with SortedDict ??
class SpanList(Sequence): """ SpanList is a container of Spans sorted by start indexes. Note: all spans in SpanList must have the same (base span) level, but SpanList itself does not validate that span levels match. It is the responsibility of a programmer to assure that the spanlist is populated with equal-level spans (for more about span levels, see the docstring of BaseSpan from estnltk_core). # TODO replace with SortedDict ?? """ def __init__(self, span_level=None): # Dict[BaseSpan, Span] self._base_span_to_span = {} # Optinal[int] self._span_level = span_level # List[Span] self.spans = [] def add_span(self, span): assert span.base_span not in self._base_span_to_span bisect.insort(self.spans, span) self._base_span_to_span[span.base_span] = span if self._span_level is None: # Level of the first span is the level # of this spanlist. Once the level is # set, it should not be changed self._span_level = span.base_span.level def get(self, span: BaseSpan): return self._base_span_to_span.get(span) def remove_span(self, span): del self._base_span_to_span[span.base_span] self.spans.remove(span) @property def text(self): return [span.text for span in self.spans] @property def span_level(self): return self._span_level def __len__(self) -> int: return len(self.spans) def __contains__(self, item: Any) -> bool: if isinstance(item, Hashable) and item in self._base_span_to_span: return True if isinstance(item, Span): span = self._base_span_to_span.get(item.base_span) return span is item def index(self, x, *args) -> int: return self.spans.index(x, *args) def __setitem__(self, key: int, value: Span): self.spans[key] = value self._base_span_to_span[value.base_span] = value def __getitem__(self, idx) -> Union[Span, List[Span]]: return self.spans[idx] def __eq__(self, other: Any) -> bool: return isinstance(other, SpanList) and self.spans == other.spans def __str__(self): return 'SL[{spans}]'.format(spans=',\n'.join(str(i) for i in self.spans)) def __repr__(self): return str(self)
(span_level=None)
57,387
estnltk_core.layer.span_list
__contains__
null
def __contains__(self, item: Any) -> bool: if isinstance(item, Hashable) and item in self._base_span_to_span: return True if isinstance(item, Span): span = self._base_span_to_span.get(item.base_span) return span is item
(self, item: Any) -> bool
57,388
estnltk_core.layer.span_list
__eq__
null
def __eq__(self, other: Any) -> bool: return isinstance(other, SpanList) and self.spans == other.spans
(self, other: Any) -> bool
57,389
estnltk_core.layer.span_list
__getitem__
null
def __getitem__(self, idx) -> Union[Span, List[Span]]: return self.spans[idx]
(self, idx) -> Union[estnltk_core.layer.span.Span, List[estnltk_core.layer.span.Span]]
57,390
estnltk_core.layer.span_list
__init__
null
def __init__(self, span_level=None): # Dict[BaseSpan, Span] self._base_span_to_span = {} # Optinal[int] self._span_level = span_level # List[Span] self.spans = []
(self, span_level=None)
57,392
estnltk_core.layer.span_list
__len__
null
def __len__(self) -> int: return len(self.spans)
(self) -> int
57,393
estnltk_core.layer.span_list
__repr__
null
def __repr__(self): return str(self)
(self)
57,395
estnltk_core.layer.span_list
__setitem__
null
def __setitem__(self, key: int, value: Span): self.spans[key] = value self._base_span_to_span[value.base_span] = value
(self, key: int, value: estnltk_core.layer.span.Span)
57,396
estnltk_core.layer.span_list
__str__
null
def __str__(self): return 'SL[{spans}]'.format(spans=',\n'.join(str(i) for i in self.spans))
(self)
57,397
estnltk_core.layer.span_list
add_span
null
def add_span(self, span): assert span.base_span not in self._base_span_to_span bisect.insort(self.spans, span) self._base_span_to_span[span.base_span] = span if self._span_level is None: # Level of the first span is the level # of this spanlist. Once the level is # set, it should not be changed self._span_level = span.base_span.level
(self, span)
57,399
estnltk_core.layer.span_list
get
null
def get(self, span: BaseSpan): return self._base_span_to_span.get(span)
(self, span: estnltk_core.layer.base_span.BaseSpan)
57,400
estnltk_core.layer.span_list
index
null
def index(self, x, *args) -> int: return self.spans.index(x, *args)
(self, x, *args) -> int
57,401
estnltk_core.layer.span_list
remove_span
null
def remove_span(self, span): del self._base_span_to_span[span.base_span] self.spans.remove(span)
(self, span)
57,402
estnltk_core.taggers.tagger
Tagger
Base class for taggers. A tagger creates new layer. Use this class as a superclass in creating concrete implementations of taggers. Tagger's derived class needs to set the instance variables: conf_param output_layer output_attributes input_layers ... and implement the following methods: __init__(...) _make_layer(...) Optionally, you may also add implementations of: _make_layer_template __copy__ __deepcopy__ Constructor ============= Every subclass of Tagger should have __init__(...) constructor, in which tagger's configuration and instance variables are set. The following instance variables should be set: * input_layers: Sequence[str] -- names of all layers that are needed by the tagger for input; * output_layer: str -- name of the layer created by the tagger; * output_attributes: Sequence[str] -- attributes of the output_layer; * conf_param: Sequence[str] -- names of all additional attributes of the tagger object, which are set in the constructor. If tagger tries to set an attribute not declared in conf_param, an exception will be raised. Note that instance variables (the configuration of the tagger) can only be set inside the constructor. After the tagger has been initialized, changing values of instance variables is no longer allowed. _make_layer(...) method ========================= The new layer is created inside the _make_layer(...) method, which returns Layer object. Optionally, you can also implement _make_layer_template() method, which returns an empty layer that contains all the proper attribute initializations, but is not associated with any text object (this is required if you want to use EstNLTK's Postgres interface). The name of the creatable layer is the output_layer, and the layers required for its creation are listed in input_layers. Note, inside the _make_layer(...) method, you should access input_layers via the layers parameter, e.g. layers[self.input_layers[0]], layers[self.input_layers[1]] etc., and NOT VIA THE INPUT TEXT OBJECT, because the input Text object is not guaranteed to have the input layers as attached layers. The attributes of the creatable layer should be listed in self.output_attributes. Creating a layer ================ You can create a new layer in the following way: from estnltk_core import Layer new_layer = Layer(name=self.output_layer, text_object=text, attributes=self.output_attributes, parent=..., enveloping=..., ambiguous=...) If you have the _make_layer_template() method implemented, it is recommended to create a new layer only inside that method, and then call for the method inside the _make_layer(...): new_layer = self._make_layer_template() new_layer.text_object = text Layer types =========== Simple layer -- a layer that is not ambiguous, nor dependent of any other layer (is not enveloping and does not have a parent layer). Ambiguous layer -- a layer that can have multiple annotations on same location (same span). Enveloping layer -- a layer which spans envelop (wrap) around spans of some other layer. E.g. 'sentences' layer can be defined as enveloping around 'words' layer. Child layer -- a layer that has a parent layer and its spans can only be at the same locations as spans of the parent layer. A dependent layer can be either enveloping or child, but not both at the same time. For more information about layer types, and how to create and and populate different types of layers, see the tutorial "low_level_layer_operations.ipynb" Adding annotations =================== Once you've created the layer, you can populate it with data: spans and corresponding annotations. You can use layer's add_annotation(...) method to add new annotations to the specific (text) locations. The method takes two inputs: the location of the span (start,end), and the dictionary of an annotation (attributes-values), and adds annotations to the layer at the specified location: assert isinstance(annotations, dict) new_layer.add_annotation( (start,end), annotations ) If all attribute names are valid Python identifiers, you can also pass annotation as keyword assignments, e.g.: new_layer.add_annotation( (start,end), attr1=..., attr2=... ) In case of an ambiguous layer, you can add multiple annotations to the same location via layer.add_annotation(...), but this is not allowed for unambiguous layers. Note #1: if the layer does not define any attributes, you can use new_layer.add_annotation( (start,end) ) to create a markup without attributes-values (an empty annotation). Note #2: location of the span can be given as (start,end) only if the output layer is not enveloping. In case of an enveloping layer, a more complex structure should be used, please consult the documentation of BaseSpan (from estnltk_core) for details. Note #3: you cannot add two Spans (or EnvelopingSpan-s) that have exactly the same text location, however, partially overlapping spans are allowed.
class Tagger(metaclass=TaggerChecker): """Base class for taggers. A tagger creates new layer. Use this class as a superclass in creating concrete implementations of taggers. Tagger's derived class needs to set the instance variables: conf_param output_layer output_attributes input_layers ... and implement the following methods: __init__(...) _make_layer(...) Optionally, you may also add implementations of: _make_layer_template __copy__ __deepcopy__ Constructor ============= Every subclass of Tagger should have __init__(...) constructor, in which tagger's configuration and instance variables are set. The following instance variables should be set: * input_layers: Sequence[str] -- names of all layers that are needed by the tagger for input; * output_layer: str -- name of the layer created by the tagger; * output_attributes: Sequence[str] -- attributes of the output_layer; * conf_param: Sequence[str] -- names of all additional attributes of the tagger object, which are set in the constructor. If tagger tries to set an attribute not declared in conf_param, an exception will be raised. Note that instance variables (the configuration of the tagger) can only be set inside the constructor. After the tagger has been initialized, changing values of instance variables is no longer allowed. _make_layer(...) method ========================= The new layer is created inside the _make_layer(...) method, which returns Layer object. Optionally, you can also implement _make_layer_template() method, which returns an empty layer that contains all the proper attribute initializations, but is not associated with any text object (this is required if you want to use EstNLTK's Postgres interface). The name of the creatable layer is the output_layer, and the layers required for its creation are listed in input_layers. Note, inside the _make_layer(...) method, you should access input_layers via the layers parameter, e.g. layers[self.input_layers[0]], layers[self.input_layers[1]] etc., and NOT VIA THE INPUT TEXT OBJECT, because the input Text object is not guaranteed to have the input layers as attached layers. The attributes of the creatable layer should be listed in self.output_attributes. Creating a layer ================ You can create a new layer in the following way: from estnltk_core import Layer new_layer = Layer(name=self.output_layer, text_object=text, attributes=self.output_attributes, parent=..., enveloping=..., ambiguous=...) If you have the _make_layer_template() method implemented, it is recommended to create a new layer only inside that method, and then call for the method inside the _make_layer(...): new_layer = self._make_layer_template() new_layer.text_object = text Layer types =========== Simple layer -- a layer that is not ambiguous, nor dependent of any other layer (is not enveloping and does not have a parent layer). Ambiguous layer -- a layer that can have multiple annotations on same location (same span). Enveloping layer -- a layer which spans envelop (wrap) around spans of some other layer. E.g. 'sentences' layer can be defined as enveloping around 'words' layer. Child layer -- a layer that has a parent layer and its spans can only be at the same locations as spans of the parent layer. A dependent layer can be either enveloping or child, but not both at the same time. For more information about layer types, and how to create and and populate different types of layers, see the tutorial "low_level_layer_operations.ipynb" Adding annotations =================== Once you've created the layer, you can populate it with data: spans and corresponding annotations. You can use layer's add_annotation(...) method to add new annotations to the specific (text) locations. The method takes two inputs: the location of the span (start,end), and the dictionary of an annotation (attributes-values), and adds annotations to the layer at the specified location: assert isinstance(annotations, dict) new_layer.add_annotation( (start,end), annotations ) If all attribute names are valid Python identifiers, you can also pass annotation as keyword assignments, e.g.: new_layer.add_annotation( (start,end), attr1=..., attr2=... ) In case of an ambiguous layer, you can add multiple annotations to the same location via layer.add_annotation(...), but this is not allowed for unambiguous layers. Note #1: if the layer does not define any attributes, you can use new_layer.add_annotation( (start,end) ) to create a markup without attributes-values (an empty annotation). Note #2: location of the span can be given as (start,end) only if the output layer is not enveloping. In case of an enveloping layer, a more complex structure should be used, please consult the documentation of BaseSpan (from estnltk_core) for details. Note #3: you cannot add two Spans (or EnvelopingSpan-s) that have exactly the same text location, however, partially overlapping spans are allowed. """ __slots__ = ['_initialized', 'conf_param', 'output_layer', 'output_attributes', 'input_layers'] def __new__(cls, *args, **kwargs): instance = super().__new__(cls) object.__setattr__(instance, '_initialized', False) return instance def __init__(self): raise NotImplementedError('__init__ method not implemented in ' + self.__class__.__name__) def __copy__(self): raise NotImplementedError('__copy__ method not implemented in ' + self.__class__.__name__) def __deepcopy__(self, memo={}): raise NotImplementedError('__deepcopy__ method not implemented in ' + self.__class__.__name__) def __setattr__(self, key, value): if self._initialized: raise AttributeError('changing of the tagger attributes is not allowed: {!r}, {!r}'.format( self.__class__.__name__, key)) assert key in {'conf_param', 'output_layer', 'output_attributes', 'input_layers', '_initialized'} or\ key in self.conf_param,\ 'attribute {!r} not listed in {}.conf_param'.format(key, self.__class__.__name__) super().__setattr__(key, value) # TODO: rename layers -> detached_layers ? # TODO: remove status parameter, use Layer.meta instead def _make_layer(self, text: Union['BaseText', 'Text'], layers: MutableMapping[str, Layer], status: dict) -> Layer: """ Creates and returns a new layer, based on the given `text` and its `layers`. **This method needs to be implemented in a derived class.** Parameters ---------- text: Union['BaseText', 'Text'] Text object to be annotated. layers: MutableMapping[str, Layer] A mapping from layer names to corresponding Layer objects. Layers in the mapping can be detached from the Text object. It can be assumed that all tagger's `input_layers` are in the mapping. IMPORTANT: input_layers should always be accessed via the layers parameter, and NOT VIA THE TEXT OBJECT, because the Text object is not guaranteed to have the input layers as attached layers at this processing stage. status: dict Dictionary for recording status messages about tagging. Note: the status parameter is **deprecated**. To store any metadata, use ``layer.meta`` instead. Returns ---------- Layer Created Layer object, which is detached from the Text object. """ raise NotImplementedError('make_layer method not implemented in ' + self.__class__.__name__) # TODO: rename layers -> detached_layers ? # TODO: change argument type layers: Set[str] def make_layer(self, text: Union['BaseText', 'Text'], layers: Union[MutableMapping[str, Layer], Set[str]] = None, status: dict = None) -> Layer: """ Creates and returns a new layer, based on the given `text` and its `layers`. Note: derived classes **should not override** this method. Parameters ---------- text: Union['BaseText', 'Text'] Text object to be annotated. layers: MutableMapping[str, Layer] A mapping from layer names to corresponding Layer objects. Layers in the mapping can be detached from the Text object. It is assumed that all tagger's `input_layers` are in the mapping. IMPORTANT: the new layer is created based on input_layers in the mapping, and not based on layers attached to the Text object. status: dict Dictionary with status messages about tagging. Note: the status parameter is **deprecated**. To store/access metadata, use ``layer.meta`` instead. Returns ---------- Layer Created Layer object, which is detached from the Text object. ============================================================================= # QUICK FIXES: layers should be a dictionary of layers but due to the changes in the Text object signature, it is actually a list of layer names which will cause a lot of problems in refactoring. Hence, we convert list of layer names to dictionary of layers. # REFLECTION: Adding layers as a separate argument is justified only if the layer is not present in the text object but then these layers become undocumented input which make the dependency graph useless. The only useful place where layers as separate argument is useful is in text collectons where we cn work with detached layers directly. Hence, it makes sense to rename layers parameter as detached_layers and check that these are indeed detached Also fix some resolving order for the case text[layer] != layers[layer] BUG: The function alters layers if it is specified as variable. This can lead to unexpected results """ assert status is None or isinstance(status, dict), 'status should be None or dict, not {!r}'.format(type(status)) if status is None: status = {} layers = layers or {} # Quick fix for refactoring problem (does not propagate changes out of the function) if type(layers) == set and (not layers or set(map(type, layers)) == {str}): layers = {layer: text[layer] for layer in layers} # End of fix for layer in self.input_layers: if layer in layers: continue if layer in text.layers: layers[layer] = text[layer] else: raise ValueError('missing input layer: {!r}'.format(layer)) try: layer = self._make_layer(text=text, layers=layers, status=status) except Exception as e: e.args += ('in the {!r}'.format(self.__class__.__name__),) raise assert isinstance(layer, Layer), '{}._make_layer did not return a Layer object, but {!r}'.format( self.__class__.__name__, type(layer)) assert layer.text_object is text, '{}._make_layer returned a layer with incorrect Text object'.format( self.__class__.__name__) assert layer.attributes == self.output_attributes,\ '{}._make_layer returned layer with unexpected attributes: {} != {}'.format( self.__class__.__name__, layer.attributes, self.output_attributes) assert isinstance(layer, Layer), self.__class__.__name__ + '._make_layer must return Layer' assert layer.name == self.output_layer,\ '{}._make_layer returned a layer with incorrect name: {} != {}'.format( self.__class__.__name__, layer.name, self.output_layer) return layer def tag(self, text: Union['BaseText', 'Text'], status: dict = None) -> Union['BaseText', 'Text']: """Annotates Text object with this tagger. Note: derived classes **should not override** this method. Parameters ----------- text: Union['BaseText', 'Text'] Text object to be tagged. status: dict, default {} This can be used to store layer creation metadata. Returns ------- Union['BaseText', 'Text'] Input Text object which has a new (attached) layer created by this tagger. """ text.add_layer(self.make_layer(text=text, layers=(text.layers).union(text.relation_layers), status=status)) return text def _make_layer_template(self) -> Layer: """ Returns an empty detached layer that contains all parameters of the output layer. This method needs to be implemented in a derived class. """ raise NotImplementedError('_make_layer_template method not implemented in ' + self.__class__.__name__) def get_layer_template(self) -> Layer: """ Returns an empty detached layer that contains all parameters of the output layer. """ return self._make_layer_template() def __call__(self, text: Union['BaseText', 'Text'], status: dict = None) -> Union['BaseText', 'Text']: return self.tag(text, status) def _repr_html_(self): assert self.__doc__ is not None, 'No docstring.' description = self.__doc__.strip().split('\n', 1)[0] return self._repr_html('Tagger', description) def _repr_html(self, heading: str, description: str): import pandas parameters = {'name': self.__class__.__name__, 'output layer': self.output_layer, 'output attributes': str(self.output_attributes), 'input layers': str(self.input_layers)} table = pandas.DataFrame(data=parameters, columns=['name', 'output layer', 'output attributes', 'input layers'], index=[0]) table = table.to_html(index=False) table = ['<h4>{}</h4>'.format(heading), description, table] if self.conf_param: public_param = [p for p in self.conf_param if not p.startswith('_')] conf_values = [to_str(getattr(self, attr)) for attr in public_param] conf_table = pandas.DataFrame(conf_values, index=public_param) conf_table = conf_table.to_html(header=False) conf_table = ('<h4>Configuration</h4>', conf_table) else: conf_table = ('No configuration parameters.',) table.extend(conf_table) return '\n'.join(table) def __repr__(self): conf_str = '' if self.conf_param: params = ['input_layers', 'output_layer', 'output_attributes'] + list(self.conf_param) try: conf = [attr+'='+to_str(getattr(self, attr)) for attr in params if not attr.startswith('_')] except AttributeError as e: e.args = e.args[0] + ", but it is listed in 'conf_param'", raise conf_str = ', '.join(conf) return self.__class__.__name__ + '(' + conf_str + ')' def __str__(self): return self.__class__.__name__ + '(' + str(self.input_layers) + '->' + self.output_layer + ')' # for compatibility with Taggers in resolve_layer_tag def parameters(self): record = {'name': self.__class__.__name__, 'layer': self.output_layer, 'attributes': self.output_attributes, 'depends_on': self.input_layers, 'configuration': [p+'='+str(getattr(self, p)) for p in self.conf_param if not p.startswith('_')] } return record
(*args, **kwargs)
57,403
estnltk_core.taggers.tagger
__call__
null
def __call__(self, text: Union['BaseText', 'Text'], status: dict = None) -> Union['BaseText', 'Text']: return self.tag(text, status)
(self, text: Union[ForwardRef('BaseText'), ForwardRef('Text')], status: dict = None) -> Union[ForwardRef('BaseText'), ForwardRef('Text')]
57,408
estnltk_core.taggers.tagger
__repr__
null
def __repr__(self): conf_str = '' if self.conf_param: params = ['input_layers', 'output_layer', 'output_attributes'] + list(self.conf_param) try: conf = [attr+'='+to_str(getattr(self, attr)) for attr in params if not attr.startswith('_')] except AttributeError as e: e.args = e.args[0] + ", but it is listed in 'conf_param'", raise conf_str = ', '.join(conf) return self.__class__.__name__ + '(' + conf_str + ')'
(self)
57,414
estnltk_core.taggers.tagger
_repr_html_
null
def _repr_html_(self): assert self.__doc__ is not None, 'No docstring.' description = self.__doc__.strip().split('\n', 1)[0] return self._repr_html('Tagger', description)
(self)
57,419
estnltk.text
Text
Central component of EstNLTK. Encapsulates the raw text and allows applying text analysers (taggers). Text analysis results (annotations) are also stored in the Text object, and can be accessed and explored as layers. Text 101 ========= You can create new Text object simply by passing analysable text to the constructor: from estnltk import Text my_text=Text('Tere, maailm!') Now, you can use `tag_layer` method to add linguistic analyses to the text: # add morphological analysis to the text my_text.tag_layer('morph_analysis') Type `Text.layer_resolver` to get more information about layers that can be tagged. Added layer can be accessed via indexing (square brackets): my_text['morph_analysis'] or as an attribute: my_text.morph_analysis This returns the whole layer, but if you need to access analyses of specific words, you can either iterate over the layer: for word in my_text['morph_analysis']: # do something with the word's analyses ... Or you can use index to access analyses of specific word: # morph analysis (span) of the first word my_text['morph_analysis'][0] Note that both index access and iteration over the layer gives you spans (locations) of annotations in the text. To access corresponding annotation values, you can either use index access: # get 'partofspeech' values from morph analysis of the first word my_text['morph_analysis'][0]['partofspeech'] Or used attribute `.annotations` to get all annotations as a list: # get all morph analysis annotations of the first word my_text['morph_analysis'][0].annotations In both cases, a list is returned, because annotations can be ambiguous, so list holds multiple alternative interpretations. Metadata ========= It is possible to add meta-information about text as a whole by specifying text.meta, which is a dictionary of type MutableMapping[str, Any]. However, we strongly advise to use the following value types: str int float DateTime as database serialisation does not work for other types. See [estnltk.storage.postgres] for further documentation. More tools =========== `Text.layer_resolver` contains taggers of the default NLP pipeline. More taggers can be found in `estnltk.taggers`: import estnltk.taggers # List names of taggers that can be imported dir( estnltk.taggers ) How to use manually a tagger imported from `estnltk.taggers` ? 1) Initialize the tagger, e.g. from estnltk.taggers import VabamorfTagger tagger = VabamorfTagger() 2) Create input layers required by the tagger, e.g. new_text = Text(...) new_text.tag_layer( tagger.input_layers ) 3) Tag layer with the tagger: tagger.tag( new_text ) Note that some of the taggers are retaggers, which means that instead of creating a layer they modify an existing layer. In that case, you should use `tagger.retag( new_text )` instead. ---
class Text( BaseText ): """Central component of EstNLTK. Encapsulates the raw text and allows applying text analysers (taggers). Text analysis results (annotations) are also stored in the Text object, and can be accessed and explored as layers. Text 101 ========= You can create new Text object simply by passing analysable text to the constructor: from estnltk import Text my_text=Text('Tere, maailm!') Now, you can use `tag_layer` method to add linguistic analyses to the text: # add morphological analysis to the text my_text.tag_layer('morph_analysis') Type `Text.layer_resolver` to get more information about layers that can be tagged. Added layer can be accessed via indexing (square brackets): my_text['morph_analysis'] or as an attribute: my_text.morph_analysis This returns the whole layer, but if you need to access analyses of specific words, you can either iterate over the layer: for word in my_text['morph_analysis']: # do something with the word's analyses ... Or you can use index to access analyses of specific word: # morph analysis (span) of the first word my_text['morph_analysis'][0] Note that both index access and iteration over the layer gives you spans (locations) of annotations in the text. To access corresponding annotation values, you can either use index access: # get 'partofspeech' values from morph analysis of the first word my_text['morph_analysis'][0]['partofspeech'] Or used attribute `.annotations` to get all annotations as a list: # get all morph analysis annotations of the first word my_text['morph_analysis'][0].annotations In both cases, a list is returned, because annotations can be ambiguous, so list holds multiple alternative interpretations. Metadata ========= It is possible to add meta-information about text as a whole by specifying text.meta, which is a dictionary of type MutableMapping[str, Any]. However, we strongly advise to use the following value types: str int float DateTime as database serialisation does not work for other types. See [estnltk.storage.postgres] for further documentation. More tools =========== `Text.layer_resolver` contains taggers of the default NLP pipeline. More taggers can be found in `estnltk.taggers`: import estnltk.taggers # List names of taggers that can be imported dir( estnltk.taggers ) How to use manually a tagger imported from `estnltk.taggers` ? 1) Initialize the tagger, e.g. from estnltk.taggers import VabamorfTagger tagger = VabamorfTagger() 2) Create input layers required by the tagger, e.g. new_text = Text(...) new_text.tag_layer( tagger.input_layers ) 3) Tag layer with the tagger: tagger.tag( new_text ) Note that some of the taggers are retaggers, which means that instead of creating a layer they modify an existing layer. In that case, you should use `tagger.retag( new_text )` instead. --- """ # All methods for BaseText/Text object # methods: Set[str] methods = { '_repr_html_', 'add_layer', 'analyse', 'layer_attributes', 'pop_layer', 'diff', 'layers', 'relation_layers', 'sorted_layers', 'sorted_relation_layers', 'tag_layer', 'topological_sort', } | {method for method in dir(object) if callable(getattr(object, method, None))} # presorted_layers: Tuple[str, ...] presorted_layers = ( 'paragraphs', 'sentences', 'tokens', 'compound_tokens', 'words', 'morph_analysis', 'morph_extended' ) """ Presorted layers used for visualization purposes (BaseText._repr_html_). """ # layer resolver that is used for computing layers layer_resolver = DEFAULT_RESOLVER """ LayerResolver that is used for computing layers. Defaults to DEFAULT_RESOLVER from estnltk.default_resolver. Note 1: if you mess up the resolver accidentially, you can restart it via make_resolver() function: from estnltk.default_resolver import make_resolver # Reset default resolver Text.layer_resolver = make_resolver() Note 2: if you want to use Python's multiprocessing, you should make a separate LayerResolver for each process/job, otherwise you'll likely run into errors. tag_layer method can take resolver as a parameter. """ def tag_layer(self, layer_names: Union[str, Sequence[str]]=None, resolver=None) -> 'Text': """ Tags given layers along with their prerequisite layers. Returns this Text object with added layers. Type `Text.layer_resolver` to get more information about layers that can be tagged by default. If you don't pass any parameters, defaults to tagging 'sentences' and 'morph_analysis' layers along with their prerequisite layers (segmentation layers). Note: if you want to use Python's multiprocessing, you should make a separate LayerResolver for each process/job, and pass it as a `resolver` parameter while tagging a text. You can use `make_resolver` from `estnltk.default_resolver` to create new resolver instances. Parameters ---------- layer_names: Union[str, Sequence[str]] (default: None) Names of the layers to be tagged. If not specified, tags `resolver.default_layers`. And if `resolver` is not specified, uses `Text.layer_resolver.default_layers` instead. Note that you can only tag layers that are available in the resolver, i.e. layers listed by resolver's `layers` attribute. resolver: LayerResolver (default: None) Resolver to be used for tagging the layers. If not specified, then uses `Text.layer_resolver` which is equivalent to DEFAULT_RESOLVER from estnltk.default_resolver. Returns ---------- Text This Text object with added layers. """ if resolver is None: resolver = self.layer_resolver if isinstance(layer_names, str): layer_names = [layer_names] if layer_names is None: layer_names = resolver.default_layers for layer_name in layer_names: resolver.apply(self, layer_name) return self def analyse(self, t: str, resolver=None) -> 'Text': """ Analyses text by adding NLP layers corresponding to the given level `t`. **Important**: this method is deprecated, please use Text.tag_layer instead! How to replace Text.analyse functionality with Text.tag_layer? * text.analyse('segmentation') is same as text.tag_layer('paragraphs'); text.pop_layer('tokens'); * text.analyse('morphology') is same as text.tag_layer('morph_analysis'); text.pop_layer('tokens'); * text.analyse('syntax_preprocessing') is same as text.tag_layer(['sentences','morph_extended']); text.pop_layer('tokens'); * text.analyse('all') is same as text.tag_layer(['paragraphs','morph_extended']); """ raise Exception("(!) Text.analyse method is deprecated. Please use Text.tag_layer instead.\n\n"+\ "How to replace Text.analyse function with Text.tag_layer? \n"+\ "1) text.analyse('segmentation') is same as text.tag_layer('paragraphs');"+\ "text.pop_layer('tokens');\n"+\ "2) text.analyse('morphology') is same as text.tag_layer('morph_analysis');"+\ "text.pop_layer('tokens');\n"+\ "3) text.analyse('syntax_preprocessing') is same as text.tag_layer(['sentences','morph_extended']);"+\ "text.pop_layer('tokens');\n"+\ "4) text.analyse('all') is same as text.tag_layer(['paragraphs','morph_extended']);\n\n"+\ "Also, you can use Text.layer_resolver to explore which layers can be tagged.") @property def layer_attributes(self) -> Dict[str, List[str]]: """ Returns a mapping from all attributes to layer names hosting them. """ result = dict() # Collect attributes from standard layers for name, layer in self._layers.items(): for attrib in layer.attributes: if attrib not in result: result[attrib] = [] result[attrib].append(name) return result # attribute_mapping_for_elementary_layers: Mapping[str, str] attribute_mapping_for_elementary_layers = { 'lemma': 'morph_analysis', 'root': 'morph_analysis', 'root_tokens': 'morph_analysis', 'ending': 'morph_analysis', 'clitic': 'morph_analysis', 'form': 'morph_analysis', 'partofspeech': 'morph_analysis' } attribute_mapping_for_enveloping_layers = attribute_mapping_for_elementary_layers def __delattr__(self, item): raise TypeError("'{}' object does not support attribute deletion, use pop_layer(...) function instead".format( self.__class__.__name__ )) def __getattr__(self, item): # Resolve slots if item in self.__class__.__slots__: return self.__getattribute__(item) # Resolve all function calls if item in self.__class__.methods: return self.__getattribute__(item) # Resolve layers if item in self.layers: return self.__getitem__(item) # Resolve attributes that uniquely determine a layer, e.g. BaseText/Text.lemmas ==> BaseText/Text.morph_layer.lemmas attributes = self.__getattribute__('layer_attributes') if len( attributes.get(item, []) ) == 1: return getattr(self._layers[attributes[item][0]], item) # Nothing else to resolve raise AttributeError("'{}' object has no layer {!r}".format( self.__class__.__name__, item ))
(text: str = None) -> None
57,420
estnltk_core.base_text
__copy__
null
def __copy__(self): raise Exception('Shallow copying of {} object is not allowed. Use deepcopy instead.'.format( self.__class__.__name__ ) )
(self)
57,421
estnltk_core.base_text
__deepcopy__
null
def __deepcopy__(self, memo={}): #print(memo) text = copy(self.text) result = self.__class__( text ) memo[id(self)] = result memo[id(text)] = text result.meta = deepcopy(self.meta, memo) # Layers must be created in the topological order for span_layer in self.sorted_layers(): layer = deepcopy(span_layer, memo) layer.text_object = None memo[id(layer)] = layer result.add_layer(layer) for relation_layer in self.sorted_relation_layers(): layer = deepcopy(relation_layer, memo) layer.text_object = None memo[id(layer)] = layer result.add_layer(layer) return result
(self, memo={})
57,422
estnltk.text
__delattr__
null
def __delattr__(self, item): raise TypeError("'{}' object does not support attribute deletion, use pop_layer(...) function instead".format( self.__class__.__name__ ))
(self, item)
57,423
estnltk_core.base_text
__delitem__
null
def __delitem__(self, key): raise TypeError("'{}' object does not support item deletion, use pop_layer(...) function instead".format( self.__class__.__name__ ))
(self, key)
57,425
estnltk.text
__getattr__
null
def __getattr__(self, item): # Resolve slots if item in self.__class__.__slots__: return self.__getattribute__(item) # Resolve all function calls if item in self.__class__.methods: return self.__getattribute__(item) # Resolve layers if item in self.layers: return self.__getitem__(item) # Resolve attributes that uniquely determine a layer, e.g. BaseText/Text.lemmas ==> BaseText/Text.morph_layer.lemmas attributes = self.__getattribute__('layer_attributes') if len( attributes.get(item, []) ) == 1: return getattr(self._layers[attributes[item][0]], item) # Nothing else to resolve raise AttributeError("'{}' object has no layer {!r}".format( self.__class__.__name__, item ))
(self, item)
57,426
estnltk_core.base_text
__getitem__
null
def __getitem__(self, item): if item in self._layers: return self._layers[item] elif item in self._relation_layers: return self._relation_layers[item] else: raise KeyError("'{}' object has no layer {!r}".format( self.__class__.__name__, item ))
(self, item)
57,427
estnltk_core.base_text
__getstate__
null
def __getstate__(self): # No copying is allowed or we cannot properly restore text object with recursive references. return dict(text=self.text, meta=self.meta, layers=[layer for layer in self.sorted_layers()], relation_layers=[layer for layer in self.sorted_relation_layers()])
(self)
57,428
estnltk_core.base_text
__init__
null
def __init__(self, text: str = None) -> None: assert text is None or isinstance(text, str), "{} takes string as an argument!".format( self.__class__.__name__ ) # self.text: str super().__setattr__('text', text) # self.meta: MutableMapping super().__setattr__('meta', {}) # self._layers: MutableMapping object.__setattr__(self, '_layers', {}) # self._relation_layers: MutableMapping object.__setattr__(self, '_relation_layers', {})
(self, text: Optional[str] = None) -> NoneType
57,429
estnltk_core.base_text
__repr__
null
def __repr__(self): if self.text is None: return '{}()'.format( self.__class__.__name__ ) text_string = self.text if len(text_string) > 10000: text_string = '{}\n\n<skipping {} characters>\n\n{}'.format(text_string[:8000], len(text_string) - 9000, text_string[-1000:]) return '{classname}(text={text_string!r})'.format(classname=self.__class__.__name__, text_string=text_string)
(self)
57,430
estnltk_core.base_text
__setattr__
null
def __setattr__(self, name, value): # Resolve meta attribute if name == 'meta': if not isinstance(value, dict): raise ValueError('meta must be of type dict') if value and set(map(type, value)) != {str}: raise ValueError('meta must be of type dict with keys of type str') return super().__setattr__(name, value) # Resolve text attribute if name == 'text': if self.__getattribute__('text') is not None: raise AttributeError('raw text has already been set') if not isinstance(value, str): raise TypeError('expecting a string as value') return super().__setattr__('text', value) # Deny access to all other attributes (layer names) raise AttributeError('layers cannot be assigned directly, use add_layer(...) function instead')
(self, name, value)
57,431
estnltk_core.base_text
__setitem__
null
def __setitem__(self, key, value): raise TypeError('layers cannot be assigned directly, use add_layer(...) function instead')
(self, key, value)
57,432
estnltk_core.base_text
__setstate__
null
def __setstate__(self, state): # Initialisation is not guaranteed! Bypass the text protection mechanism assert type(state['text']) == str, '\'field \'text\' must be of type str' super().__setattr__('text', state['text']) super().__setattr__('meta', state['meta']) super().__setattr__('_layers', {}) super().__setattr__('_relation_layers', {}) # Layer.text_object is already set! Bypass the add_layer protection mechanism # By wonders of pickling this resolves all recursive references including references to the text object itself for layer in state['layers']: assert id(layer.text_object) == id(self), '\'layer.text_object\' must reference caller' layer.text_object = None self.add_layer(layer) if 'relation_layers' in state: # Restore relation layers (available starting from version 1.7.2+) for rel_layer in state['relation_layers']: assert id(rel_layer.text_object) == id(self), '\'relation_layer.text_object\' must reference caller' rel_layer.text_object = None self.add_layer(rel_layer)
(self, state)
57,433
estnltk_core.base_text
_repr_html_
null
def _repr_html_(self): if self.text is None: table = '<h4>Empty {} object</h4>'.format( self.__class__.__name__ ) else: text = self.text if len(text) > 10000: text = '{}\n\n<skipping {} characters>\n\n{}'.format(text[:8000], len(text) - 9000, text[-1000:]) text_html = '<div align = "left">' + html.escape(text).replace('\n', '</br>') + '</div>' df = pandas.DataFrame(columns=['text'], data=[text_html]) table = df.to_html(index=False, escape=False) if self.meta: data = {'key': sorted(self.meta), 'value': [self.meta[k] for k in sorted(self.meta)]} table_meta = pandas.DataFrame(data, columns=['key', 'value']) table_meta = table_meta.to_html(header=False, index=False) table = '\n'.join((table, '<h4>Metadata</h4>', table_meta)) layer_table = '' relations_layer_table = '' if self._layers: layers = [] # Try to fetch presorted layers (only available in Text) presorted_layers = getattr(self, 'presorted_layers', ()) for layer_name in presorted_layers: assert isinstance(layer_name, str) layer = self._layers.get(layer_name) if layer is not None: layers.append(layer) # Assuming self._layers is always ordered (requires Python 3.7+) for layer_name in self._layers: if layer_name not in presorted_layers: layers.append(self._layers[layer_name]) layer_table = pandas.DataFrame() layer_table = pandas.concat([layer.get_overview_dataframe() for layer in layers]) layer_table = layer_table.to_html(index=False, escape=False) layer_table = '\n'.join(('', layer_table)) if self._relation_layers: layers = [] for layer_name in self._relation_layers: layers.append(self._relation_layers[layer_name]) relations_layer_table = pandas.DataFrame() relations_layer_table = pandas.concat([layer.get_overview_dataframe() for layer in layers]) relations_layer_table = relations_layer_table.to_html(index=False, escape=False) relations_layer_table = '\n'.join(('', relations_layer_table)) return ''.join((table, layer_table, relations_layer_table))
(self)
57,434
estnltk_core.base_text
add_layer
Adds a layer to the text object. Use this method to add both span layers and relation layers. An addable layer must satisfy the following conditions: * layer.name is unique among names of all existing layers (span layers and relation layers) of this Text object; * layer.text_object is either None or points to this Text object; if layer has already been associated with another Text object, throws an AssertionError; * (span layer specific) if the layer has parent, then its parent layer must already exist among the layers of this Text object; * (span layer specific) if the layer is enveloping, then the layer it envelops must already exist among the layers of this Text object;
def add_layer(self, layer: Union[BaseLayer, 'Layer', RelationLayer]): """ Adds a layer to the text object. Use this method to add both span layers and relation layers. An addable layer must satisfy the following conditions: * layer.name is unique among names of all existing layers (span layers and relation layers) of this Text object; * layer.text_object is either None or points to this Text object; if layer has already been associated with another Text object, throws an AssertionError; * (span layer specific) if the layer has parent, then its parent layer must already exist among the layers of this Text object; * (span layer specific) if the layer is enveloping, then the layer it envelops must already exist among the layers of this Text object; """ if isinstance(layer, BaseLayer): # add span layer name = layer.name assert name not in self._layers, \ 'this {} object already has a span layer with name {!r}'.format(self.__class__.__name__, name) assert name not in self._relation_layers, \ 'this {} object already has a relation layer with name {!r}'.format(self.__class__.__name__, name) if layer.text_object is None: layer.text_object = self else: assert layer.text_object is self, \ "can't add layer {!r}, this layer is already bound to another {} object".format(name, self.__class__.__name__) if layer.parent: assert layer.parent in self._layers, 'Cant add a layer "{layer}" before adding its parent "{parent}"'.format( parent=layer.parent, layer=layer.name) if layer.enveloping: assert layer.enveloping in self._layers, "can't add an enveloping layer before adding the layer it envelops" self._layers[name] = layer elif isinstance(layer, RelationLayer): # add relation layer name = layer.name assert name not in self._layers, \ 'this {} object already has a span layer with name {!r}'.format(self.__class__.__name__, name) assert name not in self._relation_layers, \ 'this {} object already has a relation layer with name {!r}'.format(self.__class__.__name__, name) if layer.text_object is None: layer.text_object = self else: assert layer.text_object is self, \ "can't add relation layer {!r}, this layer is already bound to another {} object".format(name, self.__class__.__name__) self._relation_layers[name] = layer else: raise AssertionError('BaseLayer or RelationLayer expected, got {!r}'.format(type(layer)))
(self, layer: Union[estnltk_core.layer.base_layer.BaseLayer, ForwardRef('Layer'), estnltk_core.layer.relation_layer.RelationLayer])
57,435
estnltk.text
analyse
Analyses text by adding NLP layers corresponding to the given level `t`. **Important**: this method is deprecated, please use Text.tag_layer instead! How to replace Text.analyse functionality with Text.tag_layer? * text.analyse('segmentation') is same as text.tag_layer('paragraphs'); text.pop_layer('tokens'); * text.analyse('morphology') is same as text.tag_layer('morph_analysis'); text.pop_layer('tokens'); * text.analyse('syntax_preprocessing') is same as text.tag_layer(['sentences','morph_extended']); text.pop_layer('tokens'); * text.analyse('all') is same as text.tag_layer(['paragraphs','morph_extended']);
def analyse(self, t: str, resolver=None) -> 'Text': """ Analyses text by adding NLP layers corresponding to the given level `t`. **Important**: this method is deprecated, please use Text.tag_layer instead! How to replace Text.analyse functionality with Text.tag_layer? * text.analyse('segmentation') is same as text.tag_layer('paragraphs'); text.pop_layer('tokens'); * text.analyse('morphology') is same as text.tag_layer('morph_analysis'); text.pop_layer('tokens'); * text.analyse('syntax_preprocessing') is same as text.tag_layer(['sentences','morph_extended']); text.pop_layer('tokens'); * text.analyse('all') is same as text.tag_layer(['paragraphs','morph_extended']); """ raise Exception("(!) Text.analyse method is deprecated. Please use Text.tag_layer instead.\n\n"+\ "How to replace Text.analyse function with Text.tag_layer? \n"+\ "1) text.analyse('segmentation') is same as text.tag_layer('paragraphs');"+\ "text.pop_layer('tokens');\n"+\ "2) text.analyse('morphology') is same as text.tag_layer('morph_analysis');"+\ "text.pop_layer('tokens');\n"+\ "3) text.analyse('syntax_preprocessing') is same as text.tag_layer(['sentences','morph_extended']);"+\ "text.pop_layer('tokens');\n"+\ "4) text.analyse('all') is same as text.tag_layer(['paragraphs','morph_extended']);\n\n"+\ "Also, you can use Text.layer_resolver to explore which layers can be tagged.")
(self, t: str, resolver=None) -> estnltk.text.Text
57,436
estnltk_core.base_text
diff
Returns a brief diagnostic message that explains why two BaseText/Text objects are different. # BUGS: - Inf loops with recursive self-references in meta dictionary.
def diff(self, other): """ Returns a brief diagnostic message that explains why two BaseText/Text objects are different. # BUGS: - Inf loops with recursive self-references in meta dictionary. """ if self is other: return None if not isinstance(other, self.__class__): return 'Not a {} object.'.format( self.__class__.__name__ ) if self.text != other.text: return 'The raw text is different.' if set(self._layers) != set(other.layers): return 'Different layer names: {} != {}'.format(set(self._layers), set(other.layers)) if set(self._relation_layers) != set(other.relation_layers): return 'Different relation layer names: {} != {}'.format( set(self._relation_layers), \ set(other.relation_layers)) if self.meta != other.meta: return 'Different metadata.' for layer_name in self._layers: difference = self._layers[layer_name].diff(other[layer_name]) if difference: return difference for layer_name in self._relation_layers: difference = self._relation_layers[layer_name].diff(other[layer_name]) if difference: return difference return None
(self, other)
57,437
estnltk_core.base_text
pop_layer
Removes a layer from the text object together with the layers that are computed from it by default. Use this method to remove both span layers and relation layers. (span layer specific) If the flag cascading is set all descendant layers are computed first and removed together with the layer. If the flag is false only the layer is removed. This does not corrupt derivative layers, as spans of each layer are independent form other layers. Returns popped layer if the layer is present in the text object. If the layer is not found, then default is returned if given, otherwise KeyError is raised.
def pop_layer(self, name: str, cascading: bool = True, default=Ellipsis) -> Union[BaseLayer, 'Layer', RelationLayer, Any]: """ Removes a layer from the text object together with the layers that are computed from it by default. Use this method to remove both span layers and relation layers. (span layer specific) If the flag cascading is set all descendant layers are computed first and removed together with the layer. If the flag is false only the layer is removed. This does not corrupt derivative layers, as spans of each layer are independent form other layers. Returns popped layer if the layer is present in the text object. If the layer is not found, then default is returned if given, otherwise KeyError is raised. """ if name in self.layers: # remove span layer if not cascading: return self._layers.pop(name, None) # Find layer's descendant layers to_delete = sorted(find_layer_dependencies(self, name, reverse=True)) result = self._layers.pop(name, None) for name in to_delete: self._layers.pop(name, None) return result elif name in self.relation_layers: # remove relation layer result = self._relation_layers.pop(name, None) return result else: if default is Ellipsis: raise KeyError('{layer!r} is not a valid layer in this {classname} object'.format(layer=name,classname=self.__class__.__name__)) else: return default
(self, name: str, cascading: bool = True, default=Ellipsis) -> Union[estnltk_core.layer.base_layer.BaseLayer, ForwardRef('Layer'), estnltk_core.layer.relation_layer.RelationLayer, Any]
57,438
estnltk_core.base_text
sorted_layers
Returns a list of span layers of this text object in order of dependencies and layer names. The order is uniquely determined.
def sorted_layers(self) -> List[Union[BaseLayer, 'Layer']]: """ Returns a list of span layers of this text object in order of dependencies and layer names. The order is uniquely determined. """ return self.topological_sort(self._layers)
(self) -> List[Union[estnltk_core.layer.base_layer.BaseLayer, ForwardRef('Layer')]]
57,439
estnltk_core.base_text
sorted_relation_layers
Returns a list of relation layers of this text object in alphabetical order of layer names. Note: the default ordering returned by this method is subject to change in future versions, if we add dependencies between relation layers.
def sorted_relation_layers(self) -> List[RelationLayer]: """ Returns a list of relation layers of this text object in alphabetical order of layer names. Note: the default ordering returned by this method is subject to change in future versions, if we add dependencies between relation layers. """ return [self._relation_layers[layer] for layer in sorted(self.relation_layers)]
(self) -> List[estnltk_core.layer.relation_layer.RelationLayer]
57,440
estnltk.text
tag_layer
Tags given layers along with their prerequisite layers. Returns this Text object with added layers. Type `Text.layer_resolver` to get more information about layers that can be tagged by default. If you don't pass any parameters, defaults to tagging 'sentences' and 'morph_analysis' layers along with their prerequisite layers (segmentation layers). Note: if you want to use Python's multiprocessing, you should make a separate LayerResolver for each process/job, and pass it as a `resolver` parameter while tagging a text. You can use `make_resolver` from `estnltk.default_resolver` to create new resolver instances. Parameters ---------- layer_names: Union[str, Sequence[str]] (default: None) Names of the layers to be tagged. If not specified, tags `resolver.default_layers`. And if `resolver` is not specified, uses `Text.layer_resolver.default_layers` instead. Note that you can only tag layers that are available in the resolver, i.e. layers listed by resolver's `layers` attribute. resolver: LayerResolver (default: None) Resolver to be used for tagging the layers. If not specified, then uses `Text.layer_resolver` which is equivalent to DEFAULT_RESOLVER from estnltk.default_resolver. Returns ---------- Text This Text object with added layers.
def tag_layer(self, layer_names: Union[str, Sequence[str]]=None, resolver=None) -> 'Text': """ Tags given layers along with their prerequisite layers. Returns this Text object with added layers. Type `Text.layer_resolver` to get more information about layers that can be tagged by default. If you don't pass any parameters, defaults to tagging 'sentences' and 'morph_analysis' layers along with their prerequisite layers (segmentation layers). Note: if you want to use Python's multiprocessing, you should make a separate LayerResolver for each process/job, and pass it as a `resolver` parameter while tagging a text. You can use `make_resolver` from `estnltk.default_resolver` to create new resolver instances. Parameters ---------- layer_names: Union[str, Sequence[str]] (default: None) Names of the layers to be tagged. If not specified, tags `resolver.default_layers`. And if `resolver` is not specified, uses `Text.layer_resolver.default_layers` instead. Note that you can only tag layers that are available in the resolver, i.e. layers listed by resolver's `layers` attribute. resolver: LayerResolver (default: None) Resolver to be used for tagging the layers. If not specified, then uses `Text.layer_resolver` which is equivalent to DEFAULT_RESOLVER from estnltk.default_resolver. Returns ---------- Text This Text object with added layers. """ if resolver is None: resolver = self.layer_resolver if isinstance(layer_names, str): layer_names = [layer_names] if layer_names is None: layer_names = resolver.default_layers for layer_name in layer_names: resolver.apply(self, layer_name) return self
(self, layer_names: Union[str, Sequence[str], NoneType] = None, resolver=None) -> estnltk.text.Text
57,441
estnltk_core.base_text
topological_sort
Returns a list of span layers of the given dict of layers in order of dependencies and layer names. The order is uniquely determined. layers: Mapping[str, Union[BaseLayer, Layer]] maps layer name to layer
@staticmethod def topological_sort(layers: Mapping[str, Union[BaseLayer, 'Layer']]) -> List[Union[BaseLayer, 'Layer']]: """ Returns a list of span layers of the given dict of layers in order of dependencies and layer names. The order is uniquely determined. layers: Mapping[str, Union[BaseLayer, Layer]] maps layer name to layer """ layer_list = sorted(layers.values(), key=lambda l: l.name) layer_name_set = set([l.name for l in layer_list]) sorted_layers = [] sorted_layer_names = set() while layer_list: success = False for layer in layer_list: if (layer.parent is None or layer.parent in sorted_layer_names) and \ (layer.enveloping is None or layer.enveloping in sorted_layer_names): sorted_layers.append(layer) sorted_layer_names.add(layer.name) layer_list.remove(layer) success = True break if layer_list and not success: # If we could not remove any layer from layer_list, then the data # is malformed: contains unknown dependencies. # Add layers with unknown dependencies to the end of the sorted list. for layer in layer_list: if (layer.parent is not None and layer.parent not in layer_name_set) or \ (layer.enveloping is not None and layer.enveloping not in layer_name_set): sorted_layers.append(layer) sorted_layer_names.add(layer.name) layer_list.remove(layer) break return sorted_layers
(layers: Mapping[str, Union[estnltk_core.layer.base_layer.BaseLayer, ForwardRef('Layer')]]) -> List[Union[estnltk_core.layer.base_layer.BaseLayer, ForwardRef('Layer')]]