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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
|
3 |
-
x = st.slider('Select a value')
|
4 |
-
st.write(x, 'squared is', x * x)
|
|
|
1 |
import streamlit as st
|
2 |
+
import os
|
3 |
+
import pathlib
|
4 |
+
import beir
|
5 |
+
from beir import util
|
6 |
+
from beir.datasets.data_loader import GenericDataLoader
|
7 |
+
import pytrec_eval
|
8 |
+
import pandas as pd
|
9 |
+
from collections import defaultdict
|
10 |
+
import json
|
11 |
+
import copy
|
12 |
+
|
13 |
+
def load_jsonl(f):
|
14 |
+
did2text = defaultdict(list)
|
15 |
+
sub_did2text = {}
|
16 |
+
|
17 |
+
for idx, line in enumerate(f):
|
18 |
+
inst = json.loads(line)
|
19 |
+
if "question" in inst:
|
20 |
+
docid = inst["metadata"][0]["passage_id"] if "doc_id" not in inst else inst["doc_id"]
|
21 |
+
did2text[docid].append(inst["question"])
|
22 |
+
elif "text" in inst:
|
23 |
+
docid = inst["doc_id"] if "doc_id" in inst else inst["did"]
|
24 |
+
did2text[docid].append(inst["text"])
|
25 |
+
sub_did2text[inst["did"]] = inst["text"]
|
26 |
+
elif "query" in inst:
|
27 |
+
docid = inst["doc_id"] if "doc_id" in inst else inst["did"]
|
28 |
+
did2text[docid].append(inst["query"])
|
29 |
+
else:
|
30 |
+
breakpoint()
|
31 |
+
raise NotImplementedError("Need to handle this case")
|
32 |
+
|
33 |
+
return did2text, sub_did2text
|
34 |
+
|
35 |
+
|
36 |
+
|
37 |
+
def get_beir(dataset_name: str):
|
38 |
+
dataset = "scifact"
|
39 |
+
url = "https://public.ukp.informatik.tu-darmstadt.de/thakur/BEIR/datasets/{}.zip".format(dataset)
|
40 |
+
out_dir = os.path.join(pathlib.Path(__file__).parent.absolute(), "datasets")
|
41 |
+
data_path = util.download_and_unzip(url, out_dir)
|
42 |
+
return GenericDataLoader(data_folder=data_path).load(split="test")
|
43 |
+
|
44 |
+
def load_run(f_run):
|
45 |
+
run = pytrec_eval.parse_run(copy.deepcopy(f_run))
|
46 |
+
# convert bytes to strings for keys
|
47 |
+
new_run = defaultdict(dict)
|
48 |
+
for key, sub_dict in run.items():
|
49 |
+
new_run[key.decode("utf-8")] = {k.decode("utf-8"): v for k, v in sub_dict.items()}
|
50 |
+
|
51 |
+
run_pandas = pd.read_csv(f_run, header=None, index_col=None, sep="\t")
|
52 |
+
run_pandas.columns = ["qid", "generic", "doc_id", "rank", "score", "model"]
|
53 |
+
run_pandas.doc_id = run_pandas.doc_id.astype(str)
|
54 |
+
run_pandas.qid = run_pandas.qid.astype(str)
|
55 |
+
run_pandas["rank"] = run_pandas["rank"].astype(int)
|
56 |
+
run_pandas.score = run_pandas.score.astype(float)
|
57 |
+
# if run_1_alt is not None:
|
58 |
+
# run_1_alt, run_1_alt_sub = load_jsonl(run_1_alt)
|
59 |
+
return new_run, run_pandas
|
60 |
+
|
61 |
+
|
62 |
+
with st.sidebar:
|
63 |
+
dataset_name = st.selectbox("Select a dataset in BEIR", ("scifact", "trec-covid", "fever"))
|
64 |
+
metric_name = st.selectbox("Select a metric", ("recall_5", "recall_10"))
|
65 |
+
# sliderbar of how many Top N to choose
|
66 |
+
top_n = st.slider("Top N", 1, 100, 3)
|
67 |
+
x = st.header('Upload a run file')
|
68 |
+
run1_file = st.file_uploader("Choose a file", key="run1")
|
69 |
+
y = st.header("Upload a second run file")
|
70 |
+
run2_file = st.file_uploader("Choose a file", key="run2")
|
71 |
+
incorrect_only = st.checkbox("Show only incorrect instances", value=False)
|
72 |
+
one_better_than_two = st.checkbox("Show only instances where run 1 is better than run 2", value=False)
|
73 |
+
two_better_than_one = st.checkbox("Show only instances where run 2 is better than run 1", value=False)
|
74 |
+
|
75 |
+
|
76 |
+
|
77 |
+
|
78 |
+
|
79 |
+
corpus, queries, qrels = get_beir(dataset_name)
|
80 |
+
|
81 |
+
evaluator = pytrec_eval.RelevanceEvaluator(
|
82 |
+
qrels, pytrec_eval.supported_measures)
|
83 |
+
|
84 |
+
if run1_file is not None:
|
85 |
+
run1, run1_pandas = load_run(run1_file)
|
86 |
+
results1 = evaluator.evaluate(run1) # dict of instance then metrics then values
|
87 |
+
|
88 |
+
if run2_file is not None:
|
89 |
+
run2, run2_pandas = load_run(run2_file)
|
90 |
+
results2 = evaluator.evaluate(run2)
|
91 |
+
|
92 |
+
|
93 |
+
col1, col2 = st.columns([1, 2], gap="medium")
|
94 |
+
|
95 |
+
incorrect = 0
|
96 |
+
is_better_run1_count = 0
|
97 |
+
is_better_run2_count = 0
|
98 |
+
with col1:
|
99 |
+
st.title("Instances")
|
100 |
+
if run1_file is not None:
|
101 |
+
name_of_columns = ["Overview"] + sorted([int(item) for item in set(run1_pandas.qid.tolist())])
|
102 |
+
checkboxes = [("Overview", st.checkbox("Overview", key=f"0overview"))]
|
103 |
+
st.divider()
|
104 |
+
for idx in range(len(name_of_columns)):
|
105 |
+
if not idx:
|
106 |
+
continue
|
107 |
+
is_incorrect = False
|
108 |
+
is_better_run1 = False
|
109 |
+
is_better_run2 = False
|
110 |
+
|
111 |
+
run1_score = results1[str(name_of_columns[idx])][metric_name] if idx else 1
|
112 |
+
if run2_file is not None:
|
113 |
+
run2_score = results2[str(name_of_columns[idx])][metric_name] if idx else 1
|
114 |
+
|
115 |
+
if idx and run1_score == 0 or run2_score == 0:
|
116 |
+
incorrect += 1
|
117 |
+
is_incorrect = True
|
118 |
+
|
119 |
+
if idx and run1_score > run2_score:
|
120 |
+
is_better_run1_count += 1
|
121 |
+
is_better_run1 = True
|
122 |
+
elif idx and run2_score > run1_score:
|
123 |
+
is_better_run2_count += 1
|
124 |
+
is_better_run2 = True
|
125 |
+
|
126 |
+
if not incorrect_only or is_incorrect:
|
127 |
+
if not one_better_than_two or is_better_run1:
|
128 |
+
if not two_better_than_one or is_better_run2:
|
129 |
+
check = st.checkbox(str(name_of_columns[idx]), key=f"{idx}check")
|
130 |
+
st.divider()
|
131 |
+
checkboxes.append((name_of_columns[idx], check))
|
132 |
+
else:
|
133 |
+
if idx and run1_score == 0:
|
134 |
+
incorrect += 1
|
135 |
+
is_incorrect = True
|
136 |
+
|
137 |
+
if not incorrect_only or is_incorrect:
|
138 |
+
check = st.checkbox(str(name_of_columns[idx]), key=f"{idx}check")
|
139 |
+
st.divider()
|
140 |
+
checkboxes.append((name_of_columns[idx], check))
|
141 |
+
|
142 |
+
|
143 |
+
with col2:
|
144 |
+
st.title(f"Information ({len(checkboxes) - 1}/{len(name_of_columns) - 1})")
|
145 |
+
### Only one run file
|
146 |
+
if run1_file is not None and run2_file is None:
|
147 |
+
for check_idx, (inst_num, checkbox) in enumerate(checkboxes):
|
148 |
+
if checkbox:
|
149 |
+
if inst_num == "Overview":
|
150 |
+
st.header("Overview")
|
151 |
+
st.markdown("TODO: Add overview")
|
152 |
+
else:
|
153 |
+
st.header(f"Instance Number: {inst_num}")
|
154 |
+
|
155 |
+
st.subheader(f"Query")
|
156 |
+
query_text = queries[str(inst_num)]
|
157 |
+
st.markdown(query_text)
|
158 |
+
st.divider()
|
159 |
+
|
160 |
+
## Documents
|
161 |
+
# relevant
|
162 |
+
relevant_docs = list(qrels[str(inst_num)].keys())
|
163 |
+
doc_texts = [(doc_id, corpus[doc_id]["title"], corpus[doc_id]["text"]) for doc_id in relevant_docs]
|
164 |
+
st.subheader("Relevant Documents")
|
165 |
+
for (docid, title, text) in doc_texts:
|
166 |
+
st.text_area(f"{docid}: {title}", text)
|
167 |
+
|
168 |
+
# top ranked
|
169 |
+
pred_doc = run1_pandas[run1_pandas.doc_id.isin(relevant_docs)]
|
170 |
+
rank_pred = pred_doc[pred_doc.qid == str(inst_num)]["rank"].tolist()
|
171 |
+
st.subheader("Ranked of Documents")
|
172 |
+
st.markdown(f"Rank: {rank_pred}")
|
173 |
+
|
174 |
+
st.divider()
|
175 |
+
|
176 |
+
if st.checkbox('Show top ranked documents'):
|
177 |
+
st.subheader("Top N Ranked Documents")
|
178 |
+
run1_top_n = run1_pandas[run1_pandas.qid == str(inst_num)][:top_n]
|
179 |
+
run1_top_n_docs = [corpus[str(doc_id)] for doc_id in run1_top_n.doc_id.tolist()]
|
180 |
+
for d_idx, doc in enumerate(run1_top_n_docs):
|
181 |
+
st.text_area(f"{run1_top_n['doc_id'].iloc[d_idx]}: {doc['title']}", doc["text"])
|
182 |
+
st.divider()
|
183 |
+
|
184 |
+
|
185 |
+
st.subheader("Score")
|
186 |
+
st.markdown(f"{results1[str(inst_num)][metric_name]}")
|
187 |
+
break
|
188 |
+
|
189 |
+
## Both run files available
|
190 |
+
elif run1_file is not None and run2_file is not None:
|
191 |
+
for check_idx, (inst_num, checkbox) in enumerate(checkboxes):
|
192 |
+
if checkbox:
|
193 |
+
if inst_num == "Overview":
|
194 |
+
st.header("Overview")
|
195 |
+
st.markdown("TODO: Add overview")
|
196 |
+
else:
|
197 |
+
st.header(f"Instance Number: {inst_num}")
|
198 |
+
|
199 |
+
st.subheader(f"Query")
|
200 |
+
query_text = queries[str(inst_num)]
|
201 |
+
st.markdown(query_text)
|
202 |
+
st.divider()
|
203 |
+
|
204 |
+
## Documents
|
205 |
+
# relevant
|
206 |
+
relevant_docs = list(qrels[str(inst_num)].keys())
|
207 |
+
doc_texts = [(doc_id, corpus[doc_id]["title"], corpus[doc_id]["text"]) for doc_id in relevant_docs]
|
208 |
+
st.subheader("Relevant Documents")
|
209 |
+
for (docid, title, text) in doc_texts:
|
210 |
+
st.text_area(f"{docid}: {title}", text)
|
211 |
+
|
212 |
+
# top ranked
|
213 |
+
pred_doc1 = run1_pandas[run1_pandas.doc_id.isin(relevant_docs)]
|
214 |
+
rank_pred1 = pred_doc1[pred_doc1.qid == str(inst_num)]["rank"].tolist()
|
215 |
+
pred_doc2 = run2_pandas[run2_pandas.doc_id.isin(relevant_docs)]
|
216 |
+
rank_pred2 = pred_doc2[pred_doc2.qid == str(inst_num)]["rank"].tolist()
|
217 |
+
st.subheader("Ranked of Documents")
|
218 |
+
st.markdown(f"Run 1 Rank: {rank_pred1}")
|
219 |
+
st.markdown(f"Run 2 Rank: {rank_pred2}")
|
220 |
+
|
221 |
+
|
222 |
+
st.divider()
|
223 |
+
|
224 |
+
if st.checkbox('Show top ranked documents for Run 1'):
|
225 |
+
st.subheader("Top N Ranked Documents")
|
226 |
+
run1_top_n = run1_pandas[run1_pandas.qid == str(inst_num)][:top_n]
|
227 |
+
run1_top_n_docs = [corpus[str(doc_id)] for doc_id in run1_top_n.doc_id.tolist()]
|
228 |
+
for d_idx, doc in enumerate(run1_top_n_docs):
|
229 |
+
st.text_area(f"{run1_top_n['doc_id'].iloc[d_idx]}: {doc['title']}", doc["text"])
|
230 |
+
|
231 |
+
if st.checkbox('Show top ranked documents for Run 2'):
|
232 |
+
st.subheader("Top N Ranked Documents")
|
233 |
+
run2_top_n = run2_pandas[run2_pandas.qid == str(inst_num)][:top_n]
|
234 |
+
run2_top_n_docs = [corpus[str(doc_id)] for doc_id in run2_top_n.doc_id.tolist()]
|
235 |
+
for d_idx, doc in enumerate(run2_top_n_docs):
|
236 |
+
st.text_area(f"{run2_top_n['doc_id'].iloc[d_idx]}: {doc['title']}", doc["text"])
|
237 |
+
|
238 |
+
st.divider()
|
239 |
+
|
240 |
+
|
241 |
+
st.subheader("Scores")
|
242 |
+
st.markdown(f"Run 1: {results1[str(inst_num)][metric_name]}")
|
243 |
+
st.markdown(f"Run 2: {results2[str(inst_num)][metric_name]}")
|
244 |
+
|
245 |
+
break
|
246 |
|
|
|
|
requirements.txt
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
beir
|
2 |
+
pandas
|
3 |
+
pytrec_eval
|
4 |
+
streamlit
|