-
Notifications
You must be signed in to change notification settings - Fork 3
/
jsonl.py
386 lines (214 loc) · 7.14 KB
/
jsonl.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
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
"""
Source from:
https://github.com/lil-lab/newsroom/blob/master/newsroom/build/jsonl.py
Copyrights are Max Grusky under Apache License, Version 2.0
Used for reading the newsroom data extract, which is in the form
of gzip-compressed JSON lines. The newsroom repository comes with
a fast library for reading the resulting lines.
"""
import bz2 as _bz2
import gzip as _gzip
import lzma as _lzma
import os as _os
import shlex as _shlex
import shutil as _shutil
import ujson as _json
_open = open
_has = {
"zcat": not not _shutil.which("zcat"),
"bzcat": not not _shutil.which("bzcat"),
"xzcat": not not _shutil.which("xzcat"),
}
class open(object):
"""
Simple tool for manipulating compressed JSON line data files.
Supports gzip, bzip2, xz/lzma and uncompressed JSON line input.
Can be used as a standard object, or in a "with" context.
Uses faster system tools for expanding files when available.
This results in approximately:
- 30x read speed increase for lzma
- 20x read speed increase for gzip
- 5x read speed increase for bzip2
Arguments:
path (str) - path of JSON lines file
Keywords:
fast (bool) - read with zcat, bzcat, or xzcat (default = True)
gzip (bool) - encode and decode with gzip (default = False)
bzip (bool) - encode and decode with bzip2 (default = False)
xz (bool) - encode and decode with xz/lzma (default = False)
level (int) - compression level for gzip and bzip2 (default = 9)
"""
def __init__(self, path, fast=True, gzip=False, bzip=False, xz=False, level=9):
self.path = path
self.fast = fast
self.use_gzip = gzip
self.use_bzip = bzip
self.use_xz = xz
self.level = level
self.is_read = None
self.file = None
# Allow only one compressor.
assert sum([gzip, bzip, xz]) <= 1
# Fast only if system supports it.
self.fast &= (
(gzip and _has["zcat"])
or (bzip and _has["bzcat"])
or (xz and _has["xzcat"])
)
def _readfile(self):
if not self.is_read:
self.close()
self.is_read = True
if self.use_gzip:
if self.fast:
quoted = _shlex.quote(self.path)
self.file = _os.popen("zcat < " + quoted)
else:
self.file = _gzip.open(self.path, mode="rt", compresslevel=self.level)
elif self.use_bzip:
if self.fast:
quoted = _shlex.quote(self.path)
self.file = _os.popen("bzcat < " + quoted)
else:
self.file = _bz2.open(self.path, mode="rt", compresslevel=self.level)
elif self.use_xz:
if self.fast:
quoted = _shlex.quote(self.path)
self.file = _os.popen("xzcat < " + quoted)
else:
self.file = _lzma.open(self.path, mode="rt")
else:
self.file = _open(self.path, "r")
return self.file
def _writefile(self):
if self.is_read is True:
self.close()
self.is_read = False
if self.use_gzip:
self.file = _gzip.open(self.path, mode="at", compresslevel=self.level)
elif self.use_bzip:
self.file = _bz2.open(self.path, mode="at", compresslevel=self.level)
elif self.use_xz:
self.file = _lzma.open(self.path, mode="at")
else:
self.file = _open(self.path, "a+")
return self.file
def __del__(self):
# Close file on cleanup.
self.close()
def __enter__(self):
# Called when entering "with" context.
return self
def __exit__(self, *_):
# Called when exiting "with" context.
self.close()
def __iter__(self):
# Return the readlines generator.
return self.readlines()
def close(self):
"""
Close the file.
"""
if self.file:
self.file.close()
def delete(self):
"""
Delete the file contents on disk.
"""
if self.is_read is True:
self.close()
self.is_read = False
if self.use_gzip:
self.file = _gzip.open(self.path, mode="wt", compresslevel=self.level)
elif self.use_bzip:
self.file = _bz2.open(self.path, mode="wt", compresslevel=self.level)
elif self.use_bzip:
self.file = _lzma.open(self.path, mode="wt")
else:
self.file = _open(self.path, "w")
self.file.close()
self.is_read = None
def readlines(self, ignore_errors=False):
"""
Read a sequence of lines (as a generator).
Yields:
individual JSON-decoded entries
"""
if not ignore_errors:
for line in self._readfile():
yield _json.loads(line)
else:
for ln, line in enumerate(self._readfile()):
try:
yield _json.loads(line)
except:
print("Decoding error on line", ln)
continue
def read(self):
"""
Read the entire file into memory.
Returns:
list of JSON-decoded entries
"""
return list(self.readlines())
def appendline(self, entry):
"""
Write a single line to the file.
Arguments:
entry (object) - JSON-encodable object
"""
f = self._writefile()
f.write(_json.dumps(entry) + "\n")
def append(self, entries):
"""
Append an entire list of lines to an existing file.
Arguments:
entry (iterable[object]) - iterable of JSON-encodable objects
"""
for entry in entries:
self.appendline(entry)
def write(self, entries):
"""
Write list of lines to file, overwriting the original data.
Arguments:
entry (iterable[object]) - iterable of JSON-encodable objects
"""
self.delete()
self.append(entries)
# Convenience functions.
def read(*args, **kwargs):
"""
Read a full uncompressed JSON lines file into memory.
"""
kwargs["bzip"] = False
kwargs["gzip"] = False
kwargs["xz"] = False
with open(*args, **kwargs) as f:
return f.read()
def bzread(*args, **kwargs):
"""
Read a full bzip2-compressed JSON lines file into memory.
"""
kwargs["bzip"] = True
kwargs["gzip"] = False
kwargs["xz"] = False
with open(*args, **kwargs) as f:
return f.read()
def gzread(*args, **kwargs):
"""
Read a full gzip-compressed JSON lines file into memory.
"""
kwargs["bzip"] = False
kwargs["gzip"] = True
kwargs["xz"] = False
with open(*args, **kwargs) as f:
return f.read()
def xzread(*args, **kwargs):
"""
Read a full xz/lzma-compressed JSON lines file into memory.
"""
kwargs["bzip"] = False
kwargs["gzip"] = False
kwargs["xz"] = True
with open(*args, **kwargs) as f:
return f.read()