Deepak7376 commited on
Commit
2d4455b
·
verified ·
1 Parent(s): 2b7b656

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +95 -117
app.py CHANGED
@@ -1,24 +1,47 @@
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)
@@ -26,29 +49,27 @@ def get_file_size(file):
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(
@@ -59,13 +80,9 @@ def initialize_qa_chain(selected_model):
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(
@@ -75,88 +92,49 @@ def initialize_qa_chain(selected_model):
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
- # edited
161
- if __name__ == "__main__":
162
- main()
 
 
 
 
1
  import streamlit as st
2
+ import os
3
+ from langchain_community.document_loaders import PDFMinerLoader
4
+ from langchain_community.embeddings import SentenceTransformerEmbeddings
 
5
  from langchain.text_splitter import RecursiveCharacterTextSplitter
6
+ from langchain_community.vectorstores import FAISS
7
+ from langchain.chains import RetrievalQA
8
+ from langchain_community.llms import HuggingFacePipeline
9
  from transformers import AutoModelForSeq2SeqLM, AutoTokenizer, pipeline
10
  import torch
11
 
12
+ st.title("Custom PDF Chatbot")
13
+
14
+ # Custom CSS for chat messages
15
+ st.markdown("""
16
+ <style>
17
+ .user-message {
18
+ text-align: right;
19
+ background-color: #3c8ce7;
20
+ color: white;
21
+ padding: 10px;
22
+ border-radius: 10px;
23
+ margin-bottom: 10px;
24
+ display: inline-block;
25
+ width: fit-content;
26
+ max-width: 70%;
27
+ margin-left: auto;
28
+ box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);
29
+ }
30
+ .assistant-message {
31
+ text-align: left;
32
+ background-color: #d16ba5;
33
+ color: white;
34
+ padding: 10px;
35
+ border-radius: 10px;
36
+ margin-bottom: 10px;
37
+ display: inline-block;
38
+ width: fit-content;
39
+ max-width: 70%;
40
+ margin-right: auto;
41
+ box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);
42
+ }
43
+ </style>
44
+ """, unsafe_allow_html=True)
45
 
46
  def get_file_size(file):
47
  file.seek(0, os.SEEK_END)
 
49
  file.seek(0)
50
  return file_size
51
 
52
+ # Add a sidebar for model selection
53
+ st.sidebar.write("Settings")
54
+ st.sidebar.write("-----------")
55
+ model_options = ["MBZUAI/LaMini-T5-738M", "google/flan-t5-base", "google/flan-t5-small"]
56
+ selected_model = st.sidebar.radio("Choose Model", model_options)
57
+ st.sidebar.write("-----------")
58
 
59
+ uploaded_file = st.sidebar.file_uploader("Upload file", type=["pdf"])
 
 
 
 
 
 
60
 
61
+ @st.cache_resource
62
+ def initialize_qa_chain(filepath, CHECKPOINT):
63
+ loader = PDFMinerLoader(filepath)
64
  documents = loader.load()
65
  text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=500)
66
  splits = text_splitter.split_documents(documents)
67
 
68
+ # Create embeddings
69
  embeddings = SentenceTransformerEmbeddings(model_name="all-MiniLM-L6-v2")
70
  vectordb = FAISS.from_documents(splits, embeddings)
 
 
71
 
72
+ # Initialize model
 
 
 
73
  TOKENIZER = AutoTokenizer.from_pretrained(CHECKPOINT)
74
  BASE_MODEL = AutoModelForSeq2SeqLM.from_pretrained(CHECKPOINT, device_map=torch.device('cpu'), torch_dtype=torch.float32)
75
  pipe = pipeline(
 
80
  do_sample=True,
81
  temperature=0.3,
82
  top_p=0.95,
 
83
  )
84
 
85
  llm = HuggingFacePipeline(pipeline=pipe)
 
 
 
86
 
87
  # Build a QA chain
88
  qa_chain = RetrievalQA.from_chain_type(
 
92
  )
93
  return qa_chain
94
 
95
+ def process_answer(instruction, qa_chain):
96
+ generated_text = qa_chain.run(instruction)
97
+ return generated_text
98
 
99
+ if uploaded_file is not None:
100
+ file_details = {
101
+ "Filename": uploaded_file.name,
102
+ "File size": get_file_size(uploaded_file)
103
+ }
104
+ os.makedirs("docs", exist_ok=True)
105
+ filepath = os.path.join("docs", uploaded_file.name)
106
+ with st.spinner('Embeddings are in process...'):
107
+ qa_chain = initialize_qa_chain(filepath, selected_model)
108
+ else:
109
+ qa_chain = None
110
+
111
+ # Initialize chat history
112
+ if "messages" not in st.session_state:
113
+ st.session_state.messages = []
114
+
115
+ # Display chat messages from history on app rerun
116
+ for message in st.session_state.messages:
117
+ if message["role"] == "user":
118
+ st.markdown(f"<div class='user-message'>{message['content']}</div>", unsafe_allow_html=True)
119
+ else:
120
+ st.markdown(f"<div class='assistant-message'>{message['content']}</div>", unsafe_allow_html=True)
121
+
122
+ # React to user input
123
+ if prompt := st.chat_input("What is up?"):
124
+ # Display user message in chat message container
125
+ st.markdown(f"<div class='user-message'>{prompt}</div>", unsafe_allow_html=True)
126
+ # Add user message to chat history
127
+ st.session_state.messages.append({"role": "user", "content": prompt})
128
+
129
+ if qa_chain:
130
+ # Generate response
131
+ response = process_answer({'query': prompt}, qa_chain)
132
+ else:
133
+ # Prompt to upload a file
134
+ response = "Please upload a PDF file to enable the chatbot."
135
+
136
+ # Display assistant response in chat message container
137
+ st.markdown(f"<div class='assistant-message'>{response}</div>", unsafe_allow_html=True)
138
 
139
+ # Add assistant response to chat history
140
+ st.session_state.messages.append({"role": "assistant", "content": response})