DeepSoft-Tech commited on
Commit
e4cd0b9
β€’
1 Parent(s): 324e211

Upload 3 files

Browse files
Files changed (3) hide show
  1. app.py +117 -0
  2. htmlTemplates.py +44 -0
  3. requirements.txt +16 -0
app.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import streamlit as st
3
+ from dotenv import load_dotenv
4
+ from PyPDF2 import PdfReader
5
+ from langchain.text_splitter import CharacterTextSplitter
6
+ from langchain.embeddings import HuggingFaceBgeEmbeddings
7
+ from langchain.vectorstores import FAISS
8
+ from langchain.chat_models import ChatOpenAI
9
+ from langchain.memory import ConversationBufferMemory
10
+ from langchain.chains import ConversationalRetrievalChain
11
+ from htmlTemplates import css, bot_template, user_template
12
+ from langchain.llms import HuggingFaceHub
13
+
14
+ # set this key as an environment variable
15
+ os.environ["HUGGINGFACEHUB_API_TOKEN"] = st.secrets['huggingface_token']
16
+
17
+ def get_pdf_text(pdf_docs : list) -> str:
18
+ text = ""
19
+ for pdf in pdf_docs:
20
+ pdf_reader = PdfReader(pdf)
21
+ for page in pdf_reader.pages:
22
+ text += page.extract_text()
23
+ return text
24
+
25
+
26
+ def get_text_chunks(text:str) ->list:
27
+ text_splitter = CharacterTextSplitter(
28
+ separator="\n", chunk_size=1500, chunk_overlap=300, length_function=len
29
+ )
30
+ chunks = text_splitter.split_text(text)
31
+ return chunks
32
+
33
+
34
+ def get_vectorstore(text_chunks : list) -> FAISS:
35
+ model = "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2"
36
+ encode_kwargs = {
37
+ "normalize_embeddings": True
38
+ } # set True to compute cosine similarity
39
+ embeddings = HuggingFaceBgeEmbeddings(
40
+ model_name=model, encode_kwargs=encode_kwargs, model_kwargs={"device": "cpu"}
41
+ )
42
+ vectorstore = FAISS.from_texts(texts=text_chunks, embedding=embeddings)
43
+ return vectorstore
44
+
45
+
46
+ def get_conversation_chain(vectorstore:FAISS) -> ConversationalRetrievalChain:
47
+ # llm = ChatOpenAI(temperature=0, model="gpt-3.5-turbo-0613")
48
+ llm = HuggingFaceHub(
49
+ repo_id="mistralai/Mixtral-8x7B-Instruct-v0.1",
50
+ #repo_id="TheBloke/Mixtral-8x7B-Instruct-v0.1-GGUF"
51
+ model_kwargs={"temperature": 0.5, "max_length": 1048},
52
+ )
53
+
54
+ memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
55
+ conversation_chain = ConversationalRetrievalChain.from_llm(
56
+ llm=llm, retriever=vectorstore.as_retriever(), memory=memory
57
+ )
58
+ return conversation_chain
59
+
60
+
61
+ def handle_userinput(user_question:str):
62
+ response = st.session_state.conversation({"question": user_question})
63
+ st.session_state.chat_history = response["chat_history"]
64
+
65
+ for i, message in enumerate(st.session_state.chat_history):
66
+ if i % 2 == 0:
67
+ st.write(" Usuario: " + message.content)
68
+ else:
69
+ st.write("πŸ€– ChatBot: " + message.content)
70
+
71
+
72
+ def main():
73
+ st.set_page_config(
74
+ page_title="Chat with a Bot that tries to answer questions about multiple PDFs",
75
+ page_icon=":books:",
76
+ )
77
+
78
+ st.markdown("# Chat with a Bot")
79
+ st.markdown("This bot tries to answer questions about multiple PDFs. Let the processing of the PDF finish before adding your question. πŸ™πŸΎ")
80
+
81
+ st.write(css, unsafe_allow_html=True)
82
+
83
+
84
+ if "conversation" not in st.session_state:
85
+ st.session_state.conversation = None
86
+ if "chat_history" not in st.session_state:
87
+ st.session_state.chat_history = None
88
+
89
+
90
+ st.header("Chat with a Bot πŸ€–πŸ¦Ύ that tries to answer questions about multiple PDFs :books:")
91
+ user_question = st.text_input("Ask a question about your documents:")
92
+ if user_question:
93
+ handle_userinput(user_question)
94
+
95
+
96
+ with st.sidebar:
97
+ st.subheader("Your documents")
98
+ pdf_docs = st.file_uploader(
99
+ "Upload your PDFs here and click on 'Process'", accept_multiple_files=True
100
+ )
101
+ if st.button("Process"):
102
+ with st.spinner("Processing"):
103
+ # get pdf text
104
+ raw_text = get_pdf_text(pdf_docs)
105
+
106
+ # get the text chunks
107
+ text_chunks = get_text_chunks(raw_text)
108
+
109
+ # create vector store
110
+ vectorstore = get_vectorstore(text_chunks)
111
+
112
+ # create conversation chain
113
+ st.session_state.conversation = get_conversation_chain(vectorstore)
114
+
115
+
116
+ if __name__ == "__main__":
117
+ main()
htmlTemplates.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ css = """
2
+ <style>
3
+ .chat-message {
4
+ padding: 1.5rem; border-radius: 0.5rem; margin-bottom: 1rem; display: flex
5
+ }
6
+ .chat-message.user {
7
+ background-color: #2b313e
8
+ }
9
+ .chat-message.bot {
10
+ background-color: #475063
11
+ }
12
+ .chat-message .avatar {
13
+ width: 20%;
14
+ }
15
+ .chat-message .avatar img {
16
+ max-width: 78px;
17
+ max-height: 78px;
18
+ border-radius: 50%;
19
+ object-fit: cover;
20
+ }
21
+ .chat-message .message {
22
+ width: 80%;
23
+ padding: 0 1.5rem;
24
+ color: #fff;
25
+ }
26
+ """
27
+
28
+ bot_template = """
29
+ <div class="chat-message bot">
30
+ <div class="avatar">
31
+ <img src="https://i.ibb.co/cN0nmSj/Screenshot-2023-05-28-at-02-37-21.png" style="max-height: 78px; max-width: 78px; border-radius: 50%; object-fit: cover;">
32
+ </div>
33
+ <div class="message">{{MSG}}</div>
34
+ </div>
35
+ """
36
+
37
+ user_template = """
38
+ <div class="chat-message user">
39
+ <div class="avatar">
40
+ <img src="https://i.ibb.co/rdZC7LZ/Photo-logo-1.png">
41
+ </div>
42
+ <div class="message">{{MSG}}</div>
43
+ </div>
44
+ """
requirements.txt ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ langchain==0.0.335
2
+ PyPDF2==3.0.1
3
+ python-dotenv==1.0.0
4
+ streamlit==1.28.2
5
+ openai==1.2.4
6
+ faiss-cpu==1.7.4
7
+ altair==5.1.2
8
+ tiktoken==0.5.1
9
+ black==23.11.0
10
+ # uncomment to use huggingface llms
11
+ huggingface-hub==0.17.3
12
+
13
+ # uncomment to use instructor embeddings
14
+ InstructorEmbedding==1.0.1
15
+ sentence-transformers==2.2.2
16
+ transformers