yunnn426 commited on
Commit
96fe4c8
β€’
1 Parent(s): 60f47b6

assignment 1 initial commit

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