Spaces:
Running on Zero
Running on Zero
File size: 6,110 Bytes
a067ada | 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 | """
Load various data formats and convert to SQLite databases.
Supports CSV, Excel, JSON file formats and converts them
into in-memory SQLite databases for SQL querying.
"""
import sqlite3
import logging
from typing import Dict, Any, Optional
from pathlib import Path
import json
logger = logging.getLogger(__name__)
class DataLoader:
"""Load data from various formats into SQLite database."""
def __init__(self) -> None:
"""Initialize data loader."""
pass
def load_csv(
self,
file_path: str | Path,
table_name: Optional[str] = None,
in_memory: bool = True,
) -> str:
"""
Load CSV file into SQLite database.
Args:
file_path: Path to CSV file
table_name: Name for the table (default: filename without extension)
in_memory: Whether to use in-memory database
Returns:
Path to database file (or ':memory:' for in-memory)
"""
try:
import pandas as pd
file_path = Path(file_path)
if not file_path.exists():
raise FileNotFoundError(f"CSV file not found: {file_path}")
logger.info(f"Loading CSV: {file_path}")
df = pd.read_csv(file_path)
table_name = table_name or file_path.stem
db_path = self._create_database(df, table_name, in_memory)
logger.info(f"CSV loaded to {db_path}, table: {table_name}")
return db_path
except ImportError:
logger.error("pandas not installed. Install with: pip install pandas")
raise
except Exception as e:
logger.error(f"Error loading CSV: {e}")
raise
def load_excel(
self,
file_path: str | Path,
sheet_name: str = 0,
table_name: Optional[str] = None,
in_memory: bool = True,
) -> str:
"""
Load Excel file into SQLite database.
Args:
file_path: Path to Excel file
sheet_name: Sheet to load
table_name: Name for the table
in_memory: Whether to use in-memory database
Returns:
Path to database file
"""
try:
import pandas as pd
file_path = Path(file_path)
if not file_path.exists():
raise FileNotFoundError(f"Excel file not found: {file_path}")
logger.info(f"Loading Excel: {file_path}, sheet: {sheet_name}")
df = pd.read_excel(file_path, sheet_name=sheet_name)
table_name = table_name or f"table_{sheet_name}"
db_path = self._create_database(df, table_name, in_memory)
logger.info(f"Excel loaded to {db_path}, table: {table_name}")
return db_path
except ImportError:
logger.error("openpyxl/pandas not installed")
raise
except Exception as e:
logger.error(f"Error loading Excel: {e}")
raise
def load_json(
self,
file_path: str | Path,
table_name: Optional[str] = None,
in_memory: bool = True,
) -> str:
"""
Load JSON file into SQLite database.
Args:
file_path: Path to JSON file
table_name: Name for the table
in_memory: Whether to use in-memory database
Returns:
Path to database file
"""
try:
import pandas as pd
file_path = Path(file_path)
if not file_path.exists():
raise FileNotFoundError(f"JSON file not found: {file_path}")
logger.info(f"Loading JSON: {file_path}")
with open(file_path) as f:
data = json.load(f)
# Handle both list of records and single record
if isinstance(data, dict):
data = [data]
df = pd.DataFrame(data)
table_name = table_name or file_path.stem
db_path = self._create_database(df, table_name, in_memory)
logger.info(f"JSON loaded to {db_path}, table: {table_name}")
return db_path
except ImportError:
logger.error("pandas not installed")
raise
except Exception as e:
logger.error(f"Error loading JSON: {e}")
raise
def _create_database(
self,
df,
table_name: str,
in_memory: bool = True,
) -> str:
"""
Create SQLite database from DataFrame.
Args:
df: Pandas DataFrame
table_name: Name for the table
in_memory: Whether to use in-memory database
Returns:
Path to database
"""
db_path = ":memory:" if in_memory else f"{table_name}.db"
try:
conn = sqlite3.connect(db_path)
df.to_sql(table_name, conn, if_exists="replace", index=False)
conn.commit()
conn.close()
logger.info(f"Created database with table: {table_name}")
return db_path
except Exception as e:
logger.error(f"Error creating database: {e}")
raise
def load_dict_list(
self,
data: list[Dict[str, Any]],
table_name: str = "data",
in_memory: bool = True,
) -> str:
"""
Load list of dictionaries into SQLite database.
Args:
data: List of dictionaries
table_name: Name for the table
in_memory: Whether to use in-memory database
Returns:
Path to database
"""
try:
import pandas as pd
if not data:
raise ValueError("Data list is empty")
logger.info(f"Loading {len(data)} records into table: {table_name}")
df = pd.DataFrame(data)
db_path = self._create_database(df, table_name, in_memory)
return db_path
except Exception as e:
logger.error(f"Error loading data: {e}")
raise
|