lakxs commited on
Commit
cf1fee6
β€’
1 Parent(s): 22b4a37

Upload 5 files

Browse files
Files changed (3) hide show
  1. app.py +191 -0
  2. htmlTemplates.py +44 -0
  3. requirements.txt +13 -0
app.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from dotenv import load_dotenv
3
+ from langchain.text_splitter import CharacterTextSplitter, RecursiveCharacterTextSplitter
4
+ from langchain.vectorstores import FAISS
5
+ from langchain.embeddings import HuggingFaceEmbeddings # General embeddings from HuggingFace models.
6
+ from langchain.memory import ConversationBufferMemory
7
+ from langchain.chains import ConversationalRetrievalChain
8
+ from htmlTemplates import css, bot_template, user_template
9
+ from langchain.llms import LlamaCpp
10
+ import json
11
+ from pathlib import Path
12
+ from pprint import pprint
13
+
14
+ from langchain.document_loaders import PyPDFLoader, TextLoader, JSONLoader, CSVLoader
15
+ import tempfile # μž„μ‹œ νŒŒμΌμ„ μƒμ„±ν•˜κΈ° μœ„ν•œ λΌμ΄λΈŒλŸ¬λ¦¬μž…λ‹ˆλ‹€.
16
+ import os
17
+ from huggingface_hub import hf_hub_download # Hugging Face Hubμ—μ„œ λͺ¨λΈμ„ λ‹€μš΄λ‘œλ“œν•˜κΈ° μœ„ν•œ ν•¨μˆ˜μž…λ‹ˆλ‹€.
18
+
19
+ # PDF λ¬Έμ„œλ‘œλΆ€ν„° ν…μŠ€νŠΈλ₯Ό μΆ”μΆœν•˜λŠ” ν•¨μˆ˜μž…λ‹ˆλ‹€.
20
+ def get_pdf_text(pdf_docs):
21
+ temp_dir = tempfile.TemporaryDirectory() # μž„μ‹œ 디렉토리λ₯Ό μƒμ„±ν•©λ‹ˆλ‹€.
22
+ temp_filepath = os.path.join(temp_dir.name, pdf_docs.name) # μž„μ‹œ 파일 경둜λ₯Ό μƒμ„±ν•©λ‹ˆλ‹€.
23
+ with open(temp_filepath, "wb") as f: # μž„μ‹œ νŒŒμΌμ„ λ°”μ΄λ„ˆλ¦¬ μ“°κΈ° λͺ¨λ“œλ‘œ μ—½λ‹ˆλ‹€.
24
+ f.write(pdf_docs.getvalue()) # PDF λ¬Έμ„œμ˜ λ‚΄μš©μ„ μž„μ‹œ νŒŒμΌμ— μ”λ‹ˆλ‹€.
25
+ pdf_loader = PyPDFLoader(temp_filepath) # PyPDFLoaderλ₯Ό μ‚¬μš©ν•΄ PDFλ₯Ό λ‘œλ“œν•©λ‹ˆλ‹€.
26
+ pdf_doc = pdf_loader.load() # ν…μŠ€νŠΈλ₯Ό μΆ”μΆœν•©λ‹ˆλ‹€.
27
+ return pdf_doc # μΆ”μΆœν•œ ν…μŠ€νŠΈλ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€.
28
+
29
+ # 과제
30
+ # μ•„λž˜ ν…μŠ€νŠΈ μΆ”μΆœ ν•¨μˆ˜λ₯Ό μž‘μ„±
31
+
32
+ def get_text_file(text_docs):
33
+ temp_dir = tempfile.TemporaryDirectory() # μž„μ‹œ 디렉토리λ₯Ό μƒμ„±ν•©λ‹ˆλ‹€.
34
+ temp_filepath = os.path.join(temp_dir.name, text_docs.name) # μž„μ‹œ 파일 경둜λ₯Ό μƒμ„±ν•©λ‹ˆλ‹€.
35
+
36
+ with open(temp_filepath, "w", encoding="utf-8") as f: # μž„μ‹œ νŒŒμΌμ„ ν…μŠ€νŠΈ μ“°κΈ° λͺ¨λ“œλ‘œ μ—½λ‹ˆλ‹€.
37
+ f.write(text_docs.getvalue()) # ν…μŠ€νŠΈ λ¬Έμ„œμ˜ λ‚΄μš©μ„ μž„μ‹œ νŒŒμΌμ— μ”λ‹ˆλ‹€.
38
+
39
+ text_loader = TextLoader(temp_filepath) # TextLoaderλ₯Ό μ‚¬μš©ν•΄ ν…μŠ€νŠΈ λ¬Έμ„œλ₯Ό λ‘œλ“œν•©λ‹ˆλ‹€.
40
+ text_doc = text_loader.load() # ν…μŠ€νŠΈλ₯Ό μΆ”μΆœν•©λ‹ˆλ‹€.
41
+ return text_doc # μΆ”μΆœλœ ν…μŠ€νŠΈλ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€.
42
+
43
+ def get_csv_file(csv_docs):
44
+ temp_dir = tempfile.TemporaryDirectory() # μž„μ‹œ 디렉토리λ₯Ό μƒμ„±ν•©λ‹ˆλ‹€.
45
+ temp_filepath = os.path.join(temp_dir.name, csv_docs.name) # μž„μ‹œ 파일 경둜λ₯Ό μƒμ„±ν•©λ‹ˆλ‹€.
46
+
47
+ with open(temp_filepath, "wb") as f: # μž„μ‹œ νŒŒμΌμ„ λ°”μ΄λ„ˆλ¦¬ μ“°κΈ° λͺ¨λ“œλ‘œ μ—½λ‹ˆλ‹€.
48
+ f.write(csv_docs.getvalue()) # CSV λ¬Έμ„œμ˜ λ‚΄μš©μ„ μž„μ‹œ νŒŒμΌμ— μ”λ‹ˆλ‹€.
49
+
50
+ csv_loader = CSVLoader(temp_filepath) # CSVLoaderλ₯Ό μ‚¬μš©ν•΄ CSV λ¬Έμ„œλ₯Ό λ‘œλ“œν•©λ‹ˆλ‹€.
51
+ csv_doc = csv_loader.load() # ν…μŠ€νŠΈλ₯Ό μΆ”μΆœν•©λ‹ˆλ‹€.
52
+ return csv_doc # μΆ”μΆœλœ ν…μŠ€νŠΈλ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€.
53
+
54
+ def get_json_file(json_docs):
55
+ temp_dir = tempfile.TemporaryDirectory() # μž„μ‹œ 디렉토리λ₯Ό μƒμ„±ν•©λ‹ˆλ‹€.
56
+ temp_filepath = os.path.join(temp_dir.name, json_docs.name) # μž„μ‹œ 파일 경둜λ₯Ό μƒμ„±ν•©λ‹ˆλ‹€.
57
+
58
+ with open(temp_filepath, "w", encoding="utf-8") as f: # μž„μ‹œ νŒŒμΌμ„ ν…μŠ€νŠΈ μ“°κΈ° λͺ¨λ“œλ‘œ μ—½λ‹ˆλ‹€.
59
+ f.write(json_docs.getvalue()) # JSON λ¬Έμ„œμ˜ λ‚΄μš©μ„ μž„μ‹œ νŒŒμΌμ— μ”λ‹ˆλ‹€.
60
+
61
+ json_loader = JSONLoader(temp_filepath) # JSONLoaderλ₯Ό μ‚¬μš©ν•΄ JSON λ¬Έμ„œλ₯Ό λ‘œλ“œν•©λ‹ˆλ‹€.
62
+ json_doc = json_loader.load() # ν…μŠ€νŠΈλ₯Ό μΆ”μΆœν•©λ‹ˆλ‹€.
63
+ return json_doc # μΆ”μΆœλœ ν…μŠ€νŠΈλ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€.
64
+
65
+
66
+
67
+
68
+ # def get_text_file(text_docs):
69
+ #
70
+ # pass
71
+ #
72
+ # def get_csv_file(csv_docs):
73
+ # pass
74
+ #
75
+ # def get_json_file(json_docs):
76
+ #
77
+ #
78
+ # pass
79
+
80
+
81
+ # λ¬Έμ„œλ“€μ„ μ²˜λ¦¬ν•˜μ—¬ ν…μŠ€νŠΈ 청크둜 λ‚˜λˆ„λŠ” ν•¨μˆ˜μž…λ‹ˆλ‹€.
82
+ def get_text_chunks(documents):
83
+ text_splitter = RecursiveCharacterTextSplitter(
84
+ chunk_size=1000, # 청크의 크기λ₯Ό μ§€μ •ν•©λ‹ˆλ‹€.
85
+ chunk_overlap=200, # 청크 μ‚¬μ΄μ˜ 쀑볡을 μ§€μ •ν•©λ‹ˆλ‹€.
86
+ length_function=len # ν…μŠ€νŠΈμ˜ 길이λ₯Ό μΈ‘μ •ν•˜λŠ” ν•¨μˆ˜λ₯Ό μ§€μ •ν•©λ‹ˆλ‹€.
87
+ )
88
+
89
+ documents = text_splitter.split_documents(documents) # λ¬Έμ„œλ“€μ„ 청크둜 λ‚˜λˆ•λ‹ˆλ‹€.
90
+ return documents # λ‚˜λˆˆ 청크λ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€.
91
+
92
+
93
+ # ν…μŠ€νŠΈ μ²­ν¬λ“€λ‘œλΆ€ν„° 벑터 μŠ€ν† μ–΄λ₯Ό μƒμ„±ν•˜λŠ” ν•¨μˆ˜μž…λ‹ˆλ‹€.
94
+ def get_vectorstore(text_chunks):
95
+ # μ›ν•˜λŠ” μž„λ² λ”© λͺ¨λΈμ„ λ‘œλ“œν•©λ‹ˆλ‹€.
96
+ embeddings = HuggingFaceEmbeddings(model_name='sentence-transformers/all-MiniLM-L12-v2',
97
+ model_kwargs={'device': 'cpu'}) # μž„λ² λ”© λͺ¨λΈμ„ μ„€μ •ν•©λ‹ˆλ‹€.
98
+ vectorstore = FAISS.from_documents(text_chunks, embeddings) # FAISS 벑터 μŠ€ν† μ–΄λ₯Ό μƒμ„±ν•©λ‹ˆλ‹€.
99
+ return vectorstore # μƒμ„±λœ 벑터 μŠ€ν† μ–΄λ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€.
100
+
101
+
102
+ def get_conversation_chain(vectorstore):
103
+ model_name_or_path = 'TheBloke/Llama-2-7B-chat-GGUF'
104
+ model_basename = 'llama-2-7b-chat.Q2_K.gguf'
105
+ model_path = hf_hub_download(repo_id=model_name_or_path, filename=model_basename)
106
+
107
+ llm = LlamaCpp(model_path=model_path,
108
+ n_ctx=4086,
109
+ input={"temperature": 0.75, "max_length": 2000, "top_p": 1},
110
+ verbose=True, )
111
+ # λŒ€ν™” 기둝을 μ €μž₯ν•˜κΈ° μœ„ν•œ λ©”λͺ¨λ¦¬λ₯Ό μƒμ„±ν•©λ‹ˆλ‹€.
112
+ memory = ConversationBufferMemory(
113
+ memory_key='chat_history', return_messages=True)
114
+ # λŒ€ν™” 검색 체인을 μƒμ„±ν•©λ‹ˆλ‹€.
115
+ conversation_chain = ConversationalRetrievalChain.from_llm(
116
+ llm=llm,
117
+ retriever=vectorstore.as_retriever(),
118
+ memory=memory
119
+ )
120
+ return conversation_chain # μƒμ„±λœ λŒ€ν™” 체인을 λ°˜ν™˜ν•©λ‹ˆλ‹€.
121
+
122
+ # μ‚¬μš©μž μž…λ ₯을 μ²˜λ¦¬ν•˜λŠ” ν•¨μˆ˜μž…λ‹ˆλ‹€.
123
+ def handle_userinput(user_question):
124
+ print('user_question => ', user_question)
125
+ # λŒ€ν™” 체인을 μ‚¬μš©ν•˜μ—¬ μ‚¬μš©μž μ§ˆλ¬Έμ— λŒ€ν•œ 응닡을 μƒμ„±ν•©λ‹ˆλ‹€.
126
+ response = st.session_state.conversation({'question': user_question})
127
+ # λŒ€ν™” 기둝을 μ €μž₯ν•©λ‹ˆλ‹€.
128
+ st.session_state.chat_history = response['chat_history']
129
+
130
+ for i, message in enumerate(st.session_state.chat_history):
131
+ if i % 2 == 0:
132
+ st.write(user_template.replace(
133
+ "{{MSG}}", message.content), unsafe_allow_html=True)
134
+ else:
135
+ st.write(bot_template.replace(
136
+ "{{MSG}}", message.content), unsafe_allow_html=True)
137
+
138
+
139
+ def main():
140
+ load_dotenv()
141
+ st.set_page_config(page_title="Chat with multiple Files",
142
+ page_icon=":books:")
143
+ st.write(css, unsafe_allow_html=True)
144
+
145
+ if "conversation" not in st.session_state:
146
+ st.session_state.conversation = None
147
+ if "chat_history" not in st.session_state:
148
+ st.session_state.chat_history = None
149
+
150
+ st.header("Chat with multiple Files:")
151
+ user_question = st.text_input("Ask a question about your documents:")
152
+ if user_question:
153
+ handle_userinput(user_question)
154
+
155
+ with st.sidebar:
156
+ st.subheader("Your documents")
157
+ docs = st.file_uploader(
158
+ "Upload your PDFs here and click on 'Process'", accept_multiple_files=True)
159
+ if st.button("Process"):
160
+ with st.spinner("Processing"):
161
+ # get pdf text
162
+ doc_list = []
163
+
164
+ for file in docs:
165
+ print('file - type : ', file.type)
166
+ if file.type == 'text/plain':
167
+ # file is .txt
168
+ doc_list.extend(get_text_file(file))
169
+ elif file.type in ['application/octet-stream', 'application/pdf']:
170
+ # file is .pdf
171
+ doc_list.extend(get_pdf_text(file))
172
+ elif file.type == 'text/csv':
173
+ # file is .csv
174
+ doc_list.extend(get_csv_file(file))
175
+ elif file.type == 'application/json':
176
+ # file is .json
177
+ doc_list.extend(get_json_file(file))
178
+
179
+ # get the text chunks
180
+ text_chunks = get_text_chunks(doc_list)
181
+
182
+ # create vector store
183
+ vectorstore = get_vectorstore(text_chunks)
184
+
185
+ # create conversation chain
186
+ st.session_state.conversation = get_conversation_chain(
187
+ vectorstore)
188
+
189
+
190
+ if __name__ == '__main__':
191
+ 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,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ langchain
2
+ llama-cpp-python
3
+ PyPDF2==3.0.1
4
+ faiss-cpu==1.7.4
5
+ ctransformers
6
+ pypdf
7
+ chromadb
8
+ tiktoken
9
+ pysqlite3-binary
10
+ streamlit-extras
11
+ InstructorEmbedding
12
+ sentence-transformers
13
+ jq