Delete app.py
Browse files
app.py
DELETED
|
@@ -1,186 +0,0 @@
|
|
| 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 |
-
# txt 문서로부터 텍스트를 추출하는 함수
|
| 31 |
-
def get_text_file(text_docs):
|
| 32 |
-
temp_dir = tempfile.TemporaryDirectory()
|
| 33 |
-
temp_filepath = os.path.join(temp_dir.name, text_docs.name)
|
| 34 |
-
with open(temp_filepath, "wb") as f:
|
| 35 |
-
f.write(text_docs.getvalue())
|
| 36 |
-
text_loader = TextLoader(temp_filepath)
|
| 37 |
-
text_doc = text_loader.load()
|
| 38 |
-
return text_doc
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
# csv 문서로부터 텍스트를 추출하는 함수
|
| 43 |
-
def get_csv_file(csv_docs):
|
| 44 |
-
temp_dir = tempfile.TemporaryDirectory()
|
| 45 |
-
temp_filepath = os.path.join(temp_dir.name, csv_docs.name)
|
| 46 |
-
with open(temp_filepath, "wb") as f:
|
| 47 |
-
f.write(csv_docs.getvalue())
|
| 48 |
-
csv_loader = CSVLoader(temp_filepath)
|
| 49 |
-
csv_doc = csv_loader.load()
|
| 50 |
-
return csv_doc
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
# json 문서로부터 텍스트를 추출하는 함수
|
| 54 |
-
class JSONLoader:
|
| 55 |
-
def __init__(self, file_path, jq_schema):
|
| 56 |
-
self.file_path = file_path
|
| 57 |
-
self.jq_schema = jq_schema
|
| 58 |
-
|
| 59 |
-
def load(self):
|
| 60 |
-
with open(self.file_path, 'r') as json_file:
|
| 61 |
-
data = json.load(json_file)
|
| 62 |
-
users_text = [user.get('text', '') for user in data.get('users', [])]
|
| 63 |
-
return users_text
|
| 64 |
-
|
| 65 |
-
def get_json_file(json_docs):
|
| 66 |
-
temp_dir = tempfile.TemporaryDirectory()
|
| 67 |
-
temp_filepath = os.path.join(temp_dir.name, json_docs.name)
|
| 68 |
-
with open(temp_filepath, "wb") as f:
|
| 69 |
-
f.write(json_docs.getvalue())
|
| 70 |
-
json_loader = JSONLoader(temp_filepath, jq_schema={})
|
| 71 |
-
users_text = json_loader.load()
|
| 72 |
-
return users_text
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
# 문서들을 처리하여 텍스트 청크로 나누는 함수입니다.
|
| 77 |
-
def get_text_chunks(documents):
|
| 78 |
-
text_splitter = RecursiveCharacterTextSplitter(
|
| 79 |
-
chunk_size=1000, # 청크의 크기를 지정합니다.
|
| 80 |
-
chunk_overlap=200, # 청크 사이의 중복을 지정합니다.
|
| 81 |
-
length_function=len # 텍스트의 길이를 측정하는 함수를 지정합니다.
|
| 82 |
-
)
|
| 83 |
-
|
| 84 |
-
documents = text_splitter.split_documents(documents) # 문서들을 청크로 나눕니다
|
| 85 |
-
return documents # 나눈 청크를 반환합니다.
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
# 텍스트 청크들로부터 벡터 스토어를 생성하는 함수입니다.
|
| 90 |
-
def get_vectorstore(text_chunks):
|
| 91 |
-
# OpenAI 임베딩 모델을 로드합니다. (Embedding models - Ada v2)
|
| 92 |
-
|
| 93 |
-
embeddings = OpenAIEmbeddings()
|
| 94 |
-
vectorstore = FAISS.from_documents(text_chunks, embeddings) # FAISS 벡터 스토어를 생성합니다.
|
| 95 |
-
|
| 96 |
-
return vectorstore # 생성된 벡터 스토어를 반환합니다.
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
def get_conversation_chain(vectorstore):
|
| 100 |
-
gpt_model_name = 'gpt-3.5-turbo'
|
| 101 |
-
llm = ChatOpenAI(model_name = gpt_model_name) #gpt-3.5 모델 로드
|
| 102 |
-
|
| 103 |
-
# 대화 기록을 저장하기 위한 메모리를 생성합니다.
|
| 104 |
-
memory = ConversationBufferMemory(
|
| 105 |
-
memory_key='chat_history', return_messages=True)
|
| 106 |
-
# 대화 검색 체인을 생성합니다.
|
| 107 |
-
conversation_chain = ConversationalRetrievalChain.from_llm(
|
| 108 |
-
llm=llm,
|
| 109 |
-
retriever=vectorstore.as_retriever(),
|
| 110 |
-
memory=memory
|
| 111 |
-
)
|
| 112 |
-
return conversation_chain
|
| 113 |
-
|
| 114 |
-
# 사용자 입력을 처리하는 함수입니다.
|
| 115 |
-
def handle_userinput(user_question):
|
| 116 |
-
# 대화 체인을 사용하여 사용자 질문에 대한 응답을 생성합니다.
|
| 117 |
-
response = st.session_state.conversation({'question': user_question})
|
| 118 |
-
# 대화 기록을 저장합니다.
|
| 119 |
-
st.session_state.chat_history = response['chat_history']
|
| 120 |
-
|
| 121 |
-
for i, message in enumerate(st.session_state.chat_history):
|
| 122 |
-
if i % 2 == 0:
|
| 123 |
-
st.write(user_template.replace(
|
| 124 |
-
"{{MSG}}", message.content), unsafe_allow_html=True)
|
| 125 |
-
else:
|
| 126 |
-
st.write(bot_template.replace(
|
| 127 |
-
"{{MSG}}", message.content), unsafe_allow_html=True)
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
def main():
|
| 131 |
-
load_dotenv()
|
| 132 |
-
st.set_page_config(page_title="Chat with multiple Files",
|
| 133 |
-
page_icon=":books:")
|
| 134 |
-
st.write(css, unsafe_allow_html=True)
|
| 135 |
-
|
| 136 |
-
if "conversation" not in st.session_state:
|
| 137 |
-
st.session_state.conversation = None
|
| 138 |
-
if "chat_history" not in st.session_state:
|
| 139 |
-
st.session_state.chat_history = None
|
| 140 |
-
|
| 141 |
-
st.header("Chat with multiple Files :")
|
| 142 |
-
user_question = st.text_input("Ask a question about your documents:")
|
| 143 |
-
if user_question:
|
| 144 |
-
handle_userinput(user_question)
|
| 145 |
-
|
| 146 |
-
with st.sidebar:
|
| 147 |
-
openai_key = st.text_input("Paste your OpenAI API key (sk-...)")
|
| 148 |
-
if openai_key:
|
| 149 |
-
os.environ["OPENAI_API_KEY"] = openai_key
|
| 150 |
-
|
| 151 |
-
st.subheader("Your documents")
|
| 152 |
-
docs = st.file_uploader(
|
| 153 |
-
"Upload your PDFs here and click on 'Process'", accept_multiple_files=True)
|
| 154 |
-
if st.button("Process"):
|
| 155 |
-
with st.spinner("Processing"):
|
| 156 |
-
# get pdf text
|
| 157 |
-
doc_list = []
|
| 158 |
-
|
| 159 |
-
for file in docs:
|
| 160 |
-
print('file - type : ', file.type)
|
| 161 |
-
if file.type == 'text/plain':
|
| 162 |
-
# file is .txt
|
| 163 |
-
doc_list.extend(get_text_file(file))
|
| 164 |
-
elif file.type in ['application/octet-stream', 'application/pdf']:
|
| 165 |
-
# file is .pdf
|
| 166 |
-
doc_list.extend(get_pdf_text(file))
|
| 167 |
-
elif file.type == 'text/csv':
|
| 168 |
-
# file is .csv
|
| 169 |
-
doc_list.extend(get_csv_file(file))
|
| 170 |
-
elif file.type == 'application/json':
|
| 171 |
-
# file is .json
|
| 172 |
-
doc_list.extend(get_json_file(file))
|
| 173 |
-
|
| 174 |
-
# get the text chunks
|
| 175 |
-
text_chunks = get_text_chunks(doc_list)
|
| 176 |
-
|
| 177 |
-
# create vector store
|
| 178 |
-
vectorstore = get_vectorstore(text_chunks)
|
| 179 |
-
|
| 180 |
-
# create conversation chain
|
| 181 |
-
st.session_state.conversation = get_conversation_chain(
|
| 182 |
-
vectorstore)
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
if __name__ == '__main__':
|
| 186 |
-
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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