Spaces:
Sleeping
Sleeping
File size: 17,383 Bytes
7af9206 | 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 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 | """
streamlit_app.py
----------------
Beautiful Streamlit GUI for the Python Q&A Assistant.
Talks to the FastAPI backend running at localhost:8000.
Run with:
streamlit run streamlit_app.py
(Make sure the FastAPI server is also running: uvicorn main:app --port 8000)
"""
import streamlit as st
import requests
import time
from datetime import datetime
# βββ Page config (MUST be first Streamlit call) ββββββββββββββββββββββββββββββ
st.set_page_config(
page_title="Python Q&A Assistant",
page_icon="π",
layout="wide",
initial_sidebar_state="expanded",
)
API_BASE = "http://localhost:8000"
# βββ Custom CSS βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
st.markdown("""
<style>
/* ββ Google Font ββ */
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Fira+Code:wght@400;500&display=swap');
/* ββ Global ββ */
html, body, [class*="css"] {
font-family: 'Inter', sans-serif;
}
/* ββ Hide default streamlit chrome ββ */
#MainMenu, footer, header { visibility: hidden; }
/* ββ Main background ββ */
.stApp {
background: linear-gradient(135deg, #0a0e1a 0%, #0d1528 50%, #0a1020 100%);
min-height: 100vh;
}
/* ββ Hero header ββ */
.hero {
background: linear-gradient(135deg, #1a2744 0%, #0f1e3d 60%, #162040 100%);
border: 1px solid rgba(99, 179, 237, 0.15);
border-radius: 20px;
padding: 36px 40px 28px;
margin-bottom: 28px;
position: relative;
overflow: hidden;
}
.hero::before {
content: '';
position: absolute;
top: -60px; right: -60px;
width: 200px; height: 200px;
background: radial-gradient(circle, rgba(99,179,237,0.12) 0%, transparent 70%);
border-radius: 50%;
}
.hero-title {
font-size: 2.4rem;
font-weight: 700;
background: linear-gradient(135deg, #63b3ed, #90cdf4, #4299e1);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
margin: 0 0 8px 0;
line-height: 1.2;
}
.hero-subtitle {
color: #94a3b8;
font-size: 1rem;
font-weight: 400;
margin: 0;
}
/* ββ Question input card ββ */
.question-card {
background: rgba(255,255,255,0.04);
border: 1px solid rgba(99, 179, 237, 0.2);
border-radius: 16px;
padding: 24px 28px;
margin-bottom: 20px;
backdrop-filter: blur(10px);
}
/* ββ Answer card ββ */
.answer-card {
background: linear-gradient(135deg, rgba(26,39,68,0.8), rgba(15,30,61,0.9));
border: 1px solid rgba(99, 179, 237, 0.25);
border-left: 4px solid #4299e1;
border-radius: 16px;
padding: 28px 32px;
margin: 16px 0;
backdrop-filter: blur(10px);
animation: fadeIn 0.4s ease;
}
@keyframes fadeIn {
from { opacity: 0; transform: translateY(12px); }
to { opacity: 1; transform: translateY(0); }
}
.answer-text {
color: #e2e8f0;
font-size: 0.97rem;
line-height: 1.75;
}
/* ββ History item ββ */
.history-item {
background: rgba(255,255,255,0.04);
border: 1px solid rgba(255,255,255,0.07);
border-radius: 10px;
padding: 12px 16px;
margin-bottom: 8px;
cursor: pointer;
transition: all 0.2s;
}
.history-item:hover {
border-color: rgba(99,179,237,0.3);
background: rgba(99,179,237,0.05);
}
.history-q {
color: #90cdf4;
font-size: 0.85rem;
font-weight: 500;
margin: 0 0 4px 0;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.history-time {
color: #4a5568;
font-size: 0.75rem;
margin: 0;
}
/* ββ Metric badges ββ */
.metric-row {
display: flex;
gap: 12px;
margin-top: 16px;
flex-wrap: wrap;
}
.metric-badge {
background: rgba(66,153,225,0.12);
border: 1px solid rgba(66,153,225,0.25);
border-radius: 20px;
padding: 5px 14px;
font-size: 0.8rem;
color: #90cdf4;
font-weight: 500;
}
/* ββ Source chip ββ */
.source-chip {
display: inline-block;
background: rgba(72,187,120,0.1);
border: 1px solid rgba(72,187,120,0.25);
border-radius: 6px;
padding: 4px 10px;
font-size: 0.78rem;
color: #68d391;
margin: 3px 3px 3px 0;
}
/* ββ Sidebar ββ */
[data-testid="stSidebar"] {
background: linear-gradient(180deg, #0d1528 0%, #0a0e1a 100%);
border-right: 1px solid rgba(99,179,237,0.1);
}
/* ββ Example button ββ */
.stButton > button {
width: 100%;
background: rgba(255,255,255,0.04) !important;
color: #90cdf4 !important;
border: 1px solid rgba(99,179,237,0.2) !important;
border-radius: 10px !important;
text-align: left !important;
font-size: 0.85rem !important;
padding: 10px 14px !important;
transition: all 0.2s !important;
white-space: normal !important;
height: auto !important;
}
.stButton > button:hover {
background: rgba(99,179,237,0.1) !important;
border-color: rgba(99,179,237,0.4) !important;
transform: translateX(3px) !important;
}
/* ββ Text area ββ */
.stTextArea textarea {
background: rgba(255,255,255,0.05) !important;
border: 1px solid rgba(99,179,237,0.25) !important;
border-radius: 12px !important;
color: #e2e8f0 !important;
font-family: 'Inter', sans-serif !important;
font-size: 0.95rem !important;
resize: none !important;
}
.stTextArea textarea:focus {
border-color: rgba(99,179,237,0.6) !important;
box-shadow: 0 0 0 3px rgba(99,179,237,0.1) !important;
}
/* ββ Submit button override ββ */
div[data-testid="stForm"] .stButton > button {
background: linear-gradient(135deg, #2b6cb0, #3182ce) !important;
color: white !important;
border: none !important;
font-weight: 600 !important;
font-size: 1rem !important;
padding: 14px 28px !important;
border-radius: 12px !important;
letter-spacing: 0.3px !important;
}
div[data-testid="stForm"] .stButton > button:hover {
background: linear-gradient(135deg, #3182ce, #4299e1) !important;
transform: translateY(-1px) !important;
box-shadow: 0 6px 20px rgba(66,153,225,0.35) !important;
}
/* ββ Status dot ββ */
.status-dot {
display: inline-block;
width: 8px; height: 8px;
border-radius: 50%;
background: #48bb78;
margin-right: 6px;
animation: pulse 2s infinite;
}
@keyframes pulse {
0%,100% { opacity: 1; }
50% { opacity: 0.4; }
}
.status-text { color: #68d391; font-size: 0.85rem; font-weight: 500; }
/* ββ Code blocks inside answers ββ */
code { font-family: 'Fira Code', monospace !important; }
/* ββ Expander ββ */
[data-testid="stExpander"] {
background: rgba(255,255,255,0.02) !important;
border: 1px solid rgba(255,255,255,0.07) !important;
border-radius: 10px !important;
}
</style>
""", unsafe_allow_html=True)
# βββ Session state init βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
if "history" not in st.session_state:
st.session_state.history = [] # list of {question, answer, sources, latency, ts}
if "current_question" not in st.session_state:
st.session_state.current_question = ""
if "api_ok" not in st.session_state:
st.session_state.api_ok = False
# βββ Helper: call API βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def ask_api(question: str) -> dict | None:
try:
t0 = time.time()
resp = requests.post(
f"{API_BASE}/ask",
json={"question": question},
timeout=60,
)
elapsed = time.time() - t0
if resp.status_code == 200:
data = resp.json()
data["latency"] = round(elapsed, 2)
return data
else:
st.error(f"API error {resp.status_code}: {resp.text}")
return None
except requests.exceptions.ConnectionError:
st.error("Cannot connect to FastAPI backend. Make sure `uvicorn main:app --port 8000` is running.")
return None
def check_health() -> dict | None:
try:
resp = requests.get(f"{API_BASE}/health", timeout=5)
if resp.status_code == 200:
return resp.json()
except Exception:
pass
return None
# βββ Sidebar ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
with st.sidebar:
st.markdown("### π Python Q&A Assistant")
st.markdown("---")
# Health check
health = check_health()
if health:
st.session_state.api_ok = True
st.markdown(
f'<span class="status-dot"></span>'
f'<span class="status-text">API Online</span>',
unsafe_allow_html=True,
)
st.caption(f"π {health['index_size']:,} Q&As indexed")
st.caption(f"β±οΈ Uptime: {health['uptime_seconds']:.0f}s")
st.caption(f"π’ Requests: {health['requests_served']}")
else:
st.markdown("π΄ API Offline")
st.warning("Start the API:\n```\nuvicorn main:app --port 8000\n```")
st.markdown("---")
st.markdown("#### π‘ Example Questions")
EXAMPLES = [
"How do I reverse a list in Python?",
"What is a Python decorator?",
"How do I handle exceptions in Python?",
"What is the difference between list and tuple?",
"How do I sort a dictionary by value?",
"How do I use *args and **kwargs?",
"What does the yield keyword do?",
"How do I read a CSV file with pandas?",
]
for ex in EXAMPLES:
if st.button(ex, key=f"ex_{ex[:20]}"):
st.session_state.current_question = ex
st.markdown("---")
# History
if st.session_state.history:
st.markdown("#### π Recent Questions")
for i, h in enumerate(reversed(st.session_state.history[-8:])):
st.markdown(
f'<div class="history-item">'
f'<p class="history-q">{h["question"][:60]}{"..." if len(h["question"]) > 60 else ""}</p>'
f'<p class="history-time">{h["ts"]} Β· {h["latency"]}s</p>'
f'</div>',
unsafe_allow_html=True,
)
if st.session_state.history:
if st.button("ποΈ Clear History"):
st.session_state.history = []
st.rerun()
# βββ Main content βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Hero
st.markdown("""
<div class="hero">
<h1 class="hero-title">π Python Q&A Assistant</h1>
<p class="hero-subtitle">
Powered by <strong>Stack Overflow</strong> data Β· <strong>RAG Pipeline</strong> Β·
<strong>Groq LLaMA-3.3-70b</strong> Β· 14,864 real Q&A pairs
</p>
</div>
""", unsafe_allow_html=True)
# βββ Question input form βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
with st.form("question_form", clear_on_submit=False):
question = st.text_area(
"Ask a Python question",
value=st.session_state.current_question,
placeholder="e.g. How do I reverse a list in Python? What is a lambda function? How does GIL work?",
height=110,
label_visibility="collapsed",
)
col1, col2, col3 = st.columns([3, 1, 1])
with col1:
submitted = st.form_submit_button("π Ask Question", use_container_width=True)
with col2:
st.form_submit_button("", disabled=True, use_container_width=True) # spacer
with col3:
pass
# βββ Handle submission ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
if submitted and question.strip():
st.session_state.current_question = question.strip()
with st.spinner("π Searching Stack Overflow knowledge base..."):
result = ask_api(question.strip())
if result:
entry = {
"question": question.strip(),
"answer": result["answer"],
"sources": result.get("sources", []),
"latency": result.get("latency", 0),
"model": result.get("model", ""),
"docs": result.get("docs_retrieved", 5),
"ts": datetime.now().strftime("%H:%M"),
}
st.session_state.history.append(entry)
elif submitted and not question.strip():
st.warning("Please type a question first!")
# βββ Display latest answer ββββββββββββββββββββββββββββββββββββββββββββββββββββ
if st.session_state.history:
latest = st.session_state.history[-1]
st.markdown("---")
# Question bubble
st.markdown(
f"""
<div style="
background: rgba(66,153,225,0.1);
border: 1px solid rgba(66,153,225,0.2);
border-radius: 14px 14px 4px 14px;
padding: 14px 20px;
margin-bottom: 4px;
display: inline-block;
max-width: 80%;
float: right;
clear: both;
">
<span style="color:#90cdf4; font-weight:600; font-size:0.95rem;">
{latest['question']}
</span>
</div>
<div style="clear:both; margin-bottom:16px;"></div>
""",
unsafe_allow_html=True,
)
# Answer card
st.markdown('<div class="answer-card">', unsafe_allow_html=True)
# Metrics row
sources_html = "".join(
f'<span class="source-chip">π {s[:55]}{"..." if len(s)>55 else ""}</span>'
for s in latest["sources"]
)
st.markdown(
f"""
<div class="metric-row">
<span class="metric-badge">β‘ {latest['latency']}s</span>
<span class="metric-badge">π€ {latest['model'].split('-')[0]+'-'+latest['model'].split('-')[1] if '-' in latest['model'] else latest['model']}</span>
<span class="metric-badge">π {latest['docs']} sources</span>
<span class="metric-badge">π {latest['ts']}</span>
</div>
""",
unsafe_allow_html=True,
)
st.markdown("<br>", unsafe_allow_html=True)
# Answer text (rendered as markdown for code highlighting)
st.markdown(latest["answer"])
# Sources expander
if latest["sources"]:
with st.expander("π View Stack Overflow Sources", expanded=False):
for i, src in enumerate(latest["sources"], 1):
st.markdown(
f'<span class="source-chip">#{i} {src}</span>',
unsafe_allow_html=True,
)
st.markdown("</div>", unsafe_allow_html=True)
# ββ Previous Q&As ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
if len(st.session_state.history) > 1:
st.markdown("<br>", unsafe_allow_html=True)
st.markdown("#### π Previous Answers")
for h in reversed(st.session_state.history[:-1]):
with st.expander(f"Q: {h['question'][:80]}... ({h['ts']} Β· {h['latency']}s)"):
st.markdown(h["answer"])
if h["sources"]:
srcs = " ".join(
f'<span class="source-chip">π {s[:50]}</span>'
for s in h["sources"]
)
st.markdown(srcs, unsafe_allow_html=True)
else:
# Empty state
st.markdown("<br>", unsafe_allow_html=True)
col1, col2, col3 = st.columns(3)
cards = [
("π", "RAG Powered", "Retrieves real Stack Overflow answers as context before generating"),
("β‘", "Groq LLaMA 3.3", "Blazing fast inference with the best open-source LLM"),
("π", "14,864 Q&As", "Indexed from 607K Python Stack Overflow questions"),
]
for col, (icon, title, desc) in zip([col1, col2, col3], cards):
with col:
st.markdown(
f"""
<div style="
background: rgba(255,255,255,0.03);
border: 1px solid rgba(255,255,255,0.08);
border-radius: 14px;
padding: 24px 20px;
text-align: center;
height: 160px;
">
<div style="font-size:2rem; margin-bottom:10px;">{icon}</div>
<div style="color:#90cdf4; font-weight:600; font-size:0.95rem; margin-bottom:6px;">{title}</div>
<div style="color:#64748b; font-size:0.82rem; line-height:1.5;">{desc}</div>
</div>
""",
unsafe_allow_html=True,
)
|