haiderlawati commited on
Commit
b3f834c
·
1 Parent(s): c08af26

first commit, add all the files

Browse files
Bank Muscat Sign Contract.pdf ADDED
Binary file (101 kB). View file
 
Dockerfile ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 1. Base image
2
+ FROM python:3.8.5-slim-buster
3
+
4
+ WORKDIR /src
5
+
6
+ # 2. Copy files
7
+ COPY . /src
8
+
9
+ # 3. Install dependencies
10
+ RUN pip install --no-cache-dir --upgrade -r /src/requirements.txt
11
+
12
+
13
+ # 4. RUN the application
14
+ CMD ["panel", "serve", "chatbot.py", "--address", "0.0.0.0", "--port", "7860", "--allow-websocket-origin", "haiderlawati-chatbot-example.hf.space"]
cbfs.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import panel as pn
2
+ import param
3
+
4
+ def load_db(file, chain_type, k):
5
+ # load documents
6
+ loader = PyPDFLoader(file)
7
+ documents = loader.load()
8
+ # split documents
9
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=150)
10
+ docs = text_splitter.split_documents(documents)
11
+ # define embedding
12
+ api_key_2 = 'VR7luIAsQnHxMwi5fOkgpkLDIaeFHnva0slnfBlu'
13
+ embeddings = CohereEmbeddings(model='embed-english-v2.0',cohere_api_key=api_key_2)
14
+ # create vector database from data
15
+ db = DocArrayInMemorySearch.from_documents(docs, embeddings)
16
+ # define retriever
17
+ retriever = db.as_retriever(search_type="similarity", search_kwargs={"k": k})
18
+ # create a chatbot chain. Memory is managed externally.
19
+ qa = ConversationalRetrievalChain.from_llm(
20
+ llm=Cohere(temperature=0, cohere_api_key=api_key_2),
21
+ chain_type=chain_type,
22
+ retriever=retriever,
23
+ return_source_documents=True,
24
+ return_generated_question=True,
25
+ )
26
+ return qa
27
+
28
+
29
+ class cbfs(param.Parameterized):
30
+ chat_history = param.List([])
31
+ answer = param.String("")
32
+ db_query = param.String("")
33
+ db_response = param.List([])
34
+
35
+ def __init__(self, **params):
36
+ super(cbfs, self).__init__( **params)
37
+ self.panels = []
38
+ self.loaded_file = "Bank Muscat Sign Contract.pdf"
39
+ self.qa = load_db(self.loaded_file,"stuff", 4)
40
+ self.clr_history_ind = 1
41
+
42
+ def call_load_db(self, count):
43
+ if count == 0 or file_input.value is None: # init or no file specified :
44
+ return pn.pane.Markdown(f"Loaded File: {self.loaded_file}")
45
+ else:
46
+ file_input.save("temp.pdf") # local copy
47
+ self.loaded_file = file_input.filename
48
+ button_load.button_style="outline"
49
+ self.qa = load_db("temp.pdf", "stuff", 4)
50
+ button_load.button_style="solid"
51
+ self.clr_history()
52
+ self.clr_chat()
53
+ return pn.pane.Markdown(f"Loaded File: {self.loaded_file}")
54
+
55
+ def convchain(self, query):
56
+ if not query:
57
+ return pn.WidgetBox(pn.Row('User:', pn.pane.Markdown("", width=600)), scroll=True)
58
+ if self.clr_history_ind == 0:
59
+ self.clr_history_ind = 1
60
+ return pn.WidgetBox(pn.Row('User:', pn.pane.Markdown("", width=600)), scroll=True)
61
+ result = self.qa({"question": query, "chat_history": self.chat_history})
62
+ self.chat_history.extend([(query, result["answer"])])
63
+ self.db_query = result["generated_question"]
64
+ self.db_response = result["source_documents"]
65
+ self.answer = result['answer']
66
+ self.panels.extend([
67
+ pn.Row('User:', pn.pane.Markdown(query, width=600)),
68
+ pn.Row('ChatBot:', pn.pane.Markdown(self.answer, width=600, style={'background-color': '#F6F6F6'}))
69
+ ])
70
+ inp.value = '' #clears loading indicator when cleared
71
+ # self.clr_history_ind = 1
72
+ return pn.WidgetBox(*self.panels,scroll=True)
73
+
74
+ @param.depends('db_query ', )
75
+ def get_lquest(self):
76
+ if not self.db_query :
77
+ return pn.Column(
78
+ pn.Row(pn.pane.Markdown(f"Last question to DB:", styles={'background-color': '#F6F6F6'})),
79
+ pn.Row(pn.pane.Str("no DB accesses so far"))
80
+ )
81
+ return pn.Column(
82
+ pn.Row(pn.pane.Markdown(f"DB query:", styles={'background-color': '#F6F6F6'})),
83
+ pn.pane.Str(self.db_query )
84
+ )
85
+
86
+ @param.depends('db_response', )
87
+ def get_sources(self):
88
+ if not self.db_response:
89
+ return
90
+ rlist=[pn.Row(pn.pane.Markdown(f"Result of DB lookup:", styles={'background-color': '#F6F6F6'}))]
91
+ for doc in self.db_response:
92
+ rlist.append(pn.Row(pn.pane.Str(doc)))
93
+ return pn.WidgetBox(*rlist, width=600, scroll=True)
94
+
95
+ @param.depends('convchain', 'clr_history', 'clr_chat')
96
+ def get_chats(self):
97
+ if not self.chat_history:
98
+ return pn.WidgetBox(pn.Row(pn.pane.Str("No History Yet")), width=600, scroll=True)
99
+ rlist=[pn.Row(pn.pane.Markdown(f"Current Chat History variable", styles={'background-color': '#F6F6F6'}))]
100
+ for exchange in self.chat_history:
101
+ rlist.append(pn.Row(pn.pane.Str(exchange)))
102
+ return pn.WidgetBox(*rlist, width=600, scroll=True)
103
+
104
+ def clr_history(self,count=0):
105
+ self.chat_history = []
106
+ return
107
+
108
+ @param.depends('convchain', 'clr_history')
109
+ def clr_chat(self,count=0):
110
+ self.panels = []
111
+ self.clr_history_ind = 0
112
+ #self.convchain(" ")
113
+ return
chatbot.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langchain.embeddings import CohereEmbeddings
2
+ from langchain.text_splitter import CharacterTextSplitter, RecursiveCharacterTextSplitter
3
+ from langchain.vectorstores import DocArrayInMemorySearch
4
+ from langchain.document_loaders import TextLoader
5
+ from langchain.chains import RetrievalQA, ConversationalRetrievalChain
6
+ from langchain.memory import ConversationBufferMemory
7
+ from langchain.chat_models import ChatOpenAI
8
+ from langchain.document_loaders import TextLoader
9
+ from langchain.document_loaders import PyPDFLoader
10
+ from langchain.llms import Cohere
11
+
12
+ import io
13
+ import cohere
14
+ import os
15
+ import panel as pn
16
+ import param
17
+
18
+ os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
19
+
20
+ def load_db(file, chain_type, k):
21
+ # load documents
22
+ loader = PyPDFLoader(file)
23
+ documents = loader.load()
24
+ # split documents
25
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=150)
26
+ docs = text_splitter.split_documents(documents)
27
+ # define embedding
28
+ api_key_2 = 'VR7luIAsQnHxMwi5fOkgpkLDIaeFHnva0slnfBlu'
29
+ embeddings = CohereEmbeddings(model='embed-english-v2.0',cohere_api_key=api_key_2)
30
+ # create vector database from data
31
+ db = DocArrayInMemorySearch.from_documents(docs, embeddings)
32
+ # define retriever
33
+ retriever = db.as_retriever(search_type="similarity", search_kwargs={"k": k})
34
+ # create a chatbot chain. Memory is managed externally.
35
+ qa = ConversationalRetrievalChain.from_llm(
36
+ llm=Cohere(temperature=0, cohere_api_key=api_key_2),
37
+ chain_type=chain_type,
38
+ retriever=retriever,
39
+ return_source_documents=True,
40
+ return_generated_question=True,
41
+ )
42
+ return qa
43
+
44
+
45
+ class cbfs(param.Parameterized):
46
+ chat_history = param.List([])
47
+ answer = param.String("")
48
+ db_query = param.String("")
49
+ db_response = param.List([])
50
+
51
+ def __init__(self, **params):
52
+ super(cbfs, self).__init__( **params)
53
+ self.panels = []
54
+ self.loaded_file = "Bank Muscat Sign Contract.pdf"
55
+ self.qa = load_db(self.loaded_file,"stuff", 4)
56
+ self.clr_history_ind = 1
57
+
58
+ def call_load_db(self, count):
59
+ if count == 0 or file_input.value is None: # init or no file specified :
60
+ return pn.pane.Markdown(f"Loaded File: {self.loaded_file}")
61
+ else:
62
+ file_input.save("temp.pdf") # local copy
63
+ self.loaded_file = file_input.filename
64
+ button_load.button_style="outline"
65
+ self.qa = load_db("temp.pdf", "stuff", 4)
66
+ button_load.button_style="solid"
67
+ self.clr_history()
68
+ self.clr_chat()
69
+ return pn.pane.Markdown(f"Loaded File: {self.loaded_file}")
70
+
71
+ def convchain(self, query):
72
+ if not query:
73
+ return pn.WidgetBox(pn.Row('User:', pn.pane.Markdown("", width=600)), scroll=True)
74
+ if self.clr_history_ind == 0:
75
+ self.clr_history_ind = 1
76
+ return pn.WidgetBox(pn.Row('User:', pn.pane.Markdown("", width=600)), scroll=True)
77
+ result = self.qa({"question": query, "chat_history": self.chat_history})
78
+ self.chat_history.extend([(query, result["answer"])])
79
+ self.db_query = result["generated_question"]
80
+ self.db_response = result["source_documents"]
81
+ self.answer = result['answer']
82
+ self.panels.extend([
83
+ pn.Row('User:', pn.pane.Markdown(query, width=600)),
84
+ pn.Row('ChatBot:', pn.pane.Markdown(self.answer, width=600, styles={'background-color': '#F6F6F6'}))
85
+ ])
86
+ inp.value = '' #clears loading indicator when cleared
87
+ # self.clr_history_ind = 1
88
+ return pn.WidgetBox(*self.panels,scroll=True)
89
+
90
+ @param.depends('db_query ', )
91
+ def get_lquest(self):
92
+ if not self.db_query :
93
+ return pn.Column(
94
+ pn.Row(pn.pane.Markdown(f"Last question to DB:", styles={'background-color': '#F6F6F6'})),
95
+ pn.Row(pn.pane.Str("no DB accesses so far"))
96
+ )
97
+ return pn.Column(
98
+ pn.Row(pn.pane.Markdown(f"DB query:", styles={'background-color': '#F6F6F6'})),
99
+ pn.pane.Str(self.db_query )
100
+ )
101
+
102
+ @param.depends('db_response', )
103
+ def get_sources(self):
104
+ if not self.db_response:
105
+ return
106
+ rlist=[pn.Row(pn.pane.Markdown(f"Result of DB lookup:", styles={'background-color': '#F6F6F6'}))]
107
+ for doc in self.db_response:
108
+ rlist.append(pn.Row(pn.pane.Str(doc)))
109
+ return pn.WidgetBox(*rlist, width=600, scroll=True)
110
+
111
+ @param.depends('convchain', 'clr_history', 'clr_chat')
112
+ def get_chats(self):
113
+ if not self.chat_history:
114
+ return pn.WidgetBox(pn.Row(pn.pane.Str("No History Yet")), width=600, scroll=True)
115
+ rlist=[pn.Row(pn.pane.Markdown(f"Current Chat History variable", styles={'background-color': '#F6F6F6'}))]
116
+ for exchange in self.chat_history:
117
+ rlist.append(pn.Row(pn.pane.Str(exchange)))
118
+ return pn.WidgetBox(*rlist, width=600, scroll=True)
119
+
120
+ def clr_history(self,count=0):
121
+ self.chat_history = []
122
+ return
123
+
124
+ @param.depends('convchain', 'clr_history')
125
+ def clr_chat(self,count=0):
126
+ self.panels = []
127
+ self.clr_history_ind = 0
128
+ #self.convchain(" ")
129
+ return
130
+
131
+
132
+
133
+ cb = cbfs()
134
+
135
+ file_input = pn.widgets.FileInput(accept='.pdf')
136
+ #file_input = pn.widgets.FileInput()
137
+ button_load = pn.widgets.Button(name="Load DB", button_type='primary')
138
+ button_clearhistory = pn.widgets.Button(name="Clear History", button_type='warning')
139
+ button_clearhistory.on_click(cb.clr_history)
140
+ button_clearchat = pn.widgets.Button(name="Clear Chat", button_type='primary')
141
+ button_clearchat.on_click(cb.clr_chat)
142
+ inp = pn.widgets.TextInput( placeholder='Enter text here…')
143
+
144
+ bound_button_load = pn.bind(cb.call_load_db, button_load.param.clicks)
145
+ conversation = pn.bind(cb.convchain, inp)
146
+
147
+ jpg_pane = pn.pane.Image( './img/NebulaAI.png')
148
+
149
+ tab1 = pn.Column(pn.Row(pn.Column(
150
+ pn.Row(inp),
151
+ pn.layout.Divider(),
152
+ pn.panel(conversation, loading_indicator=True, height=300),
153
+ pn.layout.Divider(),),
154
+ pn.Column(button_clearchat)
155
+ )
156
+ )
157
+ tab2= pn.Column(
158
+ pn.panel(cb.get_lquest),
159
+ pn.layout.Divider(),
160
+ pn.panel(cb.get_sources ),
161
+ )
162
+ tab3= pn.Column(
163
+ pn.panel(cb.get_chats),
164
+ pn.layout.Divider(),
165
+ )
166
+ tab4=pn.Column(
167
+ pn.Row( file_input, button_load, bound_button_load),
168
+ pn.Row( button_clearhistory, pn.pane.Markdown("Clears chat history. Can use to start a new topic" )),
169
+ pn.layout.Divider(),
170
+ pn.Row(jpg_pane.clone(width=400))
171
+ )
172
+ dashboard = pn.Column(
173
+ pn.Row(pn.pane.Markdown('# ODP Chat Bot')),
174
+ pn.Tabs(('Conversation', tab1), ('Database', tab2), ('Chat History', tab3),('Configure', tab4))
175
+ )
176
+ pn.extension()
177
+ dashboard.servable()
img/NebulaAI.png ADDED
img/convchain.jpg ADDED
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ cohere
2
+ python-dotenv
3
+ langchain
4
+ pypdf
5
+ chromadb
6
+ panel