-
Notifications
You must be signed in to change notification settings - Fork 1
/
predict.py
232 lines (218 loc) · 7.2 KB
/
predict.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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
import gc
import json
import math
import os
from typing import List, NamedTuple
import catma_gitlab as catma
import torch
import typer
from torch.utils.data import DataLoader, random_split
from tqdm import tqdm
import event_classify.preprocessing
from event_classify.datasets import (
EventType,
JSONDataset,
SimpleEventDataset,
SpanAnnotation,
SpeechType,
)
from event_classify.eval import evaluate
from event_classify.parser import Parser
from event_classify.preprocessing import build_pipeline
from event_classify.util import get_model, split_text
app = typer.Typer()
@app.command()
def main(
segmented_json: str,
out_path: str,
model_path: str,
device: str = "cuda:0",
batch_size: int = 16,
special_tokens: bool = True,
):
"""
Add predictions to segmented json file.
Args:
model_path: Path to run directory containing saved model and tokenizer
"""
dataset = JSONDataset(segmented_json, include_special_tokens=special_tokens)
loader = DataLoader(
dataset,
batch_size=batch_size,
collate_fn=lambda list_: SpanAnnotation.to_batch(list_, tokenizer),
)
model, tokenizer = get_model(model_path)
model.to(device)
result = evaluate(loader, model, device=device)
dataset.save_json(out_path, result)
@app.command()
def gold_spans(
model_path: str,
device: str = "cuda:0",
special_tokens: bool = True,
dev: bool = False,
):
project = catma.CatmaProject(
".",
"CATMA_DD5E9DF1-0F5C-4FBD-B333-D507976CA3C7_EvENT_root",
filter_intrinsic_markup=False,
)
in_distribution_dataset = SimpleEventDataset(
project,
["Effi_Briest_MW", "Krambambuli_MW"],
include_special_tokens=special_tokens,
)
train_size = math.floor(len(in_distribution_dataset) * 0.9)
dev_size = len(in_distribution_dataset) - train_size
train_dataset, dev_dataset = random_split(
in_distribution_dataset,
[train_size, dev_size],
generator=torch.Generator().manual_seed(13),
)
collection = project.ac_dict["Verwandlung_MV"]
test_dataset = SimpleEventDataset(
project,
["Verwandlung_MV"],
include_special_tokens=special_tokens,
)
model, tokenizer = get_model(model_path)
model.eval()
print(len(dev_dataset))
loader = DataLoader(
dev_dataset if dev else test_dataset,
batch_size=16,
collate_fn=lambda list_: SpanAnnotation.to_batch(list_, tokenizer),
)
out_file = open("gold_spans.json", "w")
evaluate(
loader,
model,
device=device,
out_file=out_file,
save_confusion_matrix=True,
)
out_file.close()
@app.command()
def dprose(
model_path: str,
output_name: str,
device: str = "cuda:0",
special_tokens: bool = True,
batch_size: int = 8,
):
"""
Predict all of d-prose, applying segmentation in the same step.
"""
if device.startswith("cuda"):
event_classify.preprocessing.use_gpu()
out_file = open(output_name, "w")
ids = open("d-prose/d-prose_ids.csv")
# skip header
_ = next(ids)
nlp = build_pipeline(Parser.SPACY)
for dprose_id, name in tqdm([line.split(",") for line in ids]):
# We want to throw out the previous iterations memory
# doc = None
# gc.collect()
# This way we might not run out of memory after a few docs...
dprose_id = int(dprose_id)
name = name.strip()
in_file = open(os.path.join("d-prose", name + ".txt"))
full_text = "".join(in_file.readlines())
splits = split_text(full_text)
# Sanity check, splitting should not change text!
assert full_text == "".join(split.text for split in splits)
data = {"text": full_text, "title": name, "annotations": []}
for split in splits:
doc = nlp(split.text)
annotations = event_classify.preprocessing.get_annotation_dicts(doc)
for annotation in annotations:
annotation["start"] += split.offset
annotation["end"] += split.offset
new_spans = []
for span in annotation["spans"]:
new_spans.append(
(
span[0] + split.offset,
span[1] + split.offset,
)
)
annotation["spans"] = new_spans
data["annotations"].extend(annotations)
towards_end = data["annotations"][-10]
print(full_text[towards_end["start"] : towards_end["end"]])
dataset = JSONDataset(
dataset_file=None, data=[data], include_special_tokens=special_tokens
)
loader = DataLoader(
dataset,
batch_size=batch_size,
collate_fn=lambda list_: SpanAnnotation.to_batch(list_, tokenizer),
)
model, tokenizer = get_model(model_path)
model.to(device)
evaluation_result = evaluate(loader, model, device=device)
# We only pass in one document, so we only use [0]
data = dataset.get_annotation_json(evaluation_result)[0]
data["dprose_id"] = dprose_id
json.dump(data, out_file)
out_file.flush()
out_file.write("\n")
out_file.flush()
@app.command()
def plain_text_file(
model_path: str,
in_name: str,
output_name: str,
device: str = "cuda:0",
special_tokens: bool = True,
batch_size: int = 8,
):
"""
Predict a plain text file.
"""
if device.startswith("cuda"):
event_classify.preprocessing.use_gpu()
out_file = open(output_name, "w")
nlp = build_pipeline(Parser.SPACY)
in_file = open(in_name, "r", encoding="utf-8")
full_text = "".join(in_file.readlines())
splits = split_text(full_text)
# Sanity check, splitting should change text!
assert full_text == "".join(split.text for split in splits)
data = {"text": full_text, "title": os.path.basename(in_name), "annotations": []}
for split in splits:
doc = nlp(split.text)
annotations = event_classify.preprocessing.get_annotation_dicts(doc)
for annotation in annotations:
annotation["start"] += split.offset
annotation["end"] += split.offset
new_spans = []
for span in annotation["spans"]:
new_spans.append(
(
span[0] + split.offset,
span[1] + split.offset,
)
)
annotation["spans"] = new_spans
data["annotations"].extend(annotations)
dataset = JSONDataset(
dataset_file=None, data=[data], include_special_tokens=special_tokens
)
loader = DataLoader(
dataset,
batch_size=batch_size,
collate_fn=lambda list_: SpanAnnotation.to_batch(list_, tokenizer),
)
model, tokenizer = get_model(model_path)
model.to(device)
evaluation_result = evaluate(loader, model, device=device)
# We only pass in one document, so we only use [0]
data = dataset.get_annotation_json(evaluation_result)[0]
json.dump(data, out_file)
out_file.flush()
out_file.write("\n")
out_file.flush()
if __name__ == "__main__":
app()