arslan-ahmed commited on
Commit
85c4fe0
1 Parent(s): 94ae908

initial push

Browse files
Files changed (3) hide show
  1. app.py +498 -0
  2. requirements.txt +7 -0
  3. whatsapp_chat_custom.py +49 -0
app.py ADDED
@@ -0,0 +1,498 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datetime
2
+ import openai
3
+ import uuid
4
+ import gradio as gr
5
+ from langchain.embeddings import OpenAIEmbeddings
6
+ from langchain.vectorstores import Chroma
7
+ from langchain.text_splitter import CharacterTextSplitter, RecursiveCharacterTextSplitter
8
+ from langchain.chains import ConversationalRetrievalChain
9
+ from langchain.chains import RetrievalQA
10
+
11
+ import os
12
+ from langchain.chat_models import ChatOpenAI
13
+ from langchain import OpenAI
14
+ from langchain.document_loaders import WebBaseLoader, TextLoader, Docx2txtLoader, PyMuPDFLoader
15
+ from whatsapp_chat_custom import WhatsAppChatLoader # use this instead of from langchain.document_loaders import WhatsAppChatLoader
16
+
17
+ from collections import deque
18
+ import re
19
+ from bs4 import BeautifulSoup
20
+ import requests
21
+ from urllib.parse import urlparse
22
+ import mimetypes
23
+ from pathlib import Path
24
+ import tiktoken
25
+
26
+
27
+ # Regex pattern to match a URL
28
+ HTTP_URL_PATTERN = r'^http[s]*://.+'
29
+
30
+ mimetypes.init()
31
+ media_files = tuple([x for x in mimetypes.types_map if mimetypes.types_map[x].split('/')[0] in ['image', 'video', 'audio']])
32
+ filter_strings = ['/email-protection#']
33
+
34
+ def get_hyperlinks(url):
35
+ try:
36
+ reqs = requests.get(url)
37
+ if not reqs.headers.get('Content-Type').startswith("text/html") or 400<=reqs.status_code<600:
38
+ return []
39
+ soup = BeautifulSoup(reqs.text, 'html.parser')
40
+ except Exception as e:
41
+ print(e)
42
+ return []
43
+
44
+ hyperlinks = []
45
+ for link in soup.find_all('a', href=True):
46
+ hyperlinks.append(link.get('href'))
47
+
48
+ return hyperlinks
49
+
50
+
51
+ # Function to get the hyperlinks from a URL that are within the same domain
52
+ def get_domain_hyperlinks(local_domain, url):
53
+ clean_links = []
54
+ for link in set(get_hyperlinks(url)):
55
+ clean_link = None
56
+
57
+ # If the link is a URL, check if it is within the same domain
58
+ if re.search(HTTP_URL_PATTERN, link):
59
+ # Parse the URL and check if the domain is the same
60
+ url_obj = urlparse(link)
61
+ if url_obj.netloc == local_domain:
62
+ clean_link = link
63
+
64
+ # If the link is not a URL, check if it is a relative link
65
+ else:
66
+ if link.startswith("/"):
67
+ link = link[1:]
68
+ elif link.startswith(("#", '?', 'mailto:')):
69
+ continue
70
+
71
+ if 'wp-content/uploads' in url:
72
+ clean_link = url+ "/" + link
73
+ else:
74
+ clean_link = "https://" + local_domain + "/" + link
75
+
76
+ if clean_link is not None:
77
+ clean_link = clean_link.strip().rstrip('/').replace('/../', '/')
78
+
79
+ if not any(x in clean_link for x in filter_strings):
80
+ clean_links.append(clean_link)
81
+
82
+ # Return the list of hyperlinks that are within the same domain
83
+ return list(set(clean_links))
84
+
85
+ # this function will get you a list of all the URLs from the base URL
86
+ def crawl(url, local_domain, prog=None):
87
+ # Create a queue to store the URLs to crawl
88
+ queue = deque([url])
89
+
90
+ # Create a set to store the URLs that have already been seen (no duplicates)
91
+ seen = set([url])
92
+
93
+ # While the queue is not empty, continue crawling
94
+ while queue:
95
+ # Get the next URL from the queue
96
+ url_pop = queue.pop()
97
+ # Get the hyperlinks from the URL and add them to the queue
98
+ for link in get_domain_hyperlinks(local_domain, url_pop):
99
+ if link not in seen:
100
+ queue.append(link)
101
+ seen.add(link)
102
+ if len(seen)>=100:
103
+ return seen
104
+ if prog is not None: prog(1, desc=f'Crawling: {url_pop}')
105
+
106
+ return seen
107
+
108
+
109
+ def ingestURL(documents, url, crawling=True, prog=None):
110
+ url = url.rstrip('/')
111
+ # Parse the URL and get the domain
112
+ local_domain = urlparse(url).netloc
113
+ if not (local_domain and url.startswith('http')):
114
+ return documents
115
+ print('Loading URL', url)
116
+ if crawling:
117
+ # crawl to get other webpages from this URL
118
+ if prog is not None: prog(0, desc=f'Crawling: {url}')
119
+ links = crawl(url, local_domain, prog)
120
+ if prog is not None: prog(1, desc=f'Crawling: {url}')
121
+ else:
122
+ links = set([url])
123
+ # separate pdf and other links
124
+ c_links, pdf_links = [], []
125
+ for x in links:
126
+ if x.endswith('.pdf'):
127
+ pdf_links.append(x)
128
+ elif not x.endswith(media_files):
129
+ c_links.append(x)
130
+
131
+ # Clean links loader using WebBaseLoader
132
+ if prog is not None: prog(0.5, desc=f'Ingesting: {url}')
133
+ if c_links:
134
+ loader = WebBaseLoader(list(c_links))
135
+ documents.extend(loader.load())
136
+
137
+ # remote PDFs loader
138
+ for pdf_link in list(pdf_links):
139
+ loader = PyMuPDFLoader(pdf_link)
140
+ doc = loader.load()
141
+ for x in doc:
142
+ x.metadata['source'] = loader.source
143
+ documents.extend(doc)
144
+
145
+ return documents
146
+
147
+ def ingestFiles(documents, files_list, prog=None):
148
+ for fPath in files_list:
149
+ doc = None
150
+ if fPath.endswith('.pdf'):
151
+ doc = PyMuPDFLoader(fPath).load()
152
+ elif fPath.endswith('.txt'):
153
+ doc = TextLoader(fPath).load()
154
+ elif fPath.endswith(('.doc', 'docx')):
155
+ doc = Docx2txtLoader(fPath).load()
156
+ elif 'WhatsApp Chat with' in fPath and fPath.endswith('.csv'):
157
+ doc = WhatsAppChatLoader(fPath).load()
158
+ else:
159
+ pass
160
+
161
+ if doc is not None and doc[0].page_content:
162
+ if prog is not None: prog(1, desc='Loaded file: '+fPath.rsplit('/')[0])
163
+ print('Loaded file:', fPath)
164
+ documents.extend(doc)
165
+ return documents
166
+
167
+
168
+ def data_ingestion(inputDir=None, file_list=[], waDir=None, url_list=[], prog=None):
169
+ documents = []
170
+ # Ingestion from Input Directory
171
+ if inputDir is not None:
172
+ files = [str(x) for x in Path(inputDir).glob('**/*')]
173
+ documents = ingestFiles(documents, files)
174
+ if file_list:
175
+ documents = ingestFiles(documents, file_list, prog)
176
+ # Ingestion of whatsapp chats - Convert Whatsapp TXT files to CSV using https://whatstk.streamlit.app/
177
+ if waDir is not None:
178
+ for fPath in [str(x) for x in Path(waDir).glob('**/*.csv')]:
179
+ waDoc = WhatsAppChatLoader(fPath).load()
180
+ if waDoc[0].page_content:
181
+ print('Loaded whatsapp file:', fPath)
182
+ documents.extend(waDoc)
183
+ # Ingestion from URLs - also try https://python.langchain.com/docs/integrations/document_loaders/recursive_url_loader
184
+ if url_list:
185
+ for url in url_list:
186
+ documents = ingestURL(documents, url, prog=prog)
187
+
188
+
189
+ # Cleanup documents
190
+ for x in documents:
191
+ if 'WhatsApp Chat with ' not in x.metadata['source']:
192
+ x.page_content = x.page_content.strip().replace('\n', ' ').replace('\\n', ' ').replace(' ', ' ')
193
+
194
+ print(f"Total number of documents: {len(documents)}")
195
+ return documents
196
+
197
+
198
+ def split_docs(documents):
199
+ # Splitting and Chunks
200
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=2500, chunk_overlap=250) # default chunk size of 4000 makes around 1k tokens per doc. with k=4, this means 4k tokens input to LLM.
201
+ docs = text_splitter.split_documents(documents)
202
+ return docs
203
+
204
+ # used for Hardcoded documents only - not uploaded by user
205
+ def getVectorStore(openApiKey, documents, chromaClient=None):
206
+ docs = split_docs(documents)
207
+ # Embeddings
208
+ embeddings = OpenAIEmbeddings(openai_api_key=openApiKey)
209
+ # create chroma client if doesnt exist
210
+ if chromaClient is None:
211
+ chromaClient = Chroma(embedding_function=embeddings)
212
+ # clear chroma client before adding new docs
213
+ if chromaClient._collection.count()>0:
214
+ chromaClient.delete(chromaClient.get()['ids'])
215
+ # add new docs to chroma client
216
+ chromaClient.add_documents(docs)
217
+ print('vectorstore count:',chromaClient._collection.count(), 'at', datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
218
+
219
+ return chromaClient
220
+
221
+
222
+ def getSourcesFromMetadata(metadata, sourceOnly=True, sepFileUrl=True):
223
+ # metadata: list of metadata dict from all documents
224
+ setSrc = set()
225
+ for x in metadata:
226
+ metadataText = '' # we need to convert each metadata dict into a string format. This string will be added to a set
227
+ if x is not None:
228
+ # extract source first, and then extract all other items
229
+ source = x['source']
230
+ source = source.rsplit('/',1)[-1] if 'http' not in source else source
231
+ notSource = []
232
+ for k,v in x.items():
233
+ if v is not None and k!='source' and k in ['page', 'title']:
234
+ notSource.extend([f"{k}: {v}"])
235
+ metadataText = ', '.join([f'source: {source}'] + notSource) if sourceOnly==False else source
236
+ setSrc.add(metadataText)
237
+
238
+ if sepFileUrl:
239
+ src_files = '\n'.join(([f"{i+1}) {x}" for i,x in enumerate(sorted([x for x in setSrc if 'http' not in x], key=str.casefold))]))
240
+ src_urls = '\n'.join(([f"{i+1}) {x}" for i,x in enumerate(sorted([x for x in setSrc if 'http' in x], key=str.casefold))]))
241
+
242
+ src_files = 'Files:\n'+src_files if src_files else ''
243
+ src_urls = 'URLs:\n'+src_urls if src_urls else ''
244
+ newLineSep = '\n\n' if src_files and src_urls else ''
245
+
246
+ return src_files + newLineSep + src_urls , len(setSrc)
247
+ else:
248
+ src_docs = '\n'.join(([f"{i+1}) {x}" for i,x in enumerate(sorted(list(setSrc), key=str.casefold))]))
249
+ return src_docs, len(setSrc)
250
+
251
+ def num_tokens_from_string(string, encoding_name = "cl100k_base"):
252
+ """Returns the number of tokens in a text string."""
253
+ encoding = tiktoken.get_encoding(encoding_name)
254
+ num_tokens = len(encoding.encode(string))
255
+ return num_tokens
256
+ ###############################################################################################
257
+
258
+ # Hardcoded Documents
259
+
260
+ # documents = []
261
+
262
+ # # Data Ingestion - take list of documents
263
+ # documents = data_ingestion(inputDir= '../reports/',waDir = '../whatsapp-exports/')
264
+ # full_text = ''.join([x.page_content for x in documents])
265
+ # print('Full Text Len:', len(full_text), 'Num tokens:', num_tokens_from_string(full_text))
266
+
267
+ # # Embeddings
268
+ # vectorstore = getVectorStore(os.getenv("OPENAI_API_KEY"), documents)
269
+
270
+
271
+
272
+ ###############################################################################################
273
+
274
+ # Gradio
275
+
276
+ ###############################################################################################
277
+
278
+ def generateExamples(api_key_st, vsDict_st):
279
+ qa_chain = RetrievalQA.from_llm(llm=ChatOpenAI(openai_api_key=api_key_st, temperature=0),
280
+ retriever=vsDict_st['chromaClient'].as_retriever(search_type="similarity", search_kwargs={"k": 4}))
281
+
282
+ result = qa_chain({'query': 'Generate top 5 questions that I can ask about this data. Questions should be very precise and short, ideally less than 10 words.'})
283
+ answer = result['result'].strip('\n')
284
+ grSamples = [[]]
285
+ if answer.startswith('1. '):
286
+ lines = answer.split("\n") # split the answers into individual lines
287
+ list_items = [line.split(". ")[1] for line in lines] # extract each answer after the numbering
288
+ grSamples = [[x] for x in list_items] # gr takes list of each item as a list
289
+
290
+ return grSamples
291
+
292
+ # initialize chatbot function sets the QA Chain, and also sets/updates any other components to start chatting. updateQaChain function only updates QA chain and will be called whenever Adv Settings are updated.
293
+ def initializeChatbot(temp, k, modelName, stdlQs, api_key_st, vsDict_st, progress=gr.Progress()):
294
+ progress(0.1, 'Analyzing your documents, please wait...')
295
+ qa_chain_st = updateQaChain(temp, k, modelName, stdlQs, api_key_st, vsDict_st)
296
+ progress(0.5, 'Analyzing your documents, please wait...')
297
+ #generate welcome message
298
+ result = qa_chain_st({'question': 'Write a short welcome message to the user. Describe the document with a brief overview and short summary or any highlights. If this document is about a person, mention his name instead of using pronouns. After this, you should include top 3 example questions that user can ask about this data. Make sure you have got answers to those questions within the data. Your response should be short and precise. Format of your response should be Summary: {summary} \n\n\n Example Questions: {examples}', 'chat_history':[]})
299
+ # exSamples = generateExamples(api_key_st, vsDict_st)
300
+ # exSamples_vis = True if exSamples[0] else False
301
+
302
+ return qa_chain_st, btn.update(interactive=True), initChatbot_btn.update('Chatbot ready. Now visit the chatbot Tab.', interactive=False)\
303
+ , status_tb.update(), gr.Tabs.update(selected='cb'), chatbot.update(value=[('', result['answer'])])
304
+
305
+
306
+
307
+ def setApiKey(api_key):
308
+ if api_key==os.getenv("TEMP_PWD") and os.getenv("OPENAI_API_KEY") is not None:
309
+ api_key=os.getenv("OPENAI_API_KEY")
310
+ try:
311
+ api_key='Null' if api_key is None or api_key=='' else api_key
312
+ openai.Model.list(api_key=api_key) # test the API key
313
+ api_key_st = api_key
314
+
315
+ return aKey_tb.update('API Key accepted', interactive=False, type='text'), aKey_btn.update(interactive=False), api_key_st
316
+ except Exception as e:
317
+ return aKey_tb.update(str(e), type='text'), *[x.update() for x in [aKey_btn, api_key_state]]
318
+
319
+ # convert user uploaded data to vectorstore
320
+ def userData_vecStore(userFiles, userUrls, api_key_st, vsDict_st={}, progress=gr.Progress()):
321
+ opComponents = [data_ingest_btn, upload_fb, urls_tb]
322
+ file_paths = []
323
+ documents = []
324
+ if userFiles is not None:
325
+ if not isinstance(userFiles, list): userFiles = [userFiles]
326
+ file_paths = [file.name for file in userFiles]
327
+ userUrls = [x.strip() for x in userUrls.split(",")] if userUrls else []
328
+ documents = data_ingestion(file_list=file_paths, url_list=userUrls, prog=progress)
329
+ if documents:
330
+ for file in file_paths:
331
+ os.remove(file)
332
+ else:
333
+ return {}, '', *[x.update() for x in opComponents]
334
+
335
+ # Splitting and Chunks
336
+ docs = split_docs(documents)
337
+ # Embeddings
338
+ try:
339
+ api_key_st='Null' if api_key_st is None or api_key_st=='' else api_key_st
340
+ openai.Model.list(api_key=api_key_st) # test the API key
341
+ embeddings = OpenAIEmbeddings(openai_api_key=api_key_st)
342
+ except Exception as e:
343
+ return {}, str(e), *[x.update() for x in opComponents]
344
+
345
+ progress(0.5, 'Creating Vector Database')
346
+ # create chroma client if doesnt exist
347
+ if vsDict_st.get('chromaDir') is None:
348
+ vsDict_st['chromaDir'] = str(uuid.uuid1())
349
+ vsDict_st['chromaClient'] = Chroma(embedding_function=embeddings, persist_directory=vsDict_st['chromaDir'])
350
+ # clear chroma client before adding new docs
351
+ if vsDict_st['chromaClient']._collection.count()>0:
352
+ vsDict_st['chromaClient'].delete(vsDict_st['chromaClient'].get()['ids'])
353
+ # add new docs to chroma client
354
+ vsDict_st['chromaClient'].add_documents(docs)
355
+ print('vectorstore count:',vsDict_st['chromaClient']._collection.count(), 'at', datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
356
+
357
+ op_docs_str = getSourcesFromMetadata(vsDict_st['chromaClient'].get()['metadatas'])
358
+ op_docs_str = str(op_docs_str[1]) + ' document(s) successfully loaded in vector store.'+'\n\n' + op_docs_str[0]
359
+ progress(1, 'Data loaded')
360
+ return vsDict_st, op_docs_str, *[x.update(interactive=False) for x in [data_ingest_btn, upload_fb]], urls_tb.update(interactive=False, placeholder='')
361
+
362
+ # just update the QA Chain, no updates to any UI
363
+ def updateQaChain(temp, k, modelName, stdlQs, api_key_st, vsDict_st):
364
+ modelName = modelName.split('(')[0].strip() # so we can provide any info in brackets
365
+ # check if the input model is chat model or legacy model
366
+ try:
367
+ ChatOpenAI(openai_api_key=api_key_st, temperature=0,model_name=modelName,max_tokens=1).predict('')
368
+ llm = ChatOpenAI(openai_api_key=api_key_st, temperature=float(temp),model_name=modelName)
369
+ except:
370
+ OpenAI(openai_api_key=api_key_st, temperature=0,model_name=modelName,max_tokens=1).predict('')
371
+ llm = OpenAI(openai_api_key=api_key_st, temperature=float(temp),model_name=modelName)
372
+ # settingsUpdated = 'Settings updated:'+ ' Model=' + modelName + ', Temp=' + str(temp)+ ', k=' + str(k)
373
+ # gr.Info(settingsUpdated)
374
+
375
+ # Now create QA Chain using the LLM
376
+ if stdlQs==0: # 0th index i.e. first option
377
+ qa_chain_st = RetrievalQA.from_llm(
378
+ llm=llm,
379
+ retriever=vsDict_st['chromaClient'].as_retriever(search_type="similarity", search_kwargs={"k": int(k)}),
380
+ return_source_documents=True,
381
+ input_key = 'question', output_key='answer' # to align with ConversationalRetrievalChain for downstream functions
382
+ )
383
+ else:
384
+ rephQs = False if stdlQs==1 else True
385
+ qa_chain_st = ConversationalRetrievalChain.from_llm(
386
+ llm=llm,
387
+ retriever=vsDict_st['chromaClient'].as_retriever(search_type="similarity", search_kwargs={"k": int(k)}),
388
+ rephrase_question=rephQs,
389
+ return_source_documents=True,
390
+ return_generated_question=True
391
+ )
392
+
393
+ return qa_chain_st
394
+
395
+
396
+ def respond(message, chat_history, qa_chain):
397
+ result = qa_chain({'question': message, "chat_history": [tuple(x) for x in chat_history]})
398
+ src_docs = getSourcesFromMetadata([x.metadata for x in result["source_documents"]], sourceOnly=False)[0]
399
+ # streaming
400
+ streaming_answer = ""
401
+ for ele in "".join(result['answer']):
402
+ streaming_answer += ele
403
+ yield "", chat_history + [(message, streaming_answer)], src_docs, btn.update('Please wait...', interactive=False)
404
+
405
+ chat_history.extend([(message, result['answer'])])
406
+ yield "", chat_history, src_docs, btn.update('Send Message', interactive=True)
407
+
408
+ #####################################################################################################
409
+
410
+ with gr.Blocks(theme=gr.themes.Default(primary_hue='orange', secondary_hue='gray', neutral_hue='blue'), css="footer {visibility: hidden}") as demo:
411
+
412
+ # Initialize state variables - stored in this browser session - these can only be used within input or output of .click/.submit etc, not as a python var coz they are not stored in backend, only as a frontend gradio component
413
+ # but if you initialize it with a default value, that value will be stored in backend and accessible across all users. You can also change it with statear.value='newValue'
414
+ qa_state = gr.State()
415
+ api_key_state = gr.State()
416
+ chromaVS_state = gr.State({})
417
+
418
+
419
+ # Setup the Gradio Layout
420
+ gr.Markdown(
421
+ """
422
+ ## Chat with your documents and websites<br>
423
+ Step 1) Enter your OpenAI API Key, and click Submit.
424
+ Step 2) Upload your documents and/or enter URLs, then click Load Data.
425
+ Step 3) Once data is loaded, click Initialize Chatbot (at the bottom of the page) to start talking to your data.
426
+
427
+ Your documents should be semantically similar (covering related topics or having the similar meaning) in order to get the best results.
428
+ You may also play around with Advanced Settings, like changing the model name and parameters.
429
+ """)
430
+ with gr.Tabs() as tabs:
431
+ with gr.Tab('Initialization', id='init'):
432
+ with gr.Row():
433
+ with gr.Column():
434
+ aKey_tb = gr.Textbox(label="OpenAI API Key", type='password'\
435
+ , info='You can find OpenAI API key at https://platform.openai.com/account/api-keys'\
436
+ , placeholder='Enter your API key here and hit enter to begin chatting')
437
+ aKey_btn = gr.Button("Submit API Key")
438
+ with gr.Row():
439
+ upload_fb = gr.Files(scale=5, label="Upload (multiple) Files - pdf/txt/docx supported", file_types=['.doc', '.docx', 'text', '.pdf', '.csv'])
440
+ urls_tb = gr.Textbox(scale=5, label="Enter URLs starting with https (comma separated)"\
441
+ , info='Upto 100 domain webpages will be crawled for each URL. You can also enter online PDF files.'\
442
+ , placeholder='https://example.com, https://another.com, https://anyremotedocument.pdf')
443
+ data_ingest_btn = gr.Button("Load Data")
444
+ status_tb = gr.TextArea(label='Status bar', show_label=False)
445
+ initChatbot_btn = gr.Button("Initialize Chatbot")
446
+
447
+ with gr.Tab('Chatbot', id='cb'):
448
+ with gr.Row():
449
+ chatbot = gr.Chatbot(label="Chat History", scale=2)
450
+ srcDocs = gr.TextArea(label="References")
451
+ msg = gr.Textbox(label="User Input",placeholder="Type your questions here")
452
+ with gr.Row():
453
+ btn = gr.Button("Send Message", interactive=False)
454
+ clear = gr.ClearButton(components=[msg, chatbot, srcDocs], value="Clear chat history")
455
+ with gr.Row():
456
+ # exp_comp = gr.Dataset(scale=0.7, samples=[['123'],['456'], ['123'],['456'],['456']], components=[msg], label='Examples (auto generated by LLM)', visible=False)
457
+ # gr.Examples(examples=exps, inputs=msg)
458
+ with gr.Accordion("Advance Settings - click to expand", open=False):
459
+ with gr.Row():
460
+ temp_sld = gr.Slider(minimum=0, maximum=1, step=0.1, value=0.7, label="Temperature", info='Sampling temperature to use when calling LLM. Defaults to 0.7')
461
+ k_sld = gr.Slider(minimum=1, maximum=10, step=1, value=4, label="K", info='Number of relavant documents to return from Vector Store. Defaults to 4')
462
+ model_dd = gr.Dropdown(label='Model Name'\
463
+ , choices=['gpt-3.5-turbo', 'gpt-3.5-turbo-16k', 'gpt-4', 'text-davinci-003 (Legacy)', 'text-curie-001 (Legacy)', 'babbage-002']\
464
+ , value='gpt-3.5-turbo', allow_custom_value=True\
465
+ , info='You can also input any OpenAI model name, compatible with /v1/completions or /v1/chat/completions endpoint. Details: https://platform.openai.com/docs/models/')
466
+ stdlQs_rb = gr.Radio(label='Standalone Question', info='Standalone question is a new rephrased question generated based on your original question and chat history'\
467
+ , type='index', value='Retrieve relavant docs using standalone question, send original question to LLM'\
468
+ , choices=['Retrieve relavant docs using original question, send original question to LLM (Chat history not considered)'\
469
+ , 'Retrieve relavant docs using standalone question, send original question to LLM'\
470
+ , 'Retrieve relavant docs using standalone question, send standalone question to LLM'])
471
+
472
+ ### Setup the Gradio Event Listeners
473
+
474
+ # API button
475
+ aKey_btn_args = {'fn':setApiKey, 'inputs':[aKey_tb], 'outputs':[aKey_tb, aKey_btn, api_key_state]}
476
+ aKey_btn.click(**aKey_btn_args)
477
+ aKey_tb.submit(**aKey_btn_args)
478
+
479
+ # Data Ingest Button
480
+ data_ingest_btn.click(userData_vecStore, [upload_fb, urls_tb, api_key_state, chromaVS_state], [chromaVS_state, status_tb, data_ingest_btn, upload_fb, urls_tb])
481
+
482
+ # Adv Settings
483
+ advSet_args = {'fn':updateQaChain, 'inputs':[temp_sld, k_sld, model_dd, stdlQs_rb, api_key_state, chromaVS_state], 'outputs':[qa_state]}
484
+ temp_sld.change(**advSet_args)
485
+ k_sld.change(**advSet_args)
486
+ model_dd.change(**advSet_args)
487
+ stdlQs_rb.change(**advSet_args)
488
+
489
+ # Initialize button
490
+ initChatbot_btn.click(initializeChatbot, [temp_sld, k_sld, model_dd, stdlQs_rb, api_key_state, chromaVS_state], [qa_state, btn, initChatbot_btn, status_tb, tabs, chatbot])
491
+
492
+ # Chatbot submit button
493
+ chat_btn_args = {'fn':respond, 'inputs':[msg, chatbot, qa_state], 'outputs':[msg, chatbot, srcDocs, btn]}
494
+ btn.click(**chat_btn_args)
495
+ msg.submit(**chat_btn_args)
496
+
497
+ demo.queue()
498
+ demo.launch(show_error=True)
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ openai
2
+ langchain
3
+ beautifulsoup4
4
+ chromadb
5
+ tiktoken
6
+ pypdf
7
+ gradio
whatsapp_chat_custom.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # created custom class for WhatsAppChatLoader - because original langchain one isnt working
2
+
3
+ import re
4
+ from pathlib import Path
5
+ from typing import List
6
+
7
+ from langchain.docstore.document import Document
8
+ from langchain.document_loaders.base import BaseLoader
9
+
10
+
11
+ def concatenate_rows(date: str, sender: str, text: str) -> str:
12
+ """Combine message information in a readable format ready to be used."""
13
+ return f"{sender} on {date}: {text}\n\n"
14
+
15
+ # def concatenate_rows(date: str, sender: str, text: str) -> str:
16
+ # """Combine message information in a readable format ready to be used."""
17
+ # return f"{text}\n"
18
+
19
+ class WhatsAppChatLoader(BaseLoader):
20
+ """Load `WhatsApp` messages text file."""
21
+
22
+ def __init__(self, path: str):
23
+ """Initialize with path."""
24
+ self.file_path = path
25
+
26
+ def load(self) -> List[Document]:
27
+ """Load documents."""
28
+ p = Path(self.file_path)
29
+ text_content = ""
30
+
31
+ ignore_lines = ["This message was deleted", "<Media omitted>"]
32
+ #########################################################################################
33
+ # original code from langchain replaced with this code
34
+ #########################################################################################
35
+ # use https://whatstk.streamlit.app/ to get CSV
36
+ import pandas as pd
37
+ df = pd.read_csv(p)[['date', 'username', 'message']]
38
+
39
+ for i,row in df.iterrows():
40
+ date = row['date']
41
+ sender = row['username']
42
+ text = row['message']
43
+
44
+ if not any(x in text for x in ignore_lines):
45
+ text_content += concatenate_rows(date, sender, text)
46
+
47
+ metadata = {"source": str(p)}
48
+
49
+ return [Document(page_content=text_content.strip(), metadata=metadata)]