Spaces:
Sleeping
Sleeping
Download src/preprocessing.py from Hamza4100/sales-dashboard: direct link, hf CLI and curl.
- Browser
- Download file 8.71 kB
-
https://huggingface.co/spaces/Hamza4100/sales-dashboard/resolve/main/src/preprocessing.py
- Command line
-
hf download hf://spaces/Hamza4100/sales-dashboard/src/preprocessing.py
-
curl -L -o preprocessing.py https://huggingface.co/spaces/Hamza4100/sales-dashboard/resolve/main/src/preprocessing.py
8.71 kB
| """ | |
| preprocessing.py | |
| ---------------- | |
| Data cleaning and preparation pipeline for the Sales Forecasting Dashboard. | |
| """ | |
| from __future__ import annotations | |
| from typing import Dict, Optional, Tuple | |
| import numpy as np | |
| import pandas as pd | |
| from src.utils import get_frequency_alias, robust_to_datetime | |
| class DataPreprocessor: | |
| """Clean, normalise, and resample raw sales data. | |
| Parameters | |
| ---------- | |
| date_col : str | |
| Name of the date column in the raw dataframe. | |
| sales_col : str | |
| Name of the sales/revenue column in the raw dataframe. | |
| freq : str, optional | |
| Target frequency: ``"Daily"``, ``"Weekly"``, ``"Monthly"``, or | |
| ``"auto"`` (default) to detect automatically from the data. | |
| """ | |
| def __init__( | |
| self, | |
| date_col: str, | |
| sales_col: str, | |
| freq: str = "auto", | |
| ) -> None: | |
| self.date_col = date_col | |
| self.sales_col = sales_col | |
| self.freq = freq | |
| # Populated during fit_transform | |
| self._col_mapping: Dict[str, str] = {} | |
| self._detected_freq: Optional[str] = None | |
| # ------------------------------------------------------------------ | |
| # Public API | |
| # ------------------------------------------------------------------ | |
| def fit_transform( | |
| self, df: pd.DataFrame | |
| ) -> Tuple[pd.DataFrame, Dict]: | |
| """Clean the raw dataframe and return a time-series ready dataframe. | |
| Steps | |
| ----- | |
| 1. Copy dataframe. | |
| 2. Normalise column names (strip + lowercase), keep original mapping. | |
| 3. Convert *date_col* to datetime; drop rows where parsing fails. | |
| 4. Convert *sales_col* to numeric; fill bad values with column median. | |
| 5. Remove fully-duplicate rows. | |
| 6. Sort by date. | |
| 7. Remove rows where sales < 0 (counted in report, not silently dropped). | |
| 8. Aggregate: group by date, sum sales. | |
| 9. Auto-detect frequency (if ``freq='auto'``). | |
| 10. Reindex to a gap-free date range; fill missing sales with 0. | |
| Parameters | |
| ---------- | |
| df : pd.DataFrame | |
| Raw input dataframe. | |
| Returns | |
| ------- | |
| cleaned_df : pd.DataFrame | |
| Cleaned dataframe with a ``DatetimeIndex`` and a single *sales_col* | |
| column. | |
| report : dict | |
| Summary of all mutations applied. | |
| """ | |
| report: Dict = {} | |
| # --- Step 1: copy ------------------------------------------------- | |
| data = df.copy() | |
| report["original_rows"] = len(data) | |
| # --- Step 2: normalise column names -------------------------------- | |
| self._col_mapping = {col.strip().lower(): col for col in data.columns} | |
| data.columns = [col.strip().lower() for col in data.columns] | |
| # Normalise the target column references | |
| norm_date = self.date_col.strip().lower() | |
| norm_sales = self.sales_col.strip().lower() | |
| # --- Step 3: parse dates ------------------------------------------- | |
| before_date_drop = len(data) | |
| data[norm_date] = robust_to_datetime(data[norm_date]) | |
| data = data.dropna(subset=[norm_date]) | |
| date_errors_removed = before_date_drop - len(data) | |
| report["date_errors_removed"] = date_errors_removed | |
| # --- Step 4: parse sales -> clean currency symbols, commas & fill with median | |
| if data[norm_sales].dtype == object: | |
| sales_clean = ( | |
| data[norm_sales].astype(str) | |
| .str.replace(r"[^\d.-]", "", regex=True) | |
| ) | |
| data[norm_sales] = pd.to_numeric(sales_clean, errors="coerce") | |
| else: | |
| data[norm_sales] = pd.to_numeric(data[norm_sales], errors="coerce") | |
| missing_sales = int(data[norm_sales].isna().sum()) | |
| if missing_sales > 0: | |
| median_val = data[norm_sales].median() | |
| data[norm_sales] = data[norm_sales].fillna(median_val) | |
| report["missing_sales_filled"] = missing_sales | |
| # --- Step 5: remove duplicate rows --------------------------------- | |
| before_dedup = len(data) | |
| data = data.drop_duplicates() | |
| duplicate_rows_removed = before_dedup - len(data) | |
| report["duplicate_rows_removed"] = duplicate_rows_removed | |
| # --- Step 6: sort by date ----------------------------------------- | |
| data = data.sort_values(norm_date).reset_index(drop=True) | |
| # --- Step 7: remove negative sales --------------------------------- | |
| negative_mask = data[norm_sales] < 0 | |
| negative_rows_removed = int(negative_mask.sum()) | |
| if negative_rows_removed: | |
| data = data[~negative_mask].reset_index(drop=True) | |
| report["negative_rows_removed"] = negative_rows_removed | |
| # --- Step 8: aggregate (sum) by date ------------------------------- | |
| pre_agg_rows = len(data) | |
| data = ( | |
| data.groupby(norm_date, as_index=True)[norm_sales] | |
| .sum() | |
| .reset_index() | |
| ) | |
| aggregation_performed = len(data) < pre_agg_rows | |
| report["aggregation_performed"] = aggregation_performed | |
| # --- Step 9: detect / confirm frequency ---------------------------- | |
| freq_normalized = str(self.freq).strip().lower() | |
| if freq_normalized in ("auto", "auto-detect", "default", "none", ""): | |
| detected = self._detect_frequency(data[norm_date]) | |
| elif freq_normalized in ("daily", "d"): | |
| detected = "Daily" | |
| elif freq_normalized in ("weekly", "w"): | |
| detected = "Weekly" | |
| elif freq_normalized in ("monthly", "m", "ms"): | |
| detected = "Monthly" | |
| else: | |
| detected = self._detect_frequency(data[norm_date]) | |
| self._detected_freq = detected | |
| report["detected_frequency"] = detected | |
| freq_alias = get_frequency_alias(detected) | |
| # --- Step 10: gap-free reindex ------------------------------------ | |
| date_min = data[norm_date].min() | |
| date_max = data[norm_date].max() | |
| full_index = pd.date_range(start=date_min, end=date_max, freq=freq_alias) | |
| data = data.set_index(norm_date) | |
| data.index = pd.DatetimeIndex(data.index) | |
| data = data.reindex(full_index, fill_value=0) | |
| data.index.name = None | |
| # Keep only sales column, rename back to original user-supplied name | |
| data = data[[norm_sales]].rename(columns={norm_sales: self.sales_col}) | |
| data[self.date_col] = data.index | |
| report["cleaned_rows"] = len(data) | |
| report["date_range_start"] = str(date_min.date()) | |
| report["date_range_end"] = str(date_max.date()) | |
| return data, report | |
| def get_data_quality_score(self, report: Dict) -> float: | |
| """Compute a 0-100 data-quality score based on the cleaning report. | |
| A higher score means the data required fewer corrections. | |
| Parameters | |
| ---------- | |
| report : dict | |
| The report dict returned by :meth:`fit_transform`. | |
| Returns | |
| ------- | |
| float | |
| Quality score between 0 and 100. | |
| """ | |
| original = max(report.get("original_rows", 1), 1) | |
| # Weight each penalty type (more severe = higher weight) | |
| date_errors = report.get("date_errors_removed", 0) | |
| missing_filled = report.get("missing_sales_filled", 0) | |
| duplicates = report.get("duplicate_rows_removed", 0) | |
| negatives = report.get("negative_rows_removed", 0) | |
| penalties = ( | |
| (date_errors / original) * 40 # up to 40 pts | |
| + (missing_filled / original) * 25 # up to 25 pts | |
| + (duplicates / original) * 20 # up to 20 pts | |
| + (negatives / original) * 15 # up to 15 pts | |
| ) | |
| score = max(0.0, 100.0 - penalties * 100) | |
| return round(score, 1) | |
| # ------------------------------------------------------------------ | |
| # Private helpers | |
| # ------------------------------------------------------------------ | |
| def _detect_frequency(date_series: pd.Series) -> str: | |
| """Infer 'Daily', 'Weekly', or 'Monthly' from date diffs. | |
| Parameters | |
| ---------- | |
| date_series : pd.Series | |
| Sorted datetime series. | |
| Returns | |
| ------- | |
| str | |
| One of ``"Daily"``, ``"Weekly"``, ``"Monthly"``. | |
| """ | |
| sorted_dates = pd.to_datetime(date_series).sort_values() | |
| diffs = sorted_dates.diff().dropna() | |
| if diffs.empty: | |
| return "Monthly" | |
| median_days = diffs.dt.days.median() | |
| if median_days <= 1.5: | |
| return "Daily" | |
| if median_days <= 10: | |
| return "Weekly" | |
| return "Monthly" | |