Source code for pie_extended.spec

""" Small helpers that PaPie provides, kept here so that importing `pie_extended` does not need PaPie (0.x or 1.0).
They behave as the ones of PaPie (`pie.utils`), whose syntax is the one of the models of `--model_path`.
"""
import os
from typing import Iterable, Iterator, List, Optional, Tuple

import regex as re


[docs] def model_spec(inp: str) -> List[Tuple[str, List[str]]]: """ Reads `<file,task,...><file,task>`: the models and what each one gives >>> model_spec('model-pos-2018:03:05.tar') [('model-pos-2018:03:05.tar', [])] >>> model_spec('<model-pos-2018:03:05.tar,pos><model-pos-2018:03:05.tar,lemma>') [('model-pos-2018:03:05.tar', ['pos']), ('model-pos-2018:03:05.tar', ['lemma'])] """ if not inp.startswith("<"): return [(inp, [])] output = [] for string in re.findall(r"<([^>]+)>", inp): model_path, *tasks = string.split(",") output.append((model_path, tasks)) return output
[docs] def chunks(it: Iterable, size: int) -> Iterator[list]: """ Cuts an iterable in lists of `size` (the last one may be smaller) >>> list(chunks(range(5), 2)) [[0, 1], [2, 3], [4]] """ buf = [] for item in it: buf.append(item) if len(buf) == size: yield buf buf = [] if buf: yield buf
[docs] def ensure_ext(path: str, ext: str, infix: Optional[str] = None) -> str: """ Path with an infix and an extension >>> ensure_ext("model.test", "test", infix="pie") 'model-pie.test' >>> ensure_ext("model.test", "pt", infix="0.87") 'model-0.87.test.pt' """ path, oldext = os.path.splitext(path) ext = ext[1:] if ext.startswith(".") else ext oldext = oldext[1:] if oldext.startswith(".") else oldext if infix is not None: path = "-".join([path, infix]) if oldext and oldext != ext: path = ".".join([path, oldext]) return ".".join([path, ext])
[docs] def regexsplitter(regex: str): """ Function that cuts a text at a regular expression, and gives the non-empty stripped parts """ def func(line): for part in re.split(regex, line): part = part.strip() if part: yield part return func
SECTION = r"([A-Z\. ]+\.)" FULLSTOP = r"([^\.]+\.)"