File size: 11,367 Bytes
6e78b52
 
 
 
 
addae57
6e78b52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c97bfb3
 
 
 
 
 
 
d66aee8
c97bfb3
 
6e78b52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6263ce1
 
6e78b52
 
 
 
 
6176e99
0f80cd2
6263ce1
6e78b52
 
 
0f80cd2
6e78b52
 
6263ce1
6e78b52
 
 
 
833996b
98eb843
6e78b52
 
 
 
 
 
 
 
 
98eb843
6e78b52
 
f41cbd5
6e78b52
 
11debf7
6e78b52
 
 
 
0efb16d
559a5f6
0efb16d
 
 
 
6e78b52
74c89d6
 
559a5f6
98eb843
74c89d6
98eb843
 
0efb16d
74c89d6
 
559a5f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1642055
 
 
 
 
 
 
 
 
 
 
 
 
4c5f2fb
0efb16d
1642055
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b4adf52
1642055
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e78b52
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
import os
import streamlit as st
from langchain.text_splitter import RecursiveCharacterTextSplitter
import re
import pathlib
from tempfile import NamedTemporaryFile

from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
from langchain.llms import HuggingFacePipeline
from langchain.llms import LlamaCpp
from langchain import PromptTemplate, LLMChain
from langchain.callbacks.manager import CallbackManager
from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
from langchain.embeddings import HuggingFaceEmbeddings
from langchain.chains import RetrievalQA
from langchain.vectorstores import FAISS
from PyPDF2 import PdfReader
import os
import time
from langchain.chains.question_answering import load_qa_chain
from langchain.chains.conversational_retrieval.prompts import CONDENSE_QUESTION_PROMPT

from langchain.document_loaders import TextLoader
from langchain.document_loaders import PyPDFLoader
from langchain.document_loaders import Docx2txtLoader
from langchain.document_loaders.image import UnstructuredImageLoader
from langchain.document_loaders import UnstructuredHTMLLoader
from langchain.document_loaders import UnstructuredPowerPointLoader
from langchain.document_loaders import TextLoader
from langchain.memory import ConversationBufferWindowMemory

from langchain.memory import ConversationBufferMemory
from langchain.chains import ConversationalRetrievalChain
from langchain.memory.chat_message_histories.streamlit import StreamlitChatMessageHistory

# sidebar contents
with st.sidebar:
	st.title('DOC-QA DEMO ')
	st.markdown('''
	## About 	
	Detail this application:
	- LLM model: llama2-7b-chat-4bit 
	- Hardware resource : Huggingface space 8 vCPU 32 GB 
	''')

class UploadDoc:
    def __init__(self, path_data):
        self.path_data = path_data

    def prepare_filetype(self):
        extension_lists = {
            ".docx": [],
            ".pdf": [],
            ".html": [],
            ".png": [],
            ".pptx": [],
            ".txt": [],
        }

        path_list = []
        for path, subdirs, files in os.walk(self.path_data):
            for name in files:
                path_list.append(os.path.join(path, name))
                #print(os.path.join(path, name))

        # Loop through the path_list and categorize files
        for filename in path_list:
            file_extension = pathlib.Path(filename).suffix
            #print("File Extension:", file_extension)
            
            if file_extension in extension_lists:
                extension_lists[file_extension].append(filename)
        return extension_lists
    
    def upload_docx(self, extension_lists):
        #word
        data_docxs = []
        for doc in extension_lists[".docx"]:
            loader = Docx2txtLoader(doc)
            data = loader.load()
            data_docxs.extend(data)
        return data_docxs
    
    def upload_pdf(self, extension_lists):
        #pdf 
        data_pdf = []
        for doc in extension_lists[".pdf"]:
            loader = PyPDFLoader(doc)
            data = loader.load_and_split()
            data_pdf.extend(data)
        return data_pdf
    
    def upload_html(self, extension_lists):
        #html 
        data_html = []
        for doc in extension_lists[".html"]:
            loader = UnstructuredHTMLLoader(doc)
            data = loader.load()
            data_html.extend(data)
        return data_html
    
    def upload_png_ocr(self, extension_lists):
        #png ocr
        data_png = []
        for doc in extension_lists[".png"]:
            loader = UnstructuredImageLoader(doc)
            data = loader.load()
            data_png.extend(data)
        return data_png 
    
    def upload_pptx(self, extension_lists):
        #power point
        data_pptx = []
        for doc in extension_lists[".pptx"]:
            loader = UnstructuredPowerPointLoader(doc)
            data = loader.load()
            data_pptx.extend(data)
        return data_pptx
    
    def upload_txt(self, extension_lists):
        #txt 
        data_txt = []
        for doc in extension_lists[".txt"]:
            loader = TextLoader(doc)
            data = loader.load()
            data_txt.extend(data)
        return data_txt
    
    def count_files(self, extension_lists):
        file_extension_counts = {}
        # Count the quantity of each item
        for ext, file_list in extension_lists.items():
            file_extension_counts[ext] = len(file_list)
        return print(f"number of file:{file_extension_counts}")
        # Print the counts
        # for ext, count in file_extension_counts.items():
        #     return print(f"{ext}: {count} file")

    def create_document(self, dataframe=True):
        documents = []
        extension_lists = self.prepare_filetype()
        self.count_files(extension_lists)
        
        upload_functions = {
            ".docx": self.upload_docx,
            ".pdf": self.upload_pdf,
            ".html": self.upload_html,
            ".png": self.upload_png_ocr,
            ".pptx": self.upload_pptx,
            ".txt": self.upload_txt,
        }

        for extension, upload_function in upload_functions.items():
            if len(extension_lists[extension]) > 0:
                if extension == ".xlsx" or extension == ".csv":
                    data = upload_function(extension_lists, dataframe)
                else:
                    data = upload_function(extension_lists)
                documents.extend(data)
    
        return documents
    
def split_docs(documents,chunk_size=1000):
    text_splitter = RecursiveCharacterTextSplitter(chunk_size=chunk_size, chunk_overlap=200)
    sp_docs = text_splitter.split_documents(documents)
    return sp_docs

@st.cache_resource
def load_llama2_llamaCpp():
    core_model_name = "llama-2-7b-chat.Q4_0.gguf"
    #n_gpu_layers = 32
    n_batch = 512
    callback_manager = CallbackManager([StreamingStdOutCallbackHandler()])
    llm = LlamaCpp(
        model_path=core_model_name,
        #n_gpu_layers=n_gpu_layers,
        n_batch=n_batch,
        callback_manager=callback_manager,
        verbose=True,n_ctx = 4096, temperature = 0.1, max_tokens = 512
    )
    return llm

def set_custom_prompt():
    custom_prompt_template = """ Use the following pieces of information from context to answer the user's question.
    If you don't know the answer, don't try to make up an answer.

    Context : {context}
    Question : {question}

    Only returns the helpful answer below and nothing else.
    Helpful answer:
    """
    prompt = PromptTemplate(template=custom_prompt_template, input_variables=['context',
                                                                              'question',
                                                                              ])
    return prompt


@st.cache_resource
def load_embeddings():
    embeddings = HuggingFaceEmbeddings(model_name = "thenlper/gte-base",
                                       model_kwargs = {'device': 'cpu'})
    return embeddings

def main():
    data = []
    sp_docs_list = []
    msgs = StreamlitChatMessageHistory(key="langchain_messages")
    print(msgs)
    if "messages" not in st.session_state:
        st.session_state.messages = []

    llm = load_llama2_llamaCpp()
    qa_prompt = set_custom_prompt()
    embeddings = load_embeddings()
    #memory = ConversationBufferWindowMemory(k = 0, return_messages=True,  input_key= 'question', output_key='answer', memory_key="chat_history")
    #memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
    #doc_chain = load_qa_chain(llm, chain_type="stuff", prompt = qa_prompt)
    #question_generator = LLMChain(llm=llm, prompt=CONDENSE_QUESTION_PROMPT)
    #embeddings = load_embeddings()

    
    uploaded_file = st.file_uploader('Choose your .pdf file', type="pdf")
    if uploaded_file is not None :
        with NamedTemporaryFile(dir='PDF', suffix='.pdf', delete=False) as f:
            f.write(uploaded_file.getbuffer())
            print(f.name)
            #filename = f.name
            loader = PyPDFLoader(f.name)
            pages = loader.load_and_split()
            data.extend(pages)
            #st.write(pages)
            f.close()
            os.unlink(f.name)
            os.path.exists(f.name)
    if len(data) > 0 :
        embeddings = load_embeddings()
        sp_docs = split_docs(documents = data)
        st.write(f"This document have {len(sp_docs)} chunks")
        sp_docs_list.extend(sp_docs)

    try :
        db = FAISS.from_documents(sp_docs_list, embeddings)
        memory = ConversationBufferMemory(memory_key="chat_history", 
                                  return_messages=True, 
                                  input_key="query", 
                                  output_key="result")
        qa_chain = RetrievalQA.from_chain_type(
            llm = llm,
            chain_type = "stuff",
            retriever = db.as_retriever(search_kwargs = {'k':3}), 
            return_source_documents = True,
            memory = memory,
            chain_type_kwargs = {"prompt":qa_prompt}) 
    
        
            # qa_chain = ConversationalRetrievalChain(
            #     retriever =db.as_retriever(search_kwargs={'k':2}), 
            #     question_generator=question_generator,
            #     #condense_question_prompt=CONDENSE_QUESTION_PROMPT,
            #     combine_docs_chain=doc_chain,
            #     return_source_documents=True,
            #     memory = memory,
            #     #get_chat_history=lambda h :h
            # )
    
        for message in st.session_state.messages:
            with st.chat_message(message["role"]):
                st.markdown(message["content"])
    
            # Accept user input
        if query := st.chat_input("What is up?"):
            # Display user message in chat message container
            with st.chat_message("user"):
                st.markdown(query)
            # Add user message to chat history
            st.session_state.messages.append({"role": "user", "content": query})
    
            start = time.time()
    
            response = qa_chain({'query': query})
    
            #url_list = set([i.metadata['page']  for i in response['source_documents']])
            #print(f"condensed quesion : {question_generator.run({'chat_history': response['chat_history'], 'question' : query})}")
            
            with st.chat_message("assistant"):
                st.markdown(response['result'])
            
            end = time.time()
            st.write("Respone time:",int(end-start),"sec")
            print(response)
                    
            # Add assistant response to chat history
            st.session_state.messages.append({"role": "assistant", "content": response['result']})
    
            with st.expander("See the related documents"):
                for count, url in enumerate(response['source_documents']):
                    #url_reg = regex_source(url)
                    st.write(str(count+1)+":", url)
    
        clear_button = st.button("Start new convo")
        if clear_button :
            st.session_state.messages = []
            qa_chain.memory.chat_memory.clear() 

    except :
        st.write("Plaese upload your pdf file.")
                
  
if __name__ == '__main__':
	main()