"""DataTools Clean Text — Streamlit page.""" from __future__ import annotations import io import json import sys from pathlib import Path import pandas as pd import streamlit as st _project_root = Path(__file__).resolve().parent.parent.parent.parent if str(_project_root) not in sys.path: sys.path.insert(0, str(_project_root)) from src.gui.components import ( back_to_home_link, hide_streamlit_chrome, pickup_or_upload, render_hidden_aware_preview, require_feature_or_render_upgrade, ) from src.license import FeatureFlag from src.core.text_clean import ( PRESETS, CleanOptions, clean_dataframe, hidden_char_css, visualize_hidden_html, ) hide_streamlit_chrome() back_to_home_link() require_feature_or_render_upgrade(FeatureFlag.TEXT_CLEANER) # --------------------------------------------------------------------------- # Header # --------------------------------------------------------------------------- st.title("✂️ Clean Text") st.caption( "Trim whitespace, fold smart quotes, strip invisible characters, and " "normalize line endings. Runs locally — your data never leaves this computer." ) # --------------------------------------------------------------------------- # File upload # --------------------------------------------------------------------------- uploaded = pickup_or_upload( label="Upload CSV or Excel file", key="textclean_file_upload", types=["csv", "tsv", "xlsx", "xls"], ) if uploaded is None: st.info("Upload a CSV, TSV, or Excel file to begin.") st.stop() @st.cache_data(show_spinner=False) def _read_uploaded(name: str, data: bytes) -> pd.DataFrame: """Read the uploaded bytes into a DataFrame, treating all cells as strings.""" suffix = Path(name).suffix.lower() bio = io.BytesIO(data) if suffix in (".xlsx", ".xls"): return pd.read_excel(bio, dtype=str, keep_default_na=False) # CSV / TSV — try utf-8 then utf-8-sig then latin-1 as a fallback for enc in ("utf-8", "utf-8-sig", "latin-1"): try: bio.seek(0) sep = "\t" if suffix == ".tsv" else "," return pd.read_csv( bio, dtype=str, keep_default_na=False, encoding=enc, sep=sep, on_bad_lines="warn", ) except UnicodeDecodeError: continue bio.seek(0) return pd.read_csv(bio, dtype=str, keep_default_na=False, encoding="latin-1") try: df = _read_uploaded(uploaded.name, uploaded.getvalue()) except UnicodeDecodeError as e: st.error( f"**Could not decode `{uploaded.name}`**\n\n" f"The file isn't UTF-8, UTF-8-with-BOM, or Latin-1.\n\n" f"_Underlying error: {e}_\n\n" f"Try re-saving the file as UTF-8 from the source application, " f"or convert it with `iconv -f -t utf-8`." ) st.stop() except Exception as e: from src.core.errors import format_for_user st.error( f"**Could not read `{uploaded.name}`**\n\n" f"```\n{format_for_user(e)}\n```" ) st.stop() # Collapse the input preview once the user has clicked Clean Text so # the Results section below is the primary visual focus. The user can # re-expand the expander to re-inspect the source rows. _has_result = st.session_state.get("textclean_result") is not None with st.expander(f"Preview: {uploaded.name}", expanded=not _has_result): st.caption(f"{len(df)} rows, {len(df.columns)} columns") preview_show_hidden = st.toggle( "Show hidden characters in preview", value=True, help="Highlights NBSP, zero-width chars, smart quotes, and leading/trailing whitespace.", key="textclean_preview_show_hidden", ) if preview_show_hidden: render_hidden_aware_preview(df, n_rows=10) else: st.dataframe(df.head(10), use_container_width=True) st.divider() # --------------------------------------------------------------------------- # Options # --------------------------------------------------------------------------- # # Wrapped in an outer expander whose default state mirrors the preview # expander above: open before a result exists, folded once the user has # clicked Clean Text. Together they push the Results section to the top # of the visible area after a run. with st.expander("Options", expanded=not _has_result): preset_label = st.radio( "Preset", ["excel-hygiene (recommended)", "minimal", "paranoid"], index=0, horizontal=True, help=( "excel-hygiene: trim, collapse whitespace, fold smart quotes, strip " "invisible chars, normalize line endings, NFC. " "minimal: only trim and collapse. " "paranoid: everything including NFKC compat fold (lossy)." ), ) preset_key = preset_label.split(" ", 1)[0] options = CleanOptions.from_preset(preset_key) with st.expander("Advanced options"): col_a, col_b = st.columns(2) with col_a: options.trim = st.checkbox("Trim leading/trailing whitespace", value=options.trim) options.collapse_whitespace = st.checkbox( "Collapse internal whitespace", value=options.collapse_whitespace, ) options.normalize_line_endings = st.checkbox( "Normalize line endings (\\r\\n → \\n)", value=options.normalize_line_endings, ) options.strip_control = st.checkbox( "Strip control characters", value=options.strip_control, ) options.strip_bom = st.checkbox("Strip BOM", value=options.strip_bom) with col_b: options.fold_smart_chars = st.checkbox( "Fold smart characters (curly quotes, em-dash, NBSP)", value=options.fold_smart_chars, ) options.strip_zero_width = st.checkbox( "Strip zero-width / invisible characters", value=options.strip_zero_width, ) options.nfc = st.checkbox("Unicode NFC normalization", value=options.nfc) options.nfkc = st.checkbox( "Unicode NFKC compat fold (lossy: ① → 1, fi → fi)", value=options.nfkc, ) st.markdown("**Scope**") string_cols = [ c for c in df.columns if pd.api.types.is_object_dtype(df[c]) or pd.api.types.is_string_dtype(df[c]) ] selected_cols = st.multiselect( "Columns to clean (default: all string columns)", options=list(df.columns), default=string_cols, ) skip_cols = st.multiselect( "Columns to skip even if they look like text", options=list(df.columns), default=[], ) options.columns = selected_cols if selected_cols else None options.skip_columns = list(skip_cols) st.markdown("**Case conversion**") case_global = st.selectbox( "Apply case conversion to selected columns", ["None", "UPPER", "lower", "Title", "Sentence"], index=0, ) case_map = { "UPPER": "upper", "lower": "lower", "Title": "title", "Sentence": "sentence", } if case_global != "None": options.case = case_map[case_global] # type: ignore[assignment] # --------------------------------------------------------------------------- # Run # --------------------------------------------------------------------------- st.divider() if st.button("Clean Text", type="primary", use_container_width=True): with st.spinner("Cleaning..."): try: result = clean_dataframe(df, options) except ValueError as e: st.error(str(e)) st.stop() st.session_state["textclean_result"] = result st.session_state["textclean_input_name"] = uploaded.name # One-shot flag picked up on the next pass to scroll the parent # document to the Results anchor (see scroll snippet below). st.session_state["_textclean_scroll_to_results"] = True # Force a second rerun so the preview and options expanders see # the new result on the NEXT script pass and collapse themselves. # Without this they stay expanded until the user touches any # other widget. st.rerun() result = st.session_state.get("textclean_result") if result is None: st.stop() # --------------------------------------------------------------------------- # Results # --------------------------------------------------------------------------- # Anchor target for the auto-scroll snippet at the end of this block. # A bare ``
`` survives Streamlit's HTML sanitizer (only # `` """, height=0, )