Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,106 +1,204 @@
|
|
| 1 |
import os
|
| 2 |
import re
|
| 3 |
import requests
|
|
|
|
| 4 |
import streamlit as st
|
| 5 |
from langchain_huggingface import HuggingFaceEndpoint
|
| 6 |
from langchain_core.prompts import PromptTemplate
|
| 7 |
from langchain_core.output_parsers import StrOutputParser
|
| 8 |
from transformers import pipeline
|
| 9 |
-
from langdetect import detect
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
# β
Environment Variables
|
| 12 |
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
if not HF_TOKEN:
|
| 16 |
raise ValueError("HF_TOKEN is not set. Please add it to your environment variables.")
|
| 17 |
|
| 18 |
-
|
|
|
|
| 19 |
raise ValueError("NASA_API_KEY is not set. Please add it to your environment variables.")
|
| 20 |
|
| 21 |
-
# β
Set Streamlit
|
| 22 |
st.set_page_config(page_title="HAL - NASA ChatBot", page_icon="π")
|
| 23 |
|
| 24 |
-
# β
|
| 25 |
if "chat_history" not in st.session_state:
|
| 26 |
st.session_state.chat_history = [{"role": "assistant", "content": "Hello! How can I assist you today?"}]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
-
# β
|
| 29 |
def get_llm_hf_inference(model_id="mistralai/Mistral-7B-Instruct-v0.3", max_new_tokens=512, temperature=0.7):
|
| 30 |
return HuggingFaceEndpoint(
|
| 31 |
repo_id=model_id,
|
| 32 |
max_new_tokens=max_new_tokens,
|
| 33 |
temperature=temperature,
|
| 34 |
token=HF_TOKEN,
|
| 35 |
-
task="text-generation"
|
|
|
|
| 36 |
)
|
| 37 |
|
| 38 |
-
# β
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
def generate_follow_up(user_text):
|
|
|
|
|
|
|
| 40 |
prompt_text = (
|
| 41 |
f"Given the user's question: '{user_text}', generate a SHORT follow-up question in the format: "
|
| 42 |
-
"'Would you like to learn more about [related topic] or explore something else?'."
|
| 43 |
-
"Ensure it
|
| 44 |
)
|
| 45 |
-
|
| 46 |
-
hf = get_llm_hf_inference(max_new_tokens=30, temperature=0.6)
|
| 47 |
output = hf.invoke(input=prompt_text).strip()
|
| 48 |
|
|
|
|
| 49 |
cleaned_output = re.sub(r"```|''|\"", "", output).strip()
|
| 50 |
|
| 51 |
-
|
|
|
|
|
|
|
| 52 |
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
|
| 59 |
-
#
|
| 60 |
-
|
|
|
|
|
|
|
| 61 |
|
| 62 |
-
# Create prompt
|
| 63 |
prompt = PromptTemplate.from_template(
|
| 64 |
-
"[INST]
|
| 65 |
"User: {user_text}.\n [/INST]\n"
|
| 66 |
-
"AI: Provide a detailed
|
| 67 |
-
"
|
| 68 |
"\nHAL:"
|
| 69 |
)
|
| 70 |
|
| 71 |
chat = prompt | hf.bind(skip_prompt=True) | StrOutputParser(output_key='content')
|
| 72 |
-
response = chat.invoke(input=dict(user_text=user_text, chat_history=filtered_history))
|
| 73 |
response = response.split("HAL:")[-1].strip() if "HAL:" in response else response.strip()
|
| 74 |
|
| 75 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
follow_up = generate_follow_up(user_text)
|
| 77 |
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
|
|
|
| 82 |
|
| 83 |
-
return response, follow_up
|
| 84 |
|
| 85 |
-
# β
|
| 86 |
st.title("π HAL - NASA AI Assistant")
|
| 87 |
|
| 88 |
-
# β
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
|
| 95 |
-
# β
|
| 96 |
user_input = st.chat_input("Type your message here...")
|
| 97 |
|
| 98 |
if user_input:
|
| 99 |
-
response, follow_up = get_response(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
|
| 101 |
-
|
| 102 |
-
st.markdown(f"<div class='assistant-msg'><strong>HAL:</strong> {response}</div>", unsafe_allow_html=True)
|
| 103 |
|
| 104 |
-
|
| 105 |
-
st.markdown(f"<div class='assistant-msg'><strong>HAL:</strong> {follow_up}</div>", unsafe_allow_html=True)
|
|
|
|
| 106 |
|
|
|
|
| 1 |
import os
|
| 2 |
import re
|
| 3 |
import requests
|
| 4 |
+
import torch
|
| 5 |
import streamlit as st
|
| 6 |
from langchain_huggingface import HuggingFaceEndpoint
|
| 7 |
from langchain_core.prompts import PromptTemplate
|
| 8 |
from langchain_core.output_parsers import StrOutputParser
|
| 9 |
from transformers import pipeline
|
| 10 |
+
from langdetect import detect # Ensure this package is installed
|
| 11 |
+
|
| 12 |
+
# β
Check for GPU or Default to CPU
|
| 13 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 14 |
+
print(f"β
Using device: {device}") # Debugging info
|
| 15 |
|
| 16 |
# β
Environment Variables
|
| 17 |
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 18 |
+
if HF_TOKEN is None:
|
|
|
|
|
|
|
| 19 |
raise ValueError("HF_TOKEN is not set. Please add it to your environment variables.")
|
| 20 |
|
| 21 |
+
NASA_API_KEY = os.getenv("NASA_API_KEY")
|
| 22 |
+
if NASA_API_KEY is None:
|
| 23 |
raise ValueError("NASA_API_KEY is not set. Please add it to your environment variables.")
|
| 24 |
|
| 25 |
+
# β
Set Up Streamlit
|
| 26 |
st.set_page_config(page_title="HAL - NASA ChatBot", page_icon="π")
|
| 27 |
|
| 28 |
+
# β
Initialize Session State Variables (Ensuring Chat History Persists)
|
| 29 |
if "chat_history" not in st.session_state:
|
| 30 |
st.session_state.chat_history = [{"role": "assistant", "content": "Hello! How can I assist you today?"}]
|
| 31 |
+
if "response_ready" not in st.session_state:
|
| 32 |
+
st.session_state.response_ready = False
|
| 33 |
+
if "follow_up" not in st.session_state:
|
| 34 |
+
st.session_state.follow_up = ""
|
| 35 |
|
| 36 |
+
# β
Initialize Hugging Face Model (Explicitly Set to CPU/GPU)
|
| 37 |
def get_llm_hf_inference(model_id="mistralai/Mistral-7B-Instruct-v0.3", max_new_tokens=512, temperature=0.7):
|
| 38 |
return HuggingFaceEndpoint(
|
| 39 |
repo_id=model_id,
|
| 40 |
max_new_tokens=max_new_tokens,
|
| 41 |
temperature=temperature,
|
| 42 |
token=HF_TOKEN,
|
| 43 |
+
task="text-generation",
|
| 44 |
+
device=-1 if device == "cpu" else 0 # β
Force CPU (-1) or GPU (0)
|
| 45 |
)
|
| 46 |
|
| 47 |
+
# β
NASA API Function
|
| 48 |
+
def get_nasa_apod():
|
| 49 |
+
url = f"https://api.nasa.gov/planetary/apod?api_key={NASA_API_KEY}"
|
| 50 |
+
response = requests.get(url)
|
| 51 |
+
if response.status_code == 200:
|
| 52 |
+
data = response.json()
|
| 53 |
+
return data.get("url", ""), data.get("title", ""), data.get("explanation", "")
|
| 54 |
+
return "", "NASA Data Unavailable", "I couldn't fetch data from NASA right now."
|
| 55 |
+
|
| 56 |
+
# β
Sentiment Analysis (Now Uses Explicit Device)
|
| 57 |
+
sentiment_analyzer = pipeline(
|
| 58 |
+
"sentiment-analysis",
|
| 59 |
+
model="distilbert/distilbert-base-uncased-finetuned-sst-2-english",
|
| 60 |
+
device=-1 if device == "cpu" else 0 # β
Force CPU (-1) or GPU (0)
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
def analyze_sentiment(user_text):
|
| 64 |
+
result = sentiment_analyzer(user_text)[0]
|
| 65 |
+
return result['label']
|
| 66 |
+
|
| 67 |
+
# β
Intent Detection
|
| 68 |
+
def predict_action(user_text):
|
| 69 |
+
if "NASA" in user_text.lower() or "space" in user_text.lower():
|
| 70 |
+
return "nasa_info"
|
| 71 |
+
return "general_query"
|
| 72 |
+
|
| 73 |
+
# β
Ensure English Responses
|
| 74 |
+
def ensure_english(text):
|
| 75 |
+
try:
|
| 76 |
+
detected_lang = detect(text)
|
| 77 |
+
if detected_lang != "en":
|
| 78 |
+
return "β οΈ Sorry, I only respond in English. Can you rephrase your question?"
|
| 79 |
+
except:
|
| 80 |
+
return "β οΈ Language detection failed. Please ask your question again."
|
| 81 |
+
return text
|
| 82 |
+
|
| 83 |
+
# β
Follow-Up Question Generation
|
| 84 |
def generate_follow_up(user_text):
|
| 85 |
+
"""Generates a structured follow-up question in a concise format."""
|
| 86 |
+
|
| 87 |
prompt_text = (
|
| 88 |
f"Given the user's question: '{user_text}', generate a SHORT follow-up question in the format: "
|
| 89 |
+
"'Would you like to learn more about [related topic] or explore something else?'. "
|
| 90 |
+
"Ensure it's concise and structured exactly as requested without extra commentary."
|
| 91 |
)
|
| 92 |
+
|
| 93 |
+
hf = get_llm_hf_inference(max_new_tokens=30, temperature=0.6) # π₯ Lower temp for consistency
|
| 94 |
output = hf.invoke(input=prompt_text).strip()
|
| 95 |
|
| 96 |
+
# β
Extract the relevant part using regex to remove unwanted symbols or truncations
|
| 97 |
cleaned_output = re.sub(r"```|''|\"", "", output).strip()
|
| 98 |
|
| 99 |
+
# β
Ensure output is formatted correctly
|
| 100 |
+
if "Would you like to learn more about" not in cleaned_output:
|
| 101 |
+
cleaned_output = "Would you like to explore another related topic or ask about something else?"
|
| 102 |
|
| 103 |
+
return cleaned_output
|
| 104 |
+
|
| 105 |
+
# β
Main Response Function
|
| 106 |
+
def get_response(system_message, chat_history, user_text, max_new_tokens=512):
|
| 107 |
+
action = predict_action(user_text)
|
| 108 |
+
|
| 109 |
+
# β
Handle NASA-Specific Queries
|
| 110 |
+
if action == "nasa_info":
|
| 111 |
+
nasa_url, nasa_title, nasa_explanation = get_nasa_apod()
|
| 112 |
+
response = f"**{nasa_title}**\n\n{nasa_explanation}"
|
| 113 |
+
follow_up = generate_follow_up(user_text)
|
| 114 |
+
chat_history.extend([
|
| 115 |
+
{'role': 'user', 'content': user_text},
|
| 116 |
+
{'role': 'assistant', 'content': response},
|
| 117 |
+
{'role': 'assistant', 'content': follow_up}
|
| 118 |
+
])
|
| 119 |
+
return response, follow_up, chat_history, nasa_url
|
| 120 |
|
| 121 |
+
# β
Invoke Hugging Face Model
|
| 122 |
+
hf = get_llm_hf_inference(max_new_tokens=max_new_tokens, temperature=0.9)
|
| 123 |
+
|
| 124 |
+
filtered_history = "\n".join(f"{msg['role']}: {msg['content']}" for msg in chat_history)
|
| 125 |
|
|
|
|
| 126 |
prompt = PromptTemplate.from_template(
|
| 127 |
+
"[INST] {system_message}\n\nCurrent Conversation:\n{chat_history}\n\n"
|
| 128 |
"User: {user_text}.\n [/INST]\n"
|
| 129 |
+
"AI: Provide a detailed explanation. Use a conversational tone. "
|
| 130 |
+
"π¨ Answer **only in English**."
|
| 131 |
"\nHAL:"
|
| 132 |
)
|
| 133 |
|
| 134 |
chat = prompt | hf.bind(skip_prompt=True) | StrOutputParser(output_key='content')
|
| 135 |
+
response = chat.invoke(input=dict(system_message=system_message, user_text=user_text, chat_history=filtered_history))
|
| 136 |
response = response.split("HAL:")[-1].strip() if "HAL:" in response else response.strip()
|
| 137 |
|
| 138 |
+
response = ensure_english(response)
|
| 139 |
+
|
| 140 |
+
if not response:
|
| 141 |
+
response = "I'm sorry, but I couldn't generate a response. Can you rephrase your question?"
|
| 142 |
+
|
| 143 |
follow_up = generate_follow_up(user_text)
|
| 144 |
|
| 145 |
+
chat_history.extend([
|
| 146 |
+
{'role': 'user', 'content': user_text},
|
| 147 |
+
{'role': 'assistant', 'content': response},
|
| 148 |
+
{'role': 'assistant', 'content': follow_up}
|
| 149 |
+
])
|
| 150 |
|
| 151 |
+
return response, follow_up, chat_history, None
|
| 152 |
|
| 153 |
+
# β
Streamlit UI
|
| 154 |
st.title("π HAL - NASA AI Assistant")
|
| 155 |
|
| 156 |
+
# β
Justify all chatbot responses
|
| 157 |
+
st.markdown("""
|
| 158 |
+
<style>
|
| 159 |
+
.user-msg, .assistant-msg {
|
| 160 |
+
padding: 10px;
|
| 161 |
+
border-radius: 10px;
|
| 162 |
+
margin-bottom: 5px;
|
| 163 |
+
width: fit-content;
|
| 164 |
+
max-width: 80%;
|
| 165 |
+
text-align: justify;
|
| 166 |
+
}
|
| 167 |
+
.user-msg { background-color: #696969; color: white; }
|
| 168 |
+
.assistant-msg { background-color: #333333; color: white; }
|
| 169 |
+
.container { display: flex; flex-direction: column; align-items: flex-start; }
|
| 170 |
+
@media (max-width: 600px) { .user-msg, .assistant-msg { font-size: 16px; max-width: 100%; } }
|
| 171 |
+
</style>
|
| 172 |
+
""", unsafe_allow_html=True)
|
| 173 |
+
|
| 174 |
+
# β
Reset Chat Button
|
| 175 |
+
if st.sidebar.button("Reset Chat"):
|
| 176 |
+
st.session_state.chat_history = [{"role": "assistant", "content": "Hello! How can I assist you today?"}]
|
| 177 |
+
st.session_state.response_ready = False
|
| 178 |
+
st.session_state.follow_up = ""
|
| 179 |
|
| 180 |
+
# β
Chat UI
|
| 181 |
user_input = st.chat_input("Type your message here...")
|
| 182 |
|
| 183 |
if user_input:
|
| 184 |
+
response, follow_up, st.session_state.chat_history, image_url = get_response(
|
| 185 |
+
system_message="You are a helpful AI assistant.",
|
| 186 |
+
user_text=user_input,
|
| 187 |
+
chat_history=st.session_state.chat_history
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
if response:
|
| 191 |
+
st.markdown(f"<div class='assistant-msg'><strong>HAL:</strong> {response}</div>", unsafe_allow_html=True)
|
| 192 |
+
|
| 193 |
+
if follow_up:
|
| 194 |
+
st.markdown(f"<div class='assistant-msg'><strong>HAL:</strong> {follow_up}</div>", unsafe_allow_html=True)
|
| 195 |
+
|
| 196 |
+
if image_url:
|
| 197 |
+
st.image(image_url, caption="NASA Image of the Day")
|
| 198 |
|
| 199 |
+
st.session_state.response_ready = True
|
|
|
|
| 200 |
|
| 201 |
+
if st.session_state.response_ready and st.session_state.follow_up:
|
| 202 |
+
st.markdown(f"<div class='assistant-msg'><strong>HAL:</strong> {st.session_state.follow_up}</div>", unsafe_allow_html=True)
|
| 203 |
+
st.session_state.response_ready = False
|
| 204 |
|