File size: 5,772 Bytes
9deebf2 | 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 | """Shared helpers for audit scripts."""
import sys
from pathlib import Path
from datetime import datetime
import pandas as pd
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import seaborn as sns
from scipy import stats
import warnings
warnings.filterwarnings('ignore')
sns.set_style('whitegrid')
plt.rcParams['figure.figsize'] = (14, 6)
PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent
PARQUET_DIR = PROJECT_ROOT / 'output' / 'parquet'
DATA_DIR = PROJECT_ROOT / 'data'
OUTPUT_BASE = PROJECT_ROOT / 'output' / 'audit'
def setup_output_dir(dataset_name):
out = OUTPUT_BASE / dataset_name
out.mkdir(parents=True, exist_ok=True)
return out
def save_fig(output_dir, name):
path = output_dir / f'{name}.png'
plt.savefig(path, dpi=150, bbox_inches='tight')
print(f' -> saved {path.relative_to(PROJECT_ROOT)}')
plt.close()
def load_parquet(dataset_name):
if dataset_name == 'users':
path = PARQUET_DIR / 'users.parquet'
elif dataset_name == 'cardS':
path = PARQUET_DIR / 'cardS_cleaned.parquet'
elif dataset_name == 'cardD':
path = PARQUET_DIR / 'cardD_cleaned.parquet'
else:
path = PARQUET_DIR / f'{dataset_name}_cleaned.parquet'
print(f'Loading {path.name}...')
df = pd.read_parquet(path)
mem = df.memory_usage(deep=True).sum()
unit, divisor = ('GB', 1024**3) if mem > 1024**3 else ('MB', 1024**2)
print(f' {len(df):,} rows, {mem / divisor:.2f} {unit}')
return df
def print_section(title):
print()
print('=' * 80)
print(title)
print('=' * 80)
def standard_temporal_analysis(df, dataset_title, output_dir):
"""Yearly bar chart + gap detection. Returns (yearly_counts, gaps)."""
print_section('TEMPORAL ANALYSIS')
ts_col = next((c for c in ['timestamp', 'start_time'] if c in df.columns), None)
if not ts_col:
print('No timestamp column found — skipping temporal analysis')
return pd.Series(dtype=int), []
df['timestamp'] = pd.to_datetime(df[ts_col])
df['date'] = df['timestamp'].dt.date
df['year'] = df['timestamp'].dt.year
print(f'First record: {df["timestamp"].min()}')
print(f'Last record: {df["timestamp"].max()}')
print(f'Time span: {(df["timestamp"].max() - df["timestamp"].min()).days} days')
print(f'Years: {df["year"].min()} - {df["year"].max()}')
yearly_counts = df['year'].value_counts().sort_index()
print('\nYEARLY DISTRIBUTION')
print(yearly_counts)
plt.figure(figsize=(14, 6))
yearly_counts.plot(kind='bar', color='steelblue')
plt.title(f'{dataset_title} - Yearly Distribution', fontsize=14, fontweight='bold')
plt.xlabel('Year')
plt.ylabel('Number of Records')
plt.xticks(rotation=45)
plt.grid(axis='y', alpha=0.3)
plt.tight_layout()
save_fig(output_dir, 'yearly_distribution')
# Gap detection
daily_counts = df.groupby('date').size()
all_dates = pd.date_range(start=daily_counts.index.min(),
end=daily_counts.index.max(), freq='D')
missing_dates = pd.to_datetime(all_dates.difference(pd.to_datetime(daily_counts.index)))
gaps = []
if len(missing_dates) > 0:
gap_start = missing_dates[0]
gap_end = missing_dates[0]
for i in range(1, len(missing_dates)):
if (missing_dates[i] - missing_dates[i - 1]).days == 1:
gap_end = missing_dates[i]
else:
if (gap_end - gap_start).days >= 7:
gaps.append((gap_start, gap_end, (gap_end - gap_start).days))
gap_start = missing_dates[i]
gap_end = missing_dates[i]
if (gap_end - gap_start).days >= 7:
gaps.append((gap_start, gap_end, (gap_end - gap_start).days))
if gaps:
print(f'\nFound {len(gaps)} gaps >= 7 days:')
for start, end, days in gaps:
print(f' {start.date()} to {end.date()} ({days} days)')
else:
print('\nNo significant temporal gaps (all gaps < 7 days)')
return yearly_counts, gaps
def standard_missing_data_analysis(df, output_dir):
"""Missing data summary + chart."""
print_section('MISSING DATA ANALYSIS')
missing = df.isnull().sum()
missing_pct = (missing / len(df) * 100).round(2)
missing_df = pd.DataFrame({
'Missing Count': missing,
'Missing %': missing_pct
}).sort_values('Missing %', ascending=False)
has_missing = missing_df[missing_df['Missing Count'] > 0]
if len(has_missing) > 0:
print(has_missing)
top_missing = has_missing.head(10)
plt.figure(figsize=(12, 6))
top_missing['Missing %'].plot(kind='barh', color='coral')
plt.title('Top 10 Columns by Missing Data %', fontweight='bold')
plt.xlabel('Missing %')
plt.gca().invert_yaxis()
plt.tight_layout()
save_fig(output_dir, 'missing_data')
else:
print('No missing data found.')
return missing_df
def standard_audit_summary(dataset_title, df, extra_lines=None):
"""Print a summary block at the end of an audit."""
print_section(f'AUDIT SUMMARY: {dataset_title}')
print(f'Audit Date: {datetime.now().strftime("%Y-%m-%d")}')
print(f'Total Rows: {len(df):,}')
ts_col = next((c for c in ['timestamp', 'start_time'] if c in df.columns), None)
if ts_col:
print(f'Date Range: {df[ts_col].min().date()} to {df[ts_col].max().date()}')
uid_col = next((c for c in ['user_id_hash', 'user_id', 'username'] if c in df.columns), None)
if uid_col:
print(f'Unique Users: {df[uid_col].nunique():,}')
if extra_lines:
for line in extra_lines:
print(line)
print('=' * 80)
|