parquet-converter commited on
Commit
c5d0c67
1 Parent(s): 88cb949

Update parquet files

Browse files
.gitattributes DELETED
@@ -1,54 +0,0 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.lz4 filter=lfs diff=lfs merge=lfs -text
12
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
13
- *.model filter=lfs diff=lfs merge=lfs -text
14
- *.msgpack filter=lfs diff=lfs merge=lfs -text
15
- *.npy filter=lfs diff=lfs merge=lfs -text
16
- *.npz filter=lfs diff=lfs merge=lfs -text
17
- *.onnx filter=lfs diff=lfs merge=lfs -text
18
- *.ot filter=lfs diff=lfs merge=lfs -text
19
- *.parquet filter=lfs diff=lfs merge=lfs -text
20
- *.pb filter=lfs diff=lfs merge=lfs -text
21
- *.pickle filter=lfs diff=lfs merge=lfs -text
22
- *.pkl filter=lfs diff=lfs merge=lfs -text
23
- *.pt filter=lfs diff=lfs merge=lfs -text
24
- *.pth filter=lfs diff=lfs merge=lfs -text
25
- *.rar filter=lfs diff=lfs merge=lfs -text
26
- *.safetensors filter=lfs diff=lfs merge=lfs -text
27
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
28
- *.tar.* filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz filter=lfs diff=lfs merge=lfs -text
33
- *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
36
- # Audio files - uncompressed
37
- *.pcm filter=lfs diff=lfs merge=lfs -text
38
- *.sam filter=lfs diff=lfs merge=lfs -text
39
- *.raw filter=lfs diff=lfs merge=lfs -text
40
- # Audio files - compressed
41
- *.aac filter=lfs diff=lfs merge=lfs -text
42
- *.flac filter=lfs diff=lfs merge=lfs -text
43
- *.mp3 filter=lfs diff=lfs merge=lfs -text
44
- *.ogg filter=lfs diff=lfs merge=lfs -text
45
- *.wav filter=lfs diff=lfs merge=lfs -text
46
- # Image files - uncompressed
47
- *.bmp filter=lfs diff=lfs merge=lfs -text
48
- *.gif filter=lfs diff=lfs merge=lfs -text
49
- *.png filter=lfs diff=lfs merge=lfs -text
50
- *.tiff filter=lfs diff=lfs merge=lfs -text
51
- # Image files - compressed
52
- *.jpg filter=lfs diff=lfs merge=lfs -text
53
- *.jpeg filter=lfs diff=lfs merge=lfs -text
54
- *.webp filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bigbiohub.py DELETED
@@ -1,556 +0,0 @@
1
- from collections import defaultdict
2
- from dataclasses import dataclass
3
- from enum import Enum
4
- import logging
5
- from pathlib import Path
6
- from types import SimpleNamespace
7
- from typing import TYPE_CHECKING, Dict, Iterable, List, Tuple
8
-
9
- import datasets
10
-
11
- if TYPE_CHECKING:
12
- import bioc
13
-
14
- logger = logging.getLogger(__name__)
15
-
16
-
17
- BigBioValues = SimpleNamespace(NULL="<BB_NULL_STR>")
18
-
19
-
20
- @dataclass
21
- class BigBioConfig(datasets.BuilderConfig):
22
- """BuilderConfig for BigBio."""
23
-
24
- name: str = None
25
- version: datasets.Version = None
26
- description: str = None
27
- schema: str = None
28
- subset_id: str = None
29
-
30
-
31
- class Tasks(Enum):
32
- NAMED_ENTITY_RECOGNITION = "NER"
33
- NAMED_ENTITY_DISAMBIGUATION = "NED"
34
- EVENT_EXTRACTION = "EE"
35
- RELATION_EXTRACTION = "RE"
36
- COREFERENCE_RESOLUTION = "COREF"
37
- QUESTION_ANSWERING = "QA"
38
- TEXTUAL_ENTAILMENT = "TE"
39
- SEMANTIC_SIMILARITY = "STS"
40
- TEXT_PAIRS_CLASSIFICATION = "TXT2CLASS"
41
- PARAPHRASING = "PARA"
42
- TRANSLATION = "TRANSL"
43
- SUMMARIZATION = "SUM"
44
- TEXT_CLASSIFICATION = "TXTCLASS"
45
-
46
-
47
- entailment_features = datasets.Features(
48
- {
49
- "id": datasets.Value("string"),
50
- "premise": datasets.Value("string"),
51
- "hypothesis": datasets.Value("string"),
52
- "label": datasets.Value("string"),
53
- }
54
- )
55
-
56
- pairs_features = datasets.Features(
57
- {
58
- "id": datasets.Value("string"),
59
- "document_id": datasets.Value("string"),
60
- "text_1": datasets.Value("string"),
61
- "text_2": datasets.Value("string"),
62
- "label": datasets.Value("string"),
63
- }
64
- )
65
-
66
- qa_features = datasets.Features(
67
- {
68
- "id": datasets.Value("string"),
69
- "question_id": datasets.Value("string"),
70
- "document_id": datasets.Value("string"),
71
- "question": datasets.Value("string"),
72
- "type": datasets.Value("string"),
73
- "choices": [datasets.Value("string")],
74
- "context": datasets.Value("string"),
75
- "answer": datasets.Sequence(datasets.Value("string")),
76
- }
77
- )
78
-
79
- text_features = datasets.Features(
80
- {
81
- "id": datasets.Value("string"),
82
- "document_id": datasets.Value("string"),
83
- "text": datasets.Value("string"),
84
- "labels": [datasets.Value("string")],
85
- }
86
- )
87
-
88
- text2text_features = datasets.Features(
89
- {
90
- "id": datasets.Value("string"),
91
- "document_id": datasets.Value("string"),
92
- "text_1": datasets.Value("string"),
93
- "text_2": datasets.Value("string"),
94
- "text_1_name": datasets.Value("string"),
95
- "text_2_name": datasets.Value("string"),
96
- }
97
- )
98
-
99
- kb_features = datasets.Features(
100
- {
101
- "id": datasets.Value("string"),
102
- "document_id": datasets.Value("string"),
103
- "passages": [
104
- {
105
- "id": datasets.Value("string"),
106
- "type": datasets.Value("string"),
107
- "text": datasets.Sequence(datasets.Value("string")),
108
- "offsets": datasets.Sequence([datasets.Value("int32")]),
109
- }
110
- ],
111
- "entities": [
112
- {
113
- "id": datasets.Value("string"),
114
- "type": datasets.Value("string"),
115
- "text": datasets.Sequence(datasets.Value("string")),
116
- "offsets": datasets.Sequence([datasets.Value("int32")]),
117
- "normalized": [
118
- {
119
- "db_name": datasets.Value("string"),
120
- "db_id": datasets.Value("string"),
121
- }
122
- ],
123
- }
124
- ],
125
- "events": [
126
- {
127
- "id": datasets.Value("string"),
128
- "type": datasets.Value("string"),
129
- # refers to the text_bound_annotation of the trigger
130
- "trigger": {
131
- "text": datasets.Sequence(datasets.Value("string")),
132
- "offsets": datasets.Sequence([datasets.Value("int32")]),
133
- },
134
- "arguments": [
135
- {
136
- "role": datasets.Value("string"),
137
- "ref_id": datasets.Value("string"),
138
- }
139
- ],
140
- }
141
- ],
142
- "coreferences": [
143
- {
144
- "id": datasets.Value("string"),
145
- "entity_ids": datasets.Sequence(datasets.Value("string")),
146
- }
147
- ],
148
- "relations": [
149
- {
150
- "id": datasets.Value("string"),
151
- "type": datasets.Value("string"),
152
- "arg1_id": datasets.Value("string"),
153
- "arg2_id": datasets.Value("string"),
154
- "normalized": [
155
- {
156
- "db_name": datasets.Value("string"),
157
- "db_id": datasets.Value("string"),
158
- }
159
- ],
160
- }
161
- ],
162
- }
163
- )
164
-
165
-
166
- def get_texts_and_offsets_from_bioc_ann(ann: "bioc.BioCAnnotation") -> Tuple:
167
-
168
- offsets = [(loc.offset, loc.offset + loc.length) for loc in ann.locations]
169
-
170
- text = ann.text
171
-
172
- if len(offsets) > 1:
173
- i = 0
174
- texts = []
175
- for start, end in offsets:
176
- chunk_len = end - start
177
- texts.append(text[i : chunk_len + i])
178
- i += chunk_len
179
- while i < len(text) and text[i] == " ":
180
- i += 1
181
- else:
182
- texts = [text]
183
-
184
- return offsets, texts
185
-
186
-
187
- def remove_prefix(a: str, prefix: str) -> str:
188
- if a.startswith(prefix):
189
- a = a[len(prefix) :]
190
- return a
191
-
192
-
193
- def parse_brat_file(
194
- txt_file: Path,
195
- annotation_file_suffixes: List[str] = None,
196
- parse_notes: bool = False,
197
- ) -> Dict:
198
- """
199
- Parse a brat file into the schema defined below.
200
- `txt_file` should be the path to the brat '.txt' file you want to parse, e.g. 'data/1234.txt'
201
- Assumes that the annotations are contained in one or more of the corresponding '.a1', '.a2' or '.ann' files,
202
- e.g. 'data/1234.ann' or 'data/1234.a1' and 'data/1234.a2'.
203
- Will include annotator notes, when `parse_notes == True`.
204
- brat_features = datasets.Features(
205
- {
206
- "id": datasets.Value("string"),
207
- "document_id": datasets.Value("string"),
208
- "text": datasets.Value("string"),
209
- "text_bound_annotations": [ # T line in brat, e.g. type or event trigger
210
- {
211
- "offsets": datasets.Sequence([datasets.Value("int32")]),
212
- "text": datasets.Sequence(datasets.Value("string")),
213
- "type": datasets.Value("string"),
214
- "id": datasets.Value("string"),
215
- }
216
- ],
217
- "events": [ # E line in brat
218
- {
219
- "trigger": datasets.Value(
220
- "string"
221
- ), # refers to the text_bound_annotation of the trigger,
222
- "id": datasets.Value("string"),
223
- "type": datasets.Value("string"),
224
- "arguments": datasets.Sequence(
225
- {
226
- "role": datasets.Value("string"),
227
- "ref_id": datasets.Value("string"),
228
- }
229
- ),
230
- }
231
- ],
232
- "relations": [ # R line in brat
233
- {
234
- "id": datasets.Value("string"),
235
- "head": {
236
- "ref_id": datasets.Value("string"),
237
- "role": datasets.Value("string"),
238
- },
239
- "tail": {
240
- "ref_id": datasets.Value("string"),
241
- "role": datasets.Value("string"),
242
- },
243
- "type": datasets.Value("string"),
244
- }
245
- ],
246
- "equivalences": [ # Equiv line in brat
247
- {
248
- "id": datasets.Value("string"),
249
- "ref_ids": datasets.Sequence(datasets.Value("string")),
250
- }
251
- ],
252
- "attributes": [ # M or A lines in brat
253
- {
254
- "id": datasets.Value("string"),
255
- "type": datasets.Value("string"),
256
- "ref_id": datasets.Value("string"),
257
- "value": datasets.Value("string"),
258
- }
259
- ],
260
- "normalizations": [ # N lines in brat
261
- {
262
- "id": datasets.Value("string"),
263
- "type": datasets.Value("string"),
264
- "ref_id": datasets.Value("string"),
265
- "resource_name": datasets.Value(
266
- "string"
267
- ), # Name of the resource, e.g. "Wikipedia"
268
- "cuid": datasets.Value(
269
- "string"
270
- ), # ID in the resource, e.g. 534366
271
- "text": datasets.Value(
272
- "string"
273
- ), # Human readable description/name of the entity, e.g. "Barack Obama"
274
- }
275
- ],
276
- ### OPTIONAL: Only included when `parse_notes == True`
277
- "notes": [ # # lines in brat
278
- {
279
- "id": datasets.Value("string"),
280
- "type": datasets.Value("string"),
281
- "ref_id": datasets.Value("string"),
282
- "text": datasets.Value("string"),
283
- }
284
- ],
285
- },
286
- )
287
- """
288
-
289
- example = {}
290
- example["document_id"] = txt_file.with_suffix("").name
291
- with txt_file.open() as f:
292
- example["text"] = f.read()
293
-
294
- # If no specific suffixes of the to-be-read annotation files are given - take standard suffixes
295
- # for event extraction
296
- if annotation_file_suffixes is None:
297
- annotation_file_suffixes = [".a1", ".a2", ".ann"]
298
-
299
- if len(annotation_file_suffixes) == 0:
300
- raise AssertionError(
301
- "At least one suffix for the to-be-read annotation files should be given!"
302
- )
303
-
304
- ann_lines = []
305
- for suffix in annotation_file_suffixes:
306
- annotation_file = txt_file.with_suffix(suffix)
307
- if annotation_file.exists():
308
- with annotation_file.open() as f:
309
- ann_lines.extend(f.readlines())
310
-
311
- example["text_bound_annotations"] = []
312
- example["events"] = []
313
- example["relations"] = []
314
- example["equivalences"] = []
315
- example["attributes"] = []
316
- example["normalizations"] = []
317
-
318
- if parse_notes:
319
- example["notes"] = []
320
-
321
- for line in ann_lines:
322
- line = line.strip()
323
- if not line:
324
- continue
325
-
326
- if line.startswith("T"): # Text bound
327
- ann = {}
328
- fields = line.split("\t")
329
-
330
- ann["id"] = fields[0]
331
- ann["type"] = fields[1].split()[0]
332
- ann["offsets"] = []
333
- span_str = remove_prefix(fields[1], (ann["type"] + " "))
334
- text = fields[2]
335
- for span in span_str.split(";"):
336
- start, end = span.split()
337
- ann["offsets"].append([int(start), int(end)])
338
-
339
- # Heuristically split text of discontiguous entities into chunks
340
- ann["text"] = []
341
- if len(ann["offsets"]) > 1:
342
- i = 0
343
- for start, end in ann["offsets"]:
344
- chunk_len = end - start
345
- ann["text"].append(text[i : chunk_len + i])
346
- i += chunk_len
347
- while i < len(text) and text[i] == " ":
348
- i += 1
349
- else:
350
- ann["text"] = [text]
351
-
352
- example["text_bound_annotations"].append(ann)
353
-
354
- elif line.startswith("E"):
355
- ann = {}
356
- fields = line.split("\t")
357
-
358
- ann["id"] = fields[0]
359
-
360
- ann["type"], ann["trigger"] = fields[1].split()[0].split(":")
361
-
362
- ann["arguments"] = []
363
- for role_ref_id in fields[1].split()[1:]:
364
- argument = {
365
- "role": (role_ref_id.split(":"))[0],
366
- "ref_id": (role_ref_id.split(":"))[1],
367
- }
368
- ann["arguments"].append(argument)
369
-
370
- example["events"].append(ann)
371
-
372
- elif line.startswith("R"):
373
- ann = {}
374
- fields = line.split("\t")
375
-
376
- ann["id"] = fields[0]
377
- ann["type"] = fields[1].split()[0]
378
-
379
- ann["head"] = {
380
- "role": fields[1].split()[1].split(":")[0],
381
- "ref_id": fields[1].split()[1].split(":")[1],
382
- }
383
- ann["tail"] = {
384
- "role": fields[1].split()[2].split(":")[0],
385
- "ref_id": fields[1].split()[2].split(":")[1],
386
- }
387
-
388
- example["relations"].append(ann)
389
-
390
- # '*' seems to be the legacy way to mark equivalences,
391
- # but I couldn't find any info on the current way
392
- # this might have to be adapted dependent on the brat version
393
- # of the annotation
394
- elif line.startswith("*"):
395
- ann = {}
396
- fields = line.split("\t")
397
-
398
- ann["id"] = fields[0]
399
- ann["ref_ids"] = fields[1].split()[1:]
400
-
401
- example["equivalences"].append(ann)
402
-
403
- elif line.startswith("A") or line.startswith("M"):
404
- ann = {}
405
- fields = line.split("\t")
406
-
407
- ann["id"] = fields[0]
408
-
409
- info = fields[1].split()
410
- ann["type"] = info[0]
411
- ann["ref_id"] = info[1]
412
-
413
- if len(info) > 2:
414
- ann["value"] = info[2]
415
- else:
416
- ann["value"] = ""
417
-
418
- example["attributes"].append(ann)
419
-
420
- elif line.startswith("N"):
421
- ann = {}
422
- fields = line.split("\t")
423
-
424
- ann["id"] = fields[0]
425
- ann["text"] = fields[2]
426
-
427
- info = fields[1].split()
428
-
429
- ann["type"] = info[0]
430
- ann["ref_id"] = info[1]
431
- ann["resource_name"] = info[2].split(":")[0]
432
- ann["cuid"] = info[2].split(":")[1]
433
- example["normalizations"].append(ann)
434
-
435
- elif parse_notes and line.startswith("#"):
436
- ann = {}
437
- fields = line.split("\t")
438
-
439
- ann["id"] = fields[0]
440
- ann["text"] = fields[2] if len(fields) == 3 else BigBioValues.NULL
441
-
442
- info = fields[1].split()
443
-
444
- ann["type"] = info[0]
445
- ann["ref_id"] = info[1]
446
- example["notes"].append(ann)
447
-
448
- return example
449
-
450
-
451
- def brat_parse_to_bigbio_kb(brat_parse: Dict) -> Dict:
452
- """
453
- Transform a brat parse (conforming to the standard brat schema) obtained with
454
- `parse_brat_file` into a dictionary conforming to the `bigbio-kb` schema (as defined in ../schemas/kb.py)
455
- :param brat_parse:
456
- """
457
-
458
- unified_example = {}
459
-
460
- # Prefix all ids with document id to ensure global uniqueness,
461
- # because brat ids are only unique within their document
462
- id_prefix = brat_parse["document_id"] + "_"
463
-
464
- # identical
465
- unified_example["document_id"] = brat_parse["document_id"]
466
- unified_example["passages"] = [
467
- {
468
- "id": id_prefix + "_text",
469
- "type": "abstract",
470
- "text": [brat_parse["text"]],
471
- "offsets": [[0, len(brat_parse["text"])]],
472
- }
473
- ]
474
-
475
- # get normalizations
476
- ref_id_to_normalizations = defaultdict(list)
477
- for normalization in brat_parse["normalizations"]:
478
- ref_id_to_normalizations[normalization["ref_id"]].append(
479
- {
480
- "db_name": normalization["resource_name"],
481
- "db_id": normalization["cuid"],
482
- }
483
- )
484
-
485
- # separate entities and event triggers
486
- unified_example["events"] = []
487
- non_event_ann = brat_parse["text_bound_annotations"].copy()
488
- for event in brat_parse["events"]:
489
- event = event.copy()
490
- event["id"] = id_prefix + event["id"]
491
- trigger = next(
492
- tr
493
- for tr in brat_parse["text_bound_annotations"]
494
- if tr["id"] == event["trigger"]
495
- )
496
- if trigger in non_event_ann:
497
- non_event_ann.remove(trigger)
498
- event["trigger"] = {
499
- "text": trigger["text"].copy(),
500
- "offsets": trigger["offsets"].copy(),
501
- }
502
- for argument in event["arguments"]:
503
- argument["ref_id"] = id_prefix + argument["ref_id"]
504
-
505
- unified_example["events"].append(event)
506
-
507
- unified_example["entities"] = []
508
- anno_ids = [ref_id["id"] for ref_id in non_event_ann]
509
- for ann in non_event_ann:
510
- entity_ann = ann.copy()
511
- entity_ann["id"] = id_prefix + entity_ann["id"]
512
- entity_ann["normalized"] = ref_id_to_normalizations[ann["id"]]
513
- unified_example["entities"].append(entity_ann)
514
-
515
- # massage relations
516
- unified_example["relations"] = []
517
- skipped_relations = set()
518
- for ann in brat_parse["relations"]:
519
- if (
520
- ann["head"]["ref_id"] not in anno_ids
521
- or ann["tail"]["ref_id"] not in anno_ids
522
- ):
523
- skipped_relations.add(ann["id"])
524
- continue
525
- unified_example["relations"].append(
526
- {
527
- "arg1_id": id_prefix + ann["head"]["ref_id"],
528
- "arg2_id": id_prefix + ann["tail"]["ref_id"],
529
- "id": id_prefix + ann["id"],
530
- "type": ann["type"],
531
- "normalized": [],
532
- }
533
- )
534
- if len(skipped_relations) > 0:
535
- example_id = brat_parse["document_id"]
536
- logger.info(
537
- f"Example:{example_id}: The `bigbio_kb` schema allows `relations` only between entities."
538
- f" Skip (for now): "
539
- f"{list(skipped_relations)}"
540
- )
541
-
542
- # get coreferences
543
- unified_example["coreferences"] = []
544
- for i, ann in enumerate(brat_parse["equivalences"], start=1):
545
- is_entity_cluster = True
546
- for ref_id in ann["ref_ids"]:
547
- if not ref_id.startswith("T"): # not textbound -> no entity
548
- is_entity_cluster = False
549
- elif ref_id not in anno_ids: # event trigger -> no entity
550
- is_entity_cluster = False
551
- if is_entity_cluster:
552
- entity_ids = [id_prefix + i for i in ann["ref_ids"]]
553
- unified_example["coreferences"].append(
554
- {"id": id_prefix + str(i), "entity_ids": entity_ids}
555
- )
556
- return unified_example
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
scifact.py DELETED
@@ -1,421 +0,0 @@
1
- # coding=utf-8
2
- # Copyright 2022 The HuggingFace Datasets Authors and the current dataset script contributor.
3
- #
4
- # Licensed under the Apache License, Version 2.0 (the "License");
5
- # you may not use this file except in compliance with the License.
6
- # You may obtain a copy of the License at
7
- #
8
- # http://www.apache.org/licenses/LICENSE-2.0
9
- #
10
- # Unless required by applicable law or agreed to in writing, software
11
- # distributed under the License is distributed on an "AS IS" BASIS,
12
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- # See the License for the specific language governing permissions and
14
- # limitations under the License.
15
-
16
- import json
17
- import os
18
- from itertools import chain
19
- from typing import Dict, List, Tuple
20
-
21
- import datasets
22
- from datasets import Value
23
- import pandas as pd
24
-
25
- from .bigbiohub import pairs_features
26
- from .bigbiohub import BigBioConfig
27
- from .bigbiohub import Tasks
28
-
29
- _LANGUAGES = ['English']
30
- _PUBMED = False
31
- _LOCAL = False
32
- _CITATION = """\
33
- @article{wadden2020fact,
34
- author = {David Wadden and Shanchuan Lin and Kyle Lo and Lucy Lu Wang and Madeleine van Zuylen and Arman Cohan and Hannaneh Hajishirzi},
35
- title = {Fact or Fiction: Verifying Scientific Claims},
36
- year = {2020},
37
- address = {Online},
38
- publisher = {Association for Computational Linguistics},
39
- url = {https://aclanthology.org/2020.emnlp-main.609},
40
- doi = {10.18653/v1/2020.emnlp-main.609},
41
- pages = {7534--7550},
42
- biburl = {},
43
- bibsource = {}
44
- }
45
- """
46
-
47
- _DATASETNAME = "scifact"
48
- _DISPLAYNAME = "SciFact"
49
-
50
-
51
- _DESCRIPTION_BASE = """\
52
- SciFact is a dataset of 1.4K expert-written scientific claims paired with evidence-containing abstracts, and annotated with labels and rationales.
53
- """
54
-
55
- _SOURCE_CORPUS_DESCRIPTION = f"""\
56
- {_DESCRIPTION_BASE} This config has abstracts and document ids.
57
- """
58
-
59
- _SOURCE_CLAIMS_DESCRIPTION = """\
60
- {_DESCRIPTION_BASE} This config connects the claims to the evidence and doc ids.
61
- """
62
-
63
- _BIGBIO_PAIRS_RATIONALE_DESCRIPTION = """\
64
- {_DESCRIPTION_BASE} This task is the following: given a claim and a text span composed of one or more sentences from an abstract, predict a label from ("rationale", "not_rationale") indicating if the span is evidence (can be supporting or refuting) for the claim. This roughly corresponds to the second task outlined in Section 5 of the paper."
65
- """
66
-
67
- _BIGBIO_PAIRS_LABELPREDICTION_DESCRIPTION = """\
68
- {_DESCRIPTION_BASE} This task is the following: given a claim and a text span composed of one or more sentences from an abstract, predict a label from ("SUPPORT", "NOINFO", "CONTRADICT") indicating if the span supports, provides no info, or contradicts the claim. This roughly corresponds to the thrid task outlined in Section 5 of the paper.
69
- """
70
-
71
- _DESCRIPTION = {
72
- "scifact_corpus_source": _SOURCE_CORPUS_DESCRIPTION,
73
- "scifact_claims_source": _SOURCE_CLAIMS_DESCRIPTION,
74
- "scifact_rationale_bigbio_pairs": _BIGBIO_PAIRS_RATIONALE_DESCRIPTION,
75
- "scifact_labelprediction_bigbio_pairs": _BIGBIO_PAIRS_LABELPREDICTION_DESCRIPTION,
76
- }
77
-
78
- _HOMEPAGE = "https://scifact.apps.allenai.org/"
79
-
80
-
81
- _LICENSE = 'Creative Commons Attribution Non Commercial 2.0 Generic'
82
-
83
- _URLS = {
84
- _DATASETNAME: "https://scifact.s3-us-west-2.amazonaws.com/release/latest/data.tar.gz",
85
- }
86
-
87
- _SUPPORTED_TASKS = [Tasks.TEXT_PAIRS_CLASSIFICATION]
88
-
89
- _SOURCE_VERSION = "1.0.0"
90
-
91
- _BIGBIO_VERSION = "1.0.0"
92
-
93
-
94
- class SciFact(datasets.GeneratorBasedBuilder):
95
- """
96
- SciFact is a dataset of 1.4K expert-written scientific claims paired with evidence-containing abstracts, and annotated with labels and rationales.
97
- """
98
-
99
- SOURCE_VERSION = datasets.Version(_SOURCE_VERSION)
100
- BIGBIO_VERSION = datasets.Version(_BIGBIO_VERSION)
101
-
102
- BUILDER_CONFIGS = [
103
- BigBioConfig(
104
- name="scifact_corpus_source",
105
- version=SOURCE_VERSION,
106
- description="scifact source schema for the corpus config",
107
- schema="source",
108
- subset_id="scifact_corpus_source",
109
- ),
110
- BigBioConfig(
111
- name="scifact_claims_source",
112
- version=SOURCE_VERSION,
113
- description="scifact source schema for the claims config",
114
- schema="source",
115
- subset_id="scifact_claims_source",
116
- ),
117
- BigBioConfig(
118
- name="scifact_rationale_bigbio_pairs",
119
- version=BIGBIO_VERSION,
120
- description="scifact BigBio text pairs classification schema for rationale task",
121
- schema="bigbio_pairs",
122
- subset_id="scifact_rationale_pairs",
123
- ),
124
- BigBioConfig(
125
- name="scifact_labelprediction_bigbio_pairs",
126
- version=BIGBIO_VERSION,
127
- description="scifact BigBio text pairs classification schema for label prediction task",
128
- schema="bigbio_pairs",
129
- subset_id="scifact_labelprediction_pairs",
130
- ),
131
- ]
132
-
133
- DEFAULT_CONFIG_NAME = "scifact_claims_source"
134
-
135
- def _info(self) -> datasets.DatasetInfo:
136
-
137
- if self.config.schema == "source":
138
- # modified from
139
- # https://huggingface.co/datasets/scifact/blob/main/scifact.py#L50
140
-
141
- if self.config.name == "scifact_corpus_source":
142
- features = datasets.Features(
143
- {
144
- "doc_id": Value("int32"), # The document's S2ORC ID.
145
- "title": Value("string"), # The title.
146
- "abstract": [Value("string")], # The abstract, written as a list of sentences.
147
- "structured": Value("bool"), # Indicator for whether this is a structured abstract.
148
- }
149
- )
150
-
151
- elif self.config.name == "scifact_claims_source":
152
- features = datasets.Features(
153
- {
154
- "id": Value("int32"), # An integer claim ID.
155
- "claim": Value("string"), # The text of the claim.
156
- "evidences": [
157
- {
158
- "doc_id": Value("int32"), # source doc_id for evidence
159
- "sentence_ids": [Value("int32")], # sentence ids from doc_id
160
- "label": Value("string"), # SUPPORT or CONTRADICT
161
- },
162
- ],
163
- "cited_doc_ids": [Value("int32")], # The claim's "cited documents".
164
- }
165
- )
166
-
167
- else:
168
- raise NotImplementedError(
169
- f"{self.config.name} config not implemented"
170
- )
171
-
172
- elif self.config.schema == "bigbio_pairs":
173
- features = pairs_features
174
-
175
- else:
176
- raise NotImplementedError(f"{self.config.schema} schema not implemented")
177
-
178
- return datasets.DatasetInfo(
179
- description=_DESCRIPTION[self.config.name],
180
- features=features,
181
- homepage=_HOMEPAGE,
182
- license=str(_LICENSE),
183
- citation=_CITATION,
184
- )
185
-
186
- def _split_generators(self, dl_manager) -> List[datasets.SplitGenerator]:
187
- urls = _URLS[_DATASETNAME]
188
- self.config.data_dir = dl_manager.download_and_extract(urls)
189
-
190
- if self.config.name == "scifact_corpus_source":
191
- return [
192
- datasets.SplitGenerator(
193
- name=datasets.Split.TRAIN,
194
- gen_kwargs={
195
- "filepath": os.path.join(
196
- self.config.data_dir, "data", "corpus.jsonl"
197
- ),
198
- "split": "train",
199
- },
200
- ),
201
- ]
202
-
203
- # the test split is only returned in source schema
204
- # this is b/c it only has claims with no cited docs or evidence
205
- # the bigbio implementation of this dataset requires
206
- # cited docs or evidence to construct samples
207
- elif self.config.name == "scifact_claims_source":
208
- return [
209
- datasets.SplitGenerator(
210
- name=datasets.Split.TRAIN,
211
- gen_kwargs={
212
- "filepath": os.path.join(
213
- self.config.data_dir, "data", "claims_train.jsonl"
214
- ),
215
- "split": "train",
216
- },
217
- ),
218
- datasets.SplitGenerator(
219
- name=datasets.Split.VALIDATION,
220
- gen_kwargs={
221
- "filepath": os.path.join(
222
- self.config.data_dir, "data", "claims_dev.jsonl"
223
- ),
224
- "split": "dev",
225
- },
226
- ),
227
- datasets.SplitGenerator(
228
- name=datasets.Split.TEST,
229
- gen_kwargs={
230
- "filepath": os.path.join(
231
- self.config.data_dir, "data", "claims_test.jsonl"
232
- ),
233
- "split": "test",
234
- },
235
- ),
236
- ]
237
-
238
- elif self.config.name in [
239
- "scifact_rationale_bigbio_pairs",
240
- "scifact_labelprediction_bigbio_pairs",
241
- ]:
242
- return [
243
- datasets.SplitGenerator(
244
- name=datasets.Split.TRAIN,
245
- gen_kwargs={
246
- "filepath": os.path.join(
247
- self.config.data_dir, "data", "claims_train.jsonl"
248
- ),
249
- "split": "train",
250
- },
251
- ),
252
- datasets.SplitGenerator(
253
- name=datasets.Split.VALIDATION,
254
- gen_kwargs={
255
- "filepath": os.path.join(
256
- self.config.data_dir, "data", "claims_dev.jsonl"
257
- ),
258
- "split": "dev",
259
- },
260
- ),
261
- ]
262
-
263
-
264
- def _source_generate_examples(self, filepath, split) -> Tuple[str, Dict[str, str]]:
265
-
266
- # here we just read corpus.jsonl and return the abstracts
267
- if self.config.name == "scifact_corpus_source":
268
- with open(filepath) as fp:
269
- for id_, row in enumerate(fp.readlines()):
270
- data = json.loads(row)
271
- yield id_, {
272
- "doc_id": int(data["doc_id"]),
273
- "title": data["title"],
274
- "abstract": data["abstract"],
275
- "structured": data["structured"],
276
- }
277
-
278
- # here we are reading one of claims_(train|dev|test).jsonl
279
- elif self.config.name == "scifact_claims_source":
280
-
281
- # claims_test.jsonl only has "id" and "claim" keys
282
- # claims_train.jsonl and claims_dev.jsonl sometimes have evidence
283
- with open(filepath) as fp:
284
- for id_, row in enumerate(fp.readlines()):
285
- data = json.loads(row)
286
- evidences_dict = data.get("evidence", {})
287
- evidences_list = []
288
- for doc_id, sent_lbl_list in evidences_dict.items():
289
- for sent_lbl_dict in sent_lbl_list:
290
- evidence = {
291
- "doc_id": doc_id,
292
- "sentence_ids": sent_lbl_dict["sentences"],
293
- "label": sent_lbl_dict["label"],
294
- }
295
- evidences_list.append(evidence)
296
-
297
- yield id_, {
298
- "id": data["id"],
299
- "claim": data["claim"],
300
- "evidences": evidences_list,
301
- "cited_doc_ids": data.get("cited_doc_ids", []),
302
- }
303
-
304
-
305
- def _bigbio_generate_examples(self, filepath, split) -> Tuple[str, Dict[str, str]]:
306
- """
307
- Here we always create one sample per sentence group.
308
- Any sentence group in an evidence attribute will have
309
- a label in {"rationale"} for the rationale task or
310
- in {"SUPPORT", "CONTRADICT"} for the labelprediction task.
311
- All other sentences will have either a "not_rationale"
312
- label or a "NOINFO" label depending on the task.
313
- """
314
-
315
- # read corpus (one row per abstract)
316
- corpus_file_path = os.path.join(self.config.data_dir, "data", "corpus.jsonl")
317
- df_corpus = pd.read_json(corpus_file_path, lines=True)
318
-
319
- # create one row per sentence and create sentence index
320
- df_sents = df_corpus.explode('abstract')
321
- df_sents = df_sents.rename(columns={"abstract": "sentence"})
322
- df_sents['sent_num'] = df_sents.groupby('doc_id').transform('cumcount')
323
- df_sents['doc_sent_id'] = df_sents.apply(lambda x: f"{x['doc_id']}-{x['sent_num']}", axis=1)
324
-
325
- # read claims
326
- df_claims = pd.read_json(filepath, lines=True)
327
-
328
-
329
- # join claims to corpus
330
- for _, claim_row in df_claims.iterrows():
331
-
332
- evidence = claim_row['evidence']
333
- cited_doc_ids = set(claim_row['cited_doc_ids'])
334
- evidence_doc_ids = set([int(doc_id) for doc_id in evidence.keys()])
335
-
336
- # assert all evidence doc IDs are in cited_doc_ids
337
- assert len(evidence_doc_ids - cited_doc_ids) == 0
338
-
339
- # this will have all abstract sentences from cited docs
340
- df_claim_sents = df_sents[df_sents['doc_id'].isin(cited_doc_ids)]
341
-
342
- # create all sentence samples as NOINFO then fix
343
- noinfo_samples = {}
344
- for _, row in df_claim_sents.iterrows():
345
- sample = {
346
- "claim": claim_row["claim"],
347
- "claim_id": claim_row["id"],
348
- "doc_id": row['doc_id'],
349
- "sentence_ids": (row['sent_num'],),
350
- "doc_sent_ids": (row['doc_sent_id'],),
351
- "span": row['sentence'].strip(),
352
- "label": "NOINFO",
353
- }
354
- noinfo_samples[sample["doc_sent_ids"]] = sample
355
-
356
- # create evidence samples and remove from noinfo samples as we go
357
- evidence_samples = []
358
- for doc_id_str, sent_lbl_list in evidence.items():
359
- doc_id = int(doc_id_str)
360
-
361
- for sent_lbl_dict in sent_lbl_list:
362
- sent_ids = sent_lbl_dict['sentences']
363
- doc_sent_ids = [f"{doc_id}-{sent_id}" for sent_id in sent_ids]
364
- df_evi = df_claim_sents[df_claim_sents['doc_sent_id'].isin(doc_sent_ids)]
365
-
366
- sample = {
367
- "claim": claim_row["claim"],
368
- "claim_id": claim_row["id"],
369
- "doc_id": doc_id,
370
- "sentence_ids": tuple(sent_ids),
371
- "doc_sent_ids": tuple(doc_sent_ids),
372
- "span": " ".join([el.strip() for el in df_evi["sentence"].values]),
373
- "label": sent_lbl_dict["label"],
374
- }
375
- evidence_samples.append(sample)
376
- for doc_sent_id in doc_sent_ids:
377
- del noinfo_samples[(doc_sent_id,)]
378
-
379
- # combine all sample and put back in sentence order
380
- all_samples = evidence_samples + list(noinfo_samples.values())
381
- all_samples = sorted(all_samples, key=lambda x: (x['doc_id'], x['sentence_ids'][0]))
382
-
383
- # add a unique ID
384
- for _id, sample in enumerate(all_samples):
385
- sample["id"] = f"{_id}-{sample['claim_id']}-{sample['doc_id']}-{sample['sentence_ids'][0]}"
386
-
387
- RATIONALE_LABEL_MAP = {
388
- "SUPPORT": "rationale",
389
- "CONTRADICT": "rationale",
390
- "NOINFO": "not_rationale",
391
- }
392
-
393
- if self.config.name == "scifact_rationale_bigbio_pairs":
394
- for sample in all_samples:
395
- yield sample['id'], {
396
- "id": sample["id"],
397
- "document_id": sample["doc_id"],
398
- "text_1": sample["claim"],
399
- "text_2": sample["span"],
400
- "label": RATIONALE_LABEL_MAP[sample['label']],
401
- }
402
-
403
- elif self.config.name == "scifact_labelprediction_bigbio_pairs":
404
- for sample in all_samples:
405
- yield sample['id'], {
406
- "id": sample["id"],
407
- "document_id": sample["doc_id"],
408
- "text_1": sample["claim"],
409
- "text_2": sample["span"],
410
- "label": sample['label'],
411
- }
412
-
413
- def _generate_examples(self, filepath, split) -> Tuple[int, dict]:
414
-
415
- if "source" in self.config.name:
416
- for sample in self._source_generate_examples(filepath, split):
417
- yield sample
418
-
419
- elif "bigbio" in self.config.name:
420
- for sample in self._bigbio_generate_examples(filepath, split):
421
- yield sample
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
scifact_claims_source/scifact-test.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:91c97ab2c95a4d8667e584be64360937deb516d3d2e913fac7acd4d5473671a9
3
+ size 22061
scifact_claims_source/scifact-train.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f2d077521342a70e7a99db1b9b1627ef20c0681eb2b85d9d9734036ffdd3d0f0
3
+ size 57620
scifact_claims_source/scifact-validation.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:34892eb6df304647d565eb0c9a2f8180dc1a0aea8499109f244a476715de9ee4
3
+ size 27632
scifact_corpus_source/scifact-train.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:689e335f5019ac8423c5374635ee7a781aa8eaa84829fa4cca696ac30ef32020
3
+ size 4707932
scifact_labelprediction_bigbio_pairs/scifact-train.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:637fb60743b76b3c577a938cd8702ab84af5888250b3e5c991c0bc513221462f
3
+ size 734358
scifact_labelprediction_bigbio_pairs/scifact-validation.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1a96582cc9f591514a785cf6632e86d02ae4d1bdba55b51c1b610c36083d0e3e
3
+ size 328236
scifact_rationale_bigbio_pairs/scifact-train.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4001a495396aecab9d4c828168f8eb9553f580088a5e4381e36c01ef21988c02
3
+ size 733912
scifact_rationale_bigbio_pairs/scifact-validation.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a3b126ab585782517ea9c4856bb446c34ab7f489ae2195f5b19a187bfd234d9f
3
+ size 328081