Pipeline¶
Building a pipeline¶
What every get_iterator_and_processor does: a data iterator that does not give the excluded tokens of a tokenizer, and a chain of processors
>>> from functools import partial
>>> from pie_extended.pipeline.postprocessor.proto import ProcessorPrototype, SelectTasksProcessor
>>> processor = chained(partial(SelectTasksProcessor, selected=["lemma"]), ProcessorPrototype())
>>> processor.set_tasks(["lemma", "pos"])
['lemma']
- pie_extended.pipeline.build.chained(*links)[source]¶
A chain of processors: the outermost first (the first to see the annotations of a token), the innermost last, as an instance. Each other link makes its processor from head_processor=, the one that follows it: a class, a partial…
- Return type:
- pie_extended.pipeline.build.iterator_for(tokenizer, max_tokens=256, exclude=None, *, excluded_by_tokenizer=True)[source]¶
The data iterator of a model: the tokens that the excluders of the tokenizer put aside are not tagged, nor the patterns of exclude
- Parameters:
excluded_by_tokenizer (bool) – False for a tokenizer with no excluders (the iterator then only has exclude)
max_tokens (int)
exclude (Iterable | None)
- Return type:
Data iterator¶
- class pie_extended.pipeline.iterators.proto.GenericExcludePatterns(*values)[source]¶
Bases:
EnumUseful set of regular expresion that can be used for the exclude_patterns
- Punctuation_and_Underscore: Pattern = regex.Regex('^[_||[^\\s\\w]]+$', flags=regex.F | regex.V1)¶
- Punctuation: Pattern = regex.Regex('^[^\\s\\w]+$', flags=regex.V0)¶
- PassageMarker: Pattern = regex.Regex('_Passage_[\\w\\d_]+', flags=regex.V0)¶
- class pie_extended.pipeline.iterators.proto.DataIterator(tokenizer=None, exclude_patterns=None, max_tokens=256)[source]¶
Bases:
object- Parameters:
tokenizer (SimpleTokenizer)
exclude_patterns (List[str | Pattern])
max_tokens (int)
- tokenizer: SimpleTokenizer¶
- exclude_patterns: List[Pattern]¶
- add_pattern(pattern)[source]¶
Add a pattern for removal
- Parameters:
pattern (str) – Pattern for token removal
- reset_patterns()[source]¶
Removes removal patterns
>>> x = DataIterator(exclude_patterns=[r'\W+']) >>> x.exclude_tokens(["Je", "suis", "content", ",", "mais", "...", '"', "fatigué", '"', "."]) (['Je', 'suis', 'content', 'mais', 'fatigué'], {3: ',', 5: '...', 6: '"', 8: '"', 9: '.'}) >>> x.reset_patterns() >>> x.exclude_tokens(["Je", "suis", "content", ",", "mais", "...", '"', "fatigué", '"', "."]) (['Je', 'suis', 'content', ',', 'mais', '...', '"', 'fatigué', '"', '.'], {})
- Return type:
None
- exclude_tokens(sentence)[source]¶
Removes punctuation from a list and keeps its index
- Parameters:
sentence (List[str]) – Tokens of a sentence
- Returns:
First the sentence with things removed, then a dictionary whose keys are index of token to reinsert and associated values are punctuation to reinsert.
- Return type:
Tuple[List[str], Dict[int, str]]
You can use string when generating the exclude_pattern
>>> x = DataIterator(exclude_patterns=[r'\W+']) >>> x.exclude_tokens(["Je", "suis", "content",",", "mais", "...", '"', "fatigué", '"', "."]) (['Je', 'suis', 'content', 'mais', 'fatigué'], {3: ',', 5: '...', 6: '"', 8: '"', 9: '.'})
Pre-built removers:
>>> x = DataIterator(exclude_patterns=[GenericExcludePatterns.PassageMarker]) >>> x.exclude_tokens(["_Passage_45_78", "Ici", "commence", "le", "passage"]) (['Ici', 'commence', 'le', 'passage'], {0: '_Passage_45_78'})
And of course you can ignore this option
>>> x = DataIterator() >>> x.exclude_tokens(["_Passage_45_78", "Ici", "commence", "le", "passage"]) (['_Passage_45_78', 'Ici', 'commence', 'le', 'passage'], {})
- spacing()[source]¶
Tells, for each token of the last text read, if it is followed by a space in this text
Memorizing tokenizers know the tokens before replacement, others have not changed them.
- Returns:
A boolean per token (in the order of the text, excluded tokens included) and the number of tokens that could not be located in the text
- Return type:
Tuple[List[bool], int]
Tokenizers¶
- class pie_extended.pipeline.tokenizers.simple_tokenizer.SimpleTokenizer[source]¶
Bases:
objectTokenizer that memoryze what it tokenized.
Mostly used to normalized input as input time and then reinserting normalized input
- sentence_tokenizer(text, lower=False)[source]¶
- Parameters:
text (str)
lower (bool)
- Return type:
Generator[List[str], None, None]
- word_tokenizer(text, lower=False)[source]¶
- Parameters:
text (str)
lower (bool)
- Return type:
List[str]
- surface_tokens()[source]¶
How each token of the last text read is written in this text, if it differs from the token itself.
None (the default) means that tokens are written as they are (or, for memorizing tokenizers, that their memory knows it). A tokenizer that moves things around (see the Armenian one) overrides it to give, for each token, the part of the text it comes from, or an empty string for a token that is written nowhere.
- Return type:
List[str] | None
- bypass_tokenizer(data, lower=False)[source]¶
Function to enable pretokenized input while using replaces or the likes
- Parameters:
data (str) – The string (one new line = one word, two new lines = two words)
lower (bool) – Whether to lower the input
- Return type:
Generator[List[str], None, None]
>>> tokenizer = SimpleTokenizer() >>> list(tokenizer.bypass_tokenizer("one\ntwo\nthree\n\n.//.\na\nz")) [['one', 'two', 'three'], ['.//.', 'a', 'z']]
- class pie_extended.pipeline.tokenizers.simple_tokenizer.LengthTokenizer(max_len=35)[source]¶
Bases:
SimpleTokenizer
- class pie_extended.pipeline.tokenizers.memorizing.MemorizingTokenizer[source]¶
Bases:
SimpleTokenizerTokenizer that memoryze what it tokenized.
Mostly used to normalized input as input time and then reinserting normalized input
- replacer(token)[source]¶
This function allows for changing input and keeping it in memory
- Parameters:
token (str)
- Return type:
str
- property tokens: List[Tuple[int, str, str]]¶
(Index, Original input, Input seen by the tagger) for each token.
Replacing it (what reset does) also rewinds the cursor used by next_token.
- Type:
Memory of the tokenizer
- next_token()[source]¶
Gives the next entry of the memory, in the order of the text (O(1), unlike list.pop(0))
>>> tokenizer = MemorizingTokenizer() >>> tokenizer.tokens = [(0, "A", "a"), (1, "b", "b")] >>> tokenizer.next_token(), tokenizer.next_token() ((0, 'A', 'a'), (1, 'b', 'b')) >>> tokenizer.next_token() Traceback (most recent call last): ... IndexError: The memory of the tokenizer has no more tokens >>> tokenizer.reset() >>> tokenizer.tokens []
- Return type:
Tuple[int, str, str]
- word_tokenizer(text, lower=False)[source]¶
- Parameters:
text (str)
lower (bool)
- Return type:
List[str]
- bypass_tokenizer(data, lower=False)[source]¶
Function to enable pretokenized input while using replaces or the likes
- Parameters:
data (str) – The string (one new line = one word, two new lines = two words)
lower (bool) – Whether to lower the input
- Return type:
Generator[List[str], None, None]
>>> tokenizer = MemorizingTokenizer() >>> list(tokenizer.bypass_tokenizer("One\ntwo\nthree\n\n.//.\na\nz")) [['One', 'two', 'three'], ['.//.', 'a', 'z']] >>> tokenizer.tokens [(0, 'One', 'One'), (1, 'two', 'two'), (2, 'three', 'three'), (3, './/.', './/.'), (4, 'a', 'a'), (5, 'z', 'z')]
The tokenizer that most of the models share: it is made of data, and a hook.
A language declares what it excludes, where its sentences end and how a word is replaced:
>>> class Tokenizer(RuleTokenizer):
... def replace(self, token: str) -> str:
... return token.lower()
>>> t = Tokenizer()
>>> list(t.sentence_tokenizer("Un mot. Deux mots !"))
[['un', 'mot', '.'], ['deux', 'mots', '!']]
>>> t.tokens
[(0, 'Un', 'un'), (1, 'mot', 'mot'), (2, '.', '.'), (3, 'Deux', 'deux'), (4, 'mots', 'mots'), (5, '!', '!')]
- class pie_extended.pipeline.tokenizers.rules.RuleTokenizer[source]¶
Bases:
MemorizingTokenizerCuts a text in sentences, then in words, keeps in memory what it replaced
What a language gives:
excluders(registry): the tokens that are put aside, and given back after the tagging (references, abbreviations…)
replace(token): what the tagger sees of a token that no excluder took (treated in the output). By default, the token itself
re_sentence_boundaries, re_add_space_around_punct: where the sentences end, and the punctuation to put apart
char_registry(): the registry of the characters that the excluders write in the text while they work
replacer is the whole decision (excluders first, then replace): a language can still take it over.
- re_add_space_around_punct = regex.Regex('(\\s*)([^\\w\\s])(\\s*)', flags=regex.V0)¶
- re_sentence_boundaries = regex.Regex('([.?!\\"“”\\"«»…\\[\\]\\(\\)„“]+\\s*)+', flags=regex.V0)¶
- strict_lower = False¶
- excluders(registry)[source]¶
- Parameters:
registry (CharRegistry)
- Return type:
Tuple[ExcluderPrototype, …]
- sentence_tokenizer(text, lower=False)[source]¶
- Parameters:
text (str)
lower (bool)
- Return type:
Generator[List[str], None, None]
- exclude_patterns()[source]¶
What the data iterator must not give to the tagger: the tokens that an excluder puts aside
- Return type:
list
A segmenter that learns where a treebank cuts words, shared by the languages that need it.
Some treebanks make several words of one written word (զմեղս -> զ, մեղս), and models trained on them expect the same cuts. When no rule can say where (many words legitimately start with the same letters as a proclitic), the cuts are learned: an averaged perceptron decides, for each position inside a word, whether the treebank cuts there, from the characters around it (and from the word itself, which makes it a lexicon for the known words).
A language gives its data, nothing more: the letters of its words (WORD), its tokenizer (to know the tokens that are to be cut), and the treebank it learns from (learn). Classical Armenian is the first one: pie_extended.models.hy_xcl.
The weights are learned on the machine of the user, they are not distributed when the license of the treebank (NC, SA…) would be inherited by a file derived from it.
>>> class Letters(LearnedSegmenter):
... WORD = re.compile(r"^[a-z]+$")
>>> examples = [("inthe", {2}), ("inside", {2}), ("home", set()), ("inform", {2}), ("hotel", set())] * 4
>>> segmenter = Letters.train(examples, epochs=6)
>>> segmenter.cuts("inthe"), segmenter.cuts("hotel")
([2], [])
>>> segmenter.split("inside")
['in', 'side']
- pie_extended.pipeline.tokenizers.learned.features(word, position)[source]¶
Features of the position between word[:position] and word[position:]
- Parameters:
word (str)
position (int)
- Return type:
List[str]
- pie_extended.pipeline.tokenizers.learned.read_conllu(path)[source]¶
Sentences of a CoNLL-U file: the text, and the words (multiword token ranges and empty nodes are skipped)
- Parameters:
path (str)
- Return type:
Iterator[Tuple[str, List[str]]]
- class pie_extended.pipeline.tokenizers.learned.LearnedSegmenter(weights=None)[source]¶
Bases:
objectGives where a word has to be cut. A language sets WORD: only words that match it can be cut
- Parameters:
weights (Dict[str, float])
- WORD = regex.Regex('^\\w+$', flags=regex.V0)¶
- weights: Dict[str, float]¶
- cuts(word)[source]¶
Positions (between characters) where word is cut
- Parameters:
word (str)
- Return type:
List[int]
- classmethod load_or_warn(path, warning, warn=True)[source]¶
The segmenter that was learned, or None (with warning) if it was not
- Parameters:
path (str)
warning (str)
warn (bool)
- Return type:
LearnedSegmenter | None
- classmethod train(examples, epochs=8, seed=0)[source]¶
Averaged perceptron
- Parameters:
examples (Sequence[Tuple[str, Set[int]]]) – A word, and the positions where it has to be cut
epochs (int)
seed (int)
- Return type:
- static training_examples(sentences, tokenizer)[source]¶
Where the treebank cuts the words, for the tokens of our tokenizer (without any segmentation)
A sentence is skipped if our tokens cannot be rebuilt from its words (different spelling, for example).
- Parameters:
sentences (Iterable[Tuple[str, List[str]]])
- Return type:
List[Tuple[str, Set[int]]]
- evaluate(sentences, make_tokenizer)[source]¶
Scores on sentences of a treebank
- Parameters:
make_tokenizer (Callable[[...], object]) – Makes the tokenizer of the language: make_tokenizer() without segmentation, and make_tokenizer(segmenter=…) with it
sentences (Sequence[Tuple[str, List[str]]])
- Returns:
Precision, recall and F1 of the cut points, share of words cut as in the treebank, and share of sentences whose words are exactly the ones of the treebank
- Return type:
Dict[str, float]
- pie_extended.pipeline.tokenizers.learned.learn(segmenter, treebank, make_tokenizer, path, download)[source]¶
Learns where a treebank cuts the words, and keeps what was learned (a few seconds)
- Parameters:
segmenter (type) – The class of the language (a LearnedSegmenter)
treebank (Mapping[str, str]) – The URL of the CoNLL-U file for each of train, dev and test
make_tokenizer (Callable[[...], object]) – The tokenizer of the language, see LearnedSegmenter.evaluate
path (str) – Where to keep the weights
download (Callable[[str, str], None]) – download(url, filename)
- Return type:
Excluders¶
- class pie_extended.pipeline.tokenizers.utils.excluder.CharRegistry(use_default=True, unicode_start_range=36096)[source]¶
Bases:
object- APOSTROPHE_CONSTANT: str = '#APOSTROPHE#'¶
- class pie_extended.pipeline.tokenizers.utils.excluder.ExcluderPrototype[source]¶
Bases:
ABCExcluders should be used to remove dots and the likes from string before sentence tokenization. Data can be reintroduce later with their .denormalize() method
- property can_be_replaced: bool¶
- property exclude_regexp: compile | None¶
- class pie_extended.pipeline.tokenizers.utils.excluder.ReferenceExcluder(regex_string='(\\[REF:[^\\]]+\\])', regex_needs_replacement='[^\\w\\s]', char_registry=None)[source]¶
Bases:
ExcluderPrototypeAllows for exclusion of reference tokens such as [REF:1.b.Z]
>>> ref = ReferenceExcluder() >>> len(ref.before_sentence_tokenizer("ici [REF:###abc??<>] Paris").split()) == 3 True >>> len(ref.after_sentence_tokenizer('ici 左REF桁贆贆贆abc贉贉贇贈右 Paris').split()) == 3 True >>> ref.after_sentence_tokenizer(ref.before_sentence_tokenizer("ici [REF:###abc??<>] Paris")) 'ici [REF:###abc??<>] Paris'
- Parameters:
regex_string (str)
regex_needs_replacement (str)
char_registry (CharRegistry | None)
- re: compile¶
- char_registry: CharRegistry¶
- needs_replacement: compile¶
- property can_be_replaced: bool¶
- property exclude_regexp: compile | None¶
- before_sentence_tokenizer(value)[source]¶
Normalize a string before it goes into sentence tokenizing
- Parameters:
value (str) – String to clean
- Return type:
str
>>> excl = ReferenceExcluder() >>> excl.before_sentence_tokenizer("Choubidou [REF:1.a.Z] choubida [REF:1.b.Z]") 'Choubidou 左REF桁1語a語Z右 choubida 左REF桁1語b語Z右 '
- after_sentence_tokenizer(value)[source]¶
Reset the state of a string before it goes into sentence tokenizing
- Parameters:
value (str) – String to clean
- Return type:
str
>>> excl = ReferenceExcluder() >>> excl.after_sentence_tokenizer('Choubidou 左REF桁1語a語Z右 choubida 左REF桁1語b語Z右') 'Choubidou [REF:1.a.Z] choubida [REF:1.b.Z]'
- class pie_extended.pipeline.tokenizers.utils.excluder.RegexpExcluder(regex)[source]¶
Bases:
ExcluderPrototype- Parameters:
regex (str)
- property can_be_replaced: bool¶
- property exclude_regexp: compile | None¶
- class pie_extended.pipeline.tokenizers.utils.excluder.AbbreviationsExcluder(abbrs, apply_replacements=True, char_registry=None)[source]¶
Bases:
ExcluderPrototype- Parameters:
abbrs (List[str])
apply_replacements (bool)
char_registry (CharRegistry | None)
- char_registry: CharRegistry¶
- property can_be_replaced: bool¶
- property exclude_regexp: compile | None¶
- before_sentence_tokenizer(value)[source]¶
Normalize a string before it goes into sentence tokenizing
- Parameters:
value (str) – String to clean
- Return type:
str
>>> excl = AbbreviationsExcluder(['cf.', 'p.']) >>> excl.before_sentence_tokenizer("cf. p. 45 et les. points.") 'cf語 p語 45 et les. points.'
- after_sentence_tokenizer(value)[source]¶
Reset the state of a string before it goes into sentence tokenizing
- Parameters:
value (str) – String to clean
- Return type:
str
>>> excl = AbbreviationsExcluder(['cf.', 'p.']) >>> excl.after_sentence_tokenizer('cf語 p語 45 et les. points.') 'cf. p. 45 et les. points.'
- class pie_extended.pipeline.tokenizers.utils.excluder.AbbreviationsRemoverExcluder(abbrs, apply_replacements=True, char_registry=None)[source]¶
Bases:
AbbreviationsExcluder- Parameters:
abbrs (List[str])
apply_replacements (bool)
char_registry (CharRegistry | None)
- after_sentence_tokenizer(value)[source]¶
Reset the state of a string before it goes into sentence tokenizing
- Parameters:
value (str) – String to clean
- Return type:
str
>>> excl = AbbreviationsRemoverExcluder(['cf.', 'p.']) >>> excl.after_sentence_tokenizer('cf語 p語 45 et les. points.') 'cf p 45 et les. points.'
- class pie_extended.pipeline.tokenizers.utils.excluder.CompoundAbbreviationsExcluder(abbrs, apply_replacements=True, ignore_case=True, char_registry=None)[source]¶
Bases:
AbbreviationsExcluder- Parameters:
abbrs (List[str])
apply_replacements (bool)
ignore_case (bool)
char_registry (CharRegistry | None)
- class pie_extended.pipeline.tokenizers.utils.excluder.DottedNumberExcluder(number_regex='(?:M{1,4}(?:CM|CD|D?C{0,3})(?:XC|XL|L?X{0,3})(?:IX|IV|V?I{0,3})|M{0,4}(?:CM|C?D|D?C{1,3})(?:XC|XL|L?X{0,3})(?:IX|IV|V?I{0,3})|M{0,4}(?:CM|CD|D?C{0,3})(?:XC|X?L|L?X{1,3})(?:IX|IV|V?I{0,3})|M{0,4}(?:CM|CD|D?C{0,3})(?:XC|XL|L?X{0,3})(?:IX|I?V|V?I{1,3}))', char_registry=None)[source]¶
Bases:
ExcluderPrototype- Parameters:
number_regex (str)
char_registry (CharRegistry | None)
- char_registry: CharRegistry¶
- class pie_extended.pipeline.tokenizers.utils.excluder.ApostropheExcluder(match_apostrophes="'’ʼ", char_registry=None, add_space_after=True, add_space_before=False, regex=None)[source]¶
Bases:
ExcluderPrototypeAllows for keeping apostrophes that are the mark of an elision, mostly in French such as “l’abbé”
- Parameters:
char_registry (CharRegistry | None)
add_space_after (bool)
add_space_before (bool)
regex (str | None)
- re: compile¶
- space_before: str¶
- space_after: str¶
- before_sentence_tokenizer(value)[source]¶
Normalization run before sentence tokenization
- Parameters:
value (str) – String to normalize before sentence is toknized
- Return type:
str
>>> excl = ApostropheExcluder(add_space_after=True) >>> excl.before_sentence_tokenizer("l'abbé lorsqu’il") 'l風0abbé lorsqu風1il'
- after_sentence_tokenizer(value)[source]¶
Normalization run after sentence tokenization
- Parameters:
value (str) – String to normalize before sentence is toknized
- Return type:
str
>>> excl = ApostropheExcluder(add_space_after=True) >>> excl.after_sentence_tokenizer('l風0abbé lorsqu風1il') "l' abbé lorsqu’ il"
Spacing¶
- pie_extended.pipeline.tokenizers.spacing.space_after(text, tokens, lower=False)[source]¶
Finds out, for each token, if it is followed by a space in the original text.
Tokenizers throw away whitespace (str.split, inserted spaces around punctuation, sentence splitting…), so the tokens are aligned back, in order, on the original text.
A token is followed by a space when the next character in the text is whitespace. At the very end of the text, we consider there is a space after (nothing is glued to the next token).
- Parameters:
text (str) – Original text
tokens (List[str]) – Tokens in the order they were found in the text, before any replacement. An empty string is a token that is not written in the text but moved from somewhere else (see below).
lower (bool) – Whether the tokens were lowercased by the tokenizer
- Returns:
One boolean per token (True if a space follows), and the number of tokens that could not be located in the text (those are given True)
- Return type:
Tuple[List[bool], int]
>>> space_after("Arma uirumque: cano", ["Arma", "uirumque", ":", "cano"]) ([True, False, True, True], 0) >>> space_after("Arma uirumque\n:cano.", ["Arma", "uirumque", ":", "cano", "."]) ([True, True, False, False, True], 0)
Case is ignored if the tokenizer lowered the input:
>>> space_after("Arma uirumque", ["arma", "uirumque"], lower=True) ([True, True], 0)
A token that is not written in the text (an empty string) is glued to the previous token. This is for tokenizers that detach a character from its word and output it after it (Armenian Մի՞թե -> Միթե, ՞): the word is given with the whole written form (mark included), and the moved token with an empty string.
>>> space_after("Մի՞թե այդ", ["Մի՞թե", "", "այդ"]) ([False, True, True], 0) >>> space_after("Ո՞րն էր", ["Ո՞րն", "", "էր"]) ([False, True, True], 0)
A token we cannot find does not prevent the next ones from being aligned:
>>> space_after("Arma (uirumque) cano", ["Arma", "(", "ZZZ", ")", "cano"]) ([True, False, True, True, True], 1)
Processors¶
- class pie_extended.pipeline.postprocessor.proto.ProcessorPrototype(empty_value=None)[source]¶
Bases:
object- Parameters:
empty_value (str)
- empty_value: str¶
- property tasks: List[str]¶
- set_spacing(spacing)[source]¶
Receives, for each token of the document, if it is followed by a space (only used by the processors that output it, see SpaceAfterProcessor)
- Parameters:
spacing (List[bool])
- Return type:
None
- required_tasks(requested, available)[source]¶
Translates output columns into the tasks that models must produce for them
- Parameters:
requested (List[str]) – Output columns that are wanted
available (List[str]) – Tasks that models can produce
- Returns:
Tasks (of the layer below) required to build the requested columns
- Return type:
List[str]
>>> ProcessorPrototype().required_tasks(["a"], ["a", "b"]) ['a']
- reinsert(form)[source]¶
Generates an automatic line for a token that was removed from lemmatization
- Parameters:
form (str) – Token to reinsert
- Returns:
Dictionary representation of the token, as an annotation
- Return type:
Dict[str, str]
>>> x = ProcessorPrototype(empty_value="%") >>> x.set_tasks(["a", "b"]) ['a', 'b'] >>> x.reinsert("x") == {"form": "x", "a": "%", "b": "%"} True
- get_dict(token, tags)[source]¶
Get the dictionary representation of a token annotation
- Parameters:
token (str) – Token used as input for pie
tags (List[str]) – List of tags generated
- Returns:
Dictionary representation of the token and its annotations
- Return type:
List[Dict[str, str]]
>>> x = ProcessorPrototype(empty_value="%") >>> x.set_tasks(["a", "b"]) ['a', 'b'] >>> x.get_dict("y", ["1", "2"]) == [{"form": "y", "a": "1", "b": "2"}] True
- class pie_extended.pipeline.postprocessor.proto.RenamedTaskProcessor(task_map, **kwargs)[source]¶
Bases:
ProcessorPrototype- Parameters:
task_map (Dict[str, str])
- class pie_extended.pipeline.postprocessor.proto.ChainedProcessor(head_processor, **kwargs)[source]¶
Bases:
ProcessorPrototypeAllows for easy chaining !
The ChainedProcessor is basically using its headprocessor in the background and checking it’s output to some extent
The prototype of ChainedProcessor using Processor Prototype would have the same results because chained processor is not doing anything new except enabling chaining
>>> x = ProcessorPrototype(empty_value="%") >>> x.set_tasks(["a", "b"]) ['a', 'b'] >>> y = ChainedProcessor(x) >>> y.set_tasks(["a", "b"]) ['a', 'b'] >>> x.reinsert("x") == y.reinsert("x") True >>> x.get_dict("y", ["1", "2"]) == y.get_dict("y", ["1", "2"]) True
You can subclass it to modify the output of the preceding processor :
>>> class ExampleChained(ChainedProcessor): ... def reinsert(self, form: str) -> Dict[str, str]: ... annotation = self.head_processor.reinsert(form) ... annotation["col3"] = "x" ... return annotation ... ... def get_dict(self, form: str, tags: List[str]) -> List[Dict[str, str]]: ... return [{"col3": "x", **{x:y for x, y in anno.items() if x != "col3"}} ... for anno in self.head_processor.get_dict(form, tags)] >>> x = ExampleChained(ProcessorPrototype(empty_value="EMPTY")) >>> x.set_tasks(["a", "b"]) ['a', 'b'] >>> x.reinsert("x") == {"form": "x", "a": "EMPTY", "b": "EMPTY", "col3": "x"} True >>> x.get_dict("y", ["1", "2"]) == [{"form": "y", "a": "1", "b": "2", "col3": "x"}] True
- Parameters:
head_processor (ProcessorPrototype)
- head_processor: ProcessorPrototype¶
- get_dict(token, tags)[source]¶
- Parameters:
token (str)
tags (List[str])
- Return type:
List[Dict[str, str]]
- class pie_extended.pipeline.postprocessor.proto.SelectTasksProcessor(head_processor, selected, **kwargs)[source]¶
Bases:
ChainedProcessorRestricts the output columns to a subset of the tasks.
Useful when a processor needs hidden dependencies (e.g. a lemma to split clitics) that were not asked for by the user.
>>> x = SelectTasksProcessor(ProcessorPrototype(), ["b"]) >>> x.set_tasks(["a", "b"]) ['b'] >>> x.get_dict("y", ["1", "2"])[0]["b"] '2'
- Parameters:
head_processor (ProcessorPrototype)
selected (List[str])
- selected: List[str]¶
- property tasks: List[str]¶
- class pie_extended.pipeline.postprocessor.memory.MemoryzingProcessor(tokenizer_memory, head_processor, key=None, **kwargs)[source]¶
Bases:
ChainedProcessorMemoryzingProcessor proposes to keep track of changes operated on input string by reinserting the original data alongside a new task (KEY) where we output the input seen by the Model
It reuses the memory from a class derived from MemorizingTokenizer so that it reintroduced the original input into the token.
>>> from pie_extended.pipeline.tokenizers.memorizing import MemorizingTokenizer >>> tokenizer = MemorizingTokenizer() >>> # Fake token memory : (Index, Original Input, Input seen by Tagger) >>> tokenizer.tokens = [(0, "A", "a"), (0, "b", "b"), (0, "q'", "q")] >>> processor = MemoryzingProcessor(tokenizer_memory=tokenizer, head_processor=ProcessorPrototype()) >>> processor.set_tasks(["lem"]) ['lem', 'treated'] >>> # Lowercase a was taken in the input but uppercase a is returned in form. For transparency, input seen >>> # By the tagger is returned in a new column, treated (cf. MemorizingProcessor.KEY) >>> processor.get_dict("a", ["lemma"]) == [{"form": "A", "treated": "a", "lem": "lemma"}] True >>> # Some would have the same treated and input >>> processor.get_dict("b", ["lemma"]) == [{"form": "b", "treated": "b", "lem": "lemma"}] True >>> # Some differ with more characters >>> processor.get_dict("q", ["lemma"]) == [{"form": "q'", "treated": "q", "lem": "lemma"}] True
This allows for easier output alignment as well as removing unknown characters to the model. If your lemmatizer in training has never seen the “@” character, you can remove it at tokenization time and reinsert it with MemoryzingProcessor
- Parameters:
tokenizer_memory (MemorizingTokenizer)
head_processor (ProcessorPrototype)
key (str | None)
- KEY: str = 'treated'¶
- get_dict(token, tags)[source]¶
- Parameters:
token (str)
tags (List[str])
- Return type:
List[Dict[str, str]]
- property tasks: List[str]¶
- reinsert(form)[source]¶
Reinsert the token, should add treated to the output
>>> from pie_extended.pipeline.tokenizers.memorizing import MemorizingTokenizer >>> tokenizer = MemorizingTokenizer() >>> tokenizer.tokens = ["$"] >>> x = MemoryzingProcessor(tokenizer, ProcessorPrototype()) >>> x.set_tasks(["task1", "task2"]) ['task1', 'task2', 'treated'] >>> x.reinsert("$") {'form': '$', 'task1': '_', 'task2': '_', 'treated': '--IGN.--'}
- Parameters:
form (str)
- Return type:
Dict[str, str]
- class pie_extended.pipeline.postprocessor.glue.GlueProcessor(*args, **kwargs)[source]¶
Bases:
ChainedProcessorGlues together specific tasks
>>> from pie_extended.pipeline.postprocessor.proto import ProcessorPrototype, RenamedTaskProcessor >>> class SimpleGlue(GlueProcessor): ... OUTPUT_KEYS = ["form", "lemma", "task3"] ... GLUE = {"task3": ["1", "2"]} # Merges Task `1` output and task `2` output in `task3` ... EMPTY_TAG = {"1": "_", "2": "_"} # If _ is tagged in task `1`, it's the same as an empty tag ... GLUE_EMPTY = {"task3": "NO-DATA"} # When all merged data are empty, default value >>> x = SimpleGlue(head_processor=ProcessorPrototype()) >>> x.set_tasks(["lemma", "1", "2"]) # You can see things are remaped ['lemma', 'task3'] >>> # Merges b and c values from task 1 and 2 into a new task >>> x.get_dict("a", ["a", "b", "c"]) == [{"form": "a", "lemma": "a", "task3": "1=b|2=c"}] True >>> # Keeps only one task because 2 is empty >>> x.get_dict("a", ["a", "b", "_"]) == [{"form": "a", "lemma": "a", "task3": "1=b"}] True >>> # Fills with the default empty tag because both task 1 and 2 were empty >>> x.get_dict("a", ["a", "_", "_"]) == [{"form": "a", "lemma": "a", "task3": "NO-DATA"}] True
You can also use remaped tasks:
>>> class AnotherGlue(GlueProcessor): ... OUTPUT_KEYS = ["form", "lemma", "POS", "task3"] ... GLUE = {"task3": ["1", "2"]} # Merges Task `1` output and task `2` output in `task3` ... EMPTY_TAG = {"1": "_", "2": "_"} # If _ is tagged in task `1`, it's the same as an empty tag ... GLUE_EMPTY = {"task3": "NO-DATA"} # When all merged data are empty, default value >>> x = AnotherGlue(head_processor=RenamedTaskProcessor({"pos": "POS"})) >>> x.set_tasks(["lemma", "pos", "1", "2"]) # You can see things are remaped ['lemma', 'POS', 'task3'] >>> # Merges b and c values from task 1 and 2 into a new task >>> x.get_dict("a", ["a", "p", "b", "c"]) [{'form': 'a', 'lemma': 'a', 'POS': 'p', 'task3': '1=b|2=c'}]
- OUTPUT_KEYS: List[str] = ['form', 'lemma', 'POS', 'morph']¶
- GLUE: Dict[str, List[str]] = {'morph': ['Case', 'Numb', 'Deg', 'Mood', 'Tense', 'Voice', 'Person']}¶
- GLUE_CHAR: str = '|'¶
- GLUE_EMPTY: Dict[str, str] = {'morph': 'MORPH=empty'}¶
- EMPTY_TAG: Dict[str, str] = {'Case': '_', 'Deg': '_', 'Mood': '_', 'Numb': '_', 'Person': '_', 'Tense': '_', 'Voice': '_'}¶
- KEEP_EMPTY = False¶
- set_tasks(tasks)[source]¶
Only keeps the output keys that can be built from the tasks that were actually produced
>>> from pie_extended.pipeline.postprocessor.proto import ProcessorPrototype >>> x = GlueProcessor(head_processor=ProcessorPrototype()) >>> x.set_tasks(["lemma", "POS"]) ['lemma', 'POS'] >>> x.get_dict("a", ["l", "p"]) == [{"form": "a", "lemma": "l", "POS": "p"}] True >>> x.set_tasks(["Case", "lemma"]) ['lemma', 'morph'] >>> x.get_dict("a", ["c", "l"]) == [{"form": "a", "lemma": "l", "morph": "Case=c"}] True
- required_tasks(requested, available)[source]¶
- Parameters:
requested (List[str])
available (List[str])
- Return type:
List[str]
- get_dict(token, tags)[source]¶
- Parameters:
token (str)
tags (List[str])
- Return type:
List[Dict[str, str]]
- property tasks: List[str]¶
- class pie_extended.pipeline.postprocessor.rulebased.RuleBasedProcessor(apply_on_reinsert=False, head_processor=None, **kwargs)[source]¶
Bases:
ChainedProcessorApplies rules found in rules(token_annotation)
- Parameters:
apply_on_reinsert (bool)
head_processor (ProcessorPrototype)
- class pie_extended.pipeline.postprocessor.splitter.SplitterPostProcessor(split_char='界', column='lemma', keep=False, head_processor=None, prefix='', **kwargs)[source]¶
Bases:
ChainedProcessorThis processor aims to help in splitting enclitics and proclitics
>>> proc = SplitterPostProcessor() >>> proc.set_tasks(["lemma", "POS", "Case"]) ['lemma', 'POS', 'Case'] >>> proc.get_dict("praedicatione", ["praedicatio界-ne", "NOMcom", "Nominatif"]) == [ ... {"form": "praedicatione", "lemma": "praedicatio", "POS": "NOMcom", "Case": "Nominatif"}, ... {"form": "praedicatione", "lemma": "-ne", "POS": "NOMcom", "Case": "Nominatif"}, ... ] True
keep=True can be used with something like a RuleBased tokenizer to detect beforehand clitics and treat the tokens for example with RuleBased on top of it (len(get_dict()) > 1)
>>> proc = SplitterPostProcessor(keep=True) >>> proc.set_tasks(["lemma", "POS", "Case"]) ['lemma', 'POS', 'Case'] >>> proc.get_dict("praedicatione", ["praedicatio界-ne", "NOMcom", "Nominatif"]) == [ ... {"form": "praedicatione", "lemma": "praedicatio界-ne", "POS": "NOMcom", "Case": "Nominatif"}, ... {"form": "praedicatione", "lemma": "praedicatio界-ne", "POS": "NOMcom", "Case": "Nominatif"} ... ] True >>> proc = SplitterPostProcessor(keep=False, prefix="界") >>> proc.set_tasks(["lemma", "POS", "Case"]) ['lemma', 'POS', 'Case'] >>> proc.get_dict("praedicatione", ["praedicatio界ne", "NOMcom", "Nominatif"]) == [ ... {"form": "praedicatione", "lemma": "praedicatio", "POS": "NOMcom", "Case": "Nominatif"}, ... {"form": "praedicatione", "lemma": "界ne", "POS": "NOMcom", "Case": "Nominatif"} ... ] True
- Parameters:
split_char (str)
column (str)
keep (bool)
head_processor (ProcessorPrototype)
prefix (str)
- class pie_extended.pipeline.postprocessor.spacing.SpaceAfterProcessor(head_processor, **kwargs)[source]¶
Bases:
ChainedProcessorAdds a column telling if a token is followed by a space in the original text (CoNLL-U SpaceAfter).
The value is No when the next token is glued to this one, and the empty value (_) otherwise.
It has to be the outermost processor: it is called once per input token (either with get_dict or with reinsert, in the order of the text), whatever the number of annotations the processors below generate. When a token is split in several annotations (clitics, for example), all of them but the last one are glued to the next one.
>>> processor = SpaceAfterProcessor(ProcessorPrototype()) >>> processor.set_tasks(["lemma"]) ['lemma', 'SpaceAfter'] >>> processor.set_spacing([False, True, True]) >>> processor.get_dict("virumque", ["uir"]) == [{"form": "virumque", "lemma": "uir", "SpaceAfter": "No"}] True >>> processor.reinsert(":") == {"form": ":", "lemma": "_", "SpaceAfter": "_"} True >>> processor.get_dict("cano", ["cano"]) == [{"form": "cano", "lemma": "cano", "SpaceAfter": "_"}] True
The consumed values are forgotten at reset (between documents):
>>> processor.reset() >>> processor.get_dict("cano", ["cano"])[0]["SpaceAfter"] '_'
- Parameters:
head_processor (ProcessorPrototype)
- KEY: str = 'SpaceAfter'¶
- NO_SPACE: str = 'No'¶
- needs_spacing: bool = True¶
- property tasks: List[str]¶
- set_spacing(spacing)[source]¶
Gives, for each token of the document, if it is followed by a space
- Parameters:
spacing (List[bool])
- Return type:
None
Disambiguators¶
- class pie_extended.pipeline.disambiguators.proto.Disambiguator[source]¶
Bases:
objectFunction or class that takes a list of words and returns the disambiguated list of words as tuples
- required: Tuple[str, ...] = ()¶
- class pie_extended.pipeline.disambiguators.autocat.Autocat(autocat_categorizer, separator='', required=(), **kwargs)[source]¶
Bases:
Disambiguator- Parameters:
autocat_categorizer (ProtoDisambiguator)
separator (str)
required (Tuple[str, ...])
- class pie_extended.pipeline.disambiguators.autocat.DisambiguationAsTask(impossible_disambiguator, task_name='Dis', separator='', undisambiguated_marker='?', lemma_key='lemma', empty_value='_')[source]¶
Bases:
ProtoDisambiguator- Parameters:
impossible_disambiguator (NeedsDisambiguation)
task_name (str)
separator (str)
undisambiguated_marker (str)
lemma_key (str)
empty_value (str)
- property known_tokens: Set[str]¶
Lexicons¶
Disambiguation of the lemmas (qui1, qui2) from a lexicon that follows from another annotation.
Disambiguation of lemmas with a lexicon built from an annotated corpus.
Some lemmas are numbered to tell homographs apart (qui1, qui2, sum1…). The number often follows from another annotation: the part of speech. A lexicon says, for a lemma, which number goes with which category, and the model does not need to learn it.
These classes were the library autodisambiguator (autocat) by the same author, now part of Pie Extended.
The lexicons themselves are built from a corpus with pie_extended.pipeline.disambiguators.detector
(or pie-extended build-lexicons).
Each class takes the annotations of a token as a dictionary ({“lemma”: “qui”, “pos”: “PROint”}) and gives back what has to be added to the lemma, or None.
- class pie_extended.pipeline.disambiguators.lexicons.ProtoDisambiguator[source]¶
Bases:
objectSomething that tells what to add to a lemma, given the annotations of the token
- known_tokens: Set[str]¶
- class pie_extended.pipeline.disambiguators.lexicons.NeedsDisambiguation(categorizable, lemma_key='lemma', return_char='?')[source]¶
Bases:
ProtoDisambiguatorMarks the lemmas that need a disambiguation, whatever it is
>>> needs = NeedsDisambiguation(["qui", "sum"]) >>> needs.disambiguate({"lemma": "qui"}), needs.disambiguate({"lemma": "amo"}) ('?', None)
- Parameters:
categorizable (List[str])
lemma_key (str)
- class pie_extended.pipeline.disambiguators.lexicons.CategoryAutodisambiguation(category_key, categorizable, lemma_key='lemma')[source]¶
Bases:
ProtoDisambiguatorDisambiguation that follows from another annotation (the part of speech, for example)
>>> by_pos = CategoryAutodisambiguation("pos", {"qui": {"PROrel": "1", "PROint": "2"}}) >>> by_pos.disambiguate({"lemma": "qui", "pos": "PROint"}) '2' >>> by_pos.disambiguate({"lemma": "qui", "pos": "ADV"}) is None, by_pos.disambiguate({"lemma": "amo", "pos": "VER"}) (True, None)
- Parameters:
category_key (str)
categorizable (Dict[str, Dict[str, str]])
lemma_key (str)
- categorizable: Dict[str, Dict[str, str]]¶
- class pie_extended.pipeline.disambiguators.lexicons.StraightAutodisambiguation(categorizable=None, lemma_key='lemma')[source]¶
Bases:
ProtoDisambiguatorLemmas that have only one possible disambiguation
>>> straight = StraightAutodisambiguation({"sum": "1"}) >>> straight.disambiguate({"lemma": "sum"}), straight.disambiguate({"lemma": "qui"}) ('1', None)
- Parameters:
categorizable (Dict[str, str])
lemma_key (str)
- categorizable: Dict[str, str]¶
- class pie_extended.pipeline.disambiguators.lexicons.GroupAutodisambiguation(categorizers, lemma_key='lemma')[source]¶
Bases:
ProtoDisambiguatorTries several disambiguators in order: the first one that has an answer wins
>>> straight = StraightAutodisambiguation({"sum": "1"}) >>> by_pos = CategoryAutodisambiguation("pos", {"qui": {"PROint": "2"}}) >>> group = GroupAutodisambiguation((straight, by_pos)) >>> list(group.disambiguate_rows([ ... {"lemma": "sum", "pos": "VER"}, {"lemma": "qui", "pos": "PROint"}, {"lemma": "amo", "pos": "VER"}])) ['1', '2', '']
- Parameters:
categorizers (Tuple[ProtoDisambiguator, ...])
lemma_key (str)
The lexicons are built from an annotated corpus (pie-extended build-lexicons):
Builds the lexicons of pie_extended.pipeline.disambiguators.lexicons from an annotated corpus.
It analyzes which disambiguation can be learned from a category (the part of speech, usually) only. The result is the JSON files that feed the lexicons, and the list of the lemmas that cannot be disambiguated this way: these are the ones where the real work of disambiguation (word sense disambiguation) is.
The corpus is TSV files with a header, that contain at least the columns “lemma”, the category (for example “pos”) and “Dis”, the disambiguation index (1 for qui1…):
token lemma pos Dis
qui qui PROint 2
est sum VER 1
qui qui PROrel 1
Use it with pie-extended build-lexicons pos corpus/*.tsv –prefix latin-, or from Python with build_lexicons. (This was the command autodisambiguator of the library of the same name, now part of Pie Extended.)
- pie_extended.pipeline.disambiguators.detector.read_corpus(files, lemma_key='lemma', category_key='pos', disambiguation_key='Dis', null_dis=<function default_null_dis>)[source]¶
- Parameters:
lemma_key (str)
category_key (str)
disambiguation_key (str)
null_dis (Callable[[str], bool])
- Return type:
Dict[str, Dict[str, Counter[str]]]
- pie_extended.pipeline.disambiguators.detector.stats_dict()[source]¶
Function used to generate new dict entry for default dict
- Return type:
Dict[str, int | List]
- class pie_extended.pipeline.disambiguators.detector.Dispatched(stats_per_dis_nb, partially_categorizable, uncategorizable, one_disambiguation_only, autodisambiguation)¶
Bases:
tuple- autodisambiguation¶
Alias for field number 4
- one_disambiguation_only¶
Alias for field number 3
- partially_categorizable¶
Alias for field number 1
- stats_per_dis_nb¶
Alias for field number 0
- uncategorizable¶
Alias for field number 2
- pie_extended.pipeline.disambiguators.detector.dispatch(stats, limit_counter=1)[source]¶
Based on a dictionary of counters
- Parameters:
stats (Dict[str, Dict[str, Dict[str, int]]]) – Dictionary of lemma to disambiguate with a dictionary of index below, themselves holding each CATEGORY it has been found with and their count eg {“qui”: {“1”: {“ADV”: 1, “PROrel”: 50}, “2” {“PROint”: 87}}}
limit_counter (int) – Limit at which we assume the presence of a Category is an error
- Returns:
- pie_extended.pipeline.disambiguators.detector.summary(dispatched)[source]¶
Lines that tell how much of the lemmas can be disambiguated automatically
- Parameters:
dispatched (Dispatched)
- Return type:
List[str]
- pie_extended.pipeline.disambiguators.detector.write_lexicons(dispatched, prefix, category_key)[source]¶
Writes the JSON files of the lexicons
- Returns:
Their paths: {prefix}{category_key}.json (for CategoryAutodisambiguation), {prefix}straight.json (for StraightAutodisambiguation) and {prefix}needs.json (for NeedsDisambiguation)
- Parameters:
dispatched (Dispatched)
prefix (str)
category_key (str)
- Return type:
List[str]
- pie_extended.pipeline.disambiguators.detector.build_lexicons(prefix, category_key, lemma_key, files, disambiguation_key)[source]¶
Reads the corpus, prints a summary, and writes the JSON files of the lexicons (see write_lexicons)
- Parameters:
prefix (str)
category_key (str)
lemma_key (str)
files (Iterable[str])
disambiguation_key (str)
- Return type:
Formatters¶
- class pie_extended.pipeline.formatters.proto.Formatter(tasks)[source]¶
Bases:
objectThe CSV formatter necessarily starts with form in its header.
- Parameters:
tasks (List[str])
- format_line: Callable[[Dict[str, str]], List[str]]¶
- format_line_3_6(annotation)[source]¶
Format the tags
- Parameters:
annotation (Dict[str, str])
- Return type:
List[str]
- Return type:
str