christophalt
commited on
Commit
·
298e310
1
Parent(s):
baa2a47
Upload conll2003.py
Browse files- conll2003.py +56 -0
conll2003.py
ADDED
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from dataclasses import dataclass
|
2 |
+
|
3 |
+
import pytorch_ie.data.builder
|
4 |
+
from pytorch_ie.annotations import AnnotationList, LabeledSpan
|
5 |
+
from pytorch_ie.document import TextDocument, annotation_field
|
6 |
+
|
7 |
+
# import tests.data.test_new_document_and_datasets
|
8 |
+
from pytorch_ie.utils.span import bio_tags_to_spans
|
9 |
+
|
10 |
+
# from tests.data.test_new_document_and_datasets import (
|
11 |
+
# AnnotationList,
|
12 |
+
# Document,
|
13 |
+
# LabeledSpan,
|
14 |
+
# annotation_field,
|
15 |
+
# )
|
16 |
+
|
17 |
+
|
18 |
+
@dataclass
|
19 |
+
class CoNLL2003Document(TextDocument):
|
20 |
+
entities: AnnotationList[LabeledSpan] = annotation_field(target="text")
|
21 |
+
|
22 |
+
|
23 |
+
class Conll2003(pytorch_ie.data.builder.GeneratorBasedBuilder):
|
24 |
+
DOCUMENT_TYPE = CoNLL2003Document
|
25 |
+
|
26 |
+
BASE_PATH = "conll2003"
|
27 |
+
|
28 |
+
def _generate_document_kwargs(self, dataset):
|
29 |
+
return {"int_to_str": dataset.features["ner_tags"].feature.int2str}
|
30 |
+
|
31 |
+
def _generate_document(self, example, int_to_str):
|
32 |
+
doc_id = example["id"]
|
33 |
+
tokens = example["tokens"]
|
34 |
+
ner_tags = example["ner_tags"]
|
35 |
+
|
36 |
+
start = 0
|
37 |
+
token_offsets = []
|
38 |
+
tag_sequence = []
|
39 |
+
for token, tag_id in zip(tokens, ner_tags):
|
40 |
+
end = start + len(token)
|
41 |
+
token_offsets.append((start, end))
|
42 |
+
tag_sequence.append(int_to_str(tag_id))
|
43 |
+
|
44 |
+
start = end + 1
|
45 |
+
|
46 |
+
text = " ".join(tokens)
|
47 |
+
spans = bio_tags_to_spans(tag_sequence)
|
48 |
+
|
49 |
+
document = CoNLL2003Document(text=text, id=doc_id)
|
50 |
+
|
51 |
+
for label, (start, end) in spans:
|
52 |
+
start_offset = token_offsets[start][0]
|
53 |
+
end_offset = token_offsets[end][1]
|
54 |
+
document.entities.append(LabeledSpan(start=start_offset, end=end_offset, label=label))
|
55 |
+
|
56 |
+
return document
|