File size: 5,970 Bytes
152b8ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import json
import csv
import os
import datasets

logger = datasets.logging.get_logger(__name__)


_DESCRIPTION = "BEIR Benchmark"
_DATASETS = ["fiqa", "trec-covid", ""]

URL = ""
_URLs = {
    dataset: {
        "queries": URL + f"{dataset}/queries.jsonl", 
        "qrels": {
            "train": URL + f"{dataset}/qrels/train.tsv",
            "dev": URL + f"{dataset}/qrels/dev.tsv",
            "test": URL + f"{dataset}/qrels/test.tsv"
        }} for dataset in _DATASETS}


class BEIR(datasets.GeneratorBasedBuilder):
    """BEIR BenchmarkDataset."""

    BUILDER_CONFIGS = [
        datasets.BuilderConfig(
            name=dataset,
            description=f"This is the {dataset} dataset in BEIR Benchmark.",
        ) for dataset in _DATASETS
    ]
    

    def _info(self):
        return datasets.DatasetInfo(
            description=_DESCRIPTION,
             features=datasets.Features({
                "query": datasets.Value("string"), 
                "relevant": [{
                    "_id": datasets.Value("string"),
                    "score": datasets.Value("int32"),
                }],
             }),
            supervised_keys=None,
        )

    def _split_generators(self, dl_manager):
        """Returns SplitGenerators."""

        my_urls = _URLs[self.config.name]

        # All train, dev and test splits available for these datasets
        if self.config.name in ["msmarco", "nfcorpus", "hotpotqa", "fiqa", "fever"]:
            data_dir = dl_manager.download_and_extract(my_urls)
            return [
                datasets.SplitGenerator(
                    name=datasets.Split.TRAIN,
                    # These kwargs will be passed to _generate_examples
                    gen_kwargs={"query_path": data_dir["queries"],
                                "qrels_path": data_dir["qrels"]["train"]}
                ),
                datasets.SplitGenerator(
                    name="dev",
                    # These kwargs will be passed to _generate_examples
                    gen_kwargs={"query_path": data_dir["queries"],
                                "qrels_path": data_dir["qrels"]["dev"]}
                ),
                datasets.SplitGenerator(
                    name=datasets.Split.TEST,
                    # These kwargs will be passed to _generate_examples
                    gen_kwargs={"query_path": data_dir["queries"],
                                "qrels_path": data_dir["qrels"]["test"]}
                ),
            ]
        
        # Only train and test splits available for these datasets
        elif self.config.name in ["nq", "scifact"]:
            my_urls["qrels"].pop("dev", None)
            data_dir = dl_manager.download_and_extract(my_urls)
            
            return [
                datasets.SplitGenerator(
                    name=datasets.Split.TRAIN,
                    # These kwargs will be passed to _generate_examples
                    gen_kwargs={"query_path": data_dir["queries"],
                                "qrels_path": data_dir["qrels"]["train"]}
                ),
                datasets.SplitGenerator(
                    name=datasets.Split.TEST,
                    # These kwargs will be passed to _generate_examples
                    gen_kwargs={"query_path": data_dir["queries"],
                                "qrels_path": data_dir["qrels"]["test"]}
                ),
            ]
        
        # Only dev and test splits available for these datasets
        elif self.config.name in ["dbpedia", "quora"]:
            my_urls["qrels"].pop("train", None)
            data_dir = dl_manager.download_and_extract(my_urls)
            return [
                datasets.SplitGenerator(
                    name="dev",
                    # These kwargs will be passed to _generate_examples
                    gen_kwargs={"query_path": data_dir["queries"],
                                "qrels_path": data_dir["qrels"]["dev"]}
                ),
                datasets.SplitGenerator(
                    name=datasets.Split.TEST,
                    # These kwargs will be passed to _generate_examples
                    gen_kwargs={"query_path": data_dir["queries"],
                                "qrels_path": data_dir["qrels"]["test"]}
                ),
            ]
        
        # Only test split available for these datasets
        else:
            for split in ["train", "dev"]:
                my_urls["qrels"].pop(split, None)
            data_dir = dl_manager.download_and_extract(my_urls)
            return [
                datasets.SplitGenerator(
                    name=datasets.Split.TEST,
                    # These kwargs will be passed to _generate_examples
                    gen_kwargs={"query_path": data_dir["queries"],
                                "qrels_path": data_dir["qrels"]["test"]}
                ),
            ]


    def _generate_examples(self, query_path, qrels_path):
        """Yields examples."""
        
        queries, qrels = {}, {}

        with open(query_path, encoding="utf-8") as fIn:        
            text = fIn.readlines()

        for line in text:
            line = json.loads(line)
            queries[line.get("_id")] = line.get("text", "")
        
        reader = csv.reader(open(qrels_path, encoding="utf-8"), 
                    delimiter="\t", quoting=csv.QUOTE_MINIMAL)
        
        next(reader)

        for id, row in enumerate(reader):
            query_id, corpus_id, score = row[0], row[1], int(row[2])
            if query_id not in qrels:
                qrels[query_id] = {corpus_id: score}
            else:
                qrels[query_id][corpus_id] = score
        
        for i, query_id in enumerate(qrels):
            yield i, {
                "query": queries[query_id], 
                "relevant": [{"_id": doc_id, "score": score
                    } for doc_id, score in qrels[query_id].items()]
                    }