redkye2 commited on
Commit
2db23b8
Β·
1 Parent(s): e7c2ad2
Files changed (3) hide show
  1. README.md +1 -1
  2. app.py +177 -0
  3. requirements.txt +14 -0
README.md CHANGED
@@ -4,7 +4,7 @@ emoji: πŸ’»
4
  colorFrom: indigo
5
  colorTo: purple
6
  sdk: streamlit
7
- sdk_version: 1.28.2
8
  app_file: app.py
9
  pinned: false
10
  ---
 
4
  colorFrom: indigo
5
  colorTo: purple
6
  sdk: streamlit
7
+ sdk_version: 1.27.2
8
  app_file: app.py
9
  pinned: false
10
  ---
app.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 csv
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
+
33
+ def get_text_file(text_docs):
34
+ try:
35
+ with open(text_docs, 'r', encoding='utf-8') as file:
36
+ text_doc = file.read()
37
+ return text_doc
38
+ finally:
39
+ pass
40
+
41
+
42
+ def get_csv_file(csv_docs):
43
+ try:
44
+ with open(csv_docs, 'r', encoding='utf-8', newline='') as file:
45
+ reader = csv.reader(file)
46
+
47
+ text_list = []
48
+ for row in reader:
49
+ text_list.extend(row)
50
+
51
+ csv_doc = '\n'.join(text_list)
52
+
53
+ return csv_doc
54
+ finally:
55
+ pass
56
+
57
+
58
+ def get_json_file(json_docs,messages):
59
+ try:
60
+ with open(json_docs, 'r', encoding='utf-8') as file:
61
+ json_data = json.load(file)
62
+ text = json_data[messages]
63
+ return text
64
+ finally:
65
+ pass
66
+
67
+
68
+ # λ¬Έμ„œλ“€μ„ μ²˜λ¦¬ν•˜μ—¬ ν…μŠ€νŠΈ 청크둜 λ‚˜λˆ„λŠ” ν•¨μˆ˜μž…λ‹ˆλ‹€.
69
+ def get_text_chunks(documents):
70
+ text_splitter = RecursiveCharacterTextSplitter(
71
+ chunk_size=1000, # 청크의 크기λ₯Ό μ§€μ •ν•©λ‹ˆλ‹€.
72
+ chunk_overlap=200, # 청크 μ‚¬μ΄μ˜ 쀑볡을 μ§€μ •ν•©λ‹ˆλ‹€.
73
+ length_function=len # ν…μŠ€νŠΈμ˜ 길이λ₯Ό μΈ‘μ •ν•˜λŠ” ν•¨μˆ˜λ₯Ό μ§€μ •ν•©λ‹ˆλ‹€.
74
+ )
75
+
76
+ documents = text_splitter.split_documents(documents) # λ¬Έμ„œλ“€μ„ 청크둜 λ‚˜λˆ•λ‹ˆλ‹€
77
+ return documents # λ‚˜λˆˆ 청크λ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€.
78
+
79
+
80
+ # ν…μŠ€νŠΈ μ²­ν¬λ“€λ‘œλΆ€ν„° 벑터 μŠ€ν† μ–΄λ₯Ό μƒμ„±ν•˜λŠ” ν•¨μˆ˜μž…λ‹ˆλ‹€.
81
+ def get_vectorstore(text_chunks):
82
+ # OpenAI μž„λ² λ”© λͺ¨λΈμ„ λ‘œλ“œν•©λ‹ˆλ‹€. (Embedding models - Ada v2)
83
+
84
+ embeddings = OpenAIEmbeddings()
85
+ vectorstore = FAISS.from_documents(text_chunks, embeddings) # FAISS 벑터 μŠ€ν† μ–΄λ₯Ό μƒμ„±ν•©λ‹ˆλ‹€.
86
+
87
+ return vectorstore # μƒμ„±λœ 벑터 μŠ€ν† μ–΄λ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€.
88
+
89
+
90
+ def get_conversation_chain(vectorstore):
91
+ gpt_model_name = 'gpt-3.5-turbo'
92
+ llm = ChatOpenAI(model_name = gpt_model_name) #gpt-3.5 λͺ¨λΈ λ‘œλ“œ
93
+
94
+ # λŒ€ν™” 기둝을 μ €μž₯ν•˜κΈ° μœ„ν•œ λ©”λͺ¨λ¦¬λ₯Ό μƒμ„±ν•©λ‹ˆλ‹€.
95
+ memory = ConversationBufferMemory(
96
+ memory_key='chat_history', return_messages=True)
97
+ # λŒ€ν™” 검색 체인을 μƒμ„±ν•©λ‹ˆλ‹€.
98
+ conversation_chain = ConversationalRetrievalChain.from_llm(
99
+ llm=llm,
100
+ retriever=vectorstore.as_retriever(),
101
+ memory=memory
102
+ )
103
+ return conversation_chain
104
+
105
+ # μ‚¬μš©μž μž…λ ₯을 μ²˜λ¦¬ν•˜λŠ” ν•¨μˆ˜μž…λ‹ˆλ‹€.
106
+ def handle_userinput(user_question):
107
+ # λŒ€ν™” 체인을 μ‚¬μš©ν•˜μ—¬ μ‚¬μš©μž μ§ˆλ¬Έμ— λŒ€ν•œ 응닡을 μƒμ„±ν•©λ‹ˆλ‹€.
108
+ response = st.session_state.conversation({'question': user_question})
109
+ # λŒ€ν™” 기둝을 μ €μž₯ν•©λ‹ˆλ‹€.
110
+ st.session_state.chat_history = response['chat_history']
111
+
112
+ for i, message in enumerate(st.session_state.chat_history):
113
+ if i % 2 == 0:
114
+ st.write(user_template.replace(
115
+ "{{MSG}}", message.content), unsafe_allow_html=True)
116
+ else:
117
+ st.write(bot_template.replace(
118
+ "{{MSG}}", message.content), unsafe_allow_html=True)
119
+
120
+
121
+ def main():
122
+ load_dotenv()
123
+ st.set_page_config(page_title="Chat with multiple Files",
124
+ page_icon=":books:")
125
+ st.write(css, unsafe_allow_html=True)
126
+
127
+ if "conversation" not in st.session_state:
128
+ st.session_state.conversation = None
129
+ if "chat_history" not in st.session_state:
130
+ st.session_state.chat_history = None
131
+
132
+ st.header("Chat with multiple Files :")
133
+ user_question = st.text_input("Ask a question about your documents:")
134
+ if user_question:
135
+ handle_userinput(user_question)
136
+
137
+ with st.sidebar:
138
+ openai_key = st.text_input("Paste your OpenAI API key (sk-...)")
139
+ if openai_key:
140
+ os.environ["OPENAI_API_KEY"] = openai_key
141
+
142
+ st.subheader("Your documents")
143
+ docs = st.file_uploader(
144
+ "Upload your PDFs here and click on 'Process'", accept_multiple_files=True)
145
+ if st.button("Process"):
146
+ with st.spinner("Processing"):
147
+ # get pdf text
148
+ doc_list = []
149
+
150
+ for file, key in docs:
151
+ print('file - type : ', file.type)
152
+ if file.type == 'text/plain':
153
+ # file is .txt
154
+ doc_list.extend(get_text_file(file))
155
+ elif file.type in ['application/octet-stream', 'application/pdf']:
156
+ # file is .pdf
157
+ doc_list.extend(get_pdf_text(file))
158
+ elif file.type == 'text/csv':
159
+ # file is .csv
160
+ doc_list.extend(get_csv_file(file))
161
+ elif file.type == 'application/json':
162
+ # file is .json
163
+ doc_list.extend(get_json_file(file,key))
164
+
165
+ # get the text chunks
166
+ text_chunks = get_text_chunks(doc_list)
167
+
168
+ # create vector store
169
+ vectorstore = get_vectorstore(text_chunks)
170
+
171
+ # create conversation chain
172
+ st.session_state.conversation = get_conversation_chain(
173
+ vectorstore)
174
+
175
+
176
+ if __name__ == '__main__':
177
+ 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