This repository has been archived by the owner on Jan 12, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreaders.py
131 lines (118 loc) · 4.81 KB
/
readers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
# Copyright (c) 2021 Kemal Kurniawan
from collections import defaultdict
from typing import Collection, Iterator, Optional, Set, Tuple
from pathlib import Path
from conllu import parse_incr
class UDReader:
DEFAULT_TREEBANK = {
"ar": ("Arabic", ["PADT"]),
"bg": ("Bulgarian", ["BTB"]),
"ca": ("Catalan", ["AnCora"]),
"cs": ("Czech", ["PDT", "CAC", "CLTT", "FicTree"]),
"da": ("Danish", ["DDT"]),
"de": ("German", ["GSD"]),
"en": ("English", ["EWT"]),
"es": ("Spanish", ["GSD", "AnCora"]),
"et": ("Estonian", ["EDT"]),
"eu": ("Basque", ["BDT"]),
"fa": ("Persian", ["Seraji"]),
"fi": ("Finnish", ["TDT"]),
"fr": ("French", ["GSD"]),
"he": ("Hebrew", ["HTB"]),
"hi": ("Hindi", ["HDTB"]),
"hr": ("Croatian", ["SET"]),
"id": ("Indonesian", ["GSD"]),
"it": ("Italian", ["ISDT"]),
"ja": ("Japanese", ["GSD"]),
"ko": ("Korean", ["GSD", "Kaist"]),
"la": ("Latin", ["PROIEL"]),
"lv": ("Latvian", ["LVTB"]),
"nl": ("Dutch", ["Alpino", "LassySmall"]),
"no": ("Norwegian", ["Bokmaal", "Nynorsk"]),
"pl": ("Polish", ["LFG", "SZ"]),
"pt": ("Portuguese", ["Bosque", "GSD"]),
"ro": ("Romanian", ["RRT"]),
"ru": ("Russian", ["SynTagRus"]),
"sk": ("Slovak", ["SNK"]),
"sl": ("Slovenian", ["SSJ", "SST"]),
"sv": ("Swedish", ["Talbanken"]),
"tr": ("Turkish", ["IMST"]),
"uk": ("Ukrainian", ["IU"]),
"zh": ("Chinese", ["GSD"]),
}
def __init__(
self,
ud_path: Path,
skip_mwe_and_empty: bool = True,
version: int = 2,
treebank_dict: Optional[dict] = None,
) -> None:
if treebank_dict is None:
treebank_dict = self.DEFAULT_TREEBANK
if version not in (1, 2):
raise ValueError("version must be 1 or 2")
self.ud_path = ud_path
self.treebank_dict = treebank_dict
self.skip_mwe_and_empty = skip_mwe_and_empty
self.version = version
def read_samples(self, langcode: str, which: str = "train") -> Iterator[dict]:
if self.version == 1:
return self._read_samples_v1(langcode, which)
return self._read_samples_v2(langcode, which)
def _read_samples_v2(self, langcode: str, which: str = "train") -> Iterator[dict]:
langname, tbnames = self.treebank_dict[langcode]
for tbname in tbnames:
path = (
self.ud_path
/ f"UD_{langname}-{tbname}"
/ f"{langcode}_{tbname.lower()}-ud-{which}.conllu"
)
with open(path, encoding="utf-8") as f:
for sent in parse_incr(f):
sample: dict = defaultdict(list)
for tok in sent:
# skip MWEs or empty words
if self.skip_mwe_and_empty and not isinstance(tok["id"], int):
continue
sample["words"].append(tok["form"])
sample["tags"].append(tok["upostag"])
sample["heads"].append(tok["head"])
sample["types"].append(tok["deprel"])
yield sample
def _read_samples_v1(self, langcode: str, which: str = "train") -> Iterator[dict]:
langname, _ = self.treebank_dict[langcode]
path = self.ud_path / f"UD_{langname}" / f"{langcode}-ud-{which}.conllu"
with open(path, encoding="utf-8") as f:
for sent in parse_incr(f):
sample: dict = defaultdict(list)
for tok in sent:
# skip MWEs or empty words
if self.skip_mwe_and_empty and not isinstance(tok["id"], int):
continue
sample["words"].append(tok["form"])
sample["tags"].append(tok["upostag"])
sample["heads"].append(tok["head"])
sample["types"].append(tok["deprel"])
yield sample
def get_proj_edges(edges: Collection[Tuple[int, int]]) -> Iterator[Tuple[int, int]]:
"""Obtain projective edges from a collection of edges of a dependency tree."""
adj_set: dict = defaultdict(set)
for u, v in edges:
adj_set[u].add(v)
def dfs(root: int) -> Set[int]:
stack, seen = [root], set()
while stack:
u = stack.pop()
seen.add(u)
for v in adj_set[u]:
if v not in seen:
stack.append(v)
return seen
nodes = {u for e in edges for u in e}
reachable_from = {u: dfs(u) for u in nodes}
for u, v in edges:
for w in range(min(u, v) + 1, max(u, v)):
if w not in reachable_from[u]:
break
else:
yield (u, v)