Commit Β·
412a390
1
Parent(s): 7d397b0
added authentication
Browse filesFiles changed (4)
- app.py+138-123
- generate_keys.pyAdded+15
- hashed_password.pklAdded
- requirements.txt+1
12345610 unmodified lines171819202122232425262773 unmodified lines101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242from utils.check_pydantic_version import use_pydantic_v1use_pydantic_v1() #This function has to be run before importing haystack. as haystack requires pydantic v1 to runfrom operator import indeximport streamlit as stimport logging10 unmodified linesfrom datetime import datetimefrom haystack.nodes import TextConverter, PDFToTextConverter, DocxToTextConverter, PreProcessorpdf_converter = PDFToTextConverter(remove_numeric_tables=True, valid_languages=["en","de"])docx_converter = DocxToTextConverter(remove_numeric_tables=False, valid_languages=["en","de"])txt_converter = TextConverter(remove_numeric_tables=True, valid_languages=["en","de"])# Whether the file upload should be enabled or not73 unmodified lines)st.sidebar.image("ml_logo.png", use_column_width=True)# Sidebar for Task Selectionst.sidebar.header('Options:')# OpenAI Key Inputopenai_key = st.sidebar.text_input("Enter OpenAI Key:", type="password")if openai_key:task_options = ['Extractive', 'Generative']else:task_options = ['Extractive']task_selection = st.sidebar.radio('Select the task:', task_options)# Check the task and initialize pipeline accordinglyif task_selection == 'Extractive':pipeline_extractive = initialize_pipeline("extractive", document_store, retriever, reader)elif task_selection == 'Generative' and openai_key: # Check for openai_key to ensure user has entered itpipeline_rag = initialize_pipeline("rag", document_store, retriever, reader, openai_key=openai_key)set_initial_state()st.write('# ' + args.name)# File upload blockif not DISABLE_FILE_UPLOAD:upload_container = st.sidebar.container()upload_container.write("## File Upload:")data_files = upload_files()# Button to update files in the documentStoreupload_container.button('Upload Files', on_click=upload_document, args=())# Button to reset the documents in DocumentStorest.sidebar.button("Reset documents", on_click=reset_documents, args=())if "question" not in st.session_state:st.session_state.question = ""# Search barquestion = st.text_input("Question", value=st.session_state.question, max_chars=100, on_change=reset_results, label_visibility="hidden")run_pressed = st.button("Run")run_query = (run_pressed or question != st.session_state.question #or task_selection != st.session_state.task)# Get results for queryif run_query and question:if task_selection == 'Extractive':reset_results()st.session_state.question = questionwith st.spinner("π Running your pipeline"):try:st.session_state.results_extractive = query(pipeline_extractive, question)st.session_state.task = task_selectionexcept JSONDecodeError as je:st.error("π An error occurred reading the results. Is the document store working?")except Exception as e:logging.exception(e)st.error("π An error occurred during the request.")elif task_selection == 'Generative':reset_results()st.session_state.question = questionwith st.spinner("π Running your pipeline"):try:st.session_state.results_generative = query(pipeline_rag, question)st.session_state.task = task_selectionexcept JSONDecodeError as je:st.error("π An error occurred reading the results. Is the document store working?")except Exception as e:if "API key is invalid" in str(e):logging.exception(e)st.error("π incorrect API key provided. You can find your API key at https://platform.openai.com/account/api-keys.")else:logging.exception(e)st.error("π An error occurred during the request.")# Display resultsif (st.session_state.results_extractive or st.session_state.results_generative) and run_query:# Handle Extractive Answersif task_selection == 'Extractive':results = st.session_state.results_extractivest.subheader("Extracted Answers:")if 'answers' in results:answers = results['answers']treshold = 0.2higher_then_treshold = any(ans.score > treshold for ans in answers)if not higher_then_treshold:st.markdown(f"<span style='color:red'>Please note none of the answers achieved a score higher then {int(treshold) * 100}%. Which probably means that the desired answer is not in the searched documents.</span>", unsafe_allow_html=True)for count, answer in enumerate(answers):if answer.answer:text, context = answer.answer, answer.contextstart_idx = context.find(text)end_idx = start_idx + len(text)score = round(answer.score, 3)st.markdown(f"**Answer {count + 1}:**")st.markdown(context[:start_idx] + str(annotation(body=text, label=f'SCORE {score}', background='#964448', color='#ffffff')) + context[end_idx:],unsafe_allow_html=True,)else:st.info("π€ Haystack is unsure whether any of the documents contain an answer to your question. Try to reformulate it!")# Handle Generative Answerselif task_selection == 'Generative':results = st.session_state.results_generativest.subheader("Generated Answer:")if 'results' in results:st.markdown("**Answer:**")st.write(results['results'][0])# Handle Retrieved Documentsif 'documents' in results:retrieved_documents = results['documents']st.subheader("Retriever Results:")data = []for i, document in enumerate(retrieved_documents):# Truncate the contenttruncated_content = (document.content[:150] + '...') if len(document.content) > 150 else document.contentdata.append([i + 1, document.meta['name'], truncated_content])# Convert data to DataFrame and display using Streamlitdf = pd.DataFrame(data, columns=['Ranked Context', 'Document Name', 'Content'])st.table(df)except SystemExit as e:os._exit(e.code)123456710 unmodified lines18192021222324252627282930313273 unmodified lines106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257from utils.check_pydantic_version import use_pydantic_v1use_pydantic_v1() #This function has to be run before importing haystack. as haystack requires pydantic v1 to runfrom operator import indeximport streamlit as stimport logging10 unmodified linesfrom datetime import datetimeimport streamlit_authenticator as stauthimport picklenames = ['admin']usernames = ['admin']with open('hashed_password.pkl','rb') as f:hashed_passwords = pickle.load(f)# Whether the file upload should be enabled or not73 unmodified lines)st.sidebar.image("ml_logo.png", use_column_width=True)authenticator = stauth.Authenticate(names, usernames, hashed_passwords, "document_search", "random_text", cookie_expiry_days=2)name, authentication_status, username = authenticator.login("Login", "main")if authentication_status == False:st.error("Username/Password is incorrect")if authentication_status == None:st.warning("Please enter youe username and password")if authentication_status:# Sidebar for Task Selectionst.sidebar.header('Options:')# OpenAI Key Inputopenai_key = st.sidebar.text_input("Enter OpenAI Key:", type="password")if openai_key:task_options = ['Extractive', 'Generative']else:task_options = ['Extractive']task_selection = st.sidebar.radio('Select the task:', task_options)# Check the task and initialize pipeline accordinglyif task_selection == 'Extractive':pipeline_extractive = initialize_pipeline("extractive", document_store, retriever, reader)elif task_selection == 'Generative' and openai_key: # Check for openai_key to ensure user has entered itpipeline_rag = initialize_pipeline("rag", document_store, retriever, reader, openai_key=openai_key)set_initial_state()st.write('# ' + args.name)# File upload blockif not DISABLE_FILE_UPLOAD:upload_container = st.sidebar.container()upload_container.write("## File Upload:")data_files = upload_files()# Button to update files in the documentStoreupload_container.button('Upload Files', on_click=upload_document, args=())# Button to reset the documents in DocumentStorest.sidebar.button("Reset documents", on_click=reset_documents, args=())if "question" not in st.session_state:st.session_state.question = ""# Search barquestion = st.text_input("Question", value=st.session_state.question, max_chars=100, on_change=reset_results, label_visibility="hidden")run_pressed = st.button("Run")run_query = (run_pressed or question != st.session_state.question #or task_selection != st.session_state.task)# Get results for queryif run_query and question:if task_selection == 'Extractive':reset_results()st.session_state.question = questionwith st.spinner("π Running your pipeline"):try:st.session_state.results_extractive = query(pipeline_extractive, question)st.session_state.task = task_selectionexcept JSONDecodeError as je:st.error("π An error occurred reading the results. Is the document store working?")except Exception as e:logging.exception(e)st.error("π An error occurred during the request.")elif task_selection == 'Generative':reset_results()st.session_state.question = questionwith st.spinner("π Running your pipeline"):try:st.session_state.results_generative = query(pipeline_rag, question)st.session_state.task = task_selectionexcept JSONDecodeError as je:st.error("π An error occurred reading the results. Is the document store working?")except Exception as e:if "API key is invalid" in str(e):logging.exception(e)st.error("π incorrect API key provided. You can find your API key at https://platform.openai.com/account/api-keys.")else:logging.exception(e)st.error("π An error occurred during the request.")# Display resultsif (st.session_state.results_extractive or st.session_state.results_generative) and run_query:# Handle Extractive Answersif task_selection == 'Extractive':results = st.session_state.results_extractivest.subheader("Extracted Answers:")if 'answers' in results:answers = results['answers']treshold = 0.2higher_then_treshold = any(ans.score > treshold for ans in answers)if not higher_then_treshold:st.markdown(f"<span style='color:red'>Please note none of the answers achieved a score higher then {int(treshold) * 100}%. Which probably means that the desired answer is not in the searched documents.</span>", unsafe_allow_html=True)for count, answer in enumerate(answers):if answer.answer:text, context = answer.answer, answer.contextstart_idx = context.find(text)end_idx = start_idx + len(text)score = round(answer.score, 3)st.markdown(f"**Answer {count + 1}:**")st.markdown(context[:start_idx] + str(annotation(body=text, label=f'SCORE {score}', background='#964448', color='#ffffff')) + context[end_idx:],unsafe_allow_html=True,)else:st.info("π€ Haystack is unsure whether any of the documents contain an answer to your question. Try to reformulate it!")# Handle Generative Answerselif task_selection == 'Generative':results = st.session_state.results_generativest.subheader("Generated Answer:")if 'results' in results:st.markdown("**Answer:**")st.write(results['results'][0])# Handle Retrieved Documentsif 'documents' in results:retrieved_documents = results['documents']st.subheader("Retriever Results:")data = []for i, document in enumerate(retrieved_documents):# Truncate the contenttruncated_content = (document.content[:150] + '...') if len(document.content) > 150 else document.contentdata.append([i + 1, document.meta['name'], truncated_content])# Convert data to DataFrame and display using Streamlitdf = pd.DataFrame(data, columns=['Ranked Context', 'Document Name', 'Content'])st.table(df)except SystemExit as e:os._exit(e.code)
123456789101112131415# -*- coding: utf-8 -*-
import picklefrom pathlib import Path
import streamlit_authenticator as stauth
names = ['admin']usernames = ['admin']passwords = ['admin1']
hashed_passwords = stauth.Hasher((passwords)).generate()
with open('hashed_password.pkl','wb') as f: pickle.dump(hashed_passwords, f)1 unmodified line2345671 unmodified linefarm-haystack[inference,weaviate,opensearch,file-conversion,pdf]==1.20.0milvus-haystackstreamlit==1.23.0markdownst-annotated-textdatasets1 unmodified line23456781 unmodified linefarm-haystack[inference,weaviate,opensearch,file-conversion,pdf]==1.20.0milvus-haystackstreamlit==1.23.0streamlit-authenticator==0.1.5markdownst-annotated-textdatasets
app.py+138-123
generate_keys.pyAdded+15
hashed_password.pklAdded
requirements.txt+1