""" High-performance data processing using Polars and DuckDB. Handles file loading, format detection, and data transformation with hybrid in-memory/temp file approach. """ import logging import polars as pl import duckdb from pathlib import Path from typing import Dict, Any, Optional, Tuple, Union from enum import Enum import json import tempfile import os from io import BytesIO, StringIO logger = logging.getLogger(__name__) class FileFormat(str, Enum): """Supported file formats.""" CSV = "csv" EXCEL = "excel" JSON = "json" SQL = "sql" PARQUET = "parquet" class DataProcessor: """High-performance data processor using Polars and DuckDB with hybrid processing approach.""" def __init__(self): """Initialize the data processor.""" self.duckdb_conn = None def detect_file_format(self, file_path: Union[str, Path]) -> FileFormat: """Detect file format from file extension. Args: file_path: Path to the file Returns: Detected file format Raises: ValueError: If file format is not supported """ file_path = Path(file_path) extension = file_path.suffix.lower() format_mapping = { '.csv': FileFormat.CSV, '.xlsx': FileFormat.EXCEL, '.xls': FileFormat.EXCEL, '.json': FileFormat.JSON, '.sql': FileFormat.SQL, '.parquet': FileFormat.PARQUET } if extension not in format_mapping: raise ValueError(f"Unsupported file format: {extension}") return format_mapping[extension] def load_file(self, file_path: Union[str, Path], file_format: Optional[FileFormat] = None) -> pl.DataFrame: """Load file into Polars DataFrame using optimal loader. Args: file_path: Path to the file file_format: File format (auto-detected if None) Returns: Polars DataFrame with loaded data Raises: ValueError: If file format is not supported FileNotFoundError: If file doesn't exist """ file_path = Path(file_path) if not file_path.exists(): raise FileNotFoundError(f"File not found: {file_path}") if file_format is None: file_format = self.detect_file_format(file_path) logger.info(f"Loading {file_format.value} file: {file_path}") try: if file_format == FileFormat.CSV: return self._load_csv(file_path) elif file_format == FileFormat.EXCEL: return self._load_excel(file_path) elif file_format == FileFormat.JSON: return self._load_json(file_path) elif file_format == FileFormat.SQL: return self._load_sql(file_path) elif file_format == FileFormat.PARQUET: return self._load_parquet(file_path) else: raise ValueError(f"Unsupported file format: {file_format}") except Exception as e: logger.error(f"Failed to load file {file_path}: {e}") raise def _load_csv(self, file_path: Path) -> pl.DataFrame: """Load CSV file using Polars.""" return pl.read_csv( file_path, infer_schema_length=10000, # Analyze more rows for better type inference try_parse_dates=True, null_values=["", "NULL", "null", "None", "N/A", "n/a"] ) def _load_excel(self, file_path: Path) -> pl.DataFrame: """Load Excel file using Polars.""" try: # Try to read Excel file directly with Polars return pl.read_excel(file_path) except Exception as e: logger.warning(f"Direct Excel loading failed: {e}. Trying alternative method.") # Fallback: use pandas to read Excel, then convert to Polars import pandas as pd df_pandas = pd.read_excel(file_path) return pl.from_pandas(df_pandas) def _load_json(self, file_path: Path) -> pl.DataFrame: """Load JSON file using Polars.""" try: # Try reading as NDJSON first (more efficient) return pl.read_ndjson(file_path) except Exception: # Fallback to regular JSON with open(file_path, 'r', encoding='utf-8') as f: data = json.load(f) # Handle different JSON structures if isinstance(data, list): return pl.DataFrame(data) elif isinstance(data, dict): # If it's a single object, wrap in list return pl.DataFrame([data]) else: raise ValueError("JSON must contain array of objects or single object") def _load_sql(self, file_path: Path) -> pl.DataFrame: """Load SQL file using DuckDB.""" if self.duckdb_conn is None: self.duckdb_conn = duckdb.connect() # Read SQL file content with open(file_path, 'r', encoding='utf-8') as f: sql_content = f.read() # Execute SQL and convert to Polars DataFrame result = self.duckdb_conn.execute(sql_content) return result.pl() def _load_parquet(self, file_path: Path) -> pl.DataFrame: """Load Parquet file using Polars.""" return pl.read_parquet(file_path) def load_from_bytes(self, file_bytes: bytes, file_format: FileFormat, filename: str = "data") -> pl.DataFrame: """Load data from bytes using hybrid approach (in-memory for some formats, temp files for others). Args: file_bytes: File content as bytes file_format: File format filename: Original filename (for context) Returns: Polars DataFrame with loaded data """ logger.info(f"Loading {file_format.value} data from bytes (original: {filename})") # Use in-memory processing for these formats (fast and secure) if file_format in [FileFormat.CSV, FileFormat.JSON, FileFormat.PARQUET]: return self._load_from_bytes_in_memory(file_bytes, file_format, filename) # Use temp file processing for these formats (more reliable) elif file_format in [FileFormat.EXCEL, FileFormat.SQL]: return self._load_from_bytes_temp_file(file_bytes, file_format, filename) else: raise ValueError(f"Unsupported file format: {file_format}") def _load_from_bytes_in_memory(self, file_bytes: bytes, file_format: FileFormat, filename: str) -> pl.DataFrame: """Load data from bytes completely in-memory (no temp files). Args: file_bytes: File content as bytes file_format: File format (CSV, JSON, or PARQUET) filename: Original filename (for context) Returns: Polars DataFrame with loaded data """ logger.info(f"Processing {file_format.value} in-memory (secure, fast)") try: if file_format == FileFormat.CSV: return self._load_csv_from_bytes_in_memory(file_bytes) elif file_format == FileFormat.JSON: return self._load_json_from_bytes_in_memory(file_bytes) elif file_format == FileFormat.PARQUET: return self._load_parquet_from_bytes_in_memory(file_bytes) else: raise ValueError(f"In-memory processing not supported for: {file_format}") except Exception as e: logger.error(f"Failed to load {file_format.value} from bytes in-memory: {e}") raise def _load_from_bytes_temp_file(self, file_bytes: bytes, file_format: FileFormat, filename: str) -> pl.DataFrame: """Load data from bytes using temporary file (for complex formats). Args: file_bytes: File content as bytes file_format: File format (EXCEL or SQL) filename: Original filename (for context) Returns: Polars DataFrame with loaded data """ logger.info(f"Processing {file_format.value} with temp file (reliable for complex formats)") # Create temporary file with tempfile.NamedTemporaryFile(delete=False, suffix=f".{file_format.value}") as temp_file: temp_file.write(file_bytes) temp_path = temp_file.name try: return self.load_file(temp_path, file_format) finally: # Clean up temporary file try: os.unlink(temp_path) logger.debug(f"Cleaned up temp file: {temp_path}") except OSError as e: logger.warning(f"Failed to clean up temp file {temp_path}: {e}") def _load_csv_from_bytes_in_memory(self, file_bytes: bytes) -> pl.DataFrame: """Load CSV from bytes using in-memory StringIO.""" # Convert bytes to string and create StringIO object csv_string = file_bytes.decode('utf-8') csv_io = StringIO(csv_string) return pl.read_csv( csv_io, infer_schema_length=10000, try_parse_dates=True, null_values=["", "NULL", "null", "None", "N/A", "n/a"] ) def _load_json_from_bytes_in_memory(self, file_bytes: bytes) -> pl.DataFrame: """Load JSON from bytes using in-memory processing.""" # Convert bytes to string json_string = file_bytes.decode('utf-8') # Parse JSON data directly (more reliable than NDJSON for regular JSON) data = json.loads(json_string) # Handle different JSON structures if isinstance(data, list): return pl.DataFrame(data) elif isinstance(data, dict): # If it's a single object, wrap in list return pl.DataFrame([data]) else: raise ValueError("JSON must contain array of objects or single object") def _load_parquet_from_bytes_in_memory(self, file_bytes: bytes) -> pl.DataFrame: """Load Parquet from bytes using in-memory BytesIO.""" parquet_io = BytesIO(file_bytes) return pl.read_parquet(parquet_io) def load_from_string(self, data_string: str, file_format: FileFormat) -> pl.DataFrame: """Load data from string completely in-memory. Args: data_string: Data content as string file_format: File format Returns: Polars DataFrame with loaded data """ logger.info(f"Loading {file_format.value} data from string - in-memory processing") try: if file_format == FileFormat.CSV: csv_io = StringIO(data_string) return pl.read_csv( csv_io, infer_schema_length=10000, try_parse_dates=True, null_values=["", "NULL", "null", "None", "N/A", "n/a"] ) elif file_format == FileFormat.JSON: data = json.loads(data_string) if isinstance(data, list): return pl.DataFrame(data) elif isinstance(data, dict): return pl.DataFrame([data]) else: raise ValueError("JSON must contain array of objects or single object") elif file_format == FileFormat.SQL: if self.duckdb_conn is None: self.duckdb_conn = duckdb.connect() result = self.duckdb_conn.execute(data_string) return result.pl() else: raise ValueError(f"String loading not supported for format: {file_format}") except Exception as e: logger.error(f"Failed to load {file_format.value} from string: {e}") raise def normalize_column_names(self, df: pl.DataFrame) -> pl.DataFrame: """Normalize column names for consistent processing. Args: df: Input DataFrame Returns: DataFrame with normalized column names """ # Convert to lowercase and replace spaces/special chars with underscores column_mapping = {} for col in df.columns: normalized = col.lower().strip() # Replace common separators with underscores normalized = normalized.replace(' ', '_').replace('-', '_').replace('.', '_') # Remove multiple underscores while '__' in normalized: normalized = normalized.replace('__', '_') # Remove leading/trailing underscores normalized = normalized.strip('_') column_mapping[col] = normalized return df.rename(column_mapping) def get_column_info(self, df: pl.DataFrame) -> Dict[str, Any]: """Get detailed information about DataFrame columns. Args: df: Input DataFrame Returns: Dictionary with column information """ return { "column_count": len(df.columns), "row_count": len(df), "columns": list(df.columns), "dtypes": {col: str(dtype) for col, dtype in zip(df.columns, df.dtypes)}, "null_counts": df.null_count().to_dict(), "sample_data": df.head(3).to_dict(as_series=False) if len(df) > 0 else {} } def to_dict(self, df: pl.DataFrame) -> list[dict]: """Convert DataFrame to list of dictionaries. Args: df: Input DataFrame Returns: List of dictionaries representing rows """ return df.to_dicts() def to_json_string(self, df: pl.DataFrame) -> str: """Convert DataFrame to JSON string in-memory. Args: df: Input DataFrame Returns: JSON string representation """ return df.write_json() def to_csv_string(self, df: pl.DataFrame) -> str: """Convert DataFrame to CSV string in-memory. Args: df: Input DataFrame Returns: CSV string representation """ # Use StringIO to capture CSV output csv_buffer = StringIO() df.write_csv(csv_buffer) csv_buffer.seek(0) return csv_buffer.getvalue() def to_parquet_bytes(self, df: pl.DataFrame) -> bytes: """Convert DataFrame to Parquet bytes in-memory. Args: df: Input DataFrame Returns: Parquet bytes representation """ parquet_buffer = BytesIO() df.write_parquet(parquet_buffer) parquet_buffer.seek(0) return parquet_buffer.getvalue() def to_bytes(self, df: pl.DataFrame, file_format: FileFormat) -> bytes: """Convert DataFrame to bytes in specified format - completely in-memory. Args: df: Input DataFrame file_format: Output format Returns: Bytes representation of the DataFrame """ if file_format == FileFormat.CSV: csv_string = self.to_csv_string(df) return csv_string.encode('utf-8') elif file_format == FileFormat.JSON: json_string = self.to_json_string(df) return json_string.encode('utf-8') elif file_format == FileFormat.PARQUET: return self.to_parquet_bytes(df) elif file_format == FileFormat.EXCEL: # For Excel, we need to use pandas and BytesIO import pandas as pd df_pandas = df.to_pandas() excel_buffer = BytesIO() df_pandas.to_excel(excel_buffer, index=False, engine='openpyxl') excel_buffer.seek(0) return excel_buffer.getvalue() else: raise ValueError(f"Bytes conversion not supported for format: {file_format}") def export_dataframe(self, df: pl.DataFrame, output_path: Union[str, Path], format: FileFormat = FileFormat.CSV) -> None: """Export DataFrame to file. Args: df: DataFrame to export output_path: Output file path format: Output format """ output_path = Path(output_path) logger.info(f"Exporting DataFrame to {format.value}: {output_path}") if format == FileFormat.CSV: df.write_csv(output_path) elif format == FileFormat.JSON: df.write_ndjson(output_path) elif format == FileFormat.PARQUET: df.write_parquet(output_path) elif format == FileFormat.EXCEL: # Convert to pandas for Excel export df_pandas = df.to_pandas() df_pandas.to_excel(output_path, index=False, engine='openpyxl') else: raise ValueError(f"Export format {format} not supported") def get_processing_method(self, file_format: FileFormat) -> str: """Get the processing method used for a file format. Args: file_format: File format to check Returns: Processing method: 'in-memory' or 'temp-file' """ if file_format in [FileFormat.CSV, FileFormat.JSON, FileFormat.PARQUET]: return 'in-memory' elif file_format in [FileFormat.EXCEL, FileFormat.SQL]: return 'temp-file' else: return 'unknown' def close(self): """Close DuckDB connection if open.""" if self.duckdb_conn: self.duckdb_conn.close() self.duckdb_conn = None def __enter__(self): """Context manager entry.""" return self def __exit__(self, exc_type, exc_val, exc_tb): """Context manager exit.""" self.close() class PerformanceDataProcessor(DataProcessor): """Enhanced data processor with performance optimizations and hybrid processing.""" def __init__(self, memory_limit: str = "1GB"): """Initialize with performance settings. Args: memory_limit: Memory limit for DuckDB operations """ super().__init__() self.memory_limit = memory_limit def _get_duckdb_connection(self) -> duckdb.DuckDBPyConnection: """Get optimized DuckDB connection.""" if self.duckdb_conn is None: self.duckdb_conn = duckdb.connect() # Set performance optimizations self.duckdb_conn.execute(f"SET memory_limit='{self.memory_limit}'") self.duckdb_conn.execute("SET threads TO -1") # Use all available cores return self.duckdb_conn def load_large_csv_from_bytes(self, file_bytes: bytes) -> pl.DataFrame: """Load large CSV from bytes efficiently using DuckDB - completely in-memory. Args: file_bytes: CSV file content as bytes Returns: Polars DataFrame """ conn = self._get_duckdb_connection() # Convert bytes to string and create a virtual table csv_string = file_bytes.decode('utf-8') csv_io = StringIO(csv_string) # Use DuckDB's optimized CSV reader with StringIO # Register the StringIO as a virtual file conn.register('csv_data', csv_io) result = conn.execute("SELECT * FROM read_csv_auto('csv_data')") return result.pl() def aggregate_data(self, df: pl.DataFrame, group_by: list[str], aggregations: Dict[str, str]) -> pl.DataFrame: """Perform high-performance aggregations - completely in-memory. Args: df: Input DataFrame group_by: Columns to group by aggregations: Dictionary of column -> aggregation function Returns: Aggregated DataFrame """ agg_expressions = [] for col, func in aggregations.items(): if func == "sum": agg_expressions.append(pl.col(col).sum().alias(f"{col}_sum")) elif func == "mean": agg_expressions.append(pl.col(col).mean().alias(f"{col}_mean")) elif func == "count": agg_expressions.append(pl.col(col).count().alias(f"{col}_count")) elif func == "max": agg_expressions.append(pl.col(col).max().alias(f"{col}_max")) elif func == "min": agg_expressions.append(pl.col(col).min().alias(f"{col}_min")) return df.group_by(group_by).agg(agg_expressions)