alex6095 commited on
Commit
4298efb
β€’
1 Parent(s): 8946e3e

Kant_demo initial commit

Browse files
.gitattributes CHANGED
@@ -33,3 +33,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ books_paragraphs_data.csv filter=lfs diff=lfs merge=lfs -text
37
+ kant_faiss_index/index.faiss filter=lfs diff=lfs merge=lfs -text
38
+ kant_faiss_index/index.pkl filter=lfs diff=lfs merge=lfs -text
app.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## Import Modules
2
+
3
+ from langchain.document_loaders.csv_loader import CSVLoader
4
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
5
+ from langchain.embeddings.openai import OpenAIEmbeddings
6
+ from langchain.vectorstores import FAISS
7
+ from langchain import OpenAI
8
+ from langchain.chains import RetrievalQA
9
+ from langchain.chat_models import ChatOpenAI
10
+ from langchain.prompts import PromptTemplate
11
+ from langchain.prompts.few_shot import FewShotPromptTemplate
12
+ import os
13
+
14
+ import streamlit as st
15
+ from streamlit_chat import message
16
+ from PIL import Image
17
+
18
+ os.environ['OPENAI_API_KEY'] = st.secrets["OPENAI_API_KEY"]
19
+
20
+
21
+ def check_password():
22
+ """Returns `True` if the user had the correct password."""
23
+
24
+ def password_entered():
25
+ """Checks whether a password entered by the user is correct."""
26
+ # Add at secret
27
+ if hmac.compare_digest(st.session_state["password"], st.secrets["password"]):
28
+ st.session_state["password_correct"] = True
29
+ del st.session_state["password"] # Don't store the password.
30
+ else:
31
+ st.session_state["password_correct"] = False
32
+
33
+ # Return True if the passward is validated.
34
+ if st.session_state.get("password_correct", False):
35
+ return True
36
+
37
+ # Show input for password.
38
+ st.text_input(
39
+ "Password", type="password", on_change=password_entered, key="password"
40
+ )
41
+ if "password_correct" in st.session_state:
42
+ st.error("πŸ˜• Password incorrect")
43
+ return False
44
+
45
+
46
+ if not check_password():
47
+ st.stop() # Do not continue if check_password is not True.
48
+
49
+
50
+ # 주석 λΆ€λΆ„ μžλ™μœΌλ‘œ λ˜λŠ” μ˜μ—­ κ°™μŒ
51
+ loader = CSVLoader(file_path='./books_paragraphs_data.csv',
52
+ encoding='utf-8',
53
+ source_column="Book",
54
+ csv_args={
55
+ # 'delimiter': ',',
56
+ # 'quotechar': '"',
57
+ # 'fieldnames': ['Paragraph ID', 'Paragraph'], : Section λΆ€λΆ„κΉŒμ§€ 탐색에 λ“€μ–΄κ°€λ©΄ λΆ€μ •ν™•ν• μˆ˜λ„? 사싀 크게 영ν–₯ μ—†μ„μˆ˜λ„ μžˆλ‹€.
58
+ # 'fieldnames': ['Section', 'Paragraph ID', 'Paragraph'],
59
+
60
+ })
61
+ docs = loader.load()
62
+
63
+ ## Get data
64
+
65
+ # Get your text splitter ready
66
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
67
+
68
+ # Split your documents into texts
69
+ texts = text_splitter.split_documents(docs)
70
+
71
+ # Turn your texts into embeddings
72
+ embeddings = OpenAIEmbeddings() # model="text-embedding-ada-002"
73
+
74
+ # Get your docsearch ready
75
+ # docsearch = FAISS.from_documents(texts, embeddings)
76
+
77
+ # Save your docsearch
78
+ # docsearch.save_local("faiss_index")
79
+
80
+ # Load your docsearch
81
+ docsearch = FAISS.load_local("kant_faiss_index", embeddings)
82
+
83
+ from langchain.callbacks.base import BaseCallbackHandler
84
+
85
+ class MyCustomHandler(BaseCallbackHandler):
86
+ def __init__(self):
87
+ super().__init__()
88
+ self.tokens = []
89
+
90
+ def on_llm_new_token(self, token: str, **kwargs) -> None:
91
+ # print(f"My custom handler, token: {token}")
92
+ global full_response
93
+ global message_placeholder
94
+ self.tokens.append(token)
95
+ # print(self.tokens)
96
+
97
+ full_response += token
98
+ message_placeholder.markdown(full_response + "β–Œ")
99
+
100
+ # Load up your LLM
101
+ # llm = OpenAI() # 'text-davinci-003', model_name="gpt-4"
102
+ chat = ChatOpenAI(model_name="gpt-4", temperature=0.7, streaming=True, callbacks=[MyCustomHandler()]) # gpt-3.5-turbo, gpt-3.5-turbo-16k, gpt-4-32k : μ •μ œλœ Prompt 7μž₯을 λ„£μœΌλ €λ©΄ Prompt만 4k 이상이어야 함
103
+
104
+ prompt_template = """Imagine yourself as the philosopher Immanuel Kant, living in the 18th century. Engage in a dialogue as him, expressing his views. Be eloquent and reasoned, as befits a man of Hume's intellect and rhetorical skill. Always keep a friendly and conversational tone. Use the following pieces of context to answer the question at the end. If you don't know the answer, just say that you don't know, don't try to make up an answer.
105
+
106
+ {context}
107
+
108
+ Question: {question}
109
+ Answer:"""
110
+ PROMPT = PromptTemplate(
111
+ template=prompt_template, input_variables=["context", "question"]
112
+ )
113
+
114
+ chain_type_kwargs = {"prompt": PROMPT}
115
+ qa = RetrievalQA.from_chain_type(llm=chat,
116
+ chain_type="stuff",
117
+ retriever=docsearch.as_retriever(search_type="mmr", search_kwargs={'k': 10}),
118
+ chain_type_kwargs=chain_type_kwargs,
119
+ return_source_documents=True)
120
+
121
+
122
+ img = Image.open('resource/kant.jpg')
123
+
124
+ # def generate_response(prompt):
125
+ # # query = "How do you define the notion of a cause in his A Treatise of Human Nature? And how is it different from the traditional definition that you reject?"
126
+ # result = qa({"query": prompt})
127
+ # message = result['result']
128
+ # sources = []
129
+ # for src in result['source_documents']:
130
+ # if src.page_content.startswith('Paragraph:'):
131
+ # sources.append(src.metadata['source'])
132
+
133
+ # if len(sources)==0:
134
+ # message = message + "\n\n[No sources]"
135
+ # else:
136
+ # message = message + "\n\n[" + ", ".join(sources) + "]"
137
+
138
+ # return message
139
+
140
+
141
+ col1, col2, col3 = st.columns(3)
142
+
143
+ with col1:
144
+ st.write(' ')
145
+
146
+ with col2:
147
+ st.image(img)
148
+
149
+ with col3:
150
+ st.write(' ')
151
+
152
+
153
+ st.header("Chat with Kant (Demo)")
154
+
155
+ if "messages" not in st.session_state:
156
+ st.session_state.messages = []
157
+
158
+ for message in st.session_state.messages:
159
+ with st.chat_message(message["role"]):
160
+ st.markdown(message["content"])
161
+
162
+ if prompt := st.chat_input("What is up?"):
163
+ st.session_state.messages.append({"role": "user", "content": prompt})
164
+ with st.chat_message("user"):
165
+ st.markdown(prompt)
166
+
167
+ with st.chat_message("assistant"):
168
+ message_placeholder = st.empty()
169
+
170
+ full_response = ""
171
+ result = qa({"query": prompt})
172
+
173
+ sources = set()
174
+ for src in result['source_documents']:
175
+ if src.page_content.startswith('Paragraph:'):
176
+ sources.add(src.metadata['source'])
177
+ sources = list(sources)
178
+
179
+ if len(sources)==0:
180
+ full_response = full_response + "\n\n[No sources]"
181
+ else:
182
+ full_response = full_response + "\n\n[" + ", ".join(sources) + "]"
183
+
184
+ message_placeholder.markdown(full_response)
185
+ st.session_state.messages.append({"role": "assistant", "content": full_response})
books_paragraphs_data.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:36c000721130fe2d2fe2ed6f902777db31dea07a8cf303dcd1a28207292ad03a
3
+ size 4008870
kant_faiss_index/index.faiss ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0e5ff84f605346df2f76df1364493140a902c9e9cd973ed038dd1d6377465516
3
+ size 63412269
kant_faiss_index/index.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3b18f4a4a396f8a78fdd8baabf5944e78dc7a184b8b7e055477a007762ae53e3
3
+ size 5575809
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ openai
2
+ langchain
3
+ tiktoken
4
+ faiss-cpu
5
+ streamlit
6
+ streamlit-chat
resource/kant.jpg ADDED