翻译的两种实现方式——基于transformers

1.基于pipeline 

(可加参数 device,默认为-1,使用cpu,如果非负,则表示指定哪块gpu)
from transformers import (
     AutoTokenizer,
     AutoModelForSeq2SeqLM,
     pipeline
)

text = "从时间上看,中国空间站的建造比国际空间站晚20多年。"

tokenizer = AutoTokenizer.from_pretrained("./Helsinki-NLP/opus-mt-zh-en")
model = AutoModelForSeq2SeqLM.from_pretrained("./Helsinki-NLP/opus-mt-zh-en")

tokenizer_back_translate = AutoTokenizer.from_pretrained("./Helsinki-NLP/opus-mt-en-zh")
model_back_translate = AutoModelForSeq2SeqLM.from_pretrained("./Helsinki-NLP/opus-mt-en-zh")

zh2en = pipeline("translation_zh_to_en", model=model, tokenizer=tokenizer)
en2zh = pipeline("translation_en_to_zh", model=model_back_translate, tokenizer=tokenizer_back_translate)
print("tran", zh2en(text[:5])[0]['translation_text'])
print("tran_back", en2zh(zh2en(text[:5])[0]['translation_text'], max_length=510)[0]['translation_text'])

2.逐步实现

batch = tokenizer.prepare_seq2seq_batch(src_texts=[text], return_tensors='pt', max_length=512)
# Perform the translation and decode the output
translation = model.generate(**batch)
result = tokenizer.batch_decode(translation, skip_special_tokens=True)
print("tran", result)
batch_back_translate = tokenizer_back_translate.prepare_seq2seq_batch(src_texts=result, return_tensors='pt', max_length=512)
# Perform the translation and decode the output
translation_back_translate = model_back_translate.generate(**batch_back_translate)
result = tokenizer_back_translate.batch_decode(translation_back_translate, skip_special_tokens=True)
print("tran_back", result)

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值