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 
 
 
2aeabe5
 
 
 
 
 
f12ad36
 
 
2aeabe5
 
f12ad36
 
2aeabe5
f12ad36
 
2aeabe5
f12ad36
2aeabe5
 
 
 
 
 
f12ad36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2aeabe5
f12ad36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2aeabe5
 
f12ad36
 
2aeabe5
f12ad36
 
 
 
 
 
2aeabe5
 
 
 
 
 
 
 
f12ad36
 
 
 
 
2aeabe5
f12ad36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
"""
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)