Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
# INSTRUCTIONS for Chat Bot on line
|
| 2 |
|
| 3 |
# Imports
|
| 4 |
import gradio as gr
|
|
@@ -12,18 +12,9 @@ import time
|
|
| 12 |
openai_key = os.getenv("OPENAI_KEY")
|
| 13 |
if not openai_key:
|
| 14 |
raise ValueError("OPENAI_KEY not set")
|
| 15 |
-
|
| 16 |
-
# Scrub hidden spaces from the OpenAI key
|
| 17 |
-
openai_key = openai_key.replace('\xa0', '').strip()
|
| 18 |
-
|
| 19 |
-
github_key = os.getenv("GITHUB_KEY")
|
| 20 |
-
# Scrub hidden spaces from the GitHub key if it exists
|
| 21 |
-
if github_key:
|
| 22 |
-
github_key = github_key.replace('\xa0', '').strip()
|
| 23 |
-
|
| 24 |
client = OpenAI(api_key=openai_key)
|
| 25 |
|
| 26 |
-
|
| 27 |
g = Github(github_key) if github_key else None
|
| 28 |
|
| 29 |
# Repo name, if you want to save to a github repository change RepositoryName to your repo name, name must be under quotations
|
|
@@ -32,35 +23,37 @@ REPO_NAME = "RepositoryName"
|
|
| 32 |
# Session data for each user
|
| 33 |
user_dictionary = {}
|
| 34 |
|
| 35 |
-
# Gradio user interface
|
| 36 |
with gr.Blocks(theme=gr.themes.Monochrome(), css="""footer {display:none !important;}[class*="status"] {display:none !important;}[class*="progress"] {display:none !important;}""") as chatblock:
|
| 37 |
-
|
| 38 |
# Hidden session variables
|
| 39 |
user_id = gr.Textbox(visible=False)
|
| 40 |
notifier = gr.HTML(visible=False)
|
| 41 |
-
|
| 42 |
# Load user session
|
| 43 |
@chatblock.load(outputs=[user_id, notifier])
|
| 44 |
def load_user():
|
| 45 |
global user_dictionary
|
| 46 |
-
|
| 47 |
# Creating user ID
|
| 48 |
new_id = str(uuid.uuid4())
|
| 49 |
print("Loading user:", new_id)
|
| 50 |
user_dictionary[new_id] = []
|
| 51 |
-
|
| 52 |
# INSTRUCTIONS, instructions must be in quotations
|
| 53 |
instructions = (
|
| 54 |
-
"
|
| 55 |
-
"You
|
| 56 |
-
|
| 57 |
-
|
|
|
|
|
|
|
| 58 |
# Add ID and instructions to users session data
|
| 59 |
user_dictionary[new_id].append({
|
| 60 |
"role": "system",
|
| 61 |
"content": instructions
|
| 62 |
})
|
| 63 |
-
|
| 64 |
# Create a GitHub repository file to store the Data
|
| 65 |
if g:
|
| 66 |
try:
|
|
@@ -71,7 +64,7 @@ with gr.Blocks(theme=gr.themes.Monochrome(), css="""footer {display:none !import
|
|
| 71 |
print("GitHub file creation failed:", e)
|
| 72 |
else:
|
| 73 |
print("No GitHub key found. Skipping file creation.")
|
| 74 |
-
|
| 75 |
return new_id, f"<script>window.parent.postMessage({{user_id:'{new_id}'}}, '*')</script>"
|
| 76 |
|
| 77 |
# User message function so we can show the messages separately
|
|
@@ -80,19 +73,19 @@ with gr.Blocks(theme=gr.themes.Monochrome(), css="""footer {display:none !import
|
|
| 80 |
return [], ""
|
| 81 |
if user_id not in user_dictionary:
|
| 82 |
user_dictionary[user_id] = []
|
| 83 |
-
|
| 84 |
# Add messages to users session data
|
| 85 |
user_dictionary[user_id].append({
|
| 86 |
"role": "user",
|
| 87 |
"content": user_input
|
| 88 |
})
|
| 89 |
-
|
| 90 |
# Format conversation
|
| 91 |
formatted_chat = [
|
| 92 |
msg for msg in user_dictionary[user_id]
|
| 93 |
if msg["role"] != "system"
|
| 94 |
]
|
| 95 |
-
|
| 96 |
return formatted_chat, ""
|
| 97 |
|
| 98 |
# Optional function to simulate the time it takes a "person" to read your message, (amount of time reading, bubbles dont show up).
|
|
@@ -103,10 +96,10 @@ with gr.Blocks(theme=gr.themes.Monochrome(), css="""footer {display:none !import
|
|
| 103 |
def predict_prompt(user_id):
|
| 104 |
if not user_id or user_id not in user_dictionary:
|
| 105 |
return []
|
| 106 |
-
|
| 107 |
# Optional delay for a realistic human response time (amount of time typing message, bubbles show up)
|
| 108 |
time.sleep(1)
|
| 109 |
-
|
| 110 |
# Try to get the response from OpenAI
|
| 111 |
try:
|
| 112 |
response = client.chat.completions.create(
|
|
@@ -116,19 +109,19 @@ with gr.Blocks(theme=gr.themes.Monochrome(), css="""footer {display:none !import
|
|
| 116 |
reply = response.choices[0].message.content
|
| 117 |
except Exception as e:
|
| 118 |
reply = f"Error: {str(e)}"
|
| 119 |
-
|
| 120 |
# Add chatbot reply to session data
|
| 121 |
user_dictionary[user_id].append({
|
| 122 |
"role": "assistant",
|
| 123 |
"content": reply
|
| 124 |
})
|
| 125 |
-
|
| 126 |
# Format conversation
|
| 127 |
formatted_chat = [
|
| 128 |
msg for msg in user_dictionary[user_id]
|
| 129 |
if msg["role"] != "system"
|
| 130 |
]
|
| 131 |
-
|
| 132 |
# Save to GitHub
|
| 133 |
if g:
|
| 134 |
try:
|
|
@@ -142,7 +135,7 @@ with gr.Blocks(theme=gr.themes.Monochrome(), css="""footer {display:none !import
|
|
| 142 |
repo.update_file(file.path, "Update chat log", content, file.sha)
|
| 143 |
except Exception as e:
|
| 144 |
print("GitHub update failed:", e)
|
| 145 |
-
|
| 146 |
return formatted_chat
|
| 147 |
|
| 148 |
# User Interface components
|
|
@@ -150,14 +143,14 @@ with gr.Blocks(theme=gr.themes.Monochrome(), css="""footer {display:none !import
|
|
| 150 |
type="messages",
|
| 151 |
label="Anonymous User"
|
| 152 |
)
|
| 153 |
-
|
| 154 |
txt = gr.Textbox(
|
| 155 |
show_label=False,
|
| 156 |
placeholder="Please write your message and press Enter",
|
| 157 |
container=False
|
| 158 |
)
|
| 159 |
-
|
| 160 |
-
#
|
| 161 |
txt.submit(
|
| 162 |
add_user_message,
|
| 163 |
inputs=[txt, user_id],
|
|
|
|
| 1 |
+
# INSTRUCTIONS for Chat Bot on line #, Repository name on line #
|
| 2 |
|
| 3 |
# Imports
|
| 4 |
import gradio as gr
|
|
|
|
| 12 |
openai_key = os.getenv("OPENAI_KEY")
|
| 13 |
if not openai_key:
|
| 14 |
raise ValueError("OPENAI_KEY not set")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
client = OpenAI(api_key=openai_key)
|
| 16 |
|
| 17 |
+
github_key = os.getenv("GITHUB_KEY")
|
| 18 |
g = Github(github_key) if github_key else None
|
| 19 |
|
| 20 |
# Repo name, if you want to save to a github repository change RepositoryName to your repo name, name must be under quotations
|
|
|
|
| 23 |
# Session data for each user
|
| 24 |
user_dictionary = {}
|
| 25 |
|
| 26 |
+
# Gradio user interface, footer and progress made invisible
|
| 27 |
with gr.Blocks(theme=gr.themes.Monochrome(), css="""footer {display:none !important;}[class*="status"] {display:none !important;}[class*="progress"] {display:none !important;}""") as chatblock:
|
| 28 |
+
|
| 29 |
# Hidden session variables
|
| 30 |
user_id = gr.Textbox(visible=False)
|
| 31 |
notifier = gr.HTML(visible=False)
|
| 32 |
+
|
| 33 |
# Load user session
|
| 34 |
@chatblock.load(outputs=[user_id, notifier])
|
| 35 |
def load_user():
|
| 36 |
global user_dictionary
|
| 37 |
+
|
| 38 |
# Creating user ID
|
| 39 |
new_id = str(uuid.uuid4())
|
| 40 |
print("Loading user:", new_id)
|
| 41 |
user_dictionary[new_id] = []
|
| 42 |
+
|
| 43 |
# INSTRUCTIONS, instructions must be in quotations
|
| 44 |
instructions = (
|
| 45 |
+
"On the first message, you must respond: 'You can edit this Spaces code to change my instructions!'"
|
| 46 |
+
"You are a Chat Bot for the KU HMC Lab"
|
| 47 |
+
"instruction..."
|
| 48 |
+
"instruction..."
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
# Add ID and instructions to users session data
|
| 52 |
user_dictionary[new_id].append({
|
| 53 |
"role": "system",
|
| 54 |
"content": instructions
|
| 55 |
})
|
| 56 |
+
|
| 57 |
# Create a GitHub repository file to store the Data
|
| 58 |
if g:
|
| 59 |
try:
|
|
|
|
| 64 |
print("GitHub file creation failed:", e)
|
| 65 |
else:
|
| 66 |
print("No GitHub key found. Skipping file creation.")
|
| 67 |
+
|
| 68 |
return new_id, f"<script>window.parent.postMessage({{user_id:'{new_id}'}}, '*')</script>"
|
| 69 |
|
| 70 |
# User message function so we can show the messages separately
|
|
|
|
| 73 |
return [], ""
|
| 74 |
if user_id not in user_dictionary:
|
| 75 |
user_dictionary[user_id] = []
|
| 76 |
+
|
| 77 |
# Add messages to users session data
|
| 78 |
user_dictionary[user_id].append({
|
| 79 |
"role": "user",
|
| 80 |
"content": user_input
|
| 81 |
})
|
| 82 |
+
|
| 83 |
# Format conversation
|
| 84 |
formatted_chat = [
|
| 85 |
msg for msg in user_dictionary[user_id]
|
| 86 |
if msg["role"] != "system"
|
| 87 |
]
|
| 88 |
+
|
| 89 |
return formatted_chat, ""
|
| 90 |
|
| 91 |
# Optional function to simulate the time it takes a "person" to read your message, (amount of time reading, bubbles dont show up).
|
|
|
|
| 96 |
def predict_prompt(user_id):
|
| 97 |
if not user_id or user_id not in user_dictionary:
|
| 98 |
return []
|
| 99 |
+
|
| 100 |
# Optional delay for a realistic human response time (amount of time typing message, bubbles show up)
|
| 101 |
time.sleep(1)
|
| 102 |
+
|
| 103 |
# Try to get the response from OpenAI
|
| 104 |
try:
|
| 105 |
response = client.chat.completions.create(
|
|
|
|
| 109 |
reply = response.choices[0].message.content
|
| 110 |
except Exception as e:
|
| 111 |
reply = f"Error: {str(e)}"
|
| 112 |
+
|
| 113 |
# Add chatbot reply to session data
|
| 114 |
user_dictionary[user_id].append({
|
| 115 |
"role": "assistant",
|
| 116 |
"content": reply
|
| 117 |
})
|
| 118 |
+
|
| 119 |
# Format conversation
|
| 120 |
formatted_chat = [
|
| 121 |
msg for msg in user_dictionary[user_id]
|
| 122 |
if msg["role"] != "system"
|
| 123 |
]
|
| 124 |
+
|
| 125 |
# Save to GitHub
|
| 126 |
if g:
|
| 127 |
try:
|
|
|
|
| 135 |
repo.update_file(file.path, "Update chat log", content, file.sha)
|
| 136 |
except Exception as e:
|
| 137 |
print("GitHub update failed:", e)
|
| 138 |
+
|
| 139 |
return formatted_chat
|
| 140 |
|
| 141 |
# User Interface components
|
|
|
|
| 143 |
type="messages",
|
| 144 |
label="Anonymous User"
|
| 145 |
)
|
| 146 |
+
|
| 147 |
txt = gr.Textbox(
|
| 148 |
show_label=False,
|
| 149 |
placeholder="Please write your message and press Enter",
|
| 150 |
container=False
|
| 151 |
)
|
| 152 |
+
|
| 153 |
+
# Submits/Steps
|
| 154 |
txt.submit(
|
| 155 |
add_user_message,
|
| 156 |
inputs=[txt, user_id],
|