import os
import time
import streamlit as st
import subprocess
import sys
import logging
import pandas as pd
from json import JSONDecodeError
from pathlib import Path
from markdown import markdown
import random
from typing import List, Dict, Any, Tuple
from haystack.document_stores import ElasticsearchDocumentStore, FAISSDocumentStore
from haystack.nodes import EmbeddingRetriever
from haystack.pipelines import ExtractiveQAPipeline
from haystack.preprocessor.preprocessor import PreProcessor
from haystack.nodes import FARMReader, TransformersReader
from haystack.pipelines import ExtractiveQAPipeline
from annotated_text import annotation
import shutil
# FAISS index directory
INDEX_DIR = 'data/index'
# the following function is cached to make index and models load only at start
@st.cache(hash_funcs={"builtins.SwigPyObject": lambda _: None}, allow_output_mutation=True)
def start_haystack():
"""
load document store, retriever, reader and create pipeline
"""
shutil.copy(f'{INDEX_DIR}/faiss_document_store.db','.')
document_store = FAISSDocumentStore(
faiss_index_path=f'{INDEX_DIR}/my_faiss_index.faiss',
faiss_config_path=f'{INDEX_DIR}/my_faiss_index.json')
print (f'Index size: {document_store.get_document_count()}')
retriever = EmbeddingRetriever(
document_store=document_store,
embedding_model="sentence-transformers/multi-qa-mpnet-base-dot-v1",
model_format="sentence_transformers"
)
reader = FARMReader(model_name_or_path="deepset/roberta-base-squad2", use_gpu=True)
pipe = ExtractiveQAPipeline(reader, retriever)
return pipe
def set_state_if_absent(key, value):
if key not in st.session_state:
st.session_state[key] = value
def get_backlink(result, ip) -> str:
"""
Build URL from metadata and Google VM IP
(quick and dirty)
"""
meta = result['meta']
fpath = meta['filepath'].rpartition('/')[-1]
fname = fpath.rpartition('.')[0]
return f'http://{ip}:8000/data/final/ner_html/{fname}.html'
def query(pipe, question):
"""Run query and get answers"""
return (pipe.run(question, params={"Retriever": {"top_k": 10}, "Reader": {"top_k": 5}}), None)
def main():
# st.set_page_config(page_title='Who killed Laura Palmer?',
# page_icon="https://static.wikia.nocookie.net/twinpeaks/images/4/4a/Site-favicon.ico/revision/latest?cb=20210710003705")
pipe=start_haystack()
# my_ip=subprocess.run(['curl', 'ifconfig.me'], stdout=subprocess.PIPE).stdout.decode('utf-8')
# Persistent state
set_state_if_absent('question', "Where is Twin Peaks?")
set_state_if_absent('answer', '')
set_state_if_absent('results', None)
set_state_if_absent('raw_json', None)
set_state_if_absent('random_question_requested', False)
# Small callback to reset the interface in case the text of the question changes
def reset_results(*args):
st.session_state.answer = None
st.session_state.results = None
st.session_state.raw_json = None
# Title
st.write("# Who killed Laura Palmer?")
st.write("### The first Twin Peaks Question Answering system!")
st.markdown("""
Ask any question on Twin Peaks and see if the systsem can find the correct answer to your query!
*Note: do not use keywords, but full-fledged questions.*
""", unsafe_allow_html=True)
# Sidebar
st.sidebar.header("Who killed Laura Palmer?")
st.sidebar.image("https://upload.wikimedia.org/wikipedia/it/3/39/Twin-peaks-1990.jpg")
st.sidebar.markdown("#### Twin Peaks Question Answering system")
st.sidebar.markdown(f"""