| """ |
| Process full Users dataset and export to Parquet. |
| |
| Processes all user survey files (users14.dat and questions.dat) and exports cleaned data. |
| """ |
|
|
| import sys |
| import argparse |
| from pathlib import Path |
| from datetime import datetime |
|
|
| sys.path.insert(0, str(Path(__file__).parent.parent)) |
|
|
| from src.core.config import Config |
| from src.core.output_lock import seal_output, unlock_for_write |
| from src.processors.users_processor import UsersProcessor |
|
|
|
|
| def main(): |
| parser = argparse.ArgumentParser(description='Process Users dataset') |
| parser.add_argument('--audit', action='store_true', |
| help='Include source_file and source_row_number columns in output') |
| parser.add_argument('--data-dir', |
| help='Override raw data directory (default: data/)') |
| args = parser.parse_args() |
| print("="*70) |
| print("Users Dataset Full Processing") |
| print("="*70) |
| print() |
|
|
| start_time = datetime.now() |
|
|
| |
| config = Config('config/cleaning_config.yaml') |
|
|
| |
| if args.audit: |
| config.set('processing.audit_mode', True) |
| print("Audit mode: ENABLED (including source_file and source_row_number columns)") |
| print() |
|
|
| |
| if args.data_dir: |
| config.set('directories.raw_data', args.data_dir) |
|
|
|
|
| |
| output_dir = config.output_dir / 'parquet' |
| output_dir.mkdir(parents=True, exist_ok=True) |
|
|
| output_file = output_dir / 'users.parquet' |
|
|
| print(f"Output file: {output_file}") |
| print() |
|
|
| |
| processor = UsersProcessor(config) |
|
|
| |
| try: |
| all_files = processor.get_file_list() |
| print(f"Total files to process: {len(all_files)}") |
| for f in all_files: |
| file_type = processor.detect_file_type(f) |
| print(f" - {f.name} ({file_type})") |
| print() |
| except Exception as e: |
| print(f"✗ Error getting file list: {e}") |
| print() |
| print("Expected directory: data/user_data/") |
| print("Make sure the raw data is in the correct location.") |
| print("Files expected: users14.dat and/or questions.dat") |
| sys.exit(1) |
|
|
| |
| print("Processing all user files...") |
| print() |
|
|
| try: |
| df = processor.process() |
|
|
| elapsed = datetime.now() - start_time |
|
|
| print() |
| print("="*70) |
| print("✓ Processing Complete!") |
| print("="*70) |
| print() |
|
|
| |
| stats = processor.get_stats() |
| print("Processing Statistics:") |
| print(f" Files processed: {stats['files_processed']:,}") |
| print(f" Files failed: {stats['files_failed']:,}") |
| print(f" Success rate: {stats['files_processed'] / len(all_files) * 100:.1f}%") |
| print() |
| print(f" users14.dat rows: {stats['users14_rows']:,}") |
| print(f" questions.dat rows: {stats['questions_rows']:,}") |
| print() |
| print(f" Total rows (pre-dedup): {stats['rows_total']:,}") |
| print(f" Duplicates removed: {stats['duplicates_removed']:,}") |
| print(f" Final rows: {len(df):,}") |
| print(f" NA usernames (kept): {stats['na_usernames_count']:,}") |
| print() |
|
|
| |
| print("Data Quality:") |
| completeness = df.notna().sum() / len(df) |
| print(f" Overall completeness (avg): {completeness.mean():.1%}") |
| print() |
|
|
| |
| print("Column Completeness:") |
| key_cols = ['username', 'timestamp', 'email', 'state', |
| 'coordinates', 'country', 'na_count_psi_and_hemi'] |
| for col in key_cols: |
| if col in df.columns: |
| complete = df[col].notna().sum() |
| pct = complete / len(df) * 100 |
| print(f" {col:25s}: {complete:6,} / {len(df):6,} ({pct:5.1f}%)") |
| print() |
|
|
| |
| psi_cols = [f'psi_{i:02d}' for i in range(1, 16)] |
| existing_psi = [col for col in psi_cols if col in df.columns] |
| if existing_psi: |
| psi_complete = df[existing_psi].notna().sum().sum() |
| psi_total = len(df) * len(existing_psi) |
| print(f"Psi columns (1-15) completeness: {psi_complete:,} / {psi_total:,} ({psi_complete/psi_total*100:.1f}%)") |
| print() |
|
|
| |
| hemi_cols = [f'hemi_{i:02d}' for i in range(1, 11)] |
| existing_hemi = [col for col in hemi_cols if col in df.columns] |
| if existing_hemi: |
| hemi_complete = df[existing_hemi].notna().sum().sum() |
| hemi_total = len(df) * len(existing_hemi) |
| print(f"Hemi columns (1-10) completeness: {hemi_complete:,} / {hemi_total:,} ({hemi_complete/hemi_total*100:.1f}%)") |
| print() |
|
|
| |
| if 'timestamp' in df.columns: |
| valid_ts = df['timestamp'].dropna() |
| if not valid_ts.empty: |
| print(f"Date range: {valid_ts.min()} to {valid_ts.max()}") |
| print(f"Span: {(valid_ts.max() - valid_ts.min()).days} days") |
| print() |
|
|
| |
| if 'file_type' in df.columns: |
| print("File Type Distribution:") |
| for file_type in df['file_type'].unique(): |
| count = (df['file_type'] == file_type).sum() |
| pct = count / len(df) * 100 |
| print(f" {file_type}: {count:,} rows ({pct:.1f}%)") |
| print() |
|
|
| |
| if 'country' in df.columns: |
| print("Top 10 Countries:") |
| country_counts = df['country'].value_counts().head(10) |
| for country, count in country_counts.items(): |
| pct = count / len(df) * 100 |
| print(f" {country}: {count:,} ({pct:.1f}%)") |
| print() |
|
|
| |
| if 'na_count_psi_and_hemi' in df.columns: |
| print("NA Count (Psi + Hemi) Distribution:") |
| na_stats = df['na_count_psi_and_hemi'].describe() |
| print(f" Min: {na_stats['min']:.0f}") |
| print(f" Max: {na_stats['max']:.0f}") |
| print(f" Mean: {na_stats['mean']:.1f}") |
| print(f" Median: {na_stats['50%']:.0f}") |
| print() |
|
|
| |
| print(f"Processing time: {elapsed}") |
| if elapsed.total_seconds() > 0: |
| print(f"Speed: {len(df) / elapsed.total_seconds():.0f} rows/second") |
| print() |
|
|
| |
| df = df.drop(columns=['city', 'how_find'], errors='ignore') |
|
|
| |
| print("Exporting to Parquet...") |
| unlock_for_write(output_file) |
| df.to_parquet( |
| output_file, |
| engine='pyarrow', |
| compression='snappy', |
| index=False |
| ) |
| seal_output(output_file) |
|
|
| file_size_mb = output_file.stat().st_size / (1024 * 1024) |
| print(f"✓ Exported to: {output_file}") |
| print(f" File size: {file_size_mb:.1f} MB") |
| print() |
|
|
| |
| raw_size_estimate = len(df) * 400 |
| compression_ratio = raw_size_estimate / output_file.stat().st_size |
| print(f" Compression ratio: {compression_ratio:.1f}x") |
| print() |
|
|
| |
| errata_summary = processor.errata_logger.get_summary() |
| print("Error Summary:") |
| print(f" Total errors: {errata_summary['total_errors']:,}") |
| print(f" Files with errors: {errata_summary['files_with_errors']:,}") |
| if errata_summary['error_types']: |
| print(f" Error types:") |
| for error_type, count in sorted(errata_summary['error_types'].items(), |
| key=lambda x: x[1], reverse=True)[:10]: |
| print(f" - {error_type}: {count:,}") |
| print(f" Errata log: {errata_summary['log_file']}") |
| print() |
|
|
| print("="*70) |
| print("✓ Users Dataset Processing Complete!") |
| print("="*70) |
|
|
| except KeyboardInterrupt: |
| print("\n\n✗ Processing interrupted by user") |
| sys.exit(1) |
| except Exception as e: |
| print(f"\n✗ Processing failed: {e}") |
| import traceback |
| traceback.print_exc() |
| sys.exit(1) |
|
|
|
|
| if __name__ == '__main__': |
| main() |
|
|