JirasakJo's picture
Update app.py
b1760d3 verified
raw
history blame
6.62 kB
import streamlit as st
import json
import os
from datetime import datetime
from calendar_rag import (
create_default_config,
AcademicCalendarRAG,
PipelineConfig
)
# Page config
st.set_page_config(
page_title="Academic Calendar Assistant",
page_icon="📅",
layout="wide"
)
# Initialize session state for pipeline and chat history
if 'pipeline' not in st.session_state:
st.session_state.pipeline = None
if 'chat_history' not in st.session_state:
st.session_state.chat_history = []
def initialize_pipeline():
"""Initialize RAG pipeline with configurations"""
try:
# Get OpenAI API key from environment variable or Streamlit secrets
openai_api_key = os.getenv('OPENAI_API_KEY') or st.secrets['OPENAI_API_KEY']
# Create config
config = create_default_config(openai_api_key)
config.localization.enable_thai_normalization = True
config.retriever.top_k = 5
config.model.temperature = 0.3
# Initialize pipeline
pipeline = AcademicCalendarRAG(config)
# Load calendar data
with open("calendar.json", "r", encoding="utf-8") as f:
calendar_data = json.load(f)
pipeline.load_data(calendar_data)
return pipeline
except Exception as e:
st.error(f"Error initializing pipeline: {str(e)}")
return None
def display_chat_history():
"""Display chat history with user and assistant messages"""
for i, (role, message) in enumerate(st.session_state.chat_history):
if role == "user":
st.markdown(f"**🧑 คำถาม:**")
st.markdown(f"> {message}")
else:
st.markdown(f"**🤖 คำตอบ:**")
st.markdown(message)
st.markdown("---")
def add_to_history(role: str, message: str):
"""Add message to chat history"""
st.session_state.chat_history.append((role, message))
def main():
# Header
st.title("🎓 ระบบค้นหาข้อมูลปฏิทินการศึกษา")
st.markdown("---")
# Initialize pipeline if needed
if st.session_state.pipeline is None:
with st.spinner("กำลังเริ่มต้นระบบ..."):
st.session_state.pipeline = initialize_pipeline()
# Create two columns for chat layout
chat_col, info_col = st.columns([2, 1])
with chat_col:
# Display chat history
display_chat_history()
# Main query interface
query = st.text_input(
"โปรดระบุคำถามเกี่ยวกับปฏิทินการศึกษา:",
placeholder="เช่น: วันสุดท้ายของการสอบปากเปล่าในภาคเรียนที่ 1/2567 คือวันที่เท่าไร?",
key="query_input"
)
# Add query button and clear chat button in the same line
col1, col2 = st.columns([1, 4])
with col1:
send_query = st.button("ส่งคำถาม", type="primary", use_container_width=True)
with col2:
if st.button("ล้างประวัติการสนทนา", type="secondary", use_container_width=True):
st.session_state.chat_history = []
st.rerun()
# Process query when button is clicked
if send_query and query:
if st.session_state.pipeline is None:
st.error("ไม่สามารถเชื่อมต่อกับระบบได้ กรุณาลองใหม่อีกครั้ง")
return
# Add user query to history
add_to_history("user", query)
try:
with st.spinner("กำลังค้นหาคำตอบ..."):
# Process query
result = st.session_state.pipeline.process_query(query)
# Add assistant response to history
add_to_history("assistant", result["answer"])
# Create containers for additional information
with st.expander("📚 แสดงข้อมูลอ้างอิง"):
for i, doc in enumerate(result["documents"], 1):
st.markdown(f"**เอกสารที่ {i}:**")
st.text(doc.content)
st.markdown("---")
with st.expander("🔍 รายละเอียดการวิเคราะห์คำถาม"):
st.json(result["query_info"])
# Clear the input field
st.session_state.query_input = ""
# Rerun to update chat display
st.rerun()
except Exception as e:
st.error(f"เกิดข้อผิดพลาด: {str(e)}")
elif send_query and not query:
st.warning("กรุณาระบุคำถาม")
with info_col:
# System information
st.markdown("### ℹ️ เกี่ยวกับระบบ")
st.markdown("""
ระบบนี้ใช้เทคโนโลยี RAG (Retrieval-Augmented Generation)
ในการค้นหาและตอบคำถามเกี่ยวกับปฏิทินการศึกษา
สามารถสอบถามข้อมูลเกี่ยวกับ:
- กำหนดการต่างๆ ในปฏิทินการศึกษา
- วันสำคัญและกิจกรรม
- การลงทะเบียนเรียน
- กำหนดการสอบ
- วันหยุดการศึกษา
""")
# System status
st.markdown("### 🔄 สถานะระบบ")
st.markdown(f"**เวลาปัจจุบัน:** {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
st.markdown(f"**สถานะระบบ:** {'🟢 พร้อมใช้งาน' if st.session_state.pipeline else '🔴 ไม่พร้อมใช้งาน'}")
if __name__ == "__main__":
main()