simple-text-analyzer / web_app /session_manager.py
egumasa's picture
removed temporary file writing
ca02ec3
"""
Session state management module for the text analysis application.
Handles initialization, clearing, and management of session state.
"""
import streamlit as st
from typing import Dict, Any, Optional
class SessionManager:
"""Manages Streamlit session state for the application."""
@staticmethod
def initialize_session_state():
"""Initialize all session state variables with default values."""
defaults = {
'language': 'en',
'model_size': 'trf',
'analyzer': None,
'pos_parser': None,
'reference_lists': {},
'uploaded_file_configs': {},
'uploaded_files_content': {}, # Store file contents in memory
'last_language_change': st.session_state.get('language', 'en'),
'show_language_warning': False
}
for key, default_value in defaults.items():
if key not in st.session_state:
st.session_state[key] = default_value
@staticmethod
def clear_analyzers():
"""Clear analyzer and parser instances (e.g., when language/model changes)."""
st.session_state.analyzer = None
st.session_state.pos_parser = None
@staticmethod
def handle_language_change():
"""Handle language change logic."""
current_lang = st.session_state.get('language', 'en')
if st.session_state.last_language_change != current_lang:
SessionManager.clear_analyzers()
st.session_state.last_language_change = current_lang
@staticmethod
def get_reference_lists() -> Dict[str, Any]:
"""Get reference lists from session state."""
return st.session_state.get('reference_lists', {})
@staticmethod
def set_reference_lists(reference_lists: Dict[str, Any]):
"""Set reference lists in session state."""
st.session_state.reference_lists = reference_lists
@staticmethod
def add_reference_list(name: str, data: Dict[str, Any]):
"""Add a single reference list to session state."""
if 'reference_lists' not in st.session_state:
st.session_state.reference_lists = {}
st.session_state.reference_lists[name] = data
@staticmethod
def remove_reference_list(name: str):
"""Remove a reference list from session state."""
if name in st.session_state.get('reference_lists', {}):
del st.session_state.reference_lists[name]
@staticmethod
def get_uploaded_file_configs() -> Dict[str, Any]:
"""Get uploaded file configurations from session state."""
return st.session_state.get('uploaded_file_configs', {})
@staticmethod
def set_uploaded_file_config(file_key: str, config: Dict[str, Any]):
"""Set configuration for an uploaded file."""
if 'uploaded_file_configs' not in st.session_state:
st.session_state.uploaded_file_configs = {}
st.session_state.uploaded_file_configs[file_key] = config
@staticmethod
def get_temp_dir() -> Optional[str]:
"""
DEPRECATED: This method is no longer used.
File handling is now done in-memory to support read-only filesystems.
"""
import warnings
warnings.warn(
"get_temp_dir() is deprecated. Use in-memory file handling instead.",
DeprecationWarning,
stacklevel=2
)
return None
@staticmethod
def is_custom_reference_list(name: str) -> bool:
"""Check if a reference list is custom (uploaded) or default."""
reference_lists = SessionManager.get_reference_lists()
if name not in reference_lists:
return False
ref_data = reference_lists[name]
if 'token' in ref_data and isinstance(ref_data['token'], dict):
return ref_data['token'].get('is_custom_config', False)
return False
@staticmethod
def get_session_info() -> Dict[str, Any]:
"""Get session state information for debugging."""
return {
'language': st.session_state.get('language'),
'model_size': st.session_state.get('model_size'),
'analyzer_loaded': st.session_state.get('analyzer') is not None,
'reference_lists_count': len(st.session_state.get('reference_lists', {})),
'uploaded_files_count': len(st.session_state.get('uploaded_file_configs', {}))
}