nijoow commited on
Commit
ee08ee9
Β·
1 Parent(s): e167a91

Delete import streamlit as st.py

Browse files
Files changed (1) hide show
  1. import streamlit as st.py +0 -158
import streamlit as st.py DELETED
@@ -1,158 +0,0 @@
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
- # ν…μŠ€νŠΈ νŒŒμΌμ—μ„œ ν…μŠ€νŠΈλ₯Ό μΆ”μΆœν•˜λŠ” ν•¨μˆ˜μž…λ‹ˆλ‹€.
28
- def get_text_file(docs):
29
- text = docs.getvalue().decode('utf-8') # ν…μŠ€νŠΈ νŒŒμΌμ„ 읽고 UTF-8둜 λ””μ½”λ”©ν•©λ‹ˆλ‹€.
30
- return [text] # μΆ”μΆœν•œ ν…μŠ€νŠΈλ₯Ό 리슀트둜 λ°˜ν™˜ν•©λ‹ˆλ‹€.
31
-
32
- # CSV νŒŒμΌμ—μ„œ ν…μŠ€νŠΈλ₯Ό μΆ”μΆœν•˜λŠ” ν•¨μˆ˜μž…λ‹ˆλ‹€.
33
- def get_csv_file(docs):
34
- import pandas as pd
35
- df = pd.read_csv(docs) # CSV νŒŒμΌμ„ μ½μŠ΅λ‹ˆλ‹€.
36
- text = df.to_string(index=False) # λ°μ΄ν„°ν”„λ ˆμž„μ„ λ¬Έμžμ—΄λ‘œ λ³€ν™˜ν•©λ‹ˆλ‹€.
37
- return [text] # μΆ”μΆœν•œ ν…μŠ€νŠΈλ₯Ό 리슀트둜 λ°˜ν™˜ν•©λ‹ˆλ‹€.
38
-
39
- # JSON νŒŒμΌμ—μ„œ ν…μŠ€νŠΈλ₯Ό μΆ”μΆœν•˜λŠ” ν•¨μˆ˜μž…λ‹ˆλ‹€.
40
- def get_json_file(docs):
41
- import json
42
- data = json.load(docs) # JSON νŒŒμΌμ„ λ‘œλ“œν•©λ‹ˆλ‹€.
43
- text = json.dumps(data) # JSON 데이터λ₯Ό λ¬Έμžμ—΄λ‘œ λ³€ν™˜ν•©λ‹ˆλ‹€.
44
- return [text]
45
-
46
-
47
-
48
- # λ¬Έμ„œλ“€μ„ μ²˜λ¦¬ν•˜μ—¬ ν…μŠ€νŠΈ 청크둜 λ‚˜λˆ„λŠ” ν•¨μˆ˜μž…λ‹ˆλ‹€.
49
- def get_text_chunks(documents):
50
- text_splitter = RecursiveCharacterTextSplitter(
51
- chunk_size=1000, # 청크의 크기λ₯Ό μ§€μ •ν•©λ‹ˆλ‹€.
52
- chunk_overlap=200, # 청크 μ‚¬μ΄μ˜ 쀑볡을 μ§€μ •ν•©λ‹ˆλ‹€.
53
- length_function=len # ν…μŠ€νŠΈμ˜ 길이λ₯Ό μΈ‘μ •ν•˜λŠ” ν•¨μˆ˜λ₯Ό μ§€μ •ν•©λ‹ˆλ‹€.
54
- )
55
-
56
- documents = text_splitter.split_documents(documents) # λ¬Έμ„œλ“€μ„ 청크둜 λ‚˜λˆ•λ‹ˆλ‹€.
57
- return documents # λ‚˜λˆˆ 청크λ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€.
58
-
59
-
60
- # ν…μŠ€νŠΈ μ²­ν¬λ“€λ‘œλΆ€ν„° 벑터 μŠ€ν† μ–΄λ₯Ό μƒμ„±ν•˜λŠ” ν•¨μˆ˜μž…λ‹ˆλ‹€.
61
- def get_vectorstore(text_chunks):
62
- # μ›ν•˜λŠ” μž„λ² λ”© λͺ¨λΈμ„ λ‘œλ“œν•©λ‹ˆλ‹€.
63
- embeddings = HuggingFaceEmbeddings(model_name='sentence-transformers/all-MiniLM-L12-v2',
64
- model_kwargs={'device': 'cpu'}) # μž„λ² λ”© λͺ¨λΈμ„ μ„€μ •ν•©λ‹ˆλ‹€.
65
- vectorstore = FAISS.from_documents(text_chunks, embeddings) # FAISS 벑터 μŠ€ν† μ–΄λ₯Ό μƒμ„±ν•©λ‹ˆλ‹€.
66
- return vectorstore # μƒμ„±λœ 벑터 μŠ€ν† μ–΄λ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€.
67
-
68
-
69
- def get_conversation_chain(vectorstore):
70
- model_name_or_path = 'TheBloke/Llama-2-7B-chat-GGUF'
71
- model_basename = 'llama-2-7b-chat.Q2_K.gguf'
72
- model_path = hf_hub_download(repo_id=model_name_or_path, filename=model_basename)
73
-
74
- llm = LlamaCpp(model_path=model_path,
75
- n_ctx=4086,
76
- input={"temperature": 0.75, "max_length": 2000, "top_p": 1},
77
- verbose=True, )
78
- # λŒ€ν™” 기둝을 μ €μž₯ν•˜κΈ° μœ„ν•œ λ©”λͺ¨λ¦¬λ₯Ό μƒμ„±ν•©λ‹ˆλ‹€.
79
- memory = ConversationBufferMemory(
80
- memory_key='chat_history', return_messages=True)
81
- # λŒ€ν™” 검색 체인을 μƒμ„±ν•©λ‹ˆλ‹€.
82
- conversation_chain = ConversationalRetrievalChain.from_llm(
83
- llm=llm,
84
- retriever=vectorstore.as_retriever(),
85
- memory=memory
86
- )
87
- return conversation_chain # μƒμ„±λœ λŒ€ν™” 체인을 λ°˜ν™˜ν•©λ‹ˆλ‹€.
88
-
89
- # μ‚¬μš©μž μž…λ ₯을 μ²˜λ¦¬ν•˜λŠ” ν•¨μˆ˜μž…λ‹ˆλ‹€.
90
- def handle_userinput(user_question):
91
- print('user_question => ', user_question)
92
- # λŒ€ν™” 체인을 μ‚¬μš©ν•˜μ—¬ μ‚¬μš©μž μ§ˆλ¬Έμ— λŒ€ν•œ 응닡을 μƒμ„±ν•©λ‹ˆλ‹€.
93
- response = st.session_state.conversation({'question': user_question})
94
- # λŒ€ν™” 기둝을 μ €μž₯ν•©λ‹ˆλ‹€.
95
- st.session_state.chat_history = response['chat_history']
96
-
97
- for i, message in enumerate(st.session_state.chat_history):
98
- if i % 2 == 0:
99
- st.write(user_template.replace(
100
- "{{MSG}}", message.content), unsafe_allow_html=True)
101
- else:
102
- st.write(bot_template.replace(
103
- "{{MSG}}", message.content), unsafe_allow_html=True)
104
-
105
-
106
- def main():
107
- load_dotenv()
108
- st.set_page_config(page_title="Chat with multiple Files",
109
- page_icon=":books:")
110
- st.write(css, unsafe_allow_html=True)
111
-
112
- if "conversation" not in st.session_state:
113
- st.session_state.conversation = None
114
- if "chat_history" not in st.session_state:
115
- st.session_state.chat_history = None
116
-
117
- st.header("Chat with multiple Files:")
118
- user_question = st.text_input("Ask a question about your documents:")
119
- if user_question:
120
- handle_userinput(user_question)
121
-
122
- with st.sidebar:
123
- st.subheader("Your documents")
124
- docs = st.file_uploader(
125
- "Upload your PDFs here and click on 'Process'", accept_multiple_files=True)
126
- if st.button("Process"):
127
- with st.spinner("Processing"):
128
- # get pdf text
129
- doc_list = []
130
-
131
- for file in docs:
132
- print('file - type : ', file.type)
133
- if file.type == 'text/plain':
134
- # file is .txt
135
- doc_list.extend(get_text_file(file))
136
- elif file.type in ['application/octet-stream', 'application/pdf']:
137
- # file is .pdf
138
- doc_list.extend(get_pdf_text(file))
139
- elif file.type == 'text/csv':
140
- # file is .csv
141
- doc_list.extend(get_csv_file(file))
142
- elif file.type == 'application/json':
143
- # file is .json
144
- doc_list.extend(get_json_file(file))
145
-
146
- # get the text chunks
147
- text_chunks = get_text_chunks(doc_list)
148
-
149
- # create vector store
150
- vectorstore = get_vectorstore(text_chunks)
151
-
152
- # create conversation chain
153
- st.session_state.conversation = get_conversation_chain(
154
- vectorstore)
155
-
156
-
157
- if __name__ == '__main__':
158
- main()