Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,89 +1,74 @@
|
|
| 1 |
import streamlit as st
|
| 2 |
-
from
|
| 3 |
-
from
|
| 4 |
-
from langchain.
|
| 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
|
| 12 |
-
|
| 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())
|
| 24 |
-
pdf_loader = PyPDFLoader(temp_filepath)
|
| 25 |
-
pdf_doc = pdf_loader.load()
|
| 26 |
-
return pdf_doc
|
| 27 |
|
| 28 |
|
| 29 |
-
#
|
| 30 |
-
# 아래 텍스트 추출 함수를 작성
|
| 31 |
-
|
| 32 |
def get_text_file(docs):
|
| 33 |
-
text = docs.getvalue().decode("utf-8")
|
| 34 |
-
return [text]
|
|
|
|
| 35 |
|
|
|
|
| 36 |
def get_csv_file(docs):
|
| 37 |
import pandas as pd
|
| 38 |
-
csv_text = docs.getvalue().decode("utf-8")
|
| 39 |
-
csv_data = pd.read_csv(pd.compat.StringIO(csv_text))
|
| 40 |
csv_columns = csv_data.columns.tolist()
|
| 41 |
csv_rows = csv_data.to_dict(orient='records')
|
| 42 |
-
# Convert CSV rows to text
|
| 43 |
csv_texts = [', '.join([f"{col}: {row[col]}" for col in csv_columns]) for row in csv_rows]
|
| 44 |
-
return csv_texts
|
| 45 |
|
|
|
|
|
|
|
| 46 |
def get_json_file(docs):
|
| 47 |
import json
|
| 48 |
-
json_text = docs.getvalue().decode("utf-8")
|
| 49 |
-
json_data = json.loads(json_text)
|
| 50 |
-
# Extract text from JSON data based on your JSON structure
|
| 51 |
-
# For instance, assuming JSON has a 'text' key in each object:
|
| 52 |
json_texts = [item.get('text', '') for item in json_data]
|
| 53 |
-
return json_texts
|
| 54 |
-
|
| 55 |
|
| 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)
|
| 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)
|
| 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(),
|
|
@@ -94,25 +79,18 @@ def get_conversation_chain(vectorstore):
|
|
| 94 |
|
| 95 |
# 사용자 입력을 처리하는 함수입니다.
|
| 96 |
def handle_userinput(user_question):
|
| 97 |
-
# 대화 체인을 사용하여 사용자 질문에 대한 응답을 생성합니다.
|
| 98 |
response = st.session_state.conversation({'question': user_question})
|
| 99 |
-
# 대화 기록을 저장합니다.
|
| 100 |
st.session_state.chat_history = response['chat_history']
|
| 101 |
|
| 102 |
for i, message in enumerate(st.session_state.chat_history):
|
| 103 |
if i % 2 == 0:
|
| 104 |
-
st.write(
|
| 105 |
-
"{{MSG}}", message.content), unsafe_allow_html=True)
|
| 106 |
else:
|
| 107 |
-
st.write(
|
| 108 |
-
"{{MSG}}", message.content), unsafe_allow_html=True)
|
| 109 |
|
| 110 |
|
| 111 |
def main():
|
| 112 |
-
|
| 113 |
-
st.set_page_config(page_title="Chat with multiple Files",
|
| 114 |
-
page_icon=":books:")
|
| 115 |
-
st.write(css, unsafe_allow_html=True)
|
| 116 |
|
| 117 |
if "conversation" not in st.session_state:
|
| 118 |
st.session_state.conversation = None
|
|
@@ -121,46 +99,34 @@ def main():
|
|
| 121 |
|
| 122 |
st.header("Chat with multiple Files :")
|
| 123 |
user_question = st.text_input("Ask a question about your documents:")
|
|
|
|
| 124 |
if user_question:
|
| 125 |
handle_userinput(user_question)
|
| 126 |
|
| 127 |
with st.sidebar:
|
| 128 |
-
openai_key = st.text_input("Paste your OpenAI API key (sk-...)")
|
| 129 |
-
if openai_key:
|
| 130 |
-
os.environ["OPENAI_API_KEY"] = openai_key
|
| 131 |
-
|
| 132 |
st.subheader("Your documents")
|
| 133 |
docs = st.file_uploader(
|
| 134 |
-
"Upload your
|
|
|
|
|
|
|
|
|
|
| 135 |
if st.button("Process"):
|
| 136 |
with st.spinner("Processing"):
|
| 137 |
-
# get pdf text
|
| 138 |
doc_list = []
|
| 139 |
|
| 140 |
for file in docs:
|
| 141 |
-
print('file - type : ', file.type)
|
| 142 |
if file.type == 'text/plain':
|
| 143 |
-
# file is .txt
|
| 144 |
doc_list.extend(get_text_file(file))
|
| 145 |
-
elif file.type
|
| 146 |
-
# file is .pdf
|
| 147 |
doc_list.extend(get_pdf_text(file))
|
| 148 |
elif file.type == 'text/csv':
|
| 149 |
-
# file is .csv
|
| 150 |
doc_list.extend(get_csv_file(file))
|
| 151 |
elif file.type == 'application/json':
|
| 152 |
-
# file is .json
|
| 153 |
doc_list.extend(get_json_file(file))
|
| 154 |
|
| 155 |
-
# get the text chunks
|
| 156 |
text_chunks = get_text_chunks(doc_list)
|
| 157 |
-
|
| 158 |
-
# create vector store
|
| 159 |
vectorstore = get_vectorstore(text_chunks)
|
| 160 |
-
|
| 161 |
-
# create conversation chain
|
| 162 |
-
st.session_state.conversation = get_conversation_chain(
|
| 163 |
-
vectorstore)
|
| 164 |
|
| 165 |
|
| 166 |
if __name__ == '__main__':
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 3 |
+
from langchain.embeddings import OpenAIEmbeddings
|
| 4 |
+
from langchain.vectorstores import FAISS
|
|
|
|
|
|
|
|
|
|
| 5 |
from langchain.chat_models import ChatOpenAI
|
| 6 |
from langchain.memory import ConversationBufferMemory
|
| 7 |
from langchain.chains import ConversationalRetrievalChain
|
| 8 |
+
from langchain.document_loaders import PyPDFLoader
|
| 9 |
+
import tempfile
|
|
|
|
|
|
|
| 10 |
import os
|
| 11 |
|
| 12 |
|
| 13 |
# PDF 문서로부터 텍스트를 추출하는 함수입니다.
|
| 14 |
def get_pdf_text(pdf_docs):
|
| 15 |
+
temp_dir = tempfile.TemporaryDirectory()
|
| 16 |
+
temp_filepath = os.path.join(temp_dir.name, pdf_docs.name)
|
| 17 |
+
with open(temp_filepath, "wb") as f:
|
| 18 |
+
f.write(pdf_docs.getvalue())
|
| 19 |
+
pdf_loader = PyPDFLoader(temp_filepath)
|
| 20 |
+
pdf_doc = pdf_loader.load()
|
| 21 |
+
return pdf_doc
|
| 22 |
|
| 23 |
|
| 24 |
+
# 텍스트 파일을 처리하는 함수입니다.
|
|
|
|
|
|
|
| 25 |
def get_text_file(docs):
|
| 26 |
+
text = docs.getvalue().decode("utf-8")
|
| 27 |
+
return [text]
|
| 28 |
+
|
| 29 |
|
| 30 |
+
# CSV 파일을 처리하는 함수입니다.
|
| 31 |
def get_csv_file(docs):
|
| 32 |
import pandas as pd
|
| 33 |
+
csv_text = docs.getvalue().decode("utf-8")
|
| 34 |
+
csv_data = pd.read_csv(pd.compat.StringIO(csv_text))
|
| 35 |
csv_columns = csv_data.columns.tolist()
|
| 36 |
csv_rows = csv_data.to_dict(orient='records')
|
|
|
|
| 37 |
csv_texts = [', '.join([f"{col}: {row[col]}" for col in csv_columns]) for row in csv_rows]
|
| 38 |
+
return csv_texts
|
| 39 |
|
| 40 |
+
|
| 41 |
+
# JSON 파일을 처리하는 함수입니다.
|
| 42 |
def get_json_file(docs):
|
| 43 |
import json
|
| 44 |
+
json_text = docs.getvalue().decode("utf-8")
|
| 45 |
+
json_data = json.loads(json_text)
|
|
|
|
|
|
|
| 46 |
json_texts = [item.get('text', '') for item in json_data]
|
| 47 |
+
return json_texts
|
|
|
|
| 48 |
|
| 49 |
|
| 50 |
# 문서들을 처리하여 텍스트 청크로 나누는 함수입니다.
|
| 51 |
def get_text_chunks(documents):
|
| 52 |
text_splitter = RecursiveCharacterTextSplitter(
|
| 53 |
+
chunk_size=1000,
|
| 54 |
+
chunk_overlap=200,
|
| 55 |
+
length_function=len
|
| 56 |
)
|
| 57 |
+
return text_splitter.split_documents(documents)
|
|
|
|
|
|
|
| 58 |
|
| 59 |
|
| 60 |
# 텍스트 청크들로부터 벡터 스토어를 생성하는 함수입니다.
|
| 61 |
def get_vectorstore(text_chunks):
|
|
|
|
|
|
|
| 62 |
embeddings = OpenAIEmbeddings()
|
| 63 |
+
vectorstore = FAISS.from_documents(text_chunks, embeddings)
|
| 64 |
+
return vectorstore
|
|
|
|
| 65 |
|
| 66 |
|
| 67 |
+
# 대화 체인을 생성하는 함수입니다.
|
| 68 |
def get_conversation_chain(vectorstore):
|
| 69 |
gpt_model_name = 'gpt-3.5-turbo'
|
| 70 |
+
llm = ChatOpenAI(model_name=gpt_model_name)
|
| 71 |
+
memory = ConversationBufferMemory(memory_key='chat_history', return_messages=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
conversation_chain = ConversationalRetrievalChain.from_llm(
|
| 73 |
llm=llm,
|
| 74 |
retriever=vectorstore.as_retriever(),
|
|
|
|
| 79 |
|
| 80 |
# 사용자 입력을 처리하는 함수입니다.
|
| 81 |
def handle_userinput(user_question):
|
|
|
|
| 82 |
response = st.session_state.conversation({'question': user_question})
|
|
|
|
| 83 |
st.session_state.chat_history = response['chat_history']
|
| 84 |
|
| 85 |
for i, message in enumerate(st.session_state.chat_history):
|
| 86 |
if i % 2 == 0:
|
| 87 |
+
st.write(f"<div>{message.content}</div>", unsafe_allow_html=True)
|
|
|
|
| 88 |
else:
|
| 89 |
+
st.write(f"<div>{message.content}</div>", unsafe_allow_html=True)
|
|
|
|
| 90 |
|
| 91 |
|
| 92 |
def main():
|
| 93 |
+
st.set_page_config(page_title="Chat with multiple Files", page_icon=":books:")
|
|
|
|
|
|
|
|
|
|
| 94 |
|
| 95 |
if "conversation" not in st.session_state:
|
| 96 |
st.session_state.conversation = None
|
|
|
|
| 99 |
|
| 100 |
st.header("Chat with multiple Files :")
|
| 101 |
user_question = st.text_input("Ask a question about your documents:")
|
| 102 |
+
|
| 103 |
if user_question:
|
| 104 |
handle_userinput(user_question)
|
| 105 |
|
| 106 |
with st.sidebar:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
st.subheader("Your documents")
|
| 108 |
docs = st.file_uploader(
|
| 109 |
+
"Upload your files here and click on 'Process'",
|
| 110 |
+
accept_multiple_files=True
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
if st.button("Process"):
|
| 114 |
with st.spinner("Processing"):
|
|
|
|
| 115 |
doc_list = []
|
| 116 |
|
| 117 |
for file in docs:
|
|
|
|
| 118 |
if file.type == 'text/plain':
|
|
|
|
| 119 |
doc_list.extend(get_text_file(file))
|
| 120 |
+
elif file.type == 'application/pdf':
|
|
|
|
| 121 |
doc_list.extend(get_pdf_text(file))
|
| 122 |
elif file.type == 'text/csv':
|
|
|
|
| 123 |
doc_list.extend(get_csv_file(file))
|
| 124 |
elif file.type == 'application/json':
|
|
|
|
| 125 |
doc_list.extend(get_json_file(file))
|
| 126 |
|
|
|
|
| 127 |
text_chunks = get_text_chunks(doc_list)
|
|
|
|
|
|
|
| 128 |
vectorstore = get_vectorstore(text_chunks)
|
| 129 |
+
st.session_state.conversation = get_conversation_chain(vectorstore)
|
|
|
|
|
|
|
|
|
|
| 130 |
|
| 131 |
|
| 132 |
if __name__ == '__main__':
|