EUNSEO56 commited on
Commit
2487ea2
โ€ข
1 Parent(s): fa1826c

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +174 -0
app.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ def get_text_file(text_docs):
32
+ temp_dir2 = tempfile.TemporaryDirectory() # ์ž„์‹œ ๋””๋ ‰ํ† ๋ฆฌ๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค.
33
+ temp_filepath2 = os.path.join(temp_dir2.name, text_docs.name) # ์ž„์‹œ ํŒŒ์ผ ๊ฒฝ๋กœ๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค.
34
+ with open(temp_filepath2, "wb") as f: # ์ž„์‹œ ํŒŒ์ผ์„ ๋ฐ”์ด๋„ˆ๋ฆฌ ์“ฐ๊ธฐ ๋ชจ๋“œ๋กœ ์—ฝ๋‹ˆ๋‹ค.
35
+ f.write(text_docs.getvalue()) # text ๋ฌธ์„œ์˜ ๋‚ด์šฉ์„ ์ž„์‹œ ํŒŒ์ผ์— ์”๋‹ˆ๋‹ค.
36
+ text_loader = TextLoader(temp_filepath2) # TextLoader๋ฅผ ์‚ฌ์šฉํ•ด text๋ฅผ ๋กœ๋“œํ•ฉ๋‹ˆ๋‹ค.
37
+ text_doc = text_loader.load() # ํ…์ŠคํŠธ๋ฅผ ์ถ”์ถœํ•ฉ๋‹ˆ๋‹ค.
38
+ return text_doc # ์ถ”์ถœํ•œ ํ…์ŠคํŠธ๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.
39
+
40
+ def get_csv_file(csv_docs):
41
+ temp_dir3 = tempfile.TemporaryDirectory() # ์ž„์‹œ ๋””๋ ‰ํ† ๋ฆฌ๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค.
42
+ temp_filepath3 = os.path.join(temp_dir3.name, csv_docs.name) # ์ž„์‹œ ํŒŒ์ผ ๊ฒฝ๋กœ๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค.
43
+ with open(temp_filepath3, "wb") as f: # ์ž„์‹œ ํŒŒ์ผ์„ ๋ฐ”์ด๋„ˆ๋ฆฌ ์“ฐ๊ธฐ ๋ชจ๋“œ๋กœ ์—ฝ๋‹ˆ๋‹ค.
44
+ f.write(csv_docs.getvalue()) # csv ๋ฌธ์„œ์˜ ๋‚ด์šฉ์„ ์ž„์‹œ ํŒŒ์ผ์— ์”๋‹ˆ๋‹ค.
45
+ csv_loader = CSVLoader(temp_filepath3) # CSVLoader๋ฅผ ์‚ฌ์šฉํ•ด csv๋ฅผ ๋กœ๋“œํ•ฉ๋‹ˆ๋‹ค.
46
+ csv_doc = csv_loader.load() # ํ…์ŠคํŠธ๋ฅผ ์ถ”์ถœํ•ฉ๋‹ˆ๋‹ค.
47
+ return csv_doc # ์ถ”์ถœํ•œ ํ…์ŠคํŠธ๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.
48
+
49
+ def get_json_file(json_docs):
50
+ temp_dir4 = tempfile.TemporaryDirectory() # ์ž„์‹œ ๋””๋ ‰ํ† ๋ฆฌ๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค.
51
+ temp_filepath4 = os.path.join(temp_dir4.name, json_docs.name) # ์ž„์‹œ ํŒŒ์ผ ๊ฒฝ๋กœ๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค.
52
+ with open(temp_filepath4, "wb") as f: # ์ž„์‹œ ํŒŒ์ผ์„ ๋ฐ”์ด๋„ˆ๋ฆฌ ์“ฐ๊ธฐ ๋ชจ๋“œ๋กœ ์—ฝ๋‹ˆ๋‹ค.
53
+ f.write(json_docs.getvalue()) # json ๋ฌธ์„œ์˜ ๋‚ด์šฉ์„ ์ž„์‹œ ํŒŒ์ผ์— ์”๋‹ˆ๋‹ค.
54
+ json_loader = JSONLoader(temp_filepath4, jq_schema=<your_json_schema>) # JSONLoader๋ฅผ ์‚ฌ์šฉํ•ด json๋ฅผ ๋กœ๋“œํ•ฉ๋‹ˆ๋‹ค.
55
+ json_doc = json_loader.load() # ํ…์ŠคํŠธ๋ฅผ ์ถ”์ถœํ•ฉ๋‹ˆ๋‹ค.
56
+ return json_doc # ์ถ”์ถœํ•œ ํ…์ŠคํŠธ๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.
57
+
58
+
59
+ # ๋ฌธ์„œ๋“ค์„ ์ฒ˜๋ฆฌํ•˜์—ฌ ํ…์ŠคํŠธ ์ฒญํฌ๋กœ ๋‚˜๋ˆ„๋Š” ํ•จ์ˆ˜์ž…๋‹ˆ๋‹ค.
60
+ def get_text_chunks(documents):
61
+ text_splitter = RecursiveCharacterTextSplitter(
62
+ chunk_size=1000, # ์ฒญํฌ์˜ ํฌ๊ธฐ๋ฅผ ์ง€์ •ํ•ฉ๋‹ˆ๋‹ค.
63
+ chunk_overlap=200, # ์ฒญํฌ ์‚ฌ์ด์˜ ์ค‘๋ณต์„ ์ง€์ •ํ•ฉ๋‹ˆ๋‹ค.
64
+ length_function=len # ํ…์ŠคํŠธ์˜ ๊ธธ์ด๋ฅผ ์ธก์ •ํ•˜๋Š” ํ•จ์ˆ˜๋ฅผ ์ง€์ •ํ•ฉ๋‹ˆ๋‹ค.
65
+ )
66
+
67
+ documents = text_splitter.split_documents(documents) # ๋ฌธ์„œ๋“ค์„ ์ฒญํฌ๋กœ ๋‚˜๋ˆ•๋‹ˆ๋‹ค
68
+ if not documents:
69
+ raise ValueError("์—…๋กœ๋“œ๋œ ๋ฌธ์„œ๊ฐ€ ์—†๊ฑฐ๋‚˜ ๋ชจ๋“  ๋ฌธ์„œ๊ฐ€ ๋น„์–ด ์žˆ์Šต๋‹ˆ๋‹ค.")
70
+ return documents # ๋‚˜๋ˆˆ ์ฒญํฌ๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.
71
+
72
+
73
+ # ํ…์ŠคํŠธ ์ฒญํฌ๋“ค๋กœ๋ถ€ํ„ฐ ๋ฒกํ„ฐ ์Šคํ† ์–ด๋ฅผ ์ƒ์„ฑํ•˜๋Š” ํ•จ์ˆ˜์ž…๋‹ˆ๋‹ค.
74
+ def get_vectorstore(text_chunks):
75
+ # OpenAI ์ž„๋ฒ ๋”ฉ ๋ชจ๋ธ์„ ๋กœ๋“œํ•ฉ๋‹ˆ๋‹ค. (Embedding models - Ada v2)
76
+
77
+ embeddings = OpenAIEmbeddings()
78
+ vectorstore = FAISS.from_documents(text_chunks, embeddings) # FAISS ๋ฒกํ„ฐ ์Šคํ† ์–ด๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค.
79
+
80
+ return vectorstore # ์ƒ์„ฑ๋œ ๋ฒกํ„ฐ ์Šคํ† ์–ด๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.
81
+
82
+
83
+ def get_conversation_chain(vectorstore):
84
+ gpt_model_name = 'gpt-3.5-turbo'
85
+ llm = ChatOpenAI(model_name = gpt_model_name) #gpt-3.5 ๋ชจ๋ธ ๋กœ๋“œ
86
+
87
+ # ๋Œ€ํ™” ๊ธฐ๋ก์„ ์ €์žฅํ•˜๊ธฐ ์œ„ํ•œ ๋ฉ”๋ชจ๋ฆฌ๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค.
88
+ memory = ConversationBufferMemory(
89
+ memory_key='chat_history', return_messages=True)
90
+ # ๋Œ€ํ™” ๊ฒ€์ƒ‰ ์ฒด์ธ์„ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค.
91
+ conversation_chain = ConversationalRetrievalChain.from_llm(
92
+ llm=llm,
93
+ retriever=vectorstore.as_retriever(),
94
+ memory=memory
95
+ )
96
+ return conversation_chain
97
+
98
+ # ์‚ฌ์šฉ์ž ์ž…๋ ฅ์„ ์ฒ˜๋ฆฌํ•˜๋Š” ํ•จ์ˆ˜์ž…๋‹ˆ๋‹ค.
99
+ def handle_userinput(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 or st.session_state.conversation is None:
121
+ st.session_state.conversation = None
122
+ st.session_state.chat_history = None
123
+
124
+ st.header("Chat with multiple Files :")
125
+ user_question = st.text_input("Ask a question about your documents:")
126
+
127
+ # "Send" ๋ฒ„ํŠผ
128
+ if st.button("Send"):
129
+ if user_question:
130
+ handle_userinput(user_question)
131
+
132
+ if user_question:
133
+ handle_userinput(user_question)
134
+
135
+ with st.sidebar:
136
+ openai_key = st.text_input("Paste your OpenAI API key (sk-...)")
137
+ if openai_key:
138
+ os.environ["OPENAI_API_KEY"] = openai_key
139
+
140
+ st.subheader("Your documents")
141
+ docs = st.file_uploader(
142
+ "Upload your PDFs, TEXTfiles, CSVfiles, JSONfiles here and click on 'Process'", accept_multiple_files=True)
143
+ if st.button("Process"):
144
+ with st.spinner("Processing"):
145
+ # get pdf text
146
+ doc_list = []
147
+
148
+ for file in docs:
149
+ print('file - type : ', file.type)
150
+ if file.type == 'text/plain':
151
+ # file is .txt
152
+ doc_list.extend(get_text_file(file))
153
+ elif file.type in ['application/octet-stream', 'application/pdf']:
154
+ # file is .pdf
155
+ doc_list.extend(get_pdf_text(file))
156
+ elif file.type == 'text/csv':
157
+ # file is .csv
158
+ doc_list.extend(get_csv_file(file))
159
+ elif file.type == 'application/json':
160
+ # file is .json
161
+ doc_list.extend(get_json_file(file))
162
+
163
+ # get the text chunks
164
+ text_chunks = get_text_chunks(doc_list)
165
+
166
+ # create vector store
167
+ vectorstore = get_vectorstore(text_chunks)
168
+
169
+ # create conversation chain
170
+ st.session_state.conversation = get_conversation_chain(
171
+ vectorstore)
172
+
173
+ if __name__ == '__main__':
174
+ main()