anakin87 commited on
Commit
1434337
1 Parent(s): 35f0167

great progress in showing output

Browse files
Rock_fact_checker.py CHANGED
@@ -1,46 +1,50 @@
1
- import streamlit as st
2
-
3
  import time
4
  import logging
5
  from json import JSONDecodeError
6
- # from markdown import markdown
7
- # from annotated_text import annotation
8
- # from urllib.parse import unquote
9
- import random
10
  import pandas as pd
 
11
 
12
  from app_utils.backend_utils import load_statements, query
13
- from app_utils.frontend_utils import set_state_if_absent, reset_results, entailment_html_messages
 
 
 
 
 
14
  from app_utils.config import RETRIEVER_TOP_K
15
 
16
 
17
  def main():
18
-
19
-
20
  statements = load_statements()
21
 
22
  # Persistent state
23
- set_state_if_absent('statement', "Elvis Presley is alive")
24
- set_state_if_absent('answer', '')
25
- set_state_if_absent('results', None)
26
- set_state_if_absent('raw_json', None)
27
- set_state_if_absent('random_statement_requested', False)
28
 
29
-
30
- ## MAIN CONTAINER
31
  st.write("# Fact checking 🎸 Rocks!")
32
  st.write()
33
- st.markdown("""
 
34
  ##### Enter a factual statement about [Rock music](https://en.wikipedia.org/wiki/List_of_mainstream_rock_performers) and let the AI check it out for you...
35
- """)
 
36
  # Search bar
37
- statement = st.text_input("", value=st.session_state.statement,
38
- max_chars=100, on_change=reset_results)
 
39
  col1, col2 = st.columns(2)
40
  col1.markdown(
41
- "<style>.stButton button {width:100%;}</style>", unsafe_allow_html=True)
 
42
  col2.markdown(
43
- "<style>.stButton button {width:100%;}</style>", unsafe_allow_html=True)
 
44
  # Run button
45
  run_pressed = col1.button("Run")
46
  # Random statement button
@@ -54,12 +58,15 @@ def main():
54
  st.session_state.random_statement_requested = True
55
  # Re-runs the script setting the random statement as the textbox value
56
  # Unfortunately necessary as the Random statement button is _below_ the textbox
57
- # raise st.script_runner.RerunException(
58
- # st.script_request_queue.RerunData(None))
 
 
59
  else:
60
  st.session_state.random_statement_requested = False
61
- run_query = (run_pressed or statement != st.session_state.statement) \
62
- and not st.session_state.random_statement_requested
 
63
 
64
  # Get results for query
65
  if run_query and statement:
@@ -68,14 +75,14 @@ def main():
68
  st.session_state.statement = statement
69
  with st.spinner("🧠 &nbsp;&nbsp; Performing neural search on documents..."):
70
  try:
71
- st.session_state.results = query(
72
- statement, RETRIEVER_TOP_K)
73
  time_end = time.time()
74
  print(time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime()))
75
- print(f'elapsed time: {time_end - time_start}')
76
  except JSONDecodeError as je:
77
  st.error(
78
- "👓 &nbsp;&nbsp; An error occurred reading the results. Is the document store working?")
 
79
  return
80
  except Exception as e:
81
  logging.exception(e)
@@ -85,85 +92,36 @@ def main():
85
  # Display results
86
  if st.session_state.results:
87
  results = st.session_state.results
88
- docs, agg_entailment_info = results['documents'], results['agg_entailment_info']
89
- print(results)
90
-
91
  max_key = max(agg_entailment_info, key=agg_entailment_info.get)
92
  message = entailment_html_messages[max_key]
93
- st.markdown(f'<h4>{message}</h4>', unsafe_allow_html=True)
94
- st.markdown(f'###### Aggregate entailment information:')
95
- st.write(results['agg_entailment_info'])
96
- st.markdown(f'###### Relevant snippets:')
97
-
98
- # colms = st.columns((2, 5, 1, 1, 1, 1))
99
- # fields = ["Page title",'Content', 'Relevance', 'contradiction', 'neutral', 'entailment']
100
- # for col, field_name in zip(colms, fields):
101
- # # header
102
- # col.write(field_name)
103
- df = []
104
- for doc in docs:
105
- # col1, col2, col3, col4, col5, col6 = st.columns((2, 5, 1, 1, 1, 1))
106
- # col1.write(f"[{doc.meta['name']}]({doc.meta['url']})")
107
- # col2.write(f"{doc.content}")
108
- # col3.write(f"{doc.score:.3f}")
109
- # col4.write(f"{doc.meta['entailment_info']['contradiction']:.2f}")
110
- # col5.write(f"{doc.meta['entailment_info']['neutral']:.2f}")
111
- # col6.write(f"{doc.meta['entailment_info']['entailment']:.2f}")
112
-
113
- # 'con': f"{doc.meta['entailment_info']['contradiction']:.2f}",
114
- # 'neu': f"{doc.meta['entailment_info']['neutral']:.2f}",
115
- # 'ent': f"{doc.meta['entailment_info']['entailment']:.2f}",
116
- # # 'url': doc.meta['url'],
117
- # 'Content': doc.content}
118
- #
119
- #
120
- #
121
- row = {'Title': doc.meta['name'],
122
- 'Relevance': f"{doc.score:.3f}",
123
- 'con': f"{doc.meta['entailment_info']['contradiction']:.2f}",
124
- 'neu': f"{doc.meta['entailment_info']['neutral']:.2f}",
125
- 'ent': f"{doc.meta['entailment_info']['entailment']:.2f}",
126
- # 'url': doc.meta['url'],
127
- 'Content': doc.content}
128
- df.append(row)
129
- st.dataframe(pd.DataFrame(df))#.style.apply(highlight))
130
-
131
-
132
- # if len(st.session_state.results['answers']) == 0:
133
- # st.info("""🤔 &nbsp;&nbsp; Haystack is unsure whether any of
134
- # the documents contain an answer to your question. Try to reformulate it!""")
135
-
136
- # for result in st.session_state.results['answers']:
137
- # result = result.to_dict()
138
- # if result["answer"]:
139
- # if alert_irrelevance and result['score'] < LOW_RELEVANCE_THRESHOLD:
140
- # alert_irrelevance = False
141
- # st.write("""
142
- # <h4 style='color: darkred'>Attention, the
143
- # following answers have low relevance:</h4>""",
144
- # unsafe_allow_html=True)
145
-
146
- # answer, context = result["answer"], result["context"]
147
- # start_idx = context.find(answer)
148
- # end_idx = start_idx + len(answer)
149
- # # Hack due to this bug: https://github.com/streamlit/streamlit/issues/3190
150
- # st.write(markdown("- ..."+context[:start_idx] +
151
- # str(annotation(answer, "ANSWER", "#3e1c21", "white")) +
152
- # context[end_idx:]+"..."), unsafe_allow_html=True)
153
- # source = ""
154
- # name = unquote(result['meta']['name']).replace('_', ' ')
155
- # url = result['meta']['url']
156
- # source = f"[{name}]({url})"
157
- # st.markdown(
158
- # f"**Score:** {result['score']:.2f} - **Source:** {source}")
159
-
160
- # def make_pretty(styler):
161
- # styler.set_caption("Weather Conditions")
162
- # # styler.format(rain_condition)
163
- # styler.format_con(lambda v: v.float(v))
164
- # styler.background_gradient(axis=None, vmin=0, vmax=1, cmap="YlGnBu")
165
- # return styler
166
-
167
- def highlight(s):
168
- return ['background-color: red']*5
169
- main()
 
1
+ import random
 
2
  import time
3
  import logging
4
  from json import JSONDecodeError
5
+
6
+ import streamlit as st
 
 
7
  import pandas as pd
8
+ import plotly.express as px
9
 
10
  from app_utils.backend_utils import load_statements, query
11
+ from app_utils.frontend_utils import (
12
+ set_state_if_absent,
13
+ reset_results,
14
+ entailment_html_messages,
15
+ create_df_for_relevant_snippets,
16
+ )
17
  from app_utils.config import RETRIEVER_TOP_K
18
 
19
 
20
  def main():
 
 
21
  statements = load_statements()
22
 
23
  # Persistent state
24
+ set_state_if_absent("statement", "Elvis Presley is alive")
25
+ set_state_if_absent("answer", "")
26
+ set_state_if_absent("results", None)
27
+ set_state_if_absent("raw_json", None)
28
+ set_state_if_absent("random_statement_requested", False)
29
 
 
 
30
  st.write("# Fact checking 🎸 Rocks!")
31
  st.write()
32
+ st.markdown(
33
+ """
34
  ##### Enter a factual statement about [Rock music](https://en.wikipedia.org/wiki/List_of_mainstream_rock_performers) and let the AI check it out for you...
35
+ """
36
+ )
37
  # Search bar
38
+ statement = st.text_input(
39
+ "", value=st.session_state.statement, max_chars=100, on_change=reset_results
40
+ )
41
  col1, col2 = st.columns(2)
42
  col1.markdown(
43
+ "<style>.stButton button {width:100%;}</style>", unsafe_allow_html=True
44
+ )
45
  col2.markdown(
46
+ "<style>.stButton button {width:100%;}</style>", unsafe_allow_html=True
47
+ )
48
  # Run button
49
  run_pressed = col1.button("Run")
50
  # Random statement button
 
58
  st.session_state.random_statement_requested = True
59
  # Re-runs the script setting the random statement as the textbox value
60
  # Unfortunately necessary as the Random statement button is _below_ the textbox
61
+ # Adapted for Streamlit>=1.12
62
+ raise st.runtime.scriptrunner.script_runner.RerunException(
63
+ st.runtime.scriptrunner.script_requests.RerunData("")
64
+ )
65
  else:
66
  st.session_state.random_statement_requested = False
67
+ run_query = (
68
+ run_pressed or statement != st.session_state.statement
69
+ ) and not st.session_state.random_statement_requested
70
 
71
  # Get results for query
72
  if run_query and statement:
 
75
  st.session_state.statement = statement
76
  with st.spinner("🧠 &nbsp;&nbsp; Performing neural search on documents..."):
77
  try:
78
+ st.session_state.results = query(statement, RETRIEVER_TOP_K)
 
79
  time_end = time.time()
80
  print(time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime()))
81
+ print(f"elapsed time: {time_end - time_start}")
82
  except JSONDecodeError as je:
83
  st.error(
84
+ "👓 &nbsp;&nbsp; An error occurred reading the results. Is the document store working?"
85
+ )
86
  return
87
  except Exception as e:
88
  logging.exception(e)
 
92
  # Display results
93
  if st.session_state.results:
94
  results = st.session_state.results
95
+ docs, agg_entailment_info = results["documents"], results["agg_entailment_info"]
96
+
97
+ # show different messages depending on entailment results
98
  max_key = max(agg_entailment_info, key=agg_entailment_info.get)
99
  message = entailment_html_messages[max_key]
100
+ st.markdown(f"<br/><h4>{message}</h4>", unsafe_allow_html=True)
101
+
102
+ st.markdown(f"###### Aggregate entailment information:")
103
+ col1, col2 = st.columns([2, 1])
104
+ df_agg_entailment_info = pd.DataFrame([results["agg_entailment_info"]])
105
+ fig = px.scatter_ternary(
106
+ df_agg_entailment_info,
107
+ a="contradiction",
108
+ b="neutral",
109
+ c="entailment",
110
+ size="contradiction",
111
+ )
112
+ with col1:
113
+ st.plotly_chart(fig, use_container_width=True)
114
+ with col2:
115
+ st.write(results["agg_entailment_info"])
116
+
117
+ st.markdown(f"###### Relevant snippets:")
118
+ df, urls = create_df_for_relevant_snippets(docs)
119
+ st.dataframe(df)
120
+
121
+ str_wiki_pages = "Wikipedia source pages: "
122
+ for doc, url in urls.items():
123
+ str_wiki_pages += f"[{doc}]({url}) "
124
+ st.markdown(str_wiki_pages)
125
+
126
+
127
+ main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app_utils/backend_utils.py CHANGED
@@ -1,42 +1,61 @@
1
  import shutil
 
2
  from haystack.document_stores import FAISSDocumentStore
3
  from haystack.nodes import EmbeddingRetriever
4
  from haystack.pipelines import Pipeline
5
-
6
  import streamlit as st
7
 
8
  from app_utils.entailment_checker import EntailmentChecker
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
- from app_utils.config import STATEMENTS_PATH, INDEX_DIR, RETRIEVER_MODEL, RETRIEVER_MODEL_FORMAT, NLI_MODEL
11
 
12
  # cached to make index and models load only at start
13
- @st.cache(hash_funcs={"builtins.SwigPyObject": lambda _: None}, allow_output_mutation=True)
 
 
14
  def start_haystack():
15
  """
16
  load document store, retriever, reader and create pipeline
17
  """
18
- shutil.copy(f'{INDEX_DIR}/faiss_document_store.db', '.')
19
  document_store = FAISSDocumentStore(
20
- faiss_index_path=f'{INDEX_DIR}/my_faiss_index.faiss',
21
- faiss_config_path=f'{INDEX_DIR}/my_faiss_index.json')
22
- print(f'Index size: {document_store.get_document_count()}')
23
-
 
24
  retriever = EmbeddingRetriever(
25
  document_store=document_store,
26
  embedding_model=RETRIEVER_MODEL,
27
- model_format=RETRIEVER_MODEL_FORMAT
28
  )
29
-
30
- entailment_checker = EntailmentChecker(model_name_or_path=NLI_MODEL,
31
- use_gpu=False)
32
-
33
 
34
  pipe = Pipeline()
35
  pipe.add_node(component=retriever, name="retriever", inputs=["Query"])
36
  pipe.add_node(component=entailment_checker, name="ec", inputs=["retriever"])
37
  return pipe
38
 
 
39
  pipe = start_haystack()
 
40
  # the pipeline is not included as parameter of the following function,
41
  # because it is difficult to cache
42
  @st.cache(persist=True, allow_output_mutation=True)
@@ -45,28 +64,28 @@ def query(statement: str, retriever_top_k: int = 5):
45
  params = {"retriever": {"top_k": retriever_top_k}}
46
  results = pipe.run(statement, params=params)
47
 
48
- scores, agg_con, agg_neu, agg_ent = 0,0,0,0
49
- for doc in results['documents']:
50
- scores+=doc.score
51
- ent_info=doc.meta['entailment_info']
52
- con,neu,ent = ent_info['contradiction'], ent_info['neutral'], ent_info['entailment']
53
- agg_con+=con*doc.score
54
- agg_neu+=neu*doc.score
55
- agg_ent+=ent*doc.score
56
-
57
- results['agg_entailment_info'] = {
58
- 'contradiction': round(agg_con/scores, 2),
59
- 'neutral': round(agg_neu/scores, 2),
60
- 'entailment': round(agg_ent/scores, 2)}
61
-
62
- return results
63
 
64
- @st.cache()
65
- def load_statements():
66
- """Load statements from file"""
67
- with open(STATEMENTS_PATH) as fin:
68
- statements = [line.strip() for line in fin.readlines()
69
- if not line.startswith('#')]
70
- return statements
71
 
72
-
 
 
 
 
 
 
1
  import shutil
2
+
3
  from haystack.document_stores import FAISSDocumentStore
4
  from haystack.nodes import EmbeddingRetriever
5
  from haystack.pipelines import Pipeline
 
6
  import streamlit as st
7
 
8
  from app_utils.entailment_checker import EntailmentChecker
9
+ from app_utils.config import (
10
+ STATEMENTS_PATH,
11
+ INDEX_DIR,
12
+ RETRIEVER_MODEL,
13
+ RETRIEVER_MODEL_FORMAT,
14
+ NLI_MODEL,
15
+ )
16
+
17
+
18
+ @st.cache()
19
+ def load_statements():
20
+ """Load statements from file"""
21
+ with open(STATEMENTS_PATH) as fin:
22
+ statements = [
23
+ line.strip() for line in fin.readlines() if not line.startswith("#")
24
+ ]
25
+ return statements
26
 
 
27
 
28
  # cached to make index and models load only at start
29
+ @st.cache(
30
+ hash_funcs={"builtins.SwigPyObject": lambda _: None}, allow_output_mutation=True
31
+ )
32
  def start_haystack():
33
  """
34
  load document store, retriever, reader and create pipeline
35
  """
36
+ shutil.copy(f"{INDEX_DIR}/faiss_document_store.db", ".")
37
  document_store = FAISSDocumentStore(
38
+ faiss_index_path=f"{INDEX_DIR}/my_faiss_index.faiss",
39
+ faiss_config_path=f"{INDEX_DIR}/my_faiss_index.json",
40
+ )
41
+ print(f"Index size: {document_store.get_document_count()}")
42
+
43
  retriever = EmbeddingRetriever(
44
  document_store=document_store,
45
  embedding_model=RETRIEVER_MODEL,
46
+ model_format=RETRIEVER_MODEL_FORMAT,
47
  )
48
+
49
+ entailment_checker = EntailmentChecker(model_name_or_path=NLI_MODEL, use_gpu=False)
 
 
50
 
51
  pipe = Pipeline()
52
  pipe.add_node(component=retriever, name="retriever", inputs=["Query"])
53
  pipe.add_node(component=entailment_checker, name="ec", inputs=["retriever"])
54
  return pipe
55
 
56
+
57
  pipe = start_haystack()
58
+
59
  # the pipeline is not included as parameter of the following function,
60
  # because it is difficult to cache
61
  @st.cache(persist=True, allow_output_mutation=True)
 
64
  params = {"retriever": {"top_k": retriever_top_k}}
65
  results = pipe.run(statement, params=params)
66
 
67
+ scores, agg_con, agg_neu, agg_ent = 0, 0, 0, 0
68
+ for i, doc in enumerate(results["documents"]):
69
+ scores += doc.score
70
+ ent_info = doc.meta["entailment_info"]
71
+ con, neu, ent = (
72
+ ent_info["contradiction"],
73
+ ent_info["neutral"],
74
+ ent_info["entailment"],
75
+ )
76
+ agg_con += con * doc.score
77
+ agg_neu += neu * doc.score
78
+ agg_ent += ent * doc.score
 
 
 
79
 
80
+ # if in the first 3 documents there is a strong evidence of entailment/contradiction,
81
+ # there is non need to consider less relevant documents
82
+ if i == 2 and max(agg_con, agg_ent) / scores > 0.5:
83
+ results["documents"] = results["documents"][: i + 1]
84
+ break
 
 
85
 
86
+ results["agg_entailment_info"] = {
87
+ "contradiction": round(agg_con / scores, 2),
88
+ "neutral": round(agg_neu / scores, 2),
89
+ "entailment": round(agg_ent / scores, 2),
90
+ }
91
+ return results
app_utils/config.py CHANGED
@@ -1,6 +1,5 @@
1
-
2
- INDEX_DIR = 'data/index'
3
- STATEMENTS_PATH = 'data/statements.txt'
4
 
5
  RETRIEVER_MODEL = "sentence-transformers/msmarco-distilbert-base-tas-b"
6
  RETRIEVER_MODEL_FORMAT = "sentence_transformers"
 
1
+ INDEX_DIR = "data/index"
2
+ STATEMENTS_PATH = "data/statements.txt"
 
3
 
4
  RETRIEVER_MODEL = "sentence-transformers/msmarco-distilbert-base-tas-b"
5
  RETRIEVER_MODEL_FORMAT = "sentence_transformers"
app_utils/entailment_checker.py CHANGED
@@ -1,11 +1,12 @@
1
  from typing import List, Optional
2
 
3
- from transformers import AutoModelForSequenceClassification,AutoTokenizer,AutoConfig
4
  import torch
5
  from haystack.nodes.base import BaseComponent
6
  from haystack.modeling.utils import initialize_device_settings
7
  from haystack.schema import Document, Answer, Span
8
 
 
9
  class EntailmentChecker(BaseComponent):
10
  """
11
  This node checks the entailment between every document content and the query.
@@ -38,29 +39,37 @@ class EntailmentChecker(BaseComponent):
38
 
39
  tokenizer = tokenizer or model_name_or_path
40
  self.tokenizer = AutoTokenizer.from_pretrained(tokenizer)
41
- self.model = AutoModelForSequenceClassification.from_pretrained(pretrained_model_name_or_path=model_name_or_path,revision=model_version)
 
 
42
  self.batch_size = batch_size
43
  self.model.to(str(self.devices[0]))
44
-
45
  id2label = AutoConfig.from_pretrained(model_name_or_path).id2label
46
- self.labels= [id2label[k].lower() for k in sorted(id2label)]
47
- if 'entailment' not in self.labels:
48
- raise ValueError("The model config must contain entailment value in the id2label dict.")
49
-
 
 
50
  def run(self, query: str, documents: List[Document]):
51
  for doc in documents:
52
- entailment_dict=self.get_entailment(premise=doc.content, hypotesis=query)
53
- doc.meta['entailment_info']=entailment_dict
54
- return {'documents':documents}, "output_1"
55
-
56
  def run_batch():
57
  pass
58
-
59
- def get_entailment(self, premise,hypotesis):
60
  with torch.no_grad():
61
- inputs = self.tokenizer(f'{premise}{self.tokenizer.sep_token}{hypotesis}', return_tensors="pt").to(self.devices[0])
 
 
62
  out = self.model(**inputs)
63
  logits = out.logits
64
- probs = torch.nn.functional.softmax(logits, dim=-1)[0,:].cpu().detach().numpy()
65
- entailment_dict={k.lower():v for k,v in zip (self.labels, probs)}
66
- return entailment_dict
 
 
 
1
  from typing import List, Optional
2
 
3
+ from transformers import AutoModelForSequenceClassification, AutoTokenizer, AutoConfig
4
  import torch
5
  from haystack.nodes.base import BaseComponent
6
  from haystack.modeling.utils import initialize_device_settings
7
  from haystack.schema import Document, Answer, Span
8
 
9
+
10
  class EntailmentChecker(BaseComponent):
11
  """
12
  This node checks the entailment between every document content and the query.
 
39
 
40
  tokenizer = tokenizer or model_name_or_path
41
  self.tokenizer = AutoTokenizer.from_pretrained(tokenizer)
42
+ self.model = AutoModelForSequenceClassification.from_pretrained(
43
+ pretrained_model_name_or_path=model_name_or_path, revision=model_version
44
+ )
45
  self.batch_size = batch_size
46
  self.model.to(str(self.devices[0]))
47
+
48
  id2label = AutoConfig.from_pretrained(model_name_or_path).id2label
49
+ self.labels = [id2label[k].lower() for k in sorted(id2label)]
50
+ if "entailment" not in self.labels:
51
+ raise ValueError(
52
+ "The model config must contain entailment value in the id2label dict."
53
+ )
54
+
55
  def run(self, query: str, documents: List[Document]):
56
  for doc in documents:
57
+ entailment_dict = self.get_entailment(premise=doc.content, hypotesis=query)
58
+ doc.meta["entailment_info"] = entailment_dict
59
+ return {"documents": documents}, "output_1"
60
+
61
  def run_batch():
62
  pass
63
+
64
+ def get_entailment(self, premise, hypotesis):
65
  with torch.no_grad():
66
+ inputs = self.tokenizer(
67
+ f"{premise}{self.tokenizer.sep_token}{hypotesis}", return_tensors="pt"
68
+ ).to(self.devices[0])
69
  out = self.model(**inputs)
70
  logits = out.logits
71
+ probs = (
72
+ torch.nn.functional.softmax(logits, dim=-1)[0, :].cpu().detach().numpy()
73
+ )
74
+ entailment_dict = {k.lower(): v for k, v in zip(self.labels, probs)}
75
+ return entailment_dict
app_utils/frontend_utils.py CHANGED
@@ -1,16 +1,45 @@
1
  import streamlit as st
 
 
 
 
 
 
 
2
 
3
 
4
  def set_state_if_absent(key, value):
5
  if key not in st.session_state:
6
  st.session_state[key] = value
7
 
 
8
  # Small callback to reset the interface in case the text of the question changes
9
  def reset_results(*args):
10
  st.session_state.answer = None
11
  st.session_state.results = None
12
  st.session_state.raw_json = None
13
 
14
- entailment_html_messages = {'entailment': 'The knowledge base seems to <span style="color:green">confirm</span> your statement',
15
- 'contradiction': 'The knowledge base seems to <span style="color:red">contradict</span> your statement',
16
- 'neutral': 'The knowledge base is <span style="color:darkgray">neutral</span> about your statement'}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ import pandas as pd
3
+
4
+ entailment_html_messages = {
5
+ "entailment": 'The knowledge base seems to <span style="color:green">confirm</span> your statement',
6
+ "contradiction": 'The knowledge base seems to <span style="color:red">contradict</span> your statement',
7
+ "neutral": 'The knowledge base is <span style="color:darkgray">neutral</span> about your statement',
8
+ }
9
 
10
 
11
  def set_state_if_absent(key, value):
12
  if key not in st.session_state:
13
  st.session_state[key] = value
14
 
15
+
16
  # Small callback to reset the interface in case the text of the question changes
17
  def reset_results(*args):
18
  st.session_state.answer = None
19
  st.session_state.results = None
20
  st.session_state.raw_json = None
21
 
22
+
23
+ def highlight_cols(s):
24
+ coldict = {"con": "#FFA07A", "neu": "#E5E4E2", "ent": "#a9d39e"}
25
+ if s.name in coldict.keys():
26
+ return ["background-color: {}".format(coldict[s.name])] * len(s)
27
+ return [""] * len(s)
28
+
29
+
30
+ def create_df_for_relevant_snippets(docs):
31
+ rows = []
32
+ urls = {}
33
+ for doc in docs:
34
+ row = {
35
+ "Title": doc.meta["name"],
36
+ "Relevance": f"{doc.score:.3f}",
37
+ "con": f"{doc.meta['entailment_info']['contradiction']:.2f}",
38
+ "neu": f"{doc.meta['entailment_info']['neutral']:.2f}",
39
+ "ent": f"{doc.meta['entailment_info']['entailment']:.2f}",
40
+ "Content": doc.content,
41
+ }
42
+ urls[doc.meta["name"]] = doc.meta["url"]
43
+ rows.append(row)
44
+ df = pd.DataFrame(rows).style.apply(highlight_cols)
45
+ return df, urls
data/statements.txt CHANGED
@@ -17,4 +17,10 @@ Steve Vai collaborated with Frank Zappa
17
  The White Stripes were a trio
18
  The White Stripes were composed by Jack White and Meg White
19
  Scorpions is a German trap band
20
- Sepultura is a heavy metal band
 
 
 
 
 
 
 
17
  The White Stripes were a trio
18
  The White Stripes were composed by Jack White and Meg White
19
  Scorpions is a German trap band
20
+ Sepultura is a heavy metal band
21
+ Toxicity is a song by System of a down
22
+ System of a down is a Italian band
23
+ The Cure is a pop band
24
+ Mick Jagger loves pasta
25
+ Ozzy Osbourne was part of the Black Sabbath
26
+ Zucchero is an international artist
notebooks/get_wikipedia_data.ipynb CHANGED
@@ -1 +1,582 @@
1
- {"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.7.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Download data from Wikipedia","metadata":{}},{"cell_type":"code","source":"# install wikipedia API python wrapper\n! pip install wikipedia","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-08-20T21:43:59.293655Z","iopub.execute_input":"2022-08-20T21:43:59.294792Z","iopub.status.idle":"2022-08-20T21:44:15.263363Z","shell.execute_reply.started":"2022-08-20T21:43:59.294746Z","shell.execute_reply":"2022-08-20T21:44:15.262171Z"},"trusted":true},"execution_count":3,"outputs":[]},{"cell_type":"code","source":"import wikipedia\nimport json\nimport traceback","metadata":{"execution":{"iopub.status.busy":"2022-08-20T21:44:15.265341Z","iopub.execute_input":"2022-08-20T21:44:15.265753Z","iopub.status.idle":"2022-08-20T21:44:15.470330Z","shell.execute_reply.started":"2022-08-20T21:44:15.265709Z","shell.execute_reply":"2022-08-20T21:44:15.468665Z"},"trusted":true},"execution_count":4,"outputs":[]},{"cell_type":"code","source":"# titles to download, from https://en.wikipedia.org/wiki/List_of_mainstream_rock_performers\n\npages_titles=\"\"\"10cc\n10_Years_(band)\n3_Doors_Down\n311_(band)\n38_Special_(band)\nAccept_(band)\nAC/DC\nBryan_Adams\nAerosmith\nAFI_(band)\nAir_Supply\nThe_Alan_Parsons_Project\nAlice_in_Chains\nThe_All-American_Rejects\nThe_Allman_Brothers_Band\nAlter_Bridge\nAmbrosia_(band)\nAmerica_(band)\nThe_Animals\nAdam_Ant\nAnthrax_(American_band)\nApril_Wine\nArcade_Fire\nArctic_Monkeys\nAsia_(band)\nAudioslave\nAvenged_Sevenfold\nAwolnation\nThe_B-52's\nBachman–Turner_Overdrive\nBad_Company\nBadfinger\nThe_Band\nThe_Bangles\nBarenaked_Ladies\nBay_City_Rollers\nThe_Beach_Boys\nThe_Beatles\nBeck\nBen_Folds_Five\nPat_Benatar\nChuck_Berry\nThe_Big_Bopper\nBilly_Talent\nThe_Black_Crowes\nThe_Black_Keys\nBlack_Sabbath\nBlack_Stone_Cherry\nBlack_Veil_Brides\nBlink-182\nBloodhound_Gang\nBlue_October\nBlue_Öyster_Cult\nBlues_Traveler\nJames_Blunt\nBlur_(band)\nBon_Jovi\nBoston_(band)\nDavid_Bowie\nBowling_for_Soup\nBoys_Like_Girls\nBread_(band)\nBreaking_Benjamin\nBring_Me_the_Horizon\nJackson_Browne\nBuckcherry\nJeff_Buckley\nBullet_for_My_Valentine\nBush_(British_band)\nThe_Byrds\nCage_the_Elephant\nCake_(band)\nCanned_Heat\nThe_Cab\nThe_Cardigans\nThe_Cars\nCatfish_and_the_Bottlemen\nHarry_Chapin\nTracy_Chapman\nCheap_Trick\nChevelle_(band)\nChicago_(band)\nChubby_Checker\nCinderella_(band)\nDallas_Green_(musician)\nEric_Clapton\nThe_Clash\nEddie_Cochran\nJoe_Cocker\nCoheed_and_Cambria\nCold_Chisel\nColdplay\nCollective_Soul\nPhil_Collins\nAlice_Cooper\nChris_Cornell\nElvis_Costello\nCounting_Crows\nThe_Cranberries\nCrash_Test_Dummies\nCream_(band)\nCreed_(band)\nCreedence_Clearwater_Revival\nJim_Croce\nCrosby,_Stills,_Nash_&_Young\nChristopher_Cross\nSheryl_Crow\nCrowded_House\nThe_Cult\nThe_Cure\nDamn_Yankees_(band)\nDashboard_Confessional\nDaughtry_(band)\nThe_Dave_Clark_Five\nDave_Matthews_Band\nDays_of_the_New\nDeath_Cab_for_Cutie\nDeep_Purple\nDef_Leppard\nDeftones\nDepeche_Mode\nBo_Diddley\nDio_(band)\nDire_Straits\nDisturbed_(band)\nFats_Domino\nDonovan\nThe_Doobie_Brothers\nThe_Doors\nDr._Hook_&_the_Medicine_Show\nDropkick_Murphys\nDrowning_Pool\nDuran_Duran\nIan_Dury\nBob_Dylan\nEagles_(band)\nEcho_&_the_Bunnymen\nDuane_Eddy\nEdgar_Winter\nElectric_Light_Orchestra\nEmerson,_Lake_&_Palmer\nEngland_Dan_&_John_Ford_Coley\nMelissa_Etheridge\nEurope_(band)\nEvanescence\nEverclear_(band)\nEverlast\nThe_Everly_Brothers\nExtreme_(band)\nFaces_(band)\nFaith_No_More\nFall_Out_Boy\nBryan_Ferry\nFilter_(band)\nFinger_Eleven\nFireHouse\nFive_Finger_Death_Punch\nFive_for_Fighting\nThe_Fixx\nThe_Flaming_Lips\nFleetwood_Mac\nFlogging_Molly\nFlorence_and_the_Machine\nFlyleaf_(band)\nFoals_(band)\nDan_Fogelberg\nJohn_Fogerty\nFoo_Fighters\nForeigner_(band)\nFoster_the_People\nThe_Four_Seasons_(band)\nPeter_Frampton\nFranz_Ferdinand_(band)\nThe_Fray\nGlenn_Frey\nFuel_(band)\nFun_(band)\nPeter_Gabriel\nGarbage_(band)\nGenesis_(band)\nGhost_(Swedish_band)\nGin_Blossoms\nGary_Glitter\nThe_Go-Go's\nGodsmack\nGolden_Earring\nGoo_Goo_Dolls\nGood_Charlotte\nGrand_Funk_Railroad\nGrateful_Dead\nGreat_White\nGreen_Day\nGreta_Van_Fleet\nThe_Guess_Who\nGuns_N'_Roses\nHalestorm\nBill_Haley_&_His_Comets\nHall_&_Oates\nGeorge_Harrison\nHeart_(band)\nJimi_Hendrix\nDon_Henley\nHerman's_Hermits\nHighly_Suspect\nHinder\nThe_Hives\nHole_(band)\nThe_Hollies\nBuddy_Holly\nHoobastank\nHootie_&_the_Blowfish\nIcehouse_(band)\nBilly_Idol\nImagine_Dragons\nIncubus_(band)\nInterpol_(band)\nINXS\nIron_Maiden\nThe_J._Geils_Band\nThe_Jam\nTommy_James_and_the_Shondells\nJane's_Addiction\nJefferson_Airplane\nJefferson_Starship\nThe_Jesus_and_Mary_Chain\nJet_(Australian_band)\nJethro_Tull_(band)\nJoan_Jett\nJimmy_Eat_World\nBilly_Joel\nElton_John\nJanis_Joplin\nJourney_(band)\nJoy_Division\nJudas_Priest\nKaiser_Chiefs\nKaleo_(band)\nKansas_(band)\nKeane_(band)\nKid_Rock\nThe_Killers\nKillswitch_Engage\nKings_of_Leon\nThe_Kinks\nKiss_(band)\nKorn\nLenny_Kravitz\nLacuna_Coil\nLamb_of_God_(band)\nAvril_Lavigne\nLed_Zeppelin\nJohn_Lennon\nHuey_Lewis_and_the_News\nJerry_Lee_Lewis\nLifehouse_(band)\nLimp_Bizkit\nLinkin_Park\nLittle_Richard\nLittle_River_Band\nLive_(band)\nLiving_Colour\nKenny_Loggins\nLoverboy\nThe_Lovin'_Spoonful\nThe_Lumineers\nLynyrd_Skynyrd\nThe_Mamas_&_the_Papas\nMarilyn_Manson\nThe_Marshall_Tucker_Band\nMatchbox_Twenty\nJohn_Mayer\nPaul_McCartney\nMeat_Loaf\nMegadeth\nJohn_Mellencamp\nMen_at_Work\nMetallica\nMidnight_Oil\nMike_and_the_Mechanics\nModest_Mouse\nEddie_Money\nThe_Monkees\nThe_Moody_Blues\nAlanis_Morissette\nVan_Morrison\nMorrissey\nMötley_Crüe\nMotörhead\nMudvayne\nMumford_&_Sons\nMuse_(band)\nMy_Chemical_Romance\nNickelback\nStevie_Nicks\nHarry_Nilsson\nNine_Inch_Nails\nNirvana_(band)\nNo_Doubt\nTed_Nugent\nOasis_(band)\nThe_Offspring\nRoy_Orbison\nOzzy_Osbourne\nOur_Lady_Peace\nThe_Outfield\nP.O.D.\nPanic!_at_the_Disco\nPantera\nPapa_Roach\nParamore\nPearl_Jam\nA_Perfect_Circle\nTom_Petty_and_the_Heartbreakers\nPink_Floyd\nPixies_(band)\nRobert_Plant\nPoison_(American_band)\nThe_Police\nIggy_Pop\nPop_Evil\nThe_Presidents_of_the_United_States_of_America_(band)\nThe_Pretenders\nElvis_Presley\nThe_Pretty_Reckless\nPrimus_(band)\nPuddle_of_Mudd\nQueen_(band)\nQueens_of_the_Stone_Age\nQueensrÿche\nQuiet_Riot\nR.E.M.\nRadiohead\nRage_Against_the_Machine\nRainbow_(rock_band)\nRammstein\nRamones\nRed_Hot_Chili_Peppers\nLou_Reed\nREO_Speedwagon\nRise_Against\nThe_Rolling_Stones\nLinda_Ronstadt\nRoxy_Music\nRoyal_Blood_(band)\nRush_(band)\nSaliva_(band)\nSam_Fender\nSantana_(band)\nJoe_Satriani\nSaving_Abel\nScorpions_(band)\nThe_Script\nSeether\nBob_Seger\nSepultura\nSex_Pistols\nShakin'_Stevens\nShinedown\nSilverchair\nSimon_&_Garfunkel\nSimple_Minds\nSimple_Plan\nSkid_Row_(American_band)\nSkillet_(band)\nSlade\nSlayer\nSlipknot_(band)\nSmall_Faces\nSmash_Mouth\nThe_Smashing_Pumpkins\nThe_Smiths\nSmokie_(band)\nSnow_Patrol\nSocial_Distortion\nSoundgarden\nBruce_Springsteen\nBilly_Squier\nStaind\nRingo_Starr\nStarset\nStarship_(band)\nStatus_Quo_(band)\nSteely_Dan\nSteppenwolf_(band)\nSteve_Miller_Band\nRod_Stewart\nSting_(musician)\nThe_Stone_Roses\nStone_Sour\nStone_Temple_Pilots\nThe_Strokes\nStyx_(band)\nSublime_(band)\nSum_41\nSupertramp\nSurvivor_(band)\nThe_Sweet\nSystem_of_a_Down\nT._Rex_(band)\nTalking_Heads\nJames_Taylor\nTenacious_D\nTesla_(band)\nTheory_of_a_Deadman\nThin_Lizzy\nThird_Eye_Blind\nThirty_Seconds_to_Mars\nGeorge_Thorogood\nThousand_Foot_Krutch\nThree_Days_Grace\nThree_Dog_Night\nTool_(band)\nToto_(band)\nTraffic_(band)\nThe_Tragically_Hip\nTrain_(band)\nTraveling_Wilburys\nTravis_(band)\nTrivium_(band)\nTwenty_One_Pilots\nTwisted_Sister\nU2\nUriah_Heep_(band)\nThe_Used\nSteve_Vai\nRitchie_Valens\nVampire_Weekend\nVan_Halen\nStevie_Ray_Vaughan\nVelvet_Revolver\nThe_Velvet_Underground\nThe_Verve\nVolbeat\nJoe_Walsh\nWarrant_(American_band)\nWeezer\nJack_White\nThe_White_Stripes\nWhite_Zombie_(band)\nWhitesnake\nThe_Who\nPaul_McCartney_and_Wings\nSteve_Winwood\nThe_Yardbirds\nYes_(band)\nNeil_Young\nFrank_Zappa\nRob_Zombie\nThe_Zombies\nZZ_Top\"\"\".split('\\n')","metadata":{"execution":{"iopub.status.busy":"2022-08-20T23:34:24.681697Z","iopub.execute_input":"2022-08-20T23:34:24.682223Z","iopub.status.idle":"2022-08-20T23:34:24.693942Z","shell.execute_reply.started":"2022-08-20T23:34:24.682178Z","shell.execute_reply":"2022-08-20T23:34:24.693004Z"},"trusted":true},"execution_count":54,"outputs":[]},{"cell_type":"code","source":"for i,raw_title in enumerate(pages_titles):\n if i%10==0:\n print(i/len(pages_titles)*100)\n try:\n page=wikipedia.page(title=raw_title.replace('_', ' '), auto_suggest=False)\n id_ = page.pageid\n url= page.url\n dic={'content': page.content,\n 'meta':{'name': page.title,\n 'url': url}}\n\n \n with open(f'/kaggle/working/rock_wiki/{id_}.json','w') as fo:\n json.dump(dic, fo)\n except Exception as e:\n traceback.print_exc()\n print(raw_title)\n ","metadata":{"execution":{"iopub.status.busy":"2022-08-20T23:34:49.157641Z","iopub.execute_input":"2022-08-20T23:34:49.158086Z","iopub.status.idle":"2022-08-20T23:44:29.346317Z","shell.execute_reply.started":"2022-08-20T23:34:49.158047Z","shell.execute_reply":"2022-08-20T23:44:29.345032Z"},"trusted":true},"execution_count":57,"outputs":[]},{"cell_type":"code","source":"! tar -czvf rock_wiki.tar.gz ./rock_wiki","metadata":{"execution":{"iopub.status.busy":"2022-08-20T23:50:44.643851Z","iopub.execute_input":"2022-08-20T23:50:44.644378Z","iopub.status.idle":"2022-08-20T23:50:44.650366Z","shell.execute_reply.started":"2022-08-20T23:50:44.644328Z","shell.execute_reply":"2022-08-20T23:50:44.649169Z"},"trusted":true},"execution_count":60,"outputs":[]}]}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "kernelspec": {
4
+ "language": "python",
5
+ "display_name": "Python 3",
6
+ "name": "python3"
7
+ },
8
+ "language_info": {
9
+ "name": "python",
10
+ "version": "3.7.12",
11
+ "mimetype": "text/x-python",
12
+ "codemirror_mode": {
13
+ "name": "ipython",
14
+ "version": 3
15
+ },
16
+ "pygments_lexer": "ipython3",
17
+ "nbconvert_exporter": "python",
18
+ "file_extension": ".py"
19
+ }
20
+ },
21
+ "nbformat_minor": 4,
22
+ "nbformat": 4,
23
+ "cells": [
24
+ {
25
+ "cell_type": "markdown",
26
+ "source": "# Download data from Wikipedia",
27
+ "metadata": {}
28
+ },
29
+ {
30
+ "cell_type": "code",
31
+ "source": "# install wikipedia API python wrapper\n! pip install wikipedia",
32
+ "metadata": {
33
+ "_uuid": "8f2839f25d086af736a60e9eeb907d3b93b6e0e5",
34
+ "_cell_guid": "b1076dfc-b9ad-4769-8c92-a6c4dae69d19",
35
+ "execution": {
36
+ "iopub.status.busy": "2022-08-20T21:43:59.293655Z",
37
+ "iopub.execute_input": "2022-08-20T21:43:59.294792Z",
38
+ "iopub.status.idle": "2022-08-20T21:44:15.263363Z",
39
+ "shell.execute_reply.started": "2022-08-20T21:43:59.294746Z",
40
+ "shell.execute_reply": "2022-08-20T21:44:15.262171Z"
41
+ },
42
+ "trusted": true
43
+ },
44
+ "execution_count": 3,
45
+ "outputs": []
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "source": "import wikipedia\nimport json\nimport traceback",
50
+ "metadata": {
51
+ "execution": {
52
+ "iopub.status.busy": "2022-08-20T21:44:15.265341Z",
53
+ "iopub.execute_input": "2022-08-20T21:44:15.265753Z",
54
+ "iopub.status.idle": "2022-08-20T21:44:15.470330Z",
55
+ "shell.execute_reply.started": "2022-08-20T21:44:15.265709Z",
56
+ "shell.execute_reply": "2022-08-20T21:44:15.468665Z"
57
+ },
58
+ "trusted": true
59
+ },
60
+ "execution_count": 4,
61
+ "outputs": []
62
+ },
63
+ {
64
+ "cell_type": "code",
65
+ "source": [
66
+ "# titles to download, from https://en.wikipedia.org/wiki/List_of_mainstream_rock_performers\n",
67
+ "\n",
68
+ "pages_titles = \"\"\"10cc\n",
69
+ "10_Years_(band)\n",
70
+ "3_Doors_Down\n",
71
+ "311_(band)\n",
72
+ "38_Special_(band)\n",
73
+ "Accept_(band)\n",
74
+ "AC/DC\n",
75
+ "Bryan_Adams\n",
76
+ "Aerosmith\n",
77
+ "AFI_(band)\n",
78
+ "Air_Supply\n",
79
+ "The_Alan_Parsons_Project\n",
80
+ "Alice_in_Chains\n",
81
+ "The_All-American_Rejects\n",
82
+ "The_Allman_Brothers_Band\n",
83
+ "Alter_Bridge\n",
84
+ "Ambrosia_(band)\n",
85
+ "America_(band)\n",
86
+ "The_Animals\n",
87
+ "Adam_Ant\n",
88
+ "Anthrax_(American_band)\n",
89
+ "April_Wine\n",
90
+ "Arcade_Fire\n",
91
+ "Arctic_Monkeys\n",
92
+ "Asia_(band)\n",
93
+ "Audioslave\n",
94
+ "Avenged_Sevenfold\n",
95
+ "Awolnation\n",
96
+ "The_B-52's\n",
97
+ "Bachman–Turner_Overdrive\n",
98
+ "Bad_Company\n",
99
+ "Badfinger\n",
100
+ "The_Band\n",
101
+ "The_Bangles\n",
102
+ "Barenaked_Ladies\n",
103
+ "Bay_City_Rollers\n",
104
+ "The_Beach_Boys\n",
105
+ "The_Beatles\n",
106
+ "Beck\n",
107
+ "Ben_Folds_Five\n",
108
+ "Pat_Benatar\n",
109
+ "Chuck_Berry\n",
110
+ "The_Big_Bopper\n",
111
+ "Billy_Talent\n",
112
+ "The_Black_Crowes\n",
113
+ "The_Black_Keys\n",
114
+ "Black_Sabbath\n",
115
+ "Black_Stone_Cherry\n",
116
+ "Black_Veil_Brides\n",
117
+ "Blink-182\n",
118
+ "Bloodhound_Gang\n",
119
+ "Blue_October\n",
120
+ "Blue_Öyster_Cult\n",
121
+ "Blues_Traveler\n",
122
+ "James_Blunt\n",
123
+ "Blur_(band)\n",
124
+ "Bon_Jovi\n",
125
+ "Boston_(band)\n",
126
+ "David_Bowie\n",
127
+ "Bowling_for_Soup\n",
128
+ "Boys_Like_Girls\n",
129
+ "Bread_(band)\n",
130
+ "Breaking_Benjamin\n",
131
+ "Bring_Me_the_Horizon\n",
132
+ "Jackson_Browne\n",
133
+ "Buckcherry\n",
134
+ "Jeff_Buckley\n",
135
+ "Bullet_for_My_Valentine\n",
136
+ "Bush_(British_band)\n",
137
+ "The_Byrds\n",
138
+ "Cage_the_Elephant\n",
139
+ "Cake_(band)\n",
140
+ "Canned_Heat\n",
141
+ "The_Cab\n",
142
+ "The_Cardigans\n",
143
+ "The_Cars\n",
144
+ "Catfish_and_the_Bottlemen\n",
145
+ "Harry_Chapin\n",
146
+ "Tracy_Chapman\n",
147
+ "Cheap_Trick\n",
148
+ "Chevelle_(band)\n",
149
+ "Chicago_(band)\n",
150
+ "Chubby_Checker\n",
151
+ "Cinderella_(band)\n",
152
+ "Dallas_Green_(musician)\n",
153
+ "Eric_Clapton\n",
154
+ "The_Clash\n",
155
+ "Eddie_Cochran\n",
156
+ "Joe_Cocker\n",
157
+ "Coheed_and_Cambria\n",
158
+ "Cold_Chisel\n",
159
+ "Coldplay\n",
160
+ "Collective_Soul\n",
161
+ "Phil_Collins\n",
162
+ "Alice_Cooper\n",
163
+ "Chris_Cornell\n",
164
+ "Elvis_Costello\n",
165
+ "Counting_Crows\n",
166
+ "The_Cranberries\n",
167
+ "Crash_Test_Dummies\n",
168
+ "Cream_(band)\n",
169
+ "Creed_(band)\n",
170
+ "Creedence_Clearwater_Revival\n",
171
+ "Jim_Croce\n",
172
+ "Crosby,_Stills,_Nash_&_Young\n",
173
+ "Christopher_Cross\n",
174
+ "Sheryl_Crow\n",
175
+ "Crowded_House\n",
176
+ "The_Cult\n",
177
+ "The_Cure\n",
178
+ "Damn_Yankees_(band)\n",
179
+ "Dashboard_Confessional\n",
180
+ "Daughtry_(band)\n",
181
+ "The_Dave_Clark_Five\n",
182
+ "Dave_Matthews_Band\n",
183
+ "Days_of_the_New\n",
184
+ "Death_Cab_for_Cutie\n",
185
+ "Deep_Purple\n",
186
+ "Def_Leppard\n",
187
+ "Deftones\n",
188
+ "Depeche_Mode\n",
189
+ "Bo_Diddley\n",
190
+ "Dio_(band)\n",
191
+ "Dire_Straits\n",
192
+ "Disturbed_(band)\n",
193
+ "Fats_Domino\n",
194
+ "Donovan\n",
195
+ "The_Doobie_Brothers\n",
196
+ "The_Doors\n",
197
+ "Dr._Hook_&_the_Medicine_Show\n",
198
+ "Dropkick_Murphys\n",
199
+ "Drowning_Pool\n",
200
+ "Duran_Duran\n",
201
+ "Ian_Dury\n",
202
+ "Bob_Dylan\n",
203
+ "Eagles_(band)\n",
204
+ "Echo_&_the_Bunnymen\n",
205
+ "Duane_Eddy\n",
206
+ "Edgar_Winter\n",
207
+ "Electric_Light_Orchestra\n",
208
+ "Emerson,_Lake_&_Palmer\n",
209
+ "England_Dan_&_John_Ford_Coley\n",
210
+ "Melissa_Etheridge\n",
211
+ "Europe_(band)\n",
212
+ "Evanescence\n",
213
+ "Everclear_(band)\n",
214
+ "Everlast\n",
215
+ "The_Everly_Brothers\n",
216
+ "Extreme_(band)\n",
217
+ "Faces_(band)\n",
218
+ "Faith_No_More\n",
219
+ "Fall_Out_Boy\n",
220
+ "Bryan_Ferry\n",
221
+ "Filter_(band)\n",
222
+ "Finger_Eleven\n",
223
+ "FireHouse\n",
224
+ "Five_Finger_Death_Punch\n",
225
+ "Five_for_Fighting\n",
226
+ "The_Fixx\n",
227
+ "The_Flaming_Lips\n",
228
+ "Fleetwood_Mac\n",
229
+ "Flogging_Molly\n",
230
+ "Florence_and_the_Machine\n",
231
+ "Flyleaf_(band)\n",
232
+ "Foals_(band)\n",
233
+ "Dan_Fogelberg\n",
234
+ "John_Fogerty\n",
235
+ "Foo_Fighters\n",
236
+ "Foreigner_(band)\n",
237
+ "Foster_the_People\n",
238
+ "The_Four_Seasons_(band)\n",
239
+ "Peter_Frampton\n",
240
+ "Franz_Ferdinand_(band)\n",
241
+ "The_Fray\n",
242
+ "Glenn_Frey\n",
243
+ "Fuel_(band)\n",
244
+ "Fun_(band)\n",
245
+ "Peter_Gabriel\n",
246
+ "Garbage_(band)\n",
247
+ "Genesis_(band)\n",
248
+ "Ghost_(Swedish_band)\n",
249
+ "Gin_Blossoms\n",
250
+ "Gary_Glitter\n",
251
+ "The_Go-Go's\n",
252
+ "Godsmack\n",
253
+ "Golden_Earring\n",
254
+ "Goo_Goo_Dolls\n",
255
+ "Good_Charlotte\n",
256
+ "Grand_Funk_Railroad\n",
257
+ "Grateful_Dead\n",
258
+ "Great_White\n",
259
+ "Green_Day\n",
260
+ "Greta_Van_Fleet\n",
261
+ "The_Guess_Who\n",
262
+ "Guns_N'_Roses\n",
263
+ "Halestorm\n",
264
+ "Bill_Haley_&_His_Comets\n",
265
+ "Hall_&_Oates\n",
266
+ "George_Harrison\n",
267
+ "Heart_(band)\n",
268
+ "Jimi_Hendrix\n",
269
+ "Don_Henley\n",
270
+ "Herman's_Hermits\n",
271
+ "Highly_Suspect\n",
272
+ "Hinder\n",
273
+ "The_Hives\n",
274
+ "Hole_(band)\n",
275
+ "The_Hollies\n",
276
+ "Buddy_Holly\n",
277
+ "Hoobastank\n",
278
+ "Hootie_&_the_Blowfish\n",
279
+ "Icehouse_(band)\n",
280
+ "Billy_Idol\n",
281
+ "Imagine_Dragons\n",
282
+ "Incubus_(band)\n",
283
+ "Interpol_(band)\n",
284
+ "INXS\n",
285
+ "Iron_Maiden\n",
286
+ "The_J._Geils_Band\n",
287
+ "The_Jam\n",
288
+ "Tommy_James_and_the_Shondells\n",
289
+ "Jane's_Addiction\n",
290
+ "Jefferson_Airplane\n",
291
+ "Jefferson_Starship\n",
292
+ "The_Jesus_and_Mary_Chain\n",
293
+ "Jet_(Australian_band)\n",
294
+ "Jethro_Tull_(band)\n",
295
+ "Joan_Jett\n",
296
+ "Jimmy_Eat_World\n",
297
+ "Billy_Joel\n",
298
+ "Elton_John\n",
299
+ "Janis_Joplin\n",
300
+ "Journey_(band)\n",
301
+ "Joy_Division\n",
302
+ "Judas_Priest\n",
303
+ "Kaiser_Chiefs\n",
304
+ "Kaleo_(band)\n",
305
+ "Kansas_(band)\n",
306
+ "Keane_(band)\n",
307
+ "Kid_Rock\n",
308
+ "The_Killers\n",
309
+ "Killswitch_Engage\n",
310
+ "Kings_of_Leon\n",
311
+ "The_Kinks\n",
312
+ "Kiss_(band)\n",
313
+ "Korn\n",
314
+ "Lenny_Kravitz\n",
315
+ "Lacuna_Coil\n",
316
+ "Lamb_of_God_(band)\n",
317
+ "Avril_Lavigne\n",
318
+ "Led_Zeppelin\n",
319
+ "John_Lennon\n",
320
+ "Huey_Lewis_and_the_News\n",
321
+ "Jerry_Lee_Lewis\n",
322
+ "Lifehouse_(band)\n",
323
+ "Limp_Bizkit\n",
324
+ "Linkin_Park\n",
325
+ "Little_Richard\n",
326
+ "Little_River_Band\n",
327
+ "Live_(band)\n",
328
+ "Living_Colour\n",
329
+ "Kenny_Loggins\n",
330
+ "Loverboy\n",
331
+ "The_Lovin'_Spoonful\n",
332
+ "The_Lumineers\n",
333
+ "Lynyrd_Skynyrd\n",
334
+ "The_Mamas_&_the_Papas\n",
335
+ "Marilyn_Manson\n",
336
+ "The_Marshall_Tucker_Band\n",
337
+ "Matchbox_Twenty\n",
338
+ "John_Mayer\n",
339
+ "Paul_McCartney\n",
340
+ "Meat_Loaf\n",
341
+ "Megadeth\n",
342
+ "John_Mellencamp\n",
343
+ "Men_at_Work\n",
344
+ "Metallica\n",
345
+ "Midnight_Oil\n",
346
+ "Mike_and_the_Mechanics\n",
347
+ "Modest_Mouse\n",
348
+ "Eddie_Money\n",
349
+ "The_Monkees\n",
350
+ "The_Moody_Blues\n",
351
+ "Alanis_Morissette\n",
352
+ "Van_Morrison\n",
353
+ "Morrissey\n",
354
+ "Mötley_Crüe\n",
355
+ "Motörhead\n",
356
+ "Mudvayne\n",
357
+ "Mumford_&_Sons\n",
358
+ "Muse_(band)\n",
359
+ "My_Chemical_Romance\n",
360
+ "Nickelback\n",
361
+ "Stevie_Nicks\n",
362
+ "Harry_Nilsson\n",
363
+ "Nine_Inch_Nails\n",
364
+ "Nirvana_(band)\n",
365
+ "No_Doubt\n",
366
+ "Ted_Nugent\n",
367
+ "Oasis_(band)\n",
368
+ "The_Offspring\n",
369
+ "Roy_Orbison\n",
370
+ "Ozzy_Osbourne\n",
371
+ "Our_Lady_Peace\n",
372
+ "The_Outfield\n",
373
+ "P.O.D.\n",
374
+ "Panic!_at_the_Disco\n",
375
+ "Pantera\n",
376
+ "Papa_Roach\n",
377
+ "Paramore\n",
378
+ "Pearl_Jam\n",
379
+ "A_Perfect_Circle\n",
380
+ "Tom_Petty_and_the_Heartbreakers\n",
381
+ "Pink_Floyd\n",
382
+ "Pixies_(band)\n",
383
+ "Robert_Plant\n",
384
+ "Poison_(American_band)\n",
385
+ "The_Police\n",
386
+ "Iggy_Pop\n",
387
+ "Pop_Evil\n",
388
+ "The_Presidents_of_the_United_States_of_America_(band)\n",
389
+ "The_Pretenders\n",
390
+ "Elvis_Presley\n",
391
+ "The_Pretty_Reckless\n",
392
+ "Primus_(band)\n",
393
+ "Puddle_of_Mudd\n",
394
+ "Queen_(band)\n",
395
+ "Queens_of_the_Stone_Age\n",
396
+ "Queensrÿche\n",
397
+ "Quiet_Riot\n",
398
+ "R.E.M.\n",
399
+ "Radiohead\n",
400
+ "Rage_Against_the_Machine\n",
401
+ "Rainbow_(rock_band)\n",
402
+ "Rammstein\n",
403
+ "Ramones\n",
404
+ "Red_Hot_Chili_Peppers\n",
405
+ "Lou_Reed\n",
406
+ "REO_Speedwagon\n",
407
+ "Rise_Against\n",
408
+ "The_Rolling_Stones\n",
409
+ "Linda_Ronstadt\n",
410
+ "Roxy_Music\n",
411
+ "Royal_Blood_(band)\n",
412
+ "Rush_(band)\n",
413
+ "Saliva_(band)\n",
414
+ "Sam_Fender\n",
415
+ "Santana_(band)\n",
416
+ "Joe_Satriani\n",
417
+ "Saving_Abel\n",
418
+ "Scorpions_(band)\n",
419
+ "The_Script\n",
420
+ "Seether\n",
421
+ "Bob_Seger\n",
422
+ "Sepultura\n",
423
+ "Sex_Pistols\n",
424
+ "Shakin'_Stevens\n",
425
+ "Shinedown\n",
426
+ "Silverchair\n",
427
+ "Simon_&_Garfunkel\n",
428
+ "Simple_Minds\n",
429
+ "Simple_Plan\n",
430
+ "Skid_Row_(American_band)\n",
431
+ "Skillet_(band)\n",
432
+ "Slade\n",
433
+ "Slayer\n",
434
+ "Slipknot_(band)\n",
435
+ "Small_Faces\n",
436
+ "Smash_Mouth\n",
437
+ "The_Smashing_Pumpkins\n",
438
+ "The_Smiths\n",
439
+ "Smokie_(band)\n",
440
+ "Snow_Patrol\n",
441
+ "Social_Distortion\n",
442
+ "Soundgarden\n",
443
+ "Bruce_Springsteen\n",
444
+ "Billy_Squier\n",
445
+ "Staind\n",
446
+ "Ringo_Starr\n",
447
+ "Starset\n",
448
+ "Starship_(band)\n",
449
+ "Status_Quo_(band)\n",
450
+ "Steely_Dan\n",
451
+ "Steppenwolf_(band)\n",
452
+ "Steve_Miller_Band\n",
453
+ "Rod_Stewart\n",
454
+ "Sting_(musician)\n",
455
+ "The_Stone_Roses\n",
456
+ "Stone_Sour\n",
457
+ "Stone_Temple_Pilots\n",
458
+ "The_Strokes\n",
459
+ "Styx_(band)\n",
460
+ "Sublime_(band)\n",
461
+ "Sum_41\n",
462
+ "Supertramp\n",
463
+ "Survivor_(band)\n",
464
+ "The_Sweet\n",
465
+ "System_of_a_Down\n",
466
+ "T._Rex_(band)\n",
467
+ "Talking_Heads\n",
468
+ "James_Taylor\n",
469
+ "Tenacious_D\n",
470
+ "Tesla_(band)\n",
471
+ "Theory_of_a_Deadman\n",
472
+ "Thin_Lizzy\n",
473
+ "Third_Eye_Blind\n",
474
+ "Thirty_Seconds_to_Mars\n",
475
+ "George_Thorogood\n",
476
+ "Thousand_Foot_Krutch\n",
477
+ "Three_Days_Grace\n",
478
+ "Three_Dog_Night\n",
479
+ "Tool_(band)\n",
480
+ "Toto_(band)\n",
481
+ "Traffic_(band)\n",
482
+ "The_Tragically_Hip\n",
483
+ "Train_(band)\n",
484
+ "Traveling_Wilburys\n",
485
+ "Travis_(band)\n",
486
+ "Trivium_(band)\n",
487
+ "Twenty_One_Pilots\n",
488
+ "Twisted_Sister\n",
489
+ "U2\n",
490
+ "Uriah_Heep_(band)\n",
491
+ "The_Used\n",
492
+ "Steve_Vai\n",
493
+ "Ritchie_Valens\n",
494
+ "Vampire_Weekend\n",
495
+ "Van_Halen\n",
496
+ "Stevie_Ray_Vaughan\n",
497
+ "Velvet_Revolver\n",
498
+ "The_Velvet_Underground\n",
499
+ "The_Verve\n",
500
+ "Volbeat\n",
501
+ "Joe_Walsh\n",
502
+ "Warrant_(American_band)\n",
503
+ "Weezer\n",
504
+ "Jack_White\n",
505
+ "The_White_Stripes\n",
506
+ "White_Zombie_(band)\n",
507
+ "Whitesnake\n",
508
+ "The_Who\n",
509
+ "Paul_McCartney_and_Wings\n",
510
+ "Steve_Winwood\n",
511
+ "The_Yardbirds\n",
512
+ "Yes_(band)\n",
513
+ "Neil_Young\n",
514
+ "Frank_Zappa\n",
515
+ "Rob_Zombie\n",
516
+ "The_Zombies\n",
517
+ "ZZ_Top\"\"\".split(\n",
518
+ " \"\\n\"\n",
519
+ ")"
520
+ ],
521
+ "metadata": {
522
+ "execution": {
523
+ "iopub.status.busy": "2022-08-20T23:34:24.681697Z",
524
+ "iopub.execute_input": "2022-08-20T23:34:24.682223Z",
525
+ "iopub.status.idle": "2022-08-20T23:34:24.693942Z",
526
+ "shell.execute_reply.started": "2022-08-20T23:34:24.682178Z",
527
+ "shell.execute_reply": "2022-08-20T23:34:24.693004Z"
528
+ },
529
+ "trusted": true
530
+ },
531
+ "execution_count": 54,
532
+ "outputs": []
533
+ },
534
+ {
535
+ "cell_type": "code",
536
+ "source": [
537
+ "for i, raw_title in enumerate(pages_titles):\n",
538
+ " if i % 10 == 0:\n",
539
+ " print(i / len(pages_titles) * 100)\n",
540
+ " try:\n",
541
+ " page = wikipedia.page(title=raw_title.replace(\"_\", \" \"), auto_suggest=False)\n",
542
+ " id_ = page.pageid\n",
543
+ " url = page.url\n",
544
+ " dic = {\"content\": page.content, \"meta\": {\"name\": page.title, \"url\": url}}\n",
545
+ "\n",
546
+ " with open(f\"/kaggle/working/rock_wiki/{id_}.json\", \"w\") as fo:\n",
547
+ " json.dump(dic, fo)\n",
548
+ " except Exception as e:\n",
549
+ " traceback.print_exc()\n",
550
+ " print(raw_title)"
551
+ ],
552
+ "metadata": {
553
+ "execution": {
554
+ "iopub.status.busy": "2022-08-20T23:34:49.157641Z",
555
+ "iopub.execute_input": "2022-08-20T23:34:49.158086Z",
556
+ "iopub.status.idle": "2022-08-20T23:44:29.346317Z",
557
+ "shell.execute_reply.started": "2022-08-20T23:34:49.158047Z",
558
+ "shell.execute_reply": "2022-08-20T23:44:29.345032Z"
559
+ },
560
+ "trusted": true
561
+ },
562
+ "execution_count": 57,
563
+ "outputs": []
564
+ },
565
+ {
566
+ "cell_type": "code",
567
+ "source": "! tar -czvf rock_wiki.tar.gz ./rock_wiki",
568
+ "metadata": {
569
+ "execution": {
570
+ "iopub.status.busy": "2022-08-20T23:50:44.643851Z",
571
+ "iopub.execute_input": "2022-08-20T23:50:44.644378Z",
572
+ "iopub.status.idle": "2022-08-20T23:50:44.650366Z",
573
+ "shell.execute_reply.started": "2022-08-20T23:50:44.644328Z",
574
+ "shell.execute_reply": "2022-08-20T23:50:44.649169Z"
575
+ },
576
+ "trusted": true
577
+ },
578
+ "execution_count": 60,
579
+ "outputs": []
580
+ }
581
+ ]
582
+ }
notebooks/indexing.ipynb CHANGED
@@ -1 +1,417 @@
1
- {"cells":[{"cell_type":"markdown","metadata":{},"source":["# Indexing\n","Using [Haystack](https://github.com/deepset-ai/haystack), the following steps are performed:\n","- load and preprocess documents downloaded from Wikipedia\n","- create document store and write documents\n","- initialize retriever and generate document embeddings"]},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","trusted":true},"outputs":[],"source":["! pip install farm-haystack[faiss-gpu]==1.7.0"]},{"cell_type":"markdown","metadata":{},"source":["## Load documents"]},{"cell_type":"code","execution_count":2,"metadata":{"execution":{"iopub.execute_input":"2022-08-21T08:23:23.692554Z","iopub.status.busy":"2022-08-21T08:23:23.692208Z","iopub.status.idle":"2022-08-21T08:23:23.700721Z","shell.execute_reply":"2022-08-21T08:23:23.698130Z","shell.execute_reply.started":"2022-08-21T08:23:23.692512Z"},"trusted":true},"outputs":[],"source":["import glob, json"]},{"cell_type":"code","execution_count":3,"metadata":{"execution":{"iopub.execute_input":"2022-08-21T08:23:23.707774Z","iopub.status.busy":"2022-08-21T08:23:23.704107Z","iopub.status.idle":"2022-08-21T08:23:25.026910Z","shell.execute_reply":"2022-08-21T08:23:25.025990Z","shell.execute_reply.started":"2022-08-21T08:23:23.705010Z"},"trusted":true},"outputs":[],"source":["docs=[]\n","\n","for json_file in glob.glob('../input/crawl-rock/rock_wiki/*.json'):\n"," with open(json_file, 'r') as fin:\n"," doc=json.load(fin)\n","\n"," docs.append(doc)\n"]},{"cell_type":"code","execution_count":4,"metadata":{"execution":{"iopub.execute_input":"2022-08-21T08:23:25.030530Z","iopub.status.busy":"2022-08-21T08:23:25.029931Z","iopub.status.idle":"2022-08-21T08:23:25.039324Z","shell.execute_reply":"2022-08-21T08:23:25.037960Z","shell.execute_reply.started":"2022-08-21T08:23:25.030491Z"},"trusted":true},"outputs":[{"data":{"text/plain":["453"]},"execution_count":4,"metadata":{},"output_type":"execute_result"}],"source":["len(docs)"]},{"cell_type":"markdown","metadata":{},"source":["## Preprocess documents"]},{"cell_type":"code","execution_count":6,"metadata":{"execution":{"iopub.execute_input":"2022-08-21T08:23:25.050479Z","iopub.status.busy":"2022-08-21T08:23:25.050099Z","iopub.status.idle":"2022-08-21T08:23:42.089083Z","shell.execute_reply":"2022-08-21T08:23:42.087929Z","shell.execute_reply.started":"2022-08-21T08:23:25.050446Z"},"trusted":true},"outputs":[{"data":{"application/vnd.jupyter.widget-view+json":{"model_id":"108e8c46426f44e7be98a8ae930d81ce","version_major":2,"version_minor":0},"text/plain":["Preprocessing: 0%| | 0/453 [00:00<?, ?docs/s]"]},"metadata":{},"output_type":"display_data"}],"source":["# preprocess documents, splitting by chunks of 2 sentences\n","\n","from haystack.nodes import PreProcessor\n","\n","processor = PreProcessor(\n"," clean_empty_lines=True,\n"," clean_whitespace=True,\n"," clean_header_footer=True,\n"," split_by=\"sentence\",\n"," split_length=2,\n"," split_respect_sentence_boundary=False,\n"," split_overlap=0,\n"," language ='en'\n",")\n","preprocessed_docs = processor.process(docs)"]},{"cell_type":"code","execution_count":7,"metadata":{"execution":{"iopub.execute_input":"2022-08-21T08:23:42.092031Z","iopub.status.busy":"2022-08-21T08:23:42.090654Z","iopub.status.idle":"2022-08-21T08:23:42.105757Z","shell.execute_reply":"2022-08-21T08:23:42.104500Z","shell.execute_reply.started":"2022-08-21T08:23:42.091989Z"},"trusted":true},"outputs":[{"data":{"text/plain":["50024"]},"execution_count":7,"metadata":{},"output_type":"execute_result"}],"source":["len(preprocessed_docs)"]},{"cell_type":"code","execution_count":8,"metadata":{"execution":{"iopub.execute_input":"2022-08-21T08:23:42.108367Z","iopub.status.busy":"2022-08-21T08:23:42.107604Z","iopub.status.idle":"2022-08-21T08:23:42.117080Z","shell.execute_reply":"2022-08-21T08:23:42.115996Z","shell.execute_reply.started":"2022-08-21T08:23:42.108271Z"},"trusted":true},"outputs":[{"data":{"text/plain":["[<Document: {'content': 'Disturbed is an American heavy metal band from Chicago, formed in 1994. The band includes vocalist David Draiman, guitarist/keyboardist Dan Donegan, bassist John Moyer, and drummer Mike Wengren.', 'content_type': 'text', 'score': None, 'meta': {'name': 'Disturbed (band)', 'url': 'https://en.wikipedia.org/wiki/Disturbed_(band)', '_split_id': 0}, 'embedding': None, 'id': '543d4f9f9023bfc277edf307a6aef870'}>,\n"," <Document: {'content': 'Donegan and Wengren have been involved in the band since its inception, with Moyer replacing former bassist Steve \"Fuzz\" Kmak and Draiman replacing original lead vocalist Erich Awalt. The band has released seven studio albums, five of which have consecutively debuted at number one on the Billboard 200.', 'content_type': 'text', 'score': None, 'meta': {'name': 'Disturbed (band)', 'url': 'https://en.wikipedia.org/wiki/Disturbed_(band)', '_split_id': 1}, 'embedding': None, 'id': 'dfb0ef877837c95b2e8b03cfe2ae2057'}>,\n"," <Document: {'content': \"Disturbed went into hiatus in October 2011, during which the band's members focused on various side projects, and returned in June 2015, releasing their first album in four years, Immortalized in August 2015. They also released two live albums, Music as a Weapon II in February 2004 and Disturbed: Live at Red Rocks in November 2016.\", 'content_type': 'text', 'score': None, 'meta': {'name': 'Disturbed (band)', 'url': 'https://en.wikipedia.org/wiki/Disturbed_(band)', '_split_id': 2}, 'embedding': None, 'id': 'e498da0cc7477f698f4a30c85dbfd95d'}>,\n"," <Document: {'content': 'With over 17 million records sold worldwide, Disturbed ranks alongside Slipknot and Godsmack as one of the most successful rock bands of the 21st century. == History ==\\n\\n=== Early years (1994–1996) ===\\nBefore David Draiman joined Disturbed, guitarist Dan Donegan, drummer Mike Wengren and bassist Steve \"Fuzz\" Kmak were in a band called Brawl with vocalist Erich Awalt.', 'content_type': 'text', 'score': None, 'meta': {'name': 'Disturbed (band)', 'url': 'https://en.wikipedia.org/wiki/Disturbed_(band)', '_split_id': 3}, 'embedding': None, 'id': '2b51b8f38befc2c53c65c66af6de1e05'}>,\n"," <Document: {'content': 'Before changing their name to \"Brawl\", however, Donegan mentioned in the band\\'s DVD, Decade of Disturbed, that the name was originally going to be \"Crawl\"; they switched it to \"Brawl\", due to the name already being used by another band. Awalt left the band shortly after the recording of a demo tape; the other three members advertised for a singer.', 'content_type': 'text', 'score': None, 'meta': {'name': 'Disturbed (band)', 'url': 'https://en.wikipedia.org/wiki/Disturbed_(band)', '_split_id': 4}, 'embedding': None, 'id': 'c9b3a4a74f8332c9d4c3d1e30cac49f7'}>,\n"," <Document: {'content': 'They posted an advertisement in the local music publication in Chicago, Illinois, called the \"Illinois Entertainer\". Draiman answered the advertisement after going to twenty other auditions that month.', 'content_type': 'text', 'score': None, 'meta': {'name': 'Disturbed (band)', 'url': 'https://en.wikipedia.org/wiki/Disturbed_(band)', '_split_id': 5}, 'embedding': None, 'id': '946a4a27f2f1838ec070a951dab2e1b0'}>,\n"," <Document: {'content': 'Guitarist Dan Donegan commented on Draiman: \"You know, out of all the singers that we had talked to or auditioned, he [Draiman] was the only singer who was ready to go with originals. And that impressed me, just to attempt that\".With regard to Draiman being the singer for the band, Donegan said, \"After a minute or two, he just starts banging out these melodies that were huge...I\\'m playing my guitar and I\\'m grinning from ear to ear, trying not to give it away that I like this guy, you know, because I don\\'t want to, you know...[say] \\'Yeah, we\\'ll give you a call back.', 'content_type': 'text', 'score': None, 'meta': {'name': 'Disturbed (band)', 'url': 'https://en.wikipedia.org/wiki/Disturbed_(band)', '_split_id': 6}, 'embedding': None, 'id': 'ac2bea954f4d19cc0e48868fb503e23e'}>,\n"," <Document: {'content': \"We'll, you know, discuss it.' But I was so psyched.\", 'content_type': 'text', 'score': None, 'meta': {'name': 'Disturbed (band)', 'url': 'https://en.wikipedia.org/wiki/Disturbed_(band)', '_split_id': 7}, 'embedding': None, 'id': '852a32a0d3ce1eefa48d6420fab35dba'}>,\n"," <Document: {'content': 'Chill up my spine. I\\'m like, \\'There is something here.\\'\"', 'content_type': 'text', 'score': None, 'meta': {'name': 'Disturbed (band)', 'url': 'https://en.wikipedia.org/wiki/Disturbed_(band)', '_split_id': 8}, 'embedding': None, 'id': 'ebb584a0fee18b51cd14ceadcb4a7bb8'}>,\n"," <Document: {'content': 'As drummer Mike Wengren commented, \"We clicked right off the bat.\" Draiman then joined the band in 1996 and the band was renamed Disturbed.', 'content_type': 'text', 'score': None, 'meta': {'name': 'Disturbed (band)', 'url': 'https://en.wikipedia.org/wiki/Disturbed_(band)', '_split_id': 9}, 'embedding': None, 'id': '51340b7bf229e5b8d4460341f7aaa9d0'}>]"]},"execution_count":8,"metadata":{},"output_type":"execute_result"}],"source":["preprocessed_docs[:10]"]},{"cell_type":"markdown","metadata":{},"source":["## Create document store ([FAISS](https://github.com/facebookresearch/faiss)) and write documents"]},{"cell_type":"code","execution_count":9,"metadata":{"execution":{"iopub.execute_input":"2022-08-21T08:23:42.119585Z","iopub.status.busy":"2022-08-21T08:23:42.118544Z","iopub.status.idle":"2022-08-21T08:23:42.124669Z","shell.execute_reply":"2022-08-21T08:23:42.123597Z","shell.execute_reply.started":"2022-08-21T08:23:42.119551Z"},"trusted":true},"outputs":[],"source":["from haystack.document_stores import FAISSDocumentStore\n","from haystack.nodes import EmbeddingRetriever"]},{"cell_type":"code","execution_count":10,"metadata":{"execution":{"iopub.execute_input":"2022-08-21T08:23:42.129562Z","iopub.status.busy":"2022-08-21T08:23:42.128772Z","iopub.status.idle":"2022-08-21T08:23:42.259879Z","shell.execute_reply":"2022-08-21T08:23:42.258950Z","shell.execute_reply.started":"2022-08-21T08:23:42.129518Z"},"trusted":true},"outputs":[],"source":["# the document store settings are those compatible with Embedding Retriever\n","document_store = FAISSDocumentStore(\n"," similarity=\"dot_product\",\n"," embedding_dim=768)"]},{"cell_type":"code","execution_count":46,"metadata":{"execution":{"iopub.execute_input":"2022-08-21T08:43:25.952230Z","iopub.status.busy":"2022-08-21T08:43:25.951856Z","iopub.status.idle":"2022-08-21T08:46:12.506842Z","shell.execute_reply":"2022-08-21T08:46:12.505845Z","shell.execute_reply.started":"2022-08-21T08:43:25.952198Z"},"trusted":true},"outputs":[{"data":{"application/vnd.jupyter.widget-view+json":{"model_id":"dbd72ecf0d36401ba26826f7d9a42540","version_major":2,"version_minor":0},"text/plain":["Writing Documents: 0%| | 0/50024 [00:00<?, ?it/s]"]},"metadata":{},"output_type":"display_data"}],"source":["# write documents\n","document_store.write_documents(preprocessed_docs)"]},{"cell_type":"markdown","metadata":{},"source":["## Initialize retriever (Embedding Retriever) and generate document embeddings\n","We choose a Sentence Tranformer model that is suitable for asymmetric semantic search (short query and longer passages), according to [documentation](https://www.sbert.net/examples/applications/semantic-search/README.html#symmetric-vs-asymmetric-semantic-search)."]},{"cell_type":"code","execution_count":null,"metadata":{"execution":{"iopub.execute_input":"2022-08-21T08:56:25.360959Z","iopub.status.busy":"2022-08-21T08:56:25.360546Z","iopub.status.idle":"2022-08-21T08:58:07.214654Z","shell.execute_reply":"2022-08-21T08:58:07.213653Z","shell.execute_reply.started":"2022-08-21T08:56:25.360926Z"},"trusted":true},"outputs":[],"source":["from haystack.nodes import EmbeddingRetriever\n","\n","retriever = EmbeddingRetriever(\n"," document_store=document_store,\n"," embedding_model=\"sentence-transformers/msmarco-distilbert-base-tas-b\",\n"," model_format=\"sentence_transformers\",\n"," embed_meta_fields=['name']\n",")\n","\n","# generate embeddings\n","document_store.update_embeddings(retriever)"]},{"cell_type":"markdown","metadata":{},"source":["## Save and export index"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["import shutil\n","import glob"]},{"cell_type":"code","execution_count":73,"metadata":{"execution":{"iopub.execute_input":"2022-08-21T08:58:33.494417Z","iopub.status.busy":"2022-08-21T08:58:33.493822Z","iopub.status.idle":"2022-08-21T08:58:33.635915Z","shell.execute_reply":"2022-08-21T08:58:33.634599Z","shell.execute_reply.started":"2022-08-21T08:58:33.494382Z"},"trusted":true},"outputs":[],"source":["OUT_DIR = 'YOUR-OUT-DIR'\n","\n","document_store.save(\"my_faiss_index.faiss\")\n","for f in glob.glob('*faiss*.*')+glob.glob('faiss*.*'):\n"," shutil.copy(f, OUT_DIR)"]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.7.12"}},"nbformat":4,"nbformat_minor":4}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "# Indexing\n",
8
+ "Using [Haystack](https://github.com/deepset-ai/haystack), the following steps are performed:\n",
9
+ "- load and preprocess documents downloaded from Wikipedia\n",
10
+ "- create document store and write documents\n",
11
+ "- initialize retriever and generate document embeddings"
12
+ ]
13
+ },
14
+ {
15
+ "cell_type": "code",
16
+ "execution_count": null,
17
+ "metadata": {
18
+ "_cell_guid": "b1076dfc-b9ad-4769-8c92-a6c4dae69d19",
19
+ "_uuid": "8f2839f25d086af736a60e9eeb907d3b93b6e0e5",
20
+ "trusted": true
21
+ },
22
+ "outputs": [],
23
+ "source": [
24
+ "! pip install farm-haystack[faiss-gpu]==1.7.0"
25
+ ]
26
+ },
27
+ {
28
+ "cell_type": "markdown",
29
+ "metadata": {},
30
+ "source": [
31
+ "## Load documents"
32
+ ]
33
+ },
34
+ {
35
+ "cell_type": "code",
36
+ "execution_count": 2,
37
+ "metadata": {
38
+ "execution": {
39
+ "iopub.execute_input": "2022-08-21T08:23:23.692554Z",
40
+ "iopub.status.busy": "2022-08-21T08:23:23.692208Z",
41
+ "iopub.status.idle": "2022-08-21T08:23:23.700721Z",
42
+ "shell.execute_reply": "2022-08-21T08:23:23.698130Z",
43
+ "shell.execute_reply.started": "2022-08-21T08:23:23.692512Z"
44
+ },
45
+ "trusted": true
46
+ },
47
+ "outputs": [],
48
+ "source": [
49
+ "import glob, json"
50
+ ]
51
+ },
52
+ {
53
+ "cell_type": "code",
54
+ "execution_count": 3,
55
+ "metadata": {
56
+ "execution": {
57
+ "iopub.execute_input": "2022-08-21T08:23:23.707774Z",
58
+ "iopub.status.busy": "2022-08-21T08:23:23.704107Z",
59
+ "iopub.status.idle": "2022-08-21T08:23:25.026910Z",
60
+ "shell.execute_reply": "2022-08-21T08:23:25.025990Z",
61
+ "shell.execute_reply.started": "2022-08-21T08:23:23.705010Z"
62
+ },
63
+ "trusted": true
64
+ },
65
+ "outputs": [],
66
+ "source": [
67
+ "docs = []\n",
68
+ "\n",
69
+ "for json_file in glob.glob(\"../input/crawl-rock/rock_wiki/*.json\"):\n",
70
+ " with open(json_file, \"r\") as fin:\n",
71
+ " doc = json.load(fin)\n",
72
+ "\n",
73
+ " docs.append(doc)"
74
+ ]
75
+ },
76
+ {
77
+ "cell_type": "code",
78
+ "execution_count": 4,
79
+ "metadata": {
80
+ "execution": {
81
+ "iopub.execute_input": "2022-08-21T08:23:25.030530Z",
82
+ "iopub.status.busy": "2022-08-21T08:23:25.029931Z",
83
+ "iopub.status.idle": "2022-08-21T08:23:25.039324Z",
84
+ "shell.execute_reply": "2022-08-21T08:23:25.037960Z",
85
+ "shell.execute_reply.started": "2022-08-21T08:23:25.030491Z"
86
+ },
87
+ "trusted": true
88
+ },
89
+ "outputs": [
90
+ {
91
+ "data": {
92
+ "text/plain": [
93
+ "453"
94
+ ]
95
+ },
96
+ "execution_count": 4,
97
+ "metadata": {},
98
+ "output_type": "execute_result"
99
+ }
100
+ ],
101
+ "source": [
102
+ "len(docs)"
103
+ ]
104
+ },
105
+ {
106
+ "cell_type": "markdown",
107
+ "metadata": {},
108
+ "source": [
109
+ "## Preprocess documents"
110
+ ]
111
+ },
112
+ {
113
+ "cell_type": "code",
114
+ "execution_count": 6,
115
+ "metadata": {
116
+ "execution": {
117
+ "iopub.execute_input": "2022-08-21T08:23:25.050479Z",
118
+ "iopub.status.busy": "2022-08-21T08:23:25.050099Z",
119
+ "iopub.status.idle": "2022-08-21T08:23:42.089083Z",
120
+ "shell.execute_reply": "2022-08-21T08:23:42.087929Z",
121
+ "shell.execute_reply.started": "2022-08-21T08:23:25.050446Z"
122
+ },
123
+ "trusted": true
124
+ },
125
+ "outputs": [
126
+ {
127
+ "data": {
128
+ "application/vnd.jupyter.widget-view+json": {
129
+ "model_id": "108e8c46426f44e7be98a8ae930d81ce",
130
+ "version_major": 2,
131
+ "version_minor": 0
132
+ },
133
+ "text/plain": [
134
+ "Preprocessing: 0%| | 0/453 [00:00<?, ?docs/s]"
135
+ ]
136
+ },
137
+ "metadata": {},
138
+ "output_type": "display_data"
139
+ }
140
+ ],
141
+ "source": [
142
+ "# preprocess documents, splitting by chunks of 2 sentences\n",
143
+ "\n",
144
+ "from haystack.nodes import PreProcessor\n",
145
+ "\n",
146
+ "processor = PreProcessor(\n",
147
+ " clean_empty_lines=True,\n",
148
+ " clean_whitespace=True,\n",
149
+ " clean_header_footer=True,\n",
150
+ " split_by=\"sentence\",\n",
151
+ " split_length=2,\n",
152
+ " split_respect_sentence_boundary=False,\n",
153
+ " split_overlap=0,\n",
154
+ " language=\"en\",\n",
155
+ ")\n",
156
+ "preprocessed_docs = processor.process(docs)"
157
+ ]
158
+ },
159
+ {
160
+ "cell_type": "code",
161
+ "execution_count": 7,
162
+ "metadata": {
163
+ "execution": {
164
+ "iopub.execute_input": "2022-08-21T08:23:42.092031Z",
165
+ "iopub.status.busy": "2022-08-21T08:23:42.090654Z",
166
+ "iopub.status.idle": "2022-08-21T08:23:42.105757Z",
167
+ "shell.execute_reply": "2022-08-21T08:23:42.104500Z",
168
+ "shell.execute_reply.started": "2022-08-21T08:23:42.091989Z"
169
+ },
170
+ "trusted": true
171
+ },
172
+ "outputs": [
173
+ {
174
+ "data": {
175
+ "text/plain": [
176
+ "50024"
177
+ ]
178
+ },
179
+ "execution_count": 7,
180
+ "metadata": {},
181
+ "output_type": "execute_result"
182
+ }
183
+ ],
184
+ "source": [
185
+ "len(preprocessed_docs)"
186
+ ]
187
+ },
188
+ {
189
+ "cell_type": "code",
190
+ "execution_count": 8,
191
+ "metadata": {
192
+ "execution": {
193
+ "iopub.execute_input": "2022-08-21T08:23:42.108367Z",
194
+ "iopub.status.busy": "2022-08-21T08:23:42.107604Z",
195
+ "iopub.status.idle": "2022-08-21T08:23:42.117080Z",
196
+ "shell.execute_reply": "2022-08-21T08:23:42.115996Z",
197
+ "shell.execute_reply.started": "2022-08-21T08:23:42.108271Z"
198
+ },
199
+ "trusted": true
200
+ },
201
+ "outputs": [
202
+ {
203
+ "data": {
204
+ "text/plain": [
205
+ "[<Document: {'content': 'Disturbed is an American heavy metal band from Chicago, formed in 1994. The band includes vocalist David Draiman, guitarist/keyboardist Dan Donegan, bassist John Moyer, and drummer Mike Wengren.', 'content_type': 'text', 'score': None, 'meta': {'name': 'Disturbed (band)', 'url': 'https://en.wikipedia.org/wiki/Disturbed_(band)', '_split_id': 0}, 'embedding': None, 'id': '543d4f9f9023bfc277edf307a6aef870'}>,\n",
206
+ " <Document: {'content': 'Donegan and Wengren have been involved in the band since its inception, with Moyer replacing former bassist Steve \"Fuzz\" Kmak and Draiman replacing original lead vocalist Erich Awalt. The band has released seven studio albums, five of which have consecutively debuted at number one on the Billboard 200.', 'content_type': 'text', 'score': None, 'meta': {'name': 'Disturbed (band)', 'url': 'https://en.wikipedia.org/wiki/Disturbed_(band)', '_split_id': 1}, 'embedding': None, 'id': 'dfb0ef877837c95b2e8b03cfe2ae2057'}>,\n",
207
+ " <Document: {'content': \"Disturbed went into hiatus in October 2011, during which the band's members focused on various side projects, and returned in June 2015, releasing their first album in four years, Immortalized in August 2015. They also released two live albums, Music as a Weapon II in February 2004 and Disturbed: Live at Red Rocks in November 2016.\", 'content_type': 'text', 'score': None, 'meta': {'name': 'Disturbed (band)', 'url': 'https://en.wikipedia.org/wiki/Disturbed_(band)', '_split_id': 2}, 'embedding': None, 'id': 'e498da0cc7477f698f4a30c85dbfd95d'}>,\n",
208
+ " <Document: {'content': 'With over 17 million records sold worldwide, Disturbed ranks alongside Slipknot and Godsmack as one of the most successful rock bands of the 21st century. == History ==\\n\\n=== Early years (1994–1996) ===\\nBefore David Draiman joined Disturbed, guitarist Dan Donegan, drummer Mike Wengren and bassist Steve \"Fuzz\" Kmak were in a band called Brawl with vocalist Erich Awalt.', 'content_type': 'text', 'score': None, 'meta': {'name': 'Disturbed (band)', 'url': 'https://en.wikipedia.org/wiki/Disturbed_(band)', '_split_id': 3}, 'embedding': None, 'id': '2b51b8f38befc2c53c65c66af6de1e05'}>,\n",
209
+ " <Document: {'content': 'Before changing their name to \"Brawl\", however, Donegan mentioned in the band\\'s DVD, Decade of Disturbed, that the name was originally going to be \"Crawl\"; they switched it to \"Brawl\", due to the name already being used by another band. Awalt left the band shortly after the recording of a demo tape; the other three members advertised for a singer.', 'content_type': 'text', 'score': None, 'meta': {'name': 'Disturbed (band)', 'url': 'https://en.wikipedia.org/wiki/Disturbed_(band)', '_split_id': 4}, 'embedding': None, 'id': 'c9b3a4a74f8332c9d4c3d1e30cac49f7'}>,\n",
210
+ " <Document: {'content': 'They posted an advertisement in the local music publication in Chicago, Illinois, called the \"Illinois Entertainer\". Draiman answered the advertisement after going to twenty other auditions that month.', 'content_type': 'text', 'score': None, 'meta': {'name': 'Disturbed (band)', 'url': 'https://en.wikipedia.org/wiki/Disturbed_(band)', '_split_id': 5}, 'embedding': None, 'id': '946a4a27f2f1838ec070a951dab2e1b0'}>,\n",
211
+ " <Document: {'content': 'Guitarist Dan Donegan commented on Draiman: \"You know, out of all the singers that we had talked to or auditioned, he [Draiman] was the only singer who was ready to go with originals. And that impressed me, just to attempt that\".With regard to Draiman being the singer for the band, Donegan said, \"After a minute or two, he just starts banging out these melodies that were huge...I\\'m playing my guitar and I\\'m grinning from ear to ear, trying not to give it away that I like this guy, you know, because I don\\'t want to, you know...[say] \\'Yeah, we\\'ll give you a call back.', 'content_type': 'text', 'score': None, 'meta': {'name': 'Disturbed (band)', 'url': 'https://en.wikipedia.org/wiki/Disturbed_(band)', '_split_id': 6}, 'embedding': None, 'id': 'ac2bea954f4d19cc0e48868fb503e23e'}>,\n",
212
+ " <Document: {'content': \"We'll, you know, discuss it.' But I was so psyched.\", 'content_type': 'text', 'score': None, 'meta': {'name': 'Disturbed (band)', 'url': 'https://en.wikipedia.org/wiki/Disturbed_(band)', '_split_id': 7}, 'embedding': None, 'id': '852a32a0d3ce1eefa48d6420fab35dba'}>,\n",
213
+ " <Document: {'content': 'Chill up my spine. I\\'m like, \\'There is something here.\\'\"', 'content_type': 'text', 'score': None, 'meta': {'name': 'Disturbed (band)', 'url': 'https://en.wikipedia.org/wiki/Disturbed_(band)', '_split_id': 8}, 'embedding': None, 'id': 'ebb584a0fee18b51cd14ceadcb4a7bb8'}>,\n",
214
+ " <Document: {'content': 'As drummer Mike Wengren commented, \"We clicked right off the bat.\" Draiman then joined the band in 1996 and the band was renamed Disturbed.', 'content_type': 'text', 'score': None, 'meta': {'name': 'Disturbed (band)', 'url': 'https://en.wikipedia.org/wiki/Disturbed_(band)', '_split_id': 9}, 'embedding': None, 'id': '51340b7bf229e5b8d4460341f7aaa9d0'}>]"
215
+ ]
216
+ },
217
+ "execution_count": 8,
218
+ "metadata": {},
219
+ "output_type": "execute_result"
220
+ }
221
+ ],
222
+ "source": [
223
+ "preprocessed_docs[:10]"
224
+ ]
225
+ },
226
+ {
227
+ "cell_type": "code",
228
+ "execution_count": null,
229
+ "metadata": {},
230
+ "outputs": [],
231
+ "source": [
232
+ "# select only documents with at least 10 words. Otherwise, the documents are not very informative\n",
233
+ "preprocessed_docs = [doc for doc in preprocessed_docs if len(doc.content.split()) >= 10]"
234
+ ]
235
+ },
236
+ {
237
+ "cell_type": "markdown",
238
+ "metadata": {},
239
+ "source": [
240
+ "## Create document store ([FAISS](https://github.com/facebookresearch/faiss)) and write documents"
241
+ ]
242
+ },
243
+ {
244
+ "cell_type": "code",
245
+ "execution_count": 9,
246
+ "metadata": {
247
+ "execution": {
248
+ "iopub.execute_input": "2022-08-21T08:23:42.119585Z",
249
+ "iopub.status.busy": "2022-08-21T08:23:42.118544Z",
250
+ "iopub.status.idle": "2022-08-21T08:23:42.124669Z",
251
+ "shell.execute_reply": "2022-08-21T08:23:42.123597Z",
252
+ "shell.execute_reply.started": "2022-08-21T08:23:42.119551Z"
253
+ },
254
+ "trusted": true
255
+ },
256
+ "outputs": [],
257
+ "source": [
258
+ "from haystack.document_stores import FAISSDocumentStore\n",
259
+ "from haystack.nodes import EmbeddingRetriever"
260
+ ]
261
+ },
262
+ {
263
+ "cell_type": "code",
264
+ "execution_count": 10,
265
+ "metadata": {
266
+ "execution": {
267
+ "iopub.execute_input": "2022-08-21T08:23:42.129562Z",
268
+ "iopub.status.busy": "2022-08-21T08:23:42.128772Z",
269
+ "iopub.status.idle": "2022-08-21T08:23:42.259879Z",
270
+ "shell.execute_reply": "2022-08-21T08:23:42.258950Z",
271
+ "shell.execute_reply.started": "2022-08-21T08:23:42.129518Z"
272
+ },
273
+ "trusted": true
274
+ },
275
+ "outputs": [],
276
+ "source": [
277
+ "# the document store settings are those compatible with Embedding Retriever\n",
278
+ "document_store = FAISSDocumentStore(similarity=\"dot_product\", embedding_dim=768)"
279
+ ]
280
+ },
281
+ {
282
+ "cell_type": "code",
283
+ "execution_count": 46,
284
+ "metadata": {
285
+ "execution": {
286
+ "iopub.execute_input": "2022-08-21T08:43:25.952230Z",
287
+ "iopub.status.busy": "2022-08-21T08:43:25.951856Z",
288
+ "iopub.status.idle": "2022-08-21T08:46:12.506842Z",
289
+ "shell.execute_reply": "2022-08-21T08:46:12.505845Z",
290
+ "shell.execute_reply.started": "2022-08-21T08:43:25.952198Z"
291
+ },
292
+ "trusted": true
293
+ },
294
+ "outputs": [
295
+ {
296
+ "data": {
297
+ "application/vnd.jupyter.widget-view+json": {
298
+ "model_id": "dbd72ecf0d36401ba26826f7d9a42540",
299
+ "version_major": 2,
300
+ "version_minor": 0
301
+ },
302
+ "text/plain": [
303
+ "Writing Documents: 0%| | 0/50024 [00:00<?, ?it/s]"
304
+ ]
305
+ },
306
+ "metadata": {},
307
+ "output_type": "display_data"
308
+ }
309
+ ],
310
+ "source": [
311
+ "# write documents\n",
312
+ "document_store.write_documents(preprocessed_docs)"
313
+ ]
314
+ },
315
+ {
316
+ "cell_type": "markdown",
317
+ "metadata": {},
318
+ "source": [
319
+ "## Initialize retriever (Embedding Retriever) and generate document embeddings\n",
320
+ "We choose a Sentence Tranformer model that is suitable for asymmetric semantic search (short query and longer passages), according to [documentation](https://www.sbert.net/examples/applications/semantic-search/README.html#symmetric-vs-asymmetric-semantic-search)."
321
+ ]
322
+ },
323
+ {
324
+ "cell_type": "code",
325
+ "execution_count": null,
326
+ "metadata": {
327
+ "execution": {
328
+ "iopub.execute_input": "2022-08-21T08:56:25.360959Z",
329
+ "iopub.status.busy": "2022-08-21T08:56:25.360546Z",
330
+ "iopub.status.idle": "2022-08-21T08:58:07.214654Z",
331
+ "shell.execute_reply": "2022-08-21T08:58:07.213653Z",
332
+ "shell.execute_reply.started": "2022-08-21T08:56:25.360926Z"
333
+ },
334
+ "trusted": true
335
+ },
336
+ "outputs": [],
337
+ "source": [
338
+ "from haystack.nodes import EmbeddingRetriever\n",
339
+ "\n",
340
+ "retriever = EmbeddingRetriever(\n",
341
+ " document_store=document_store,\n",
342
+ " embedding_model=\"sentence-transformers/msmarco-distilbert-base-tas-b\",\n",
343
+ " model_format=\"sentence_transformers\",\n",
344
+ " embed_meta_fields=[\"name\"],\n",
345
+ ")\n",
346
+ "\n",
347
+ "# generate embeddings\n",
348
+ "document_store.update_embeddings(retriever)"
349
+ ]
350
+ },
351
+ {
352
+ "cell_type": "markdown",
353
+ "metadata": {},
354
+ "source": [
355
+ "## Save and export index"
356
+ ]
357
+ },
358
+ {
359
+ "cell_type": "code",
360
+ "execution_count": null,
361
+ "metadata": {},
362
+ "outputs": [],
363
+ "source": [
364
+ "import shutil\n",
365
+ "import glob"
366
+ ]
367
+ },
368
+ {
369
+ "cell_type": "code",
370
+ "execution_count": 73,
371
+ "metadata": {
372
+ "execution": {
373
+ "iopub.execute_input": "2022-08-21T08:58:33.494417Z",
374
+ "iopub.status.busy": "2022-08-21T08:58:33.493822Z",
375
+ "iopub.status.idle": "2022-08-21T08:58:33.635915Z",
376
+ "shell.execute_reply": "2022-08-21T08:58:33.634599Z",
377
+ "shell.execute_reply.started": "2022-08-21T08:58:33.494382Z"
378
+ },
379
+ "trusted": true
380
+ },
381
+ "outputs": [],
382
+ "source": [
383
+ "OUT_DIR = \"YOUR-OUT-DIR\"\n",
384
+ "\n",
385
+ "document_store.save(\"my_faiss_index.faiss\")\n",
386
+ "for f in glob.glob(\"*faiss*.*\") + glob.glob(\"faiss*.*\"):\n",
387
+ " shutil.copy(f, OUT_DIR)"
388
+ ]
389
+ }
390
+ ],
391
+ "metadata": {
392
+ "kernelspec": {
393
+ "display_name": "Python 3.7.13 ('venv': venv)",
394
+ "language": "python",
395
+ "name": "python3"
396
+ },
397
+ "language_info": {
398
+ "codemirror_mode": {
399
+ "name": "ipython",
400
+ "version": 3
401
+ },
402
+ "file_extension": ".py",
403
+ "mimetype": "text/x-python",
404
+ "name": "python",
405
+ "nbconvert_exporter": "python",
406
+ "pygments_lexer": "ipython3",
407
+ "version": "3.7.13"
408
+ },
409
+ "vscode": {
410
+ "interpreter": {
411
+ "hash": "c114177cb475e38b99e396ae1ef7cfcaaa7967120589f47745b82f90d7e35d1b"
412
+ }
413
+ }
414
+ },
415
+ "nbformat": 4,
416
+ "nbformat_minor": 4
417
+ }
pages/Info.py CHANGED
@@ -1,3 +1 @@
1
  import streamlit as st
2
-
3
-
 
1
  import streamlit as st