Spaces:
Runtime error
Runtime error
Download generate_raw_data.py from StrategyForge/PRISM-Marketing-Mix-Intelligence: direct link, hf CLI and curl.
- Browser
- Download file 10.5 kB
-
https://huggingface.co/spaces/StrategyForge/PRISM-Marketing-Mix-Intelligence/resolve/main/generate_raw_data.py
- Command line
-
hf download hf://spaces/StrategyForge/PRISM-Marketing-Mix-Intelligence/generate_raw_data.py
-
curl -L -o generate_raw_data.py https://huggingface.co/spaces/StrategyForge/PRISM-Marketing-Mix-Intelligence/resolve/main/generate_raw_data.py
10.5 kB
| """Generate messy raw Excel files that simulate real-world client data exports. | |
| Reads clean synthetic CSVs and introduces controlled data quality issues: | |
| - Renamed/inconsistent column names | |
| - Mixed date formats | |
| - Missing values, duplicates, outliers | |
| - Inconsistent casing and typos | |
| """ | |
| import pandas as pd | |
| import numpy as np | |
| import os | |
| np.random.seed(99) | |
| BASE_DIR = os.path.dirname(__file__) | |
| SYNTHETIC_DIR = os.path.join(BASE_DIR, 'data', 'synthetic') | |
| RAW_DIR = os.path.join(BASE_DIR, 'data', 'raw') | |
| os.makedirs(RAW_DIR, exist_ok=True) | |
| def mess_dates(series, formats=None, pct=1.0): | |
| """Convert a date column to mixed string formats.""" | |
| if formats is None: | |
| formats = ['%m/%d/%Y', '%d-%b-%Y', '%Y/%m/%d'] | |
| result = [] | |
| for val in series: | |
| try: | |
| dt = pd.to_datetime(val) | |
| if np.random.random() < pct: | |
| fmt = np.random.choice(formats) | |
| result.append(dt.strftime(fmt)) | |
| else: | |
| result.append(dt.strftime('%Y-%m-%d')) | |
| except Exception: | |
| result.append(val) | |
| return result | |
| def add_duplicates(df, pct=0.03): | |
| """Add duplicate rows.""" | |
| n_dupes = int(len(df) * pct) | |
| if n_dupes > 0: | |
| dupe_idx = np.random.choice(df.index, n_dupes, replace=True) | |
| dupes = df.loc[dupe_idx].copy() | |
| df = pd.concat([df, dupes], ignore_index=True) | |
| return df | |
| def add_nulls(df, column, pct=0.08): | |
| """Set random values to NaN.""" | |
| mask = np.random.random(len(df)) < pct | |
| df.loc[mask, column] = np.nan | |
| return df | |
| def generate_raw_media(): | |
| """Media data with renamed columns, mixed dates, casing issues, outliers.""" | |
| df = pd.read_csv(os.path.join(SYNTHETIC_DIR, 'media_data.csv')) | |
| # Rename columns to realistic messy names | |
| df = df.rename(columns={ | |
| 'channel': 'Media Channel', | |
| 'sub_channel': 'Sub Channel', | |
| 'spend': 'Spend_USD', | |
| 'impressions': 'Imp', | |
| 'brand': 'Brand Name', | |
| 'campaign_name': 'Campaign', | |
| 'campaign_objective': 'Objective', | |
| 'ad_format': 'Format', | |
| 'media_type': 'Type', | |
| }) | |
| # Mix date formats | |
| df['date'] = mess_dates(df['date']) | |
| # Inconsistent channel casing | |
| casing_variants = { | |
| 'TV': ['tv', 'TV ', 'Tv', 'TV', 'tv '], | |
| 'Radio': ['radio', 'RADIO', 'Radio', 'Radio '], | |
| 'Print': ['print', 'PRINT', 'Print', 'Print '], | |
| } | |
| for std, variants in casing_variants.items(): | |
| mask = df['Media Channel'] == std | |
| df.loc[mask, 'Media Channel'] = np.random.choice(variants, mask.sum()) | |
| # Missing values | |
| df = add_nulls(df, 'clicks', 0.08) | |
| df = add_nulls(df, 'region', 0.05) | |
| df = add_nulls(df, 'leads', 0.06) | |
| # Outliers: 2% of spend values multiplied by 10x (fat-finger errors) | |
| outlier_mask = np.random.random(len(df)) < 0.02 | |
| df.loc[outlier_mask, 'Spend_USD'] = df.loc[outlier_mask, 'Spend_USD'] * 10 | |
| # Add duplicates | |
| df = add_duplicates(df, 0.03) | |
| # Shuffle rows | |
| df = df.sample(frac=1, random_state=42).reset_index(drop=True) | |
| df.to_excel(os.path.join(RAW_DIR, 'Media_Spend_Report_2024-25.xlsx'), index=False) | |
| print(f"Raw media: {len(df)} rows -> Media_Spend_Report_2024-25.xlsx") | |
| def generate_raw_sales(): | |
| """Sales data with renamed columns, format issues, negative revenues.""" | |
| df = pd.read_csv(os.path.join(SYNTHETIC_DIR, 'sales_data.csv')) | |
| # Rename columns | |
| df = df.rename(columns={ | |
| 'product': 'Product Name', | |
| 'revenue': 'Sales_Revenue', | |
| 'price': 'Unit Price', | |
| 'units_sold': 'Units', | |
| }) | |
| # Mix date formats - some DD/MM/YYYY | |
| dates_mixed = [] | |
| for val in df['date']: | |
| dt = pd.to_datetime(val) | |
| r = np.random.random() | |
| if r < 0.4: | |
| dates_mixed.append(dt.strftime('%d/%m/%Y')) | |
| elif r < 0.7: | |
| dates_mixed.append(dt.strftime('%m-%d-%Y')) | |
| else: | |
| dates_mixed.append(dt.strftime('%Y-%m-%d')) | |
| df['date'] = dates_mixed | |
| # Missing values | |
| df = add_nulls(df, 'new_customers', 0.06) | |
| df = add_nulls(df, 'Unit Price', 0.03) | |
| # Outliers: 1% negative revenues (returns mixed in) | |
| neg_mask = np.random.random(len(df)) < 0.01 | |
| df.loc[neg_mask, 'Sales_Revenue'] = -abs(df.loc[neg_mask, 'Sales_Revenue']) * np.random.uniform(0.1, 0.3, neg_mask.sum()) | |
| # Add a junk column (from prior Excel export) | |
| df.insert(0, 'Unnamed: 0', range(len(df))) | |
| # Add duplicates | |
| df = add_duplicates(df, 0.02) | |
| df = df.sample(frac=1, random_state=42).reset_index(drop=True) | |
| df.to_excel(os.path.join(RAW_DIR, 'Sales_Extract_All_Regions.xlsx'), index=False) | |
| print(f"Raw sales: {len(df)} rows -> Sales_Extract_All_Regions.xlsx") | |
| def generate_raw_consumer_promo(): | |
| """Consumer promo with renamed cols, inconsistent promo types, mixed dates.""" | |
| df = pd.read_csv(os.path.join(SYNTHETIC_DIR, 'consumer_promo_data.csv')) | |
| # Rename columns | |
| df = df.rename(columns={ | |
| 'promo_id': 'Promo ID', | |
| 'promo_name': 'Promo Name', | |
| 'promo_type': 'Type', | |
| 'promo_mechanic': 'Mechanic', | |
| 'promo_spend': 'Spend', | |
| 'promo_depth': 'Depth_%', | |
| 'start_date': 'Start', | |
| 'end_date': 'End', | |
| 'units_redeemed': 'Redeemed', | |
| 'total_units_distributed': 'Distributed', | |
| 'brand': 'Brand', | |
| }) | |
| # Mix date formats for start/end | |
| df['Start'] = mess_dates(df['Start'], ['%Y-%m-%d', '%b %d, %Y', '%m/%d/%Y']) | |
| df['End'] = mess_dates(df['End'], ['%Y-%m-%d', '%b %d, %Y', '%m/%d/%Y']) | |
| df['date'] = mess_dates(df['date'], ['%Y-%m-%d', '%d-%b-%Y']) | |
| # Inconsistent promo type casing | |
| type_variants = { | |
| 'Coupon': ['coupon', 'COUPON', 'Coupon', 'coupon '], | |
| 'Discount %': ['discount %', 'DISCOUNT %', 'Discount%', 'Discount %'], | |
| 'BOGO': ['BOGO', 'bogo', 'Bogo', 'Buy One Get One'], | |
| 'Cashback': ['cashback', 'CASHBACK', 'Cash Back', 'Cashback'], | |
| 'Free Sample': ['free sample', 'FREE SAMPLE', 'Free sample', 'FreeSample'], | |
| 'Bundle Deal': ['bundle deal', 'BUNDLE DEAL', 'Bundle', 'Bundle Deal'], | |
| } | |
| for std, variants in type_variants.items(): | |
| mask = df['Type'] == std | |
| if mask.sum() > 0: | |
| df.loc[mask, 'Type'] = np.random.choice(variants, mask.sum()) | |
| # Missing values | |
| df = add_nulls(df, 'Redeemed', 0.10) | |
| df = add_nulls(df, 'Depth_%', 0.07) | |
| # Outliers: 3% extreme spend values | |
| outlier_mask = np.random.random(len(df)) < 0.03 | |
| df.loc[outlier_mask, 'Spend'] = df.loc[outlier_mask, 'Spend'] * np.random.uniform(5, 15, outlier_mask.sum()) | |
| # Add duplicates | |
| df = add_duplicates(df, 0.04) | |
| df = df.sample(frac=1, random_state=42).reset_index(drop=True) | |
| df.to_excel(os.path.join(RAW_DIR, 'Consumer_Promotions_Master.xlsx'), index=False) | |
| print(f"Raw consumer promo: {len(df)} rows -> Consumer_Promotions_Master.xlsx") | |
| def generate_raw_trade_promo(): | |
| """Trade promo with renamed cols, compliance typos, spend outliers.""" | |
| df = pd.read_csv(os.path.join(SYNTHETIC_DIR, 'trade_promo_data.csv')) | |
| # Rename columns | |
| df = df.rename(columns={ | |
| 'event_id': 'Event ID', | |
| 'promo_type': 'Promo Type', | |
| 'retailer': 'Retailer Name', | |
| 'planned_spend': 'Plan_Spend', | |
| 'actual_spend': 'Act_Spend', | |
| 'baseline_volume': 'Base_Vol', | |
| 'actual_volume': 'Act_Vol', | |
| 'compliance_status': 'Compliance', | |
| 'start_date': 'Start Date', | |
| 'end_date': 'End Date', | |
| }) | |
| # Mix some dates to DD-MMM-YY | |
| date_mask = np.random.random(len(df)) < 0.05 | |
| for idx in df[date_mask].index: | |
| try: | |
| dt = pd.to_datetime(df.at[idx, 'date']) | |
| df.at[idx, 'date'] = dt.strftime('%d-%b-%y') | |
| except Exception: | |
| pass | |
| # Compliance status typos | |
| compliance_typos = { | |
| 'Compliant': ['Compliant', 'compliant', 'Complient', 'COMPLIANT'], | |
| 'Partially Compliant': ['Partial', 'partially compliant', 'Partially Compliant', 'Part. Compliant'], | |
| 'Non-compliant': ['Non-compliant', 'non-compliant', 'NonCompliant', 'NC'], | |
| } | |
| for std, variants in compliance_typos.items(): | |
| mask = df['Compliance'] == std | |
| if mask.sum() > 0: | |
| df.loc[mask, 'Compliance'] = np.random.choice(variants, mask.sum()) | |
| # Missing values | |
| df = add_nulls(df, 'Base_Vol', 0.12) | |
| df = add_nulls(df, 'Compliance', 0.05) | |
| # Outliers: some actual_spend values are 100x (units error) | |
| outlier_mask = np.random.random(len(df)) < 0.02 | |
| df.loc[outlier_mask, 'Act_Spend'] = df.loc[outlier_mask, 'Act_Spend'] * 100 | |
| # Add duplicates | |
| df = add_duplicates(df, 0.02) | |
| df = df.sample(frac=1, random_state=42).reset_index(drop=True) | |
| df.to_excel(os.path.join(RAW_DIR, 'Trade_Promo_Events_Log.xlsx'), index=False) | |
| print(f"Raw trade promo: {len(df)} rows -> Trade_Promo_Events_Log.xlsx") | |
| def generate_raw_external(): | |
| """External factors with renamed cols, Yes/No strings, sensor errors.""" | |
| df = pd.read_csv(os.path.join(SYNTHETIC_DIR, 'external_factors_data.csv')) | |
| # Rename columns | |
| df = df.rename(columns={ | |
| 'temperature': 'temp_f', | |
| 'precipitation': 'rain_inches', | |
| 'holiday_flag': 'is_holiday', | |
| 'economic_index': 'econ_idx', | |
| 'competitor_price_index': 'comp_price_idx', | |
| }) | |
| # Convert boolean holiday_flag to Yes/No strings | |
| df['is_holiday'] = df['is_holiday'].map({True: 'Yes', False: 'No', 'True': 'Yes', 'False': 'No'}) | |
| # Convert event_flag similarly | |
| df['event_flag'] = df['event_flag'].map({True: 'Y', False: 'N', 'True': 'Y', 'False': 'N'}) | |
| # Missing values | |
| df = add_nulls(df, 'temp_f', 0.03) | |
| df = add_nulls(df, 'econ_idx', 0.02) | |
| # Sensor errors: some temperature values as -999 | |
| sensor_mask = np.random.random(len(df)) < 0.01 | |
| df.loc[sensor_mask, 'temp_f'] = -999.0 | |
| # Add duplicates | |
| df = add_duplicates(df, 0.01) | |
| df = df.sample(frac=1, random_state=42).reset_index(drop=True) | |
| df.to_excel(os.path.join(RAW_DIR, 'Weather_Economic_Data.xlsx'), index=False) | |
| print(f"Raw external factors: {len(df)} rows -> Weather_Economic_Data.xlsx") | |
| if __name__ == '__main__': | |
| print("Generating messy raw Excel files...") | |
| print("=" * 50) | |
| generate_raw_media() | |
| generate_raw_sales() | |
| generate_raw_consumer_promo() | |
| generate_raw_trade_promo() | |
| generate_raw_external() | |
| print("=" * 50) | |
| print(f"All raw files generated in {RAW_DIR}") | |