translate / app.py
Dy3257's picture
Upload 19 files
535a983 verified
raw
history blame
2.22 kB
#该应用创建工具共包含三个区域,顶部工具栏,左侧代码区,右侧交互效果区,其中右侧交互效果是通过左侧代码生成的,存在对照关系。
#顶部工具栏:运行、保存、新开浏览器打开、实时预览开关,针对运行和在浏览器打开选项进行重要说明:
#[运行]:交互效果并非实时更新,代码变更后,需点击运行按钮获得最新交互效果。
#[在浏览器打开]:新建页面查看交互效果。
#以下为应用创建工具的示例代码
import gradio as gr
import ctranslate2
from split import split_string
translator_zh2en = ctranslate2.Translator("zh-en_model/", device="cpu")##路径
translator2_zh2en = ctranslate2.Translator("zh2en_cmodel/", device="cpu")##路径
translator_en2zh = ctranslate2.Translator("en-zh_model/", device="cpu")##路径
translator2_en2zh = ctranslate2.Translator("en2zh_cmodel", device="cpu")##路径
def translate(input_tokens, input_tokens2, mode):
input_tokens = input_tokens.split()
input_tokens2 = input_tokens2.split()
source = split_string(input_tokens)
lenth = len(source)
source2 = split_string(input_tokens2)
lenth2 = len(source2)
results = []
results2 = []
if mode == "汉译英" :
results = translator_zh2en.translate_batch(source)##翻译的分词分句
results2 = translator2_zh2en.translate_batch(source2)##翻译的分词分句
else :
results = translator_en2zh.translate_batch(source)##翻译的分词分句
results2 = translator2_en2zh.translate_batch(source2)##翻译的分词分句
target = []
target2 = []
for i in range(0, lenth, 1):
target = target + results[i].hypotheses[0]
for i in range(0, lenth2, 1):
target2 = target2 + results2[i].hypotheses[0]
#print(results[0].hypotheses[0])##results[0]为第0句,hypotheses[0]保持0
##print(results[1].hypotheses[0])
#return results[0].hypotheses[0]
return ' '.join(target),' '.join(target2)
demo = gr.Interface(fn=translate,
inputs=["text", "text", gr.Dropdown(["汉译英", "英译汉"])],
outputs=["text", "text"],)
demo.launch()