""" data_loader.py -------------- Functions to load raw data from CSV / XLSX sources and perform initial column detection. """ from __future__ import annotations import io from typing import Dict, List, Optional, Union import numpy as np import pandas as pd # --------------------------------------------------------------------------- # Loading # --------------------------------------------------------------------------- def load_data(file_or_path: Union[str, "UploadedFile"]) -> pd.DataFrame: # noqa: F821 """Load a CSV or XLSX file into a :class:`pd.DataFrame`. Parameters ---------- file_or_path : str or Streamlit UploadedFile Either an absolute/relative file-system path (``str``) or a Streamlit ``UploadedFile`` object whose ``.name`` attribute supplies the file extension and whose ``.read()`` / seek interface provides the bytes. Returns ------- pd.DataFrame Raw dataframe — no preprocessing applied. Raises ------ ValueError When the file cannot be read, the format is unsupported, or the resulting dataframe is empty. """ # ---- Determine extension and raw bytes / path ------------------------- if isinstance(file_or_path, str): path = file_or_path ext = path.rsplit(".", 1)[-1].lower() raw_bytes: Optional[bytes] = None else: # Streamlit UploadedFile or file-like name = getattr(file_or_path, "name", "") or "" ext = name.rsplit(".", 1)[-1].lower() if "." in name else "" file_or_path.seek(0) raw_bytes = file_or_path.read() path = None # type: ignore[assignment] # ---- Dispatch by extension ------------------------------------------- try: if ext == "csv": df = _load_csv(path, raw_bytes) elif ext in ("xlsx", "xls"): df = _load_excel(path, raw_bytes) else: raise ValueError( f"Unsupported file format '.{ext}'. Please upload a CSV or XLSX file." ) except ValueError: raise except Exception as exc: # noqa: BLE001 raise ValueError(f"Failed to read the file: {exc}") from exc if df.empty: raise ValueError("The loaded file contains no data rows.") return df def _load_csv(path: Optional[str], raw_bytes: Optional[bytes]) -> pd.DataFrame: """Internal helper: load CSV with encoding and delimiter fallback.""" for encoding in ("utf-8", "latin-1", "cp1252"): try: if raw_bytes is not None: df = pd.read_csv(io.BytesIO(raw_bytes), encoding=encoding) if df.shape[1] == 1: try: df_alt = pd.read_csv(io.BytesIO(raw_bytes), encoding=encoding, sep=None, engine="python") if df_alt.shape[1] > 1: df = df_alt except Exception: pass return df df = pd.read_csv(path, encoding=encoding) if df.shape[1] == 1: try: df_alt = pd.read_csv(path, encoding=encoding, sep=None, engine="python") if df_alt.shape[1] > 1: df = df_alt except Exception: pass return df except UnicodeDecodeError: continue except Exception as exc: # noqa: BLE001 raise ValueError(f"Could not parse CSV: {exc}") from exc raise ValueError("Could not decode the CSV file with utf-8 or latin-1 encoding.") def _load_excel(path: Optional[str], raw_bytes: Optional[bytes]) -> pd.DataFrame: """Internal helper: load Excel file.""" try: if raw_bytes is not None: return pd.read_excel(io.BytesIO(raw_bytes)) return pd.read_excel(path) except Exception as exc: # noqa: BLE001 raise ValueError(f"Could not parse Excel file: {exc}") from exc # --------------------------------------------------------------------------- # File info # --------------------------------------------------------------------------- def get_file_info(df: pd.DataFrame) -> Dict: """Return a summary dictionary describing the dataframe. Parameters ---------- df : pd.DataFrame Returns ------- dict Keys: * ``rows`` – number of rows * ``columns`` – number of columns * ``column_names`` – list of column names * ``dtypes`` – ``{col: dtype_str}`` mapping * ``missing_per_col`` – ``{col: missing_count}`` for columns with ≥ 1 null * ``duplicate_count`` – number of fully duplicate rows """ missing_per_col: Dict[str, int] = { col: int(df[col].isna().sum()) for col in df.columns if df[col].isna().any() } return { "rows": len(df), "columns": df.shape[1], "column_names": list(df.columns), "dtypes": {col: str(df[col].dtype) for col in df.columns}, "missing_per_col": missing_per_col, "duplicate_count": int(df.duplicated().sum()), } # --------------------------------------------------------------------------- # Column detection # --------------------------------------------------------------------------- #: Common date column name substrings (lower-case). _DATE_CANDIDATES: List[str] = [ "date", "order_date", "sales_date", "transaction_date", "datetime", "timestamp", "invoice_date", ] #: Common sales column name fragments (lower-case). _SALES_CANDIDATES: List[str] = [ "sales", "sale", "revenue", "amount", "total_sales", "total", "revenue_amount", "sales_amount", "qty", "quantity", ] def detect_date_column(df: pd.DataFrame) -> Optional[str]: """Heuristically identify the date column in *df*. Detection strategy (in priority order): 1. Exact case-insensitive match against common date column names. 2. Any column whose name contains ``"date"`` or ``"time"`` (case-insensitive). 3. Already-datetime dtype columns. 4. Attempt ``pd.to_datetime`` on each object/string column; pick the one with the highest parse success rate (≥ 50 %). Parameters ---------- df : pd.DataFrame Returns ------- str or None Best candidate column name, or ``None`` if none found. """ lower_map: Dict[str, str] = {col.strip().lower(): col for col in df.columns} # 1 — exact known names for candidate in _DATE_CANDIDATES: if candidate in lower_map: return lower_map[candidate] # 2 — partial match on "date" / "time" in column name for col_lower, col_orig in lower_map.items(): if "date" in col_lower or "time" in col_lower: return col_orig # 3 — already datetime dtype for col in df.columns: if pd.api.types.is_datetime64_any_dtype(df[col]): return col # 4 — try parsing each non-numeric column best_col: Optional[str] = None best_rate: float = 0.5 # minimum 50 % for col in df.columns: if pd.api.types.is_numeric_dtype(df[col]): continue try: parsed = pd.to_datetime(df[col], errors="coerce", infer_datetime_format=True) rate = parsed.notna().mean() if rate > best_rate: best_rate = rate best_col = col except Exception: # noqa: BLE001 continue return best_col def detect_sales_column(df: pd.DataFrame, exclude: Optional[List[str]] = None) -> Optional[str]: """Heuristically identify the sales/revenue column in *df*. Detection strategy (in priority order): 1. Exact case-insensitive match against common sales column names. 2. Any numeric column not in *exclude* whose name contains a sales-related substring. 3. First remaining numeric column not in *exclude*. Parameters ---------- df : pd.DataFrame exclude : list[str], optional Columns to skip (e.g. the date column). Returns ------- str or None Best candidate column name, or ``None`` if none found. """ if exclude is None: exclude = [] exclude_set = set(exclude) lower_map: Dict[str, str] = { col.strip().lower(): col for col in df.columns if col not in exclude_set } # 1 — exact known names for candidate in _SALES_CANDIDATES: if candidate in lower_map: return lower_map[candidate] # 2 — partial match on sales-related substrings in numeric columns numeric_cols = { col for col in df.columns if col not in exclude_set and pd.api.types.is_numeric_dtype(df[col]) } for candidate_fragment in ("sales", "revenue", "amount", "total", "qty", "quantity"): for col_lower, col_orig in lower_map.items(): if candidate_fragment in col_lower and col_orig in numeric_cols: return col_orig # 3 — first numeric column not excluded for col in df.columns: if col not in exclude_set and pd.api.types.is_numeric_dtype(df[col]): return col return None