nijoow commited on
Commit
36463f1
Β·
1 Parent(s): fd9c269

Delete app.py

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