Spaces:
Running
Running
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,162 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import base64
|
2 |
+
import os
|
3 |
+
|
4 |
+
import streamlit as st
|
5 |
+
from langchain.chains import RetrievalQA
|
6 |
+
from langchain.document_loaders import PDFMinerLoader
|
7 |
+
from langchain.embeddings import SentenceTransformerEmbeddings
|
8 |
+
from langchain.llms import HuggingFacePipeline
|
9 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
10 |
+
from langchain.vectorstores import FAISS
|
11 |
+
from streamlit_chat import message
|
12 |
+
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer, pipeline
|
13 |
+
import torch
|
14 |
+
|
15 |
+
st.set_page_config(layout="wide")
|
16 |
+
|
17 |
+
def process_answer(instruction, qa_chain):
|
18 |
+
response = ''
|
19 |
+
generated_text = qa_chain.run(instruction)
|
20 |
+
return generated_text
|
21 |
+
|
22 |
+
|
23 |
+
def get_file_size(file):
|
24 |
+
file.seek(0, os.SEEK_END)
|
25 |
+
file_size = file.tell()
|
26 |
+
file.seek(0)
|
27 |
+
return file_size
|
28 |
+
|
29 |
+
|
30 |
+
@st.cache_resource
|
31 |
+
def data_ingestion():
|
32 |
+
for root, dirs, files in os.walk("docs"):
|
33 |
+
for file in files:
|
34 |
+
if file.endswith(".pdf"):
|
35 |
+
print(file)
|
36 |
+
loader = PDFMinerLoader(os.path.join(root, file))
|
37 |
+
|
38 |
+
documents = loader.load()
|
39 |
+
text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=500)
|
40 |
+
splits = text_splitter.split_documents(documents)
|
41 |
+
|
42 |
+
# create embeddings here
|
43 |
+
embeddings = SentenceTransformerEmbeddings(model_name="all-MiniLM-L6-v2")
|
44 |
+
vectordb = FAISS.from_documents(splits, embeddings)
|
45 |
+
vectordb.save_local("faiss_index")
|
46 |
+
|
47 |
+
|
48 |
+
@st.cache_resource
|
49 |
+
def initialize_qa_chain(selected_model):
|
50 |
+
# Constants
|
51 |
+
CHECKPOINT = selected_model
|
52 |
+
TOKENIZER = AutoTokenizer.from_pretrained(CHECKPOINT)
|
53 |
+
BASE_MODEL = AutoModelForSeq2SeqLM.from_pretrained(CHECKPOINT, device_map=torch.device('cpu'), torch_dtype=torch.float32)
|
54 |
+
pipe = pipeline(
|
55 |
+
'text2text-generation',
|
56 |
+
model=BASE_MODEL,
|
57 |
+
tokenizer=TOKENIZER,
|
58 |
+
max_length=256,
|
59 |
+
do_sample=True,
|
60 |
+
temperature=0.3,
|
61 |
+
top_p=0.95,
|
62 |
+
# device=torch.device('cpu')
|
63 |
+
)
|
64 |
+
|
65 |
+
llm = HuggingFacePipeline(pipeline=pipe)
|
66 |
+
embeddings = SentenceTransformerEmbeddings(model_name="all-MiniLM-L6-v2")
|
67 |
+
|
68 |
+
vectordb = FAISS.load_local("faiss_index", embeddings)
|
69 |
+
|
70 |
+
# Build a QA chain
|
71 |
+
qa_chain = RetrievalQA.from_chain_type(
|
72 |
+
llm=llm,
|
73 |
+
chain_type="stuff",
|
74 |
+
retriever=vectordb.as_retriever(),
|
75 |
+
)
|
76 |
+
return qa_chain
|
77 |
+
|
78 |
+
|
79 |
+
@st.cache_data
|
80 |
+
# function to display the PDF of a given file
|
81 |
+
def display_pdf(file):
|
82 |
+
try:
|
83 |
+
# Opening file from file path
|
84 |
+
with open(file, "rb") as f:
|
85 |
+
base64_pdf = base64.b64encode(f.read()).decode('utf-8')
|
86 |
+
|
87 |
+
# Embedding PDF in HTML
|
88 |
+
pdf_display = f'<iframe src="data:application/pdf;base64,{base64_pdf}" width="100%" height="600" type="application/pdf"></iframe>'
|
89 |
+
|
90 |
+
# Displaying File
|
91 |
+
st.markdown(pdf_display, unsafe_allow_html=True)
|
92 |
+
except Exception as e:
|
93 |
+
st.error(f"An error occurred while displaying the PDF: {e}")
|
94 |
+
|
95 |
+
|
96 |
+
# Display conversation history using Streamlit messages
|
97 |
+
def display_conversation(history):
|
98 |
+
for i in range(len(history["generated"])):
|
99 |
+
message(history["past"][i], is_user=True, key=f"{i}_user")
|
100 |
+
message(history["generated"][i], key=str(i))
|
101 |
+
|
102 |
+
|
103 |
+
def main():
|
104 |
+
# Add a sidebar for model selection
|
105 |
+
model_options = ["MBZUAI/LaMini-T5-738M", "google/flan-t5-base", "google/flan-t5-small"]
|
106 |
+
selected_model = st.sidebar.selectbox("Select Model", model_options)
|
107 |
+
|
108 |
+
st.markdown("<h1 style='text-align: center; color: blue;'>Custom PDF Chatbot π¦π </h1>", unsafe_allow_html=True)
|
109 |
+
st.markdown("<h2 style='text-align: center; color:red;'>Upload your PDF, and Ask Questions π</h2>", unsafe_allow_html=True)
|
110 |
+
|
111 |
+
uploaded_file = st.file_uploader("", type=["pdf"])
|
112 |
+
|
113 |
+
if uploaded_file is not None:
|
114 |
+
file_details = {
|
115 |
+
"Filename": uploaded_file.name,
|
116 |
+
"File size": get_file_size(uploaded_file)
|
117 |
+
}
|
118 |
+
os.makedirs("docs", exist_ok=True)
|
119 |
+
filepath = os.path.join("docs", uploaded_file.name)
|
120 |
+
try:
|
121 |
+
with open(filepath, "wb") as temp_file:
|
122 |
+
temp_file.write(uploaded_file.read())
|
123 |
+
|
124 |
+
col1, col2 = st.columns([1, 2])
|
125 |
+
with col1:
|
126 |
+
st.markdown("<h4 style color:black;'>File details</h4>", unsafe_allow_html=True)
|
127 |
+
st.json(file_details)
|
128 |
+
st.markdown("<h4 style color:black;'>File preview</h4>", unsafe_allow_html=True)
|
129 |
+
pdf_view = display_pdf(filepath)
|
130 |
+
|
131 |
+
with col2:
|
132 |
+
st.success(f'model selected successfully: {selected_model}')
|
133 |
+
with st.spinner('Embeddings are in process...'):
|
134 |
+
ingested_data = data_ingestion()
|
135 |
+
st.success('Embeddings are created successfully!')
|
136 |
+
st.markdown("<h4 style color:black;'>Chat Here</h4>", unsafe_allow_html=True)
|
137 |
+
|
138 |
+
user_input = st.text_input("", key="input")
|
139 |
+
|
140 |
+
# Initialize session state for generated responses and past messages
|
141 |
+
if "generated" not in st.session_state:
|
142 |
+
st.session_state["generated"] = ["I am ready to help you"]
|
143 |
+
if "past" not in st.session_state:
|
144 |
+
st.session_state["past"] = ["Hey there!"]
|
145 |
+
|
146 |
+
# Search the database for a response based on user input and update session state
|
147 |
+
if user_input:
|
148 |
+
answer = process_answer({'query': user_input}, initialize_qa_chain(selected_model))
|
149 |
+
st.session_state["past"].append(user_input)
|
150 |
+
response = answer
|
151 |
+
st.session_state["generated"].append(response)
|
152 |
+
|
153 |
+
# Display conversation history using Streamlit messages
|
154 |
+
if st.session_state["generated"]:
|
155 |
+
display_conversation(st.session_state)
|
156 |
+
|
157 |
+
except Exception as e:
|
158 |
+
st.error(f"An error occurred: {e}")
|
159 |
+
|
160 |
+
|
161 |
+
if __name__ == "__main__":
|
162 |
+
main()
|