timmy0079 commited on
Commit
f993782
β€’
1 Parent(s): 147bc3d
Files changed (1) hide show
  1. app.py +177 -0
app.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from dotenv import load_dotenv
3
+ from PyPDF2 import PdfReader
4
+ from langchain.text_splitter import CharacterTextSplitter, RecursiveCharacterTextSplitter
5
+ from langchain.embeddings import OpenAIEmbeddings, HuggingFaceInstructEmbeddings
6
+ from langchain.vectorstores import FAISS, Chroma
7
+ from langchain.embeddings import HuggingFaceEmbeddings # General embeddings from HuggingFace models.
8
+ from langchain.chat_models import ChatOpenAI
9
+ from langchain.memory import ConversationBufferMemory
10
+ from langchain.chains import ConversationalRetrievalChain
11
+ from htmlTemplates import css, bot_template, user_template
12
+ from langchain.llms import HuggingFaceHub, LlamaCpp, CTransformers # For loading transformer models.
13
+ from langchain.document_loaders import PyPDFLoader, TextLoader, JSONLoader, CSVLoader
14
+ import tempfile # μž„μ‹œ νŒŒμΌμ„ μƒμ„±ν•˜κΈ° μœ„ν•œ λΌμ΄λΈŒλŸ¬λ¦¬μž…λ‹ˆλ‹€.
15
+ import os
16
+
17
+
18
+ # PDF λ¬Έμ„œλ‘œλΆ€ν„° ν…μŠ€νŠΈλ₯Ό μΆ”μΆœν•˜λŠ” ν•¨μˆ˜μž…λ‹ˆλ‹€.
19
+ def get_pdf_text(pdf_docs):
20
+ temp_dir = tempfile.TemporaryDirectory() # μž„μ‹œ 디렉토리λ₯Ό μƒμ„±ν•©λ‹ˆλ‹€.
21
+ temp_filepath = os.path.join(temp_dir.name, pdf_docs.name) # μž„μ‹œ 파일 경둜λ₯Ό μƒμ„±ν•©λ‹ˆλ‹€.
22
+ with open(temp_filepath, "wb") as f: # μž„μ‹œ νŒŒμΌμ„ λ°”μ΄λ„ˆλ¦¬ μ“°κΈ° λͺ¨λ“œλ‘œ μ—½λ‹ˆλ‹€.
23
+ f.write(pdf_docs.getvalue()) # PDF λ¬Έμ„œμ˜ λ‚΄μš©μ„ μž„μ‹œ νŒŒμΌμ— μ”λ‹ˆλ‹€.
24
+ pdf_loader = PyPDFLoader(temp_filepath) # PyPDFLoaderλ₯Ό μ‚¬μš©ν•΄ PDFλ₯Ό λ‘œλ“œν•©λ‹ˆλ‹€.
25
+ pdf_doc = pdf_loader.load() # ν…μŠ€νŠΈλ₯Ό μΆ”μΆœν•©λ‹ˆλ‹€.
26
+ return pdf_doc # μΆ”μΆœν•œ ν…μŠ€νŠΈλ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€.
27
+
28
+
29
+ # 과제
30
+ # μ•„λž˜ ν…μŠ€νŠΈ μΆ”μΆœ ν•¨μˆ˜λ₯Ό μž‘μ„±
31
+
32
+ def get_text_file(txt_docs):
33
+ temp_dir = tempfile.TemporaryDirectory()
34
+ temp_filepath = os.path.join(temp_dir.name, txt_docs.name)
35
+ with open(temp_filepath, "wb") as f:
36
+ f.write(txt_docs.getvalue())
37
+ txt_loader = TextLoader(temp_filepath)
38
+ txt_doc = txt_loader.load()
39
+ return txt_doc
40
+
41
+ def get_csv_file(csv_docs):
42
+ temp_dir = tempfile.TemporaryDirectory()
43
+ temp_filepath = os.path.join(temp_dir.name, csv_docs.name)
44
+ with open(temp_filepath, "wb") as f:
45
+ f.write(csv_docs.getvalue())
46
+ csv_loader = CSVLoader(
47
+ file_path=temp_filepath
48
+ )
49
+ csv_doc = csv_loader.load()
50
+ return csv_doc
51
+
52
+
53
+ def get_json_file(json_docs):
54
+ temp_dir = tempfile.TemporaryDirectory()
55
+ temp_filepath = os.path.join(temp_dir.name, json_docs.name)
56
+ with open(temp_filepath, "wb") as f:
57
+ f.write(json_docs.getvalue())
58
+ json_loader = JSONLoader(
59
+ file_path=temp_filepath,
60
+ jq_schema='.messages[].content',
61
+ text_content=False)
62
+
63
+ json_doc = json_loader.load()
64
+ return json_doc
65
+
66
+
67
+ # λ¬Έμ„œλ“€μ„ μ²˜λ¦¬ν•˜μ—¬ ν…μŠ€νŠΈ 청크둜 λ‚˜λˆ„λŠ” ν•¨μˆ˜μž…λ‹ˆλ‹€.
68
+ def get_text_chunks(documents):
69
+ text_splitter = RecursiveCharacterTextSplitter(
70
+ chunk_size=1000, # 청크의 크기λ₯Ό μ§€μ •ν•©λ‹ˆλ‹€.
71
+ chunk_overlap=200, # 청크 μ‚¬μ΄μ˜ 쀑볡을 μ§€μ •ν•©λ‹ˆλ‹€.
72
+ length_function=len # ν…μŠ€νŠΈμ˜ 길이λ₯Ό μΈ‘μ •ν•˜λŠ” ν•¨μˆ˜λ₯Ό μ§€μ •ν•©λ‹ˆλ‹€.
73
+ )
74
+
75
+ documents = text_splitter.split_documents(documents) # λ¬Έμ„œλ“€μ„ 청크둜 λ‚˜λˆ•λ‹ˆλ‹€
76
+ return documents # λ‚˜λˆˆ 청크λ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€.
77
+
78
+
79
+ # ν…μŠ€νŠΈ μ²­ν¬λ“€λ‘œλΆ€ν„° 벑터 μŠ€ν† μ–΄λ₯Ό μƒμ„±ν•˜λŠ” ν•¨μˆ˜μž…λ‹ˆλ‹€.
80
+ def get_vectorstore(text_chunks):
81
+ # OpenAI μž„λ² λ”© λͺ¨λΈμ„ λ‘œλ“œν•©λ‹ˆλ‹€. (Embedding models - Ada v2)
82
+
83
+ embeddings = OpenAIEmbeddings()
84
+ vectorstore = FAISS.from_documents(text_chunks, embeddings) # FAISS 벑터 μŠ€ν† μ–΄λ₯Ό μƒμ„±ν•©λ‹ˆλ‹€.
85
+
86
+ return vectorstore # μƒμ„±λœ 벑터 μŠ€ν† μ–΄λ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€.
87
+
88
+
89
+ def get_conversation_chain(vectorstore):
90
+ gpt_model_name = 'gpt-3.5-turbo'
91
+ llm = ChatOpenAI(model_name=gpt_model_name) # gpt-3.5 λͺ¨λΈ λ‘œλ“œ
92
+
93
+ # λŒ€ν™” 기둝을 μ €μž₯ν•˜κΈ° μœ„ν•œ λ©”λͺ¨λ¦¬λ₯Ό μƒμ„±ν•©λ‹ˆλ‹€.
94
+ memory = ConversationBufferMemory(
95
+ memory_key='chat_history', return_messages=True)
96
+ # λŒ€ν™” 검색 체인을 μƒμ„±ν•©λ‹ˆλ‹€.
97
+ conversation_chain = ConversationalRetrievalChain.from_llm(
98
+ llm=llm,
99
+ retriever=vectorstore.as_retriever(),
100
+ memory=memory
101
+ )
102
+ return conversation_chain
103
+
104
+
105
+ # μ‚¬μš©μž μž…λ ₯을 μ²˜λ¦¬ν•˜λŠ” ν•¨μˆ˜μž…λ‹ˆλ‹€.
106
+ def handle_userinput(user_question):
107
+ # λŒ€ν™” 체인을 μ‚¬μš©ν•˜μ—¬ μ‚¬μš©μž μ§ˆλ¬Έμ— λŒ€ν•œ 응닡을 μƒμ„±ν•©λ‹ˆλ‹€.
108
+ response = st.session_state.conversation({'question': user_question})
109
+ # λŒ€ν™” 기둝을 μ €μž₯ν•©λ‹ˆλ‹€.
110
+ st.session_state.chat_history = response['chat_history']
111
+
112
+ for i, message in enumerate(st.session_state.chat_history):
113
+ if i % 2 == 0:
114
+ st.write(user_template.replace(
115
+ "{{MSG}}", message.content), unsafe_allow_html=True)
116
+ else:
117
+ st.write(bot_template.replace(
118
+ "{{MSG}}", message.content), unsafe_allow_html=True)
119
+
120
+
121
+ def main():
122
+ load_dotenv()
123
+ st.set_page_config(page_title="Chat with multiple Files",
124
+ page_icon=":books:")
125
+ st.write(css, unsafe_allow_html=True)
126
+
127
+ if "conversation" not in st.session_state:
128
+ st.session_state.conversation = None
129
+ if "chat_history" not in st.session_state:
130
+ st.session_state.chat_history = None
131
+
132
+ st.header("Chat with multiple Files :")
133
+ user_question = st.text_input("Ask a question about your documents:")
134
+ if user_question:
135
+ handle_userinput(user_question)
136
+
137
+ with st.sidebar:
138
+ openai_key = st.text_input("Paste your OpenAI API key (sk-...)")
139
+ if openai_key:
140
+ os.environ["OPENAI_API_KEY"] = openai_key
141
+
142
+ st.subheader("Your documents")
143
+ docs = st.file_uploader(
144
+ "Upload your PDFs here and click on 'Process'", accept_multiple_files=True)
145
+ if st.button("Process"):
146
+ with st.spinner("Processing"):
147
+ # get pdf text
148
+ doc_list = []
149
+
150
+ for file in docs:
151
+ print('file - type : ', file.type)
152
+ if file.type == 'text/plain':
153
+ # file is .txt
154
+ doc_list.extend(get_text_file(file))
155
+ elif file.type in ['application/octet-stream', 'application/pdf']:
156
+ # file is .pdf
157
+ doc_list.extend(get_pdf_text(file))
158
+ elif file.type == 'text/csv':
159
+ # file is .csv
160
+ doc_list.extend(get_csv_file(file))
161
+ elif file.type == 'application/json':
162
+ # file is .json
163
+ doc_list.extend(get_json_file(file))
164
+
165
+ # get the text chunks
166
+ text_chunks = get_text_chunks(doc_list)
167
+
168
+ # create vector store
169
+ vectorstore = get_vectorstore(text_chunks)
170
+
171
+ # create conversation chain
172
+ st.session_state.conversation = get_conversation_chain(
173
+ vectorstore)
174
+
175
+
176
+ if __name__ == '__main__':
177
+ main()