JBHF commited on
Commit
9e0beed
1 Parent(s): ae80635
Files changed (1) hide show
  1. app.py +372 -368
app.py CHANGED
@@ -27,9 +27,9 @@ import streamlit as st
27
 
28
  tab1, tab2, tab3 = st.tabs(["Cat", "Dog", "Owl"])
29
 
30
- with tab1:
31
- st.header("A cat")
32
- st.image("https://static.streamlit.io/examples/cat.jpg", width=200)
33
 
34
  with tab2:
35
  st.header("A dog")
@@ -42,394 +42,398 @@ with tab3:
42
 
43
 
44
 
45
- # JB:
46
- # LangChainDeprecationWarning: Importing embeddings from langchain is deprecated.
47
- # Importing from langchain will no longer be supported as of langchain==0.2.0.
48
- # Please import from langchain-community instead:
49
- # `from langchain_community.embeddings import FastEmbedEmbeddings`.
50
- # To install langchain-community run `pip install -U langchain-community`.
51
- from langchain_community.embeddings import FastEmbedEmbeddings
52
 
53
- import os
54
- import streamlit as st
55
- from langchain_groq import ChatGroq
56
- from langchain_community.document_loaders import WebBaseLoader
57
- # JB:
58
- from langchain_community.document_loaders import PyPDFLoader
59
- from langchain_community.embeddings import OllamaEmbeddings
60
-
61
- # JB:
62
- from langchain_community.embeddings import FastEmbedEmbeddings
63
- from langchain_community.document_loaders import PyPDFDirectoryLoader
64
-
65
- # JB:
66
- # File Directory
67
- # This covers how to load all documents in a directory.
68
- # Under the hood, by default this uses the UnstructuredLoader.
69
- from langchain_community.document_loaders import DirectoryLoader
70
- from langchain_community.document_loaders import TextLoader
71
- import chardet
72
-
73
- from langchain_community.vectorstores import FAISS
74
- # from langchain.vectorstores import Chroma
75
- # from langchain_community.vectorstores import Chroma
76
-
77
- from langchain.text_splitter import RecursiveCharacterTextSplitter
78
- from langchain.chains.combine_documents import create_stuff_documents_chain
79
- from langchain_core.prompts import ChatPromptTemplate
80
- from langchain.chains import create_retrieval_chain
81
- import time
82
- from dotenv import load_dotenv
83
-
84
- import glob
85
-
86
- load_dotenv() #
87
-
88
- groq_api_key = os.environ['GROQ_API_KEY']
89
- # groq_api_key = "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" # os.environ['GROQ_API_KEY']
90
- # groq_api_key = "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" # JB OK 24-03-2024
91
- # print("groq_api_key: ", groq_api_key)
92
-
93
- # st.title("Chat with Docs - Groq Edition :) ")
94
- # # st.title ("this is the app title")
95
- # st.title("Non-Toxic Glaze Advisor:")
96
- # st.subheader("A tool for getting advicgroqe on non-toxic ceramic glazes for earthenware temperature ranges.")
97
- # st.subheader("Victor Benchuijsen : (Glaze techniques / Ceramics)")
98
- # st.subheader("Jan Bours : Artificial Intelligence / Data Science / Natural Language Processing (ALL RIGHTS RESERVED)")
99
- # st.write("---------------------------------")
100
- # st.subheader("Chat with Docs - Using AI: 'mixtral-8x7b-32768' Groq Edition (Very Fast!) - VERSION 1 - March 18, 2024")
101
- # st.write("---------------------------------")
102
-
103
- st.title("Adviseur voor niet-giftige glazuren:")
104
- st.subheader("Een gereedschap gebaseerd op Kunstmatige Intelligentie (AI) om advies te krijgen over niet-giftige keramische glazuren voor aardewerk temperatuur bereiken.")
105
- st.write("---------------------------------")
106
- st.subheader("Victor Benckhuijsen : (Glazuur technieken / Keramiek)")
107
- st.subheader("(ALL RIGHTS RESERVED)")
108
- st.image('Victor_Benckhuijsen_2.png', caption='Victor Benckhuijsen', width=100)
109
- # st.subheader("---------------------------------")
110
- # st.write("---------------------------------")
111
- st.subheader("Jan Bours : Artificial Intelligence / Data Science / Natural Language Processing")
112
- st.subheader("(ALL RIGHTS RESERVED)")
113
- st.image('Jan_Bours_2.png', caption='Jan Bours', width=100)
114
- st.write("---------------------------------")
115
- st.subheader("Chat with Docs - Using AI: 'mixtral-8x7b-32768' Groq Edition (Very Fast!) - VERSION 2 - April 3, 2024")
116
- st.write("---------------------------------")
117
-
118
- # st.header("LIST OF ALL THE LOADED DOCUMENTS: ")
119
- st.header("LIJST MET ALLE ACTUEEL GELADEN DOCUMENTEN: ")
120
-
121
- st.write("")
122
- pdf_files = glob.glob("*.pdf")
123
- # word_files = glob.glob("*.docx")
124
- for file in pdf_files:
125
- # for file in word_files:
126
- st.subheader(file)
127
-
128
- st.write("---------------------------------")
129
-
130
-
131
- start1 = time.process_time()
132
-
133
- if "vector" not in st.session_state:
134
 
135
- st.write("Even geduld a.u.b. ........")
136
- # st.header("Chunking, embedding, storing in FAISS vectorstore (Can take a long time!).")
137
- # st.subheader("Wait till this hase been done before you can enter your query! .......")
138
-
139
- # st.session_state.embeddings = OllamaEmbeddings() # ORIGINAL
140
- st.session_state.embeddings = FastEmbedEmbeddings() # JB
141
-
 
 
 
 
 
 
 
 
142
 
143
- # st.session_state.loader = WebBaseLoader("https://paulgraham.com/greatwork.html") # ORIGINAL
144
- # st.session_state.docs = st.session_state.loader.load() # ORIGINAL
145
- # https://api.python.langchain.com/en/latest/document_loaders/langchain_community.document_loaders.pdf.PyPDFLoader.html
146
- # https://python.langchain.com/docs/integrations/document_loaders/merge_doc
147
- # from langchain_community.document_loaders import PyPDFLoader
148
- # loader_pdf = PyPDFLoader("../MachineLearning-Lecture01.pdf")
149
- #
150
- # https://stackoverflow.com/questions/60215731/pypdf-to-read-each-pdf-in-a-folder
151
- #
152
- # https://api.python.langchain.com/en/latest/document_loaders/langchain_community.document_loaders.pdf.PyPDFDirectoryLoader.html
153
- # https://python.langchain.com/docs/modules/data_connection/document_loaders/pdf#pypdf-directory
154
- # !!!!!
155
- # PyPDF Directory
156
- # Load PDFs from directory
157
- # from langchain_community.document_loaders import PyPDFDirectoryLoader
158
- # loader = PyPDFDirectoryLoader("example_data/")
159
- # docs = loader.load()
160
- #
161
- # ZIE OOK:
162
- # https://python.langchain.com/docs/modules/data_connection/document_loaders/pdf#using-pypdf
163
- # Using MathPix
164
- # Inspired by Daniel Gross's https://gist.github.com/danielgross/3ab4104e14faccc12b49200843adab21
165
- # from langchain_community.document_loaders import MathpixPDFLoader
166
- # loader = MathpixPDFLoader("example_data/layout-parser-paper.pdf")
167
- # data = loader.load()
168
- # pdf_file_path = "*.pdf" # JB
169
- # st.session_state.loader = PyPDFLoader(file_path=pdf_file_path).load() # JB
170
- # st.session_state.loader = PyPDFLoader(*.pdf).load() # JB syntax error *.pdf !
171
- # st.session_state.loader = PyPDFDirectoryLoader("*.pdf") # JB PyPDFDirectoryLoader("example_data/")
172
- # chunks = self.text_splitter.split_documents(docs)
173
- # chunks = filter_complex_metadata(chunks)
174
 
175
  # JB:
176
- # https://python.langchain.com/docs/modules/data_connection/document_loaders/pdf#pypdf-directory
177
- # st.session_state.docs = st.session_state.loader.load()
178
- # loader = PyPDFDirectoryLoader(".")
179
- # docs = loader.load()
180
- # st.session_state.docs = docs
181
-
182
-
183
- # https://docs.streamlit.io/library/api-reference/status/st.status
184
- # st.status(label, *, expanded=False, state="running")
185
- with st.status("Laden van de PDF documenten / Splitting de teksten / Genereer de Vector Store ...", expanded=True) as status:
186
- # st.write("Searching for data...")
187
- # time.sleep(2)
188
- # st.write("Found URL.")
189
- # time.sleep(1)
190
- # st.write("Downloading data...")
191
- # time.sleep(1)
192
- #status.update(label="Download complete!", state="complete", expanded=False)
193
-
194
- st.write("Laden van de PDF documenten...")
195
- # JB:
196
- # https://python.langchain.com/docs/modules/data_connection/document_loaders/file_directory
197
- # text_loader_kwargs={'autodetect_encoding': True}
198
- text_loader_kwargs={'autodetect_encoding': False}
199
- path = '../'
200
- # loader = DirectoryLoader(path, glob="**/*.pdf", loader_cls=TextLoader, loader_kwargs=text_loader_kwargs)
201
- # PyPDFDirectoryLoader (TEST):
202
- # loader = PyPDFDirectoryLoader(path, glob="**/*.pdf", loader_cls=TextLoader, loader_kwargs=text_loader_kwargs)
203
- # loader = PyPDFDirectoryLoader(path, glob="**/*.pdf", loader_kwargs=text_loader_kwargs)
204
- loader = PyPDFDirectoryLoader(path, glob="**/*.pdf")
205
- docs = loader.load()
206
- st.session_state.docs = docs
207
-
208
- # JB 18-03-2024:
209
- # https://python.langchain.com/docs/integrations/document_loaders/
210
- # MICROSOFT WORD:
211
- # https://python.langchain.com/docs/integrations/document_loaders/microsoft_word
212
- # 1 - Using Docx2txt
213
- # Load .docx using Docx2txt into a document.
214
- # %pip install --upgrade --quiet docx2txt
215
- # from langchain_community.document_loaders import Docx2txtLoader
216
- # loader = Docx2txtLoader("example_data/fake.docx")
217
- # data = loader.load()
218
- # data
219
- # [Document(page_content='Lorem ipsum dolor sit amet.', metadata={'source': 'example_data/fake.docx'})]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
220
  #
221
- # 2A - Using Unstructured
222
- # from langchain_community.document_loaders import UnstructuredWordDocumentLoader
223
- # loader = UnstructuredWordDocumentLoader("example_data/fake.docx")
224
- # data = loader.load()
225
- # data
226
- # [Document(page_content='Lorem ipsum dolor sit amet.', lookup_str='', metadata={'source': 'fake.docx'}, lookup_index=0)]
 
 
 
 
227
  #
228
- # 2B - Retain Elements
229
- # Under the hood, Unstructured creates different “elements” for different chunks of text.
230
- # By default we combine those together, but you can easily keep that separation by specifying mode="elements".
231
- # loader = UnstructuredWordDocumentLoader("example_data/fake.docx", mode="elements")
 
 
232
  # data = loader.load()
233
- # data[0]
234
- # Document(page_content='Lorem ipsum dolor sit amet.', lookup_str='', metadata={'source': 'fake.docx', 'filename': 'fake.docx', 'category': 'Title'}, lookup_index=0)
235
- #
236
- # 2A - Using Unstructured
237
- # from langchain_community.document_loaders import UnstructuredWordDocumentLoader
238
- # loader = UnstructuredWordDocumentLoader(path, glob="**/*.docx")
 
 
 
 
 
239
  # docs = loader.load()
240
  # st.session_state.docs = docs
241
 
242
 
243
- st.write("Splitting / chunking de teksten...")
244
- st.session_state.text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
245
- st.session_state.documents = st.session_state.text_splitter.split_documents(st.session_state.docs)
246
-
247
- st.write("Genereer de Vector Store (kan enige minuten duren)...")
248
- # https://python.langchain.com/docs/integrations/vectorstores/faiss
249
- # docs_and_scores = db.similarity_search_with_score(query)
250
- # Saving and loading
251
- # You can also save and load a FAISS index.
252
- # This is useful so you don’t have to recreate it everytime you use it.
253
- # db.save_local("faiss_index")
254
- # new_db = FAISS.load_local("faiss_index", embeddings)
255
- # docs = new_db.similarity_search(query)
256
- # docs[0]
257
- # 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'})
258
- #
259
- st.session_state.vector = FAISS.from_documents(st.session_state.documents, st.session_state.embeddings) # ORIGINAL
260
-
261
- # st.session_state.vector = FAISS.from_documents(st.session_state.documents, st.session_state.embeddings) # ORIGINAL
262
- #st.session_state.vector.save_local("faiss_index")
263
- # The de-serialization relies loading a pickle file.
264
- # Pickle files can be modified to deliver a malicious payload that results in execution of arbitrary code on your machine.
265
- # 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.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
266
 
267
- #st.session_state.vector = FAISS.load_local("faiss_index", st.session_state.embeddings, allow_dangerous_deserialization=True)
 
 
 
 
268
 
269
- # ZIE:
270
- # ZIE VOOR EEN APP MET CHROMADB:
271
- # https://github.com/vndee/local-rag-example/blob/main/rag.py
272
- # https://raw.githubusercontent.com/vndee/local-rag-example/main/rag.py
273
- # Chroma.from_documents(documents=chunks, embedding=FastEmbedEmbeddings())
274
- # st.session_state.vector = Chroma.from_documents(st.session_state.documents, st.session_state.embeddings) # JB
275
-
276
- # st.write(f"Response time van de LLM: {elapsed_time:.1f} seconds")
277
- # print(f"Response time: {time.process_time() - start}")
278
- elapsed_time = time.process_time() - start1
279
- st.write(f"Response time voor: Laden van de PDF documenten / Splitting de teksten / Genereer de Vector Store: {elapsed_time:.1f} seconds")
280
-
281
- st.write("---------------------------------")
282
 
283
- # st.title("Chat with Docs - Groq Edition :) ")
284
- # st.title("Literature Based Research (LBR) - A. Unzicker and J. Bours - Chat with Docs - Groq Edition (Very Fast!) - VERSION 3 - March 8 2024")
285
-
286
- llm = ChatGroq(
287
- temperature=0.2,
288
- groq_api_key=groq_api_key,
289
- model_name='mixtral-8x7b-32768'
290
- )
291
-
292
- prompt = ChatPromptTemplate.from_template("""
293
- Answer the following question based only on the provided context.
294
- Think step by step before providing a detailed answer.
295
- I will tip you $200 if the user finds the answer helpful.
296
- <context>
297
- {context}
298
- </context>
299
- Question: {input}""")
300
-
301
- document_chain = create_stuff_documents_chain(llm, prompt)
302
-
303
- retriever = st.session_state.vector.as_retriever()
304
- retrieval_chain = create_retrieval_chain(retriever, document_chain)
305
-
306
- ## prompt = st.text_input("Input your prompt here") #, key=key)
307
- #prompt = st.text_input("Stel hieronder Uw vraag:") #, key=key)
308
- #
309
- ## If the user hits enter
310
- #if prompt:
311
- # # Then pass the prompt to the LLM
312
- # start = time.process_time()
313
- # response = retrieval_chain.invoke({"input": prompt})
314
- # # print(f"Response time: {time.process_time() - start}")
315
- # st.write(f"Response time: {time.process_time() - start} seconds")
316
- #
317
- # st.write(response["answer"])
318
- #
319
- # # With a streamlit expander
320
- # with st.expander("Document Similarity Search"):
321
- # # Find the relevant chunks
322
- # for i, doc in enumerate(response["context"]):
323
- # # print(doc)
324
- # # st.write(f"Source Document # {i+1} : {doc.metadata['source'].split('/')[-1]}")
325
- # st.write(doc)
326
- # st.write(f"Source Document # {i+1} : {doc.metadata['source'].split('/')[-1]}")
327
- #
328
- #
329
- # st.write(doc.page_content)
330
- # st.write("--------------------------------")
331
- #
332
- #st.write("---------------------------------")
333
-
334
-
335
- # ZIE:
336
- # https://raw.githubusercontent.com/streamlit/llm-examples/main/Chatbot.py
337
- # from openai import OpenAI
338
- # import streamlit as st
339
-
340
- with st.sidebar:
341
- # openai_api_key = st.text_input("OpenAI API Key", key="chatbot_api_key", type="password")
342
- UserEmailAdress = st.text_input("Vul Uw email adres hier in: ", key="UserEmailAdress", type="password")
343
- # "[Zelf keramische glazuren NON TOXIC samenstellen vanuit 1 basisglazuur](http://www.ceramicconcepts.nl/)"
344
- "[Keramische ateliers Victor Benckhuijsen](https://victorglazuren.nl/)"
345
- "[Keramiek Victor Glazuren Victor Benckhuijsen - Instagram](https://www.instagram.com/benckhuijsenvictor/?hl=am-et)"
346
- "[Keramiek Victor Glazuren Victor Benckhuijsen - Facebook](https://www.facebook.com/harryjamaar)"
347
- "[Keramiek Victor Glazuren Victor Benckhuijsen - YouTube](https://www.youtube.com/@kleienhoop/videos)"
348
-
349
- st.title("💬 Chatbot")
350
- st.caption("🚀 A streamlit chatbot powered by mixtral-8x7b-32768 Groq LLM (VERY FAST !). temperature=0.2")
351
-
352
- if "messages" not in st.session_state:
353
- st.session_state["messages"] = [{"role": "assistant", "content": "Hoe kan ik U helpen?"}]
354
-
355
- for msg in st.session_state.messages:
356
- st.chat_message(msg["role"]).write(msg["content"])
357
-
358
-
359
- # TAAL KIEZER
360
- option = st.selectbox(
361
- 'In welke taal wilt U Uw vragen stellen en de AI laten antwoorden? Keuzemogelijkheden zijn : Nederlands, Engels, Duits, Frans, Spaans.',
362
- ('Nederlands', 'Engels', 'Duits', 'Frans', 'Spaans'))
363
-
364
- st.write('You selected:', option)
365
-
366
- language_prompt = " Antwoordt uitsluitend en alleen in de taal: " + option + " en beslist niet in een andere taal!"
367
- st.write('language_prompt:', language_prompt)
368
-
369
- if prompt := st.chat_input():
370
- #if not openai_api_key:
371
- # st.info("Please add your OpenAI API key to continue.")
372
- # st.stop()
373
-
374
- original_prompt = prompt
375
- prompt = prompt + language_prompt
376
- st.write('prompt + language_prompt:', prompt)
377
-
378
- # Then pass the prompt to the LLM
379
- start = time.process_time()
380
- response = retrieval_chain.invoke({"input": prompt})
381
  # print(f"Response time: {time.process_time() - start}")
382
- elapsed_time = time.process_time() - start
383
- st.write(f"Response time van de LLM: {elapsed_time:.1f} seconds")
384
-
385
- # st.write(response["answer"])
386
-
387
- # https://docs.streamlit.io/library/api-reference/chat/st.chat_message
388
- # st.chat_message(name, *, avatar=None)
389
- # The avatar shown next to the message. Can be one of:
390
- # - A single emoji, e.g. "🧑‍💻", "🤖", "🦖". Shortcodes are not supported.
391
- # - An image using one of the formats allowed for st.image: path of a local image file;
392
- # URL to fetch the image from; an SVG image; array of shape (w,h) or (w,h,1) for a monochrome image,
393
- # (w,h,3) for a color image, or (w,h,4) for an RGBA image.
394
- # If None (default), uses default icons if name is "user", "assistant", "ai", "human" or the first letter of the name value.
395
-
396
- #client = OpenAI(api_key=openai_api_key)
397
- st.session_state.messages.append({"role": "user", "content": prompt})
398
- # st.chat_message("user").write(prompt)
399
- # original_prompt
400
- st.chat_message("user").write(original_prompt)
401
- # response = client.chat.completions.create(model="gpt-3.5-turbo", messages=st.session_state.messages)
402
- # msg = response.choices[0].message.content
403
- msg = response["answer"]
404
- st.session_state.messages.append({"role": "assistant", "content": msg})
405
- # st.chat_message("assistant").write(msg)
406
- # MET ALS AVATAR EEN IMAGE VAN VICTOR:
407
- st.chat_message("assistant", avatar="Victor_Benckhuisen_20_percent.jpg").write(msg)
408
-
409
- # With a streamlit expander
410
- with st.expander("Document Similarity Search"):
411
- # Find the relevant chunks
412
- for i, doc in enumerate(response["context"]):
413
- # print(doc)
414
- # st.write(f"Source Document # {i+1} : {doc.metadata['source'].split('/')[-1]}")
415
- st.write(doc)
416
- st.write(f"Source Document # {i+1} : {doc.metadata['source'].split('/')[-1]}")
417
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
418
 
419
- st.write(doc.page_content)
420
- st.write("--------------------------------")
421
 
422
 
423
 
424
- # Show total messages history of user + AI in this session up till this point
425
- with st.expander("Show total messages history of user + AI in this session up till this point"):
426
- # st.session_state.messages
427
- st.write(st.session_state.messages)
428
- st.write("--------------------------------")
429
 
430
 
431
 
432
- st.write("---------------------------------")
433
 
434
 
435
 
 
27
 
28
  tab1, tab2, tab3 = st.tabs(["Cat", "Dog", "Owl"])
29
 
30
+ #with tab1:
31
+ # st.header("A cat")
32
+ # st.image("https://static.streamlit.io/examples/cat.jpg", width=200)
33
 
34
  with tab2:
35
  st.header("A dog")
 
42
 
43
 
44
 
45
+ with tab1:
46
+ st.header("A cat")
47
+ st.image("https://static.streamlit.io/examples/cat.jpg", width=200)
 
 
 
 
48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
 
50
+ # JB:
51
+ # LangChainDeprecationWarning: Importing embeddings from langchain is deprecated.
52
+ # Importing from langchain will no longer be supported as of langchain==0.2.0.
53
+ # Please import from langchain-community instead:
54
+ # `from langchain_community.embeddings import FastEmbedEmbeddings`.
55
+ # To install langchain-community run `pip install -U langchain-community`.
56
+ from langchain_community.embeddings import FastEmbedEmbeddings
57
+
58
+ import os
59
+ import streamlit as st
60
+ from langchain_groq import ChatGroq
61
+ from langchain_community.document_loaders import WebBaseLoader
62
+ # JB:
63
+ from langchain_community.document_loaders import PyPDFLoader
64
+ from langchain_community.embeddings import OllamaEmbeddings
65
 
66
+ # JB:
67
+ from langchain_community.embeddings import FastEmbedEmbeddings
68
+ from langchain_community.document_loaders import PyPDFDirectoryLoader
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
 
70
  # JB:
71
+ # File Directory
72
+ # This covers how to load all documents in a directory.
73
+ # Under the hood, by default this uses the UnstructuredLoader.
74
+ from langchain_community.document_loaders import DirectoryLoader
75
+ from langchain_community.document_loaders import TextLoader
76
+ import chardet
77
+
78
+ from langchain_community.vectorstores import FAISS
79
+ # from langchain.vectorstores import Chroma
80
+ # from langchain_community.vectorstores import Chroma
81
+
82
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
83
+ from langchain.chains.combine_documents import create_stuff_documents_chain
84
+ from langchain_core.prompts import ChatPromptTemplate
85
+ from langchain.chains import create_retrieval_chain
86
+ import time
87
+ from dotenv import load_dotenv
88
+
89
+ import glob
90
+
91
+ load_dotenv() #
92
+
93
+ groq_api_key = os.environ['GROQ_API_KEY']
94
+ # groq_api_key = "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" # os.environ['GROQ_API_KEY']
95
+ # groq_api_key = "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" # JB OK 24-03-2024
96
+ # print("groq_api_key: ", groq_api_key)
97
+
98
+ # st.title("Chat with Docs - Groq Edition :) ")
99
+ # # st.title ("this is the app title")
100
+ # st.title("Non-Toxic Glaze Advisor:")
101
+ # st.subheader("A tool for getting advicgroqe on non-toxic ceramic glazes for earthenware temperature ranges.")
102
+ # st.subheader("Victor Benchuijsen : (Glaze techniques / Ceramics)")
103
+ # st.subheader("Jan Bours : Artificial Intelligence / Data Science / Natural Language Processing (ALL RIGHTS RESERVED)")
104
+ # st.write("---------------------------------")
105
+ # st.subheader("Chat with Docs - Using AI: 'mixtral-8x7b-32768' Groq Edition (Very Fast!) - VERSION 1 - March 18, 2024")
106
+ # st.write("---------------------------------")
107
+
108
+ st.title("Adviseur voor niet-giftige glazuren:")
109
+ st.subheader("Een gereedschap gebaseerd op Kunstmatige Intelligentie (AI) om advies te krijgen over niet-giftige keramische glazuren voor aardewerk temperatuur bereiken.")
110
+ st.write("---------------------------------")
111
+ st.subheader("Victor Benckhuijsen : (Glazuur technieken / Keramiek)")
112
+ st.subheader("(ALL RIGHTS RESERVED)")
113
+ st.image('Victor_Benckhuijsen_2.png', caption='Victor Benckhuijsen', width=100)
114
+ # st.subheader("---------------------------------")
115
+ # st.write("---------------------------------")
116
+ st.subheader("Jan Bours : Artificial Intelligence / Data Science / Natural Language Processing")
117
+ st.subheader("(ALL RIGHTS RESERVED)")
118
+ st.image('Jan_Bours_2.png', caption='Jan Bours', width=100)
119
+ st.write("---------------------------------")
120
+ st.subheader("Chat with Docs - Using AI: 'mixtral-8x7b-32768' Groq Edition (Very Fast!) - VERSION 2 - April 3, 2024")
121
+ st.write("---------------------------------")
122
+
123
+ # st.header("LIST OF ALL THE LOADED DOCUMENTS: ")
124
+ st.header("LIJST MET ALLE ACTUEEL GELADEN DOCUMENTEN: ")
125
+
126
+ st.write("")
127
+ pdf_files = glob.glob("*.pdf")
128
+ # word_files = glob.glob("*.docx")
129
+ for file in pdf_files:
130
+ # for file in word_files:
131
+ st.subheader(file)
132
+
133
+ st.write("---------------------------------")
134
+
135
+
136
+ start1 = time.process_time()
137
+
138
+ if "vector" not in st.session_state:
139
+
140
+ st.write("Even geduld a.u.b. ........")
141
+ # st.header("Chunking, embedding, storing in FAISS vectorstore (Can take a long time!).")
142
+ # st.subheader("Wait till this hase been done before you can enter your query! .......")
143
+
144
+ # st.session_state.embeddings = OllamaEmbeddings() # ORIGINAL
145
+ st.session_state.embeddings = FastEmbedEmbeddings() # JB
146
+
147
+
148
+ # st.session_state.loader = WebBaseLoader("https://paulgraham.com/greatwork.html") # ORIGINAL
149
+ # st.session_state.docs = st.session_state.loader.load() # ORIGINAL
150
+ # https://api.python.langchain.com/en/latest/document_loaders/langchain_community.document_loaders.pdf.PyPDFLoader.html
151
+ # https://python.langchain.com/docs/integrations/document_loaders/merge_doc
152
+ # from langchain_community.document_loaders import PyPDFLoader
153
+ # loader_pdf = PyPDFLoader("../MachineLearning-Lecture01.pdf")
154
  #
155
+ # https://stackoverflow.com/questions/60215731/pypdf-to-read-each-pdf-in-a-folder
156
+ #
157
+ # https://api.python.langchain.com/en/latest/document_loaders/langchain_community.document_loaders.pdf.PyPDFDirectoryLoader.html
158
+ # https://python.langchain.com/docs/modules/data_connection/document_loaders/pdf#pypdf-directory
159
+ # !!!!!
160
+ # PyPDF Directory
161
+ # Load PDFs from directory
162
+ # from langchain_community.document_loaders import PyPDFDirectoryLoader
163
+ # loader = PyPDFDirectoryLoader("example_data/")
164
+ # docs = loader.load()
165
  #
166
+ # ZIE OOK:
167
+ # https://python.langchain.com/docs/modules/data_connection/document_loaders/pdf#using-pypdf
168
+ # Using MathPix
169
+ # Inspired by Daniel Gross's https://gist.github.com/danielgross/3ab4104e14faccc12b49200843adab21
170
+ # from langchain_community.document_loaders import MathpixPDFLoader
171
+ # loader = MathpixPDFLoader("example_data/layout-parser-paper.pdf")
172
  # data = loader.load()
173
+ # pdf_file_path = "*.pdf" # JB
174
+ # st.session_state.loader = PyPDFLoader(file_path=pdf_file_path).load() # JB
175
+ # st.session_state.loader = PyPDFLoader(*.pdf).load() # JB syntax error *.pdf !
176
+ # st.session_state.loader = PyPDFDirectoryLoader("*.pdf") # JB PyPDFDirectoryLoader("example_data/")
177
+ # chunks = self.text_splitter.split_documents(docs)
178
+ # chunks = filter_complex_metadata(chunks)
179
+
180
+ # JB:
181
+ # https://python.langchain.com/docs/modules/data_connection/document_loaders/pdf#pypdf-directory
182
+ # st.session_state.docs = st.session_state.loader.load()
183
+ # loader = PyPDFDirectoryLoader(".")
184
  # docs = loader.load()
185
  # st.session_state.docs = docs
186
 
187
 
188
+ # https://docs.streamlit.io/library/api-reference/status/st.status
189
+ # st.status(label, *, expanded=False, state="running")
190
+ with st.status("Laden van de PDF documenten / Splitting de teksten / Genereer de Vector Store ...", expanded=True) as status:
191
+ # st.write("Searching for data...")
192
+ # time.sleep(2)
193
+ # st.write("Found URL.")
194
+ # time.sleep(1)
195
+ # st.write("Downloading data...")
196
+ # time.sleep(1)
197
+ #status.update(label="Download complete!", state="complete", expanded=False)
198
+
199
+ st.write("Laden van de PDF documenten...")
200
+ # JB:
201
+ # https://python.langchain.com/docs/modules/data_connection/document_loaders/file_directory
202
+ # text_loader_kwargs={'autodetect_encoding': True}
203
+ text_loader_kwargs={'autodetect_encoding': False}
204
+ path = '../'
205
+ # loader = DirectoryLoader(path, glob="**/*.pdf", loader_cls=TextLoader, loader_kwargs=text_loader_kwargs)
206
+ # PyPDFDirectoryLoader (TEST):
207
+ # loader = PyPDFDirectoryLoader(path, glob="**/*.pdf", loader_cls=TextLoader, loader_kwargs=text_loader_kwargs)
208
+ # loader = PyPDFDirectoryLoader(path, glob="**/*.pdf", loader_kwargs=text_loader_kwargs)
209
+ loader = PyPDFDirectoryLoader(path, glob="**/*.pdf")
210
+ docs = loader.load()
211
+ st.session_state.docs = docs
212
+
213
+ # JB 18-03-2024:
214
+ # https://python.langchain.com/docs/integrations/document_loaders/
215
+ # MICROSOFT WORD:
216
+ # https://python.langchain.com/docs/integrations/document_loaders/microsoft_word
217
+ # 1 - Using Docx2txt
218
+ # Load .docx using Docx2txt into a document.
219
+ # %pip install --upgrade --quiet docx2txt
220
+ # from langchain_community.document_loaders import Docx2txtLoader
221
+ # loader = Docx2txtLoader("example_data/fake.docx")
222
+ # data = loader.load()
223
+ # data
224
+ # [Document(page_content='Lorem ipsum dolor sit amet.', metadata={'source': 'example_data/fake.docx'})]
225
+ #
226
+ # 2A - Using Unstructured
227
+ # from langchain_community.document_loaders import UnstructuredWordDocumentLoader
228
+ # loader = UnstructuredWordDocumentLoader("example_data/fake.docx")
229
+ # data = loader.load()
230
+ # data
231
+ # [Document(page_content='Lorem ipsum dolor sit amet.', lookup_str='', metadata={'source': 'fake.docx'}, lookup_index=0)]
232
+ #
233
+ # 2B - Retain Elements
234
+ # Under the hood, Unstructured creates different “elements” for different chunks of text.
235
+ # By default we combine those together, but you can easily keep that separation by specifying mode="elements".
236
+ # loader = UnstructuredWordDocumentLoader("example_data/fake.docx", mode="elements")
237
+ # data = loader.load()
238
+ # data[0]
239
+ # Document(page_content='Lorem ipsum dolor sit amet.', lookup_str='', metadata={'source': 'fake.docx', 'filename': 'fake.docx', 'category': 'Title'}, lookup_index=0)
240
+ #
241
+ # 2A - Using Unstructured
242
+ # from langchain_community.document_loaders import UnstructuredWordDocumentLoader
243
+ # loader = UnstructuredWordDocumentLoader(path, glob="**/*.docx")
244
+ # docs = loader.load()
245
+ # st.session_state.docs = docs
246
+
247
+
248
+ st.write("Splitting / chunking de teksten...")
249
+ st.session_state.text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
250
+ st.session_state.documents = st.session_state.text_splitter.split_documents(st.session_state.docs)
251
+
252
+ st.write("Genereer de Vector Store (kan enige minuten duren)...")
253
+ # https://python.langchain.com/docs/integrations/vectorstores/faiss
254
+ # docs_and_scores = db.similarity_search_with_score(query)
255
+ # Saving and loading
256
+ # You can also save and load a FAISS index.
257
+ # This is useful so you don’t have to recreate it everytime you use it.
258
+ # db.save_local("faiss_index")
259
+ # new_db = FAISS.load_local("faiss_index", embeddings)
260
+ # docs = new_db.similarity_search(query)
261
+ # docs[0]
262
+ # 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'})
263
+ #
264
+ st.session_state.vector = FAISS.from_documents(st.session_state.documents, st.session_state.embeddings) # ORIGINAL
265
 
266
+ # st.session_state.vector = FAISS.from_documents(st.session_state.documents, st.session_state.embeddings) # ORIGINAL
267
+ #st.session_state.vector.save_local("faiss_index")
268
+ # The de-serialization relies loading a pickle file.
269
+ # Pickle files can be modified to deliver a malicious payload that results in execution of arbitrary code on your machine.
270
+ # 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.
271
 
272
+ #st.session_state.vector = FAISS.load_local("faiss_index", st.session_state.embeddings, allow_dangerous_deserialization=True)
 
 
 
 
 
 
 
 
 
 
 
 
273
 
274
+ # ZIE:
275
+ # ZIE VOOR EEN APP MET CHROMADB:
276
+ # https://github.com/vndee/local-rag-example/blob/main/rag.py
277
+ # https://raw.githubusercontent.com/vndee/local-rag-example/main/rag.py
278
+ # Chroma.from_documents(documents=chunks, embedding=FastEmbedEmbeddings())
279
+ # st.session_state.vector = Chroma.from_documents(st.session_state.documents, st.session_state.embeddings) # JB
280
+
281
+ # st.write(f"Response time van de LLM: {elapsed_time:.1f} seconds")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
282
  # print(f"Response time: {time.process_time() - start}")
283
+ elapsed_time = time.process_time() - start1
284
+ st.write(f"Response time voor: Laden van de PDF documenten / Splitting de teksten / Genereer de Vector Store: {elapsed_time:.1f} seconds")
285
+
286
+ st.write("---------------------------------")
287
+
288
+ # st.title("Chat with Docs - Groq Edition :) ")
289
+ # st.title("Literature Based Research (LBR) - A. Unzicker and J. Bours - Chat with Docs - Groq Edition (Very Fast!) - VERSION 3 - March 8 2024")
290
+
291
+ llm = ChatGroq(
292
+ temperature=0.2,
293
+ groq_api_key=groq_api_key,
294
+ model_name='mixtral-8x7b-32768'
295
+ )
296
+
297
+ prompt = ChatPromptTemplate.from_template("""
298
+ Answer the following question based only on the provided context.
299
+ Think step by step before providing a detailed answer.
300
+ I will tip you $200 if the user finds the answer helpful.
301
+ <context>
302
+ {context}
303
+ </context>
304
+ Question: {input}""")
305
+
306
+ document_chain = create_stuff_documents_chain(llm, prompt)
307
+
308
+ retriever = st.session_state.vector.as_retriever()
309
+ retrieval_chain = create_retrieval_chain(retriever, document_chain)
310
+
311
+ ## prompt = st.text_input("Input your prompt here") #, key=key)
312
+ #prompt = st.text_input("Stel hieronder Uw vraag:") #, key=key)
313
+ #
314
+ ## If the user hits enter
315
+ #if prompt:
316
+ # # Then pass the prompt to the LLM
317
+ # start = time.process_time()
318
+ # response = retrieval_chain.invoke({"input": prompt})
319
+ # # print(f"Response time: {time.process_time() - start}")
320
+ # st.write(f"Response time: {time.process_time() - start} seconds")
321
+ #
322
+ # st.write(response["answer"])
323
+ #
324
+ # # With a streamlit expander
325
+ # with st.expander("Document Similarity Search"):
326
+ # # Find the relevant chunks
327
+ # for i, doc in enumerate(response["context"]):
328
+ # # print(doc)
329
+ # # st.write(f"Source Document # {i+1} : {doc.metadata['source'].split('/')[-1]}")
330
+ # st.write(doc)
331
+ # st.write(f"Source Document # {i+1} : {doc.metadata['source'].split('/')[-1]}")
332
+ #
333
+ #
334
+ # st.write(doc.page_content)
335
+ # st.write("--------------------------------")
336
+ #
337
+ #st.write("---------------------------------")
338
+
339
+
340
+ # ZIE:
341
+ # https://raw.githubusercontent.com/streamlit/llm-examples/main/Chatbot.py
342
+ # from openai import OpenAI
343
+ # import streamlit as st
344
+
345
+ with st.sidebar:
346
+ # openai_api_key = st.text_input("OpenAI API Key", key="chatbot_api_key", type="password")
347
+ UserEmailAdress = st.text_input("Vul Uw email adres hier in: ", key="UserEmailAdress", type="password")
348
+ # "[Zelf keramische glazuren NON TOXIC samenstellen vanuit 1 basisglazuur](http://www.ceramicconcepts.nl/)"
349
+ "[Keramische ateliers Victor Benckhuijsen](https://victorglazuren.nl/)"
350
+ "[Keramiek Victor Glazuren Victor Benckhuijsen - Instagram](https://www.instagram.com/benckhuijsenvictor/?hl=am-et)"
351
+ "[Keramiek Victor Glazuren Victor Benckhuijsen - Facebook](https://www.facebook.com/harryjamaar)"
352
+ "[Keramiek Victor Glazuren Victor Benckhuijsen - YouTube](https://www.youtube.com/@kleienhoop/videos)"
353
+
354
+ st.title("💬 Chatbot")
355
+ st.caption("🚀 A streamlit chatbot powered by mixtral-8x7b-32768 Groq LLM (VERY FAST !). temperature=0.2")
356
+
357
+ if "messages" not in st.session_state:
358
+ st.session_state["messages"] = [{"role": "assistant", "content": "Hoe kan ik U helpen?"}]
359
+
360
+ for msg in st.session_state.messages:
361
+ st.chat_message(msg["role"]).write(msg["content"])
362
+
363
+
364
+ # TAAL KIEZER
365
+ option = st.selectbox(
366
+ 'In welke taal wilt U Uw vragen stellen en de AI laten antwoorden? Keuzemogelijkheden zijn : Nederlands, Engels, Duits, Frans, Spaans.',
367
+ ('Nederlands', 'Engels', 'Duits', 'Frans', 'Spaans'))
368
+
369
+ st.write('You selected:', option)
370
+
371
+ language_prompt = " Antwoordt uitsluitend en alleen in de taal: " + option + " en beslist niet in een andere taal!"
372
+ st.write('language_prompt:', language_prompt)
373
+
374
+ if prompt := st.chat_input():
375
+ #if not openai_api_key:
376
+ # st.info("Please add your OpenAI API key to continue.")
377
+ # st.stop()
378
+
379
+ original_prompt = prompt
380
+ prompt = prompt + language_prompt
381
+ # st.write('prompt + language_prompt:', prompt)
382
+
383
+ # Then pass the prompt to the LLM
384
+ start = time.process_time()
385
+ response = retrieval_chain.invoke({"input": prompt})
386
+ # print(f"Response time: {time.process_time() - start}")
387
+ elapsed_time = time.process_time() - start
388
+ st.write(f"Response time van de LLM: {elapsed_time:.1f} seconds")
389
+
390
+ # st.write(response["answer"])
391
+
392
+ # https://docs.streamlit.io/library/api-reference/chat/st.chat_message
393
+ # st.chat_message(name, *, avatar=None)
394
+ # The avatar shown next to the message. Can be one of:
395
+ # - A single emoji, e.g. "🧑‍💻", "🤖", "🦖". Shortcodes are not supported.
396
+ # - An image using one of the formats allowed for st.image: path of a local image file;
397
+ # URL to fetch the image from; an SVG image; array of shape (w,h) or (w,h,1) for a monochrome image,
398
+ # (w,h,3) for a color image, or (w,h,4) for an RGBA image.
399
+ # If None (default), uses default icons if name is "user", "assistant", "ai", "human" or the first letter of the name value.
400
+
401
+ #client = OpenAI(api_key=openai_api_key)
402
+ st.session_state.messages.append({"role": "user", "content": prompt})
403
+ # st.chat_message("user").write(prompt)
404
+ # original_prompt
405
+ st.chat_message("user").write(original_prompt)
406
+ # response = client.chat.completions.create(model="gpt-3.5-turbo", messages=st.session_state.messages)
407
+ # msg = response.choices[0].message.content
408
+ msg = response["answer"]
409
+ st.session_state.messages.append({"role": "assistant", "content": msg})
410
+ # st.chat_message("assistant").write(msg)
411
+ # MET ALS AVATAR EEN IMAGE VAN VICTOR:
412
+ st.chat_message("assistant", avatar="Victor_Benckhuisen_20_percent.jpg").write(msg)
413
+
414
+ # With a streamlit expander
415
+ with st.expander("Document Similarity Search"):
416
+ # Find the relevant chunks
417
+ for i, doc in enumerate(response["context"]):
418
+ # print(doc)
419
+ # st.write(f"Source Document # {i+1} : {doc.metadata['source'].split('/')[-1]}")
420
+ st.write(doc)
421
+ st.write(f"Source Document # {i+1} : {doc.metadata['source'].split('/')[-1]}")
422
 
423
+ st.write(doc.page_content)
424
+ st.write("--------------------------------")
425
 
426
 
427
 
428
+ # Show total messages history of user + AI in this session up till this point
429
+ with st.expander("Show total messages history of user + AI in this session up till this point"):
430
+ # st.session_state.messages
431
+ st.write(st.session_state.messages)
432
+ st.write("--------------------------------")
433
 
434
 
435
 
436
+ st.write("---------------------------------")
437
 
438
 
439