github.com/instill-ai/component@v0.16.0-beta/pkg/connector/instill/v0/ocr.go (about)

     1  package instill
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  
     7  	"google.golang.org/grpc/metadata"
     8  	"google.golang.org/protobuf/encoding/protojson"
     9  	"google.golang.org/protobuf/types/known/structpb"
    10  
    11  	modelPB "github.com/instill-ai/protogen-go/model/model/v1alpha"
    12  )
    13  
    14  func (e *execution) executeOCR(grpcClient modelPB.ModelPublicServiceClient, modelName string, inputs []*structpb.Struct) ([]*structpb.Struct, error) {
    15  	if len(inputs) <= 0 {
    16  		return nil, fmt.Errorf("invalid input: %v for model: %s", inputs, modelName)
    17  	}
    18  
    19  	if grpcClient == nil {
    20  		return nil, fmt.Errorf("uninitialized client")
    21  	}
    22  
    23  	outputs := []*structpb.Struct{}
    24  	for _, input := range inputs {
    25  		inputJSON, err := protojson.Marshal(input)
    26  		if err != nil {
    27  			return nil, err
    28  		}
    29  		ocrInput := &modelPB.OcrInput{}
    30  		err = protojson.UnmarshalOptions{DiscardUnknown: true}.Unmarshal(inputJSON, ocrInput)
    31  		if err != nil {
    32  			return nil, err
    33  		}
    34  
    35  		taskInput := &modelPB.TaskInput_Ocr{
    36  			Ocr: ocrInput,
    37  		}
    38  
    39  		// only support batch 1
    40  		req := modelPB.TriggerUserModelRequest{
    41  			Name:       modelName,
    42  			TaskInputs: []*modelPB.TaskInput{{Input: taskInput}},
    43  		}
    44  		ctx := metadata.NewOutgoingContext(context.Background(), getRequestMetadata(e.SystemVariables))
    45  		res, err := grpcClient.TriggerUserModel(ctx, &req)
    46  		if err != nil || res == nil {
    47  			return nil, err
    48  		}
    49  		taskOutputs := res.GetTaskOutputs()
    50  		if len(taskOutputs) <= 0 {
    51  			return nil, fmt.Errorf("invalid output: %v for model: %s", taskOutputs, modelName)
    52  		}
    53  
    54  		ocrOutput := taskOutputs[0].GetOcr()
    55  		if ocrOutput == nil {
    56  			return nil, fmt.Errorf("invalid output: %v for model: %s", ocrOutput, modelName)
    57  		}
    58  		outputJSON, err := protojson.MarshalOptions{
    59  			UseProtoNames:   true,
    60  			EmitUnpopulated: true,
    61  		}.Marshal(ocrOutput)
    62  		if err != nil {
    63  			return nil, err
    64  		}
    65  		output := &structpb.Struct{}
    66  		err = protojson.Unmarshal(outputJSON, output)
    67  		if err != nil {
    68  			return nil, err
    69  		}
    70  		outputs = append(outputs, output)
    71  	}
    72  	return outputs, nil
    73  }