-
Notifications
You must be signed in to change notification settings - Fork 1
/
tfrecord_utils.py
77 lines (67 loc) · 2.02 KB
/
tfrecord_utils.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
# -*- coding: utf-8 -*-
"""
TFRecord utils file.
======================
Collection of useful functions for TFRecords generation.
"""
from utils import *
import tensorflow as tf
class RotatingRecord(object):
"""
Class to write TFRecord files that don't exceed a certain size to make trainings more efficient.
See https://www.tensorflow.org/guide/performance/overview
"""
def __init__(self, directory, last, purpose, max_file_size):
"""
Initializes file rotation.
:param directory: file path.
:param last: last file ID.
:param purpose: record type.
:param max_file_size: maximum allowed file size (bytes).
"""
self.directory = directory
self.purpose = purpose
self.max_file_size = max_file_size
self.ii = int(last) + 1
self.writer = None
self.open()
def rotate(self):
"""
Checks if current file reached the maximum size and opens a new one if necessary.
:return: void.
"""
# File might be not on disk yet.
try:
if os.stat(self.filename_template).st_size > self.max_file_size:
self.close()
self.ii += 1
self.open()
except:
pass
def open(self):
"""
Creates new empty file.
:return: void.
"""
self.writer = tf.python_io.TFRecordWriter(self.filename_template)
def write(self, record):
"""
Appends content in current file.
:param record: TFRecord entry.
:return: void.
"""
self.rotate()
self.writer.write(record.SerializeToString())
def close(self):
"""
Freezes current file.
:return: void.
"""
self.writer.close()
@property
def filename_template(self):
"""
Returns current file name.
:return: filename as string.
"""
return os.path.join(self.directory, TFRECORD_CONFIG[self.purpose].format(id=self.ii))