Update app.py
Browse files
app.py
CHANGED
@@ -4,8 +4,10 @@ from openai import OpenAI
|
|
4 |
import time
|
5 |
import os
|
6 |
import shutil
|
|
|
|
|
7 |
|
8 |
-
# SSL configuration
|
9 |
try:
|
10 |
_create_unverified_https_context = ssl._create_unverified_context
|
11 |
except AttributeError:
|
@@ -13,6 +15,7 @@ except AttributeError:
|
|
13 |
else:
|
14 |
ssl._create_default_https_context = _create_unverified_https_context
|
15 |
|
|
|
16 |
# OpenAI client setup
|
17 |
client = OpenAI(
|
18 |
base_url='https://api.openai-proxy.org/v1',
|
@@ -24,9 +27,9 @@ def openai_api_call(messages, retries=3, delay=5):
|
|
24 |
for attempt in range(retries):
|
25 |
try:
|
26 |
completion = client.chat.completions.create(
|
27 |
-
model="gpt-
|
28 |
messages=messages,
|
29 |
-
timeout=10
|
30 |
)
|
31 |
return completion.choices[0].message.content
|
32 |
except Exception as e:
|
@@ -36,17 +39,20 @@ def openai_api_call(messages, retries=3, delay=5):
|
|
36 |
|
37 |
# Chatbot response function
|
38 |
def chatbot_response(message, history):
|
39 |
-
|
40 |
-
|
|
|
41 |
for human, assistant in history:
|
42 |
messages.append({"role": "user", "content": human})
|
43 |
messages.append({"role": "assistant", "content": assistant})
|
44 |
messages.append({"role": "user", "content": message})
|
45 |
|
46 |
-
# Get response from OpenAI API with retry logic
|
47 |
response = openai_api_call(messages)
|
|
|
48 |
return response
|
49 |
|
|
|
|
|
50 |
def upload_file(file):
|
51 |
foldername = 'cache'
|
52 |
if not os.path.exists(foldername):
|
@@ -62,14 +68,81 @@ def list_uploaded_files():
|
|
62 |
files = os.listdir(foldername)
|
63 |
return [[file] for file in files]
|
64 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
65 |
def refresh_files():
|
66 |
return list_uploaded_files()
|
67 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
68 |
# Create the Gradio interface for the chatbot
|
69 |
chatbot_interface = gr.ChatInterface(
|
70 |
chatbot_response,
|
71 |
-
chatbot=gr.Chatbot(height=
|
72 |
-
textbox=gr.Textbox(placeholder="Type your message here...", container=
|
73 |
title="Review With Arcana",
|
74 |
description="ArcanaUI v0.7 - Chatbot",
|
75 |
theme="soft",
|
@@ -77,7 +150,9 @@ chatbot_interface = gr.ChatInterface(
|
|
77 |
"What is Hydrogen Bonding?",
|
78 |
"Tell me the difference between impulse and force.",
|
79 |
"Tell me a joke that Calculus students will know.",
|
80 |
-
"How should I review for the AP Biology Exam?"
|
|
|
|
|
81 |
],
|
82 |
cache_examples=False,
|
83 |
retry_btn=None,
|
@@ -91,42 +166,7 @@ with gr.Blocks() as demo:
|
|
91 |
with gr.Tabs():
|
92 |
with gr.TabItem("Welcome Page"):
|
93 |
gr.Markdown("""
|
94 |
-
|
95 |
-
Program Base Powered by StandardCAS™
|
96 |
-
## Introduction
|
97 |
-
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.
|
98 |
-
|
99 |
-
## How to Use
|
100 |
-
- Navigate to the 'Chatbot' tab to ask your study-related questions.
|
101 |
-
- Type your question into the textbox and press Enter.
|
102 |
-
- The chatbot will respond with helpful information.
|
103 |
-
- Use the 'Delete Previous' button to remove the last interaction or 'Clear' to reset the chat.
|
104 |
-
|
105 |
-
## Works Cited
|
106 |
-
Below is a sample citation in BibTeX format:
|
107 |
-
```
|
108 |
-
@article{Fan2023CELSIA,
|
109 |
-
title={CELSIA-Nylon},
|
110 |
-
author={Chengjui Fan},
|
111 |
-
journal={Conf-MLA 2023},
|
112 |
-
year={2023},
|
113 |
-
volume={NAN},
|
114 |
-
number={NAN},
|
115 |
-
pages={NAN},
|
116 |
-
publisher={Conf-MLA}
|
117 |
-
}
|
118 |
-
|
119 |
-
@misc{Indexademics,
|
120 |
-
title={indexademics Chatbot},
|
121 |
-
author={NAN},
|
122 |
-
journal={SHSID},
|
123 |
-
year={2024},
|
124 |
-
volume={NAN},
|
125 |
-
number={NAN},
|
126 |
-
pages={NAN},
|
127 |
-
publisher={Peer Advisor(PA) SHSID}
|
128 |
-
}
|
129 |
-
```
|
130 |
""")
|
131 |
|
132 |
with gr.TabItem("Chatbot"):
|
@@ -135,12 +175,45 @@ with gr.Blocks() as demo:
|
|
135 |
# File uploading interface
|
136 |
with gr.TabItem('Upload'):
|
137 |
gr.Markdown('# Upload and View Files')
|
138 |
-
|
139 |
-
|
140 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
141 |
refresh_button.click(fn=refresh_files, outputs=uploaded_files_list)
|
142 |
upload_button.upload(upload_file, inputs=upload_button, outputs=uploaded_files_list)
|
143 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
144 |
|
145 |
# Launch the interface
|
146 |
demo.launch(share=True)
|
|
|
4 |
import time
|
5 |
import os
|
6 |
import shutil
|
7 |
+
from datetime import datetime
|
8 |
+
import Arcana
|
9 |
|
10 |
+
# SSL configuration to avoid verification issues
|
11 |
try:
|
12 |
_create_unverified_https_context = ssl._create_unverified_context
|
13 |
except AttributeError:
|
|
|
15 |
else:
|
16 |
ssl._create_default_https_context = _create_unverified_https_context
|
17 |
|
18 |
+
|
19 |
# OpenAI client setup
|
20 |
client = OpenAI(
|
21 |
base_url='https://api.openai-proxy.org/v1',
|
|
|
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:
|
|
|
39 |
|
40 |
# Chatbot response function
|
41 |
def chatbot_response(message, history):
|
42 |
+
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:
|
43 |
+
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.'''}]
|
44 |
+
|
45 |
for human, assistant in history:
|
46 |
messages.append({"role": "user", "content": human})
|
47 |
messages.append({"role": "assistant", "content": assistant})
|
48 |
messages.append({"role": "user", "content": message})
|
49 |
|
|
|
50 |
response = openai_api_call(messages)
|
51 |
+
|
52 |
return response
|
53 |
|
54 |
+
selected = None
|
55 |
+
|
56 |
def upload_file(file):
|
57 |
foldername = 'cache'
|
58 |
if not os.path.exists(foldername):
|
|
|
68 |
files = os.listdir(foldername)
|
69 |
return [[file] for file in files]
|
70 |
|
71 |
+
def on_select(evt: gr.SelectData):
|
72 |
+
global selected
|
73 |
+
selected_value = evt.value
|
74 |
+
selected_index = evt.index
|
75 |
+
selected = selected_value
|
76 |
+
print(f"Selected value: {selected_value} at index: {selected_index}")
|
77 |
+
|
78 |
+
file_path = os.path.join("cache", selected_value) if selected_value else None
|
79 |
+
status_message = f"Selected: {selected_value}" if selected_value else "No file selected"
|
80 |
+
|
81 |
+
file_size = get_file_size(file_path) if file_path else ""
|
82 |
+
file_creation_time = get_file_creation_time(file_path) if file_path else ""
|
83 |
+
|
84 |
+
return file_path, status_message, file_size, file_creation_time
|
85 |
+
|
86 |
+
def get_file_size(file_path):
|
87 |
+
if file_path and os.path.exists(file_path):
|
88 |
+
size_bytes = os.path.getsize(file_path)
|
89 |
+
if size_bytes < 1024:
|
90 |
+
return f"{size_bytes} bytes"
|
91 |
+
elif size_bytes < 1024 * 1024:
|
92 |
+
return f"{size_bytes / 1024:.2f} KB"
|
93 |
+
else:
|
94 |
+
return f"{size_bytes / (1024 * 1024):.2f} MB"
|
95 |
+
return ""
|
96 |
+
|
97 |
+
def get_file_creation_time(file_path):
|
98 |
+
if file_path and os.path.exists(file_path):
|
99 |
+
creation_time = os.path.getctime(file_path)
|
100 |
+
return datetime.fromtimestamp(creation_time).strftime("%Y-%m-%d %H:%M:%S")
|
101 |
+
return ""
|
102 |
+
|
103 |
+
def delete_file():
|
104 |
+
global selected
|
105 |
+
if selected:
|
106 |
+
foldername = 'cache'
|
107 |
+
file_path = os.path.join(foldername, selected)
|
108 |
+
if os.path.exists(file_path):
|
109 |
+
os.remove(file_path)
|
110 |
+
return list_uploaded_files(), None, f"File {selected} deleted successfully", "", ""
|
111 |
+
else:
|
112 |
+
return list_uploaded_files(), None, f"File {selected} not found", "", ""
|
113 |
+
else:
|
114 |
+
return list_uploaded_files(), None, "No file selected for deletion", "", ""
|
115 |
+
|
116 |
def refresh_files():
|
117 |
return list_uploaded_files()
|
118 |
|
119 |
+
def display_file(evt: gr.SelectData, df):
|
120 |
+
file_path = os.path.join("cache", evt.value)
|
121 |
+
return file_path, file_path if file_path.lower().endswith(('.png', '.jpg', '.jpeg', '.gif')) else None, f"Displaying: {evt.value}"
|
122 |
+
|
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
|
130 |
+
if selected and new_name:
|
131 |
+
old_path = os.path.join('cache', selected)
|
132 |
+
new_path = os.path.join('cache', new_name+'.'+selected.split('.')[-1])
|
133 |
+
if os.path.exists(old_path):
|
134 |
+
os.rename(old_path, new_path)
|
135 |
+
selected = new_name
|
136 |
+
return list_uploaded_files(), f"File renamed to {new_name}", new_path, get_file_size(new_path), get_file_creation_time(new_path)
|
137 |
+
else:
|
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",
|
|
|
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,
|
|
|
166 |
with gr.Tabs():
|
167 |
with gr.TabItem("Welcome Page"):
|
168 |
gr.Markdown("""
|
169 |
+
hi
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
170 |
""")
|
171 |
|
172 |
with gr.TabItem("Chatbot"):
|
|
|
175 |
# File uploading interface
|
176 |
with gr.TabItem('Upload'):
|
177 |
gr.Markdown('# Upload and View Files')
|
178 |
+
|
179 |
+
with gr.Row():
|
180 |
+
# Left column: File list and buttons
|
181 |
+
with gr.Column(scale=1):
|
182 |
+
uploaded_files_list = gr.DataFrame(headers=["Uploaded Files"], datatype="str", interactive=False)
|
183 |
+
|
184 |
+
with gr.Row():
|
185 |
+
upload_button = gr.UploadButton('Upload File')
|
186 |
+
refresh_button = gr.Button('Refresh')
|
187 |
+
delete_button = gr.Button('Delete Selected File')
|
188 |
+
|
189 |
+
# Right column: File viewer and Image viewer
|
190 |
+
with gr.Column(scale=1):
|
191 |
+
with gr.Tab("File Viewer"):
|
192 |
+
file_viewer = gr.File(label="File Restore")
|
193 |
+
file_status = gr.Textbox(label="File Status", interactive=False)
|
194 |
+
file_size = gr.Textbox(label="File Size", interactive=False)
|
195 |
+
file_creation_time = gr.Textbox(label="File Creation Time", interactive=False)
|
196 |
+
|
197 |
+
with gr.Row():
|
198 |
+
new_file_name = gr.Textbox(label="New File Name", placeholder="Enter new file name")
|
199 |
+
rename_button = gr.Button("Rename File")
|
200 |
+
|
201 |
+
|
202 |
+
with gr.Tab("Image Viewer"):
|
203 |
+
image_viewer = gr.Image(label="Image Viewer", type="filepath")
|
204 |
+
|
205 |
+
# Event handlers
|
206 |
refresh_button.click(fn=refresh_files, outputs=uploaded_files_list)
|
207 |
upload_button.upload(upload_file, inputs=upload_button, outputs=uploaded_files_list)
|
208 |
+
delete_button.click(fn=delete_file, outputs=[uploaded_files_list, file_viewer, file_status, file_size, file_creation_time])
|
209 |
+
uploaded_files_list.select(fn=display_file, inputs=uploaded_files_list, outputs=[file_viewer, image_viewer, file_status])
|
210 |
+
uploaded_files_list.select(fn=on_select, outputs=[file_viewer, file_status, file_size, file_creation_time])
|
211 |
+
rename_button.click(fn=rename_file,
|
212 |
+
inputs=new_file_name,
|
213 |
+
outputs=[uploaded_files_list, file_status, file_viewer, file_size, file_creation_time])
|
214 |
+
|
215 |
+
render_button = gr.Button("Render all PDFs to Database")
|
216 |
+
render_button.click(fn=render_to_database)
|
217 |
|
218 |
# Launch the interface
|
219 |
demo.launch(share=True)
|