1 package translatortext 2 3 // Copyright (c) Microsoft Corporation. All rights reserved. 4 // Licensed under the MIT License. See License.txt in the project root for license information. 5 // 6 // Code generated by Microsoft (R) AutoRest Code Generator. 7 // Changes may cause incorrect behavior and will be lost if the code is regenerated. 8 9 import ( 10 "context" 11 "github.com/Azure/go-autorest/autorest" 12 "github.com/Azure/go-autorest/autorest/azure" 13 "github.com/Azure/go-autorest/autorest/validation" 14 "github.com/Azure/go-autorest/tracing" 15 "net/http" 16 ) 17 18 // TranslatorClient is the # Introduction 19 // 20 // The Microsoft Translator Text API provides a JSON-based Web API. It provides: 21 // 22 // * Translation between any supported languages to any other supported language. 23 // * Translation to multiple languages in one request. 24 // * Transliteration to convert text from one script to another script of the same language. 25 // * Language detection, translation, and transliteration in one request. 26 // * Dictionary to lookup alternative translations of a term, to find back-translations and examples showing terms used 27 // in context. 28 // * Rich language detection. 29 // # Base URLs 30 // 31 // The Translator Text API is available in the following clouds: 32 // 33 // | Description | Region | Base URL | 34 // | ------- | -------- | ------- | 35 // | Azure | Global | api.cognitive.microsofttranslator.com | 36 // | Azure | Europe | api-eur.cognitive.microsofttranslator.com | 37 // 38 // 39 // # Authentication 40 // 41 // Subscribe to the Translator Text API, part of Azure Cognitive Services, and use your subscription key from the Azure 42 // portal to authenticate. You can follow the steps in 43 // https://docs.microsoft.com/en-us/azure/cognitive-services/translator/translator-text-how-to-signup. 44 // 45 // 46 // The simplest way is to pass your Azure secret key to the Translator service using the http request header 47 // `Ocp-Apim-Subscription-Key`. 48 // 49 // If you prefer using a short-lived authentication, you may use your secret key to obtain an authorization token from 50 // the token service. In that case you pass the authorization token to the Translator service using the `Authorization` 51 // request header. To obtain an authorization token, make a `POST` request to the following URL: 52 // 53 // | Environment | Authentication service URL | 54 // | ---------- | ---------- | 55 // | Azure | `https://api.cognitive.microsoft.com/sts/v1.0/issueToken` | 56 // 57 // Here are example requests to obtain a token with a lifetime of 10 minutes, given a secret key: 58 // 59 // ```python 60 // // Pass secret key using header 61 // curl --header 'Ocp-Apim-Subscription-Key: <your-key>' --data "" 62 // 'https://api.cognitive.microsoft.com/sts/v1.0/issueToken' 63 // // Pass secret key using query string parameter 64 // curl --data "" 'https://api.cognitive.microsoft.com/sts/v1.0/issueToken?Subscription-Key=<your-key>' 65 // ``` 66 // 67 // A successful request returns the encoded access token as plain text in the response body. The valid token is passed 68 // to the Translator service as a bearer token in the Authorization. 69 // 70 // ``` 71 // Authorization: Bearer <Base64-access_token> 72 // ``` 73 // 74 // An authentication token is valid for 10 minutes. The token should be re-used when making multiple calls to the 75 // Translator APIs. If you make requests to the Translator API over an extended period of time, you must request a 76 // new access token at regular intervals before the token expires, for instance every 9 minutes. 77 // 78 // To summarize, a client request to the Translator API will include one authorization header taken from the following 79 // table: 80 // 81 // | Headers | Description | 82 // | ---------- | ---------- | 83 // | Ocp-Apim-Subscription-key | Use with Cognitive Services subscription if you are passing your secret key. 84 // The value is the Azure secret key for your subscription to Translator Text API. | 85 // | Authorization | Use with Cognitive Services subscription if you are passing an authentication 86 // token. The value is the Bearer token: `Bearer <token>`. | 87 // 88 // ## All-in-one subscription 89 // The last authentication option is to use a Cognitive Service’s all-in-one subscription. This allows you to use a 90 // single secret key to authenticate requests for multiple services. 91 // When you use an all-in-one secret key, you must include two authentication headers with your request. The first 92 // passes the secret key, the second specifies the region associated with your subscription. 93 // `Ocp-Api-Subscription-Key` `Ocp-Apim-Subscription-Region` 94 // If you pass the secret key in the query string with the parameter `Subscription-Key`, then you must specify the 95 // region with query parameter `Subscription-Region`. 96 // If you use a bearer token, you must obtain the token from the region endpoint: 97 // `https://<your-region>.api.cognitive.microsoft.com/sts/v1.0/issueToken`. 98 // 99 // Available regions are: `australiaeast`, `brazilsouth`, `canadacentral`, `centralindia`, `centraluseuap`, `eastasia`, 100 // `eastus`, `eastus2`, `japaneast`, `northeurope`, `southcentralus`, `southeastasia`, `uksouth`, `westcentralus`, 101 // `westeurope`, `westus`, and `westus2`. 102 // 103 // Region is required for the all-in-one Text API subscription. 104 // 105 // 106 // # Errors 107 // 108 // A standard error response is a JSON object with name/value pair named `error`. The value is also a JSON object with 109 // properties: 110 // * `code`: A server-defined error code. 111 // * `message`: A string giving a human-readable representation of the error. 112 // 113 // For example, a customer with a free trial subscription receives the following error once the free quota is 114 // exhausted: 115 // 116 // ```json 117 // { 118 // "error": { 119 // "code":403000, 120 // "message":"The subscription has exceeded its free quota." 121 // } 122 // } 123 // ``` 124 // # Enter your subscription keys to try out Microsoft Translator. 125 // Select the `Authorize` button and enter your Microsoft Translator subscription key, OR your `all in one Cognitive 126 // Services` subscription key. If you are using the all in one Cognitive Services key you will need to also enter your 127 // subscription region. 128 // ## Available regions are: 129 // 130 // `australiaeast`, `brazilsouth`, `canadacentral`, `centralindia`, `centraluseuap`, `eastasia`, `eastus`, `eastus2`, 131 // `japaneast`, `northeurope`, `southcentralus`, `southeastasia`, `uksouth`, `westcentralus`, `westeurope`, `westus`, 132 // `westus2`. 133 type TranslatorClient struct { 134 BaseClient 135 } 136 137 // NewTranslatorClient creates an instance of the TranslatorClient client. 138 func NewTranslatorClient(endpoint string) TranslatorClient { 139 return TranslatorClient{New(endpoint)} 140 } 141 142 // BreakSentence identifies the position of sentence boundaries in a piece of text. 143 // Parameters: 144 // textParameter - # Request Body 145 // The body of the request is a JSON array. Each array element is a JSON object with a string property named 146 // Text. Sentence boundaries are computed for the value of the Text property. 147 // 148 // The following limitations apply: 149 // * The array can have at most 100 elements. 150 // * The text value of an array element cannot exceed 10,000 characters including spaces. 151 // * The entire text included in the request cannot exceed 50,000 characters including spaces. 152 // * If the `language` query parameter is specified, then all array elements must be in the same language. 153 // Otherwise, language auto-detection is applied to each array element independently. 154 // 155 // # Response Body 156 // A successful response is a JSON array with one result for each string in the input array. A result object 157 // includes the following properties: 158 // * `sentLen`- An array of integers representing the lengths of the sentences in the text element. The length 159 // of the array is the number of sentences, and the values are the length of each sentence. 160 // * `detectedLanguage`- An object describing the detected language through the following properties 161 // * `language`- Code of the detected language. 162 // * `score`- A float value indicating the confidence in the result. The score is between zero and one and a 163 // low score indicates a low confidence. 164 // * Note that the `detectedLanguage` property is only present in the result object when language 165 // auto-detection is requested. 166 // # Response Header 167 // X-RequestId - Value generated by the service to identify the request. It is used for troubleshooting 168 // purposes. 169 // language - language tag of the language of the input text. If not specified, Translator will apply automatic 170 // language detection. 171 // script - script identifier of the script used by the input text. If a script is not specified, the default 172 // script of the language will be assumed. 173 // xClientTraceID - a client-generated GUID to uniquely identify the request. Note that you can omit this 174 // header if you include the trace ID in the query string using a query parameter named ClientTraceId. 175 func (client TranslatorClient) BreakSentence(ctx context.Context, textParameter []BreakSentenceTextInput, language string, script string, xClientTraceID string) (result ListBreakSentenceResultItem, err error) { 176 if tracing.IsEnabled() { 177 ctx = tracing.StartSpan(ctx, fqdn+"/TranslatorClient.BreakSentence") 178 defer func() { 179 sc := -1 180 if result.Response.Response != nil { 181 sc = result.Response.Response.StatusCode 182 } 183 tracing.EndSpan(ctx, sc, err) 184 }() 185 } 186 if err := validation.Validate([]validation.Validation{ 187 {TargetValue: textParameter, 188 Constraints: []validation.Constraint{{Target: "textParameter", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { 189 return result, validation.NewError("translatortext.TranslatorClient", "BreakSentence", err.Error()) 190 } 191 192 req, err := client.BreakSentencePreparer(ctx, textParameter, language, script, xClientTraceID) 193 if err != nil { 194 err = autorest.NewErrorWithError(err, "translatortext.TranslatorClient", "BreakSentence", nil, "Failure preparing request") 195 return 196 } 197 198 resp, err := client.BreakSentenceSender(req) 199 if err != nil { 200 result.Response = autorest.Response{Response: resp} 201 err = autorest.NewErrorWithError(err, "translatortext.TranslatorClient", "BreakSentence", resp, "Failure sending request") 202 return 203 } 204 205 result, err = client.BreakSentenceResponder(resp) 206 if err != nil { 207 err = autorest.NewErrorWithError(err, "translatortext.TranslatorClient", "BreakSentence", resp, "Failure responding to request") 208 return 209 } 210 211 return 212 } 213 214 // BreakSentencePreparer prepares the BreakSentence request. 215 func (client TranslatorClient) BreakSentencePreparer(ctx context.Context, textParameter []BreakSentenceTextInput, language string, script string, xClientTraceID string) (*http.Request, error) { 216 urlParameters := map[string]interface{}{ 217 "Endpoint": client.Endpoint, 218 } 219 220 const APIVersion = "3.0" 221 queryParameters := map[string]interface{}{ 222 "api-version": APIVersion, 223 } 224 if len(language) > 0 { 225 queryParameters["Language"] = autorest.Encode("query", language) 226 } 227 if len(script) > 0 { 228 queryParameters["Script"] = autorest.Encode("query", script) 229 } 230 231 preparer := autorest.CreatePreparer( 232 autorest.AsContentType("application/json; charset=utf-8"), 233 autorest.AsPost(), 234 autorest.WithCustomBaseURL("{Endpoint}", urlParameters), 235 autorest.WithPath("/BreakSentence"), 236 autorest.WithJSON(textParameter), 237 autorest.WithQueryParameters(queryParameters)) 238 if len(xClientTraceID) > 0 { 239 preparer = autorest.DecoratePreparer(preparer, 240 autorest.WithHeader("X-ClientTraceId", autorest.String(xClientTraceID))) 241 } 242 return preparer.Prepare((&http.Request{}).WithContext(ctx)) 243 } 244 245 // BreakSentenceSender sends the BreakSentence request. The method will close the 246 // http.Response Body if it receives an error. 247 func (client TranslatorClient) BreakSentenceSender(req *http.Request) (*http.Response, error) { 248 return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) 249 } 250 251 // BreakSentenceResponder handles the response to the BreakSentence request. The method always 252 // closes the http.Response Body. 253 func (client TranslatorClient) BreakSentenceResponder(resp *http.Response) (result ListBreakSentenceResultItem, err error) { 254 err = autorest.Respond( 255 resp, 256 azure.WithErrorUnlessStatusCode(http.StatusOK), 257 autorest.ByUnmarshallingJSON(&result.Value), 258 autorest.ByClosing()) 259 result.Response = autorest.Response{Response: resp} 260 return 261 } 262 263 // Detect identifies the language of a string of text. 264 // Parameters: 265 // textParameter - # Request Body 266 // The body of the request is a JSON array. Each array element is a JSON object with a string property named 267 // Text. Language detection is applied to the value of the Text property. 268 // The following limitations apply: 269 // * The array can have at most 100 elements. 270 // * The text value of an array element cannot exceed 10,000 characters including spaces. 271 // * The entire text included in the request cannot exceed 50,000 characters including spaces. 272 // 273 // # Response Body 274 // A successful response is a JSON array with one result for each string in the input array. A result object 275 // includes the following properties: 276 // * language- Code of the detected language. 277 // * score- A float value indicating the confidence in the result. The score is between zero and one and a low 278 // score indicates a low confidence. 279 // * isTranslationSupported- A boolean value which is true if the detected language is one of the languages 280 // supported for text translation. Not all detected languages can be translated by the API. 281 // * isTransliterationSupported- A boolean value which is true if the detected language is one of the languages 282 // supported for transliteration. 283 // * alternatives- An array of other possible languages. Each element of the array is another object with the 284 // same properties listed above- language, score, isTranslationSupported and isTransliterationSupported. 285 // # Response Header 286 // X-RequestId - Value generated by the service to identify the request. It is used for troubleshooting 287 // purposes. 288 // xClientTraceID - a client-generated GUID to uniquely identify the request. Note that you can omit this 289 // header if you include the trace ID in the query string using a query parameter named ClientTraceId. 290 func (client TranslatorClient) Detect(ctx context.Context, textParameter []DetectTextInput, xClientTraceID string) (result ListDetectResultItem, err error) { 291 if tracing.IsEnabled() { 292 ctx = tracing.StartSpan(ctx, fqdn+"/TranslatorClient.Detect") 293 defer func() { 294 sc := -1 295 if result.Response.Response != nil { 296 sc = result.Response.Response.StatusCode 297 } 298 tracing.EndSpan(ctx, sc, err) 299 }() 300 } 301 if err := validation.Validate([]validation.Validation{ 302 {TargetValue: textParameter, 303 Constraints: []validation.Constraint{{Target: "textParameter", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { 304 return result, validation.NewError("translatortext.TranslatorClient", "Detect", err.Error()) 305 } 306 307 req, err := client.DetectPreparer(ctx, textParameter, xClientTraceID) 308 if err != nil { 309 err = autorest.NewErrorWithError(err, "translatortext.TranslatorClient", "Detect", nil, "Failure preparing request") 310 return 311 } 312 313 resp, err := client.DetectSender(req) 314 if err != nil { 315 result.Response = autorest.Response{Response: resp} 316 err = autorest.NewErrorWithError(err, "translatortext.TranslatorClient", "Detect", resp, "Failure sending request") 317 return 318 } 319 320 result, err = client.DetectResponder(resp) 321 if err != nil { 322 err = autorest.NewErrorWithError(err, "translatortext.TranslatorClient", "Detect", resp, "Failure responding to request") 323 return 324 } 325 326 return 327 } 328 329 // DetectPreparer prepares the Detect request. 330 func (client TranslatorClient) DetectPreparer(ctx context.Context, textParameter []DetectTextInput, xClientTraceID string) (*http.Request, error) { 331 urlParameters := map[string]interface{}{ 332 "Endpoint": client.Endpoint, 333 } 334 335 const APIVersion = "3.0" 336 queryParameters := map[string]interface{}{ 337 "api-version": APIVersion, 338 } 339 340 preparer := autorest.CreatePreparer( 341 autorest.AsContentType("application/json; charset=utf-8"), 342 autorest.AsPost(), 343 autorest.WithCustomBaseURL("{Endpoint}", urlParameters), 344 autorest.WithPath("/Detect"), 345 autorest.WithJSON(textParameter), 346 autorest.WithQueryParameters(queryParameters)) 347 if len(xClientTraceID) > 0 { 348 preparer = autorest.DecoratePreparer(preparer, 349 autorest.WithHeader("X-ClientTraceId", autorest.String(xClientTraceID))) 350 } 351 return preparer.Prepare((&http.Request{}).WithContext(ctx)) 352 } 353 354 // DetectSender sends the Detect request. The method will close the 355 // http.Response Body if it receives an error. 356 func (client TranslatorClient) DetectSender(req *http.Request) (*http.Response, error) { 357 return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) 358 } 359 360 // DetectResponder handles the response to the Detect request. The method always 361 // closes the http.Response Body. 362 func (client TranslatorClient) DetectResponder(resp *http.Response) (result ListDetectResultItem, err error) { 363 err = autorest.Respond( 364 resp, 365 azure.WithErrorUnlessStatusCode(http.StatusOK), 366 autorest.ByUnmarshallingJSON(&result.Value), 367 autorest.ByClosing()) 368 result.Response = autorest.Response{Response: resp} 369 return 370 } 371 372 // DictionaryExamples provides examples that show how terms in the dictionary are used in context. This operation is 373 // used in tandem with `Dictionary lookup`. 374 // Parameters: 375 // from - specifies the language of the input text. The source language must be one of the supported languages 376 // included in the `dictionary` scope. 377 // toParameter - specifies the language of the output text. The target language must be one of the supported 378 // languages included in the `dictionary` scope. 379 // textParameter - # Request body 380 // The body of the request is a JSON array. Each array element is a JSON object with the following properties: 381 // * `Text-` A string specifying the term to lookup. This should be the value of a `normalizedText` field from 382 // the back-translations of a previous Dictionary lookup request. It can also be the value of the 383 // `normalizedSource` field. 384 // * `Translation-` A string specifying the translated text previously returned by the Dictionary lookup 385 // operation. This should be the value from the `normalizedTarget` field in the `translations` list of the 386 // Dictionary lookup response. The service will return examples for the specific source-target word-pair. 387 // 388 // The following limitations apply: 389 // * The array can have at most 10 elements. 390 // * The text value of an array element cannot exceed 100 characters including spaces. 391 // 392 // # Response body 393 // A successful response is a JSON array with one result for each string in the input array. A result object 394 // includes the following properties: 395 // * `normalizedSource-` A string giving the normalized form of the source term. Generally, this should be 396 // identical to the value of the `Text` field at the matching list index in the body of the request. 397 // * `normalizedTarget-` A string giving the normalized form of the target term. Generally, this should be 398 // identical to the value of the `Translation` field at the matching list index in the body of the request. 399 // * `examples-` A list of examples for the (source term, target term) pair. Each element of the list is an 400 // object with the following properties: 401 // * `sourcePrefix-` The string to concatenate before the value of `sourceTerm` to form a complete example. Do 402 // not add a space character, since it is already there when it should be. This value may be an empty string. 403 // * `sourceTerm-` A string equal to the actual term looked up. The string is added with `sourcePrefix` and 404 // `sourceSuffix` to form the complete example. Its value is separated so it can be marked in a user interface, 405 // e.g., by bolding it. 406 // * `sourceSuffix-` The string to concatenate after the value of `sourceTerm` to form a complete example. Do 407 // not add a space character, since it is already there when it should be. This value may be an empty string. 408 // * `targetPrefix-` A string similar to `sourcePrefix` but for the target. 409 // * `targetTerm-` A string similar to `sourceTerm` but for the target. 410 // * `targetSuffix-` A string similar to `sourceSuffix` but for the target. 411 // 412 // # Response Header 413 // X-RequestId - Value generated by the service to identify the request. It is used for troubleshooting 414 // purposes. 415 // NOTE - If there are no examples in the dictionary, the response is 200 (OK) but the `examples` list is an 416 // empty list. 417 // xClientTraceID - a client-generated GUID to uniquely identify the request. Note that you can omit this 418 // header if you include the trace ID in the query string using a query parameter named ClientTraceId. 419 func (client TranslatorClient) DictionaryExamples(ctx context.Context, from string, toParameter string, textParameter []DictionaryExampleTextInput, xClientTraceID string) (result ListDictionaryExampleResultItem, err error) { 420 if tracing.IsEnabled() { 421 ctx = tracing.StartSpan(ctx, fqdn+"/TranslatorClient.DictionaryExamples") 422 defer func() { 423 sc := -1 424 if result.Response.Response != nil { 425 sc = result.Response.Response.StatusCode 426 } 427 tracing.EndSpan(ctx, sc, err) 428 }() 429 } 430 if err := validation.Validate([]validation.Validation{ 431 {TargetValue: textParameter, 432 Constraints: []validation.Constraint{{Target: "textParameter", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { 433 return result, validation.NewError("translatortext.TranslatorClient", "DictionaryExamples", err.Error()) 434 } 435 436 req, err := client.DictionaryExamplesPreparer(ctx, from, toParameter, textParameter, xClientTraceID) 437 if err != nil { 438 err = autorest.NewErrorWithError(err, "translatortext.TranslatorClient", "DictionaryExamples", nil, "Failure preparing request") 439 return 440 } 441 442 resp, err := client.DictionaryExamplesSender(req) 443 if err != nil { 444 result.Response = autorest.Response{Response: resp} 445 err = autorest.NewErrorWithError(err, "translatortext.TranslatorClient", "DictionaryExamples", resp, "Failure sending request") 446 return 447 } 448 449 result, err = client.DictionaryExamplesResponder(resp) 450 if err != nil { 451 err = autorest.NewErrorWithError(err, "translatortext.TranslatorClient", "DictionaryExamples", resp, "Failure responding to request") 452 return 453 } 454 455 return 456 } 457 458 // DictionaryExamplesPreparer prepares the DictionaryExamples request. 459 func (client TranslatorClient) DictionaryExamplesPreparer(ctx context.Context, from string, toParameter string, textParameter []DictionaryExampleTextInput, xClientTraceID string) (*http.Request, error) { 460 urlParameters := map[string]interface{}{ 461 "Endpoint": client.Endpoint, 462 } 463 464 const APIVersion = "3.0" 465 queryParameters := map[string]interface{}{ 466 "api-version": APIVersion, 467 "from": autorest.Encode("query", from), 468 "to": autorest.Encode("query", toParameter), 469 } 470 471 preparer := autorest.CreatePreparer( 472 autorest.AsContentType("application/json; charset=utf-8"), 473 autorest.AsPost(), 474 autorest.WithCustomBaseURL("{Endpoint}", urlParameters), 475 autorest.WithPath("/Dictionary/Examples"), 476 autorest.WithJSON(textParameter), 477 autorest.WithQueryParameters(queryParameters)) 478 if len(xClientTraceID) > 0 { 479 preparer = autorest.DecoratePreparer(preparer, 480 autorest.WithHeader("X-ClientTraceId", autorest.String(xClientTraceID))) 481 } 482 return preparer.Prepare((&http.Request{}).WithContext(ctx)) 483 } 484 485 // DictionaryExamplesSender sends the DictionaryExamples request. The method will close the 486 // http.Response Body if it receives an error. 487 func (client TranslatorClient) DictionaryExamplesSender(req *http.Request) (*http.Response, error) { 488 return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) 489 } 490 491 // DictionaryExamplesResponder handles the response to the DictionaryExamples request. The method always 492 // closes the http.Response Body. 493 func (client TranslatorClient) DictionaryExamplesResponder(resp *http.Response) (result ListDictionaryExampleResultItem, err error) { 494 err = autorest.Respond( 495 resp, 496 azure.WithErrorUnlessStatusCode(http.StatusOK), 497 autorest.ByUnmarshallingJSON(&result.Value), 498 autorest.ByClosing()) 499 result.Response = autorest.Response{Response: resp} 500 return 501 } 502 503 // DictionaryLookup provides alternative translations for a word and a small number of idiomatic phrases. Each 504 // translation has a `part-of-speech` and a list of `back-translations`. The back-translations enable a user to 505 // understand the translation in context. The Dictionary Example operation allows further drill down to see example 506 // uses of each translation pair. 507 // Parameters: 508 // from - specifies the language of the input text. The source language must be one of the supported languages 509 // included in the `dictionary` scope. 510 // toParameter - specifies the language of the output text. The target language must be one of the supported 511 // languages included in the `dictionary` scope of the Languages resource. 512 // textParameter - # Request Body 513 // The body of the request is a JSON array. Each array element is a JSON object with a string property named 514 // `Text`, which represents the term to lookup. 515 // The following limitations apply: 516 // * The array can have at most 10 elements. 517 // * The text value of an array element cannot exceed 100 characters including spaces. 518 // 519 // # Response Body 520 // A successful response is a JSON array with one result for each string in the input array. A result object 521 // includes the following properties: 522 // * `normalizedSource`- A string giving the normalized form of the source term. For example, if the request is 523 // "JOHN", the normalized form will be "john". The content of this field becomes the input to lookup examples. 524 // * `displaySource`- A string giving the source term in a form best suited for end-user display. For example, 525 // if the input is "JOHN", the display form will reflect the usual spelling of the name- "John". 526 // * `translations`- A list of translations for the source term. Each element of the list is an object with the 527 // following properties: 528 // * `normalizedTarget`- A string giving the normalized form of this term in the target language. This value 529 // should be used as input to lookup examples. 530 // * `displayTarget`- A string giving the term in the target language and in a form best suited for end-user 531 // display. Generally, this will only differ from the `normalizedTarget` in terms of capitalization. For 532 // example, a proper noun like "Juan" will have `normalizedTarget = "juan"` and `displayTarget = "Juan"`. 533 // * `posTag`- A string associating this term with a part-of-speech tag. 534 // 535 // | Tag name | Description | 536 // | --------- | ---------------- | 537 // | ADJ | Adjectives | 538 // | ADV | Adverbs | 539 // | CONJ | Conjunctions | 540 // | DET | Determiners | 541 // | MODAL | Verbs | 542 // | NOUN | Nouns | 543 // | PREP | Prepositions | 544 // | PRON | Pronouns | 545 // | VERB | Verbs | 546 // | OTHER | Other | 547 // 548 // As an implementation note, these tags were determined by part-of-speech tagging the English side, and then 549 // taking the most frequent tag for each source/target pair. So if people frequently translate a Spanish word 550 // to a different part-of-speech tag in English, tags may end up being wrong (with respect to the Spanish 551 // word). 552 // * `confidence`- A value between 0.0 and 1.0 which represents the "confidence" (or perhaps more accurately, 553 // "probability in the training data") of that translation pair. The sum of confidence scores for one source 554 // word may or may not sum to 1.0. 555 // * `prefixWord-` A string giving the word to display as a prefix of the translation. Currently, this is the 556 // gendered determiner of nouns, in languages that have gendered determiners. For example, the prefix of the 557 // Spanish word "mosca" is "la", since "mosca" is a feminine noun in Spanish. This is only dependent on the 558 // translation, and not on the source. If there is no prefix, it will be the empty string. 559 // * `backTranslations-` A list of "back translations" of the target. For example, source words that the target 560 // can translate to. The list is guaranteed to contain the source word that was requested (e.g., if the source 561 // word being looked up is "fly", then it is guaranteed that "fly" will be in the `backTranslations` list). 562 // However, it is not guaranteed to be in the first position, and often will not be. Each element of the 563 // `backTranslations` list is an object described by the following properties- 564 // * `normalizedText-` A string giving the normalized form of the source term that is a back-translation of the 565 // target. This value should be used as input to lookup examples. 566 // * `displayText-` A string giving the source term that is a back-translation of the target in a form best 567 // suited for end-user display. 568 // * `numExamples-` An integer representing the number of examples that are available for this translation 569 // pair. Actual examples must be retrieved with a separate call to lookup examples. The number is mostly 570 // intended to facilitate display in a UX. For example, a user interface may add a hyperlink to the 571 // back-translation if the number of examples is greater than zero and show the back-translation as plain text 572 // if there are no examples. Note that the actual number of examples returned by a call to lookup examples may 573 // be less than `numExamples`, because additional filtering may be applied on the fly to remove "bad" examples. 574 // * `frequencyCount-` An integer representing the frequency of this translation pair in the data. The main 575 // purpose of this field is to provide a user interface with a means to sort back-translations so the most 576 // frequent terms are first. 577 // 578 // Note - If the term being looked up does not exist in the dictionary, the response is 200 (OK) but the 579 // `translations` list is an empty list. 580 // 581 // # Response Header 582 // X-RequestId - Value generated by the service to identify the request. It is used for troubleshooting 583 // purposes. 584 // xClientTraceID - a client-generated GUID to uniquely identify the request. Note that you can omit this 585 // header if you include the trace ID in the query string using a query parameter named ClientTraceId. 586 func (client TranslatorClient) DictionaryLookup(ctx context.Context, from string, toParameter string, textParameter []DictionaryLookupTextInput, xClientTraceID string) (result ListDictionaryLookupResultItem, err error) { 587 if tracing.IsEnabled() { 588 ctx = tracing.StartSpan(ctx, fqdn+"/TranslatorClient.DictionaryLookup") 589 defer func() { 590 sc := -1 591 if result.Response.Response != nil { 592 sc = result.Response.Response.StatusCode 593 } 594 tracing.EndSpan(ctx, sc, err) 595 }() 596 } 597 if err := validation.Validate([]validation.Validation{ 598 {TargetValue: textParameter, 599 Constraints: []validation.Constraint{{Target: "textParameter", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { 600 return result, validation.NewError("translatortext.TranslatorClient", "DictionaryLookup", err.Error()) 601 } 602 603 req, err := client.DictionaryLookupPreparer(ctx, from, toParameter, textParameter, xClientTraceID) 604 if err != nil { 605 err = autorest.NewErrorWithError(err, "translatortext.TranslatorClient", "DictionaryLookup", nil, "Failure preparing request") 606 return 607 } 608 609 resp, err := client.DictionaryLookupSender(req) 610 if err != nil { 611 result.Response = autorest.Response{Response: resp} 612 err = autorest.NewErrorWithError(err, "translatortext.TranslatorClient", "DictionaryLookup", resp, "Failure sending request") 613 return 614 } 615 616 result, err = client.DictionaryLookupResponder(resp) 617 if err != nil { 618 err = autorest.NewErrorWithError(err, "translatortext.TranslatorClient", "DictionaryLookup", resp, "Failure responding to request") 619 return 620 } 621 622 return 623 } 624 625 // DictionaryLookupPreparer prepares the DictionaryLookup request. 626 func (client TranslatorClient) DictionaryLookupPreparer(ctx context.Context, from string, toParameter string, textParameter []DictionaryLookupTextInput, xClientTraceID string) (*http.Request, error) { 627 urlParameters := map[string]interface{}{ 628 "Endpoint": client.Endpoint, 629 } 630 631 const APIVersion = "3.0" 632 queryParameters := map[string]interface{}{ 633 "api-version": APIVersion, 634 "from": autorest.Encode("query", from), 635 "to": autorest.Encode("query", toParameter), 636 } 637 638 preparer := autorest.CreatePreparer( 639 autorest.AsContentType("application/json; charset=utf-8"), 640 autorest.AsPost(), 641 autorest.WithCustomBaseURL("{Endpoint}", urlParameters), 642 autorest.WithPath("/Dictionary/Lookup"), 643 autorest.WithJSON(textParameter), 644 autorest.WithQueryParameters(queryParameters)) 645 if len(xClientTraceID) > 0 { 646 preparer = autorest.DecoratePreparer(preparer, 647 autorest.WithHeader("X-ClientTraceId", autorest.String(xClientTraceID))) 648 } 649 return preparer.Prepare((&http.Request{}).WithContext(ctx)) 650 } 651 652 // DictionaryLookupSender sends the DictionaryLookup request. The method will close the 653 // http.Response Body if it receives an error. 654 func (client TranslatorClient) DictionaryLookupSender(req *http.Request) (*http.Response, error) { 655 return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) 656 } 657 658 // DictionaryLookupResponder handles the response to the DictionaryLookup request. The method always 659 // closes the http.Response Body. 660 func (client TranslatorClient) DictionaryLookupResponder(resp *http.Response) (result ListDictionaryLookupResultItem, err error) { 661 err = autorest.Respond( 662 resp, 663 azure.WithErrorUnlessStatusCode(http.StatusOK), 664 autorest.ByUnmarshallingJSON(&result.Value), 665 autorest.ByClosing()) 666 result.Response = autorest.Response{Response: resp} 667 return 668 } 669 670 // Languages gets the set of languages currently supported by other operations of the Translator Text API. 671 // **Authentication is not required to get language resources.** 672 // 673 // # Response Body 674 // A client uses the `scope` query parameter to define which groups of languages it is interested in. 675 // * `scope=translation` provides languages supported to translate text from one language to another language. 676 // * `scope=transliteration` provides capabilities for converting text in one language from one script to another 677 // script. 678 // * `scope=dictionary` provides language pairs for which `Dictionary` operations return data. 679 // 680 // A client may retrieve several groups simultaneously by specifying a comma-separated list of names. For example, 681 // `scope=translation,transliteration,dictionary` would return supported languages for all groups. 682 // 683 // A successful response is a JSON object with one property for each requested group. 684 // The value for each property is as follows. 685 // 686 // * `translation` property 687 // The value of the `translation` property is a dictionary of (key, value) pairs. Each key is a BCP 47 language tag. A 688 // key identifies a language for which text can be translated to or translated from. The value associated with the key 689 // is a JSON object with properties that describe the language 690 // * `name-` Display name of the language in the locale requested via `Accept-Language` header. 691 // * `nativeName-` Display name of the language in the locale native for this language. 692 // * `dir-` Directionality, which is `rtl` for right-to-left languages or `ltr` for left-to-right languages. 693 // ```json 694 // { 695 // "translation": { 696 // ... 697 // "fr": { 698 // "name": "French", 699 // "nativeName": "Français", 700 // "dir": "ltr" 701 // }, 702 // ... 703 // } 704 // } 705 // ``` 706 // * `transliteration` property 707 // The value of the `transliteration` property is a dictionary of (key, value) pairs. Each key is a BCP 47 language 708 // tag. A key identifies a language for which text can be converted from one script to another script. The value 709 // associated with the key is a JSON object with properties that describe the language and its supported scripts 710 // * `name-` Display name of the language in the locale requested via `Accept-Language` header. 711 // * `nativeName-` Display name of the language in the locale native for this language. 712 // * `scripts-` List of scripts to convert from. Each element of the `scripts` list has properties- 713 // * `code-` Code identifying the script. 714 // * `name-` Display name of the script in the locale requested via `Accept-Language` header. 715 // * `nativeName-` Display name of the language in the locale native for the language. 716 // * `dir-` Directionality, which is `rtl` for right-to-left languages or `ltr` for left-to-right languages. 717 // * `toScripts-` List of scripts available to convert text to. Each element of the `toScripts` list has properties 718 // `code`, `name`, `nativeName`, and `dir` as described earlier. 719 // 720 // ```json 721 // { 722 // "transliteration": { 723 // ... 724 // "ja": { 725 // "name": "Japanese", 726 // "nativeName": "日本語", 727 // "scripts": [ 728 // { 729 // "code": "Jpan", 730 // "name": "Japanese", 731 // "nativeName": "日本語", 732 // "dir": "ltr", 733 // "toScripts": [ 734 // { 735 // "code": "Latn", 736 // "name": "Latin", 737 // "nativeName": "ラテン語", 738 // "dir": "ltr" 739 // } 740 // ] 741 // }, 742 // { 743 // "code": "Latn", 744 // "name": "Latin", 745 // "nativeName": "ラテン語", 746 // "dir": "ltr", 747 // "toScripts": [ 748 // { 749 // "code": "Jpan", 750 // "name": "Japanese", 751 // "nativeName": "日本語", 752 // "dir": "ltr" 753 // } 754 // ] 755 // } 756 // ] 757 // }, 758 // ... 759 // } 760 // } 761 // 762 // ``` 763 // * `dictionary` property 764 // The value of the `dictionary` property is a dictionary of (key, value) pairs. Each key is a BCP 47 language tag. The 765 // key identifies a language for which alternative translations and back-translations are available. The value is a 766 // JSON object that describes the source language and the target languages with available translations. 767 // * `name-` Display name of the source language in the locale requested via `Accept-Language` header. 768 // * `nativeName-` Display name of the language in the locale native for this language. 769 // * `dir-` Directionality, which is `rtl` for right-to-left languages or `ltr` for left-to-right languages. 770 // * `translations-` List of languages with alterative translations and examples for the query expressed in the source 771 // language. Each element of the `translations` list has properties 772 // * `name-` Display name of the target language in the locale requested via `Accept-Language` header. 773 // * `nativeName-` Display name of the target language in the locale native for the target language. 774 // * `dir-` Directionality, which is `rtl` for right-to-left languages or `ltr` for left-to-right languages. 775 // * `code-` Language code identifying the target language. 776 // 777 // ```json 778 // 779 // "es": { 780 // "name": "Spanish", 781 // "nativeName": "Español", 782 // "dir": "ltr", 783 // "translations": [ 784 // { 785 // "name": "English", 786 // "nativeName": "English", 787 // "dir": "ltr", 788 // "code": "en" 789 // } 790 // ] 791 // }, 792 // 793 // ``` 794 // 795 // The structure of the response object will not change without a change in the version of the API. For the same 796 // version of the API, the list of available languages may change over time because Microsoft Translator continually 797 // extends the list of languages supported by its services. 798 // 799 // The list of supported languages will not change frequently. To save network bandwidth and improve responsiveness, a 800 // client application should consider caching language resources and the corresponding entity tag (`ETag`). Then, the 801 // client application can periodically (for example, once every 24 hours) query the service to fetch the latest set of 802 // supported languages. Passing the current `ETag` value in an `If-None-Match` header field will allow the service to 803 // optimize the response. If the resource has not been modified, the service will return status code 304 and an empty 804 // response body. 805 // 806 // # Response Header 807 // ETag - Current value of the entity tag for the requested groups of supported languages. To make subsequent requests 808 // more efficient, the client may send the `ETag` value in an `If-None-Match` header field. 809 // 810 // X-RequestId - Value generated by the service to identify the request. It is used for troubleshooting purposes. 811 // Parameters: 812 // scope - a comma-separated list of names defining the group of languages to return. Allowed group names are- 813 // `translation`, `transliteration` and `dictionary`. If no scope is given, then all groups are returned, which 814 // is equivalent to passing `scope=translation,transliteration,dictionary`. To decide which set of supported 815 // languages is appropriate for your scenario, see the description of the response object. 816 // acceptLanguage - the language to use for user interface strings. Some of the fields in the response are 817 // names of languages or names of regions. Use this parameter to define the language in which these names are 818 // returned. The language is specified by providing a well-formed BCP 47 language tag. For instance, use the 819 // value `fr` to request names in French or use the value `zh-Hant` to request names in Chinese Traditional. 820 // Names are provided in the English language when a target language is not specified or when localization is 821 // not available. 822 // xClientTraceID - a client-generated GUID to uniquely identify the request. Note that you can omit this 823 // header if you include the trace ID in the query string using a query parameter named ClientTraceId. 824 func (client TranslatorClient) Languages(ctx context.Context, scope []string, acceptLanguage string, xClientTraceID string) (result LanguagesResult, err error) { 825 if tracing.IsEnabled() { 826 ctx = tracing.StartSpan(ctx, fqdn+"/TranslatorClient.Languages") 827 defer func() { 828 sc := -1 829 if result.Response.Response != nil { 830 sc = result.Response.Response.StatusCode 831 } 832 tracing.EndSpan(ctx, sc, err) 833 }() 834 } 835 if err := validation.Validate([]validation.Validation{ 836 {TargetValue: scope, 837 Constraints: []validation.Constraint{{Target: "scope", Name: validation.Null, Rule: false, 838 Chain: []validation.Constraint{{Target: "scope", Name: validation.MaxItems, Rule: 3, Chain: nil}, 839 {Target: "scope", Name: validation.MinItems, Rule: 0, Chain: nil}, 840 }}}}}); err != nil { 841 return result, validation.NewError("translatortext.TranslatorClient", "Languages", err.Error()) 842 } 843 844 req, err := client.LanguagesPreparer(ctx, scope, acceptLanguage, xClientTraceID) 845 if err != nil { 846 err = autorest.NewErrorWithError(err, "translatortext.TranslatorClient", "Languages", nil, "Failure preparing request") 847 return 848 } 849 850 resp, err := client.LanguagesSender(req) 851 if err != nil { 852 result.Response = autorest.Response{Response: resp} 853 err = autorest.NewErrorWithError(err, "translatortext.TranslatorClient", "Languages", resp, "Failure sending request") 854 return 855 } 856 857 result, err = client.LanguagesResponder(resp) 858 if err != nil { 859 err = autorest.NewErrorWithError(err, "translatortext.TranslatorClient", "Languages", resp, "Failure responding to request") 860 return 861 } 862 863 return 864 } 865 866 // LanguagesPreparer prepares the Languages request. 867 func (client TranslatorClient) LanguagesPreparer(ctx context.Context, scope []string, acceptLanguage string, xClientTraceID string) (*http.Request, error) { 868 urlParameters := map[string]interface{}{ 869 "Endpoint": client.Endpoint, 870 } 871 872 const APIVersion = "3.0" 873 queryParameters := map[string]interface{}{ 874 "api-version": APIVersion, 875 } 876 if scope != nil && len(scope) > 0 { 877 queryParameters["scope"] = autorest.Encode("query", scope, ",") 878 } 879 880 preparer := autorest.CreatePreparer( 881 autorest.AsGet(), 882 autorest.WithCustomBaseURL("{Endpoint}", urlParameters), 883 autorest.WithPath("/Languages"), 884 autorest.WithQueryParameters(queryParameters)) 885 if len(acceptLanguage) > 0 { 886 preparer = autorest.DecoratePreparer(preparer, 887 autorest.WithHeader("Accept-Language", autorest.String(acceptLanguage))) 888 } 889 if len(xClientTraceID) > 0 { 890 preparer = autorest.DecoratePreparer(preparer, 891 autorest.WithHeader("X-ClientTraceId", autorest.String(xClientTraceID))) 892 } 893 return preparer.Prepare((&http.Request{}).WithContext(ctx)) 894 } 895 896 // LanguagesSender sends the Languages request. The method will close the 897 // http.Response Body if it receives an error. 898 func (client TranslatorClient) LanguagesSender(req *http.Request) (*http.Response, error) { 899 return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) 900 } 901 902 // LanguagesResponder handles the response to the Languages request. The method always 903 // closes the http.Response Body. 904 func (client TranslatorClient) LanguagesResponder(resp *http.Response) (result LanguagesResult, err error) { 905 err = autorest.Respond( 906 resp, 907 azure.WithErrorUnlessStatusCode(http.StatusOK), 908 autorest.ByUnmarshallingJSON(&result), 909 autorest.ByClosing()) 910 result.Response = autorest.Response{Response: resp} 911 return 912 } 913 914 // Translate translates text into one or more languages. 915 // Parameters: 916 // toParameter - specifies the language of the output text. Find which languages are available to translate to 917 // by using the languages method. For example, use `to=de` to translate to German. 918 // It's possible to translate to multiple languages simultaneously by repeating the `to` parameter in the query 919 // string. For example, use `to=de&to=it` to translate to German and Italian in the same request. 920 // textParameter - # Request body 921 // The body of the request is a JSON array. Each array element is a JSON object with a string property named 922 // `Text`, which represents the string to translate. 923 // The following limitations apply: 924 // * The array can have at most 25 elements. 925 // * The entire text included in the request cannot exceed 5,000 characters including spaces. 926 // # Response body 927 // A successful response is a JSON array with one result for each string in the input array. A result object 928 // includes the following properties- 929 // * `detectedLanguage`- An object describing the detected language through the following properties. 930 // * `language`- A string representing the code of the detected language. 931 // * `score`- A float value indicating the confidence in the result. The score is between zero and one and a 932 // low score indicates a low confidence. 933 // The `detectedLanguage` property is only present in the result object when language auto-detection is 934 // requested. 935 // * `translations`- An array of translation results. The size of the array matches the number of target 936 // languages specified in the `to` query parameter. Each element in the array includes. 937 // * `to` A string representing the language code of the target language. 938 // * `text`- A string giving the translated text. 939 // * `transliteration`- An object giving the translated text in the script specified by the `toScript` 940 // parameter. 941 // * `script`- A string specifying the target script. 942 // * `text`- A string giving the translated text in the target script. 943 // The `transliteration` object is not included if transliteration does not take place. 944 // *`alignment`- An object with a single string property named `proj`, which maps input text to translated 945 // text. The alignment information is only provided when the request parameter `includeAlignment` is `true`. 946 // Alignment is returned as a string value of the following format- 947 // `[[SourceTextStartIndex]-[SourceTextEndIndex]–[TgtTextStartIndex]-[TgtTextEndIndex]]`. The colon separates 948 // start and end index, the dash separates the languages, and space separates the words. One word may align 949 // with zero, one, or multiple words in the other language, and the aligned words may be non-contiguous. When 950 // no alignment information is available, the alignment element will be empty. See Obtain alignment information 951 // for an example and restrictions. 952 // * `sentLen`- An object returning sentence boundaries in the input and output texts. 953 // * `srcSentLen`- An integer array representing the lengths of the sentences in the input text. The length of 954 // the array is the number of sentences, and the values are the length of each sentence. 955 // * `transSentLen`- An integer array representing the lengths of the sentences in the translated text. The 956 // length of the array is the number of sentences, and the values are the length of each sentence. 957 // Sentence boundaries are only included when the request parameter `includeSentenceLength` is `true`. 958 // * `sourceText`- An object with a single string property named `text`, which gives the input text in the 959 // default script of the source language. `sourceText` property is present only when the input is expressed in 960 // a script that's not the usual script for the language. For example, if the input were Arabic written in 961 // Latin script, then `sourceText.text` would be the same Arabic text converted into Arab script. 962 // Example of JSON responses are provided in the examples section. 963 // from - specifies the language of the input text. Find which languages are available to translate from by 964 // using the languages method. If the `from` parameter is not specified, automatic language detection is 965 // applied to determine the source language. 966 // textType - defines whether the text being translated is plain text or HTML text. Any HTML needs to be a 967 // well-formed, complete HTML element. Possible values are `plain` (default) or `html` 968 // category - a string specifying the category (domain) of the translation. This parameter retrieves 969 // translations from a customized system built with Custom Translator. Default value is `general`. 970 // profanityAction - specifies how profanities should be treated in translations. Possible values are: 971 // `NoAction` (default), `Marked` or `Deleted`. 972 // ### Handling Profanity 973 // Normally the Translator service will retain profanity that is present in the source in the translation. The 974 // degree of profanity and the context that makes words profane differ between cultures, and as a result the 975 // degree of profanity in the target language may be amplified or reduced. 976 // 977 // If you want to avoid getting profanity in the translation, regardless of the presence of profanity in the 978 // source text, you can use the profanity filtering option. The option allows you to choose whether you want to 979 // see profanity deleted, whether you want to mark profanities with appropriate tags (giving you the option to 980 // add your own post-processing), or you want no action taken. The accepted values of `ProfanityAction` are 981 // `Deleted`, `Marked` and `NoAction` (default). 982 // 983 // | ProfanityAction | Action | 984 // | ---------- | ---------- | 985 // | `NoAction` | This is the default behavior. Profanity will pass from source to target. | 986 // | | Example Source (Japanese)- 彼はジャッカスです。 | 987 // | | Example Translation (English)- He is a jackass. | 988 // | | | 989 // | `Deleted` | Profane words will be removed from the output without replacement. | 990 // | | Example Source (Japanese)- 彼はジャッカスです。 | 991 // | | Example Translation (English)- He is a. | 992 // | `Marked` | Profane words are replaced by a marker in the output. The marker depends on the 993 // `ProfanityMarker` parameter. 994 // | | For `ProfanityMarker=Asterisk`, profane words are replaced with `***` | 995 // | | Example Source (Japanese)- 彼はジャッカスです。 | 996 // | | Example Translation (English)- He is a ***. | 997 // | | For `ProfanityMarker=Tag`, profane words are surrounded by XML tags <profanity> and 998 // </profanity> 999 // | | Example Source (Japanese)- 彼はジャッカスです。 | 1000 // | | Example Translation (English)- He is a <profanity>jackass</profanity>. 1001 // profanityMarker - specifies how profanities should be marked in translations. Possible values are- 1002 // `Asterisk` (default) or `Tag`. 1003 // includeAlignment - specifies whether to include alignment projection from source text to translated text. 1004 // Possible values are- `true` or `false` (default). 1005 // includeSentenceLength - specifies whether to include sentence boundaries for the input text and the 1006 // translated text. Possible values are- `true` or `false` (default). 1007 // suggestedFrom - specifies a fallback language if the language of the input text can't be identified. 1008 // Language auto-detection is applied when the `from` parameter is omitted. If detection fails, the 1009 // `suggestedFrom` language will be assumed. 1010 // fromScript - specifies the script of the input text. Supported scripts are available from the languages 1011 // method 1012 // toScript - specifies the script of the translated text. Supported scripts are available from the languages 1013 // method 1014 // xClientTraceID - a client-generated GUID to uniquely identify the request. Note that you can omit this 1015 // header if you include the trace ID in the query string using a query parameter named ClientTraceId. 1016 func (client TranslatorClient) Translate(ctx context.Context, toParameter []string, textParameter []TranslateTextInput, from string, textType string, category string, profanityAction string, profanityMarker string, includeAlignment *bool, includeSentenceLength *bool, suggestedFrom string, fromScript string, toScript []string, xClientTraceID string) (result ListTranslateResultAllItem, err error) { 1017 if tracing.IsEnabled() { 1018 ctx = tracing.StartSpan(ctx, fqdn+"/TranslatorClient.Translate") 1019 defer func() { 1020 sc := -1 1021 if result.Response.Response != nil { 1022 sc = result.Response.Response.StatusCode 1023 } 1024 tracing.EndSpan(ctx, sc, err) 1025 }() 1026 } 1027 if err := validation.Validate([]validation.Validation{ 1028 {TargetValue: toParameter, 1029 Constraints: []validation.Constraint{{Target: "toParameter", Name: validation.Null, Rule: true, Chain: nil}}}, 1030 {TargetValue: textParameter, 1031 Constraints: []validation.Constraint{{Target: "textParameter", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { 1032 return result, validation.NewError("translatortext.TranslatorClient", "Translate", err.Error()) 1033 } 1034 1035 req, err := client.TranslatePreparer(ctx, toParameter, textParameter, from, textType, category, profanityAction, profanityMarker, includeAlignment, includeSentenceLength, suggestedFrom, fromScript, toScript, xClientTraceID) 1036 if err != nil { 1037 err = autorest.NewErrorWithError(err, "translatortext.TranslatorClient", "Translate", nil, "Failure preparing request") 1038 return 1039 } 1040 1041 resp, err := client.TranslateSender(req) 1042 if err != nil { 1043 result.Response = autorest.Response{Response: resp} 1044 err = autorest.NewErrorWithError(err, "translatortext.TranslatorClient", "Translate", resp, "Failure sending request") 1045 return 1046 } 1047 1048 result, err = client.TranslateResponder(resp) 1049 if err != nil { 1050 err = autorest.NewErrorWithError(err, "translatortext.TranslatorClient", "Translate", resp, "Failure responding to request") 1051 return 1052 } 1053 1054 return 1055 } 1056 1057 // TranslatePreparer prepares the Translate request. 1058 func (client TranslatorClient) TranslatePreparer(ctx context.Context, toParameter []string, textParameter []TranslateTextInput, from string, textType string, category string, profanityAction string, profanityMarker string, includeAlignment *bool, includeSentenceLength *bool, suggestedFrom string, fromScript string, toScript []string, xClientTraceID string) (*http.Request, error) { 1059 urlParameters := map[string]interface{}{ 1060 "Endpoint": client.Endpoint, 1061 } 1062 1063 const APIVersion = "3.0" 1064 queryParameters := map[string]interface{}{ 1065 "api-version": APIVersion, 1066 "to": autorest.Encode("query", toParameter, ","), 1067 } 1068 if len(from) > 0 { 1069 queryParameters["from"] = autorest.Encode("query", from) 1070 } 1071 if len(string(textType)) > 0 { 1072 queryParameters["textType"] = autorest.Encode("query", textType) 1073 } 1074 if len(category) > 0 { 1075 queryParameters["category"] = autorest.Encode("query", category) 1076 } 1077 if len(string(profanityAction)) > 0 { 1078 queryParameters["profanityAction"] = autorest.Encode("query", profanityAction) 1079 } 1080 if len(profanityMarker) > 0 { 1081 queryParameters["profanityMarker"] = autorest.Encode("query", profanityMarker) 1082 } 1083 if includeAlignment != nil { 1084 queryParameters["includeAlignment"] = autorest.Encode("query", *includeAlignment) 1085 } 1086 if includeSentenceLength != nil { 1087 queryParameters["includeSentenceLength"] = autorest.Encode("query", *includeSentenceLength) 1088 } 1089 if len(suggestedFrom) > 0 { 1090 queryParameters["suggestedFrom"] = autorest.Encode("query", suggestedFrom) 1091 } 1092 if len(fromScript) > 0 { 1093 queryParameters["fromScript"] = autorest.Encode("query", fromScript) 1094 } 1095 if toScript != nil && len(toScript) > 0 { 1096 queryParameters["toScript"] = autorest.Encode("query", toScript, ",") 1097 } 1098 1099 preparer := autorest.CreatePreparer( 1100 autorest.AsContentType("application/json; charset=utf-8"), 1101 autorest.AsPost(), 1102 autorest.WithCustomBaseURL("{Endpoint}", urlParameters), 1103 autorest.WithPath("/translate"), 1104 autorest.WithJSON(textParameter), 1105 autorest.WithQueryParameters(queryParameters)) 1106 if len(xClientTraceID) > 0 { 1107 preparer = autorest.DecoratePreparer(preparer, 1108 autorest.WithHeader("X-ClientTraceId", autorest.String(xClientTraceID))) 1109 } 1110 return preparer.Prepare((&http.Request{}).WithContext(ctx)) 1111 } 1112 1113 // TranslateSender sends the Translate request. The method will close the 1114 // http.Response Body if it receives an error. 1115 func (client TranslatorClient) TranslateSender(req *http.Request) (*http.Response, error) { 1116 return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) 1117 } 1118 1119 // TranslateResponder handles the response to the Translate request. The method always 1120 // closes the http.Response Body. 1121 func (client TranslatorClient) TranslateResponder(resp *http.Response) (result ListTranslateResultAllItem, err error) { 1122 err = autorest.Respond( 1123 resp, 1124 azure.WithErrorUnlessStatusCode(http.StatusOK), 1125 autorest.ByUnmarshallingJSON(&result.Value), 1126 autorest.ByClosing()) 1127 result.Response = autorest.Response{Response: resp} 1128 return 1129 } 1130 1131 // Transliterate converts the text of a language in one script into another type of script. Example- 1132 // Japanese script "こんにちは" 1133 // Same word in Latin script "konnichiha" 1134 // Parameters: 1135 // language - specifies the language of the text to convert from one script to another. Possible languages are 1136 // listed in the `transliteration` scope obtained by querying the service for its supported languages. 1137 // fromScript - specifies the script used by the input text. Lookup supported languages using the 1138 // `transliteration` scope, to find input scripts available for the selected language. 1139 // toScript - specifies the output script. Lookup supported languages using the `transliteration` scope, to 1140 // find output scripts available for the selected combination of input language and input script. 1141 // texts - # Request body 1142 // The body of the request is a JSON array. Each array element is a JSON object with a string property named 1143 // `Text`, which represents the string to convert. 1144 // The following limitations apply: 1145 // * The array can have at most 10 elements. 1146 // * The text value of an array element cannot exceed 1,000 characters including spaces. 1147 // * The entire text included in the request cannot exceed 5,000 characters including spaces. 1148 // 1149 // # Response body 1150 // A successful response is a JSON array with one result for each element in the input array. A result object 1151 // includes the following properties: 1152 // * `text`- A string which is the result of converting the input string to the output script. 1153 // * `script`- A string specifying the script used in the output. 1154 // xClientTraceID - a client-generated GUID to uniquely identify the request. Note that you can omit this 1155 // header if you include the trace ID in the query string using a query parameter named ClientTraceId. 1156 func (client TranslatorClient) Transliterate(ctx context.Context, language string, fromScript string, toScript string, texts []TransliterateTextInput, xClientTraceID string) (result ListTransliterateResultItem, err error) { 1157 if tracing.IsEnabled() { 1158 ctx = tracing.StartSpan(ctx, fqdn+"/TranslatorClient.Transliterate") 1159 defer func() { 1160 sc := -1 1161 if result.Response.Response != nil { 1162 sc = result.Response.Response.StatusCode 1163 } 1164 tracing.EndSpan(ctx, sc, err) 1165 }() 1166 } 1167 if err := validation.Validate([]validation.Validation{ 1168 {TargetValue: texts, 1169 Constraints: []validation.Constraint{{Target: "texts", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { 1170 return result, validation.NewError("translatortext.TranslatorClient", "Transliterate", err.Error()) 1171 } 1172 1173 req, err := client.TransliteratePreparer(ctx, language, fromScript, toScript, texts, xClientTraceID) 1174 if err != nil { 1175 err = autorest.NewErrorWithError(err, "translatortext.TranslatorClient", "Transliterate", nil, "Failure preparing request") 1176 return 1177 } 1178 1179 resp, err := client.TransliterateSender(req) 1180 if err != nil { 1181 result.Response = autorest.Response{Response: resp} 1182 err = autorest.NewErrorWithError(err, "translatortext.TranslatorClient", "Transliterate", resp, "Failure sending request") 1183 return 1184 } 1185 1186 result, err = client.TransliterateResponder(resp) 1187 if err != nil { 1188 err = autorest.NewErrorWithError(err, "translatortext.TranslatorClient", "Transliterate", resp, "Failure responding to request") 1189 return 1190 } 1191 1192 return 1193 } 1194 1195 // TransliteratePreparer prepares the Transliterate request. 1196 func (client TranslatorClient) TransliteratePreparer(ctx context.Context, language string, fromScript string, toScript string, texts []TransliterateTextInput, xClientTraceID string) (*http.Request, error) { 1197 urlParameters := map[string]interface{}{ 1198 "Endpoint": client.Endpoint, 1199 } 1200 1201 const APIVersion = "3.0" 1202 queryParameters := map[string]interface{}{ 1203 "api-version": APIVersion, 1204 "fromScript": autorest.Encode("query", fromScript), 1205 "language": autorest.Encode("query", language), 1206 "toScript": autorest.Encode("query", toScript), 1207 } 1208 1209 preparer := autorest.CreatePreparer( 1210 autorest.AsContentType("application/json; charset=utf-8"), 1211 autorest.AsPost(), 1212 autorest.WithCustomBaseURL("{Endpoint}", urlParameters), 1213 autorest.WithPath("/transliterate"), 1214 autorest.WithJSON(texts), 1215 autorest.WithQueryParameters(queryParameters)) 1216 if len(xClientTraceID) > 0 { 1217 preparer = autorest.DecoratePreparer(preparer, 1218 autorest.WithHeader("X-ClientTraceId", autorest.String(xClientTraceID))) 1219 } 1220 return preparer.Prepare((&http.Request{}).WithContext(ctx)) 1221 } 1222 1223 // TransliterateSender sends the Transliterate request. The method will close the 1224 // http.Response Body if it receives an error. 1225 func (client TranslatorClient) TransliterateSender(req *http.Request) (*http.Response, error) { 1226 return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) 1227 } 1228 1229 // TransliterateResponder handles the response to the Transliterate request. The method always 1230 // closes the http.Response Body. 1231 func (client TranslatorClient) TransliterateResponder(resp *http.Response) (result ListTransliterateResultItem, err error) { 1232 err = autorest.Respond( 1233 resp, 1234 azure.WithErrorUnlessStatusCode(http.StatusOK), 1235 autorest.ByUnmarshallingJSON(&result.Value), 1236 autorest.ByClosing()) 1237 result.Response = autorest.Response{Response: resp} 1238 return 1239 } 1240