Spaces:
Sleeping
Sleeping
namkwonwoo
commited on
Commit
β’
2c1110b
1
Parent(s):
0270b03
Upload 3 files
Browse files- app.py +166 -0
- htmlTemplates.py +44 -0
- requirements.txt +13 -0
app.py
ADDED
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 # For loading transformer models.
|
10 |
+
from langchain.document_loaders import PyPDFLoader, TextLoader, JSONLoader, CSVLoader
|
11 |
+
import tempfile # μμ νμΌμ μμ±νκΈ° μν λΌμ΄λΈλ¬λ¦¬μ
λλ€.
|
12 |
+
import os
|
13 |
+
from huggingface_hub import hf_hub_download # Hugging Face Hubμμ λͺ¨λΈμ λ€μ΄λ‘λνκΈ° μν ν¨μμ
λλ€.
|
14 |
+
|
15 |
+
# PDF λ¬Έμλ‘λΆν° ν
μ€νΈλ₯Ό μΆμΆνλ ν¨μμ
λλ€.
|
16 |
+
def get_pdf_text(pdf_docs):
|
17 |
+
temp_dir = tempfile.TemporaryDirectory() # μμ λλ ν 리λ₯Ό μμ±ν©λλ€.
|
18 |
+
temp_filepath = os.path.join(temp_dir.name, pdf_docs.name) # μμ νμΌ κ²½λ‘λ₯Ό μμ±ν©λλ€.
|
19 |
+
with open(temp_filepath, "wb") as f: # μμ νμΌμ λ°μ΄λ리 μ°κΈ° λͺ¨λλ‘ μ½λλ€.
|
20 |
+
f.write(pdf_docs.getvalue()) # PDF λ¬Έμμ λ΄μ©μ μμ νμΌμ μλλ€.
|
21 |
+
pdf_loader = PyPDFLoader(temp_filepath) # PyPDFLoaderλ₯Ό μ¬μ©ν΄ PDFλ₯Ό λ‘λν©λλ€.
|
22 |
+
pdf_doc = pdf_loader.load() # ν
μ€νΈλ₯Ό μΆμΆν©λλ€.
|
23 |
+
return pdf_doc # μΆμΆν ν
μ€νΈλ₯Ό λ°νν©λλ€.
|
24 |
+
|
25 |
+
# κ³Όμ
|
26 |
+
# μλ ν
μ€νΈ μΆμΆ ν¨μλ₯Ό μμ±
|
27 |
+
def get_text_file(text_docs):
|
28 |
+
temp_dir = tempfile.TemporaryDirectory()
|
29 |
+
temp_filepath = os.path.join(temp_dir.name, text_docs.name)
|
30 |
+
with open(temp_filepath, "wb") as f:
|
31 |
+
f.write(text_docs.getvalue())
|
32 |
+
text_loader = TextLoader(temp_filepath)
|
33 |
+
text_doc = text_loader.load()
|
34 |
+
return text_doc
|
35 |
+
|
36 |
+
|
37 |
+
def get_csv_file(csv_docs):
|
38 |
+
temp_dir = tempfile.TemporaryDirectory()
|
39 |
+
temp_filepath = os.path.join(temp_dir.name, csv_docs.name)
|
40 |
+
with open(temp_filepath, "wb") as f:
|
41 |
+
f.write(csv_docs.getvalue())
|
42 |
+
csv_loader = CSVLoader(temp_filepath)
|
43 |
+
csv_doc = csv_loader.load()
|
44 |
+
return csv_doc
|
45 |
+
|
46 |
+
def get_json_file(json_docs):
|
47 |
+
temp_dir = tempfile.TemporaryDirectory()
|
48 |
+
temp_filepath = os.path.join(temp_dir.name, json_docs.name)
|
49 |
+
with open(temp_filepath, "wb") as f:
|
50 |
+
f.write(json_docs.getvalue())
|
51 |
+
json_loader = JSONLoader(temp_filepath)
|
52 |
+
json_doc = json_loader.load()
|
53 |
+
return json_doc
|
54 |
+
|
55 |
+
|
56 |
+
# λ¬Έμλ€μ μ²λ¦¬νμ¬ ν
μ€νΈ μ²ν¬λ‘ λλλ ν¨μμ
λλ€.
|
57 |
+
def get_text_chunks(documents):
|
58 |
+
text_splitter = RecursiveCharacterTextSplitter(
|
59 |
+
chunk_size=1000, # μ²ν¬μ ν¬κΈ°λ₯Ό μ§μ ν©λλ€.
|
60 |
+
chunk_overlap=200, # μ²ν¬ μ¬μ΄μ μ€λ³΅μ μ§μ ν©λλ€.
|
61 |
+
length_function=len # ν
μ€νΈμ κΈΈμ΄λ₯Ό μΈ‘μ νλ ν¨μλ₯Ό μ§μ ν©λλ€.
|
62 |
+
)
|
63 |
+
|
64 |
+
documents = text_splitter.split_documents(documents) # λ¬Έμλ€μ μ²ν¬λ‘ λλλλ€.
|
65 |
+
return documents # λλ μ²ν¬λ₯Ό λ°νν©λλ€.
|
66 |
+
|
67 |
+
|
68 |
+
# ν
μ€νΈ μ²ν¬λ€λ‘λΆν° λ²‘ν° μ€ν μ΄λ₯Ό μμ±νλ ν¨μμ
λλ€.
|
69 |
+
def get_vectorstore(text_chunks):
|
70 |
+
# μνλ μλ² λ© λͺ¨λΈμ λ‘λν©λλ€.
|
71 |
+
embeddings = HuggingFaceEmbeddings(model_name='sentence-transformers/all-MiniLM-L12-v2',
|
72 |
+
model_kwargs={'device': 'cpu'}) # μλ² λ© λͺ¨λΈμ μ€μ ν©λλ€.
|
73 |
+
vectorstore = FAISS.from_documents(text_chunks, embeddings) # FAISS λ²‘ν° μ€ν μ΄λ₯Ό μμ±ν©λλ€.
|
74 |
+
return vectorstore # μμ±λ λ²‘ν° μ€ν μ΄λ₯Ό λ°νν©λλ€.
|
75 |
+
|
76 |
+
|
77 |
+
def get_conversation_chain(vectorstore):
|
78 |
+
model_name_or_path = 'TheBloke/Llama-2-7B-chat-GGUF'
|
79 |
+
model_basename = 'llama-2-7b-chat.Q2_K.gguf'
|
80 |
+
model_path = hf_hub_download(repo_id=model_name_or_path, filename=model_basename)
|
81 |
+
|
82 |
+
llm = LlamaCpp(model_path=model_path,
|
83 |
+
n_ctx=4086,
|
84 |
+
input={"temperature": 0.75, "max_length": 2000, "top_p": 1},
|
85 |
+
verbose=True, )
|
86 |
+
# λν κΈ°λ‘μ μ μ₯νκΈ° μν λ©λͺ¨λ¦¬λ₯Ό μμ±ν©λλ€.
|
87 |
+
memory = ConversationBufferMemory(
|
88 |
+
memory_key='chat_history', return_messages=True)
|
89 |
+
# λν κ²μ 체μΈμ μμ±ν©λλ€.
|
90 |
+
conversation_chain = ConversationalRetrievalChain.from_llm(
|
91 |
+
llm=llm,
|
92 |
+
retriever=vectorstore.as_retriever(),
|
93 |
+
memory=memory
|
94 |
+
)
|
95 |
+
return conversation_chain # μμ±λ λν 체μΈμ λ°νν©λλ€.
|
96 |
+
|
97 |
+
# μ¬μ©μ μ
λ ₯μ μ²λ¦¬νλ ν¨μμ
λλ€.
|
98 |
+
def handle_userinput(user_question):
|
99 |
+
print('user_question => ', user_question)
|
100 |
+
# λν 체μΈμ μ¬μ©νμ¬ μ¬μ©μ μ§λ¬Έμ λν μλ΅μ μμ±ν©λλ€.
|
101 |
+
response = st.session_state.conversation({'question': user_question})
|
102 |
+
# λν κΈ°λ‘μ μ μ₯ν©λλ€.
|
103 |
+
st.session_state.chat_history = response['chat_history']
|
104 |
+
|
105 |
+
for i, message in enumerate(st.session_state.chat_history):
|
106 |
+
if i % 2 == 0:
|
107 |
+
st.write(user_template.replace(
|
108 |
+
"{{MSG}}", message.content), unsafe_allow_html=True)
|
109 |
+
else:
|
110 |
+
st.write(bot_template.replace(
|
111 |
+
"{{MSG}}", message.content), unsafe_allow_html=True)
|
112 |
+
|
113 |
+
|
114 |
+
def main():
|
115 |
+
load_dotenv()
|
116 |
+
st.set_page_config(page_title="Chat with multiple Files",
|
117 |
+
page_icon=":books:")
|
118 |
+
st.write(css, unsafe_allow_html=True)
|
119 |
+
|
120 |
+
if "conversation" not in st.session_state:
|
121 |
+
st.session_state.conversation = None
|
122 |
+
if "chat_history" not in st.session_state:
|
123 |
+
st.session_state.chat_history = None
|
124 |
+
|
125 |
+
st.header("Chat with multiple Files:")
|
126 |
+
user_question = st.text_input("Ask a question about your documents:")
|
127 |
+
if user_question:
|
128 |
+
handle_userinput(user_question)
|
129 |
+
|
130 |
+
with st.sidebar:
|
131 |
+
st.subheader("Your documents")
|
132 |
+
docs = st.file_uploader(
|
133 |
+
"Upload your PDFs here and click on 'Process'", accept_multiple_files=True)
|
134 |
+
if st.button("Process"):
|
135 |
+
with st.spinner("Processing"):
|
136 |
+
# get pdf text
|
137 |
+
doc_list = []
|
138 |
+
|
139 |
+
for file in docs:
|
140 |
+
print('file - type : ', file.type)
|
141 |
+
if file.type == 'text/plain':
|
142 |
+
# file is .txt
|
143 |
+
doc_list.extend(get_text_file(file))
|
144 |
+
elif file.type in ['application/octet-stream', 'application/pdf']:
|
145 |
+
# file is .pdf
|
146 |
+
doc_list.extend(get_pdf_text(file))
|
147 |
+
elif file.type == 'text/csv':
|
148 |
+
# file is .csv
|
149 |
+
doc_list.extend(get_csv_file(file))
|
150 |
+
elif file.type == 'application/json':
|
151 |
+
# file is .json
|
152 |
+
doc_list.extend(get_json_file(file))
|
153 |
+
|
154 |
+
# get the text chunks
|
155 |
+
text_chunks = get_text_chunks(doc_list)
|
156 |
+
|
157 |
+
# create vector store
|
158 |
+
vectorstore = get_vectorstore(text_chunks)
|
159 |
+
|
160 |
+
# create conversation chain
|
161 |
+
st.session_state.conversation = get_conversation_chain(
|
162 |
+
vectorstore)
|
163 |
+
|
164 |
+
|
165 |
+
if __name__ == '__main__':
|
166 |
+
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
|