LibJF/libjf-translate-v1/src/main/java/io/gitlab/jfronny/libjf/translate/api/TranslateService.java

86 lines
3.2 KiB
Java

package io.gitlab.jfronny.libjf.translate.api;
import io.gitlab.jfronny.libjf.LibJf;
import io.gitlab.jfronny.libjf.translate.impl.TranslateConfig;
import io.gitlab.jfronny.libjf.translate.impl.google.GoogleTranslateService;
import io.gitlab.jfronny.libjf.translate.impl.libretranslate.LibreTranslateService;
import io.gitlab.jfronny.libjf.translate.impl.noop.NoopTranslateService;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.LinkedList;
import java.util.List;
public interface TranslateService<T extends Language> {
/**
* Returns the TranslateService the user configured. Implementations may change without notice.
* @return configured translation service
*/
static TranslateService<?> getConfigured() {
return getAvailable().stream()
.filter(svc -> svc.getName().equals(TranslateConfig.translationService))
.findFirst()
.orElseGet(() -> {
LibJf.LOGGER.error("Falling back to NOOP translate service");
return NoopTranslateService.INSTANCE;
});
}
/**
* Returns all available TranslateServices. Please use getConfigured() instead where possible.
* @return available services
*/
static List<TranslateService<?>> getAvailable() {
List<TranslateService<?>> result = new LinkedList<>();
try {
result.add(GoogleTranslateService.get());
} catch (URISyntaxException | IOException e) {
LibJf.LOGGER.error("Could not create Google Translate service", e);
}
try {
result.add(LibreTranslateService.get(TranslateConfig.libreTranslateHost));
} catch (TranslateException e) {
LibJf.LOGGER.error("Could not create LibreTranslate service", e);
}
if (result.isEmpty()) result.add(NoopTranslateService.INSTANCE);
return List.copyOf(result);
}
/**
* Translates a string from the specified source language (or null to auto-detect) to the target language.
* @param textToTranslate text to translate
* @param translateFrom language to translate from. Use parseLang("auto") to detect automatically.
* @param translateTo language to translate to. Use parseLang() to get a language by its ID
* @return translated text
* @throws TranslateException Something went wrong during the translation
*/
String translate(String textToTranslate, T translateFrom, T translateTo) throws TranslateException;
/**
* Detects the language used in the specified string. May return "auto" if detection is unavailable.
* @param text The text of which to detect the language
* @return detected language
* @throws TranslateException Something went wrong during the detection
*/
T detect(String text) throws TranslateException;
/**
* Gets the language for the specified ID
* @param lang the ID
* @return language for the specified ID or null
*/
T parseLang(String lang);
/**
* Get all available languages for the configured service.
* @return available languages
*/
List<T> getAvailableLanguages();
/**
* Get the name of this translate service.
* @return name
*/
String getName();
}