JBHF commited on
Commit
50a7d7c
1 Parent(s): 4b505c0

Create app-26-03-2024

Browse files
Files changed (1) hide show
  1. app-26-03-2024 +286 -0
app-26-03-2024 ADDED
@@ -0,0 +1,286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # NonToxicGlazeAdvisor_Chat_with_Docs_Groq_Edition_1 - app.py - 26-03-2024
2
+
3
+ # STREAMLIT:
4
+ # https://www.datacamp.com/tutorial/streamlit:
5
+ #
6
+ # st.title(): This function allows you to add the title of the app.
7
+ # st.header(): This function is used to set header of a section.
8
+ # st.markdown(): This function is used to set a markdown of a section.
9
+ # st.subheader(): This function is used to set sub-header of a section.
10
+ # st.caption(): This function is used to write caption.
11
+ # st.code(): This function is used to set a code.
12
+ # st.latex(): This function is used to display mathematical expressions formatted as LaTeX.
13
+ #
14
+ # st.title ("this is the app title")
15
+ # st.header("this is the header ")
16
+ # st.markdown("this is the markdown")
17
+ # st.subheader("this is the subheader")
18
+ # st.caption("this is the caption")
19
+ # st.code("x=2021")
20
+ # st.latex(r''' a+a r^1+a r^2+a r^3 ''')
21
+
22
+
23
+
24
+ # JB:
25
+ # LangChainDeprecationWarning: Importing embeddings from langchain is deprecated.
26
+ # Importing from langchain will no longer be supported as of langchain==0.2.0.
27
+ # Please import from langchain-community instead:
28
+ # `from langchain_community.embeddings import FastEmbedEmbeddings`.
29
+ # To install langchain-community run `pip install -U langchain-community`.
30
+ from langchain_community.embeddings import FastEmbedEmbeddings
31
+
32
+ import os
33
+ import streamlit as st
34
+ from langchain_groq import ChatGroq
35
+ from langchain_community.document_loaders import WebBaseLoader
36
+ # JB:
37
+ from langchain_community.document_loaders import PyPDFLoader
38
+ from langchain_community.embeddings import OllamaEmbeddings
39
+
40
+ # JB:
41
+ from langchain_community.embeddings import FastEmbedEmbeddings
42
+ from langchain_community.document_loaders import PyPDFDirectoryLoader
43
+
44
+ # JB:
45
+ # File Directory
46
+ # This covers how to load all documents in a directory.
47
+ # Under the hood, by default this uses the UnstructuredLoader.
48
+ from langchain_community.document_loaders import DirectoryLoader
49
+ from langchain_community.document_loaders import TextLoader
50
+ import chardet
51
+
52
+ from langchain_community.vectorstores import FAISS
53
+ # from langchain.vectorstores import Chroma
54
+ # from langchain_community.vectorstores import Chroma
55
+
56
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
57
+ from langchain.chains.combine_documents import create_stuff_documents_chain
58
+ from langchain_core.prompts import ChatPromptTemplate
59
+ from langchain.chains import create_retrieval_chain
60
+ import time
61
+ from dotenv import load_dotenv
62
+
63
+ import glob
64
+
65
+ load_dotenv() #
66
+
67
+ groq_api_key = os.environ['GROQ_API_KEY']
68
+ # groq_api_key = "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" # os.environ['GROQ_API_KEY']
69
+ # groq_api_key = "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" # JB OK 24-03-2024
70
+ print("groq_api_key: ", groq_api_key)
71
+
72
+ # st.title("Chat with Docs - Groq Edition :) ")
73
+ # # st.title ("this is the app title")
74
+ # st.title("Non-Toxic Glaze Advisor:")
75
+ # st.subheader("A tool for getting advicgroqe on non-toxic ceramic glazes for earthenware temperature ranges.")
76
+ # st.subheader("Victor Benchuijsen : (Glaze techniques / Ceramics)")
77
+ # st.subheader("Jan Bours : Artificial Intelligence / Data Science / Natural Language Processing (ALL RIGHTS RESERVED)")
78
+ # st.write("---------------------------------")
79
+ # st.subheader("Chat with Docs - Using AI: 'mixtral-8x7b-32768' Groq Edition (Very Fast!) - VERSION 1 - March 18, 2024")
80
+ # st.write("---------------------------------")
81
+
82
+ st.title("Adviseur voor niet-giftige glazuren:")
83
+ st.subheader("Een gereedschap om advies te krijgen over niet-giftige keramische glazuren voor aardewerk temperatuur bereiken.")
84
+ st.write("---------------------------------")
85
+ st.subheader("Victor Benchuijsen : (Glazuur technieken / Keramiek)")
86
+ st.subheader("(ALL RIGHTS RESERVED)")
87
+ # st.subheader("---------------------------------")
88
+ # st.write("---------------------------------")
89
+ st.subheader("Jan Bours : Artificial Intelligence / Data Science / Natural Language Processing")
90
+ st.subheader("(ALL RIGHTS RESERVED)")
91
+ st.write("---------------------------------")
92
+ st.subheader("Chat with Docs - Using AI: 'mixtral-8x7b-32768' Groq Edition (Very Fast!) - VERSION 1 - March 26, 2024")
93
+ st.write("---------------------------------")
94
+
95
+ # st.header("LIST OF ALL THE LOADED DOCUMENTS: ")
96
+ st.header("LIJST MET ALLE ACTUEEL GELADEN DOCUMENTEN: ")
97
+
98
+ st.write("")
99
+ pdf_files = glob.glob("*.pdf")
100
+ # word_files = glob.glob("*.docx")
101
+ for file in pdf_files:
102
+ # for file in word_files:
103
+ st.subheader(file)
104
+
105
+ st.write("---------------------------------")
106
+
107
+ if "vector" not in st.session_state:
108
+
109
+ # st.header("Chunking, embedding, storing in FAISS vectorstore (Can take a long time!).")
110
+ # st.subheader("Wait till this hase been done before you can enter your query! .......")
111
+
112
+ # st.session_state.embeddings = OllamaEmbeddings() # ORIGINAL
113
+ st.session_state.embeddings = FastEmbedEmbeddings() # JB
114
+
115
+
116
+ # st.session_state.loader = WebBaseLoader("https://paulgraham.com/greatwork.html") # ORIGINAL
117
+ # st.session_state.docs = st.session_state.loader.load() # ORIGINAL
118
+ # https://api.python.langchain.com/en/latest/document_loaders/langchain_community.document_loaders.pdf.PyPDFLoader.html
119
+ # https://python.langchain.com/docs/integrations/document_loaders/merge_doc
120
+ # from langchain_community.document_loaders import PyPDFLoader
121
+ # loader_pdf = PyPDFLoader("../MachineLearning-Lecture01.pdf")
122
+ #
123
+ # https://stackoverflow.com/questions/60215731/pypdf-to-read-each-pdf-in-a-folder
124
+ #
125
+ # https://api.python.langchain.com/en/latest/document_loaders/langchain_community.document_loaders.pdf.PyPDFDirectoryLoader.html
126
+ # https://python.langchain.com/docs/modules/data_connection/document_loaders/pdf#pypdf-directory
127
+ # !!!!!
128
+ # PyPDF Directory
129
+ # Load PDFs from directory
130
+ # from langchain_community.document_loaders import PyPDFDirectoryLoader
131
+ # loader = PyPDFDirectoryLoader("example_data/")
132
+ # docs = loader.load()
133
+ #
134
+ # ZIE OOK:
135
+ # https://python.langchain.com/docs/modules/data_connection/document_loaders/pdf#using-pypdf
136
+ # Using MathPix
137
+ # Inspired by Daniel Gross's https://gist.github.com/danielgross/3ab4104e14faccc12b49200843adab21
138
+ # from langchain_community.document_loaders import MathpixPDFLoader
139
+ # loader = MathpixPDFLoader("example_data/layout-parser-paper.pdf")
140
+ # data = loader.load()
141
+ # pdf_file_path = "*.pdf" # JB
142
+ # st.session_state.loader = PyPDFLoader(file_path=pdf_file_path).load() # JB
143
+ # st.session_state.loader = PyPDFLoader(*.pdf).load() # JB syntax error *.pdf !
144
+ # st.session_state.loader = PyPDFDirectoryLoader("*.pdf") # JB PyPDFDirectoryLoader("example_data/")
145
+ # chunks = self.text_splitter.split_documents(docs)
146
+ # chunks = filter_complex_metadata(chunks)
147
+
148
+ # JB:
149
+ # https://python.langchain.com/docs/modules/data_connection/document_loaders/pdf#pypdf-directory
150
+ # st.session_state.docs = st.session_state.loader.load()
151
+ # loader = PyPDFDirectoryLoader(".")
152
+ # docs = loader.load()
153
+ # st.session_state.docs = docs
154
+
155
+ # JB:
156
+ # https://python.langchain.com/docs/modules/data_connection/document_loaders/file_directory
157
+ # text_loader_kwargs={'autodetect_encoding': True}
158
+ text_loader_kwargs={'autodetect_encoding': False}
159
+ path = '../'
160
+ # loader = DirectoryLoader(path, glob="**/*.pdf", loader_cls=TextLoader, loader_kwargs=text_loader_kwargs)
161
+ # PyPDFDirectoryLoader (TEST):
162
+ # loader = PyPDFDirectoryLoader(path, glob="**/*.pdf", loader_cls=TextLoader, loader_kwargs=text_loader_kwargs)
163
+ # loader = PyPDFDirectoryLoader(path, glob="**/*.pdf", loader_kwargs=text_loader_kwargs)
164
+ loader = PyPDFDirectoryLoader(path, glob="**/*.pdf")
165
+ docs = loader.load()
166
+ st.session_state.docs = docs
167
+
168
+ # JB 18-03-2024:
169
+ # https://python.langchain.com/docs/integrations/document_loaders/
170
+ # MICROSOFT WORD:
171
+ # https://python.langchain.com/docs/integrations/document_loaders/microsoft_word
172
+ # 1 - Using Docx2txt
173
+ # Load .docx using Docx2txt into a document.
174
+ # %pip install --upgrade --quiet docx2txt
175
+ # from langchain_community.document_loaders import Docx2txtLoader
176
+ # loader = Docx2txtLoader("example_data/fake.docx")
177
+ # data = loader.load()
178
+ # data
179
+ # [Document(page_content='Lorem ipsum dolor sit amet.', metadata={'source': 'example_data/fake.docx'})]
180
+ #
181
+ # 2A - Using Unstructured
182
+ # from langchain_community.document_loaders import UnstructuredWordDocumentLoader
183
+ # loader = UnstructuredWordDocumentLoader("example_data/fake.docx")
184
+ # data = loader.load()
185
+ # data
186
+ # [Document(page_content='Lorem ipsum dolor sit amet.', lookup_str='', metadata={'source': 'fake.docx'}, lookup_index=0)]
187
+ #
188
+ # 2B - Retain Elements
189
+ # Under the hood, Unstructured creates different “elements” for different chunks of text.
190
+ # By default we combine those together, but you can easily keep that separation by specifying mode="elements".
191
+ # loader = UnstructuredWordDocumentLoader("example_data/fake.docx", mode="elements")
192
+ # data = loader.load()
193
+ # data[0]
194
+ # Document(page_content='Lorem ipsum dolor sit amet.', lookup_str='', metadata={'source': 'fake.docx', 'filename': 'fake.docx', 'category': 'Title'}, lookup_index=0)
195
+ #
196
+ # 2A - Using Unstructured
197
+ # from langchain_community.document_loaders import UnstructuredWordDocumentLoader
198
+ # loader = UnstructuredWordDocumentLoader(path, glob="**/*.docx")
199
+ # docs = loader.load()
200
+ # st.session_state.docs = docs
201
+
202
+
203
+
204
+
205
+ st.session_state.text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
206
+ st.session_state.documents = st.session_state.text_splitter.split_documents(st.session_state.docs)
207
+ # https://python.langchain.com/docs/integrations/vectorstores/faiss
208
+ # docs_and_scores = db.similarity_search_with_score(query)
209
+ # Saving and loading
210
+ # You can also save and load a FAISS index.
211
+ # This is useful so you don’t have to recreate it everytime you use it.
212
+ # db.save_local("faiss_index")
213
+ # new_db = FAISS.load_local("faiss_index", embeddings)
214
+ # docs = new_db.similarity_search(query)
215
+ # docs[0]
216
+ # Document(page_content='Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. \n\nTonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. \n\nOne of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. \n\nAnd I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.', metadata={'source': '../../../state_of_the_union.txt'})
217
+ #
218
+ st.session_state.vector = FAISS.from_documents(st.session_state.documents, st.session_state.embeddings) # ORIGINAL
219
+
220
+ # st.session_state.vector = FAISS.from_documents(st.session_state.documents, st.session_state.embeddings) # ORIGINAL
221
+ #st.session_state.vector.save_local("faiss_index")
222
+ # The de-serialization relies loading a pickle file.
223
+ # Pickle files can be modified to deliver a malicious payload that results in execution of arbitrary code on your machine.
224
+ # You will need to set `allow_dangerous_deserialization` to `True` to enable deserialization. If you do this, make sure that you trust the source of the data.
225
+
226
+ #st.session_state.vector = FAISS.load_local("faiss_index", st.session_state.embeddings, allow_dangerous_deserialization=True)
227
+
228
+ # ZIE:
229
+ # ZIE VOOR EEN APP MET CHROMADB:
230
+ # https://github.com/vndee/local-rag-example/blob/main/rag.py
231
+ # https://raw.githubusercontent.com/vndee/local-rag-example/main/rag.py
232
+ # Chroma.from_documents(documents=chunks, embedding=FastEmbedEmbeddings())
233
+ # st.session_state.vector = Chroma.from_documents(st.session_state.documents, st.session_state.embeddings) # JB
234
+
235
+ st.write("---------------------------------")
236
+
237
+ # st.title("Chat with Docs - Groq Edition :) ")
238
+ # st.title("Literature Based Research (LBR) - A. Unzicker and J. Bours - Chat with Docs - Groq Edition (Very Fast!) - VERSION 3 - March 8 2024")
239
+
240
+ llm = ChatGroq(
241
+ temperature=0.2,
242
+ groq_api_key=groq_api_key,
243
+ model_name='mixtral-8x7b-32768'
244
+ )
245
+
246
+ prompt = ChatPromptTemplate.from_template("""
247
+ Answer the following question based only on the provided context.
248
+ Think step by step before providing a detailed answer.
249
+ I will tip you $200 if the user finds the answer helpful.
250
+ <context>
251
+ {context}
252
+ </context>
253
+ Question: {input}""")
254
+
255
+ document_chain = create_stuff_documents_chain(llm, prompt)
256
+
257
+ retriever = st.session_state.vector.as_retriever()
258
+ retrieval_chain = create_retrieval_chain(retriever, document_chain)
259
+
260
+ prompt = st.text_input("Input your prompt here")
261
+
262
+
263
+ # If the user hits enter
264
+ if prompt:
265
+ # Then pass the prompt to the LLM
266
+ start = time.process_time()
267
+ response = retrieval_chain.invoke({"input": prompt})
268
+ # print(f"Response time: {time.process_time() - start}")
269
+ st.write(f"Response time: {time.process_time() - start} seconds")
270
+
271
+ st.write(response["answer"])
272
+
273
+ # With a streamlit expander
274
+ with st.expander("Document Similarity Search"):
275
+ # Find the relevant chunks
276
+ for i, doc in enumerate(response["context"]):
277
+ # print(doc)
278
+ # st.write(f"Source Document # {i+1} : {doc.metadata['source'].split('/')[-1]}")
279
+ st.write(doc)
280
+ st.write(f"Source Document # {i+1} : {doc.metadata['source'].split('/')[-1]}")
281
+
282
+
283
+ st.write(doc.page_content)
284
+ st.write("--------------------------------")
285
+
286
+ st.write("---------------------------------")