Separate2 commited on
Commit
a587b94
ยท
verified ยท
1 Parent(s): f497da5

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +253 -213
src/streamlit_app.py CHANGED
@@ -1,214 +1,254 @@
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
- # ํ…์ŠคํŠธ ์Šคํ”Œ๋ฆฌํ„ฐ
12
- from langchain_text_splitters import CharacterTextSplitter, RecursiveCharacterTextSplitter
13
-
14
- # ๋ฒกํ„ฐ์Šคํ† ์–ด/์ž„๋ฒ ๋”ฉ/LLM
15
- from langchain_community.vectorstores import FAISS
16
- from langchain_community.embeddings import HuggingFaceEmbeddings
17
-
18
- # ๋กœ๋”๋“ค (pebblo/pwd ๋Œ๋ ค์˜ค์ง€ ์•Š๊ฒŒ ์„œ๋ธŒ๋ชจ๋“ˆ๋กœ)
19
- from langchain_community.document_loaders.pdf import PyPDFLoader
20
- from langchain_community.document_loaders.text import TextLoader
21
- from langchain_community.document_loaders.csv_loader import CSVLoader
22
- from langchain_community.document_loaders.json_loader import JSONLoader
23
- import tempfile # ์ž„์‹œ ํŒŒ์ผ์„ ์ƒ์„ฑํ•˜๊ธฐ ์œ„ํ•œ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ์ž…๋‹ˆ๋‹ค.
24
- import os
25
- import json
26
- from langchain.docstore.document import Document
27
- from langchain_groq import ChatGroq
28
-
29
- # PDF ๋ฌธ์„œ๋กœ๋ถ€ํ„ฐ ํ…์ŠคํŠธ๋ฅผ ์ถ”์ถœํ•˜๋Š” ํ•จ์ˆ˜์ž…๋‹ˆ๋‹ค.
30
- def get_pdf_text(pdf_docs):
31
- temp_dir = tempfile.TemporaryDirectory() # ์ž„์‹œ ๋””๋ ‰ํ† ๋ฆฌ๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค.
32
- temp_filepath = os.path.join(temp_dir.name, pdf_docs.name) # ์ž„์‹œ ํŒŒ์ผ ๊ฒฝ๋กœ๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค.
33
- with open(temp_filepath, "wb") as f: # ์ž„์‹œ ํŒŒ์ผ์„ ๋ฐ”์ด๋„ˆ๋ฆฌ ์“ฐ๊ธฐ ๋ชจ๋“œ๋กœ ์—ฝ๋‹ˆ๋‹ค.
34
- f.write(pdf_docs.getvalue()) # PDF ๋ฌธ์„œ์˜ ๋‚ด์šฉ์„ ์ž„์‹œ ํŒŒ์ผ์— ์”๋‹ˆ๋‹ค.
35
- pdf_loader = PyPDFLoader(temp_filepath) # PyPDFLoader๋ฅผ ์‚ฌ์šฉํ•ด PDF๋ฅผ ๋กœ๋“œํ•ฉ๋‹ˆ๋‹ค.
36
- pdf_doc = pdf_loader.load() # ํ…์ŠคํŠธ๋ฅผ ์ถ”์ถœํ•ฉ๋‹ˆ๋‹ค.
37
- return pdf_doc # ์ถ”์ถœํ•œ ํ…์ŠคํŠธ๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.
38
-
39
-
40
- def get_text_file(docs):
41
- #################### ๋‚ด์šฉ์„ ์ถ”๊ฐ€ํ•  ๋ถ€๋ถ„
42
- return text_doc
43
-
44
-
45
- def get_csv_file(docs):
46
- #################### ๋‚ด์šฉ์„ ์ถ”๊ฐ€ํ•  ๋ถ€๋ถ„
47
- return csv_doc
48
-
49
- # def get_json_file(docs):
50
- # temp_dir = tempfile.TemporaryDirectory()
51
- # temp_filepath = os.path.join(temp_dir.name, docs.name)
52
- # with open(temp_filepath, "wb") as f:
53
- # f.write(docs.getvalue())
54
- # json_loader = JSONLoader(temp_filepath,
55
- # jq_schema='.scans[].relationships',
56
- # text_content=False)
57
- #
58
- # json_doc = json_loader.load()
59
- # # print('json_doc = ',json_doc)
60
- # return json_doc
61
-
62
- def get_json_file(file) -> list[Document]:
63
- # Streamlit UploadedFile -> str
64
- raw = file.getvalue().decode("utf-8", errors="ignore")
65
- data = json.loads(raw)
66
-
67
- docs = []
68
-
69
- # ์˜ˆ์ „ jq ๊ฒฝ๋กœ๊ฐ€ '.scans[].relationships'์˜€๋‹ค๋ฉด, ๋™์ผํ•œ ์˜๋ฏธ๋กœ ํŒŒ์‹ฑ:
70
- # ์กด์žฌํ•˜๋ฉด ๊ทธ๊ฒƒ๋งŒ ๋ฝ‘๊ณ , ์—†์œผ๋ฉด ํ†ต์œผ๋กœ ๋ฌธ์„œํ™”
71
- def add_doc(x):
72
- docs.append(Document(page_content=json.dumps(x, ensure_ascii=False)))
73
-
74
- if isinstance(data, dict) and "scans" in data and isinstance(data["scans"], list):
75
- for s in data["scans"]:
76
- rels = s.get("relationships", [])
77
- if isinstance(rels, list) and rels:
78
- for r in rels:
79
- add_doc(r)
80
- if not docs: # ๊ทธ๋ž˜๋„ ๋ชป ๋ฝ‘์•˜์œผ๋ฉด ์ „์ฒด๋ฅผ ํ•˜๋‚˜๋กœ
81
- add_doc(data)
82
- elif isinstance(data, list):
83
- for item in data:
84
- add_doc(item)
85
- else:
86
- add_doc(data)
87
-
88
- return docs
89
-
90
- # ๋ฌธ์„œ๋“ค์„ ์ฒ˜๋ฆฌํ•˜์—ฌ ํ…์ŠคํŠธ ์ฒญํฌ๋กœ ๋‚˜๋ˆ„๋Š” ํ•จ์ˆ˜์ž…๋‹ˆ๋‹ค.
91
- def get_text_chunks(documents):
92
- text_splitter = RecursiveCharacterTextSplitter(
93
- chunk_size=1000, # ์ฒญํฌ์˜ ํฌ๊ธฐ๋ฅผ ์ง€์ •ํ•ฉ๋‹ˆ๋‹ค.
94
- chunk_overlap=200, # ์ฒญํฌ ์‚ฌ์ด์˜ ์ค‘๋ณต์„ ์ง€์ •ํ•ฉ๋‹ˆ๋‹ค.
95
- length_function=len # ํ…์ŠคํŠธ์˜ ๊ธธ์ด๋ฅผ ์ธก์ •ํ•˜๋Š” ํ•จ์ˆ˜๋ฅผ ์ง€์ •ํ•ฉ๋‹ˆ๋‹ค.
96
- )
97
-
98
- documents = text_splitter.split_documents(documents) # ๋ฌธ์„œ๋“ค์„ ์ฒญํฌ๋กœ ๋‚˜๋ˆ•๋‹ˆ๋‹ค.
99
- return documents # ๋‚˜๋ˆˆ ์ฒญํฌ๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.
100
-
101
-
102
- # ํ…์ŠคํŠธ ์ฒญํฌ๋“ค๋กœ๋ถ€ํ„ฐ ๋ฒกํ„ฐ ์Šคํ† ์–ด๋ฅผ ์ƒ์„ฑํ•˜๋Š” ํ•จ์ˆ˜์ž…๋‹ˆ๋‹ค.
103
- def get_vectorstore(text_chunks):
104
- # ์›ํ•˜๋Š” ์ž„๋ฒ ๋”ฉ ๋ชจ๋ธ์„ ๋กœ๋“œํ•ฉ๋‹ˆ๋‹ค.
105
- embeddings = HuggingFaceEmbeddings(model_name='sentence-transformers/all-MiniLM-L12-v2',
106
- model_kwargs={'device': 'cpu'}) # ์ž„๋ฒ ๋”ฉ ๋ชจ๋ธ์„ ์„ค์ •ํ•ฉ๋‹ˆ๋‹ค.
107
- vectorstore = FAISS.from_documents(text_chunks, embeddings) # FAISS ๋ฒกํ„ฐ ์Šคํ† ์–ด๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค.
108
- return vectorstore # ์ƒ์„ฑ๋œ ๋ฒกํ„ฐ ์Šคํ† ์–ด๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.
109
-
110
-
111
- def get_conversation_chain(vectorstore):
112
- # Groq LLM
113
- llm = ChatGroq(
114
- groq_api_key=os.environ.get("GROQ_API_KEY"),
115
- model_name="llama-3.1-8b-instant",
116
- temperature=0.75, # ํ•„์š”์— ๋งž๊ฒŒ ํŠœ๋‹
117
- max_tokens=512 # ์ปจํ…์ŠคํŠธ ์ดˆ๊ณผ ๋ฐฉ์ง€์šฉ (ํ•„์š”์‹œ ์กฐ์ •)
118
- )
119
-
120
- memory = ConversationBufferMemory(
121
- memory_key="chat_history",
122
- return_messages=True
123
- )
124
- retriever = vectorstore.as_retriever(search_kwargs={"k": 3})
125
-
126
- conversation_chain = ConversationalRetrievalChain.from_llm(
127
- llm=llm,
128
- retriever=retriever,
129
- memory=memory,
130
- )
131
- return conversation_chain
132
-
133
- # ์‚ฌ์šฉ์ž ์ž…๋ ฅ์„ ์ฒ˜๋ฆฌํ•˜๋Š” ํ•จ์ˆ˜์ž…๋‹ˆ๋‹ค.
134
- def handle_userinput(user_question):
135
- print('user_question => ', user_question)
136
- # ๋Œ€ํ™” ์ฒด์ธ์„ ์‚ฌ์šฉํ•˜์—ฌ ์‚ฌ์šฉ์ž ์งˆ๋ฌธ์— ๋Œ€ํ•œ ์‘๋‹ต์„ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค.
137
- response = st.session_state.conversation({'question': user_question})
138
- # ๋Œ€ํ™” ๊ธฐ๋ก์„ ์ €์žฅํ•ฉ๋‹ˆ๋‹ค.
139
- st.session_state.chat_history = response['chat_history']
140
-
141
- for i, message in enumerate(st.session_state.chat_history):
142
- if i % 2 == 0:
143
- st.write(user_template.replace(
144
- "{{MSG}}", message.content), unsafe_allow_html=True)
145
- else:
146
- st.write(bot_template.replace(
147
- "{{MSG}}", message.content), unsafe_allow_html=True)
148
-
149
-
150
- def main():
151
- load_dotenv()
152
- st.set_page_config(page_title="Basic_RAG_AI_Chatbot_with_Llama",
153
- page_icon=":books:")
154
- st.write(css, unsafe_allow_html=True)
155
-
156
- if "conversation" not in st.session_state:
157
- st.session_state.conversation = None
158
- if "chat_history" not in st.session_state:
159
- st.session_state.chat_history = None
160
-
161
- st.header("Basic_RAG_AI_Chatbot_with_Llama3 :books:")
162
- user_question = st.text_input("Ask a question about your documents:")
163
- if user_question:
164
- handle_userinput(user_question)
165
-
166
- with st.sidebar:
167
- st.subheader("Your documents")
168
- docs = st.file_uploader(
169
- "Upload your Files here and click on 'Process'", accept_multiple_files=True)
170
- if st.button("Process[PDF]"):
171
- with st.spinner("Processing"):
172
- # get pdf text
173
- doc_list = []
174
- for file in docs:
175
- print('file - type : ', file.type)
176
- if file.type in ['application/octet-stream', 'application/pdf']:
177
- # file is .pdf
178
- doc_list.extend(get_pdf_text(file))
179
- else:
180
- st.error("PDF ํŒŒ์ผ์ด ์•„๋‹™๋‹ˆ๋‹ค.")
181
- if not doc_list:
182
- st.error("์ฒ˜๋ฆฌ ๊ฐ€๋Šฅํ•œ ๋ฌธ์„œ๋ฅผ ์ฐพ์ง€ ๋ชปํ–ˆ์Šต๋‹ˆ๋‹ค.")
183
- st.stop()
184
-
185
- text_chunks = get_text_chunks(doc_list)
186
- vectorstore = get_vectorstore(text_chunks)
187
- st.session_state.conversation = get_conversation_chain(vectorstore)
188
-
189
- ################## TXT, CSV ๋ฒ„ํŠผ ๊ตฌํ˜„
190
- # TXT ๋ฒ„ํŠผ ๊ตฌํ˜„ ์ฐธ๊ณ  : if file.type == 'text/plain':
191
- # CSV ๋ฒ„ํŠผ ๊ตฌํ˜„ ์ฐธ๊ณ  : if file.type == 'text/csv':
192
-
193
- if st.button("Process[JSON]"):
194
- with st.spinner("Processing"):
195
- # get txt text
196
- doc_list = []
197
- for file in docs:
198
- print('file - type : ', file.type)
199
- if file.type == 'application/json':
200
- # file is .json
201
- doc_list.extend(get_json_file(file))
202
- else:
203
- st.error("JSON ํŒŒ์ผ์ด ์•„๋‹™๋‹ˆ๋‹ค.")
204
- if not doc_list:
205
- st.error("์ฒ˜๋ฆฌ ๊ฐ€๋Šฅํ•œ ๋ฌธ์„œ๋ฅผ ์ฐพ์ง€ ๋ชปํ–ˆ์Šต๋‹ˆ๋‹ค.")
206
- st.stop()
207
-
208
- text_chunks = get_text_chunks(doc_list)
209
- vectorstore = get_vectorstore(text_chunks)
210
- st.session_state.conversation = get_conversation_chain(vectorstore)
211
-
212
-
213
- if __name__ == '__main__':
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
214
  main()
 
1
+ import streamlit as st
2
+ from dotenv import load_dotenv
3
+ from langchain.memory import ConversationBufferMemory
4
+ from langchain.chains import ConversationalRetrievalChain
5
+ from htmlTemplates import css, bot_template, user_template
6
+ # ํ…์ŠคํŠธ ์Šคํ”Œ๋ฆฌํ„ฐ
7
+ from langchain_text_splitters import CharacterTextSplitter, RecursiveCharacterTextSplitter
8
+
9
+ # ๋ฒกํ„ฐ์Šคํ† ์–ด/์ž„๋ฒ ๋”ฉ/LLM
10
+ from langchain_community.vectorstores import FAISS
11
+ from langchain_community.embeddings import HuggingFaceEmbeddings
12
+
13
+ # ๋กœ๋”๋“ค (pebblo/pwd ๋Œ๋ ค์˜ค์ง€ ์•Š๊ฒŒ ์„œ๋ธŒ๋ชจ๋“ˆ๋กœ)
14
+ from langchain_community.document_loaders.pdf import PyPDFLoader
15
+ from langchain_community.document_loaders.text import TextLoader
16
+ from langchain_community.document_loaders.csv_loader import CSVLoader
17
+ from langchain_community.document_loaders.json_loader import JSONLoader
18
+ import tempfile # ์ž„์‹œ ํŒŒ์ผ์„ ์ƒ์„ฑํ•˜๊ธฐ ์œ„ํ•œ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ์ž…๋‹ˆ๋‹ค.
19
+ import os
20
+ import json
21
+ from langchain.docstore.document import Document
22
+ from langchain_groq import ChatGroq
23
+
24
+ # PDF ๋ฌธ์„œ๋กœ๋ถ€ํ„ฐ ํ…์ŠคํŠธ๋ฅผ ์ถ”์ถœํ•˜๋Š” ํ•จ์ˆ˜์ž…๋‹ˆ๋‹ค.
25
+ def get_pdf_text(pdf_docs):
26
+ temp_dir = tempfile.TemporaryDirectory() # ์ž„์‹œ ๋””๋ ‰ํ† ๋ฆฌ๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค.
27
+ temp_filepath = os.path.join(temp_dir.name, pdf_docs.name) # ์ž„์‹œ ํŒŒ์ผ ๊ฒฝ๋กœ๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค.
28
+ with open(temp_filepath, "wb") as f: # ์ž„์‹œ ํŒŒ์ผ์„ ๋ฐ”์ด๋„ˆ๋ฆฌ ์“ฐ๊ธฐ ๋ชจ๋“œ๋กœ ์—ฝ๋‹ˆ๋‹ค.
29
+ f.write(pdf_docs.getvalue()) # PDF ๋ฌธ์„œ์˜ ๋‚ด์šฉ์„ ์ž„์‹œ ํŒŒ์ผ์— ์”๋‹ˆ๋‹ค.
30
+ pdf_loader = PyPDFLoader(temp_filepath) # PyPDFLoader๋ฅผ ์‚ฌ์šฉํ•ด PDF๋ฅผ ๋กœ๋“œํ•ฉ๋‹ˆ๋‹ค.
31
+ pdf_doc = pdf_loader.load() # ํ…์ŠคํŠธ๋ฅผ ์ถ”์ถœํ•ฉ๋‹ˆ๋‹ค.
32
+ return pdf_doc # ์ถ”์ถœํ•œ ํ…์ŠคํŠธ๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.
33
+
34
+
35
+ # TXT ๋ฌธ์„œ๋กœ๋ถ€ํ„ฐ ํ…์ŠคํŠธ๋ฅผ ์ถ”์ถœํ•˜๋Š” ํ•จ์ˆ˜์ž…๋‹ˆ๋‹ค.
36
+ def get_text_file(docs):
37
+ # Streamlit UploadedFile -> str
38
+ # TextLoader๋Š” ํŒŒ์ผ ๊ฒฝ๋กœ๋ฅผ ์ธ์ž๋กœ ๋ฐ›์œผ๋ฏ€๋กœ, PDF ๋กœ๋”์™€ ์œ ์‚ฌํ•˜๊ฒŒ ์ž„์‹œ ํŒŒ์ผ์„ ์ƒ์„ฑํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.
39
+ temp_dir = tempfile.TemporaryDirectory()
40
+ temp_filepath = os.path.join(temp_dir.name, docs.name)
41
+ with open(temp_filepath, "wb") as f:
42
+ f.write(docs.getvalue())
43
+
44
+ text_loader = TextLoader(temp_filepath) # TextLoader๋ฅผ ์‚ฌ์šฉํ•ด TXT๋ฅผ ๋กœ๋“œํ•ฉ๋‹ˆ๋‹ค.
45
+ text_doc = text_loader.load() # ํ…์ŠคํŠธ๋ฅผ ์ถ”์ถœํ•ฉ๋‹ˆ๋‹ค.
46
+ return text_doc
47
+
48
+
49
+ # CSV ๋ฌธ์„œ๋กœ๋ถ€ํ„ฐ ํ…์ŠคํŠธ๋ฅผ ์ถ”์ถœํ•˜๋Š” ํ•จ์ˆ˜์ž…๋‹ˆ๋‹ค.
50
+ def get_csv_file(docs):
51
+ # CSVLoader๋Š” ํŒŒ์ผ ๊ฒฝ๋กœ๋ฅผ ์ธ์ž๋กœ ๋ฐ›์œผ๋ฏ€๋กœ, ์ž„์‹œ ํŒŒ์ผ์„ ์ƒ์„ฑํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.
52
+ temp_dir = tempfile.TemporaryDirectory()
53
+ temp_filepath = os.path.join(temp_dir.name, docs.name)
54
+ with open(temp_filepath, "wb") as f:
55
+ f.write(docs.getvalue())
56
+
57
+ # CSVLoader๋ฅผ ์‚ฌ์šฉํ•ด CSV๋ฅผ ๋กœ๋“œํ•ฉ๋‹ˆ๋‹ค.
58
+ # header๊ฐ€ ์žˆ๊ณ , ํ•˜๋‚˜์˜ Document๋กœ ํ†ตํ•ฉํ•˜๋Š” ๊ฒƒ์ด ์•„๋‹ˆ๋ผ ๊ฐ ํ–‰์„ Document๋กœ ๋กœ๋“œํ•ฉ๋‹ˆ๋‹ค.
59
+ csv_loader = CSVLoader(temp_filepath, encoding="utf8")
60
+ csv_doc = csv_loader.load() # ํ…์ŠคํŠธ๋ฅผ ์ถ”์ถœํ•ฉ๋‹ˆ๋‹ค.
61
+ return csv_doc
62
+
63
+ def get_json_file(file) -> list[Document]:
64
+ # Streamlit UploadedFile -> str
65
+ raw = file.getvalue().decode("utf-8", errors="ignore")
66
+ data = json.loads(raw)
67
+
68
+ docs = []
69
+
70
+ # ์˜ˆ์ „ jq ๊ฒฝ๋กœ๊ฐ€ '.scans[].relationships'์˜€๋‹ค๋ฉด, ๋™์ผํ•œ ์˜๋ฏธ๋กœ ํŒŒ์‹ฑ:
71
+ # ์กด์žฌํ•˜๋ฉด ๊ทธ๊ฒƒ๋งŒ ๋ฝ‘๊ณ , ์—†์œผ๋ฉด ํ†ต์œผ๋กœ ๋ฌธ์„œํ™”
72
+ def add_doc(x):
73
+ docs.append(Document(page_content=json.dumps(x, ensure_ascii=False)))
74
+
75
+ if isinstance(data, dict) and "scans" in data and isinstance(data["scans"], list):
76
+ for s in data["scans"]:
77
+ rels = s.get("relationships", [])
78
+ if isinstance(rels, list) and rels:
79
+ for r in rels:
80
+ add_doc(r)
81
+ if not docs: # ๊ทธ๋ž˜๋„ ๋ชป ๋ฝ‘์•˜์œผ๋ฉด ์ „์ฒด๋ฅผ ํ•˜๋‚˜๋กœ
82
+ add_doc(data)
83
+ elif isinstance(data, list):
84
+ for item in data:
85
+ add_doc(item)
86
+ else:
87
+ add_doc(data)
88
+
89
+ return docs
90
+
91
+ # ๋ฌธ์„œ๋“ค์„ ์ฒ˜๋ฆฌํ•˜์—ฌ ํ…์ŠคํŠธ ์ฒญํฌ๋กœ ๋‚˜๋ˆ„๋Š” ํ•จ์ˆ˜์ž…๋‹ˆ๋‹ค.
92
+ def get_text_chunks(documents):
93
+ text_splitter = RecursiveCharacterTextSplitter(
94
+ chunk_size=1000, # ์ฒญํฌ์˜ ํฌ๊ธฐ๋ฅผ ์ง€์ •ํ•ฉ๋‹ˆ๋‹ค.
95
+ chunk_overlap=200, # ์ฒญํฌ ์‚ฌ์ด์˜ ์ค‘๋ณต์„ ์ง€์ •ํ•ฉ๋‹ˆ๋‹ค.
96
+ length_function=len # ํ…์ŠคํŠธ์˜ ๊ธธ์ด๋ฅผ ์ธก์ •ํ•˜๋Š” ํ•จ์ˆ˜๋ฅผ ์ง€์ •ํ•ฉ๋‹ˆ๋‹ค.
97
+ )
98
+
99
+ documents = text_splitter.split_documents(documents) # ๋ฌธ์„œ๋“ค์„ ์ฒญํฌ๋กœ ๋‚˜๋ˆ•๋‹ˆ๋‹ค.
100
+ return documents # ๋‚˜๋ˆˆ ์ฒญํฌ๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.
101
+
102
+
103
+ # ํ…์ŠคํŠธ ์ฒญํฌ๋“ค๋กœ๋ถ€ํ„ฐ ๋ฒกํ„ฐ ์Šคํ† ์–ด๋ฅผ ์ƒ์„ฑํ•˜๋Š” ํ•จ์ˆ˜์ž…๋‹ˆ๋‹ค.
104
+ def get_vectorstore(text_chunks):
105
+ # ์›ํ•˜๋Š” ์ž„๋ฒ ๋”ฉ ๋ชจ๋ธ์„ ๋กœ๋“œํ•ฉ๋‹ˆ๋‹ค.
106
+ embeddings = HuggingFaceEmbeddings(model_name='sentence-transformers/all-MiniLM-L12-v2',
107
+ model_kwargs={'device': 'cpu'}) # ์ž„๋ฒ ๋”ฉ ๋ชจ๋ธ์„ ์„ค์ •ํ•ฉ๋‹ˆ๋‹ค.
108
+ vectorstore = FAISS.from_documents(text_chunks, embeddings) # FAISS ๋ฒกํ„ฐ ์Šคํ† ์–ด๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค.
109
+ return vectorstore # ์ƒ์„ฑ๋œ ๋ฒกํ„ฐ ์Šคํ† ์–ด๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.
110
+
111
+
112
+ def get_conversation_chain(vectorstore):
113
+ # Groq LLM
114
+ llm = ChatGroq(
115
+ groq_api_key=os.environ.get("GROQ_API_KEY"),
116
+ model_name="llama-3.1-8b-instant",
117
+ temperature=0.75, # ํ•„์š”์— ๋งž๊ฒŒ ํŠœ๋‹
118
+ max_tokens=512 # ์ปจํ…์ŠคํŠธ ์ดˆ๊ณผ ๋ฐฉ์ง€์šฉ (ํ•„์š”์‹œ ์กฐ์ •)
119
+ )
120
+
121
+ memory = ConversationBufferMemory(
122
+ memory_key="chat_history",
123
+ return_messages=True
124
+ )
125
+ retriever = vectorstore.as_retriever(search_kwargs={"k": 3})
126
+
127
+ conversation_chain = ConversationalRetrievalChain.from_llm(
128
+ llm=llm,
129
+ retriever=retriever,
130
+ memory=memory,
131
+ )
132
+ return conversation_chain
133
+
134
+ # ์‚ฌ์šฉ์ž ์ž…๋ ฅ์„ ์ฒ˜๋ฆฌํ•˜๋Š” ํ•จ์ˆ˜์ž…๋‹ˆ๋‹ค.
135
+ def handle_userinput(user_question):
136
+ print('user_question => ', user_question)
137
+ # ๋Œ€ํ™” ์ฒด์ธ์„ ๏ฟฝ๏ฟฝ๏ฟฝ์šฉํ•˜์—ฌ ์‚ฌ์šฉ์ž ์งˆ๋ฌธ์— ๋Œ€ํ•œ ์‘๋‹ต์„ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค.
138
+ response = st.session_state.conversation({'question': user_question})
139
+ # ๋Œ€ํ™” ๊ธฐ๋ก์„ ์ €์žฅํ•ฉ๋‹ˆ๋‹ค.
140
+ st.session_state.chat_history = response['chat_history']
141
+
142
+ for i, message in enumerate(st.session_state.chat_history):
143
+ if i % 2 == 0:
144
+ st.write(user_template.replace(
145
+ "{{MSG}}", message.content), unsafe_allow_html=True)
146
+ else:
147
+ st.write(bot_template.replace(
148
+ "{{MSG}}", message.content), unsafe_allow_html=True)
149
+
150
+
151
+ def main():
152
+ load_dotenv()
153
+ st.set_page_config(page_title="Basic_RAG_AI_Chatbot_with_Llama",
154
+ page_icon=":books:")
155
+ st.write(css, unsafe_allow_html=True)
156
+
157
+ if "conversation" not in st.session_state:
158
+ st.session_state.conversation = None
159
+ if "chat_history" not in st.session_state:
160
+ st.session_state.chat_history = None
161
+
162
+ st.header("Basic_RAG_AI_Chatbot_with_Llama3 :books:")
163
+ user_question = st.text_input("Ask a question about your documents:")
164
+ if user_question:
165
+ handle_userinput(user_question)
166
+
167
+ with st.sidebar:
168
+ st.subheader("Your documents")
169
+ docs = st.file_uploader(
170
+ "Upload your Files here and click on 'Process'", accept_multiple_files=True)
171
+
172
+ # --- PDF ์ฒ˜๋ฆฌ ๋ฒ„ํŠผ ---
173
+ if st.button("Process[PDF]"):
174
+ with st.spinner("Processing"):
175
+ # get pdf text
176
+ doc_list = []
177
+ for file in docs:
178
+ print('file - type : ', file.type)
179
+ if file.type in ['application/octet-stream', 'application/pdf']:
180
+ # file is .pdf
181
+ doc_list.extend(get_pdf_text(file))
182
+ else:
183
+ st.error("PDF ํŒŒ์ผ์ด ์•„๋‹™๋‹ˆ๋‹ค.")
184
+ if not doc_list:
185
+ st.error("์ฒ˜๋ฆฌ ๊ฐ€๋Šฅํ•œ ๋ฌธ์„œ๋ฅผ ์ฐพ์ง€ ๋ชปํ–ˆ์Šต๋‹ˆ๋‹ค.")
186
+ st.stop()
187
+
188
+ text_chunks = get_text_chunks(doc_list)
189
+ vectorstore = get_vectorstore(text_chunks)
190
+ st.session_state.conversation = get_conversation_chain(vectorstore)
191
+
192
+ # --- TXT ์ฒ˜๋ฆฌ ๋ฒ„ํŠผ (์ž‘์—… 3 ์ถ”๊ฐ€) ---
193
+ if st.button("Process[TXT]"):
194
+ with st.spinner("Processing"):
195
+ # get txt text
196
+ doc_list = []
197
+ for file in docs:
198
+ print('file - type : ', file.type)
199
+ if file.type == 'text/plain':
200
+ # file is .txt
201
+ doc_list.extend(get_text_file(file))
202
+ else:
203
+ st.error("TXT ํŒŒ์ผ์ด ์•„๋‹™๋‹ˆ๋‹ค.")
204
+ if not doc_list:
205
+ st.error("์ฒ˜๋ฆฌ ๊ฐ€๋Šฅํ•œ ๋ฌธ์„œ๋ฅผ ์ฐพ์ง€ ๋ชปํ–ˆ์Šต๋‹ˆ๋‹ค.")
206
+ st.stop()
207
+
208
+ text_chunks = get_text_chunks(doc_list)
209
+ vectorstore = get_vectorstore(text_chunks)
210
+ st.session_state.conversation = get_conversation_chain(vectorstore)
211
+
212
+ # --- CSV ์ฒ˜๋ฆฌ ๋ฒ„ํŠผ (์ž‘์—… 3 ์ถ”๊ฐ€) ---
213
+ if st.button("Process[CSV]"):
214
+ with st.spinner("Processing"):
215
+ # get csv text
216
+ doc_list = []
217
+ for file in docs:
218
+ print('file - type : ', file.type)
219
+ if file.type == 'text/csv':
220
+ # file is .csv
221
+ doc_list.extend(get_csv_file(file))
222
+ else:
223
+ st.error("CSV ํŒŒ์ผ์ด ์•„๋‹™๋‹ˆ๋‹ค.")
224
+ if not doc_list:
225
+ st.error("์ฒ˜๋ฆฌ ๊ฐ€๋Šฅํ•œ ๋ฌธ์„œ๋ฅผ ์ฐพ์ง€ ๋ชปํ–ˆ์Šต๋‹ˆ๋‹ค.")
226
+ st.stop()
227
+
228
+ text_chunks = get_text_chunks(doc_list)
229
+ vectorstore = get_vectorstore(text_chunks)
230
+ st.session_state.conversation = get_conversation_chain(vectorstore)
231
+
232
+ # --- JSON ์ฒ˜๋ฆฌ ๋ฒ„ํŠผ ---
233
+ if st.button("Process[JSON]"):
234
+ with st.spinner("Processing"):
235
+ # get json text
236
+ doc_list = []
237
+ for file in docs:
238
+ print('file - type : ', file.type)
239
+ if file.type == 'application/json':
240
+ # file is .json
241
+ doc_list.extend(get_json_file(file))
242
+ else:
243
+ st.error("JSON ํŒŒ์ผ์ด ์•„๋‹™๋‹ˆ๋‹ค.")
244
+ if not doc_list:
245
+ st.error("์ฒ˜๋ฆฌ ๊ฐ€๋Šฅํ•œ ๋ฌธ์„œ๋ฅผ ์ฐพ์ง€ ๋ชปํ–ˆ์Šต๋‹ˆ๋‹ค.")
246
+ st.stop()
247
+
248
+ text_chunks = get_text_chunks(doc_list)
249
+ vectorstore = get_vectorstore(text_chunks)
250
+ st.session_state.conversation = get_conversation_chain(vectorstore)
251
+
252
+
253
+ if __name__ == '__main__':
254
  main()