se0kcess commited on
Commit
e765f70
β€’
1 Parent(s): e5a3dff

"new file"

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