import os
import sys
from typing import Tuple, Iterable, List, Union, Optional
import requests
from .. import models
from ..utils import Metadata, PATH, get_path
from ..tagger import ExtensibleTagger
from ..backends import BACKENDS
from ..composite_tagger import ENGINE_PREFIXES
from ..papie import PAPIE
from ..wrappers import resolve
from ..utils import ObjectCreator
from ..pipeline.postprocessor.proto import SelectTasksProcessor
from ..pipeline.postprocessor.spacing import SpaceAfterProcessor
from ..spec import model_spec
[docs]
def get_model(model: str):
""" Retrieve a module given a string
:param model: Module Name
:return: Module
"""
package, generic = resolve(model)
if generic is not None:
return generic
return models.BY_NAME[package]
[docs]
def get_imports(module):
""" The processes of a model: `get_iterator_and_processor`, `Disambiguator`, `DISAMBIGUATION_TASKS`, `addons` """
return module.IMPORTS
# Seconds to wait for the server (connection, then between two chunks of data)
DOWNLOAD_TIMEOUT = 60
def _download(url, filename):
""" Download `url` into `filename`.
The data is written in a temporary file that replaces `filename` only once complete, so that a failure
(HTTP error, network issue, interruption) never leaves a corrupted file that would be taken for a model.
:raises requests.HTTPError: If the server answers with an error status
"""
temporary = filename + ".part"
try:
with requests.get(url, stream=True, timeout=DOWNLOAD_TIMEOUT) as response:
response.raise_for_status()
total = response.headers.get('content-length')
with open(temporary, 'wb') as f:
if total is None:
f.write(response.content)
else:
downloaded = 0
total = int(total)
for data in response.iter_content(chunk_size=max(int(total/1000), 1024*1024)):
downloaded += len(data)
f.write(data)
done = int(50*downloaded/total)
sys.stdout.write('\r[{}{}]'.format('█' * done, '.' * (50-done)))
sys.stdout.flush()
os.replace(temporary, filename)
finally:
if os.path.exists(temporary):
os.remove(temporary)
sys.stdout.write('\n')
[docs]
class FilesNotDownloaded(FileNotFoundError):
""" A model needs files besides its model of Hugging Face (the lexicons of Latin...) that were not downloaded """
[docs]
def missing_files(model) -> List:
""" The files of a model (`DOWNLOADS`) that are not on the disk """
package = getattr(model, "name", None)
return [file for file in model.DOWNLOADS if not os.path.exists(get_path(package, file.name))]
[docs]
def ensure_files(model: str, echo=None) -> List[str]:
""" Downloads the files of a model that are not on the disk yet (the ones that `pie-extended download` fetches, without
the model of Hugging Face, that is downloaded when it is first used)
:param echo: Called with a message for each file that is downloaded
:return: The names of the files that were downloaded
:raises requests.RequestException: If a download fails
"""
module = get_model(model)
done = []
for file in missing_files(module):
if echo:
echo("Downloading {} (needed by {})".format(file.name, module.name))
os.makedirs(os.path.join(PATH, module.name), exist_ok=True)
_download(file.url, get_path(module.name, file.name))
done.append(file.name)
return done
[docs]
def download_papie(module: str) -> Iterable[str]:
""" Fetches the models of PaPie 1.0 of a module from Hugging Face (only the files of the variant: no pickle) """
from ..papie import parse
spec = getattr(get_model(module), "Models", "")
repos = [parse(path) for path, _ in model_spec(spec) if path.startswith(PAPIE)]
from huggingface_hub import snapshot_download
for repo, variant, revision in repos:
patterns = None
if variant:
patterns = ["papie.json", "pie_thunder.json", variant if variant.endswith("/*") else variant + "/*"]
snapshot_download(repo, revision=revision, allow_patterns=patterns)
yield "{}{}".format(repo, "#" + variant if variant else "")
[docs]
def download(module: str) -> Iterable[Union[str, int]]:
""" Download dependencies for the given module: its files, and its models of PaPie 1.0 (from Hugging Face)
:param module: Module for which to download models and static files in general
"""
lemmatizer = get_model(module)
package = getattr(lemmatizer, "name", module) # `module` may be a model of Hugging Face that a model of the table wraps
if lemmatizer.DOWNLOADS:
os.makedirs(os.path.join(PATH, package), exist_ok=True)
papie_models = [path for path, _ in model_spec(getattr(lemmatizer, "Models", "")) if path.startswith(PAPIE)]
yield len(lemmatizer.DOWNLOADS) + len(papie_models)
for file in lemmatizer.DOWNLOADS:
new_path = get_path(package, file.name)
_download(file.url, new_path)
yield file.name
if papie_models:
yield from download_papie(module)
[docs]
def get_list() -> Iterable[Tuple[str, Metadata]]:
""" Retrieve a list of available modules
"""
for module in models.modules:
desc = getattr(get_model(module), "DESC", None)
if desc:
yield module, desc
[docs]
def all_but(model: str, disabled: Iterable[str], spec: List[Tuple[str, List[str]]]) -> List[str]:
""" The output columns of a model, but the disabled ones (case insensitive)
:raises ValueError: If a column does not exist for this model, or if none would be left
"""
probe = get_imports(get_model(model)).get_iterator_and_processor()[1]
outputs = list(probe.set_tasks(sorted({task for _, tasks in spec for task in tasks})))
lookup = {name.lower(): name for name in outputs}
unknown = [name for name in disabled if name.strip().lower() not in lookup]
if unknown:
raise ValueError("Unknown task(s) {} for {}. Available: {}".format(", ".join(unknown), model, ", ".join(outputs)))
off = {name.strip().lower() for name in disabled}
kept = [name for name in outputs if name.lower() not in off]
if not kept:
raise ValueError("Cannot disable every task of {} ({})".format(model, ", ".join(outputs)))
return kept
[docs]
def resolve_tasks(model: str, requested: Iterable[str], spec: List[Tuple[str, List[str]]]
) -> Tuple[List[str], List[Tuple[str, List[str]]]]:
""" Finds out which models/tasks need to be run to produce the requested output columns
:param model: Module name of the language
:param requested: Output columns wanted (case insensitive), e.g. ["lemma", "POS"]
:param spec: Parsed model specification [(path, [tasks])]
:return: Canonical output columns and the reduced model specification. Models for which no task
is needed are dropped, so that they are neither loaded nor run.
:raises ValueError: If a requested column does not exist for this language
"""
imports = get_imports(get_model(model))
available = sorted({task for _, tasks in spec for task in tasks})
# What the processor would output when everything is tagged
probe = imports.get_iterator_and_processor()[1]
outputs = list(probe.set_tasks(available))
lookup = {name.lower(): name for name in outputs}
selected, unknown = [], []
for name in requested:
found = lookup.get(name.strip().lower())
if found is None:
unknown.append(name)
elif found not in selected:
selected.append(found)
if unknown:
raise ValueError("Unknown task(s) {} for {}. Available: {}".format(
", ".join(unknown), model, ", ".join(outputs)))
needed = set(probe.required_tasks(selected, available))
# The disambiguation modifies the lemma: it is only worth its (costly) tasks if the lemma is wanted
if "lemma" in [s.lower() for s in selected]:
needed.update(getattr(imports, "DISAMBIGUATION_TASKS", ()))
reduced = []
for path, tasks in spec:
kept = [task for task in tasks if task in needed]
if kept:
reduced.append((path, kept))
return selected, reduced
[docs]
def get_tagger(model: str, batch_size: int = 16, device="cpu", model_path=None,
quantize: bool = True, cache: bool = True, tasks: Optional[Iterable[str]] = None,
cache_size: Optional[int] = None, num_threads: Optional[int] = None,
disable: Optional[Iterable[str]] = None) -> ExtensibleTagger:
""" Retrieve the tagger
:param model: Module of the tagger
:param batch_size: Size of the batch
:param device: Device to use (cuda/cpu)
:param model_path: The model to run instead of the one of the package: files and tasks
(`"<lemma.tar,lemma><pos.tar,pos>"`), or, for a model that runs a spaCy pipeline, just the name of the
pipeline (`"grc_proiel_sm"`): it gives the tasks of the model
:param quantize: Use Int8 quantization (cpu only)
:param cache: Use cache
:param tasks: The output columns you want (e.g. ["lemma", "POS"]): the models, or the tasks, that are not needed
for them are not loaded. None means everything. This is not the same as the tasks given to `add_model` or to
the constructor of a tagger (what a model computes): from the columns, `get_tagger` works out what has to be
computed, and keeps the columns in `tagger.selected_outputs` for `get_pipeline`.
:param disable: The output columns you do not want: all the others are kept. The inverse of `tasks`, and the same
rules apply (what is not needed is not loaded or run). Not with `tasks`
:param cache_size: Size of the embedding cache
:param num_threads: Number of torch threads
:return: Tagger
"""
module = get_model(model)
missing = missing_files(module)
if missing:
raise FilesNotDownloaded("{} needs files that are not downloaded ({}): run `pie-extended download {}`".format(
module.name, ", ".join(file.name for file in missing), module.name))
if model_path and "<" not in model_path and getattr(module, "Backend", "composite") in ("spacy", "composite"):
# Only the name of a spaCy pipeline: it has to give what the model gives
model_tasks = [task for _, tasks_of_model in model_spec(module.Models) for task in tasks_of_model]
model_path = "<{},{}>".format(model_path, ",".join(model_tasks))
spec = list(model_spec(model_path or getattr(module, "Models")))
selected = None
if disable:
if tasks:
raise ValueError("`tasks` and `disable` cannot be used together")
tasks = all_but(model, disable, spec)
if tasks:
selected, spec = resolve_tasks(model, tasks, spec)
disambiguator = getattr(get_imports(module), "Disambiguator", None)
if isinstance(disambiguator, ObjectCreator):
disambiguator = disambiguator.create()
backend = getattr(module, "Backend", "composite")
if backend not in BACKENDS:
raise ValueError("Unknown Backend {!r} for the model {}. Available: {}".format(
backend, model, ", ".join(sorted(BACKENDS))))
if any(path.startswith(ENGINE_PREFIXES) for path, _ in spec) or (backend == "spacy" and len(spec) > 1):
backend = "composite" # The tasks come from several engines (PaPie 1.0, a lemmatizer, a spaCy pipeline...)
tagger_class = BACKENDS[backend]
tagger = tagger_class(disambiguation=disambiguator, batch_size=batch_size, device=device,
quantize=quantize, cache=cache, cache_size=cache_size, num_threads=num_threads)
for path, model_tasks in spec:
tagger.add_model(path, *model_tasks)
# Output columns to keep when writing (hidden dependencies such as lemma for clitic splitting are dropped)
tagger.selected_outputs = selected
return tagger
[docs]
def get_pipeline(
model: str, tagger: ExtensibleTagger,
reset_exclude_patterns: bool = False,
exclude_patterns: Optional[Iterable[str]] = None,
max_tokens: int = 256,
space_after: bool = True):
""" Builds the (iterator, processor) couple for a model, ready to be reused over several files
This is the *processing* pipeline of Pie Extended (tokenization, then the columns of the output), that is
the same whatever the model it is used with: not a spaCy pipeline. The columns are those that were asked for
when the tagger was made (`tagger.selected_outputs`, see `get_tagger(tasks=...)`).
Reuse is safe because `ExtensibleTagger.iter_tag_token` resets the processor chain and the tokenizer
before each document (memory of the tokenizer, cursor of the memorizing processor, ...).
:param model: Module name of the model
:param tagger: Tagger that will be used (gives the subset of outputs, if any)
:param reset_exclude_patterns: Remove all pre-registered token exclusion regular expressions
:param exclude_patterns: New exclude patterns to add to the data iterator (Does not require reset)
:param max_tokens: Maximum sentence length
:param space_after: Add a `SpaceAfter` column (`No` when the next token is glued to the token, `_` otherwise)
"""
module = get_model(model)
iterator, processor = getattr(get_imports(module), "get_iterator_and_processor")(max_tokens=max_tokens)
selected = getattr(tagger, "selected_outputs", None)
if selected:
processor = SelectTasksProcessor(processor, selected)
if space_after:
# Outermost: it must be called once per input token
processor = SpaceAfterProcessor(processor)
# Remove first pattern
if reset_exclude_patterns:
iterator.reset_patterns()
# Add new
for pattern in exclude_patterns or []:
iterator.add_pattern(pattern)
return iterator, processor
[docs]
def tag_file(
model: str, tagger: ExtensibleTagger,
fpath: str,
reset_exclude_patterns: bool = False,
exclude_patterns: List[str] = None,
no_tokenizer: bool = False,
max_tokens: int = 256,
pipeline: Optional[Tuple] = None,
space_after: bool = True):
""" Tag a file with a given model
:param model: Module name of the model
:param tagger: Tagger that should be used
:param fpath: Path to the file to edit
:param reset_exclude_patterns: Remove all pre-registered token exclusion regular expressions
:param exclude_patterns: New exclude patterns to add to the data iterator (Does not require reset)
:param no_tokenizer: Does not use usual tokenizers (new line = word separator, two new lines = sentence)
:param pipeline: (iterator, processor) built by `get_pipeline` to reuse over several files. When given,
`reset_exclude_patterns`, `exclude_patterns`, `max_tokens` and `space_after` were applied at its creation
and are ignored here.
:param space_after: Add a `SpaceAfter` column (ignored if a pipeline is given)
"""
if pipeline is None:
pipeline = get_pipeline(model, tagger, reset_exclude_patterns=reset_exclude_patterns,
exclude_patterns=exclude_patterns, max_tokens=max_tokens,
space_after=space_after)
iterator, processor = pipeline
tagger.tag_file(fpath, iterator=iterator, processor=processor, no_tokenizer=no_tokenizer)
return True
[docs]
def get_addons(model: str):
""" Runs the `addons` function from a module """
module = get_model(model)
addons = getattr(get_imports(module), "addons", None)
if addons is None:
print("No add-ons needed for " + model)
return True
return addons()