Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,66 +1,89 @@
|
|
1 |
import streamlit as st
|
2 |
from dotenv import load_dotenv
|
3 |
-
from
|
4 |
-
from langchain.
|
5 |
-
from langchain.
|
|
|
|
|
6 |
from langchain.chat_models import ChatOpenAI
|
7 |
from langchain.memory import ConversationBufferMemory
|
8 |
from langchain.chains import ConversationalRetrievalChain
|
|
|
|
|
9 |
from langchain.document_loaders import PyPDFLoader, TextLoader, JSONLoader, CSVLoader
|
10 |
-
import tempfile
|
11 |
import os
|
12 |
|
13 |
-
css = """
|
14 |
-
<style>
|
15 |
-
/* 여기에 CSS 코드를 넣어주세요 */
|
16 |
-
</style>
|
17 |
-
"""
|
18 |
|
|
|
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 |
def get_text_file(docs):
|
29 |
-
|
30 |
-
text
|
31 |
-
return [text]
|
32 |
|
33 |
def get_csv_file(docs):
|
34 |
-
|
35 |
-
csv_text =
|
36 |
-
|
|
|
|
|
|
|
|
|
|
|
37 |
|
38 |
def get_json_file(docs):
|
39 |
-
|
40 |
-
json_text =
|
41 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
42 |
|
|
|
43 |
def get_text_chunks(documents):
|
44 |
text_splitter = RecursiveCharacterTextSplitter(
|
45 |
-
chunk_size=1000,
|
46 |
-
chunk_overlap=200,
|
47 |
-
length_function=len
|
48 |
)
|
49 |
|
50 |
-
documents = text_splitter.split_documents(documents)
|
51 |
-
return documents
|
52 |
|
|
|
|
|
53 |
def get_vectorstore(text_chunks):
|
|
|
|
|
54 |
embeddings = OpenAIEmbeddings()
|
55 |
-
vectorstore = FAISS.from_documents(text_chunks, embeddings)
|
56 |
-
|
|
|
|
|
57 |
|
58 |
def get_conversation_chain(vectorstore):
|
59 |
gpt_model_name = 'gpt-3.5-turbo'
|
60 |
-
llm = ChatOpenAI(model_name=gpt_model_name)
|
61 |
|
|
|
62 |
memory = ConversationBufferMemory(
|
63 |
memory_key='chat_history', return_messages=True)
|
|
|
64 |
conversation_chain = ConversationalRetrievalChain.from_llm(
|
65 |
llm=llm,
|
66 |
retriever=vectorstore.as_retriever(),
|
@@ -68,8 +91,12 @@ def get_conversation_chain(vectorstore):
|
|
68 |
)
|
69 |
return conversation_chain
|
70 |
|
|
|
|
|
71 |
def handle_userinput(user_question):
|
|
|
72 |
response = st.session_state.conversation({'question': user_question})
|
|
|
73 |
st.session_state.chat_history = response['chat_history']
|
74 |
|
75 |
for i, message in enumerate(st.session_state.chat_history):
|
@@ -80,6 +107,7 @@ def handle_userinput(user_question):
|
|
80 |
st.write(bot_template.replace(
|
81 |
"{{MSG}}", message.content), unsafe_allow_html=True)
|
82 |
|
|
|
83 |
def main():
|
84 |
load_dotenv()
|
85 |
st.set_page_config(page_title="Chat with multiple Files",
|
@@ -103,26 +131,37 @@ def main():
|
|
103 |
|
104 |
st.subheader("Your documents")
|
105 |
docs = st.file_uploader(
|
106 |
-
"Upload your
|
107 |
if st.button("Process"):
|
108 |
with st.spinner("Processing"):
|
|
|
109 |
doc_list = []
|
110 |
|
111 |
for file in docs:
|
|
|
112 |
if file.type == 'text/plain':
|
|
|
113 |
doc_list.extend(get_text_file(file))
|
114 |
elif file.type in ['application/octet-stream', 'application/pdf']:
|
|
|
115 |
doc_list.extend(get_pdf_text(file))
|
116 |
elif file.type == 'text/csv':
|
|
|
117 |
doc_list.extend(get_csv_file(file))
|
118 |
elif file.type == 'application/json':
|
|
|
119 |
doc_list.extend(get_json_file(file))
|
120 |
|
|
|
121 |
text_chunks = get_text_chunks(doc_list)
|
|
|
|
|
122 |
vectorstore = get_vectorstore(text_chunks)
|
|
|
|
|
123 |
st.session_state.conversation = get_conversation_chain(
|
124 |
vectorstore)
|
125 |
|
|
|
126 |
if __name__ == '__main__':
|
127 |
main()
|
128 |
-
|
|
|
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 |
|
32 |
def get_text_file(docs):
|
33 |
+
text = docs.getvalue().decode("utf-8") # Read the text file
|
34 |
+
return [text] # Return a list containing the text
|
|
|
35 |
|
36 |
def get_csv_file(docs):
|
37 |
+
import pandas as pd
|
38 |
+
csv_text = docs.getvalue().decode("utf-8") # Read the CSV content
|
39 |
+
csv_data = pd.read_csv(pd.compat.StringIO(csv_text)) # Parse CSV data
|
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 # Return a list containing text from CSV rows
|
45 |
|
46 |
def get_json_file(docs):
|
47 |
+
import json
|
48 |
+
json_text = docs.getvalue().decode("utf-8") # Read the JSON content
|
49 |
+
json_data = json.loads(json_text) # Parse JSON data
|
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 # Return a list containing text from JSON
|
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) # 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(),
|
|
|
91 |
)
|
92 |
return conversation_chain
|
93 |
|
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):
|
|
|
107 |
st.write(bot_template.replace(
|
108 |
"{{MSG}}", message.content), unsafe_allow_html=True)
|
109 |
|
110 |
+
|
111 |
def main():
|
112 |
load_dotenv()
|
113 |
st.set_page_config(page_title="Chat with multiple Files",
|
|
|
131 |
|
132 |
st.subheader("Your documents")
|
133 |
docs = st.file_uploader(
|
134 |
+
"Upload your PDFs here and click on 'Process'", accept_multiple_files=True)
|
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 in ['application/octet-stream', 'application/pdf']:
|
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__':
|
167 |
main()
|
|