File size: 1,592 Bytes
7477da2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""CSV File Handler Plugin"""
import pandas as pd
from typing import Dict, Any
from pathlib import Path

class CSVHandler:
    """Handle CSV files with auto-detection."""
    def __init__(self):
        self.supported_extensions = ['.csv', '.tsv', '.txt']
    
    def can_handle(self, filename: str) -> bool:
        return Path(filename).suffix.lower() in self.supported_extensions
    
    def load(self, file_path: str) -> Dict[str, Any]:
        delimiter = ','
        try:
            for d in [',', '\t', ';', '|']:
                try:
                    df = pd.read_csv(file_path, delimiter=d, nrows=5)
                    if len(df.columns) > 1:
                        delimiter = d
                        df = pd.read_csv(file_path, delimiter=delimiter)
                        break
                except: continue
            metadata = {"total_rows": len(df), "delimiter": delimiter}
            return {"success": True, "data": df, "metadata": metadata, "file_type": "csv"}
        except Exception as e:
            return {"success": False, "error": f"Failed to load CSV: {str(e)}", "file_type": "csv"}
    
    def preview(self, data: Dict[str, Any], max_rows: int = 5) -> str:
        if not data.get("success"): 
            return f"<p class='text-red-500'>Error: {data.get('error')}</p>"
        html = f"<h4>📄 CSV File</h4><p><strong>Rows:</strong> {data['metadata']['total_rows']:,}</p>"
        df = data["data"]
        html += df.head(max_rows).to_html(index=False, classes="preview-table border w-full text-xs")
        return html