import streamlit as st import json import os from datetime import datetime from calendar_rag import ( create_default_config, AcademicCalendarRAG, PipelineConfig ) # Custom CSS for enhanced styling def load_custom_css(): st.markdown(""" """, unsafe_allow_html=True) # Page config st.set_page_config( page_title="Academic Calendar Assistant", page_icon="📅", layout="wide", initial_sidebar_state="collapsed" ) # Load custom CSS load_custom_css() # Initialize session state 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 = [] if 'feedback_data' not in st.session_state: st.session_state.feedback_data = [] def initialize_pipeline(): """Initialize RAG pipeline with configurations""" try: openai_api_key = os.getenv('OPENAI_API_KEY') or st.secrets['OPENAI_API_KEY'] config = create_default_config(openai_api_key) config.localization.enable_thai_normalization = True config.retriever.top_k = 5 config.model.temperature = 0.3 pipeline = AcademicCalendarRAG(config) 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 save_feedback_to_json(): """Save feedback data to a JSON file""" try: # Get current directory current_dir = os.path.dirname(os.path.abspath(__file__)) file_path = os.path.join(current_dir, 'feedback_data.json') # Log the attempt st.write(f"Attempting to save feedback to: {file_path}") # Create directory if it doesn't exist os.makedirs(current_dir, exist_ok=True) # Save the file with open(file_path, "w", encoding="utf-8") as f: json.dump( st.session_state.feedback_data, f, ensure_ascii=False, indent=2 ) # Verify file was created if os.path.exists(file_path): st.write(f"✅ Feedback saved successfully to {file_path}") st.write(f"Current feedback data: {st.session_state.feedback_data}") return True else: st.error("File was not created despite no errors") return False except Exception as e: st.error(f"Error saving feedback: {str(e)}") st.write(f"Current directory: {current_dir}") st.write(f"Current feedback data: {st.session_state.feedback_data}") return False def add_feedback(query: str, answer: str, is_correct: bool): """Add feedback entry to session state and save to JSON""" feedback_entry = { "timestamp": datetime.now().isoformat(), "query": query, "answer": answer, "is_correct": is_correct } st.session_state.feedback_data.append(feedback_entry) save_feedback_to_json() def evaluate_answer(query: str, answer: str): """Display evaluation buttons for the answer""" col1, col2, col3 = st.columns([1, 1, 4]) with col1: if st.button("✅ ถูกต้อง", type="primary", key=f"correct_{len(st.session_state.chat_history)}"): add_feedback(query, answer, True) st.success("บันทึกผลการประเมินแล้ว") return True with col2: if st.button("❌ ไม่ถูกต้อง", type="secondary", key=f"incorrect_{len(st.session_state.chat_history)}"): add_feedback(query, answer, False) st.error("บันทึกผลการประเมินแล้ว") return True return False def display_chat_history(): """Display chat history with enhanced styling""" for i, (role, message) in enumerate(st.session_state.chat_history): if role == "user": st.markdown(f"""
""", unsafe_allow_html=True) else: st.markdown(f""" """, unsafe_allow_html=True) # Add evaluation buttons after each assistant response if i == len(st.session_state.chat_history) - 1: # Only for the latest answer user_query = st.session_state.chat_history[i-1][1] # Get the corresponding user query evaluate_answer(user_query, message) def add_to_history(role: str, message: str): """Add message to chat history""" st.session_state.chat_history.append((role, message)) def main(): # Header with animation st.markdown("""ระบบนี้ใช้เทคโนโลยี RAG (Retrieval-Augmented Generation) ในการค้นหาและตอบคำถามเกี่ยวกับปฏิทินการศึกษา
⏰ เวลาปัจจุบัน:
{}
📡 สถานะระบบ:
{} {}