ryul99 commited on
Commit
2f6de34
Β·
1 Parent(s): ed66c30

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +161 -0
  2. htmlTemplates.py +44 -0
app.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
29
+ text = docs.getvalue().decode('utf-8')
30
+ return [text]
31
+
32
+ def get_csv_file(docs):
33
+
34
+ csv_text = ""
35
+ for line in docs:
36
+ csv_text += line.decode('utf-8') # ν•„μš”ν•œ 경우 인코딩을 μ‘°μ •ν•˜μ„Έμš”.
37
+
38
+ text = "\n".join(row.split(',')[0] for row in csv_text.split('\n'))
39
+ return [text]
40
+
41
+ def get_json_file(docs):
42
+
43
+ import json
44
+ json_data = json.loads(docs.getvalue().decode('utf-8'))
45
+
46
+ text_list = [item.get('text', '') for item in json_data.get('items', [])]
47
+ return text_list
48
+
49
+
50
+
51
+ # λ¬Έμ„œλ“€μ„ μ²˜λ¦¬ν•˜μ—¬ ν…μŠ€νŠΈ 청크둜 λ‚˜λˆ„λŠ” ν•¨μˆ˜μž…λ‹ˆλ‹€.
52
+ def get_text_chunks(documents):
53
+ text_splitter = RecursiveCharacterTextSplitter(
54
+ chunk_size=1000, # 청크의 크기λ₯Ό μ§€μ •ν•©λ‹ˆλ‹€.
55
+ chunk_overlap=200, # 청크 μ‚¬μ΄μ˜ 쀑볡을 μ§€μ •ν•©λ‹ˆλ‹€.
56
+ length_function=len # ν…μŠ€νŠΈμ˜ 길이λ₯Ό μΈ‘μ •ν•˜λŠ” ν•¨μˆ˜λ₯Ό μ§€μ •ν•©λ‹ˆλ‹€.
57
+ )
58
+
59
+ documents = text_splitter.split_documents(documents) # λ¬Έμ„œλ“€μ„ 청크둜 λ‚˜λˆ•λ‹ˆλ‹€.
60
+ return documents # λ‚˜λˆˆ 청크λ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€.
61
+
62
+
63
+ # ν…μŠ€νŠΈ μ²­ν¬λ“€λ‘œλΆ€ν„° 벑터 μŠ€ν† μ–΄λ₯Ό μƒμ„±ν•˜λŠ” ν•¨μˆ˜μž…λ‹ˆλ‹€.
64
+ def get_vectorstore(text_chunks):
65
+ # μ›ν•˜λŠ” μž„λ² λ”© λͺ¨λΈμ„ λ‘œλ“œν•©λ‹ˆλ‹€.
66
+ embeddings = HuggingFaceEmbeddings(model_name='sentence-transformers/all-MiniLM-L12-v2',
67
+ model_kwargs={'device': 'cpu'}) # μž„λ² λ”© λͺ¨λΈμ„ μ„€μ •ν•©λ‹ˆλ‹€.
68
+ vectorstore = FAISS.from_documents(text_chunks, embeddings) # FAISS 벑터 μŠ€ν† μ–΄λ₯Ό μƒμ„±ν•©λ‹ˆλ‹€.
69
+ return vectorstore # μƒμ„±λœ 벑터 μŠ€ν† μ–΄λ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€.
70
+
71
+
72
+ def get_conversation_chain(vectorstore):
73
+ model_name_or_path = 'TheBloke/Llama-2-7B-chat-GGUF'
74
+ model_basename = 'llama-2-7b-chat.Q2_K.gguf'
75
+ model_path = hf_hub_download(repo_id=model_name_or_path, filename=model_basename)
76
+
77
+ llm = LlamaCpp(model_path=model_path,
78
+ n_ctx=4086,
79
+ input={"temperature": 0.75, "max_length": 2000, "top_p": 1},
80
+ verbose=True, )
81
+ # λŒ€ν™” 기둝을 μ €μž₯ν•˜κΈ° μœ„ν•œ λ©”λͺ¨λ¦¬λ₯Ό μƒμ„±ν•©λ‹ˆλ‹€.
82
+ memory = ConversationBufferMemory(
83
+ memory_key='chat_history', return_messages=True)
84
+ # λŒ€ν™” 검색 체인을 μƒμ„±ν•©λ‹ˆλ‹€.
85
+ conversation_chain = ConversationalRetrievalChain.from_llm(
86
+ llm=llm,
87
+ retriever=vectorstore.as_retriever(),
88
+ memory=memory
89
+ )
90
+ return conversation_chain # μƒμ„±λœ λŒ€ν™” 체인을 λ°˜ν™˜ν•©λ‹ˆλ‹€.
91
+
92
+ # μ‚¬μš©μž μž…λ ₯을 μ²˜λ¦¬ν•˜λŠ” ν•¨μˆ˜μž…λ‹ˆλ‹€.
93
+ def handle_userinput(user_question):
94
+ print('user_question => ', user_question)
95
+ # λŒ€ν™” 체인을 μ‚¬μš©ν•˜μ—¬ μ‚¬μš©μž μ§ˆλ¬Έμ— λŒ€ν•œ 응닡을 μƒμ„±ν•©λ‹ˆλ‹€.
96
+ response = st.session_state.conversation({'question': user_question})
97
+ # λŒ€ν™” 기둝을 μ €μž₯ν•©λ‹ˆλ‹€.
98
+ st.session_state.chat_history = response['chat_history']
99
+
100
+ for i, message in enumerate(st.session_state.chat_history):
101
+ if i % 2 == 0:
102
+ st.write(user_template.replace(
103
+ "{{MSG}}", message.content), unsafe_allow_html=True)
104
+ else:
105
+ st.write(bot_template.replace(
106
+ "{{MSG}}", message.content), unsafe_allow_html=True)
107
+
108
+
109
+ def main():
110
+ load_dotenv()
111
+ st.set_page_config(page_title="Chat with multiple Files",
112
+ page_icon=":books:")
113
+ st.write(css, unsafe_allow_html=True)
114
+
115
+ if "conversation" not in st.session_state:
116
+ st.session_state.conversation = None
117
+ if "chat_history" not in st.session_state:
118
+ st.session_state.chat_history = None
119
+
120
+ st.header("Chat with multiple Files:")
121
+ user_question = st.text_input("Ask a question about your documents:")
122
+ if user_question:
123
+ handle_userinput(user_question)
124
+
125
+ with st.sidebar:
126
+ st.subheader("Your documents")
127
+ docs = st.file_uploader(
128
+ "Upload your PDFs here and click on 'Process'", accept_multiple_files=True)
129
+ if st.button("Process"):
130
+ with st.spinner("Processing"):
131
+ # get pdf text
132
+ doc_list = []
133
+
134
+ for file in docs:
135
+ print('file - type : ', file.type)
136
+ if file.type == 'text/plain':
137
+ # file is .txt
138
+ doc_list.extend(get_text_file(file))
139
+ elif file.type in ['application/octet-stream', 'application/pdf']:
140
+ # file is .pdf
141
+ doc_list.extend(get_pdf_text(file))
142
+ elif file.type == 'text/csv':
143
+ # file is .csv
144
+ doc_list.extend(get_csv_file(file))
145
+ elif file.type == 'application/json':
146
+ # file is .json
147
+ doc_list.extend(get_json_file(file))
148
+
149
+ # get the text chunks
150
+ text_chunks = get_text_chunks(doc_list)
151
+
152
+ # create vector store
153
+ vectorstore = get_vectorstore(text_chunks)
154
+
155
+ # create conversation chain
156
+ st.session_state.conversation = get_conversation_chain(
157
+ vectorstore)
158
+
159
+
160
+ if __name__ == '__main__':
161
+ 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
+ '''