| """ |
| File profiler for detecting format characteristics. |
| |
| Analyzes files to determine encoding, delimiter, column count, |
| schema version, and other structural properties. |
| """ |
|
|
| from pathlib import Path |
| from typing import Dict, Any, Optional, List |
| import pandas as pd |
|
|
| from ..core.base_classes import BaseProfiler |
| from ..core.config import Config |
| from ..core.exceptions import ProfilerError |
| from ..cleaners.encoding_cleaner import EncodingCleaner |
| from ..cleaners.delimiter_cleaner import DelimiterCleaner |
|
|
|
|
| class FileProfiler(BaseProfiler): |
| """ |
| Profiles data files to detect their format characteristics. |
| |
| Creates a comprehensive profile including: |
| - File size and line count |
| - Encoding and confidence |
| - Delimiter type and consistency |
| - Column count and consistency |
| - Sample data |
| - Detected schema version |
| """ |
|
|
| def __init__(self, config: Config): |
| """ |
| Initialize file profiler. |
| |
| Args: |
| config: Configuration object |
| """ |
| super().__init__(config) |
|
|
| |
| self.encoding_cleaner = EncodingCleaner(config) |
| self.delimiter_cleaner = DelimiterCleaner(config) |
|
|
| 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 |
| |
| Raises: |
| ProfilerError: If profiling fails |
| """ |
| file_path = Path(file_path) |
|
|
| if not file_path.exists(): |
| raise ProfilerError(f"File not found: {file_path}") |
|
|
| profile = { |
| 'file_path': str(file_path), |
| 'file_name': file_path.name, |
| 'file_size_bytes': file_path.stat().st_size |
| } |
|
|
| try: |
| |
| encoding, encoding_confidence = self.encoding_cleaner.detect_encoding( |
| file_path |
| ) |
| profile['encoding'] = encoding |
| profile['encoding_confidence'] = encoding_confidence |
|
|
| |
| text = self.encoding_cleaner.clean(file_path) |
| lines = text.strip().split('\n') |
| profile['line_count'] = len(lines) |
|
|
| if not lines: |
| profile['status'] = 'empty' |
| return profile |
|
|
| |
| delimiter, delimiter_consistency = self.delimiter_cleaner.detect_delimiter( |
| text |
| ) |
| profile['delimiter'] = delimiter |
| profile['delimiter_consistency'] = delimiter_consistency |
|
|
| |
| column_counts = [] |
| for i, line in enumerate(lines[:100]): |
| if line.strip(): |
| cols = line.split(delimiter) |
| column_counts.append(len(cols)) |
|
|
| if column_counts: |
| profile['column_count_mode'] = max(set(column_counts), key=column_counts.count) |
| profile['column_count_min'] = min(column_counts) |
| profile['column_count_max'] = max(column_counts) |
| profile['column_count_std'] = pd.Series(column_counts).std() |
|
|
| |
| profile['sample_lines'] = lines[:5] |
|
|
| |
| profile['schema_version'] = self._detect_schema_version( |
| profile.get('column_count_mode') |
| ) |
|
|
| profile['status'] = 'success' |
|
|
| except Exception as e: |
| profile['status'] = 'failed' |
| profile['error'] = str(e) |
|
|
| return profile |
|
|
| def _detect_schema_version(self, column_count: Optional[int]) -> Optional[str]: |
| """ |
| Detect schema version based on column count. |
| |
| Args: |
| column_count: Number of columns |
| |
| Returns: |
| Schema version identifier or None |
| """ |
| if column_count is None: |
| return None |
|
|
| |
| |
| if column_count <= 10: |
| return 'v1' |
| elif column_count <= 13: |
| return 'v2' |
| elif column_count <= 15: |
| return 'v3' |
| elif column_count <= 18: |
| return 'v4' |
| else: |
| return 'v5' |
|
|
| def profile_batch( |
| self, |
| file_paths: List[str | Path], |
| show_progress: bool = True |
| ) -> List[Dict[str, Any]]: |
| """ |
| Profile multiple files. |
| |
| Args: |
| file_paths: List of file paths |
| show_progress: Whether to show progress bar |
| |
| Returns: |
| List of profile dictionaries |
| """ |
| profiles = [] |
|
|
| if show_progress: |
| try: |
| from tqdm import tqdm |
| iterator = tqdm(file_paths, desc="Profiling files") |
| except ImportError: |
| iterator = file_paths |
| else: |
| iterator = file_paths |
|
|
| for file_path in iterator: |
| try: |
| profile = self.profile(file_path) |
| profiles.append(profile) |
| except ProfilerError as e: |
| |
| profiles.append({ |
| 'file_path': str(file_path), |
| 'status': 'failed', |
| 'error': str(e) |
| }) |
|
|
| return profiles |
|
|
| def generate_summary_report( |
| self, |
| profiles: List[Dict[str, Any]] |
| ) -> Dict[str, Any]: |
| """ |
| Generate summary report from batch profiling results. |
| |
| Args: |
| profiles: List of profile dictionaries |
| |
| Returns: |
| Summary statistics dictionary |
| """ |
| total_files = len(profiles) |
| successful = sum(1 for p in profiles if p.get('status') == 'success') |
| failed = sum(1 for p in profiles if p.get('status') == 'failed') |
|
|
| |
| encodings = [p.get('encoding') for p in profiles if 'encoding' in p] |
| encoding_counts = pd.Series(encodings).value_counts().to_dict() |
|
|
| |
| delimiters = [p.get('delimiter') for p in profiles if 'delimiter' in p] |
| delimiter_counts = pd.Series(delimiters).value_counts().to_dict() |
|
|
| |
| versions = [p.get('schema_version') for p in profiles if 'schema_version' in p] |
| version_counts = pd.Series(versions).value_counts().to_dict() |
|
|
| |
| sizes = [p.get('file_size_bytes', 0) for p in profiles] |
| total_size_bytes = sum(sizes) |
| avg_size_bytes = total_size_bytes / len(sizes) if sizes else 0 |
|
|
| return { |
| 'total_files': total_files, |
| 'successful': successful, |
| 'failed': failed, |
| 'total_size_bytes': total_size_bytes, |
| 'total_size_gb': total_size_bytes / (1024**3), |
| 'avg_size_bytes': avg_size_bytes, |
| 'encodings': encoding_counts, |
| 'delimiters': delimiter_counts, |
| 'schema_versions': version_counts |
| } |