Skip to content

Commit

Permalink
add support workers AI and weblio
Browse files Browse the repository at this point in the history
Signed-off-by: Asutorufa <[email protected]>
  • Loading branch information
Asutorufa committed Jul 30, 2024
1 parent f012887 commit 7f86215
Show file tree
Hide file tree
Showing 12 changed files with 305 additions and 121 deletions.
6 changes: 5 additions & 1 deletion cmd/hj/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"github.com/Asutorufa/hujiang_dictionary/jp"
"github.com/Asutorufa/hujiang_dictionary/kotobakku"
"github.com/Asutorufa/hujiang_dictionary/kr"
"github.com/Asutorufa/hujiang_dictionary/weblio"
)

func main() {
Expand All @@ -17,6 +18,7 @@ func main() {
krFlag := flag.String("kr", "", "korean")
ktbkFlag := flag.String("ktbk", "", "コトバック")
jsonFlag := flag.Bool("json", false, "output json")
webliFlag := flag.String("weblio", "", "weblio辞書")
flag.Parse()

if *jsonFlag {
Expand Down Expand Up @@ -48,9 +50,11 @@ func main() {
case *enFlag != "":
fmt.Println(en.FormatString(*enFlag))
case *ktbkFlag != "":
kotobakku.Show(*ktbkFlag)
fmt.Println(kotobakku.FormatString(*ktbkFlag))
case *krFlag != "":
fmt.Println(kr.FormatString(*krFlag))
case *webliFlag != "":
fmt.Println(weblio.FormatString(*webliFlag))
default:
return
}
Expand Down
75 changes: 75 additions & 0 deletions cmd/worker/ai_js.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
package main

import (
"syscall/js"
_ "unsafe"

_ "github.com/syumai/workers"
"github.com/syumai/workers/cloudflare"
)

type AI struct {
instance js.Value
}

func NewAI() *AI {
return &AI{
instance: cloudflare.GetBinding("AI"),
}
}

func (a *AI) Translate(opts TranslateOptions) (string, error) {
p := a.instance.Call("run", "@cf/meta/m2m100-1.2b", opts.toJS())

t, err := AwaitPromise(p)
if err != nil {
return "", err
}

return t.Get("translated_text").String(), nil
}

/*
"@cf/meta/m2m100-1.2b",
{
text: "I'll have an order of the moule frites",
source_lang: "english", // defaults to english
target_lang: "french",
}
​​Response
{
"translated_text": "Je vais commander des moules frites"
}
*/
type TranslateOptions struct {
Text string
SourceLang string
TargetLang string
}

func (opts *TranslateOptions) toJS() js.Value {
if opts == nil {
return js.Undefined()
}
obj := NewObject()
if opts.Text != "" {
obj.Set("text", opts.Text)
}
if opts.SourceLang != "" {
obj.Set("source_lang", opts.SourceLang)
}
if opts.TargetLang != "" {
obj.Set("target_lang", opts.TargetLang)
}
return obj
}

//go:linkname NewObject github.com/syumai/workers/internal/jsutil.NewObject
func NewObject() js.Value

//go:linkname AwaitPromise github.com/syumai/workers/internal/jsutil.AwaitPromise
func AwaitPromise(promiseVal js.Value) (js.Value, error)
148 changes: 106 additions & 42 deletions cmd/worker/main.go → cmd/worker/main_js.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,12 @@ import (
"strings"

"github.com/Asutorufa/hujiang_dictionary/en"
"github.com/Asutorufa/hujiang_dictionary/google"
"github.com/Asutorufa/hujiang_dictionary/httpclient"
"github.com/Asutorufa/hujiang_dictionary/jp"
"github.com/Asutorufa/hujiang_dictionary/kotobakku"
"github.com/Asutorufa/hujiang_dictionary/kr"
"github.com/Asutorufa/hujiang_dictionary/weblio"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"github.com/syumai/tinyutil/httputil"
"github.com/syumai/workers"
Expand Down Expand Up @@ -43,12 +45,15 @@ command = "make build"
telegram_token = "****:*****"
worker_url = "https://*****.workers.dev"
telegram_ids = "40xxxxxx,42xxxxx"
[ai]
binding = "AI"
*/

func main() {
httpclient.DefaultClient = httputil.DefaultClient

bot()
http.HandleFunc("/tgbot", bot())

http.HandleFunc("/tgbot/register", func(w http.ResponseWriter, r *http.Request) {
wh, err := tgbotapi.NewWebhook(cloudflare.Getenv("worker_url") + "/tgbot")
Expand All @@ -67,19 +72,28 @@ func main() {
return
}

info, err := Bot.GetWebhookInfo()

json.NewEncoder(w).Encode([]any{
info, err,
})

Bot.Request(tgbotapi.NewSetMyCommands(
resp, err := Bot.Request(tgbotapi.NewSetMyCommands(
tgbotapi.BotCommand{Command: "en", Description: "en"},
tgbotapi.BotCommand{Command: "jpcn", Description: "jp -> cn"},
tgbotapi.BotCommand{Command: "cnjp", Description: "cn -> jp"},
tgbotapi.BotCommand{Command: "ktbk", Description: "コトバック"},
tgbotapi.BotCommand{Command: "kr", Description: "kr"},
tgbotapi.BotCommand{Command: "weblio", Description: "weblio辞書"},
tgbotapi.BotCommand{Command: "ko", Description: "korean"},
tgbotapi.BotCommand{Command: "cfaija", Description: "cloudflare worker ai -> japanese"},
tgbotapi.BotCommand{Command: "cfaicn", Description: "cloudflare worker ai -> chinese"},
tgbotapi.BotCommand{Command: "cfaitar_lang", Description: "cloudflare worker ai -> [tar_lang]"},
tgbotapi.BotCommand{Command: "cfaisrc_lang2tar_lang", Description: "cloudflare worker ai src_lang -> tar_lang"},
tgbotapi.BotCommand{Command: "ggtar_lang", Description: "google translate to tar_lang"},
))

if err != nil {
json.NewEncoder(w).Encode([]any{
err.Error(),
})
return
}

json.NewEncoder(w).Encode(resp)
})

http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
Expand All @@ -94,26 +108,91 @@ func main() {

fmt.Println(t, word)

switch t {
case "jp":
w.Write([]byte(jp.FormatString(word)))
case "cnjp":
w.Write([]byte(jp.FormatCNString(word)))
case "kr":
w.Write([]byte(kr.FormatString(word)))
case "ktbk":
w.Write([]byte(kotobakku.FormatString(word)))
case "en":
w.Write([]byte(en.FormatString(word)))
default:
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("unsupported type"))
w.Header().Set("Content-Type", "text/plain; charset=utf-8")

resp := translate(t, Args{Text: word})
if resp == "" {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte("not found"))
return
}

w.Write([]byte(resp))
})
workers.Serve(nil) // use http.DefaultServeMux
}

func bot() {
type Args struct {
Text string
}

func translate(cmd string, args Args) string {
var resp string
argument := args.Text

if strings.HasPrefix(cmd, "cfai") {
cmd = strings.TrimPrefix(cmd, "cfai")
var src string
target := cmd
if i := strings.IndexByte(cmd, '2'); i != -1 {
src = cmd[:i]
target = cmd[i+1:]
}

switch target {
case "en":
target = "english"
case "jp":
target = "japanese"
case "cn":
target = "chinese"
}

str, err := NewAI().Translate(TranslateOptions{
Text: argument,
SourceLang: src,
TargetLang: target,
})
if err != nil {
resp = err.Error()
} else {
resp = str
}

return resp
}

if strings.HasPrefix(cmd, "gg") {
cmd = strings.TrimPrefix(cmd, "gg")
str, err := google.Translate(argument, "", cmd)
if err != nil {
resp = err.Error()
} else {
resp = strings.Join(str.Target, "\n")
}

return resp
}

switch cmd {
case "en":
resp = en.FormatString(argument)
case "jpcn":
resp = jp.FormatString(argument)
case "cnjp":
resp = jp.FormatCNString(argument)
case "ktbk":
resp = kotobakku.FormatString(argument)
case "ko":
resp = kr.FormatString(argument)
case "weblio":
resp = weblio.FormatString(argument)
}

return resp
}

func bot() func(w http.ResponseWriter, r *http.Request) {
idMap := make(map[int64]bool)
for _, id := range strings.FieldsFunc(cloudflare.Getenv("telegram_ids"), func(r rune) bool { return r == ',' }) {
i, err := strconv.ParseInt(id, 10, 64)
Expand All @@ -125,7 +204,7 @@ func bot() {
idMap[i] = true
}

http.HandleFunc("/tgbot", func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
update, err := Bot.HandleUpdate(r)
if err != nil {
json.NewEncoder(w).Encode([]any{
Expand All @@ -147,22 +226,7 @@ func bot() {
return
}

var resp string
switch update.Message.Command() {
case "en":
resp = en.FormatString(argument)
case "jpcn":
resp = jp.FormatString(argument)
case "cnjp":
resp = jp.FormatCNString(argument)
case "ktbk":
resp = kotobakku.FormatString(argument)
case "kr":
resp = kr.FormatString(argument)
default:
return
}

resp := translate(update.Message.Command(), Args{Text: argument})
if resp == "" {
return
}
Expand All @@ -171,5 +235,5 @@ func bot() {
msg.ReplyToMessageID = update.Message.MessageID

Bot.Send(msg)
})
}
}
23 changes: 12 additions & 11 deletions cmd/worker/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion cmd/worker/package.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"dependencies": {
"wrangler": "^3.65.1"
"wrangler": "^3.67.1"
}
}
Loading

0 comments on commit 7f86215

Please sign in to comment.