spaCy/spacy/lang/es/lemmatizer.py
Connor Brinton 657af5f91f
🏷 Add Mypy check to CI and ignore all existing Mypy errors (#9167)
* 🚨 Ignore all existing Mypy errors

* 🏗 Add Mypy check to CI

* Add types-mock and types-requests as dev requirements

* Add additional type ignore directives

* Add types packages to dev-only list in reqs test

* Add types-dataclasses for python 3.6

* Add ignore to pretrain

* 🏷 Improve type annotation on `run_command` helper

The `run_command` helper previously declared that it returned an
`Optional[subprocess.CompletedProcess]`, but it isn't actually possible
for the function to return `None`. These changes modify the type
annotation of the `run_command` helper and remove all now-unnecessary
`# type: ignore` directives.

* 🔧 Allow variable type redefinition in limited contexts

These changes modify how Mypy is configured to allow variables to have
their type automatically redefined under certain conditions. The Mypy
documentation contains the following example:

```python
def process(items: List[str]) -> None:
    # 'items' has type List[str]
    items = [item.split() for item in items]
    # 'items' now has type List[List[str]]
    ...
```

This configuration change is especially helpful in reducing the number
of `# type: ignore` directives needed to handle the common pattern of:
* Accepting a filepath as a string
* Overwriting the variable using `filepath = ensure_path(filepath)`

These changes enable redefinition and remove all `# type: ignore`
directives rendered redundant by this change.

* 🏷 Add type annotation to converters mapping

* 🚨 Fix Mypy error in convert CLI argument verification

* 🏷 Improve type annotation on `resolve_dot_names` helper

* 🏷 Add type annotations for `Vocab` attributes `strings` and `vectors`

* 🏷 Add type annotations for more `Vocab` attributes

* 🏷 Add loose type annotation for gold data compilation

* 🏷 Improve `_format_labels` type annotation

* 🏷 Fix `get_lang_class` type annotation

* 🏷 Loosen return type of `Language.evaluate`

* 🏷 Don't accept `Scorer` in `handle_scores_per_type`

* 🏷 Add `string_to_list` overloads

* 🏷 Fix non-Optional command-line options

* 🙈 Ignore redefinition of `wandb_logger` in `loggers.py`

*  Install `typing_extensions` in Python 3.8+

The `typing_extensions` package states that it should be used when
"writing code that must be compatible with multiple Python versions".
Since SpaCy needs to support multiple Python versions, it should be used
when newer `typing` module members are required. One example of this is
`Literal`, which is available starting with Python 3.8.

Previously SpaCy tried to import `Literal` from `typing`, falling back
to `typing_extensions` if the import failed. However, Mypy doesn't seem
to be able to understand what `Literal` means when the initial import
means. Therefore, these changes modify how `compat` imports `Literal` by
always importing it from `typing_extensions`.

These changes also modify how `typing_extensions` is installed, so that
it is a requirement for all Python versions, including those greater
than or equal to 3.8.

* 🏷 Improve type annotation for `Language.pipe`

These changes add a missing overload variant to the type signature of
`Language.pipe`. Additionally, the type signature is enhanced to allow
type checkers to differentiate between the two overload variants based
on the `as_tuple` parameter.

Fixes #8772

*  Don't install `typing-extensions` in Python 3.8+

After more detailed analysis of how to implement Python version-specific
type annotations using SpaCy, it has been determined that by branching
on a comparison against `sys.version_info` can be statically analyzed by
Mypy well enough to enable us to conditionally use
`typing_extensions.Literal`. This means that we no longer need to
install `typing_extensions` for Python versions greater than or equal to
3.8! 🎉

These changes revert previous changes installing `typing-extensions`
regardless of Python version and modify how we import the `Literal` type
to ensure that Mypy treats it properly.

* resolve mypy errors for Strict pydantic types

* refactor code to avoid missing return statement

* fix types of convert CLI command

* avoid list-set confustion in debug_data

* fix typo and formatting

* small fixes to avoid type ignores

* fix types in profile CLI command and make it more efficient

* type fixes in projects CLI

* put one ignore back

* type fixes for render

* fix render types - the sequel

* fix BaseDefault in language definitions

* fix type of noun_chunks iterator - yields tuple instead of span

* fix types in language-specific modules

* 🏷 Expand accepted inputs of `get_string_id`

`get_string_id` accepts either a string (in which case it returns its 
ID) or an ID (in which case it immediately returns the ID). These 
changes extend the type annotation of `get_string_id` to indicate that 
it can accept either strings or IDs.

* 🏷 Handle override types in `combine_score_weights`

The `combine_score_weights` function allows users to pass an `overrides` 
mapping to override data extracted from the `weights` argument. Since it 
allows `Optional` dictionary values, the return value may also include 
`Optional` dictionary values.

These changes update the type annotations for `combine_score_weights` to 
reflect this fact.

* 🏷 Fix tokenizer serialization method signatures in `DummyTokenizer`

* 🏷 Fix redefinition of `wandb_logger`

These changes fix the redefinition of `wandb_logger` by giving a 
separate name to each `WandbLogger` version. For 
backwards-compatibility, `spacy.train` still exports `wandb_logger_v3` 
as `wandb_logger` for now.

* more fixes for typing in language

* type fixes in model definitions

* 🏷 Annotate `_RandomWords.probs` as `NDArray`

* 🏷 Annotate `tok2vec` layers to help Mypy

* 🐛 Fix `_RandomWords.probs` type annotations for Python 3.6

Also remove an import that I forgot to move to the top of the module 😅

* more fixes for matchers and other pipeline components

* quick fix for entity linker

* fixing types for spancat, textcat, etc

* bugfix for tok2vec

* type annotations for scorer

* add runtime_checkable for Protocol

* type and import fixes in tests

* mypy fixes for training utilities

* few fixes in util

* fix import

* 🐵 Remove unused `# type: ignore` directives

* 🏷 Annotate `Language._components`

* 🏷 Annotate `spacy.pipeline.Pipe`

* add doc as property to span.pyi

* small fixes and cleanup

* explicit type annotations instead of via comment

Co-authored-by: Adriane Boyd <adrianeboyd@gmail.com>
Co-authored-by: svlandeg <sofie.vanlandeghem@gmail.com>
Co-authored-by: svlandeg <svlandeg@github.com>
2021-10-14 15:21:40 +02:00

429 lines
16 KiB
Python

from typing import List, Optional, Tuple
import re
from ...pipeline import Lemmatizer
from ...tokens import Token
class SpanishLemmatizer(Lemmatizer):
"""
Spanish rule-based lemmatizer with morph-based rule selection.
"""
@classmethod
def get_lookups_config(cls, mode: str) -> Tuple[List[str], List[str]]:
if mode == "rule":
required = ["lemma_rules", "lemma_rules_groups", "lemma_index", "lemma_exc"]
return (required, [])
else:
return super().get_lookups_config(mode)
def rule_lemmatize(self, token: Token) -> List[str]:
cache_key = (token.orth, token.pos, str(token.morph))
if cache_key in self.cache:
return self.cache[cache_key]
string = token.text
pos = token.pos_.lower()
features = set(token.morph)
if pos in ("", "eol", "space"):
return [string.lower()]
if pos in (
"adp",
"cconj",
"intj",
"part",
"propn",
"punct",
"sconj",
"sym",
"x",
):
if token.is_sent_start and pos != "propn":
return [string.lower()]
else:
return [string]
string = string.lower()
exc = self.lookups.get_table("lemma_exc").get(pos, {}).get(string)
if exc is not None:
lemmas = list(exc)
else:
if pos == "aux":
rule_pos = "verb"
else:
rule_pos = pos
rule = self.select_rule(rule_pos, list(features))
index = self.lookups.get_table("lemma_index").get(rule_pos, [])
lemmas = getattr(self, "lemmatize_" + rule_pos)(
string, features, rule, index
)
# Remove duplicates but preserve the ordering
lemmas = list(dict.fromkeys(lemmas))
self.cache[cache_key] = lemmas
return lemmas
def select_rule(self, pos: str, features: List[str]) -> Optional[str]:
groups = self.lookups.get_table("lemma_rules_groups")
if pos in groups:
for group in groups[pos]:
if set(group[1]).issubset(features):
return group[0]
return None
def lemmatize_adj(
self, word: str, features: List[str], rule: str, index: List[str]
) -> List[str]:
"""
Lemmatize an adjective.
word (str): The word to lemmatize.
features (List[str]): The morphological features as a list of Feat=Val
pairs.
index (List[str]): The POS-specific lookup list.
RETURNS (List[str]): The list of lemmas.
"""
# Initialize empty lists for the generated lemmas
possible_lemmas = []
selected_lemmas = []
# Apply lemmatization rules
for old, new in self.lookups.get_table("lemma_rules").get(rule, []):
possible_lemma = re.sub(old + "$", new, word)
if possible_lemma != word:
possible_lemmas.append(possible_lemma)
# Additional rule for plurals that go from esdrújula to grave and end in
# 'n' or 's', e.g., jóvenes -> joven
additional_lemmas = []
if "Number=Plur" in features:
for possible_lemma in possible_lemmas:
if possible_lemma.endswith("n") or possible_lemma.endswith("s"):
for old, new in self.lookups.get_table("lemma_rules").get(
"accents", []
):
additional_lemmas.append(re.sub(old, new, possible_lemma))
possible_lemmas.extend(additional_lemmas)
for lemma in possible_lemmas:
if lemma in index:
selected_lemmas.append(lemma)
# If one or more of the created possible lemmas are in the lookup list,
# return all of them
if len(selected_lemmas) > 0:
return selected_lemmas
elif len(possible_lemmas) > 0:
return possible_lemmas
else:
return [word]
def lemmatize_adv(
self, word: str, features: List[str], rule: str, index: List[str]
) -> List[str]:
"""
Lemmatize an adverb.
word (str): The word to lemmatize.
features (List[str]): The morphological features as a list of Feat=Val
pairs.
index (List[str]): The POS-specific lookup list.
RETURNS (List[str]): The list of lemmas.
"""
# Apply lemmatization rules
for old, new in self.lookups.get_table("lemma_rules").get("adverbs", []):
if word == old:
return [new]
# If none of the rules applies, return the original word
return [word]
def lemmatize_det(
self, word: str, features: List[str], rule: str, index: List[str]
) -> List[str]:
"""
Lemmatize a determiner.
word (str): The word to lemmatize.
features (List[str]): The morphological features as a list of Feat=Val
pairs.
index (List[str]): The POS-specific lookup list.
RETURNS (List[str]): The list of lemmas.
"""
# Initialize empty lists for the generated lemmas
possible_lemmas = []
selected_lemmas = []
# First, search in rules specific to determiners
for old, new in self.lookups.get_table("lemma_rules").get("det", []):
if word == old:
return [new]
# If none of the specfic rules apply, search in the common rules for
# determiners and pronouns that follow a unique pattern for
# lemmatization. If the word is in the list, return the corresponding
# lemma.
for old, new in self.lookups.get_table("lemma_rules").get(
"det_and_pron_fixed", []
):
if word == old:
return [new]
# If the word is not in the list of unique determiners and pronouns,
# apply general rules of lemmatization. Include the original word in the # list of possible lemmas.
for old, new in self.lookups.get_table("lemma_rules").get(
"det_and_pron_general", []
):
possible_lemma = re.sub(old + "$", new, word)
possible_lemmas.append(possible_lemma)
possible_lemmas.append(word)
if len(possible_lemmas) == 1:
return possible_lemmas
elif len(possible_lemmas) > 1:
for lemma in possible_lemmas:
if lemma in index:
selected_lemmas.append(lemma)
if len(selected_lemmas) >= 1:
return selected_lemmas
else:
return possible_lemmas
else:
return []
def lemmatize_noun(
self, word: str, features: List[str], rule: str, index: List[str]
) -> List[str]:
"""
Lemmatize a noun.
word (str): The word to lemmatize.
features (List[str]): The morphological features as a list of Feat=Val
pairs.
index (List[str]): The POS-specific lookup list.
RETURNS (List[str]): The list of lemmas.
"""
# Initialize empty lists for the generated lemmas
possible_lemmas = []
selected_lemmas = []
# Apply lemmatization rules
for old, new in self.lookups.get_table("lemma_rules").get(rule, []):
possible_lemma = re.sub(old + "$", new, word)
if possible_lemma != word:
possible_lemmas.append(possible_lemma)
# Additional rule for plurals that go from esdrújula to grave and end in
# 'n' or 's', e.g., órdenes -> orden, exámenes -> examen
additional_lemmas = []
if "Number=Plur" in features:
for possible_lemma in possible_lemmas:
if possible_lemma.endswith("n") or possible_lemma.endswith("s"):
for old, new in self.lookups.get_table("lemma_rules").get(
"accents", []
):
additional_lemmas.append(re.sub(old, new, possible_lemma))
possible_lemmas.extend(additional_lemmas)
for lemma in possible_lemmas:
if lemma in index:
selected_lemmas.append(lemma)
# If one or more of the created possible lemmas are in the lookup list,
# return all of them
if len(selected_lemmas) > 0:
return selected_lemmas
elif len(possible_lemmas) > 0:
return possible_lemmas
else:
return [word]
def lemmatize_num(
self, word: str, features: List[str], rule: str, index: List[str]
) -> List[str]:
"""
Lemmatize a numeral.
word (str): The word to lemmatize.
features (List[str]): The morphological features as a list of Feat=Val
pairs.
index (List[str]): The POS-specific lookup list.
RETURNS (List[str]): The list of lemmas.
"""
# If the word is in the list of rules for numerals, return the
# corresponding lemma
for old, new in self.lookups.get_table("lemma_rules").get("num", []):
if word == old:
return [new]
# Normalize punctuation
splitted_word = word.split(",")
if re.search(r"(\.)([0-9]{3})$", splitted_word[0]):
word = re.sub(r"\.", r"", word)
word = re.sub(r",", r".", word)
return [word]
def lemmatize_pron(
self, word: str, features: List[str], rule: Optional[str], index: List[str]
) -> List[str]:
"""
Lemmatize a pronoun.
word (str): The word to lemmatize.
features (List[str]): The morphological features as a list of Feat=Val
pairs.
index (List[str]): The POS-specific lookup list.
RETURNS (List[str]): The list of lemmas.
"""
# Initialize empty lists for the generated lemmas
possible_lemmas = []
selected_lemmas = []
# First, search in rules specific to pronouns
for old, new in self.lookups.get_table("lemma_rules").get("pron", []):
if word == old:
return [new]
# If none of the specfic rules apply, search in the common rules for
# determiners and pronouns that follow a unique pattern for
# lemmatization. If the word is in the list, return the corresponding
# lemma.
for old, new in self.lookups.get_table("lemma_rules").get(
"det_and_pron_fixed", []
):
if word == old:
return [new]
# If the word is not in the list of unique determiners and pronouns,
# apply general rules of lemmatization. Include the original word in the
# list of possible lemmas.
for old, new in self.lookups.get_table("lemma_rules").get(
"det_and_pron_general", []
):
possible_lemma = re.sub(old + "$", new, word)
if possible_lemma != word:
possible_lemmas.append(possible_lemma)
possible_lemmas.append(word)
if len(possible_lemmas) == 1:
return possible_lemmas
elif len(possible_lemmas) > 1:
for lemma in possible_lemmas:
if lemma in index:
selected_lemmas.append(lemma)
if len(selected_lemmas) >= 1:
return selected_lemmas
else:
return possible_lemmas
else:
return []
def lemmatize_verb(
self, word: str, features: List[str], rule: Optional[str], index: List[str]
) -> List[str]:
"""
Lemmatize a verb.
word (str): The word to lemmatize.
features (List[str]): The morphological features as a list of Feat=Val
pairs.
index (List[str]): The POS-specific lookup list.
RETURNS (List[str]): The list of lemmas.
"""
# Exceptions for verb+pronoun(s)
if "PronType=Prs" in features:
return self.lemmatize_verb_pron(word, features, rule, index)
# Initialize empty lists for the generated lemmas
possible_lemmas = []
selected_lemmas = []
# Apply lemmatization rules
rule = str(rule or "")
for old, new in self.lookups.get_table("lemma_rules").get(rule, []):
possible_lemma = re.sub(old + "$", new, word)
if possible_lemma != word:
possible_lemmas.append(possible_lemma)
for lemma in possible_lemmas:
if lemma in index:
selected_lemmas.append(lemma)
if len(selected_lemmas) == 0:
# If none of the possible lemmas are in the lookup list,
# apply vocalic alternation rules and search in the lookup list
# again
for lemma in possible_lemmas:
for old, new in self.lookups.get_table("lemma_rules").get(
"voc_alt_1", []
):
if old in lemma:
for i, char in enumerate(lemma):
if char == old:
voc_alt_lemma = lemma[:i] + new + lemma[i + 1 :]
if voc_alt_lemma in index:
selected_lemmas.append(voc_alt_lemma)
for old, new in self.lookups.get_table("lemma_rules").get(
"voc_alt_2", []
):
if old in lemma:
voc_alt_lemma = lemma.replace(old, new, 1)
if voc_alt_lemma in index:
selected_lemmas.append(voc_alt_lemma)
# Additional rule for verbs that lose the accent mark when lemmatized,
# e.g., amplían -> ampliar
additional_lemmas = []
for possible_lemma in possible_lemmas:
for old, new in self.lookups.get_table("lemma_rules").get("accents", []):
additional_lemmas.append(re.sub(old, new, possible_lemma))
possible_lemmas.extend(additional_lemmas)
# If one or more of the created possible lemmas are in the lookup list,
# return all of them
if len(selected_lemmas) > 0:
return selected_lemmas
elif len(possible_lemmas) > 0:
return possible_lemmas
else:
return [word]
def lemmatize_verb_pron(
self, word: str, features: List[str], rule: Optional[str], index: List[str]
) -> List[str]:
# Strip and collect pronouns
pron_patt = "^(.*?)([mts]e|l[aeo]s?|n?os)$"
prons: List[str] = []
verb = word
m = re.search(pron_patt, verb)
while m is not None and len(prons) <= 3:
verb = re.sub(m.group(2) + "$", "", verb)
prons = [m.group(2)] + prons
m = re.search(pron_patt, verb)
# Strip accents from verb form
for old, new in self.lookups.get_table("lemma_rules").get("accents", []):
verb = re.sub(old, new, verb)
# Lemmatize the verb and pronouns, checking for exceptions
exc = self.lookups.get_table("lemma_exc").get("verb", {}).get(verb)
if exc is not None:
verb_lemma = exc[0]
else:
rule = self.select_rule("verb", features)
verb_lemma = self.lemmatize_verb(
verb, features - {"PronType=Prs"}, rule, index # type: ignore[operator]
)[0]
pron_lemmas = []
for pron in prons:
exc = self.lookups.get_table("lemma_exc").get("pron", {}).get(pron)
if exc is not None:
pron_lemmas.append(exc[0])
else:
rule = self.select_rule("pron", features)
pron_lemmas.append(self.lemmatize_pron(pron, features, rule, index)[0])
return [verb_lemma + " " + " ".join(pron_lemmas)]