Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import streamlit as st
|
| 3 |
+
import pickle
|
| 4 |
+
import time
|
| 5 |
+
import langchain
|
| 6 |
+
#from langchain import OpenAI
|
| 7 |
+
#from langchain.chains import RetrievalQAWithSourcesChain
|
| 8 |
+
#from langchain.chains.qa_with_sources.loading import load_qa_with_sources_chain
|
| 9 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 10 |
+
from langchain.document_loaders import UnstructuredURLLoader
|
| 11 |
+
#from langchain.embeddings import OpenAIEmbeddings
|
| 12 |
+
from langchain.vectorstores import FAISS
|
| 13 |
+
import requests
|
| 14 |
+
import pandas as pd
|
| 15 |
+
from langchain_community.llms import HuggingFaceEndpoint
|
| 16 |
+
from sentence_transformers import SentenceTransformer
|
| 17 |
+
from langchain.document_loaders import TextLoader
|
| 18 |
+
from sentence_transformers import SentenceTransformer, util
|
| 19 |
+
from langchain.schema import SystemMessage, HumanMessage, AIMessage
|
| 20 |
+
import faiss
|
| 21 |
+
from dotenv import load_dotenv
|
| 22 |
+
load_dotenv() # take environment variables from .env (especially openai api key)
|
| 23 |
+
|
| 24 |
+
def querypreprocess(query: str ):
|
| 25 |
+
vec = model.encode(query) #again embeddings of query by sentencetransformer and able to search the index vector.
|
| 26 |
+
#svec = np.array(vec).reshape(1,-1) # as 2D needed
|
| 27 |
+
distances, I = index.search(vec, k=2)
|
| 28 |
+
row_indices = I.tolist()[0]
|
| 29 |
+
list1 = [docs[i].page_content for i in row_indices]
|
| 30 |
+
str1 = " "
|
| 31 |
+
str1 = str1.join(list1)
|
| 32 |
+
#str1 = '\n'.join([str(message) for message in list1])
|
| 33 |
+
#results = ' '.join(map(str, list1)) #list to string convert
|
| 34 |
+
return str1
|
| 35 |
+
|
| 36 |
+
def augmented_prompt(query: str):
|
| 37 |
+
messages = querypreprocess(query)
|
| 38 |
+
source_knowledge =''.join([str(message) for message in messages])
|
| 39 |
+
#source_knowledge =results
|
| 40 |
+
augmented_prompt = f"""
|
| 41 |
+
using the contexts below, answer the query.
|
| 42 |
+
|
| 43 |
+
Contexts:
|
| 44 |
+
{source_knowledge}
|
| 45 |
+
Question: {query}
|
| 46 |
+
Answer:"""
|
| 47 |
+
return augmented_prompt
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
st.title("RockyBot: News Research Tool π")
|
| 51 |
+
st.sidebar.title("News Article URLs")
|
| 52 |
+
|
| 53 |
+
urls = []
|
| 54 |
+
for i in range(3):
|
| 55 |
+
url = st.sidebar.text_input(f"URL {i+1}")
|
| 56 |
+
urls.append(url)
|
| 57 |
+
|
| 58 |
+
process_url_clicked = st.sidebar.button("Process URLs")
|
| 59 |
+
file_path = "vector_index.pkl"
|
| 60 |
+
|
| 61 |
+
main_placeholder = st.empty()
|
| 62 |
+
#llm = OpenAI(temperature=0.9, max_tokens=500)
|
| 63 |
+
llm = HuggingFaceEndpoint(repo_id="mistralai/Mistral-7B-Instruct-v0.2")
|
| 64 |
+
|
| 65 |
+
if process_url_clicked:
|
| 66 |
+
# load data
|
| 67 |
+
loader = UnstructuredURLLoader(urls=urls)
|
| 68 |
+
main_placeholder.text("Data Loading...Started...β
β
β
")
|
| 69 |
+
data = loader.load()
|
| 70 |
+
# split data
|
| 71 |
+
text_splitter = RecursiveCharacterTextSplitter(
|
| 72 |
+
separators=['\n\n', '\n', '.', ','],
|
| 73 |
+
chunk_size=1000,
|
| 74 |
+
chunk_overlap=0
|
| 75 |
+
)
|
| 76 |
+
main_placeholder.text("Text Splitter...Started...β
β
β
")
|
| 77 |
+
docs = text_splitter.split_documents(data)
|
| 78 |
+
# Create an array of text to embed
|
| 79 |
+
sentences = []
|
| 80 |
+
for i, row in enumerate(docs):
|
| 81 |
+
sentences.append(row.page_content)
|
| 82 |
+
# create embeddings and save it to FAISS index
|
| 83 |
+
#embeddings = OpenAIEmbeddings()
|
| 84 |
+
#vectorstore_openai = FAISS.from_documents(docs, embeddings)
|
| 85 |
+
# initialize sentence transformer model
|
| 86 |
+
model = SentenceTransformer('bert-base-nli-mean-tokens')
|
| 87 |
+
# create sentence embeddings
|
| 88 |
+
sentence_embeddings = model.encode(sentences)
|
| 89 |
+
main_placeholder.text("Embedding Vector Started Building...β
β
β
")
|
| 90 |
+
time.sleep(2)
|
| 91 |
+
|
| 92 |
+
# Save the FAISS index to a pickle file
|
| 93 |
+
with open(file_path, "wb") as f:
|
| 94 |
+
pickle.dump(vector_index, f)
|
| 95 |
+
|
| 96 |
+
query = main_placeholder.text_input("Question: ")
|
| 97 |
+
if query:
|
| 98 |
+
if os.path.exists(file_path):
|
| 99 |
+
with open(file_path, "rb") as f:
|
| 100 |
+
query = pickle.load(f)
|
| 101 |
+
import faiss
|
| 102 |
+
d = sentence_embeddings.shape[1]
|
| 103 |
+
index = faiss.IndexFlatL2(d) # build the index, d=size of vectors
|
| 104 |
+
# here we assume xb contains a n-by-d numpy matrix of type float32
|
| 105 |
+
index.add(sentence_embeddings) # add vectors to the index
|
| 106 |
+
#chain = RetrievalQAWithSourcesChain.from_llm(llm=llm, retriever=vectorstore.as_retriever())
|
| 107 |
+
#result = chain({"question": query}, return_only_outputs=True)
|
| 108 |
+
# result will be a dictionary of this format --> {"answer": "", "sources": [] }
|
| 109 |
+
#xq = model.encode([query])
|
| 110 |
+
#k=2
|
| 111 |
+
#D, I = index.search(xq, k=k)
|
| 112 |
+
#result1 = [f'{i}: {sentences[i]}' for i in I[0]]
|
| 113 |
+
messages = [
|
| 114 |
+
SystemMessage(content="You are a helpful assistant."),
|
| 115 |
+
HumanMessage(content=query),
|
| 116 |
+
AIMessage(content="I am Great, Thank You, How Can I Help You.")
|
| 117 |
+
]
|
| 118 |
+
prompt = augmented_prompt(query)
|
| 119 |
+
messages.append(prompt)
|
| 120 |
+
result = llm.invoke(messages)
|
| 121 |
+
st.header("Answer")
|
| 122 |
+
# Display sources, if available
|
| 123 |
+
sources = result.get("sources", "")
|
| 124 |
+
if sources:
|
| 125 |
+
st.subheader("Sources:")
|
| 126 |
+
sources_list = sources.split("\n") # Split the sources by newline
|
| 127 |
+
for source in sources_list:
|
| 128 |
+
st.write(source)
|