Ocillus commited on
Commit
7a1d277
·
verified ·
1 Parent(s): 0a9a90c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +158 -16
app.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):
@@ -123,7 +195,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,28 +212,75 @@ 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.8 - 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.8")
@@ -215,8 +336,29 @@ with gr.Blocks() as demo:
215
  render_button = gr.Button("Render all PDFs to Database")
216
  render_button.click(fn=render_to_database)
217
 
218
- with gr.Tabitem('Settings'):
219
- gr.Markdown('Settings')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
220
 
221
  # Launch the interface
222
  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):
 
195
  def render_to_database():
196
  # This function is undefined as per your request
197
  Arcana.main()
198
+
199
+ def change_theme(theme):
200
+ gr.Interface.theme = theme
201
 
202
  def rename_file(new_name):
203
  global selected
 
212
  return list_uploaded_files(), f"File {selected} not found", None, "", ""
213
  return list_uploaded_files(), "No file selected or new name not provided", None, "", ""
214
 
215
+ def query_database(query):
216
+ # Usage example
217
+ db = ChatDatabase('memory.txt')
218
+
219
+ # Example 1: Get relevant messages
220
+ sender = 'Arcana'
221
+ N = 10
222
+ cache = {}
223
+ query_tag = None
224
+
225
+ relevant_messages = db.get_relevant_messages(sender, query, N, cache, query_tag)
226
+
227
+ print("Relevant messages:")
228
+ for message in relevant_messages:
229
+ print(f"Sender: {message[0]}, Time: {message[1]}, Tag: {message[3]}")
230
+ print(f"Message: {message[2][:100]}...")
231
+ print()
232
+
233
+ df_data = [{"Nylon Returned Query": str(message)} for message in relevant_messages]
234
+
235
+ # Create a pandas DataFrame
236
+ df = pd.DataFrame(df_data)
237
+
238
+ return df
239
+
240
+
241
+ example_database = [
242
+ "What is Hydrogen Bonding?",
243
+ "Tell me the difference between impulse and force.",
244
+ "Tell me a joke that Calculus students will understand.",
245
+ "How should I review for the AP Biology Exam?",
246
+ "What kind of resources are available in PA and Indexademics?",
247
+ "What is the StandardCAS™ group?",
248
+ "Explain the concept of quantum entanglement.",
249
+ "What are the main differences between mitosis and meiosis?",
250
+ "How does the Doppler effect work?",
251
+ "Explain the process of photosynthesis.",
252
+ "What is the significance of the Pythagorean theorem?",
253
+ "How does natural selection contribute to evolution?",
254
+ "What is the most important chapter in AP Statistics?",
255
+ "How should I prepare on the IB Chinese Exam?"
256
+ ]
257
+
258
+ import random
259
+
260
+ def get_random_examples(num_examples=5):
261
+ return random.sample(example_database, min(num_examples, len(example_database)))
262
+
263
  # Create the Gradio interface for the chatbot
264
  chatbot_interface = gr.ChatInterface(
265
  chatbot_response,
266
  chatbot=gr.Chatbot(height=400),
267
+ textbox=gr.Textbox(placeholder="Type your message here...", container=True, scale=10),
268
  title="Review With Arcana",
269
  description="ArcanaUI v0.8 - Chatbot",
270
  theme="soft",
271
+ examples=get_random_examples(),
 
 
 
 
 
 
 
272
  cache_examples=False,
273
  retry_btn=None,
274
  undo_btn="Delete Previous",
275
  clear_btn="Clear"
276
  )
277
 
278
+
279
+ def relaunch():
280
+ global demo
281
+ demo.close()
282
+ demo.launch(share=True)
283
+
284
  # Combine the interfaces using Tabs
285
  with gr.Blocks() as demo:
286
  gr.Markdown("# ArcanaUI v0.8")
 
336
  render_button = gr.Button("Render all PDFs to Database")
337
  render_button.click(fn=render_to_database)
338
 
339
+ with gr.TabItem('Settings'):
340
+ with gr.TabItem('Database'):
341
+ gr.Markdown('Settings')
342
+
343
+ test_nylon = gr.Textbox(label='Test Nylon', placeholder='Query')
344
+ uploaded_files_list2 = gr.DataFrame(headers=["Nylon Returned Query"], datatype="str", interactive=False)
345
+
346
+ query_button = gr.Button('Query')
347
+
348
+ query_button.click(fn=query_database, inputs=test_nylon, outputs=uploaded_files_list2)
349
+ with gr.TabItem('Theme'):
350
+ gr.Markdown('Change Theme')
351
+
352
+ theme_dropdown = gr.Dropdown(choices=['default', 'compact', 'huggingface', 'soft', 'dark'], label='Choose Theme')
353
+ theme_button = gr.Button('Apply Theme')
354
+
355
+ theme_button.click(fn=change_theme, inputs=theme_dropdown)
356
+ relaunch_button = gr.Button('Relaunch')
357
+ relaunch_button.click(fn=relaunch)
358
+
359
 
360
  # Launch the interface
361
  demo.launch(share=True)
362
+
363
+
364
+