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