JBHF commited on
Commit
5d98490
1 Parent(s): 9016cad

Create app-19-03-2024.py

Browse files
Files changed (1) hide show
  1. app-19-03-2024.py +242 -0
app-19-03-2024.py ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app-19-03-2024.py
2
+
3
+ # JB:
4
+ # LangChainDeprecationWarning: Importing embeddings from langchain is deprecated.
5
+ # Importing from langchain will no longer be supported as of langchain==0.2.0.
6
+ # Please import from langchain-community instead:
7
+ # `from langchain_community.embeddings import FastEmbedEmbeddings`.
8
+ # To install langchain-community run `pip install -U langchain-community`.
9
+ from langchain_community.embeddings import FastEmbedEmbeddings
10
+
11
+ import os
12
+ import streamlit as st
13
+ from langchain_groq import ChatGroq
14
+ from langchain_community.document_loaders import WebBaseLoader
15
+ # JB:
16
+ from langchain_community.document_loaders import PyPDFLoader
17
+ from langchain_community.embeddings import OllamaEmbeddings
18
+
19
+ # JB:
20
+ from langchain_community.embeddings import FastEmbedEmbeddings
21
+ from langchain_community.document_loaders import PyPDFDirectoryLoader
22
+
23
+ # JB:
24
+ # File Directory
25
+ # This covers how to load all documents in a directory.
26
+ # Under the hood, by default this uses the UnstructuredLoader.
27
+ from langchain_community.document_loaders import DirectoryLoader
28
+ from langchain_community.document_loaders import TextLoader
29
+ import chardet
30
+
31
+ from langchain_community.vectorstores import FAISS
32
+ # from langchain.vectorstores import Chroma
33
+ # from langchain_community.vectorstores import Chroma
34
+
35
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
36
+ from langchain.chains.combine_documents import create_stuff_documents_chain
37
+ from langchain_core.prompts import ChatPromptTemplate
38
+ from langchain.chains import create_retrieval_chain
39
+ import time
40
+ from dotenv import load_dotenv
41
+
42
+ import glob
43
+
44
+ load_dotenv() #
45
+
46
+ # groq_api_key = os.environ['GROQ_API_KEY']
47
+ groq_api_key = "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" # os.environ['GROQ_API_KEY']
48
+ print("groq_api_key: ", groq_api_key)
49
+
50
+ # st.title("Chat with Docs - Groq Edition :) ")
51
+ st.write("NonToxicGlazeAdvisor: A tool for getting advice on non-toxic ceramic glazes for earthenware temperature ranges.")
52
+ st.write("Victor Benchuijsen : (Glaze techniques / Ceramics)")
53
+ st.write("Jan Bours : Artificial Intelligence / Data Science / Natural Language Processing (ALL RIGHTS RESERVED)")
54
+ st.write("---------------------------------")
55
+ st.write("Chat with Docs - Using AI: 'mixtral-8x7b-32768' Groq Edition (Very Fast!) - VERSION 1 - March 18, 2024")
56
+ st.write("---------------------------------")
57
+
58
+ st.write("LIST OF ALL THE LOADED DOCUMENTS: ")
59
+ st.write("")
60
+ pdf_files = glob.glob("*.pdf")
61
+ # word_files = glob.glob("*.docx")
62
+ for file in pdf_files:
63
+ # for file in word_files:
64
+ st.write(file)
65
+
66
+ st.write("---------------------------------")
67
+
68
+ if "vector" not in st.session_state:
69
+
70
+ st.write("Chunking, embedding, storing in FAISS vectorstore (Can take a long time!).")
71
+ st.write("Wait till this hase been done before you can enter your query! .......")
72
+
73
+ # st.session_state.embeddings = OllamaEmbeddings() # ORIGINAL
74
+ st.session_state.embeddings = FastEmbedEmbeddings() # JB
75
+
76
+
77
+ # st.session_state.loader = WebBaseLoader("https://paulgraham.com/greatwork.html") # ORIGINAL
78
+ # st.session_state.docs = st.session_state.loader.load() # ORIGINAL
79
+ # https://api.python.langchain.com/en/latest/document_loaders/langchain_community.document_loaders.pdf.PyPDFLoader.html
80
+ # https://python.langchain.com/docs/integrations/document_loaders/merge_doc
81
+ # from langchain_community.document_loaders import PyPDFLoader
82
+ # loader_pdf = PyPDFLoader("../MachineLearning-Lecture01.pdf")
83
+ #
84
+ # https://stackoverflow.com/questions/60215731/pypdf-to-read-each-pdf-in-a-folder
85
+ #
86
+ # https://api.python.langchain.com/en/latest/document_loaders/langchain_community.document_loaders.pdf.PyPDFDirectoryLoader.html
87
+ # https://python.langchain.com/docs/modules/data_connection/document_loaders/pdf#pypdf-directory
88
+ # !!!!!
89
+ # PyPDF Directory
90
+ # Load PDFs from directory
91
+ # from langchain_community.document_loaders import PyPDFDirectoryLoader
92
+ # loader = PyPDFDirectoryLoader("example_data/")
93
+ # docs = loader.load()
94
+ #
95
+ # ZIE OOK:
96
+ # https://python.langchain.com/docs/modules/data_connection/document_loaders/pdf#using-pypdf
97
+ # Using MathPix
98
+ # Inspired by Daniel Gross's https://gist.github.com/danielgross/3ab4104e14faccc12b49200843adab21
99
+ # from langchain_community.document_loaders import MathpixPDFLoader
100
+ # loader = MathpixPDFLoader("example_data/layout-parser-paper.pdf")
101
+ # data = loader.load()
102
+ # pdf_file_path = "*.pdf" # JB
103
+ # st.session_state.loader = PyPDFLoader(file_path=pdf_file_path).load() # JB
104
+ # st.session_state.loader = PyPDFLoader(*.pdf).load() # JB syntax error *.pdf !
105
+ # st.session_state.loader = PyPDFDirectoryLoader("*.pdf") # JB PyPDFDirectoryLoader("example_data/")
106
+ # chunks = self.text_splitter.split_documents(docs)
107
+ # chunks = filter_complex_metadata(chunks)
108
+
109
+ # JB:
110
+ # https://python.langchain.com/docs/modules/data_connection/document_loaders/pdf#pypdf-directory
111
+ # st.session_state.docs = st.session_state.loader.load()
112
+ # loader = PyPDFDirectoryLoader(".")
113
+ # docs = loader.load()
114
+ # st.session_state.docs = docs
115
+
116
+ # JB:
117
+ # https://python.langchain.com/docs/modules/data_connection/document_loaders/file_directory
118
+ # text_loader_kwargs={'autodetect_encoding': True}
119
+ text_loader_kwargs={'autodetect_encoding': False}
120
+ path = '../'
121
+ # loader = DirectoryLoader(path, glob="**/*.pdf", loader_cls=TextLoader, loader_kwargs=text_loader_kwargs)
122
+ # PyPDFDirectoryLoader (TEST):
123
+ # loader = PyPDFDirectoryLoader(path, glob="**/*.pdf", loader_cls=TextLoader, loader_kwargs=text_loader_kwargs)
124
+ # loader = PyPDFDirectoryLoader(path, glob="**/*.pdf", loader_kwargs=text_loader_kwargs)
125
+ loader = PyPDFDirectoryLoader(path, glob="**/*.pdf")
126
+ docs = loader.load()
127
+ st.session_state.docs = docs
128
+
129
+ # JB 18-03-2024:
130
+ # https://python.langchain.com/docs/integrations/document_loaders/
131
+ # MICROSOFT WORD:
132
+ # https://python.langchain.com/docs/integrations/document_loaders/microsoft_word
133
+ # 1 - Using Docx2txt
134
+ # Load .docx using Docx2txt into a document.
135
+ # %pip install --upgrade --quiet docx2txt
136
+ # from langchain_community.document_loaders import Docx2txtLoader
137
+ # loader = Docx2txtLoader("example_data/fake.docx")
138
+ # data = loader.load()
139
+ # data
140
+ # [Document(page_content='Lorem ipsum dolor sit amet.', metadata={'source': 'example_data/fake.docx'})]
141
+ #
142
+ # 2A - Using Unstructured
143
+ # from langchain_community.document_loaders import UnstructuredWordDocumentLoader
144
+ # loader = UnstructuredWordDocumentLoader("example_data/fake.docx")
145
+ # data = loader.load()
146
+ # data
147
+ # [Document(page_content='Lorem ipsum dolor sit amet.', lookup_str='', metadata={'source': 'fake.docx'}, lookup_index=0)]
148
+ #
149
+ # 2B - Retain Elements
150
+ # Under the hood, Unstructured creates different “elements” for different chunks of text.
151
+ # By default we combine those together, but you can easily keep that separation by specifying mode="elements".
152
+ # loader = UnstructuredWordDocumentLoader("example_data/fake.docx", mode="elements")
153
+ # data = loader.load()
154
+ # data[0]
155
+ # Document(page_content='Lorem ipsum dolor sit amet.', lookup_str='', metadata={'source': 'fake.docx', 'filename': 'fake.docx', 'category': 'Title'}, lookup_index=0)
156
+ #
157
+ # 2A - Using Unstructured
158
+ # from langchain_community.document_loaders import UnstructuredWordDocumentLoader
159
+ # loader = UnstructuredWordDocumentLoader(path, glob="**/*.docx")
160
+ # docs = loader.load()
161
+ # st.session_state.docs = docs
162
+
163
+
164
+
165
+
166
+ st.session_state.text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
167
+ st.session_state.documents = st.session_state.text_splitter.split_documents(st.session_state.docs)
168
+ # https://python.langchain.com/docs/integrations/vectorstores/faiss
169
+ # docs_and_scores = db.similarity_search_with_score(query)
170
+ # Saving and loading
171
+ # You can also save and load a FAISS index.
172
+ # This is useful so you don’t have to recreate it everytime you use it.
173
+ # db.save_local("faiss_index")
174
+ # new_db = FAISS.load_local("faiss_index", embeddings)
175
+ # docs = new_db.similarity_search(query)
176
+ # docs[0]
177
+ # 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'})
178
+ #
179
+ st.session_state.vector = FAISS.from_documents(st.session_state.documents, st.session_state.embeddings) # ORIGINAL
180
+
181
+ # st.session_state.vector = FAISS.from_documents(st.session_state.documents, st.session_state.embeddings) # ORIGINAL
182
+ #st.session_state.vector.save_local("faiss_index")
183
+ # The de-serialization relies loading a pickle file.
184
+ # Pickle files can be modified to deliver a malicious payload that results in execution of arbitrary code on your machine.
185
+ # 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.
186
+
187
+ #st.session_state.vector = FAISS.load_local("faiss_index", st.session_state.embeddings, allow_dangerous_deserialization=True)
188
+
189
+ # ZIE:
190
+ # ZIE VOOR EEN APP MET CHROMADB:
191
+ # https://github.com/vndee/local-rag-example/blob/main/rag.py
192
+ # https://raw.githubusercontent.com/vndee/local-rag-example/main/rag.py
193
+ # Chroma.from_documents(documents=chunks, embedding=FastEmbedEmbeddings())
194
+ # st.session_state.vector = Chroma.from_documents(st.session_state.documents, st.session_state.embeddings) # JB
195
+
196
+ st.write("---------------------------------")
197
+
198
+ # st.title("Chat with Docs - Groq Edition :) ")
199
+ # st.title("Literature Based Research (LBR) - A. Unzicker and J. Bours - Chat with Docs - Groq Edition (Very Fast!) - VERSION 3 - March 8 2024")
200
+
201
+ llm = ChatGroq(
202
+ temperature=0.2,
203
+ groq_api_key=groq_api_key,
204
+ model_name='mixtral-8x7b-32768'
205
+ )
206
+
207
+ prompt = ChatPromptTemplate.from_template("""
208
+ Answer the following question based only on the provided context.
209
+ Think step by step before providing a detailed answer.
210
+ I will tip you $200 if the user finds the answer helpful.
211
+ <context>
212
+ {context}
213
+ </context>
214
+ Question: {input}""")
215
+
216
+ document_chain = create_stuff_documents_chain(llm, prompt)
217
+
218
+ retriever = st.session_state.vector.as_retriever()
219
+ retrieval_chain = create_retrieval_chain(retriever, document_chain)
220
+
221
+ prompt = st.text_input("Input your prompt here")
222
+
223
+
224
+ # If the user hits enter
225
+ if prompt:
226
+ # Then pass the prompt to the LLM
227
+ start = time.process_time()
228
+ response = retrieval_chain.invoke({"input": prompt})
229
+ print(f"Response time: {time.process_time() - start}")
230
+
231
+ st.write(response["answer"])
232
+
233
+ # With a streamlit expander
234
+ with st.expander("Document Similarity Search"):
235
+ # Find the relevant chunks
236
+ for i, doc in enumerate(response["context"]):
237
+ # print(doc)
238
+ # st.write(f"Source Document # {i+1} : {doc.metadata['source'].split('/')[-1]}")
239
+ st.write(doc.page_content)
240
+ st.write("--------------------------------")
241
+
242
+ st.write("---------------------------------")