-
Notifications
You must be signed in to change notification settings - Fork 2
/
ocr.go
73 lines (64 loc) · 1.93 KB
/
ocr.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
package instill
import (
"context"
"fmt"
"google.golang.org/grpc/metadata"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/types/known/structpb"
modelPB "github.com/instill-ai/protogen-go/model/model/v1alpha"
)
func (e *execution) executeOCR(grpcClient modelPB.ModelPublicServiceClient, modelName string, inputs []*structpb.Struct) ([]*structpb.Struct, error) {
if len(inputs) <= 0 {
return nil, fmt.Errorf("invalid input: %v for model: %s", inputs, modelName)
}
if grpcClient == nil {
return nil, fmt.Errorf("uninitialized client")
}
outputs := []*structpb.Struct{}
for _, input := range inputs {
inputJSON, err := protojson.Marshal(input)
if err != nil {
return nil, err
}
ocrInput := &modelPB.OcrInput{}
err = protojson.UnmarshalOptions{DiscardUnknown: true}.Unmarshal(inputJSON, ocrInput)
if err != nil {
return nil, err
}
taskInput := &modelPB.TaskInput_Ocr{
Ocr: ocrInput,
}
// only support batch 1
req := modelPB.TriggerUserModelRequest{
Name: modelName,
TaskInputs: []*modelPB.TaskInput{{Input: taskInput}},
}
ctx := metadata.NewOutgoingContext(context.Background(), getRequestMetadata(e.SystemVariables))
res, err := grpcClient.TriggerUserModel(ctx, &req)
if err != nil || res == nil {
return nil, err
}
taskOutputs := res.GetTaskOutputs()
if len(taskOutputs) <= 0 {
return nil, fmt.Errorf("invalid output: %v for model: %s", taskOutputs, modelName)
}
ocrOutput := taskOutputs[0].GetOcr()
if ocrOutput == nil {
return nil, fmt.Errorf("invalid output: %v for model: %s", ocrOutput, modelName)
}
outputJSON, err := protojson.MarshalOptions{
UseProtoNames: true,
EmitUnpopulated: true,
}.Marshal(ocrOutput)
if err != nil {
return nil, err
}
output := &structpb.Struct{}
err = protojson.Unmarshal(outputJSON, output)
if err != nil {
return nil, err
}
outputs = append(outputs, output)
}
return outputs, nil
}