textin/textin.go
2024-10-13 12:08:57 +08:00

87 lines
2.1 KiB
Go

package textin
import (
"apigo.cc/gojs"
"apigo.cc/gojs/goja"
_ "embed"
"errors"
"github.com/ssgo/config"
"github.com/ssgo/httpclient"
"github.com/ssgo/u"
"time"
)
//go:embed textin.ts
var textinTS string
type Conf struct {
AKey string
SKey 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{}{
"name": "textin",
"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("apigo.cc/ai/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)
if resMap["code"] != 200 {
panic(vm.NewGoError(errors.New(u.BRed(resMap["message"]))))
}
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
}