forked from sjwhitworth/golearn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserialize.go
426 lines (360 loc) · 11.5 KB
/
serialize.go
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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
package base
import (
"archive/tar"
"compress/gzip"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"reflect"
)
const (
SerializationFormatVersion = "golearn 1.0"
)
// FunctionalTarReader allows you to read anything in a tar file in any order, rather than just
// sequentially.
type FunctionalTarReader struct {
Regenerate func() *tar.Reader
}
// NewFunctionalTarReader creates a new FunctionalTarReader using a function that it can call
// to get a tar.Reader at the beginning of the file.
func NewFunctionalTarReader(regenFunc func() *tar.Reader) *FunctionalTarReader {
return &FunctionalTarReader{
regenFunc,
}
}
// GetNamedFile returns a file named a given thing from the tar file. If there's more than one
// entry, the most recent is returned.
func (f *FunctionalTarReader) GetNamedFile(name string) ([]byte, error) {
tr := f.Regenerate()
var returnCandidate []byte = nil
for {
hdr, err := tr.Next()
if err == io.EOF {
break
} else if err != nil {
return nil, err
}
if hdr.Name == name {
ret, err := ioutil.ReadAll(tr)
if err != nil {
return nil, WrapError(err)
}
if int64(len(ret)) != hdr.Size {
if int64(len(ret)) < hdr.Size {
log.Printf("Size mismatch, got %d byte(s) for %s, expected %d (err was %s)", len(ret), hdr.Name, hdr.Size, err)
} else {
return nil, WrapError(fmt.Errorf("Size mismatch, expected %d byte(s) for %s, got %d", len(ret), hdr.Name, hdr.Size))
}
}
if err != nil {
return nil, err
}
returnCandidate = ret
}
}
if returnCandidate == nil {
return nil, WrapError(fmt.Errorf("Not found (looking for %s)", name))
}
return returnCandidate, nil
}
func tarPrefix(prefix string, suffix string) string {
if prefix == "" {
return suffix
}
return fmt.Sprintf("%s/%s", prefix, suffix)
}
// ClassifierMetadataV1 is what gets written into METADATA
// in a classification file format.
type ClassifierMetadataV1 struct {
// FormatVersion should always be 1 for this structure
FormatVersion int `json:"format_version"`
// Uses the classifier name (provided by the classifier)
ClassifierName string `json:"classifier"`
// ClassifierVersion is also provided by the classifier
// and checks whether this version of GoLearn can read what's
// be written.
ClassifierVersion string `json"classifier_version"`
// This is a custom metadata field, provided by the classifier
ClassifierMetadata map[string]interface{} `json:"classifier_metadata"`
}
// ClassifierDeserializer attaches helper functions useful for reading classificatiers. (UNSTABLE).
type ClassifierDeserializer struct {
gzipReader io.Reader
fileReader io.ReadCloser
tarReader *FunctionalTarReader
Metadata *ClassifierMetadataV1
}
// Prefix outputs a string in the right format for TAR
func (c *ClassifierDeserializer) Prefix(prefix string, suffix string) string {
if prefix == "" {
return suffix
}
return fmt.Sprintf("%s/%s", prefix, suffix)
}
// ReadMetadataAtPrefix reads the METADATA file after prefix. If an error is returned, the first value is undefined.
func (c *ClassifierDeserializer) ReadMetadataAtPrefix(prefix string) (ClassifierMetadataV1, error) {
var ret ClassifierMetadataV1
err := c.GetJSONForKey(c.Prefix(prefix, "METADATA"), &ret)
return ret, err
}
// ReadSerializedClassifierStub is the counterpart of CreateSerializedClassifierStub.
// It's used inside SaveableClassifiers to read information from a perviously saved
// model file.
func ReadSerializedClassifierStub(filePath string) (*ClassifierDeserializer, error) {
f, err := os.Open(filePath)
if err != nil {
return nil, DescribeError("Can't open file", err)
}
gzr, err := gzip.NewReader(f)
if err != nil {
return nil, DescribeError("Can't decompress", err)
}
regenerateFunc := func() *tar.Reader {
f.Seek(0, os.SEEK_SET)
gzr.Reset(f)
tz := tar.NewReader(gzr)
return tz
}
tz := NewFunctionalTarReader(regenerateFunc)
// Check that the serialization format is right
// Retrieve the MANIFEST and verify
manifestBytes, err := tz.GetNamedFile("CLS_MANIFEST")
if err != nil {
return nil, DescribeError("Error reading CLS_MANIFEST", err)
}
if !reflect.DeepEqual(manifestBytes, []byte(SerializationFormatVersion)) {
return nil, fmt.Errorf("Unsupported CLS_MANIFEST: %s", string(manifestBytes))
}
//
// Parse METADATA
//
var metadata ClassifierMetadataV1
ret := &ClassifierDeserializer{
f,
gzr,
tz,
&metadata,
}
metadata, err = ret.ReadMetadataAtPrefix("")
if err != nil {
return nil, fmt.Errorf("Error whilst reading METADATA: %s", err)
}
ret.Metadata = &metadata
// Check that we can understand this archive
if metadata.FormatVersion != 1 {
return nil, fmt.Errorf("METADATA: wrong format_version for this version of golearn")
}
return ret, nil
}
// GetBytesForKey returns the bytes at a given location in the output.
func (c *ClassifierDeserializer) GetBytesForKey(key string) ([]byte, error) {
return c.tarReader.GetNamedFile(key)
}
func (c *ClassifierDeserializer) GetStringForKey(key string) (string, error) {
b, err := c.GetBytesForKey(key)
if err != nil {
return "", err
}
return string(b), err
}
// GetJSONForKey deserializes a JSON key in the output file.
func (c *ClassifierDeserializer) GetJSONForKey(key string, v interface{}) error {
b, err := c.GetBytesForKey(key)
if err != nil {
return err
}
return json.Unmarshal(b, v)
}
// GetInstancesForKey deserializes some instances stored in a classifier output file
func (c *ClassifierDeserializer) GetInstancesForKey(key string) (FixedDataGrid, error) {
return DeserializeInstancesFromTarReader(c.tarReader, key)
}
// GetUInt64ForKey returns a int64 stored at a given key
func (c *ClassifierDeserializer) GetU64ForKey(key string) (uint64, error) {
b, err := c.GetBytesForKey(key)
if err != nil {
return 0, err
}
return UnpackBytesToU64(b), nil
}
// GetAttributeForKey returns an Attribute stored at a given key
func (c *ClassifierDeserializer) GetAttributeForKey(key string) (Attribute, error) {
b, err := c.GetBytesForKey(key)
if err != nil {
return nil, WrapError(err)
}
attr, err := DeserializeAttribute(b)
if err != nil {
return nil, WrapError(err)
}
return attr, nil
}
// GetAttributesForKey returns an Attribute list stored at a given key
func (c *ClassifierDeserializer) GetAttributesForKey(key string) ([]Attribute, error) {
attrCountKey := c.Prefix(key, "ATTR_COUNT")
attrCount, err := c.GetU64ForKey(attrCountKey)
if err != nil {
return nil, DescribeError("Unable to read ATTR_COUNT", err)
}
ret := make([]Attribute, attrCount)
for i := range ret {
attrKey := c.Prefix(key, fmt.Sprintf("%d", i))
ret[i], err = c.GetAttributeForKey(attrKey)
if err != nil {
return nil, DescribeError("Unable to read Attribute", err)
}
}
return ret, nil
}
// Close cleans up everything.
func (c *ClassifierDeserializer) Close() {
c.fileReader.Close()
}
// ClassifierSerializer is an object used by SaveableClassifiers.
type ClassifierSerializer struct {
gzipWriter *gzip.Writer
fileWriter *os.File
tarWriter *tar.Writer
f *os.File
filePath string
}
// Close finalizes the Classifier serialization session.
func (c *ClassifierSerializer) Close() error {
// Finally, close and flush the various levels
if err := c.tarWriter.Flush(); err != nil {
return fmt.Errorf("Could not flush tar: %s", err)
}
if err := c.tarWriter.Close(); err != nil {
return fmt.Errorf("Could not close tar: %s", err)
}
if err := c.gzipWriter.Flush(); err != nil {
return fmt.Errorf("Could not flush gz: %s", err)
}
if err := c.gzipWriter.Close(); err != nil {
return fmt.Errorf("Could not close gz: %s", err)
}
if err := c.fileWriter.Sync(); err != nil {
return fmt.Errorf("Could not close file writer: %s", err)
}
if err := c.fileWriter.Close(); err != nil {
return fmt.Errorf("Could not close file writer: %s", err)
}
return nil
}
// WriteBytesForKey creates a new entry in the serializer file with some user-defined bytes.
func (c *ClassifierSerializer) WriteBytesForKey(key string, b []byte) error {
//
// Write header for key
//
hdr := &tar.Header{
Name: key,
Size: int64(len(b)),
}
if err := c.tarWriter.WriteHeader(hdr); err != nil {
return fmt.Errorf("Could not write header for '%s': %s", key, err)
}
//
// Write data
//
if _, err := c.tarWriter.Write(b); err != nil {
return fmt.Errorf("Could not write data for '%s': %s", key, err)
}
c.tarWriter.Flush()
c.gzipWriter.Flush()
c.fileWriter.Sync()
return nil
}
// WriteU64ForKey creates a new entry in the serializer file with the bytes of a uint64
func (c *ClassifierSerializer) WriteU64ForKey(key string, v uint64) error {
b := PackU64ToBytes(v)
return c.WriteBytesForKey(key, b)
}
// WriteJSONForKey creates a new entry in the file with an interface serialized as JSON.
func (c *ClassifierSerializer) WriteJSONForKey(key string, v interface{}) error {
b, err := json.Marshal(v)
if err != nil {
return err
}
return c.WriteBytesForKey(key, b)
}
// WriteAttributeForKey creates a new entry in the file containing a serialized representation of Attribute
func (c *ClassifierSerializer) WriteAttributeForKey(key string, a Attribute) error {
b, err := SerializeAttribute(a)
if err != nil {
return WrapError(err)
}
return c.WriteBytesForKey(key, b)
}
// WriteAttributesForKey does the same as WriteAttributeForKey, just with more than one Attribute.
func (c *ClassifierSerializer) WriteAttributesForKey(key string, attrs []Attribute) error {
attrCountKey := c.Prefix(key, "ATTR_COUNT")
err := c.WriteU64ForKey(attrCountKey, uint64(len(attrs)))
if err != nil {
return DescribeError("Unable to write ATTR_COUNT", err)
}
for i, a := range attrs {
attrKey := c.Prefix(key, fmt.Sprintf("%d", i))
err = c.WriteAttributeForKey(attrKey, a)
if err != nil {
return DescribeError("Unable to write Attribute", err)
}
}
return nil
}
// WriteInstances for key creates a new entry in the file containing some training instances
func (c *ClassifierSerializer) WriteInstancesForKey(key string, g FixedDataGrid, includeData bool) error {
fmt.Sprintf("%v", c)
return SerializeInstancesToTarWriter(g, c.tarWriter, key, includeData)
}
// Prefix outputs a string in the right format for TAR
func (c *ClassifierSerializer) Prefix(prefix string, suffix string) string {
if prefix == "" {
return suffix
}
return fmt.Sprintf("%s/%s", prefix, suffix)
}
// WriteMetadataAtPrefix outputs a METADATA entry in the right place
func (c *ClassifierSerializer) WriteMetadataAtPrefix(prefix string, metadata ClassifierMetadataV1) error {
return c.WriteJSONForKey(c.Prefix(prefix, "METADATA"), &metadata)
}
// CreateSerializedClassifierStub generates a file to serialize into
// and writes the METADATA header.
func CreateSerializedClassifierStub(filePath string, metadata ClassifierMetadataV1) (*ClassifierSerializer, error) {
// Open the filePath
f, err := os.OpenFile(filePath, os.O_RDWR|os.O_TRUNC|os.O_CREATE, 0600)
if err != nil {
return nil, err
}
var hdr *tar.Header
gzWriter := gzip.NewWriter(f)
tw := tar.NewWriter(gzWriter)
ret := ClassifierSerializer{
gzipWriter: gzWriter,
fileWriter: f,
tarWriter: tw,
}
//
// Write the MANIFEST entry
//
hdr = &tar.Header{
Name: "CLS_MANIFEST",
Size: int64(len(SerializationFormatVersion)),
}
if err := tw.WriteHeader(hdr); err != nil {
return nil, fmt.Errorf("Could not write CLS_MANIFEST header: %s", err)
}
if _, err := tw.Write([]byte(SerializationFormatVersion)); err != nil {
return nil, fmt.Errorf("Could not write CLS_MANIFEST contents: %s", err)
}
//
// Write the METADATA entry
//
err = ret.WriteMetadataAtPrefix("", metadata)
if err != nil {
return nil, fmt.Errorf("JSON marshal error: %s", err)
}
return &ret, nil
}