pie-extended 0.1.4__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pie_extended/__init__.py +0 -0
- pie_extended/__main__.py +4 -0
- pie_extended/cli/__init__.py +0 -0
- pie_extended/cli/main.py +122 -0
- pie_extended/cli/utils.py +138 -0
- pie_extended/models/__init__.py +10 -0
- pie_extended/models/dum/__init__.py +21 -0
- pie_extended/models/dum/imports.py +14 -0
- pie_extended/models/fr/__init__.py +32 -0
- pie_extended/models/fr/excluders.py +127 -0
- pie_extended/models/fr/imports.py +22 -0
- pie_extended/models/fr/processor.py +40 -0
- pie_extended/models/fr/tokenizer.py +95 -0
- pie_extended/models/freem/__init__.py +21 -0
- pie_extended/models/freem/imports.py +28 -0
- pie_extended/models/frm/__init__.py +46 -0
- pie_extended/models/frm/imports.py +1 -0
- pie_extended/models/fro/__init__.py +44 -0
- pie_extended/models/fro/imports.py +31 -0
- pie_extended/models/fro/processor.py +54 -0
- pie_extended/models/fro/tokenizer.py +88 -0
- pie_extended/models/grc/__init__.py +46 -0
- pie_extended/models/grc/imports.py +24 -0
- pie_extended/models/grc/processor.py +40 -0
- pie_extended/models/grc/tokenizer.py +73 -0
- pie_extended/models/lasla/__init__.py +51 -0
- pie_extended/models/lasla/_params.py +92 -0
- pie_extended/models/lasla/imports.py +64 -0
- pie_extended/models/lasla/processor.py +146 -0
- pie_extended/models/lasla/tokenizer.py +115 -0
- pie_extended/models/occ_cont/__init__.py +25 -0
- pie_extended/models/occ_cont/imports.py +23 -0
- pie_extended/models/occ_cont/processor.py +0 -0
- pie_extended/models/occ_cont/tokenizer.py +127 -0
- pie_extended/pipeline/__init__.py +0 -0
- pie_extended/pipeline/disambiguators/__init__.py +0 -0
- pie_extended/pipeline/disambiguators/autocat.py +59 -0
- pie_extended/pipeline/disambiguators/proto.py +7 -0
- pie_extended/pipeline/formatters/__init__.py +0 -0
- pie_extended/pipeline/formatters/proto.py +46 -0
- pie_extended/pipeline/iterators/__init__.py +3 -0
- pie_extended/pipeline/iterators/proto.py +133 -0
- pie_extended/pipeline/postprocessor/__init__.py +0 -0
- pie_extended/pipeline/postprocessor/glue.py +96 -0
- pie_extended/pipeline/postprocessor/memory.py +78 -0
- pie_extended/pipeline/postprocessor/proto.py +157 -0
- pie_extended/pipeline/postprocessor/rulebased.py +44 -0
- pie_extended/pipeline/postprocessor/splitter.py +63 -0
- pie_extended/pipeline/tokenizers/__init__.py +0 -0
- pie_extended/pipeline/tokenizers/memorizing.py +55 -0
- pie_extended/pipeline/tokenizers/simple_tokenizer.py +73 -0
- pie_extended/pipeline/tokenizers/utils/__init__.py +0 -0
- pie_extended/pipeline/tokenizers/utils/chars.py +2 -0
- pie_extended/pipeline/tokenizers/utils/excluder.py +349 -0
- pie_extended/pipeline/tokenizers/utils/regexps.py +15 -0
- pie_extended/tagger.py +120 -0
- pie_extended/testing_utils/__init__.py +106 -0
- pie_extended/utils/__init__.py +59 -0
- pie_extended-0.1.4.dist-info/METADATA +198 -0
- pie_extended-0.1.4.dist-info/RECORD +64 -0
- pie_extended-0.1.4.dist-info/WHEEL +5 -0
- pie_extended-0.1.4.dist-info/entry_points.txt +2 -0
- pie_extended-0.1.4.dist-info/licenses/LICENSE +373 -0
- pie_extended-0.1.4.dist-info/top_level.txt +1 -0
pie_extended/__init__.py
ADDED
|
File without changes
|
pie_extended/__main__.py
ADDED
|
File without changes
|
pie_extended/cli/main.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import click
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
from pie_extended.cli import utils
|
|
5
|
+
from typing import Iterable
|
|
6
|
+
|
|
7
|
+
MODELS = [name for name, *_ in utils.get_list()]
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@click.group("pie-ext")
|
|
11
|
+
def pie_ext():
|
|
12
|
+
""" Addon for Pie that allows you to download and install modules that you might be interested in """
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@pie_ext.command("list")
|
|
16
|
+
@click.option("--full", is_flag=True, help="Display full information on models")
|
|
17
|
+
def print_list(full):
|
|
18
|
+
""" List available model to download and use """
|
|
19
|
+
click.echo("Available Models:")
|
|
20
|
+
for module, desc in utils.get_list():
|
|
21
|
+
click.echo("\t- {} ({}) : {}".format(
|
|
22
|
+
click.style(module, bold=True),
|
|
23
|
+
desc.lang,
|
|
24
|
+
click.style(desc.title, underline=True)
|
|
25
|
+
))
|
|
26
|
+
if full:
|
|
27
|
+
click.echo("\t\tAuthor(s): {}".format(", ".join(desc.authors)))
|
|
28
|
+
click.echo("\t\tDescription(s): {}".format(desc.description))
|
|
29
|
+
click.echo("\t\tURL: {}".format(desc.link))
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@pie_ext.command("download")
|
|
33
|
+
@click.argument("model", type=click.Choice(MODELS, case_sensitive=False))
|
|
34
|
+
def download(model):
|
|
35
|
+
""" Download a [model] for future availability. Check list for available models"""
|
|
36
|
+
click.echo(click.style("Starting downloading...", bold=True))
|
|
37
|
+
for index, file in enumerate(utils.download(model)):
|
|
38
|
+
if index == 0:
|
|
39
|
+
click.echo("{} files to download".format(file))
|
|
40
|
+
else:
|
|
41
|
+
click.echo("- {} downloaded".format(file))
|
|
42
|
+
click.echo(click.style("Finished !", bold=True))
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@pie_ext.command("tag")
|
|
46
|
+
@click.argument("model", type=click.Choice(MODELS, case_sensitive=False))
|
|
47
|
+
@click.argument("filepath", nargs=-1, type=click.Path(exists=True, dir_okay=False))
|
|
48
|
+
@click.option("--no-tokenizer", "no_tokenizer", is_flag=True,
|
|
49
|
+
help="Do not apply advanced tokenizer: new line = one word, two new lines = one sentence")
|
|
50
|
+
@click.option("--allow-n-failures", "allowed_failure", type=int, default=5,
|
|
51
|
+
help="Number of failures before things crash")
|
|
52
|
+
@click.option("--batch_size", type=int, default=16,
|
|
53
|
+
help="Group of sentences tagged together")
|
|
54
|
+
@click.option("--device", type=str, default="cpu",
|
|
55
|
+
help="Use cpu or gpu for prediction")
|
|
56
|
+
@click.option("--debug", is_flag=True,
|
|
57
|
+
help="Raise error when a file is not tagged correctly")
|
|
58
|
+
@click.option("--model_path", type=str, default=None,
|
|
59
|
+
help="Provide this with your own model path if you want to test it")
|
|
60
|
+
@click.option("--reset-exclude-patterns", "reset_patterns", is_flag=True, default=False,
|
|
61
|
+
help="Reset exclude patterns")
|
|
62
|
+
@click.option("--add-pattern", "add_pattern",
|
|
63
|
+
help="Add new exclude patterns for token (Regular expression)", multiple=True)
|
|
64
|
+
@click.option("--max-tokens", "max_tokens",
|
|
65
|
+
help="Maximum length of sentence", type=int, default=64)
|
|
66
|
+
def tag(model: str, filepath: str, allowed_failure: bool, batch_size: int, device: str, debug: bool,
|
|
67
|
+
model_path: str,
|
|
68
|
+
reset_patterns: bool, add_pattern: Iterable[str],
|
|
69
|
+
no_tokenizer: bool = False,
|
|
70
|
+
max_tokens: int = 64):
|
|
71
|
+
""" Tag as many [filepath] as you want with [model] """
|
|
72
|
+
from tqdm import tqdm
|
|
73
|
+
click.echo(click.style("Getting the tagger", bold=True))
|
|
74
|
+
try:
|
|
75
|
+
tagger = utils.get_tagger(model, batch_size=batch_size, device=device, model_path=model_path)
|
|
76
|
+
except FileNotFoundError as e:
|
|
77
|
+
click.echo("Model not found: please make sure you have downloaded the model files with "
|
|
78
|
+
"pie-extended download " + model)
|
|
79
|
+
if debug:
|
|
80
|
+
raise e
|
|
81
|
+
return
|
|
82
|
+
failures = []
|
|
83
|
+
for file in tqdm(filepath):
|
|
84
|
+
try:
|
|
85
|
+
utils.tag_file(
|
|
86
|
+
model, tagger, file, reset_exclude_patterns=reset_patterns,
|
|
87
|
+
exclude_patterns=add_pattern, no_tokenizer=no_tokenizer,
|
|
88
|
+
max_tokens=max_tokens)
|
|
89
|
+
except Exception as E:
|
|
90
|
+
failures.append((file, E))
|
|
91
|
+
click.echo("{} could not be lemmatized".format(file))
|
|
92
|
+
if debug:
|
|
93
|
+
raise E
|
|
94
|
+
if len(failures) > allowed_failure:
|
|
95
|
+
click.echo(
|
|
96
|
+
click.style("Too many errors, stopping the process", fg="red")
|
|
97
|
+
)
|
|
98
|
+
for failure in failures:
|
|
99
|
+
print(failure)
|
|
100
|
+
break
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
@pie_ext.command("install-addons")
|
|
104
|
+
@click.argument("model", type=click.Choice(MODELS, case_sensitive=False))
|
|
105
|
+
def install(model):
|
|
106
|
+
""" Install addons for specific models"""
|
|
107
|
+
click.echo(click.style("Installing add-ons", bold=True))
|
|
108
|
+
utils.get_addons(model)
|
|
109
|
+
click.echo(click.style("Done", bold=True))
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
@pie_ext.command("details")
|
|
113
|
+
@click.argument("model", type=click.Choice(MODELS, case_sensitive=False))
|
|
114
|
+
@click.option("--model_path", type=str, default=None,
|
|
115
|
+
help="Provide this with your own model path if you want to test it")
|
|
116
|
+
def details(model: str, model_path: str = None):
|
|
117
|
+
""" Get details about known characters by the [model] """
|
|
118
|
+
from tqdm import tqdm
|
|
119
|
+
click.echo(click.style("Getting the tagger", bold=True))
|
|
120
|
+
tagger = utils.get_tagger(model, model_path=model_path)
|
|
121
|
+
for model, tasks in tagger.models:
|
|
122
|
+
print(sorted(list(model.label_encoder.char.table.keys())))
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import sys
|
|
3
|
+
from typing import Tuple, Iterable, List, Union
|
|
4
|
+
from importlib import import_module
|
|
5
|
+
|
|
6
|
+
import requests
|
|
7
|
+
|
|
8
|
+
from .. import models
|
|
9
|
+
from ..utils import Metadata, PATH, get_path
|
|
10
|
+
from ..tagger import ExtensibleTagger
|
|
11
|
+
from ..utils import ObjectCreator
|
|
12
|
+
from pie.utils import model_spec
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def check(model: str, force: bool = False) -> bool:
|
|
16
|
+
""" Check if files are available for a given model """
|
|
17
|
+
module = get_model(model)
|
|
18
|
+
return False not in [
|
|
19
|
+
os.path.exists(
|
|
20
|
+
get_path(model, file.name)
|
|
21
|
+
)
|
|
22
|
+
for file in module.DOWNLOADS
|
|
23
|
+
] or force
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def get_model(model: str):
|
|
27
|
+
""" Retrieve a module given a string
|
|
28
|
+
|
|
29
|
+
:param model: Module Name
|
|
30
|
+
:return: Module
|
|
31
|
+
"""
|
|
32
|
+
return import_module("{}.{}".format(models.__name__, model))
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def get_imports(module):
|
|
36
|
+
return import_module("{}.{}".format(module.__name__, "imports"))
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _download(url, filename):
|
|
40
|
+
with open(filename, 'wb') as f:
|
|
41
|
+
response = requests.get(url, stream=True)
|
|
42
|
+
total = response.headers.get('content-length')
|
|
43
|
+
|
|
44
|
+
if total is None:
|
|
45
|
+
f.write(response.content)
|
|
46
|
+
else:
|
|
47
|
+
downloaded = 0
|
|
48
|
+
total = int(total)
|
|
49
|
+
for data in response.iter_content(chunk_size=max(int(total/1000), 1024*1024)):
|
|
50
|
+
downloaded += len(data)
|
|
51
|
+
f.write(data)
|
|
52
|
+
done = int(50*downloaded/total)
|
|
53
|
+
sys.stdout.write('\r[{}{}]'.format('█' * done, '.' * (50-done)))
|
|
54
|
+
sys.stdout.flush()
|
|
55
|
+
sys.stdout.write('\n')
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def download(module: str) -> Iterable[Union[str, int]]:
|
|
59
|
+
""" Download dependencies for the given module
|
|
60
|
+
|
|
61
|
+
:param module: Module for which to download models and static files in general
|
|
62
|
+
"""
|
|
63
|
+
lemmatizer = get_model(module)
|
|
64
|
+
os.makedirs(os.path.join(PATH, module), exist_ok=True)
|
|
65
|
+
yield len(lemmatizer.DOWNLOADS)
|
|
66
|
+
for file in lemmatizer.DOWNLOADS:
|
|
67
|
+
|
|
68
|
+
new_path = get_path(module, file.name)
|
|
69
|
+
_download(file.url, new_path)
|
|
70
|
+
yield file.name
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def get_list() -> Iterable[Tuple[str, Metadata]]:
|
|
74
|
+
""" Retrieve a list of available modules
|
|
75
|
+
"""
|
|
76
|
+
for module in models.modules:
|
|
77
|
+
desc = getattr(get_model(module), "DESC", None)
|
|
78
|
+
if desc:
|
|
79
|
+
yield module, desc
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def get_tagger(model: str, batch_size: int = 16, device="cpu", model_path=None) -> ExtensibleTagger:
|
|
83
|
+
""" Retrieve the tagger
|
|
84
|
+
|
|
85
|
+
:param model: Module of the tagger
|
|
86
|
+
:param batch_size: Size of the batch
|
|
87
|
+
:param device: Device to use (cuda/cpu)
|
|
88
|
+
:param model_path: Path to the model if you want to override the package one
|
|
89
|
+
:return: Tagger
|
|
90
|
+
"""
|
|
91
|
+
module = get_model(model)
|
|
92
|
+
|
|
93
|
+
disambiguator = getattr(get_imports(module), "Disambiguator", None)
|
|
94
|
+
if isinstance(disambiguator, ObjectCreator):
|
|
95
|
+
disambiguator = disambiguator.create()
|
|
96
|
+
tagger = ExtensibleTagger(disambiguation=disambiguator, batch_size=batch_size, device=device)
|
|
97
|
+
model_spec_string = model_path or getattr(module, "Models")
|
|
98
|
+
for model, tasks in model_spec(model_spec_string):
|
|
99
|
+
tagger.add_model(model, *tasks)
|
|
100
|
+
return tagger
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def tag_file(
|
|
104
|
+
model: str, tagger: ExtensibleTagger,
|
|
105
|
+
fpath: str,
|
|
106
|
+
reset_exclude_patterns: bool = False,
|
|
107
|
+
exclude_patterns: List[str] = None,
|
|
108
|
+
no_tokenizer: bool = False,
|
|
109
|
+
max_tokens: int = 256):
|
|
110
|
+
""" Tag a file with a given model
|
|
111
|
+
|
|
112
|
+
:param model: Module name of the model
|
|
113
|
+
:param tagger: Tagger that should be used
|
|
114
|
+
:param fpath: Path to the file to edit
|
|
115
|
+
:param reset_exclude_patterns: Remove all pre-registered token exclusion regular expressions
|
|
116
|
+
:param exclude_patterns: New exclude patterns to add to the data iterator (Does not require reset)
|
|
117
|
+
:param no_tokenizer: Does not use usual tokenizers (new line = word separator, two new lines = sentence_
|
|
118
|
+
"""
|
|
119
|
+
module = get_model(model)
|
|
120
|
+
iterator, processor = getattr(get_imports(module), "get_iterator_and_processor")(max_tokens=max_tokens)
|
|
121
|
+
# Remove first pattern
|
|
122
|
+
if reset_exclude_patterns:
|
|
123
|
+
iterator.reset_patterns()
|
|
124
|
+
|
|
125
|
+
# Add new
|
|
126
|
+
if exclude_patterns:
|
|
127
|
+
for pattern in exclude_patterns:
|
|
128
|
+
iterator.add_pattern(pattern)
|
|
129
|
+
|
|
130
|
+
tagger.tag_file(fpath, iterator=iterator, processor=processor, no_tokenizer=no_tokenizer)
|
|
131
|
+
return True
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def get_addons(model: str):
|
|
135
|
+
""" Runs the `addons` function from a module """
|
|
136
|
+
module = get_model(model)
|
|
137
|
+
addons = getattr(get_imports(module), "addons", lambda: print("No add-ons needed for " + model))
|
|
138
|
+
return addons()
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
from ...utils import Metadata, File, get_path
|
|
2
|
+
|
|
3
|
+
DESC = Metadata(
|
|
4
|
+
"Middle Dutch",
|
|
5
|
+
"dum",
|
|
6
|
+
["Mike Kestemont"],
|
|
7
|
+
"Middle Dutch Model",
|
|
8
|
+
"https://github.com/hipster-philology/middle-dutch-model"
|
|
9
|
+
)
|
|
10
|
+
|
|
11
|
+
VERSION = "0.0.1"
|
|
12
|
+
DOWNLOADS = [
|
|
13
|
+
File(f"https://github.com/hipster-philology/middle-dutch-model/releases/download/{VERSION}/lemma.tar", "lemma.tar"),
|
|
14
|
+
File(f"https://github.com/hipster-philology/middle-dutch-model/releases/download/{VERSION}/pos.tar", "pos.tar")
|
|
15
|
+
]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
Models = "<{},lemma><{},pos>".format(
|
|
19
|
+
get_path("dum", "lemma.tar"),
|
|
20
|
+
get_path("dum", "pos.tar")
|
|
21
|
+
)
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
from pie_extended.pipeline.postprocessor.proto import ProcessorPrototype
|
|
2
|
+
from pie_extended.pipeline.iterators.proto import DataIterator
|
|
3
|
+
from pie_extended.pipeline.tokenizers.simple_tokenizer import LengthTokenizer
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def get_iterator_and_processor(max_tokens=256):
|
|
7
|
+
tokenizer = LengthTokenizer(35)
|
|
8
|
+
processor = ProcessorPrototype()
|
|
9
|
+
iterator = DataIterator(
|
|
10
|
+
tokenizer=tokenizer,
|
|
11
|
+
max_tokens=max_tokens
|
|
12
|
+
)
|
|
13
|
+
return iterator, processor
|
|
14
|
+
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
from ...utils import Metadata, File, get_path
|
|
2
|
+
|
|
3
|
+
DESC = Metadata(
|
|
4
|
+
"Français classique et moderne",
|
|
5
|
+
"fr",
|
|
6
|
+
["Jean-Baptiste Camps", "Simon Gabay", "Thibault Clérice", "Florian Cafiero"],
|
|
7
|
+
"Corpus and Models for Lemmatisation and POS-tagging of Classical French Theatre",
|
|
8
|
+
"TODO: add arXiv link"
|
|
9
|
+
)
|
|
10
|
+
|
|
11
|
+
DOWNLOADS = [
|
|
12
|
+
File("https://zenodo.org/record/3701294/files/fr-class-wembs-lemma-2020_03_06-01_52_24.tar?download=1", "lemma.tar"),
|
|
13
|
+
File("https://zenodo.org/record/3701320/files/fr-class-pos-wembs_aux-pos-2020_03_03-18_52_52.tar?download=1", "pos.tar"),
|
|
14
|
+
File("https://zenodo.org/record/3701320/files/fr-class-morph-wembs_aux-MODE-2020_03_08-17_46_05.tar?download=1", "mode.tar"),
|
|
15
|
+
File("https://zenodo.org/record/3701320/files/fr-class-morph-wembs_aux-TEMPS-2020_03_08-19_03_26.tar?download=1", "temps.tar"),
|
|
16
|
+
File("https://zenodo.org/record/3701320/files/fr-class-morph-wembs_aux-PERS-2020_03_08-18_24_29.tar?download=1", "pers.tar"),
|
|
17
|
+
File("https://zenodo.org/record/3701320/files/fr-class-morph-wembs_aux-NOMB-2020_03_08-17_55_50.tar?download=1", "nomb.tar"),
|
|
18
|
+
File("https://zenodo.org/record/3701320/files/fr-class-morph-wembs_aux-GENRE-2020_03_08-16_54_44.tar?download=1", "genre.tar"),
|
|
19
|
+
File("https://zenodo.org/record/3701320/files/fr-class-morph-wembs_aux-CAS-2020_03_08-16_23_57.tar?download=1", "cas.tar")
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
Models = "<{},lemma><{},pos><{},MODE><{},TEMPS><{},PERS><{},NOMB><{},GENRE><{},CAS>".format(
|
|
24
|
+
get_path("fr", "lemma.tar"),
|
|
25
|
+
get_path("fr", "pos.tar"),
|
|
26
|
+
get_path("fr", "mode.tar"),
|
|
27
|
+
get_path("fr", "temps.tar"),
|
|
28
|
+
get_path("fr", "pers.tar"),
|
|
29
|
+
get_path("fr", "nomb.tar"),
|
|
30
|
+
get_path("fr", "genre.tar"),
|
|
31
|
+
get_path("fr", "cas.tar")
|
|
32
|
+
)
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
from typing import Tuple, Match, Optional
|
|
2
|
+
import regex as re
|
|
3
|
+
|
|
4
|
+
from pie_extended.pipeline.tokenizers.utils.excluder import ExcluderPrototype, DASH, APOSTROPHE, CharRegistry
|
|
5
|
+
from pie_extended.pipeline.tokenizers.utils import chars
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
AUJOURDHUI_CONSTANT = "#AUJOURDHUI#"
|
|
9
|
+
|
|
10
|
+
CLITICS = tuple(sorted([
|
|
11
|
+
'-ce', '-ci', '-elle', '-elles', '-en', '-eux', '-il', '-ils', '-je', '-la', '-le',
|
|
12
|
+
'-les', '-leur', '-leurs',
|
|
13
|
+
'-lui', '-là', '-m', '-me', '-moi', '-même', '-mêmes', '-nous', '-on', '-t',
|
|
14
|
+
'-te', '-toi', '-tu', '-un',
|
|
15
|
+
'-une', '-unes', '-uns', '-vous', '-y',
|
|
16
|
+
# No idea what was the goal of the following line...
|
|
17
|
+
# r'-m字\d', r'-t字\d' # 字 replaces all kinds of apostrophe
|
|
18
|
+
], key=len, reverse=True))
|
|
19
|
+
|
|
20
|
+
# Abbreviations separated by `; ` (SEMICOLON+SPACE)
|
|
21
|
+
# You can use regexp inside this list, such as [Cc]f. but I would rather recommend to add both `cf.; Cf;`
|
|
22
|
+
# for readability.
|
|
23
|
+
ABBREVIATIONS = sorted(list(set(
|
|
24
|
+
"Acad.; Adj.; Agricol.; Agricul.; Apocal.; anc.; Bot.; Botan.; Botaniq.; ca.; cap.; capi.; cf.; Cf.; "
|
|
25
|
+
"Cha.; Chap.; Col.; Dic.; Diction.; Dictionn.; Eccl.; Écon.; Élem.; Fig.; Fr.; Geog.; Gram.; "
|
|
26
|
+
"Gramm.; Hist.; Ibid.; Ibid.; Inst.; Jard.; Jurisprud.; Latit.; Li.; Lib.; Libr.; Lig.; Lit.; "
|
|
27
|
+
"Littérat.; Liv.; Long.; Mar.; Mat.; Mathém.; Mech.; Med.; Med.; Mem.; Menuis.; Milit.; Mod.; "
|
|
28
|
+
"Mor.; Mr.; Monsr.; nat.; natur.; N.b.; Orat.; Ornith.; Ornythol.; Ornitholog.; Part.; Pag.; "
|
|
29
|
+
"Pharm.; Phil.; Philos.; Pl.; Pl.; Politiq.; P.S.; Phys.; Physiq.; Sr.; St.; Subst.; s.f.; "
|
|
30
|
+
"S.M.; s.m.; Tab.; Théât.; Trév.; Tom.; Vol.; V. n.; V. a.; V. act.; Zoo.; "
|
|
31
|
+
"Zoolog.".split("; ")
|
|
32
|
+
)), key=len, reverse=True)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class AujourdhuiExcluder(ExcluderPrototype):
|
|
36
|
+
""" Normalizes Aujourd'hui before it goes into splitting sentences
|
|
37
|
+
|
|
38
|
+
>>> excl = AujourdhuiExcluder()
|
|
39
|
+
>>> len(excl.before_sentence_tokenizer("Aujourd'hui j'ai poney").split()) == 3
|
|
40
|
+
True
|
|
41
|
+
>>> len(excl.after_sentence_tokenizer("Aujourd字0hui j'ai poney").split()) == 3
|
|
42
|
+
True
|
|
43
|
+
>>> excl.after_sentence_tokenizer(excl.before_sentence_tokenizer("Aujourd'hui j'ai poney"))
|
|
44
|
+
"Aujourd'hui j'ai poney"
|
|
45
|
+
"""
|
|
46
|
+
def __init__(self, char_registry: Optional[CharRegistry] = None, apostrophe: str = chars.APOSTROPHE):
|
|
47
|
+
self.char_registry: CharRegistry = char_registry or CharRegistry()
|
|
48
|
+
self.apostrophes = apostrophe
|
|
49
|
+
self.re = re.compile("(aujourd)(["+self.apostrophes+"])(hui)", flags=re.IGNORECASE)
|
|
50
|
+
|
|
51
|
+
def _replace(self, regex_match: Match) -> str:
|
|
52
|
+
return regex_match.group(1) + \
|
|
53
|
+
self.char_registry[AUJOURDHUI_CONSTANT] + \
|
|
54
|
+
str(self.apostrophes.index(regex_match.group(2))) +\
|
|
55
|
+
regex_match.group(3)
|
|
56
|
+
|
|
57
|
+
def before_sentence_tokenizer(self, value: str) -> str:
|
|
58
|
+
return self.re.sub(self._replace, value)
|
|
59
|
+
|
|
60
|
+
def after_sentence_tokenizer(self, value: str) -> str:
|
|
61
|
+
for index_apo, apostrophe in enumerate(self.apostrophes):
|
|
62
|
+
value = value.replace(
|
|
63
|
+
self.char_registry[AUJOURDHUI_CONSTANT] + str(index_apo),
|
|
64
|
+
apostrophe
|
|
65
|
+
)
|
|
66
|
+
return value
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class FrenchCliticsExcluder(ExcluderPrototype):
|
|
70
|
+
def __init__(self,
|
|
71
|
+
clitics: Tuple[str, ...] = CLITICS, char_registry: Optional[CharRegistry] = None,
|
|
72
|
+
add_space_before: bool = True, add_space_after: bool = True,
|
|
73
|
+
apostrophes: str = chars.APOSTROPHE):
|
|
74
|
+
self.clitics = clitics
|
|
75
|
+
self.char_registry: CharRegistry = char_registry or CharRegistry()
|
|
76
|
+
self.apostrophes = apostrophes
|
|
77
|
+
self.re = re.compile(
|
|
78
|
+
r"((-)(t))?(-)(" +
|
|
79
|
+
r"|".join([tok.replace("-", "") for tok in self.clitics]) +
|
|
80
|
+
# We use apostrophe_mask and the \d because a mask could have already been applied
|
|
81
|
+
r")([" + self.apostrophes + r"]|" +
|
|
82
|
+
self.char_registry[self.char_registry.APOSTROPHE_CONSTANT] + r"\d|\b|$)",
|
|
83
|
+
flags=re.IGNORECASE
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
# Space handling
|
|
87
|
+
self.space_before: str = ""
|
|
88
|
+
if add_space_before:
|
|
89
|
+
self.space_before = " "
|
|
90
|
+
|
|
91
|
+
self.space_after: str = ""
|
|
92
|
+
if add_space_after:
|
|
93
|
+
self.space_after = " "
|
|
94
|
+
|
|
95
|
+
def _replace_clitic(self, match: Match) -> str:
|
|
96
|
+
# Group 1: - (of -t)
|
|
97
|
+
# Group 2: t (of -t)
|
|
98
|
+
# Group 3: - (of clitic)
|
|
99
|
+
# Group 4: t (the clitic)
|
|
100
|
+
# Group 5: apostrophe or word boundary
|
|
101
|
+
g0, g1, g2, g3, g4, g5 = match.groups()
|
|
102
|
+
before = ""
|
|
103
|
+
if g0:
|
|
104
|
+
before = self.char_registry["-"]+"t"
|
|
105
|
+
|
|
106
|
+
return self.space_before + before + self.char_registry["-"] + g4 + g5 + self.space_after
|
|
107
|
+
|
|
108
|
+
def before_sentence_tokenizer(self, value: str) -> str:
|
|
109
|
+
""" Normalize before sentence is tokenized
|
|
110
|
+
|
|
111
|
+
>>> excl = FrenchCliticsExcluder()
|
|
112
|
+
>>> excl.before_sentence_tokenizer("A-t-il mangé le peut-être que moi-même je connais ?")
|
|
113
|
+
'A 精t精il mangé le peut-être que moi 精même je connais ?'
|
|
114
|
+
|
|
115
|
+
Note that it introduces a secondary space.
|
|
116
|
+
|
|
117
|
+
>>> excl.before_sentence_tokenizer("Va-t'en va-nu-pieds !")
|
|
118
|
+
"Va 精t' en va-nu-pieds !"
|
|
119
|
+
|
|
120
|
+
"""
|
|
121
|
+
return self.re.sub(
|
|
122
|
+
self._replace_clitic,
|
|
123
|
+
value
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
def after_sentence_tokenizer(self, value: str) -> str:
|
|
127
|
+
return value.replace(self.char_registry["-"], "-")
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
from .processor import FrGlueProcessor
|
|
2
|
+
from pie_extended.pipeline.postprocessor.proto import RenamedTaskProcessor
|
|
3
|
+
from .tokenizer import FrMemorizingTokenizer
|
|
4
|
+
from pie_extended.pipeline.iterators.proto import DataIterator
|
|
5
|
+
from pie_extended.pipeline.postprocessor.memory import MemoryzingProcessor
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def get_iterator_and_processor(max_tokens=256):
|
|
9
|
+
tokenizer = FrMemorizingTokenizer()
|
|
10
|
+
processor = MemoryzingProcessor(
|
|
11
|
+
tokenizer_memory=tokenizer,
|
|
12
|
+
head_processor=FrGlueProcessor(
|
|
13
|
+
head_processor=RenamedTaskProcessor({"pos": "POS", "NOMB": "NOMB.", "PERS": "PERS."})
|
|
14
|
+
)
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
iterator = DataIterator(
|
|
18
|
+
tokenizer=tokenizer,
|
|
19
|
+
max_tokens=max_tokens
|
|
20
|
+
)
|
|
21
|
+
return iterator, processor
|
|
22
|
+
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
from typing import Dict, Generator
|
|
2
|
+
from pie_extended.pipeline.postprocessor.glue import GlueProcessor
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class FrGlueProcessor(GlueProcessor):
|
|
6
|
+
""" We glue morphological features into one column
|
|
7
|
+
"""
|
|
8
|
+
OUTPUT_KEYS = ["form", "lemma", "POS", "morph"]
|
|
9
|
+
GLUE = {"morph": ["MODE", "TEMPS", "PERS.", "NOMB.", "GENRE", "CAS"]} # , "DEGRE"]}
|
|
10
|
+
EMPTY_TAG: Dict[str, str] = {"CAS": "CAS=x", "NOMB.": "NOMB.=x", "MODE": "MODE=x", "TEMPS": "TEMPS=x",
|
|
11
|
+
"GENRE": "GENRE=x", "PERS.": "PERS.=x"}
|
|
12
|
+
|
|
13
|
+
# We need to change the definition of this function, because, for now,
|
|
14
|
+
# the model gives us an output like
|
|
15
|
+
# MODE=imp
|
|
16
|
+
# and not
|
|
17
|
+
# imp
|
|
18
|
+
def _yield_annotation(
|
|
19
|
+
self,
|
|
20
|
+
token_dict: Dict[str, str]
|
|
21
|
+
) -> Generator[str, None, None]:
|
|
22
|
+
# For each key we should return
|
|
23
|
+
for head in self._out:
|
|
24
|
+
if head not in self._glue:
|
|
25
|
+
yield head, token_dict[head]
|
|
26
|
+
else:
|
|
27
|
+
# Otherwise, we glue together things that should be glued together
|
|
28
|
+
joined = self._glue_char.join([
|
|
29
|
+
# HERE
|
|
30
|
+
# glued_task + "=" +
|
|
31
|
+
token_dict[glued_task]
|
|
32
|
+
for glued_task in self._glue[head]
|
|
33
|
+
if token_dict[glued_task] != self._empty_tags.get(glued_task, None)
|
|
34
|
+
])
|
|
35
|
+
if not joined:
|
|
36
|
+
joined = self._glue_empty[head]
|
|
37
|
+
yield head, joined
|
|
38
|
+
|
|
39
|
+
def __init__(self, *args, **kwargs):
|
|
40
|
+
super(FrGlueProcessor, self).__init__(*args, **kwargs)
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import regex as re
|
|
2
|
+
from typing import List, Generator, Tuple
|
|
3
|
+
|
|
4
|
+
from pie_extended.pipeline.tokenizers.memorizing import MemorizingTokenizer
|
|
5
|
+
from pie_extended.pipeline.tokenizers.utils import regexps, chars
|
|
6
|
+
from pie_extended.pipeline.tokenizers.utils.excluder import (
|
|
7
|
+
ExcluderPrototype, CompoundAbbreviationsExcluder, ApostropheExcluder,
|
|
8
|
+
ReferenceExcluder,
|
|
9
|
+
CharRegistry
|
|
10
|
+
)
|
|
11
|
+
from pie_extended.models.fr.excluders import FrenchCliticsExcluder, ABBREVIATIONS, AujourdhuiExcluder
|
|
12
|
+
|
|
13
|
+
_Dots_except_apostrophe = r".?!\"“”\"«»…\[\]\(\)„“"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
""" This code has been removed for now, might be reused later
|
|
17
|
+
|
|
18
|
+
# ToDo: Transform into Agglutinated excluder ?
|
|
19
|
+
_data_re_keep_together = "peut-être, peut-estre, sur-tout, long-temps, par-tout, vis-à-vis".split(", ")
|
|
20
|
+
re_keep_together = re.compile(
|
|
21
|
+
r"("+"|".join([
|
|
22
|
+
token
|
|
23
|
+
for token in _data_re_keep_together
|
|
24
|
+
])+r")(?:\b|$)",
|
|
25
|
+
flags=re.IGNORECASE
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
def replace_keep_together(self, regex_match) -> str:
|
|
29
|
+
return regex_match.group(0).replace("-", "分")
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class FrMemorizingTokenizer(MemorizingTokenizer):
|
|
34
|
+
re_add_space_around_punct = re.compile(regexps.NON_WORD_NON_SPACE)
|
|
35
|
+
re_remove_ending_apostrophe = re.compile(regexps.ENDING_APOSTROPHE)
|
|
36
|
+
re_sentence_boundaries = re.compile(r"([" + chars.DOTS_EXCEPT_APOSTROPHES + r"]+\s*)+")
|
|
37
|
+
|
|
38
|
+
def __init__(self):
|
|
39
|
+
super(FrMemorizingTokenizer, self).__init__()
|
|
40
|
+
self.tokens = []
|
|
41
|
+
self.char_registry = CharRegistry()
|
|
42
|
+
self.normalizers: Tuple[ExcluderPrototype, ...] = (
|
|
43
|
+
AujourdhuiExcluder(char_registry=self.char_registry),
|
|
44
|
+
ApostropheExcluder(char_registry=self.char_registry),
|
|
45
|
+
FrenchCliticsExcluder(char_registry=self.char_registry),
|
|
46
|
+
CompoundAbbreviationsExcluder(abbrs=ABBREVIATIONS, ignore_case=False, char_registry=self.char_registry),
|
|
47
|
+
ReferenceExcluder(char_registry=self.char_registry),
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
@staticmethod
|
|
51
|
+
def _sentence_tokenizer_merge_matches(match):
|
|
52
|
+
""" Best way we found to deal with repeating groups"""
|
|
53
|
+
start, end = match.span()
|
|
54
|
+
return match.string[start:end] + "<SPLIT>"
|
|
55
|
+
|
|
56
|
+
def _real_sentence_tokenizer(self, string: str) -> List[str]:
|
|
57
|
+
string = self.re_sentence_boundaries.sub(self._sentence_tokenizer_merge_matches, string)
|
|
58
|
+
|
|
59
|
+
for excluder in self.normalizers:
|
|
60
|
+
string = excluder.after_sentence_tokenizer(string)
|
|
61
|
+
|
|
62
|
+
return string.split("<SPLIT>")
|
|
63
|
+
|
|
64
|
+
def _real_word_tokenizer(self, text: str, lower: bool = False) -> List[str]:
|
|
65
|
+
if lower:
|
|
66
|
+
text = text.lower()
|
|
67
|
+
text = text.split()
|
|
68
|
+
return text
|
|
69
|
+
|
|
70
|
+
def sentence_tokenizer(self, text: str, lower: bool = False) -> Generator[List[str], None, None]:
|
|
71
|
+
sentences = list()
|
|
72
|
+
data = self.normalizer(text)
|
|
73
|
+
for sent in self._real_sentence_tokenizer(data):
|
|
74
|
+
sent = sent.strip()
|
|
75
|
+
if sent:
|
|
76
|
+
sentences.append(self.word_tokenizer(sent))
|
|
77
|
+
yield from sentences
|
|
78
|
+
|
|
79
|
+
def normalizer(self, data: str) -> str:
|
|
80
|
+
for excluder in self.normalizers:
|
|
81
|
+
data = excluder.before_sentence_tokenizer(data)
|
|
82
|
+
|
|
83
|
+
data = self.re_add_space_around_punct.sub(
|
|
84
|
+
r" \g<2> ",
|
|
85
|
+
data
|
|
86
|
+
)
|
|
87
|
+
return data
|
|
88
|
+
|
|
89
|
+
def replacer(self, inp: str):
|
|
90
|
+
for excluder in self.normalizers:
|
|
91
|
+
if not excluder.can_be_replaced and excluder.exclude_regexp.match(inp):
|
|
92
|
+
return inp
|
|
93
|
+
|
|
94
|
+
return self.re_remove_ending_apostrophe.sub("'", inp)\
|
|
95
|
+
.replace("-t-", "-") # Temp feature until retrain has been done
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
from ...utils import Metadata, File, get_path
|
|
2
|
+
|
|
3
|
+
DESC = Metadata(
|
|
4
|
+
"Early Modern French",
|
|
5
|
+
"freem",
|
|
6
|
+
["Simon Gabay", "Jean-Baptiste Camps", "Thibault Clérice", "Jean-Baptiste Tanguy", "Matthias Gille-Levenson",
|
|
7
|
+
"Florian Cafiero"],
|
|
8
|
+
"Standardizing linguistic data: method and tools for annotating(pre-orthographic) French",
|
|
9
|
+
"https://github.com/FreEM-corpora/FreEMlpm"
|
|
10
|
+
)
|
|
11
|
+
VERSION ="v4"
|
|
12
|
+
DOWNLOADS = [
|
|
13
|
+
File(f"https://github.com/FreEM-corpora/FreEMlpm/releases/download/{VERSION}/lemma.tar", "lemma.tar"),
|
|
14
|
+
File(f"https://github.com/FreEM-corpora/FreEMlpm/releases/download/{VERSION}/pos.tar", "pos.tar")
|
|
15
|
+
]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
Models = "<{},lemma><{},POS,MODE,TEMPS,PERS,NOMB,GENRE,CAS>".format(
|
|
19
|
+
get_path("freem", "lemma.tar"),
|
|
20
|
+
get_path("freem", "pos.tar")
|
|
21
|
+
)
|