https://github.com/ArneBinder/pie-datasets/pull/100
Browse files- README.md +144 -1
- img/rtd-label_scitdb-argmin.png +3 -0
- img/slt_scitdb-argmin.png +3 -0
- img/tl_scidtb-argmin.png +3 -0
- requirements.txt +2 -2
- scidtb_argmin.py +173 -173
README.md
CHANGED
|
@@ -3,11 +3,32 @@
|
|
| 3 |
This is a [PyTorch-IE](https://github.com/ChristophAlt/pytorch-ie) wrapper for the
|
| 4 |
[SciDTB ArgMin Huggingface dataset loading script](https://huggingface.co/datasets/DFKI-SLT/scidtb_argmin).
|
| 5 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
## Data Schema
|
| 7 |
|
| 8 |
The document type for this dataset is `SciDTBArgminDocument` which defines the following data fields:
|
| 9 |
|
| 10 |
-
- `tokens` (
|
| 11 |
- `id` (str, optional)
|
| 12 |
- `metadata` (dictionary, optional)
|
| 13 |
|
|
@@ -23,6 +44,128 @@ See [here](https://github.com/ChristophAlt/pytorch-ie/blob/main/src/pytorch_ie/a
|
|
| 23 |
The dataset provides document converters for the following target document types:
|
| 24 |
|
| 25 |
- `pytorch_ie.documents.TextDocumentWithLabeledSpansAndBinaryRelations`
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
See [here](https://github.com/ChristophAlt/pytorch-ie/blob/main/src/pytorch_ie/documents.py) for the document type
|
| 28 |
definitions.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
This is a [PyTorch-IE](https://github.com/ChristophAlt/pytorch-ie) wrapper for the
|
| 4 |
[SciDTB ArgMin Huggingface dataset loading script](https://huggingface.co/datasets/DFKI-SLT/scidtb_argmin).
|
| 5 |
|
| 6 |
+
## Usage
|
| 7 |
+
|
| 8 |
+
```python
|
| 9 |
+
from pie_datasets import load_dataset
|
| 10 |
+
from pytorch_ie.documents import TextDocumentWithLabeledSpansAndBinaryRelations
|
| 11 |
+
|
| 12 |
+
# load English variant
|
| 13 |
+
dataset = load_dataset("pie/scidtb_argmin")
|
| 14 |
+
|
| 15 |
+
# if required, normalize the document type (see section Document Converters below)
|
| 16 |
+
dataset_converted = dataset.to_document_type(TextDocumentWithLabeledSpansAndBinaryRelations)
|
| 17 |
+
assert isinstance(dataset_converted["train"][0], TextDocumentWithLabeledSpansAndBinaryRelations)
|
| 18 |
+
|
| 19 |
+
# get first relation in the first document
|
| 20 |
+
doc = dataset_converted["train"][0]
|
| 21 |
+
print(doc.binary_relations[0])
|
| 22 |
+
# BinaryRelation(head=LabeledSpan(start=251, end=454, label='means', score=1.0), tail=LabeledSpan(start=455, end=712, label='proposal', score=1.0), label='detail', score=1.0)
|
| 23 |
+
print(doc.binary_relations[0].resolve())
|
| 24 |
+
# ('detail', (('means', 'We observe , identify , and detect naturally occurring signals of interestingness in click transitions on the Web between source and target documents , which we collect from commercial Web browser logs .'), ('proposal', 'The DSSM is trained on millions of Web transitions , and maps source-target document pairs to feature vectors in a latent space in such a way that the distance between source documents and their corresponding interesting targets in that space is minimized .')))
|
| 25 |
+
```
|
| 26 |
+
|
| 27 |
## Data Schema
|
| 28 |
|
| 29 |
The document type for this dataset is `SciDTBArgminDocument` which defines the following data fields:
|
| 30 |
|
| 31 |
+
- `tokens` (tuple of string)
|
| 32 |
- `id` (str, optional)
|
| 33 |
- `metadata` (dictionary, optional)
|
| 34 |
|
|
|
|
| 44 |
The dataset provides document converters for the following target document types:
|
| 45 |
|
| 46 |
- `pytorch_ie.documents.TextDocumentWithLabeledSpansAndBinaryRelations`
|
| 47 |
+
- `labeled_spans`: `LabeledSpan` annotations, converted from`SciDTBArgminDocument`'s `units`
|
| 48 |
+
- labels: `proposal`, `assertion`, `result`, `observation`, `means`, `description`
|
| 49 |
+
- tuples of `tokens` are joined with a whitespace to create `text` for `LabeledSpans`
|
| 50 |
+
- `binary_relations`: `BinaryRelation` annotations, converted from `SciDTBArgminDocument`'s `relations`
|
| 51 |
+
- labels: `support`, `attack`, `additional`, `detail`, `sequence`
|
| 52 |
|
| 53 |
See [here](https://github.com/ChristophAlt/pytorch-ie/blob/main/src/pytorch_ie/documents.py) for the document type
|
| 54 |
definitions.
|
| 55 |
+
|
| 56 |
+
### Collected Statistics after Document Conversion
|
| 57 |
+
|
| 58 |
+
We use the script `evaluate_documents.py` from [PyTorch-IE-Hydra-Template](https://github.com/ArneBinder/pytorch-ie-hydra-template-1) to generate these statistics.
|
| 59 |
+
After checking out that code, the statistics and plots can be generated by the command:
|
| 60 |
+
|
| 61 |
+
```commandline
|
| 62 |
+
python src/evaluate_documents.py dataset=scidtb_argmin_base metric=METRIC
|
| 63 |
+
```
|
| 64 |
+
|
| 65 |
+
where a `METRIC` is called according to the available metric configs in `config/metric/METRIC` (see [metrics](https://github.com/ArneBinder/pytorch-ie-hydra-template-1/tree/main/configs/metric)).
|
| 66 |
+
|
| 67 |
+
This also requires to have the following dataset config in `configs/dataset/scidtb_argmin_base.yaml` of this dataset within the repo directory:
|
| 68 |
+
|
| 69 |
+
```commandline
|
| 70 |
+
_target_: src.utils.execute_pipeline
|
| 71 |
+
input:
|
| 72 |
+
_target_: pie_datasets.DatasetDict.load_dataset
|
| 73 |
+
path: pie/scidtb_argmin
|
| 74 |
+
revision: 335a8e6168919d7f204c6920eceb96745dbd161b
|
| 75 |
+
```
|
| 76 |
+
|
| 77 |
+
For token based metrics, this uses `bert-base-uncased` from `transformer.AutoTokenizer` (see [AutoTokenizer](https://huggingface.co/docs/transformers/v4.37.1/en/model_doc/auto#transformers.AutoTokenizer), and [bert-based-uncased](https://huggingface.co/bert-base-uncased) to tokenize `text` in `TextDocumentWithLabeledSpansAndBinaryRelations` (see [document type](https://github.com/ChristophAlt/pytorch-ie/blob/main/src/pytorch_ie/documents.py)).
|
| 78 |
+
|
| 79 |
+
#### Relation argument (outer) token distance per label
|
| 80 |
+
|
| 81 |
+
The distance is measured from the first token of the first argumentative unit to the last token of the last unit, a.k.a. outer distance.
|
| 82 |
+
|
| 83 |
+
We collect the following statistics: number of documents in the split (*no. doc*), no. of relations (*len*), mean of token distance (*mean*), standard deviation of the distance (*std*), minimum outer distance (*min*), and maximum outer distance (*max*).
|
| 84 |
+
We also present histograms in the collapsible, showing the distribution of these relation distances (x-axis; and unit-counts in y-axis), accordingly.
|
| 85 |
+
|
| 86 |
+
<details>
|
| 87 |
+
<summary>Command</summary>
|
| 88 |
+
|
| 89 |
+
```
|
| 90 |
+
python src/evaluate_documents.py dataset=scidtb_argmin_base metric=relation_argument_token_distances
|
| 91 |
+
```
|
| 92 |
+
|
| 93 |
+
</details>
|
| 94 |
+
|
| 95 |
+
| | len | max | mean | min | std |
|
| 96 |
+
| :--------- | --: | --: | -----: | --: | -----: |
|
| 97 |
+
| ALL | 586 | 277 | 75.239 | 21 | 40.312 |
|
| 98 |
+
| additional | 54 | 180 | 59.593 | 36 | 29.306 |
|
| 99 |
+
| detail | 258 | 163 | 65.62 | 22 | 29.21 |
|
| 100 |
+
| sequence | 22 | 93 | 59.727 | 38 | 17.205 |
|
| 101 |
+
| support | 252 | 277 | 89.794 | 21 | 48.118 |
|
| 102 |
+
|
| 103 |
+
<details>
|
| 104 |
+
<summary>Histogram (split: train, 60 documents)</summary>
|
| 105 |
+
|
| 106 |
+

|
| 107 |
+
|
| 108 |
+
</details>
|
| 109 |
+
|
| 110 |
+
#### Span lengths (tokens)
|
| 111 |
+
|
| 112 |
+
The span length is measured from the first token of the first argumentative unit to the last token of the particular unit.
|
| 113 |
+
|
| 114 |
+
We collect the following statistics: number of documents in the split (*no. doc*), no. of spans (*len*), mean of number of tokens in a span (*mean*), standard deviation of the number of tokens (*std*), minimum tokens in a span (*min*), and maximum tokens in a span (*max*).
|
| 115 |
+
We also present histograms in the collapsible, showing the distribution of these token-numbers (x-axis; and unit-counts in y-axis), accordingly.
|
| 116 |
+
|
| 117 |
+
<details>
|
| 118 |
+
<summary>Command</summary>
|
| 119 |
+
|
| 120 |
+
```
|
| 121 |
+
python src/evaluate_documents.py dataset=scidtb_argmin_base metric=span_lengths_tokens
|
| 122 |
+
```
|
| 123 |
+
|
| 124 |
+
</details>
|
| 125 |
+
|
| 126 |
+
| statistics | train |
|
| 127 |
+
| :--------- | -----: |
|
| 128 |
+
| no. doc | 60 |
|
| 129 |
+
| len | 353 |
|
| 130 |
+
| mean | 27.946 |
|
| 131 |
+
| std | 13.054 |
|
| 132 |
+
| min | 7 |
|
| 133 |
+
| max | 123 |
|
| 134 |
+
|
| 135 |
+
<details>
|
| 136 |
+
<summary>Histogram (split: train, 60 documents)</summary>
|
| 137 |
+
|
| 138 |
+

|
| 139 |
+
|
| 140 |
+
</details>
|
| 141 |
+
|
| 142 |
+
#### Token length (tokens)
|
| 143 |
+
|
| 144 |
+
The token length is measured from the first token of the document to the last one.
|
| 145 |
+
|
| 146 |
+
We collect the following statistics: number of documents in the split (*no. doc*), mean of document token-length (*mean*), standard deviation of the length (*std*), minimum number of tokens in a document (*min*), and maximum number of tokens in a document (*max*).
|
| 147 |
+
We also present histograms in the collapsible, showing the distribution of these token lengths (x-axis; and unit-counts in y-axis), accordingly.
|
| 148 |
+
|
| 149 |
+
<details>
|
| 150 |
+
<summary>Command</summary>
|
| 151 |
+
|
| 152 |
+
```
|
| 153 |
+
python src/evaluate_documents.py dataset=scidtb_argmin_base metric=count_text_tokens
|
| 154 |
+
```
|
| 155 |
+
|
| 156 |
+
</details>
|
| 157 |
+
|
| 158 |
+
| statistics | train |
|
| 159 |
+
| :--------- | ------: |
|
| 160 |
+
| no. doc | 60 |
|
| 161 |
+
| mean | 164.417 |
|
| 162 |
+
| std | 64.572 |
|
| 163 |
+
| min | 80 |
|
| 164 |
+
| max | 532 |
|
| 165 |
+
|
| 166 |
+
<details>
|
| 167 |
+
<summary>Histogram (split: train, 60 documents)</summary>
|
| 168 |
+
|
| 169 |
+

|
| 170 |
+
|
| 171 |
+
</details>
|
img/rtd-label_scitdb-argmin.png
ADDED
|
Git LFS Details
|
img/slt_scitdb-argmin.png
ADDED
|
Git LFS Details
|
img/tl_scidtb-argmin.png
ADDED
|
Git LFS Details
|
requirements.txt
CHANGED
|
@@ -1,2 +1,2 @@
|
|
| 1 |
-
pie-datasets>=0.6.0,<0.
|
| 2 |
-
pie-modules>=0.8.0,<0.
|
|
|
|
| 1 |
+
pie-datasets>=0.6.0,<0.11.0
|
| 2 |
+
pie-modules>=0.8.0,<0.12.0
|
scidtb_argmin.py
CHANGED
|
@@ -1,173 +1,173 @@
|
|
| 1 |
-
import dataclasses
|
| 2 |
-
import logging
|
| 3 |
-
from typing import Any, Dict, List, Tuple
|
| 4 |
-
|
| 5 |
-
import datasets
|
| 6 |
-
from pie_modules.document.processing import token_based_document_to_text_based
|
| 7 |
-
from pytorch_ie.annotations import BinaryRelation, LabeledSpan
|
| 8 |
-
from pytorch_ie.core import AnnotationList, annotation_field
|
| 9 |
-
from pytorch_ie.documents import (
|
| 10 |
-
TextDocumentWithLabeledSpansAndBinaryRelations,
|
| 11 |
-
TokenBasedDocument,
|
| 12 |
-
)
|
| 13 |
-
from pytorch_ie.utils.span import bio_tags_to_spans
|
| 14 |
-
|
| 15 |
-
from pie_datasets import GeneratorBasedBuilder
|
| 16 |
-
|
| 17 |
-
log = logging.getLogger(__name__)
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
def labels_and_spans_to_bio_tags(
|
| 21 |
-
labels: List[str], spans: List[Tuple[int, int]], sequence_length: int
|
| 22 |
-
) -> List[str]:
|
| 23 |
-
bio_tags = ["O"] * sequence_length
|
| 24 |
-
for label, (start, end) in zip(labels, spans):
|
| 25 |
-
bio_tags[start] = f"B-{label}"
|
| 26 |
-
for i in range(start + 1, end):
|
| 27 |
-
bio_tags[i] = f"I-{label}"
|
| 28 |
-
return bio_tags
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
@dataclasses.dataclass
|
| 32 |
-
class SciDTBArgminDocument(TokenBasedDocument):
|
| 33 |
-
units: AnnotationList[LabeledSpan] = annotation_field(target="tokens")
|
| 34 |
-
relations: AnnotationList[BinaryRelation] = annotation_field(target="units")
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
@dataclasses.dataclass
|
| 38 |
-
class SimplifiedSciDTBArgminDocument(TokenBasedDocument):
|
| 39 |
-
labeled_spans: AnnotationList[LabeledSpan] = annotation_field(target="tokens")
|
| 40 |
-
binary_relations: AnnotationList[BinaryRelation] = annotation_field(target="labeled_spans")
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
def example_to_document(
|
| 44 |
-
example: Dict[str, Any],
|
| 45 |
-
unit_bio: datasets.ClassLabel,
|
| 46 |
-
unit_label: datasets.ClassLabel,
|
| 47 |
-
relation: datasets.ClassLabel,
|
| 48 |
-
):
|
| 49 |
-
document = SciDTBArgminDocument(id=example["id"], tokens=tuple(example["data"]["token"]))
|
| 50 |
-
bio_tags = unit_bio.int2str(example["data"]["unit-bio"])
|
| 51 |
-
unit_labels = unit_label.int2str(example["data"]["unit-label"])
|
| 52 |
-
roles = relation.int2str(example["data"]["role"])
|
| 53 |
-
tag_sequence = [
|
| 54 |
-
f"{bio}-{label}|{role}|{parent_offset}"
|
| 55 |
-
for bio, label, role, parent_offset in zip(
|
| 56 |
-
bio_tags, unit_labels, roles, example["data"]["parent-offset"]
|
| 57 |
-
)
|
| 58 |
-
]
|
| 59 |
-
spans_with_label = sorted(
|
| 60 |
-
bio_tags_to_spans(tag_sequence), key=lambda label_and_span: label_and_span[1][0]
|
| 61 |
-
)
|
| 62 |
-
labels, spans = zip(*spans_with_label)
|
| 63 |
-
span_unit_labels, span_roles, span_parent_offsets = zip(
|
| 64 |
-
*[label.split("|") for label in labels]
|
| 65 |
-
)
|
| 66 |
-
|
| 67 |
-
units = [
|
| 68 |
-
LabeledSpan(start=start, end=end + 1, label=label)
|
| 69 |
-
for (start, end), label in zip(spans, span_unit_labels)
|
| 70 |
-
]
|
| 71 |
-
document.units.extend(units)
|
| 72 |
-
|
| 73 |
-
# The relation direction is as in "f{head} {relation_label} {tail}"
|
| 74 |
-
relations = []
|
| 75 |
-
for idx, parent_offset in enumerate(span_parent_offsets):
|
| 76 |
-
if span_roles[idx] != "none":
|
| 77 |
-
relations.append(
|
| 78 |
-
BinaryRelation(
|
| 79 |
-
head=units[idx], tail=units[idx + int(parent_offset)], label=span_roles[idx]
|
| 80 |
-
)
|
| 81 |
-
)
|
| 82 |
-
|
| 83 |
-
document.relations.extend(relations)
|
| 84 |
-
|
| 85 |
-
return document
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
def document_to_example(
|
| 89 |
-
document: SciDTBArgminDocument,
|
| 90 |
-
unit_bio: datasets.ClassLabel,
|
| 91 |
-
unit_label: datasets.ClassLabel,
|
| 92 |
-
relation: datasets.ClassLabel,
|
| 93 |
-
) -> Dict[str, Any]:
|
| 94 |
-
unit2idx = {unit: idx for idx, unit in enumerate(document.units)}
|
| 95 |
-
unit2parent_relation = {relation.head: relation for relation in document.relations}
|
| 96 |
-
|
| 97 |
-
unit_labels = [unit.label for unit in document.units]
|
| 98 |
-
roles = [
|
| 99 |
-
unit2parent_relation[unit].label if unit in unit2parent_relation else "none"
|
| 100 |
-
for unit in document.units
|
| 101 |
-
]
|
| 102 |
-
parent_offsets = [
|
| 103 |
-
unit2idx[unit2parent_relation[unit].tail] - idx if unit in unit2parent_relation else 0
|
| 104 |
-
for idx, unit in enumerate(document.units)
|
| 105 |
-
]
|
| 106 |
-
labels = [
|
| 107 |
-
f"{unit_label}-{role}-{parent_offset}"
|
| 108 |
-
for unit_label, role, parent_offset in zip(unit_labels, roles, parent_offsets)
|
| 109 |
-
]
|
| 110 |
-
|
| 111 |
-
tag_sequence = labels_and_spans_to_bio_tags(
|
| 112 |
-
labels=labels,
|
| 113 |
-
spans=[(unit.start, unit.end) for unit in document.units],
|
| 114 |
-
sequence_length=len(document.tokens),
|
| 115 |
-
)
|
| 116 |
-
bio_tags, unit_labels, roles, parent_offsets = zip(
|
| 117 |
-
*[tag.split("-", maxsplit=3) for tag in tag_sequence]
|
| 118 |
-
)
|
| 119 |
-
|
| 120 |
-
data = {
|
| 121 |
-
"token": list(document.tokens),
|
| 122 |
-
"unit-bio": unit_bio.str2int(bio_tags),
|
| 123 |
-
"unit-label": unit_label.str2int(unit_labels),
|
| 124 |
-
"role": relation.str2int(roles),
|
| 125 |
-
"parent-offset": [int(idx_str) for idx_str in parent_offsets],
|
| 126 |
-
}
|
| 127 |
-
result = {"id": document.id, "data": data}
|
| 128 |
-
return result
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
def convert_to_text_document_with_labeled_spans_and_binary_relations(
|
| 132 |
-
document: SciDTBArgminDocument,
|
| 133 |
-
) -> TextDocumentWithLabeledSpansAndBinaryRelations:
|
| 134 |
-
doc_simplified = document.as_type(
|
| 135 |
-
SimplifiedSciDTBArgminDocument,
|
| 136 |
-
field_mapping={"units": "labeled_spans", "relations": "binary_relations"},
|
| 137 |
-
)
|
| 138 |
-
result = token_based_document_to_text_based(
|
| 139 |
-
doc_simplified,
|
| 140 |
-
result_document_type=TextDocumentWithLabeledSpansAndBinaryRelations,
|
| 141 |
-
join_tokens_with=" ",
|
| 142 |
-
)
|
| 143 |
-
return result
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
class SciDTBArgmin(GeneratorBasedBuilder):
|
| 147 |
-
DOCUMENT_TYPE = SciDTBArgminDocument
|
| 148 |
-
|
| 149 |
-
DOCUMENT_CONVERTERS = {
|
| 150 |
-
TextDocumentWithLabeledSpansAndBinaryRelations: convert_to_text_document_with_labeled_spans_and_binary_relations
|
| 151 |
-
}
|
| 152 |
-
|
| 153 |
-
BASE_DATASET_PATH = "DFKI-SLT/scidtb_argmin"
|
| 154 |
-
BASE_DATASET_REVISION = "8c02587edcb47ab5b102692bd10bfffd1844a09b"
|
| 155 |
-
|
| 156 |
-
BUILDER_CONFIGS = [datasets.BuilderConfig(name="default")]
|
| 157 |
-
|
| 158 |
-
DEFAULT_CONFIG_NAME = "default"
|
| 159 |
-
|
| 160 |
-
def _generate_document_kwargs(self, dataset):
|
| 161 |
-
return {
|
| 162 |
-
"unit_bio": dataset.features["data"].feature["unit-bio"],
|
| 163 |
-
"unit_label": dataset.features["data"].feature["unit-label"],
|
| 164 |
-
"relation": dataset.features["data"].feature["role"],
|
| 165 |
-
}
|
| 166 |
-
|
| 167 |
-
def _generate_document(self, example, unit_bio, unit_label, relation):
|
| 168 |
-
return example_to_document(
|
| 169 |
-
example,
|
| 170 |
-
unit_bio=unit_bio,
|
| 171 |
-
unit_label=unit_label,
|
| 172 |
-
relation=relation,
|
| 173 |
-
)
|
|
|
|
| 1 |
+
import dataclasses
|
| 2 |
+
import logging
|
| 3 |
+
from typing import Any, Dict, List, Tuple
|
| 4 |
+
|
| 5 |
+
import datasets
|
| 6 |
+
from pie_modules.document.processing import token_based_document_to_text_based
|
| 7 |
+
from pytorch_ie.annotations import BinaryRelation, LabeledSpan
|
| 8 |
+
from pytorch_ie.core import AnnotationList, annotation_field
|
| 9 |
+
from pytorch_ie.documents import (
|
| 10 |
+
TextDocumentWithLabeledSpansAndBinaryRelations,
|
| 11 |
+
TokenBasedDocument,
|
| 12 |
+
)
|
| 13 |
+
from pytorch_ie.utils.span import bio_tags_to_spans
|
| 14 |
+
|
| 15 |
+
from pie_datasets import GeneratorBasedBuilder
|
| 16 |
+
|
| 17 |
+
log = logging.getLogger(__name__)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def labels_and_spans_to_bio_tags(
|
| 21 |
+
labels: List[str], spans: List[Tuple[int, int]], sequence_length: int
|
| 22 |
+
) -> List[str]:
|
| 23 |
+
bio_tags = ["O"] * sequence_length
|
| 24 |
+
for label, (start, end) in zip(labels, spans):
|
| 25 |
+
bio_tags[start] = f"B-{label}"
|
| 26 |
+
for i in range(start + 1, end):
|
| 27 |
+
bio_tags[i] = f"I-{label}"
|
| 28 |
+
return bio_tags
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@dataclasses.dataclass
|
| 32 |
+
class SciDTBArgminDocument(TokenBasedDocument):
|
| 33 |
+
units: AnnotationList[LabeledSpan] = annotation_field(target="tokens")
|
| 34 |
+
relations: AnnotationList[BinaryRelation] = annotation_field(target="units")
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
@dataclasses.dataclass
|
| 38 |
+
class SimplifiedSciDTBArgminDocument(TokenBasedDocument):
|
| 39 |
+
labeled_spans: AnnotationList[LabeledSpan] = annotation_field(target="tokens")
|
| 40 |
+
binary_relations: AnnotationList[BinaryRelation] = annotation_field(target="labeled_spans")
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def example_to_document(
|
| 44 |
+
example: Dict[str, Any],
|
| 45 |
+
unit_bio: datasets.ClassLabel,
|
| 46 |
+
unit_label: datasets.ClassLabel,
|
| 47 |
+
relation: datasets.ClassLabel,
|
| 48 |
+
):
|
| 49 |
+
document = SciDTBArgminDocument(id=example["id"], tokens=tuple(example["data"]["token"]))
|
| 50 |
+
bio_tags = unit_bio.int2str(example["data"]["unit-bio"])
|
| 51 |
+
unit_labels = unit_label.int2str(example["data"]["unit-label"])
|
| 52 |
+
roles = relation.int2str(example["data"]["role"])
|
| 53 |
+
tag_sequence = [
|
| 54 |
+
f"{bio}-{label}|{role}|{parent_offset}"
|
| 55 |
+
for bio, label, role, parent_offset in zip(
|
| 56 |
+
bio_tags, unit_labels, roles, example["data"]["parent-offset"]
|
| 57 |
+
)
|
| 58 |
+
]
|
| 59 |
+
spans_with_label = sorted(
|
| 60 |
+
bio_tags_to_spans(tag_sequence), key=lambda label_and_span: label_and_span[1][0]
|
| 61 |
+
)
|
| 62 |
+
labels, spans = zip(*spans_with_label)
|
| 63 |
+
span_unit_labels, span_roles, span_parent_offsets = zip(
|
| 64 |
+
*[label.split("|") for label in labels]
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
units = [
|
| 68 |
+
LabeledSpan(start=start, end=end + 1, label=label)
|
| 69 |
+
for (start, end), label in zip(spans, span_unit_labels)
|
| 70 |
+
]
|
| 71 |
+
document.units.extend(units)
|
| 72 |
+
|
| 73 |
+
# The relation direction is as in "f{head} {relation_label} {tail}"
|
| 74 |
+
relations = []
|
| 75 |
+
for idx, parent_offset in enumerate(span_parent_offsets):
|
| 76 |
+
if span_roles[idx] != "none":
|
| 77 |
+
relations.append(
|
| 78 |
+
BinaryRelation(
|
| 79 |
+
head=units[idx], tail=units[idx + int(parent_offset)], label=span_roles[idx]
|
| 80 |
+
)
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
document.relations.extend(relations)
|
| 84 |
+
|
| 85 |
+
return document
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def document_to_example(
|
| 89 |
+
document: SciDTBArgminDocument,
|
| 90 |
+
unit_bio: datasets.ClassLabel,
|
| 91 |
+
unit_label: datasets.ClassLabel,
|
| 92 |
+
relation: datasets.ClassLabel,
|
| 93 |
+
) -> Dict[str, Any]:
|
| 94 |
+
unit2idx = {unit: idx for idx, unit in enumerate(document.units)}
|
| 95 |
+
unit2parent_relation = {relation.head: relation for relation in document.relations}
|
| 96 |
+
|
| 97 |
+
unit_labels = [unit.label for unit in document.units]
|
| 98 |
+
roles = [
|
| 99 |
+
unit2parent_relation[unit].label if unit in unit2parent_relation else "none"
|
| 100 |
+
for unit in document.units
|
| 101 |
+
]
|
| 102 |
+
parent_offsets = [
|
| 103 |
+
unit2idx[unit2parent_relation[unit].tail] - idx if unit in unit2parent_relation else 0
|
| 104 |
+
for idx, unit in enumerate(document.units)
|
| 105 |
+
]
|
| 106 |
+
labels = [
|
| 107 |
+
f"{unit_label}-{role}-{parent_offset}"
|
| 108 |
+
for unit_label, role, parent_offset in zip(unit_labels, roles, parent_offsets)
|
| 109 |
+
]
|
| 110 |
+
|
| 111 |
+
tag_sequence = labels_and_spans_to_bio_tags(
|
| 112 |
+
labels=labels,
|
| 113 |
+
spans=[(unit.start, unit.end) for unit in document.units],
|
| 114 |
+
sequence_length=len(document.tokens),
|
| 115 |
+
)
|
| 116 |
+
bio_tags, unit_labels, roles, parent_offsets = zip(
|
| 117 |
+
*[tag.split("-", maxsplit=3) for tag in tag_sequence]
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
data = {
|
| 121 |
+
"token": list(document.tokens),
|
| 122 |
+
"unit-bio": unit_bio.str2int(bio_tags),
|
| 123 |
+
"unit-label": unit_label.str2int(unit_labels),
|
| 124 |
+
"role": relation.str2int(roles),
|
| 125 |
+
"parent-offset": [int(idx_str) for idx_str in parent_offsets],
|
| 126 |
+
}
|
| 127 |
+
result = {"id": document.id, "data": data}
|
| 128 |
+
return result
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def convert_to_text_document_with_labeled_spans_and_binary_relations(
|
| 132 |
+
document: SciDTBArgminDocument,
|
| 133 |
+
) -> TextDocumentWithLabeledSpansAndBinaryRelations:
|
| 134 |
+
doc_simplified = document.as_type(
|
| 135 |
+
SimplifiedSciDTBArgminDocument,
|
| 136 |
+
field_mapping={"units": "labeled_spans", "relations": "binary_relations"},
|
| 137 |
+
)
|
| 138 |
+
result = token_based_document_to_text_based(
|
| 139 |
+
doc_simplified,
|
| 140 |
+
result_document_type=TextDocumentWithLabeledSpansAndBinaryRelations,
|
| 141 |
+
join_tokens_with=" ",
|
| 142 |
+
)
|
| 143 |
+
return result
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
class SciDTBArgmin(GeneratorBasedBuilder):
|
| 147 |
+
DOCUMENT_TYPE = SciDTBArgminDocument
|
| 148 |
+
|
| 149 |
+
DOCUMENT_CONVERTERS = {
|
| 150 |
+
TextDocumentWithLabeledSpansAndBinaryRelations: convert_to_text_document_with_labeled_spans_and_binary_relations
|
| 151 |
+
}
|
| 152 |
+
|
| 153 |
+
BASE_DATASET_PATH = "DFKI-SLT/scidtb_argmin"
|
| 154 |
+
BASE_DATASET_REVISION = "8c02587edcb47ab5b102692bd10bfffd1844a09b"
|
| 155 |
+
|
| 156 |
+
BUILDER_CONFIGS = [datasets.BuilderConfig(name="default")]
|
| 157 |
+
|
| 158 |
+
DEFAULT_CONFIG_NAME = "default"
|
| 159 |
+
|
| 160 |
+
def _generate_document_kwargs(self, dataset):
|
| 161 |
+
return {
|
| 162 |
+
"unit_bio": dataset.features["data"].feature["unit-bio"],
|
| 163 |
+
"unit_label": dataset.features["data"].feature["unit-label"],
|
| 164 |
+
"relation": dataset.features["data"].feature["role"],
|
| 165 |
+
}
|
| 166 |
+
|
| 167 |
+
def _generate_document(self, example, unit_bio, unit_label, relation):
|
| 168 |
+
return example_to_document(
|
| 169 |
+
example,
|
| 170 |
+
unit_bio=unit_bio,
|
| 171 |
+
unit_label=unit_label,
|
| 172 |
+
relation=relation,
|
| 173 |
+
)
|