Moonjunho commited on
Commit
66729bb
Β·
1 Parent(s): 412a556

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +166 -0
app.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from dotenv import load_dotenv
3
+ from langchain.text_splitter import CharacterTextSplitter, RecursiveCharacterTextSplitter
4
+ from langchain.vectorstores import FAISS
5
+ from langchain.embeddings import HuggingFaceEmbeddings # General embeddings from HuggingFace models.
6
+ from langchain.memory import ConversationBufferMemory
7
+ from langchain.chains import ConversationalRetrievalChain
8
+ from htmlTemplates import css, bot_template, user_template
9
+ from langchain.llms import LlamaCpp # For loading transformer models.
10
+ from langchain.document_loaders import PyPDFLoader, TextLoader, JSONLoader, CSVLoader
11
+ import tempfile # μž„μ‹œ νŒŒμΌμ„ μƒμ„±ν•˜κΈ° μœ„ν•œ λΌμ΄λΈŒλŸ¬λ¦¬μž…λ‹ˆλ‹€.
12
+ import os
13
+ from huggingface_hub import hf_hub_download # Hugging Face Hubμ—μ„œ λͺ¨λΈμ„ λ‹€μš΄λ‘œλ“œν•˜κΈ° μœ„ν•œ ν•¨μˆ˜μž…λ‹ˆλ‹€.
14
+
15
+ # PDF λ¬Έμ„œλ‘œλΆ€ν„° ν…μŠ€νŠΈλ₯Ό μΆ”μΆœν•˜λŠ” ν•¨μˆ˜μž…λ‹ˆλ‹€.
16
+ def get_pdf_text(pdf_docs):
17
+ temp_dir = tempfile.TemporaryDirectory() # μž„μ‹œ 디렉토리λ₯Ό μƒμ„±ν•©λ‹ˆλ‹€.
18
+ temp_filepath = os.path.join(temp_dir.name, pdf_docs.name) # μž„μ‹œ 파일 경둜λ₯Ό μƒμ„±ν•©λ‹ˆλ‹€.
19
+ with open(temp_filepath, "wb") as f: # μž„μ‹œ νŒŒμΌμ„ λ°”μ΄λ„ˆλ¦¬ μ“°κΈ° λͺ¨λ“œλ‘œ μ—½λ‹ˆλ‹€.
20
+ f.write(pdf_docs.getvalue()) # PDF λ¬Έμ„œμ˜ λ‚΄μš©μ„ μž„μ‹œ νŒŒμΌμ— μ”λ‹ˆλ‹€.
21
+ pdf_loader = PyPDFLoader(temp_filepath) # PyPDFLoaderλ₯Ό μ‚¬μš©ν•΄ PDFλ₯Ό λ‘œλ“œν•©λ‹ˆλ‹€.
22
+ pdf_doc = pdf_loader.load() # ν…μŠ€νŠΈλ₯Ό μΆ”μΆœν•©λ‹ˆλ‹€.
23
+ return pdf_doc # μΆ”μΆœν•œ ν…μŠ€νŠΈλ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€.
24
+
25
+ # 과제
26
+ # μ•„λž˜ ν…μŠ€νŠΈ μΆ”μΆœ ν•¨μˆ˜λ₯Ό μž‘μ„±
27
+ def get_text_file(docs):
28
+ text = file.getvalue().decode("utf-8") # ν…μŠ€νŠΈ νŒŒμΌμ„ λ¬Έμžμ—΄λ‘œ λ””μ½”λ”©ν•©λ‹ˆλ‹€.
29
+ return [text] # ν…μŠ€νŠΈλ₯Ό λ¦¬μŠ€νŠΈμ— λ‹΄μ•„ λ°˜ν™˜ν•©λ‹ˆλ‹€.
30
+
31
+ def get_csv_file(docs):
32
+ import pandas as pd
33
+
34
+ # CSV νŒŒμΌμ„ Pandas DataFrame으둜 μ½μŠ΅λ‹ˆλ‹€.
35
+ df = pd.read_csv(file)
36
+
37
+ # μ—¬κΈ°μ—μ„œ μ›ν•˜λŠ” 열을 μ„ νƒν•˜κ±°λ‚˜ 전체 νŒŒμΌμ„ μ½μ–΄μ˜¬ 수 μžˆμŠ΅λ‹ˆλ‹€.
38
+ # 예λ₯Ό λ“€μ–΄, 'text_column' μ—΄μ—μ„œ ν…μŠ€νŠΈλ₯Ό μΆ”μΆœν•˜λŠ” 방법은 λ‹€μŒκ³Ό κ°™μŠ΅λ‹ˆλ‹€.
39
+ texts = df['text_column'].tolist()
40
+
41
+ return texts # ν…μŠ€νŠΈ 리슀트λ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€.
42
+
43
+ def get_json_file(docs):
44
+ import json
45
+
46
+ # JSON νŒŒμΌμ„ λ””μ½”λ”©ν•˜μ—¬ 데이터λ₯Ό μΆ”μΆœν•©λ‹ˆλ‹€.
47
+ data = json.load(file)
48
+
49
+ # μ—¬κΈ°μ—μ„œ μ μ ˆν•œ λ°©λ²•μœΌλ‘œ JSON λ°μ΄ν„°μ—μ„œ ν…μŠ€νŠΈλ₯Ό μΆ”μΆœν•©λ‹ˆλ‹€.
50
+ # 예λ₯Ό λ“€μ–΄, 'text' 킀에 ν•΄λ‹Ήν•˜λŠ” 값을 μΆ”μΆœν•˜λŠ” 방법은 λ‹€μŒκ³Ό κ°™μŠ΅λ‹ˆλ‹€.
51
+ texts = [item['text'] for item in data]
52
+
53
+ return texts # ν…μŠ€νŠΈ 리슀트λ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€.
54
+
55
+
56
+ # λ¬Έμ„œλ“€μ„ μ²˜λ¦¬ν•˜μ—¬ ν…μŠ€νŠΈ 청크둜 λ‚˜λˆ„λŠ” ν•¨μˆ˜μž…λ‹ˆλ‹€.
57
+ def get_text_chunks(documents):
58
+ text_splitter = RecursiveCharacterTextSplitter(
59
+ chunk_size=1000, # 청크의 크기λ₯Ό μ§€μ •ν•©λ‹ˆλ‹€.
60
+ chunk_overlap=200, # 청크 μ‚¬μ΄μ˜ 쀑볡을 μ§€μ •ν•©λ‹ˆλ‹€.
61
+ length_function=len # ν…μŠ€νŠΈμ˜ 길이λ₯Ό μΈ‘μ •ν•˜λŠ” ν•¨μˆ˜λ₯Ό μ§€μ •ν•©λ‹ˆλ‹€.
62
+ )
63
+
64
+ documents = text_splitter.split_documents(documents) # λ¬Έμ„œλ“€μ„ 청크둜 λ‚˜λˆ•λ‹ˆλ‹€.
65
+ return documents # λ‚˜λˆˆ 청크λ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€.
66
+
67
+
68
+ # ν…μŠ€νŠΈ μ²­ν¬λ“€λ‘œλΆ€ν„° 벑터 μŠ€ν† μ–΄λ₯Ό μƒμ„±ν•˜λŠ” ν•¨μˆ˜μž…λ‹ˆλ‹€.
69
+ def get_vectorstore(text_chunks):
70
+ # μ›ν•˜λŠ” μž„λ² λ”© λͺ¨λΈμ„ λ‘œλ“œν•©λ‹ˆλ‹€.
71
+ embeddings = HuggingFaceEmbeddings(model_name='sentence-transformers/all-MiniLM-L12-v2',
72
+ model_kwargs={'device': 'cpu'}) # μž„λ² λ”© λͺ¨λΈμ„ μ„€μ •ν•©λ‹ˆλ‹€.
73
+ vectorstore = FAISS.from_documents(text_chunks, embeddings) # FAISS 벑터 μŠ€ν† μ–΄λ₯Ό μƒμ„±ν•©λ‹ˆλ‹€.
74
+ return vectorstore # μƒμ„±λœ 벑터 μŠ€ν† μ–΄λ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€.
75
+
76
+
77
+ def get_conversation_chain(vectorstore):
78
+ model_name_or_path = 'TheBloke/Llama-2-7B-chat-GGUF'
79
+ model_basename = 'llama-2-7b-chat.Q2_K.gguf'
80
+ model_path = hf_hub_download(repo_id=model_name_or_path, filename=model_basename)
81
+
82
+ llm = LlamaCpp(model_path=model_path,
83
+ n_ctx=4086,
84
+ input={"temperature": 0.75, "max_length": 2000, "top_p": 1},
85
+ verbose=True, )
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
+ print('user_question => ', user_question)
100
+ # λŒ€ν™” 체인을 μ‚¬μš©ν•˜μ—¬ μ‚¬μš©μž μ§ˆλ¬Έμ— λŒ€ν•œ 응닡을 μƒμ„±ν•©λ‹ˆλ‹€.
101
+ response = st.session_state.conversation({'question': user_question})
102
+ # λŒ€ν™” 기둝을 μ €μž₯ν•©λ‹ˆλ‹€.
103
+ st.session_state.chat_history = response['chat_history']
104
+
105
+ for i, message in enumerate(st.session_state.chat_history):
106
+ if i % 2 == 0:
107
+ st.write(user_template.replace(
108
+ "{{MSG}}", message.content), unsafe_allow_html=True)
109
+ else:
110
+ st.write(bot_template.replace(
111
+ "{{MSG}}", message.content), unsafe_allow_html=True)
112
+
113
+
114
+ def main():
115
+ load_dotenv()
116
+ st.set_page_config(page_title="Chat with multiple Files",
117
+ page_icon=":books:")
118
+ st.write(css, unsafe_allow_html=True)
119
+
120
+ if "conversation" not in st.session_state:
121
+ st.session_state.conversation = None
122
+ if "chat_history" not in st.session_state:
123
+ st.session_state.chat_history = None
124
+
125
+ st.header("Chat with multiple Files:")
126
+ user_question = st.text_input("Ask a question about your documents:")
127
+ if user_question:
128
+ handle_userinput(user_question)
129
+
130
+ with st.sidebar:
131
+ st.subheader("Your documents")
132
+ docs = st.file_uploader(
133
+ "Upload your PDFs here and click on 'Process'", accept_multiple_files=True)
134
+ if st.button("Process"):
135
+ with st.spinner("Processing"):
136
+ # get pdf text
137
+ doc_list = []
138
+
139
+ for file in docs:
140
+ print('file - type : ', file.type)
141
+ if file.type == 'text/plain':
142
+ # file is .txt
143
+ doc_list.extend(get_text_file(file))
144
+ elif file.type in ['application/octet-stream', 'application/pdf']:
145
+ # file is .pdf
146
+ doc_list.extend(get_pdf_text(file))
147
+ elif file.type == 'text/csv':
148
+ # file is .csv
149
+ doc_list.extend(get_csv_file(file))
150
+ elif file.type == 'application/json':
151
+ # file is .json
152
+ doc_list.extend(get_json_file(file))
153
+
154
+ # get the text chunks
155
+ text_chunks = get_text_chunks(doc_list)
156
+
157
+ # create vector store
158
+ vectorstore = get_vectorstore(text_chunks)
159
+
160
+ # create conversation chain
161
+ st.session_state.conversation = get_conversation_chain(
162
+ vectorstore)
163
+
164
+
165
+ if __name__ == '__main__':
166
+ main()