abanm commited on
Commit
381273f
·
verified ·
1 Parent(s): 72517e1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +34 -69
app.py CHANGED
@@ -5,10 +5,10 @@ import os
5
  import datetime
6
 
7
  # Constants
8
- SPACE_URL = "https://abanm-dubs.hf.space/api/generate"
9
- API_KEY = "s3cr3t_k3y" # Replace with your actual API key
10
  EOS_TOKEN = "<|end|>"
11
- CHAT_HISTORY_DIR = "chat_histories" # Directory to save chat histories
12
  IMAGE_PATH = "DubsChat.png"
13
  IMAGE_PATH_2 = "Reboot AI.png"
14
  Dubs_PATH = "Dubs.png"
@@ -20,17 +20,26 @@ except OSError as e:
20
  st.error(f"Failed to create chat history directory: {e}")
21
 
22
  # Streamlit Configurations
23
- st.set_page_config(page_title="DUBSChat",page_icon=IMAGE_PATH, layout="wide")
24
-
25
-
26
  st.logo(IMAGE_PATH_2)
27
 
28
-
29
  # Utility Functions
30
- def save_chat_history(session_name, messages):
31
  """
32
- Save the chat history to a JSON file.
33
  """
 
 
 
 
 
 
 
 
 
 
 
 
34
  file_path = os.path.join(CHAT_HISTORY_DIR, f"{session_name}.json")
35
  try:
36
  with open(file_path, "w") as f:
@@ -38,11 +47,7 @@ def save_chat_history(session_name, messages):
38
  except IOError as e:
39
  st.error(f"Failed to save chat history: {e}")
40
 
41
-
42
  def load_chat_history(file_name):
43
- """
44
- Load the chat history from a JSON file.
45
- """
46
  file_path = os.path.join(CHAT_HISTORY_DIR, file_name)
47
  try:
48
  with open(file_path, "r") as f:
@@ -51,18 +56,11 @@ def load_chat_history(file_name):
51
  st.error("Failed to load chat history. Starting with a new session.")
52
  return []
53
 
54
-
55
  def get_saved_sessions():
56
- """
57
- Get the list of saved chat sessions.
58
- """
59
  return [f.replace(".json", "") for f in os.listdir(CHAT_HISTORY_DIR) if f.endswith(".json")]
60
 
61
-
62
  # Sidebar Configuration
63
  with st.sidebar:
64
-
65
- # Reset chat
66
  if st.button("New Chat"):
67
  st.session_state["messages"] = [
68
  {"role": "system", "content": "You are DUBS, a helpful assistant capable of conversing in a friendly and knowledgeable way."},
@@ -72,11 +70,7 @@ with st.sidebar:
72
  save_chat_history(st.session_state["session_name"], st.session_state["messages"])
73
  st.success("Chat reset and new session started.")
74
 
75
- dubs_key = st.text_input("Enter Dubs Key", key="chatbot_api_key", type="password")
76
  saved_sessions = get_saved_sessions()
77
-
78
-
79
- # Display saved sessions
80
  if saved_sessions:
81
  selected_session = st.radio("Past Sessions:", saved_sessions)
82
  if st.button("Load Session"):
@@ -86,8 +80,6 @@ with st.sidebar:
86
  else:
87
  st.write("No past sessions available.")
88
 
89
-
90
-
91
  # Chat History Initialization
92
  if "messages" not in st.session_state:
93
  st.session_state["messages"] = [
@@ -98,9 +90,7 @@ if "session_name" not in st.session_state:
98
  st.session_state["session_name"] = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
99
 
100
  # Main Chat UI
101
-
102
- st.image(IMAGE_PATH,width=250)
103
-
104
  st.markdown("Empowering you with a Sustainable AI")
105
 
106
  # Display Chat History
@@ -108,15 +98,13 @@ for message in st.session_state["messages"]:
108
  if message["role"] == "user":
109
  st.chat_message("user").write(message["content"])
110
  elif message["role"] == "assistant":
111
- st.chat_message("assistant",avatar=Dubs_PATH).write(message["content"])
112
-
113
 
114
  # User Input
115
  if prompt := st.chat_input():
116
- if not dubs_key:
117
- st.warning("Please provide a valid Dubs Key.")
118
  else:
119
- # Append the user's message to the chat history
120
  st.session_state["messages"].append({"role": "user", "content": prompt})
121
  st.chat_message("user").write(prompt)
122
 
@@ -125,42 +113,19 @@ if prompt := st.chat_input():
125
  [f"<|{msg['role']}|>{msg['content']}<|end|>" for msg in st.session_state["messages"]]
126
  )
127
 
128
- # Stream response
129
  with st.spinner("Dubs is thinking... Woof Woof! 🐾"):
130
  assistant_message_placeholder = st.chat_message("assistant").empty()
131
 
132
- # Function to stream the response
133
- def stream_response():
134
- try:
135
- response = requests.post(
136
- SPACE_URL,
137
- json={"prompt": chat_history},
138
- headers={"Authorization": f"Bearer {dubs_key}"},
139
- stream=True, # Enable streaming
140
- timeout=120,
141
- )
142
- response.raise_for_status()
143
-
144
- # Process and yield only the response field
145
- for line in response.iter_lines():
146
- if line:
147
- data = json.loads(line.decode("utf-8"))
148
- yield data.get("response", "")
149
- except requests.exceptions.Timeout:
150
- yield "The request timed out. Please try again later."
151
- except requests.exceptions.RequestException as e:
152
- yield f"Error: {e}"
153
- except json.JSONDecodeError:
154
- yield "Error decoding server response."
155
-
156
- # Update assistant's message incrementally
157
- full_response = ""
158
- for chunk in stream_response():
159
- full_response += chunk
160
- assistant_message_placeholder.write(full_response)
161
-
162
- # Append the assistant's final response to the chat history
163
- st.session_state["messages"].append({"role": "assistant", "content": full_response})
164
-
165
- # Auto-save the updated chat history
166
  save_chat_history(st.session_state["session_name"], st.session_state["messages"])
 
5
  import datetime
6
 
7
  # Constants
8
+ API_URL = "https://z7svds7k42bwhhgm.us-east-1.aws.endpoints.huggingface.cloud"
9
+ HF_API_KEY = os.getenv("HF_API_KEY") # Retrieve the Hugging Face API key from system variables
10
  EOS_TOKEN = "<|end|>"
11
+ CHAT_HISTORY_DIR = "chat_histories"
12
  IMAGE_PATH = "DubsChat.png"
13
  IMAGE_PATH_2 = "Reboot AI.png"
14
  Dubs_PATH = "Dubs.png"
 
20
  st.error(f"Failed to create chat history directory: {e}")
21
 
22
  # Streamlit Configurations
23
+ st.set_page_config(page_title="DUBSChat", page_icon=IMAGE_PATH, layout="wide")
 
 
24
  st.logo(IMAGE_PATH_2)
25
 
 
26
  # Utility Functions
27
+ def query(payload):
28
  """
29
+ Query the Hugging Face endpoint.
30
  """
31
+ headers = {
32
+ "Authorization": f"Bearer {HF_API_KEY}",
33
+ "Content-Type": "application/json",
34
+ }
35
+ try:
36
+ response = requests.post(API_URL, headers=headers, json=payload)
37
+ response.raise_for_status()
38
+ return response.json()
39
+ except requests.exceptions.RequestException as e:
40
+ return {"error": str(e)}
41
+
42
+ def save_chat_history(session_name, messages):
43
  file_path = os.path.join(CHAT_HISTORY_DIR, f"{session_name}.json")
44
  try:
45
  with open(file_path, "w") as f:
 
47
  except IOError as e:
48
  st.error(f"Failed to save chat history: {e}")
49
 
 
50
  def load_chat_history(file_name):
 
 
 
51
  file_path = os.path.join(CHAT_HISTORY_DIR, file_name)
52
  try:
53
  with open(file_path, "r") as f:
 
56
  st.error("Failed to load chat history. Starting with a new session.")
57
  return []
58
 
 
59
  def get_saved_sessions():
 
 
 
60
  return [f.replace(".json", "") for f in os.listdir(CHAT_HISTORY_DIR) if f.endswith(".json")]
61
 
 
62
  # Sidebar Configuration
63
  with st.sidebar:
 
 
64
  if st.button("New Chat"):
65
  st.session_state["messages"] = [
66
  {"role": "system", "content": "You are DUBS, a helpful assistant capable of conversing in a friendly and knowledgeable way."},
 
70
  save_chat_history(st.session_state["session_name"], st.session_state["messages"])
71
  st.success("Chat reset and new session started.")
72
 
 
73
  saved_sessions = get_saved_sessions()
 
 
 
74
  if saved_sessions:
75
  selected_session = st.radio("Past Sessions:", saved_sessions)
76
  if st.button("Load Session"):
 
80
  else:
81
  st.write("No past sessions available.")
82
 
 
 
83
  # Chat History Initialization
84
  if "messages" not in st.session_state:
85
  st.session_state["messages"] = [
 
90
  st.session_state["session_name"] = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
91
 
92
  # Main Chat UI
93
+ st.image(IMAGE_PATH, width=250)
 
 
94
  st.markdown("Empowering you with a Sustainable AI")
95
 
96
  # Display Chat History
 
98
  if message["role"] == "user":
99
  st.chat_message("user").write(message["content"])
100
  elif message["role"] == "assistant":
101
+ st.chat_message("assistant", avatar=Dubs_PATH).write(message["content"])
 
102
 
103
  # User Input
104
  if prompt := st.chat_input():
105
+ if not HF_API_KEY:
106
+ st.warning("Please set the Hugging Face API key in the system environment.")
107
  else:
 
108
  st.session_state["messages"].append({"role": "user", "content": prompt})
109
  st.chat_message("user").write(prompt)
110
 
 
113
  [f"<|{msg['role']}|>{msg['content']}<|end|>" for msg in st.session_state["messages"]]
114
  )
115
 
116
+ # Query the model
117
  with st.spinner("Dubs is thinking... Woof Woof! 🐾"):
118
  assistant_message_placeholder = st.chat_message("assistant").empty()
119
 
120
+ payload = {
121
+ "inputs": chat_history,
122
+ "parameters": {
123
+ "max_new_tokens": 150
124
+ }
125
+ }
126
+ response = query(payload)
127
+ assistant_response = response.get("generated_text", "Error: Unable to fetch response.")
128
+ assistant_message_placeholder.write(assistant_response)
129
+
130
+ st.session_state["messages"].append({"role": "assistant", "content": assistant_response})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
131
  save_chat_history(st.session_state["session_name"], st.session_state["messages"])