import io import os from pathlib import Path import pandas as pd import streamlit as st from business_export_job import JobConfig, run_job # On HF Spaces /app/output doesn't exist; default to a local output folder. if "SWISSPARL_OUTPUT_DIR" not in os.environ: os.environ["SWISSPARL_OUTPUT_DIR"] = str(Path(__file__).parent / "output") OUTPUT_DIR = Path(os.environ["SWISSPARL_OUTPUT_DIR"]) OUTPUT_DIR.mkdir(parents=True, exist_ok=True) st.set_page_config(page_title="SwissParl Topic Tagger – Results", layout="wide") st.title("SwissParl Topic Tagger – Results") with st.sidebar: st.header("Actions") if st.button("Trigger Topic Modelling", help="Run the topic modelling job now."): with st.spinner("Running topic modelling... this may take a while."): try: config = JobConfig.from_env() # Ensure the filename template includes the timestamp if we want it to be unique if "{timestamp}" not in config.output_filename_template: config = JobConfig( output_dir=config.output_dir, output_filename_template=config.output_filename_template.replace(".xlsx", "-{timestamp}.xlsx"), days_past=config.days_past, start_date=config.start_date, end_date=config.end_date, languages=config.languages, language_priority=config.language_priority, topic_score_threshold=config.topic_score_threshold, min_chunk_days=config.min_chunk_days, excel_sheet_name=config.excel_sheet_name, ) output_path = run_job(config) st.success(f"Job completed! Result saved to `{output_path.name}`") st.rerun() except Exception as e: st.error(f"Job failed: {e}") excel_files = sorted(OUTPUT_DIR.glob("*.xlsx"), reverse=True) if not excel_files: st.warning(f"No Excel files found in `{OUTPUT_DIR}`. Use the sidebar button to run the topic modelling job.") st.stop() selected = st.selectbox( "Select a result file", excel_files, format_func=lambda p: p.name, ) @st.cache_data def load_excel(path: str) -> pd.DataFrame: return pd.read_excel(path, engine="openpyxl") df = load_excel(str(selected)) # Download button (above the table so it's always visible) buf = io.BytesIO() with pd.ExcelWriter(buf, engine="openpyxl") as writer: df.to_excel(writer, index=False) buf.seek(0) col1, col2 = st.columns([3, 1]) with col1: st.caption(f"{len(df):,} rows · {len(df.columns)} columns · `{selected.name}`") with col2: st.download_button( label="Download Excel", data=buf, file_name=selected.name, mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", ) # Row filter search = st.text_input("Filter rows (searches all text columns)", "") if search: mask = df.apply( lambda col: col.astype(str).str.contains(search, case=False, na=False) ).any(axis=1) df = df[mask] st.caption(f"{len(df):,} rows match the filter") st.dataframe(df, use_container_width=True, height=600)