A simple example of implementing the Google Cloud Translation API for C #
Google.Cloud.Translation.V2 library must be installed into the project through the NuGet
public class TranslateServiceGoogle
{
public int MaxTextLenght => 4999;
private readonly string apiKey;
private TranslationClient _client;
private TranslationClient Client => _client ?? (_client = TranslationClient.CreateFromApiKey(apiKey));
public TranslateServiceGoogle(string apiKey)
{
this.apiKey = apiKey;
}
public string TranslateText(
string text,
string languageFrom,
string languageTo
)
{
if (string.IsNullOrWhiteSpace(text)) return "";
CheckTranslatebleText(text);
var res = Client.TranslateText(text, languageTo, languageFrom);
return res.TranslatedText;
}
public string TranslateHtml(
string text,
string languageFrom,
string languageTo
)
{
if (string.IsNullOrWhiteSpace(text))
return "";
CheckTranslatebleText(text);
var response = Client.TranslateHtml(text, languageTo, languageFrom);
return response.TranslatedText;
}
public void CheckTranslatebleText(string text)
{
if (text.Length > MaxTextLenght)
{
throw new ArgumentOutOfRangeException($"Text length exceeds ({text.Length} symbols)!");
}
}
}
Google.Cloud.Translation.V2 library must be installed into the project through the NuGet
public class TranslateServiceGoogle
{
public int MaxTextLenght => 4999;
private readonly string apiKey;
private TranslationClient _client;
private TranslationClient Client => _client ?? (_client = TranslationClient.CreateFromApiKey(apiKey));
public TranslateServiceGoogle(string apiKey)
{
this.apiKey = apiKey;
}
public string TranslateText(
string text,
string languageFrom,
string languageTo
)
{
if (string.IsNullOrWhiteSpace(text)) return "";
CheckTranslatebleText(text);
var res = Client.TranslateText(text, languageTo, languageFrom);
return res.TranslatedText;
}
public string TranslateHtml(
string text,
string languageFrom,
string languageTo
)
{
if (string.IsNullOrWhiteSpace(text))
return "";
CheckTranslatebleText(text);
var response = Client.TranslateHtml(text, languageTo, languageFrom);
return response.TranslatedText;
}
public void CheckTranslatebleText(string text)
{
if (text.Length > MaxTextLenght)
{
throw new ArgumentOutOfRangeException($"Text length exceeds ({text.Length} symbols)!");
}
}
}
Комментариев нет:
Отправить комментарий