CCockrum commited on
Commit
47a03de
Β·
verified Β·
1 Parent(s): 3af8ac2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +19 -76
app.py CHANGED
@@ -1,6 +1,5 @@
1
  import os
2
  import re
3
- import random
4
  import requests
5
  import streamlit as st
6
  from langchain_huggingface import HuggingFaceEndpoint
@@ -21,9 +20,7 @@ if NASA_API_KEY is None:
21
  # βœ… Set Up Streamlit
22
  st.set_page_config(page_title="HAL - NASA ChatBot", page_icon="πŸš€")
23
 
24
- user_input = st.chat_input("Type your message here...") # Make sure this is executed first
25
-
26
- # βœ… Ensure Session State Variables
27
  if "chat_history" not in st.session_state:
28
  st.session_state.chat_history = [{"role": "assistant", "content": "Hello! How can I assist you today?"}]
29
  if "response_ready" not in st.session_state:
@@ -35,7 +32,7 @@ if "follow_up" not in st.session_state:
35
  model_id = "mistralai/Mistral-7B-Instruct-v0.3"
36
 
37
  # βœ… Initialize Hugging Face Model
38
- def get_llm_hf_inference(model_id=model_id, max_new_tokens=1024, temperature=0.7):
39
  return HuggingFaceEndpoint(
40
  repo_id=model_id,
41
  max_new_tokens=max_new_tokens,
@@ -65,28 +62,11 @@ def analyze_sentiment(user_text):
65
 
66
  # βœ… Intent Detection
67
  def predict_action(user_text):
68
- if "NASA" in user_text or "space" in user_text:
69
  return "nasa_info"
70
  return "general_query"
71
 
72
  # βœ… Follow-Up Question Generation
73
- def generate_follow_up(user_text):
74
- prompt_text = f"Based on: '{user_text}', generate a concise, friendly follow-up."
75
- hf = get_llm_hf_inference(max_new_tokens=80, temperature=0.9)
76
- output = hf.invoke(input=prompt_text).strip()
77
- return output if output else "Would you like to explore this topic further?"
78
-
79
- # βœ… Ensure English Responses
80
- def ensure_english(text):
81
- try:
82
- detected_lang = detect(text)
83
- if detected_lang != "en":
84
- return "⚠️ Sorry, I only respond in English. Can you rephrase your question?"
85
- except:
86
- return "⚠️ Language detection failed. Please ask your question again."
87
- return text
88
-
89
- # βœ… Ensure Every Response Has a Follow-Up Question
90
  def generate_follow_up(user_text):
91
  """Generates a clean follow-up question to guide the user toward related topics or next steps."""
92
  prompt_text = (
@@ -98,13 +78,22 @@ def generate_follow_up(user_text):
98
 
99
  hf = get_llm_hf_inference(max_new_tokens=40, temperature=0.8)
100
  output = hf.invoke(input=prompt_text).strip()
101
-
102
  # βœ… Remove unnecessary characters (like backticks and misplaced formatting)
103
  cleaned_output = re.sub(r"```|''|\"", "", output).strip()
104
 
105
  # βœ… Fallback in case the response is empty or invalid
106
  return cleaned_output if cleaned_output else "Would you like to explore another related topic or ask about something else?"
107
 
 
 
 
 
 
 
 
 
 
108
 
109
  # βœ… Main Response Function
110
  def get_response(system_message, chat_history, user_text, max_new_tokens=512):
@@ -155,70 +144,27 @@ def get_response(system_message, chat_history, user_text, max_new_tokens=512):
155
 
156
  return response, follow_up, chat_history, None
157
 
158
- # βœ… Ensure response is displayed
159
- if response:
160
- st.markdown(f"<div class='assistant-msg'><strong>HAL:</strong> {response}</div>", unsafe_allow_html=True)
161
-
162
- # βœ… Save and display follow-up question separately
163
- if follow_up: # πŸ” Here is the `if follow_up:` section
164
- st.session_state.chat_history.append({'role': 'assistant', 'content': follow_up})
165
- st.markdown(f"<div class='assistant-msg'><strong>HAL:</strong> {follow_up}</div>", unsafe_allow_html=True)
166
-
167
-
168
  # βœ… Streamlit UI
169
  st.title("πŸš€ HAL - NASA AI Assistant")
170
 
171
- # βœ… Justify all chatbot responses
172
- st.markdown("""
173
- <style>
174
- .user-msg {
175
- background-color: #696969;
176
- color: white;
177
- padding: 10px;
178
- border-radius: 10px;
179
- margin-bottom: 5px;
180
- width: fit-content;
181
- max-width: 80%;
182
- text-align: justify; /* βœ… Justify text */
183
- }
184
- .assistant-msg {
185
- background-color: #333333;
186
- color: white;
187
- padding: 10px;
188
- border-radius: 10px;
189
- margin-bottom: 5px;
190
- width: fit-content;
191
- max-width: 80%;
192
- text-align: justify; /* βœ… Justify text */
193
- }
194
- .container {
195
- display: flex;
196
- flex-direction: column;
197
- align-items: flex-start;
198
- }
199
- @media (max-width: 600px) {
200
- .user-msg, .assistant-msg { font-size: 16px; max-width: 100%; }
201
- }
202
- </style>
203
- """, unsafe_allow_html=True)
204
-
205
-
206
  # βœ… Reset Chat Button
207
  if st.sidebar.button("Reset Chat"):
208
  st.session_state.chat_history = [{"role": "assistant", "content": "Hello! How can I assist you today?"}]
209
  st.session_state.response_ready = False
210
  st.session_state.follow_up = ""
211
 
 
 
212
 
213
  if user_input:
214
- # βœ… Ensure get_response() returns a response
215
  response, follow_up, st.session_state.chat_history, image_url = get_response(
216
  system_message="You are a helpful AI assistant.",
217
  user_text=user_input,
218
  chat_history=st.session_state.chat_history
219
  )
220
 
221
- # βœ… Set default value if `response` is missing
222
  if not response:
223
  response = "I'm sorry, but I couldn't generate a response."
224
 
@@ -227,14 +173,11 @@ if user_input:
227
 
228
  # βœ… Handle follow-up question
229
  if follow_up:
 
230
  st.markdown(f"<div class='assistant-msg'><strong>HAL:</strong> {follow_up}</div>", unsafe_allow_html=True)
231
 
232
  # βœ… Display NASA image if available
233
  if image_url:
234
  st.image(image_url, caption="NASA Image of the Day")
235
 
236
-
237
- # βœ… Check before displaying follow-up message
238
- if st.session_state.response_ready and st.session_state.follow_up:
239
- st.markdown(f"<div class='assistant-msg'><strong>HAL:</strong> {st.session_state.follow_up}</div>", unsafe_allow_html=True)
240
- st.session_state.response_ready = False
 
1
  import os
2
  import re
 
3
  import requests
4
  import streamlit as st
5
  from langchain_huggingface import HuggingFaceEndpoint
 
20
  # βœ… Set Up Streamlit
21
  st.set_page_config(page_title="HAL - NASA ChatBot", page_icon="πŸš€")
22
 
23
+ # βœ… Initialize Session State Variables
 
 
24
  if "chat_history" not in st.session_state:
25
  st.session_state.chat_history = [{"role": "assistant", "content": "Hello! How can I assist you today?"}]
26
  if "response_ready" not in st.session_state:
 
32
  model_id = "mistralai/Mistral-7B-Instruct-v0.3"
33
 
34
  # βœ… Initialize Hugging Face Model
35
+ def get_llm_hf_inference(model_id=model_id, max_new_tokens=512, temperature=0.7):
36
  return HuggingFaceEndpoint(
37
  repo_id=model_id,
38
  max_new_tokens=max_new_tokens,
 
62
 
63
  # βœ… Intent Detection
64
  def predict_action(user_text):
65
+ if "NASA" in user_text.lower() or "space" in user_text.lower():
66
  return "nasa_info"
67
  return "general_query"
68
 
69
  # βœ… Follow-Up Question Generation
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
  def generate_follow_up(user_text):
71
  """Generates a clean follow-up question to guide the user toward related topics or next steps."""
72
  prompt_text = (
 
78
 
79
  hf = get_llm_hf_inference(max_new_tokens=40, temperature=0.8)
80
  output = hf.invoke(input=prompt_text).strip()
81
+
82
  # βœ… Remove unnecessary characters (like backticks and misplaced formatting)
83
  cleaned_output = re.sub(r"```|''|\"", "", output).strip()
84
 
85
  # βœ… Fallback in case the response is empty or invalid
86
  return cleaned_output if cleaned_output else "Would you like to explore another related topic or ask about something else?"
87
 
88
+ # βœ… Ensure English Responses
89
+ def ensure_english(text):
90
+ try:
91
+ detected_lang = detect(text)
92
+ if detected_lang != "en":
93
+ return "⚠️ Sorry, I only respond in English. Can you rephrase your question?"
94
+ except:
95
+ return "⚠️ Language detection failed. Please ask your question again."
96
+ return text
97
 
98
  # βœ… Main Response Function
99
  def get_response(system_message, chat_history, user_text, max_new_tokens=512):
 
144
 
145
  return response, follow_up, chat_history, None
146
 
 
 
 
 
 
 
 
 
 
 
147
  # βœ… Streamlit UI
148
  st.title("πŸš€ HAL - NASA AI Assistant")
149
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
150
  # βœ… Reset Chat Button
151
  if st.sidebar.button("Reset Chat"):
152
  st.session_state.chat_history = [{"role": "assistant", "content": "Hello! How can I assist you today?"}]
153
  st.session_state.response_ready = False
154
  st.session_state.follow_up = ""
155
 
156
+ # βœ… Chat UI
157
+ user_input = st.chat_input("Type your message here...")
158
 
159
  if user_input:
160
+ # βœ… Ensure `get_response()` is executed BEFORE using `response`
161
  response, follow_up, st.session_state.chat_history, image_url = get_response(
162
  system_message="You are a helpful AI assistant.",
163
  user_text=user_input,
164
  chat_history=st.session_state.chat_history
165
  )
166
 
167
+ # βœ… Ensure `response` is not None before using it
168
  if not response:
169
  response = "I'm sorry, but I couldn't generate a response."
170
 
 
173
 
174
  # βœ… Handle follow-up question
175
  if follow_up:
176
+ st.session_state.chat_history.append({'role': 'assistant', 'content': follow_up})
177
  st.markdown(f"<div class='assistant-msg'><strong>HAL:</strong> {follow_up}</div>", unsafe_allow_html=True)
178
 
179
  # βœ… Display NASA image if available
180
  if image_url:
181
  st.image(image_url, caption="NASA Image of the Day")
182
 
183
+ st.session_state.response_ready = True