/
datasets.py
279 lines (217 loc) · 8.36 KB
/
datasets.py
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
import os
from contextlib import contextmanager, ExitStack
from csv import DictReader
from pathlib import Path
from random import shuffle
from typing import Any, Optional
from sqlalchemy import MetaData, create_engine
from sqlalchemy.sql.elements import quoted_name
from sqlalchemy.sql.expression import func, select
from yaml.representer import Representer
from snowfakery.data_gen_exceptions import DataGenError, DataGenNameError
from snowfakery.plugins import (
PluginResult,
PluginResultIterator,
SnowfakeryPlugin,
memorable,
)
from snowfakery.utils.files import FileLike, open_file_like
from snowfakery.utils.yaml_utils import SnowfakeryDumper
def _open_db(db_url):
"Internal function for opening the database up."
engine = create_engine(db_url)
metadata = MetaData()
metadata.reflect(views=True, bind=engine)
return engine, metadata
def sql_dataset(
db_url: str, tablename: Optional[str] = None, mode="linear", repeat: bool = True
):
"Open the right SQL Dataset iterator based on the params"
assert db_url
engine, metadata = _open_db(db_url)
tables = {
name: value
for name, value in metadata.tables.items()
if not name.startswith("sqlite")
}
table = None
if tablename:
table = tables.get(tablename)
if table is None:
raise AttributeError(f"Cannot find table: {tablename}")
elif len(tables) == 0:
raise Exception("Database does not exist or has no tables in it")
elif len(tables) == 1:
table = next(iter(tables.values()))
elif len(tables) > 1:
raise Exception(
f"Database has multiple tables in it and none was selected: {metadata.tables.keys()}"
)
if mode == "linear":
return SQLDatasetLinearIterator(engine, table, repeat)
elif mode == "shuffle":
return SQLDatasetRandomPermutationIterator(engine, table, repeat)
raise AssertionError(f"Unknown mode: {mode}")
class DatasetIteratorBase(PluginResultIterator):
"""Base class for Dataset Iterators
Subclasses should implement 'self.restart' which puts an iterator into 'self.results'
"""
def __init__(self, repeat):
# subclasses can register stuff to be cleaned up here.
self.cleanup = ExitStack()
super().__init__(repeat)
def next_result(self):
return next(self.results)
def close(self):
self.cleanup.close()
class SQLDatasetIterator(DatasetIteratorBase):
def __init__(self, engine, table, repeat):
self.connection = engine.connect()
self.table = table
super().__init__(repeat)
self.start()
def start(self):
self.results = (
DatasetPluginResult(dict(row._mapping))
for row in self.connection.execute(self.query())
)
def close(self):
self.results = None
self.connection.close()
super().close()
def query(self):
"Return a SQL Alchemy SELECT statement"
raise NotImplementedError(f"query method on {self.__class__.__name__}")
class SQLDatasetLinearIterator(SQLDatasetIterator):
"Iterator that reads a SQL table from top to bottom"
def query(self):
return select(self.table)
class SQLDatasetRandomPermutationIterator(SQLDatasetIterator):
"Iterator that reads a SQL table in random order"
def query(self):
return select(self.table).order_by(func.random())
class CSVDatasetLinearIterator(DatasetIteratorBase):
def __init__(self, datasource: FileLike, repeat: bool):
super().__init__(repeat)
# utf-8-sig and newline="" are for Windows
self.path, self.file = self.cleanup.enter_context(
open_file_like(datasource, "r", newline="", encoding="utf-8-sig")
)
self.start()
def start(self):
assert self.file
self.file.seek(0)
d = DictReader(self.file) # type: ignore
plugin_result = self.plugin_result
self.results = (plugin_result(row) for row in d)
def close(self):
self.results = None
super().close()
def plugin_result(self, row):
if None in row:
raise DataGenError(
f"Your CSV row has more columns than the CSV header: {row[None]}, {self.path} {self.file}"
)
return DatasetPluginResult(row)
class DatasetPluginResult(PluginResult):
def __getattr__(self, name):
try:
return super().__getattr__(name)
except KeyError:
raise DataGenNameError(
f"`{name}` attribute not found. Should be one of {tuple(self.result.keys())}"
)
class CSVDatasetRandomPermutationIterator(CSVDatasetLinearIterator):
# This algorithm shuffles a million records without a problem on my laptop.
# If you needed to scale it up to 40 or 50 times the scale, you could do
# this instead:
# * don't read the whole file into memory. Just figure out where the line
# breaks are and shuffle the address of THOSE. Then seek to lines
# during parsing
#
# To scale even further:
#
# * load the rows or indexes into a SQLite DB. Ask SQlite to generate
# another table that randomizes the rows. (haven't decided whether
# copying the rows up-front is better)
#
# * segment the file into hundred-thousand-row partitions. Shuffle the
# rows in each partition and then pick randomly among the partitions
# before grabbing a row
def start(self):
assert self.file
self.file.seek(0)
d = DictReader(self.file) # type: ignore
rows = [DatasetPluginResult(row) for row in d]
shuffle(rows)
self.results = iter(rows)
def close(self):
self.results = None
class DatasetBase:
def __init__(self, *args, **kwargs):
self.datasets = {}
def _get_dataset_instance(self, plugin_context, iteration_mode, kwargs):
filename = plugin_context.field_vars()["template"].filename
assert filename
rootpath = Path(filename).parent
dataset_instance = self._load_dataset(iteration_mode, rootpath, kwargs)
return dataset_instance
def _load_dataset(self, iteration_mode, rootpath, kwargs):
raise NotImplementedError("_load_dataset not implemented")
def close(self):
raise NotImplementedError("close not implemented: " + repr(self))
class FileDataset(DatasetBase):
def close(self):
pass
def _load_dataset(self, iteration_mode, rootpath, kwargs):
dataset = kwargs.get("dataset")
tablename = kwargs.get("table")
repeat = kwargs.get("repeat", True)
with chdir(rootpath):
if "://" in dataset:
return sql_dataset(dataset, tablename, iteration_mode, repeat)
else:
filename = Path(dataset)
if not filename.exists():
raise FileNotFoundError("File not found:" + str(filename))
if filename.suffix != ".csv":
raise AssertionError(
f"Filename extension must be .csv, not {filename.suffix}"
)
if iteration_mode == "linear":
return CSVDatasetLinearIterator(filename, repeat)
elif iteration_mode == "shuffle":
return CSVDatasetRandomPermutationIterator(filename, repeat)
class DatasetPluginBase(SnowfakeryPlugin):
class Functions:
context: Any
@memorable
def iterate(self, **kwargs):
return self.context.plugin.dataset_impl._get_dataset_instance(
self.context, "linear", kwargs
)
@memorable
def shuffle(self, **kwargs):
return self.context.plugin.dataset_impl._get_dataset_instance(
self.context, "shuffle", kwargs
)
def close(self):
if self.dataset_impl:
self.dataset_impl.close()
self.dataset_impl = None
class Dataset(DatasetPluginBase):
def __init__(self, *args, **kwargs):
self.dataset_impl = FileDataset()
super().__init__(*args, **kwargs)
@contextmanager
def chdir(path):
"""Context manager that changes to another directory
Not thread-safe!!!
"""
cwd = os.getcwd()
os.chdir(path)
try:
yield
finally:
os.chdir(cwd)
SnowfakeryDumper.add_representer(quoted_name, Representer.represent_str) # type: ignore