textin/textin.go
2024-10-02 14:55:11 +08:00

83 lines
2.0 KiB
Go

package textin
import (
"apigo.cc/apigo/gojs"
"apigo.cc/apigo/gojs/dop251/goja"
_ "embed"
"errors"
"github.com/ssgo/config"
"github.com/ssgo/httpclient"
"github.com/ssgo/u"
"time"
)
type Conf struct {
AKey string
SKey string
}
//go:embed textin.ts
var textinTS string
var conf = Conf{}
var confAes = u.NewAes([]byte("?GQ$0K0GgLdO=f+~L68PLm$uhKr4'=tV"), []byte("VFs7@sK61cj^f?HZ"))
var keysIsSet = false
func SetSSKey(key, iv []byte) {
if !keysIsSet {
confAes = u.NewAes(key, iv)
keysIsSet = true
}
}
func init() {
obj := map[string]interface{}{
"OCR": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(1)
return vm.ToValue(OCR(args.Bytes(0), vm))
},
"OCRFromFile": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
path := gojs.MakeArgs(&argsIn, vm).Check(1).Path(0)
if file, err := u.ReadFileBytes(path); err != nil {
panic(vm.NewGoError(err))
} else {
return vm.ToValue(OCR(file, vm))
}
},
}
config.LoadConfig("textin", &conf)
conf.AKey = confAes.DecryptUrlBase64ToString(conf.AKey)
conf.SKey = confAes.DecryptUrlBase64ToString(conf.SKey)
//log.DefaultLogger.Info("conf", "", conf)
gojs.Register("textin", gojs.Module{
Object: obj,
TsCode: textinTS,
Example: "",
})
}
func OCR(file []byte, vm *goja.Runtime) string {
resMap := httpclient.GetClient(time.Second*30).Post("https://api.textin.com/ai/service/v2/recognize/multipage", file, "x-ti-app-id", conf.AKey, "x-ti-secret-code", conf.SKey).Map()
res := struct {
Result struct {
Pages []struct {
Lines []struct {
Text string
} `json:"lines"`
} `json:"pages"`
} `json:"result"`
}{}
//log.DefaultLogger.Info("Result", "", resMap)
str := ""
u.Convert(resMap, &res)
if len(res.Result.Pages) < 1 {
panic(vm.NewGoError(errors.New(u.BRed("no characters recognized"))))
}
for _, k := range res.Result.Pages[len(res.Result.Pages)-1].Lines {
str += "" + k.Text
}
//log.DefaultLogger.Info("OCRResult", "Map", resMap, "Text", str)
return str
}