构建自己 AI 翻译助手取代谷歌翻译
本文分享一种方式通过使用 Hugging Face LLM 和 Python 不受限制地翻译长文档。
在全球化的今天,与来自不同国家和文化的人交流变得越来越重要,而对于技术人员来说,阅读英文资料是常见的需求。通常语言障碍往往会降低学习英文资料的效率。虽然谷歌翻译成为弥补这一不足的流行工具,但它有其局限性,特别是在准确翻译较长的文本时。
真的很烦把一小部分文本复制/粘贴
到谷歌翻译中,等待结果,复制到文件中,重复的复制、粘贴,所以为什么不使用现在最流行的方式 AI 助理来解决问题?
有人可能担心使用第三方服务翻译敏感信息的隐私和安全问题。在本文中,将探索使用 Hugging Face 构建自己的人工智能翻译应用程序的替代解决方案。通过构建自己的翻译应用程序,确保数据的隐私和安全,同时还可以实现较长文本的体面准确翻译。
最终应用的结果是这样的:
安装依赖项
需要的包并不多,访问 Hugging Face 模型、创建大块的长文本和图形界面。但首先,作为良好实践,为新的 Python 项目创建一个虚拟环境。创建一个全新的目录 AI_Translator
并运行 venv
创建指令:
<span class="code-block-extension-codeLine" data-line-num="1">python3 -m venv venv</span>
激活虚拟环境:
<span class="code-block-extension-codeLine" data-line-num="1"><span class="hljs-built_in">source</span> venv/bin/activate <span class="hljs-comment">#for mac</span></span>
<span class="code-block-extension-codeLine" data-line-num="2">venv\Scripts\activate <span class="hljs-comment">#for windows users</span></span>
激活 venv
后安装下面依赖性:
<span class="code-block-extension-codeLine" data-line-num="1">pip install mkl mkl-include <span class="hljs-comment"># Mac 用户的 CPU 使用率需要</span></span>
<span class="code-block-extension-codeLine" data-line-num="2">pip install <span class="hljs-attr">torch</span>==<span class="hljs-number">1.11</span>.<span class="hljs-number">0</span> torchvision==<span class="hljs-number">0.12</span>.<span class="hljs-number">0</span> torchaudio==<span class="hljs-number">0.11</span>.<span class="hljs-number">0</span> <span class="hljs-comment"># 核心</span></span>
<span class="code-block-extension-codeLine" data-line-num="4">pip install transformers</span>
<span class="code-block-extension-codeLine" data-line-num="5">pip install <span class="hljs-attr">langchain</span>==<span class="hljs-number">0.0</span>.<span class="hljs-number">173</span></span>
<span class="code-block-extension-codeLine" data-line-num="6">pip install streamlit</span>
<span class="code-block-extension-codeLine" data-line-num="7">pip install streamlit-extras</span>
如果要使用的模型使用 Tensorflow
来创建权重,则还必须安装 Tensorflow
:
<span class="code-block-extension-codeLine" data-line-num="1">pip install tensorflow</span>
下载语言模型
应用程序的核心是语言翻译模型,这里的目标语言(中文)和原始文本语言(English),翻译模型是按照特定顺序训练的:
上面是一个翻译的模型:从英文到中文。 在Hugging Face Hub 翻译模型中,通常只有一对和一对的翻译,而这是个特定的顺序。从英文到中文(en-to-zh
) 。
可以在 Helsinki
语言技术研究组的 Hugging Face 库中找到一组适合的翻译模型。
这里有 1440 个语言模型,想要一个从英文到中文的翻译模型:所以需要查找到以 en-to-zh
结尾的模型。
正如图中所看到的,这个模型卡片告诉我们在 PyTorch 和 Tensorflow 中都有可用的权重。
- 创建子文件夹
model_zh
- 转到模型卡的文件选项卡并下载下面列出的所有文件:对于目录
model_zh
中的中文模型下载,需要下载如下:
<span class="code-block-extension-codeLine" data-line-num="1">README.md</span>
<span class="code-block-extension-codeLine" data-line-num="2">config.json</span>
<span class="code-block-extension-codeLine" data-line-num="3">generation_config.json</span>
<span class="code-block-extension-codeLine" data-line-num="4">pytorch_model.bin</span>
<span class="code-block-extension-codeLine" data-line-num="5">source.spm</span>
<span class="code-block-extension-codeLine" data-line-num="6">target.spm</span>
<span class="code-block-extension-codeLine" data-line-num="7">tokenizer_config.json</span>
<span class="code-block-extension-codeLine" data-line-num="8">vocab.json</span>
一旦所有文件都下载到它们的相关子文件夹中,准备工作就完成了。
测试模型
如果模型的权重为 .h5
格式,则需要安装 tensorflow(如上例所示)
<span class="code-block-extension-codeLine" data-line-num="1">pip install tensorflow</span>
调用模型时需要指定 tensorflow
框架,使用参数 from_tf=True
,如下:
<span class="code-block-extension-codeLine" data-line-num="1"><span class="hljs-attr">repo_id</span> = <span class="hljs-string">"Helsinki-NLP/opus-mt-en-zh"</span></span>
<span class="code-block-extension-codeLine" data-line-num="2"><span class="hljs-attr">model_tt0zh</span> = AutoModelForSeq2SeqLM.from_pretrained(repo_id, from_tf=<span class="hljs-literal">True</span>)</span>
创建一个名为 test-en-zh.py
的新文件:在开始创建用户界面之前,将使用它来测试带有 pytorch 模型的翻译管道的功能。该文件的代码如下(随后将进行解释)
<span class="code-block-extension-codeLine" data-line-num="1"><span class="hljs-keyword">import</span> torch</span>
<span class="code-block-extension-codeLine" data-line-num="2"><span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoTokenizer, AutoModelForSeq2SeqLM</span>
<span class="code-block-extension-codeLine" data-line-num="3"><span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> pipeline</span>
<span class="code-block-extension-codeLine" data-line-num="4"><span class="hljs-keyword">import</span> datetime</span>
<span class="code-block-extension-codeLine" data-line-num="6"><span class="hljs-comment">#LOCAL MODEL EN-IT</span></span>
<span class="code-block-extension-codeLine" data-line-num="7"><span class="hljs-comment">#---------------------------------</span></span>
<span class="code-block-extension-codeLine" data-line-num="8"><span class="hljs-comment"># Helsinki-NLP/opus-mt-en-zh</span></span>
<span class="code-block-extension-codeLine" data-line-num="9">Model_ZH = <span class="hljs-string">'./model_zh/'</span> <span class="hljs-comment">#torch</span></span>
<span class="code-block-extension-codeLine" data-line-num="10"><span class="hljs-comment">#---------------------------------</span></span>
<span class="code-block-extension-codeLine" data-line-num="11">English = <span class="hljs-string">"Imagine a world where AI-driven technologies enable us to communicate more effectively, analyze enormous amounts of textual data, and make informed decisions in just seconds. A world where chatbots comprehend our intentions and respond with human-like clarity. This world is no longer a far-off dream, but an approaching reality, due to the remarkable advancements in AI technologies such as ChatGPT and LangChain. In this article, we will dive into the groundbreaking innovations of ChatGPT and LangChain, examine their potential applications, and uncover how they are transforming the AI landscape."</span></span>
<span class="code-block-extension-codeLine" data-line-num="12"><span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoTokenizer, AutoModelForSeq2SeqLM </span>
<span class="code-block-extension-codeLine" data-line-num="13">tokenizer_tt0zh = AutoTokenizer.from_pretrained(Model_ZH) </span>
<span class="code-block-extension-codeLine" data-line-num="14"><span class="hljs-built_in">print</span>(<span class="hljs-string">'===>初始化AI语言模型...'</span>)</span>
<span class="code-block-extension-codeLine" data-line-num="15"><span class="hljs-comment">#repo_id = "Helsinki-NLP/opus-mt-en-zh"</span></span>
<span class="code-block-extension-codeLine" data-line-num="16"><span class="hljs-comment">#model_tt0zh = AutoModelForSeq2SeqLM.from_pretrained(repo_id, from_tf=True)</span></span>
<span class="code-block-extension-codeLine" data-line-num="17">model_tt0zh = AutoModelForSeq2SeqLM.from_pretrained(Model_ZH) <span class="hljs-comment">#Helsinki-NLP/opus-mt-en-zh</span></span>
<span class="code-block-extension-codeLine" data-line-num="18"><span class="hljs-built_in">print</span>(<span class="hljs-string">"===>pipeline"</span>)</span>
<span class="code-block-extension-codeLine" data-line-num="19">TToZH = pipeline(<span class="hljs-string">"translation"</span>, model=model_tt0zh, tokenizer=tokenizer_tt0zh)</span>
<span class="code-block-extension-codeLine" data-line-num="20"><span class="hljs-built_in">print</span>(<span class="hljs-string">"===>翻译正在进行中"</span>)</span>
<span class="code-block-extension-codeLine" data-line-num="21">start = datetime.datetime.now() </span>
<span class="code-block-extension-codeLine" data-line-num="22">finaltext = TToZH(English)</span>
<span class="code-block-extension-codeLine" data-line-num="23">stop = datetime.datetime.now() </span>
<span class="code-block-extension-codeLine" data-line-num="24">elapsed = stop - start</span>
<span class="code-block-extension-codeLine" data-line-num="25"><span class="hljs-built_in">print</span>(<span class="hljs-string">f'===>翻译完成于: <span class="hljs-subst">{elapsed}</span>...\n'</span>)</span>
<span class="code-block-extension-codeLine" data-line-num="26"><span class="hljs-built_in">print</span>(finaltext[<span class="hljs-number">0</span>][<span class="hljs-string">'translation_text'</span>])</span>
<span class="code-block-extension-codeLine" data-line-num="27"><span class="hljs-built_in">print</span>(<span class="hljs-string">f"\n===>翻译内容包含单词 <span class="hljs-subst">{<span class="hljs-built_in">len</span>(English.split(' '))}</span> 个"</span>)</span>
导入模型交互的核心:pytorch
和 transformers
库。然后为本地下载的模型设置检查点,存储它的路径 Model_ZH = './model_zh/'
。
要翻译的字符串存储在变量 English
中。然后,为分词器、模型和要执行的管道初始化对转换器库的调用:请注意,为分词器和模型传递了路径(Model_ZH
变量)。管道实例化为:
<span class="code-block-extension-codeLine" data-line-num="1"><span class="hljs-attr">TToZH</span> = pipeline(<span class="hljs-string">"translation"</span>, model=model_tt0zh, tokenizer=tokenizer_tt0zh)</span>
如果运行代码,将看到如下内容:
创建前端界面
创建一个名为 translationer.py
的新文件,在这里将使用 Streamlit 库来创建 Web 界面。
Streamlit 是一个无需了解任何前端技术(如 HTML 和 CSS)即可构建 Web 应用程序的库。如果想了解更多信息,请在此处查看清晰的文档。
<span class="code-block-extension-codeLine" data-line-num="1"><span class="hljs-keyword">import</span> streamlit <span class="hljs-keyword">as</span> st</span>
<span class="code-block-extension-codeLine" data-line-num="2"><span class="hljs-keyword">import</span> torch</span>
<span class="code-block-extension-codeLine" data-line-num="3"><span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoTokenizer, AutoModelForSeq2SeqLM</span>
<span class="code-block-extension-codeLine" data-line-num="4"><span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> pipeline</span>
<span class="code-block-extension-codeLine" data-line-num="5"><span class="hljs-keyword">from</span> langchain.text_splitter <span class="hljs-keyword">import</span> CharacterTextSplitter</span>
<span class="code-block-extension-codeLine" data-line-num="6"><span class="hljs-keyword">import</span> datetime</span>
<span class="code-block-extension-codeLine" data-line-num="8"><span class="hljs-comment">############# 在前端显示图像 #################</span></span>
<span class="code-block-extension-codeLine" data-line-num="9">st.set_page_config(page_title=<span class="hljs-string">"私人AI翻译助理"</span>,</span>
<span class="code-block-extension-codeLine" data-line-num="10"> page_icon=<span class="hljs-string">'♾️'</span>,</span>
<span class="code-block-extension-codeLine" data-line-num="11"> layout=<span class="hljs-string">"centered"</span>, <span class="hljs-comment">#or wide</span></span>
<span class="code-block-extension-codeLine" data-line-num="12"> initial_sidebar_state=<span class="hljs-string">"expanded"</span>,</span>
<span class="code-block-extension-codeLine" data-line-num="13"> menu_items={</span>
<span class="code-block-extension-codeLine" data-line-num="14"> <span class="hljs-string">'Get Help'</span>: <span class="hljs-string">'https://docs.streamlit.io/library/api-reference'</span>,</span>
<span class="code-block-extension-codeLine" data-line-num="15"> <span class="hljs-string">'Report a bug'</span>: <span class="hljs-string">"https://www.extremelycoolapp.com/bug"</span>,</span>
<span class="code-block-extension-codeLine" data-line-num="16"> <span class="hljs-string">'About'</span>: <span class="hljs-string">"一个懂你的AI翻译助理"</span></span>
<span class="code-block-extension-codeLine" data-line-num="17"> },</span>
<span class="code-block-extension-codeLine" data-line-num="18"> )</span>
<span class="code-block-extension-codeLine" data-line-num="19"><span class="hljs-comment"># </span></span>
<span class="code-block-extension-codeLine" data-line-num="20"><span class="hljs-comment">#LOCAL MODEL EN-ZH</span></span>
<span class="code-block-extension-codeLine" data-line-num="21"><span class="hljs-comment">#---------------------------------</span></span>
<span class="code-block-extension-codeLine" data-line-num="22"><span class="hljs-comment"># Helsinki-NLP/opus-mt-en-zh</span></span>
<span class="code-block-extension-codeLine" data-line-num="23">Model_ZH = <span class="hljs-string">'./model_zh/'</span> <span class="hljs-comment">#torch</span></span>
<span class="code-block-extension-codeLine" data-line-num="24"><span class="hljs-comment">#---------------------------------</span></span>
上述代码主要导入库、模型和 streamlit
页面的一般设置。如果模型是 .h5
模型,请记住导入 tensorflow
。
<span class="code-block-extension-codeLine" data-line-num="1"><span class="hljs-comment">### HEADER section</span></span>
<span class="code-block-extension-codeLine" data-line-num="2">st.header("私人AI翻译助理:帮你把英文翻译成中文")</span>
<span class="code-block-extension-codeLine" data-line-num="4"><span class="hljs-attr">English</span> = st.text_area(<span class="hljs-string">""</span>, height=<span class="hljs-number">240</span>, key=<span class="hljs-string">"original"</span>,placeholder=<span class="hljs-string">"请输入或者黏贴英文内容..."</span>)</span>
<span class="code-block-extension-codeLine" data-line-num="5">col1, col2, <span class="hljs-attr">col3</span> = st.columns([<span class="hljs-number">2</span>,<span class="hljs-number">5</span>,<span class="hljs-number">2</span>])</span>
<span class="code-block-extension-codeLine" data-line-num="6"><span class="hljs-attr">btn_translate</span> = col2.button(<span class="hljs-string">"✅ 开始翻译"</span>, use_container_width=<span class="hljs-literal">True</span>, type=<span class="hljs-string">"primary"</span>, key=<span class="hljs-string">'start'</span>)</span>
基本结构在这里完成,创建了 3 列并指定了 3 的比率。
<span class="code-block-extension-codeLine" data-line-num="1">col1, col2, <span class="hljs-attr">col3</span> = st.columns([<span class="hljs-number">2</span>,<span class="hljs-number">5</span>,<span class="hljs-number">2</span>])</span>
<span class="code-block-extension-codeLine" data-line-num="2"><span class="hljs-attr">btn_translate</span> = col2.button(<span class="hljs-string">"✅ 开始翻译"</span>, use_container_width=<span class="hljs-literal">True</span>, type=<span class="hljs-string">"primary"</span>, key=<span class="hljs-string">'start'</span>)</span>
只有在按下名为 btn_translate
的按钮时才会调用翻译管道。
<span class="code-block-extension-codeLine" data-line-num="1"><span class="hljs-keyword">if</span> btn_translate:</span>
<span class="code-block-extension-codeLine" data-line-num="2"> <span class="hljs-keyword">if</span> English:</span>
<span class="code-block-extension-codeLine" data-line-num="4"> <span class="hljs-keyword">else</span>:</span>
<span class="code-block-extension-codeLine" data-line-num="5"> st.<span class="hljs-built_in">warning</span>(<span class="hljs-string">"请输入您需要翻译的文本内容!"</span>, icon=<span class="hljs-string">"⚠️"</span>)</span>
2 个嵌套的 if
语句检查单击的按钮(如果 btn_translate
)以及英文文本是否为空,即变量 English
是否为空。后面使用 text-splitter
将长文本分成更小的部分,这样就不会溢出最大数量的标记。
pipeline
的调用和上一节测试代码一样,只是需要迭代。将文本分块,因此必须为每个块获取翻译管道的结果,然后将它们拼接起来:
<span class="code-block-extension-codeLine" data-line-num="1"><span class="hljs-comment"># 遍历块并连接翻译</span></span>
<span class="code-block-extension-codeLine" data-line-num="2"><span class="hljs-attr">finaltext</span> = <span class="hljs-string">''</span></span>
<span class="code-block-extension-codeLine" data-line-num="3"><span class="hljs-attr">start</span> = datetime.datetime.now() <span class="hljs-comment">#not used now but useful</span></span>
<span class="code-block-extension-codeLine" data-line-num="4">print('<span class="hljs-section">[bold yellow]</span> 翻译进行中...')</span>
<span class="code-block-extension-codeLine" data-line-num="5">for item in texts:</span>
<span class="code-block-extension-codeLine" data-line-num="6"> <span class="hljs-attr">line</span> = TToIT(item.page_content)[<span class="hljs-number">0</span>][<span class="hljs-string">'translation_text'</span>]</span>
<span class="code-block-extension-codeLine" data-line-num="7"> <span class="hljs-attr">finaltext</span> = finaltext+line+<span class="hljs-string">'\n'</span></span>
最后,可以在 text_area
部件中显示翻译的最终文本:
<span class="code-block-extension-codeLine" data-line-num="1">st.text_area(<span class="hljs-attr">label</span>=<span class="hljs-string">"中文翻译:"</span>, value=finaltext, height=<span class="hljs-number">350</span>)</span>
完整的代码如下:
<span class="code-block-extension-codeLine" data-line-num="1">import streamlit as st</span>
<span class="code-block-extension-codeLine" data-line-num="2">import torch</span>
<span class="code-block-extension-codeLine" data-line-num="3">from transformers import AutoTokenizer, AutoModelForSeq2SeqLM</span>
<span class="code-block-extension-codeLine" data-line-num="4">from transformers import pipeline</span>
<span class="code-block-extension-codeLine" data-line-num="5">from langchain.text_splitter import CharacterTextSplitter</span>
<span class="code-block-extension-codeLine" data-line-num="6">import datetime</span>
<span class="code-block-extension-codeLine" data-line-num="8"><span class="hljs-comment">############# 在前端显示图像 #################</span></span>
<span class="code-block-extension-codeLine" data-line-num="9">st.set_page_config(<span class="hljs-attr">page_title</span>=<span class="hljs-string">"私人AI翻译助理"</span>,</span>
<span class="code-block-extension-codeLine" data-line-num="10"> <span class="hljs-attr">page_icon</span>=<span class="hljs-string">'♾️'</span>,</span>
<span class="code-block-extension-codeLine" data-line-num="11"> <span class="hljs-attr">layout</span>=<span class="hljs-string">"centered"</span>, <span class="hljs-comment">#or wide</span></span>
<span class="code-block-extension-codeLine" data-line-num="12"> <span class="hljs-attr">initial_sidebar_state</span>=<span class="hljs-string">"expanded"</span>,</span>
<span class="code-block-extension-codeLine" data-line-num="13"> <span class="hljs-attr">menu_items</span>={</span>
<span class="code-block-extension-codeLine" data-line-num="14"> 'Get Help': 'https://docs.streamlit.io/library/api-reference',</span>
<span class="code-block-extension-codeLine" data-line-num="15"> 'Report a bug': "https://www.extremelycoolapp.com/bug",</span>
<span class="code-block-extension-codeLine" data-line-num="16"> 'About': "一个懂你的AI翻译助理"</span>
<span class="code-block-extension-codeLine" data-line-num="17"> },</span>
<span class="code-block-extension-codeLine" data-line-num="18"> )</span>
<span class="code-block-extension-codeLine" data-line-num="19"><span class="hljs-comment"># </span></span>
<span class="code-block-extension-codeLine" data-line-num="20"><span class="hljs-comment">#LOCAL MODEL EN-ZH</span></span>
<span class="code-block-extension-codeLine" data-line-num="21"><span class="hljs-comment">#---------------------------------</span></span>
<span class="code-block-extension-codeLine" data-line-num="22"><span class="hljs-comment"># Helsinki-NLP/opus-mt-en-zh</span></span>
<span class="code-block-extension-codeLine" data-line-num="23"><span class="hljs-attr">Model_ZH</span> = <span class="hljs-string">'./model_zh/'</span> <span class="hljs-comment">#torch</span></span>
<span class="code-block-extension-codeLine" data-line-num="24"><span class="hljs-comment">#---------------------------------</span></span>
<span class="code-block-extension-codeLine" data-line-num="26"><span class="hljs-comment">### HEADER section</span></span>
<span class="code-block-extension-codeLine" data-line-num="27">st.header("私人AI翻译助理:帮你把英文翻译成中文")</span>
<span class="code-block-extension-codeLine" data-line-num="29"><span class="hljs-attr">English</span> = st.text_area(<span class="hljs-string">""</span>, height=<span class="hljs-number">240</span>, key=<span class="hljs-string">"original"</span>,placeholder=<span class="hljs-string">"请输入或者黏贴英文内容..."</span>)</span>
<span class="code-block-extension-codeLine" data-line-num="30">col1, col2, <span class="hljs-attr">col3</span> = st.columns([<span class="hljs-number">2</span>,<span class="hljs-number">5</span>,<span class="hljs-number">2</span>])</span>
<span class="code-block-extension-codeLine" data-line-num="31"><span class="hljs-attr">btn_translate</span> = col2.button(<span class="hljs-string">"✅ 开始翻译"</span>, use_container_width=<span class="hljs-literal">True</span>, type=<span class="hljs-string">"primary"</span>, key=<span class="hljs-string">'start'</span>)</span>
<span class="code-block-extension-codeLine" data-line-num="32">if btn_translate:</span>
<span class="code-block-extension-codeLine" data-line-num="33"> if English:</span>
<span class="code-block-extension-codeLine" data-line-num="34"> <span class="hljs-attr">Model_ZH</span> = <span class="hljs-string">'./model_zh/'</span> <span class="hljs-comment">#torch</span></span>
<span class="code-block-extension-codeLine" data-line-num="35"> with st.spinner('AI翻译助理准备中...'):</span>
<span class="code-block-extension-codeLine" data-line-num="36"> st.success(' AI翻译助理开始翻译', <span class="hljs-attr">icon</span>=<span class="hljs-string">"🆗"</span>)</span>
<span class="code-block-extension-codeLine" data-line-num="37"> <span class="hljs-comment"># 用于分块的文本分离器函数</span></span>
<span class="code-block-extension-codeLine" data-line-num="38"> <span class="hljs-attr">text_splitter</span> = CharacterTextSplitter( </span>
<span class="code-block-extension-codeLine" data-line-num="39"> <span class="hljs-attr">separator</span> = <span class="hljs-string">"\n\n"</span>,</span>
<span class="code-block-extension-codeLine" data-line-num="40"> <span class="hljs-attr">chunk_size</span> = <span class="hljs-number">300</span>,</span>
<span class="code-block-extension-codeLine" data-line-num="41"> <span class="hljs-attr">chunk_overlap</span> = <span class="hljs-number">0</span>,</span>
<span class="code-block-extension-codeLine" data-line-num="42"> <span class="hljs-attr">length_function</span> = len,</span>
<span class="code-block-extension-codeLine" data-line-num="43"> )</span>
<span class="code-block-extension-codeLine" data-line-num="44"> <span class="hljs-comment"># 将文档分块</span></span>
<span class="code-block-extension-codeLine" data-line-num="45"> st.success(' 文档块文本...', <span class="hljs-attr">icon</span>=<span class="hljs-string">"🆗"</span>)</span>
<span class="code-block-extension-codeLine" data-line-num="46"> <span class="hljs-attr">texts</span> = text_splitter.create_documents([English])</span>
<span class="code-block-extension-codeLine" data-line-num="48"> from transformers import AutoTokenizer, AutoModelForSeq2SeqLM</span>
<span class="code-block-extension-codeLine" data-line-num="49"> <span class="hljs-comment"># 初始化翻译从英文到中文</span></span>
<span class="code-block-extension-codeLine" data-line-num="50"> <span class="hljs-attr">tokenizer_tt0zh</span> = AutoTokenizer.from_pretrained(Model_ZH)</span>
<span class="code-block-extension-codeLine" data-line-num="51"> st.success(' 初始AI语言模型...', <span class="hljs-attr">icon</span>=<span class="hljs-string">"🆗"</span>)</span>
<span class="code-block-extension-codeLine" data-line-num="52"> <span class="hljs-attr">model_tt0zh</span> = AutoModelForSeq2SeqLM.from_pretrained(Model_ZH) <span class="hljs-comment">#Helsinki-NLP/opus-mt-en-zh or #Helsinki-NLP/opus-mt-it-zh</span></span>
<span class="code-block-extension-codeLine" data-line-num="53"> <span class="hljs-attr">TToZH</span> = pipeline(<span class="hljs-string">"translation"</span>, model=model_tt0zh, tokenizer=tokenizer_tt0zh)</span>
<span class="code-block-extension-codeLine" data-line-num="54"> <span class="hljs-comment"># 遍历块并连接翻译</span></span>
<span class="code-block-extension-codeLine" data-line-num="55"> <span class="hljs-attr">finaltext</span> = <span class="hljs-string">''</span></span>
<span class="code-block-extension-codeLine" data-line-num="56"> <span class="hljs-attr">start</span> = datetime.datetime.now()</span>
<span class="code-block-extension-codeLine" data-line-num="57"> print('<span class="hljs-section">[bold yellow]</span>翻译进行中...')</span>
<span class="code-block-extension-codeLine" data-line-num="58"> for item in texts:</span>
<span class="code-block-extension-codeLine" data-line-num="59"> <span class="hljs-attr">line</span> = TToZH(item.page_content)[<span class="hljs-number">0</span>][<span class="hljs-string">'translation_text'</span>]</span>
<span class="code-block-extension-codeLine" data-line-num="60"> <span class="hljs-attr">finaltext</span> = finaltext+line+<span class="hljs-string">'\n'</span></span>
<span class="code-block-extension-codeLine" data-line-num="61"> <span class="hljs-attr">stop</span> = datetime.datetime.now() </span>
<span class="code-block-extension-codeLine" data-line-num="62"> <span class="hljs-attr">elapsed</span> = stop - start</span>
<span class="code-block-extension-codeLine" data-line-num="63"> st.success(f'翻译完成于 {elapsed}', <span class="hljs-attr">icon</span>=<span class="hljs-string">"🆗"</span>)</span>
<span class="code-block-extension-codeLine" data-line-num="64"> print(f'<span class="hljs-section">[bold underline green1]</span> Translation generated in <span class="hljs-section">[reverse dodger_blue2]</span>{elapsed}<span class="hljs-section">[/reverse dodger_blue2]</span>...')</span>
<span class="code-block-extension-codeLine" data-line-num="65"> st.text_area(<span class="hljs-attr">label</span>=<span class="hljs-string">"中文翻译:"</span>, value=finaltext, height=<span class="hljs-number">350</span>)</span>
<span class="code-block-extension-codeLine" data-line-num="66"> st.markdown(f'翻译完成于: **{elapsed}**')</span>
<span class="code-block-extension-codeLine" data-line-num="67"> st.markdown(f"翻译内容包含单词 {len(English.split(' '))} 个")</span>
<span class="code-block-extension-codeLine" data-line-num="69"> else:</span>
<span class="code-block-extension-codeLine" data-line-num="70"> st.warning("请输入您需要翻译的文本内容!", <span class="hljs-attr">icon</span>=<span class="hljs-string">"⚠️"</span>)</span>
接下来执行命令:
<span class="code-block-extension-codeLine" data-line-num="1">streamlit run translationer.py</span>
打开浏览器就可以体验自己构建的 AI 翻译助理了。
完
链接:https://juejin.cn/post/7247079349848047676
来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
文章评论