abanm commited on
Commit
f0c5a50
ยท
verified ยท
1 Parent(s): f1c266e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -93
app.py CHANGED
@@ -2,6 +2,7 @@ import streamlit as st
2
  import requests
3
  import json
4
  import os
 
5
 
6
  # Constants
7
  SPACE_URL = "https://abanm-dubs.hf.space/api/generate"
@@ -12,101 +13,56 @@ CHAT_HISTORY_DIR = "chat_histories" # Directory to save chat histories
12
  # Ensure the directory exists
13
  os.makedirs(CHAT_HISTORY_DIR, exist_ok=True)
14
 
15
- # Streamlit Configurations (must come first)
16
  st.set_page_config(page_title="๐Ÿถ DUBSChat", layout="wide")
17
 
18
- # Sidebar Configuration
19
- with st.sidebar:
20
- dubs_key = st.text_input("Enter Dubs Key", key="chatbot_api_key", type="password")
21
- st.markdown("### Dubs Recall")
22
-
23
- # Save chat history
24
- if st.button("๐Ÿ’พ Save Chat"):
25
- if "messages" in st.session_state:
26
- file_name = st.text_input("Enter filename to save chat:", "chat_history.json")
27
- if file_name:
28
- file_path = os.path.join(CHAT_HISTORY_DIR, file_name)
29
- with open(file_path, "w") as f:
30
- json.dump(st.session_state["messages"], f)
31
- st.success(f"Chat saved as {file_name}!")
32
-
33
- # Load chat history
34
- file_to_load = st.selectbox("Select a chat to load:", os.listdir(CHAT_HISTORY_DIR))
35
- if st.button("๐Ÿ“‚ Load Chat"):
36
- file_path = os.path.join(CHAT_HISTORY_DIR, file_to_load)
37
- if os.path.exists(file_path):
38
- with open(file_path, "r") as f:
39
- st.session_state["messages"] = json.load(f)
40
- st.success(f"Loaded chat from {file_to_load}!")
41
- else:
42
- st.error(f"File {file_to_load} does not exist.")
43
-
44
- # Reset chat
45
- if st.button("๐Ÿ”„ Reset Chat"):
46
- st.session_state["messages"] = [
47
- {"role": "system", "content": "You are DUBS, a helpful assistant capable of conversing in a friendly and knowledgeable way."},
48
- {"role": "assistant", "content": "Hello! How can I assist you today?"}
49
- ]
50
-
51
- # Template for serializing chat history
52
- CHAT_TEMPLATE = """
53
- {% for message in messages %}
54
- {% if message['role'] == 'system' %}{{'<|system|>\n' + message['content'] + '<|end|>\n'}}
55
- {% elif message['role'] == 'user' %}{{'<|user|>\n' + message['content'] + '<|end|>\n'}}
56
- {% elif message['role'] == 'assistant' %}{{'<|assistant|>\n' + message['content'] + '<|end|>\n'}}
57
- {% endif %}
58
- {% endfor %}
59
- {% if add_generation_prompt %}{{ '<|assistant|>\n' }}{% else %}{{ eos_token }}{% endif %}
60
- """
61
-
62
- def format_chat_history(messages, add_generation_prompt=True):
63
  """
64
- Format the chat history using the provided template.
65
-
66
- Args:
67
- messages (list): List of message dictionaries with 'role' and 'content'.
68
- add_generation_prompt (bool): Whether to include an assistant generation prompt.
69
-
70
- Returns:
71
- str: Formatted chat history string.
72
  """
73
- from jinja2 import Template
 
 
74
 
75
- template = Template(CHAT_TEMPLATE)
76
- return template.render(messages=messages, add_generation_prompt=add_generation_prompt, eos_token=EOS_TOKEN)
 
 
 
 
 
77
 
78
- def call_api(chat_history):
 
 
79
  """
80
- Calls the backend API with the formatted chat history.
 
 
 
 
 
81
 
82
- Args:
83
- chat_history (str): Formatted chat history string.
 
 
 
 
 
 
84
 
85
- Yields:
86
- str: Streamed response chunks from the backend API.
87
- """
88
- headers = {
89
- "Authorization": f"Bearer {dubs_key}",
90
- "Content-Type": "application/json",
91
- }
92
- payload = {"prompt": chat_history}
93
-
94
- try:
95
- response = requests.post(SPACE_URL, json=payload, headers=headers, stream=True)
96
- response.raise_for_status()
97
-
98
- for chunk in response.iter_lines(decode_unicode=True):
99
- if chunk.strip():
100
- try:
101
- data = json.loads(chunk)
102
- if "response" in data:
103
- yield data["response"]
104
- except json.JSONDecodeError:
105
- yield "Error decoding response chunk."
106
- except requests.exceptions.Timeout:
107
- yield "Error: The API call timed out."
108
- except requests.exceptions.RequestException as e:
109
- yield f"Error: {str(e)}"
110
 
111
  # Chat History Initialization
112
  if "messages" not in st.session_state:
@@ -114,6 +70,8 @@ if "messages" not in st.session_state:
114
  {"role": "system", "content": "You are DUBS, a helpful assistant capable of conversing in a friendly and knowledgeable way."},
115
  {"role": "assistant", "content": "Hello! How can I assist you today?"}
116
  ]
 
 
117
 
118
  # Main Chat UI
119
  st.title("๐Ÿถ DUBSChat")
@@ -133,15 +91,30 @@ if prompt := st.chat_input():
133
  st.chat_message("user").write(prompt)
134
 
135
  # Serialize chat history for API
136
- chat_history = format_chat_history(st.session_state["messages"])
 
 
137
 
138
  # Get response from API
139
  with st.spinner("Translating Dubs language (Woof Woof!)"):
140
  assistant_message_placeholder = st.chat_message("assistant").empty()
141
  full_response = ""
142
- for response_chunk in call_api(chat_history):
143
- full_response += response_chunk
144
- assistant_message_placeholder.write(full_response)
145
-
146
- # Append the assistant's response to the chat history
147
- st.session_state["messages"].append({"role": "assistant", "content": full_response})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  import requests
3
  import json
4
  import os
5
+ import datetime
6
 
7
  # Constants
8
  SPACE_URL = "https://abanm-dubs.hf.space/api/generate"
 
13
  # Ensure the directory exists
14
  os.makedirs(CHAT_HISTORY_DIR, exist_ok=True)
15
 
16
+ # Streamlit Configurations
17
  st.set_page_config(page_title="๐Ÿถ DUBSChat", layout="wide")
18
 
19
+ # Utility Functions
20
+ def save_chat_history(session_name, messages):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  """
22
+ Save the chat history to a JSON file.
 
 
 
 
 
 
 
23
  """
24
+ file_path = os.path.join(CHAT_HISTORY_DIR, f"{session_name}.json")
25
+ with open(file_path, "w") as f:
26
+ json.dump(messages, f)
27
 
28
+ def load_chat_history(file_name):
29
+ """
30
+ Load the chat history from a JSON file.
31
+ """
32
+ file_path = os.path.join(CHAT_HISTORY_DIR, file_name)
33
+ with open(file_path, "r") as f:
34
+ return json.load(f)
35
 
36
+ def get_saved_sessions():
37
+ """
38
+ Get the list of saved chat sessions.
39
  """
40
+ return [f.replace(".json", "") for f in os.listdir(CHAT_HISTORY_DIR) if f.endswith(".json")]
41
+
42
+ # Sidebar Configuration
43
+ with st.sidebar:
44
+ st.title("๐Ÿ“‚ Sessions")
45
+ saved_sessions = get_saved_sessions()
46
 
47
+ # Display saved sessions
48
+ if saved_sessions:
49
+ selected_session = st.radio("Load a past session:", saved_sessions)
50
+ if st.button("Load Session"):
51
+ st.session_state["messages"] = load_chat_history(f"{selected_session}.json")
52
+ st.success(f"Loaded session: {selected_session}")
53
+ else:
54
+ st.write("No saved sessions yet.")
55
 
56
+ # Create new session
57
+ if st.button("Start New Session"):
58
+ session_name = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
59
+ st.session_state["messages"] = [
60
+ {"role": "system", "content": "You are DUBS, a helpful assistant capable of conversing in a friendly and knowledgeable way."},
61
+ {"role": "assistant", "content": "Hello! How can I assist you today?"}
62
+ ]
63
+ st.session_state["session_name"] = session_name
64
+ save_chat_history(session_name, st.session_state["messages"])
65
+ st.success(f"New session started: {session_name}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
 
67
  # Chat History Initialization
68
  if "messages" not in st.session_state:
 
70
  {"role": "system", "content": "You are DUBS, a helpful assistant capable of conversing in a friendly and knowledgeable way."},
71
  {"role": "assistant", "content": "Hello! How can I assist you today?"}
72
  ]
73
+ st.session_state["session_name"] = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
74
+ save_chat_history(st.session_state["session_name"], st.session_state["messages"])
75
 
76
  # Main Chat UI
77
  st.title("๐Ÿถ DUBSChat")
 
91
  st.chat_message("user").write(prompt)
92
 
93
  # Serialize chat history for API
94
+ chat_history = "".join(
95
+ [f"<|{msg['role']}|>{msg['content']}<|end|>" for msg in st.session_state["messages"]]
96
+ )
97
 
98
  # Get response from API
99
  with st.spinner("Translating Dubs language (Woof Woof!)"):
100
  assistant_message_placeholder = st.chat_message("assistant").empty()
101
  full_response = ""
102
+ try:
103
+ response = requests.post(
104
+ SPACE_URL,
105
+ json={"prompt": chat_history},
106
+ headers={"Authorization": f"Bearer {API_KEY}"},
107
+ timeout=60,
108
+ )
109
+ response.raise_for_status()
110
+ full_response = response.json().get("response", "Sorry, something went wrong!")
111
+ except requests.exceptions.RequestException as e:
112
+ full_response = f"Error: {e}"
113
+
114
+ assistant_message_placeholder.write(full_response)
115
+
116
+ # Append the assistant's response to the chat history
117
+ st.session_state["messages"].append({"role": "assistant", "content": full_response})
118
+
119
+ # Auto-save the updated chat history
120
+ save_chat_history(st.session_state["session_name"], st.session_state["messages"])