File size: 7,993 Bytes
196184d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2fa3d6f
 
196184d
 
 
22958d5
196184d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da81c3c
 
 
196184d
 
 
 
 
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
"""The Argumentative Microtext Corpus for German and English Argumentation Mining."""
import glob
import logging
import os
from os.path import abspath, isdir
from pathlib import Path
from xml.etree import ElementTree

import datasets

_CITATION = """\
@inproceedings{peldszus2015annotated,
  title={An annotated corpus of argumentative microtexts},
  author={Peldszus, Andreas and Stede, Manfred},
  booktitle={Argumentation and Reasoned Action: Proceedings of the 1st European Conference on Argumentation, Lisbon},
  volume={2},
  pages={801--815},
  year={2015}
}
"""

_DESCRIPTION = "The Argumentative Microtext Corpus for German and English Argumentation Mining."

_HOMEPAGE = "http://angcl.ling.uni-potsdam.de/resources/argmicro.html"

_LICENSE = "Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License, see https://creativecommons.org/licenses/by-nc-sa/4.0/"


# The HuggingFace dataset library don't host the datasets but only point to the original files
# This can be an arbitrary nested dict/list of URLs (see below in `_split_generators` method)
_URL = "https://github.com/peldszus/arg-microtexts/archive/refs/heads/master.zip"

_VERSION = datasets.Version("1.0.0")

_STANCE_CLASS_LABELS = ["con", "pro", "unclear", "UNDEFINED"]
_ADU_CLASS_LABELS = ["opp", "pro"]
_EDGE_CLASS_LABELS = ["seg", "sup", "exa", "add", "reb", "und"]


logger = logging.getLogger(__name__)


class ArgMicro(datasets.GeneratorBasedBuilder):
    """ArgMicro is a argumentation mining dataset."""

    BUILDER_CONFIGS = [
        datasets.BuilderConfig(name="en"),
        datasets.BuilderConfig(name="de"),
    ]

    def _info(self):
        features = datasets.Features(
            {
                "id": datasets.Value("string"),
                "topic_id": datasets.Value("string"),
                "stance": datasets.ClassLabel(names=_STANCE_CLASS_LABELS),
                "text": datasets.Value("string"),
                "edus": datasets.Sequence(
                    {
                        "id": datasets.Value("string"),
                        "start": datasets.Value("int32"),
                        "end": datasets.Value("int32"),
                    }
                ),
                "adus": datasets.Sequence(
                    {
                        "id": datasets.Value("string"),
                        "type": datasets.ClassLabel(names=_ADU_CLASS_LABELS),
                    }
                ),
                "edges": datasets.Sequence(
                    {
                        "id": datasets.Value("string"),
                        "src": datasets.Value("string"),
                        "trg": datasets.Value("string"),
                        "type": datasets.ClassLabel(names=_EDGE_CLASS_LABELS),
                    }
                ),
            }
        )

        return datasets.DatasetInfo(
            # This is the description that will appear on the datasets page.
            description=_DESCRIPTION,
            # This defines the different columns of the dataset and their types
            features=features,  # Here we define them above because they are different between the two configurations
            # If there's a common (input, target) tuple from the features,
            # specify them here. They'll be used if as_supervised=True in
            # builder.as_dataset.
            supervised_keys=None,
            # Homepage of the dataset for documentation
            homepage=_HOMEPAGE,
            # License for the dataset if available
            license=_LICENSE,
            # Citation for the dataset
            citation=_CITATION,
        )

    def _split_generators(self, dl_manager):
        """Returns SplitGenerators."""
        # If several configurations are possible (listed in BUILDER_CONFIGS), the configuration selected by the user is in self.config.name

        # dl_manager is a datasets.download.DownloadManager that can be used to download and extract URLs
        # It can accept any type or nested list/dict and will give back the same structure with the url replaced with path to local files.
        # By default the archives will be extracted and a path to a cached folder where they are extracted is returned instead of the archive

        if dl_manager.manual_dir is not None:
            base_path = abspath(dl_manager.manual_dir)
            if not isdir(base_path):
                base_path = os.path.join(dl_manager.extract(base_path), "arg-microtexts-master")
        else:
            base_path = os.path.join(
                dl_manager.download_and_extract(_URL), "arg-microtexts-master"
            )
        base_path = Path(base_path) / "corpus"

        dtd = None
        etree = None
        try:
            from lxml import etree

            # dtd = etree.DTD(base_path / "arggraph.dtd")
        except ModuleNotFoundError:
            logger.warning("lxml not installed. Skipping DTD validation.")

        return [
            datasets.SplitGenerator(
                name=datasets.Split.TRAIN,
                gen_kwargs={"path": base_path / self.config.name, "dtd": dtd, "etree": etree},
            ),
        ]

    def _generate_examples(self, path, dtd=None, etree=None):
        """Yields examples."""
        # This method will receive as arguments the `gen_kwargs` defined in the previous `_split_generators` method.
        # It is in charge of opening the given file and yielding (key, example) tuples from the dataset
        # The key is not important, it's more here for legacy reason (legacy from tfds)

        _id = 0
        text_file_names = sorted(glob.glob(f"{path}/*.txt"))
        if len(text_file_names) == 0:
            raise Exception(f"No text files found in {path}. Did you set the correct data_dir?")
        invalid_files = []
        for text_file_name in text_file_names:
            txt_fn = Path(text_file_name)
            ann_fn = txt_fn.with_suffix(".xml")
            with open(txt_fn, encoding="utf-8") as f:
                text = f.read()

            # validate xml file, if dtd is available
            if dtd is not None and etree is not None:
                e = etree.parse(ann_fn)
                v = dtd.validate(e)
                if not v:
                    logger.error(f"{ann_fn} is INVALID:")
                    logger.error(dtd.error_log.filter_from_errors()[0])
                    invalid_files.append(ann_fn)
                    continue

            annotations = ElementTree.parse(ann_fn).getroot()
            edus = []
            start_pos = 0
            for edu in annotations.findall("edu"):
                start = text.find(edu.text, start_pos)
                if start == -1:
                    raise Exception(f"Cannot find {edu.text} in {text}")
                end = start + len(edu.text)
                edus.append({"id": edu.attrib["id"], "start": start, "end": end})
                start_pos = end
            adus = [
                {"id": adu.attrib["id"], "type": adu.attrib["type"]}
                for adu in annotations.findall("adu")
            ]
            edges = [
                {
                    "id": edge.attrib["id"],
                    "src": edge.attrib["src"],
                    "trg": edge.attrib["trg"],
                    "type": edge.attrib["type"],
                }
                for edge in annotations.findall("edge")
            ]
            yield _id, {
                "id": annotations.attrib["id"],
                "topic_id": annotations.attrib.get("topic_id", "UNDEFINED"),
                "stance": annotations.attrib.get("stance", "UNDEFINED"),
                "text": text,
                "edus": sorted(edus, key=lambda x: x["id"]),
                "adus": sorted(adus, key=lambda x: x["id"]),
                "edges": sorted(edges, key=lambda x: x["id"]),
            }
            _id += 1

        if len(invalid_files) > 0:
            raise Exception(f"Found {len(invalid_files)} invalid files: {invalid_files}")