Если вам нужно качественно перефразировать фразу, можно использовать метод back-translation, переводим на английский, потом обратно на русский. Чтобы избежать повторения одной и той же фразы, модельный переводчик может запретить воспроизводить n-грамм (токен), найденные в оригинальном предложении.
Введенная фраза
Так же, как эта чашка, — сказал Нан-ин, — Вы полны Ваших собственных мнений и размышлений
Результат
Как и в этой чаше, сказал Нань Ин, вы полны собственных мыслей и желаний."
Сам код в colab
!nvidia-smi4
!pip install transformers
!pip install sacremoses
import torch
from transformers import FSMTModel, FSMTTokenizer, FSMTForConditionalGeneration
tokenizer = FSMTTokenizer.from_pretrained("facebook/wmt19-en-ru")
model = FSMTForConditionalGeneration.from_pretrained("facebook/wmt19-en-ru")
inverse_tokenizer = FSMTTokenizer.from_pretrained("facebook/wmt19-ru-en")
inverse_model = FSMTForConditionalGeneration.from_pretrained("facebook/wmt19-ru-en")
model.cuda();
inverse_model.cuda();
def paraphrase(text, gram=4, num_beams=5, **kwargs):
""" Generate a paraphrase using back translation.
Parameter `gram` denotes size of token n-grams of the original sentence that cannot appear in the paraphrase.
"""
input_ids = inverse_tokenizer.encode(text, return_tensors="pt")
with torch.no_grad():
outputs = inverse_model.generate(input_ids.to(inverse_model.device), num_beams=num_beams, **kwargs)
other_lang = inverse_tokenizer.decode(outputs[0], skip_special_tokens=True)
# print(other_lang)
input_ids = input_ids[0, :-1].tolist()
bad_word_ids = [input_ids[i:(i+gram)] for i in range(len(input_ids)-gram)]
input_ids = tokenizer.encode(other_lang, return_tensors="pt")
with torch.no_grad():
outputs = model.generate(input_ids.to(model.device), num_beams=num_beams, bad_words_ids=bad_word_ids, **kwargs)
decoded = tokenizer.decode(outputs[0], skip_special_tokens=True)
return decoded
text = input('Enter text:\n ')
print(paraphrase(text, gram=3, do_sample=False))
Закомментировав строки ниже, можно обойтись традиционным процессором вместо графической карты
#model.cuda();
#inverse_model.cuda();
Изучить этот код можно самостоятельно в colab
Используя данный код можно даже целые тексты перефразировать построчно. Нужно лишь добавить текстовый файл себе в проект и прописать в конце код:
import time
f = open("text.txt", "r", encoding='utf-8')
f2 = open("new_text_721.txt", "a", encoding='utf-8')
count = 0
for line in f:
try:
print(line)
print (paraphrase(line, gram=3, do_sample=False))
f2.write(paraphrase(line, gram=3, do_sample=False) + '\n')
time.sleep(0.5)
count += 1
print(count)
except:
print(line)
print (paraphrase(line, gram=3, do_sample=False))
f2.write(paraphrase(line, gram=3, do_sample=False) + '\n')
time.sleep(0.5)
count += 1
print(count)
f2.close()
print(count)
try и except добавлены, т.к. были замечены непредвиденные ошибки в выполнении, а счетчик count поможет определить на какой строке мы остановились