Ejemplo n.º 1
0
        public async Task <TranslationResult> TranslateAsync(TranslatorConfig cfg)
        {
            var apiToken = cfg.YandexTranslateToken;

            if (apiToken == null && cfg.YandexTranslateOAuthToken != null)
            {
                var yandexIamTokensApi = ApiFactory.CreateIamApi();
                apiToken = await yandexIamTokensApi.CreateToken(cfg.YandexTranslateOAuthToken);
            }

            if (string.IsNullOrEmpty(apiToken))
            {
                return(TranslationResult.FromError("Error: Yandex Translate api token is not provided."));
            }

            var api = ApiFactory.CreateTranslateApi(apiToken);

            var parser = new SubtitlesParser.Classes.Parsers.SrtParser();

            await using var fileStream = File.OpenRead(cfg.SourceFile);

            var items      = parser.ParseStream(fileStream, Encoding.Default);
            var allStrings = items.SelectMany(x => x.Lines).Distinct().ToList();

            var translations = new Dictionary <string, string>();

            foreach (var batch in allStrings.Batch(10))
            {
                var src = batch.ToList();
                try
                {
                    var translateResponse = await api.Translate(new TranslateRequest
                    {
                        folder_id          = cfg.YandexCloudFolderId,
                        targetLanguageCode = cfg.TargetLanguageCode,
                        texts = src
                    });

                    for (var i = 0; i < src.Count; i++)
                    {
                        var dst = translateResponse.Translations[i].Text;
                        dst = FixTags(dst);
                        translations.Add(src[i], dst);
                    }
                }
                catch (Exception exc)
                {
                    return(TranslationResult.FromError(exc.ToString()));
                }
            }

            var translation = SubtitlesToString(items, translations);

            return(TranslationResult.Ok(translation));
        }