added translate

This commit is contained in:
Paul Wilde 2022-05-10 22:18:37 +01:00
parent 9713f40fac
commit 598b695327
3 changed files with 81 additions and 2 deletions

View file

@ -18,6 +18,8 @@ which are selectable options in dmenu.
- `calculate` a calculator, utilising `qalculate` - inspired by [@fedops](https://codeberg.org/fedops/scripts)
- `emoji` an emoji picker
- `remmina` reads the files in your remmina config directory and allows you to connect to and edit them
- `translate` utilises libretranslate (you'll need and API key or your own instance) to translate test. Prefix the text with `en>de`, `de>en`, `en>fr`, etc. as you need.
- must be compiled with `-d:ssl`
The next two do not work with `rofi` unless you have `alias dmenu=rofi` set, but they're pretty nice tools

View file

@ -1,6 +1,5 @@
import base
import lib/emojilist
import std/[re,os,osproc,tables,algorithm]
import std/[os,osproc,tables,algorithm]
import configparser
const REMMINA_DIR = getHomeDir() & ".local/share/remmina"

78
translate.nim Normal file
View file

@ -0,0 +1,78 @@
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()