Google translate API lib for DNX

This commit is contained in:
2018-12-11 09:15:16 +00:00
parent 8632f544b5
commit 4ea4d5b795
17 changed files with 525 additions and 0 deletions

View File

@ -0,0 +1,196 @@
using System;
using System.Collections.Generic;
using System.Text;
using GoogleTranslateNET.Misc;
using GoogleTranslateNET.Objects.Error;
using GoogleTranslateNET.Objects.LanguageDetection;
using GoogleTranslateNET.Objects.SupportedLanguages;
using GoogleTranslateNET.Objects.Translation;
using RestSharp;
using RestSharp.Deserializers;
using System.Linq;
namespace GoogleTranslateNET
{
public class GoogleTranslate
{
private string _key;
private static RestClient _client = new RestClient("https://www.googleapis.com/language/translate/v2");
public GoogleTranslate(string key)
{
if (string.IsNullOrEmpty(key))
throw new ArgumentException("Key is required.", "key");
_key = key;
}
/// <summary>
/// When true, the output from google is in human readable format.
/// Default: Not set, Google defaults to true
/// </summary>
public bool? PrettyPrint { get; set; }
/// <summary>
/// When true, queries will be sent using HTTP POST instead of GET.
/// GET queries have a limit of 2000 characters, POST queries have a limit of 5000 characters.
/// Default: Not set, Google defaults to false
/// </summary>
public bool? LargeQuery { get; set; }
/// <summary>
/// Translates a text from one language to another.
/// You can input multiple texts and get them translated all at once.
/// Warning: Setting source and destination languages to the same language will result in an error.
/// </summary>
/// <param name="sourceLanguage">The language to translate from. Set it to Language.Automatic to let Google Translate determine the language.</param>
/// <param name="destinationLanaguage">The language to translate to.</param>
/// <param name="text">The text to translate. You may input more than one text.</param>
/// <returns>The translated text.</returns>
public List<Translation> Translate(Language sourceLanguage, Language destinationLanaguage, params string[] text)
{
//https://www.googleapis.com/language/translate/v2?key=key&q=hello%20world&source=en&target=de
RestRequest request = CreateRequest(string.Empty);
CheckRequest(text);
//Required
foreach (string q in text)
{
request.AddParameter("q", q);
}
request.AddParameter("target", destinationLanaguage.GetStringValue());
//Optional
if (sourceLanguage != Language.Automatic)
request.AddParameter("source", sourceLanguage.GetStringValue());
//Output
TranslateResult results = GetResponse<TranslateResult>(request);
return results.Data.Translations;
}
/// <summary>
/// Gives you a list of supported languages.
/// </summary>
/// <param name="targetLanguage">When defined, gives you a list of languages that translates into the target language.</param>
/// <returns>A list of supported languages</returns>
public List<TranslationLanaguage> GetSupportedLanguages(Language targetLanguage = Language.Unknown)
{
//https://www.googleapis.com/language/translate/v2/languages?key=key&target=zh-TW
RestRequest request = CreateRequest("languages");
//Optional
if (targetLanguage != Language.Unknown)
request.AddParameter("target", targetLanguage.GetStringValue());
//Output
SupportedLanguageResult results = GetResponse<SupportedLanguageResult>(request);
return results.Data.Languages;
}
/// <summary>
/// Detects the languages that might be used in the text.
/// You can send more than one text in a single request to detect multiple texts.
/// </summary>
/// <param name="text">The text to use when detecting languages.</param>
/// <returns>A list of languages that might be used in the text.</returns>
public List<LanguageDetection> DetectLanguage(params string[] text)
{
//https://www.googleapis.com/language/translate/v2/detect?key=key&q=google+translate+is+fast
RestRequest request = CreateRequest("detect");
CheckRequest(text);
//Required
foreach (string q in text)
{
request.AddParameter("q", q);
}
//Output
LanguageDetectionResult results = GetResponse<LanguageDetectionResult>(request);
//Flatten the results from Google Translate API
List<LanguageDetection> detections = new List<LanguageDetection>();
foreach (List<LanguageDetection> languageDetections in results.Data.Detections)
{
detections.AddRange(languageDetections);
}
return detections;
}
private void CheckRequest(IEnumerable<string> requestContent)
{
//Compute the total size of the content
int sum = requestContent.Sum(item => item.Length);
if (((LargeQuery.HasValue && !LargeQuery.Value) || !LargeQuery.HasValue) && sum >= 2000)
{
throw new ArgumentException("Your text content is larger than 2000 characters. Set LargeQuery to 'true' to enable support up to 5000 characters.");
}
if (sum > 5000)
throw new ArgumentException("Your text content is larger than 5000 characters. Google Translate only allow up to 5000 characters");
}
private RestRequest CreateRequest(string function)
{
RestRequest request;
if (LargeQuery.HasValue && LargeQuery.Value)
{
request = new RestRequest(function, Method.POST);
//To use POST, you must use the X-HTTP-Method-Override header to tell the Translate API to treat the request as a GET (use X-HTTP-Method-Override: GET).
request.AddHeader("X-HTTP-Method-Override", "GET");
}
else
{
request = new RestRequest(function, Method.GET);
}
request.AddParameter("key", _key);
if (PrettyPrint.HasValue)
request.AddParameter("prettyprint", PrettyPrint.ToString().ToLower());
return request;
}
private T GetResponse<T>(RestRequest request)
{
RestResponse response = (RestResponse)_client.Execute(request);
JsonDeserializer deserializer = new JsonDeserializer();
T results = deserializer.Deserialize<T>(response);
//Try to deserialize it as an error - it is a hack since I'm using generics here.
ErrorResponse errorResponse = deserializer.Deserialize<ErrorResponse>(response);
if (errorResponse.Error != null)
throw new Exception(GetErrorText(errorResponse.Error));
return results;
}
private string GetErrorText(Error error)
{
if (error != null)
{
StringBuilder sb = new StringBuilder();
sb.Append(error.Message);
if (error.Errors.Count >= 1)
{
ErrorData errorData = error.Errors.First();
sb.Append("Reason: " + errorData.Reason);
}
return sb.ToString();
}
return "There was an error. Unable to determine the cause.";
}
}
}

View File

@ -0,0 +1,118 @@
using GoogleTranslateNET.Misc;
namespace GoogleTranslateNET
{
public enum Language
{
Unknown,
Automatic,
[StringValue("af")]
Afrikaans,
[StringValue("sq")]
Albanian,
[StringValue("ar")]
Arabic,
[StringValue("be")]
Belarusian,
[StringValue("bg")]
Bulgarian,
[StringValue("ca")]
Catalan,
[StringValue("zh")]
ChineseSimplified,
[StringValue("zh-TW")]
ChineseTraditional,
[StringValue("hr")]
Croatian,
[StringValue("cs")]
Czech,
[StringValue("da")]
Danish,
[StringValue("nl")]
Dutch,
[StringValue("en")]
English,
[StringValue("eo")]
Esperanto,
[StringValue("et")]
Estonian,
[StringValue("tl")]
Filipino,
[StringValue("fi")]
Finnish,
[StringValue("fr")]
French,
[StringValue("gl")]
Galician,
[StringValue("de")]
German,
[StringValue("el")]
Greek,
[StringValue("ht")]
HaitianCreole,
[StringValue("iw")]
Hebrew,
[StringValue("hi")]
Hindi,
[StringValue("hu")]
Hungarian,
[StringValue("is")]
Icelandic,
[StringValue("id")]
Indonesian,
[StringValue("ga")]
Irish,
[StringValue("it")]
Italian,
[StringValue("ja")]
Japanese,
[StringValue("ko")]
Korean,
[StringValue("lv")]
Latvian,
[StringValue("lt")]
Lithuanian,
[StringValue("mk")]
Macedonian,
[StringValue("ms")]
Malay,
[StringValue("mt")]
Maltese,
[StringValue("no")]
Norwegian,
[StringValue("fa")]
Persian,
[StringValue("pl")]
Polish,
[StringValue("pt")]
Portuguese,
[StringValue("ro")]
Romanian,
[StringValue("ru")]
Russian,
[StringValue("sr")]
Serbian,
[StringValue("sk")]
Slovak,
[StringValue("sl")]
Slovenian,
[StringValue("es")]
Spanish,
[StringValue("sw")]
Swahili,
[StringValue("sv")]
Swedish,
[StringValue("th")]
Thai,
[StringValue("tr")]
Turkish,
[StringValue("uk")]
Ukrainian,
[StringValue("vi")]
Vietnamese,
[StringValue("cy")]
Welsh,
[StringValue("yi")]
Yiddish
}
}

View File

@ -0,0 +1,32 @@
using System;
using System.Reflection;
namespace GoogleTranslateNET.Misc
{
public static class ExtensionMethods
{
/// <summary>
/// Will get the string value for a given enums value, this will
/// only work if you assign the StringValue attribute to
/// the items in your enum.
/// Source: http://weblogs.asp.net/stefansedich/archive/2008/03/12/enum-with-string-values-in-c.aspx
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static string GetStringValue(this Enum value)
{
// Get the type
Type type = value.GetType();
// Get fieldinfo for this type
FieldInfo fieldInfo = type.GetField(value.ToString());
// Get the stringvalue attributes
StringValueAttribute[] attribs = fieldInfo.GetCustomAttributes(
typeof(StringValueAttribute), false) as StringValueAttribute[];
// Return the first if there was a match.
return attribs.Length > 0 ? attribs[0].StringValue : null;
}
}
}

View File

@ -0,0 +1,18 @@
using System;
namespace GoogleTranslateNET.Misc
{
/// <summary>
/// This attribute is used to represent a string value
/// for a value in an enum.
/// </summary>
public class StringValueAttribute : Attribute
{
public string StringValue { get; private set; }
public StringValueAttribute(string value)
{
StringValue = value;
}
}
}

View File

@ -0,0 +1,11 @@
using System.Collections.Generic;
namespace GoogleTranslateNET.Objects.Error
{
public class Error
{
public int Code { get; set; }
public string Message { get; set; }
public List<ErrorData> Errors { get; set; }
}
}

View File

@ -0,0 +1,11 @@
namespace GoogleTranslateNET.Objects.Error
{
public class ErrorData
{
public string Domain { get; set; }
public string Reason { get; set; }
public string Message { get; set; }
public string LocationType { get; set; }
public string Location { get; set; }
}
}

View File

@ -0,0 +1,7 @@
namespace GoogleTranslateNET.Objects.Error
{
public class ErrorResponse
{
public Error Error { get; set; }
}
}

View File

@ -0,0 +1,9 @@
namespace GoogleTranslateNET.Objects.LanguageDetection
{
public class LanguageDetection
{
public string Language { get; set; }
public bool IsReliable { get; set; }
public float Confidence { get; set; }
}
}

View File

@ -0,0 +1,9 @@
using System.Collections.Generic;
namespace GoogleTranslateNET.Objects.LanguageDetection
{
public class LanguageDetectionData
{
public List<List<LanguageDetection>> Detections { get; set; }
}
}

View File

@ -0,0 +1,7 @@
namespace GoogleTranslateNET.Objects.LanguageDetection
{
public class LanguageDetectionResult
{
public LanguageDetectionData Data { get; set; }
}
}

View File

@ -0,0 +1,9 @@
using System.Collections.Generic;
namespace GoogleTranslateNET.Objects.SupportedLanguages
{
public class SupportedLanguageData
{
public List<TranslationLanaguage> Languages { get; set; }
}
}

View File

@ -0,0 +1,7 @@
namespace GoogleTranslateNET.Objects.SupportedLanguages
{
public class SupportedLanguageResult
{
public SupportedLanguageData Data { get; set; }
}
}

View File

@ -0,0 +1,8 @@
namespace GoogleTranslateNET.Objects.SupportedLanguages
{
public class TranslationLanaguage
{
public string Language { get; set; }
public string Name { get; set; }
}
}

View File

@ -0,0 +1,7 @@
namespace GoogleTranslateNET.Objects.Translation
{
public class TranslateResult
{
public TranslationData Data { get; set; }
}
}

View File

@ -0,0 +1,8 @@
namespace GoogleTranslateNET.Objects.Translation
{
public class Translation
{
public string TranslatedText { get; set; }
public string DetectedSourceLanguage { get; set; }
}
}

View File

@ -0,0 +1,9 @@
using System.Collections.Generic;
namespace GoogleTranslateNET.Objects.Translation
{
public class TranslationData
{
public List<Translation> Translations { get; set; }
}
}

View File

@ -0,0 +1,59 @@
{
"version": "1.0.5-*",
"title": "Yavsc Google Translate [DNX]",
"description": "Google Translate for DNX",
"authors": [
"Paul Schneider <paul@pschneider.fr>"
],
"packOptions": {
"repository": {
"type": "git",
"url": "https://github.com/pazof/yavsc"
},
"licenseUrl": "https://github.com/pazof/yavsc/blob/vnext/LICENSE",
"requireLicenseAcceptance": true,
"owners": [
"Paul Schneider <paul@pschneider.fr>"
],
"summary": "CSharp Google Tranlate API",
"projectUrl": "http://yavsc.pschneider.fr",
"tags": [
"Translation"
]
},
"tooling": {
"defaultNamespace": "Yavsc"
},
"dependencies": {
"Newtonsoft.Json": "9.0.1",
"Gapi.net45": "1.0.1",
"RestSharp": "103.4.0"
},
"frameworks": {
"dnx451": {
"frameworkAssemblies": {
"System.ComponentModel.DataAnnotations": "4.0.0"
}
},
"net46": {
"frameworkAssemblies": {
"System.ComponentModel.DataAnnotations": "4.0.0"
}
},
"net461": {
"frameworkAssemblies": {
"System.ComponentModel.DataAnnotations": "4.0.0"
}
},
"net452": {
"frameworkAssemblies": {
"System.ComponentModel.DataAnnotations": "4.0.0"
}
},
"net451": {
"frameworkAssemblies": {
"System.ComponentModel.DataAnnotations": "4.0.0"
}
}
}
}