🎓 DTMI UGM Academic Assistant
Asisten Cerdas Multimodal untuk Informasi Akademik DTMI UGM
💬 Tanyakan apapun tentang kurikulum, silabus, gambar, dan tabel data
import shutil from huggingface_hub import snapshot_download, hf_hub_download, list_repo_files, HfApi from pathlib import Path from huggingface_hub import list_repo_files, hf_hub_download import streamlit as st import os from PIL import Image import pandas as pd import json from datetime import datetime from typing import List, Dict, Any, Optional from RAG import EnhancedMultimodalRAGSystem from config import * # Page config st.set_page_config( page_title="DTMI UGM Academic Assistant", page_icon="🎓", layout="wide", initial_sidebar_state="expanded" ) st.markdown(""" """, unsafe_allow_html=True) @st.cache_resource def initialize_rag_system(): try: return EnhancedMultimodalRAGSystem() except Exception as e: st.error(f"❌ Error initializing RAG system: {e}") st.stop() def display_example_queries(): """Display clickable example queries""" st.markdown("### 💡 Contoh Pertanyaan") for category, queries in EXAMPLE_QUERIES.items(): with st.expander(f"{category}", expanded=True): for query in queries: if st.button(f"💬 {query}", key=f"example_{hash(query)}", use_container_width=True): st.session_state.user_input = query st.rerun() def display_tables_in_chat(table_data: List[Dict]): """Display tables directly in chat""" if not table_data: return st.markdown("### 📊 Tabel Data") for i, table_info in enumerate(table_data, 1): with st.expander(f"📊 {table_info['title']} (Hal. {table_info['page']}, {table_info['year']})", expanded=True): # Table metadata col1, col2, col3 = st.columns(3) with col1: st.metric("📄 Halaman", table_info['page']) with col2: st.metric("📅 Tahun", table_info['year']) with col3: st.metric("📊 Score", f"{table_info['score']:.3f}") # Display table data try: if table_info.get("data_type") == "dataframe" and isinstance(table_info["data"], pd.DataFrame): st.dataframe(table_info["data"], use_container_width=True) # Download CSV csv_data = table_info["data"].to_csv(index=False) st.download_button( label="💾 Download CSV", data=csv_data, file_name=f"table_{i}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv", mime="text/csv" ) elif table_info.get("data_type") == "json": st.json(table_info["data"]) # Download JSON json_str = json.dumps(table_info["data"], indent=2, ensure_ascii=False) st.download_button( label="💾 Download JSON", data=json_str, file_name=f"data_{i}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json", mime="application/json" ) # Show description if table_info.get('description'): st.markdown("**📝 Deskripsi:**") st.text(table_info['description']) except Exception as e: st.error(f"❌ Error displaying table: {e}") def display_single_image_compact(img_info: Dict, index: int): """Display single image in compact format - CLEAN VERSION""" try: image_path = img_info["path"] # Check if file exists if not os.path.exists(image_path): st.error(f"❌ Gambar {index} tidak ditemukan") return # Load and display image image = Image.open(image_path) # Display image with nice styling st.image(image, caption=f"📖 {img_info.get('title', 'Gambar')} - Hal. {img_info.get('page', 'N/A')} ({img_info.get('year', 'N/A')})", use_container_width=True) # Compact metadata col1, col2 = st.columns(2) with col1: st.metric("📊 Relevance Score", f"None") # {img_info.get('score', 0):.2f}") with col2: st.metric("📐 Ukuran", f"{image.width}×{image.height}px") # Expandable details with st.expander(f"📝 Detail Gambar {index}", expanded=False): if img_info.get('description'): st.markdown("**📄 Deskripsi:**") st.text(img_info['description']) if img_info.get('caption'): st.markdown("**💬 Caption:**") st.text(img_info['caption']) except Exception as e: st.error(f"❌ Error loading image {index}: {str(e)}") def display_single_image_full(img_info: Dict): """Display single image in full format - CLEAN VERSION""" try: image_path = img_info["path"] if not os.path.exists(image_path): st.error("❌ Gambar tidak ditemukan") return # Load image image = Image.open(image_path) # Display with title st.markdown(f"### 🖼️ {img_info.get('title', 'Gambar')}") # Create columns for image and metadata col1, col2 = st.columns([3, 1]) with col1: st.image(image, use_column_width=True) with col2: st.markdown("**📋 Informasi Gambar**") st.metric("📄 Halaman", img_info.get('page', 'N/A')) st.metric("📅 Tahun", img_info.get('year', 'N/A')) # st.metric("📊 Score", f"{img_info.get('score', 0):.3f}") st.metric("📐 Dimensi", f"{image.width} × {image.height}") # Download button with open(image_path, "rb") as file: st.download_button( label="💾 Download Gambar", data=file.read(), file_name=os.path.basename(image_path), mime="image/png", use_container_width=True ) # Description below image if img_info.get('description'): st.markdown("**📝 Deskripsi Gambar:**") st.info(img_info['description']) if img_info.get('caption'): st.markdown("**💬 Caption:**") st.info(img_info['caption']) except Exception as e: st.error(f"❌ Error loading image: {str(e)}") def display_images_in_chat(image_data: List[Dict], show_details: bool = True): """Display images directly in chat - CLEAN VERSION""" if not image_data: return st.markdown("### 🖼️ Gambar Terkait") if len(image_data) == 1: st.markdown(f"*Ditemukan 1 gambar relevan*") else: st.markdown(f"*Ditemukan {len(image_data)} gambar relevan*") if len(image_data) > 1: cols = st.columns(min(len(image_data), 2)) # Max 2 columns for i, img_info in enumerate(image_data): with cols[i % 2]: display_single_image_compact(img_info, i+1) else: display_single_image_full(image_data[0]) def enhanced_chat_interface(): if 'messages' not in st.session_state: st.session_state.messages = [] if 'user_input' not in st.session_state: st.session_state.user_input = "" rag_system = initialize_rag_system() st.markdown("""
Asisten Cerdas Multimodal untuk Informasi Akademik DTMI UGM
💬 Tanyakan apapun tentang kurikulum, silabus, gambar, dan tabel data