File size: 23,635 Bytes
fb1cc1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
"""
Data Preprocessing Pipeline for Olist E-commerce
=================================================
CLO4: Kiểm soát chất lượng dữ liệu, làm sạch, chuẩn hóa, giảm số chiều

Pipeline:
1. Data Quality Assessment (6 dimensions)
2. Missing Value Handling (multiple strategies)
3. Outlier Detection & Treatment (IQR, Z-score)
4. Normalization (Min-Max, Z-Score, Robust)
5. Dimensionality Reduction (PCA)
6. Feature Engineering (domain-specific)

Usage:
    python analytics/data_preprocessing.py --data-dir ./data/raw --output-dir ./data/processed
"""

import os
import sys
import json
import logging
import argparse
from datetime import datetime

import pandas as pd
import numpy as np
from sklearn.preprocessing import MinMaxScaler, StandardScaler, RobustScaler
from sklearn.decomposition import PCA
from sklearn.impute import KNNImputer

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')

logging.basicConfig(level=logging.INFO, format='%(asctime)s [%(levelname)s] %(message)s')
logger = logging.getLogger(__name__)


# ==============================================================================
# 1. DATA QUALITY ASSESSMENT
# ==============================================================================

class DataQualityAssessor:
    """Đánh giá chất lượng dữ liệu theo 6 chiều."""

    def __init__(self):
        self.report = {}

    def assess(self, df: pd.DataFrame, name: str) -> dict:
        logger.info(f"[QUALITY] Assessing '{name}': {df.shape}")
        r = {'table': name, 'rows': len(df), 'columns': len(df.columns)}

        # 1. Completeness
        missing = df.isnull().sum()
        total_cells = df.shape[0] * df.shape[1]
        r['completeness_pct'] = round((1 - missing.sum() / total_cells) * 100, 2)
        r['missing_by_col'] = {c: int(v) for c, v in missing.items() if v > 0}

        # 2. Uniqueness
        r['duplicate_rows'] = int(df.duplicated().sum())

        # 3. Validity — negatives in numeric
        num_cols = df.select_dtypes(include=[np.number]).columns
        r['negative_values'] = {c: int((df[c] < 0).sum()) for c in num_cols if (df[c] < 0).sum() > 0}

        # 4. Consistency — mixed case, whitespace
        str_cols = df.select_dtypes(include=['object']).columns
        r['consistency_issues'] = {}
        for c in str_cols:
            vals = df[c].dropna().unique()
            lower_unique = set(v.strip().lower() for v in vals if isinstance(v, str))
            if len(lower_unique) < len(vals):
                r['consistency_issues'][c] = f"{len(vals)} unique → {len(lower_unique)} after normalization"

        # 5. Outliers (IQR) on key numeric columns
        r['outliers'] = {}
        for c in num_cols:
            data = df[c].dropna()
            if len(data) < 10:
                continue
            Q1, Q3 = data.quantile(0.25), data.quantile(0.75)
            IQR = Q3 - Q1
            out_count = int(((data < Q1 - 1.5 * IQR) | (data > Q3 + 1.5 * IQR)).sum())
            if out_count > 0:
                r['outliers'][c] = {'count': out_count, 'pct': round(out_count / len(data) * 100, 2),
                                    'Q1': round(Q1, 2), 'Q3': round(Q3, 2), 'IQR': round(IQR, 2)}

        self.report[name] = r
        return r

    def print_report(self):
        for name, r in self.report.items():
            print(f"\n{'='*70}")
            print(f"  DATA QUALITY: {name} ({r['rows']:,} rows × {r['columns']} cols)")
            print(f"{'='*70}")
            print(f"  Completeness: {r['completeness_pct']}%")
            print(f"  Duplicates: {r['duplicate_rows']}")
            if r['missing_by_col']:
                print(f"  Missing values:")
                for c, v in sorted(r['missing_by_col'].items(), key=lambda x: -x[1])[:10]:
                    print(f"    {c}: {v} ({v/r['rows']*100:.1f}%)")
            if r['negative_values']:
                print(f"  Negative values: {r['negative_values']}")
            if r['consistency_issues']:
                print(f"  Consistency issues: {r['consistency_issues']}")
            if r['outliers']:
                print(f"  Outliers (IQR):")
                for c, info in list(r['outliers'].items())[:8]:
                    print(f"    {c}: {info['count']} ({info['pct']}%) | Q1={info['Q1']}, Q3={info['Q3']}")


# ==============================================================================
# 2. DATA CLEANER
# ==============================================================================

class OlistDataCleaner:
    """Làm sạch và chuẩn hóa dữ liệu Olist."""

    def __init__(self):
        self.log = []

    def _log(self, msg):
        self.log.append(msg)
        logger.info(f"[CLEAN] {msg}")

    def clean_orders(self, df: pd.DataFrame) -> pd.DataFrame:
        self._log(f"Orders: start {len(df)} rows")
        df = df.drop_duplicates(subset=['order_id'])

        # Timestamp columns
        ts_cols = ['order_purchase_timestamp', 'order_approved_at',
                   'order_delivered_carrier_date', 'order_delivered_customer_date',
                   'order_estimated_delivery_date']
        for c in ts_cols:
            if c in df.columns:
                df[c] = pd.to_datetime(df[c], errors='coerce')

        # Standardize status
        df['order_status'] = df['order_status'].str.strip().str.lower()

        # Remove orders without purchase timestamp
        before = len(df)
        df = df.dropna(subset=['order_purchase_timestamp'])
        self._log(f"Orders: removed {before - len(df)} without purchase_ts → {len(df)} rows")

        # Derived: delivery_days
        mask = df['order_delivered_customer_date'].notna() & df['order_purchase_timestamp'].notna()
        df.loc[mask, 'delivery_days'] = (
            (df.loc[mask, 'order_delivered_customer_date'] - df.loc[mask, 'order_purchase_timestamp'])
            .dt.total_seconds() / 86400
        ).round(1)

        # delivery_delay
        mask2 = df['order_delivered_customer_date'].notna() & df['order_estimated_delivery_date'].notna()
        df.loc[mask2, 'delivery_delay_days'] = (
            (df.loc[mask2, 'order_delivered_customer_date'] - df.loc[mask2, 'order_estimated_delivery_date'])
            .dt.total_seconds() / 86400
        ).round(1)
        df['is_late_delivery'] = df['delivery_delay_days'] > 0

        return df

    def clean_order_items(self, df: pd.DataFrame) -> pd.DataFrame:
        self._log(f"Order items: start {len(df)} rows")
        df = df.drop_duplicates(subset=['order_id', 'order_item_id'])
        for c in ['price', 'freight_value']:
            df[c] = pd.to_numeric(df[c], errors='coerce')
            neg = (df[c] < 0).sum()
            if neg > 0:
                df.loc[df[c] < 0, c] = np.nan
                self._log(f"  {c}: {neg} negatives → NaN")
        df['total_value'] = df['price'].fillna(0) + df['freight_value'].fillna(0)
        self._log(f"Order items: {len(df)} rows after clean")
        return df

    def clean_customers(self, df: pd.DataFrame) -> pd.DataFrame:
        self._log(f"Customers: start {len(df)} rows")
        df = df.drop_duplicates(subset=['customer_id'])
        if 'customer_city' in df.columns:
            df['customer_city'] = df['customer_city'].str.strip().str.title()
        if 'customer_state' in df.columns:
            df['customer_state'] = df['customer_state'].str.strip().str.upper()
        self._log(f"Customers: {len(df)} rows after clean")
        return df

    def clean_products(self, df: pd.DataFrame) -> pd.DataFrame:
        self._log(f"Products: start {len(df)} rows")
        df = df.drop_duplicates(subset=['product_id'])
        num_cols = ['product_weight_g', 'product_length_cm', 'product_height_cm', 'product_width_cm']
        for c in num_cols:
            if c in df.columns:
                df[c] = pd.to_numeric(df[c], errors='coerce')
                median_val = df[c].median()
                n_miss = df[c].isna().sum()
                if n_miss > 0:
                    df[c].fillna(median_val, inplace=True)
                    self._log(f"  {c}: {n_miss} missing → median ({median_val:.0f})")
        # Volume
        if all(c in df.columns for c in ['product_length_cm', 'product_height_cm', 'product_width_cm']):
            df['product_volume_cm3'] = df['product_length_cm'] * df['product_height_cm'] * df['product_width_cm']
        self._log(f"Products: {len(df)} rows after clean")
        return df

    def clean_reviews(self, df: pd.DataFrame) -> pd.DataFrame:
        self._log(f"Reviews: start {len(df)} rows")
        df = df.drop_duplicates(subset=['review_id'])
        df['review_score'] = pd.to_numeric(df['review_score'], errors='coerce')
        df['has_comment'] = df['review_comment_message'].notna() & (df['review_comment_message'].str.len() > 0)
        df['comment_length'] = df['review_comment_message'].fillna('').str.len()
        for c in ['review_creation_date', 'review_answer_timestamp']:
            if c in df.columns:
                df[c] = pd.to_datetime(df[c], errors='coerce')
        self._log(f"Reviews: {len(df)} rows after clean")
        return df

    def clean_payments(self, df: pd.DataFrame) -> pd.DataFrame:
        self._log(f"Payments: start {len(df)} rows")
        df = df.drop_duplicates(subset=['order_id', 'payment_sequential'])
        df['payment_type'] = df['payment_type'].str.strip().str.lower()
        df['payment_value'] = pd.to_numeric(df['payment_value'], errors='coerce')
        self._log(f"Payments: {len(df)} rows after clean")
        return df


# ==============================================================================
# 3. OUTLIER TREATMENT
# ==============================================================================

def treat_outliers(df: pd.DataFrame, columns: list, method: str = 'cap') -> pd.DataFrame:
    """
    Xử lý outliers bằng capping (winsorizing) ở percentile 1% và 99%.

    Args:
        df: DataFrame
        columns: List of numeric columns
        method: 'cap' (winsorize) or 'remove'
    """
    df = df.copy()
    for col in columns:
        if col not in df.columns:
            continue
        p01, p99 = df[col].quantile(0.01), df[col].quantile(0.99)
        n_outliers = ((df[col] < p01) | (df[col] > p99)).sum()
        if method == 'cap':
            df[col] = df[col].clip(lower=p01, upper=p99)
        elif method == 'remove':
            df = df[(df[col] >= p01) & (df[col] <= p99)]
        logger.info(f"[OUTLIER] {col}: {n_outliers} outliers treated ({method}) [{p01:.2f}, {p99:.2f}]")
    return df


# ==============================================================================
# 4. NORMALIZATION
# ==============================================================================

def normalize_features(df: pd.DataFrame, columns: list, method: str = 'standard') -> pd.DataFrame:
    """Chuẩn hóa dữ liệu."""
    df = df.copy()
    scalers = {'minmax': MinMaxScaler(), 'standard': StandardScaler(), 'robust': RobustScaler()}
    scaler = scalers.get(method, StandardScaler())

    valid_cols = [c for c in columns if c in df.columns]
    df[valid_cols] = scaler.fit_transform(df[valid_cols].fillna(0))
    logger.info(f"[NORMALIZE] {method} applied to {len(valid_cols)} columns")
    return df


# ==============================================================================
# 5. PCA
# ==============================================================================

def apply_pca(df: pd.DataFrame, columns: list, n_components: float = 0.95):
    """PCA với giải thích variance ratio."""
    valid_cols = [c for c in columns if c in df.columns]
    data = df[valid_cols].dropna()

    scaler = StandardScaler()
    data_scaled = scaler.fit_transform(data)

    pca = PCA(n_components=n_components)
    result = pca.fit_transform(data_scaled)

    logger.info(f"[PCA] {len(valid_cols)} features → {pca.n_components_} components "
                f"({sum(pca.explained_variance_ratio_)*100:.1f}% variance)")

    for i, (var, cum) in enumerate(zip(pca.explained_variance_ratio_,
                                        np.cumsum(pca.explained_variance_ratio_))):
        logger.info(f"  PC{i+1}: {var:.4f} ({var*100:.1f}%) | Cumulative: {cum*100:.1f}%")

    # Loadings
    loadings = pd.DataFrame(pca.components_.T, index=valid_cols,
                            columns=[f'PC{i+1}' for i in range(pca.n_components_)])

    return result, pca, loadings


# ==============================================================================
# 6. FEATURE ENGINEERING
# ==============================================================================

def engineer_features(orders: pd.DataFrame, items: pd.DataFrame,
                      products: pd.DataFrame, customers: pd.DataFrame,
                      reviews: pd.DataFrame, payments: pd.DataFrame) -> pd.DataFrame:
    """Feature Engineering tổng hợp cho phân tích và ML."""
    logger.info("[FEATURE] Building feature table...")

    # Aggregate items per order
    order_items_agg = items.groupby('order_id').agg(
        item_count=('order_item_id', 'count'),
        total_price=('price', 'sum'),
        total_freight=('freight_value', 'sum'),
        avg_item_price=('price', 'mean'),
        max_item_price=('price', 'max'),
        n_sellers=('seller_id', 'nunique'),
        n_products=('product_id', 'nunique'),
    ).reset_index()

    # Aggregate payments per order
    order_pay_agg = payments.groupby('order_id').agg(
        total_payment=('payment_value', 'sum'),
        n_payment_methods=('payment_type', 'nunique'),
        max_installments=('payment_installments', 'max'),
        primary_payment=('payment_type', lambda x: x.mode()[0] if len(x) > 0 else 'unknown'),
    ).reset_index()

    # Merge
    feat = orders[['order_id', 'customer_id', 'order_status', 'order_purchase_timestamp',
                    'delivery_days', 'delivery_delay_days', 'is_late_delivery']].copy()

    feat = feat.merge(order_items_agg, on='order_id', how='left')
    feat = feat.merge(order_pay_agg, on='order_id', how='left')
    feat = feat.merge(reviews[['order_id', 'review_score', 'has_comment', 'comment_length']],
                      on='order_id', how='left')

    # Customer features
    cust_feats = customers[['customer_id', 'customer_city', 'customer_state']].drop_duplicates('customer_id')
    feat = feat.merge(cust_feats, on='customer_id', how='left')

    # Time features
    if 'order_purchase_timestamp' in feat.columns:
        ts = pd.to_datetime(feat['order_purchase_timestamp'])
        feat['purchase_hour'] = ts.dt.hour
        feat['purchase_dayofweek'] = ts.dt.dayofweek
        feat['purchase_month'] = ts.dt.month
        feat['is_weekend'] = (ts.dt.dayofweek >= 5).astype(int)

    # Price features
    feat['freight_ratio'] = (feat['total_freight'] / feat['total_price'].replace(0, np.nan)).round(4)
    feat['gmv'] = feat['total_price'].fillna(0) + feat['total_freight'].fillna(0)
    feat['is_free_shipping'] = (feat['total_freight'] == 0).astype(int)
    feat['is_multi_item'] = (feat['item_count'] > 1).astype(int)
    feat['is_multi_seller'] = (feat['n_sellers'] > 1).astype(int)

    # Satisfaction
    feat['is_satisfied'] = (feat['review_score'] >= 4).astype(int)

    # State region mapping
    region_map = {
        'SP': 'Southeast', 'RJ': 'Southeast', 'MG': 'Southeast', 'ES': 'Southeast',
        'PR': 'South', 'SC': 'South', 'RS': 'South',
        'BA': 'Northeast', 'PE': 'Northeast', 'CE': 'Northeast', 'MA': 'Northeast',
        'PB': 'Northeast', 'RN': 'Northeast', 'AL': 'Northeast', 'PI': 'Northeast', 'SE': 'Northeast',
        'DF': 'Central-West', 'GO': 'Central-West', 'MT': 'Central-West', 'MS': 'Central-West',
        'AM': 'North', 'PA': 'North', 'RO': 'North', 'AC': 'North',
        'AP': 'North', 'RR': 'North', 'TO': 'North',
    }
    feat['region'] = feat['customer_state'].map(region_map).fillna('Other')

    logger.info(f"[FEATURE] Feature table: {feat.shape[0]} rows × {feat.shape[1]} columns")
    return feat


# ==============================================================================
# 7. VISUALIZATION
# ==============================================================================

def create_preprocessing_report(feat: pd.DataFrame, output_dir: str):
    """Tạo visualization cho preprocessing report."""
    os.makedirs(output_dir, exist_ok=True)

    fig, axes = plt.subplots(2, 3, figsize=(18, 10))

    # 1. Missing values
    missing = feat.isnull().sum().sort_values(ascending=False).head(15)
    missing = missing[missing > 0]
    if len(missing) > 0:
        axes[0, 0].barh(range(len(missing)), missing.values, color='#e74c3c')
        axes[0, 0].set_yticks(range(len(missing)))
        axes[0, 0].set_yticklabels(missing.index, fontsize=8)
        axes[0, 0].set_title('Missing Values (Top 15)')
        axes[0, 0].set_xlabel('Count')
    else:
        axes[0, 0].text(0.5, 0.5, 'No missing values', ha='center', va='center', fontsize=14)
        axes[0, 0].set_title('Missing Values')

    # 2. Price distribution
    if 'total_price' in feat.columns:
        data = feat['total_price'].dropna()
        axes[0, 1].hist(data.clip(upper=data.quantile(0.99)), bins=50, color='#3498db', alpha=0.7)
        axes[0, 1].axvline(data.median(), color='red', linestyle='--', label=f'Median={data.median():.0f}')
        axes[0, 1].set_title('Price Distribution')
        axes[0, 1].legend()

    # 3. Delivery days distribution
    if 'delivery_days' in feat.columns:
        data = feat['delivery_days'].dropna()
        axes[0, 2].hist(data.clip(upper=data.quantile(0.99)), bins=50, color='#2ecc71', alpha=0.7)
        axes[0, 2].axvline(data.median(), color='red', linestyle='--', label=f'Median={data.median():.0f}')
        axes[0, 2].set_title('Delivery Days Distribution')
        axes[0, 2].legend()

    # 4. Review score distribution
    if 'review_score' in feat.columns:
        feat['review_score'].dropna().value_counts().sort_index().plot(
            kind='bar', ax=axes[1, 0], color=['#e74c3c', '#f39c12', '#f1c40f', '#2ecc71', '#27ae60'])
        axes[1, 0].set_title('Review Score Distribution')
        axes[1, 0].set_xlabel('Score')

    # 5. Region distribution
    if 'region' in feat.columns:
        feat['region'].value_counts().plot(kind='bar', ax=axes[1, 1], color='#9b59b6', alpha=0.7)
        axes[1, 1].set_title('Orders by Region')
        axes[1, 1].tick_params(axis='x', rotation=45)

    # 6. Correlation heatmap (top features)
    num_cols = ['total_price', 'total_freight', 'delivery_days', 'review_score',
                'item_count', 'freight_ratio']
    valid_cols = [c for c in num_cols if c in feat.columns]
    if len(valid_cols) >= 3:
        corr = feat[valid_cols].corr()
        im = axes[1, 2].imshow(corr, cmap='RdBu_r', vmin=-1, vmax=1)
        axes[1, 2].set_xticks(range(len(valid_cols)))
        axes[1, 2].set_yticks(range(len(valid_cols)))
        axes[1, 2].set_xticklabels(valid_cols, fontsize=7, rotation=45, ha='right')
        axes[1, 2].set_yticklabels(valid_cols, fontsize=7)
        axes[1, 2].set_title('Correlation Matrix')
        for i in range(len(valid_cols)):
            for j in range(len(valid_cols)):
                axes[1, 2].text(j, i, f'{corr.iloc[i, j]:.2f}', ha='center', va='center', fontsize=7)

    plt.suptitle('Data Preprocessing Report - Olist E-commerce', fontsize=14, fontweight='bold')
    plt.tight_layout()
    path = os.path.join(output_dir, 'preprocessing_report.png')
    plt.savefig(path, dpi=150, bbox_inches='tight')
    plt.close()
    logger.info(f"[VIZ] Saved: {path}")


# ==============================================================================
# MAIN PIPELINE
# ==============================================================================

def main():
    parser = argparse.ArgumentParser(description='Olist Data Preprocessing Pipeline')
    parser.add_argument('--data-dir', type=str, default='./data/raw')
    parser.add_argument('--output-dir', type=str, default='./data/processed')
    args = parser.parse_args()

    os.makedirs(args.output_dir, exist_ok=True)

    # ---- Load data ----
    logger.info("Loading Olist CSV files...")
    tables = {}
    files = {
        'orders': 'olist_orders_dataset.csv',
        'items': 'olist_order_items_dataset.csv',
        'customers': 'olist_customers_dataset.csv',
        'products': 'olist_products_dataset.csv',
        'sellers': 'olist_sellers_dataset.csv',
        'payments': 'olist_order_payments_dataset.csv',
        'reviews': 'olist_order_reviews_dataset.csv',
    }
    for name, fname in files.items():
        path = os.path.join(args.data_dir, fname)
        if os.path.exists(path):
            tables[name] = pd.read_csv(path)
            logger.info(f"  Loaded {name}: {tables[name].shape}")
        else:
            logger.warning(f"  File not found: {path}")

    if not tables:
        logger.error("No data files found. Please download Olist dataset from Kaggle.")
        sys.exit(1)

    # ---- 1. Quality Assessment ----
    qa = DataQualityAssessor()
    for name, df in tables.items():
        qa.assess(df, name)
    qa.print_report()

    # Save quality report
    with open(os.path.join(args.output_dir, 'quality_report.json'), 'w') as f:
        json.dump(qa.report, f, indent=2, default=str)

    # ---- 2. Clean data ----
    cleaner = OlistDataCleaner()
    orders = cleaner.clean_orders(tables['orders'])
    items = cleaner.clean_order_items(tables['items'])
    customers = cleaner.clean_customers(tables['customers'])
    products = cleaner.clean_products(tables['products'])
    reviews = cleaner.clean_reviews(tables['reviews'])
    payments = cleaner.clean_payments(tables['payments'])

    # ---- 3. Outlier treatment ----
    items = treat_outliers(items, ['price', 'freight_value'], method='cap')
    orders = treat_outliers(orders, ['delivery_days'], method='cap')

    # ---- 4. Feature Engineering ----
    features = engineer_features(orders, items, products, customers, reviews, payments)

    # ---- 5. PCA on product features ----
    pca_cols = ['total_price', 'total_freight', 'delivery_days', 'item_count', 'freight_ratio']
    pca_result, pca_model, loadings = apply_pca(features, pca_cols)
    logger.info(f"PCA Loadings:\n{loadings}")

    # ---- 6. Save cleaned data ----
    orders.to_parquet(os.path.join(args.output_dir, 'clean_orders.parquet'), index=False)
    items.to_parquet(os.path.join(args.output_dir, 'clean_order_items.parquet'), index=False)
    customers.to_parquet(os.path.join(args.output_dir, 'clean_customers.parquet'), index=False)
    products.to_parquet(os.path.join(args.output_dir, 'clean_products.parquet'), index=False)
    reviews.to_parquet(os.path.join(args.output_dir, 'clean_reviews.parquet'), index=False)
    payments.to_parquet(os.path.join(args.output_dir, 'clean_payments.parquet'), index=False)
    features.to_parquet(os.path.join(args.output_dir, 'feature_table.parquet'), index=False)

    logger.info(f"All cleaned data saved to {args.output_dir}/")

    # ---- 7. Visualization ----
    create_preprocessing_report(features, args.output_dir)

    # ---- Summary ----
    print(f"\n{'='*70}")
    print(f"  PREPROCESSING PIPELINE COMPLETE")
    print(f"{'='*70}")
    print(f"  Cleaned tables: {', '.join(['orders', 'items', 'customers', 'products', 'reviews', 'payments'])}")
    print(f"  Feature table: {features.shape[0]:,} rows × {features.shape[1]} columns")
    print(f"  Output: {args.output_dir}/")
    print(f"{'='*70}")


if __name__ == '__main__':
    main()