Ocillus commited on
Commit
7185edf
·
verified ·
1 Parent(s): 423585c

Update ArcanaUI2.py

Browse files
Files changed (1) hide show
  1. ArcanaUI2.py +188 -39
ArcanaUI2.py CHANGED
@@ -9,6 +9,20 @@ import Arcana
9
  from nylon import *
10
  import pandas as pd
11
  import json
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
  # SSL configuration to avoid verification issues
14
  try:
@@ -19,23 +33,62 @@ else:
19
  ssl._create_default_https_context = _create_unverified_https_context
20
 
21
  def query_database2(query):
22
- db = ChatDatabase('memory.txt')
23
-
24
- sender = 'Arcana'
25
- N = 10
26
- cache = {}
27
- query_tag = None
28
-
29
- relevant_messages = db.get_relevant_messages(sender, query, N, cache, query_tag)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
- print("Relevant messages:")
32
- for message in relevant_messages:
33
- print(f"Sender: {message[0]}, Time: {message[1]}, Tag: {message[3]}")
34
- print(f"Message: {message[2][:100]}...")
35
- print()
36
 
37
- df_data = [str(message) for message in relevant_messages]
38
- return ';'.join(df_data)
39
 
40
  # OpenAI client setup
41
  client = OpenAI(
@@ -46,7 +99,7 @@ client = OpenAI(
46
  # Function list for OpenAI API
47
  function_list = [
48
  {
49
- "name": "query_database",
50
  "description": "Query the database and return a list of results as strings",
51
  "parameters": {
52
  "type": "object",
@@ -58,12 +111,27 @@ function_list = [
58
  },
59
  "required": ["query"]
60
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  }
62
  ]
63
 
64
  # Mapping of function names to actual function objects
65
  function_map = {
66
- "query_database": query_database2
 
67
  }
68
 
69
  def execute_function(function_name, function_args):
@@ -72,12 +140,19 @@ def execute_function(function_name, function_args):
72
  else:
73
  return f"Error: Function {function_name} not found"
74
 
75
- # Retry logic for OpenAI API call
 
76
  def openai_api_call(messages, retries=3, delay=5):
 
 
77
  for attempt in range(retries):
78
  try:
 
 
 
 
79
  completion = client.chat.completions.create(
80
- model="gpt-3.5-turbo", # Changed from "gpt-4o" to "gpt-4"
81
  messages=messages,
82
  functions=function_list,
83
  function_call='auto',
@@ -109,10 +184,43 @@ def openai_api_call(messages, retries=3, delay=5):
109
  else:
110
  return "Sorry, I am having trouble connecting to the server. Please try again later."
111
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
  # Chatbot response function
113
  def chatbot_response(message, history):
114
  messages = [{"role": "system", "content": '''You are Arcana, a dynamic study resource database designed to help students excel in their exams. Your responses should be accurate, informative, and evidence-based whenever possible. Follow these guidelines:
115
- Your primary goal is to provide students with the most helpful and accurate study information, utilizing both your internal knowledge and the PDF resources at your disposal.'''}]
116
 
117
  for human, assistant in history:
118
  messages.append({"role": "user", "content": human})
@@ -130,7 +238,7 @@ from concurrent.futures import ThreadPoolExecutor
130
  # Function to handle the file upload
131
  def handle_file_upload(file):
132
  # Ensure the cache2 directory exists
133
- cache_dir = 'cache'
134
  os.makedirs(cache_dir, exist_ok=True)
135
 
136
  # Get the uploaded file path
@@ -154,7 +262,7 @@ def handle_file_upload_threaded(file):
154
  return future.result()
155
 
156
  def list_uploaded_files():
157
- foldername = 'cache'
158
  if not os.path.exists(foldername):
159
  return []
160
  files = os.listdir(foldername)
@@ -167,7 +275,7 @@ def on_select(evt: gr.SelectData):
167
  selected = selected_value
168
  print(f"Selected value: {selected_value} at index: {selected_index}")
169
 
170
- file_path = os.path.join("cache", selected_value) if selected_value else None
171
  status_message = f"Selected: {selected_value}" if selected_value else "No file selected"
172
 
173
  file_size = get_file_size(file_path) if file_path else ""
@@ -193,9 +301,8 @@ def get_file_creation_time(file_path):
193
  return ""
194
 
195
  def delete_file():
196
- global selected
197
  if selected:
198
- foldername = 'cache'
199
  file_path = os.path.join(foldername, selected)
200
  if os.path.exists(file_path):
201
  os.remove(file_path)
@@ -209,12 +316,12 @@ def refresh_files():
209
  return list_uploaded_files()
210
 
211
  def display_file(evt: gr.SelectData, df):
212
- file_path = os.path.join("cache", evt.value)
213
  return file_path, file_path if file_path.lower().endswith(('.png', '.jpg', '.jpeg', '.gif')) else None, f"Displaying: {evt.value}"
214
 
215
  def render_to_database():
216
  # This function is undefined as per your request
217
- Arcana.main()
218
 
219
  def change_theme(theme):
220
  gr.Interface.theme = theme
@@ -222,8 +329,8 @@ def change_theme(theme):
222
  def rename_file(new_name):
223
  global selected
224
  if selected and new_name:
225
- old_path = os.path.join('cache', selected)
226
- new_path = os.path.join('cache', new_name+'.'+selected.split('.')[-1])
227
  if os.path.exists(old_path):
228
  os.rename(old_path, new_path)
229
  selected = new_name
@@ -234,7 +341,7 @@ def rename_file(new_name):
234
 
235
  def query_database(query):
236
  # Usage example
237
- db = ChatDatabase('memory.txt')
238
 
239
  # Example 1: Get relevant messages
240
  sender = 'Arcana'
@@ -257,6 +364,27 @@ def query_database(query):
257
 
258
  return df
259
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
260
 
261
  example_database = [
262
  "What is Hydrogen Bonding?",
@@ -284,17 +412,20 @@ def get_random_examples(num_examples=5):
284
  chatbot_interface = gr.ChatInterface(
285
  chatbot_response,
286
  chatbot=gr.Chatbot(height=400),
287
- textbox=gr.Textbox(placeholder="Type your message here...", container=True, scale=10),
288
  title="Review With Arcana",
289
  description="ArcanaUI v0.8 - Chatbot",
290
- theme="soft",
291
  examples=get_random_examples(),
292
  cache_examples=False,
293
- retry_btn=None,
294
  undo_btn="Delete Previous",
295
- clear_btn="Clear"
296
  )
297
 
 
 
 
298
 
299
  def relaunch():
300
  global demo
@@ -324,7 +455,7 @@ async () => {
324
 
325
  with gr.TabItem("Chatbot"):
326
  chatbot_interface.render()
327
-
328
  # File uploading interface
329
  with gr.TabItem('Upload'):
330
  gr.Markdown('# Upload and View Files')
@@ -380,10 +511,22 @@ async () => {
380
 
381
  test_nylon = gr.Textbox(label='Test Nylon', placeholder='Query')
382
  uploaded_files_list2 = gr.DataFrame(headers=["Nylon Returned Query"], datatype="str", interactive=False)
383
-
384
- query_button = gr.Button('Query')
385
-
386
- query_button.click(fn=query_database, inputs=test_nylon, outputs=uploaded_files_list2)
 
 
 
 
 
 
 
 
 
 
 
 
387
  with gr.TabItem('Theme'):
388
  gr.Markdown('Change Theme')
389
 
@@ -393,7 +536,13 @@ async () => {
393
  theme_button.click(fn=change_theme, inputs=theme_dropdown)
394
  relaunch_button = gr.Button('Relaunch')
395
  relaunch_button.click(fn=relaunch)
 
 
396
 
 
 
 
 
397
 
398
  # Launch the interface
399
  demo.launch(share=True)
 
9
  from nylon import *
10
  import pandas as pd
11
  import json
12
+ import fiber
13
+ import cite_source
14
+
15
+ foldername = 'Celsiaaa'
16
+ dbmsmode = 'Fiber'
17
+
18
+ try:
19
+ with open('settings.arcana',mode='r') as file:
20
+ foldername,dbmsmode = file.read().split('\n')
21
+ except Exception as e:
22
+ print(e)
23
+ with open('settings.arcana',mode='w') as file:
24
+ newsettings = foldername+'\n'+dbmsmode
25
+ file.write(newsettings)
26
 
27
  # SSL configuration to avoid verification issues
28
  try:
 
33
  ssl._create_default_https_context = _create_unverified_https_context
34
 
35
  def query_database2(query):
36
+ print(dbmsmode)
37
+ if dbmsmode == 'Nylon':
38
+ db = ChatDatabase(foldername+'.txt')
39
+
40
+ sender = 'Arcana'
41
+ N = 10
42
+ cache = {}
43
+ query_tag = None
44
+
45
+ relevant_messages = db.get_relevant_messages(sender, query, N, cache, query_tag)
46
+
47
+ print("Relevant messages:")
48
+ for message in relevant_messages:
49
+ print(f"Sender: {message[0]}, Time: {message[1]}, Tag: {message[3]}")
50
+ print(f"Message: {message[2][:100]}...")
51
+ print()
52
+
53
+ df_data = [str(message) for message in relevant_messages]
54
+ return ';'.join(df_data)
55
+ elif dbmsmode == 'Fiber':
56
+ dbms = fiber.FiberDBMS()
57
+ # Load or create the database
58
+ dbms.load_or_create(foldername+'.txt')
59
+ results = dbms.query(query, 3)
60
+
61
+ # Convert each result dictionary to a string
62
+ result_strings = []
63
+ for result in results:
64
+ result_str = f"Name: {result['name']}\nContent: {result['content']}\nTags: {result['tags']}\nIndex: {result['index']}"
65
+ result_strings.append(result_str)
66
+
67
+ # Join all result strings with a separator
68
+ return ';'.join(result_strings)
69
+
70
+ def cite(style=None,author=None,title=None,publisher=None,year=None,url=None,date_accessed=None):
71
+ return cite_source.generate_citation(style=style,author=author,title=title,publisher=publisher,year=year,url=url,access_date=date_accessed)
72
+
73
+
74
+ def list_files_indb(directory=foldername):
75
+ """
76
+ List all files in the given directory, separated by semicolons.
77
+
78
+ :param directory: The directory to list files from. Defaults to the current directory.
79
+ :return: A string of filenames separated by semicolons.
80
+ """
81
+ try:
82
+ # Get all files in the directory
83
+ files = [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))]
84
+
85
+ # Join the filenames with semicolons
86
+ return ';'.join(files)
87
+ except Exception as e:
88
+ return f"An error occurred: {str(e)}"
89
 
90
+ search_mode = 0#Always Search
 
 
 
 
91
 
 
 
92
 
93
  # OpenAI client setup
94
  client = OpenAI(
 
99
  # Function list for OpenAI API
100
  function_list = [
101
  {
102
+ "name": "search_database",
103
  "description": "Query the database and return a list of results as strings",
104
  "parameters": {
105
  "type": "object",
 
111
  },
112
  "required": ["query"]
113
  }
114
+ },
115
+
116
+ {
117
+ "name": "list_database_files",
118
+ "description": "Check what files are present in the database",
119
+ "parameters":{
120
+ "type":"object",
121
+ "properties":{
122
+ "query":{
123
+ "type":"string",
124
+ "description":"Gives a list of semicolon seperated file names in the database"
125
+ },
126
+ },
127
+ }
128
  }
129
  ]
130
 
131
  # Mapping of function names to actual function objects
132
  function_map = {
133
+ "search_database": query_database2,
134
+ "list_database_files":list_files_indb
135
  }
136
 
137
  def execute_function(function_name, function_args):
 
140
  else:
141
  return f"Error: Function {function_name} not found"
142
 
143
+ mapsearchmode = ['always', 'auto', 'none']
144
+
145
  def openai_api_call(messages, retries=3, delay=5):
146
+ global search_mode # Declare search_mode as a global variable
147
+
148
  for attempt in range(retries):
149
  try:
150
+ # Modify the user's message if search_mode is 0
151
+ if search_mode == 0:
152
+ messages[-1]['content'] = "[System: SEARCH when the user ASKED A QUESTION & remember to CITE(the source is the first tag). Otherwise do not search];" + messages[-1]['content']
153
+
154
  completion = client.chat.completions.create(
155
+ model="gpt-3.5-turbo",
156
  messages=messages,
157
  functions=function_list,
158
  function_call='auto',
 
184
  else:
185
  return "Sorry, I am having trouble connecting to the server. Please try again later."
186
 
187
+ return "Failed to get a response after multiple attempts."
188
+
189
+
190
+ def handle_search_mode(mode):
191
+ print(mode)
192
+ global search_mode
193
+ if mode == "Always":
194
+ search_mode = 0
195
+ return "You are in Mode 1"
196
+ elif mode == "Automatic":
197
+ search_mode = 1
198
+ return "You are in Mode 2"
199
+ else:
200
+ search_mode = 0
201
+ return "Select a mode"
202
+
203
+ def handle_dbms_mode(mode):
204
+ print(mode)
205
+ global dbmsmode
206
+ with open('settings.arcana',mode='w') as file:
207
+ newsettings = foldername+'\n'+mode
208
+ file.write(newsettings)
209
+
210
+ if mode == "Nylon":
211
+ dbmsmode = "Nylon"
212
+ return "You are in Mode 1"
213
+ elif mode == "Fiber":
214
+ dbmsmode = "Fiber"
215
+ return "You are in Mode 2"
216
+ else:
217
+ search_mode = 0
218
+ return "Select a mode"
219
+
220
  # Chatbot response function
221
  def chatbot_response(message, history):
222
  messages = [{"role": "system", "content": '''You are Arcana, a dynamic study resource database designed to help students excel in their exams. Your responses should be accurate, informative, and evidence-based whenever possible. Follow these guidelines:
223
+ Your primary goal is to provide students with the most helpful and accurate study information, utilizing both your internal knowledge and the PDF resources at your disposal. You will search your database for answers and properly intext cite them, unless there is no such data, then you will intextcite[Arcana].'''}]
224
 
225
  for human, assistant in history:
226
  messages.append({"role": "user", "content": human})
 
238
  # Function to handle the file upload
239
  def handle_file_upload(file):
240
  # Ensure the cache2 directory exists
241
+ cache_dir = foldername
242
  os.makedirs(cache_dir, exist_ok=True)
243
 
244
  # Get the uploaded file path
 
262
  return future.result()
263
 
264
  def list_uploaded_files():
265
+ global foldername
266
  if not os.path.exists(foldername):
267
  return []
268
  files = os.listdir(foldername)
 
275
  selected = selected_value
276
  print(f"Selected value: {selected_value} at index: {selected_index}")
277
 
278
+ file_path = os.path.join(foldername,selected_value) if selected_value else None
279
  status_message = f"Selected: {selected_value}" if selected_value else "No file selected"
280
 
281
  file_size = get_file_size(file_path) if file_path else ""
 
301
  return ""
302
 
303
  def delete_file():
304
+ global selected,foldername
305
  if selected:
 
306
  file_path = os.path.join(foldername, selected)
307
  if os.path.exists(file_path):
308
  os.remove(file_path)
 
316
  return list_uploaded_files()
317
 
318
  def display_file(evt: gr.SelectData, df):
319
+ file_path = os.path.join(foldername, evt.value)
320
  return file_path, file_path if file_path.lower().endswith(('.png', '.jpg', '.jpeg', '.gif')) else None, f"Displaying: {evt.value}"
321
 
322
  def render_to_database():
323
  # This function is undefined as per your request
324
+ Arcana.main(foldername)
325
 
326
  def change_theme(theme):
327
  gr.Interface.theme = theme
 
329
  def rename_file(new_name):
330
  global selected
331
  if selected and new_name:
332
+ old_path = os.path.join(foldername, selected)
333
+ new_path = os.path.join(foldername, new_name+'.'+selected.split('.')[-1])
334
  if os.path.exists(old_path):
335
  os.rename(old_path, new_path)
336
  selected = new_name
 
341
 
342
  def query_database(query):
343
  # Usage example
344
+ db = ChatDatabase(foldername+'.txt')
345
 
346
  # Example 1: Get relevant messages
347
  sender = 'Arcana'
 
364
 
365
  return df
366
 
367
+ def query_database_fiber(query):
368
+ dbms = fiber.FiberDBMS()
369
+ # Load or create the database
370
+ dbms.load_or_create(foldername+'.txt')
371
+ results = dbms.query(query, 10)
372
+
373
+ # Convert the results to a pandas DataFrame
374
+ df = pd.DataFrame(results)
375
+
376
+ # Reorder columns if needed
377
+ columns_order = ['name', 'content', 'tags', 'index']
378
+ df = df[columns_order]
379
+
380
+ return df
381
+
382
+ def setdbname(name):
383
+ global foldername
384
+ foldername = name
385
+ with open('settings.arcana',mode='w') as file:
386
+ newsettings = foldername+'\n'+dbmsmode
387
+ file.write(newsettings)
388
 
389
  example_database = [
390
  "What is Hydrogen Bonding?",
 
412
  chatbot_interface = gr.ChatInterface(
413
  chatbot_response,
414
  chatbot=gr.Chatbot(height=400),
415
+ textbox=gr.Textbox(placeholder="Type your message here...", container=False, scale=100),
416
  title="Review With Arcana",
417
  description="ArcanaUI v0.8 - Chatbot",
418
+ theme="default",
419
  examples=get_random_examples(),
420
  cache_examples=False,
421
+ retry_btn=gr.Button('Retry'),
422
  undo_btn="Delete Previous",
423
+ clear_btn="Clear",
424
  )
425
 
426
+ def chatbot_response(message):
427
+ # Your chatbot response logic here
428
+ return f"Response to: {message}"
429
 
430
  def relaunch():
431
  global demo
 
455
 
456
  with gr.TabItem("Chatbot"):
457
  chatbot_interface.render()
458
+
459
  # File uploading interface
460
  with gr.TabItem('Upload'):
461
  gr.Markdown('# Upload and View Files')
 
511
 
512
  test_nylon = gr.Textbox(label='Test Nylon', placeholder='Query')
513
  uploaded_files_list2 = gr.DataFrame(headers=["Nylon Returned Query"], datatype="str", interactive=False)
514
+ query_button2 = gr.Button('Query')
515
+ query_button2.click(fn=query_database, inputs=test_nylon, outputs=uploaded_files_list2)
516
+
517
+ test_fiber = gr.Textbox(label='Test Fiber', placeholder='Query')
518
+ uploaded_files_list3 = gr.DataFrame(headers=["Fiber Returned Query"], datatype="str", interactive=False)
519
+ query_button3 = gr.Button('Query')
520
+ query_button3.click(fn=query_database_fiber, inputs=test_fiber, outputs=uploaded_files_list3)
521
+
522
+ gr.Markdown('Nylon 2.1 will be deprecated in text-text selections, as it is built for image-text selections.\nDefault model is Fiber.')
523
+ dbmsmode_selector = gr.Radio(["Nylon", "Fiber"], label="Select Model")
524
+ dbmsmode_selector.change(handle_dbms_mode, dbmsmode_selector)
525
+
526
+ database_name = gr.Textbox(label='Database Name', placeholder='cache')
527
+ set_dbname = gr.Button('Set Database Name')
528
+ set_dbname.click(fn=setdbname, inputs=database_name)
529
+
530
  with gr.TabItem('Theme'):
531
  gr.Markdown('Change Theme')
532
 
 
536
  theme_button.click(fn=change_theme, inputs=theme_dropdown)
537
  relaunch_button = gr.Button('Relaunch')
538
  relaunch_button.click(fn=relaunch)
539
+ with gr.TabItem('Search'):
540
+ gr.Markdown('Set Search Modes')
541
 
542
+ searchmode_selector = gr.Radio(["Always", "Automatic"], label="Select Mode")
543
+ output = gr.Textbox(label="Output")
544
+ searchmode_selector.change(handle_search_mode, searchmode_selector, output)
545
+
546
 
547
  # Launch the interface
548
  demo.launch(share=True)