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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Lab 2b: Medallion Architecture Implementation
|
| 3 |
+
==============================================
|
| 4 |
+
BIM5021 - Nhà kho dữ liệu và Tích hợp
|
| 5 |
+
Chương 2: Mô hình hóa dữ liệu cho Cloud Warehousing
|
| 6 |
+
|
| 7 |
+
Mục tiêu:
|
| 8 |
+
- Implement Medallion Architecture (Bronze → Silver → Gold) bằng Python + Pandas
|
| 9 |
+
- Mô phỏng quy trình ETL/ELT cho Olist dataset
|
| 10 |
+
- Xử lý data quality ở mỗi tầng
|
| 11 |
+
|
| 12 |
+
Yêu cầu: pip install pandas numpy
|
| 13 |
+
Dataset: Olist Brazilian E-commerce (download từ Kaggle)
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
import pandas as pd
|
| 17 |
+
import numpy as np
|
| 18 |
+
import os
|
| 19 |
+
import json
|
| 20 |
+
from datetime import datetime
|
| 21 |
+
|
| 22 |
+
# ==============================================================================
|
| 23 |
+
# CẤU HÌNH
|
| 24 |
+
# ==============================================================================
|
| 25 |
+
|
| 26 |
+
# Đường dẫn đến thư mục chứa CSV files của Olist
|
| 27 |
+
# Download từ: https://www.kaggle.com/datasets/olistbr/brazilian-ecommerce
|
| 28 |
+
DATA_DIR = os.environ.get('OLIST_DATA_DIR', './data/raw/')
|
| 29 |
+
OUTPUT_DIR = os.environ.get('OUTPUT_DIR', './data/')
|
| 30 |
+
|
| 31 |
+
# Tạo thư mục output
|
| 32 |
+
for layer in ['bronze', 'silver', 'gold']:
|
| 33 |
+
os.makedirs(f'{OUTPUT_DIR}/{layer}', exist_ok=True)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
# ==============================================================================
|
| 37 |
+
# BRONZE LAYER: Raw Data Ingestion
|
| 38 |
+
# ==============================================================================
|
| 39 |
+
|
| 40 |
+
class BronzeLayer:
|
| 41 |
+
"""
|
| 42 |
+
Bronze Layer: Ingest raw data as-is.
|
| 43 |
+
- Không transform
|
| 44 |
+
- Chỉ thêm metadata (ingestion timestamp, source file)
|
| 45 |
+
- Lưu dưới dạng Parquet (columnar, compressed)
|
| 46 |
+
"""
|
| 47 |
+
|
| 48 |
+
def __init__(self, data_dir: str, output_dir: str):
|
| 49 |
+
self.data_dir = data_dir
|
| 50 |
+
self.output_dir = f'{output_dir}/bronze'
|
| 51 |
+
self.ingestion_log = []
|
| 52 |
+
|
| 53 |
+
def ingest_csv(self, filename: str, table_name: str) -> pd.DataFrame:
|
| 54 |
+
"""Ingest 1 CSV file vào Bronze layer."""
|
| 55 |
+
filepath = os.path.join(self.data_dir, filename)
|
| 56 |
+
|
| 57 |
+
if not os.path.exists(filepath):
|
| 58 |
+
print(f" [SKIP] File not found: {filepath}")
|
| 59 |
+
print(f" Download Olist dataset from Kaggle first!")
|
| 60 |
+
# Tạo sample data để demo
|
| 61 |
+
return self._create_sample_data(table_name)
|
| 62 |
+
|
| 63 |
+
# Read raw CSV
|
| 64 |
+
df = pd.read_csv(filepath)
|
| 65 |
+
|
| 66 |
+
# Add metadata columns (Bronze standard)
|
| 67 |
+
df['_ingested_at'] = datetime.now().isoformat()
|
| 68 |
+
df['_source_file'] = filename
|
| 69 |
+
df['_row_hash'] = df.apply(lambda row: hash(tuple(row)), axis=1)
|
| 70 |
+
|
| 71 |
+
# Save as Parquet
|
| 72 |
+
output_path = f'{self.output_dir}/{table_name}.parquet'
|
| 73 |
+
df.to_parquet(output_path, index=False)
|
| 74 |
+
|
| 75 |
+
# Log
|
| 76 |
+
log_entry = {
|
| 77 |
+
'table': table_name,
|
| 78 |
+
'source': filename,
|
| 79 |
+
'rows': len(df),
|
| 80 |
+
'columns': len(df.columns),
|
| 81 |
+
'size_mb': os.path.getsize(output_path) / (1024*1024),
|
| 82 |
+
'ingested_at': datetime.now().isoformat()
|
| 83 |
+
}
|
| 84 |
+
self.ingestion_log.append(log_entry)
|
| 85 |
+
|
| 86 |
+
print(f" [BRONZE] {table_name}: {len(df):,} rows, "
|
| 87 |
+
f"{len(df.columns)} cols → {output_path}")
|
| 88 |
+
|
| 89 |
+
return df
|
| 90 |
+
|
| 91 |
+
def _create_sample_data(self, table_name: str) -> pd.DataFrame:
|
| 92 |
+
"""Tạo sample data khi không có file thật (cho demo)."""
|
| 93 |
+
np.random.seed(42)
|
| 94 |
+
|
| 95 |
+
sample_data = {
|
| 96 |
+
'orders': pd.DataFrame({
|
| 97 |
+
'order_id': [f'ord_{i:05d}' for i in range(100)],
|
| 98 |
+
'customer_id': [f'cust_{np.random.randint(1, 50):04d}' for _ in range(100)],
|
| 99 |
+
'order_status': np.random.choice(
|
| 100 |
+
['delivered', 'shipped', 'canceled', 'processing'],
|
| 101 |
+
100, p=[0.8, 0.1, 0.05, 0.05]
|
| 102 |
+
),
|
| 103 |
+
'order_purchase_timestamp': pd.date_range(
|
| 104 |
+
'2017-01-01', periods=100, freq='3D'
|
| 105 |
+
).strftime('%Y-%m-%d %H:%M:%S'),
|
| 106 |
+
'order_delivered_customer_date': [
|
| 107 |
+
(pd.Timestamp('2017-01-01') + pd.Timedelta(days=i*3+np.random.randint(3, 15)))
|
| 108 |
+
.strftime('%Y-%m-%d %H:%M:%S') if np.random.random() > 0.1 else None
|
| 109 |
+
for i in range(100)
|
| 110 |
+
],
|
| 111 |
+
}),
|
| 112 |
+
'order_items': pd.DataFrame({
|
| 113 |
+
'order_id': [f'ord_{np.random.randint(0, 100):05d}' for _ in range(150)],
|
| 114 |
+
'order_item_id': np.random.randint(1, 5, 150),
|
| 115 |
+
'product_id': [f'prod_{np.random.randint(1, 30):03d}' for _ in range(150)],
|
| 116 |
+
'seller_id': [f'seller_{np.random.randint(1, 10):03d}' for _ in range(150)],
|
| 117 |
+
'price': np.round(np.random.uniform(10, 500, 150), 2),
|
| 118 |
+
'freight_value': np.round(np.random.uniform(5, 80, 150), 2),
|
| 119 |
+
}),
|
| 120 |
+
'customers': pd.DataFrame({
|
| 121 |
+
'customer_id': [f'cust_{i:04d}' for i in range(50)],
|
| 122 |
+
'customer_unique_id': [f'unique_{i:04d}' for i in range(50)],
|
| 123 |
+
'customer_zip_code_prefix': np.random.randint(10000, 99999, 50).astype(str),
|
| 124 |
+
'customer_city': np.random.choice(
|
| 125 |
+
['sao paulo', 'rio de janeiro', 'belo horizonte', 'brasilia', 'curitiba'],
|
| 126 |
+
50
|
| 127 |
+
),
|
| 128 |
+
'customer_state': np.random.choice(['SP', 'RJ', 'MG', 'DF', 'PR'], 50),
|
| 129 |
+
}),
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
+
df = sample_data.get(table_name, pd.DataFrame({'id': range(10)}))
|
| 133 |
+
df['_ingested_at'] = datetime.now().isoformat()
|
| 134 |
+
df['_source_file'] = f'sample_{table_name}.csv'
|
| 135 |
+
|
| 136 |
+
print(f" [BRONZE] {table_name}: {len(df):,} rows (SAMPLE DATA)")
|
| 137 |
+
return df
|
| 138 |
+
|
| 139 |
+
def ingest_all(self) -> dict:
|
| 140 |
+
"""Ingest tất cả files của Olist dataset."""
|
| 141 |
+
print("\n" + "=" * 60)
|
| 142 |
+
print(" BRONZE LAYER - Raw Data Ingestion")
|
| 143 |
+
print("=" * 60)
|
| 144 |
+
|
| 145 |
+
files = {
|
| 146 |
+
'orders': 'olist_orders_dataset.csv',
|
| 147 |
+
'order_items': 'olist_order_items_dataset.csv',
|
| 148 |
+
'customers': 'olist_customers_dataset.csv',
|
| 149 |
+
'products': 'olist_products_dataset.csv',
|
| 150 |
+
'sellers': 'olist_sellers_dataset.csv',
|
| 151 |
+
'payments': 'olist_order_payments_dataset.csv',
|
| 152 |
+
'reviews': 'olist_order_reviews_dataset.csv',
|
| 153 |
+
'geolocation': 'olist_geolocation_dataset.csv',
|
| 154 |
+
'category_translation': 'product_category_name_translation.csv',
|
| 155 |
+
}
|
| 156 |
+
|
| 157 |
+
bronze_tables = {}
|
| 158 |
+
for table_name, filename in files.items():
|
| 159 |
+
bronze_tables[table_name] = self.ingest_csv(filename, table_name)
|
| 160 |
+
|
| 161 |
+
print(f"\n Total: {sum(len(df) for df in bronze_tables.values()):,} rows ingested")
|
| 162 |
+
return bronze_tables
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
# ==============================================================================
|
| 166 |
+
# SILVER LAYER: Cleansed & Conformed Data
|
| 167 |
+
# ==============================================================================
|
| 168 |
+
|
| 169 |
+
class SilverLayer:
|
| 170 |
+
"""
|
| 171 |
+
Silver Layer: Clean, validate, and conform data.
|
| 172 |
+
- Data type casting
|
| 173 |
+
- Null handling
|
| 174 |
+
- Deduplication
|
| 175 |
+
- Standardization
|
| 176 |
+
- Business rules validation
|
| 177 |
+
"""
|
| 178 |
+
|
| 179 |
+
def __init__(self, output_dir: str):
|
| 180 |
+
self.output_dir = f'{output_dir}/silver'
|
| 181 |
+
self.quality_report = {}
|
| 182 |
+
|
| 183 |
+
def process_orders(self, df: pd.DataFrame) -> pd.DataFrame:
|
| 184 |
+
"""Clean orders table."""
|
| 185 |
+
print(f"\n [SILVER] Processing orders...")
|
| 186 |
+
|
| 187 |
+
original_count = len(df)
|
| 188 |
+
report = {'table': 'orders', 'original_rows': original_count}
|
| 189 |
+
|
| 190 |
+
# 1. Remove metadata columns from bronze
|
| 191 |
+
meta_cols = [c for c in df.columns if c.startswith('_')]
|
| 192 |
+
df = df.drop(columns=meta_cols, errors='ignore')
|
| 193 |
+
|
| 194 |
+
# 2. Deduplicate
|
| 195 |
+
df = df.drop_duplicates(subset=['order_id'])
|
| 196 |
+
report['after_dedup'] = len(df)
|
| 197 |
+
|
| 198 |
+
# 3. Cast timestamps
|
| 199 |
+
timestamp_cols = [c for c in df.columns if 'timestamp' in c or 'date' in c]
|
| 200 |
+
for col in timestamp_cols:
|
| 201 |
+
df[col] = pd.to_datetime(df[col], errors='coerce')
|
| 202 |
+
|
| 203 |
+
# 4. Validate order_status
|
| 204 |
+
valid_statuses = ['delivered', 'shipped', 'canceled', 'unavailable',
|
| 205 |
+
'invoiced', 'processing', 'created', 'approved']
|
| 206 |
+
invalid_mask = ~df['order_status'].isin(valid_statuses)
|
| 207 |
+
report['invalid_status'] = int(invalid_mask.sum())
|
| 208 |
+
df.loc[invalid_mask, 'order_status'] = 'unknown'
|
| 209 |
+
|
| 210 |
+
# 5. Validate business rules
|
| 211 |
+
# - purchase_timestamp should exist
|
| 212 |
+
null_purchase = df['order_purchase_timestamp'].isna()
|
| 213 |
+
report['null_purchase_ts'] = int(null_purchase.sum())
|
| 214 |
+
df = df[~null_purchase] # Remove orders without purchase date
|
| 215 |
+
|
| 216 |
+
# 6. Add derived columns
|
| 217 |
+
if 'order_delivered_customer_date' in df.columns and 'order_purchase_timestamp' in df.columns:
|
| 218 |
+
df['delivery_days'] = (
|
| 219 |
+
df['order_delivered_customer_date'] - df['order_purchase_timestamp']
|
| 220 |
+
).dt.total_seconds() / 86400
|
| 221 |
+
df['delivery_days'] = df['delivery_days'].round(1)
|
| 222 |
+
|
| 223 |
+
# 7. Add silver metadata
|
| 224 |
+
df['_processed_at'] = datetime.now().isoformat()
|
| 225 |
+
|
| 226 |
+
report['final_rows'] = len(df)
|
| 227 |
+
report['rows_removed'] = original_count - len(df)
|
| 228 |
+
self.quality_report['orders'] = report
|
| 229 |
+
|
| 230 |
+
# Save
|
| 231 |
+
output_path = f'{self.output_dir}/silver_orders.parquet'
|
| 232 |
+
df.to_parquet(output_path, index=False)
|
| 233 |
+
|
| 234 |
+
print(f" Original: {original_count:,} → Cleaned: {len(df):,} "
|
| 235 |
+
f"(removed {original_count - len(df):,})")
|
| 236 |
+
|
| 237 |
+
return df
|
| 238 |
+
|
| 239 |
+
def process_customers(self, df: pd.DataFrame) -> pd.DataFrame:
|
| 240 |
+
"""Clean customers table."""
|
| 241 |
+
print(f" [SILVER] Processing customers...")
|
| 242 |
+
|
| 243 |
+
original_count = len(df)
|
| 244 |
+
meta_cols = [c for c in df.columns if c.startswith('_')]
|
| 245 |
+
df = df.drop(columns=meta_cols, errors='ignore')
|
| 246 |
+
|
| 247 |
+
# Deduplicate by customer_id (keep first)
|
| 248 |
+
df = df.drop_duplicates(subset=['customer_id'], keep='first')
|
| 249 |
+
|
| 250 |
+
# Standardize city names
|
| 251 |
+
if 'customer_city' in df.columns:
|
| 252 |
+
df['customer_city'] = (
|
| 253 |
+
df['customer_city']
|
| 254 |
+
.str.strip()
|
| 255 |
+
.str.lower()
|
| 256 |
+
.str.title()
|
| 257 |
+
)
|
| 258 |
+
|
| 259 |
+
# Standardize state codes
|
| 260 |
+
if 'customer_state' in df.columns:
|
| 261 |
+
df['customer_state'] = df['customer_state'].str.upper().str.strip()
|
| 262 |
+
|
| 263 |
+
df['_processed_at'] = datetime.now().isoformat()
|
| 264 |
+
|
| 265 |
+
output_path = f'{self.output_dir}/silver_customers.parquet'
|
| 266 |
+
df.to_parquet(output_path, index=False)
|
| 267 |
+
|
| 268 |
+
print(f" Original: {original_count:,} → Cleaned: {len(df):,}")
|
| 269 |
+
return df
|
| 270 |
+
|
| 271 |
+
def process_order_items(self, df: pd.DataFrame) -> pd.DataFrame:
|
| 272 |
+
"""Clean order_items table."""
|
| 273 |
+
print(f" [SILVER] Processing order_items...")
|
| 274 |
+
|
| 275 |
+
original_count = len(df)
|
| 276 |
+
meta_cols = [c for c in df.columns if c.startswith('_')]
|
| 277 |
+
df = df.drop(columns=meta_cols, errors='ignore')
|
| 278 |
+
|
| 279 |
+
# Cast numeric
|
| 280 |
+
for col in ['price', 'freight_value']:
|
| 281 |
+
if col in df.columns:
|
| 282 |
+
df[col] = pd.to_numeric(df[col], errors='coerce')
|
| 283 |
+
|
| 284 |
+
# Remove negative prices
|
| 285 |
+
if 'price' in df.columns:
|
| 286 |
+
df = df[df['price'] >= 0]
|
| 287 |
+
|
| 288 |
+
# Add total_value
|
| 289 |
+
if 'price' in df.columns and 'freight_value' in df.columns:
|
| 290 |
+
df['total_value'] = df['price'] + df['freight_value'].fillna(0)
|
| 291 |
+
|
| 292 |
+
df['_processed_at'] = datetime.now().isoformat()
|
| 293 |
+
|
| 294 |
+
output_path = f'{self.output_dir}/silver_order_items.parquet'
|
| 295 |
+
df.to_parquet(output_path, index=False)
|
| 296 |
+
|
| 297 |
+
print(f" Original: {original_count:,} → Cleaned: {len(df):,}")
|
| 298 |
+
return df
|
| 299 |
+
|
| 300 |
+
def process_all(self, bronze_tables: dict) -> dict:
|
| 301 |
+
"""Process tất cả bronze tables → silver."""
|
| 302 |
+
print("\n" + "=" * 60)
|
| 303 |
+
print(" SILVER LAYER - Data Cleansing & Conforming")
|
| 304 |
+
print("=" * 60)
|
| 305 |
+
|
| 306 |
+
silver = {}
|
| 307 |
+
|
| 308 |
+
if 'orders' in bronze_tables:
|
| 309 |
+
silver['orders'] = self.process_orders(bronze_tables['orders'])
|
| 310 |
+
|
| 311 |
+
if 'customers' in bronze_tables:
|
| 312 |
+
silver['customers'] = self.process_customers(bronze_tables['customers'])
|
| 313 |
+
|
| 314 |
+
if 'order_items' in bronze_tables:
|
| 315 |
+
silver['order_items'] = self.process_order_items(bronze_tables['order_items'])
|
| 316 |
+
|
| 317 |
+
# Print quality report
|
| 318 |
+
print(f"\n Quality Report:")
|
| 319 |
+
for table, report in self.quality_report.items():
|
| 320 |
+
print(f" {table}: {report}")
|
| 321 |
+
|
| 322 |
+
return silver
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
# ==============================================================================
|
| 326 |
+
# GOLD LAYER: Business-Ready Data
|
| 327 |
+
# ==============================================================================
|
| 328 |
+
|
| 329 |
+
class GoldLayer:
|
| 330 |
+
"""
|
| 331 |
+
Gold Layer: Business-ready aggregations and star schema.
|
| 332 |
+
- Star Schema (dims + facts)
|
| 333 |
+
- Pre-computed aggregations
|
| 334 |
+
- KPI tables
|
| 335 |
+
- ML-ready feature tables
|
| 336 |
+
"""
|
| 337 |
+
|
| 338 |
+
def __init__(self, output_dir: str):
|
| 339 |
+
self.output_dir = f'{output_dir}/gold'
|
| 340 |
+
|
| 341 |
+
def create_dim_time(self, silver_orders: pd.DataFrame) -> pd.DataFrame:
|
| 342 |
+
"""Tạo dim_time từ range ngày trong orders."""
|
| 343 |
+
print(f"\n [GOLD] Creating dim_time...")
|
| 344 |
+
|
| 345 |
+
if 'order_purchase_timestamp' in silver_orders.columns:
|
| 346 |
+
min_date = silver_orders['order_purchase_timestamp'].min()
|
| 347 |
+
max_date = silver_orders['order_purchase_timestamp'].max()
|
| 348 |
+
|
| 349 |
+
# Nếu là string, convert
|
| 350 |
+
if isinstance(min_date, str):
|
| 351 |
+
min_date = pd.Timestamp(min_date)
|
| 352 |
+
max_date = pd.Timestamp(max_date)
|
| 353 |
+
else:
|
| 354 |
+
min_date = pd.Timestamp('2017-01-01')
|
| 355 |
+
max_date = pd.Timestamp('2018-12-31')
|
| 356 |
+
|
| 357 |
+
dates = pd.date_range(
|
| 358 |
+
start=min_date.normalize(),
|
| 359 |
+
end=max_date.normalize() + pd.Timedelta(days=30),
|
| 360 |
+
freq='D'
|
| 361 |
+
)
|
| 362 |
+
|
| 363 |
+
dim_time = pd.DataFrame({
|
| 364 |
+
'time_key': dates.strftime('%Y%m%d').astype(int),
|
| 365 |
+
'full_date': dates.date,
|
| 366 |
+
'day_of_week': dates.dayofweek + 1,
|
| 367 |
+
'day_name': dates.day_name(),
|
| 368 |
+
'day_of_month': dates.day,
|
| 369 |
+
'week_of_year': dates.isocalendar().week.values,
|
| 370 |
+
'month_number': dates.month,
|
| 371 |
+
'month_name': dates.month_name(),
|
| 372 |
+
'quarter': dates.quarter,
|
| 373 |
+
'year': dates.year,
|
| 374 |
+
'is_weekend': dates.dayofweek >= 5,
|
| 375 |
+
})
|
| 376 |
+
|
| 377 |
+
output_path = f'{self.output_dir}/dim_time.parquet'
|
| 378 |
+
dim_time.to_parquet(output_path, index=False)
|
| 379 |
+
print(f" dim_time: {len(dim_time):,} rows ({dates[0].date()} → {dates[-1].date()})")
|
| 380 |
+
|
| 381 |
+
return dim_time
|
| 382 |
+
|
| 383 |
+
def create_agg_daily_revenue(self, silver_orders: pd.DataFrame,
|
| 384 |
+
silver_items: pd.DataFrame) -> pd.DataFrame:
|
| 385 |
+
"""Tạo bảng aggregate doanh thu theo ngày."""
|
| 386 |
+
print(f" [GOLD] Creating agg_daily_revenue...")
|
| 387 |
+
|
| 388 |
+
# Ensure datetime
|
| 389 |
+
if 'order_purchase_timestamp' in silver_orders.columns:
|
| 390 |
+
silver_orders['purchase_date'] = pd.to_datetime(
|
| 391 |
+
silver_orders['order_purchase_timestamp']
|
| 392 |
+
).dt.date
|
| 393 |
+
|
| 394 |
+
# Merge orders with items
|
| 395 |
+
merged = silver_items.merge(
|
| 396 |
+
silver_orders[['order_id', 'purchase_date', 'order_status']],
|
| 397 |
+
on='order_id',
|
| 398 |
+
how='inner'
|
| 399 |
+
)
|
| 400 |
+
|
| 401 |
+
# Aggregate by day
|
| 402 |
+
daily = merged.groupby('purchase_date').agg(
|
| 403 |
+
total_orders=('order_id', 'nunique'),
|
| 404 |
+
total_items=('order_id', 'count'),
|
| 405 |
+
total_revenue=('price', 'sum'),
|
| 406 |
+
total_freight=('freight_value', 'sum'),
|
| 407 |
+
avg_price=('price', 'mean'),
|
| 408 |
+
).reset_index()
|
| 409 |
+
|
| 410 |
+
daily['avg_order_value'] = daily['total_revenue'] / daily['total_orders']
|
| 411 |
+
daily = daily.round(2)
|
| 412 |
+
else:
|
| 413 |
+
# Sample data fallback
|
| 414 |
+
dates = pd.date_range('2017-01-01', periods=30, freq='D')
|
| 415 |
+
daily = pd.DataFrame({
|
| 416 |
+
'purchase_date': dates.date,
|
| 417 |
+
'total_orders': np.random.randint(10, 100, 30),
|
| 418 |
+
'total_items': np.random.randint(20, 200, 30),
|
| 419 |
+
'total_revenue': np.round(np.random.uniform(1000, 50000, 30), 2),
|
| 420 |
+
'total_freight': np.round(np.random.uniform(200, 5000, 30), 2),
|
| 421 |
+
'avg_price': np.round(np.random.uniform(50, 200, 30), 2),
|
| 422 |
+
'avg_order_value': np.round(np.random.uniform(100, 500, 30), 2),
|
| 423 |
+
})
|
| 424 |
+
|
| 425 |
+
output_path = f'{self.output_dir}/agg_daily_revenue.parquet'
|
| 426 |
+
daily.to_parquet(output_path, index=False)
|
| 427 |
+
print(f" agg_daily_revenue: {len(daily):,} rows")
|
| 428 |
+
|
| 429 |
+
return daily
|
| 430 |
+
|
| 431 |
+
def create_customer_rfm(self, silver_orders: pd.DataFrame,
|
| 432 |
+
silver_items: pd.DataFrame) -> pd.DataFrame:
|
| 433 |
+
"""Tạo bảng RFM (Recency, Frequency, Monetary) cho phân khúc khách hàng."""
|
| 434 |
+
print(f" [GOLD] Creating customer_rfm_segments...")
|
| 435 |
+
|
| 436 |
+
if 'order_purchase_timestamp' not in silver_orders.columns:
|
| 437 |
+
print(" [SKIP] No timestamp column for RFM")
|
| 438 |
+
return pd.DataFrame()
|
| 439 |
+
|
| 440 |
+
# Merge
|
| 441 |
+
merged = silver_items.merge(
|
| 442 |
+
silver_orders[['order_id', 'customer_id', 'order_purchase_timestamp']],
|
| 443 |
+
on='order_id', how='inner'
|
| 444 |
+
)
|
| 445 |
+
merged['order_purchase_timestamp'] = pd.to_datetime(
|
| 446 |
+
merged['order_purchase_timestamp']
|
| 447 |
+
)
|
| 448 |
+
|
| 449 |
+
# Reference date
|
| 450 |
+
reference_date = merged['order_purchase_timestamp'].max() + pd.Timedelta(days=1)
|
| 451 |
+
|
| 452 |
+
# RFM calculation
|
| 453 |
+
rfm = merged.groupby('customer_id').agg(
|
| 454 |
+
recency_days=('order_purchase_timestamp',
|
| 455 |
+
lambda x: (reference_date - x.max()).days),
|
| 456 |
+
frequency=('order_id', 'nunique'),
|
| 457 |
+
monetary=('price', 'sum'),
|
| 458 |
+
).reset_index()
|
| 459 |
+
|
| 460 |
+
# RFM scoring (quintiles)
|
| 461 |
+
rfm['r_score'] = pd.qcut(rfm['recency_days'], q=5, labels=[5,4,3,2,1]).astype(int)
|
| 462 |
+
rfm['f_score'] = pd.qcut(rfm['frequency'].rank(method='first'), q=5, labels=[1,2,3,4,5]).astype(int)
|
| 463 |
+
rfm['m_score'] = pd.qcut(rfm['monetary'].rank(method='first'), q=5, labels=[1,2,3,4,5]).astype(int)
|
| 464 |
+
|
| 465 |
+
rfm['rfm_score'] = rfm['r_score'] * 100 + rfm['f_score'] * 10 + rfm['m_score']
|
| 466 |
+
|
| 467 |
+
# Segment naming
|
| 468 |
+
def segment_name(row):
|
| 469 |
+
r, f, m = row['r_score'], row['f_score'], row['m_score']
|
| 470 |
+
if r >= 4 and f >= 4:
|
| 471 |
+
return 'Champions'
|
| 472 |
+
elif r >= 3 and f >= 3:
|
| 473 |
+
return 'Loyal Customers'
|
| 474 |
+
elif r >= 4 and f <= 2:
|
| 475 |
+
return 'New Customers'
|
| 476 |
+
elif r <= 2 and f >= 3:
|
| 477 |
+
return 'At Risk'
|
| 478 |
+
elif r <= 2 and f <= 2:
|
| 479 |
+
return 'Lost'
|
| 480 |
+
else:
|
| 481 |
+
return 'Regular'
|
| 482 |
+
|
| 483 |
+
rfm['rfm_segment'] = rfm.apply(segment_name, axis=1)
|
| 484 |
+
rfm = rfm.round(2)
|
| 485 |
+
|
| 486 |
+
output_path = f'{self.output_dir}/customer_rfm_segments.parquet'
|
| 487 |
+
rfm.to_parquet(output_path, index=False)
|
| 488 |
+
|
| 489 |
+
print(f" customer_rfm: {len(rfm):,} customers")
|
| 490 |
+
print(f" Segments: {rfm['rfm_segment'].value_counts().to_dict()}")
|
| 491 |
+
|
| 492 |
+
return rfm
|
| 493 |
+
|
| 494 |
+
def build_all(self, silver_tables: dict) -> dict:
|
| 495 |
+
"""Build tất cả Gold layer tables."""
|
| 496 |
+
print("\n" + "=" * 60)
|
| 497 |
+
print(" GOLD LAYER - Business-Ready Data")
|
| 498 |
+
print("=" * 60)
|
| 499 |
+
|
| 500 |
+
gold = {}
|
| 501 |
+
|
| 502 |
+
orders = silver_tables.get('orders', pd.DataFrame())
|
| 503 |
+
items = silver_tables.get('order_items', pd.DataFrame())
|
| 504 |
+
|
| 505 |
+
gold['dim_time'] = self.create_dim_time(orders)
|
| 506 |
+
gold['agg_daily_revenue'] = self.create_agg_daily_revenue(orders, items)
|
| 507 |
+
gold['customer_rfm'] = self.create_customer_rfm(orders, items)
|
| 508 |
+
|
| 509 |
+
return gold
|
| 510 |
+
|
| 511 |
+
|
| 512 |
+
# ==============================================================================
|
| 513 |
+
# MAIN: Orchestrate Bronze → Silver → Gold
|
| 514 |
+
# ==============================================================================
|
| 515 |
+
|
| 516 |
+
if __name__ == '__main__':
|
| 517 |
+
print("=" * 70)
|
| 518 |
+
print(" MEDALLION ARCHITECTURE: Bronze → Silver → Gold")
|
| 519 |
+
print(" BIM5021 - Lab 2b")
|
| 520 |
+
print(" Dataset: Olist Brazilian E-commerce")
|
| 521 |
+
print("=" * 70)
|
| 522 |
+
|
| 523 |
+
# Bronze
|
| 524 |
+
bronze = BronzeLayer(DATA_DIR, OUTPUT_DIR)
|
| 525 |
+
bronze_tables = bronze.ingest_all()
|
| 526 |
+
|
| 527 |
+
# Silver
|
| 528 |
+
silver = SilverLayer(OUTPUT_DIR)
|
| 529 |
+
silver_tables = silver.process_all(bronze_tables)
|
| 530 |
+
|
| 531 |
+
# Gold
|
| 532 |
+
gold = GoldLayer(OUTPUT_DIR)
|
| 533 |
+
gold_tables = gold.build_all(silver_tables)
|
| 534 |
+
|
| 535 |
+
# Summary
|
| 536 |
+
print("\n" + "=" * 70)
|
| 537 |
+
print(" PIPELINE SUMMARY")
|
| 538 |
+
print("=" * 70)
|
| 539 |
+
|
| 540 |
+
for layer_name, tables in [('Bronze', bronze_tables), ('Silver', silver_tables), ('Gold', gold_tables)]:
|
| 541 |
+
total_rows = sum(len(df) for df in tables.values() if isinstance(df, pd.DataFrame))
|
| 542 |
+
print(f"\n {layer_name}: {len(tables)} tables, {total_rows:,} total rows")
|
| 543 |
+
for name, df in tables.items():
|
| 544 |
+
if isinstance(df, pd.DataFrame):
|
| 545 |
+
print(f" - {name}: {len(df):,} rows x {len(df.columns)} columns")
|
| 546 |
+
|
| 547 |
+
print("\n" + "=" * 70)
|
| 548 |
+
print(" HOAN THANH! Check output in: " + OUTPUT_DIR)
|
| 549 |
+
print("=" * 70)
|