seojun commited on
Commit
8b5c28c
1 Parent(s): bb93105

FEAT : 첫번째 커밋

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