File size: 5,133 Bytes
c20f7c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
import gradio as gr
import ssl
from openai import OpenAI
import time
import os
import shutil

# SSL configuration
try:
    _create_unverified_https_context = ssl._create_unverified_context
except AttributeError:
    pass
else:
    ssl._create_default_https_context = _create_unverified_https_context

# OpenAI client setup
client = OpenAI(
    base_url='https://api.openai-proxy.org/v1',
    api_key='sk-Nxf8HmLpfIMhCd83n3TOr00TR57uBZ0jMbAgGCOzppXvlsx1',
)

# Retry logic for OpenAI API call
def openai_api_call(messages, retries=3, delay=5):
    for attempt in range(retries):
        try:
            completion = client.chat.completions.create(
                model="gpt-3.5-turbo",
                messages=messages,
                timeout=10  # Increase timeout
            )
            return completion.choices[0].message.content
        except Exception as e:
            print(f"Attempt {attempt + 1} failed: {e}")
            time.sleep(delay)
    return "Sorry, I am having trouble connecting to the server. Please try again later."

# Chatbot response function
def chatbot_response(message, history):
    # Prepare the conversation history for the API
    messages = [{"role": "system", "content": "You are a dynamic study resource database named Arcana. Your goal is to help students study and excel in their exams."}]
    for human, assistant in history:
        messages.append({"role": "user", "content": human})
        messages.append({"role": "assistant", "content": assistant})
    messages.append({"role": "user", "content": message})

    # Get response from OpenAI API with retry logic
    response = openai_api_call(messages)
    return response

def upload_file(file):
    foldername = 'cache'
    if not os.path.exists(foldername):
        os.mkdir(foldername)
    file_path = os.path.join(foldername, os.path.basename(file.name))
    shutil.copy(file.name, file_path)
    return list_uploaded_files()

def list_uploaded_files():
    foldername = 'cache'
    if not os.path.exists(foldername):
        return []
    files = os.listdir(foldername)
    return [[file] for file in files]

def refresh_files():
    return list_uploaded_files()

# Create the Gradio interface for the chatbot
chatbot_interface = gr.ChatInterface(
    chatbot_response,
    chatbot=gr.Chatbot(height=300),
    textbox=gr.Textbox(placeholder="Type your message here...", container=False, scale=7),
    title="Review With Arcana",
    description="ArcanaUI v0.7 - Chatbot",
    theme="soft",
    examples=[
        "What is Hydrogen Bonding?",
        "Tell me the difference between impulse and force.",
        "Tell me a joke that Calculus students will know.",
        "How should I review for the AP Biology Exam?"
    ],
    cache_examples=False,
    retry_btn=None,
    undo_btn="Delete Previous",
    clear_btn="Clear"
)

# Combine the interfaces using Tabs
with gr.Blocks() as demo:
    gr.Markdown("# ArcanaUI v0.7")
    with gr.Tabs():
        with gr.TabItem("Welcome Page"):
            gr.Markdown("""
            # Welcome to ArcanaUI v0.7 by the Indexademics Team
            Program Base Powered by StandardCAS™
            ## Introduction
            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.

            ## How to Use
            - Navigate to the 'Chatbot' tab to ask your study-related questions.
            - Type your question into the textbox and press Enter.
            - The chatbot will respond with helpful information.
            - Use the 'Delete Previous' button to remove the last interaction or 'Clear' to reset the chat.

            ## Works Cited
            Below is a sample citation in BibTeX format:
            ```
            @article{Fan2023CELSIA,
              title={CELSIA-Nylon},
              author={Chengjui Fan},
              journal={Conf-MLA 2023},
              year={2023},
              volume={NAN},
              number={NAN},
              pages={NAN},
              publisher={Conf-MLA}
            }

            @misc{Indexademics,
              title={indexademics Chatbot},
              author={NAN},
              journal={SHSID},
              year={2024},
              volume={NAN},
              number={NAN},
              pages={NAN},
              publisher={Peer Advisor(PA) SHSID}
            }
            ```
            """)

        with gr.TabItem("Chatbot"):
            chatbot_interface.render()

        # File uploading interface
        with gr.TabItem('Upload'):
            gr.Markdown('# Upload and View Files')
            refresh_button = gr.Button('Refresh')
            upload_button = gr.UploadButton('Upload File')
            uploaded_files_list = gr.DataFrame(headers=["Uploaded Files"])
            refresh_button.click(fn=refresh_files, outputs=uploaded_files_list)
            upload_button.upload(upload_file, inputs=upload_button, outputs=uploaded_files_list)
            gr.Row([upload_button, refresh_button, uploaded_files_list])

# Launch the interface
demo.launch(share=True)