Spaces:
Sleeping
Sleeping
File size: 9,233 Bytes
7f5d85f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 | """
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
|