78 lines
1.9 KiB
Nim
78 lines
1.9 KiB
Nim
import base
|
|
import std/[re,httpclient,json,strutils]
|
|
|
|
const LIBRETRANSLATE_URL = "https://libretranslate.pussthecat.org/translate"
|
|
const PRIMARY = "en"
|
|
const SECONDARY = "de"
|
|
let LANG_RE = re"\w+>\w+"
|
|
|
|
type
|
|
Request = object
|
|
source: string
|
|
target: string
|
|
q: string
|
|
format: string
|
|
|
|
proc main(message: varargs[string] = @[])
|
|
|
|
proc newRequest(): Request =
|
|
return Request(source:SECONDARY,
|
|
target:PRIMARY,
|
|
q: "",
|
|
format: "text",)
|
|
|
|
proc parseReq(req: string): Request =
|
|
var r = newRequest()
|
|
var langs = findAll(req,LANG_RE)
|
|
if len(langs) > 0:
|
|
let lang = langs[0]
|
|
langs = lang.split(re">")
|
|
let query = replace(req,LANG_RE,"")
|
|
if query != "":
|
|
r.source = langs[0].toLowerAscii()
|
|
r.target = langs[1].toLowerAscii()
|
|
r.q = query
|
|
else:
|
|
main()
|
|
else:
|
|
main("No language selections made. i.e. en>de, de>en, etc.")
|
|
return r
|
|
|
|
proc answerTranslate(response: string, req: Request) =
|
|
let r = parseJson(response)
|
|
try:
|
|
let ans = r["translatedText"].getStr()
|
|
main(ans, req.source & " > " & req.target)
|
|
except:
|
|
main("Error : " & r["error"].getStr())
|
|
|
|
proc goTranslate(req: string) =
|
|
let r = parseReq(req)
|
|
if r.q != "":
|
|
var client = newHTTPClient()
|
|
client.headers = newHttpHeaders({"Content-Type":"application/json"})
|
|
let body = %*r
|
|
let response = client.request(LIBRETRANSLATE_URL, httpMethod = HttpPost, body = $body)
|
|
if response.status != "":
|
|
answerTranslate(response.body, r)
|
|
|
|
|
|
proc main(message:varargs[string] = @[]) =
|
|
var info = newInfo("Translate")
|
|
info.selected_bg = green
|
|
var args: seq[string] = @[]
|
|
for msg in message:
|
|
if msg != "":
|
|
args.add(msg)
|
|
args.add("exit")
|
|
let output = outputData(info,args)
|
|
if output == "exit" or output == "":
|
|
return
|
|
elif output in message:
|
|
copyToClipboard(output)
|
|
else:
|
|
goTranslate(output)
|
|
return
|
|
|
|
if isMainModule:
|
|
main()
|