File size: 1,315 Bytes
5c5407c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
43
44
45
46
47
from collections import namedtuple
from functools import partial

import torch
from transformers import pipeline


def get_translator():
    return pipeline(
        "translation_en_to_ru",
        model="Helsinki-NLP/opus-mt-ru-en",
        device="cuda" if torch.cuda.is_available() else "cpu",
        torch_dtype="auto",
    )

class Input:
    def __init__(self, title, abstract, authors):
        self.title = title
        self.abstract = abstract
        self.authors = authors
    
class TranslationModel:
    def __init__(self, get_model):
        self.translator = get_translator()
        self.model = get_model()

    def __call__(self, input):
        def translate(text):
            if text is None or text.strip() == "":
                return ""
            text = str(text).strip()
            translated = self.translator(text)[0]['translation_text']
            return translated
        title = translate(input.title)
        abstract = translate(input.abstract)
        authors = translate(input.authors)
        out = self.model(Input(title, abstract, authors))
        return out


def create_translation_models(models):
    return {
        f"{name} (С помощью перевода)": partial(TranslationModel, get_model=get_model)
        for name, get_model in models.items()
    }