dataroadmap commited on
Commit
02cae1b
1 Parent(s): f66b5a2

updated BAM models

Browse files
Files changed (1) hide show
  1. ttyd_functions.py +376 -0
ttyd_functions.py ADDED
@@ -0,0 +1,376 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datetime
2
+ import gradio as gr
3
+ import time
4
+ import uuid
5
+ import openai
6
+ from langchain.embeddings import OpenAIEmbeddings
7
+ from langchain.vectorstores import Chroma
8
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
9
+ from langchain.embeddings import SentenceTransformerEmbeddings
10
+
11
+ import os
12
+ from langchain.document_loaders import WebBaseLoader, TextLoader, Docx2txtLoader, PyMuPDFLoader, UnstructuredPowerPointLoader
13
+ from whatsapp_chat_custom import WhatsAppChatLoader # use this instead of from langchain.document_loaders import WhatsAppChatLoader
14
+
15
+ from collections import deque
16
+ import re
17
+ from bs4 import BeautifulSoup
18
+ import requests
19
+ from urllib.parse import urlparse
20
+ import mimetypes
21
+ from pathlib import Path
22
+ import tiktoken
23
+ import gdown
24
+
25
+ from langchain.chat_models import ChatOpenAI
26
+ from langchain import OpenAI
27
+
28
+ from ibm_watson_machine_learning.metanames import GenTextParamsMetaNames as GenParams
29
+ from ibm_watson_machine_learning.foundation_models.utils.enums import DecodingMethods
30
+ from ibm_watson_machine_learning.foundation_models import Model
31
+ from ibm_watson_machine_learning.foundation_models.extensions.langchain import WatsonxLLM
32
+
33
+
34
+ import genai
35
+ from genai.extensions.langchain import LangChainInterface
36
+ from genai.schemas import GenerateParams
37
+
38
+ # Regex pattern to match a URL
39
+ HTTP_URL_PATTERN = r'^http[s]*://.+'
40
+
41
+ mimetypes.init()
42
+ media_files = tuple([x for x in mimetypes.types_map if mimetypes.types_map[x].split('/')[0] in ['image', 'video', 'audio']])
43
+ filter_strings = ['/email-protection#']
44
+
45
+ def getOaiCreds(key):
46
+ key = key if key else 'Null'
47
+ return {'service': 'openai',
48
+ 'oai_key' : key
49
+ }
50
+
51
+
52
+ def getBamCreds(key):
53
+ key = key if key else 'Null'
54
+ return {'service': 'bam',
55
+ 'bam_creds' : genai.Credentials(key, api_endpoint='https://bam-api.res.ibm.com/v1')
56
+ }
57
+
58
+
59
+ def getWxCreds(key, p_id):
60
+ key = key if key else 'Null'
61
+ p_id = p_id if p_id else 'Null'
62
+ return {'service': 'watsonx',
63
+ 'credentials' : {"url": "https://us-south.ml.cloud.ibm.com", "apikey": key },
64
+ 'project_id': p_id
65
+ }
66
+
67
+ def getPersonalBotApiKey():
68
+ if os.getenv("OPENAI_API_KEY"):
69
+ return getOaiCreds(os.getenv("OPENAI_API_KEY"))
70
+ elif os.getenv("WX_API_KEY") and os.getenv("WX_PROJECT_ID"):
71
+ return getWxCreds(os.getenv("WX_API_KEY"), os.getenv("WX_PROJECT_ID"))
72
+ elif os.getenv("BAM_API_KEY"):
73
+ return getBamCreds(os.getenv("BAM_API_KEY"))
74
+ else:
75
+ return {}
76
+
77
+
78
+
79
+ def getOaiLlm(temp, modelNameDD, api_key_st):
80
+ modelName = modelNameDD.split('(')[0].strip()
81
+ # check if the input model is chat model or legacy model
82
+ try:
83
+ ChatOpenAI(openai_api_key=api_key_st['oai_key'], temperature=0,model_name=modelName,max_tokens=1).predict('')
84
+ llm = ChatOpenAI(openai_api_key=api_key_st['oai_key'], temperature=float(temp),model_name=modelName)
85
+ except:
86
+ OpenAI(openai_api_key=api_key_st['oai_key'], temperature=0,model_name=modelName,max_tokens=1).predict('')
87
+ llm = OpenAI(openai_api_key=api_key_st['oai_key'], temperature=float(temp),model_name=modelName)
88
+ return llm
89
+
90
+
91
+ MAX_NEW_TOKENS = 1024
92
+ TOP_K = None
93
+ TOP_P = 1
94
+
95
+ def getWxLlm(temp, modelNameDD, api_key_st):
96
+ modelName = modelNameDD.split('(')[0].strip()
97
+ wxModelParams = {
98
+ GenParams.DECODING_METHOD: DecodingMethods.SAMPLE,
99
+ GenParams.MAX_NEW_TOKENS: MAX_NEW_TOKENS,
100
+ GenParams.TEMPERATURE: float(temp),
101
+ GenParams.TOP_K: TOP_K,
102
+ GenParams.TOP_P: TOP_P
103
+ }
104
+ model = Model(
105
+ model_id=modelName,
106
+ params=wxModelParams,
107
+ credentials=api_key_st['credentials'], project_id=api_key_st['project_id'])
108
+ llm = WatsonxLLM(model=model)
109
+ return llm
110
+
111
+
112
+ def getBamLlm(temp, modelNameDD, api_key_st):
113
+ modelName = modelNameDD.split('(')[0].strip()
114
+ parameters = GenerateParams(decoding_method="sample", max_new_tokens=MAX_NEW_TOKENS, temperature=float(temp), top_k=TOP_K, top_p=TOP_P)
115
+ llm = LangChainInterface(model=modelName, params=parameters, credentials=api_key_st['bam_creds'])
116
+ return llm
117
+
118
+
119
+ def get_hyperlinks(url):
120
+ try:
121
+ reqs = requests.get(url)
122
+ if not reqs.headers.get('Content-Type').startswith("text/html") or 400<=reqs.status_code<600:
123
+ return []
124
+ soup = BeautifulSoup(reqs.text, 'html.parser')
125
+ except Exception as e:
126
+ print(e)
127
+ return []
128
+
129
+ hyperlinks = []
130
+ for link in soup.find_all('a', href=True):
131
+ hyperlinks.append(link.get('href'))
132
+
133
+ return hyperlinks
134
+
135
+
136
+ # Function to get the hyperlinks from a URL that are within the same domain
137
+ def get_domain_hyperlinks(local_domain, url):
138
+ clean_links = []
139
+ for link in set(get_hyperlinks(url)):
140
+ clean_link = None
141
+
142
+ # If the link is a URL, check if it is within the same domain
143
+ if re.search(HTTP_URL_PATTERN, link):
144
+ # Parse the URL and check if the domain is the same
145
+ url_obj = urlparse(link)
146
+ if url_obj.netloc.replace('www.','') == local_domain.replace('www.',''):
147
+ clean_link = link
148
+
149
+ # If the link is not a URL, check if it is a relative link
150
+ else:
151
+ if link.startswith("/"):
152
+ link = link[1:]
153
+ elif link.startswith(("#", '?', 'mailto:')):
154
+ continue
155
+
156
+ if 'wp-content/uploads' in url:
157
+ clean_link = url+ "/" + link
158
+ else:
159
+ clean_link = "https://" + local_domain + "/" + link
160
+
161
+ if clean_link is not None:
162
+ clean_link = clean_link.strip().rstrip('/').replace('/../', '/')
163
+
164
+ if not any(x in clean_link for x in filter_strings):
165
+ clean_links.append(clean_link)
166
+
167
+ # Return the list of hyperlinks that are within the same domain
168
+ return list(set(clean_links))
169
+
170
+ # this function will get you a list of all the URLs from the base URL
171
+ def crawl(url, local_domain, prog=None):
172
+ # Create a queue to store the URLs to crawl
173
+ queue = deque([url])
174
+
175
+ # Create a set to store the URLs that have already been seen (no duplicates)
176
+ seen = set([url])
177
+
178
+ # While the queue is not empty, continue crawling
179
+ while queue:
180
+ # Get the next URL from the queue
181
+ url_pop = queue.pop()
182
+ # Get the hyperlinks from the URL and add them to the queue
183
+ for link in get_domain_hyperlinks(local_domain, url_pop):
184
+ if link not in seen:
185
+ queue.append(link)
186
+ seen.add(link)
187
+ if len(seen)>=100:
188
+ return seen
189
+ if prog is not None: prog(1, desc=f'Crawling: {url_pop}')
190
+
191
+ return seen
192
+
193
+
194
+ def ingestURL(documents, url, crawling=True, prog=None):
195
+ url = url.rstrip('/')
196
+ # Parse the URL and get the domain
197
+ local_domain = urlparse(url).netloc
198
+ if not (local_domain and url.startswith('http')):
199
+ return documents
200
+ print('Loading URL', url)
201
+ if crawling:
202
+ # crawl to get other webpages from this URL
203
+ if prog is not None: prog(0, desc=f'Crawling: {url}')
204
+ links = crawl(url, local_domain, prog)
205
+ if prog is not None: prog(1, desc=f'Crawling: {url}')
206
+ else:
207
+ links = set([url])
208
+ # separate pdf and other links
209
+ c_links, pdf_links = [], []
210
+ for x in links:
211
+ if x.endswith('.pdf'):
212
+ pdf_links.append(x)
213
+ elif not x.endswith(media_files):
214
+ c_links.append(x)
215
+
216
+ # Clean links loader using WebBaseLoader
217
+ if prog is not None: prog(0.5, desc=f'Ingesting: {url}')
218
+ if c_links:
219
+ loader = WebBaseLoader(list(c_links))
220
+ documents.extend(loader.load())
221
+
222
+ # remote PDFs loader
223
+ for pdf_link in list(pdf_links):
224
+ loader = PyMuPDFLoader(pdf_link)
225
+ doc = loader.load()
226
+ for x in doc:
227
+ x.metadata['source'] = loader.source
228
+ documents.extend(doc)
229
+
230
+ return documents
231
+
232
+ def ingestFiles(documents, files_list, prog=None):
233
+ for fPath in files_list:
234
+ doc = None
235
+ if fPath.endswith('.pdf'):
236
+ doc = PyMuPDFLoader(fPath).load()
237
+ elif fPath.endswith('.txt') and not 'WhatsApp Chat with' in fPath:
238
+ doc = TextLoader(fPath).load()
239
+ elif fPath.endswith(('.doc', 'docx')):
240
+ doc = Docx2txtLoader(fPath).load()
241
+ elif 'WhatsApp Chat with' in fPath and fPath.endswith('.csv'): # Convert Whatsapp TXT files to CSV using https://whatstk.streamlit.app/
242
+ doc = WhatsAppChatLoader(fPath).load()
243
+ elif fPath.endswith(('.ppt', '.pptx')):
244
+ doc = UnstructuredPowerPointLoader(fPath).load()
245
+ else:
246
+ pass
247
+
248
+ if doc is not None and doc[0].page_content:
249
+ if prog is not None: prog(0.9, desc='Loaded file: '+fPath.rsplit('/')[0])
250
+ print('Loaded file:', fPath)
251
+ documents.extend(doc)
252
+ return documents
253
+
254
+
255
+ def data_ingestion(inputDir=None, file_list=[], url_list=[], gDriveFolder='', prog=None):
256
+ documents = []
257
+ # Ingestion from Google Drive Folder
258
+ if gDriveFolder:
259
+ opFolder = './gDriveDocs/'
260
+ gdown.download_folder(url=gDriveFolder, output=opFolder, quiet=True)
261
+ files = [str(x) for x in Path(opFolder).glob('**/*')]
262
+ documents = ingestFiles(documents, files, prog)
263
+ # Ingestion from Input Directory
264
+ if inputDir is not None:
265
+ files = [str(x) for x in Path(inputDir).glob('**/*')]
266
+ documents = ingestFiles(documents, files, prog)
267
+ if file_list:
268
+ documents = ingestFiles(documents, file_list, prog)
269
+ # Ingestion from URLs - also try https://python.langchain.com/docs/integrations/document_loaders/recursive_url_loader
270
+ if url_list:
271
+ for url in url_list:
272
+ documents = ingestURL(documents, url, prog=prog)
273
+
274
+ # Cleanup documents
275
+ for x in documents:
276
+ if 'WhatsApp Chat with' not in x.metadata['source']:
277
+ x.page_content = x.page_content.strip().replace('\n', ' ').replace('\\n', ' ').replace(' ', ' ')
278
+
279
+ # print(f"Total number of documents: {len(documents)}")
280
+ return documents
281
+
282
+
283
+ def split_docs(documents):
284
+ # Splitting and Chunks
285
+ 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.
286
+ docs = text_splitter.split_documents(documents)
287
+ return docs
288
+
289
+
290
+ def getSourcesFromMetadata(metadata, sourceOnly=True, sepFileUrl=True):
291
+ # metadata: list of metadata dict from all documents
292
+ setSrc = set()
293
+ for x in metadata:
294
+ metadataText = '' # we need to convert each metadata dict into a string format. This string will be added to a set
295
+ if x is not None:
296
+ # extract source first, and then extract all other items
297
+ source = x['source']
298
+ source = source.rsplit('/',1)[-1] if 'http' not in source else source
299
+ notSource = []
300
+ for k,v in x.items():
301
+ if v is not None and k!='source' and k in ['page']:
302
+ notSource.extend([f"{k}: {v}"])
303
+ metadataText = ', '.join([f'source: {source}'] + notSource) if sourceOnly==False else source
304
+ setSrc.add(metadataText)
305
+
306
+ if sepFileUrl:
307
+ 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))]))
308
+ 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))]))
309
+
310
+ src_files = 'Files:\n'+src_files if src_files else ''
311
+ src_urls = 'URLs:\n'+src_urls if src_urls else ''
312
+ newLineSep = '\n\n' if src_files and src_urls else ''
313
+
314
+ return src_files + newLineSep + src_urls , len(setSrc)
315
+ else:
316
+ src_docs = '\n'.join(([f"{i+1}) {x}" for i,x in enumerate(sorted(list(setSrc), key=str.casefold))]))
317
+ return src_docs, len(setSrc)
318
+
319
+ def getEmbeddingFunc(creds):
320
+ # OpenAI key used
321
+ if creds.get('service')=='openai':
322
+ embeddings = OpenAIEmbeddings(openai_api_key=creds.get('oai_key','Null'))
323
+ # WX key used
324
+ elif creds.get('service')=='watsonx' or creds.get('service')=='bam':
325
+ # testModel = Model(model_id=ModelTypes.FLAN_UL2, credentials=creds['credentials'], project_id=creds['project_id']) # test the API key
326
+ # del testModel
327
+ embeddings = SentenceTransformerEmbeddings(model_name="all-MiniLM-L6-v2") # for now use OpenSource model for embedding as WX doesnt have any embedding model
328
+ else:
329
+ raise Exception('Error: Invalid or None Credentials')
330
+ return embeddings
331
+
332
+ def getVsDict(embeddingFunc, docs, vsDict={}):
333
+ # create chroma client if doesnt exist
334
+ if vsDict.get('chromaClient') is None:
335
+ vsDict['chromaDir'] = './vecstore/'+str(uuid.uuid1())
336
+ vsDict['chromaClient'] = Chroma(embedding_function=embeddingFunc, persist_directory=vsDict['chromaDir'])
337
+ # clear chroma client before adding new docs
338
+ if vsDict['chromaClient']._collection.count()>0:
339
+ vsDict['chromaClient'].delete(vsDict['chromaClient'].get()['ids'])
340
+ # add new docs to chroma client
341
+ vsDict['chromaClient'].add_documents(docs)
342
+ print('vectorstore count:',vsDict['chromaClient']._collection.count(), 'at', datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
343
+ return vsDict
344
+
345
+ # used for Hardcoded documents only - not uploaded by user (userData_vecStore is separate function)
346
+ def localData_vecStore(embKey={}, inputDir=None, file_list=[], url_list=[], vsDict={}, gGrUrl=''):
347
+ documents = data_ingestion(inputDir, file_list, url_list, gGrUrl)
348
+ if not documents:
349
+ raise Exception('Error: No Documents Found')
350
+ docs = split_docs(documents)
351
+ # Embeddings
352
+ embeddings = getEmbeddingFunc(embKey)
353
+ # create chroma client if doesnt exist
354
+ vsDict_hd = getVsDict(embeddings, docs, vsDict)
355
+ # get sources from metadata
356
+ src_str = getSourcesFromMetadata(vsDict_hd['chromaClient'].get()['metadatas'])
357
+ src_str = str(src_str[1]) + ' source document(s) successfully loaded in vector store.'+'\n\n' + src_str[0]
358
+ print(src_str)
359
+ return vsDict_hd
360
+
361
+
362
+ def num_tokens_from_string(string, encoding_name = "cl100k_base"):
363
+ """Returns the number of tokens in a text string."""
364
+ encoding = tiktoken.get_encoding(encoding_name)
365
+ num_tokens = len(encoding.encode(string))
366
+ return num_tokens
367
+
368
+ def changeModel(oldModel, newModel):
369
+ if oldModel:
370
+ warning = 'Credentials not found for '+oldModel+'. Using default model '+newModel
371
+ gr.Warning(warning)
372
+ time.sleep(1)
373
+ return newModel
374
+
375
+ def getModelChoices(openAi_models, wml_models, bam_models):
376
+ return [model for model in openAi_models] + [model.value+' (watsonx)' for model in wml_models] + [model + ' (bam)' for model in bam_models]