...

Source file src/github.com/Azure/azure-sdk-for-go/services/preview/cognitiveservices/v1.0/visualsearch/images.go

Documentation: github.com/Azure/azure-sdk-for-go/services/preview/cognitiveservices/v1.0/visualsearch

     1  package visualsearch
     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/tracing"
    14  	"io"
    15  	"net/http"
    16  )
    17  
    18  // ImagesClient is the visual Search API lets you discover insights about an image such as visually similar images,
    19  // shopping sources, and related searches. The API can also perform text recognition, identify entities (people,
    20  // places, things), return other topical content for the user to explore, and more. For more information, see [Visual
    21  // Search Overview](https://docs.microsoft.com/azure/cognitive-services/bing-visual-search/overview).  **NOTE:** To
    22  // comply with the new EU Copyright Directive in France, the Bing Visual Search API must omit some content from certain
    23  // EU News sources for French users. The removed content may include thumbnail images and videos, video previews, and
    24  // snippets which accompany search results from these sources. As a consequence, the Bing APIs may serve fewer results
    25  // with thumbnail images and videos, video previews, and snippets to French users.
    26  type ImagesClient struct {
    27  	BaseClient
    28  }
    29  
    30  // NewImagesClient creates an instance of the ImagesClient client.
    31  func NewImagesClient() ImagesClient {
    32  	return ImagesClient{New()}
    33  }
    34  
    35  // VisualSearch sends the visual search request.
    36  // Parameters:
    37  // acceptLanguage - a comma-delimited list of one or more languages to use for user interface strings. The list
    38  // is in decreasing order of preference. For additional information, including expected format, see
    39  // [RFC2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). This header and the
    40  // [setLang](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-visual-search-api-v7-reference#setlang)
    41  // query parameter are mutually exclusive; do not specify both. If you set this header, you must also specify
    42  // the [cc](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-visual-search-api-v7-reference#cc)
    43  // query parameter. To determine the market to return results for, Bing uses the first supported language it
    44  // finds from the list and combines it with the cc parameter value. If the list does not include a supported
    45  // language, Bing finds the closest language and market that supports the request or it uses an aggregated or
    46  // default market for the results. To determine the market that Bing used, see the BingAPIs-Market header. Use
    47  // this header and the cc query parameter only if you specify multiple languages. Otherwise, use the
    48  // [mkt](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-visual-search-api-v7-reference#mkt)
    49  // and
    50  // [setLang](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-visual-search-api-v7-reference#setlang)
    51  // query parameters. A user interface string is a string that's used as a label in a user interface. There are
    52  // few user interface strings in the JSON response objects. Any links to Bing.com properties in the response
    53  // objects apply the specified language.
    54  // contentType - must be set to multipart/form-data and include a boundary parameter (for example,
    55  // multipart/form-data; boundary=<boundary string>). For more details, see [Content form types](
    56  // https://docs.microsoft.com/en-us/azure/cognitive-services/bing-visual-search/overview#content-form-types).
    57  // userAgent - the user agent originating the request. Bing uses the user agent to provide mobile users with an
    58  // optimized experience. Although optional, you are encouraged to always specify this header. The user-agent
    59  // should be the same string that any commonly used browser sends. For information about user agents, see [RFC
    60  // 2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). The following are examples of user-agent
    61  // strings. Windows Phone: Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0;
    62  // ARM; Touch; NOKIA; Lumia 822). Android: Mozilla / 5.0 (Linux; U; Android 2.3.5; en - us; SCH - I500 Build /
    63  // GINGERBREAD) AppleWebKit / 533.1 (KHTML; like Gecko) Version / 4.0 Mobile Safari / 533.1. iPhone: Mozilla /
    64  // 5.0 (iPhone; CPU iPhone OS 6_1 like Mac OS X) AppleWebKit / 536.26 (KHTML; like Gecko) Mobile / 10B142
    65  // iPhone4; 1 BingWeb / 3.03.1428.20120423. PC: Mozilla / 5.0 (Windows NT 6.3; WOW64; Trident / 7.0; Touch;
    66  // rv:11.0) like Gecko. iPad: Mozilla / 5.0 (iPad; CPU OS 7_0 like Mac OS X) AppleWebKit / 537.51.1 (KHTML,
    67  // like Gecko) Version / 7.0 Mobile / 11A465 Safari / 9537.53.
    68  // clientID - bing uses this header to provide users with consistent behavior across Bing API calls. Bing often
    69  // flights new features and improvements, and it uses the client ID as a key for assigning traffic on different
    70  // flights. If you do not use the same client ID for a user across multiple requests, then Bing may assign the
    71  // user to multiple conflicting flights. Being assigned to multiple conflicting flights can lead to an
    72  // inconsistent user experience. For example, if the second request has a different flight assignment than the
    73  // first, the experience may be unexpected. Also, Bing can use the client ID to tailor web results to that
    74  // client ID’s search history, providing a richer experience for the user. Bing also uses this header to help
    75  // improve result rankings by analyzing the activity generated by a client ID. The relevance improvements help
    76  // with better quality of results delivered by Bing APIs and in turn enables higher click-through rates for the
    77  // API consumer. IMPORTANT: Although optional, you should consider this header required. Persisting the client
    78  // ID across multiple requests for the same end user and device combination enables 1) the API consumer to
    79  // receive a consistent user experience, and 2) higher click-through rates via better quality of results from
    80  // the Bing APIs. Each user that uses your application on the device must have a unique, Bing generated client
    81  // ID. If you do not include this header in the request, Bing generates an ID and returns it in the
    82  // X-MSEdge-ClientID response header. The only time that you should NOT include this header in a request is the
    83  // first time the user uses your app on that device. Use the client ID for each Bing API request that your app
    84  // makes for this user on the device. Persist the client ID. To persist the ID in a browser app, use a
    85  // persistent HTTP cookie to ensure the ID is used across all sessions. Do not use a session cookie. For other
    86  // apps such as mobile apps, use the device's persistent storage to persist the ID. The next time the user uses
    87  // your app on that device, get the client ID that you persisted. Bing responses may or may not include this
    88  // header. If the response includes this header, capture the client ID and use it for all subsequent Bing
    89  // requests for the user on that device. ATTENTION: You must ensure that this Client ID is not linkable to any
    90  // authenticatable user account information. If you include the X-MSEdge-ClientID, you must not include cookies
    91  // in the request.
    92  // clientIP - the IPv4 or IPv6 address of the client device. The IP address is used to discover the user's
    93  // location. Bing uses the location information to determine safe search behavior. Although optional, you are
    94  // encouraged to always specify this header and the X-Search-Location header. Do not obfuscate the address (for
    95  // example, by changing the last octet to 0). Obfuscating the address results in the location not being
    96  // anywhere near the device's actual location, which may result in Bing serving erroneous results.
    97  // location - a semicolon-delimited list of key/value pairs that describe the client's geographical location.
    98  // Bing uses the location information to determine safe search behavior and to return relevant local content.
    99  // Specify the key/value pair as <key>:<value>. The following are the keys that you use to specify the user's
   100  // location. lat (required): The latitude of the client's location, in degrees. The latitude must be greater
   101  // than or equal to -90.0 and less than or equal to +90.0. Negative values indicate southern latitudes and
   102  // positive values indicate northern latitudes. long (required): The longitude of the client's location, in
   103  // degrees. The longitude must be greater than or equal to -180.0 and less than or equal to +180.0. Negative
   104  // values indicate western longitudes and positive values indicate eastern longitudes. re (required): The
   105  // radius, in meters, which specifies the horizontal accuracy of the coordinates. Pass the value returned by
   106  // the device's location service. Typical values might be 22m for GPS/Wi-Fi, 380m for cell tower triangulation,
   107  // and 18,000m for reverse IP lookup. ts (optional): The UTC UNIX timestamp of when the client was at the
   108  // location. (The UNIX timestamp is the number of seconds since January 1, 1970.) head (optional): The client's
   109  // relative heading or direction of travel. Specify the direction of travel as degrees from 0 through 360,
   110  // counting clockwise relative to true north. Specify this key only if the sp key is nonzero. sp (optional):
   111  // The horizontal velocity (speed), in meters per second, that the client device is traveling. alt (optional):
   112  // The altitude of the client device, in meters. are (optional): The radius, in meters, that specifies the
   113  // vertical accuracy of the coordinates. Specify this key only if you specify the alt key. Although many of the
   114  // keys are optional, the more information that you provide, the more accurate the location results are.
   115  // Although optional, you are encouraged to always specify the user's geographical location. Providing the
   116  // location is especially important if the client's IP address does not accurately reflect the user's physical
   117  // location (for example, if the client uses VPN). For optimal results, you should include this header and the
   118  // X-MSEdge-ClientIP header, but at a minimum, you should include this header.
   119  // market - the market where the results come from. Typically, mkt is the country where the user is making the
   120  // request from. However, it could be a different country if the user is not located in a country where Bing
   121  // delivers results. The market must be in the form <language code>-<country code>. For example, en-US. The
   122  // string is case insensitive. For a list of possible market values, see [Market
   123  // Codes](https://docs.microsoft.com/en-us/azure/cognitive-services/bing-visual-search/supported-countries-markets).
   124  // NOTE: If known, you are encouraged to always specify the market. Specifying the market helps Bing route the
   125  // request and return an appropriate and optimal response. If you specify a market that is not listed in
   126  // [Market
   127  // Codes](https://docs.microsoft.com/en-us/azure/cognitive-services/bing-visual-search/supported-countries-markets),
   128  // Bing uses a best fit market code based on an internal mapping that is subject to change.
   129  // safeSearch - filter the image results in actions with type 'VisualSearch' for adult content. The following
   130  // are the possible filter values. Off: May return images with adult content. Moderate: Do not return images
   131  // with adult content. Strict: Do not return images with adult content. The default is Moderate. If the request
   132  // comes from a market that Bing's adult policy requires that safeSearch is set to Strict, Bing ignores the
   133  // safeSearch value and uses Strict. If you use the site: filter in the knowledge request, there is the chance
   134  // that the response may contain adult content regardless of what the safeSearch query parameter is set to. Use
   135  // site: only if you are aware of the content on the site and your scenario supports the possibility of adult
   136  // content.
   137  // setLang - the language to use for user interface strings. Specify the language using the ISO 639-1 2-letter
   138  // language code. For example, the language code for English is EN. The default is EN (English). Although
   139  // optional, you should always specify the language. Typically, you set setLang to the same language specified
   140  // by mkt unless the user wants the user interface strings displayed in a different language. A user interface
   141  // string is a string that's used as a label in a user interface. There are few user interface strings in the
   142  // JSON response objects. Also, any links to Bing.com properties in the response objects apply the specified
   143  // language.
   144  // knowledgeRequest - the form data is a JSON object that identifies the image using an insights token or URL
   145  // to the image. The object may also include an optional crop area that identifies an area of interest in the
   146  // image. The insights token and URL are mutually exclusive – do not specify both. You may specify
   147  // knowledgeRequest form data and image form data in the same request only if knowledgeRequest form data
   148  // specifies the cropArea field only (it must not include an insights token or URL).
   149  // imageParameter - the form data is an image binary. The Content-Disposition header's name parameter must be
   150  // set to "image". You must specify an image binary if you do not use knowledgeRequest form data to specify the
   151  // image; you may not use both forms to specify an image. You may specify knowledgeRequest form data and image
   152  // form data in the same request only if knowledgeRequest form data specifies the cropArea field only  (it must
   153  // not include an insights token or URL).
   154  func (client ImagesClient) VisualSearch(ctx context.Context, acceptLanguage string, contentType string, userAgent string, clientID string, clientIP string, location string, market string, safeSearch SafeSearch, setLang string, knowledgeRequest string, imageParameter io.ReadCloser) (result ImageKnowledge, err error) {
   155  	if tracing.IsEnabled() {
   156  		ctx = tracing.StartSpan(ctx, fqdn+"/ImagesClient.VisualSearch")
   157  		defer func() {
   158  			sc := -1
   159  			if result.Response.Response != nil {
   160  				sc = result.Response.Response.StatusCode
   161  			}
   162  			tracing.EndSpan(ctx, sc, err)
   163  		}()
   164  	}
   165  	req, err := client.VisualSearchPreparer(ctx, acceptLanguage, contentType, userAgent, clientID, clientIP, location, market, safeSearch, setLang, knowledgeRequest, imageParameter)
   166  	if err != nil {
   167  		err = autorest.NewErrorWithError(err, "visualsearch.ImagesClient", "VisualSearch", nil, "Failure preparing request")
   168  		return
   169  	}
   170  
   171  	resp, err := client.VisualSearchSender(req)
   172  	if err != nil {
   173  		result.Response = autorest.Response{Response: resp}
   174  		err = autorest.NewErrorWithError(err, "visualsearch.ImagesClient", "VisualSearch", resp, "Failure sending request")
   175  		return
   176  	}
   177  
   178  	result, err = client.VisualSearchResponder(resp)
   179  	if err != nil {
   180  		err = autorest.NewErrorWithError(err, "visualsearch.ImagesClient", "VisualSearch", resp, "Failure responding to request")
   181  		return
   182  	}
   183  
   184  	return
   185  }
   186  
   187  // VisualSearchPreparer prepares the VisualSearch request.
   188  func (client ImagesClient) VisualSearchPreparer(ctx context.Context, acceptLanguage string, contentType string, userAgent string, clientID string, clientIP string, location string, market string, safeSearch SafeSearch, setLang string, knowledgeRequest string, imageParameter io.ReadCloser) (*http.Request, error) {
   189  	urlParameters := map[string]interface{}{
   190  		"Endpoint": client.Endpoint,
   191  	}
   192  
   193  	queryParameters := map[string]interface{}{}
   194  	if len(market) > 0 {
   195  		queryParameters["mkt"] = autorest.Encode("query", market)
   196  	}
   197  	if len(string(safeSearch)) > 0 {
   198  		queryParameters["safeSearch"] = autorest.Encode("query", safeSearch)
   199  	}
   200  	if len(setLang) > 0 {
   201  		queryParameters["setLang"] = autorest.Encode("query", setLang)
   202  	}
   203  
   204  	formDataParameters := map[string]interface{}{}
   205  	if len(knowledgeRequest) > 0 {
   206  		formDataParameters["knowledgeRequest"] = knowledgeRequest
   207  	}
   208  	if imageParameter != nil {
   209  		formDataParameters["image"] = imageParameter
   210  	}
   211  
   212  	preparer := autorest.CreatePreparer(
   213  		autorest.AsPost(),
   214  		autorest.WithCustomBaseURL("{Endpoint}/bing/v7.0", urlParameters),
   215  		autorest.WithPath("/images/visualsearch"),
   216  		autorest.WithQueryParameters(queryParameters),
   217  		autorest.WithMultiPartFormData(formDataParameters),
   218  		autorest.WithHeader("X-BingApis-SDK", "true"))
   219  	if len(acceptLanguage) > 0 {
   220  		preparer = autorest.DecoratePreparer(preparer,
   221  			autorest.WithHeader("Accept-Language", autorest.String(acceptLanguage)))
   222  	}
   223  	if len(contentType) > 0 {
   224  		preparer = autorest.DecoratePreparer(preparer,
   225  			autorest.WithHeader("Content-Type", autorest.String(contentType)))
   226  	}
   227  	if len(userAgent) > 0 {
   228  		preparer = autorest.DecoratePreparer(preparer,
   229  			autorest.WithHeader("User-Agent", autorest.String(userAgent)))
   230  	}
   231  	if len(clientID) > 0 {
   232  		preparer = autorest.DecoratePreparer(preparer,
   233  			autorest.WithHeader("X-MSEdge-ClientID", autorest.String(clientID)))
   234  	}
   235  	if len(clientIP) > 0 {
   236  		preparer = autorest.DecoratePreparer(preparer,
   237  			autorest.WithHeader("X-MSEdge-ClientIP", autorest.String(clientIP)))
   238  	}
   239  	if len(location) > 0 {
   240  		preparer = autorest.DecoratePreparer(preparer,
   241  			autorest.WithHeader("X-Search-Location", autorest.String(location)))
   242  	}
   243  	return preparer.Prepare((&http.Request{}).WithContext(ctx))
   244  }
   245  
   246  // VisualSearchSender sends the VisualSearch request. The method will close the
   247  // http.Response Body if it receives an error.
   248  func (client ImagesClient) VisualSearchSender(req *http.Request) (*http.Response, error) {
   249  	return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
   250  }
   251  
   252  // VisualSearchResponder handles the response to the VisualSearch request. The method always
   253  // closes the http.Response Body.
   254  func (client ImagesClient) VisualSearchResponder(resp *http.Response) (result ImageKnowledge, err error) {
   255  	err = autorest.Respond(
   256  		resp,
   257  		azure.WithErrorUnlessStatusCode(http.StatusOK),
   258  		autorest.ByUnmarshallingJSON(&result),
   259  		autorest.ByClosing())
   260  	result.Response = autorest.Response{Response: resp}
   261  	return
   262  }
   263  

View as plain text