--- title: PRISM Marketing Intelligence emoji: 📊 colorFrom: blue colorTo: green sdk: docker app_port: 7860 pinned: false license: mit --- # PRISM Marketing Intelligence — MMM Dashboard ## Table of Contents 1. [Project Overview](#project-overview) 2. [Tech Stack](#tech-stack) 3. [Project Structure](#project-structure) 4. [Data Harmonization & Pipeline](#data-harmonization--pipeline) - [Architecture Overview](#architecture-overview) - [Medallion Pipeline Layers](#medallion-pipeline-layers) - [Raw Data Sources](#raw-data-sources) - [Data Quality Issues (Simulated)](#data-quality-issues-simulated) - [Pipeline Operations](#pipeline-operations) - [Step 1: Load Raw](#step-1-load-raw) - [Step 2: Data Profiling](#step-2-data-profiling) - [Step 3: Auto Column Mapping](#step-3-auto-column-mapping) - [Step 4: Apply Mapping (Raw → Bronze)](#step-4-apply-mapping-raw--bronze) - [Step 5: Date Standardization (Bronze → Silver)](#step-5-date-standardization-bronze--silver) - [Step 6: Missing Value Imputation](#step-6-missing-value-imputation) - [Step 7: Outlier Detection & Handling](#step-7-outlier-detection--handling) - [Step 8: Merge to Gold (Silver → Gold)](#step-8-merge-to-gold-silver--gold) - [Step 9: Activate Gold Layer](#step-9-activate-gold-layer) - [AIRA Agent Cards](#aira-agent-cards) - [Column Alias Dictionary](#column-alias-dictionary) - [Standard Value Normalization](#standard-value-normalization) - [Schema Definitions](#schema-definitions) - [API Endpoints](#api-endpoints) - [Frontend Pipeline UI](#frontend-pipeline-ui) --- ## Project Overview An end-to-end **Marketing Mix Modelling (MMM)** solution covering Media, Consumer Promo, and Trade Promo analysis with interactive dashboards, modelling capabilities, **NOVA** (Next-gen Optimization & Value Advisor), and an **Intelligent Alert & Simulation framework**. The system ingests raw, messy data files (simulating real client exports), transforms them through a multi-layer pipeline, and feeds clean, standardized data into 13 analytical dashboards. --- ## Tech Stack | Layer | Technology | |-------|-----------| | Backend | Python 3, Flask | | Frontend | HTML5, JavaScript (vanilla), CSS3 | | Charts | Plotly.js | | Data Processing | Pandas, NumPy | | Fuzzy Matching | `difflib.SequenceMatcher` (Python stdlib) | | File Formats | Excel (.xlsx) input, CSV output | --- ## Project Structure ``` Marketing Effectivness/ ├── app_pkg/ # Flask application package │ ├── __init__.py # App factory, DataService initialization │ ├── blueprints/ │ │ ├── data_mgmt.py # Data Harmonization routes + Pipeline API │ │ ├── main.py # Executive Summary routes │ │ └── media.py # Media Analysis routes │ └── services/ │ ├── data_service.py # DataService - loads data for all dashboards │ ├── pipeline_service.py # PipelineService - medallion pipeline engine │ └── upload_service.py # Upload validation service ├── data/ │ ├── raw/ # Raw messy Excel files (input) │ ├── bronze/ # (in-memory only, not persisted to disk) │ ├── silver/ # (in-memory only, not persisted to disk) │ ├── gold/ # Final clean CSVs (output, used by dashboards) │ └── synthetic/ # Original clean synthetic data (fallback) ├── static/ │ ├── css/ │ │ ├── style.css # Global styles, themes (dark/light) │ │ └── components.css # Component styles including pipeline UI │ └── js/ │ ├── pipeline.js # Pipeline interaction logic │ ├── charts.js # Chart rendering utilities │ └── theme.js # Theme toggle (dark/light mode) ├── templates/ │ ├── base.html # Base template with sidebar, NOVA, filters │ ├── data_mgmt.html # Data Harmonization page │ ├── index.html # Executive Summary / Home │ └── media.html # Media Analysis page ├── config.py # Flask configuration (paths, secrets) ├── generate_raw_data.py # Script to generate messy raw Excel files ├── generate_data.py # Script to generate clean synthetic CSVs ├── run.py # Flask entry point ├── CLAUDE.md # Full project specification └── README.md # This file ``` --- ## Data Harmonization & Pipeline ### Architecture Overview The Data Harmonization system implements a **Medallion Architecture** — a multi-layer data pipeline pattern used in data engineering to progressively improve data quality: ``` ┌─────────────────────────────────────────────────────────────────────┐ │ DATA PIPELINE FLOW │ │ │ │ ┌─────────┐ ┌──────────┐ ┌──────────┐ ┌─────────┐ │ │ │ RAW │───▸│ BRONZE │───▸│ SILVER │───▸│ GOLD │ │ │ │ (Excel) │ │ (Mapped) │ │(Cleaned) │ │ (Final) │ │ │ └─────────┘ └──────────┘ └──────────┘ └─────────┘ │ │ │ │ │ │ │ │ Load raw Column mapping Transforms Dedup + │ │ Excel files via aliases + (dates, normalize + │ │ fuzzy match missing, save CSVs │ │ outliers) │ │ │ │ 5 source files ──────────────────────────────▸ 5 gold CSVs │ │ │ │ ┌─────────────────────────────────────────────────────────┐ │ │ │ DataService (Hot-Reload) │ │ │ │ Dashboards use Gold if available, else Synthetic CSVs │ │ │ └─────────────────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────────────────┘ ``` **Why Medallion Architecture?** - **Traceability**: Each layer preserves the state of data at that stage, enabling debugging and auditability - **Separation of Concerns**: Each transformation step is isolated and independently testable - **Incremental Processing**: Sources can be processed independently and at different times - **Rollback**: If a transformation produces unexpected results, you can re-run from a previous layer --- ### Medallion Pipeline Layers | Layer | Description | Storage | Contents | |-------|-------------|---------|----------| | **Raw** | Original client data exactly as received | `data/raw/*.xlsx` | Excel files with messy column names, mixed formats, errors | | **Bronze** | Schema-aligned data | In-memory (DataFrame) | Columns renamed to standard names, junk columns dropped | | **Silver** | Cleaned and transformed data | In-memory (DataFrame) | Dates standardized, missing values imputed, outliers handled | | **Gold** | Production-ready analytical data | `data/gold/*.csv` | Deduplicated, string-normalized, sorted, final CSVs | --- ### Raw Data Sources Five raw Excel files simulate the kind of messy data a marketing analytics team would receive from various internal teams, agencies, and third-party vendors: | # | File Name | Source Type | Simulates | Rows (approx.) | |---|-----------|-------------|-----------|-----------------| | 1 | `Media_Spend_Report_2024-25.xlsx` | `media` | Agency media spend export | ~1,870 | | 2 | `Sales_Extract_All_Regions.xlsx` | `sales` | ERP/sales system extract | ~1,475 | | 3 | `Consumer_Promotions_Master.xlsx` | `consumer_promo` | Marketing promo tracker | ~750 | | 4 | `Trade_Promo_Events_Log.xlsx` | `trade_promo` | Trade marketing event log | ~735 | | 5 | `Weather_Economic_Data.xlsx` | `external_factors` | External data vendor feed | ~740 | **To regenerate raw files:** ```bash python generate_raw_data.py ``` This reads the clean synthetic CSVs from `data/synthetic/` and introduces controlled data quality issues. --- ### Data Quality Issues (Simulated) Each raw file has specific, realistic data quality problems that the pipeline is designed to handle: #### Media Data (`Media_Spend_Report_2024-25.xlsx`) | Issue | Details | Why It Happens in Real Life | |-------|---------|----------------------------| | **Renamed columns** | `channel` → `Media Channel`, `spend` → `Spend_USD`, `impressions` → `Imp`, `brand` → `Brand Name` | Different agencies and platforms use different naming conventions | | **Mixed date formats** | `MM/DD/YYYY`, `DD-Mon-YYYY`, `YYYY/MM/DD` mixed in the same column | Data combined from multiple exports across different locales | | **Inconsistent channel casing** | `tv`, `TV`, `Tv`, `TV ` (with trailing space) for the same channel | Manual data entry, copy-paste from different sources | | **Missing clicks** | ~8% of click values are `NaN` | Not all media platforms report clicks (e.g., TV, Radio) | | **Missing regions** | ~5% of region values are `NaN` | Some campaigns are national (no region tagged) | | **Missing leads** | ~6% of lead values are `NaN` | Lead tracking not set up for all campaigns | | **Spend outliers** | ~2% of spend values multiplied by 10x | Fat-finger errors, currency unit mistakes (e.g., entering cents instead of dollars) | | **Duplicate rows** | ~3% duplicate records | Re-runs of export queries, overlapping report pulls | #### Sales Data (`Sales_Extract_All_Regions.xlsx`) | Issue | Details | Why It Happens in Real Life | |-------|---------|----------------------------| | **Renamed columns** | `product` → `Product Name`, `revenue` → `Sales_Revenue`, `price` → `Unit Price`, `units_sold` → `Units` | ERP systems have their own column naming conventions | | **DD/MM/YYYY dates** | 40% `DD/MM/YYYY`, 30% `MM-DD-YYYY`, 30% `YYYY-MM-DD` | International teams using different locale settings | | **Negative revenues** | ~1% of revenue values are negative | Returns/refunds mixed into the sales data | | **Junk column** | `Unnamed: 0` column with sequential integers | Excel auto-generated index column from a prior save | | **Missing new_customers** | ~6% null values | Customer tracking not available for all channels | | **Missing prices** | ~3% null values | Promotional pricing not recorded properly | | **Duplicate rows** | ~2% duplicates | Overlapping regional exports | #### Consumer Promo Data (`Consumer_Promotions_Master.xlsx`) | Issue | Details | Why It Happens in Real Life | |-------|---------|----------------------------| | **Renamed columns** | `promo_id` → `Promo ID`, `promo_type` → `Type`, `promo_spend` → `Spend`, `start_date` → `Start`, `end_date` → `End` | Marketing teams use informal spreadsheet naming | | **Inconsistent promo type casing** | `coupon`, `COUPON`, `Coupon`, `coupon ` for the same type; `BOGO`, `bogo`, `Buy One Get One` | Multiple team members entering data manually | | **Mixed date formats** | Start/End dates in `YYYY-MM-DD`, `Mon DD, YYYY`, `MM/DD/YYYY` | Promo dates copied from different calendar systems | | **Missing units_redeemed** | ~10% null values | Redemption tracking delayed, especially for in-store promos | | **Missing promo_depth** | ~7% null values | Some promos have variable/dynamic discounts | | **Spend outliers** | ~3% of spend values multiplied by 5-15x | Budget approvals recorded instead of actual spend | | **Duplicate rows** | ~4% duplicates | Promo events spanning multiple periods double-counted | #### Trade Promo Data (`Trade_Promo_Events_Log.xlsx`) | Issue | Details | Why It Happens in Real Life | |-------|---------|----------------------------| | **Renamed columns** | `event_id` → `Event ID`, `retailer` → `Retailer Name`, `planned_spend` → `Plan_Spend`, `actual_spend` → `Act_Spend` | Trade marketing systems export with custom labels | | **Compliance status typos** | `Complient`, `Partial`, `NC`, `COMPLIANT`, `Part. Compliant` | Field reps entering compliance status manually on mobile devices | | **Mixed date formats** | ~5% of dates in `DD-Mon-YY` format, rest in original format | Some events entered from handwritten notes | | **Missing baseline_volume** | ~12% null values | Baseline calculation requires historical data not always available | | **Missing compliance_status** | ~5% null values | Compliance audits not completed for all events | | **Actual spend outliers** | ~2% of actual_spend multiplied by 100x | Units error (entering in minor currency units vs. major) | | **Duplicate rows** | ~2% duplicates | Same events reported by both brand team and retailer | #### External Factors Data (`Weather_Economic_Data.xlsx`) | Issue | Details | Why It Happens in Real Life | |-------|---------|----------------------------| | **Renamed columns** | `temperature` → `temp_f`, `precipitation` → `rain_inches`, `holiday_flag` → `is_holiday`, `economic_index` → `econ_idx` | Vendor APIs return abbreviated field names | | **Boolean as Yes/No strings** | `holiday_flag` contains `Yes`/`No` instead of `True`/`False`; `event_flag` contains `Y`/`N` | CSV/Excel export from legacy systems that don't support boolean types | | **Sensor error values** | ~1% of temperature readings are `-999.0` | Weather station sensor failures recorded as sentinel values | | **Missing temperature** | ~3% null values | Weather station outages | | **Missing economic_index** | ~2% null values | Economic data published with a lag, some periods missing | | **Duplicate rows** | ~1% duplicates | Overlapping API pulls | --- ### Pipeline Operations Each operation is a discrete, traceable step. Here's what each one does, why it's needed, and how it works internally: --- #### Step 1: Load Raw **What it does:** Reads a raw Excel file (`.xlsx`) from the `data/raw/` directory into an in-memory Pandas DataFrame. **Why it's required:** The pipeline needs the data in memory to perform analysis and transformations. Loading also validates that the file exists and is readable. **How it works:** ``` 1. Look up the raw file name for the given source_type (e.g., 'media' → 'Media_Spend_Report_2024-25.xlsx') 2. Read with pd.read_excel(filepath) 3. Store the DataFrame in pipeline state as raw_df 4. Set the source's layer to 'raw' 5. Reset any previous bronze/silver/gold state for this source 6. Log: "Loaded {N} rows, {M} columns from {filename}" ``` **API:** `POST /api/pipeline/load-raw` with `{"source_type": "media"}` **Output:** Row count, column count, column names --- #### Step 2: Data Profiling **What it does:** Computes comprehensive statistics for every column in the raw data — data types, null percentages, distributions, outliers, date format detection, mixed casing detection. **Why it's required:** Before you can clean data, you need to understand what's wrong with it. Profiling surfaces all quality issues systematically rather than discovering them one-by-one during analysis. It answers questions like: - How many values are missing per column? - Are there outliers? How extreme? - What date formats are present? - Are there sentinel values (like `-999`)? - Are string values inconsistently cased? **How it works per column:** ``` For each column in the DataFrame: 1. Basic stats: total count, null count, null %, unique count 2. TYPE INFERENCE — try to classify the column: a. NUMERIC: If >50% of non-null values can be parsed as numbers: - Compute: min, max, mean, median, std deviation - IQR-based outlier detection: values outside [Q1 - 1.5*IQR, Q3 + 1.5*IQR] - Sentinel detection: count of values < -900 (e.g., -999) - Negative value count (flags potential errors in spend/revenue columns) b. DATE: If >50% of non-null values can be parsed as dates: - Date range: earliest to latest - Format detection: tests each value against 8 known date patterns: YYYY-MM-DD, MM/DD/YYYY, DD/MM/YYYY, DD-Mon-YYYY, DD-Mon-YY, Mon DD YYYY, MM-DD-YYYY, YYYY/MM/DD - Parse failure count: values that couldn't be interpreted as dates c. STRING: Everything else: - Top 5 most frequent values with counts - Mixed casing detection: compares unique values vs unique values after lowercasing — if different, casing is inconsistent - Reports the number of "casing variants" (e.g., 'TV', 'tv', 'Tv' = 2 variants) ``` **Dataset-level stats:** - Total duplicate rows (full row matches) - Quality score: `(1 - missing_cells / total_cells) × 100` - Total missing cells across all columns **API:** `POST /api/pipeline/profile` with `{"source_type": "media"}` **Output example:** ```json { "rows": 1872, "columns_count": 14, "duplicates": 54, "quality_score": 96.8, "missing_total": 385, "column_profiles": [ { "name": "Media Channel", "dtype": "object", "inferred_type": "string", "nulls": 0, "null_pct": 0.0, "unique": 9, "mixed_casing": true, "casing_variants": 3, "top_values": [{"value": "tv", "count": 210}, ...] }, { "name": "Spend_USD", "dtype": "float64", "inferred_type": "numeric", "nulls": 0, "min": 120.50, "max": 95420.00, "mean": 4520.30, "outliers": 38, "negatives": 0 } ] } ``` --- #### Step 3: Auto Column Mapping **What it does:** Automatically figures out which raw column corresponds to which schema column. For example, it determines that `Spend_USD` in the raw file should map to the standard `spend` column. **Why it's required:** Every data source uses different column names. Media agencies call it "Spend_USD", finance teams call it "Cost", analytics platforms call it "Amount Spent". The system needs a single, consistent schema to work with. Manual mapping of dozens of columns across 5 data sources is tedious and error-prone — auto-mapping handles this intelligently. **How it works — Three-Tier Matching:** ``` For each raw column name, try matching in this priority order: ┌─────────────────────────────────────────────────────────┐ │ TIER 1: EXACT MATCH (Confidence: 100%) │ │ │ │ Normalize the raw column: lowercase, strip whitespace, │ │ replace spaces and hyphens with underscores. │ │ │ │ Example: "clicks" → "clicks" = exact match │ │ Example: "date" → "date" = exact match │ └─────────────────────────────┬───────────────────────────┘ │ No match? Try next tier ┌─────────────────────────────▼───────────────────────────┐ │ TIER 2: ALIAS DICTIONARY LOOKUP (Confidence: 92%) │ │ │ │ Check against a curated dictionary of ~60 known column │ │ name aliases. Each standard column has a list of known │ │ alternative names from common platforms and systems. │ │ │ │ Example: "Spend_USD" → alias "spend_usd" → maps to │ │ "spend" (92% confidence) │ │ Example: "Imp" → alias "imp" → maps to │ │ "impressions" (92% confidence) │ │ Example: "Brand Name" → alias "brand_name" → maps to │ │ "brand" (92% confidence) │ └─────────────────────────────┬───────────────────────────┘ │ No match? Try next tier ┌─────────────────────────────▼───────────────────────────┐ │ TIER 3: FUZZY MATCHING (Confidence: varies, min 60%) │ │ │ │ Uses Python's difflib.SequenceMatcher to compute string │ │ similarity ratio between the raw column name and all │ │ remaining unmapped schema columns. │ │ │ │ Picks the best match above 60% similarity threshold. │ │ Confidence score = similarity ratio × 100. │ │ │ │ Example: "campaign" → 78% similar to "campaign_name" │ │ → maps with 78% confidence │ └─────────────────────────────┬───────────────────────────┘ │ No match above 60%? ┌─────────────────────────────▼───────────────────────────┐ │ SPECIAL CASES │ │ │ │ • Junk columns (starting with "Unnamed") → marked as │ │ "__drop__" (100% confidence, method: "drop") │ │ • No match found → marked as "__unmapped__" │ │ (0% confidence, method: "unmapped") │ └─────────────────────────────────────────────────────────┘ ``` **Collision prevention:** Once a target column is matched, it's removed from the candidate pool. This prevents two raw columns from mapping to the same target. **API:** `POST /api/pipeline/auto-map` with `{"source_type": "media"}` **Output example:** ```json { "mappings": { "Media Channel": {"mapped_to": "channel", "confidence": 92, "method": "alias"}, "Spend_USD": {"mapped_to": "spend", "confidence": 92, "method": "alias"}, "Imp": {"mapped_to": "impressions", "confidence": 92, "method": "alias"}, "clicks": {"mapped_to": "clicks", "confidence": 100, "method": "exact"}, "Unnamed: 0": {"mapped_to": "__drop__", "confidence": 100, "method": "drop"} }, "target_columns": ["date", "channel", "spend", "impressions", "brand", ...] } ``` --- #### Step 4: Apply Mapping (Raw → Bronze) **What it does:** Takes the column mappings (from Step 3) and physically renames the columns, drops junk/unmapped columns, and creates the Bronze DataFrame. **Why it's required:** This is the structural transformation — the data now conforms to the expected schema column names. Without this, downstream transformations wouldn't know which column is "spend" vs "Spend_USD" vs "cost". It also cleans up garbage columns that would pollute analysis. **How it works:** ``` 1. Build a rename dictionary from confirmed mappings Example: {"Media Channel" → "channel", "Spend_USD" → "spend", ...} 2. Build a drop list from mappings marked as __drop__ or __unmapped__ Example: ["Unnamed: 0"] 3. Drop junk columns from DataFrame 4. Rename remaining columns to standard names 5. Clean string columns: - Strip leading/trailing whitespace from all string values - Convert literal "nan" strings back to actual NaN 6. Remove fully empty rows (rows where every cell is NaN) 7. Store result as bronze_df 8. Also copy to silver_df (silver starts as a copy of bronze, then transforms are applied incrementally) 9. Set layer to 'bronze' ``` **API:** `POST /api/pipeline/apply-mapping` with `{"source_type": "media"}` --- #### Step 5: Date Standardization (Bronze → Silver) **What it does:** Converts all date columns to a consistent `YYYY-MM-DD` format, regardless of what format they were originally in. **Why it's required:** A single dataset might contain dates in 3-4 different formats (`01/15/2024`, `15-Jan-2024`, `2024/01/15`) because data was compiled from multiple sources or regions. Date sorting, filtering, time series analysis, and joins between tables all require consistent date formatting. Ambiguous dates like `01/02/2024` (is that Jan 2 or Feb 1?) must be resolved. **How it works:** ``` 1. Identify all date columns from the schema definition (e.g., 'date', 'start_date', 'end_date') 2. For each date column: a. Count nulls BEFORE transformation b. Parse with pd.to_datetime(format='mixed', dayfirst=False) - 'mixed' format allows pandas to try multiple date patterns - dayfirst=False resolves ambiguous dates as MM/DD (US convention) c. Count nulls AFTER transformation (new nulls = unparseable values) d. Detect which formats were present in the original data by testing a 50-row sample against 8 known format patterns e. Convert all successfully parsed dates to 'YYYY-MM-DD' string format f. Values that couldn't be parsed remain as NaN 3. Log: "Standardized {N} date columns. Fixed {M} values." ``` **Date format patterns detected:** | Pattern | Format Code | Example | |---------|------------|---------| | `YYYY-MM-DD` | `%Y-%m-%d` | `2024-01-15` | | `MM/DD/YYYY` | `%m/%d/%Y` | `01/15/2024` | | `DD/MM/YYYY` | `%d/%m/%Y` | `15/01/2024` | | `DD-Mon-YYYY` | `%d-%b-%Y` | `15-Jan-2024` | | `DD-Mon-YY` | `%d-%b-%y` | `15-Jan-24` | | `Mon DD, YYYY` | `%b %d, %Y` | `Jan 15, 2024` | | `MM-DD-YYYY` | `%m-%d-%Y` | `01-15-2024` | | `YYYY/MM/DD` | `%Y/%m/%d` | `2024/01/15` | **API:** `POST /api/pipeline/transform/dates` with `{"source_type": "media"}` **Output example:** ```json { "results": [ { "column": "date", "formats_found": ["MM/DD/YYYY", "DD-Mon-YYYY", "YYYY/MM/DD"], "converted": 1872, "failed": 0 } ], "total_fixed": 1872 } ``` --- #### Step 6: Missing Value Imputation **What it does:** Fills in missing (`NaN`) values using statistically appropriate methods based on the column's data type and business context. **Why it's required:** Missing values cause multiple problems: - Many statistical models and chart libraries can't handle NaN values - Missing data biases aggregations (averages, totals, etc.) - Downstream joins may fail or produce incorrect results - A 10% missing rate in clicks means CTR calculations are wrong for those periods The imputation strategy must be appropriate for each column type — you can't fill missing dates with a median, and you shouldn't fill missing IDs. **How it works — Strategy per column type:** ``` For each column with missing values: ┌─────────────────────────────────────────────────────┐ │ STRATEGY SELECTION BY COLUMN TYPE │ │ │ │ ID Columns (promo_id, event_id, ad_id): │ │ → SKIP: IDs are unique identifiers, imputing │ │ them would create fake records │ │ │ │ Date Columns (date, start_date, end_date): │ │ → FORWARD FILL: Use the previous row's date │ │ Rationale: time series data is sequential, │ │ a missing date likely falls between neighbors │ │ │ │ Float Columns (spend, revenue, price, etc.): │ │ → MEDIAN: Use the column's median value │ │ Rationale: median is robust to outliers │ │ (unlike mean, which gets skewed by extremes) │ │ │ │ Integer Columns (clicks, conversions, units): │ │ → MEDIAN + ROUND: Median, then round to integer │ │ Rationale: same as float, but maintain int type │ │ Uses nullable Int64 dtype (supports NaN) │ │ │ │ Boolean Columns (holiday_flag, event_flag): │ │ → FILL FALSE: Assume no holiday/event │ │ Rationale: holidays are rare; missing usually │ │ means "no event" rather than unknown event │ │ │ │ String/Categorical (channel, brand, region): │ │ → MODE: Use the most frequent value │ │ Rationale: categorical data should match the │ │ most common category (conservative approach) │ └─────────────────────────────────────────────────────┘ ``` **API:** `POST /api/pipeline/transform/missing` with `{"source_type": "media"}` **Output example:** ```json { "results": [ {"column": "clicks", "missing_before": 150, "missing_after": 0, "method": "median (245.0)", "imputed": 150}, {"column": "region", "missing_before": 94, "missing_after": 0, "method": "mode (\"North\")", "imputed": 94}, {"column": "leads", "missing_before": 112, "missing_after": 0, "method": "median (18.0)", "imputed": 112} ], "total_imputed": 356 } ``` --- #### Step 7: Outlier Detection & Handling **What it does:** Identifies values that are statistically extreme or represent data entry errors, then caps them at reasonable bounds (winsorization) rather than deleting the entire row. **Why it's required:** Outliers distort every statistical analysis: - A single `$95,000` spend entry (should be `$9,500`) inflates average spend by 5-10% - Outlier revenue values skew ROAS calculations - Sentinel values like `-999` (sensor errors) get treated as real negatives - Fat-finger errors propagate through all downstream charts and models **Why winsorization (capping) instead of deletion:** - Deleting rows loses all the other valid columns in that row - The row represents a real marketing event; only the specific value is wrong - Capping to the statistical boundary preserves the directional information **How it works:** ``` For each numeric column defined in the schema: 1. CONVERT TO FLOAT64 Why: Previous missing value imputation may have set columns to Int64 (nullable integer) dtype. Float64 is required for statistical operations and clip(). 2. SENTINEL VALUE DETECTION Check for values < -900 (common sensor error codes: -999, -998, etc.) If found: Replace -999, -998, -997 with NaN These are not real data — they're error codes masquerading as numbers. 3. IQR-BASED OUTLIER DETECTION Q1 = 25th percentile Q3 = 75th percentile IQR = Q3 - Q1 (interquartile range) Lower bound = Q1 - 1.5 × IQR Upper bound = Q3 + 1.5 × IQR Values outside [lower, upper] are classified as outliers. This is the standard Tukey's fence method used in box plots. 4. POSITIVE-ONLY CONSTRAINT For columns that can never be negative in business context: (spend, revenue, impressions, clicks, conversions, units_sold, price, promo_spend, planned_spend, actual_spend, temperature, precipitation, etc.) → Set lower bound to max(0, calculated_lower) → Also count and fix any negative values Why: You can't have -$500 in media spend or -100 impressions. 5. WINSORIZATION (Capping) All outlier values are clipped to [lower_bound, upper_bound]: - Values below lower bound → set to lower bound - Values above upper bound → set to upper bound Example: If spend bounds are [$200, $12,000]: - A value of $95,420 (fat-finger) → capped to $12,000 - A value of -$500 (error) → capped to $0 ``` **Minimum data requirement:** Skips columns with fewer than 10 non-null values (not enough data for meaningful statistical bounds). **API:** `POST /api/pipeline/transform/outliers` with `{"source_type": "media"}` **Output example:** ```json { "results": [ {"column": "spend", "outliers_found": 38, "sentinel_values": 0, "negatives_fixed": 0, "bounds": [120.50, 12000.00], "action": "capped"}, {"column": "impressions", "outliers_found": 12, "sentinel_values": 0, "negatives_fixed": 0, "bounds": [1000, 500000], "action": "capped"}, {"column": "clicks", "outliers_found": 5, "sentinel_values": 0, "negatives_fixed": 0, "bounds": [0, 8500], "action": "capped"} ], "total_outliers": 55 } ``` --- #### Step 8: Merge to Gold (Silver → Gold) **What it does:** Takes all 5 Silver DataFrames, performs final cleaning and normalization, and saves them as individual CSV files in the `data/gold/` directory. **Why it's required:** The Gold layer is the single source of truth for all downstream dashboards. This step ensures: - No duplicate records inflate metrics - All string values are consistently formatted (no `tv` vs `TV` vs `Tv`) - Boolean values are actual booleans (not `Yes`/`No` strings) - Data is chronologically sorted for time series analysis - Files are in CSV format for fast loading by DataService **How it works:** ``` For each of the 5 source types: 1. DEDUPLICATION - Remove exact duplicate rows (every column matches) - Track count of duplicates removed - Why: Prevents double-counting in aggregations 2. STRING VALUE NORMALIZATION Standardize common string values using a lookup dictionary: Channel: 'tv' → 'TV', 'digital display' → 'Digital Display', etc. Brand: 'alpha' → 'Alpha', 'beta' → 'Beta', etc. Region: 'north' → 'North', 'south' → 'South', etc. Compliance: 'complient' → 'Compliant', 'nc' → 'Non-compliant', etc. Promo Type: 'bogo' → 'BOGO', 'cash back' → 'Cashback', etc. Process: lowercase the value → look up in normalization map → replace Values not in the map are left unchanged. 3. BOOLEAN CONVERSION holiday_flag: 'Yes'/'No'/'Y'/'N'/'True'/'False'/'1'/'0' → True/False event_flag: Same conversion Unrecognized values → default to False 4. CHRONOLOGICAL SORTING Parse 'date' column as datetime, sort ascending, reset index Convert back to 'YYYY-MM-DD' string for CSV storage 5. SAVE TO CSV Save as: data/gold/{source_type}_data.csv Files: media_data.csv, sales_data.csv, consumer_promo_data.csv, trade_promo_data.csv, external_factors_data.csv No index column (index=False) 6. Update pipeline state to 'gold' for all sources ``` **API:** `POST /api/pipeline/to-gold` **Output example:** ```json { "success": true, "stats": { "media": {"rows": 1818, "columns": 14, "duplicates_removed": 54}, "sales": {"rows": 1446, "columns": 9, "duplicates_removed": 29}, "consumer_promo": {"rows": 700, "columns": 14, "duplicates_removed": 50}, "trade_promo": {"rows": 718, "columns": 14, "duplicates_removed": 17}, "external_factors": {"rows": 725, "columns": 9, "duplicates_removed": 8} }, "gold_dir": "data/gold" } ``` --- #### Step 9: Activate Gold Layer **What it does:** Hot-reloads the application's DataService to use Gold layer CSVs instead of the original synthetic data, without restarting the server. **Why it's required:** The DataService is initialized at app startup and loads data into memory. After the pipeline creates Gold CSVs, the running app would still be using the old synthetic data. This step swaps the data source live, so all dashboards immediately reflect the cleaned, pipeline-processed data. **How it works:** ``` 1. Check that gold directory exists 2. Call data_service.reload_from_gold(gold_dir) 3. DataService re-reads all CSVs from data/gold/ 4. All dashboard routes now serve cleaned data 5. DataService._source changes from 'synthetic' to 'gold' ``` **Effect on dashboards:** - Revenue numbers may change slightly (outliers removed, duplicates cleaned) - Channel names are consistent (no more `tv` vs `TV`) - Date-based filtering works reliably - Missing value gaps in charts are filled **API:** `POST /api/pipeline/activate-gold` --- ### NOVA Pipeline Agents The UI presents three "NOVA Pipeline Agent" cards that orchestrate the pipeline operations in logical groups: | Agent Card | Operations Performed | Description | |------------|---------------------|-------------| | **Data Profiler (NOVA)** | Load Raw → Profile (for all 5 sources) | Loads all raw Excel files and runs comprehensive profiling. Shows column-level statistics, quality scores, and detected issues in a tabular results panel. | | **Auto Column Mapper (NOVA)** | Auto-Map → Apply Mapping (for all 5 sources) | Runs three-tier column matching, displays mapping results with confidence badges (green ≥90%, yellow ≥70%, red <70%), then applies confirmed mappings to create Bronze DataFrames. | | **Apply All Transforms (NOVA)** | Date Transform → Missing → Outliers → Merge to Gold (for all 5 sources) | Sequentially runs all three Silver transformations across all sources, then merges to Gold. Shows individual transform results with statistics. | Each agent card also has individual transform buttons for running steps one at a time: | Transform Card | What it Runs | |----------------|-------------| | Date Standardization | `transform_dates` on all sources | | Missing Value Handler | `transform_missing` on all sources | | Outlier Detection | `transform_outliers` on all sources | | Merge to Gold | `merge_to_gold` | --- ### Column Alias Dictionary The auto-mapper uses a curated dictionary of ~60 known column name aliases. This is the complete mapping: | Standard Column | Known Aliases | |----------------|---------------| | `date` | date, dt, week, period | | `channel` | media_channel, media channel, platform, channel_name | | `sub_channel` | sub_channel, sub channel, subchannel, sub_platform | | `campaign_name` | campaign, campaign_name, camp_name, campaign_id | | `campaign_objective` | objective, campaign_objective, obj, goal | | `ad_id` | ad_id, ad id, creative_id, ad_identifier | | `ad_format` | format, ad_format, creative_format, ad_type | | `spend` | spend_usd, spend, cost, media_spend, amount_spent, budget, investment | | `impressions` | imp, imps, impressions, total_impressions, views | | `clicks` | clicks, click, total_clicks | | `conversions` | conversions, conv, conversion, total_conversions | | `leads` | leads, lead, total_leads | | `region` | region, geo, geography, area, territory | | `brand` | brand_name, brand, product_brand, brand_id | | `media_type` | type, media_type, paid_organic | | `product` | product_name, product, item, sku_name, sku | | `units_sold` | units, units_sold, quantity, qty, volume, unit_sold | | `revenue` | sales_revenue, revenue, total_revenue, sales, rev, gross_revenue | | `price` | unit_price, price, selling_price, avg_price, unit price | | `new_customers` | new_customers, new_cust, acquired, new_customer | | `promo_id` | promo_id, promo id, promotion_id, promo_code | | `promo_name` | promo_name, promo name, promotion_name, name | | `promo_type` | type, promo_type, promotion_type, promo_category | | `promo_mechanic` | mechanic, promo_mechanic, delivery_mechanism, mechanism | | `promo_spend` | spend, promo_spend, promo_cost, promotion_spend, cost | | `promo_depth` | depth_%, depth, promo_depth, discount_depth, discount_%, discount_pct | | `units_redeemed` | redeemed, units_redeemed, redemptions, redeemed_units | | `total_units_distributed` | distributed, total_units_distributed, total_distributed, units_distributed | | `start_date` | start, start_date, promo_start, begin_date, start date | | `end_date` | end, end_date, promo_end, finish_date, end date | | `event_id` | event_id, event id, event_code, trade_event_id | | `retailer` | retailer_name, retailer, account, customer_name, store | | `planned_spend` | plan_spend, planned_spend, budget_planned, planned_cost | | `actual_spend` | act_spend, actual_spend, actual_cost, real_spend | | `baseline_volume` | base_vol, baseline_volume, base_volume, baseline_vol | | `actual_volume` | act_vol, actual_volume, actual_vol, real_volume | | `compliance_status` | compliance, compliance_status, comp_status, execution_status | | `temperature` | temp_f, temp_c, temperature, avg_temp, avg_temperature | | `precipitation` | rain_inches, rainfall, precipitation, precip, rain | | `holiday_flag` | is_holiday, holiday_flag, holiday, holiday_indicator | | `holiday_name` | holiday_name, holiday_desc, holiday_description | | `economic_index` | econ_idx, economic_index, econ_index, consumer_confidence | | `competitor_price_index` | comp_price_idx, competitor_price_index, comp_idx, competitor_index | | `event_flag` | event_flag, event_indicator, special_event | | `event_name` | event_name, event_desc, event_description | --- ### Standard Value Normalization The Gold layer normalizes string values to a single canonical form. Here's the complete normalization map: #### Channels | Input Variants | Normalized To | |---------------|---------------| | `tv`, `television` | `TV` | | `digital display`, `display` | `Digital Display` | | `paid search`, `search` | `Paid Search` | | `social media`, `social` | `Social Media` | | `radio` | `Radio` | | `print` | `Print` | #### Brands | Input Variants | Normalized To | |---------------|---------------| | `alpha` | `Alpha` | | `beta` | `Beta` | | `gamma` | `Gamma` | #### Regions | Input Variants | Normalized To | |---------------|---------------| | `north` | `North` | | `south` | `South` | | `east` | `East` | | `west` | `West` | #### Compliance Status | Input Variants | Normalized To | |---------------|---------------| | `compliant`, `complient` | `Compliant` | | `partially compliant`, `partial`, `part. compliant` | `Partially Compliant` | | `non-compliant`, `noncompliant`, `nc` | `Non-compliant` | #### Promo Types | Input Variants | Normalized To | |---------------|---------------| | `coupon` | `Coupon` | | `discount %`, `discount%` | `Discount %` | | `bogo`, `buy one get one` | `BOGO` | | `cashback`, `cash back` | `Cashback` | | `free sample`, `freesample` | `Free Sample` | | `bundle deal`, `bundle` | `Bundle Deal` | | `off-invoice discount` | `Off-invoice discount` | | `bill-back` | `Bill-back` | | `scan-down` | `Scan-down` | | `display allowance` | `Display allowance` | | `slotting fee` | `Slotting fee` | | `co-op advertising` | `Co-op advertising` | | `volume rebate` | `Volume rebate` | --- ### Schema Definitions Each data source has a defined schema with required and optional fields: #### Media Schema | Field | Type | Required | Description | |-------|------|----------|-------------| | `date` | date | Yes | Activity date | | `channel` | string | Yes | Media channel (TV, Digital, etc.) | | `spend` | float | Yes | Spend amount ($) | | `impressions` | int | Yes | Number of impressions | | `brand` | string | Yes | Brand name | | `sub_channel` | string | No | Sub-channel (Facebook, Google, etc.) | | `campaign_name` | string | No | Campaign identifier | | `campaign_objective` | string | No | Campaign goal | | `ad_id` | string | No | Individual ad identifier | | `ad_format` | string | No | Creative format | | `clicks` | int | No | Number of clicks | | `conversions` | int | No | Number of conversions | | `leads` | int | No | Number of leads | | `region` | string | No | Geographic region | | `media_type` | string | No | Paid/Owned/Earned | #### Sales Schema | Field | Type | Required | Description | |-------|------|----------|-------------| | `date` | date | Yes | Sales date | | `product` | string | Yes | Product name/SKU | | `brand` | string | Yes | Brand name | | `units_sold` | int | Yes | Units sold | | `revenue` | float | Yes | Revenue ($) | | `price` | float | Yes | Selling price | | `region` | string | No | Geographic region | | `channel` | string | No | Sales channel | | `new_customers` | int | No | New customer count | #### Consumer Promo Schema | Field | Type | Required | Description | |-------|------|----------|-------------| | `date` | date | Yes | Activity date | | `promo_id` | string | Yes | Promo identifier | | `promo_name` | string | Yes | Promo name | | `promo_type` | string | Yes | Coupon/Discount/BOGO etc. | | `product` | string | Yes | Target product | | `promo_spend` | float | Yes | Promo cost ($) | | `start_date` | date | Yes | Promo start | | `end_date` | date | Yes | Promo end | | `brand` | string | Yes | Brand name | | `promo_mechanic` | string | No | Delivery mechanism | | `promo_depth` | float | No | Discount depth (%) | | `units_redeemed` | int | No | Units redeemed | | `total_units_distributed` | int | No | Total distributed | | `region` | string | No | Geographic region | #### Trade Promo Schema | Field | Type | Required | Description | |-------|------|----------|-------------| | `date` | date | Yes | Activity date | | `event_id` | string | Yes | Event identifier | | `promo_type` | string | Yes | Trade promo type | | `retailer` | string | Yes | Retailer/account name | | `product` | string | Yes | Target product/SKU | | `planned_spend` | float | Yes | Planned spend ($) | | `actual_spend` | float | Yes | Actual spend ($) | | `actual_volume` | float | Yes | During-promo volume | | `start_date` | date | Yes | Event start | | `end_date` | date | Yes | Event end | | `brand` | string | Yes | Brand name | | `baseline_volume` | float | No | Pre-promo baseline | | `compliance_status` | string | No | Execution compliance | | `region` | string | No | Geographic region | #### External Factors Schema | Field | Type | Required | Description | |-------|------|----------|-------------| | `date` | date | Yes | Date | | `temperature` | float | No | Average temperature | | `precipitation` | float | No | Rainfall amount | | `holiday_flag` | boolean | No | Holiday indicator | | `holiday_name` | string | No | Holiday name | | `economic_index` | float | No | Consumer confidence index | | `competitor_price_index` | float | No | Competitor pricing index | | `event_flag` | boolean | No | Special event indicator | | `event_name` | string | No | Event name | --- ### API Endpoints All pipeline endpoints are prefixed under the Data Management blueprint: | Method | Endpoint | Description | Request Body | |--------|----------|-------------|-------------| | `GET` | `/api/pipeline/status` | Get pipeline status for all sources | — | | `POST` | `/api/pipeline/load-raw` | Load a raw Excel file | `{"source_type": "media"}` | | `POST` | `/api/pipeline/profile` | Profile a loaded source | `{"source_type": "media"}` | | `POST` | `/api/pipeline/auto-map` | Auto-detect column mappings | `{"source_type": "media"}` | | `POST` | `/api/pipeline/apply-mapping` | Apply mappings to create Bronze | `{"source_type": "media", "mappings": {...}}` | | `POST` | `/api/pipeline/transform/dates` | Standardize date columns | `{"source_type": "media"}` | | `POST` | `/api/pipeline/transform/missing` | Impute missing values | `{"source_type": "media"}` | | `POST` | `/api/pipeline/transform/outliers` | Detect and handle outliers | `{"source_type": "media"}` | | `POST` | `/api/pipeline/to-gold` | Merge all Silver sources to Gold | — | | `POST` | `/api/pipeline/activate-gold` | Hot-reload DataService with Gold data | — | | `GET` | `/api/pipeline/preview?source_type=media&layer=silver` | Preview data at any layer | Query params | | `GET` | `/api/pipeline/log` | Get transformation log | — | --- ### Frontend Pipeline UI The Data Harmonization page (`templates/data_mgmt.html`) provides a visual interface for the pipeline: #### Pipeline Progress Tracker A horizontal stepper showing all 4 layers: **Raw → Bronze → Silver → Gold** - Each step shows a count (e.g., `3/5`) of how many sources have reached that layer - Steps turn green when all 5 sources are at that layer or beyond - Connectors between steps animate when transitions are happening #### Source Cards Grid Five cards (one per data source) showing: - Current layer badge (color-coded: gray=none, copper=raw, bronze=bronze, green=silver, gold=gold) - File name and size - Row × column dimensions - Action buttons contextual to current layer #### Results Panel Tabbed panel showing operation results: - **Profile Tab**: Column statistics table with type, nulls, outliers, distributions - **Mapping Tab**: Column mapping results with confidence badges and match methods - **Preview Tab**: Data preview at any layer (raw/bronze/silver/gold) - **Log Tab**: Chronological transformation log with timestamps #### Gold Banner Appears after Gold layer is created, with an "Activate Gold Layer" button that hot-reloads all dashboards with cleaned data. --- ## Running the Application ```bash # 1. Install dependencies pip install flask pandas numpy openpyxl # 2. Generate synthetic data (if not present) python generate_data.py # 3. Generate messy raw files (if not present) python generate_raw_data.py # 4. Start the Flask server python run.py # 5. Open in browser # http://localhost:5000 ``` **Pipeline workflow in the UI:** 1. Navigate to "Data Harmonization" (first item in sidebar) 2. Click "Data Profiler" agent card → loads and profiles all 5 sources 3. Click "Auto Column Mapper" agent card → maps columns and creates Bronze 4. Click "Apply All Transforms" agent card → runs all transforms and creates Gold 5. Click "Activate Gold Layer" → dashboards now use cleaned data --- ## Known Limitations 1. **In-memory state**: Pipeline state is held in the Flask process memory. Restarting the server (or Flask's debug reloader triggering) resets the pipeline state. Gold CSVs persist on disk and are auto-loaded on next startup. 2. **Date ambiguity**: Dates like `01/02/2024` are interpreted as MM/DD/YYYY (US convention) due to `dayfirst=False`. This may be incorrect for European data sources where it would mean Feb 1st, not Jan 2nd. 3. **Fuzzy matching threshold**: The 60% similarity threshold for fuzzy column matching may produce false positives on short column names (e.g., a 3-letter column matching a 4-letter target at 62% similarity). 4. **Single-process design**: The PipelineService singleton assumes a single Flask worker process. Multiple workers (e.g., gunicorn with multiple workers) would each have independent pipeline states. --- *Last updated: May 2026 — PRISM Marketing Intelligence powered by NOVA*