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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import os
|
| 3 |
+
import base64
|
| 4 |
+
import time
|
| 5 |
+
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
|
| 6 |
+
from transformers import pipeline
|
| 7 |
+
import torch
|
| 8 |
+
import textwrap
|
| 9 |
+
from langchain.document_loaders import PyPDFLoader, DirectoryLoader, PDFMinerLoader
|
| 10 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 11 |
+
from langchain.embeddings import SentenceTransformerEmbeddings
|
| 12 |
+
from langchain.vectorstores import Chroma
|
| 13 |
+
from langchain.llms import HuggingFacePipeline
|
| 14 |
+
from langchain.chains import RetrievalQA
|
| 15 |
+
from constants import CHROMA_SETTINGS
|
| 16 |
+
from streamlit_chat import message
|
| 17 |
+
|
| 18 |
+
st.set_page_config(layout="wide")
|
| 19 |
+
|
| 20 |
+
device = torch.device('cpu')
|
| 21 |
+
|
| 22 |
+
checkpoint = "MBZUAI/LaMini-T5-738M"
|
| 23 |
+
tokenizer = AutoTokenizer.from_pretrained(checkpoint)
|
| 24 |
+
base_model = AutoModelForSeq2SeqLM.from_pretrained(
|
| 25 |
+
checkpoint,
|
| 26 |
+
device_map=device,
|
| 27 |
+
torch_dtype=torch.float32
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
persist_directory = "db"
|
| 31 |
+
|
| 32 |
+
@st.cache_resource
|
| 33 |
+
def data_ingestion():
|
| 34 |
+
for root, dirs, files in os.walk("docs"):
|
| 35 |
+
for file in files:
|
| 36 |
+
if file.endswith(".pdf"):
|
| 37 |
+
print(file)
|
| 38 |
+
loader = PDFMinerLoader(os.path.join(root, file))
|
| 39 |
+
|
| 40 |
+
documents = loader.load()
|
| 41 |
+
text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=500)
|
| 42 |
+
splits = text_splitter.split_documents(document)
|
| 43 |
+
|
| 44 |
+
#create embeddings here
|
| 45 |
+
embeddings = SentenceTransformerEmbeddings(model_name="all-MiniLM-L6-v2")
|
| 46 |
+
vectordb = FAISS.from_documents(splits, embeddings)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
# #create vector store here
|
| 50 |
+
# db = Chroma.from_documents(texts, embeddings, persist_directory=persist_directory, client_settings=CHROMA_SETTINGS)
|
| 51 |
+
# db.persist()
|
| 52 |
+
# db=None
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
@st.cache_resource
|
| 56 |
+
def qa_llm():
|
| 57 |
+
pipe = pipeline(
|
| 58 |
+
'text2text-generation',
|
| 59 |
+
model = base_model,
|
| 60 |
+
tokenizer = tokenizer,
|
| 61 |
+
max_length = 256,
|
| 62 |
+
do_sample = True,
|
| 63 |
+
temperature = 0.3,
|
| 64 |
+
top_p= 0.95,
|
| 65 |
+
device=device
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
llm = HuggingFacePipeline(pipeline=pipe)
|
| 69 |
+
embeddings = SentenceTransformerEmbeddings(model_name="all-MiniLM-L6-v2")
|
| 70 |
+
|
| 71 |
+
db = Chroma(persist_directory="db", embedding_function = embeddings, client_settings=CHROMA_SETTINGS)
|
| 72 |
+
retriever = db.as_retriever()
|
| 73 |
+
qa = RetrievalQA.from_chain_type(
|
| 74 |
+
llm = llm,
|
| 75 |
+
chain_type = "stuff",
|
| 76 |
+
retriever = retriever,
|
| 77 |
+
return_source_documents=True
|
| 78 |
+
)
|
| 79 |
+
return qa
|
| 80 |
+
|
| 81 |
+
def process_answer(instruction):
|
| 82 |
+
response = ''
|
| 83 |
+
instruction = instruction
|
| 84 |
+
qa = qa_llm()
|
| 85 |
+
generated_text = qa(instruction)
|
| 86 |
+
answer = generated_text['result']
|
| 87 |
+
return answer
|
| 88 |
+
|
| 89 |
+
def get_file_size(file):
|
| 90 |
+
file.seek(0, os.SEEK_END)
|
| 91 |
+
file_size = file.tell()
|
| 92 |
+
file.seek(0)
|
| 93 |
+
return file_size
|
| 94 |
+
|
| 95 |
+
@st.cache_data
|
| 96 |
+
#function to display the PDF of a given file
|
| 97 |
+
def displayPDF(file):
|
| 98 |
+
# Opening file from file path
|
| 99 |
+
with open(file, "rb") as f:
|
| 100 |
+
base64_pdf = base64.b64encode(f.read()).decode('utf-8')
|
| 101 |
+
|
| 102 |
+
# Embedding PDF in HTML
|
| 103 |
+
pdf_display = F'<iframe src="data:application/pdf;base64,{base64_pdf}" width="100%" height="600" type="application/pdf"></iframe>'
|
| 104 |
+
|
| 105 |
+
# Displaying File
|
| 106 |
+
st.markdown(pdf_display, unsafe_allow_html=True)
|
| 107 |
+
|
| 108 |
+
# Display conversation history using Streamlit messages
|
| 109 |
+
def display_conversation(history):
|
| 110 |
+
for i in range(len(history["generated"])):
|
| 111 |
+
message(history["past"][i], is_user=True, key=str(i) + "_user")
|
| 112 |
+
message(history["generated"][i],key=str(i))
|
| 113 |
+
|
| 114 |
+
def main():
|
| 115 |
+
st.markdown("<h1 style='text-align: center; color: blue;'>Chat with your PDF 🦜📄 </h1>", unsafe_allow_html=True)
|
| 116 |
+
st.markdown("<h3 style='text-align: center; color: grey;'>Built by <a href='https://github.com/AIAnytime'>AI Anytime with ❤️ </a></h3>", unsafe_allow_html=True)
|
| 117 |
+
|
| 118 |
+
st.markdown("<h2 style='text-align: center; color:red;'>Upload your PDF 👇</h2>", unsafe_allow_html=True)
|
| 119 |
+
|
| 120 |
+
uploaded_file = st.file_uploader("", type=["pdf"])
|
| 121 |
+
|
| 122 |
+
if uploaded_file is not None:
|
| 123 |
+
file_details = {
|
| 124 |
+
"Filename": uploaded_file.name,
|
| 125 |
+
"File size": get_file_size(uploaded_file)
|
| 126 |
+
}
|
| 127 |
+
filepath = "docs/"+uploaded_file.name
|
| 128 |
+
with open(filepath, "wb") as temp_file:
|
| 129 |
+
temp_file.write(uploaded_file.read())
|
| 130 |
+
|
| 131 |
+
col1, col2= st.columns([1,2])
|
| 132 |
+
with col1:
|
| 133 |
+
st.markdown("<h4 style color:black;'>File details</h4>", unsafe_allow_html=True)
|
| 134 |
+
st.json(file_details)
|
| 135 |
+
st.markdown("<h4 style color:black;'>File preview</h4>", unsafe_allow_html=True)
|
| 136 |
+
pdf_view = displayPDF(filepath)
|
| 137 |
+
|
| 138 |
+
with col2:
|
| 139 |
+
with st.spinner('Embeddings are in process...'):
|
| 140 |
+
ingested_data = data_ingestion()
|
| 141 |
+
st.success('Embeddings are created successfully!')
|
| 142 |
+
st.markdown("<h4 style color:black;'>Chat Here</h4>", unsafe_allow_html=True)
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
user_input = st.text_input("", key="input")
|
| 146 |
+
|
| 147 |
+
# Initialize session state for generated responses and past messages
|
| 148 |
+
if "generated" not in st.session_state:
|
| 149 |
+
st.session_state["generated"] = ["I am ready to help you"]
|
| 150 |
+
if "past" not in st.session_state:
|
| 151 |
+
st.session_state["past"] = ["Hey there!"]
|
| 152 |
+
|
| 153 |
+
# Search the database for a response based on user input and update session state
|
| 154 |
+
if user_input:
|
| 155 |
+
answer = process_answer({'query': user_input})
|
| 156 |
+
st.session_state["past"].append(user_input)
|
| 157 |
+
response = answer
|
| 158 |
+
st.session_state["generated"].append(response)
|
| 159 |
+
|
| 160 |
+
# Display conversation history using Streamlit messages
|
| 161 |
+
if st.session_state["generated"]:
|
| 162 |
+
display_conversation(st.session_state)
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
if __name__ == "__main__":
|
| 171 |
+
main()
|
| 172 |
+
|