[18] | 1 | // $TheSupernovaDuo: suwako,v 1.5.1 2023/4/15 23:9:28 yakumo_izuru Exp $
|
---|
| 2 | // Command line client for Mozhi, a (yet another) privacy friendly frontend to other translation engines
|
---|
| 3 | package main
|
---|
| 4 |
|
---|
| 5 | import (
|
---|
| 6 | "encoding/json"
|
---|
| 7 | "flag"
|
---|
| 8 | "fmt"
|
---|
| 9 | "log"
|
---|
| 10 | "net/http"
|
---|
| 11 | "net/url"
|
---|
| 12 | "marisa.chaotic.ninja/suwako"
|
---|
| 13 | "os"
|
---|
| 14 | )
|
---|
| 15 |
|
---|
| 16 | var (
|
---|
| 17 | engine string
|
---|
| 18 | instance string
|
---|
| 19 | input string
|
---|
| 20 | source string
|
---|
| 21 | target string
|
---|
| 22 | )
|
---|
| 23 | type Translate struct {
|
---|
| 24 | Output string `json:"translated-text"`
|
---|
| 25 | }
|
---|
| 26 | func init() {
|
---|
| 27 | flag.StringVar(&source, "f", "auto", "Set the language to translate from. This can be skipped as it will autodetect the language you're translating from")
|
---|
| 28 | flag.StringVar(&input, "i", "", "Enter the text to be translated")
|
---|
| 29 | flag.StringVar(&target, "t", "en", "Set the language to translate to")
|
---|
| 30 | flag.Usage = func() {
|
---|
| 31 | fmt.Printf("usage: suwako -f [lang] -i [text] -t [lang]\nversion: %v\n", suwako.FullVersion())
|
---|
| 32 | }
|
---|
| 33 | }
|
---|
| 34 | func main() {
|
---|
| 35 | engine = os.Getenv("SUWAKO_ENGINE")
|
---|
| 36 | instance = os.Getenv("SUWAKO_INSTANCE")
|
---|
| 37 |
|
---|
| 38 | flag.Parse()
|
---|
| 39 |
|
---|
| 40 | if len(engine) == 0 || len(instance) == 0 {
|
---|
| 41 | log.Println("SUWAKO_ENGINE and/or SUWAKO_INSTANCE are unset")
|
---|
| 42 | log.Println("Defaulting to mozhi.aryak.me with engine 'google'")
|
---|
| 43 | engine = "google"
|
---|
| 44 | instance = "https://mozhi.aryak.me"
|
---|
| 45 | }
|
---|
| 46 | if len(input) == 0 {
|
---|
| 47 | log.Fatal("Missing input text.")
|
---|
| 48 | }
|
---|
| 49 | // Map a variable to the struct
|
---|
| 50 | var translate Translate
|
---|
| 51 | // Build the full URL to query
|
---|
| 52 | var encInput = url.PathEscape(input)
|
---|
| 53 | var apiEndpoint = "/api/translate"
|
---|
| 54 | var queryURL = instance + apiEndpoint + "?engine=" + engine + "&from=" + source + "&to=" + target + "&text=" + encInput
|
---|
| 55 | // Begin the request and process the response
|
---|
| 56 | resp, err := http.Get(queryURL)
|
---|
| 57 | sanityCheck(err)
|
---|
| 58 | defer resp.Body.Close()
|
---|
| 59 | // JSON decoding
|
---|
| 60 | _ = json.NewDecoder(resp.Body).Decode(&translate)
|
---|
| 61 | sanityCheck(err)
|
---|
| 62 | fmt.Printf("%v\n",translate.Output)
|
---|
| 63 | }
|
---|
| 64 | func sanityCheck(err error) {
|
---|
| 65 | if err != nil {
|
---|
| 66 | log.Fatal(err)
|
---|
| 67 | }
|
---|
| 68 | }
|
---|