phucdev commited on
Commit
263dea7
1 Parent(s): 7f84b3c

Delete loading script

Browse files
Files changed (1) hide show
  1. science_ie.py +0 -427
science_ie.py DELETED
@@ -1,427 +0,0 @@
1
- # Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
- """ScienceIE is a dataset for the SemEval task of extracting key phrases and relations between them from scientific documents"""
15
-
16
- import glob
17
- import datasets
18
-
19
- from pathlib import Path
20
- from itertools import permutations
21
-
22
- # Find for instance the citation on arxiv or on the dataset repo/website
23
- _CITATION = """\
24
- @article{DBLP:journals/corr/AugensteinDRVM17,
25
- author = {Isabelle Augenstein and
26
- Mrinal Das and
27
- Sebastian Riedel and
28
- Lakshmi Vikraman and
29
- Andrew McCallum},
30
- title = {SemEval 2017 Task 10: ScienceIE - Extracting Keyphrases and Relations
31
- from Scientific Publications},
32
- journal = {CoRR},
33
- volume = {abs/1704.02853},
34
- year = {2017},
35
- url = {http://arxiv.org/abs/1704.02853},
36
- eprinttype = {arXiv},
37
- eprint = {1704.02853},
38
- timestamp = {Mon, 13 Aug 2018 16:46:36 +0200},
39
- biburl = {https://dblp.org/rec/journals/corr/AugensteinDRVM17.bib},
40
- bibsource = {dblp computer science bibliography, https://dblp.org}
41
- }
42
- """
43
-
44
- # You can copy an official description
45
- _DESCRIPTION = """\
46
- ScienceIE is a dataset for the SemEval task of extracting key phrases and relations between them from scientific documents.
47
- A corpus for the task was built from ScienceDirect open access publications and was available freely for participants, without the need to sign a copyright agreement. Each data instance consists of one paragraph of text, drawn from a scientific paper.
48
- Publications were provided in plain text, in addition to xml format, which included the full text of the publication as well as additional metadata. 500 paragraphs from journal articles evenly distributed among the domains Computer Science, Material Sciences and Physics were selected.
49
- The training data part of the corpus consists of 350 documents, 50 for development and 100 for testing. This is similar to the pilot task described in Section 5, for which 144 articles were used for training, 40 for development and for 100 testing.
50
-
51
- The dataset has three labels: Material, Process, Task
52
- """
53
-
54
- _HOMEPAGE = "https://scienceie.github.io/resources.html"
55
-
56
- # TODO: Add the licence for the dataset here if you can find it
57
- _LICENSE = ""
58
-
59
- # The HuggingFace Datasets library doesn't host the datasets but only points to the original files.
60
- # This can be an arbitrary nested dict/list of URLs (see below in `_split_generators` method)
61
- _URLS = {
62
- "train": "https://github.com/ScienceIE/scienceie.github.io/raw/master/resources/scienceie2017_train.zip",
63
- "validation": "https://github.com/ScienceIE/scienceie.github.io/raw/master/resources/scienceie2017_dev.zip",
64
- "test": "https://github.com/ScienceIE/scienceie.github.io/raw/master/resources/semeval_articles_test.zip"
65
- }
66
-
67
-
68
- def generate_relation(entities, arg1_id, arg2_id, relation, offset=0):
69
- arg1 = None
70
- arg2 = None
71
- for e in entities:
72
- if e["id"] == arg1_id:
73
- arg1 = e
74
- elif e["id"] == arg2_id:
75
- arg2 = e
76
- assert arg1 is not None and arg2 is not None, \
77
- f"Did not find corresponding entities {arg1_id} & {arg2_id} in {entities}"
78
- return {
79
- "arg1_start": arg1["start"] - offset,
80
- "arg1_end": arg1["end"] - offset,
81
- "arg1_type": arg1["type"],
82
- "arg2_start": arg2["start"] - offset,
83
- "arg2_end": arg2["end"] - offset,
84
- "arg2_type": arg2["type"],
85
- "relation": relation
86
- }
87
-
88
-
89
- class ScienceIE(datasets.GeneratorBasedBuilder):
90
- """ScienceIE is a dataset for the task of extracting key phrases and relations between them from scientific
91
- documents"""
92
-
93
- VERSION = datasets.Version("1.1.0")
94
-
95
- BUILDER_CONFIGS = [
96
- datasets.BuilderConfig(name="science_ie", version=VERSION, description="Full ScienceIE dataset"),
97
- datasets.BuilderConfig(name="subtask_a", version=VERSION,
98
- description="Subtask A of ScienceIE for tokens being outside, at the beginning, "
99
- "or inside a key phrase"),
100
- datasets.BuilderConfig(name="subtask_b", version=VERSION,
101
- description="Subtask B of ScienceIE for tokens being outside, or part of a material, "
102
- "process or task"),
103
- datasets.BuilderConfig(name="subtask_c", version=VERSION,
104
- description="Subtask C of ScienceIE for Synonym-of and Hyponym-of relations"),
105
- datasets.BuilderConfig(name="ner", version=VERSION, description="NER part of ScienceIE"),
106
- datasets.BuilderConfig(name="re", version=VERSION, description="Relation extraction part of ScienceIE"),
107
- ]
108
-
109
- DEFAULT_CONFIG_NAME = "science_ie"
110
-
111
- def _info(self):
112
- if self.config.name == "science_ie":
113
- features = datasets.Features(
114
- {
115
- "id": datasets.Value("string"),
116
- "text": datasets.Value("string"),
117
- "keyphrases": [
118
- {
119
- "id": datasets.Value("string"),
120
- "start": datasets.Value("int32"),
121
- "end": datasets.Value("int32"),
122
- "type": datasets.features.ClassLabel(
123
- names=[
124
- "Material",
125
- "Process",
126
- "Task"
127
- ]
128
- ),
129
- "type_": datasets.Value("string")
130
- }
131
- ],
132
- "relations": [
133
- {
134
- "arg1": datasets.Value("string"),
135
- "arg2": datasets.Value("string"),
136
- "relation": datasets.features.ClassLabel(names=["O", "Synonym-of", "Hyponym-of"]),
137
- "relation_": datasets.Value("string")
138
- }
139
- ]
140
- }
141
- )
142
- elif self.config.name == "subtask_a":
143
- features = datasets.Features(
144
- {
145
- "id": datasets.Value("string"),
146
- "tokens": datasets.Sequence(datasets.Value("string")),
147
- "tags": datasets.Sequence(datasets.features.ClassLabel(names=["O", "B", "I"]))
148
- }
149
- )
150
- elif self.config.name == "subtask_b":
151
- features = datasets.Features(
152
- {
153
- "id": datasets.Value("string"),
154
- "tokens": datasets.Sequence(datasets.Value("string")),
155
- "tags": datasets.Sequence(datasets.features.ClassLabel(names=["O", "M", "P", "T"]))
156
- }
157
- )
158
- elif self.config.name == "subtask_c":
159
- features = datasets.Features(
160
- {
161
- "id": datasets.Value("string"),
162
- "tokens": datasets.Sequence(datasets.Value("string")),
163
- "tags": datasets.Sequence(datasets.Sequence(datasets.features.ClassLabel(names=["O", "S", "H"])))
164
- }
165
- )
166
- elif self.config.name == "re":
167
- features = datasets.Features(
168
- {
169
- "id": datasets.Value("string"),
170
- "tokens": datasets.Value("string"),
171
- "arg1_start": datasets.Value("int32"),
172
- "arg1_end": datasets.Value("int32"),
173
- "arg1_type": datasets.Value("string"),
174
- "arg2_start": datasets.Value("int32"),
175
- "arg2_end": datasets.Value("int32"),
176
- "arg2_type": datasets.Value("string"),
177
- "relation": datasets.features.ClassLabel(names=["O", "Synonym-of", "Hyponym-of"])
178
- }
179
- )
180
- else:
181
- features = datasets.Features(
182
- {
183
- "id": datasets.Value("string"),
184
- "tokens": datasets.Sequence(datasets.Value("string")),
185
- "tags": datasets.Sequence(
186
- datasets.features.ClassLabel(
187
- names=[
188
- "O",
189
- "B-Material",
190
- "I-Material",
191
- "B-Process",
192
- "I-Process",
193
- "B-Task",
194
- "I-Task"
195
- ]
196
- )
197
- )
198
- }
199
- )
200
- return datasets.DatasetInfo(
201
- # This is the description that will appear on the datasets page.
202
- description=_DESCRIPTION,
203
- # This defines the different columns of the dataset and their types
204
- features=features, # Here we define them above because they are different between the two configurations
205
- # If there's a common (input, target) tuple from the features, uncomment supervised_keys line below and
206
- # specify them. They'll be used if as_supervised=True in builder.as_dataset.
207
- # supervised_keys=("sentence", "label"),
208
- # Homepage of the dataset for documentation
209
- homepage=_HOMEPAGE,
210
- # License for the dataset if available
211
- license=_LICENSE,
212
- # Citation for the dataset
213
- citation=_CITATION,
214
- )
215
-
216
- def _split_generators(self, dl_manager):
217
- # If several configurations are possible (listed in BUILDER_CONFIGS), the configuration selected by the user is in self.config.name
218
-
219
- # dl_manager is a datasets.download.DownloadManager that can be used to download and extract URLS
220
- # 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.
221
- # By default the archives will be extracted and a path to a cached folder where they are extracted is returned instead of the archive
222
- downloaded_files = dl_manager.download_and_extract(_URLS)
223
-
224
- return [datasets.SplitGenerator(name=i, gen_kwargs={"dir_path": downloaded_files[str(i)]})
225
- for i in [datasets.Split.TRAIN, datasets.Split.VALIDATION, datasets.Split.TEST]]
226
-
227
- # method parameters are unpacked from `gen_kwargs` as given in `_split_generators`
228
- def _generate_examples(self, dir_path):
229
- # The `key` is for legacy reasons (tfds) and is not important in itself, but must be unique for each example.
230
- annotation_files = glob.glob(dir_path + "/**/*.ann", recursive=True)
231
- if self.config.name != "science_ie":
232
- from spacy.lang.en import English
233
- word_splitter = English()
234
- word_splitter.add_pipe('sentencizer')
235
- else:
236
- word_splitter = None
237
- for f_anno_file in annotation_files:
238
- doc_example_idx = 0
239
- f_anno_path = Path(f_anno_file)
240
- f_text_path = f_anno_path.with_suffix(".txt")
241
- doc_id = f_anno_path.stem
242
- with open(f_anno_path, mode="r", encoding="utf8") as f_anno, \
243
- open(f_text_path, mode="r", encoding="utf8") as f_text:
244
- text = f_text.read().strip()
245
- if word_splitter:
246
- doc = word_splitter(text)
247
- else:
248
- doc = None
249
- entities = []
250
- synonym_groups = []
251
- hyponyms = []
252
- for line in f_anno:
253
- split_line = line.strip("\n").split("\t")
254
- identifier = split_line[0]
255
- annotation = split_line[1].split(" ")
256
- key_type = annotation[0]
257
- if key_type == "Synonym-of":
258
- synonym_ids = annotation[1:]
259
- synonym_groups.append(synonym_ids)
260
- else:
261
- if len(annotation) == 3:
262
- _, start, end = annotation
263
- else:
264
- _, start, _, end = annotation
265
- if key_type == "Hyponym-of":
266
- assert start.startswith("Arg1:") and end.startswith("Arg2:")
267
- hyponyms.append({
268
- "id": identifier,
269
- "arg1_id": start[5:],
270
- "arg2_id": end[5:]
271
- })
272
- else:
273
- # NER annotation
274
- # look up span in text and print error message if it doesn't match the .ann span text
275
- keyphr_text_lookup = text[int(start):int(end)]
276
- keyphr_ann = split_line[2]
277
- if keyphr_text_lookup != keyphr_ann:
278
- print("Spans don't match for anno " + line.strip() + " in file " + f_anno_file)
279
- char_start = int(start)
280
- char_end = int(end)
281
- if doc:
282
- entity_span = doc.char_span(char_start, char_end, alignment_mode="expand")
283
- start = entity_span.start
284
- end = entity_span.end
285
- entities.append({
286
- "id": identifier,
287
- "start": start,
288
- "end": end,
289
- "char_start": char_start,
290
- "char_end": char_end,
291
- "type": key_type,
292
- "type_": key_type
293
- })
294
- else:
295
- entities.append({
296
- "id": identifier,
297
- "start": char_start,
298
- "end": char_end,
299
- "type": key_type,
300
- "type_": key_type
301
- })
302
- if self.config.name == "science_ie":
303
- # just to pass the assertion at the end of the method, check is not relevant for this config
304
- synonym_groups_used = [True for _ in synonym_groups]
305
- hyponyms_used = [True for _ in hyponyms]
306
- gen_relations = []
307
- for idx, synonym_group in enumerate(synonym_groups):
308
- for arg1_id, arg2_id in permutations(synonym_group, 2):
309
- gen_relations.append(dict(arg1=arg1_id, arg2=arg2_id, relation="Synonym-of",
310
- relation_="Synonym-of"))
311
- for hyponym in hyponyms:
312
- gen_relations.append(dict(arg1=hyponym["arg1_id"], arg2=hyponym["arg2_id"],
313
- relation="Hyponym-of", relation_="Hyponym-of"))
314
- yield doc_id, {
315
- "id": doc_id,
316
- "text": text,
317
- "keyphrases": entities,
318
- "relations": gen_relations
319
- }
320
- else:
321
- # check if any annotation is lost during sentence splitting
322
- synonym_groups_used = [False for _ in synonym_groups]
323
- hyponyms_used = [False for _ in hyponyms]
324
- for sent in doc.sents:
325
- token_offset = sent.start
326
- tokens = [token.text for token in sent]
327
- tags = ["O" for _ in tokens]
328
- sent_entities = []
329
- sent_entity_ids = []
330
- for entity in entities:
331
- if entity["start"] >= sent.start and entity["end"] <= sent.end:
332
- sent_entity = {k: v for k, v in entity.items()}
333
- sent_entity["start"] -= token_offset
334
- sent_entity["end"] -= token_offset
335
- sent_entities.append(sent_entity)
336
- sent_entity_ids.append(entity["id"])
337
- for entity in sent_entities:
338
- tags[entity["start"]] = "B-" + entity["type"]
339
- for i in range(entity["start"] + 1, entity["end"]):
340
- tags[i] = "I-" + entity["type"]
341
-
342
- relations = []
343
- entity_pairs_in_relation = []
344
- for idx, synonym_group in enumerate(synonym_groups):
345
- if all(entity_id in sent_entity_ids for entity_id in synonym_group):
346
- synonym_groups_used[idx] = True
347
- for arg1_id, arg2_id in permutations(synonym_group, 2):
348
- relations.append(
349
- generate_relation(sent_entities, arg1_id, arg2_id, relation="Synonym-of"))
350
- entity_pairs_in_relation.append((arg1_id, arg2_id))
351
- for idx, hyponym in enumerate(hyponyms):
352
- if hyponym["arg1_id"] in sent_entity_ids and hyponym["arg2_id"] in sent_entity_ids:
353
- hyponyms_used[idx] = True
354
- relations.append(
355
- generate_relation(sent_entities, hyponym["arg1_id"], hyponym["arg2_id"],
356
- relation="Hyponym-of"))
357
-
358
- entity_pairs_in_relation.append((arg1_id, arg2_id))
359
- entity_pairs = [(arg1["id"], arg2["id"]) for arg1, arg2 in permutations(sent_entities, 2)
360
- if (arg1["id"], arg2["id"]) not in entity_pairs_in_relation]
361
- for arg1_id, arg2_id in entity_pairs:
362
- relations.append(generate_relation(sent_entities, arg1_id, arg2_id, relation="O"))
363
-
364
- if self.config.name == "subtask_a":
365
- doc_example_idx += 1
366
- key = f"{doc_id}_{doc_example_idx}"
367
- # Yields examples as (key, example) tuples
368
- yield key, {
369
- "id": key,
370
- "tokens": tokens,
371
- "tags": [tag[0] for tag in tags]
372
- }
373
- elif self.config.name == "subtask_b":
374
- doc_example_idx += 1
375
- key = f"{doc_id}_{doc_example_idx}"
376
- # Yields examples as (key, example) tuples
377
- key_phrase_tags = []
378
- for tag in tags:
379
- if tag == "O":
380
- key_phrase_tags.append(tag)
381
- else:
382
- # use first letter of key phrase type
383
- key_phrase_tags.append(tag[2])
384
- yield key, {
385
- "id": key,
386
- "tokens": tokens,
387
- "tags": key_phrase_tags
388
- }
389
- elif self.config.name == "subtask_c":
390
- doc_example_idx += 1
391
- key = f"{doc_id}_{doc_example_idx}"
392
- tag_vectors = [["O" for _ in tokens] for _ in tokens]
393
- for relation in relations:
394
- tag = relation["relation"][0]
395
- if tag != "O":
396
- tag_vectors[relation["arg1_start"]][relation["arg2_start"]] = tag
397
- # Yields examples as (key, example) tuples
398
- yield key, {
399
- "id": key,
400
- "tokens": tokens,
401
- "tags": tag_vectors
402
- }
403
- elif self.config.name == "re":
404
- for relation in relations:
405
- doc_example_idx += 1
406
- key = f"{doc_id}_{doc_example_idx}"
407
- # Yields examples as (key, example) tuples
408
- example = {
409
- "id": key,
410
- "tokens": tokens
411
- }
412
- for k, v in relation.items():
413
- example[k] = v
414
- yield key, example
415
- else: # NER config
416
- doc_example_idx += 1
417
- key = f"{doc_id}_{doc_example_idx}"
418
- # Yields examples as (key, example) tuples
419
- yield key, {
420
- "id": key,
421
- "tokens": tokens,
422
- "tags": tags
423
- }
424
-
425
- assert all(synonym_groups_used) and all(hyponyms_used), \
426
- f"Annotations were lost: {len([e for e in synonym_groups_used if e])} synonym annotations," \
427
- f"{len([e for e in hyponyms_used if e])} synonym annotations"