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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import tempfile
|
3 |
+
from weaviate.client import Client
|
4 |
+
import weaviate
|
5 |
+
import time
|
6 |
+
import pandas as pd
|
7 |
+
from openpyxl import Workbook
|
8 |
+
from openpyxl.utils.dataframe import dataframe_to_rows
|
9 |
+
import tempfile
|
10 |
+
from sentence_transformers import SentenceTransformer
|
11 |
+
|
12 |
+
############################
|
13 |
+
### Variable Declaration ###
|
14 |
+
############################
|
15 |
+
|
16 |
+
# -- Global Variables
|
17 |
+
g_product_details={}
|
18 |
+
g_client=None
|
19 |
+
g_weaviate_url=""
|
20 |
+
g_ui_model_name=""
|
21 |
+
|
22 |
+
def update_global_variables(ui_action_dropdown, ui_model_name,ui_weaviate_url,ui_chatbot,ui_download_excel, ui_upload_excel):
|
23 |
+
global g_ui_model_name
|
24 |
+
global g_weaviate_url
|
25 |
+
|
26 |
+
# Reset values to defaults
|
27 |
+
g_ui_model_name=""
|
28 |
+
g_weaviate_url=""
|
29 |
+
ui_product_dropdown=gr.Dropdown.update(
|
30 |
+
interactive=False
|
31 |
+
)
|
32 |
+
ui_download_excel = gr.File.update(
|
33 |
+
visible=False,
|
34 |
+
interactive=False
|
35 |
+
)
|
36 |
+
ui_upload_excel = gr.UploadButton.update(
|
37 |
+
visible=False
|
38 |
+
)
|
39 |
+
ui_chatbot.clear()
|
40 |
+
|
41 |
+
# Loading global variables
|
42 |
+
ui_chatbot.append((None,"Loading Parameters, API Key & Weaviate URL"))
|
43 |
+
|
44 |
+
try:
|
45 |
+
# Validation for Model Details
|
46 |
+
if ui_model_name != "":
|
47 |
+
print('Setting g_ui_model_name - '+ui_model_name)
|
48 |
+
g_ui_model_name=ui_model_name
|
49 |
+
ui_chatbot.append((None,"Updated SBert Model"))
|
50 |
+
else:
|
51 |
+
print("exception in function - update_global_variables")
|
52 |
+
raise ValueError('Required Sbert Model Name')
|
53 |
+
|
54 |
+
# Validation for Weaviate URL
|
55 |
+
if ui_weaviate_url != "":
|
56 |
+
print('Setting g_weaviate_url - '+ui_weaviate_url)
|
57 |
+
g_weaviate_url=ui_weaviate_url
|
58 |
+
weaviate_client()
|
59 |
+
ui_chatbot.append((None,"Updated Weaviate URL"))
|
60 |
+
|
61 |
+
# Load Product Details
|
62 |
+
update_products_variable()
|
63 |
+
ui_product_dropdown = update_products_lov()
|
64 |
+
else:
|
65 |
+
print('Required Weaviate URL')
|
66 |
+
ui_chatbot.append((None,"<b style='color:red'>Required Weaviate URL</b>"))
|
67 |
+
|
68 |
+
# If Action = Query, Enable ui_download_excel
|
69 |
+
if ui_action_dropdown == "Query":
|
70 |
+
ui_upload_excel = gr.UploadButton.update(
|
71 |
+
visible=True,
|
72 |
+
interactive=True
|
73 |
+
)
|
74 |
+
|
75 |
+
except Exception as e:
|
76 |
+
print('Exception in loading parameters - '+str(e))
|
77 |
+
ui_chatbot.append((None,"<b style='color:red'>Exception "+str(e)+"</b>"))
|
78 |
+
raise ValueError(str(e))
|
79 |
+
finally:
|
80 |
+
return ui_chatbot,ui_product_dropdown,ui_download_excel, ui_upload_excel
|
81 |
+
|
82 |
+
############################
|
83 |
+
###### Generic Code #######
|
84 |
+
############################
|
85 |
+
|
86 |
+
# -- Generate Mapping HTML Table
|
87 |
+
def convert_mapping_data_to_html_table(table_data):
|
88 |
+
|
89 |
+
html_table = f"""
|
90 |
+
<table style="border-collapse: collapse; width: 100%;">
|
91 |
+
<tr>
|
92 |
+
<th style="border: 1px solid black; text-align: center; padding: 8px;">Input</th>
|
93 |
+
<th style="border: 1px solid black; text-align: center; padding: 8px;">Key</th>
|
94 |
+
<th style="border: 1px solid black; text-align: center; padding: 8px;">Description</th>
|
95 |
+
<th style="border: 1px solid black; text-align: center; padding: 8px;">Certainty</th>
|
96 |
+
</tr>
|
97 |
+
<tr>
|
98 |
+
<td style="border: 1px solid black; text-align: center; padding: 8px;">{table_data['input']}</td>
|
99 |
+
<td style="border: 1px solid black; text-align: center; padding: 8px;">{table_data['key']}</td>
|
100 |
+
<td style="border: 1px solid black; text-align: center; padding: 8px;">{table_data['description']}</td>
|
101 |
+
<td style="border: 1px solid black; text-align: center; padding: 8px;">{table_data['certainty']}</td>
|
102 |
+
</tr>
|
103 |
+
</table><br><br>
|
104 |
+
"""
|
105 |
+
|
106 |
+
return html_table
|
107 |
+
|
108 |
+
# -- Generate Object Search HTML Table
|
109 |
+
def convert_object_id_data_to_html_table(table_data_items):
|
110 |
+
|
111 |
+
html_table=""
|
112 |
+
for table_data in table_data_items:
|
113 |
+
html_table += f"""
|
114 |
+
<table style="border-collapse: collapse; width: 100%;">
|
115 |
+
<tr>
|
116 |
+
<th style="border: 1px solid black; text-align: center; padding: 8px;">Object ID</th>
|
117 |
+
<th style="border: 1px solid black; text-align: center; padding: 8px;">Key</th>
|
118 |
+
<th style="border: 1px solid black; text-align: center; padding: 8px;">Description</th>
|
119 |
+
</tr>
|
120 |
+
<tr>
|
121 |
+
<td style="border: 1px solid black; text-align: center; padding: 8px;">{table_data['id']}</td>
|
122 |
+
<td style="border: 1px solid black; text-align: center; padding: 8px;">{table_data['key']}</td>
|
123 |
+
<td style="border: 1px solid black; text-align: center; padding: 8px;">{table_data['description']}</td>
|
124 |
+
</tr>
|
125 |
+
</table><br>
|
126 |
+
"""
|
127 |
+
|
128 |
+
# print(html_table)
|
129 |
+
return html_table
|
130 |
+
|
131 |
+
# -- Create Weaviate Connection
|
132 |
+
def weaviate_client():
|
133 |
+
global g_client
|
134 |
+
global g_weaviate_url
|
135 |
+
|
136 |
+
try:
|
137 |
+
g_client = Client(url=g_weaviate_url, timeout_config=(3.05, 9.1))
|
138 |
+
print("Weaviate client connected successfully!")
|
139 |
+
except Exception as e:
|
140 |
+
print("Failed to connect to the Weaviate instance."+str(e))
|
141 |
+
raise ValueError('Failed to connect to the Weaviate instance.')
|
142 |
+
|
143 |
+
# -- Convert input to CamelCase
|
144 |
+
def convert_to_camel_case(string):
|
145 |
+
words = string.split('_')
|
146 |
+
camel_case_words = [word.capitalize() for word in words]
|
147 |
+
return ''.join(camel_case_words)
|
148 |
+
|
149 |
+
# -- Create Sbert Embedding
|
150 |
+
def creating_embeddings(sentences):
|
151 |
+
global g_ui_model_name
|
152 |
+
# print("Creating embedding for text"+ sentences)
|
153 |
+
|
154 |
+
# Create OpenAI embeddings
|
155 |
+
model = SentenceTransformer(g_ui_model_name)
|
156 |
+
embeddings = model.encode(sentences)
|
157 |
+
|
158 |
+
# for sentence, embedding in zip(sentences, embeddings):
|
159 |
+
# print(embedding) # numpy.ndarray
|
160 |
+
# print(embeddings.shape)
|
161 |
+
|
162 |
+
return embeddings
|
163 |
+
|
164 |
+
############################
|
165 |
+
## Update Product Details ##
|
166 |
+
############################
|
167 |
+
|
168 |
+
# -- Update Product LOV
|
169 |
+
def update_products_lov():
|
170 |
+
global g_product_details
|
171 |
+
|
172 |
+
print("started function - update_products_lov")
|
173 |
+
product_details = [d["name"] for d in g_product_details]
|
174 |
+
ui_product_dropdown = gr.Dropdown.update(
|
175 |
+
choices=product_details,
|
176 |
+
value=product_details[0],
|
177 |
+
interactive=True
|
178 |
+
)
|
179 |
+
print("completed function - update_products_lov")
|
180 |
+
|
181 |
+
return ui_product_dropdown
|
182 |
+
|
183 |
+
# -- Get Product global variable
|
184 |
+
def update_products_variable():
|
185 |
+
global g_client
|
186 |
+
global g_product_details
|
187 |
+
|
188 |
+
print("started function - update_products_variable")
|
189 |
+
|
190 |
+
try:
|
191 |
+
api_response = g_client.query.get("Product", ["name","description"]).do()
|
192 |
+
print("Product API Response")
|
193 |
+
print(api_response)
|
194 |
+
g_product_details = api_response['data']['Get']['Product']
|
195 |
+
product_details = [d["name"] for d in g_product_details]
|
196 |
+
print("Product API Response")
|
197 |
+
print(product_details)
|
198 |
+
except Exception as e:
|
199 |
+
print("Error getting Product Details")
|
200 |
+
finally:
|
201 |
+
print("completed function - update_products_variable")
|
202 |
+
|
203 |
+
############################
|
204 |
+
#### Search User Manual ####
|
205 |
+
############################
|
206 |
+
|
207 |
+
def search_um(ui_search_text, ui_product_dropdown):
|
208 |
+
global g_client
|
209 |
+
|
210 |
+
um_data = "No results from User Manual"
|
211 |
+
|
212 |
+
print("started function - search_um")
|
213 |
+
print("Product Selected -->"+ui_product_dropdown)
|
214 |
+
|
215 |
+
try:
|
216 |
+
|
217 |
+
if ui_product_dropdown:
|
218 |
+
input_embedding=creating_embeddings(ui_search_text)
|
219 |
+
vector = {"vector": input_embedding}
|
220 |
+
|
221 |
+
response = g_client \
|
222 |
+
.query.get(convert_to_camel_case(ui_product_dropdown+"_um"), ["content", "_additional {certainty}"]) \
|
223 |
+
.with_near_vector(vector) \
|
224 |
+
.with_limit(1) \
|
225 |
+
.do()
|
226 |
+
|
227 |
+
# print(result)
|
228 |
+
if response:
|
229 |
+
result = response['data']['Get'][convert_to_camel_case(ui_product_dropdown+"_um")][0]['content']
|
230 |
+
result_value = result.split('\nResult : ')[0]
|
231 |
+
um_data = result_value
|
232 |
+
else:
|
233 |
+
um_data = "Please select product name to proceed"
|
234 |
+
|
235 |
+
return um_data
|
236 |
+
|
237 |
+
except Exception as e:
|
238 |
+
raise ValueError(str(e))
|
239 |
+
finally:
|
240 |
+
print("completed function - search_um")
|
241 |
+
|
242 |
+
############################
|
243 |
+
#### Search Mapping Data ###
|
244 |
+
############################
|
245 |
+
|
246 |
+
def search_mapping_data(ui_search_text, ui_product_dropdown):
|
247 |
+
global g_client
|
248 |
+
|
249 |
+
print("started function - search_mapping_data")
|
250 |
+
print("Product Selected -->"+ui_product_dropdown)
|
251 |
+
try:
|
252 |
+
print("Performing Semantic Search")
|
253 |
+
if ui_product_dropdown:
|
254 |
+
input_embedding=creating_embeddings(ui_search_text)
|
255 |
+
|
256 |
+
where_product_name = convert_to_camel_case(ui_product_dropdown+"_mapping")
|
257 |
+
vector = {"vector": input_embedding}
|
258 |
+
response = g_client \
|
259 |
+
.query.get(where_product_name, ["key","description", "_additional {certainty}"]) \
|
260 |
+
.with_near_vector(vector) \
|
261 |
+
.with_limit(1) \
|
262 |
+
.do()
|
263 |
+
|
264 |
+
# print(result)
|
265 |
+
if response:
|
266 |
+
mapping = response['data']['Get'].get(convert_to_camel_case(ui_product_dropdown+"_mapping"))
|
267 |
+
if mapping:
|
268 |
+
for item in mapping:
|
269 |
+
key = item['key']
|
270 |
+
description = item['description']
|
271 |
+
certainty = item['_additional']['certainty']
|
272 |
+
|
273 |
+
print("Key:", key)
|
274 |
+
print("Description:", description)
|
275 |
+
print("Certainty:", certainty)
|
276 |
+
|
277 |
+
return {
|
278 |
+
'input': ui_search_text,
|
279 |
+
'key':key,
|
280 |
+
'description': description,
|
281 |
+
'certainty': certainty
|
282 |
+
}
|
283 |
+
else:
|
284 |
+
print("Mapping has no data.")
|
285 |
+
return {
|
286 |
+
'input': ui_search_text,
|
287 |
+
'key': None,
|
288 |
+
'description': None,
|
289 |
+
'certainty': None
|
290 |
+
}
|
291 |
+
|
292 |
+
except Exception as e:
|
293 |
+
raise ValueError(str(e))
|
294 |
+
finally:
|
295 |
+
print("completed function - search_mapping_data")
|
296 |
+
|
297 |
+
def search_and_get_object_id_by_key(ui_search_text, ui_product_dropdown):
|
298 |
+
global g_client
|
299 |
+
items=[]
|
300 |
+
|
301 |
+
print("started function - search_and_get_object_id_by_key")
|
302 |
+
print("Product Selected -->"+ui_product_dropdown)
|
303 |
+
|
304 |
+
try:
|
305 |
+
print("Performing Normal Search")
|
306 |
+
if ui_product_dropdown:
|
307 |
+
|
308 |
+
product_name = convert_to_camel_case(ui_product_dropdown+"_mapping")
|
309 |
+
where_filter = {
|
310 |
+
"path": ["key"],
|
311 |
+
"operator": "Equal",
|
312 |
+
"valueString": ui_search_text
|
313 |
+
}
|
314 |
+
response = (
|
315 |
+
g_client.query
|
316 |
+
.get(product_name, ["key","description"])
|
317 |
+
.with_where(where_filter)
|
318 |
+
.with_limit(5)
|
319 |
+
.with_additional(["id"])
|
320 |
+
.do()
|
321 |
+
)
|
322 |
+
print(response)
|
323 |
+
|
324 |
+
if response:
|
325 |
+
mapping = response['data']['Get'].get(product_name)
|
326 |
+
if mapping:
|
327 |
+
for item in mapping:
|
328 |
+
id = item['_additional']['id']
|
329 |
+
key = item['key']
|
330 |
+
description = item['description']
|
331 |
+
|
332 |
+
print("Id:", id)
|
333 |
+
print("Key:", key)
|
334 |
+
print("Description:", description)
|
335 |
+
item = {
|
336 |
+
'input': ui_search_text,
|
337 |
+
'id': id,
|
338 |
+
'key':key,
|
339 |
+
'description': description
|
340 |
+
}
|
341 |
+
items.append(item)
|
342 |
+
print("Added Item")
|
343 |
+
else:
|
344 |
+
print("Mapping has no data.")
|
345 |
+
item= {
|
346 |
+
'input': ui_search_text,
|
347 |
+
'id': None,
|
348 |
+
'key': None,
|
349 |
+
'description': None
|
350 |
+
}
|
351 |
+
items.append(item)
|
352 |
+
|
353 |
+
except Exception as e:
|
354 |
+
print("Error - "+str(e))
|
355 |
+
raise ValueError(str(e))
|
356 |
+
finally:
|
357 |
+
print("completed function - search_and_get_object_id_by_key")
|
358 |
+
return items
|
359 |
+
|
360 |
+
############################
|
361 |
+
#### Update Mapping Data ###
|
362 |
+
############################
|
363 |
+
|
364 |
+
def update_mapping_by_object_id(ui_search_text, ui_product_dropdown):
|
365 |
+
global g_client
|
366 |
+
|
367 |
+
print("started function - update_mapping_by_object_id")
|
368 |
+
|
369 |
+
try:
|
370 |
+
object_id, description = ui_search_text.split(", ")
|
371 |
+
embedding = creating_embeddings(description)
|
372 |
+
product_name = convert_to_camel_case(ui_product_dropdown+"_mapping")
|
373 |
+
|
374 |
+
data_object = {
|
375 |
+
"description": description
|
376 |
+
}
|
377 |
+
g_client \
|
378 |
+
.data_object \
|
379 |
+
.update(
|
380 |
+
data_object,
|
381 |
+
class_name=product_name,
|
382 |
+
uuid=object_id,
|
383 |
+
consistency_level=weaviate.data.replication.ConsistencyLevel.ALL,
|
384 |
+
vector=embedding
|
385 |
+
)
|
386 |
+
|
387 |
+
except Exception as e:
|
388 |
+
print("Update Error - "+str(e))
|
389 |
+
raise ValueError(str(e))
|
390 |
+
finally:
|
391 |
+
print("completed function - update_mapping_by_object_id")
|
392 |
+
|
393 |
+
############################
|
394 |
+
#### Delete Mapping Data ###
|
395 |
+
############################
|
396 |
+
|
397 |
+
def delete_mapping_by_object_id(ui_search_text, ui_product_dropdown):
|
398 |
+
global g_client
|
399 |
+
|
400 |
+
print("completed function - delete_mapping_by_object_id")
|
401 |
+
|
402 |
+
try:
|
403 |
+
product_name = convert_to_camel_case(ui_product_dropdown+"_mapping")
|
404 |
+
g_client. \
|
405 |
+
data_object.delete(
|
406 |
+
ui_search_text,
|
407 |
+
class_name=product_name,
|
408 |
+
consistency_level=weaviate.data.replication.ConsistencyLevel.ALL
|
409 |
+
)
|
410 |
+
except Exception as e:
|
411 |
+
print("Delete Error - "+str(e))
|
412 |
+
raise ValueError(str(e))
|
413 |
+
finally:
|
414 |
+
print("completed function - delete_mapping_by_object_id")
|
415 |
+
|
416 |
+
############################
|
417 |
+
##### Search User Input ####
|
418 |
+
############################
|
419 |
+
|
420 |
+
def text_search(ui_action_dropdown, ui_product_dropdown, ui_search_text, ui_chatbot):
|
421 |
+
|
422 |
+
print("started function - text_search")
|
423 |
+
try:
|
424 |
+
if ui_action_dropdown == 'Query':
|
425 |
+
print("Starting to Query")
|
426 |
+
ui_chatbot.append(("Searching: "+ ui_search_text,None))
|
427 |
+
um_search_results = search_um(ui_search_text, ui_product_dropdown)
|
428 |
+
mapping_search_results = search_mapping_data(ui_search_text, ui_product_dropdown)
|
429 |
+
|
430 |
+
ui_chatbot.append((None,"<b style='color:green'>Mapping Results: </b><br>"+convert_mapping_data_to_html_table(mapping_search_results)+"<b style='color:green'>User Manual Search Results: </b><br>"+um_search_results))
|
431 |
+
elif ui_action_dropdown == 'Get Object ID':
|
432 |
+
print("Starting to Query Object ID")
|
433 |
+
ui_chatbot.append(("Searching Object ID: "+ ui_search_text,None))
|
434 |
+
search_results = search_and_get_object_id_by_key(ui_search_text, ui_product_dropdown)
|
435 |
+
ui_chatbot.append((None,"<b style='color:green'>Object ID Results: </b><br>"+convert_object_id_data_to_html_table(search_results)))
|
436 |
+
elif ui_action_dropdown == 'Update':
|
437 |
+
print("Starting to Update")
|
438 |
+
ui_chatbot.append(("Updating: "+ ui_search_text,None))
|
439 |
+
update_mapping_by_object_id(ui_search_text, ui_product_dropdown)
|
440 |
+
elif ui_action_dropdown == 'Delete':
|
441 |
+
print("Starting to Delete")
|
442 |
+
ui_chatbot.append(("Deleting: "+ ui_search_text,None))
|
443 |
+
delete_mapping_by_object_id(ui_search_text, ui_product_dropdown)
|
444 |
+
except Exception as e:
|
445 |
+
print('Exception '+str(e))
|
446 |
+
ui_chatbot.append((None,"<b style='color:red'>Exception "+str(e)+"</b>"))
|
447 |
+
finally:
|
448 |
+
print("completed function - text_search")
|
449 |
+
return ui_chatbot
|
450 |
+
|
451 |
+
############################
|
452 |
+
##### Upload User Input ####
|
453 |
+
############################
|
454 |
+
|
455 |
+
def excel_file_search(ui_product_dropdown, ui_excel_upload, ui_chatbot):
|
456 |
+
print("started function - excel_file_search")
|
457 |
+
|
458 |
+
# Create an empty list to store the items
|
459 |
+
items=[]
|
460 |
+
output_file_path=""
|
461 |
+
|
462 |
+
try:
|
463 |
+
file_path = ui_excel_upload.name
|
464 |
+
print("Uploaded xlsx location - "+file_path)
|
465 |
+
|
466 |
+
# Read the Excel file
|
467 |
+
xls = pd.ExcelFile(file_path)
|
468 |
+
|
469 |
+
# Iterate over each sheet in the Excel file
|
470 |
+
for sheet_name in xls.sheet_names:
|
471 |
+
|
472 |
+
# Read the sheet into a DataFrame
|
473 |
+
df = pd.read_excel(xls, sheet_name=sheet_name)
|
474 |
+
|
475 |
+
# Iterate over each input value in the 'Input' column
|
476 |
+
for input_value in df['Input']:
|
477 |
+
# Create mapping search for each input
|
478 |
+
mapping_search_results = search_mapping_data(input_value, ui_product_dropdown)
|
479 |
+
|
480 |
+
# Create a dictionary item for the sheet
|
481 |
+
item = {
|
482 |
+
'sheet': sheet_name,
|
483 |
+
'input': input_value,
|
484 |
+
'key': mapping_search_results['key'],
|
485 |
+
'description': mapping_search_results['description'],
|
486 |
+
'certainty': mapping_search_results['certainty']
|
487 |
+
}
|
488 |
+
|
489 |
+
print('key: ' + item['key'])
|
490 |
+
print('sheet: ' + item['sheet'])
|
491 |
+
print('input: ' + item['input'])
|
492 |
+
print('description: ' + item['description'])
|
493 |
+
print('certainty: ' + str(item['certainty']))
|
494 |
+
|
495 |
+
# Append the item to the list
|
496 |
+
items.append(item)
|
497 |
+
|
498 |
+
# Creating xlsx file
|
499 |
+
with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.xlsx', newline='\n') as temp_file:
|
500 |
+
# Create a Pandas DataFrame from the items list
|
501 |
+
df_items = pd.DataFrame(items)
|
502 |
+
|
503 |
+
# Create a new Workbook object
|
504 |
+
workbook = Workbook()
|
505 |
+
|
506 |
+
# Iterate over each sheet in the DataFrame
|
507 |
+
for sheet_name in df_items['sheet'].unique():
|
508 |
+
# Filter the DataFrame for the current sheet
|
509 |
+
df_sheet = df_items[df_items['sheet'] == sheet_name]
|
510 |
+
|
511 |
+
# Select only the 'key', 'description', and 'certainty' columns
|
512 |
+
df_sheet = df_sheet[['input','key', 'description', 'certainty']]
|
513 |
+
|
514 |
+
# Create a new sheet in the workbook
|
515 |
+
sheet = workbook.create_sheet(title=sheet_name)
|
516 |
+
|
517 |
+
# Write the DataFrame to the sheet
|
518 |
+
for row in dataframe_to_rows(df_sheet, index=False, header=True):
|
519 |
+
sheet.append(row)
|
520 |
+
|
521 |
+
# Remove the default sheet created by openpyxl
|
522 |
+
del workbook["Sheet"]
|
523 |
+
|
524 |
+
# Save the Excel file
|
525 |
+
workbook.save(temp_file.name)
|
526 |
+
|
527 |
+
print("File Processing Completed - "+str(temp_file.name))
|
528 |
+
output_file_path=gr.File.update( visible=True,
|
529 |
+
value=str(temp_file.name),
|
530 |
+
interactive=True
|
531 |
+
)
|
532 |
+
ui_chatbot.append((None, "File Processing Completed - "+str(temp_file.name)))
|
533 |
+
|
534 |
+
except Exception as e:
|
535 |
+
print('Exception '+str(e))
|
536 |
+
ui_chatbot.append((None,"<b style='color:red'>Exception "+str(e)+"</b>"))
|
537 |
+
finally:
|
538 |
+
print("completed function - excel_file_search")
|
539 |
+
return ui_chatbot, output_file_path
|
540 |
+
|
541 |
+
############################
|
542 |
+
####### Main Program #######
|
543 |
+
############################
|
544 |
+
|
545 |
+
# -- Start of Program - Main
|
546 |
+
def main():
|
547 |
+
print("\nStarted Knowledge Base Chat Application")
|
548 |
+
|
549 |
+
with gr.Blocks() as demo:
|
550 |
+
with gr.Accordion("Settings"):
|
551 |
+
ui_model_name=gr.Textbox(placeholder="Semantic Search Model, https://www.sbert.net/docs/pretrained_models.html#semantic-search",label="Semantic Search Model")
|
552 |
+
ui_weaviate_url=gr.Textbox(placeholder="Weaviate URL, https://weaviate.xxx",label="Weaviate URL", type="password")
|
553 |
+
|
554 |
+
ui_chatbot = gr.Chatbot([], elem_id="chatbot").style(height=450)
|
555 |
+
|
556 |
+
with gr.Row():
|
557 |
+
with gr.Column(scale=0.2, min_width=0):
|
558 |
+
ui_action_dropdown = gr.Dropdown(
|
559 |
+
["Query","Update","Delete","Get Object ID"],
|
560 |
+
label="Action Type"
|
561 |
+
)
|
562 |
+
with gr.Column(scale=0.2, min_width=0):
|
563 |
+
ui_product_dropdown = gr.Dropdown(
|
564 |
+
[],
|
565 |
+
interactive=False,
|
566 |
+
label="Select Product"
|
567 |
+
)
|
568 |
+
with gr.Column(scale=0.6):
|
569 |
+
ui_search_text = gr.Textbox(
|
570 |
+
show_label=False,
|
571 |
+
# lines=3.2,
|
572 |
+
placeholder="Message me, I am your migration assistance",
|
573 |
+
)
|
574 |
+
|
575 |
+
ui_upload_excel = gr.UploadButton("Upload Mapping File", file_types=["*.xlsx"])
|
576 |
+
ui_download_excel = gr.File(label="Download Recommendations", interactive=False, visible=False)
|
577 |
+
|
578 |
+
# Loading global variables
|
579 |
+
ui_action_dropdown.change(
|
580 |
+
fn=update_global_variables,
|
581 |
+
inputs=[ui_action_dropdown, ui_model_name,ui_weaviate_url,ui_chatbot,ui_download_excel, ui_upload_excel],
|
582 |
+
outputs=[ui_chatbot,ui_product_dropdown,ui_download_excel, ui_upload_excel]
|
583 |
+
)
|
584 |
+
|
585 |
+
try:
|
586 |
+
# Search Text
|
587 |
+
ui_search_text.submit(fn=text_search,
|
588 |
+
inputs=[ui_action_dropdown, ui_product_dropdown, ui_search_text, ui_chatbot],
|
589 |
+
outputs=[ui_chatbot]
|
590 |
+
)
|
591 |
+
except Exception as e:
|
592 |
+
ui_chatbot.append((None,"<b style='color:red'>Exception Searching "+str(e)+"</b>"))
|
593 |
+
|
594 |
+
try:
|
595 |
+
# Upload Mapping
|
596 |
+
ui_upload_excel.upload(fn=excel_file_search,
|
597 |
+
inputs=[ui_product_dropdown, ui_upload_excel, ui_chatbot],
|
598 |
+
outputs=[ui_chatbot,ui_download_excel]
|
599 |
+
)
|
600 |
+
except Exception as e:
|
601 |
+
ui_chatbot.append((None,"<b style='color:red'>Exception Searching Excel "+str(e)+"</b>"))
|
602 |
+
|
603 |
+
demo.launch(server_name="0.0.0.0",server_port=8080)
|
604 |
+
|
605 |
+
# -- Calling Main Function
|
606 |
+
if __name__ == '__main__':
|
607 |
+
main()
|