File size: 15,989 Bytes
42889e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# I am trying to understand to the following code. Do not use this for any purpose as I do not support this.
# Use the original source from https://huggingface.co/datasets/DFKI-SLT/science_ie/raw/main/science_ie.py


# Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""DWIE is conceived as an entity-centric dataset that describes interactions and properties of conceptual entities on the level of the complete document."""  

import datasets
from datasets import DownloadManager
import os
import json
import requests
from typing import Optional, List, Union
import argparse
import hashlib
from collections import OrderedDict
from time import sleep

#from dataset.utils.tokenizer import TokenizerCPN


# Find for instance the citation on arxiv or on the dataset repo/website
_CITATION = """\
@article{ZAPOROJETS2021102563,
title = {{DWIE}: An entity-centric dataset for multi-task document-level information extraction},
journal = {Information Processing & Management},
volume = {58},
number = {4},
pages = {102563},
year = {2021},
issn = {0306-4573},
doi = {https://doi.org/10.1016/j.ipm.2021.102563},
url = {https://www.sciencedirect.com/science/article/pii/S0306457321000662},
author = {Klim Zaporojets and Johannes Deleu and Chris Develder and Thomas Demeester}
}
"""

# You can copy an official description
_DESCRIPTION = """\
DWIE is conceived as an entity-centric dataset that describes interactions and properties of conceptual entities 
on the level of the complete document. This contrasts with currently dominant mention-driven approaches that start 
from the detection and classification of named entity mentions in individual sentences. Also, the dataset was
randomly sampled from a news platform (English online content from Deutsche Welle), and the annotation scheme 
was generated to cover that content. This makes the setting more realistic than in datasets with pre-determined 
annotation schemes, and non-uniform sampling of content to obtain balanced annotations."""

# Add a link to an official homepage for the dataset here
_HOMEPAGE = "https://github.com/klimzaporojets/DWIE"

# Add the licence for the dataset here if you can find it
_LICENSE = ""

# Add link to the official dataset URLs here
# The HuggingFace Datasets library doesn't host the datasets but only points to the original files.
# This can be an arbitrary nested dict/list of URLs (see below in `_split_generators` method)
_URLS = {"Task_1":
          {
          "url":"https://github.com/klimzaporojets/DWIE/archive/refs/heads/master.zip"
            }
          }



class DWIE(datasets.GeneratorBasedBuilder):
    """
    DWIE is conceived as an entity-centric dataset that describes interactions and properties of conceptual entities on the level of the complete document.
    """

    VERSION = datasets.Version("1.1.0")

    BUILDER_CONFIGS = [
        datasets.BuilderConfig(name="Task_1", version=VERSION,
                               description="Relation classification"),
    ]
    DEFAULT_CONFIG_NAME = "Task_1"

    def _info(self):
        features = datasets.Features(
            {
                "id": datasets.Value("string"),
                "content": datasets.Value("string"),
                "tags": datasets.Value("string"),
                "mentions": [
                    {
                        "begin": datasets.Value("int32"),
                        "end": datasets.Value("int32"),
                        "text": datasets.Value("string"),
                        "concept": datasets.Value("int32"),
                        "candidates" : datasets.Sequence(datasets.Value("string")),
                        "scores": datasets.Sequence(datasets.Value("float32"))
                    }
                ],
                "concepts": [
                    {
                        "concept": datasets.Value("int32"),
                        "text": datasets.Value("string"),
                        "keyword": datasets.Value("bool"),
                        "count": datasets.Value("int32"),
                        "link": datasets.Value("string"),
                        "tags": datasets.Sequence(datasets.Value("string")),  
                        
                    }
                ],
                "relations": [
                    {
                        "s": datasets.Value("int32"),
                        "p": datasets.Value("string"),
                        "o": datasets.Value("int32"),
                        
                    }
                ],
                "frames": [
                    {
                        "type": datasets.Value("string"),
                        "slots": [{
                          "name": datasets.Value("string"),
                          "value":datasets.Value("int32")
                        }]
                        
                    }
                ],
                "iptc": datasets.Sequence(datasets.Value("string"))
                
            }
        )

        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, uncomment supervised_keys line below and
            # specify them. They'll be used if as_supervised=True in builder.as_dataset.
            # supervised_keys=("sentence", "label"),
            # 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):
        
        # 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
        
        urls = _URLS[self.config.name]
        downloaded = dl_manager.download_and_extract(_URLS) 
        article_id_to_url_json= json.load(open(downloaded['Task_1']['url'] + '/DWIE-master/data/article_id_to_url.json'))
        ids_to_new_ids = dict()
        # some ids seem to be different, for now only this one:
        ids_to_new_ids[18525950] = 19026607

        should_tokenize = False

        content_to_new_content = {'DW_40663341': [('starting with Sunday\'s', 'starting Sunday\'s'),
                                              ('$1 million (€840,000)', 'one million dollars (840,000 euros)'),
                                              ('who kneel in protest during', 'to kneel in protest during')]}
        
        articles_done = 0
        total_articles = len(article_id_to_url_json)
        problematic_articles = set()
        problematic_hash_articles = set()
        all_annos = []
        for curr_article in article_id_to_url_json:
          article_id = curr_article['id']
          article_url = curr_article['url']
          article_id_nr = int(article_id[3:])
          if article_id_nr in ids_to_new_ids:
            article_url = article_url.replace(str(article_id_nr), str(ids_to_new_ids[article_id_nr]))
          article_hash = curr_article['hash']
          #print('fetching {} out of {} articles -'.format(articles_done, total_articles), curr_article)

          annos_only_art_path = downloaded['Task_1']['url'] + '/DWIE-master/data/annos/' + curr_article['id'] + '.json'
          annos_only_json = json.load(open(annos_only_art_path))
          done = False
          attempts = 0
          while not done and attempts <= 3:
            # try:
            a = requests.get(article_url, allow_redirects=True).json()
            if 'name' in a:
                article_title = a['name']
            else:
                print('WARNING: no name detected for ', article_id)
                article_title = ''
            if 'teaser' in a:
                article_teaser = a['teaser']
            else:
                print('WARNING: no teaser detected for ', article_id)
                article_teaser = ''

            if 'text' in a:
                article_text = a['text']
            else:
                print('WARNING: no text detected for ', article_id)
                article_text = ''

            article_content_no_strip = '{}\n{}\n{}'.format(article_title, article_teaser, article_text)
            article_content = article_content_no_strip

            if article_id in content_to_new_content:
                for str_dw, str_dwie in content_to_new_content[article_id]:
                    article_content = article_content.replace(str_dw, str_dwie)
            
            if 'mentions' in annos_only_json:
                for idx_mention, curr_mention in enumerate(annos_only_json['mentions']):
                    curr_mention_text = curr_mention['text'].replace(' ', ' ')
                    curr_mention_text = curr_mention_text.replace('​', '')
                    solved = False
                    if "begin" not in curr_mention:
                      curr_mention["begin"] = 0
                    if "end" not in curr_mention:
                      curr_mention["end"] = 0
                    if "text" not in curr_mention:
                      curr_mention["text"] = ""
                    if "concept" not in curr_mention:
                      curr_mention["concept"] = 0
                    
                    
                    if "candidates" not in curr_mention:
                      curr_mention["candidates"] = []
                    if "scores" not in curr_mention:
                      curr_mention["scores"] = []
                
                    if article_content[curr_mention['begin']:curr_mention['end']] != curr_mention_text:
                        curr_mention_begin = curr_mention['begin']
                        curr_mention_end = curr_mention['end']
                        offset = 0

                        if not solved:
                            print('--------------------------------')
                            print('ERROR ALIGNMENT: texts don\'t match for {}: "{}" vs "{}", the textual content of '
                                  'the files won\'t be complete '
                                  .format(article_id, article_content[curr_mention['begin']:curr_mention['end']],
                                          curr_mention_text))
                            print('--------------------------------')
                            problematic_articles.add(article_id)
                        else:
                            if "candidates" not in curr_mention:
                              curr_mention["candidates"] = []
                
                            curr_mention['begin'] = curr_mention_begin - offset
                            curr_mention['end'] = curr_mention_end - offset
            if 'concepts' in annos_only_json:
                for idx_concept, curr_concept in enumerate(annos_only_json['concepts']):
                    if "concept" not in curr_concept:
                      curr_concept["concept"] = 0
                    if "text" not in curr_concept:
                      curr_concept["text"] = ""
                    if "count" not in curr_concept:
                      curr_concept["count"] = 0
                    if "link" not in curr_concept:
                      curr_concept["link"] = ""
                    if "tags" not in curr_concept:
                      curr_concept["tags"] = []
            
            if not should_tokenize:
                annos_json = {'id': annos_only_json['id'],
                                          'content': article_content,
                                          'tags': annos_only_json['tags'],
                                          'mentions': annos_only_json['mentions'],
                                          'concepts': annos_only_json['concepts'],
                                          'relations': annos_only_json['relations'],
                                          'frames': annos_only_json['frames'],
                                          'iptc': annos_only_json['iptc']}
                all_annos.append(annos_json)
                
                #print("annos_json",annos_json)
            else:
                tokenized = tokenizer.tokenize(article_content)
                tokens = list()
                begin = list()
                end = list()
                for curr_token in tokenized:
                    tokens.append(curr_token['token'])
                    begin.append(curr_token['offset'])
                    end.append(curr_token['offset'] + curr_token['length'])
                annos_json = OrderedDict({'id': annos_only_json['id'],
                                          'content': article_content,
                                          'tokenization': OrderedDict({'tokens': tokens, 'begin': begin, 'end': end}),
                                          'tags': annos_only_json['tags'],
                                          'mentions': annos_only_json['mentions'],
                                          'concepts': annos_only_json['concepts'],
                                          'relations': annos_only_json['relations'],
                                          'frames': annos_only_json['frames'],
                                          'iptc': annos_only_json['iptc']})
                
            hash_content = hashlib.sha1(article_content.encode("UTF-8")).hexdigest()

            if hash_content != article_hash:
                print('!!ERROR - hash doesn\'t match for ', article_id)
                problematic_hash_articles.add(article_id)
                attempts += 1

            sleep(.1)
            done = True
          if done:
              articles_done += 1

          
        return[
            datasets.SplitGenerator(
                name=datasets.Split.TRAIN,
                # These kwargs will be passed to _generate_examples
                gen_kwargs={
                    "all_annos" : all_annos,
                    
                }

            )
          ]
        
    # method parameters are unpacked from `gen_kwargs` as given in `_split_generators`
    def _generate_examples(self, all_annos):
        # TODO: This method handles input defined in _split_generators to yield (key, example) tuples from the dataset.
        # The `key` is for legacy reasons (tfds) and is not important in itself, but must be unique for each example.               
        for data in all_annos:
          yield data['id'], {
            "id": data['id'],
            "content":data['content'],
            "tags": data['tags'],
            "mentions": data['mentions'],
            "concepts": data['concepts'],
            "relations": data['relations'],
            "frames": data['frames'],
            "iptc": data['iptc']
          }