-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathclient.go
More file actions
72 lines (62 loc) · 1.69 KB
/
client.go
File metadata and controls
72 lines (62 loc) · 1.69 KB
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
package tfclient
import (
"errors"
"sync"
tfcore "tensorflow/core/framework"
tf "tensorflow_serving/apis"
"golang.org/x/net/context"
"google.golang.org/grpc"
)
type PredictionClient struct {
mu sync.RWMutex
rpcConn *grpc.ClientConn
svcConn tf.PredictionServiceClient
}
type Prediction struct {
Class string `json:"class"`
Score float32 `json:"score"`
}
func NewClient(addr string) (*PredictionClient, error) {
conn, err := grpc.Dial(addr, grpc.WithInsecure())
if err != nil {
return nil, err
}
c := tf.NewPredictionServiceClient(conn)
return &PredictionClient{rpcConn: conn, svcConn: c}, nil
}
func (c *PredictionClient) Predict(modelName string, imgdata []byte) ([]Prediction, error) {
resp, err := c.svcConn.Predict(context.Background(), &tf.PredictRequest{
ModelSpec: &tf.ModelSpec{
Name: modelName,
},
Inputs: map[string]*tfcore.TensorProto{
"images": &tfcore.TensorProto{
Dtype: tfcore.DataType_DT_STRING,
StringVal: [][]byte{imgdata},
TensorShape: &tfcore.TensorShapeProto{
Dim: []*tfcore.TensorShapeProto_Dim{{Size: 1}},
},
},
},
})
if err != nil {
return nil, err
}
classesTensor, scoresTensor := resp.Outputs["classes"], resp.Outputs["scores"]
if classesTensor == nil || scoresTensor == nil {
return nil, errors.New("missing expected tensors in response")
}
classes := classesTensor.StringVal
scores := scoresTensor.FloatVal
var result []Prediction
for i := 0; i < len(classes) && i < len(scores); i++ {
result = append(result, Prediction{Class: string(classes[i]), Score: scores[i]})
}
return result, nil
}
func (c *PredictionClient) Close() error {
c.mu.Lock()
defer c.mu.Unlock()
c.svcConn = nil
return c.rpcConn.Close()
}