nijoow commited on
Commit
169f837
Β·
1 Parent(s): 36463f1

Upload app.py

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