diff --git a/GoogleCode/GoogleTranslate/GoogleTranslate.cs b/GoogleCode/GoogleTranslate/GoogleTranslate.cs new file mode 100644 index 00000000..9d19e9c2 --- /dev/null +++ b/GoogleCode/GoogleTranslate/GoogleTranslate.cs @@ -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; + } + + /// + /// When true, the output from google is in human readable format. + /// Default: Not set, Google defaults to true + /// + public bool? PrettyPrint { get; set; } + + /// + /// 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 + /// + public bool? LargeQuery { get; set; } + + /// + /// 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. + /// + /// The language to translate from. Set it to Language.Automatic to let Google Translate determine the language. + /// The language to translate to. + /// The text to translate. You may input more than one text. + /// The translated text. + public List 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(request); + return results.Data.Translations; + } + + /// + /// Gives you a list of supported languages. + /// + /// When defined, gives you a list of languages that translates into the target language. + /// A list of supported languages + public List 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(request); + return results.Data.Languages; + } + + /// + /// 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. + /// + /// The text to use when detecting languages. + /// A list of languages that might be used in the text. + public List 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(request); + + //Flatten the results from Google Translate API + List detections = new List(); + foreach (List languageDetections in results.Data.Detections) + { + detections.AddRange(languageDetections); + } + + return detections; + } + + private void CheckRequest(IEnumerable 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(RestRequest request) + { + RestResponse response = (RestResponse)_client.Execute(request); + JsonDeserializer deserializer = new JsonDeserializer(); + T results = deserializer.Deserialize(response); + + //Try to deserialize it as an error - it is a hack since I'm using generics here. + ErrorResponse errorResponse = deserializer.Deserialize(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."; + } + } +} \ No newline at end of file diff --git a/GoogleCode/GoogleTranslate/Language.cs b/GoogleCode/GoogleTranslate/Language.cs new file mode 100644 index 00000000..264d3505 --- /dev/null +++ b/GoogleCode/GoogleTranslate/Language.cs @@ -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 + } +} \ No newline at end of file diff --git a/GoogleCode/GoogleTranslate/Misc/ExtensionMethods.cs b/GoogleCode/GoogleTranslate/Misc/ExtensionMethods.cs new file mode 100644 index 00000000..daa6203c --- /dev/null +++ b/GoogleCode/GoogleTranslate/Misc/ExtensionMethods.cs @@ -0,0 +1,32 @@ +using System; +using System.Reflection; + +namespace GoogleTranslateNET.Misc +{ + public static class ExtensionMethods + { + /// + /// 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 + /// + /// + /// + 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; + } + } +} \ No newline at end of file diff --git a/GoogleCode/GoogleTranslate/Misc/StringValueAttribute.cs b/GoogleCode/GoogleTranslate/Misc/StringValueAttribute.cs new file mode 100644 index 00000000..e1c39c00 --- /dev/null +++ b/GoogleCode/GoogleTranslate/Misc/StringValueAttribute.cs @@ -0,0 +1,18 @@ +using System; + +namespace GoogleTranslateNET.Misc +{ + /// + /// This attribute is used to represent a string value + /// for a value in an enum. + /// + public class StringValueAttribute : Attribute + { + public string StringValue { get; private set; } + + public StringValueAttribute(string value) + { + StringValue = value; + } + } +} \ No newline at end of file diff --git a/GoogleCode/GoogleTranslate/Objects/Error/Error.cs b/GoogleCode/GoogleTranslate/Objects/Error/Error.cs new file mode 100644 index 00000000..953dc0e5 --- /dev/null +++ b/GoogleCode/GoogleTranslate/Objects/Error/Error.cs @@ -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 Errors { get; set; } + } +} \ No newline at end of file diff --git a/GoogleCode/GoogleTranslate/Objects/Error/ErrorData.cs b/GoogleCode/GoogleTranslate/Objects/Error/ErrorData.cs new file mode 100644 index 00000000..2bafbec9 --- /dev/null +++ b/GoogleCode/GoogleTranslate/Objects/Error/ErrorData.cs @@ -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; } + } +} \ No newline at end of file diff --git a/GoogleCode/GoogleTranslate/Objects/Error/ErrorResponse.cs b/GoogleCode/GoogleTranslate/Objects/Error/ErrorResponse.cs new file mode 100644 index 00000000..df25034f --- /dev/null +++ b/GoogleCode/GoogleTranslate/Objects/Error/ErrorResponse.cs @@ -0,0 +1,7 @@ +namespace GoogleTranslateNET.Objects.Error +{ + public class ErrorResponse + { + public Error Error { get; set; } + } +} \ No newline at end of file diff --git a/GoogleCode/GoogleTranslate/Objects/LanguageDetection/LanguageDetection.cs b/GoogleCode/GoogleTranslate/Objects/LanguageDetection/LanguageDetection.cs new file mode 100644 index 00000000..82f094cf --- /dev/null +++ b/GoogleCode/GoogleTranslate/Objects/LanguageDetection/LanguageDetection.cs @@ -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; } + } +} \ No newline at end of file diff --git a/GoogleCode/GoogleTranslate/Objects/LanguageDetection/LanguageDetectionData.cs b/GoogleCode/GoogleTranslate/Objects/LanguageDetection/LanguageDetectionData.cs new file mode 100644 index 00000000..a8a7e256 --- /dev/null +++ b/GoogleCode/GoogleTranslate/Objects/LanguageDetection/LanguageDetectionData.cs @@ -0,0 +1,9 @@ +using System.Collections.Generic; + +namespace GoogleTranslateNET.Objects.LanguageDetection +{ + public class LanguageDetectionData + { + public List> Detections { get; set; } + } +} \ No newline at end of file diff --git a/GoogleCode/GoogleTranslate/Objects/LanguageDetection/LanguageDetectionResult.cs b/GoogleCode/GoogleTranslate/Objects/LanguageDetection/LanguageDetectionResult.cs new file mode 100644 index 00000000..8fa1528e --- /dev/null +++ b/GoogleCode/GoogleTranslate/Objects/LanguageDetection/LanguageDetectionResult.cs @@ -0,0 +1,7 @@ +namespace GoogleTranslateNET.Objects.LanguageDetection +{ + public class LanguageDetectionResult + { + public LanguageDetectionData Data { get; set; } + } +} \ No newline at end of file diff --git a/GoogleCode/GoogleTranslate/Objects/SupportedLanguages/SupportedLanguageData.cs b/GoogleCode/GoogleTranslate/Objects/SupportedLanguages/SupportedLanguageData.cs new file mode 100644 index 00000000..3cf16092 --- /dev/null +++ b/GoogleCode/GoogleTranslate/Objects/SupportedLanguages/SupportedLanguageData.cs @@ -0,0 +1,9 @@ +using System.Collections.Generic; + +namespace GoogleTranslateNET.Objects.SupportedLanguages +{ + public class SupportedLanguageData + { + public List Languages { get; set; } + } +} \ No newline at end of file diff --git a/GoogleCode/GoogleTranslate/Objects/SupportedLanguages/SupportedLanguageResult.cs b/GoogleCode/GoogleTranslate/Objects/SupportedLanguages/SupportedLanguageResult.cs new file mode 100644 index 00000000..165fae43 --- /dev/null +++ b/GoogleCode/GoogleTranslate/Objects/SupportedLanguages/SupportedLanguageResult.cs @@ -0,0 +1,7 @@ +namespace GoogleTranslateNET.Objects.SupportedLanguages +{ + public class SupportedLanguageResult + { + public SupportedLanguageData Data { get; set; } + } +} \ No newline at end of file diff --git a/GoogleCode/GoogleTranslate/Objects/SupportedLanguages/TranslationLanaguage.cs b/GoogleCode/GoogleTranslate/Objects/SupportedLanguages/TranslationLanaguage.cs new file mode 100644 index 00000000..5b01c8ce --- /dev/null +++ b/GoogleCode/GoogleTranslate/Objects/SupportedLanguages/TranslationLanaguage.cs @@ -0,0 +1,8 @@ +namespace GoogleTranslateNET.Objects.SupportedLanguages +{ + public class TranslationLanaguage + { + public string Language { get; set; } + public string Name { get; set; } + } +} \ No newline at end of file diff --git a/GoogleCode/GoogleTranslate/Objects/Translation/TranslateResult.cs b/GoogleCode/GoogleTranslate/Objects/Translation/TranslateResult.cs new file mode 100644 index 00000000..87e3803a --- /dev/null +++ b/GoogleCode/GoogleTranslate/Objects/Translation/TranslateResult.cs @@ -0,0 +1,7 @@ +namespace GoogleTranslateNET.Objects.Translation +{ + public class TranslateResult + { + public TranslationData Data { get; set; } + } +} \ No newline at end of file diff --git a/GoogleCode/GoogleTranslate/Objects/Translation/Translation.cs b/GoogleCode/GoogleTranslate/Objects/Translation/Translation.cs new file mode 100644 index 00000000..eaf47131 --- /dev/null +++ b/GoogleCode/GoogleTranslate/Objects/Translation/Translation.cs @@ -0,0 +1,8 @@ +namespace GoogleTranslateNET.Objects.Translation +{ + public class Translation + { + public string TranslatedText { get; set; } + public string DetectedSourceLanguage { get; set; } + } +} \ No newline at end of file diff --git a/GoogleCode/GoogleTranslate/Objects/Translation/TranslationData.cs b/GoogleCode/GoogleTranslate/Objects/Translation/TranslationData.cs new file mode 100644 index 00000000..4acaf545 --- /dev/null +++ b/GoogleCode/GoogleTranslate/Objects/Translation/TranslationData.cs @@ -0,0 +1,9 @@ +using System.Collections.Generic; + +namespace GoogleTranslateNET.Objects.Translation +{ + public class TranslationData + { + public List Translations { get; set; } + } +} \ No newline at end of file diff --git a/GoogleCode/GoogleTranslate/project.json b/GoogleCode/GoogleTranslate/project.json new file mode 100644 index 00000000..3393ac44 --- /dev/null +++ b/GoogleCode/GoogleTranslate/project.json @@ -0,0 +1,59 @@ +{ + "version": "1.0.5-*", + "title": "Yavsc Google Translate [DNX]", + "description": "Google Translate for DNX", + "authors": [ + "Paul Schneider " + ], + "packOptions": { + "repository": { + "type": "git", + "url": "https://github.com/pazof/yavsc" + }, + "licenseUrl": "https://github.com/pazof/yavsc/blob/vnext/LICENSE", + "requireLicenseAcceptance": true, + "owners": [ + "Paul Schneider " + ], + "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" + } + } + } +}