abanm commited on
Commit
fbb95dd
·
verified ·
1 Parent(s): f3ac531

Update app.py

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