File size: 1,437 Bytes
6add590 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
from deep_translator import GoogleTranslator
from transformers import pipeline
class MangaTranslator:
def __init__(self):
self.target = "en"
self.source = "ja"
def translate(self, text, method="google"):
"""
Translates the given text to the target language using the specified method.
Args:
text (str): The text to be translated.
method (str):'google' for Google Translator,
'hf' for Helsinki-NLP's opus-mt-ja-en model (HF pipeline)
Returns:
str: The translated text.
"""
if method == "hf":
return self._translate_with_hf(self._preprocess_text(text))
elif method == "google":
return self._translate_with_google(self._preprocess_text(text))
else:
raise ValueError("Invalid translation method.")
def _translate_with_google(self, text):
translator = GoogleTranslator(source=self.source, target=self.target)
translated_text = translator.translate(text)
return translated_text
def _translate_with_hf(self, text):
pipe = pipeline("translation", model=f"Helsinki-NLP/opus-mt-ja-en")
translated_text = pipe(text)[0]["translation_text"]
return translated_text
def _preprocess_text(self, text):
preprocessed_text = text.replace(".", ".")
return preprocessed_text
|