| """ |
| Base classes for the GotPsi data cleaning pipeline. |
| |
| Defines abstract base classes that establish the interface |
| for cleaners, processors, and exporters. |
| """ |
|
|
| from abc import ABC, abstractmethod |
| from pathlib import Path |
| from typing import Any, Dict, List, Optional |
| import warnings |
| import pandas as pd |
| from collections import defaultdict |
|
|
| warnings.filterwarnings('ignore', message='.*empty or all-NA entries.*') |
|
|
| from .config import Config |
| from .errata_logger import ErrataLogger |
| from .file_discovery_logger import FileDiscoveryLogger |
|
|
|
|
| class BaseCleaner(ABC): |
| """ |
| Abstract base class for data cleaning modules. |
| |
| Cleaners handle specific aspects of data cleaning such as |
| encoding normalization, delimiter standardization, etc. |
| """ |
|
|
| def __init__(self, config: Config, errata_logger: Optional[ErrataLogger] = None): |
| """ |
| Initialize cleaner with configuration. |
| |
| Args: |
| config: Configuration object |
| errata_logger: Optional errata logger for error tracking |
| """ |
| self.config = config |
| self.errata_logger = errata_logger |
|
|
| @abstractmethod |
| def clean(self, data: Any, **kwargs) -> Any: |
| """ |
| Clean the input data. |
| |
| Args: |
| data: Input data to clean (format varies by cleaner) |
| **kwargs: Additional parameters |
| |
| Returns: |
| Cleaned data |
| """ |
| pass |
|
|
| def log_error( |
| self, |
| error_type: str, |
| message: str, |
| **kwargs |
| ) -> None: |
| """ |
| Log an error to the errata logger if available. |
| |
| Args: |
| error_type: Type of error |
| message: Error message |
| **kwargs: Additional context (file_path, row_number, etc.) |
| """ |
| if self.errata_logger: |
| self.errata_logger.log_error(error_type, message, **kwargs) |
|
|
|
|
| class BaseProcessor(ABC): |
| """ |
| Abstract base class for dataset-specific processors. |
| |
| Processors handle the complete data cleaning workflow for |
| a specific dataset type (e.g., card tests, RV tests). |
| """ |
|
|
| def __init__(self, config: Config, dataset_name: str): |
| """ |
| Initialize processor for a dataset. |
| |
| Args: |
| config: Configuration object |
| dataset_name: Name of the dataset to process |
| """ |
| self.config = config |
| self.dataset_name = dataset_name |
| self.dataset_config = config.dataset_config(dataset_name) |
|
|
| |
| errata_dir = config.logs_dir / 'errata' |
| self.errata_logger = ErrataLogger(errata_dir, dataset_name) |
|
|
| |
| file_discovery_dir = config.logs_dir / 'file_discovery' |
| self.file_discovery_logger = FileDiscoveryLogger(file_discovery_dir, dataset_name) |
|
|
| def process(self, max_files: Optional[int] = None, chunk_size: int = 100) -> pd.DataFrame: |
| """ |
| Process all files with parallel cleaning and chunked concatenation. |
| |
| Override this in subclasses that need custom post-processing (e.g., users). |
| |
| Args: |
| max_files: Optional limit on number of files to process |
| chunk_size: Number of files to process before concatenating (default: 100) |
| |
| Returns: |
| Combined DataFrame |
| """ |
| import gc |
| from .exceptions import ProcessorError |
|
|
| files = self.get_file_list() |
| if max_files: |
| files = files[:max_files] |
|
|
| print(f"Processing {len(files)} {self.dataset_name} files...") |
|
|
| |
| use_delim = getattr(self, 'BATCH_DELIMITER_CLEAN', True) |
| cleaned_texts = self._batch_clean_files(files, use_delimiter_cleaner=use_delim) |
| print(f"Successfully cleaned {len(cleaned_texts)}/{len(files)} files") |
|
|
| |
| intermediate_chunks = [] |
| current_chunk = [] |
|
|
| try: |
| from tqdm import tqdm |
| iterator = tqdm(files, desc=f"Processing {self.dataset_name} files") |
| except ImportError: |
| iterator = files |
|
|
| for file_path in iterator: |
| pre_cleaned = cleaned_texts.get(file_path) |
| if pre_cleaned is None: |
| continue |
|
|
| df = self.process_file(file_path, pre_cleaned_text=pre_cleaned) |
|
|
| if df is not None and not df.empty: |
| current_chunk.append(df) |
|
|
| if len(current_chunk) >= chunk_size: |
| chunk_df = pd.concat(current_chunk, ignore_index=True) |
| del current_chunk |
| current_chunk = [] |
| intermediate_chunks.append(chunk_df) |
| gc.collect() |
|
|
| if current_chunk: |
| chunk_df = pd.concat(current_chunk, ignore_index=True) |
| del current_chunk |
| intermediate_chunks.append(chunk_df) |
| gc.collect() |
|
|
| if not intermediate_chunks: |
| raise ProcessorError("No valid data processed") |
|
|
| print(f"Combining {len(intermediate_chunks)} intermediate chunks...") |
|
|
| |
| while len(intermediate_chunks) > 1: |
| pair_results = [] |
| for i in range(0, len(intermediate_chunks), 2): |
| if i + 1 < len(intermediate_chunks): |
| pair_df = pd.concat( |
| [intermediate_chunks[i], intermediate_chunks[i + 1]], |
| ignore_index=True |
| ) |
| pair_results.append(pair_df) |
| else: |
| pair_results.append(intermediate_chunks[i]) |
| intermediate_chunks = pair_results |
| gc.collect() |
|
|
| combined = intermediate_chunks[0] |
| del intermediate_chunks |
| gc.collect() |
|
|
| |
| combined = self._post_process(combined) |
|
|
| |
| self.errata_logger.close() |
|
|
| return combined |
|
|
| def _post_process(self, combined: pd.DataFrame) -> pd.DataFrame: |
| """ |
| Post-processing hook called after all files are combined. |
| |
| Default: removes audit columns if audit_mode is disabled. |
| Override in subclasses for custom post-processing. |
| """ |
| |
| audit_mode = self.config.get('processing.audit_mode', False) |
| if not audit_mode: |
| audit_cols = ['source_file', 'source_row_number'] |
| cols_to_drop = [col for col in audit_cols if col in combined.columns] |
| if cols_to_drop: |
| combined = combined.drop(columns=cols_to_drop) |
| print(f"Audit mode disabled: Removed columns {cols_to_drop}") |
| print() |
|
|
| return combined |
|
|
| def pre_validate_csv_lines( |
| self, |
| text: str, |
| file_path: Optional[str] = None, |
| ) -> str: |
| """Remove lines with inconsistent column counts, logging each drop. |
| |
| Determines the modal (most common) comma count, then filters out |
| any non-blank line that doesn't match. This replaces the silent |
| on_bad_lines='skip' with an audited pre-filter. |
| """ |
| from collections import Counter |
|
|
| lines = text.split('\n') |
| if not lines: |
| return text |
|
|
| comma_counts = [] |
| for line in lines: |
| stripped = line.strip() |
| if stripped: |
| comma_counts.append(stripped.count(',')) |
|
|
| if not comma_counts: |
| return text |
|
|
| modal_count = Counter(comma_counts).most_common(1)[0][0] |
|
|
| kept = [] |
| dropped = 0 |
| for lineno, line in enumerate(lines, 1): |
| stripped = line.strip() |
| if not stripped: |
| kept.append(line) |
| continue |
| if stripped.count(',') == modal_count: |
| kept.append(line) |
| else: |
| dropped += 1 |
| if dropped <= 20: |
| preview = stripped[:120] |
| self.errata_logger.log_error( |
| 'bad_csv_line', |
| f"Line {lineno}: expected {modal_count} commas, got {stripped.count(',')}: {preview!r}", |
| file_path=file_path, |
| line_number=lineno, |
| scope='row', |
| ) |
|
|
| if dropped > 0: |
| self.errata_logger.log_error( |
| 'bad_csv_lines_total', |
| f"{dropped} line(s) dropped due to inconsistent column count (expected {modal_count + 1} columns)", |
| file_path=file_path, |
| scope='file', |
| ) |
|
|
| return '\n'.join(kept) |
|
|
| def to_numeric_logged( |
| self, |
| series: pd.Series, |
| col_name: str, |
| file_path: Optional[str] = None, |
| ) -> pd.Series: |
| """Convert series to numeric, logging any values that get coerced to NaN.""" |
| coerced = pd.to_numeric(series, errors='coerce') |
| bad_mask = coerced.isna() & series.notna() & (series.astype(str).str.strip() != '') |
| if bad_mask.any(): |
| bad_values = series[bad_mask].astype(str).unique()[:10] |
| self.errata_logger.log_error( |
| 'numeric_coercion', |
| f"{bad_mask.sum()} non-numeric value(s) coerced to NaN in '{col_name}': {list(bad_values)}", |
| file_path=file_path, |
| scope='row', |
| ) |
| return coerced |
|
|
| @abstractmethod |
| def process_file(self, file_path: Path, pre_cleaned_text: Optional[str] = None) -> Optional[pd.DataFrame]: |
| """ |
| Process a single file. |
| |
| Args: |
| file_path: Path to the raw data file |
| pre_cleaned_text: Pre-cleaned text (from parallel batch cleaning). |
| If None, the processor should clean the file itself. |
| |
| Returns: |
| DataFrame or None if processing fails |
| """ |
| pass |
|
|
| |
| FILE_PATTERNS: List[str] = [] |
|
|
| def get_file_list(self) -> List[Path]: |
| """ |
| Get list of files to process for this dataset. |
| |
| Checks config 'file_discovery.use_manifest': |
| - False (default): recursive glob using FILE_PATTERNS |
| - True: reads from manifest.json in the experiment directory |
| |
| Returns: |
| List of file paths |
| """ |
| use_manifest = self.config.get('file_discovery.use_manifest', False) |
|
|
| if use_manifest: |
| experiment_dir = self.config.raw_data_dir / self.dataset_name |
| return self.discover_files_from_manifest(experiment_dir) |
| else: |
| files = self.discover_files(self.FILE_PATTERNS) |
| if not files: |
| from .exceptions import ProcessorError |
| raise ProcessorError( |
| f"No {self.dataset_name} files found matching patterns " |
| f"{self.FILE_PATTERNS} in {self.config.raw_data_dir}" |
| ) |
| return files |
|
|
| def get_dataset_path(self) -> Path: |
| """ |
| Get the full path to the dataset directory. |
| |
| Returns: |
| Path to dataset directory |
| """ |
| rel_path = self.dataset_config['path'] |
| return self.config.raw_data_dir / rel_path |
|
|
| def discover_files(self, patterns: List[str], search_root: Optional[Path] = None) -> List[Path]: |
| """ |
| Recursively discover files matching patterns, with deduplication. |
| |
| Searches the data directory recursively for files matching the given patterns. |
| When duplicate filenames are found, keeps the larger file. |
| Logs all discoveries and deduplication decisions. |
| |
| Args: |
| patterns: List of filename patterns (e.g., ['users*.dat', 'questions*.dat']) |
| search_root: Root directory to search (defaults to config.raw_data_dir) |
| |
| Returns: |
| List of unique file paths (deduplicated) |
| """ |
| if search_root is None: |
| search_root = Path(self.config.raw_data_dir) |
|
|
| |
| self.file_discovery_logger.set_search_params(search_root, patterns) |
|
|
| |
| all_files = [] |
| for pattern in patterns: |
| matching_files = list(search_root.rglob(pattern)) |
| all_files.extend(matching_files) |
|
|
| |
| print(f"File Discovery: Found {len(all_files)} file(s) matching patterns {patterns}") |
| for file_path in all_files: |
| self.file_discovery_logger.add_discovered_file(file_path) |
| print(f" - {file_path.name}: {file_path.stat().st_size / (1024*1024):.2f} MB") |
|
|
| |
| deduplicated_files = self._deduplicate_files(all_files) |
|
|
| |
| print(f"\nAfter deduplication: {len(deduplicated_files)} unique file(s) selected") |
| for file_path in deduplicated_files: |
| self.file_discovery_logger.add_selected_file(file_path) |
|
|
| |
| self.file_discovery_logger.finalize_and_write() |
| print(f"File discovery log: {self.file_discovery_logger.get_log_file()}") |
| print() |
|
|
| return deduplicated_files |
|
|
| def _deduplicate_files(self, files: List[Path]) -> List[Path]: |
| """ |
| Deduplicate files by name, keeping the larger file. |
| |
| Args: |
| files: List of file paths |
| |
| Returns: |
| Deduplicated list of file paths |
| """ |
| |
| files_by_name = defaultdict(list) |
| for file_path in files: |
| files_by_name[file_path.name].append(file_path) |
|
|
| |
| selected_files = [] |
| for filename, file_list in files_by_name.items(): |
| if len(file_list) == 1: |
| |
| selected_files.append(file_list[0]) |
| else: |
| |
| largest_file = max(file_list, key=lambda f: f.stat().st_size) |
| selected_files.append(largest_file) |
|
|
| |
| self.file_discovery_logger.add_duplicate_set( |
| files=file_list, |
| selected_file=largest_file, |
| reason=f"Largest file ({largest_file.stat().st_size} bytes)" |
| ) |
|
|
| |
| print(f"\n⚠ Found {len(file_list)} copies of '{filename}':") |
| for f in file_list: |
| marker = "✓ SELECTED" if f == largest_file else " skipped" |
| print(f" {marker}: {f} ({f.stat().st_size / (1024*1024):.2f} MB)") |
|
|
| return sorted(selected_files) |
|
|
| def discover_files_from_manifest(self, experiment_dir: Path) -> List[Path]: |
| """ |
| Discover files by reading the experiment directory's manifest.json. |
| |
| Args: |
| experiment_dir: Path to the experiment directory containing manifest.json |
| |
| Returns: |
| List of file paths that exist on disk |
| |
| Raises: |
| ProcessorError: If no manifest-listed files exist on disk |
| """ |
| import json |
| import logging |
| from .exceptions import ProcessorError |
|
|
| logger = logging.getLogger(__name__) |
|
|
| manifest_path = experiment_dir / 'manifest.json' |
| if not manifest_path.exists(): |
| raise ProcessorError( |
| f"No manifest.json found in {experiment_dir}. " |
| f"Run scripts/migrate_raw_data.py first." |
| ) |
|
|
| manifest = json.loads(manifest_path.read_text()) |
| found = [] |
| missing = [] |
|
|
| for entry in manifest.get('files', []): |
| file_path = experiment_dir / entry['filename'] |
| if file_path.exists(): |
| found.append(file_path) |
| else: |
| missing.append(entry['filename']) |
| logger.warning(f"Manifest-listed file not found: {file_path}") |
|
|
| if missing: |
| logger.warning( |
| f"{len(missing)}/{len(manifest['files'])} manifest files missing " |
| f"in {experiment_dir}" |
| ) |
|
|
| if not found: |
| raise ProcessorError( |
| f"No manifest-listed files found in {experiment_dir}. " |
| f"Run scripts/download_data.py to fetch the data." |
| ) |
|
|
| return sorted(found) |
|
|
| def _read_and_clean_text( |
| self, |
| file_path: Path, |
| use_delimiter_cleaner: bool = True |
| ) -> str: |
| """ |
| Read a file and clean its encoding and delimiters. |
| |
| This is the unit of work for parallel batch cleaning. |
| |
| Args: |
| file_path: Path to the raw data file |
| use_delimiter_cleaner: Whether to apply delimiter standardization |
| |
| Returns: |
| Cleaned UTF-8 text string |
| """ |
| |
| text = self.encoding_cleaner.clean(file_path) |
|
|
| |
| if use_delimiter_cleaner and hasattr(self, 'delimiter_cleaner'): |
| text = self.delimiter_cleaner.clean(text, file_path=str(file_path)) |
|
|
| return text |
|
|
| def _batch_clean_files( |
| self, |
| files: List[Path], |
| use_delimiter_cleaner: bool = True, |
| max_workers: Optional[int] = None |
| ) -> Dict[Path, str]: |
| """ |
| Clean all files in parallel using ThreadPoolExecutor. |
| |
| Encoding detection (chardet) and file I/O release the GIL, |
| making threads effective here. |
| |
| Args: |
| files: List of file paths to clean |
| use_delimiter_cleaner: Whether to apply delimiter standardization |
| max_workers: Max threads (defaults to min(8, len(files))) |
| |
| Returns: |
| Dict mapping file path to cleaned text. Failed files are excluded. |
| """ |
| from concurrent.futures import ThreadPoolExecutor, as_completed |
|
|
| if not files: |
| return {} |
|
|
| if max_workers is None: |
| max_workers = min(8, len(files)) |
|
|
| results: Dict[Path, str] = {} |
|
|
| def clean_one(file_path: Path) -> tuple: |
| try: |
| text = self._read_and_clean_text(file_path, use_delimiter_cleaner) |
| return (file_path, text, None) |
| except Exception as e: |
| return (file_path, None, e) |
|
|
| with ThreadPoolExecutor(max_workers=max_workers) as executor: |
| futures = {executor.submit(clean_one, f): f for f in files} |
|
|
| try: |
| from tqdm import tqdm |
| iterator = tqdm( |
| as_completed(futures), |
| total=len(futures), |
| desc="Cleaning files" |
| ) |
| except ImportError: |
| iterator = as_completed(futures) |
|
|
| for future in iterator: |
| file_path, text, error = future.result() |
| if error is not None: |
| self.errata_logger.log_error( |
| 'batch_clean_failed', |
| f'Failed to clean file: {error}', |
| file_path=str(file_path), |
| scope='file' |
| ) |
| else: |
| results[file_path] = text |
|
|
| return results |
|
|
|
|
| class BaseProfiler(ABC): |
| """ |
| Abstract base class for file profilers. |
| |
| Profilers analyze files to detect format characteristics |
| such as encoding, delimiters, and schema. |
| """ |
|
|
| def __init__(self, config: Config): |
| """ |
| Initialize profiler with configuration. |
| |
| Args: |
| config: Configuration object |
| """ |
| self.config = config |
|
|
| @abstractmethod |
| def profile(self, file_path: str | Path) -> Dict[str, Any]: |
| """ |
| Profile a file to detect its characteristics. |
| |
| Args: |
| file_path: Path to file to profile |
| |
| Returns: |
| Dictionary with profile information |
| """ |
| pass |
|
|
|
|
| class BaseExporter(ABC): |
| """ |
| Abstract base class for data exporters. |
| |
| Exporters handle writing cleaned data to various formats |
| (HDF5, Parquet, CSV). |
| """ |
|
|
| def __init__(self, config: Config): |
| """ |
| Initialize exporter with configuration. |
| |
| Args: |
| config: Configuration object |
| """ |
| self.config = config |
|
|
| @abstractmethod |
| def export(self, data: pd.DataFrame, output_path: str | Path, **kwargs) -> None: |
| """ |
| Export data to output file. |
| |
| Args: |
| data: DataFrame to export |
| output_path: Output file path |
| **kwargs: Format-specific parameters |
| """ |
| pass |
|
|
|
|
| class BaseQualityAssessor(ABC): |
| """ |
| Abstract base class for data quality assessment. |
| |
| Quality assessors analyze cleaned data and compute |
| quality scores and metrics. |
| """ |
|
|
| def __init__(self, config: Config): |
| """ |
| Initialize quality assessor with configuration. |
| |
| Args: |
| config: Configuration object |
| """ |
| self.config = config |
|
|
| @abstractmethod |
| def assess(self, data: pd.DataFrame) -> Dict[str, Any]: |
| """ |
| Assess data quality and compute metrics. |
| |
| Args: |
| data: DataFrame to assess |
| |
| Returns: |
| Dictionary with quality metrics |
| """ |
| pass |
|
|
| @abstractmethod |
| def compute_quality_score(self, metrics: Dict[str, Any]) -> float: |
| """ |
| Compute overall quality score from metrics. |
| |
| Args: |
| metrics: Quality metrics dictionary |
| |
| Returns: |
| Quality score (0-10) |
| """ |
| pass |