File size: 6,833 Bytes
62692d2
 
 
 
 
 
 
72bc61d
62692d2
 
 
 
 
 
b97c07d
62692d2
 
 
 
9fd3e2f
62692d2
 
 
 
 
 
 
 
 
 
 
 
 
 
d1a8022
62692d2
 
 
 
9fd3e2f
62692d2
 
 
 
 
 
 
 
d8797b9
62692d2
 
 
 
 
 
 
 
 
 
 
 
b97c07d
 
 
 
9fd3e2f
 
b97c07d
 
 
 
9fd3e2f
 
b97c07d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62692d2
 
 
 
 
9fd3e2f
 
62692d2
9fd3e2f
 
62692d2
 
 
 
b97c07d
 
 
 
62692d2
 
 
 
43ccb0d
62692d2
 
 
 
 
 
 
1320a6a
62692d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Loading script for the BLURB (Biomedical Language Understanding and Reasoning Benchmark)
benchmark for biomedical NLP."""

import json
from pathlib import Path
import datasets
import shutil
from constants import CITATIONS, DESCRIPTIONS, HOMEPAGES, DATA_URL

_LICENSE = "TBD"
_VERSION = "1.0.0"
DATA_DIR = "blurb/"


logger = datasets.logging.get_logger(__name__)

class BlurbConfig(datasets.BuilderConfig):
    """BuilderConfig for BLURB."""

    def __init__(self, task, data_url, citation, homepage, label_classes=("False", "True"), **kwargs):
        """BuilderConfig for BLURB.
        Args:
            task: `string` task the dataset is used for: 'ner', 'pico', 'rel-ext', 'sent-sim', 'doc-clas', 'qa'
          features: `list[string]`, list of the features that will appear in the
            feature dict. Should not include "label".
          data_url: `string`, url to download the data files from.
          citation: `string`, citation for the data set.
          url: `string`, url for information about the data set.
          label_classes: `list[string]`, the list of classes for the label if the
            label is present as a string. Non-string labels will be cast to either
            'False' or 'True'.
          **kwargs: keyword arguments forwarded to super.
        """
        # Version history:
        super(BlurbConfig, self).__init__(version=datasets.Version(_VERSION), **kwargs)
        self.task = task
        self.label_classes = label_classes
        self.data_url = data_url
        self.citation = citation
        self.homepage = homepage
        if self.task == 'ner':
            self.features = datasets.Features(
                                              {"id": datasets.Value("string"),
                                                  "tokens": datasets.Sequence(datasets.Value("string")),
                                                  "ner_tags": datasets.Sequence(
                                                      datasets.features.ClassLabel(names=self.label_classes)
                                                  )}
                                          )
            self.base_url = f"{self.data_url}{self.name}/"
            self.urls = {
                        "train": f"{self.base_url}{'train.tsv'}",
                        "validation": f"{self.base_url}{'devel.tsv'}",
                        "test": f"{self.base_url}{'test.tsv'}"
                        }


class Blurb(datasets.GeneratorBasedBuilder):
  """BLURB benchmark dataset for Biomedical Language Understanding and Reasoning Benchmark."""

  BUILDER_CONFIGS = [
    BlurbConfig(name='BC5CDR-chem-IOB', task='ner', label_classes=['O', 'B-Chemical', 'I-Chemical'],
                    data_url = DATA_URL['BC5CDR-chem-IOB'],
                    description=DESCRIPTIONS['BC5CDR-chem-IOB'],
                    citation=CITATIONS['BC5CDR-chem-IOB'],
                    homepage=HOMEPAGES['BC5CDR-chem-IOB']),

    BlurbConfig(name='BC5CDR-disease-IOB', task='ner', label_classes=['O', 'B-Disease', 'I-Disease'],
                    data_url = DATA_URL['BC5CDR-disease-IOB'],
                    description=DESCRIPTIONS['BC5CDR-disease-IOB'],
                    citation=CITATIONS['BC5CDR-disease-IOB'],
                    homepage=HOMEPAGES['BC5CDR-disease-IOB']),

    BlurbConfig(name='BC2GM-IOB', task='ner', label_classes=['O', 'B-GENE', 'I-GENE'],
                    data_url = DATA_URL['BC2GM-IOB'],
                    description=DESCRIPTIONS['BC2GM-IOB'],
                    citation=CITATIONS['BC2GM-IOB'],
                    homepage=HOMEPAGES['BC2GM-IOB']),

    BlurbConfig(name='NCBI-disease-IOB', task='ner', label_classes=['O', 'B-Disease', 'I-Disease'],
                    data_url = DATA_URL['NCBI-disease-IOB'],
                    description=DESCRIPTIONS['NCBI-disease-IOB'],
                    citation=CITATIONS['NCBI-disease-IOB'],
                    homepage=HOMEPAGES['NCBI-disease-IOB']),

    BlurbConfig(name='JNLPBA', task='ner', label_classes=['O', 'B-protein', 'I-protein',
                                                          'B-cell_type', 'I-cell_type',
                                                          'B-cell_line', 'I-cell_line',
                                                          'B-DNA','I-DNA', 'B-RNA', 'I-RNA'],
                    data_url = DATA_URL['JNLPBA'],
                    description=DESCRIPTIONS['JNLPBA'],
                    citation=CITATIONS['JNLPBA'],
                    homepage=HOMEPAGES['JNLPBA']),

  ]


  def _info(self):
      return datasets.DatasetInfo(
          description=self.config.description,
          features=self.config.features,
          supervised_keys=None,
          homepage=self.config.homepage,
          citation=self.config.citation,
      )

  def _split_generators(self, dl_manager):
      """Returns SplitGenerators."""
      print(self.config.base_url)
      print(self.config.data_url)
      for i in self.config.urls:    
        print(self.config.urls[i])
      
      if self.config.task == 'ner':
        downloaded_files = dl_manager.download_and_extract(self.config.urls)

      return self._ner_split_generator(downloaded_files)


  def _generate_examples(self, filepath):
    print("Before the download")
    logger.info("⏳ Generating examples from = %s", filepath)

    if self.config.task == 'ner':
      return self._ner_example_generator(filepath)

  def _ner_split_generator(self, downloaded_files):
      return [
          datasets.SplitGenerator(name=datasets.Split.TRAIN,
                                  gen_kwargs={"filepath": downloaded_files["train"]}),
          datasets.SplitGenerator(name=datasets.Split.VALIDATION,
                                  gen_kwargs={"filepath": downloaded_files["validation"]}),
          datasets.SplitGenerator(name=datasets.Split.TEST,
                                  gen_kwargs={"filepath": downloaded_files["test"]}),
      ]

  def _ner_example_generator(self, filepath):
    with open(filepath, encoding="utf-8") as f:
        guid = 0
        tokens = []
        ner_tags = []
        for line in f:
            if line == "" or line == "\n":
                if tokens:
                    yield guid, {
                        "id": str(guid),
                        "tokens": tokens,
                        "ner_tags": ner_tags,
                    }
                    guid += 1
                    tokens = []
                    ner_tags = []
            else:
                # tokens are tab separated
                splits = line.split("\t")
                tokens.append(splits[0])
                ner_tags.append(splits[1].rstrip())
        # last example
        yield guid, {
            "id": str(guid),
            "tokens": tokens,
            "ner_tags": ner_tags,
        }