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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# app.py - 25-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.header("LIST OF ALL THE LOADED DOCUMENTS: ")
|
83 |
+
st.write("")
|
84 |
+
pdf_files = glob.glob("*.pdf")
|
85 |
+
# word_files = glob.glob("*.docx")
|
86 |
+
for file in pdf_files:
|
87 |
+
# for file in word_files:
|
88 |
+
st.subheader(file)
|
89 |
+
|
90 |
+
st.write("---------------------------------")
|
91 |
+
|
92 |
+
if "vector" not in st.session_state:
|
93 |
+
|
94 |
+
st.header("Chunking, embedding, storing in FAISS vectorstore (Can take a long time!).")
|
95 |
+
st.subheader("Wait till this hase been done before you can enter your query! .......")
|
96 |
+
|
97 |
+
# st.session_state.embeddings = OllamaEmbeddings() # ORIGINAL
|
98 |
+
st.session_state.embeddings = FastEmbedEmbeddings() # JB
|
99 |
+
|
100 |
+
|
101 |
+
# st.session_state.loader = WebBaseLoader("https://paulgraham.com/greatwork.html") # ORIGINAL
|
102 |
+
# st.session_state.docs = st.session_state.loader.load() # ORIGINAL
|
103 |
+
# https://api.python.langchain.com/en/latest/document_loaders/langchain_community.document_loaders.pdf.PyPDFLoader.html
|
104 |
+
# https://python.langchain.com/docs/integrations/document_loaders/merge_doc
|
105 |
+
# from langchain_community.document_loaders import PyPDFLoader
|
106 |
+
# loader_pdf = PyPDFLoader("../MachineLearning-Lecture01.pdf")
|
107 |
+
#
|
108 |
+
# https://stackoverflow.com/questions/60215731/pypdf-to-read-each-pdf-in-a-folder
|
109 |
+
#
|
110 |
+
# https://api.python.langchain.com/en/latest/document_loaders/langchain_community.document_loaders.pdf.PyPDFDirectoryLoader.html
|
111 |
+
# https://python.langchain.com/docs/modules/data_connection/document_loaders/pdf#pypdf-directory
|
112 |
+
# !!!!!
|
113 |
+
# PyPDF Directory
|
114 |
+
# Load PDFs from directory
|
115 |
+
# from langchain_community.document_loaders import PyPDFDirectoryLoader
|
116 |
+
# loader = PyPDFDirectoryLoader("example_data/")
|
117 |
+
# docs = loader.load()
|
118 |
+
#
|
119 |
+
# ZIE OOK:
|
120 |
+
# https://python.langchain.com/docs/modules/data_connection/document_loaders/pdf#using-pypdf
|
121 |
+
# Using MathPix
|
122 |
+
# Inspired by Daniel Gross's https://gist.github.com/danielgross/3ab4104e14faccc12b49200843adab21
|
123 |
+
# from langchain_community.document_loaders import MathpixPDFLoader
|
124 |
+
# loader = MathpixPDFLoader("example_data/layout-parser-paper.pdf")
|
125 |
+
# data = loader.load()
|
126 |
+
# pdf_file_path = "*.pdf" # JB
|
127 |
+
# st.session_state.loader = PyPDFLoader(file_path=pdf_file_path).load() # JB
|
128 |
+
# st.session_state.loader = PyPDFLoader(*.pdf).load() # JB syntax error *.pdf !
|
129 |
+
# st.session_state.loader = PyPDFDirectoryLoader("*.pdf") # JB PyPDFDirectoryLoader("example_data/")
|
130 |
+
# chunks = self.text_splitter.split_documents(docs)
|
131 |
+
# chunks = filter_complex_metadata(chunks)
|
132 |
+
|
133 |
+
# JB:
|
134 |
+
# https://python.langchain.com/docs/modules/data_connection/document_loaders/pdf#pypdf-directory
|
135 |
+
# st.session_state.docs = st.session_state.loader.load()
|
136 |
+
# loader = PyPDFDirectoryLoader(".")
|
137 |
+
# docs = loader.load()
|
138 |
+
# st.session_state.docs = docs
|
139 |
+
|
140 |
+
# JB:
|
141 |
+
# https://python.langchain.com/docs/modules/data_connection/document_loaders/file_directory
|
142 |
+
# text_loader_kwargs={'autodetect_encoding': True}
|
143 |
+
text_loader_kwargs={'autodetect_encoding': False}
|
144 |
+
path = '../'
|
145 |
+
# loader = DirectoryLoader(path, glob="**/*.pdf", loader_cls=TextLoader, loader_kwargs=text_loader_kwargs)
|
146 |
+
# PyPDFDirectoryLoader (TEST):
|
147 |
+
# loader = PyPDFDirectoryLoader(path, glob="**/*.pdf", loader_cls=TextLoader, loader_kwargs=text_loader_kwargs)
|
148 |
+
# loader = PyPDFDirectoryLoader(path, glob="**/*.pdf", loader_kwargs=text_loader_kwargs)
|
149 |
+
loader = PyPDFDirectoryLoader(path, glob="**/*.pdf")
|
150 |
+
docs = loader.load()
|
151 |
+
st.session_state.docs = docs
|
152 |
+
|
153 |
+
# JB 18-03-2024:
|
154 |
+
# https://python.langchain.com/docs/integrations/document_loaders/
|
155 |
+
# MICROSOFT WORD:
|
156 |
+
# https://python.langchain.com/docs/integrations/document_loaders/microsoft_word
|
157 |
+
# 1 - Using Docx2txt
|
158 |
+
# Load .docx using Docx2txt into a document.
|
159 |
+
# %pip install --upgrade --quiet docx2txt
|
160 |
+
# from langchain_community.document_loaders import Docx2txtLoader
|
161 |
+
# loader = Docx2txtLoader("example_data/fake.docx")
|
162 |
+
# data = loader.load()
|
163 |
+
# data
|
164 |
+
# [Document(page_content='Lorem ipsum dolor sit amet.', metadata={'source': 'example_data/fake.docx'})]
|
165 |
+
#
|
166 |
+
# 2A - Using Unstructured
|
167 |
+
# from langchain_community.document_loaders import UnstructuredWordDocumentLoader
|
168 |
+
# loader = UnstructuredWordDocumentLoader("example_data/fake.docx")
|
169 |
+
# data = loader.load()
|
170 |
+
# data
|
171 |
+
# [Document(page_content='Lorem ipsum dolor sit amet.', lookup_str='', metadata={'source': 'fake.docx'}, lookup_index=0)]
|
172 |
+
#
|
173 |
+
# 2B - Retain Elements
|
174 |
+
# Under the hood, Unstructured creates different “elements” for different chunks of text.
|
175 |
+
# By default we combine those together, but you can easily keep that separation by specifying mode="elements".
|
176 |
+
# loader = UnstructuredWordDocumentLoader("example_data/fake.docx", mode="elements")
|
177 |
+
# data = loader.load()
|
178 |
+
# data[0]
|
179 |
+
# Document(page_content='Lorem ipsum dolor sit amet.', lookup_str='', metadata={'source': 'fake.docx', 'filename': 'fake.docx', 'category': 'Title'}, lookup_index=0)
|
180 |
+
#
|
181 |
+
# 2A - Using Unstructured
|
182 |
+
# from langchain_community.document_loaders import UnstructuredWordDocumentLoader
|
183 |
+
# loader = UnstructuredWordDocumentLoader(path, glob="**/*.docx")
|
184 |
+
# docs = loader.load()
|
185 |
+
# st.session_state.docs = docs
|
186 |
+
|
187 |
+
|
188 |
+
|
189 |
+
|
190 |
+
st.session_state.text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
|
191 |
+
st.session_state.documents = st.session_state.text_splitter.split_documents(st.session_state.docs)
|
192 |
+
# https://python.langchain.com/docs/integrations/vectorstores/faiss
|
193 |
+
# docs_and_scores = db.similarity_search_with_score(query)
|
194 |
+
# Saving and loading
|
195 |
+
# You can also save and load a FAISS index.
|
196 |
+
# This is useful so you don’t have to recreate it everytime you use it.
|
197 |
+
# db.save_local("faiss_index")
|
198 |
+
# new_db = FAISS.load_local("faiss_index", embeddings)
|
199 |
+
# docs = new_db.similarity_search(query)
|
200 |
+
# docs[0]
|
201 |
+
# 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'})
|
202 |
+
#
|
203 |
+
st.session_state.vector = FAISS.from_documents(st.session_state.documents, st.session_state.embeddings) # ORIGINAL
|
204 |
+
|
205 |
+
# st.session_state.vector = FAISS.from_documents(st.session_state.documents, st.session_state.embeddings) # ORIGINAL
|
206 |
+
#st.session_state.vector.save_local("faiss_index")
|
207 |
+
# The de-serialization relies loading a pickle file.
|
208 |
+
# Pickle files can be modified to deliver a malicious payload that results in execution of arbitrary code on your machine.
|
209 |
+
# 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.
|
210 |
+
|
211 |
+
#st.session_state.vector = FAISS.load_local("faiss_index", st.session_state.embeddings, allow_dangerous_deserialization=True)
|
212 |
+
|
213 |
+
# ZIE:
|
214 |
+
# ZIE VOOR EEN APP MET CHROMADB:
|
215 |
+
# https://github.com/vndee/local-rag-example/blob/main/rag.py
|
216 |
+
# https://raw.githubusercontent.com/vndee/local-rag-example/main/rag.py
|
217 |
+
# Chroma.from_documents(documents=chunks, embedding=FastEmbedEmbeddings())
|
218 |
+
# st.session_state.vector = Chroma.from_documents(st.session_state.documents, st.session_state.embeddings) # JB
|
219 |
+
|
220 |
+
st.write("---------------------------------")
|
221 |
+
|
222 |
+
# st.title("Chat with Docs - Groq Edition :) ")
|
223 |
+
# st.title("Literature Based Research (LBR) - A. Unzicker and J. Bours - Chat with Docs - Groq Edition (Very Fast!) - VERSION 3 - March 8 2024")
|
224 |
+
|
225 |
+
llm = ChatGroq(
|
226 |
+
temperature=0.2,
|
227 |
+
groq_api_key=groq_api_key,
|
228 |
+
model_name='mixtral-8x7b-32768'
|
229 |
+
)
|
230 |
+
|
231 |
+
prompt = ChatPromptTemplate.from_template("""
|
232 |
+
Answer the following question based only on the provided context.
|
233 |
+
Think step by step before providing a detailed answer.
|
234 |
+
I will tip you $200 if the user finds the answer helpful.
|
235 |
+
<context>
|
236 |
+
{context}
|
237 |
+
</context>
|
238 |
+
Question: {input}""")
|
239 |
+
|
240 |
+
document_chain = create_stuff_documents_chain(llm, prompt)
|
241 |
+
|
242 |
+
retriever = st.session_state.vector.as_retriever()
|
243 |
+
retrieval_chain = create_retrieval_chain(retriever, document_chain)
|
244 |
+
|
245 |
+
prompt = st.text_input("Input your prompt here")
|
246 |
+
|
247 |
+
|
248 |
+
# If the user hits enter
|
249 |
+
if prompt:
|
250 |
+
# Then pass the prompt to the LLM
|
251 |
+
start = time.process_time()
|
252 |
+
response = retrieval_chain.invoke({"input": prompt})
|
253 |
+
# print(f"Response time: {time.process_time() - start}")
|
254 |
+
st.write(f"Response time: {time.process_time() - start} seconds")
|
255 |
+
|
256 |
+
st.write(response["answer"])
|
257 |
+
|
258 |
+
# With a streamlit expander
|
259 |
+
with st.expander("Document Similarity Search"):
|
260 |
+
# Find the relevant chunks
|
261 |
+
for i, doc in enumerate(response["context"]):
|
262 |
+
# print(doc)
|
263 |
+
# st.write(f"Source Document # {i+1} : {doc.metadata['source'].split('/')[-1]}")
|
264 |
+
st.write(doc)
|
265 |
+
st.write(f"Source Document # {i+1} : {doc.metadata['source'].split('/')[-1]}")
|
266 |
+
|
267 |
+
|
268 |
+
st.write(doc.page_content)
|
269 |
+
st.write("--------------------------------")
|
270 |
+
|
271 |
+
st.write("---------------------------------")
|