Download scripts/audit/_common.py from instNoeticSciences/GotPsi: direct link, hf CLI and curl.
- Browser
- Download file 5.77 kB
-
https://huggingface.co/datasets/instNoeticSciences/GotPsi/resolve/main/scripts/audit/_common.py
- Command line
-
hf download hf://datasets/instNoeticSciences/GotPsi/scripts/audit/_common.py
-
curl -L -o _common.py https://huggingface.co/datasets/instNoeticSciences/GotPsi/resolve/main/scripts/audit/_common.py
5.77 kB
| """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) | |