2020-07-22 11:42:59 +00:00
|
|
|
from typing import List, Dict, Iterable, Optional, Union, TYPE_CHECKING
|
2019-10-27 12:35:49 +00:00
|
|
|
from wasabi import Printer
|
2020-02-28 11:20:23 +00:00
|
|
|
import warnings
|
2019-10-27 12:35:49 +00:00
|
|
|
|
2019-10-30 16:19:36 +00:00
|
|
|
from .tokens import Doc, Token, Span
|
2020-02-28 11:20:23 +00:00
|
|
|
from .errors import Errors, Warnings
|
2020-07-22 11:42:59 +00:00
|
|
|
from .util import dot_to_dict
|
2019-10-27 12:35:49 +00:00
|
|
|
|
2020-07-22 11:42:59 +00:00
|
|
|
if TYPE_CHECKING:
|
|
|
|
# This lets us add type hints for mypy etc. without causing circular imports
|
|
|
|
from .language import Language # noqa: F401
|
2019-10-27 12:35:49 +00:00
|
|
|
|
2020-07-22 11:42:59 +00:00
|
|
|
|
|
|
|
def analyze_pipes(
|
|
|
|
nlp: "Language", name: str, index: int, warn: bool = True
|
|
|
|
) -> List[str]:
|
2019-10-27 12:35:49 +00:00
|
|
|
"""Analyze a pipeline component with respect to its position in the current
|
|
|
|
pipeline and the other components. Will check whether requirements are
|
|
|
|
fulfilled (e.g. if previous components assign the attributes).
|
|
|
|
|
2020-07-22 11:42:59 +00:00
|
|
|
nlp (Language): The current nlp object.
|
2020-05-24 15:20:58 +00:00
|
|
|
name (str): The name of the pipeline component to analyze.
|
2019-10-27 12:35:49 +00:00
|
|
|
index (int): The index of the component in the pipeline.
|
|
|
|
warn (bool): Show user warning if problem is found.
|
2020-07-22 11:42:59 +00:00
|
|
|
RETURNS (List[str]): The problems found for the given pipeline component.
|
2019-10-27 12:35:49 +00:00
|
|
|
"""
|
2020-07-22 11:42:59 +00:00
|
|
|
assert nlp.pipeline[index][0] == name
|
|
|
|
prev_pipes = nlp.pipeline[:index]
|
|
|
|
meta = nlp.get_pipe_meta(name)
|
|
|
|
requires = {annot: False for annot in meta.requires}
|
2019-10-27 12:35:49 +00:00
|
|
|
if requires:
|
|
|
|
for prev_name, prev_pipe in prev_pipes:
|
2020-07-22 11:42:59 +00:00
|
|
|
prev_meta = nlp.get_pipe_meta(prev_name)
|
|
|
|
for annot in prev_meta.assigns:
|
2019-10-27 12:35:49 +00:00
|
|
|
requires[annot] = True
|
|
|
|
problems = []
|
|
|
|
for annot, fulfilled in requires.items():
|
|
|
|
if not fulfilled:
|
|
|
|
problems.append(annot)
|
|
|
|
if warn:
|
2020-02-28 11:20:23 +00:00
|
|
|
warnings.warn(Warnings.W025.format(name=name, attr=annot))
|
2019-10-27 12:35:49 +00:00
|
|
|
return problems
|
|
|
|
|
|
|
|
|
2020-07-22 11:42:59 +00:00
|
|
|
def validate_attrs(values: Iterable[str]) -> Iterable[str]:
|
2019-10-27 12:35:49 +00:00
|
|
|
"""Validate component attributes provided to "assigns", "requires" etc.
|
|
|
|
Raises error for invalid attributes and formatting. Doesn't check if
|
|
|
|
custom extension attributes are registered, since this is something the
|
|
|
|
user might want to do themselves later in the component.
|
|
|
|
|
2020-07-22 11:42:59 +00:00
|
|
|
values (Iterable[str]): The string attributes to check, e.g. `["token.pos"]`.
|
|
|
|
RETURNS (Iterable[str]): The checked attributes.
|
2019-10-27 12:35:49 +00:00
|
|
|
"""
|
2020-07-22 11:42:59 +00:00
|
|
|
data = dot_to_dict({value: True for value in values})
|
2019-10-30 16:19:36 +00:00
|
|
|
objs = {"doc": Doc, "token": Token, "span": Span}
|
2019-10-27 12:35:49 +00:00
|
|
|
for obj_key, attrs in data.items():
|
2019-10-30 16:19:36 +00:00
|
|
|
if obj_key == "span":
|
|
|
|
# Support Span only for custom extension attributes
|
|
|
|
span_attrs = [attr for attr in values if attr.startswith("span.")]
|
|
|
|
span_attrs = [attr for attr in span_attrs if not attr.startswith("span._.")]
|
|
|
|
if span_attrs:
|
2019-10-27 12:35:49 +00:00
|
|
|
raise ValueError(Errors.E180.format(attrs=", ".join(span_attrs)))
|
2019-10-30 16:19:36 +00:00
|
|
|
if obj_key not in objs: # first element is not doc/token/span
|
2019-10-27 12:35:49 +00:00
|
|
|
invalid_attrs = ", ".join(a for a in values if a.startswith(obj_key))
|
|
|
|
raise ValueError(Errors.E181.format(obj=obj_key, attrs=invalid_attrs))
|
|
|
|
if not isinstance(attrs, dict): # attr is something like "doc"
|
|
|
|
raise ValueError(Errors.E182.format(attr=obj_key))
|
|
|
|
for attr, value in attrs.items():
|
|
|
|
if attr == "_":
|
|
|
|
if value is True: # attr is something like "doc._"
|
|
|
|
raise ValueError(Errors.E182.format(attr="{}._".format(obj_key)))
|
|
|
|
for ext_attr, ext_value in value.items():
|
|
|
|
# We don't check whether the attribute actually exists
|
|
|
|
if ext_value is not True: # attr is something like doc._.x.y
|
2019-12-22 00:53:56 +00:00
|
|
|
good = f"{obj_key}._.{ext_attr}"
|
|
|
|
bad = f"{good}.{'.'.join(ext_value)}"
|
2019-10-27 12:35:49 +00:00
|
|
|
raise ValueError(Errors.E183.format(attr=bad, solution=good))
|
|
|
|
continue # we can't validate those further
|
|
|
|
if attr.endswith("_"): # attr is something like "token.pos_"
|
|
|
|
raise ValueError(Errors.E184.format(attr=attr, solution=attr[:-1]))
|
|
|
|
if value is not True: # attr is something like doc.x.y
|
2019-12-22 00:53:56 +00:00
|
|
|
good = f"{obj_key}.{attr}"
|
|
|
|
bad = f"{good}.{'.'.join(value)}"
|
2019-10-27 12:35:49 +00:00
|
|
|
raise ValueError(Errors.E183.format(attr=bad, solution=good))
|
|
|
|
obj = objs[obj_key]
|
|
|
|
if not hasattr(obj, attr):
|
|
|
|
raise ValueError(Errors.E185.format(obj=obj_key, attr=attr))
|
|
|
|
return values
|
|
|
|
|
|
|
|
|
2020-07-22 11:42:59 +00:00
|
|
|
def _get_feature_for_attr(nlp: "Language", attr: str, feature: str) -> List[str]:
|
2019-10-27 12:35:49 +00:00
|
|
|
assert feature in ["assigns", "requires"]
|
|
|
|
result = []
|
2020-07-22 11:42:59 +00:00
|
|
|
for pipe_name in nlp.pipe_names:
|
|
|
|
meta = nlp.get_pipe_meta(pipe_name)
|
|
|
|
pipe_assigns = getattr(meta, feature, [])
|
2019-10-27 12:35:49 +00:00
|
|
|
if attr in pipe_assigns:
|
2020-07-22 11:42:59 +00:00
|
|
|
result.append(pipe_name)
|
2019-10-27 12:35:49 +00:00
|
|
|
return result
|
|
|
|
|
|
|
|
|
2020-07-22 11:42:59 +00:00
|
|
|
def get_assigns_for_attr(nlp: "Language", attr: str) -> List[str]:
|
2019-10-27 12:35:49 +00:00
|
|
|
"""Get all pipeline components that assign an attr, e.g. "doc.tensor".
|
|
|
|
|
2020-07-22 11:42:59 +00:00
|
|
|
pipeline (Language): The current nlp object.
|
2020-05-24 15:20:58 +00:00
|
|
|
attr (str): The attribute to check.
|
2020-07-22 11:42:59 +00:00
|
|
|
RETURNS (List[str]): Names of components that require the attr.
|
2019-10-27 12:35:49 +00:00
|
|
|
"""
|
2020-07-22 11:42:59 +00:00
|
|
|
return _get_feature_for_attr(nlp, attr, "assigns")
|
2019-10-27 12:35:49 +00:00
|
|
|
|
|
|
|
|
2020-07-22 11:42:59 +00:00
|
|
|
def get_requires_for_attr(nlp: "Language", attr: str) -> List[str]:
|
2019-10-27 12:35:49 +00:00
|
|
|
"""Get all pipeline components that require an attr, e.g. "doc.tensor".
|
|
|
|
|
2020-07-22 11:42:59 +00:00
|
|
|
pipeline (Language): The current nlp object.
|
2020-05-24 15:20:58 +00:00
|
|
|
attr (str): The attribute to check.
|
2020-07-22 11:42:59 +00:00
|
|
|
RETURNS (List[str]): Names of components that require the attr.
|
2019-10-27 12:35:49 +00:00
|
|
|
"""
|
2020-07-22 11:42:59 +00:00
|
|
|
return _get_feature_for_attr(nlp, attr, "requires")
|
2019-10-27 12:35:49 +00:00
|
|
|
|
|
|
|
|
2020-07-22 11:42:59 +00:00
|
|
|
def print_summary(
|
2020-07-31 16:34:35 +00:00
|
|
|
nlp: "Language",
|
|
|
|
*,
|
|
|
|
keys: List[str] = ["requires", "assigns", "scores", "retokenizes"],
|
|
|
|
pretty: bool = True,
|
|
|
|
no_print: bool = False,
|
2020-07-22 11:42:59 +00:00
|
|
|
) -> Optional[Dict[str, Union[List[str], Dict[str, List[str]]]]]:
|
2019-10-27 12:35:49 +00:00
|
|
|
"""Print a formatted summary for the current nlp object's pipeline. Shows
|
|
|
|
a table with the pipeline components and why they assign and require, as
|
|
|
|
well as any problems if available.
|
|
|
|
|
|
|
|
nlp (Language): The nlp object.
|
2020-07-31 16:34:35 +00:00
|
|
|
keys (List[str]): The meta keys to show in the table.
|
2019-10-27 12:35:49 +00:00
|
|
|
pretty (bool): Pretty-print the results (color etc).
|
|
|
|
no_print (bool): Don't print anything, just return the data.
|
|
|
|
RETURNS (dict): A dict with "overview" and "problems".
|
|
|
|
"""
|
|
|
|
msg = Printer(pretty=pretty, no_print=no_print)
|
2020-07-31 16:34:35 +00:00
|
|
|
overview = {}
|
2019-10-27 12:35:49 +00:00
|
|
|
problems = {}
|
2020-07-22 11:42:59 +00:00
|
|
|
for i, name in enumerate(nlp.pipe_names):
|
|
|
|
meta = nlp.get_pipe_meta(name)
|
2020-07-31 16:34:35 +00:00
|
|
|
overview[name] = {"i": i, "name": name}
|
|
|
|
for key in keys:
|
|
|
|
overview[name][key] = getattr(meta, key, None)
|
2020-07-22 11:42:59 +00:00
|
|
|
problems[name] = analyze_pipes(nlp, name, i, warn=False)
|
2019-10-27 12:35:49 +00:00
|
|
|
msg.divider("Pipeline Overview")
|
2020-07-31 16:34:35 +00:00
|
|
|
header = ["#", "Component", *[key.capitalize() for key in keys]]
|
|
|
|
body = [[info for info in entry.values()] for entry in overview.values()]
|
|
|
|
msg.table(body, header=header, divider=True, multiline=True)
|
2019-10-27 12:35:49 +00:00
|
|
|
n_problems = sum(len(p) for p in problems.values())
|
|
|
|
if any(p for p in problems.values()):
|
2019-12-22 00:53:56 +00:00
|
|
|
msg.divider(f"Problems ({n_problems})")
|
2019-10-27 12:35:49 +00:00
|
|
|
for name, problem in problems.items():
|
|
|
|
if problem:
|
2019-12-22 00:53:56 +00:00
|
|
|
msg.warn(f"'{name}' requirements not met: {', '.join(problem)}")
|
2019-10-27 12:35:49 +00:00
|
|
|
else:
|
|
|
|
msg.good("No problems found.")
|
|
|
|
if no_print:
|
|
|
|
return {"overview": overview, "problems": problems}
|
2020-05-22 14:43:18 +00:00
|
|
|
|
|
|
|
|
2020-07-22 11:42:59 +00:00
|
|
|
def count_pipeline_interdependencies(nlp: "Language") -> List[int]:
|
2020-05-22 14:43:18 +00:00
|
|
|
"""Count how many subsequent components require an annotation set by each
|
|
|
|
component in the pipeline.
|
2020-07-22 11:42:59 +00:00
|
|
|
|
|
|
|
nlp (Language): The current nlp object.
|
|
|
|
RETURNS (List[int]): The interdependency counts.
|
2020-05-22 14:43:18 +00:00
|
|
|
"""
|
|
|
|
pipe_assigns = []
|
|
|
|
pipe_requires = []
|
2020-07-22 11:42:59 +00:00
|
|
|
for name in nlp.pipe_names:
|
|
|
|
meta = nlp.get_pipe_meta(name)
|
|
|
|
pipe_assigns.append(set(meta.assigns))
|
|
|
|
pipe_requires.append(set(meta.requires))
|
2020-05-22 14:43:18 +00:00
|
|
|
counts = []
|
|
|
|
for i, assigns in enumerate(pipe_assigns):
|
|
|
|
count = 0
|
2020-05-22 15:42:06 +00:00
|
|
|
for requires in pipe_requires[i + 1 :]:
|
2020-05-22 14:43:18 +00:00
|
|
|
if assigns.intersection(requires):
|
|
|
|
count += 1
|
|
|
|
counts.append(count)
|
|
|
|
return counts
|