translateBatch method
Translates multiple texts concurrently with proper throttling.
Automatically batches requests to respect rate limits and prevents overwhelming the translation API.
translations: Map of key-value pairs to translate.
targetLang: The target language code.
sourceLang: Optional source language code.
Returns a Future<Map<String, String>> with translated values.
Implementation
Future<Map<String, String>> translateBatch(
Map<String, String> translations,
String targetLang, {
String? sourceLang,
}) async {
_logger.info(
'Starting batch translation of ${translations.length} items to $targetLang',
);
final results = <String, String>{};
final entries = translations.entries.toList();
final batchSize = _config.maxConcurrentTranslations;
// Process in batches to respect rate limits
for (var i = 0; i < entries.length; i += batchSize) {
final batch = entries.skip(i).take(batchSize).toList();
_logger.progress(
'Translating batch ${(i ~/ batchSize) + 1} of ${(entries.length / batchSize).ceil()}',
);
final futures = batch.map((entry) async {
try {
final translated = await translateText(
entry.value,
targetLang,
sourceLang: sourceLang,
);
return MapEntry(entry.key, translated);
} catch (e) {
_logger.warning('Failed to translate "${entry.key}": $e');
return MapEntry(entry.key, entry.value); // Keep original on failure
}
});
final batchResults = await Future.wait(futures);
results.addEntries(batchResults);
}
_logger.success('Completed batch translation');
return results;
}