han-byeol commited on
Commit
711869a
·
1 Parent(s): 05291dc

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -196
app.py DELETED
@@ -1,196 +0,0 @@
1
- import streamlit as st
2
- import json
3
- from dotenv import load_dotenv
4
- from PyPDF2 import PdfReader
5
- from langchain.text_splitter import CharacterTextSplitter, RecursiveCharacterTextSplitter
6
- from langchain.embeddings import OpenAIEmbeddings, HuggingFaceInstructEmbeddings
7
- from langchain.vectorstores import FAISS, Chroma
8
- from langchain.embeddings import HuggingFaceEmbeddings # General embeddings from HuggingFace models.
9
- from langchain.chat_models import ChatOpenAI
10
- from langchain.memory import ConversationBufferMemory
11
- from langchain.chains import ConversationalRetrievalChain
12
- from htmlTemplates import css, bot_template, user_template
13
- from langchain.llms import HuggingFaceHub, LlamaCpp, CTransformers # For loading transformer models.
14
- from langchain.document_loaders import PyPDFLoader, TextLoader, JSONLoader, CSVLoader
15
- import tempfile # 임시 파일을 생성하기 위한 라이브러리입니다.
16
- import os
17
-
18
-
19
- # PDF 문서로부터 텍스트를 추출하는 함수입니다.
20
- def get_pdf_text(pdf_docs):
21
- temp_dir = tempfile.TemporaryDirectory() # 임시 디렉토리를 생성합니다.
22
- temp_filepath = os.path.join(temp_dir.name, pdf_docs.name) # 임시 파일 경로를 생성합니다.
23
- with open(temp_filepath, "wb") as f: # 임시 파일을 바이너리 쓰기 모드로 엽니다.
24
- f.write(pdf_docs.getvalue()) # PDF 문서의 내용을 임시 파일에 씁니다.
25
- pdf_loader = PyPDFLoader(temp_filepath) # PyPDFLoader를 사용해 PDF를 로드합니다.
26
- pdf_doc = pdf_loader.load() # 텍스트를 추출합니다.
27
- return pdf_doc # 추출한 텍스트를 반환합니다.
28
-
29
- # 과제
30
- # 아래 텍스트 추출 함수를 작성
31
-
32
- def get_text_file(txt_docs):
33
- temp_dir = tempfile.TemporaryDirectory()
34
- temp_filepath = os.path.join(temp_dir.name, txt_docs.name)
35
- with open(temp_filepath, "wb") as f:
36
- f.write(txt_docs.getvalue())
37
- text_loader = TextLoader(temp_filepath)
38
- text_doc = text_loader.load()
39
- return text_doc
40
-
41
-
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())
47
- csv_loader = CSVLoader(temp_filepath)
48
- csv_doc = csv_loader.load()
49
- return csv_doc
50
-
51
- class JSONLoader:
52
- def __init__(self, file_path):
53
- self.file_path = file_path
54
-
55
- def load(self):
56
- try:
57
- with open(self.file_path, 'r', encoding='utf-8') as json_file:
58
- data = json.load(json_file)
59
- # JSON 파일 안에 특정 필드에 있는 텍스트 추출하는 부분
60
- if 'text_field_name' in data: # 'text_field_name'은 실제 JSON 파일에서 텍스트가 있는 필드명입니다.
61
- text = data['text_field_name']
62
- return text
63
- else:
64
- return "Text field not found in JSON"
65
- except Exception as e:
66
- return str(e)
67
-
68
- def get_json_file(json_docs):
69
- temp_dir = tempfile.TemporaryDirectory()
70
- temp_filepath = os.path.join(temp_dir.name, json_docs.name)
71
- with open(temp_filepath, "wb") as f:
72
- f.write(json_docs.getvalue())
73
- json_loader = JSONLoader(temp_filepath)
74
- json_doc = json_loader.load()
75
- return json_doc
76
-
77
-
78
-
79
- # 문서들을 처리하여 텍스트 청크로 나누는 함수입니다.
80
- def get_text_chunks(documents):
81
- text_splitter = RecursiveCharacterTextSplitter(
82
- chunk_size=1000, # 청크의 크기를 지정합니다.
83
- chunk_overlap=200, # 청크 사이의 중복을 지정합니다.
84
- length_function=len # 텍스트의 길이를 측정하는 함수를 지정합니다.
85
- )
86
-
87
- valid_documents = [doc for doc in documents if hasattr(doc, 'page_content')]
88
- # documents 리스트에서 page_content 속성이 있는 유효한 문서 객체들만 선택합니다.
89
-
90
- texts = []
91
- for doc in valid_documents:
92
- texts.append(doc.page_content)
93
- # 유효한 문서 객체에서 page_content를 추출합니다.
94
-
95
- text_chunks = text_splitter.split_documents(texts)
96
- return text_chunks
97
-
98
-
99
- # 텍스트 청크들로부터 벡터 스토어를 생성하는 함수입니다.
100
- def get_vectorstore(text_chunks):
101
- # OpenAI 임베딩 모델을 로드합니다. (Embedding models - Ada v2)
102
-
103
- embeddings = OpenAIEmbeddings()
104
- vectorstore = FAISS.from_documents(text_chunks, embeddings) # FAISS 벡터 스토어를 생성합니다.
105
-
106
- return vectorstore # 생성된 벡터 스토어를 반환합니다.
107
-
108
-
109
- def get_conversation_chain(vectorstore):
110
- gpt_model_name = 'gpt-3.5-turbo'
111
- llm = ChatOpenAI(model_name = gpt_model_name) #gpt-3.5 모델 로드
112
-
113
- # 대화 기록을 저장하기 위한 메모리를 생성합니다.
114
- memory = ConversationBufferMemory(
115
- memory_key='chat_history', return_messages=True)
116
- # 대화 검색 체인을 생성합니다.
117
- conversation_chain = ConversationalRetrievalChain.from_llm(
118
- llm=llm,
119
- retriever=vectorstore.as_retriever(),
120
- memory=memory
121
- )
122
- return conversation_chain
123
-
124
- # 사용자 입력을 처리하는 함수입니다.
125
- def handle_userinput(user_question):
126
- # 대화 체인을 사용하여 사용자 질문에 대한 응답을 생성합니다.
127
- response = st.session_state.conversation({'question': user_question})
128
- # 대화 기록을 저장합니다.
129
- st.session_state.chat_history = response['chat_history']
130
-
131
- for i, message in enumerate(st.session_state.chat_history):
132
- if i % 2 == 0:
133
- st.write(user_template.replace(
134
- "{{MSG}}", message.content), unsafe_allow_html=True)
135
- else:
136
- st.write(bot_template.replace(
137
- "{{MSG}}", message.content), unsafe_allow_html=True)
138
-
139
-
140
- def main():
141
- load_dotenv()
142
- st.set_page_config(page_title="Chat with multiple Files",
143
- page_icon=":books:")
144
- st.write(css, unsafe_allow_html=True)
145
-
146
- if "conversation" not in st.session_state:
147
- st.session_state.conversation = None
148
- if "chat_history" not in st.session_state:
149
- st.session_state.chat_history = None
150
-
151
- st.header("Chat with multiple Files :")
152
- user_question = st.text_input("Ask a question about your documents:")
153
- if user_question:
154
- handle_userinput(user_question)
155
-
156
- with st.sidebar:
157
- openai_key = st.text_input("Paste your OpenAI API key (sk-...)")
158
- if openai_key:
159
- os.environ["OPENAI_API_KEY"] = openai_key
160
-
161
- st.subheader("Your documents")
162
- docs = st.file_uploader(
163
- "Upload your Files here and click on 'Process'", accept_multiple_files=True)
164
- if st.button("Process"):
165
- with st.spinner("Processing"):
166
- # get pdf text
167
- doc_list = []
168
-
169
- for file in docs:
170
- print('file - type : ', file.type)
171
- if file.type == 'text/plain':
172
- # file is .txt
173
- doc_list.extend(get_text_file(file))
174
- elif file.type in ['application/octet-stream', 'application/pdf']:
175
- # file is .pdf
176
- doc_list.extend(get_pdf_text(file))
177
- elif file.type == 'text/csv':
178
- # file is .csv
179
- doc_list.extend(get_csv_file(file))
180
- elif file.type == 'application/json':
181
- # file is .json
182
- doc_list.extend(get_json_file(file))
183
-
184
- # get the text chunks
185
- text_chunks = get_text_chunks(doc_list)
186
-
187
- # create vector store
188
- vectorstore = get_vectorstore(text_chunks)
189
-
190
- # create conversation chain
191
- st.session_state.conversation = get_conversation_chain(
192
- vectorstore)
193
-
194
-
195
- if __name__ == '__main__':
196
- main()