A815 commited on
Commit
21bc9b6
·
1 Parent(s): 811da59
app.py ADDED
@@ -0,0 +1,637 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+ import pickle
3
+ import os
4
+ from typing import Iterable, Callable, List, Dict, Optional, Type, TypeVar
5
+ from nlp4web_codebase.ir.data_loaders.dm import Document
6
+ from collections import Counter
7
+ import tqdm
8
+ import re
9
+ import nltk
10
+ nltk.download("stopwords", quiet=True)
11
+ from nltk.corpus import stopwords as nltk_stopwords
12
+
13
+ LANGUAGE = "english"
14
+ word_splitter = re.compile(r"(?u)\b\w\w+\b").findall
15
+ stopwords = set(nltk_stopwords.words(LANGUAGE))
16
+
17
+
18
+ def word_splitting(text: str) -> List[str]:
19
+ return word_splitter(text.lower())
20
+
21
+ def lemmatization(words: List[str]) -> List[str]:
22
+ return words # We ignore lemmatization here for simplicity
23
+
24
+ def simple_tokenize(text: str) -> List[str]:
25
+ words = word_splitting(text)
26
+ tokenized = list(filter(lambda w: w not in stopwords, words))
27
+ tokenized = lemmatization(tokenized)
28
+ return tokenized
29
+
30
+ T = TypeVar("T", bound="InvertedIndex")
31
+
32
+ @dataclass
33
+ class PostingList:
34
+ term: str # The term
35
+ docid_postings: List[int] # docid_postings[i] means the docid (int) of the i-th associated posting
36
+ tweight_postings: List[float] # tweight_postings[i] means the term weight (float) of the i-th associated posting
37
+
38
+
39
+ @dataclass
40
+ class InvertedIndex:
41
+ posting_lists: List[PostingList] # docid -> posting_list
42
+ vocab: Dict[str, int]
43
+ cid2docid: Dict[str, int] # collection_id -> docid
44
+ collection_ids: List[str] # docid -> collection_id
45
+ doc_texts: Optional[List[str]] = None # docid -> document text
46
+
47
+ def save(self, output_dir: str) -> None:
48
+ os.makedirs(output_dir, exist_ok=True)
49
+ with open(os.path.join(output_dir, "index.pkl"), "wb") as f:
50
+ pickle.dump(self, f)
51
+
52
+ @classmethod
53
+ def from_saved(cls: Type[T], saved_dir: str) -> T:
54
+ index = cls(
55
+ posting_lists=[], vocab={}, cid2docid={}, collection_ids=[], doc_texts=None
56
+ )
57
+ with open(os.path.join(saved_dir, "index.pkl"), "rb") as f:
58
+ index = pickle.load(f)
59
+ return index
60
+
61
+
62
+ # The output of the counting function:
63
+ @dataclass
64
+ class Counting:
65
+ posting_lists: List[PostingList]
66
+ vocab: Dict[str, int]
67
+ cid2docid: Dict[str, int]
68
+ collection_ids: List[str]
69
+ dfs: List[int] # tid -> df
70
+ dls: List[int] # docid -> doc length
71
+ avgdl: float
72
+ nterms: int
73
+ doc_texts: Optional[List[str]] = None
74
+
75
+ def run_counting(
76
+ documents: Iterable[Document],
77
+ tokenize_fn: Callable[[str], List[str]] = simple_tokenize,
78
+ store_raw: bool = True, # store the document text in doc_texts
79
+ ndocs: Optional[int] = None,
80
+ show_progress_bar: bool = True,
81
+ ) -> Counting:
82
+ """Counting TFs, DFs, doc_lengths, etc."""
83
+ posting_lists: List[PostingList] = []
84
+ vocab: Dict[str, int] = {}
85
+ cid2docid: Dict[str, int] = {}
86
+ collection_ids: List[str] = []
87
+ dfs: List[int] = [] # tid -> df
88
+ dls: List[int] = [] # docid -> doc length
89
+ nterms: int = 0
90
+ doc_texts: Optional[List[str]] = []
91
+ for doc in tqdm.tqdm(
92
+ documents,
93
+ desc="Counting",
94
+ total=ndocs,
95
+ disable=not show_progress_bar,
96
+ ):
97
+ if doc.collection_id in cid2docid:
98
+ continue
99
+ collection_ids.append(doc.collection_id)
100
+ docid = cid2docid.setdefault(doc.collection_id, len(cid2docid))
101
+ toks = tokenize_fn(doc.text)
102
+ tok2tf = Counter(toks)
103
+ dls.append(sum(tok2tf.values()))
104
+ for tok, tf in tok2tf.items():
105
+ nterms += tf
106
+ tid = vocab.get(tok, None)
107
+ if tid is None:
108
+ posting_lists.append(
109
+ PostingList(term=tok, docid_postings=[], tweight_postings=[])
110
+ )
111
+ tid = vocab.setdefault(tok, len(vocab))
112
+ posting_lists[tid].docid_postings.append(docid)
113
+ posting_lists[tid].tweight_postings.append(tf)
114
+ if tid < len(dfs):
115
+ dfs[tid] += 1
116
+ else:
117
+ dfs.append(0)
118
+ if store_raw:
119
+ doc_texts.append(doc.text)
120
+ else:
121
+ doc_texts = None
122
+ return Counting(
123
+ posting_lists=posting_lists,
124
+ vocab=vocab,
125
+ cid2docid=cid2docid,
126
+ collection_ids=collection_ids,
127
+ dfs=dfs,
128
+ dls=dls,
129
+ avgdl=sum(dls) / len(dls),
130
+ nterms=nterms,
131
+ doc_texts=doc_texts,
132
+ )
133
+
134
+ from nlp4web_codebase.ir.data_loaders.sciq import load_sciq
135
+ sciq = load_sciq()
136
+ counting = run_counting(documents=iter(sciq.corpus), ndocs=len(sciq.corpus))
137
+
138
+
139
+ from __future__ import annotations
140
+ from dataclasses import asdict, dataclass
141
+ import math
142
+ import os
143
+ from typing import Iterable, List, Optional, Type
144
+ import tqdm
145
+ from nlp4web_codebase.ir.data_loaders.dm import Document
146
+
147
+
148
+ @dataclass
149
+ class BM25Index(InvertedIndex):
150
+
151
+ @staticmethod
152
+ def tokenize(text: str) -> List[str]:
153
+ return simple_tokenize(text)
154
+
155
+ @staticmethod
156
+ def cache_term_weights(
157
+ posting_lists: List[PostingList],
158
+ total_docs: int,
159
+ avgdl: float,
160
+ dfs: List[int],
161
+ dls: List[int],
162
+ k1: float,
163
+ b: float,
164
+ ) -> None:
165
+ """Compute term weights and caching"""
166
+
167
+ N = total_docs
168
+ for tid, posting_list in enumerate(
169
+ tqdm.tqdm(posting_lists, desc="Regularizing TFs")
170
+ ):
171
+ idf = BM25Index.calc_idf(df=dfs[tid], N=N)
172
+ for i in range(len(posting_list.docid_postings)):
173
+ docid = posting_list.docid_postings[i]
174
+ tf = posting_list.tweight_postings[i]
175
+ dl = dls[docid]
176
+ regularized_tf = BM25Index.calc_regularized_tf(
177
+ tf=tf, dl=dl, avgdl=avgdl, k1=k1, b=b
178
+ )
179
+ posting_list.tweight_postings[i] = regularized_tf * idf
180
+
181
+ @staticmethod
182
+ def calc_regularized_tf(
183
+ tf: int, dl: float, avgdl: float, k1: float, b: float
184
+ ) -> float:
185
+ return tf / (tf + k1 * (1 - b + b * dl / avgdl))
186
+
187
+ @staticmethod
188
+ def calc_idf(df: int, N: int):
189
+ return math.log(1 + (N - df + 0.5) / (df + 0.5))
190
+
191
+ @classmethod
192
+ def build_from_documents(
193
+ cls: Type[BM25Index],
194
+ documents: Iterable[Document],
195
+ store_raw: bool = True,
196
+ output_dir: Optional[str] = None,
197
+ ndocs: Optional[int] = None,
198
+ show_progress_bar: bool = True,
199
+ k1: float = 0.9,
200
+ b: float = 0.4,
201
+ ) -> BM25Index:
202
+ # Counting TFs, DFs, doc_lengths, etc.:
203
+ counting = run_counting(
204
+ documents=documents,
205
+ tokenize_fn=BM25Index.tokenize,
206
+ store_raw=store_raw,
207
+ ndocs=ndocs,
208
+ show_progress_bar=show_progress_bar,
209
+ )
210
+
211
+ # Compute term weights and caching:
212
+ posting_lists = counting.posting_lists
213
+ total_docs = len(counting.cid2docid)
214
+ BM25Index.cache_term_weights(
215
+ posting_lists=posting_lists,
216
+ total_docs=total_docs,
217
+ avgdl=counting.avgdl,
218
+ dfs=counting.dfs,
219
+ dls=counting.dls,
220
+ k1=k1,
221
+ b=b,
222
+ )
223
+
224
+ # Assembly and save:
225
+ index = BM25Index(
226
+ posting_lists=posting_lists,
227
+ vocab=counting.vocab,
228
+ cid2docid=counting.cid2docid,
229
+ collection_ids=counting.collection_ids,
230
+ doc_texts=counting.doc_texts,
231
+ )
232
+ return index
233
+
234
+ bm25_index = BM25Index.build_from_documents(
235
+ documents=iter(sciq.corpus),
236
+ ndocs=12160,
237
+ show_progress_bar=True,
238
+ )
239
+ bm25_index.save("output/bm25_index")
240
+
241
+
242
+ from nlp4web_codebase.ir.models import BaseRetriever
243
+ from typing import Type
244
+ from abc import abstractmethod
245
+
246
+
247
+ class BaseInvertedIndexRetriever(BaseRetriever):
248
+
249
+ @property
250
+ @abstractmethod
251
+ def index_class(self) -> Type[InvertedIndex]:
252
+ pass
253
+
254
+ def __init__(self, index_dir: str) -> None:
255
+ self.index = self.index_class.from_saved(index_dir)
256
+
257
+ def get_term_weights(self, query: str, cid: str) -> Dict[str, float]:
258
+ toks = self.index.tokenize(query)
259
+ target_docid = self.index.cid2docid[cid]
260
+ term_weights = {}
261
+ for tok in toks:
262
+ if tok not in self.index.vocab:
263
+ continue
264
+ tid = self.index.vocab[tok]
265
+ posting_list = self.index.posting_lists[tid]
266
+ for docid, tweight in zip(
267
+ posting_list.docid_postings, posting_list.tweight_postings
268
+ ):
269
+ if docid == target_docid:
270
+ term_weights[tok] = tweight
271
+ break
272
+ return term_weights
273
+
274
+ def score(self, query: str, cid: str) -> float:
275
+ return sum(self.get_term_weights(query=query, cid=cid).values())
276
+
277
+ def retrieve(self, query: str, topk: int = 10) -> Dict[str, float]:
278
+ toks = self.index.tokenize(query)
279
+ docid2score: Dict[int, float] = {}
280
+ for tok in toks:
281
+ if tok not in self.index.vocab:
282
+ continue
283
+ tid = self.index.vocab[tok]
284
+ posting_list = self.index.posting_lists[tid]
285
+ for docid, tweight in zip(
286
+ posting_list.docid_postings, posting_list.tweight_postings
287
+ ):
288
+ docid2score.setdefault(docid, 0)
289
+ docid2score[docid] += tweight
290
+ docid2score = dict(
291
+ sorted(docid2score.items(), key=lambda pair: pair[1], reverse=True)[:topk]
292
+ )
293
+ return {
294
+ self.index.collection_ids[docid]: score
295
+ for docid, score in docid2score.items()
296
+ }
297
+
298
+
299
+ class BM25Retriever(BaseInvertedIndexRetriever):
300
+
301
+ @property
302
+ def index_class(self) -> Type[BM25Index]:
303
+ return BM25Index
304
+
305
+
306
+ from nlp4web_codebase.ir.data_loaders import Split
307
+ import pytrec_eval
308
+ import numpy as np
309
+
310
+
311
+ def evaluate_map(rankings: Dict[str, Dict[str, float]], split=Split.dev) -> float:
312
+ metric = "map_cut_10"
313
+ qrels = sciq.get_qrels_dict(split)
314
+ evaluator = pytrec_eval.RelevanceEvaluator(sciq.get_qrels_dict(split), (metric,))
315
+ qps = evaluator.evaluate(rankings)
316
+ return float(np.mean([qp[metric] for qp in qps.values()]))
317
+
318
+
319
+
320
+ # Loading dataset:
321
+ from nlp4web_codebase.ir.data_loaders.sciq import load_sciq
322
+ sciq = load_sciq()
323
+ counting = run_counting(documents=iter(sciq.corpus), ndocs=len(sciq.corpus))
324
+
325
+ # Building BM25 index and save:
326
+ bm25_index = BM25Index.build_from_documents(
327
+ documents=iter(sciq.corpus),
328
+ ndocs=12160,
329
+ show_progress_bar=True
330
+ )
331
+ bm25_index.save("output/bm25_index")
332
+
333
+
334
+
335
+ from scipy.sparse._csc import csc_matrix
336
+
337
+
338
+ @dataclass
339
+ class CSCInvertedIndex:
340
+ posting_lists_matrix: csc_matrix # docid -> posting_list
341
+ vocab: Dict[str, int]
342
+ cid2docid: Dict[str, int] # collection_id -> docid
343
+ collection_ids: List[str] # docid -> collection_id
344
+ doc_texts: Optional[List[str]] = None # docid -> document text
345
+
346
+ def save(self, output_dir: str) -> None:
347
+ os.makedirs(output_dir, exist_ok=True)
348
+ with open(os.path.join(output_dir, "index.pkl"), "wb") as f:
349
+ pickle.dump(self, f)
350
+
351
+ @classmethod
352
+ def from_saved(cls: Type[T], saved_dir: str) -> T:
353
+ index = cls(
354
+ posting_lists_matrix=None, vocab={}, cid2docid={}, collection_ids=[], doc_texts=None
355
+ )
356
+ with open(os.path.join(saved_dir, "index.pkl"), "rb") as f:
357
+ index = pickle.load(f)
358
+ return index
359
+
360
+
361
+ @dataclass
362
+ class CSCBM25Index(CSCInvertedIndex):
363
+
364
+ @staticmethod
365
+ def tokenize(text: str) -> List[str]:
366
+ return simple_tokenize(text)
367
+
368
+ @staticmethod
369
+ def cache_term_weights(
370
+ posting_lists: List[PostingList],
371
+ total_docs: int,
372
+ avgdl: float,
373
+ dfs: List[int],
374
+ dls: List[int],
375
+ k1: float,
376
+ b: float,
377
+ ) -> csc_matrix:
378
+ """Compute term weights and caching"""
379
+
380
+ ## YOUR_CODE_STARTS_HERE
381
+
382
+ # total_terms = len(posting_lists)
383
+ # matrix = np.zeros((total_terms, total_docs))
384
+ # N = total_docs
385
+ # for tid, posting_list in enumerate(
386
+ # tqdm.tqdm(posting_lists, desc="Regularizing TFs")
387
+ # ):
388
+ # df = dfs[tid]
389
+ # idf = CSCBM25Index.calc_idf(df, N)
390
+ # for i in range(len(posting_list.docid_postings)):
391
+ # docid = posting_list.docid_postings[i]
392
+ # dl = dls[docid]
393
+ # tf = posting_list.tweight_postings[i]
394
+ # regularized_tf = CSCBM25Index.calc_regularized_tf(tf, dl, avgdl, k1, b)
395
+ # new_weight = regularized_tf * idf
396
+
397
+ # posting_list.tweight_postings[i] = new_weight
398
+ # matrix[tid][docid] = new_weight
399
+
400
+ # posting_lists_matrix = csc_matrix(matrix)
401
+ # return posting_lists_matrix
402
+
403
+
404
+ # total_terms = len(posting_lists)
405
+ # matrix = np.zeros((total_docs, total_terms))
406
+ # N = total_docs
407
+ # for tid, posting_list in enumerate(
408
+ # tqdm.tqdm(posting_lists, desc="Regularizing TFs")
409
+ # ):
410
+ # df = dfs[tid] # Document Frequency für jeden Term
411
+ # idf = CSCBM25Index.calc_idf(df, N)
412
+ # for i in range(len(posting_list.docid_postings)):
413
+ # docid = posting_list.docid_postings[i]
414
+ # dl = dls[docid]
415
+ # tf = posting_list.tweight_postings[i]
416
+ # regularized_tf = CSCBM25Index.calc_regularized_tf(tf, dl, avgdl, k1, b)
417
+ # new_weight = regularized_tf * idf
418
+
419
+ # # posting_list.tweight_postings[i] = new_weight
420
+ # matrix[docid][tid] = new_weight
421
+
422
+ # posting_lists_matrix = csc_matrix(matrix)
423
+ # return posting_lists_matrix
424
+
425
+ data_tweights = []
426
+ row_ind = []
427
+ col_ind = []
428
+ shape = (total_docs, len(posting_lists))
429
+ N = total_docs
430
+ for tid, posting_el in enumerate(
431
+ tqdm.tqdm(posting_lists, desc="Regularizing TFs")
432
+ ):
433
+ df = dfs[tid]
434
+ idf = CSCBM25Index.calc_idf(df, N)
435
+ for i in range(len(posting_el.docid_postings)):
436
+ docid = posting_el.docid_postings[i]
437
+ dl = dls[docid]
438
+ tf = posting_el.tweight_postings[i]
439
+ regularized_tf = CSCBM25Index.calc_regularized_tf(tf, dl, avgdl, k1, b)
440
+ new_weight = regularized_tf * idf
441
+
442
+ data_tweights.append(new_weight)
443
+ col_ind.append(tid)
444
+ row_ind.append(docid)
445
+
446
+ posting_lists_matrix = csc_matrix((data_tweights, (row_ind, col_ind)), shape, dtype=np.float32)
447
+ return posting_lists_matrix
448
+
449
+
450
+ ## YOUR_CODE_ENDS_HERE
451
+
452
+ @staticmethod
453
+ def calc_regularized_tf(
454
+ tf: int, dl: float, avgdl: float, k1: float, b: float
455
+ ) -> float:
456
+ return tf / (tf + k1 * (1 - b + b * dl / avgdl))
457
+
458
+ @staticmethod
459
+ def calc_idf(df: int, N: int):
460
+ return math.log(1 + (N - df + 0.5) / (df + 0.5))
461
+
462
+ @classmethod
463
+ def build_from_documents(
464
+ cls: Type[CSCBM25Index],
465
+ documents: Iterable[Document],
466
+ store_raw: bool = True,
467
+ output_dir: Optional[str] = None,
468
+ ndocs: Optional[int] = None,
469
+ show_progress_bar: bool = True,
470
+ k1: float = 0.9,
471
+ b: float = 0.4,
472
+ ) -> CSCBM25Index:
473
+ # Counting TFs, DFs, doc_lengths, etc.:
474
+ counting = run_counting(
475
+ documents=documents,
476
+ tokenize_fn=CSCBM25Index.tokenize,
477
+ store_raw=store_raw,
478
+ ndocs=ndocs,
479
+ show_progress_bar=show_progress_bar,
480
+ )
481
+
482
+ # Compute term weights and caching:
483
+ posting_lists = counting.posting_lists
484
+ total_docs = len(counting.cid2docid)
485
+ posting_lists_matrix = CSCBM25Index.cache_term_weights(
486
+ posting_lists=posting_lists,
487
+ total_docs=total_docs,
488
+ avgdl=counting.avgdl,
489
+ dfs=counting.dfs,
490
+ dls=counting.dls,
491
+ k1=k1,
492
+ b=b,
493
+ )
494
+
495
+ # Assembly and save:
496
+ index = CSCBM25Index(
497
+ posting_lists_matrix=posting_lists_matrix,
498
+ vocab=counting.vocab,
499
+ cid2docid=counting.cid2docid,
500
+ collection_ids=counting.collection_ids,
501
+ doc_texts=counting.doc_texts,
502
+ )
503
+ return index
504
+
505
+ csc_bm25_index = CSCBM25Index.build_from_documents(
506
+ documents=iter(sciq.corpus),
507
+ ndocs=12160,
508
+ show_progress_bar=True,
509
+ k1=best_k1,
510
+ b=best_b
511
+ )
512
+ csc_bm25_index.save("output/csc_bm25_index")
513
+
514
+
515
+
516
+ class BaseCSCInvertedIndexRetriever(BaseRetriever):
517
+
518
+ @property
519
+ @abstractmethod
520
+ def index_class(self) -> Type[CSCInvertedIndex]:
521
+ pass
522
+
523
+ def __init__(self, index_dir: str) -> None:
524
+ self.index = self.index_class.from_saved(index_dir)
525
+
526
+ def get_term_weights(self, query: str, cid: str) -> Dict[str, float]:
527
+ ## YOUR_CODE_STARTS_HERE
528
+
529
+ # toks = self.index.tokenize(query)
530
+ # term_weight = {}
531
+ # docid = self.index.cid2docid[cid]
532
+ # csc_output = self.index.posting_lists_matrix.getcol(docid)
533
+ # for tok in toks:
534
+ # if tok not in self.index.vocab:
535
+ # continue
536
+ # tid = self.index.vocab[tok]
537
+ # for id, tweight in zip(csc_output.indices, csc_output.data):
538
+ # if id == tid:
539
+ # term_weight[tok] = tweight
540
+ # continue
541
+
542
+ # return term_weight
543
+
544
+ toks = self.index.tokenize(query)
545
+ term_weight = {}
546
+ docid = self.index.cid2docid[cid]
547
+ csc_output = self.index.posting_lists_matrix.getrow(docid)
548
+ for tok in toks:
549
+ if tok not in self.index.vocab:
550
+ continue
551
+ tid = self.index.vocab[tok]
552
+ for id, tweight in zip(csc_output.indices, csc_output.data):
553
+ if id == tid:
554
+ term_weight[tok] = tweight
555
+ continue
556
+
557
+ return term_weight
558
+
559
+ ## YOUR_CODE_ENDS_HERE
560
+
561
+ def score(self, query: str, cid: str) -> float:
562
+ return sum(self.get_term_weights(query=query, cid=cid).values())
563
+
564
+ def retrieve(self, query: str, topk: int = 10) -> Dict[str, float]:
565
+ ## YOUR_CODE_STARTS_HERE
566
+
567
+ ranking: Dict[str, float] = {}
568
+ toks = self.index.tokenize(query)
569
+ docid2score: Dict[int, float] = {}
570
+ for tok in toks:
571
+ if tok not in self.index.vocab:
572
+ continue
573
+ tid = self.index.vocab[tok]
574
+ tid2documents = self.index.posting_lists_matrix.getcol(tid)
575
+ for docid, tweight in zip(tid2documents.indices, tid2documents.data):
576
+ docid2score.setdefault(docid, 0)
577
+ docid2score[docid] += tweight
578
+
579
+ docid2score = dict(
580
+ sorted(docid2score.items(), key=lambda pair: pair[1], reverse=True)[:topk]
581
+ )
582
+ ranking = {
583
+ self.index.collection_ids[docid]: score
584
+ for docid, score in docid2score.items()
585
+ }
586
+ return ranking
587
+
588
+
589
+ ## YOUR_CODE_ENDS_HERE
590
+
591
+
592
+ class CSCBM25Retriever(BaseCSCInvertedIndexRetriever):
593
+
594
+ @property
595
+ def index_class(self) -> Type[CSCBM25Index]:
596
+ return CSCBM25Index
597
+
598
+
599
+
600
+ import gradio as gr
601
+ from typing import TypedDict
602
+
603
+ class Hit(TypedDict):
604
+ cid: str
605
+ score: float
606
+ text: str
607
+
608
+ demo: Optional[gr.Interface] = None # Assign your gradio demo to this variable
609
+ return_type = List[Hit]
610
+
611
+ ## YOUR_CODE_STARTS_HERE
612
+
613
+ def search(query) -> List[Hit]:
614
+ return_type: List[Hit] = []
615
+ bm_25_retriever = BM25Retriever(index_dir="output/bm25_index")
616
+ ranking = bm_25_retriever.retrieve(query)
617
+ for rank in ranking:
618
+ # print(rank, ranking[rank])
619
+ # print(bm_25_retriever.index.cid2docid[rank])
620
+ # print(bm_25_retriever.index.doc_texts[bm_25_retriever.index.cid2docid[rank]])
621
+ hit = {
622
+ "cid": rank,
623
+ "score": ranking[rank],
624
+ "text": bm_25_retriever.index.doc_texts[bm_25_retriever.index.cid2docid[rank]]
625
+ }
626
+ return_type.append(hit)
627
+
628
+ return return_type
629
+
630
+ demo = gr.Interface(
631
+ fn=search,
632
+ inputs=["text"],
633
+ outputs="json"
634
+ )
635
+
636
+ ## YOUR_CODE_ENDS_HERE
637
+ demo.launch()
nlp4web_codebase/__init__.py ADDED
File without changes
nlp4web_codebase/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (171 Bytes). View file
 
nlp4web_codebase/ir/__init__.py ADDED
File without changes
nlp4web_codebase/ir/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (174 Bytes). View file
 
nlp4web_codebase/ir/__pycache__/analysis.cpython-312.pyc ADDED
Binary file (7.58 kB). View file
 
nlp4web_codebase/ir/analysis.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from typing import Dict, List, Optional, Protocol
3
+ import pandas as pd
4
+ import tqdm
5
+ import ujson
6
+ from nlp4web_codebase.ir.data_loaders import IRDataset
7
+
8
+
9
+ def round_dict(obj: Dict[str, float], ndigits: int = 4) -> Dict[str, float]:
10
+ return {k: round(v, ndigits=ndigits) for k, v in obj.items()}
11
+
12
+
13
+ def sort_dict(obj: Dict[str, float], reverse: bool = True) -> Dict[str, float]:
14
+ return dict(sorted(obj.items(), key=lambda pair: pair[1], reverse=reverse))
15
+
16
+
17
+ def save_ranking_results(
18
+ output_dir: str,
19
+ query_ids: List[str],
20
+ rankings: List[Dict[str, float]],
21
+ query_performances_lists: List[Dict[str, float]],
22
+ cid2tweights_lists: Optional[List[Dict[str, Dict[str, float]]]] = None,
23
+ ):
24
+ os.makedirs(output_dir, exist_ok=True)
25
+ output_path = os.path.join(output_dir, "ranking_results.jsonl")
26
+ rows = []
27
+ for i, (query_id, ranking, query_performances) in enumerate(
28
+ zip(query_ids, rankings, query_performances_lists)
29
+ ):
30
+ row = {
31
+ "query_id": query_id,
32
+ "ranking": round_dict(ranking),
33
+ "query_performances": round_dict(query_performances),
34
+ "cid2tweights": {},
35
+ }
36
+ if cid2tweights_lists is not None:
37
+ row["cid2tweights"] = {
38
+ cid: round_dict(tws) for cid, tws in cid2tweights_lists[i].items()
39
+ }
40
+ rows.append(row)
41
+ pd.DataFrame(rows).to_json(
42
+ output_path,
43
+ orient="records",
44
+ lines=True,
45
+ )
46
+
47
+
48
+ class TermWeightingFunction(Protocol):
49
+ def __call__(self, query: str, cid: str) -> Dict[str, float]: ...
50
+
51
+
52
+ def compare(
53
+ dataset: IRDataset,
54
+ results_path1: str,
55
+ results_path2: str,
56
+ output_dir: str,
57
+ main_metric: str = "recip_rank",
58
+ system1: Optional[str] = None,
59
+ system2: Optional[str] = None,
60
+ term_weighting_fn1: Optional[TermWeightingFunction] = None,
61
+ term_weighting_fn2: Optional[TermWeightingFunction] = None,
62
+ ) -> None:
63
+ os.makedirs(output_dir, exist_ok=True)
64
+ df1 = pd.read_json(results_path1, orient="records", lines=True)
65
+ df2 = pd.read_json(results_path2, orient="records", lines=True)
66
+ assert len(df1) == len(df2)
67
+ all_qrels = {}
68
+ for split in dataset.split2qrels:
69
+ all_qrels.update(dataset.get_qrels_dict(split))
70
+ qid2query = {query.query_id: query for query in dataset.queries}
71
+ cid2doc = {doc.collection_id: doc for doc in dataset.corpus}
72
+ diff_col = f"{main_metric}:qp1-qp2"
73
+ merged = pd.merge(df1, df2, on="query_id", how="outer")
74
+ rows = []
75
+ for _, example in tqdm.tqdm(merged.iterrows(), desc="Comparing", total=len(merged)):
76
+ docs = {cid: cid2doc[cid].text for cid in dict(example["ranking_x"])}
77
+ docs.update({cid: cid2doc[cid].text for cid in dict(example["ranking_y"])})
78
+ query_id = example["query_id"]
79
+ row = {
80
+ "query_id": query_id,
81
+ "query": qid2query[query_id].text,
82
+ diff_col: example["query_performances_x"][main_metric]
83
+ - example["query_performances_y"][main_metric],
84
+ "ranking1": ujson.dumps(example["ranking_x"], indent=4),
85
+ "ranking2": ujson.dumps(example["ranking_y"], indent=4),
86
+ "docs": ujson.dumps(docs, indent=4),
87
+ "query_performances1": ujson.dumps(
88
+ example["query_performances_x"], indent=4
89
+ ),
90
+ "query_performances2": ujson.dumps(
91
+ example["query_performances_y"], indent=4
92
+ ),
93
+ "qrels": ujson.dumps(all_qrels[query_id], indent=4),
94
+ }
95
+ if term_weighting_fn1 is not None and term_weighting_fn2 is not None:
96
+ all_cids = set(example["ranking_x"]) | set(example["ranking_y"])
97
+ cid2tweights1 = {}
98
+ cid2tweights2 = {}
99
+ ranking1 = {}
100
+ ranking2 = {}
101
+ for cid in all_cids:
102
+ tweights1 = term_weighting_fn1(query=qid2query[query_id].text, cid=cid)
103
+ tweights2 = term_weighting_fn2(query=qid2query[query_id].text, cid=cid)
104
+ ranking1[cid] = sum(tweights1.values())
105
+ ranking2[cid] = sum(tweights2.values())
106
+ cid2tweights1[cid] = tweights1
107
+ cid2tweights2[cid] = tweights2
108
+ ranking1 = sort_dict(ranking1)
109
+ ranking2 = sort_dict(ranking2)
110
+ row["ranking1"] = ujson.dumps(ranking1, indent=4)
111
+ row["ranking2"] = ujson.dumps(ranking2, indent=4)
112
+ cid2tweights1 = {cid: cid2tweights1[cid] for cid in ranking1}
113
+ cid2tweights2 = {cid: cid2tweights2[cid] for cid in ranking2}
114
+ row["cid2tweights1"] = ujson.dumps(cid2tweights1, indent=4)
115
+ row["cid2tweights2"] = ujson.dumps(cid2tweights2, indent=4)
116
+ rows.append(row)
117
+ table = pd.DataFrame(rows).sort_values(by=diff_col, ascending=False)
118
+ output_path = os.path.join(output_dir, f"compare-{system1}_vs_{system2}.tsv")
119
+ table.to_csv(output_path, sep="\t", index=False)
120
+
121
+
122
+ # if __name__ == "__main__":
123
+ # # python -m lecture2.bm25.analysis
124
+ # from nlp4web_codebase.ir.data_loaders.sciq import load_sciq
125
+ # from lecture2.bm25.bm25_retriever import BM25Retriever
126
+ # from lecture2.bm25.tfidf_retriever import TFIDFRetriever
127
+ # import numpy as np
128
+
129
+ # sciq = load_sciq()
130
+ # system1 = "bm25"
131
+ # system2 = "tfidf"
132
+ # results_path1 = f"output/sciq-{system1}/results/ranking_results.jsonl"
133
+ # results_path2 = f"output/sciq-{system2}/results/ranking_results.jsonl"
134
+ # index_dir1 = f"output/sciq-{system1}"
135
+ # index_dir2 = f"output/sciq-{system2}"
136
+ # compare(
137
+ # dataset=sciq,
138
+ # results_path1=results_path1,
139
+ # results_path2=results_path2,
140
+ # output_dir=f"output/sciq-{system1}_vs_{system2}",
141
+ # system1=system1,
142
+ # system2=system2,
143
+ # term_weighting_fn1=BM25Retriever(index_dir1).get_term_weights,
144
+ # term_weighting_fn2=TFIDFRetriever(index_dir2).get_term_weights,
145
+ # )
146
+
147
+ # # bias on #shared_terms of TFIDF:
148
+ # df1 = pd.read_json(results_path1, orient="records", lines=True)
149
+ # df2 = pd.read_json(results_path2, orient="records", lines=True)
150
+ # merged = pd.merge(df1, df2, on="query_id", how="outer")
151
+ # nterms1 = []
152
+ # nterms2 = []
153
+ # for _, row in merged.iterrows():
154
+ # nterms1.append(len(list(dict(row["cid2tweights_x"]).values())[0]))
155
+ # nterms2.append(len(list(dict(row["cid2tweights_y"]).values())[0]))
156
+ # percentiles = (5, 25, 50, 75, 95)
157
+ # print(system1, np.percentile(nterms1, percentiles), np.mean(nterms1).round(2))
158
+ # print(system2, np.percentile(nterms2, percentiles), np.mean(nterms2).round(2))
159
+ # # bm25 [ 3. 4. 5. 7. 11.] 5.64
160
+ # # tfidf [1. 2. 3. 5. 9.] 3.58
nlp4web_codebase/ir/data_loaders/__init__.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+ from enum import Enum
3
+ from typing import Dict, List
4
+ from nlp4web_codebase.ir.data_loaders.dm import Document, Query, QRel
5
+
6
+
7
+ class Split(str, Enum):
8
+ train = "train"
9
+ dev = "dev"
10
+ test = "test"
11
+
12
+
13
+ @dataclass
14
+ class IRDataset:
15
+ corpus: List[Document]
16
+ queries: List[Query]
17
+ split2qrels: Dict[Split, List[QRel]]
18
+
19
+ def get_stats(self) -> Dict[str, int]:
20
+ stats = {"|corpus|": len(self.corpus), "|queries|": len(self.queries)}
21
+ for split, qrels in self.split2qrels.items():
22
+ stats[f"|qrels-{split}|"] = len(qrels)
23
+ return stats
24
+
25
+ def get_qrels_dict(self, split: Split) -> Dict[str, Dict[str, int]]:
26
+ qrels_dict = {}
27
+ for qrel in self.split2qrels[split]:
28
+ qrels_dict.setdefault(qrel.query_id, {})
29
+ qrels_dict[qrel.query_id][qrel.collection_id] = qrel.relevance
30
+ return qrels_dict
31
+
32
+ def get_split_queries(self, split: Split) -> List[Query]:
33
+ qrels = self.split2qrels[split]
34
+ qids = {qrel.query_id for qrel in qrels}
35
+ return list(filter(lambda query: query.query_id in qids, self.queries))
nlp4web_codebase/ir/data_loaders/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (2.73 kB). View file
 
nlp4web_codebase/ir/data_loaders/__pycache__/dm.cpython-312.pyc ADDED
Binary file (1.05 kB). View file
 
nlp4web_codebase/ir/data_loaders/__pycache__/sciq.cpython-312.pyc ADDED
Binary file (3.4 kB). View file
 
nlp4web_codebase/ir/data_loaders/dm.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+ from typing import Optional
3
+
4
+
5
+ @dataclass
6
+ class Document:
7
+ collection_id: str
8
+ text: str
9
+
10
+
11
+ @dataclass
12
+ class Query:
13
+ query_id: str
14
+ text: str
15
+
16
+
17
+ @dataclass
18
+ class QRel:
19
+ query_id: str
20
+ collection_id: str
21
+ relevance: int
22
+ answer: Optional[str] = None
nlp4web_codebase/ir/data_loaders/sciq.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, List
2
+ from nlp4web_codebase.ir.data_loaders import IRDataset, Split
3
+ from nlp4web_codebase.ir.data_loaders.dm import Document, Query, QRel
4
+ from datasets import load_dataset
5
+ import joblib
6
+
7
+
8
+ @(joblib.Memory(".cache").cache)
9
+ def load_sciq(verbose: bool = False) -> IRDataset:
10
+ train = load_dataset("allenai/sciq", split="train")
11
+ validation = load_dataset("allenai/sciq", split="validation")
12
+ test = load_dataset("allenai/sciq", split="test")
13
+ data = {Split.train: train, Split.dev: validation, Split.test: test}
14
+
15
+ # Each duplicated record is the same to each other:
16
+ df = train.to_pandas() + validation.to_pandas() + test.to_pandas()
17
+ for question, group in df.groupby("question"):
18
+ assert len(set(group["support"].tolist())) == len(group)
19
+ assert len(set(group["correct_answer"].tolist())) == len(group)
20
+
21
+ # Build:
22
+ corpus = []
23
+ queries = []
24
+ split2qrels: Dict[str, List[dict]] = {}
25
+ question2id = {}
26
+ support2id = {}
27
+ for split, rows in data.items():
28
+ if verbose:
29
+ print(f"|raw_{split}|", len(rows))
30
+ split2qrels[split] = []
31
+ for i, row in enumerate(rows):
32
+ example_id = f"{split}-{i}"
33
+ support: str = row["support"]
34
+ if len(support.strip()) == 0:
35
+ continue
36
+ question = row["question"]
37
+ if len(support.strip()) == 0:
38
+ continue
39
+ if support in support2id:
40
+ continue
41
+ else:
42
+ support2id[support] = example_id
43
+ if question in question2id:
44
+ continue
45
+ else:
46
+ question2id[question] = example_id
47
+ doc = {"collection_id": example_id, "text": support}
48
+ query = {"query_id": example_id, "text": row["question"]}
49
+ qrel = {
50
+ "query_id": example_id,
51
+ "collection_id": example_id,
52
+ "relevance": 1,
53
+ "answer": row["correct_answer"],
54
+ }
55
+ corpus.append(Document(**doc))
56
+ queries.append(Query(**query))
57
+ split2qrels[split].append(QRel(**qrel))
58
+
59
+ # Assembly and return:
60
+ return IRDataset(corpus=corpus, queries=queries, split2qrels=split2qrels)
61
+
62
+
63
+ if __name__ == "__main__":
64
+ # python -m nlp4web_codebase.ir.data_loaders.sciq
65
+ import ujson
66
+ import time
67
+
68
+ start = time.time()
69
+ dataset = load_sciq(verbose=True)
70
+ print(f"Loading costs: {time.time() - start}s")
71
+ print(ujson.dumps(dataset.get_stats(), indent=4))
72
+ # ________________________________________________________________________________
73
+ # [Memory] Calling __main__--home-kwang-research-nlp4web-ir-exercise-nlp4web-nlp4web-ir-data_loaders-sciq.load_sciq...
74
+ # load_sciq(verbose=True)
75
+ # |raw_train| 11679
76
+ # |raw_dev| 1000
77
+ # |raw_test| 1000
78
+ # ________________________________________________________load_sciq - 7.3s, 0.1min
79
+ # Loading costs: 7.260092735290527s
80
+ # {
81
+ # "|corpus|": 12160,
82
+ # "|queries|": 12160,
83
+ # "|qrels-train|": 10409,
84
+ # "|qrels-dev|": 875,
85
+ # "|qrels-test|": 876
86
+ # }
nlp4web_codebase/ir/models/__init__.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from abc import ABC, abstractmethod
2
+ from typing import Any, Dict, Type
3
+
4
+
5
+ class BaseRetriever(ABC):
6
+
7
+ @property
8
+ @abstractmethod
9
+ def index_class(self) -> Type[Any]:
10
+ pass
11
+
12
+ def get_term_weights(self, query: str, cid: str) -> Dict[str, float]:
13
+ raise NotImplementedError
14
+
15
+ @abstractmethod
16
+ def score(self, query: str, cid: str) -> float:
17
+ pass
18
+
19
+ @abstractmethod
20
+ def retrieve(self, query: str, topk: int = 10) -> Dict[str, float]:
21
+ pass
nlp4web_codebase/ir/models/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (1.4 kB). View file
 
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ dataclasses
2
+ tqdm
3
+ nltk
4
+ numpy
5
+ scipy
6
+ pytrec_eval
7
+ gradio
8
+ nlp4web-codebase
9
+