kavansaun commited on
Commit
c475a85
·
verified ·
1 Parent(s): 03ff8de

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +22 -19
app.py CHANGED
@@ -1,4 +1,4 @@
1
- # INSTRUCTIONS for Chat Bot on line 81, Repository name on line 25
2
 
3
  # Imports
4
  import gradio as gr
@@ -14,7 +14,6 @@ github_key = os.getenv("GITHUB_KEY")
14
 
15
  # Check openai key
16
  if not openai_key:
17
- print("OPENAI_KEY not set")
18
  raise gr.Error("OPENAI_KEY not set")
19
  client = OpenAI(api_key=openai_key)
20
 
@@ -49,16 +48,13 @@ def update_github_log(uid):
49
  error_msg = str(e).lower()
50
  # Catch invalid GitHub keys and raise a UI error
51
  if "bad_credentials" in error_msg or "bad credentials" in error_msg:
52
- print("The GitHub API Key provided is invalid.")
53
  gr.Warning("The GitHub API Key provided is invalid.")
54
- elif "repository" in error_msg:
55
- print("Repo not found, Possible incorrect Repository name")
56
  gr.Warning("Repo not found, Possible incorrect Repository name")
57
  else:
58
- print("GitHub update failed:", e)
59
- gr.Warning(f"{str(e)}")
60
  else:
61
- print("No GitHub key found. Skipping file creation.")
62
 
63
  # Gradio user interface, status and progress made invisible
64
  with gr.Blocks(theme=gr.themes.Monochrome(), css="""footer {display:none !important;}[class*="status"] {display:none !important;}[class*="progress"] {display:none !important;}""") as chatblock:
@@ -74,7 +70,7 @@ with gr.Blocks(theme=gr.themes.Monochrome(), css="""footer {display:none !import
74
 
75
  # Creating user ID
76
  new_id = str(uuid.uuid4())
77
- print("\nLoading user:", new_id)
78
  user_dictionary[new_id] = []
79
 
80
  # INSTRUCTIONS, instructions must be in quotations, \n means a new line to the AI.
@@ -117,17 +113,21 @@ with gr.Blocks(theme=gr.themes.Monochrome(), css="""footer {display:none !import
117
  return formatted_chat, ""
118
 
119
  # Optional function to simulate the time it takes a "person" to read your message, (amount of time reading, bubbles dont show up).
120
- def pause_before_typing():
121
- time.sleep(1)
 
 
 
 
 
 
 
122
 
123
  # Generate Chat Bot response
124
  def predict_prompt(user_id):
125
  if not user_id or user_id not in user_dictionary:
126
  return []
127
 
128
- # Optional delay for a realistic human response time (amount of time typing message, bubbles show up)
129
- time.sleep(1)
130
-
131
  # Try to get the response from OpenAI
132
  try:
133
  response = client.chat.completions.create(
@@ -135,20 +135,23 @@ with gr.Blocks(theme=gr.themes.Monochrome(), css="""footer {display:none !import
135
  messages=user_dictionary[user_id]
136
  )
137
  reply = response.choices[0].message.content
 
 
 
 
 
 
138
  except Exception as e:
139
  error_msg = str(e).lower()
140
  # Catch invalid or expired API keys and show a clean error message
141
  if "invalid_api_key" in error_msg or "incorrect api key" in error_msg:
142
- print("The OpenAI API Key provided is invalid or expired.")
143
  gr.Warning("The OpenAI API Key provided is invalid or expired.")
144
  reply = "System Error: The OpenAI API Key is invalid."
145
  elif "ascii" in error_msg:
146
- print("OPENAI_KEY was set incorrectly.")
147
  gr.Warning("OPENAI_KEY was set incorrectly.")
148
  reply = "System Error: The OpenAI API Key is improperly formatted."
149
  else:
150
- print(str(e))
151
- gr.Warning(f"{str(e)}")
152
  reply = f"System Error: {str(e)}"
153
 
154
  # Add chatbot reply to session data
@@ -188,7 +191,7 @@ with gr.Blocks(theme=gr.themes.Monochrome(), css="""footer {display:none !import
188
  queue=False
189
  ).then(
190
  pause_before_typing,
191
- inputs=None,
192
  outputs=None
193
  ).then(
194
  predict_prompt,
 
1
+ # INSTRUCTIONS for Chat Bot on line 77, Repository name on line 24
2
 
3
  # Imports
4
  import gradio as gr
 
14
 
15
  # Check openai key
16
  if not openai_key:
 
17
  raise gr.Error("OPENAI_KEY not set")
18
  client = OpenAI(api_key=openai_key)
19
 
 
48
  error_msg = str(e).lower()
49
  # Catch invalid GitHub keys and raise a UI error
50
  if "bad_credentials" in error_msg or "bad credentials" in error_msg:
 
51
  gr.Warning("The GitHub API Key provided is invalid.")
52
+ elif "repository" in error_msg or "404" in error_msg:
 
53
  gr.Warning("Repo not found, Possible incorrect Repository name")
54
  else:
55
+ gr.Warning(f"GitHub Error: {str(e)}")
 
56
  else:
57
+ pass
58
 
59
  # Gradio user interface, status and progress made invisible
60
  with gr.Blocks(theme=gr.themes.Monochrome(), css="""footer {display:none !important;}[class*="status"] {display:none !important;}[class*="progress"] {display:none !important;}""") as chatblock:
 
70
 
71
  # Creating user ID
72
  new_id = str(uuid.uuid4())
73
+ print(f"Session started. User ID: {new_id}") # Cleaned up console print
74
  user_dictionary[new_id] = []
75
 
76
  # INSTRUCTIONS, instructions must be in quotations, \n means a new line to the AI.
 
113
  return formatted_chat, ""
114
 
115
  # Optional function to simulate the time it takes a "person" to read your message, (amount of time reading, bubbles dont show up).
116
+ def pause_before_typing(user_id):
117
+ # Calculate reading time based on the length of the user's message
118
+ if user_id and user_id in user_dictionary and len(user_dictionary[user_id]) > 0:
119
+ user_msg = user_dictionary[user_id][-1]["content"]
120
+ # Fast reading speed, caps between 1 and 3 seconds
121
+ read_delay = max(1.0, min(len(user_msg) / 30, 3.0))
122
+ time.sleep(read_delay)
123
+ else:
124
+ time.sleep(1)
125
 
126
  # Generate Chat Bot response
127
  def predict_prompt(user_id):
128
  if not user_id or user_id not in user_dictionary:
129
  return []
130
 
 
 
 
131
  # Try to get the response from OpenAI
132
  try:
133
  response = client.chat.completions.create(
 
135
  messages=user_dictionary[user_id]
136
  )
137
  reply = response.choices[0].message.content
138
+
139
+ # Optional delay for a realistic human response time (amount of time typing message, bubbles show up)
140
+ # Dynamically calculated based on the length of the chatbot's generated reply
141
+ typing_delay = max(1.0, min(len(reply) / 40, 5.0)) # Caps typing delay between 1 and 5 seconds
142
+ time.sleep(typing_delay)
143
+
144
  except Exception as e:
145
  error_msg = str(e).lower()
146
  # Catch invalid or expired API keys and show a clean error message
147
  if "invalid_api_key" in error_msg or "incorrect api key" in error_msg:
 
148
  gr.Warning("The OpenAI API Key provided is invalid or expired.")
149
  reply = "System Error: The OpenAI API Key is invalid."
150
  elif "ascii" in error_msg:
 
151
  gr.Warning("OPENAI_KEY was set incorrectly.")
152
  reply = "System Error: The OpenAI API Key is improperly formatted."
153
  else:
154
+ gr.Warning(f"OpenAI Error: {str(e)}")
 
155
  reply = f"System Error: {str(e)}"
156
 
157
  # Add chatbot reply to session data
 
191
  queue=False
192
  ).then(
193
  pause_before_typing,
194
+ inputs=[user_id], # Updated to pass the user_id so it can check message length
195
  outputs=None
196
  ).then(
197
  predict_prompt,