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
|
# (C) Copyright 2005-2023 Enthought, Inc., Austin, TX
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in LICENSE.txt and may be redistributed only under
# the conditions described in the aforementioned license. The license
# is also available online at http://www.enthought.com/licenses/BSD.txt
#
# Thanks for using Enthought open source!
import csv
from functools import partial
from io import BytesIO, StringIO
import os
import json
from pyface.data_view.i_data_wrapper import DataFormat, text_format
# Scalar formats
def to_json(data, default=None):
""" Serialize an object to a JSON bytestring.
Parameters
----------
data : Any
The data to be serialized.
default : Callable or None
Callable that takes a Python object and returns a JSON-serializable
data structure.
Returns
-------
raw_data : bytes
The serialized data as a bytestring.
"""
str_data = json.dumps(data, default=default, separators=(',', ':'))
return str_data.encode('utf-8')
def from_json(raw_data, object_hook=None):
""" Deserialize a JSON bytestring.
Parameters
----------
raw_data : bytes
The serialized JSON data as a byte string.
object_hook : Callable
Callable that takes a dictionary and returns an corresponding
Python object.
Returns
-------
data : Any
The data extracted.
"""
return json.loads(raw_data.decode('utf-8'), object_hook=object_hook)
#: The text/plain format with utf-8 encoding.
standard_text_format = text_format()
#: The text/html format with utf-8 encoding.
html_format = text_format(mimetype='text/html')
#: A generic JSON format.
json_format = DataFormat('application/json', to_json, from_json)
# 1D formats
def to_csv_row(data, delimiter=',', encoding='utf-8', **kwargs):
""" Serialize a list to a single-row CSV bytestring.
Parameters
----------
data : list
The list to be serialized. Any elements which are not strings will
be converted to strings by calling ``str()``.
delimiter : str
The CSV delimiter.
encoding : str
The encoding of the bytes
**kwargs
Additional arguments to csv.writer.
Returns
-------
raw_data : bytes
The serialized data as a bytestring.
"""
fp = StringIO()
writer = csv.writer(fp, delimiter=delimiter, **kwargs)
writer.writerow(data)
return fp.getvalue().encode(encoding)
def from_csv_row(raw_data, delimiter=',', encoding='utf-8', **kwargs):
""" Deserialize the first row of a CSV bytestring as a list.
Any rows beyond the first are ignored.
Parameters
----------
raw_data : bytes
The serialized CSV data as a byte string.
delimiter : str
The CSV delimiter.
encoding : str
The encoding of the bytes
**kwargs
Additional arguments to csv.reader.
Returns
-------
data : list of str
The data extracted as a list of strings.
"""
fp = StringIO(raw_data.decode(encoding))
reader = csv.reader(fp, delimiter=delimiter, **kwargs)
return next(reader)
def to_csv_column(data, delimiter=',', encoding='utf-8', **kwargs):
""" Serialize a list to a single-column CSV bytestring.
Parameters
----------
data : list
The list to be serialized. Any elements which are not strings will
be converted to strings by calling ``str()``.
delimiter : str
The CSV delimiter.
encoding : str
The encoding of the bytes
**kwargs
Additional arguments to csv.writer.
Returns
-------
raw_data : bytes
The serialized data as a bytestring.
"""
fp = StringIO()
writer = csv.writer(fp, delimiter=delimiter, **kwargs)
for row in data:
writer.writerow([row])
return fp.getvalue().encode(encoding)
def from_csv_column(raw_data, delimiter=',', encoding='utf-8', **kwargs):
""" Deserialize the first column of a CSV bytestring as a list.
Any columns beyond the first are ignored.
Parameters
----------
raw_data : bytes
The serialized CSV data as a byte string.
delimiter : str
The CSV delimiter.
encoding : str
The encoding of the bytes
**kwargs
Additional arguments to csv.reader.
Returns
-------
data : list of str
The data extracted as a list of strings.
"""
fp = StringIO(raw_data.decode(encoding))
reader = csv.reader(fp, delimiter=delimiter, **kwargs)
return [row[0] for row in reader]
text_row_format = DataFormat(
'text/plain',
partial(to_csv_row, delimiter='\t', lineterminator=os.linesep),
partial(from_csv_row, delimiter='\t'),
)
csv_row_format = DataFormat('text/csv', to_csv_row, from_csv_row)
text_column_format = DataFormat(
'text/plain',
partial(to_csv_column, delimiter='\t', lineterminator=os.linesep),
partial(from_csv_column, delimiter='\t'),
)
csv_column_format = DataFormat('text/csv', to_csv_column, from_csv_column)
# 2D formats
def to_csv(data, delimiter=',', encoding='utf-8', **kwargs):
""" Serialize a list of lists to a CSV bytestring.
Parameters
----------
data : list of lists
The data to be serialized. Any elements which are not strings will
be converted to strings by calling ``str()``.
delimiter : str
The CSV delimiter.
encoding : str
The encoding of the bytes
**kwargs
Additional arguments to csv.writer.
Returns
-------
raw_data : bytes
The serialized data as a bytestring.
"""
fp = StringIO()
writer = csv.writer(fp, delimiter=delimiter, **kwargs)
for row in data:
writer.writerow(row)
return fp.getvalue().encode(encoding)
def from_csv(raw_data, delimiter=',', encoding='utf-8', **kwargs):
""" Deserialize a CSV bytestring.
Parameters
----------
raw_data : bytes
The serialized CSV data as a byte string.
delimiter : str
The CSV delimiter.
encoding : str
The encoding of the bytes
**kwargs
Additional arguments to csv.reader.
Returns
-------
data : list of list of str
The data extracted as a list of lists of strings.
"""
fp = StringIO(raw_data.decode(encoding))
reader = csv.reader(fp, delimiter=delimiter, **kwargs)
return list(reader)
def to_npy(data):
""" Serialize an array to a bytestring using .npy format.
Parameters
----------
data : array-like
The array to be serialized.
Returns
-------
raw_data : bytes
The serialized data as a bytestring.
"""
import numpy as np
data = np.atleast_2d(data)
fp = BytesIO()
np.save(fp, data, allow_pickle=False)
return fp.getvalue()
def from_npy(raw_data):
""" Deserialize a .npy-format bytestring.
Parameters
----------
raw_data : bytes
The serialized CSV data as a byte string.
Returns
-------
data : list of list of str
The data extracted as a list of lists of strings.
"""
import numpy as np
fp = BytesIO(raw_data)
return np.load(fp, allow_pickle=False)
table_format = DataFormat(
'text/plain',
partial(to_csv, delimiter='\t', lineterminator=os.linesep),
partial(from_csv, delimiter='\t'),
)
csv_format = DataFormat('text/csv', to_csv, from_csv)
npy_format = DataFormat('application/x-npy', to_npy, from_npy)
|