wmtools/translate.nim

87 lines
2.1 KiB
Nim
Raw Normal View History

2022-05-10 23:18:37 +02:00
import base
import std/[re,httpclient,json,strutils]
2022-05-10 23:27:54 +02:00
# TODO: Add language detection and translate into HOME language
2022-05-10 23:34:47 +02:00
# Once one translation is done, stay in that translation until told otherwise
2022-05-10 23:27:54 +02:00
2022-05-10 23:18:37 +02:00
const LIBRETRANSLATE_URL = "https://libretranslate.pussthecat.org/translate"
2022-05-10 23:27:54 +02:00
const HOME = "en"
const FIRST_CHOICE = "de"
2022-05-10 23:18:37 +02:00
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 =
2022-05-10 23:27:54 +02:00
return Request(source:FIRST_CHOICE,
target:HOME,
2022-05-10 23:18:37 +02:00
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] = @[]
2022-05-10 23:34:47 +02:00
if len(message) > 0:
for msg in message:
if msg != "":
args.add(msg)
args.add("back")
2022-05-10 23:18:37 +02:00
args.add("exit")
let output = outputData(info,args)
if output == "exit" or output == "":
return
2022-05-10 23:34:47 +02:00
elif output == "back":
main()
2022-05-10 23:18:37 +02:00
elif output in message:
copyToClipboard(output)
else:
goTranslate(output)
return
if isMainModule:
main()