File size: 6,622 Bytes
69bf965
 
 
b1760d3
 
 
 
 
 
69bf965
 
 
 
 
 
 
 
b1760d3
69bf965
 
b1760d3
 
 
69bf965
 
 
 
 
 
 
b1760d3
69bf965
 
b1760d3
 
 
 
 
69bf965
 
 
 
 
 
 
 
 
 
 
 
b1760d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69bf965
 
 
 
 
 
 
 
 
 
b1760d3
 
 
 
 
 
 
 
 
 
 
 
 
69bf965
b1760d3
 
 
 
 
 
 
 
 
 
 
 
 
 
69bf965
b1760d3
 
69bf965
b1760d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69bf965
b1760d3
 
 
 
 
 
 
 
69bf965
b1760d3
 
 
69bf965
 
 
 
 
b1760d3
 
 
 
 
69bf965
b1760d3
 
 
 
 
69bf965
 
 
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
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()