|
import os
|
|
import streamlit as st
|
|
import pickle
|
|
import faiss
|
|
import time
|
|
from langchain import OpenAI
|
|
from langchain.chains import RetrievalQAWithSourcesChain
|
|
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
|
from langchain.document_loaders import UnstructuredURLLoader
|
|
from langchain.embeddings import OpenAIEmbeddings
|
|
from langchain.vectorstores import FAISS
|
|
from langchain_community.docstore.in_memory import InMemoryDocstore
|
|
from langchain.schema import Document
|
|
from dotenv import load_dotenv
|
|
|
|
load_dotenv()
|
|
|
|
|
|
st.title("Article/News Research Tool")
|
|
st.sidebar.title("Article URLs...")
|
|
|
|
|
|
if "qa_history" not in st.session_state:
|
|
st.session_state.qa_history = []
|
|
|
|
|
|
num_urls = st.sidebar.number_input("How many URLs do you want to process?", min_value=1, max_value=10, value=3)
|
|
|
|
urls = []
|
|
for i in range(num_urls):
|
|
url = st.sidebar.text_input(f"URL {i+1}")
|
|
urls.append(url)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
process_url_clicked = st.sidebar.button("Process Article URLs")
|
|
|
|
|
|
main_placeholder = st.empty()
|
|
llm = OpenAI(temperature=0.5, max_tokens=500)
|
|
|
|
index_path = "faiss_index.bin"
|
|
docs_path = "docs.pkl"
|
|
index_to_docstore_id_path = "index_to_docstore_id.pkl"
|
|
|
|
if process_url_clicked:
|
|
|
|
loader = UnstructuredURLLoader(urls=urls)
|
|
main_placeholder.text("Data Loading...Initiated...")
|
|
data = loader.load()
|
|
|
|
|
|
text_splitter = RecursiveCharacterTextSplitter(
|
|
|
|
chunk_size=1000,
|
|
|
|
)
|
|
|
|
main_placeholder.text("Text Splitter...Initiated...")
|
|
docs = text_splitter.split_documents(data)
|
|
|
|
|
|
embeddings = OpenAIEmbeddings()
|
|
embedding_dimension = 1536
|
|
docstore_dict = {str(i): doc for i, doc in enumerate(docs)}
|
|
docstore = InMemoryDocstore(docstore_dict)
|
|
|
|
|
|
index = faiss.IndexFlatL2(embedding_dimension)
|
|
|
|
|
|
index_to_docstore_id = {i: str(i) for i in range(len(docs))}
|
|
vector_store = FAISS(embedding_function=embeddings, index=index, docstore=docstore, index_to_docstore_id=index_to_docstore_id)
|
|
|
|
|
|
vector_store.add_documents(docs)
|
|
main_placeholder.text("Embedding Vector Building Initiated...")
|
|
|
|
|
|
|
|
faiss.write_index(vector_store.index, index_path)
|
|
|
|
with open(docs_path, "wb") as f:
|
|
pickle.dump(docs, f)
|
|
|
|
|
|
|
|
with open(index_to_docstore_id_path, "wb") as f:
|
|
pickle.dump(vector_store.index_to_docstore_id, f)
|
|
|
|
|
|
query = main_placeholder.text_input("Question: ")
|
|
if query:
|
|
|
|
if os.path.exists(index_path) and os.path.exists(docs_path) and os.path.exists(index_to_docstore_id_path):
|
|
index = faiss.read_index(index_path)
|
|
with open(docs_path, "rb") as f:
|
|
docs = pickle.load(f)
|
|
with open(index_to_docstore_id_path, "rb") as f:
|
|
index_to_docstore_id = pickle.load(f)
|
|
docstore = InMemoryDocstore({str(i): doc for i, doc in enumerate(docs)})
|
|
|
|
embeddings = OpenAIEmbeddings()
|
|
vector_store = FAISS(embedding_function=embeddings, index=index, docstore=docstore,
|
|
index_to_docstore_id=index_to_docstore_id)
|
|
|
|
chain = RetrievalQAWithSourcesChain.from_llm(llm=llm, retriever=vector_store.as_retriever())
|
|
result = chain.invoke({"question": query}, return_only_outputs=True)
|
|
|
|
|
|
answer = result.get("answer", "No answer found.")
|
|
sources = result.get("sources", "No sources available.")
|
|
|
|
|
|
st.session_state.qa_history.append({"question": query, "answer": answer, "sources": sources})
|
|
|
|
|
|
st.subheader("Response:")
|
|
st.write(result["answer"])
|
|
|
|
|
|
sources = result.get("sources", "")
|
|
if sources:
|
|
st.subheader("Sources:")
|
|
sources_list = sources.split("\n")
|
|
for source in sources_list:
|
|
st.write(source)
|
|
|
|
|
|
if st.session_state.qa_history:
|
|
st.write("---------------------------------------------------------------------")
|
|
st.subheader("History:")
|
|
for entry in st.session_state.qa_history:
|
|
st.write(f"**Q:** {entry['question']}")
|
|
st.write(f"**A:** {entry['answer']}")
|
|
st.write(f"**Sources:** {entry['sources']}")
|
|
|
|
|
|
|
|
|
|
|
|
|