2012-08-18 19:07:10 -04:00
|
|
|
import struct
|
2012-08-25 19:46:07 -04:00
|
|
|
import cPickle
|
2012-08-10 04:10:02 -04:00
|
|
|
|
|
|
|
|
2012-12-26 20:34:24 -05:00
|
|
|
class Batch(object):
|
|
|
|
"""
|
|
|
|
Used to store multiple RDD entries as a single Java object.
|
|
|
|
|
|
|
|
This relieves us from having to explicitly track whether an RDD
|
|
|
|
is stored as batches of objects and avoids problems when processing
|
|
|
|
the union() of batched and unbatched RDDs (e.g. the union() of textFile()
|
|
|
|
with another RDD).
|
|
|
|
"""
|
|
|
|
def __init__(self, items):
|
|
|
|
self.items = items
|
|
|
|
|
|
|
|
|
|
|
|
def batched(iterator, batchSize):
|
2012-12-29 18:34:57 -05:00
|
|
|
if batchSize == -1: # unlimited batch size
|
|
|
|
yield Batch(list(iterator))
|
|
|
|
else:
|
|
|
|
items = []
|
|
|
|
count = 0
|
|
|
|
for item in iterator:
|
|
|
|
items.append(item)
|
|
|
|
count += 1
|
|
|
|
if count == batchSize:
|
|
|
|
yield Batch(items)
|
|
|
|
items = []
|
|
|
|
count = 0
|
|
|
|
if items:
|
2012-12-26 20:34:24 -05:00
|
|
|
yield Batch(items)
|
|
|
|
|
|
|
|
|
2012-08-25 19:46:07 -04:00
|
|
|
def dump_pickle(obj):
|
|
|
|
return cPickle.dumps(obj, 2)
|
2012-08-10 04:10:02 -04:00
|
|
|
|
|
|
|
|
2012-08-25 19:46:07 -04:00
|
|
|
load_pickle = cPickle.loads
|
2012-08-10 04:10:02 -04:00
|
|
|
|
|
|
|
|
2012-10-19 13:24:49 -04:00
|
|
|
def read_long(stream):
|
|
|
|
length = stream.read(8)
|
|
|
|
if length == "":
|
|
|
|
raise EOFError
|
|
|
|
return struct.unpack("!q", length)[0]
|
|
|
|
|
|
|
|
|
|
|
|
def read_int(stream):
|
|
|
|
length = stream.read(4)
|
|
|
|
if length == "":
|
|
|
|
raise EOFError
|
|
|
|
return struct.unpack("!i", length)[0]
|
|
|
|
|
2013-01-20 04:57:44 -05:00
|
|
|
|
|
|
|
def write_int(value, stream):
|
|
|
|
stream.write(struct.pack("!i", value))
|
|
|
|
|
|
|
|
|
2012-08-25 19:46:07 -04:00
|
|
|
def write_with_length(obj, stream):
|
2013-01-20 04:57:44 -05:00
|
|
|
write_int(len(obj), stream)
|
2012-08-18 19:07:10 -04:00
|
|
|
stream.write(obj)
|
2012-08-10 04:10:02 -04:00
|
|
|
|
|
|
|
|
2012-08-25 19:46:07 -04:00
|
|
|
def read_with_length(stream):
|
2012-10-19 13:24:49 -04:00
|
|
|
length = read_int(stream)
|
2012-08-18 19:07:10 -04:00
|
|
|
obj = stream.read(length)
|
|
|
|
if obj == "":
|
|
|
|
raise EOFError
|
|
|
|
return obj
|
2012-12-24 20:20:10 -05:00
|
|
|
|
|
|
|
|
|
|
|
def read_from_pickle_file(stream):
|
|
|
|
try:
|
|
|
|
while True:
|
2012-12-26 20:34:24 -05:00
|
|
|
obj = load_pickle(read_with_length(stream))
|
|
|
|
if type(obj) == Batch: # We don't care about inheritance
|
|
|
|
for item in obj.items:
|
|
|
|
yield item
|
|
|
|
else:
|
|
|
|
yield obj
|
2012-12-24 20:20:10 -05:00
|
|
|
except EOFError:
|
|
|
|
return
|