-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathzipPickle.py
executable file
·56 lines (47 loc) · 1.6 KB
/
zipPickle.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
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
zipPickle
From http://code.activestate.com/recipes/189972-zip-and-pickle/#c3
Created on Sun Oct 16 12:38:07 2016
@author: Zach Dwiel
"""
# Copyright (c) 2020 Yul HR Kang. hk2699 at caa dot columbia dot edu.
import pickle
import gzip
import zlib
def save(object, filename, protocol = -1):
"""Save an object to a compressed disk file.
Works well with huge objects.
"""
file = gzip.GzipFile(filename, 'wb')
try:
import torch
torch.save(object, file, pickle_protocol=protocol)
except RuntimeError:
print('Failed to save with torch.save(); trying pickle.dump()')
pickle.dump(object, file, protocol)
# torch.save(object, file, pickle_protocol=protocol)
file.close()
def load(filename, map_location='cpu', use_torch=True):
"""Loads a compressed object from disk
"""
if use_torch:
try:
import torch
try:
with gzip.GzipFile(filename, 'rb') as file:
object = torch.load(file, map_location=map_location)
except (EOFError, zlib.error):
from send2trash import send2trash
send2trash(filename)
print(f'Trashed the corrupted file: {filename}')
raise
except RuntimeError:
print('Failed to load with torch.load(); trying pickle.load()')
with gzip.GzipFile(filename, 'rb') as file:
object = pickle.load(file)
else:
with gzip.GzipFile(filename, 'rb') as file:
object = pickle.load(file)
return object