|
| 1 | +from batchalign.models import WhisperFAModel |
| 2 | +from batchalign.document import * |
| 3 | +from batchalign.pipelines.base import * |
| 4 | +from batchalign.utils import * |
| 5 | +from batchalign.utils.dp import * |
| 6 | +from batchalign.constants import * |
| 7 | + |
| 8 | +from transformers import AutoProcessor, SeamlessM4TModel |
| 9 | + |
| 10 | +import logging |
| 11 | +L = logging.getLogger("batchalign") |
| 12 | + |
| 13 | +import re |
| 14 | + |
| 15 | +# !uv pip install sentencepiece |
| 16 | + |
| 17 | +import pycountry |
| 18 | +import warnings |
| 19 | + |
| 20 | +class SeamlessTranslationModel(BatchalignEngine): |
| 21 | + tasks = [ Task.TRANSLATE ] |
| 22 | + |
| 23 | + def _hook_status(self, status_hook): |
| 24 | + self.status_hook = status_hook |
| 25 | + |
| 26 | + def __init__(self): |
| 27 | + self.status_hook = None |
| 28 | + self.processor = AutoProcessor.from_pretrained("facebook/hf-seamless-m4t-medium") |
| 29 | + self.model = SeamlessM4TModel.from_pretrained("facebook/hf-seamless-m4t-medium") |
| 30 | + |
| 31 | + def process(self, doc:Document, **kwargs): |
| 32 | + |
| 33 | + for indx, i in enumerate(doc.content): |
| 34 | + if not isinstance(i, Utterance): |
| 35 | + continue |
| 36 | + if i.translation: |
| 37 | + continue |
| 38 | + |
| 39 | + text = i.strip(join_with_spaces=False, include_retrace=True, include_fp=True) |
| 40 | + text_inputs = self.processor(text=text, src_lang=doc.langs[0] if doc.langs[0] != "zho" else "cmn", return_tensors="pt") |
| 41 | + output_tokens = self.model.generate(**text_inputs, tgt_lang="eng", generate_speech=False) |
| 42 | + translated_text_from_text = self.processor.decode(output_tokens[0].tolist()[0], skip_special_tokens=True) |
| 43 | + |
| 44 | + i.translation = translated_text_from_text |
| 45 | + for j in MOR_PUNCT + ENDING_PUNCT: |
| 46 | + i.translation = i.translation.replace(j, " "+j) |
| 47 | + |
| 48 | + if self.status_hook != None: |
| 49 | + self.status_hook(indx+1, len(doc.content)) |
| 50 | + |
| 51 | + return doc |
| 52 | + |
| 53 | + |
0 commit comments