"""Prep gradio API.""" # pylint: diable=invalid-name from typing import List, Optional, Union import gradio as gr from easynmt import EasyNMT from logzero import logger translate = EasyNMT("opus-mt").translate def opusmt( text: str, from_lang: Optional[str] = None, to_lang: str = "zh", ) -> Union[str, List[str]]: """Translate via easyntm-opus-mt.""" try: from_lang = str(from_lang).strip() except Exception: from_lang = "auto" try: to_lang = str(to_lang).strip() except Exception: to_lang = "auto" # if empty, set to auto if not from_lang: from_lang = "auto" if not to_lang: to_lang = "auto" logger.debug("%s, %s, %s", text[:100], from_lang, to_lang) if to_lang in ["auto"]: if from_lang in ["zh"]: to_lang = "en" else: to_lang = "zh" if from_lang in ["auto"]: from_lang = None try: res = translate( text, target_lang=to_lang, source_lang=from_lang, ) except Exception as e: logger.error(e) if "Helsinki" in str(e): res = "errors occur" else: res = f"errors: {e}" return res inputs = [ gr.Textbox( label="text to translate", value="", lines=7, max_lines=200, ), gr.Textbox(label="from-lang", value="auto"), gr.Textbox(label="to-lang", value="zh"), ] outputs = [ gr.Textbox( label="translated", lines=7, max_lines=200, ), ] description = """Supported languages: aav, aed, af, alv, am, ar, art, ase, az, bat, bcl, be, bem, ber, bg, bi, bn, bnt, bzs, ca, cau, ccs, ceb, cel, chk, cpf, crs, cs, csg, csn, cus, cy, da, de, dra, ee, efi, el, en, eo, es, et, eu, euq, fi, fj, fr, fse, ga, gaa, gil, gl, grk, guw, gv, ha, he, hi, hil, ho, hr, ht, hu, hy, id, ig, ilo, is, iso, it, ja, jap, ka, kab, kg, kj, kl, ko, kqn, kwn, kwy, lg, ln, loz, lt, lu, lua, lue, lun, luo, lus, lv, map, mfe, mfs, mg, mh, mk, mkh, ml, mos, mr, ms, mt, mul, ng, nic, niu, nl, no, nso, ny, nyk, om, pa, pag, pap, phi, pis, pl, pon, poz, pqe, pqw, prl, pt, rn, rnd, ro, roa, ru, run, rw, sal, sg, sh, sit, sk, sl, sm, sn, sq, srn, ss, ssp, st, sv, sw, swc, taw, tdt, th, ti, tiv, tl, tll, tn, to, toi, tpi, tr, trk, ts, tum, tut, tvl, tw, ty, tzo, uk, umb, ur, ve, vi, vsl, wa, wal, war, wls, xh, yap, yo, yua, zai, zh, zne. Refer to [https://github.com/UKPLab/EasyNMT](https://github.com/UKPLab/EasyNMT) for details. Estimated speed: 6-60 sents/sec. """ _ = """ iface = gr.Interface( fn=opusmt, inputs=inputs, outputs=outputs, title="opus mt", description=description, examples=[ ["This is a test.", "en", "zh"], ["This is a test.", "en", "de"], ], allow_flagging="never", cache_examples=False, ) # """ with gr.Blocks() as iface: with gr.Row(): text = gr.Textbox( label="text to translate", value="", lines=7, max_lines=200, ) out = gr.Textbox( label="translated", lines=7, max_lines=200, ) with gr.Row(): from_lang = gr.Textbox(label="from-lang", value="auto") to_lang = gr.Textbox(label="to-lang", value="zh") btn = gr.Button("Translate") btn.click( fn=opusmt, inputs=[text, from_lang, to_lang], outputs=out, api_name="opusmt", ) gr.Markdown(f"{description}") iface.launch(enable_queue=True)