abanm commited on
Commit
6685e19
·
verified ·
1 Parent(s): e8e7572

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +124 -6
app.py CHANGED
@@ -9,6 +9,7 @@ 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
 
13
  # Ensure the directory exists
14
  try:
@@ -16,10 +17,10 @@ try:
16
  except OSError as e:
17
  st.error(f"Failed to create chat history directory: {e}")
18
 
19
- # Streamlit Configurations (must come first)
20
  st.set_page_config(page_title="🐶 DUBSChat", layout="wide")
21
 
22
- # Add custom CSS for background and positioning
23
  st.markdown(
24
  """
25
  <style>
@@ -38,25 +39,142 @@ st.markdown(
38
  unsafe_allow_html=True,
39
  )
40
 
41
- # Display the image in the corner
42
- image_path = "/Problems.png" # Static path to the image
43
  st.markdown(
44
- f'<img src="{image_path}" class="corner-image">',
45
  unsafe_allow_html=True,
46
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  # Sidebar Configuration
48
  with st.sidebar:
49
  st.title("📂 Dubs Recall")
 
50
  dubs_key = st.text_input("Enter Dubs Key", key="chatbot_api_key", type="password")
51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  # Chat History Initialization
53
  if "messages" not in st.session_state:
54
  st.session_state["messages"] = [
55
  {"role": "system", "content": "You are DUBS, a helpful assistant capable of conversing in a friendly and knowledgeable way."},
56
  {"role": "assistant", "content": "Hello! How can I assist you today?"}
57
  ]
 
 
58
 
 
59
  st.title("🐶 DUBSChat")
60
  st.markdown("Empowering you with a Sustainable AI")
61
 
62
- # Rest of the Chat App Code Here...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 = "/Problems.png" # Static path to the corner image
13
 
14
  # Ensure the directory exists
15
  try:
 
17
  except OSError as e:
18
  st.error(f"Failed to create chat history directory: {e}")
19
 
20
+ # Streamlit Configurations
21
  st.set_page_config(page_title="🐶 DUBSChat", layout="wide")
22
 
23
+ # Add custom CSS for background and corner image positioning
24
  st.markdown(
25
  """
26
  <style>
 
39
  unsafe_allow_html=True,
40
  )
41
 
42
+ # Display the static image in the corner
 
43
  st.markdown(
44
+ f'<img src="{IMAGE_PATH}" class="corner-image">',
45
  unsafe_allow_html=True,
46
  )
47
+
48
+ # Utility Functions
49
+ def save_chat_history(session_name, messages):
50
+ """
51
+ Save the chat history to a JSON file.
52
+ """
53
+ file_path = os.path.join(CHAT_HISTORY_DIR, f"{session_name}.json")
54
+ try:
55
+ with open(file_path, "w") as f:
56
+ json.dump(messages, f)
57
+ except IOError as e:
58
+ st.error(f"Failed to save chat history: {e}")
59
+
60
+
61
+ def load_chat_history(file_name):
62
+ """
63
+ Load the chat history from a JSON file.
64
+ """
65
+ file_path = os.path.join(CHAT_HISTORY_DIR, file_name)
66
+ try:
67
+ with open(file_path, "r") as f:
68
+ return json.load(f)
69
+ except (FileNotFoundError, json.JSONDecodeError):
70
+ st.error("Failed to load chat history. Starting with a new session.")
71
+ return []
72
+
73
+
74
+ def get_saved_sessions():
75
+ """
76
+ Get the list of saved chat sessions.
77
+ """
78
+ return [f.replace(".json", "") for f in os.listdir(CHAT_HISTORY_DIR) if f.endswith(".json")]
79
+
80
+
81
  # Sidebar Configuration
82
  with st.sidebar:
83
  st.title("📂 Dubs Recall")
84
+ saved_sessions = get_saved_sessions()
85
  dubs_key = st.text_input("Enter Dubs Key", key="chatbot_api_key", type="password")
86
 
87
+ # Display saved sessions
88
+ if saved_sessions:
89
+ selected_session = st.radio("Past Sessions:", saved_sessions)
90
+ if st.button("Load Session"):
91
+ st.session_state["messages"] = load_chat_history(f"{selected_session}.json")
92
+ st.session_state["session_name"] = selected_session
93
+ st.success(f"Loaded session: {selected_session}")
94
+ else:
95
+ st.write("No past sessions available.")
96
+
97
+ # Reset chat
98
+ if st.button("🔄 Reset Chat"):
99
+ st.session_state["messages"] = [
100
+ {"role": "system", "content": "You are DUBS, a helpful assistant capable of conversing in a friendly and knowledgeable way."},
101
+ {"role": "assistant", "content": "Hello! How can I assist you today?"}
102
+ ]
103
+ st.session_state["session_name"] = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
104
+ save_chat_history(st.session_state["session_name"], st.session_state["messages"])
105
+ st.success("Chat reset and new session started.")
106
+
107
  # Chat History Initialization
108
  if "messages" not in st.session_state:
109
  st.session_state["messages"] = [
110
  {"role": "system", "content": "You are DUBS, a helpful assistant capable of conversing in a friendly and knowledgeable way."},
111
  {"role": "assistant", "content": "Hello! How can I assist you today?"}
112
  ]
113
+ if "session_name" not in st.session_state:
114
+ st.session_state["session_name"] = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
115
 
116
+ # Main Chat UI
117
  st.title("🐶 DUBSChat")
118
  st.markdown("Empowering you with a Sustainable AI")
119
 
120
+ # Display Chat History
121
+ for message in st.session_state["messages"]:
122
+ if message["role"] == "user":
123
+ st.chat_message("user").write(message["content"])
124
+ elif message["role"] == "assistant":
125
+ st.chat_message("assistant").write(message["content"])
126
+
127
+ # User Input
128
+ if prompt := st.chat_input():
129
+ if not dubs_key:
130
+ st.warning("Please provide a valid Dubs Key.")
131
+ else:
132
+ # Append the user's message to the chat history
133
+ st.session_state["messages"].append({"role": "user", "content": prompt})
134
+ st.chat_message("user").write(prompt)
135
+
136
+ # Serialize chat history for API
137
+ chat_history = "".join(
138
+ [f"<|{msg['role']}|>{msg['content']}<|end|>" for msg in st.session_state["messages"]]
139
+ )
140
+
141
+ # Stream response
142
+ with st.spinner("Dubs is thinking... Woof Woof! 🐾"):
143
+ assistant_message_placeholder = st.chat_message("assistant").empty()
144
+
145
+ # Function to stream the response
146
+ def stream_response():
147
+ try:
148
+ response = requests.post(
149
+ SPACE_URL,
150
+ json={"prompt": chat_history},
151
+ headers={"Authorization": f"Bearer {dubs_key}"},
152
+ stream=True, # Enable streaming
153
+ timeout=120,
154
+ )
155
+ response.raise_for_status()
156
+
157
+ # Process and yield only the response field
158
+ for line in response.iter_lines():
159
+ if line:
160
+ data = json.loads(line.decode("utf-8"))
161
+ yield data.get("response", "")
162
+ except requests.exceptions.Timeout:
163
+ yield "The request timed out. Please try again later."
164
+ except requests.exceptions.RequestException as e:
165
+ yield f"Error: {e}"
166
+ except json.JSONDecodeError:
167
+ yield "Error decoding server response."
168
+
169
+ # Update assistant's message incrementally
170
+ full_response = ""
171
+ for chunk in stream_response():
172
+ full_response += chunk
173
+ assistant_message_placeholder.write(full_response)
174
+
175
+ # Append the assistant's final response to the chat history
176
+ st.session_state["messages"].append({"role": "assistant", "content": full_response})
177
+
178
+ # Auto-save the updated chat history
179
+ save_chat_history(st.session_state["session_name"], st.session_state["messages"])
180
+