Download src/processors/lottery_processor.py from instNoeticSciences/GotPsi: direct link, hf CLI and curl.
- Browser
- Download file 12.9 kB
-
https://huggingface.co/datasets/instNoeticSciences/GotPsi/resolve/main/src/processors/lottery_processor.py
- Command line
-
hf download hf://datasets/instNoeticSciences/GotPsi/src/processors/lottery_processor.py
-
curl -L -o lottery_processor.py https://huggingface.co/datasets/instNoeticSciences/GotPsi/resolve/main/src/processors/lottery_processor.py
12.9 kB
| """ | |
| Lottery dataset processor. | |
| Processes lottery number prediction data with mixed row types: | |
| - Lottery rows: 9 columns (user_id, timestamp, 5 numbers, 1 mega) | |
| - Immediate drawing rows: 16 columns (adds trial_num, matches, 5 target numbers, 1 target mega) | |
| """ | |
| from pathlib import Path | |
| from typing import List, Dict, Any, Optional | |
| from datetime import datetime | |
| import pandas as pd | |
| import re | |
| from ..core.base_classes import BaseProcessor | |
| from ..core.config import Config | |
| from ..core.exceptions import ProcessorError | |
| from ..cleaners.encoding_cleaner import EncodingCleaner | |
| from ..cleaners.temporal_parser import TemporalParser | |
| class LotteryProcessor(BaseProcessor): | |
| """ | |
| Processes Lottery data. | |
| Format: Mixed row types in same file | |
| - Lottery rows: user picks 5 numbers (1-47) + 1 mega (1-27) | |
| - Immediate rows: adds trial_num, matches, and 6 target numbers | |
| """ | |
| BATCH_DELIMITER_CLEAN = False # mixed row formats (9 and 16 columns), no delimiter standardization | |
| # File discovery patterns | |
| FILE_PATTERNS = ['lot*.dat'] | |
| # Unified output schema | |
| COLUMNS_UNIFIED = [ | |
| 'user_id', 'timestamp', 'row_type', | |
| 'num1', 'num2', 'num3', 'num4', 'num5', 'mega', | |
| 'trial_num', 'matches', | |
| 'target1', 'target2', 'target3', 'target4', 'target5', 'target_mega', | |
| 'file_date', 'source_file', 'source_row_number' | |
| ] | |
| def __init__(self, config: Config): | |
| """ | |
| Initialize Lottery processor. | |
| Args: | |
| config: Configuration object | |
| """ | |
| super().__init__(config, 'lottery') | |
| # Initialize cleaners | |
| self.encoding_cleaner = EncodingCleaner(config, self.errata_logger) | |
| self.temporal_parser = TemporalParser(config, self.errata_logger) | |
| # Statistics | |
| self.stats = { | |
| 'files_processed': 0, | |
| 'files_failed': 0, | |
| 'rows_total': 0, | |
| 'rows_lottery': 0, | |
| 'rows_immediate': 0, | |
| 'rows_valid': 0, | |
| 'rows_invalid': 0 | |
| } | |
| def extract_file_date(self, file_path: Path) -> Optional[datetime]: | |
| """ | |
| Extract date from filename (lotYYMMDD.dat or lotYYMMDDS.dat). | |
| Args: | |
| file_path: Path to file | |
| Returns: | |
| datetime object or None | |
| """ | |
| match = re.search(r'lot(\d{6})', file_path.name) | |
| if not match: | |
| return None | |
| return self.temporal_parser.extract_date_from_filename(file_path.name) | |
| def process_file(self, file_path: Path, pre_cleaned_text: Optional[str] = None) -> Optional[pd.DataFrame]: | |
| """ | |
| Process a single Lottery file. | |
| Args: | |
| file_path: Path to file | |
| pre_cleaned_text: Pre-cleaned text from parallel batch cleaning. | |
| If None, cleans the file inline (backward compat). | |
| Returns: | |
| DataFrame or None if processing fails | |
| """ | |
| try: | |
| # Use pre-cleaned text if available, otherwise clean inline | |
| if pre_cleaned_text is not None: | |
| text = pre_cleaned_text | |
| else: | |
| text = self.encoding_cleaner.clean(file_path) | |
| # DON'T use delimiter cleaner - Lottery has mixed row formats (9 and 16 columns) | |
| # Parse manually to handle variable column counts | |
| from io import StringIO | |
| import csv | |
| reader = csv.reader(StringIO(text), skipinitialspace=True) | |
| rows = list(reader) | |
| if not rows: | |
| self.errata_logger.log_error( | |
| 'empty_file', | |
| 'File is empty after CSV parsing - entire file omitted', | |
| file_path=str(file_path), | |
| scope='file' | |
| ) | |
| return None | |
| # Convert to DataFrame with max columns | |
| df = pd.DataFrame(rows) | |
| if df.empty: | |
| self.errata_logger.log_error( | |
| 'empty_file', | |
| 'File is empty or has no valid rows - entire file omitted', | |
| file_path=str(file_path), | |
| scope='file' | |
| ) | |
| return None | |
| # Detect row types based on column count | |
| # Lottery rows: 8 columns (user, timestamp, 5 nums, mega) | |
| # Immediate rows: 16 columns (adds trial, matches, 5 targets, target_mega) | |
| file_date = self.extract_file_date(file_path) | |
| col_counts = df.notna().sum(axis=1) | |
| is_lottery = col_counts == 8 | |
| is_immediate = col_counts == 16 | |
| # Count row types | |
| self.stats['rows_lottery'] += is_lottery.sum() | |
| self.stats['rows_immediate'] += is_immediate.sum() | |
| # Create unified DataFrame | |
| result_df = pd.DataFrame(index=df.index) | |
| # Common columns for all rows | |
| result_df['user_id'] = df.iloc[:, 0] | |
| result_df['file_date'] = file_date | |
| # Add audit columns (source file and row numbers) | |
| result_df['source_file'] = file_path.name | |
| result_df['source_row_number'] = range(1, len(result_df) + 1) | |
| # Parse timestamps | |
| result_df['timestamp'] = self.temporal_parser.parse_dates_vectorized( | |
| df.iloc[:, 1], file_path=str(file_path) | |
| ) | |
| # Process Lottery rows (8 columns) | |
| result_df.loc[is_lottery, 'row_type'] = 'lottery' | |
| result_df.loc[is_lottery, 'num1'] = self.to_numeric_logged(df.loc[is_lottery].iloc[:, 2], 'num1', str(file_path)) | |
| result_df.loc[is_lottery, 'num2'] = self.to_numeric_logged(df.loc[is_lottery].iloc[:, 3], 'num2', str(file_path)) | |
| result_df.loc[is_lottery, 'num3'] = self.to_numeric_logged(df.loc[is_lottery].iloc[:, 4], 'num3', str(file_path)) | |
| result_df.loc[is_lottery, 'num4'] = self.to_numeric_logged(df.loc[is_lottery].iloc[:, 5], 'num4', str(file_path)) | |
| result_df.loc[is_lottery, 'num5'] = self.to_numeric_logged(df.loc[is_lottery].iloc[:, 6], 'num5', str(file_path)) | |
| result_df.loc[is_lottery, 'mega'] = self.to_numeric_logged(df.loc[is_lottery].iloc[:, 7], 'mega', str(file_path)) | |
| result_df.loc[is_lottery, 'trial_num'] = None | |
| result_df.loc[is_lottery, 'matches'] = None | |
| result_df.loc[is_lottery, 'target1'] = None | |
| result_df.loc[is_lottery, 'target2'] = None | |
| result_df.loc[is_lottery, 'target3'] = None | |
| result_df.loc[is_lottery, 'target4'] = None | |
| result_df.loc[is_lottery, 'target5'] = None | |
| result_df.loc[is_lottery, 'target_mega'] = None | |
| # Process Immediate rows (16 columns) | |
| result_df.loc[is_immediate, 'row_type'] = 'immediate' | |
| result_df.loc[is_immediate, 'num1'] = self.to_numeric_logged(df.loc[is_immediate].iloc[:, 2], 'num1', str(file_path)) | |
| result_df.loc[is_immediate, 'num2'] = self.to_numeric_logged(df.loc[is_immediate].iloc[:, 3], 'num2', str(file_path)) | |
| result_df.loc[is_immediate, 'num3'] = self.to_numeric_logged(df.loc[is_immediate].iloc[:, 4], 'num3', str(file_path)) | |
| result_df.loc[is_immediate, 'num4'] = self.to_numeric_logged(df.loc[is_immediate].iloc[:, 5], 'num4', str(file_path)) | |
| result_df.loc[is_immediate, 'num5'] = self.to_numeric_logged(df.loc[is_immediate].iloc[:, 6], 'num5', str(file_path)) | |
| result_df.loc[is_immediate, 'mega'] = self.to_numeric_logged(df.loc[is_immediate].iloc[:, 7], 'mega', str(file_path)) | |
| result_df.loc[is_immediate, 'trial_num'] = self.to_numeric_logged(df.loc[is_immediate].iloc[:, 8], 'trial_num', str(file_path)) | |
| result_df.loc[is_immediate, 'matches'] = self.to_numeric_logged(df.loc[is_immediate].iloc[:, 9], 'matches', str(file_path)) | |
| result_df.loc[is_immediate, 'target1'] = self.to_numeric_logged(df.loc[is_immediate].iloc[:, 10], 'target1', str(file_path)) | |
| result_df.loc[is_immediate, 'target2'] = self.to_numeric_logged(df.loc[is_immediate].iloc[:, 11], 'target2', str(file_path)) | |
| result_df.loc[is_immediate, 'target3'] = self.to_numeric_logged(df.loc[is_immediate].iloc[:, 12], 'target3', str(file_path)) | |
| result_df.loc[is_immediate, 'target4'] = self.to_numeric_logged(df.loc[is_immediate].iloc[:, 13], 'target4', str(file_path)) | |
| result_df.loc[is_immediate, 'target5'] = self.to_numeric_logged(df.loc[is_immediate].iloc[:, 14], 'target5', str(file_path)) | |
| result_df.loc[is_immediate, 'target_mega'] = self.to_numeric_logged(df.loc[is_immediate].iloc[:, 15], 'target_mega', str(file_path)) | |
| # Validate and clean | |
| result_df = self.validate_dataframe(result_df, file_path) | |
| # Ensure all unified columns exist | |
| for col in self.COLUMNS_UNIFIED: | |
| if col not in result_df.columns: | |
| result_df[col] = None | |
| # Reorder to unified schema | |
| result_df = result_df[self.COLUMNS_UNIFIED] | |
| self.stats['files_processed'] += 1 | |
| self.stats['rows_valid'] += len(result_df) | |
| return result_df | |
| except Exception as e: | |
| import traceback | |
| self.errata_logger.log_error( | |
| 'file_processing_failed', | |
| f'{type(e).__name__}: {e} - entire file omitted', | |
| file_path=str(file_path), | |
| scope='file', | |
| context={'traceback': traceback.format_exc()}, | |
| ) | |
| return None | |
| def validate_dataframe(self, df: pd.DataFrame, file_path: Path) -> pd.DataFrame: | |
| """ | |
| Validate and clean DataFrame. | |
| Args: | |
| df: Input DataFrame | |
| file_path: Source file path | |
| Returns: | |
| Cleaned DataFrame | |
| """ | |
| initial_count = len(df) | |
| valid_mask = pd.Series([True] * len(df), index=df.index) | |
| # Validate user_id length | |
| if 'user_id' in df.columns: | |
| long_users = df['user_id'].str.len() > 64 | |
| if long_users.any(): | |
| valid_mask &= ~long_users | |
| self.errata_logger.log_error( | |
| 'user_id_too_long', | |
| f'{long_users.sum()} rows with user_id > 64 chars', | |
| file_path=str(file_path), | |
| scope='row' | |
| ) | |
| # Validate lottery numbers (1-47) | |
| for col in ['num1', 'num2', 'num3', 'num4', 'num5', 'target1', 'target2', 'target3', 'target4', 'target5']: | |
| if col in df.columns: | |
| df[col] = self.to_numeric_logged(df[col], col, str(file_path)) | |
| invalid = (df[col].notna()) & ((df[col] < 1) | (df[col] > 47)) | |
| if invalid.any(): | |
| valid_mask &= ~invalid | |
| self.errata_logger.log_error( | |
| f'{col}_out_of_range', | |
| f'{invalid.sum()} rows with {col} not in 1-47', | |
| file_path=str(file_path), | |
| scope='row' | |
| ) | |
| # Validate mega numbers (1-27) | |
| for col in ['mega', 'target_mega']: | |
| if col in df.columns: | |
| df[col] = self.to_numeric_logged(df[col], col, str(file_path)) | |
| invalid = (df[col].notna()) & ((df[col] < 1) | (df[col] > 27)) | |
| if invalid.any(): | |
| valid_mask &= ~invalid | |
| self.errata_logger.log_error( | |
| f'{col}_out_of_range', | |
| f'{invalid.sum()} rows with {col} not in 1-27', | |
| file_path=str(file_path), | |
| scope='row' | |
| ) | |
| # Validate matches (0-6) | |
| if 'matches' in df.columns: | |
| df['matches'] = self.to_numeric_logged(df['matches'], 'matches', str(file_path)) | |
| invalid = (df['matches'].notna()) & ((df['matches'] < 0) | (df['matches'] > 6)) | |
| if invalid.any(): | |
| valid_mask &= ~invalid | |
| self.errata_logger.log_error( | |
| 'matches_out_of_range', | |
| f'{invalid.sum()} rows with matches not in 0-6', | |
| file_path=str(file_path), | |
| scope='row' | |
| ) | |
| # Filter to valid rows | |
| df_valid = df[valid_mask].copy() | |
| invalid_count = initial_count - len(df_valid) | |
| if invalid_count > 0: | |
| self.errata_logger.log_file_summary( | |
| str(file_path), | |
| 'partial', | |
| initial_count, | |
| len(df_valid), | |
| invalid_count | |
| ) | |
| return df_valid | |
| def get_stats(self) -> Dict[str, Any]: | |
| """Get processing statistics.""" | |
| return self.stats.copy() | |