# Standard library imports import os import json import sys import time import base64 import io import logging from pathlib import Path from datetime import datetime # Configure logging logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) # Third-party imports import streamlit as st # Local application/module imports from preprocessing import convert_pdf_to_images, preprocess_image from ocr_processing import process_file from ui.ui_components import ( ProgressReporter, create_sidebar_options, display_results, create_file_uploader, display_about_tab, display_previous_results, display_document_with_images ) from utils import get_base64_from_image, handle_temp_files, format_timestamp from error_handler import handle_ocr_error, check_file_size from constants import ( MAX_FILE_SIZE_MB, MAX_PAGES, DOCUMENT_TYPES, DOCUMENT_LAYOUTS, CUSTOM_PROMPT_TEMPLATES, LAYOUT_PROMPT_ADDITIONS ) from structured_ocr import StructuredOCR from config import MISTRAL_API_KEY from utils.image_utils import create_results_zip # Set favicon path favicon_path = os.path.join(os.path.dirname(__file__), "static/favicon.png") # Set page configuration st.set_page_config( page_title="Historical OCR", page_icon=favicon_path if os.path.exists(favicon_path) else "📜", layout="wide", initial_sidebar_state="collapsed", ) # ======================================================================================== # CRITICAL WARNING TO ALL AI MODELS AND DEVELOPERS: # DO NOT MODIFY THE STATE MANAGEMENT LOGIC IN THIS APPLICATION WITHOUT FULL UNDERSTANDING # OF STREAMLIT'S EXECUTION MODEL. # # This state management implementation has been carefully designed to work with Streamlit's # unique execution flow. The app runs from top to bottom on EVERY interaction, and state # must be explicitly managed through st.session_state. # # The current implementation uses: # 1. A dedicated close_document() callback function triggered by the button's on_click # 2. A flag-based approach (close_clicked) to handle cleanup on the next run cycle # 3. Early cleanup detection and st.rerun() to ensure clean UI rendering # # Previous approaches using direct state manipulation or conditional rendering based on # reset flags led to persistent UI elements and resource leaks. # # Consult https://docs.streamlit.io/library/advanced-features/session-state for details. # ======================================================================================== def reset_document_state(): """Reset only document-specific state variables This function explicitly resets all document-related variables to ensure clean state between document processing, preventing cached data issues. """ st.session_state.sample_document = None st.session_state.original_sample_bytes = None st.session_state.original_sample_name = None st.session_state.original_sample_mime_type = None st.session_state.is_sample_document = False st.session_state.processed_document_active = False st.session_state.sample_document_processed = False st.session_state.sample_just_loaded = False st.session_state.last_processed_file = None st.session_state.selected_previous_result = None # Keep temp_file_paths but ensure it's empty after cleanup if 'temp_file_paths' in st.session_state: st.session_state.temp_file_paths = [] def init_session_state(): """Initialize session state variables if they don't already exist This function follows Streamlit's recommended patterns for state initialization. It only creates variables if they don't exist yet and doesn't modify existing values. """ # Initialize persistent app state variables if 'previous_results' not in st.session_state: st.session_state.previous_results = [] if 'temp_file_paths' not in st.session_state: st.session_state.temp_file_paths = [] if 'auto_process_sample' not in st.session_state: st.session_state.auto_process_sample = False if 'close_clicked' not in st.session_state: st.session_state.close_clicked = False if 'active_tab' not in st.session_state: st.session_state.active_tab = 0 # Initialize document-specific state variables if 'last_processed_file' not in st.session_state: st.session_state.last_processed_file = None if 'sample_just_loaded' not in st.session_state: st.session_state.sample_just_loaded = False if 'processed_document_active' not in st.session_state: st.session_state.processed_document_active = False if 'sample_document_processed' not in st.session_state: st.session_state.sample_document_processed = False if 'sample_document' not in st.session_state: st.session_state.sample_document = None if 'original_sample_bytes' not in st.session_state: st.session_state.original_sample_bytes = None if 'original_sample_name' not in st.session_state: st.session_state.original_sample_name = None if 'is_sample_document' not in st.session_state: st.session_state.is_sample_document = False if 'selected_previous_result' not in st.session_state: st.session_state.selected_previous_result = None def close_document(): """Called when the Close Document button is clicked This function handles proper cleanup of resources and state when closing a document. It uses Streamlit's callback mechanism which ensures the state change happens at the correct time in Streamlit's execution cycle. WARNING: Do not replace this with inline button handling using if st.button(): That approach breaks Streamlit's execution flow and causes UI artifacts. """ logger.info("Close document button clicked") # Clean up temp files first if 'temp_file_paths' in st.session_state and st.session_state.temp_file_paths: logger.info(f"Cleaning up {len(st.session_state.temp_file_paths)} temporary files") handle_temp_files(st.session_state.temp_file_paths) # Reset all document-specific state variables to prevent caching issues reset_document_state() # Set flag for having cleaned up - this will trigger a rerun in main() st.session_state.close_clicked = True def show_example_documents(): """Show example documents section""" st.header("Sample Documents") # Add a simplified info message about examples and CSS in the same markdown block # to reduce spacing between elements st.markdown(""" This app can process various historical documents: - Historical photographs, maps, and manuscripts - Handwritten letters and documents - Printed books and articles - Multi-page PDFs """, unsafe_allow_html=True) # Sample document URLs dropdown with clearer label sample_urls = [ "Select a sample document", "https://huggingface.co/spaces/milwright/historical-ocr/resolve/main/input/a-la-carte.pdf", "https://huggingface.co/spaces/milwright/historical-ocr/resolve/main/input/magician-or-bottle-cungerer.jpg", "https://huggingface.co/spaces/milwright/historical-ocr/resolve/main/input/handwritten-letter.jpg", "https://huggingface.co/spaces/milwright/historical-ocr/resolve/main/input/magellan-travels.jpg", "https://huggingface.co/spaces/milwright/historical-ocr/resolve/main/input/milgram-flier.png", "https://huggingface.co/spaces/milwright/historical-ocr/resolve/main/input/recipe.jpg", ] sample_names = [ "Select a sample document", "Restaurant Menu (PDF)", "The Magician (Image)", "Handwritten Letter (Image)", "Magellan Travels (Image)", "Milgram Flier (Image)", "Historical Recipe (Image)" ] # Initialize sample_document in session state if it doesn't exist if 'sample_document' not in st.session_state: st.session_state.sample_document = None selected_sample = st.selectbox("Select a sample document from `~/input`", options=range(len(sample_urls)), format_func=lambda i: sample_names[i]) if selected_sample > 0: selected_url = sample_urls[selected_sample] # Add process button for the sample document with consistent styling if st.button("Load Sample Document", key="load_sample_btn"): try: import requests from io import BytesIO with st.spinner(f"Downloading {sample_names[selected_sample]}..."): response = requests.get(selected_url) response.raise_for_status() # Extract filename from URL file_name = selected_url.split("/")[-1] # Create a BytesIO object from the downloaded content file_content = BytesIO(response.content) # Store as a UploadedFile-like object in session state class SampleDocument: def __init__(self, name, content, content_type): self.name = name self._content = content self.type = content_type self.size = len(content) def getvalue(self): return self._content def read(self): return self._content def seek(self, position): # Implement seek for compatibility with some file operations return def tell(self): # Implement tell for compatibility return 0 # Determine content type based on file extension if file_name.lower().endswith('.pdf'): content_type = 'application/pdf' elif file_name.lower().endswith(('.jpg', '.jpeg')): content_type = 'image/jpeg' elif file_name.lower().endswith('.png'): content_type = 'image/png' else: content_type = 'application/octet-stream' # Reset any document state before loading a new sample if st.session_state.processed_document_active: # Clean up any temporary files from previous processing if st.session_state.temp_file_paths: handle_temp_files(st.session_state.temp_file_paths) # Reset all document-specific state variables reset_document_state() # Save download info in session state st.session_state.sample_document = SampleDocument( name=file_name, content=response.content, content_type=content_type ) # Store original bytes for reprocessing with proper MIME type handling st.session_state.original_sample_bytes = response.content st.session_state.original_sample_name = file_name st.session_state.original_sample_mime_type = content_type # Set state flags st.session_state.sample_just_loaded = True st.session_state.is_sample_document = True # Generate a unique identifier for the sample document st.session_state.last_processed_file = f"{file_name}_{len(response.content)}" # Set a flag to show redirect message st.session_state.redirect_to_processing = True st.rerun() except Exception as e: st.error(f"Error downloading sample document: {str(e)}") st.info("Please try uploading your own document instead.") else: # If no sample is selected, clear the sample document in session state st.session_state.sample_document = None def process_document(uploaded_file, left_col, right_col, sidebar_options): """Process the uploaded document and display results""" if uploaded_file is None: return # Check file size (cap at 50MB) file_size_mb = len(uploaded_file.getvalue()) / (1024 * 1024) if file_size_mb > MAX_FILE_SIZE_MB: with left_col: st.error(f"File too large ({file_size_mb:.1f} MB). Maximum file size is {MAX_FILE_SIZE_MB}MB.") return # Check if this is a new file (different from the last processed file) current_file_identifier = f"{uploaded_file.name}_{len(uploaded_file.getvalue())}" # Make sure last_processed_file is initialized if 'last_processed_file' not in st.session_state: st.session_state.last_processed_file = None if st.session_state.last_processed_file != current_file_identifier: # Reset processed_document_active if a new file is uploaded st.session_state.processed_document_active = False # Process button - flush left with similar padding as file browser with left_col: # Create a process button with minimal spacing to the uploader st.markdown('