File size: 7,251 Bytes
9deebf2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 | """
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)
# Initialize cleaners for detection
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:
# Detect encoding
encoding, encoding_confidence = self.encoding_cleaner.detect_encoding(
file_path
)
profile['encoding'] = encoding
profile['encoding_confidence'] = encoding_confidence
# Read file with detected encoding
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
# Detect delimiter
delimiter, delimiter_consistency = self.delimiter_cleaner.detect_delimiter(
text
)
profile['delimiter'] = delimiter
profile['delimiter_consistency'] = delimiter_consistency
# Analyze column structure
column_counts = []
for i, line in enumerate(lines[:100]): # Sample first 100 lines
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()
# Get sample data
profile['sample_lines'] = lines[:5]
# Detect schema version based on column count
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
# Schema version heuristics based on column count
# These would be refined based on actual data analysis
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:
# Log error but continue
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')
# Encoding distribution
encodings = [p.get('encoding') for p in profiles if 'encoding' in p]
encoding_counts = pd.Series(encodings).value_counts().to_dict()
# Delimiter distribution
delimiters = [p.get('delimiter') for p in profiles if 'delimiter' in p]
delimiter_counts = pd.Series(delimiters).value_counts().to_dict()
# Schema version distribution
versions = [p.get('schema_version') for p in profiles if 'schema_version' in p]
version_counts = pd.Series(versions).value_counts().to_dict()
# File sizes
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
} |