testcolab2 commited on
Commit
8884a50
·
verified ·
1 Parent(s): c250b93

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +167 -0
app.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langchain_community.document_loaders import DirectoryLoader
2
+ from langchain_community.document_loaders import PyPDFLoader
3
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
4
+ from langchain.text_splitter import CharacterTextSplitter
5
+ from langchain_community.vectorstores import FAISS
6
+ from langchain_community.embeddings.huggingface import HuggingFaceEmbeddings
7
+ from langchain.chains import ConversationChain
8
+ from langchain.memory import ConversationBufferMemory
9
+ from langchain.chains import (
10
+ StuffDocumentsChain, LLMChain, ConversationalRetrievalChain
11
+ )
12
+ from langchain_core.prompts import PromptTemplate
13
+ import streamlit as st
14
+ from PyPDF2 import PdfReader
15
+
16
+ css = '''
17
+ <style>
18
+ .chat-message {
19
+ padding: 1.5rem; border-radius: 0.5rem; margin-bottom: 1rem; display: flex
20
+ }
21
+ .chat-message.user {
22
+ background-color: #2b313e
23
+ }
24
+ .chat-message.bot {
25
+ background-color: #475063
26
+ }
27
+ .chat-message .avatar {
28
+ width: 20%;
29
+ }
30
+ .chat-message .avatar img {
31
+ max-width: 78px;
32
+ max-height: 78px;
33
+ border-radius: 50%;
34
+ object-fit: cover;
35
+ }
36
+ .chat-message .message {
37
+ width: 80%;
38
+ padding: 0 1.5rem;
39
+ color: #fff;
40
+ }
41
+ '''
42
+
43
+ bot_template = '''
44
+ <div class="chat-message bot">
45
+ <div class="avatar">
46
+ <img src="https://i.ibb.co/cN0nmSj/Screenshot-2023-05-28-at-02-37-21.png">
47
+ </div>
48
+ <div class="message">{{MSG}}</div>
49
+ </div>
50
+ '''
51
+
52
+ user_template = '''
53
+ <div class="chat-message user">
54
+ <div class="avatar">
55
+ <img src="https://i.ibb.co/rdZC7LZ/Photo-logo-1.png">
56
+ </div>
57
+ <div class="message">{{MSG}}</div>
58
+ </div>
59
+ '''
60
+
61
+ def get_pdf_text(pdf_files):
62
+
63
+ text = ""
64
+
65
+ for pdf_file in pdf_files:
66
+ reader = PdfReader(pdf_file)
67
+ for page in reader.pages:
68
+ text += page.extract_text()
69
+
70
+ return text
71
+
72
+ def get_chunk_text(text):
73
+
74
+ text_splitter = CharacterTextSplitter(
75
+ separator = "\n",
76
+ chunk_size = 1000,
77
+ chunk_overlap = 200,
78
+ length_function = len
79
+ )
80
+
81
+ chunks = text_splitter.split_text(text)
82
+
83
+ return chunks
84
+
85
+ def get_vector_store(text_chunks):
86
+
87
+ # For Huggingface Embeddings
88
+
89
+ embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2", model_kwargs={
90
+ 'device' : 'cpu'
91
+ })
92
+ vectorstore = FAISS.from_texts(texts = text_chunks, embedding = embeddings)
93
+
94
+ return vectorstore
95
+
96
+
97
+ def get_conversation_chain(vector_store):
98
+
99
+ # llm = HuggingFaceHub(repo_id="tiiuae/falcon-40b-instruct", model_kwargs={"temperature":0.5, "max_length":512})
100
+
101
+ llm = CTransformers(model='llama-2-7b-chat.ggmlv3.q2_K.bin', # model available here: https://huggingface.co/TheBloke/Llama-2-7B-Chat-GGML/tree/main
102
+ model_type='llama',
103
+ config={'max_new_tokens': 600,
104
+ 'context_length':700,
105
+ 'temperature': 0.01})
106
+
107
+ memory = ConversationBufferMemory(memory_key='chat_history', return_messages=True)
108
+
109
+ conversation_chain = ConversationalRetrievalChain.from_llm(
110
+ llm = llm,
111
+ retriever = vector_store.as_retriever(),
112
+ memory = memory
113
+ )
114
+
115
+ return conversation_chain
116
+
117
+ def handle_user_input(question):
118
+
119
+ response = st.session_state.conversation({'question':question})
120
+ st.session_state.chat_history = response['chat_history']
121
+
122
+ for i, message in enumerate(st.session_state.chat_history):
123
+ if i % 2 == 0:
124
+ st.write(user_template.replace("{{MSG}}", message.content), unsafe_allow_html=True)
125
+ else:
126
+ st.write(bot_template.replace("{{MSG}}", message.content), unsafe_allow_html=True)
127
+
128
+ def main():
129
+ st.set_page_config(page_title='Chat with Your own PDFs', page_icon=':books:')
130
+
131
+ st.write(css, unsafe_allow_html=True)
132
+
133
+ if "conversation" not in st.session_state:
134
+ st.session_state.conversation = None
135
+
136
+ if "chat_history" not in st.session_state:
137
+ st.session_state.chat_history = None
138
+
139
+ st.header('Chat with Your own PDFs :books:')
140
+ question = st.text_input("Ask anything to your PDF: ")
141
+
142
+ if question:
143
+ handle_user_input(question)
144
+
145
+ with st.sidebar:
146
+ st.subheader("Upload your Documents Here: ")
147
+ pdf_files = st.file_uploader("Choose your PDF Files and Press OK", type=['pdf'], accept_multiple_files=True)
148
+
149
+ if st.button("OK"):
150
+ with st.spinner("Processing your PDFs..."):
151
+
152
+ # Get PDF Text
153
+ raw_text = get_pdf_text(pdf_files)
154
+
155
+ # Get Text Chunks
156
+ text_chunks = get_chunk_text(raw_text)
157
+
158
+ # Create Vector Store
159
+
160
+ vector_store = get_vector_store(text_chunks)
161
+ st.write("DONE")
162
+
163
+ # Create conversation chain
164
+
165
+ st.session_state.conversation = get_conversation_chain(vector_store)
166
+
167
+ main()