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
 
 
5786d54
9bbe4fa
 
5786d54
 
 
 
ae7bfe4
5786d54
9bbe4fa
 
 
5786d54
9bbe4fa
 
5786d54
 
 
 
ae7bfe4
5786d54
9bbe4fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5786d54
9bbe4fa
5786d54
9bbe4fa
 
 
 
 
 
 
 
 
 
 
 
ae7bfe4
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
import logging
import os
import re
import xml.etree.ElementTree as ET
from itertools import groupby
from typing import Optional

import datasets

_CITATION = """\
@misc{solar3.0,
    title = {Developmental corpus {\v S}olar 3.0},
    author = {Arhar Holdt, {\v S}pela and Rozman, Tadeja and Stritar Ku{\v c}uk, Mojca and Krek, Simon and Krap{\v s} Vodopivec, Irena and Stabej, Marko and Pori, Eva and Goli, Teja and Lavri{\v c}, Polona and Laskowski, Cyprian and Kocjan{\v c}i{\v c}, Polonca and Klemenc, Bojan and Krsnik, Luka and Kosem, Iztok},
    url = {http://hdl.handle.net/11356/1589},
    note = {Slovenian language resource repository {CLARIN}.{SI}},
    year = {2022}
}
"""

_DESCRIPTION = """\
Šolar is a developmental corpus of 5485 school texts (e.g., essays), written by students in Slovenian secondary schools 
(age 15-19) and pupils in the 7th-9th grade of primary school (13-15), with a small percentage also from the 6th grade. 
Part of the corpus (1516 texts) is annotated with teachers' corrections using a system of labels described in the 
document available at https://www.clarin.si/repository/xmlui/bitstream/handle/11356/1589/Smernice-za-oznacevanje-korpusa-Solar_V1.1.pdf (in Slovenian).
"""

_HOMEPAGE = "http://hdl.handle.net/11356/1589"

_LICENSE = "Creative Commons - Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0)"

_URLS = {
    "solar_tei": "https://www.clarin.si/repository/xmlui/bitstream/handle/11356/1589/Solar.TEI.zip"
}

XML_NAMESPACE = "{http://www.w3.org/XML/1998/namespace}"


def namespace(element):
    # https://stackoverflow.com/a/12946675
    m = re.match(r'\{.*\}', element.tag)
    return m.group(0) if m else ''


def resolve_element(tag_el, ne_tag: Optional[str] = "O"):
    if not tag_el.tag.endswith(("w", "pc", "seg")):
        return []

    if tag_el.tag.endswith(("w", "pc")):
        form = tag_el.text.strip()
        lemma = tag_el.text.strip() if tag_el.tag.endswith("pc") else tag_el.attrib["lemma"]
        ana = tag_el.attrib["ana"]  # JOS/MTE specifications
        msd = tag_el.attrib["msd"]  # UD specifications
        ret_ne_tag = ne_tag
        id_tag = tag_el.attrib[f"{XML_NAMESPACE}id"]
        space_after = False if "join" in tag_el.attrib and tag_el.attrib["join"]=="right" else True

        return [(id_tag, form, lemma, ana, msd, ret_ne_tag, space_after)]
    # Named entities: words and punctuation nested directly below current element
    elif tag_el.tag.endswith("seg"):
        anns = []
        ret_ne_tag = tag_el.attrib["subtype"].upper()
        for idx_child, curr_child in enumerate(tag_el):
            anns.extend(resolve_element(curr_child, ne_tag=f"B-{ret_ne_tag}" if idx_child == 0 else f"I-{ret_ne_tag}"))

        return anns


def extract_sent_id(tok_id):
    # e.g., `extract_sent_id("#solar1s.3.2.44") == "solar1s.3.2"` or `extract_sent_id("solar1s.3.2.44") == "solar1s.3.2"`
    _tok_id = tok_id[1:] if tok_id.startswith("#") else tok_id
    return ".".join(_tok_id.split(".")[: -1])


def find_involved_sents(correction_group_el):
    src_sent_ids = set()
    tgt_sent_ids = set()
    for _curr_corr in correction_group_el:
        sent_ids = list(map(lambda _tok_id: extract_sent_id(_tok_id),
                            _curr_corr.attrib["target"].split(" ")))

        for _s_id in sent_ids:
            if "t" in _s_id:
                tgt_sent_ids.add(_s_id)
            else:
                src_sent_ids.add(_s_id)

    return sorted(list(src_sent_ids)), sorted(list(tgt_sent_ids))


def read_data(data_path):
    data = {}  # ID_sent -> sentence_metadata
    tree = ET.parse(data_path)
    root = tree.getroot()
    NAMESPACE = namespace(root)

    for curr_text in root.iterfind(f".//{NAMESPACE}div"):
        id_text = curr_text.attrib[f"{XML_NAMESPACE}id"]
        bibl_el = curr_text.find(f"{NAMESPACE}bibl")
        if bibl_el is None:
            text_title = "Unknown_title"
            logging.warning(f"The following text does not have a 'bibl' element: {curr_text.attrib}. "
                            f"Setting title to 'Unknown_title'")
            is_manually_validated = False
        else:
            text_title = bibl_el.attrib["n"]
            note_el = bibl_el.find(f"{NAMESPACE}note")
            is_manually_validated = note_el.text == "DA"

        for idx_par, curr_par in enumerate(curr_text.iterfind(f".//{NAMESPACE}p")):
            for idx_sent, curr_sent in enumerate(curr_par.iterfind(f".//{NAMESPACE}s")):
                id_sent = curr_sent.attrib[f"{XML_NAMESPACE}id"]
                ids, forms, lemmas, msds, nes, spaces_after = [], [], [], [], [], []
                msds_jos, msds_ud = [], []
                for curr_el in curr_sent:
                    curr_annotations = resolve_element(curr_el)
                    for curr_ann in curr_annotations:
                        ids.append(curr_ann[0])
                        forms.append(curr_ann[1])
                        lemmas.append(curr_ann[2])
                        msds_jos.append(curr_ann[3])
                        msds_ud.append(curr_ann[4])
                        nes.append(curr_ann[5])
                        spaces_after.append(curr_ann[6])

                data[id_sent] = {
                    "id_doc": id_text,
                    "doc_title": text_title,
                    "id_token": ids, "form": forms, "lemma": lemmas, "ana": msds_jos, "msd": msds_ud, "ne_tag": nes, "space_after": spaces_after,
                    "is_manually_validated": is_manually_validated
                }

    return data


class Solar3(datasets.GeneratorBasedBuilder):
    """Šolar is a developmental corpus of school texts (e.g., essays), annotated with metadata and (partially)
    with teachers' corrections. """

    VERSION = datasets.Version("3.0.2")

    BUILDER_CONFIGS = [
        datasets.BuilderConfig(name="sentence_level", version=VERSION,
                               description="Annotations at sentence-level."),
        datasets.BuilderConfig(name="document_level", version=VERSION,
                               description="Annotations at document-level."),
    ]

    DEFAULT_CONFIG_NAME = "sentence_level"  # default = annotations as provided in the original data

    def _info(self):
        features = datasets.Features(
            {
                "id_doc": datasets.Value("string"),
                "doc_title": datasets.Value("string"),
                "is_manually_validated": datasets.Value("bool"),
                "src_tokens": datasets.Sequence(datasets.Value("string")),
                "src_ling_annotations": {
                    "lemma": datasets.Sequence(datasets.Value("string")),
                    "ana": datasets.Sequence(datasets.Value("string")),
                    "msd": datasets.Sequence(datasets.Value("string")),
                    "ne_tag": datasets.Sequence(datasets.Value("string")),
                    "space_after": datasets.Sequence(datasets.Value("bool"))
                },
                "tgt_tokens": datasets.Sequence(datasets.Value("string")),
                "tgt_ling_annotations": {
                    "lemma": datasets.Sequence(datasets.Value("string")),
                    "ana": datasets.Sequence(datasets.Value("string")),
                    "msd": datasets.Sequence(datasets.Value("string")),
                    "ne_tag": datasets.Sequence(datasets.Value("string")),
                    "space_after": datasets.Sequence(datasets.Value("bool"))
                },
                "corrections": [
                    {
                        "idx_src": datasets.Sequence(datasets.Value("int32")),
                        "idx_tgt": datasets.Sequence(datasets.Value("int32")),
                        "corr_types": datasets.Sequence(datasets.Value("string"))
                    }
                ]
            }
        )

        return datasets.DatasetInfo(
            description=_DESCRIPTION,
            features=features,
            homepage=_HOMEPAGE,
            license=_LICENSE,
            citation=_CITATION,
        )

    def _split_generators(self, dl_manager):
        urls = _URLS["solar_tei"]
        data_dir = dl_manager.download_and_extract(urls)

        return [
            datasets.SplitGenerator(
                name=datasets.Split.TRAIN,
                # These kwargs will be passed to _generate_examples
                gen_kwargs={
                    "source_path": os.path.join(data_dir, "Solar.TEI", "solar-orig.xml"),
                    "target_path": os.path.join(data_dir, "Solar.TEI", "solar-corr.xml"),
                    "links_path": os.path.join(data_dir, "Solar.TEI", "solar-errs.xml")
                }
            )
        ]

    @staticmethod
    def generate_sentences(source_path, target_path, links_path):
        source_data = read_data(source_path)
        target_data = read_data(target_path)

        data = ET.parse(links_path)
        root = data.getroot()
        NAMESPACE = namespace(root)

        for idx_corr, corrected_sent in enumerate(root.iterfind(f"{NAMESPACE}linkGrp")):
            # Involved sentences according to the IDs of token mappings - 'corresp' does not list all of them!
            # (possible bug in data)
            involved_src_sents, involved_tgt_sents = find_involved_sents(corrected_sent)

            id_doc, doc_title, is_manually_validated = None, None, False
            src_sent_data, tgt_sent_data = {}, {}
            tok2position = {}
            assert len(involved_src_sents) > 0 or len(involved_tgt_sents) > 0

            if len(involved_src_sents) > 0:
                src_sent_data = source_data[involved_src_sents[0]]
                for src_sent_id in involved_src_sents[1:]:
                    curr_sent_data = source_data[src_sent_id]
                    src_sent_data["id_token"].extend(curr_sent_data["id_token"])
                    src_sent_data["form"].extend(curr_sent_data["form"])
                    src_sent_data["lemma"].extend(curr_sent_data["lemma"])
                    src_sent_data["ana"].extend(curr_sent_data["ana"])
                    src_sent_data["msd"].extend(curr_sent_data["msd"])
                    src_sent_data["ne_tag"].extend(curr_sent_data["ne_tag"])
                    src_sent_data["space_after"].extend(curr_sent_data["space_after"])

                id_doc = src_sent_data["id_doc"]
                doc_title = src_sent_data["doc_title"]
                is_manually_validated |= src_sent_data["is_manually_validated"]
                for _pos, _tok in enumerate(src_sent_data["id_token"]):
                    tok2position[_tok] = _pos

            if len(involved_tgt_sents) > 0:
                tgt_sent_data = target_data[involved_tgt_sents[0]]
                for tgt_sent_id in involved_tgt_sents[1:]:
                    curr_sent_data = target_data[tgt_sent_id]
                    tgt_sent_data["id_token"].extend(curr_sent_data["id_token"])
                    tgt_sent_data["form"].extend(curr_sent_data["form"])
                    tgt_sent_data["lemma"].extend(curr_sent_data["lemma"])
                    tgt_sent_data["ana"].extend(curr_sent_data["ana"])
                    tgt_sent_data["msd"].extend(curr_sent_data["msd"])
                    tgt_sent_data["ne_tag"].extend(curr_sent_data["ne_tag"])
                    tgt_sent_data["space_after"].extend(curr_sent_data["space_after"])

                id_doc = tgt_sent_data["id_doc"]
                doc_title = tgt_sent_data["doc_title"]
                is_manually_validated |= tgt_sent_data["is_manually_validated"]
                for _pos, _tok in enumerate(tgt_sent_data["id_token"]):
                    tok2position[_tok] = _pos

            corr_data = []
            for token_info in corrected_sent.findall(f"{NAMESPACE}link"):
                connections = token_info.attrib["target"].split(" ")

                corrections = token_info.attrib["type"]
                if corrections == "ID":
                    continue

                src_inds, tgt_inds = [], []
                corr_types = []
                for curr_corr in corrections.split("|"):
                    corr_types.append(curr_corr)

                for curr_tok in connections:
                    # Token IDs have an index at the end, but it is 1-based; convert it to 0-based
                    idx_tok = tok2position[curr_tok[1:]]
                    if "t" in curr_tok:  # target token
                        tgt_inds.append(idx_tok)
                    else:  # source token
                        src_inds.append(idx_tok)

                corr_data.append({"idx_src": src_inds, "idx_tgt": tgt_inds, "corr_types": corr_types})

            yield idx_corr, {
                "id_doc": id_doc[:-1],  # doc ID without the "s" or "t" info
                "doc_title": doc_title,
                "is_manually_validated": is_manually_validated,
                "id_src_tokens": src_sent_data.get("id_token", []),
                "src_tokens": src_sent_data.get("form", []),
                "src_ling_annotations": {
                    "lemma": src_sent_data.get("lemma", []),
                    "ana": src_sent_data.get("ana", []),
                    "msd": src_sent_data.get("msd", []),
                    "ne_tag": src_sent_data.get("ne_tag", []),
                    "space_after": src_sent_data.get("space_after", [])
                },
                "id_tgt_tokens": tgt_sent_data.get("id_token", []),
                "tgt_tokens": tgt_sent_data.get("form", []),
                "tgt_ling_annotations": {
                    "lemma": tgt_sent_data.get("lemma", []),
                    "ana": tgt_sent_data.get("ana", []),
                    "msd": tgt_sent_data.get("msd", []),
                    "ne_tag": tgt_sent_data.get("ne_tag", []),
                    "space_after": tgt_sent_data.get("space_after", [])
                },
                "corrections": corr_data
            }

    @staticmethod
    def aggregate_docs(sent_level_data):
        # NOTE: assuming here that `sent_level_data` is pre-sorted by id_doc, which is done in the raw data
        for idx_doc, (curr_id, curr_group) in enumerate(groupby(sent_level_data, key=lambda tup: tup[1]["id_doc"])):
            curr_instances = map(lambda tup: tup[1], curr_group)  # remove the redundant index info from datasets

            src_tokens, tgt_tokens, mapped_corrections = [], [], []
            src_ling_anns = {"lemma": [], "ana": [], "msd": [], "ne_tag": [], "space_after": []}
            tgt_ling_anns = {"lemma": [], "ana": [], "msd": [], "ne_tag": [], "space_after": []}
            seen_src_tokens, seen_tgt_tokens = {}, {}
            # Need to keep the current base position of source and target tokens AND previous base position:
            # A source may map into multiple targets (or vice versa), but we do not want to write it twice in a doc.
            # Therefore, when the same sentence is encountered twice, the base is shifted to the previous one to map
            # the indices of corrected tokens correctly.
            src_base, tgt_base = 0, 0
            prev_src_base, prev_tgt_base = 0, 0

            doc_title, is_validated = None, None
            for curr_inst in curr_instances:
                doc_title, is_validated = curr_inst["doc_title"], curr_inst["is_manually_validated"]

                id_src_toks, id_tgt_toks = curr_inst["id_src_tokens"], curr_inst["id_tgt_tokens"]
                curr_src_toks, curr_tgt_toks = curr_inst["src_tokens"], curr_inst["tgt_tokens"]
                curr_src_anns, curr_tgt_anns = curr_inst["src_ling_annotations"], curr_inst["tgt_ling_annotations"]
                curr_corrs = curr_inst["corrections"]

                num_added_src, num_added_tgt = 0, 0
                for idx_position, (id_tok, tok) in enumerate(zip(id_src_toks, curr_src_toks)):
                    if id_tok not in seen_src_tokens:
                        src_tokens.append(tok)
                        src_ling_anns["lemma"].append(curr_src_anns["lemma"][idx_position])
                        src_ling_anns["ana"].append(curr_src_anns["ana"][idx_position])
                        src_ling_anns["msd"].append(curr_src_anns["msd"][idx_position])
                        src_ling_anns["ne_tag"].append(curr_src_anns["ne_tag"][idx_position])
                        src_ling_anns["space_after"].append(curr_src_anns["space_after"][idx_position])

                        seen_src_tokens[id_tok] = tok
                        num_added_src += 1

                for idx_position, (id_tok, tok) in enumerate(zip(id_tgt_toks, curr_tgt_toks)):
                    if id_tok not in seen_tgt_tokens:
                        tgt_tokens.append(tok)
                        tgt_ling_anns["lemma"].append(curr_tgt_anns["lemma"][idx_position])
                        tgt_ling_anns["ana"].append(curr_tgt_anns["ana"][idx_position])
                        tgt_ling_anns["msd"].append(curr_tgt_anns["msd"][idx_position])
                        tgt_ling_anns["ne_tag"].append(curr_tgt_anns["ne_tag"][idx_position])
                        tgt_ling_anns["space_after"].append(curr_tgt_anns["space_after"][idx_position])

                        seen_tgt_tokens[id_tok] = tok
                        num_added_tgt += 1

                if num_added_src == 0:
                    src_base, prev_src_base = prev_src_base, src_base

                if num_added_tgt == 0:
                    tgt_base, prev_tgt_base = prev_tgt_base, tgt_base

                for corr in curr_corrs:
                    mapped_corrections.append({
                        "idx_src": list(map(lambda _i: src_base + _i, corr["idx_src"])),
                        "idx_tgt": list(map(lambda _i: tgt_base + _i, corr["idx_tgt"])),
                        "corr_types": corr["corr_types"]
                    })

                src_base += num_added_src
                tgt_base += num_added_tgt

                if num_added_src == 0:
                    src_base, prev_src_base = prev_src_base, src_base

                if num_added_tgt == 0:
                    tgt_base, prev_tgt_base = prev_tgt_base, tgt_base

            yield idx_doc, {
                "id_doc": curr_id,
                "doc_title": doc_title,
                "is_manually_validated": is_validated,
                "src_tokens": src_tokens,
                "src_ling_annotations": src_ling_anns,
                "tgt_tokens": tgt_tokens,
                "tgt_ling_annotations": tgt_ling_anns,
                "corrections": mapped_corrections
            }

    def _generate_examples(self, source_path, target_path, links_path):
        sent_level_data = list(Solar3.generate_sentences(source_path, target_path, links_path))

        if self.config.name == "sentence_level":
            # Remove IDs that are only useful for aggregating the document-level data
            for i, instance in sent_level_data:
                yield i, {_k: _v for _k, _v in instance.items() if _k not in {"id_src_tokens", "id_tgt_tokens"}}
        else:
            yield from list(Solar3.aggregate_docs(sent_level_data))