tensorkelechi commited on
Commit
6993f7f
1 Parent(s): eb1fcea

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +98 -0
app.py CHANGED
@@ -98,6 +98,104 @@ if st.session_state != "":
98
  except Exception as e:
99
  st.error(e)
100
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
  # We store the conversation in the session state.
102
  # This will be use to render the chat conversation.
103
  # We initialize it with the first message we want to be greeted with.
 
98
  except Exception as e:
99
  st.error(e)
100
 
101
+ import os
102
+ from langchain_community.document_loaders import PyPDFLoader
103
+ from langchain_community.vectorstores import faiss
104
+ from langchain.memory import ConversationBufferMemory
105
+ from langchain_google_genai import ChatGoogleGenerativeAI, GoogleGenerativeAIEmbeddings
106
+ from tempfile import NamedTemporaryFile
107
+ from dotenv import load_dotenv
108
+ from langchain_text_splitters import RecursiveCharacterTextSplitter
109
+ from langchain.chains import ConversationalRetrievalChain
110
+ import streamlit as st
111
+ import nest_asyncio
112
+
113
+ nest_asyncio.apply()
114
+ load_dotenv()
115
+
116
+ # Initialize app resources
117
+ st.set_page_config(page_title="StudyAssist", page_icon=":book:")
118
+ st.title("StudyAssist(pharmassist-v0)")
119
+ st.write(
120
+ "An AI/RAG application to aid students in their studies, specially optimized for the pharm 028 students. In simpler terms, chat with your pdf"
121
+ )
122
+
123
+
124
+ @st.cache_resource
125
+ def initialize_resources():
126
+ llm_gemini = ChatGoogleGenerativeAI(
127
+ model="gemini-1.5-flash-latest", google_api_key=os.getenv("GOOGLE_API_KEY")
128
+ )
129
+ return llm_gemini
130
+
131
+
132
+ def get_retriever(pdf_file):
133
+ with NamedTemporaryFile(suffix="pdf") as temp:
134
+ temp.write(pdf_file.getvalue())
135
+ pdf_loader = PyPDFLoader(temp.name, extract_images=True)
136
+ pages = pdf_loader.load()
137
+
138
+ # st.write(f"AI Chatbot for {course_material}")
139
+
140
+ underlying_embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
141
+ text_splitter = RecursiveCharacterTextSplitter(
142
+ chunk_size=1000,
143
+ chunk_overlap=20,
144
+ length_function=len,
145
+ is_separator_regex=False,
146
+ separators="\n",
147
+ )
148
+ documents = text_splitter.split_documents(pages)
149
+ vectorstore = faiss.FAISS.from_documents(documents, underlying_embeddings)
150
+ doc_retiever = vectorstore.as_retriever(
151
+ search_type="mmr", search_kwargs={"k": 5, "fetch_k": 10}
152
+ )
153
+
154
+ return doc_retiever
155
+
156
+
157
+ chat_model = initialize_resources()
158
+
159
+ # Streamlit UI
160
+ # Course list and pdf retrieval
161
+
162
+ courses = ["PMB", "PCL", "Kelechi_research"] # "GSP", "CPM", "PCG", "PCH"
163
+ course_pdfs = None
164
+ doc_retriever = None
165
+ conversational_chain = None
166
+
167
+ # course = st.sidebar.selectbox("Choose course", (courses))
168
+ # docs_path = f"pdfs/{course}"
169
+ # course_pdfs = os.listdir(docs_path)
170
+ # pdfs = [os.path.join(docs_path, pdf) for pdf in course_pdfs]
171
+
172
+ course_material = "{Not selected}"
173
+
174
+
175
+ # @st.cache_resource
176
+ def query_response(query, _retriever):
177
+ memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
178
+ conversational_chain = ConversationalRetrievalChain.from_llm(
179
+ llm=chat_model, retriever=_retriever, memory=memory, verbose=False
180
+ )
181
+ response = conversational_chain.run(query)
182
+
183
+ return response
184
+
185
+
186
+ if "doc" not in st.session_state:
187
+ st.session_state.doc = ""
188
+
189
+ course_material = st.file_uploader("or Upload your own pdf", type="pdf")
190
+
191
+ if st.session_state != "":
192
+ try:
193
+ with st.spinner("loading document.."):
194
+ doc_retriever = get_retriever(course_material)
195
+ st.success("File loading successful, vector db initialize")
196
+ except Exception as e:
197
+ st.error(e)
198
+
199
  # We store the conversation in the session state.
200
  # This will be use to render the chat conversation.
201
  # We initialize it with the first message we want to be greeted with.