ZunairaHawwar commited on
Commit
8b942d6
Β·
verified Β·
1 Parent(s): b6e8b03

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -288
app.py CHANGED
@@ -299,7 +299,7 @@ def get_rag_system():
299
  return LangChainRAGSystem()
300
 
301
  def main():
302
- """Main Streamlit application with enhanced UI."""
303
  st.set_page_config(
304
  page_title="EduBot for iCodeGuru",
305
  page_icon="πŸŽ“",
@@ -307,316 +307,89 @@ def main():
307
  initial_sidebar_state="expanded"
308
  )
309
 
310
- # Custom CSS for better styling
311
- st.markdown("""
312
- <style>
313
- .main-header {
314
- background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
315
- padding: 2rem;
316
- border-radius: 10px;
317
- margin-bottom: 2rem;
318
- text-align: center;
319
- }
320
- .main-header h1 {
321
- color: white;
322
- margin: 0;
323
- font-size: 2.5rem;
324
- }
325
- .main-header p {
326
- color: #f0f0f0;
327
- margin: 0.5rem 0 0 0;
328
- font-size: 1.1rem;
329
- }
330
- .metric-card {
331
- background: #f8f9fa;
332
- padding: 1rem;
333
- border-radius: 10px;
334
- border-left: 4px solid #667eea;
335
- margin: 0.5rem 0;
336
- }
337
- .status-online {
338
- color: #28a745;
339
- font-weight: bold;
340
- }
341
- .status-offline {
342
- color: #dc3545;
343
- font-weight: bold;
344
- }
345
- .chat-input {
346
- position: fixed;
347
- bottom: 0;
348
- background: white;
349
- padding: 1rem;
350
- border-top: 1px solid #e0e0e0;
351
- }
352
- .source-card {
353
- background: #f8f9fa;
354
- border: 1px solid #e9ecef;
355
- border-radius: 8px;
356
- padding: 0.8rem;
357
- margin: 0.3rem 0;
358
- }
359
- .quick-action-btn {
360
- background: linear-gradient(45deg, #667eea, #764ba2);
361
- color: white;
362
- border: none;
363
- padding: 0.5rem 1rem;
364
- border-radius: 20px;
365
- margin: 0.2rem;
366
- }
367
- </style>
368
- """, unsafe_allow_html=True)
369
-
370
- # Enhanced Header
371
- st.markdown("""
372
- <div class="main-header">
373
- <h1>πŸŽ“ EduBot for iCodeGuru</h1>
374
- <p>Powered by LangChain | Ask questions based on iCodeGuru's knowledge base</p>
375
- </div>
376
- """, unsafe_allow_html=True)
377
 
378
  # Initialize RAG system
379
  rag_system = get_rag_system()
380
 
381
- # Enhanced Sidebar
382
  with st.sidebar:
383
- st.markdown("### βš™οΈ Control Panel")
384
-
385
- # Status indicator
386
- if rag_system.vectorstore:
387
- try:
388
- doc_count = rag_system.vectorstore._collection.count()
389
- if doc_count > 0:
390
- st.markdown('<p class="status-online">🟒 System Online</p>', unsafe_allow_html=True)
391
- else:
392
- st.markdown('<p class="status-offline">πŸ”΄ No Knowledge Base</p>', unsafe_allow_html=True)
393
- except:
394
- st.markdown('<p class="status-offline">🟑 System Loading</p>', unsafe_allow_html=True)
395
-
396
- st.markdown("---")
397
-
398
- # Admin Actions
399
- col1, col2 = st.columns(2)
400
- with col1:
401
- if st.button("πŸ”„ Refresh KB", type="primary", use_container_width=True):
402
- with st.spinner("Loading documents..."):
403
- success = rag_system.ingest_documents()
404
- if success:
405
- st.balloons()
406
- st.success("Knowledge base updated!")
407
- st.rerun()
408
 
409
- with col2:
410
- if st.button("πŸ—‘οΈ Clear Chat", use_container_width=True):
411
- rag_system.reset_conversation()
412
- st.session_state.messages = []
413
- st.rerun()
414
 
415
- # Quick Actions
416
- st.markdown("### ⚑ Quick Actions")
417
- if st.button("πŸ“š Browse Available Content", use_container_width=True):
418
- st.session_state.show_topics = True
419
-
420
- if st.button("πŸ’‘ Get Sample Question", use_container_width=True):
421
- random_questions = [
422
- "What tutorials are available in iCodeGuru?",
423
- "Show me resources about web development",
424
- "What programming languages does iCodeGuru cover?",
425
- "Find me beginner-friendly content",
426
- "What are the latest tutorials added?"
427
- ]
428
- import random
429
- random_q = random.choice(random_questions)
430
- st.session_state.messages.append({"role": "user", "content": f"🎲 {random_q}"})
431
- st.rerun()
432
 
433
  st.markdown("---")
 
434
 
435
- # Enhanced System Info
436
- st.markdown("### πŸ“Š System Statistics")
437
-
438
  if rag_system.vectorstore:
439
  try:
440
  doc_count = rag_system.vectorstore._collection.count()
441
- st.markdown(f"""
442
- <div class="metric-card">
443
- <strong>πŸ“„ Documents:</strong><br>
444
- <span style="font-size: 1.5rem; color: #667eea;">{doc_count}</span>
445
- </div>
446
- """, unsafe_allow_html=True)
447
  except:
448
- st.markdown("""
449
- <div class="metric-card">
450
- <strong>πŸ“„ Documents:</strong><br>
451
- <span style="color: #dc3545;">N/A</span>
452
- </div>
453
- """, unsafe_allow_html=True)
454
-
455
- # Conversation count
456
- chat_count = len([msg for msg in st.session_state.get("messages", []) if msg["role"] == "user"])
457
- st.markdown(f"""
458
- <div class="metric-card">
459
- <strong>πŸ’¬ Questions Asked:</strong><br>
460
- <span style="font-size: 1.5rem; color: #28a745;">{chat_count}</span>
461
- </div>
462
- """, unsafe_allow_html=True)
463
-
464
- st.markdown("---")
465
-
466
- # Tech Stack
467
- st.markdown("### πŸ› οΈ Technology Stack")
468
- tech_stack = {
469
- "🧠": "ChromaDB",
470
- "⚑": "Groq LLM",
471
- "πŸ”—": "LangChain",
472
- "🎨": "Streamlit",
473
- "πŸ€—": "HuggingFace"
474
- }
475
-
476
- for icon, tech in tech_stack.items():
477
- st.markdown(f"{icon} **{tech}**")
478
 
479
  st.markdown("---")
480
- st.markdown("*Built with ❀️ for iCodeGuru community*")
481
-
482
- # Main Content Area
483
- # Initialize session state
484
- if "messages" not in st.session_state:
485
- st.session_state.messages = []
486
- if "show_topics" not in st.session_state:
487
- st.session_state.show_topics = False
488
 
489
- # Welcome message for new users
490
- if len(st.session_state.messages) == 0:
491
- st.markdown("""
492
- ### πŸ‘‹ Welcome to iCodeGuru EduBot!
493
-
494
- I'm your knowledge assistant for iCodeGuru content. I can help you find:
495
- - **Tutorials and courses** from iCodeGuru
496
- - **Specific topics** and learning materials
497
- - **Resources and references** from the knowledge base
498
- - **Answers** based on iCodeGuru's educational content
499
-
500
- πŸš€ **Ask me anything about iCodeGuru's content!**
501
- """)
502
-
503
- # Sample questions
504
- st.markdown("### πŸ’‘ Try these sample questions:")
505
- sample_questions = [
506
- "What tutorials are available?",
507
- "Show me Python resources",
508
- "Find web development content",
509
- "What beginner courses exist?"
510
- ]
511
-
512
- cols = st.columns(2)
513
- for i, question in enumerate(sample_questions):
514
- with cols[i % 2]:
515
- if st.button(f"❓ {question}", key=f"sample_{i}", use_container_width=True):
516
- st.session_state.messages.append({"role": "user", "content": question})
517
- st.rerun()
518
-
519
- # Show topics if requested
520
- if st.session_state.get("show_topics", False):
521
- with st.expander("πŸ“š Available iCodeGuru Content", expanded=True):
522
- st.markdown("""
523
- Based on iCodeGuru's knowledge base, I can help you find:
524
- - **Video Tutorials** and course materials
525
- - **Programming Languages** covered by iCodeGuru
526
- - **Project Examples** and case studies
527
- - **Learning Paths** and structured content
528
- - **Tips and Tricks** from iCodeGuru experts
529
- - **Resource Links** and references
530
-
531
- *Ask me to find specific content from iCodeGuru's library!*
532
- """)
533
- if st.button("Close Content Browser"):
534
- st.session_state.show_topics = False
535
- st.rerun()
536
-
537
- # Chat History with Enhanced Styling
538
- if st.session_state.messages:
539
- st.markdown("### πŸ’¬ Conversation History")
540
-
541
- for i, message in enumerate(st.session_state.messages):
542
- with st.chat_message(message["role"]):
543
- # Enhanced message display
544
- if message["role"] == "user":
545
- st.markdown(f"**You:** {message['content']}")
546
- else:
547
- st.markdown(message["content"])
548
-
549
- # Enhanced sources display
550
- if "sources" in message and message["sources"]:
551
- with st.expander(f"πŸ“š Sources ({len(message['sources'])} found)", expanded=False):
552
- for j, source in enumerate(message["sources"], 1):
553
- st.markdown(f"""
554
- <div class="source-card">
555
- <strong>Source {j}:</strong><br>
556
- {source}
557
- </div>
558
- """, unsafe_allow_html=True)
559
-
560
- # Enhanced User Input Area
561
  st.markdown("---")
562
 
563
- # Input with suggestions
564
- col1, col2 = st.columns([4, 1])
565
-
566
- with col1:
567
- user_input = st.text_input(
568
- "πŸ’¬ Ask about iCodeGuru content:",
569
- placeholder="e.g., Show me Python tutorials from iCodeGuru",
570
- key="user_input"
571
- )
572
-
573
- with col2:
574
- send_button = st.button("Send πŸš€", type="primary", use_container_width=True)
575
 
576
- # Alternative chat input (modern style)
577
- if prompt := st.chat_input("πŸ’¬ Ask about iCodeGuru's knowledge base..."):
578
- user_input = prompt
579
- send_button = True
 
 
 
 
580
 
581
- # Process user input
582
- if (send_button and user_input) or prompt:
583
- question = user_input if send_button else prompt
584
-
585
- # Add user message
586
- st.session_state.messages.append({"role": "user", "content": question})
587
 
588
  # Display user message
589
  with st.chat_message("user"):
590
- st.markdown(f"**You:** {question}")
591
 
592
- # Get and display assistant response
593
  with st.chat_message("assistant"):
594
- with st.spinner("πŸ€” Let me think about that..."):
595
- response = rag_system.get_answer(question)
596
- answer = response.get("answer", "I couldn't find that information in iCodeGuru's knowledge base.")
597
  source_docs = response.get("source_documents", [])
598
 
599
  st.markdown(answer)
600
 
601
- # Enhanced sources display
602
  if source_docs:
603
  sources = []
604
- for doc in source_docs[:4]: # Show top 4 sources
605
- source_file = doc.metadata.get('source_file', 'Unknown')
606
- content_preview = doc.page_content[:150] + "..." if len(doc.page_content) > 150 else doc.page_content
607
- sources.append(f"**{source_file}**\n{content_preview}")
608
 
609
  if sources:
610
- with st.expander(f"πŸ“š Sources ({len(sources)} found)", expanded=False):
611
  for i, source in enumerate(sources, 1):
612
- st.markdown(f"""
613
- <div class="source-card">
614
- <strong>πŸ“„ Source {i}:</strong><br>
615
- {source}
616
- </div>
617
- """, unsafe_allow_html=True)
618
 
619
- # Add to session state
620
  st.session_state.messages.append({
621
  "role": "assistant",
622
  "content": answer,
@@ -626,19 +399,6 @@ def main():
626
  st.session_state.messages.append({"role": "assistant", "content": answer})
627
  else:
628
  st.session_state.messages.append({"role": "assistant", "content": answer})
629
-
630
- # Clear input and rerun
631
- if send_button:
632
- st.rerun()
633
-
634
- # Footer
635
- st.markdown("---")
636
- st.markdown("""
637
- <div style="text-align: center; color: #666; padding: 1rem;">
638
- <p>πŸŽ“ <strong>EduBot for iCodeGuru</strong> | Your gateway to iCodeGuru's knowledge</p>
639
- <p>Made with ❀️ using Streamlit β€’ LangChain β€’ ChromaDB β€’ Groq</p>
640
- </div>
641
- """, unsafe_allow_html=True)
642
 
643
  if __name__ == "__main__":
644
  main()
 
299
  return LangChainRAGSystem()
300
 
301
  def main():
302
+ """Main Streamlit application."""
303
  st.set_page_config(
304
  page_title="EduBot for iCodeGuru",
305
  page_icon="πŸŽ“",
 
307
  initial_sidebar_state="expanded"
308
  )
309
 
310
+ # Header
311
+ st.title("πŸŽ“ EduBot for @icodeguru0")
312
+ st.markdown("**Powered by LangChain** | Ask anything based on pre-loaded iCodeGuru knowledge.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
313
 
314
  # Initialize RAG system
315
  rag_system = get_rag_system()
316
 
317
+ # Sidebar for admin functions
318
  with st.sidebar:
319
+ st.header("βš™οΈ Admin Panel")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
320
 
321
+ if st.button("πŸ”„ Refresh Knowledge Base", type="primary"):
322
+ success = rag_system.ingest_documents()
323
+ if success:
324
+ st.balloons()
 
325
 
326
+ if st.button("πŸ—‘οΈ Clear Conversation"):
327
+ rag_system.reset_conversation()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
328
 
329
  st.markdown("---")
330
+ st.subheader("πŸ“Š System Info")
331
 
332
+ # Show vectorstore stats
 
 
333
  if rag_system.vectorstore:
334
  try:
335
  doc_count = rag_system.vectorstore._collection.count()
336
+ st.metric("Documents in KB", doc_count)
 
 
 
 
 
337
  except:
338
+ st.metric("Documents in KB", "N/A")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
339
 
340
  st.markdown("---")
341
+ st.caption("🧠 **ChromaDB** for vector storage")
342
+ st.caption("⚑ **Groq LLM** for answers")
343
+ st.caption("πŸ”— **LangChain** for orchestration")
 
 
 
 
 
344
 
345
+ # Main chat interface
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
346
  st.markdown("---")
347
 
348
+ # Initialize session state for chat history
349
+ if "messages" not in st.session_state:
350
+ st.session_state.messages = []
 
 
 
 
 
 
 
 
 
351
 
352
+ # Display chat history
353
+ for message in st.session_state.messages:
354
+ with st.chat_message(message["role"]):
355
+ st.markdown(message["content"])
356
+ if "sources" in message and message["sources"]:
357
+ with st.expander("πŸ“š Sources"):
358
+ for i, source in enumerate(message["sources"], 1):
359
+ st.markdown(f"**Source {i}:** {source}")
360
 
361
+ # User input
362
+ if prompt := st.chat_input("πŸ’¬ Ask your question about iCodeGuru..."):
363
+ # Add user message to chat history
364
+ st.session_state.messages.append({"role": "user", "content": prompt})
 
 
365
 
366
  # Display user message
367
  with st.chat_message("user"):
368
+ st.markdown(prompt)
369
 
370
+ # Get assistant response
371
  with st.chat_message("assistant"):
372
+ with st.spinner("πŸ€” Thinking..."):
373
+ response = rag_system.get_answer(prompt)
374
+ answer = response.get("answer", "No answer available.")
375
  source_docs = response.get("source_documents", [])
376
 
377
  st.markdown(answer)
378
 
379
+ # Show sources if available
380
  if source_docs:
381
  sources = []
382
+ for doc in source_docs[:3]: # Show top 3 sources
383
+ source = doc.metadata.get('source_file', 'Unknown source')
384
+ content_preview = doc.page_content[:100] + "..." if len(doc.page_content) > 100 else doc.page_content
385
+ sources.append(f"{source}: {content_preview}")
386
 
387
  if sources:
388
+ with st.expander("πŸ“š Sources"):
389
  for i, source in enumerate(sources, 1):
390
+ st.markdown(f"**Source {i}:** {source}")
 
 
 
 
 
391
 
392
+ # Add to session state with sources
393
  st.session_state.messages.append({
394
  "role": "assistant",
395
  "content": answer,
 
399
  st.session_state.messages.append({"role": "assistant", "content": answer})
400
  else:
401
  st.session_state.messages.append({"role": "assistant", "content": answer})
 
 
 
 
 
 
 
 
 
 
 
 
 
402
 
403
  if __name__ == "__main__":
404
  main()