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