-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathbeir.py
More file actions
337 lines (287 loc) · 9.81 KB
/
Copy pathbeir.py
File metadata and controls
337 lines (287 loc) · 9.81 KB
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
import json
import codecs
from typing import NamedTuple, Dict, List
import ir_datasets
from ir_datasets.util import ZipExtract, Cache, Lazy, Migrator
from ir_datasets.datasets.base import Dataset, YamlDocumentation, FilteredQueries
from ir_datasets.formats import BaseQueries, BaseDocs, BaseQrels, GenericDoc, GenericQuery, TrecQrel
from ir_datasets.indices import PickleLz4FullStore
_logger = ir_datasets.log.easy()
NAME = 'beir'
class BeirDoc(NamedTuple):
doc_id: str
text: str
title: str
metadata: Dict[str, str]
def default_text(self):
"""
title text
"""
return f'{self.title} {self.text}'
class BeirTitleDoc(NamedTuple):
doc_id: str
text: str
title: str
def default_text(self):
"""
title text
"""
return f'{self.title} {self.text}'
class BeirTitleUrlDoc(NamedTuple):
doc_id: str
text: str
title: str
url: str
def default_text(self):
"""
title text
"""
return f'{self.title} {self.text}'
class BeirSciDoc(NamedTuple):
doc_id: str
text: str
title: str
authors: List[str]
year: int
cited_by: List[str]
references: List[str]
def default_text(self):
"""
title text
"""
return f'{self.title} {self.text}'
class BeirCordDoc(NamedTuple):
doc_id: str
text: str
title: str
url: str
pubmed_id: str
def default_text(self):
"""
title text
"""
return f'{self.title} {self.text}'
class BeirToucheDoc(NamedTuple):
doc_id: str
text: str
title: str
stance: str
url: str
def default_text(self):
"""
title text
"""
return f'{self.title} {self.text}'
class BeirCqaDoc(NamedTuple):
doc_id: str
text: str
title: str
tags: List[str]
def default_text(self):
"""
title text
"""
return f'{self.title} {self.text}'
class BeirUrlQuery(NamedTuple):
query_id: str
text: str
url: str
def default_text(self):
"""
text
"""
return self.text
class BeirSciQuery(NamedTuple):
query_id: str
text: str
authors: List[str]
year: int
cited_by: List[str]
references: List[str]
def default_text(self):
"""
text
"""
return self.text
class BeirToucheQuery(NamedTuple):
query_id: str
text: str
description: str
narrative: str
def default_text(self):
"""
text
"""
return self.text
class BeirCovidQuery(NamedTuple):
query_id: str
text: str
query: str
narrative: str
def default_text(self):
"""
text
"""
return self.text
class BeirCqaQuery(NamedTuple):
query_id: str
text: str
tags: List[str]
def default_text(self):
"""
text
"""
return self.text
def _map_field(field, data):
if field in ('doc_id', 'query_id'):
return data['_id']
if field == 'text':
return data['text']
if field == 'title':
return data['title']
else:
return data['metadata'][field]
class BeirDocs(BaseDocs):
def __init__(self, name, dlc, doc_type):
super().__init__()
self._name = name
self._dlc = dlc
self._doc_type = doc_type
def docs_iter(self):
return iter(self.docs_store())
def _docs_iter(self):
with self._dlc.stream() as stream:
for line in stream:
data = json.loads(line)
yield self._doc_type(*(_map_field(f, data) for f in self._doc_type._fields))
def docs_cls(self):
return self._doc_type
def docs_store(self, field='doc_id'):
return PickleLz4FullStore(
path=f'{ir_datasets.util.home_path()/NAME/self._name}/docs.pklz4',
init_iter_fn=self._docs_iter,
data_cls=self.docs_cls(),
lookup_field=field,
index_fields=['doc_id'],
count_hint=ir_datasets.util.count_hint(f'{NAME}/{self._name}'),
)
def docs_count(self):
if self.docs_store().built():
return self.docs_store().count()
def docs_namespace(self):
return f'{NAME}/{self._name}'
def docs_lang(self):
return 'en'
class BeirQueries(BaseQueries):
def __init__(self, name, dlc, query_type):
super().__init__()
self._name = name
self._dlc = dlc
self._query_type = query_type
def queries_iter(self):
with self._dlc.stream() as stream:
for line in stream:
data = json.loads(line)
yield self._query_type(*(_map_field(f, data) for f in self._query_type._fields))
def queries_cls(self):
return self._query_type
def queries_namespace(self):
return f'{NAME}/{self._name}'
def queries_lang(self):
return 'en'
class BeirQrels(BaseQrels):
def __init__(self, qrels_dlc, qrels_defs):
self._qrels_dlc = qrels_dlc
self._qrels_defs = qrels_defs
def qrels_path(self):
return self._qrels_dlc.path()
def qrels_iter(self):
with self._qrels_dlc.stream() as f:
f = codecs.getreader('utf8')(f)
it = iter(f)
assert next(it).strip() == 'query-id\tcorpus-id\tscore' # header row
for line in it:
if line == '\n':
continue # ignore blank lines
cols = line.rstrip().split()
if len(cols) != 3:
raise RuntimeError(f'expected 3 columns, got {len(cols)}')
qid, did, score = cols
yield TrecQrel(qid, did, int(score), '0')
def qrels_cls(self):
return TrecQrel
def qrels_defs(self):
return self._qrels_defs
def _init():
base_path = ir_datasets.util.home_path()/NAME
dlc = ir_datasets.util.DownloadConfig.context(NAME, base_path)
documentation = YamlDocumentation(f'docs/{NAME}.yaml')
base = Dataset(documentation('_'))
subsets = {}
benchmarks = {
'msmarco': (['train', 'dev', 'test'], GenericDoc, GenericQuery),
'trec-covid': (['test'], BeirCordDoc, BeirCovidQuery),
'nfcorpus': (['train', 'dev', 'test'], BeirTitleUrlDoc, BeirUrlQuery),
'nq': (['test'], BeirTitleDoc, GenericQuery),
'hotpotqa': (['train', 'dev', 'test'], BeirTitleUrlDoc, GenericQuery),
'fiqa': (['train', 'dev', 'test'], GenericDoc, GenericQuery),
'arguana': (['test'], BeirTitleDoc, GenericQuery),
'webis-touche2020': (['test'], BeirToucheDoc, BeirToucheQuery),
'webis-touche2020/v2': (['test'], BeirToucheDoc, BeirToucheQuery),
'quora': (['dev', 'test'], GenericDoc, GenericQuery),
'dbpedia-entity': (['dev', 'test'], BeirTitleUrlDoc, GenericQuery),
'scidocs': (['test'], BeirSciDoc, BeirSciQuery),
'fever': (['train', 'dev', 'test'], BeirTitleDoc, GenericQuery),
'climate-fever': (['test'], BeirTitleDoc, GenericQuery),
'scifact': (['train', 'test'], BeirTitleDoc, GenericQuery),
}
for ds, (qrels, doc_type, query_type) in benchmarks.items():
dlc_ds = dlc[ds]
ds_zip = ds.split('/')[0]
docs_migrator = Migrator(base_path/ds/'irds_version.txt', 'v2',
affected_files=[f'{base_path/ds}/docs.pklz4'],
message=f'Migrating {NAME}/{ds} (structuring fields)')
docs = docs_migrator(BeirDocs(ds, ZipExtract(dlc_ds, f'{ds_zip}/corpus.jsonl'), doc_type))
queries = BeirQueries(ds, Cache(ZipExtract(dlc_ds, f'{ds_zip}/queries.jsonl'), base_path/ds/'queries.json'), query_type)
if len(qrels) == 1:
subsets[ds] = Dataset(
docs,
queries,
BeirQrels(Cache(ZipExtract(dlc_ds, f'{ds_zip}/qrels/{qrels[0]}.tsv'), base_path/ds/f'{qrels[0]}.qrels'), qrels_defs={}),
documentation(ds)
)
else:
subsets[ds] = Dataset(
docs,
queries,
documentation(ds)
)
for qrel in qrels:
subset_qrels = BeirQrels(Cache(ZipExtract(dlc_ds, f'{ds_zip}/qrels/{qrel}.tsv'), base_path/ds/f'{qrel}.qrels'), qrels_defs={})
subset_qids = qid_filter(subset_qrels)
subsets[f'{ds}/{qrel}'] = Dataset(
docs,
FilteredQueries(queries, subset_qids, mode='include'),
subset_qrels,
documentation(f'{ds}/{qrel}')
)
cqa = ['android', 'english', 'gaming', 'gis', 'mathematica', 'physics', 'programmers', 'stats', 'tex', 'unix', 'webmasters', 'wordpress']
cqa_dlc = dlc['cqadupstack']
for ds in cqa:
docs_migrator = Migrator(base_path/'cqadupstack'/ds/'irds_version.txt', 'v2',
affected_files=[f'{base_path/"cqadupstack"/ds}/docs.pklz4'],
message=f'Migrating {NAME}/cqadupstack/{ds} (structuring fields)')
subsets[f'cqadupstack/{ds}'] = Dataset(
docs_migrator(BeirDocs(f'cqadupstack/{ds}', ZipExtract(cqa_dlc, f'cqadupstack/{ds}/corpus.jsonl'), BeirCqaDoc)),
BeirQueries(f'cqadupstack/{ds}', Cache(ZipExtract(cqa_dlc, f'cqadupstack/{ds}/queries.jsonl'), base_path/'cqadupstack'/ds/'queries.json'), BeirCqaQuery),
BeirQrels(Cache(ZipExtract(cqa_dlc, f'cqadupstack/{ds}/qrels/test.tsv'), base_path/'cqadupstack'/ds/f'test.qrels'), qrels_defs={}),
documentation(f'cqadupstack/{ds}')
)
ir_datasets.registry.register(NAME, base)
for s in sorted(subsets):
ir_datasets.registry.register(f'{NAME}/{s}', subsets[s])
return base, subsets
def qid_filter(subset_qrels):
# NOTE: this must be in a separate function otherwise there can be weird lambda binding problems
return Lazy(lambda: {q.query_id for q in subset_qrels.qrels_iter()})
base, subsets = _init()