Ocillus commited on
Commit
6681291
·
verified ·
1 Parent(s): e0fa681

Update ArcanaUI2.py

Browse files
Files changed (1) hide show
  1. ArcanaUI2.py +213 -65
ArcanaUI2.py CHANGED
@@ -6,6 +6,9 @@ import os
6
  import shutil
7
  from datetime import datetime
8
  import Arcana
 
 
 
9
 
10
  # SSL configuration to avoid verification issues
11
  try:
@@ -15,6 +18,24 @@ except AttributeError:
15
  else:
16
  ssl._create_default_https_context = _create_unverified_https_context
17
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
 
19
  # OpenAI client setup
20
  client = OpenAI(
@@ -22,20 +43,71 @@ client = OpenAI(
22
  api_key='sk-Nxf8HmLpfIMhCd83n3TOr00TR57uBZ0jMbAgGCOzppXvlsx1',
23
  )
24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  # Retry logic for OpenAI API call
26
  def openai_api_call(messages, retries=3, delay=5):
27
  for attempt in range(retries):
28
  try:
29
  completion = client.chat.completions.create(
30
- model="gpt-4o",
31
  messages=messages,
 
 
32
  timeout=10
33
  )
34
- return completion.choices[0].message.content
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  except Exception as e:
36
  print(f"Attempt {attempt + 1} failed: {e}")
37
- time.sleep(delay)
38
- return "Sorry, I am having trouble connecting to the server. Please try again later."
 
 
39
 
40
  # Chatbot response function
41
  def chatbot_response(message, history):
@@ -53,13 +125,33 @@ Your primary goal is to provide students with the most helpful and accurate stud
53
 
54
  selected = None
55
 
56
- def upload_file(file):
57
- foldername = 'cache'
58
- if not os.path.exists(foldername):
59
- os.mkdir(foldername)
60
- file_path = os.path.join(foldername, os.path.basename(file.name))
61
- shutil.copy(file.name, file_path)
62
- return list_uploaded_files()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
 
64
  def list_uploaded_files():
65
  foldername = 'cache'
@@ -123,7 +215,9 @@ def display_file(evt: gr.SelectData, df):
123
  def render_to_database():
124
  # This function is undefined as per your request
125
  Arcana.main()
126
-
 
 
127
 
128
  def rename_file(new_name):
129
  global selected
@@ -138,71 +232,95 @@ def rename_file(new_name):
138
  return list_uploaded_files(), f"File {selected} not found", None, "", ""
139
  return list_uploaded_files(), "No file selected or new name not provided", None, "", ""
140
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
141
  # Create the Gradio interface for the chatbot
142
  chatbot_interface = gr.ChatInterface(
143
  chatbot_response,
144
  chatbot=gr.Chatbot(height=400),
145
- textbox=gr.Textbox(placeholder="Type your message here...", container=True, scale=100),
146
  title="Review With Arcana",
147
- description="ArcanaUI v0.7 - Chatbot",
148
  theme="soft",
149
- examples=[
150
- "What is Hydrogen Bonding?",
151
- "Tell me the difference between impulse and force.",
152
- "Tell me a joke that Calculus students will know.",
153
- "How should I review for the AP Biology Exam?",
154
- "What kind of resources are available in PA and Indexademics?",
155
- "What is the StandardCAS™ group?"
156
- ],
157
  cache_examples=False,
158
  retry_btn=None,
159
  undo_btn="Delete Previous",
160
  clear_btn="Clear"
161
  )
162
 
 
 
 
 
 
 
163
  # Combine the interfaces using Tabs
164
- with gr.Blocks() as demo:
165
- gr.Markdown("# ArcanaUI v0.7")
 
 
 
 
 
 
 
 
 
 
 
 
166
  with gr.Tabs():
167
  with gr.TabItem("Welcome Page"):
168
- gr.Markdown("""
169
- # Welcome to ArcanaUI v0.7 by the Indexademics Team
170
- Program Base Powered by StandardCAS™
171
- ## Introduction
172
- Welcome to Arcana, your dynamic study resource database! Our goal is to help students like you excel in your exams by providing quick and accurate answers to your study questions.
173
-
174
- ## How to Use
175
- - Navigate to the 'Chatbot' tab to ask your study-related questions.
176
- - Type your question into the textbox and press Enter.
177
- - The chatbot will respond with helpful information.
178
- - Use the 'Delete Previous' button to remove the last interaction or 'Clear' to reset the chat.
179
-
180
- ## Works Cited
181
- Below is a sample citation in BibTeX format:
182
- ```
183
- @article{Fan2023CELSIA,
184
- title={CELSIA-Nylon},
185
- author={Chengjui Fan},
186
- journal={Conf-MLA 2023},
187
- year={2023},
188
- volume={NAN},
189
- number={NAN},
190
- pages={NAN},
191
- publisher={Conf-MLA}
192
- }
193
-
194
- @misc{Indexademics,
195
- title={indexademics Chatbot},
196
- author={NAN},
197
- journal={SHSID},
198
- year={2024},
199
- volume={NAN},
200
- number={NAN},
201
- pages={NAN},
202
- publisher={Peer Advisor(PA) SHSID}
203
- }
204
- ```
205
- """)
206
 
207
  with gr.TabItem("Chatbot"):
208
  chatbot_interface.render()
@@ -212,17 +330,22 @@ with gr.Blocks() as demo:
212
  gr.Markdown('# Upload and View Files')
213
 
214
  with gr.Row():
 
215
  # Left column: File list and buttons
216
  with gr.Column(scale=1):
 
 
 
 
217
  uploaded_files_list = gr.DataFrame(headers=["Uploaded Files"], datatype="str", interactive=False)
218
 
219
  with gr.Row():
220
- upload_button = gr.UploadButton('Upload File')
221
  refresh_button = gr.Button('Refresh')
222
  delete_button = gr.Button('Delete Selected File')
223
 
 
224
  # Right column: File viewer and Image viewer
225
- with gr.Column(scale=1):
226
  with gr.Tab("File Viewer"):
227
  file_viewer = gr.File(label="File Restore")
228
  file_status = gr.Textbox(label="File Status", interactive=False)
@@ -236,10 +359,11 @@ with gr.Blocks() as demo:
236
 
237
  with gr.Tab("Image Viewer"):
238
  image_viewer = gr.Image(label="Image Viewer", type="filepath")
 
 
239
 
240
  # Event handlers
241
  refresh_button.click(fn=refresh_files, outputs=uploaded_files_list)
242
- upload_button.upload(upload_file, inputs=upload_button, outputs=uploaded_files_list)
243
  delete_button.click(fn=delete_file, outputs=[uploaded_files_list, file_viewer, file_status, file_size, file_creation_time])
244
  uploaded_files_list.select(fn=display_file, inputs=uploaded_files_list, outputs=[file_viewer, image_viewer, file_status])
245
  uploaded_files_list.select(fn=on_select, outputs=[file_viewer, file_status, file_size, file_creation_time])
@@ -250,5 +374,29 @@ with gr.Blocks() as demo:
250
  render_button = gr.Button("Render all PDFs to Database")
251
  render_button.click(fn=render_to_database)
252
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
253
  # Launch the interface
254
  demo.launch(share=True)
 
 
 
 
6
  import shutil
7
  from datetime import datetime
8
  import Arcana
9
+ from nylon import *
10
+ import pandas as pd
11
+ import json
12
 
13
  # SSL configuration to avoid verification issues
14
  try:
 
18
  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(
 
43
  api_key='sk-Nxf8HmLpfIMhCd83n3TOr00TR57uBZ0jMbAgGCOzppXvlsx1',
44
  )
45
 
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",
53
+ "properties": {
54
+ "query": {
55
+ "type": "string",
56
+ "description": "The query to execute against the database"
57
+ },
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):
70
+ if function_name in function_map:
71
+ return function_map[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',
84
  timeout=10
85
  )
86
+ response_message = completion.choices[0].message
87
+
88
+ # Check if the model wants to call a function
89
+ if response_message.function_call:
90
+ function_name = response_message.function_call.name
91
+ function_args = json.loads(response_message.function_call.arguments)
92
+ function_response = execute_function(function_name, function_args)
93
+ # Add the function response to the conversation
94
+ messages.append(response_message.model_dump()) # The model's request to call the function
95
+ messages.append({
96
+ "role": "function",
97
+ "name": function_name,
98
+ "content": json.dumps(function_response)
99
+ })
100
+ # Make a follow-up call to the model with the function response
101
+ return openai_api_call(messages)
102
+ else:
103
+ return response_message.content
104
+
105
  except Exception as e:
106
  print(f"Attempt {attempt + 1} failed: {e}")
107
+ if attempt < retries - 1:
108
+ time.sleep(delay)
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):
 
125
 
126
  selected = None
127
 
128
+ from concurrent.futures import ThreadPoolExecutor
129
+
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
137
+ file_path = file.name
138
+
139
+ # Define the new path for the uploaded file
140
+ new_file_path = os.path.join(cache_dir, os.path.basename(file_path))
141
+
142
+ # Move the file to the cache2 directory
143
+ shutil.move(file_path, new_file_path)
144
+
145
+ # Get the file size
146
+ file_size = os.path.getsize(new_file_path)
147
+
148
+ return f"File saved to {new_file_path} with size: {file_size} bytes"
149
+
150
+ # Wrapper function to run the file upload in a thread
151
+ def handle_file_upload_threaded(file):
152
+ with ThreadPoolExecutor() as executor:
153
+ future = executor.submit(handle_file_upload, file)
154
+ return future.result()
155
 
156
  def list_uploaded_files():
157
  foldername = 'cache'
 
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
221
 
222
  def rename_file(new_name):
223
  global selected
 
232
  return list_uploaded_files(), f"File {selected} not found", None, "", ""
233
  return list_uploaded_files(), "No file selected or new name not provided", None, "", ""
234
 
235
+ def query_database(query):
236
+ # Usage example
237
+ db = ChatDatabase('memory.txt')
238
+
239
+ # Example 1: Get relevant messages
240
+ sender = 'Arcana'
241
+ N = 10
242
+ cache = {}
243
+ query_tag = None
244
+
245
+ relevant_messages = db.get_relevant_messages(sender, query, N, cache, query_tag)
246
+
247
+ print("Relevant messages:")
248
+ for message in relevant_messages:
249
+ print(f"Sender: {message[0]}, Time: {message[1]}, Tag: {message[3]}")
250
+ print(f"Message: {message[2][:100]}...")
251
+ print()
252
+
253
+ df_data = [{"Nylon Returned Query": str(message)} for message in relevant_messages]
254
+
255
+ # Create a pandas DataFrame
256
+ df = pd.DataFrame(df_data)
257
+
258
+ return df
259
+
260
+
261
+ example_database = [
262
+ "What is Hydrogen Bonding?",
263
+ "Tell me the difference between impulse and force.",
264
+ "Tell me a joke that Calculus students will understand.",
265
+ "How should I review for the AP Biology Exam?",
266
+ "What kind of resources are available in PA and Indexademics?",
267
+ "What is the StandardCAS™ group?",
268
+ "Explain the concept of quantum entanglement.",
269
+ "What are the main differences between mitosis and meiosis?",
270
+ "How does the Doppler effect work?",
271
+ "Explain the process of photosynthesis.",
272
+ "What is the significance of the Pythagorean theorem?",
273
+ "How does natural selection contribute to evolution?",
274
+ "What is the most important chapter in AP Statistics?",
275
+ "How should I prepare on the IB Chinese Exam?"
276
+ ]
277
+
278
+ import random
279
+
280
+ def get_random_examples(num_examples=5):
281
+ return random.sample(example_database, min(num_examples, len(example_database)))
282
+
283
  # Create the Gradio interface for the chatbot
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
301
+ demo.close()
302
+ demo.launch(share=True)
303
+
304
  # Combine the interfaces using Tabs
305
+ with gr.Blocks(js="""
306
+ async () => {
307
+ const originalFetch = window.fetch;
308
+ window.fetch = (url, options) => {
309
+ if (options && options.signal) {
310
+ const controller = new AbortController();
311
+ options.signal = controller.signal;
312
+ setTimeout(() => controller.abort(), 3600000); // 300000 ms = 5 minutes
313
+ }
314
+ return originalFetch(url, options);
315
+ };
316
+ }
317
+ """) as demo:
318
+ gr.Markdown("# ArcanaUI v0.8")
319
  with gr.Tabs():
320
  with gr.TabItem("Welcome Page"):
321
+ with open('introduction.txt',mode='r') as file:
322
+ intro_content = file.read()
323
+ gr.Markdown(intro_content)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
324
 
325
  with gr.TabItem("Chatbot"):
326
  chatbot_interface.render()
 
330
  gr.Markdown('# Upload and View Files')
331
 
332
  with gr.Row():
333
+
334
  # Left column: File list and buttons
335
  with gr.Column(scale=1):
336
+ gr.Markdown("## Upload File")
337
+ file_input = gr.File(label="Upload your file here", file_types=["pdf", "jpeg", "jpg", "gif", "docx"])
338
+ file_input.change(handle_file_upload_threaded, inputs=file_input)
339
+
340
  uploaded_files_list = gr.DataFrame(headers=["Uploaded Files"], datatype="str", interactive=False)
341
 
342
  with gr.Row():
 
343
  refresh_button = gr.Button('Refresh')
344
  delete_button = gr.Button('Delete Selected File')
345
 
346
+
347
  # Right column: File viewer and Image viewer
348
+ with gr.Column(scale=1):
349
  with gr.Tab("File Viewer"):
350
  file_viewer = gr.File(label="File Restore")
351
  file_status = gr.Textbox(label="File Status", interactive=False)
 
359
 
360
  with gr.Tab("Image Viewer"):
361
  image_viewer = gr.Image(label="Image Viewer", type="filepath")
362
+
363
+
364
 
365
  # Event handlers
366
  refresh_button.click(fn=refresh_files, outputs=uploaded_files_list)
 
367
  delete_button.click(fn=delete_file, outputs=[uploaded_files_list, file_viewer, file_status, file_size, file_creation_time])
368
  uploaded_files_list.select(fn=display_file, inputs=uploaded_files_list, outputs=[file_viewer, image_viewer, file_status])
369
  uploaded_files_list.select(fn=on_select, outputs=[file_viewer, file_status, file_size, file_creation_time])
 
374
  render_button = gr.Button("Render all PDFs to Database")
375
  render_button.click(fn=render_to_database)
376
 
377
+ with gr.TabItem('Settings'):
378
+ with gr.TabItem('Database'):
379
+ gr.Markdown('Settings')
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
+
390
+ theme_dropdown = gr.Dropdown(choices=['default', 'compact', 'huggingface', 'soft', 'dark'], label='Choose Theme')
391
+ theme_button = gr.Button('Apply Theme')
392
+
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)
400
+
401
+
402
+