import streamlit as st from typing import Dict, List, Optional import pandas as pd from datetime import datetime import json import base64 from pathlib import Path import pypdf from PIL import Image import io class DocumentViewer: def __init__(self, case_manager, document_processor): """Initialize DocumentViewer with required components.""" self.case_manager = case_manager self.document_processor = document_processor # Initialize session state for viewer if 'current_document' not in st.session_state: st.session_state.current_document = None if 'current_page' not in st.session_state: st.session_state.current_page = 1 if 'chunk_view' not in st.session_state: st.session_state.chunk_view = False def render(self, case_id: str): """Render enhanced document viewer interface.""" case = self.case_manager.get_case(case_id) if not case: st.error("Case not found") return # Add custom CSS for document viewer self._add_viewer_styles() # Document selection and viewing area col1, col2 = st.columns([1, 3]) with col1: self._render_document_list(case) with col2: if st.session_state.current_document: self._render_document_viewer(st.session_state.current_document) def _add_viewer_styles(self): """Add custom CSS styles for document viewer.""" st.markdown(""" """, unsafe_allow_html=True) def _render_document_list(self, case: Dict): """Render enhanced document list with filtering and sorting.""" st.markdown("### 📑 Documents") # Search and filter options search = st.text_input("🔍 Search documents", key="doc_search") sort_by = st.selectbox( "Sort by", ["Recent first", "Name A-Z", "Name Z-A", "Size", "Type"], key="doc_sort" ) # Get and sort documents docs = case['documents'] if search: docs = [d for d in docs if search.lower() in d['title'].lower()] if sort_by == "Recent first": docs.sort(key=lambda x: x['added_at'], reverse=True) elif sort_by == "Name A-Z": docs.sort(key=lambda x: x['title']) elif sort_by == "Name Z-A": docs.sort(key=lambda x: x['title'], reverse=True) # Display document list for doc in docs: doc_container = st.container() with doc_container: if st.button( f"📄 {doc['title'][:30]}...", key=f"select_{doc['id']}", help=f"Click to view {doc['title']}" ): st.session_state.current_document = doc st.session_state.current_page = 1 st.session_state.chunk_view = False def _render_document_viewer(self, document: Dict): """Render enhanced document viewer with multiple view modes.""" st.markdown(f"### 📄 {document['title']}") # Document controls col1, col2, col3 = st.columns([2, 1, 1]) with col1: view_mode = st.radio( "View Mode", ["Document", "Chunks", "Analysis"], horizontal=True, key="view_mode" ) with col2: if st.button("Download", key="download_doc"): self._handle_download(document) with col3: if st.button("Process Again", key="reprocess_doc"): self._reprocess_document(document) # Render selected view mode if view_mode == "Document": self._render_document_content(document) elif view_mode == "Chunks": self._render_chunk_view(document) else: self._render_analysis_view(document) # Document metadata with st.expander("📋 Document Metadata", expanded=False): self._render_metadata(document) def _render_document_content(self, document: Dict): """Render document content with page navigation for PDFs.""" content = document.get('content', '') file_type = document.get('metadata', {}).get('file_type', '').lower() if file_type == 'pdf': self._render_pdf_viewer(document) elif file_type in ['png', 'jpg', 'jpeg']: self._render_image_viewer(document) else: st.text_area( "Content", value=content[:10000] + ("..." if len(content) > 10000 else ""), height=400, disabled=True ) def _render_pdf_viewer(self, document: Dict): """Render PDF viewer with navigation controls.""" pdf_path = document.get('file_path') if not pdf_path: st.error("PDF file path not found") return try: reader = pypdf.PdfReader(pdf_path) num_pages = len(reader.pages) # Navigation controls col1, col2, col3 = st.columns([1, 2, 1]) with col1: if st.button("◀️ Previous") and st.session_state.current_page > 1: st.session_state.current_page -= 1 with col2: st.session_state.current_page = st.select_slider( "Page", range(1, num_pages + 1), value=st.session_state.current_page ) with col3: if st.button("Next ▶️") and st.session_state.current_page < num_pages: st.session_state.current_page += 1 # Display current page page = reader.pages[st.session_state.current_page - 1] text = page.extract_text() st.text_area("Page Content", value=text, height=400, disabled=True) except Exception as e: st.error(f"Error displaying PDF: {str(e)}") def _render_chunk_view(self, document: Dict): """Render document chunks with enhanced visualization.""" chunks = document.get('chunks', []) if not chunks: st.warning("No chunks available. Try reprocessing the document.") return # Chunk navigation and filtering search = st.text_input("🔍 Search in chunks", key="chunk_search") # Display chunks for idx, chunk in enumerate(chunks): if not search or search.lower() in chunk['text'].lower(): with st.container(): st.markdown(f"""
{self._highlight_text(chunk['text'], search) if search else chunk['text']}
{ref['snippet']}