""" Tagging with a model of PaPie 1.0 (https://github.com/DEFI-COLaF/pie-thunder), from the Hugging Face Hub.
PaPie 1.0 is Pie under PyTorch-Lightning (it was developed as pie-thunder), and it imports as `papie`. Its models are plain
files (no pickle, they are safe to download), several can live in one repository (the *variants*), and it is imported only
when the model is loaded: `pip install "pie-extended[papie]"`. It replaces PaPie 0.x (`import pie`, extra `pie`): the two
cannot be installed together, as they are the same package of PyPI.
A model is named `papie:REPOSITORY#VARIANT@REVISION` (the variant and the revision, a commit, are optional):
>>> parse("papie:biblissima-textes/papie-latin#morph@4a5b6c7")
('biblissima-textes/papie-latin', 'morph', '4a5b6c7')
>>> parse("papie:biblissima-textes/papie-french")
('biblissima-textes/papie-french', None, None)
"""
from typing import List, Optional, Sequence, Tuple
PAPIE = "papie:"
[docs]
def parse(name: str) -> Tuple[str, Optional[str], Optional[str]]:
""" The repository, the variant and the revision of a name of model """
if name.startswith(PAPIE):
name = name[len(PAPIE):]
name, _, revision = name.partition("@")
repo, _, variant = name.partition("#")
if not repo:
raise ValueError("A PaPie 1.0 model needs a repository: papie:ORGANISATION/NAME[#VARIANT][@REVISION]")
return repo, variant or None, revision or None
[docs]
class PapieTagger:
""" An engine of the `CompositeTagger`: the heads of a model of PaPie 1.0 (`lemma`, `pos`, and the morphology for some)
:param tasks: What is given back (all the tasks of the model by default)
:param quantize: INT8 on CPU (about 1.5 times faster, same accuracy according to PaPie)
"""
def __init__(self, repo: str, variant: Optional[str] = None, revision: Optional[str] = None,
tasks: Optional[Sequence[str]] = None, device: str = "cpu", batch_size: int = 64,
quantize: bool = True, num_threads: Optional[int] = None):
self.repo, self.variant, self.revision = repo, variant, revision
self.device = device
self.batch_size = batch_size
self.quantize = quantize and device == "cpu"
self.num_threads = num_threads
self.requested: Optional[List[str]] = list(tasks) if tasks else None
self.annotator = None
self.tasks: List[str] = []
self._source = {}
[docs]
def load(self) -> "PapieTagger":
""" Loads the model: it is downloaded the first time (only the files of the variant) """
try:
from papie.hub import from_pretrained
except ImportError as error:
raise ImportError("PaPie 1.0 is needed for this model: pip install \"pie-extended[papie]\"") from error
if self.num_threads is not None:
import torch
torch.set_num_threads(self.num_threads)
if self.variant and self.variant.endswith("/*"): # a pack: one network for each task
from papie.hub import from_pretrained_pack
self.annotator = from_pretrained_pack(self.repo, self.variant[:-2], revision=self.revision, device=self.device)
else:
self.annotator = from_pretrained(self.repo, variant=self.variant, revision=self.revision, device=self.device)
if self.quantize:
self.annotator.quantize()
available = list(self.annotator.tasks)
# The names of the tasks are the ones of the model of the package (`POS`), the case does not matter
lookup = {name.lower(): name for name in available}
self.tasks = self.requested or available
unknown = [task for task in self.tasks if task.lower() not in lookup]
if unknown:
raise ValueError("The model {} gives {}, not {}".format(self.repo, ", ".join(available), ", ".join(unknown)))
self._source = {task: lookup[task.lower()] for task in self.tasks}
self.annotator.only(*self._source.values()) # the other heads are not run
return self
[docs]
def tag(self, sents: Sequence[Sequence[str]], lengths: Optional[Sequence[int]] = None, **kwargs
) -> Tuple[List[List[Tuple[str, Tuple[str, ...]]]], List[str]]:
""" Same contract as the taggers: tagged sentences ([(token, (a value for each task))]) and the tasks """
if self.annotator is None:
self.load()
answers = self.annotator.annotate([list(sentence) for sentence in sents], batch_size=self.batch_size)
return [
[(token, tuple(annotation[self._source[task]] for task in self.tasks)) for token, annotation in zip(sentence, answer)]
for sentence, answer in zip(sents, answers)
], list(self.tasks)
[docs]
def papie_models(repo: str, variant: Optional[str], tasks: Sequence[str], revision: Optional[str] = None) -> str:
""" The `Models` of a package that runs a model of PaPie 1.0: `<papie:REPO#VARIANT,task,...>`. A variant that ends
with `/*` is a *pack*: all the networks of a repository whose names start with it (one for each task)
>>> papie_models("org/repo", "morph", ["lemma", "pos"])
'<papie:org/repo#morph,lemma,pos>'
>>> papie_models("org/repo", "morph", ["lemma"], "abc")
'<papie:org/repo#morph@abc,lemma>'
"""
return "<{}{}{}{},{}>".format(PAPIE, repo, "#" + variant if variant else "", "@" + revision if revision else "",
",".join(tasks))