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