Download src/processors/rv_processor.py from instNoeticSciences/GotPsi: direct link, hf CLI and curl.
- Browser
- Download file 12.6 kB
-
https://huggingface.co/datasets/instNoeticSciences/GotPsi/resolve/main/src/processors/rv_processor.py
- Command line
-
hf download hf://datasets/instNoeticSciences/GotPsi/src/processors/rv_processor.py
-
curl -L -o rv_processor.py https://huggingface.co/datasets/instNoeticSciences/GotPsi/resolve/main/src/processors/rv_processor.py
12.6 kB
| """ | |
| RV (Full Remote Viewing) dataset processor. | |
| Processes remote viewing test data with dimensional attribute scoring. | |
| Format: 24-29 columns with user, timestamps, image info, 16 attribute scores, | |
| accuracy/relevance/form metrics, total score, keywords, and trial info. | |
| More complex than RVQ - uses continuous scoring (0-100) instead of binary hit/miss. | |
| """ | |
| 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.delimiter_cleaner import DelimiterCleaner | |
| from ..cleaners.temporal_parser import TemporalParser | |
| class RVProcessor(BaseProcessor): | |
| """ | |
| Processes RV (Full Remote Viewing) data. | |
| Format: 24-29 columns | |
| - user_id, start_time, end_time, image_filename, image_number, | |
| - 16 attribute scores (sr[0] through sr[15]), | |
| - accuracy, relevance, form, total_score, | |
| - keywords, trial_number, method, num_keyword_matches | |
| Users view a target image and describe it using dimensional attributes | |
| (rounded/angular, linear, etc.). Scores based on how well description | |
| matches the actual image attributes. | |
| """ | |
| # File discovery patterns | |
| FILE_PATTERNS = ['rv[0-9]*.dat'] | |
| # Attribute score column names (16 attributes) | |
| ATTRIBUTE_COLUMNS = [f'attr_{i:02d}' for i in range(16)] | |
| # Column definitions | |
| COLUMNS_BASE = [ | |
| 'user_id', 'start_time', 'end_time', 'image_filename', 'image_number' | |
| ] + ATTRIBUTE_COLUMNS + [ | |
| 'accuracy', 'relevance', 'form', 'total_score', | |
| 'keywords', 'trial_number', 'method', 'num_keyword_matches' | |
| ] | |
| COLUMNS_UNIFIED = [ | |
| 'user_id', 'start_time', 'end_time', | |
| 'image_filename', 'image_number' | |
| ] + ATTRIBUTE_COLUMNS + [ | |
| 'accuracy', 'relevance', 'form', 'total_score', | |
| 'keywords', 'trial_number', 'method', 'num_keyword_matches', | |
| 'file_date', 'source_file', 'source_row_number' | |
| ] | |
| def __init__(self, config: Config): | |
| """ | |
| Initialize RV processor. | |
| Args: | |
| config: Configuration object | |
| """ | |
| super().__init__(config, 'rv') | |
| # Initialize cleaners | |
| self.encoding_cleaner = EncodingCleaner(config, self.errata_logger) | |
| self.delimiter_cleaner = DelimiterCleaner(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_valid': 0, | |
| 'rows_invalid': 0, | |
| 'method_original': 0, | |
| 'method_match_judges': 0, | |
| 'method_keywords': 0 | |
| } | |
| def extract_file_date(self, file_path: Path) -> Optional[datetime]: | |
| """ | |
| Extract date from filename (rvYYMMDD.dat). | |
| Args: | |
| file_path: Path to file | |
| Returns: | |
| datetime object or None | |
| """ | |
| match = re.search(r'rv(\d{6})\.dat', file_path.name) | |
| if not match: | |
| return None | |
| date_str = match.group(1) | |
| 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 RV 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) | |
| text = self.delimiter_cleaner.clean(text, file_path=str(file_path)) | |
| # Parse as CSV using Python's csv module to handle variable columns | |
| 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 | |
| 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 | |
| # Check minimum column count (24) | |
| column_counts = df.notna().sum(axis=1) | |
| insufficient_cols = column_counts < 24 | |
| if insufficient_cols.all(): | |
| self.errata_logger.log_error( | |
| 'insufficient_columns', | |
| 'All rows have < 24 columns - entire file omitted', | |
| file_path=str(file_path), | |
| scope='file' | |
| ) | |
| return None | |
| # Filter rows with insufficient columns | |
| if insufficient_cols.any(): | |
| self.errata_logger.log_error( | |
| 'insufficient_columns', | |
| f'{insufficient_cols.sum()} rows with < 24 columns', | |
| file_path=str(file_path), | |
| scope='row' | |
| ) | |
| df = df[~insufficient_cols] | |
| # Assign column names based on actual column count | |
| max_cols = len(df.columns) | |
| if max_cols >= 29: | |
| # Drop extra columns if more than 29 (early files have extra columns) | |
| if max_cols > 29: | |
| # Log that we're dropping extra columns from early files | |
| self.errata_logger.log_error( | |
| 'extra_columns_dropped', | |
| f'File has {max_cols} columns, dropping {max_cols - 29} extra columns from early schema', | |
| file_path=str(file_path), | |
| scope='row' | |
| ) | |
| df = df.iloc[:, :29] | |
| df.columns = self.COLUMNS_BASE[:29] | |
| elif max_cols >= 24: | |
| df.columns = self.COLUMNS_BASE[:max_cols] | |
| else: | |
| self.errata_logger.log_error( | |
| 'insufficient_columns', | |
| f'Max columns {max_cols} < 24 - entire file omitted', | |
| file_path=str(file_path), | |
| scope='file' | |
| ) | |
| return None | |
| # Add metadata | |
| file_date = self.extract_file_date(file_path) | |
| df['file_date'] = file_date | |
| # Add audit columns (source file and row numbers) | |
| df['source_file'] = file_path.name | |
| df['source_row_number'] = range(1, len(df) + 1) | |
| # Filter test users | |
| test_user_mask = df['user_id'].astype(str).str.contains('_test9', na=False) | |
| if test_user_mask.any(): | |
| df = df[~test_user_mask] | |
| # Validate and clean | |
| df = self.validate_dataframe(df, file_path) | |
| if df.empty: | |
| return None | |
| # Ensure all unified columns exist AFTER validation | |
| for col in self.COLUMNS_UNIFIED: | |
| if col not in df.columns: | |
| df[col] = None | |
| # Reorder to unified schema | |
| df = df[self.COLUMNS_UNIFIED] | |
| # Update stats | |
| self.stats['files_processed'] += 1 | |
| self.stats['rows_valid'] += len(df) | |
| # Track method counts | |
| if 'method' in df.columns: | |
| method_counts = df['method'].value_counts() | |
| for method_val, count in method_counts.items(): | |
| if pd.notna(method_val): | |
| method_val = int(method_val) | |
| if method_val % 10 == 0: # 0 or 10 | |
| self.stats['method_original'] += count | |
| elif method_val % 10 == 3: # 3 or 13 | |
| self.stats['method_match_judges'] += count | |
| elif method_val == 9: | |
| self.stats['method_keywords'] += count | |
| return 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()}, | |
| ) | |
| self.stats['files_failed'] += 1 | |
| 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 and clamp total_score (0-100) | |
| if 'total_score' in df.columns: | |
| df['total_score'] = self.to_numeric_logged(df['total_score'], 'total_score', str(file_path)) | |
| # Clamp scores to 0-100 as per Perl code | |
| df.loc[df['total_score'] < 0, 'total_score'] = 0 | |
| df.loc[df['total_score'] > 100, 'total_score'] = 100 | |
| # Validate num_keyword_matches (0-5) | |
| if 'num_keyword_matches' in df.columns: | |
| df['num_keyword_matches'] = self.to_numeric_logged(df['num_keyword_matches'], 'num_keyword_matches', str(file_path)) | |
| invalid_nwm = (df['num_keyword_matches'] < 0) | (df['num_keyword_matches'] > 5) | |
| if invalid_nwm.any(): | |
| # Log but don't filter - just clamp | |
| self.errata_logger.log_error( | |
| 'num_keyword_matches_out_of_range', | |
| f'{invalid_nwm.sum()} rows with num_keyword_matches not in 0-5', | |
| file_path=str(file_path), | |
| scope='row' | |
| ) | |
| df.loc[df['num_keyword_matches'] < 0, 'num_keyword_matches'] = 0 | |
| df.loc[df['num_keyword_matches'] > 5, 'num_keyword_matches'] = 5 | |
| # Parse timestamps | |
| if 'start_time' in df.columns: | |
| df['start_time'] = self.temporal_parser.parse_dates_vectorized( | |
| df['start_time'], file_path=str(file_path) | |
| ) | |
| if 'end_time' in df.columns: | |
| df['end_time'] = self.temporal_parser.parse_dates_vectorized( | |
| df['end_time'], file_path=str(file_path) | |
| ) | |
| # Convert numeric columns | |
| numeric_cols = [ | |
| 'image_number', 'accuracy', 'relevance', 'form', 'total_score', | |
| 'trial_number', 'method', 'num_keyword_matches' | |
| ] + self.ATTRIBUTE_COLUMNS | |
| for col in numeric_cols: | |
| if col in df.columns: | |
| df[col] = self.to_numeric_logged(df[col], col, str(file_path)) | |
| # 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() | |