github.com/instill-ai/component@v0.16.0-beta/pkg/operator/text/v0/main.go (about) 1 //go:generate compogen readme --operator ./config ./README.mdx 2 package text 3 4 import ( 5 "fmt" 6 "sync" 7 8 _ "embed" // embed 9 10 "go.uber.org/zap" 11 "google.golang.org/protobuf/types/known/structpb" 12 13 "github.com/instill-ai/component/pkg/base" 14 ) 15 16 const ( 17 taskConvertToText string = "TASK_CONVERT_TO_TEXT" 18 taskSplitByToken string = "TASK_SPLIT_BY_TOKEN" 19 ) 20 21 var ( 22 //go:embed config/definition.json 23 definitionJSON []byte 24 //go:embed config/tasks.json 25 tasksJSON []byte 26 once sync.Once 27 op *operator 28 ) 29 30 // Operator is the derived operator 31 type operator struct { 32 base.BaseOperator 33 } 34 35 // Execution is the derived execution 36 type execution struct { 37 base.BaseOperatorExecution 38 } 39 40 // Init initializes the operator 41 func Init(l *zap.Logger, u base.UsageHandler) *operator { 42 once.Do(func() { 43 op = &operator{ 44 BaseOperator: base.BaseOperator{ 45 Logger: l, 46 UsageHandler: u, 47 }, 48 } 49 err := op.LoadOperatorDefinition(definitionJSON, tasksJSON, nil) 50 if err != nil { 51 panic(err) 52 } 53 }) 54 return op 55 } 56 57 func (o *operator) CreateExecution(sysVars map[string]any, task string) (*base.ExecutionWrapper, error) { 58 return &base.ExecutionWrapper{Execution: &execution{ 59 BaseOperatorExecution: base.BaseOperatorExecution{Operator: o, SystemVariables: sysVars, Task: task}, 60 }}, nil 61 } 62 63 // Execute executes the derived execution 64 func (e *execution) Execute(inputs []*structpb.Struct) ([]*structpb.Struct, error) { 65 outputs := []*structpb.Struct{} 66 67 for _, input := range inputs { 68 switch e.Task { 69 case taskConvertToText: 70 inputStruct := ConvertToTextInput{} 71 err := base.ConvertFromStructpb(input, &inputStruct) 72 if err != nil { 73 return nil, err 74 } 75 outputStruct, err := convertToText(inputStruct) 76 if err != nil { 77 return nil, err 78 } 79 output, err := base.ConvertToStructpb(outputStruct) 80 if err != nil { 81 return nil, err 82 } 83 outputs = append(outputs, output) 84 case taskSplitByToken: 85 inputStruct := SplitByTokenInput{} 86 err := base.ConvertFromStructpb(input, &inputStruct) 87 if err != nil { 88 return nil, err 89 } 90 outputStruct, err := splitTextIntoChunks(inputStruct) 91 if err != nil { 92 return nil, err 93 } 94 output, err := base.ConvertToStructpb(outputStruct) 95 if err != nil { 96 return nil, err 97 } 98 outputs = append(outputs, output) 99 default: 100 return nil, fmt.Errorf("not supported task: %s", e.Task) 101 } 102 } 103 return outputs, nil 104 }