# 加载必要的模型。此处我们选择中译英和英译中两个模型 # 下面的代码将从HuggingFace网站上下载对应的模型,并存储在`$HOME/.cache/huggingface/hub/`文件夹下。 try: print('Loading model: Chinese -> English ...') model_zh2en = AutoModelWithLMHead.from_pretrained('Helsinki-NLP/opus-mt-zh-en') token_zh2en = AutoTokenizer.from_pretrained('Helsinki-NLP/opus-mt-zh-en') trans_zh2en = pipeline('translation_zh_to_en', model = model_zh2en, tokenizer = token_zh2en) print('Loading model: English -> Chinese ...') model_en2zh = AutoModelWithLMHead.from_pretrained('Helsinki-NLP/opus-mt-en-zh') token_en2zh = AutoTokenizer.from_pretrained('Helsinki-NLP/opus-mt-en-zh') trans_en2zh = pipeline('translation_en_to_zh', model = model_en2zh, tokenizer = token_en2zh) except: print('A exceptence occurred when loading model...') sys.exit(1)
# 定义一个函数,通过字符串中的ASCII字符比例,判断语句是中文还是英文 defisChinese(text): l = len(text) n = 0 for c in text: if(ord(c)<256):n+=1 if(n>0.5*l): #ASCII字符占了所有字符的50%以上比例,判定为英文 returnFalse else: returnTrue
# 定义一个翻译过程的函数,传入要翻译的字符串和翻译模式,返回翻译后的字符串 # 参数`mod`代表翻译模式,默认为自动检测。仅支持中译英和英译中。 deftranslate(text, mod="auto"): # 参数mod的可选值:"auto"(default),"zh2en","en2zh" if(mod == 'zh2en'): result = trans_zh2en(text, max_length=81920)[0]['translation_text'] return result if(mod == 'en2zh'): result = trans_en2zh(text, max_length=81920)[0]['translation_text'] return result if(mod == 'auto'): if(isChinese(text)): result = trans_zh2en(text, max_length=81920)[0]['translation_text'] else: result = trans_en2zh(text, max_length=81920)[0]['translation_text'] return result
# 设置一个函数,用于调整翻译模式 Mod = "auto" defsetmod(mod): global Mod available_mod = ["auto","zh2en","en2zh"] if(mod in available_mod): Mod = mod else: print("Unavailable mod: {}\n".format(mod))
# “帮助”函数 defhelp(): help_text=""" All available commands: /? print this information /help print this information /exit quit program /quit quit program /mod [mode] set translation mode. Available value: "auto"(default): Automatically select translation mode. "zh2en": Chinese translate into English. "en2zh": English translate into Chinese. /clear clean screen If you want to translate any sentence, just type it after prompt. """ print(help_text)
# 解析并执行指令的函数 defcommand(cmd): if (cmd=="/exit"): sys.exit(0) elif(cmd=="/quit"): sys.exit(0) elif(cmd=="/help"): help() elif(cmd=="/?" ): help() elif(cmd[0:4]=="/mod"): setmod(cmd[5:]) elif(cmd=="/clear"): if(sys.platform=="win32"):os.system("cls") else: os.system("clear") else: print("{} is not recognized as an command.".format(cmd)) help()
+------------+ | pyNLP-MT | +------------+ Offline translation program (created by Wesky, modified by WZ on Dec 9th, 2022)
Loading model: Chinese -> English ... Loading model: English -> Chinese ... input `/help` for help (auto) >>>
3.1 帮助界面
在交互式模式下,输入/help即可得到帮助。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
(auto) >>> /help
All available commands: /? print this information /help print this information /exit quit program /quit quit program /mod [mode] set translation mode. Available value: "auto"(default): Automatically select translation mode. "zh2en": Chinese translate into English. "en2zh": English translate into Chinese. /clear clean screen
If you want to translate any sentence, just type it after prompt.
3.2 翻译与切换翻译模式
自动检测语言并翻译(默认):
1 2 3 4 5 6 7 8 9 10 11
(auto) >>> Sleep is an integral part of our daily routine, and, among the myriad functions attributed to this state, emotional processing stands out as a crucial aspect. Everyone has experienced at least once how a poor night’s sleep can wreak havoc on our emotions.
Translation: Now we know that every civilization goes through this: awakening from a tiny cradle world, walking out, flying, flying faster, flying further away, and finally integrating with the fate of the universe.
将翻译模式改为仅英译中:
1 2 3 4 5
(auto) >>> /mod en2zh (en2zh) >>> For markets to achieve biodiversity conservation, biodiversity must endure. A “buy and forget” model, where credits exist forever regardless of whether the biodiversity persists, would lead to perverse outcomes.
Translation: Due to the loss of water bodies, which binds large amounts of evaporation, clouds in the small universe evaporate, the sun glitters behind them, and there is a beautiful rainbow across the universe.