-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstream_app.py
More file actions
381 lines (319 loc) Β· 10.8 KB
/
stream_app.py
File metadata and controls
381 lines (319 loc) Β· 10.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
# app.py
import os
import streamlit as st
from dotenv import load_dotenv
from langchain_community.embeddings import HuggingFaceEmbeddings
from langchain_community.vectorstores import FAISS
from groq import Groq
import requests
# Load environment variables
load_dotenv()
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
NASA_API_KEY = os.getenv("NASA_API_KEY")
# Page config
st.set_page_config(
page_title="Space AI Assistant",
page_icon="assets/spacegenai_logo.png",
layout="wide"
)
# Custom CSS
st.markdown("""
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
<style>
/* Apply Inter globally */
* {
font-family: 'Inter', sans-serif;
}
/* Subtle animated gradient background */
.stApp {
background: linear-gradient(135deg, #0f0f23 0%, #1a1a2e 50%, #0f0f23 100%);
background-size: 200% 200%;
animation: subtleGradient 15s ease infinite;
color: #e2e8f0;
}
@keyframes subtleGradient {
0% { background-position: 0% 50%; }
50% { background-position: 100% 50%; }
100% { background-position: 0% 50%; }
}
.main {
background: transparent;
color: #e2e8f0;
}
/* Headers with subtle glow */
h1 {
font-family: 'Inter', sans-serif;
color: #818cf8;
font-weight: 700;
font-size: 2.5rem;
text-shadow: 0 0 20px rgba(129, 140, 248, 0.3);
animation: softGlow 3s ease-in-out infinite alternate;
}
@keyframes softGlow {
from { text-shadow: 0 0 15px rgba(129, 140, 248, 0.2); }
to { text-shadow: 0 0 25px rgba(129, 140, 248, 0.4); }
}
h2 {
font-family: 'Inter', sans-serif;
color: #a5b4fc;
font-weight: 600;
font-size: 2rem;
text-shadow: 0 0 10px rgba(165, 180, 252, 0.2);
}
h3 {
font-family: 'Inter', sans-serif;
color: #c7d2fe;
font-weight: 600;
font-size: 1.5rem;
}
/* Body text */
p, div, span, label {
font-family: 'Inter', sans-serif;
font-weight: 400;
font-size: 1rem;
color: #e2e8f0;
}
/* Text input with subtle effects */
.stTextInput>div>div>input {
background: #1a1a2e;
color: #e2e8f0;
border: 1px solid #4c1d95;
border-radius: 8px;
padding: 10px;
font-family: 'Inter', sans-serif;
transition: all 0.3s ease;
}
.stTextInput>div>div>input:focus {
border-color: #6366f1;
box-shadow: 0 0 15px rgba(99, 102, 241, 0.3);
background: #1f1f33;
}
/* Chat input */
.stChatInputContainer {
background: rgba(26, 26, 46, 0.8);
border-top: 1px solid #4c1d95;
backdrop-filter: blur(10px);
}
/* Buttons with gradient and hover */
.stButton>button {
background: linear-gradient(135deg, #4c1d95 0%, #5b21b6 100%);
color: white;
border: none;
border-radius: 8px;
padding: 10px 20px;
font-family: 'Inter', sans-serif;
font-weight: 600;
transition: all 0.3s ease;
box-shadow: 0 2px 10px rgba(76, 29, 149, 0.3);
}
.stButton>button:hover {
background: linear-gradient(135deg, #6366f1 0%, #7c3aed 100%);
transform: translateY(-2px);
box-shadow: 0 4px 15px rgba(99, 102, 241, 0.4);
}
/* Chat messages with subtle backdrop */
.stChatMessage {
background: rgba(26, 26, 46, 0.6);
border: 1px solid rgba(76, 29, 149, 0.5);
border-radius: 10px;
padding: 15px;
font-family: 'Inter', sans-serif;
backdrop-filter: blur(5px);
}
/* Sidebar with gradient */
[data-testid="stSidebar"] {
background: linear-gradient(180deg, #0f0f23 0%, #1a1a2e 100%);
border-right: 1px solid #4c1d95;
}
/* Divider with subtle glow */
hr {
border: none;
height: 1px;
background: linear-gradient(90deg, transparent, #4c1d95, transparent);
box-shadow: 0 0 5px rgba(76, 29, 149, 0.3);
margin: 20px 0;
}
/* Spinner */
.stSpinner > div {
border-color: #4c1d95 !important;
border-top-color: #6366f1 !important;
}
/* Links */
a {
color: #818cf8;
text-decoration: none;
transition: all 0.2s;
}
a:hover {
color: #a5b4fc;
text-shadow: 0 0 8px rgba(129, 140, 248, 0.4);
}
/* Images with subtle border glow */
.stImage {
border-radius: 10px;
border: 1px solid #4c1d95;
box-shadow: 0 2px 15px rgba(76, 29, 149, 0.2);
transition: all 0.3s ease;
}
.stImage:hover {
box-shadow: 0 4px 20px rgba(99, 102, 241, 0.3);
}
/* Columns */
[data-testid="column"] {
background: rgba(26, 26, 46, 0.3);
border-radius: 10px;
padding: 15px;
backdrop-filter: blur(5px);
}
/* Alert boxes */
.stAlert {
background: rgba(76, 29, 149, 0.15);
border: 1px solid #4c1d95;
border-radius: 8px;
backdrop-filter: blur(10px);
}
/* Code blocks */
code {
background: #1a1a2e;
color: #818cf8;
padding: 2px 6px;
border-radius: 4px;
border: 1px solid rgba(76, 29, 149, 0.5);
font-family: 'Monaco', monospace;
}
/* Scrollbar */
::-webkit-scrollbar {
width: 10px;
}
::-webkit-scrollbar-track {
background: #1a1a2e;
}
::-webkit-scrollbar-thumb {
background: #4c1d95;
border-radius: 5px;
}
::-webkit-scrollbar-thumb:hover {
background: #6366f1;
}
</style>
""", unsafe_allow_html=True)
# Initialize session state
if 'messages' not in st.session_state:
st.session_state.messages = []
if 'vectorstore' not in st.session_state:
with st.spinner("π Loading AI models..."):
embeddings = HuggingFaceEmbeddings(
model_name="sentence-transformers/all-MiniLM-L6-v2"
)
st.session_state.vectorstore = FAISS.load_local(
"embeddings/faiss_index",
embeddings,
allow_dangerous_deserialization=True
)
st.session_state.groq_client = Groq(api_key=GROQ_API_KEY)
# Functions
def get_nasa_apod():
"""Fetch today's Astronomy Picture of the Day"""
try:
url = f"https://api.nasa.gov/planetary/apod?api_key={NASA_API_KEY}"
response = requests.get(url)
data = response.json()
return {
'title': data.get('title'),
'url': data.get('url'),
'explanation': data.get('explanation'),
'media_type': data.get('media_type', 'image')
}
except Exception as e:
return None
def search_knowledge_base(query, k=3):
"""Search FAISS index for relevant information"""
docs = st.session_state.vectorstore.similarity_search(query, k=k)
context = "\n\n".join([doc.page_content for doc in docs])
return context
def generate_response(user_question, context):
"""Generate response using Groq LLM"""
system_prompt = """You are a helpful space and astronomy assistant.
Use the provided context to answer questions about space, NASA, astronomy, and related topics.
Be conversational, enthusiastic, and educational. Keep responses concise but informative."""
user_prompt = f"""Context from knowledge base:
{context}
User question: {user_question}
Please provide a helpful and engaging answer."""
chat_completion = st.session_state.groq_client.chat.completions.create(
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt}
],
model="llama-3.3-70b-versatile", # β Change this line
temperature=0.7,
max_tokens=500
)
return chat_completion.choices[0].message.content
# App Layout
st.title("Space AI Assistant")
st.markdown("### Your personal guide to the cosmos powered by GenAI + NASA")
# Sidebar
with st.sidebar:
st.header("π Features")
st.markdown("""
- **Chat** about space, astronomy, NASA
- **RAG-powered** answers from curated space data
- **NASA APOD** - Astronomy Picture of the Day
- **Powered by** Groq LLaMA 3.1
""")
st.divider()
if st.button("πΈ Show Today's APOD", use_container_width=True):
with st.spinner("Fetching APOD..."):
apod = get_nasa_apod()
if apod:
st.session_state.show_apod = apod
st.divider()
if st.button("ποΈ Clear Chat", use_container_width=True):
st.session_state.messages = []
st.rerun()
# Display APOD if requested
if 'show_apod' in st.session_state and st.session_state.show_apod:
apod = st.session_state.show_apod
st.subheader(f"πΈ {apod['title']}")
col1, col2 = st.columns([2, 1])
with col1:
if apod['media_type'] == 'image':
st.image(apod['url'], use_container_width=True)
else:
st.video(apod['url'])
with col2:
st.markdown(apod['explanation'])
st.divider()
# Chat interface
st.subheader("π¬ Chat with the Space Assistant")
# Display chat messages
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])
# Chat input
if prompt := st.chat_input("Ask me anything about space..."):
# Add user message
st.session_state.messages.append({"role": "user", "content": prompt})
with st.chat_message("user"):
st.markdown(prompt)
# Generate response
with st.chat_message("assistant"):
with st.spinner("π€ Thinking..."):
# Search knowledge base
context = search_knowledge_base(prompt)
# Generate response
response = generate_response(prompt, context)
st.markdown(response)
# Add assistant response to history
st.session_state.messages.append({"role": "assistant", "content": response})
# Footer
st.divider()
st.markdown("""
<div style='text-align: center; color: #60a5fa;'>
<p>π Built with Streamlit β’ Powered by Groq LLaMA 3.1 β’ NASA API Integration</p>
<p>GenAI Project with RAG (Retrieval-Augmented Generation)</p>
</div>
""", unsafe_allow_html=True)