Download scripts/summarize_datasets.py from instNoeticSciences/GotPsi: direct link, hf CLI and curl.
- Browser
- Download file 9.94 kB
-
https://huggingface.co/datasets/instNoeticSciences/GotPsi/resolve/main/scripts/summarize_datasets.py
- Command line
-
hf download hf://datasets/instNoeticSciences/GotPsi/scripts/summarize_datasets.py
-
curl -L -o summarize_datasets.py https://huggingface.co/datasets/instNoeticSciences/GotPsi/resolve/main/scripts/summarize_datasets.py
9.94 kB
| """ | |
| Summarize all GotPsi datasets from parquet files. | |
| Generates a comprehensive summary report of all processed datasets including: | |
| - Record counts | |
| - Distinct user counts | |
| - Experiment-specific metrics | |
| - Audit information (if available) | |
| """ | |
| import sys | |
| from pathlib import Path | |
| from datetime import datetime | |
| import pyarrow.parquet as pq | |
| import pyarrow.compute as pc | |
| from typing import Dict, Any, Optional | |
| import json | |
| # Dataset configurations with their specific characteristics | |
| DATASETS = { | |
| 'users': { | |
| 'file': 'users.parquet', | |
| 'description': 'User Survey Responses', | |
| 'key_fields': ['user_id'], | |
| 'metrics': ['total_users', 'has_demographics'], | |
| }, | |
| 'card': { | |
| 'file': 'card_cleaned.parquet', | |
| 'description': 'Basic Card Test (ESP 1-in-5)', | |
| 'key_fields': ['user_id', 'trial_number', 'target2', 'response'], | |
| 'metrics': ['total_trials', 'unique_users', 'conditions', 'hit_rate'], | |
| }, | |
| 'cardd': { | |
| 'file': 'cardD_cleaned.parquet', | |
| 'description': 'Card Test with Details', | |
| 'key_fields': ['user_id', 'trial_number', 'target2', 'response'], | |
| 'metrics': ['total_trials', 'unique_users', 'conditions', 'hit_rate'], | |
| }, | |
| 'cards': { | |
| 'file': 'cardS_cleaned.parquet', | |
| 'description': 'Card Test Shuffled', | |
| 'key_fields': ['user_id', 'trial_number', 'target2', 'response'], | |
| 'metrics': ['total_trials', 'unique_users', 'conditions', 'hit_rate'], | |
| }, | |
| 'rv': { | |
| 'file': 'rv_cleaned.parquet', | |
| 'description': 'Full Remote Viewing', | |
| 'key_fields': ['user_id', 'target', 'response'], | |
| 'metrics': ['total_sessions', 'unique_users', 'targets', 'response_rate'], | |
| }, | |
| 'rvq': { | |
| 'file': 'rvq_cleaned.parquet', | |
| 'description': 'Quick Remote Viewing', | |
| 'key_fields': ['user_id', 'target', 'response'], | |
| 'metrics': ['total_sessions', 'unique_users', 'targets', 'response_rate'], | |
| }, | |
| 'location': { | |
| 'file': 'location_cleaned.parquet', | |
| 'description': 'Remote Viewing Coordinates', | |
| 'key_fields': ['user_id', 'latitude', 'longitude'], | |
| 'metrics': ['total_locations', 'unique_users', 'has_coordinates'], | |
| }, | |
| 'lottery': { | |
| 'file': 'lottery_cleaned.parquet', | |
| 'description': 'Lottery Data', | |
| 'key_fields': ['user_id'], | |
| 'metrics': ['total_entries', 'unique_users'], | |
| }, | |
| } | |
| def get_parquet_summary(file_path: Path) -> Dict[str, Any]: | |
| """Get summary statistics from a parquet file using metadata and efficient operations.""" | |
| try: | |
| # Read parquet metadata | |
| parquet_file = pq.ParquetFile(file_path) | |
| metadata = parquet_file.metadata | |
| schema = parquet_file.schema_arrow | |
| # Basic stats from metadata | |
| num_rows = metadata.num_rows | |
| num_columns = metadata.num_columns | |
| # Column information | |
| columns = schema.names | |
| # Check for audit columns | |
| has_audit = 'source_file' in columns and 'source_row_number' in columns | |
| # Read only needed columns for distinct counts (more efficient than reading all data) | |
| table = pq.read_table(file_path, columns=columns) | |
| # Get distinct user count if user_id exists | |
| distinct_users = None | |
| if 'user_id' in columns: | |
| user_column = table.column('user_id') | |
| distinct_users = pc.count_distinct(user_column).as_py() | |
| # Get distinct source files if audit columns exist | |
| distinct_files = None | |
| if has_audit: | |
| file_column = table.column('source_file') | |
| distinct_files = pc.count_distinct(file_column).as_py() | |
| return { | |
| 'num_rows': num_rows, | |
| 'num_columns': num_columns, | |
| 'columns': columns, | |
| 'has_audit': has_audit, | |
| 'distinct_users': distinct_users, | |
| 'distinct_files': distinct_files, | |
| 'file_size_mb': file_path.stat().st_size / (1024 * 1024), | |
| } | |
| except Exception as e: | |
| return {'error': str(e)} | |
| def calculate_dataset_metrics(dataset_name: str, summary: Dict[str, Any]) -> Dict[str, Any]: | |
| """Calculate experiment-specific metrics for a dataset.""" | |
| metrics = {} | |
| if 'error' in summary: | |
| return metrics | |
| # Common metrics | |
| metrics['records'] = summary['num_rows'] | |
| if summary['distinct_users']: | |
| metrics['unique_users'] = summary['distinct_users'] | |
| # Card-based experiments (card, cardD, cardS) | |
| if dataset_name in ['card', 'cardd', 'cards']: | |
| metrics['experiment_type'] = 'ESP Card Test (1-in-5 chance)' | |
| metrics['expected_hit_rate'] = '20%' | |
| # Could calculate actual hit rate by reading target2 and response columns | |
| # RV experiments (rv, rvq) | |
| elif dataset_name in ['rv', 'rvq']: | |
| metrics['experiment_type'] = 'Remote Viewing' | |
| if dataset_name == 'rv': | |
| metrics['format'] = 'Full RV session' | |
| else: | |
| metrics['format'] = 'Quick RV session' | |
| # Location | |
| elif dataset_name == 'location': | |
| metrics['experiment_type'] = 'Remote Viewing Coordinates' | |
| metrics['data_type'] = 'Geographic coordinates' | |
| # Users | |
| elif dataset_name == 'users': | |
| metrics['experiment_type'] = 'Survey Responses' | |
| metrics['data_type'] = 'User demographics and survey answers' | |
| # Lottery | |
| elif dataset_name == 'lottery': | |
| metrics['experiment_type'] = 'Lottery Predictions' | |
| # Audit information | |
| if summary['has_audit'] and summary['distinct_files']: | |
| metrics['source_files_processed'] = summary['distinct_files'] | |
| return metrics | |
| def format_number(num: int) -> str: | |
| """Format large numbers with commas.""" | |
| return f"{num:,}" | |
| def print_summary_report(results: Dict[str, Any], output_format: str = 'text'): | |
| """Print formatted summary report.""" | |
| if output_format == 'json': | |
| print(json.dumps(results, indent=2)) | |
| return | |
| # Text format | |
| print("=" * 80) | |
| print("GotPsi Datasets Summary Report") | |
| print("=" * 80) | |
| print(f"\nGenerated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}") | |
| print() | |
| total_records = 0 | |
| total_size_mb = 0 | |
| datasets_processed = 0 | |
| datasets_with_audit = 0 | |
| for dataset_name, config in DATASETS.items(): | |
| result = results.get(dataset_name, {}) | |
| if 'error' in result: | |
| print(f"\n{config['description']} ({dataset_name})") | |
| print("-" * 80) | |
| print(f" Status: NOT FOUND or ERROR - {result['error']}") | |
| continue | |
| summary = result['summary'] | |
| metrics = result['metrics'] | |
| datasets_processed += 1 | |
| total_records += summary['num_rows'] | |
| total_size_mb += summary['file_size_mb'] | |
| if summary['has_audit']: | |
| datasets_with_audit += 1 | |
| print(f"\n{config['description']} ({dataset_name})") | |
| print("-" * 80) | |
| print(f" Records: {format_number(summary['num_rows'])}") | |
| if summary['distinct_users']: | |
| print(f" Unique Users: {format_number(summary['distinct_users'])}") | |
| print(f" Columns: {summary['num_columns']}") | |
| print(f" File Size: {summary['file_size_mb']:.2f} MB") | |
| if metrics.get('experiment_type'): | |
| print(f" Experiment Type: {metrics['experiment_type']}") | |
| if metrics.get('expected_hit_rate'): | |
| print(f" Expected Rate: {metrics['expected_hit_rate']}") | |
| if summary['has_audit'] and summary['distinct_files']: | |
| print(f" Source Files: {format_number(summary['distinct_files'])} distinct files processed") | |
| print(f" Audit Tracking: ENABLED") | |
| else: | |
| print(f" Audit Tracking: DISABLED") | |
| # Overall summary | |
| print("\n" + "=" * 80) | |
| print("Overall Summary") | |
| print("=" * 80) | |
| print(f" Total Datasets: {datasets_processed}") | |
| print(f" Total Records: {format_number(total_records)}") | |
| print(f" Total Size: {total_size_mb:.2f} MB") | |
| print(f" Datasets with Audit: {datasets_with_audit}") | |
| print() | |
| def main(): | |
| import argparse | |
| parser = argparse.ArgumentParser( | |
| description='Summarize all GotPsi datasets', | |
| formatter_class=argparse.RawDescriptionHelpFormatter, | |
| ) | |
| parser.add_argument('--output-dir', type=Path, default=Path('output/parquet'), | |
| help='Directory containing parquet files (default: output/parquet)') | |
| parser.add_argument('--format', choices=['text', 'json'], default='text', | |
| help='Output format (default: text)') | |
| parser.add_argument('--output-file', type=Path, | |
| help='Write report to file instead of stdout') | |
| args = parser.parse_args() | |
| # Check if output directory exists | |
| if not args.output_dir.exists(): | |
| print(f"Error: Output directory not found: {args.output_dir}", file=sys.stderr) | |
| sys.exit(1) | |
| # Process each dataset | |
| results = {} | |
| for dataset_name, config in DATASETS.items(): | |
| file_path = args.output_dir / config['file'] | |
| if not file_path.exists(): | |
| results[dataset_name] = {'error': f'File not found: {file_path}'} | |
| continue | |
| summary = get_parquet_summary(file_path) | |
| metrics = calculate_dataset_metrics(dataset_name, summary) | |
| results[dataset_name] = { | |
| 'summary': summary, | |
| 'metrics': metrics, | |
| } | |
| # Output results | |
| if args.output_file: | |
| import sys | |
| original_stdout = sys.stdout | |
| with open(args.output_file, 'w') as f: | |
| sys.stdout = f | |
| print_summary_report(results, args.format) | |
| sys.stdout = original_stdout | |
| print(f"Report written to: {args.output_file}") | |
| else: | |
| print_summary_report(results, args.format) | |
| if __name__ == '__main__': | |
| main() | |