translateBulk method

  1. @override
Future<List<Translation>> translateBulk(
  1. List<String> sources,
  2. LanguageCode sourceLanguage,
  3. List<LanguageCode> targets
)
override

Translates given texts to specified languages sources - list of texts which should be translated sourceLanguage - the language in which sources were given targets - list of languages to which sources should be translated

Implementation

@override
Future<List<Translation>> translateBulk(
  List<String> sources,
  LanguageCode sourceLanguage,
  List<LanguageCode> targets,
) async {
  logger.info(
      'Translate bulk "$sources" from $sourceLanguage to multiple $targets');

  final targetsQueryParam = targets.map((x) => 'to=$x').join('&');
  final apiResult = await _httpClient.post<List<_AzureTranslation>>(
    path: 'translate?api-version=3.0&from=$sourceLanguage&$targetsQueryParam',
    decoder: (response) => _decodeJson(response.body),
    headers: {
      'Content-Type': 'application/json',
    },
    body: sources.map((x) => {'Text': x}).toList(),
  );

  if (!apiResult.succeeded) {
    logger.warning('Translation failed');

    return sources
        .map((x) => Translation(
              source: x,
              sourceLanguage: sourceLanguage,
              translations: targets.map((y) => MapEntry(x, y)).toMap(),
            ))
        .toList();
  }

  int i = 0;
  List<Translation> result = [];

  for (final translation in apiResult.valueUnsafe) {
    Map<LanguageCode, String> translations = {};

    for (final translationItem in translation.translations) {
      translations[translationItem.to] = translationItem.text;
    }

    result.add(Translation(
      source: sources[i],
      sourceLanguage: sourceLanguage,
      translations: translations,
    ));

    i++;
  }

  return result;
}