Yoon310 commited on
Commit
83257dc
1 Parent(s): 4f36573

upload file

Browse files
Files changed (3) hide show
  1. app.py +173 -0
  2. htmlTemplates.py +44 -0
  3. requirements.txt +14 -0
app.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #[1]Document Loading : LangChain에서 제공하는 문서 파일(json, txt, csv, pdf) Loader를 통해 PDF에서 Text 추출
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
+ # TXT 문서로부터 텍스트를 추출하는 함수입니다.
32
+ def get_text_file(text_docs):
33
+ temp_dir = tempfile.TemporaryDirectory() # 임시 디렉토리를 생성합니다.
34
+ temp_filepath = os.path.join(temp_dir.name, text_docs.name) # 임시 파일 경로를 생성합니다.
35
+ with open(temp_filepath, "wb") as f: # 임시 파일을 바이너리 쓰기 모드로 엽니다.
36
+ f.write(text_docs.getvalue()) # TXT 문서의 내용을 임시 파일에 씁니다.
37
+ text_loader = TextLoader(temp_filepath) # TextLoader를 사용해 TXT를 로드합니다.
38
+ text_doc = text_loader.load() # 텍스트를 추출합니다.
39
+ return text_doc
40
+
41
+ # CSV 문서로부터 텍스트를 추출하는 함수입니다.
42
+ def get_csv_file(csv_docs):
43
+ temp_dir = tempfile.TemporaryDirectory() # 임시 디렉토리를 생성합니다.
44
+ temp_filepath = os.path.join(temp_dir.name, csv_docs.name) # 임시 파일 경로를 생성합니다.
45
+ with open(temp_filepath, "wb") as f: # 임시 파일을 바이너리 쓰기 모드로 엽니다.
46
+ f.write(csv_docs.getvalue()) # CSV 문서의 내용을 임시 파일에 씁니다.
47
+ csv_loader = CSVLoader(temp_filepath) # CSVLoader를 사용해 CSV를 로드합니다.
48
+ csv_doc = csv_loader.load() # 텍스트를 추출합니다.
49
+ return csv_doc
50
+
51
+ # JSON 문서로부터 텍스트를 추출하는 함수입니다.
52
+ def get_json_file(json_docs):
53
+ temp_dir = tempfile.TemporaryDirectory() # 임시 디렉토리를 생성합니다.
54
+ temp_filepath = os.path.join(temp_dir.name, json_docs.name) # 임시 파일 경로를 생성합니다.
55
+ jq_schema = '.messages[].content'
56
+ text_content = False
57
+ with open(temp_filepath, "wb") as f: # 임시 파일을 바이너리 쓰기 모드로 엽니다.
58
+ f.write(json_docs.getvalue()) # JSON 문서의 내용을 임시 파일에 씁니다.
59
+ json_loader = JSONLoader(temp_filepath, jq_schema, text_content) # JSONLoader를 사용해 TXT를 로드합니다.
60
+ json_doc = json_loader.load() # 텍스트를 추출합니다.
61
+ return json_doc
62
+
63
+
64
+ #[2]TextSplitter : 문서들을 처리하여 텍스트 청크로 나누는 함수입니다. -> 모든 문서를 작은 텍스트 덩어리로 분할
65
+ def get_text_chunks(documents):
66
+ text_splitter = RecursiveCharacterTextSplitter(
67
+ chunk_size=1000, # 청크의 크기를 지정합니다.
68
+ chunk_overlap=200, # 청크 사이의 중복을 지정합니다.
69
+ length_function=len # 텍스트의 길이를 측정하는 함수를 지정합니다.
70
+ )
71
+
72
+ documents = text_splitter.split_documents(documents) # 문서들을 청크로 나눕니다
73
+ return documents # 나눈 청크를 반환합니다.
74
+
75
+
76
+ #[3]Storage : 텍스트 청크들을 임베딩(벡터화) 후 벡터 저장소(Vectorstore-저장 스토어)를 생성하는 함수입니다. -> 사용자 질의와 유사한 문서를 검색하는 기능을 함
77
+ def get_vectorstore(text_chunks):
78
+ # OpenAI 임베딩 모델을 로드합니다. (Embedding models - Ada v2)
79
+
80
+ embeddings = OpenAIEmbeddings()
81
+ vectorstore = FAISS.from_documents(text_chunks, embeddings) # FAISS 벡터 스토어를 생성합니다.
82
+
83
+ return vectorstore # 생성된 벡터 스토어를 ���환합니다.
84
+
85
+ #[4]Retrieval : 문서와 언어 모델을 결합해주는 역할
86
+ def get_conversation_chain(vectorstore):
87
+ gpt_model_name = 'gpt-3.5-turbo'
88
+ llm = ChatOpenAI(model_name = gpt_model_name) #gpt-3.5 모델 로드
89
+
90
+ #[4-1]대화 기록을 저장하기 위한 메모리를 생성합니다. -> 입력/출력을 추적하고 대화를 유지하는 데 필요한 메모리 개체 생성
91
+ memory = ConversationBufferMemory(
92
+ memory_key='chat_history', return_messages=True)
93
+ #[4-2]대화 검색 체인을 생성합니다. -> 프롬프트와 문서들 간의 의미론적 유사성을 기반으로 벡터 저장소에서 검색
94
+ conversation_chain = ConversationalRetrievalChain.from_llm(
95
+ llm=llm,
96
+ retriever=vectorstore.as_retriever(),
97
+ memory=memory
98
+ )
99
+ return conversation_chain
100
+
101
+ #[5]Output : 사용자 입력을 처리하는 함수입니다. -> 사용자의 질의문을 LangChain에게 전달하여 응답으로 얻음, 채팅 기록은 "chat_history" 메모리에 저장
102
+ def handle_userinput(user_question):
103
+ # 대화 체인을 사용하여 사용자 질문에 대한 응답을 생성합니다.
104
+ response = st.session_state.conversation({'question': user_question})
105
+ # 대화 기록을 저장합니다.
106
+ st.session_state.chat_history = response['chat_history']
107
+
108
+ for i, message in enumerate(st.session_state.chat_history):
109
+ if i % 2 == 0:
110
+ st.write(user_template.replace(
111
+ "{{MSG}}", message.content), unsafe_allow_html=True)
112
+ else:
113
+ st.write(bot_template.replace(
114
+ "{{MSG}}", message.content), unsafe_allow_html=True)
115
+
116
+
117
+ def main():
118
+ load_dotenv()
119
+ st.set_page_config(page_title="Chat with multiple Files",
120
+ page_icon=":books:")
121
+ st.write(css, unsafe_allow_html=True)
122
+
123
+ if "conversation" not in st.session_state:
124
+ st.session_state.conversation = None
125
+ if "chat_history" not in st.session_state:
126
+ st.session_state.chat_history = None
127
+
128
+ st.header("Chat with multiple Files :")
129
+ user_question = st.text_input("Ask a question about your documents:")
130
+ if user_question:
131
+ handle_userinput(user_question)
132
+
133
+ with st.sidebar:
134
+ openai_key = st.text_input("Paste your OpenAI API key (sk-...)")
135
+ if openai_key:
136
+ os.environ["OPENAI_API_KEY"] = openai_key
137
+
138
+ st.subheader("Your documents")
139
+ docs = st.file_uploader(
140
+ "Upload your Files here and click on 'Process'", accept_multiple_files=True)
141
+ if st.button("Process"):
142
+ with st.spinner("Processing"):
143
+ # get pdf text
144
+ doc_list = []
145
+
146
+ for file in docs:
147
+ print('file - type : ', file.type)
148
+ if file.type == 'text/plain':
149
+ # file is .txt
150
+ doc_list.extend(get_text_file(file))
151
+ elif file.type in ['application/octet-stream', 'application/pdf']:
152
+ # file is .pdf
153
+ doc_list.extend(get_pdf_text(file))
154
+ elif file.type == 'text/csv':
155
+ # file is .csv
156
+ doc_list.extend(get_csv_file(file))
157
+ elif file.type == 'application/json':
158
+ # file is .json
159
+ doc_list.extend(get_json_file(file))
160
+
161
+ # get the text chunks
162
+ text_chunks = get_text_chunks(doc_list)
163
+
164
+ # create vector store
165
+ vectorstore = get_vectorstore(text_chunks)
166
+
167
+ # create conversation chain
168
+ st.session_state.conversation = get_conversation_chain(
169
+ vectorstore)
170
+
171
+
172
+ if __name__ == '__main__':
173
+ main()
htmlTemplates.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ css = '''
2
+ <style>
3
+ .chat-message {
4
+ padding: 1.5rem; border-radius: 0.5rem; margin-bottom: 1rem; display: flex
5
+ }
6
+ .chat-message.user {
7
+ background-color: #2b313e
8
+ }
9
+ .chat-message.bot {
10
+ background-color: #475063
11
+ }
12
+ .chat-message .avatar {
13
+ width: 20%;
14
+ }
15
+ .chat-message .avatar img {
16
+ max-width: 78px;
17
+ max-height: 78px;
18
+ border-radius: 50%;
19
+ object-fit: cover;
20
+ }
21
+ .chat-message .message {
22
+ width: 80%;
23
+ padding: 0 1.5rem;
24
+ color: #fff;
25
+ }
26
+ '''
27
+
28
+ bot_template = '''
29
+ <div class="chat-message bot">
30
+ <div class="avatar">
31
+ <img src="https://i.ibb.co/cN0nmSj/Screenshot-2023-05-28-at-02-37-21.png" style="max-height: 78px; max-width: 78px; border-radius: 50%; object-fit: cover;">
32
+ </div>
33
+ <div class="message">{{MSG}}</div>
34
+ </div>
35
+ '''
36
+
37
+ user_template = '''
38
+ <div class="chat-message user">
39
+ <div class="avatar">
40
+ <img src="https://i.ibb.co/rdZC7LZ/Photo-logo-1.png">
41
+ </div>
42
+ <div class="message">{{MSG}}</div>
43
+ </div>
44
+ '''
requirements.txt ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ langchain
2
+ llama-cpp-python
3
+ PyPDF2==3.0.1
4
+ faiss-cpu==1.7.4
5
+ ctransformers
6
+ pypdf
7
+ chromadb
8
+ tiktoken
9
+ pysqlite3-binary
10
+ streamlit-extras
11
+ InstructorEmbedding
12
+ sentence-transformers
13
+ jq
14
+ openai