/// <summary>
        /// List collections.
        ///
        /// Retrieves a list of collections for the service instance.
        /// </summary>
        /// <returns><see cref="CollectionsList" />CollectionsList</returns>
        public DetailedResponse <CollectionsList> ListCollections()
        {
            if (string.IsNullOrEmpty(VersionDate))
            {
                throw new ArgumentNullException("versionDate cannot be null.");
            }

            DetailedResponse <CollectionsList> result = null;

            try
            {
                IClient client = this.Client;
                SetAuthentication();

                var restRequest = client.GetAsync($"{this.Endpoint}/v4/collections");

                restRequest.WithArgument("version", VersionDate);
                restRequest.WithHeader("Accept", "application/json");

                restRequest.WithHeaders(Common.GetSdkHeaders("watson_vision_combined", "v4", "ListCollections"));
                restRequest.WithHeaders(customRequestHeaders);
                ClearCustomRequestHeaders();

                result = restRequest.As <CollectionsList>().Result;
                if (result == null)
                {
                    result = new DetailedResponse <CollectionsList>();
                }
            }
            catch (AggregateException ae)
            {
                throw ae.Flatten();
            }

            return(result);
        }
Пример #2
0
    // 2020/2/15 - changed to protected virtual to allow for inheritance.
    // This is where the returned chat response is set to send as output
    protected virtual void OnMessage(DetailedResponse <MessageResponse> response, IBMError error)
    {
        Debug.Log("response = " + response.Result.ToString());

        if (response == null ||
            response.Result == null ||
            response.Result.Output == null ||
            response.Result.Output.Generic == null ||
            response.Result.Output.Generic.Count < 1)
        {
            textResponse = "I don't know how to respond to that.";
        }
        else
        {
            textResponse = response.Result.Output.Generic[0].Text.ToString();
        }


        if (targetInputField != null)
        {
            targetInputField.text = textResponse;
        }

        // Check if the target GameObject has an InputField then place text into it.
        if (targetGameObject != null)
        {
            InputField target = targetGameObject.GetComponent <InputField>();
            if (target != null)
            {
                target.text = textResponse;
            }
        }

        Debug.Log(textResponse);
        messageTested = true;
    }
Пример #3
0
        /// <summary>
        /// List identifiable languages.
        ///
        /// Lists the languages that the service can identify. Returns the language code (for example, `en` for English
        /// or `es` for Spanish) and name of each language.
        /// </summary>
        /// <returns><see cref="IdentifiableLanguages" />IdentifiableLanguages</returns>
        public DetailedResponse <IdentifiableLanguages> ListIdentifiableLanguages()
        {
            if (string.IsNullOrEmpty(VersionDate))
            {
                throw new ArgumentNullException("versionDate cannot be null.");
            }

            DetailedResponse <IdentifiableLanguages> result = null;

            try
            {
                IClient client = this.Client;
                SetAuthentication();

                var restRequest = client.GetAsync($"{this.Endpoint}/v3/identifiable_languages");

                restRequest.WithArgument("version", VersionDate);
                restRequest.WithHeader("Accept", "application/json");

                restRequest.WithHeaders(Common.GetSdkHeaders("language_translator", "v3", "ListIdentifiableLanguages"));
                restRequest.WithHeaders(customRequestHeaders);
                ClearCustomRequestHeaders();

                result = restRequest.As <IdentifiableLanguages>().Result;
                if (result == null)
                {
                    result = new DetailedResponse <IdentifiableLanguages>();
                }
            }
            catch (AggregateException ae)
            {
                throw ae.Flatten();
            }

            return(result);
        }
        /// <summary>
        /// List models.
        ///
        /// Lists Watson Knowledge Studio [custom entities and relations
        /// models](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-customizing)
        /// that are deployed to your Natural Language Understanding service.
        /// </summary>
        /// <returns><see cref="ListModelsResults" />ListModelsResults</returns>
        public DetailedResponse <ListModelsResults> ListModels()
        {
            if (string.IsNullOrEmpty(VersionDate))
            {
                throw new ArgumentNullException("versionDate cannot be null.");
            }

            DetailedResponse <ListModelsResults> result = null;

            try
            {
                IClient client = this.Client;
                SetAuthentication();

                var restRequest = client.GetAsync($"{this.Endpoint}/v1/models");

                restRequest.WithArgument("version", VersionDate);
                restRequest.WithHeader("Accept", "application/json");

                restRequest.WithHeaders(Common.GetSdkHeaders("natural-language-understanding", "v1", "ListModels"));
                restRequest.WithHeaders(customRequestHeaders);
                ClearCustomRequestHeaders();

                result = restRequest.As <ListModelsResults>().Result;
                if (result == null)
                {
                    result = new DetailedResponse <ListModelsResults>();
                }
            }
            catch (AggregateException ae)
            {
                throw ae.Flatten();
            }

            return(result);
        }
Пример #5
0
 void OnCreateSession(DetailedResponse <SessionResponse> response, IBMError error)
 {
     if (response != null)
     {
         if (response.Result != null)
         {
         }
         else
         {
             Debug.Log("[" + name + "] response.Result = NULL");
             return;
         }
     }
     else
     {
         Debug.Log("[" + name + "] response = NULL");
         return;
     }
     Debug.Log("[" + name + "] OnCreateSession response = " + response.Result.SessionId);
     sessionId   = response.Result.SessionId;
     ReadyToSend = true;
     SelectableUIElement.ChangeLock(-1);
     Debug.Log("[ChatBotManager] Ready");
 }
Пример #6
0
        void OnMessage(DetailedResponse <MessageResponse> resp, IBMError error)
        {
            if (resp != null && resp.Result.Intents.Count != 0)
            {
                Debug.Log("Number of Received Intents: " + resp.Result.Intents.Count);

                for (int i = 0; i < resp.Result.Intents.Count; i++)
                {
                    Debug.Log("Received Intent: " + resp.Result.Intents[i].Intent);
                    if (resp.Result.Entities.Count > 0)
                    {
                        for (int j = 0; j < resp.Result.Entities.Count; j++)
                        {
                            Debug.Log("Received Entities: " + resp.Result.Entities[j].Entity);
                            Debug.Log("Received Entiites Value: " + resp.Result.Entities[j].Value);
                        }
                    }
                    else
                    {
                        Debug.Log("No entities received");
                    }
                }

                player.GetComponent <Control.ControlHandler>().HandleIntent
                (
                    resp.Result.Intents,
                    resp.Result.Entities,
                    resp.Result.Input.Text,
                    _intentConfidence
                );
            }
            else
            {
                Debug.Log("Failed to invoke OnMessage();");
            }
        }
Пример #7
0
        public void Tone_ToneInputEmpty()
        {
            #region response
            var response = new DetailedResponse <ToneAnalysis>()
            {
                Result = new ToneAnalysis()
                {
                    SentencesTone = new List <SentenceAnalysis>()
                    {
                        new SentenceAnalysis()
                        {
                            SentenceId     = 0,
                            InputFrom      = 0,
                            InputTo        = 0,
                            Text           = "string",
                            ToneCategories = new List <ToneCategory>()
                            {
                                new ToneCategory()
                                {
                                    CategoryName = "string",
                                    CategoryId   = "string",
                                    Tones        = new List <ToneScore>()
                                    {
                                        new ToneScore()
                                        {
                                            ToneName = "string",
                                            ToneId   = "string",
                                            Score    = 0
                                        }
                                    }
                                }
                            }
                        }
                    },
                    DocumentTone = new DocumentAnalysis()
                    {
                        ToneCategories = new List <ToneCategory>()
                        {
                            new ToneCategory()
                            {
                                CategoryName = "string",
                                CategoryId   = "string",
                                Tones        = new List <ToneScore>()
                                {
                                    new ToneScore()
                                    {
                                        ToneName = "string",
                                        ToneId   = "string",
                                        Score    = 0
                                    }
                                }
                            }
                        }
                    }
                }
            };
            #endregion

            ToneAnalyzerService service = new ToneAnalyzerService("username", "password", versionDate);
            var analyzeTone             = service.Tone(null, "application/json");
        }
Пример #8
0
        /// <summary>
        /// Translate document.
        ///
        /// Submit a document for translation. You can submit the document contents in the `file` parameter, or you can
        /// reference a previously submitted document by document ID.
        /// </summary>
        /// <param name="file">The source file to translate.
        ///
        /// [Supported file
        /// types](https://cloud.ibm.com/docs/services/language-translator?topic=language-translator-document-translator-tutorial#supported-file-formats)
        ///
        /// Maximum file size: **20 MB**.</param>
        /// <param name="filename">The filename for file.</param>
        /// <param name="fileContentType">The content type of file. (optional)</param>
        /// <param name="modelId">The model to use for translation. `model_id` or both `source` and `target` are
        /// required. (optional)</param>
        /// <param name="source">Language code that specifies the language of the source document. (optional)</param>
        /// <param name="target">Language code that specifies the target language for translation. (optional)</param>
        /// <param name="documentId">To use a previously submitted document as the source for a new translation, enter
        /// the `document_id` of the document. (optional)</param>
        /// <returns><see cref="DocumentStatus" />DocumentStatus</returns>
        public DetailedResponse <DocumentStatus> TranslateDocument(System.IO.MemoryStream file, string filename, string fileContentType = null, string modelId = null, string source = null, string target = null, string documentId = null)
        {
            if (file == null)
            {
                throw new ArgumentNullException("`file` is required for `TranslateDocument`");
            }
            if (string.IsNullOrEmpty(filename))
            {
                throw new ArgumentNullException("`filename` is required for `TranslateDocument`");
            }

            if (string.IsNullOrEmpty(VersionDate))
            {
                throw new ArgumentNullException("versionDate cannot be null.");
            }

            DetailedResponse <DocumentStatus> result = null;

            try
            {
                var formData = new MultipartFormDataContent();

                if (file != null)
                {
                    var fileContent = new ByteArrayContent(file.ToArray());
                    System.Net.Http.Headers.MediaTypeHeaderValue contentType;
                    System.Net.Http.Headers.MediaTypeHeaderValue.TryParse(fileContentType, out contentType);
                    fileContent.Headers.ContentType = contentType;
                    formData.Add(fileContent, "file", filename);
                }

                if (modelId != null)
                {
                    var modelIdContent = new StringContent(modelId, Encoding.UTF8, HttpMediaType.TEXT_PLAIN);
                    modelIdContent.Headers.ContentType = null;
                    formData.Add(modelIdContent, "model_id");
                }

                if (source != null)
                {
                    var sourceContent = new StringContent(source, Encoding.UTF8, HttpMediaType.TEXT_PLAIN);
                    sourceContent.Headers.ContentType = null;
                    formData.Add(sourceContent, "source");
                }

                if (target != null)
                {
                    var targetContent = new StringContent(target, Encoding.UTF8, HttpMediaType.TEXT_PLAIN);
                    targetContent.Headers.ContentType = null;
                    formData.Add(targetContent, "target");
                }

                if (documentId != null)
                {
                    var documentIdContent = new StringContent(documentId, Encoding.UTF8, HttpMediaType.TEXT_PLAIN);
                    documentIdContent.Headers.ContentType = null;
                    formData.Add(documentIdContent, "document_id");
                }

                IClient client = this.Client;
                SetAuthentication();

                var restRequest = client.PostAsync($"{this.Endpoint}/v3/documents");

                restRequest.WithArgument("version", VersionDate);
                restRequest.WithHeader("Accept", "application/json");
                restRequest.WithBodyContent(formData);

                restRequest.WithHeaders(Common.GetSdkHeaders("language_translator", "v3", "TranslateDocument"));
                restRequest.WithHeaders(customRequestHeaders);
                ClearCustomRequestHeaders();

                result = restRequest.As <DocumentStatus>().Result;
                if (result == null)
                {
                    result = new DetailedResponse <DocumentStatus>();
                }
            }
            catch (AggregateException ae)
            {
                throw ae.Flatten();
            }

            return(result);
        }
Пример #9
0
        /// <summary>
        /// Translate.
        ///
        /// Translates the input text from the source language to the target language.
        /// </summary>
        /// <param name="request">The translate request containing the text, and either a model ID or source and target
        /// language pair.</param>
        /// <returns><see cref="TranslationResult" />TranslationResult</returns>
        public DetailedResponse <TranslationResult> Translate(List <string> text, string modelId = null, string source = null, string target = null)
        {
            if (text == null)
            {
                throw new ArgumentNullException("`text` is required for `Translate`");
            }

            if (string.IsNullOrEmpty(VersionDate))
            {
                throw new ArgumentNullException("versionDate cannot be null.");
            }

            DetailedResponse <TranslationResult> result = null;

            try
            {
                IClient client = this.Client;
                SetAuthentication();

                var restRequest = client.PostAsync($"{this.Endpoint}/v3/translate");

                restRequest.WithArgument("version", VersionDate);
                restRequest.WithHeader("Accept", "application/json");
                restRequest.WithHeader("Content-Type", "application/json");

                JObject bodyObject = new JObject();
                if (text != null && text.Count > 0)
                {
                    bodyObject["text"] = JToken.FromObject(text);
                }
                if (!string.IsNullOrEmpty(modelId))
                {
                    bodyObject["model_id"] = modelId;
                }
                if (!string.IsNullOrEmpty(source))
                {
                    bodyObject["source"] = source;
                }
                if (!string.IsNullOrEmpty(target))
                {
                    bodyObject["target"] = target;
                }
                var httpContent = new StringContent(JsonConvert.SerializeObject(bodyObject), Encoding.UTF8, HttpMediaType.APPLICATION_JSON);
                restRequest.WithBodyContent(httpContent);

                restRequest.WithHeaders(Common.GetSdkHeaders("language_translator", "v3", "Translate"));
                restRequest.WithHeaders(customRequestHeaders);
                ClearCustomRequestHeaders();

                result = restRequest.As <TranslationResult>().Result;
                if (result == null)
                {
                    result = new DetailedResponse <TranslationResult>();
                }
            }
            catch (AggregateException ae)
            {
                throw ae.Flatten();
            }

            return(result);
        }
        /// <summary>
        /// List the feedback in a document.
        ///
        /// Lists the feedback in a document.
        /// </summary>
        /// <param name="feedbackType">An optional string that filters the output to include only feedback with the
        /// specified feedback type. The only permitted value is `element_classification`. (optional)</param>
        /// <param name="before">An optional string in the format `YYYY-MM-DD` that filters the output to include only
        /// feedback that was added before the specified date. (optional)</param>
        /// <param name="after">An optional string in the format `YYYY-MM-DD` that filters the output to include only
        /// feedback that was added after the specified date. (optional)</param>
        /// <param name="documentTitle">An optional string that filters the output to include only feedback from the
        /// document with the specified `document_title`. (optional)</param>
        /// <param name="modelId">An optional string that filters the output to include only feedback with the specified
        /// `model_id`. The only permitted value is `contracts`. (optional)</param>
        /// <param name="modelVersion">An optional string that filters the output to include only feedback with the
        /// specified `model_version`. (optional)</param>
        /// <param name="categoryRemoved">An optional string in the form of a comma-separated list of categories. If it
        /// is specified, the service filters the output to include only feedback that has at least one category from
        /// the list removed. (optional)</param>
        /// <param name="categoryAdded">An optional string in the form of a comma-separated list of categories. If this
        /// is specified, the service filters the output to include only feedback that has at least one category from
        /// the list added. (optional)</param>
        /// <param name="categoryNotChanged">An optional string in the form of a comma-separated list of categories. If
        /// this is specified, the service filters the output to include only feedback that has at least one category
        /// from the list unchanged. (optional)</param>
        /// <param name="typeRemoved">An optional string of comma-separated `nature`:`party` pairs. If this is
        /// specified, the service filters the output to include only feedback that has at least one `nature`:`party`
        /// pair from the list removed. (optional)</param>
        /// <param name="typeAdded">An optional string of comma-separated `nature`:`party` pairs. If this is specified,
        /// the service filters the output to include only feedback that has at least one `nature`:`party` pair from the
        /// list removed. (optional)</param>
        /// <param name="typeNotChanged">An optional string of comma-separated `nature`:`party` pairs. If this is
        /// specified, the service filters the output to include only feedback that has at least one `nature`:`party`
        /// pair from the list unchanged. (optional)</param>
        /// <param name="pageLimit">An optional integer specifying the number of documents that you want the service to
        /// return. (optional)</param>
        /// <param name="cursor">An optional string that returns the set of documents after the previous set. Use this
        /// parameter with the `page_limit` parameter. (optional)</param>
        /// <param name="sort">An optional comma-separated list of fields in the document to sort on. You can optionally
        /// specify the sort direction by prefixing the value of the field with `-` for descending order or `+` for
        /// ascending order (the default). Currently permitted sorting fields are `created`, `user_id`, and
        /// `document_title`. (optional)</param>
        /// <param name="includeTotal">An optional boolean value. If specified as `true`, the `pagination` object in the
        /// output includes a value called `total` that gives the total count of feedback created. (optional)</param>
        /// <returns><see cref="FeedbackList" />FeedbackList</returns>
        public DetailedResponse <FeedbackList> ListFeedback(string feedbackType = null, DateTime?before = null, DateTime?after = null, string documentTitle = null, string modelId = null, string modelVersion = null, string categoryRemoved = null, string categoryAdded = null, string categoryNotChanged = null, string typeRemoved = null, string typeAdded = null, string typeNotChanged = null, long?pageLimit = null, string cursor = null, string sort = null, bool?includeTotal = null)
        {
            if (string.IsNullOrEmpty(VersionDate))
            {
                throw new ArgumentNullException("versionDate cannot be null.");
            }

            DetailedResponse <FeedbackList> result = null;

            try
            {
                IClient client = this.Client;
                SetAuthentication();

                var restRequest = client.GetAsync($"{this.Endpoint}/v1/feedback");

                restRequest.WithArgument("version", VersionDate);
                restRequest.WithHeader("Accept", "application/json");
                if (!string.IsNullOrEmpty(feedbackType))
                {
                    restRequest.WithArgument("feedback_type", feedbackType);
                }
                if (before != null)
                {
                    restRequest.WithArgument("before", before);
                }
                if (after != null)
                {
                    restRequest.WithArgument("after", after);
                }
                if (!string.IsNullOrEmpty(documentTitle))
                {
                    restRequest.WithArgument("document_title", documentTitle);
                }
                if (!string.IsNullOrEmpty(modelId))
                {
                    restRequest.WithArgument("model_id", modelId);
                }
                if (!string.IsNullOrEmpty(modelVersion))
                {
                    restRequest.WithArgument("model_version", modelVersion);
                }
                if (!string.IsNullOrEmpty(categoryRemoved))
                {
                    restRequest.WithArgument("category_removed", categoryRemoved);
                }
                if (!string.IsNullOrEmpty(categoryAdded))
                {
                    restRequest.WithArgument("category_added", categoryAdded);
                }
                if (!string.IsNullOrEmpty(categoryNotChanged))
                {
                    restRequest.WithArgument("category_not_changed", categoryNotChanged);
                }
                if (!string.IsNullOrEmpty(typeRemoved))
                {
                    restRequest.WithArgument("type_removed", typeRemoved);
                }
                if (!string.IsNullOrEmpty(typeAdded))
                {
                    restRequest.WithArgument("type_added", typeAdded);
                }
                if (!string.IsNullOrEmpty(typeNotChanged))
                {
                    restRequest.WithArgument("type_not_changed", typeNotChanged);
                }
                if (pageLimit != null)
                {
                    restRequest.WithArgument("page_limit", pageLimit);
                }
                if (!string.IsNullOrEmpty(cursor))
                {
                    restRequest.WithArgument("cursor", cursor);
                }
                if (!string.IsNullOrEmpty(sort))
                {
                    restRequest.WithArgument("sort", sort);
                }
                if (includeTotal != null)
                {
                    restRequest.WithArgument("include_total", includeTotal);
                }

                restRequest.WithHeaders(Common.GetSdkHeaders("compare-comply", "v1", "ListFeedback"));
                restRequest.WithHeaders(customRequestHeaders);
                ClearCustomRequestHeaders();

                result = restRequest.As <FeedbackList>().Result;
                if (result == null)
                {
                    result = new DetailedResponse <FeedbackList>();
                }
            }
            catch (AggregateException ae)
            {
                throw ae.Flatten();
            }

            return(result);
        }
Пример #11
0
        /// <summary>
        /// Get profile as csv.
        ///
        /// Generates a personality profile for the author of the input text. The service accepts a maximum of 20 MB of
        /// input content, but it requires much less text to produce an accurate profile. The service can analyze text
        /// in Arabic, English, Japanese, Korean, or Spanish. It can return its results in a variety of languages.
        ///
        /// **See also:**
        /// * [Requesting a
        /// profile](https://cloud.ibm.com/docs/services/personality-insights?topic=personality-insights-input#input)
        /// * [Providing sufficient
        /// input](https://cloud.ibm.com/docs/services/personality-insights?topic=personality-insights-input#sufficient)
        ///
        ///
        /// ### Content types
        ///
        ///  You can provide input content as plain text (`text/plain`), HTML (`text/html`), or JSON
        /// (`application/json`) by specifying the **Content-Type** parameter. The default is `text/plain`.
        /// * Per the JSON specification, the default character encoding for JSON content is effectively always UTF-8.
        /// * Per the HTTP specification, the default encoding for plain text and HTML is ISO-8859-1 (effectively, the
        /// ASCII character set).
        ///
        /// When specifying a content type of plain text or HTML, include the `charset` parameter to indicate the
        /// character encoding of the input text; for example, `Content-Type: text/plain;charset=utf-8`.
        ///
        /// **See also:** [Specifying request and response
        /// formats](https://cloud.ibm.com/docs/services/personality-insights?topic=personality-insights-input#formats)
        ///
        /// ### Accept types
        ///
        ///  You must request a response as JSON (`application/json`) or comma-separated values (`text/csv`) by
        /// specifying the **Accept** parameter. CSV output includes a fixed number of columns. Set the **csv_headers**
        /// parameter to `true` to request optional column headers for CSV output.
        ///
        /// **See also:**
        /// * [Understanding a JSON
        /// profile](https://cloud.ibm.com/docs/services/personality-insights?topic=personality-insights-output#output)
        /// * [Understanding a CSV
        /// profile](https://cloud.ibm.com/docs/services/personality-insights?topic=personality-insights-outputCSV#outputCSV).
        /// </summary>
        /// <param name="content">A maximum of 20 MB of content to analyze, though the service requires much less text;
        /// for more information, see [Providing sufficient
        /// input](https://cloud.ibm.com/docs/services/personality-insights?topic=personality-insights-input#sufficient).
        /// For JSON input, provide an object of type `Content`.</param>
        /// <param name="contentType">The type of the input. For more information, see **Content types** in the method
        /// description. (optional, default to text/plain)</param>
        /// <param name="contentLanguage">The language of the input text for the request: Arabic, English, Japanese,
        /// Korean, or Spanish. Regional variants are treated as their parent language; for example, `en-US` is
        /// interpreted as `en`.
        ///
        /// The effect of the **Content-Language** parameter depends on the **Content-Type** parameter. When
        /// **Content-Type** is `text/plain` or `text/html`, **Content-Language** is the only way to specify the
        /// language. When **Content-Type** is `application/json`, **Content-Language** overrides a language specified
        /// with the `language` parameter of a `ContentItem` object, and content items that specify a different language
        /// are ignored; omit this parameter to base the language on the specification of the content items. You can
        /// specify any combination of languages for **Content-Language** and **Accept-Language**. (optional, default to
        /// en)</param>
        /// <param name="acceptLanguage">The desired language of the response. For two-character arguments, regional
        /// variants are treated as their parent language; for example, `en-US` is interpreted as `en`. You can specify
        /// any combination of languages for the input and response content. (optional, default to en)</param>
        /// <param name="rawScores">Indicates whether a raw score in addition to a normalized percentile is returned for
        /// each characteristic; raw scores are not compared with a sample population. By default, only normalized
        /// percentiles are returned. (optional, default to false)</param>
        /// <param name="csvHeaders">Indicates whether column labels are returned with a CSV response. By default, no
        /// column labels are returned. Applies only when the response type is CSV (`text/csv`). (optional, default to
        /// false)</param>
        /// <param name="consumptionPreferences">Indicates whether consumption preferences are returned with the
        /// results. By default, no consumption preferences are returned. (optional, default to false)</param>
        /// <returns><see cref="System.IO.MemoryStream" />System.IO.MemoryStream</returns>
        public DetailedResponse <System.IO.MemoryStream> ProfileAsCsv(Content content, string contentType = null, string contentLanguage = null, string acceptLanguage = null, bool?rawScores = null, bool?csvHeaders = null, bool?consumptionPreferences = null)
        {
            if (content == null)
            {
                throw new ArgumentNullException("`content` is required for `ProfileAsCsv`");
            }

            if (string.IsNullOrEmpty(VersionDate))
            {
                throw new ArgumentNullException("versionDate cannot be null.");
            }

            DetailedResponse <System.IO.MemoryStream> result = null;

            try
            {
                IClient client = this.Client;
                SetAuthentication();

                var restRequest = client.PostAsync($"{this.Endpoint}/v3/profile");

                restRequest.WithArgument("version", VersionDate);
                restRequest.WithHeader("Accept", "text/csv");

                if (!string.IsNullOrEmpty(contentType))
                {
                    restRequest.WithHeader("Content-Type", contentType);
                }

                if (!string.IsNullOrEmpty(contentLanguage))
                {
                    restRequest.WithHeader("Content-Language", contentLanguage);
                }

                if (!string.IsNullOrEmpty(acceptLanguage))
                {
                    restRequest.WithHeader("Accept-Language", acceptLanguage);
                }
                if (rawScores != null)
                {
                    restRequest.WithArgument("raw_scores", rawScores);
                }
                if (csvHeaders != null)
                {
                    restRequest.WithArgument("csv_headers", csvHeaders);
                }
                if (consumptionPreferences != null)
                {
                    restRequest.WithArgument("consumption_preferences", consumptionPreferences);
                }
                var httpContent = new StringContent(JsonConvert.SerializeObject(content), Encoding.UTF8);
                restRequest.WithBodyContent(httpContent);

                restRequest.WithHeaders(Common.GetSdkHeaders("personality_insights", "v3", "ProfileAsCsv"));
                restRequest.WithHeaders(customRequestHeaders);
                ClearCustomRequestHeaders();

                result        = new DetailedResponse <System.IO.MemoryStream>();
                result.Result = new System.IO.MemoryStream(restRequest.AsByteArray().Result);
            }
            catch (AggregateException ae)
            {
                throw ae.Flatten();
            }

            return(result);
        }
Пример #12
0
 private void OnCreateSession(DetailedResponse <SessionResponse> response, IBMError error)
 {
     Log.Debug("SimpleBot.OnCreateSession()", "Session: {0}", response.Result.SessionId);
     sessionId           = response.Result.SessionId;
     createSessionTested = true;
 }
Пример #13
0
 private void OnDeleteSession(DetailedResponse <object> response, IBMError error)
 {
     deleteSessionTested = true;
 }
Пример #14
0
        public void Analysis()
        {
            IClient  client  = CreateClient();
            IRequest request = Substitute.For <IRequest>();

            client.GetAsync(Arg.Any <string>())
            .Returns(request);

            #region response
            var analyzeResponse = new AnalyzeResponse()
            {
                Images = new List <Image>()
                {
                    new Image()
                    {
                        Source = new ImageSource()
                        {
                            Type            = "type",
                            Filename        = "filename",
                            ArchiveFilename = "archiveFilename",
                            SourceUrl       = "sourceUrl",
                            ResolvedUrl     = "resolvedUrl"
                        },
                        Dimensions = new ImageDimensions()
                        {
                            Width  = 100,
                            Height = 200
                        },
                        Objects = new DetectedObjects()
                        {
                            Collections = new List <CollectionObjects>()
                            {
                                new CollectionObjects()
                                {
                                    CollectionId = "collectionId",
                                    Objects      = new List <ObjectDetail>()
                                    {
                                        new ObjectDetail()
                                        {
                                            _Object  = "object",
                                            Location = new ObjectDetailLocation()
                                            {
                                                Top    = 0,
                                                Left   = 1,
                                                Width  = 2,
                                                Height = 3
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            };

            var response = new DetailedResponse <AnalyzeResponse>();
            response.Result = analyzeResponse;
            #endregion

            request.WithArgument(Arg.Any <string>(), Arg.Any <string>())
            .Returns(request);
            request.WithBodyContent(new MultipartFormDataContent())
            .Returns(request);
            request.As <AnalyzeResponse>()
            .Returns(Task.FromResult(response));

            NoAuthAuthenticator      authenticator = new NoAuthAuthenticator();
            VisualRecognitionService service       = new VisualRecognitionService(client);
            service.Version = "versionDate";
            service.Analyze(
                collectionIds: new List <string> {
                "colletionIds"
            },
                features: new List <string> {
                "features"
            });

            Assert.IsTrue(response.Result.Images[0].Source.Type == "type");
            Assert.IsTrue(response.Result.Images[0].Source.Filename == "filename");
            Assert.IsTrue(response.Result.Images[0].Source.ArchiveFilename == "archiveFilename");
            Assert.IsTrue(response.Result.Images[0].Source.SourceUrl == "sourceUrl");
            Assert.IsTrue(response.Result.Images[0].Source.ResolvedUrl == "resolvedUrl");
            Assert.IsTrue(response.Result.Images[0].Dimensions.Width == 100);
            Assert.IsTrue(response.Result.Images[0].Dimensions.Height == 200);
            Assert.IsTrue(response.Result.Images[0].Objects.Collections[0].CollectionId == "collectionId");
            Assert.IsTrue(response.Result.Images[0].Objects.Collections[0].Objects[0]._Object == "object");
            Assert.IsTrue(response.Result.Images[0].Objects.Collections[0].Objects[0].Location.Top == 0);
            Assert.IsTrue(response.Result.Images[0].Objects.Collections[0].Objects[0].Location.Left == 1);
            Assert.IsTrue(response.Result.Images[0].Objects.Collections[0].Objects[0].Location.Width == 2);
            Assert.IsTrue(response.Result.Images[0].Objects.Collections[0].Objects[0].Location.Height == 3);
        }
        /// <summary>
        /// Analyze text.
        ///
        /// Analyzes text, HTML, or a public webpage for the following features:
        /// - Categories
        /// - Concepts
        /// - Emotion
        /// - Entities
        /// - Keywords
        /// - Metadata
        /// - Relations
        /// - Semantic roles
        /// - Sentiment
        /// - Syntax (Experimental).
        ///
        /// If a language for the input text is not specified with the `language` parameter, the service [automatically
        /// detects the
        /// language](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-detectable-languages).
        /// </summary>
        /// <param name="parameters">An object containing request parameters. The `features` object and one of the
        /// `text`, `html`, or `url` attributes are required.</param>
        /// <returns><see cref="AnalysisResults" />AnalysisResults</returns>
        public DetailedResponse <AnalysisResults> Analyze(Features features, string text = null, string html = null, string url = null, bool?clean = null, string xpath = null, bool?fallbackToRaw = null, bool?returnAnalyzedText = null, string language = null, long?limitTextCharacters = null)
        {
            if (features == null)
            {
                throw new ArgumentNullException("`features` is required for `Analyze`");
            }

            if (string.IsNullOrEmpty(VersionDate))
            {
                throw new ArgumentNullException("versionDate cannot be null.");
            }

            DetailedResponse <AnalysisResults> result = null;

            try
            {
                IClient client = this.Client;
                SetAuthentication();

                var restRequest = client.PostAsync($"{this.Endpoint}/v1/analyze");

                restRequest.WithArgument("version", VersionDate);
                restRequest.WithHeader("Accept", "application/json");
                restRequest.WithHeader("Content-Type", "application/json");

                JObject bodyObject = new JObject();
                if (features != null)
                {
                    bodyObject["features"] = JToken.FromObject(features);
                }
                if (!string.IsNullOrEmpty(text))
                {
                    bodyObject["text"] = text;
                }
                if (!string.IsNullOrEmpty(html))
                {
                    bodyObject["html"] = html;
                }
                if (!string.IsNullOrEmpty(url))
                {
                    bodyObject["url"] = url;
                }
                if (clean != null)
                {
                    bodyObject["clean"] = JToken.FromObject(clean);
                }
                if (!string.IsNullOrEmpty(xpath))
                {
                    bodyObject["xpath"] = xpath;
                }
                if (fallbackToRaw != null)
                {
                    bodyObject["fallback_to_raw"] = JToken.FromObject(fallbackToRaw);
                }
                if (returnAnalyzedText != null)
                {
                    bodyObject["return_analyzed_text"] = JToken.FromObject(returnAnalyzedText);
                }
                if (!string.IsNullOrEmpty(language))
                {
                    bodyObject["language"] = language;
                }
                if (limitTextCharacters != null)
                {
                    bodyObject["limit_text_characters"] = JToken.FromObject(limitTextCharacters);
                }
                var httpContent = new StringContent(JsonConvert.SerializeObject(bodyObject), Encoding.UTF8, HttpMediaType.APPLICATION_JSON);
                restRequest.WithBodyContent(httpContent);

                restRequest.WithHeaders(Common.GetSdkHeaders("natural-language-understanding", "v1", "Analyze"));
                restRequest.WithHeaders(customRequestHeaders);
                ClearCustomRequestHeaders();

                result = restRequest.As <AnalysisResults>().Result;
                if (result == null)
                {
                    result = new DetailedResponse <AnalysisResults>();
                }
            }
            catch (AggregateException ae)
            {
                throw ae.Flatten();
            }

            return(result);
        }
        /// <summary>
        /// Delete a document.
        ///
        /// If the given document ID is invalid, or if the document is not found, then the a success response is
        /// returned (HTTP status code `200`) with the status set to 'deleted'.
        ///
        /// **Note:** This operation only works on collections created to accept direct file uploads. It cannot be used
        /// to modify a collection that conects to an external source such as Microsoft SharePoint.
        /// </summary>
        /// <param name="projectId">The ID of the project. This information can be found from the deploy page of the
        /// Discovery administrative tooling.</param>
        /// <param name="collectionId">The ID of the collection.</param>
        /// <param name="documentId">The ID of the document.</param>
        /// <param name="xWatsonDiscoveryForce">When `true`, the uploaded document is added to the collection even if
        /// the data for that collection is shared with other collections. (optional, default to false)</param>
        /// <returns><see cref="DeleteDocumentResponse" />DeleteDocumentResponse</returns>
        public DetailedResponse <DeleteDocumentResponse> DeleteDocument(string projectId, string collectionId, string documentId, bool?xWatsonDiscoveryForce = null)
        {
            if (string.IsNullOrEmpty(projectId))
            {
                throw new ArgumentNullException("`projectId` is required for `DeleteDocument`");
            }
            else
            {
                projectId = Uri.EscapeDataString(projectId);
            }
            if (string.IsNullOrEmpty(collectionId))
            {
                throw new ArgumentNullException("`collectionId` is required for `DeleteDocument`");
            }
            else
            {
                collectionId = Uri.EscapeDataString(collectionId);
            }
            if (string.IsNullOrEmpty(documentId))
            {
                throw new ArgumentNullException("`documentId` is required for `DeleteDocument`");
            }
            else
            {
                documentId = Uri.EscapeDataString(documentId);
            }

            if (string.IsNullOrEmpty(VersionDate))
            {
                throw new ArgumentNullException("versionDate cannot be null.");
            }

            DetailedResponse <DeleteDocumentResponse> result = null;

            try
            {
                IClient client = this.Client;
                SetAuthentication();

                var restRequest = client.DeleteAsync($"{this.Endpoint}/v2/projects/{projectId}/collections/{collectionId}/documents/{documentId}");

                restRequest.WithArgument("version", VersionDate);
                restRequest.WithHeader("Accept", "application/json");

                if (xWatsonDiscoveryForce != null)
                {
                    restRequest.WithHeader("X-Watson-Discovery-Force", (bool)xWatsonDiscoveryForce ? "true" : "false");
                }

                restRequest.WithHeaders(Common.GetSdkHeaders("discovery", "v2", "DeleteDocument"));
                restRequest.WithHeaders(customRequestHeaders);
                ClearCustomRequestHeaders();

                result = restRequest.As <DeleteDocumentResponse>().Result;
                if (result == null)
                {
                    result = new DetailedResponse <DeleteDocumentResponse>();
                }
            }
            catch (AggregateException ae)
            {
                throw ae.Flatten();
            }

            return(result);
        }
        /// <summary>
        /// Create training query.
        ///
        /// Add a query to the training data for this project. The query can contain a filter and natural language
        /// query.
        /// </summary>
        /// <param name="projectId">The ID of the project. This information can be found from the deploy page of the
        /// Discovery administrative tooling.</param>
        /// <param name="trainingQuery">An object that represents the query to be submitted. (optional)</param>
        /// <returns><see cref="TrainingQuery" />TrainingQuery</returns>
        public DetailedResponse <TrainingQuery> CreateTrainingQuery(string projectId, string naturalLanguageQuery, List <TrainingExample> examples, string filter = null)
        {
            if (string.IsNullOrEmpty(projectId))
            {
                throw new ArgumentNullException("`projectId` is required for `CreateTrainingQuery`");
            }
            else
            {
                projectId = Uri.EscapeDataString(projectId);
            }

            if (string.IsNullOrEmpty(VersionDate))
            {
                throw new ArgumentNullException("versionDate cannot be null.");
            }

            DetailedResponse <TrainingQuery> result = null;

            try
            {
                IClient client = this.Client;
                SetAuthentication();

                var restRequest = client.PostAsync($"{this.Endpoint}/v2/projects/{projectId}/training_data/queries");

                restRequest.WithArgument("version", VersionDate);
                restRequest.WithHeader("Accept", "application/json");
                restRequest.WithHeader("Content-Type", "application/json");

                JObject bodyObject = new JObject();
                if (!string.IsNullOrEmpty(naturalLanguageQuery))
                {
                    bodyObject["natural_language_query"] = naturalLanguageQuery;
                }
                if (examples != null && examples.Count > 0)
                {
                    bodyObject["examples"] = JToken.FromObject(examples);
                }
                if (!string.IsNullOrEmpty(filter))
                {
                    bodyObject["filter"] = filter;
                }
                var httpContent = new StringContent(JsonConvert.SerializeObject(bodyObject), Encoding.UTF8, HttpMediaType.APPLICATION_JSON);
                restRequest.WithBodyContent(httpContent);

                restRequest.WithHeaders(Common.GetSdkHeaders("discovery", "v2", "CreateTrainingQuery"));
                restRequest.WithHeaders(customRequestHeaders);
                ClearCustomRequestHeaders();

                result = restRequest.As <TrainingQuery>().Result;
                if (result == null)
                {
                    result = new DetailedResponse <TrainingQuery>();
                }
            }
            catch (AggregateException ae)
            {
                throw ae.Flatten();
            }

            return(result);
        }
Пример #18
0
        public void TestClassifiers_Success()
        {
            service.WithHeader("X-Watson-Test", "1");
            var listClassifiersResult = service.ListClassifiers();

            string classifierId = null;

            if (listClassifiersResult.Result.Classifiers.Count > 0)
            {
                classifierId = listClassifiersResult.Result.Classifiers[0].ClassifierId;
            }

            DetailedResponse <Classification> classifyResult = null;

            if (!string.IsNullOrEmpty(classifierId))
            {
                service.WithHeader("X-Watson-Test", "1");
                classifyResult = service.Classify(
                    classifierId: classifierId,
                    text: textToClassify1
                    );
            }

            DetailedResponse <ClassificationCollection> classifyCollectionResult = null;

            if (!string.IsNullOrEmpty(classifierId))
            {
                var collection = new List <ClassifyInput>()
                {
                    new ClassifyInput()
                    {
                        Text = textToClassify0
                    },
                    new ClassifyInput()
                    {
                        Text = textToClassify1
                    }
                };

                service.WithHeader("X-Watson-Test", "1");
                classifyCollectionResult = service.ClassifyCollection(
                    classifierId: classifierId,
                    collection: collection
                    );
            }

            DetailedResponse <Classifier> createClassifierResult = null;

            using (FileStream trainingDataFile = File.OpenRead(classifierDataFilePath), metadataFile = File.OpenRead(metadataDataFilePath))
            {
                using (MemoryStream trainingData = new MemoryStream(), metadata = new MemoryStream())
                {
                    trainingDataFile.CopyTo(trainingData);
                    metadataFile.CopyTo(metadata);
                    service.WithHeader("X-Watson-Test", "1");
                    createClassifierResult = service.CreateClassifier(
                        trainingMetadata: metadata,
                        trainingData: trainingData
                        );
                }
            }

            var createdClassifierId = createClassifierResult.Result.ClassifierId;

            service.WithHeader("X-Watson-Test", "1");
            var getClassifierResult = service.GetClassifier(
                classifierId: createdClassifierId
                );

            if (!string.IsNullOrEmpty(classifierId) && !string.IsNullOrEmpty(createdClassifierId))
            {
                service.WithHeader("X-Watson-Test", "1");
                service.DeleteClassifier(
                    classifierId: createdClassifierId
                    );
            }

            if (!string.IsNullOrEmpty(classifierId))
            {
                Assert.IsNotNull(classifyResult);
                Assert.IsNotNull(classifyCollectionResult);
            }
            Assert.IsNotNull(getClassifierResult);
            Assert.IsTrue(createdClassifierId == getClassifierResult.Result.ClassifierId);
            Assert.IsNotNull(createClassifierResult);
            Assert.IsNotNull(listClassifiersResult);
        }
Пример #19
0
 private void OnCreateSession(DetailedResponse <SessionResponse> response, IBMError error)
 {
     Log.Debug("AvatarPatternError.OnCreateSession()", "Session: {0}", response.Result.SessionId);
     sessionId      = response.Result.SessionId;
     sessionCreated = true;
 }
        public void Images_Success()
        {
            string testCollectionName        = "testCollection";
            string testCollectionDescription = ".NET test collection";

            service.WithHeader("X-Watson-Test", "1");
            var createCollectionResult = service.CreateCollection(
                name: Utility.ConvertToUtf8(testCollectionName),
                description: Utility.ConvertToUtf8(testCollectionDescription));

            var createdCollectionId = createCollectionResult.Result.CollectionId;

            DetailedResponse <ImageDetailsList> addImagesResult = null;
            List <FileWithMetadata>             imagesFile      = new List <FileWithMetadata>();

            using (FileStream fs = File.OpenRead(localGiraffePositiveExamplesFilePath))
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    fs.CopyTo(ms);

                    FileWithMetadata fileWithMetadata = new FileWithMetadata()
                    {
                        Data        = ms,
                        ContentType = "application/zip",
                        Filename    = Path.GetFileName(localGiraffePositiveExamplesFilePath)
                    };
                    imagesFile.Add(fileWithMetadata);

                    service.WithHeader("X-Watson-Test", "1");
                    addImagesResult = service.AddImages(
                        collectionId: createdCollectionId,
                        imagesFile: imagesFile);
                }
            }
            var imageId = addImagesResult.Result.Images[0].ImageId;

            service.WithHeader("X-Watson-Test", "1");
            var addImageViaUrlResult = service.AddImages(
                collectionId: createdCollectionId,
                imageUrl: new List <string>()
            {
                dogImageUrl, catImageUrl
            });

            service.WithHeader("X-Watson-Test", "1");
            var listImageResult = service.ListImages(
                collectionId: createdCollectionId);

            service.WithHeader("X-Watson-Test", "1");
            var getImageResult = service.GetImageDetails(
                collectionId: createdCollectionId,
                imageId: imageId);

            service.WithHeader("X-Watson-Test", "1");
            var getJpgImageResult = service.GetJpegImage(
                collectionId: createdCollectionId,
                imageId: imageId,
                size: "thumbnail"
                );

            //  Save file
            using (FileStream fs = File.Create("giraffe.jpg"))
            {
                getJpgImageResult.Result.WriteTo(fs);
                fs.Close();
                getJpgImageResult.Result.Close();
            }

            service.WithHeader("X-Watson-Test", "1");
            var deleteImageResult = service.DeleteImage(
                collectionId: createdCollectionId,
                imageId: imageId);

            service.WithHeader("X-Watson-Test", "1");
            var deleteCollectionResult = service.DeleteCollection(
                collectionId: createdCollectionId);

            Assert.IsTrue(deleteImageResult.StatusCode == 200);
            Assert.IsNotNull(getJpgImageResult.Result);
            Assert.IsNotNull(getImageResult.Result);
            Assert.IsTrue(getImageResult.Result.ImageId == imageId);
            Assert.IsNotNull(listImageResult.Result);
            Assert.IsNotNull(listImageResult.Result.Images);
            Assert.IsTrue(listImageResult.Result.Images.Count > 0);
            Assert.IsNotNull(addImagesResult.Result);
            Assert.IsNotNull(addImagesResult.Result.Images);
            Assert.IsTrue(addImagesResult.Result.Images.Count > 0);
        }
        /// <summary>
        /// Compare two documents.
        ///
        /// Compares two input documents. Documents must be in the same format.
        /// </summary>
        /// <param name="file1">The first document to compare.</param>
        /// <param name="file2">The second document to compare.</param>
        /// <param name="file1ContentType">The content type of file1. (optional)</param>
        /// <param name="file2ContentType">The content type of file2. (optional)</param>
        /// <param name="file1Label">A text label for the first document. (optional, default to file_1)</param>
        /// <param name="file2Label">A text label for the second document. (optional, default to file_2)</param>
        /// <param name="model">The analysis model to be used by the service. For the **Element classification** and
        /// **Compare two documents** methods, the default is `contracts`. For the **Extract tables** method, the
        /// default is `tables`. These defaults apply to the standalone methods as well as to the methods' use in
        /// batch-processing requests. (optional)</param>
        /// <returns><see cref="CompareReturn" />CompareReturn</returns>
        public DetailedResponse <CompareReturn> CompareDocuments(System.IO.MemoryStream file1, System.IO.MemoryStream file2, string file1ContentType = null, string file2ContentType = null, string file1Label = null, string file2Label = null, string model = null)
        {
            if (file1 == null)
            {
                throw new ArgumentNullException("`file1` is required for `CompareDocuments`");
            }
            if (file2 == null)
            {
                throw new ArgumentNullException("`file2` is required for `CompareDocuments`");
            }

            if (string.IsNullOrEmpty(VersionDate))
            {
                throw new ArgumentNullException("versionDate cannot be null.");
            }

            DetailedResponse <CompareReturn> result = null;

            try
            {
                var formData = new MultipartFormDataContent();

                if (file1 != null)
                {
                    var file1Content = new ByteArrayContent(file1.ToArray());
                    System.Net.Http.Headers.MediaTypeHeaderValue contentType;
                    System.Net.Http.Headers.MediaTypeHeaderValue.TryParse(file1ContentType, out contentType);
                    file1Content.Headers.ContentType = contentType;
                    formData.Add(file1Content, "file_1", "filename");
                }

                if (file2 != null)
                {
                    var file2Content = new ByteArrayContent(file2.ToArray());
                    System.Net.Http.Headers.MediaTypeHeaderValue contentType;
                    System.Net.Http.Headers.MediaTypeHeaderValue.TryParse(file2ContentType, out contentType);
                    file2Content.Headers.ContentType = contentType;
                    formData.Add(file2Content, "file_2", "filename");
                }

                IClient client = this.Client;
                SetAuthentication();

                var restRequest = client.PostAsync($"{this.Endpoint}/v1/comparison");

                restRequest.WithArgument("version", VersionDate);
                restRequest.WithHeader("Accept", "application/json");
                if (!string.IsNullOrEmpty(file1Label))
                {
                    restRequest.WithArgument("file_1_label", file1Label);
                }
                if (!string.IsNullOrEmpty(file2Label))
                {
                    restRequest.WithArgument("file_2_label", file2Label);
                }
                if (!string.IsNullOrEmpty(model))
                {
                    restRequest.WithArgument("model", model);
                }
                restRequest.WithBodyContent(formData);

                restRequest.WithHeaders(Common.GetSdkHeaders("compare-comply", "v1", "CompareDocuments"));
                restRequest.WithHeaders(customRequestHeaders);
                ClearCustomRequestHeaders();

                result = restRequest.As <CompareReturn>().Result;
                if (result == null)
                {
                    result = new DetailedResponse <CompareReturn>();
                }
            }
            catch (AggregateException ae)
            {
                throw ae.Flatten();
            }

            return(result);
        }
        public void Objects_Success()
        {
            string testCollectionName        = "testCollection";
            string testCollectionDescription = ".NET test collection";

            service.WithHeader("X-Watson-Test", "1");
            var listCollectionResult = service.ListCollections();

            service.WithHeader("X-Watson-Test", "1");
            var createCollectionResult = service.CreateCollection(
                name: Utility.ConvertToUtf8(testCollectionName),
                description: Utility.ConvertToUtf8(testCollectionDescription));

            var createdCollectionId = createCollectionResult.Result.CollectionId;

            DetailedResponse <ImageDetailsList> addImagesResult = null;
            List <FileWithMetadata>             imagesFile      = new List <FileWithMetadata>();

            using (FileStream fs = File.OpenRead(localGiraffePositiveExamplesFilePath))
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    fs.CopyTo(ms);

                    FileWithMetadata fileWithMetadata = new FileWithMetadata()
                    {
                        Data        = ms,
                        ContentType = "application/zip",
                        Filename    = Path.GetFileName(localGiraffePositiveExamplesFilePath)
                    };
                    imagesFile.Add(fileWithMetadata);

                    service.WithHeader("X-Watson-Test", "1");
                    addImagesResult = service.AddImages(
                        collectionId: createdCollectionId,
                        imagesFile: imagesFile);
                }
            }

            var imageId = addImagesResult.Result.Images[0].ImageId;

            var objectName                    = giraffeClassname;
            var updatedObjectName             = "african giraffe";
            List <TrainingDataObject> objects = new List <TrainingDataObject>()
            {
                new TrainingDataObject()
                {
                    _Object  = objectName,
                    Location = new Location()
                    {
                        Left   = 270,
                        Top    = 64,
                        Width  = 755,
                        Height = 784
                    }
                }
            };

            service.WithHeader("X-Watson-Test", "1");
            var addTrainingDataResult = service.AddImageTrainingData(
                collectionId: createdCollectionId,
                imageId: imageId,
                objects: objects
                );

            service.WithHeader("X-Watson-Test", "1");
            var listObjectMetadataResult = service.ListObjectMetadata(
                collectionId: createdCollectionId
                );

            service.WithHeader("X-Watson-Test", "1");
            var updateObjectMetadataResult = service.UpdateObjectMetadata(
                collectionId: createdCollectionId,
                _object: objectName,
                newObject: updatedObjectName
                );

            service.WithHeader("X-Watson-Test", "1");
            var getObjectMetadataResult = service.GetObjectMetadata(
                collectionId: createdCollectionId,
                _object: updatedObjectName
                );

            service.WithHeader("X-Watson-Test", "1");
            var deleteObjectResult = service.DeleteObject(
                collectionId: createdCollectionId,
                _object: updatedObjectName
                );

            service.WithHeader("X-Watson-Test", "1");
            var deleteCollectionResult = service.DeleteCollection(
                collectionId: createdCollectionId);

            Assert.IsTrue(deleteObjectResult.StatusCode == 200);
            Assert.IsTrue(updateObjectMetadataResult.Result._Object == updatedObjectName);
            Assert.IsTrue(listObjectMetadataResult.Result.Objects[0]._Object == objectName);
            Assert.IsTrue(listObjectMetadataResult.Result.ObjectCount > 0);
            Assert.IsNotNull(listObjectMetadataResult.Result);
            Assert.IsTrue(deleteCollectionResult.StatusCode == 200);
            Assert.IsNotNull(createCollectionResult.Result);
            Assert.IsTrue(!string.IsNullOrEmpty(createdCollectionId));
            Assert.IsTrue(createCollectionResult.Result.Name == testCollectionName);
        }
        /// <summary>
        /// Submit a batch-processing request.
        ///
        /// Run Compare and Comply methods over a collection of input documents.
        ///
        /// **Important:** Batch processing requires the use of the [IBM Cloud Object Storage
        /// service](https://cloud.ibm.com/docs/services/cloud-object-storage?topic=cloud-object-storage-about#about-ibm-cloud-object-storage).
        /// The use of IBM Cloud Object Storage with Compare and Comply is discussed at [Using batch
        /// processing](https://cloud.ibm.com/docs/services/compare-comply?topic=compare-comply-batching#before-you-batch).
        /// </summary>
        /// <param name="function">The Compare and Comply method to run across the submitted input documents.</param>
        /// <param name="inputCredentialsFile">A JSON file containing the input Cloud Object Storage credentials. At a
        /// minimum, the credentials must enable `READ` permissions on the bucket defined by the `input_bucket_name`
        /// parameter.</param>
        /// <param name="inputBucketLocation">The geographical location of the Cloud Object Storage input bucket as
        /// listed on the **Endpoint** tab of your Cloud Object Storage instance; for example, `us-geo`, `eu-geo`, or
        /// `ap-geo`.</param>
        /// <param name="inputBucketName">The name of the Cloud Object Storage input bucket.</param>
        /// <param name="outputCredentialsFile">A JSON file that lists the Cloud Object Storage output credentials. At a
        /// minimum, the credentials must enable `READ` and `WRITE` permissions on the bucket defined by the
        /// `output_bucket_name` parameter.</param>
        /// <param name="outputBucketLocation">The geographical location of the Cloud Object Storage output bucket as
        /// listed on the **Endpoint** tab of your Cloud Object Storage instance; for example, `us-geo`, `eu-geo`, or
        /// `ap-geo`.</param>
        /// <param name="outputBucketName">The name of the Cloud Object Storage output bucket.</param>
        /// <param name="model">The analysis model to be used by the service. For the **Element classification** and
        /// **Compare two documents** methods, the default is `contracts`. For the **Extract tables** method, the
        /// default is `tables`. These defaults apply to the standalone methods as well as to the methods' use in
        /// batch-processing requests. (optional)</param>
        /// <returns><see cref="BatchStatus" />BatchStatus</returns>
        public DetailedResponse <BatchStatus> CreateBatch(string function, System.IO.MemoryStream inputCredentialsFile, string inputBucketLocation, string inputBucketName, System.IO.MemoryStream outputCredentialsFile, string outputBucketLocation, string outputBucketName, string model = null)
        {
            if (string.IsNullOrEmpty(function))
            {
                throw new ArgumentNullException("`function` is required for `CreateBatch`");
            }
            if (inputCredentialsFile == null)
            {
                throw new ArgumentNullException("`inputCredentialsFile` is required for `CreateBatch`");
            }
            if (string.IsNullOrEmpty(inputBucketLocation))
            {
                throw new ArgumentNullException("`inputBucketLocation` is required for `CreateBatch`");
            }
            if (string.IsNullOrEmpty(inputBucketName))
            {
                throw new ArgumentNullException("`inputBucketName` is required for `CreateBatch`");
            }
            if (outputCredentialsFile == null)
            {
                throw new ArgumentNullException("`outputCredentialsFile` is required for `CreateBatch`");
            }
            if (string.IsNullOrEmpty(outputBucketLocation))
            {
                throw new ArgumentNullException("`outputBucketLocation` is required for `CreateBatch`");
            }
            if (string.IsNullOrEmpty(outputBucketName))
            {
                throw new ArgumentNullException("`outputBucketName` is required for `CreateBatch`");
            }

            if (string.IsNullOrEmpty(VersionDate))
            {
                throw new ArgumentNullException("versionDate cannot be null.");
            }

            DetailedResponse <BatchStatus> result = null;

            try
            {
                var formData = new MultipartFormDataContent();

                if (inputCredentialsFile != null)
                {
                    var inputCredentialsFileContent = new ByteArrayContent(inputCredentialsFile.ToArray());
                    System.Net.Http.Headers.MediaTypeHeaderValue contentType;
                    System.Net.Http.Headers.MediaTypeHeaderValue.TryParse("application/json", out contentType);
                    inputCredentialsFileContent.Headers.ContentType = contentType;
                    formData.Add(inputCredentialsFileContent, "input_credentials_file", "filename");
                }

                if (inputBucketLocation != null)
                {
                    var inputBucketLocationContent = new StringContent(inputBucketLocation, Encoding.UTF8, HttpMediaType.TEXT_PLAIN);
                    inputBucketLocationContent.Headers.ContentType = null;
                    formData.Add(inputBucketLocationContent, "input_bucket_location");
                }

                if (inputBucketName != null)
                {
                    var inputBucketNameContent = new StringContent(inputBucketName, Encoding.UTF8, HttpMediaType.TEXT_PLAIN);
                    inputBucketNameContent.Headers.ContentType = null;
                    formData.Add(inputBucketNameContent, "input_bucket_name");
                }

                if (outputCredentialsFile != null)
                {
                    var outputCredentialsFileContent = new ByteArrayContent(outputCredentialsFile.ToArray());
                    System.Net.Http.Headers.MediaTypeHeaderValue contentType;
                    System.Net.Http.Headers.MediaTypeHeaderValue.TryParse("application/json", out contentType);
                    outputCredentialsFileContent.Headers.ContentType = contentType;
                    formData.Add(outputCredentialsFileContent, "output_credentials_file", "filename");
                }

                if (outputBucketLocation != null)
                {
                    var outputBucketLocationContent = new StringContent(outputBucketLocation, Encoding.UTF8, HttpMediaType.TEXT_PLAIN);
                    outputBucketLocationContent.Headers.ContentType = null;
                    formData.Add(outputBucketLocationContent, "output_bucket_location");
                }

                if (outputBucketName != null)
                {
                    var outputBucketNameContent = new StringContent(outputBucketName, Encoding.UTF8, HttpMediaType.TEXT_PLAIN);
                    outputBucketNameContent.Headers.ContentType = null;
                    formData.Add(outputBucketNameContent, "output_bucket_name");
                }

                IClient client = this.Client;
                SetAuthentication();

                var restRequest = client.PostAsync($"{this.Endpoint}/v1/batches");

                restRequest.WithArgument("version", VersionDate);
                restRequest.WithHeader("Accept", "application/json");
                if (!string.IsNullOrEmpty(function))
                {
                    restRequest.WithArgument("function", function);
                }
                if (!string.IsNullOrEmpty(model))
                {
                    restRequest.WithArgument("model", model);
                }
                restRequest.WithBodyContent(formData);

                restRequest.WithHeaders(Common.GetSdkHeaders("compare-comply", "v1", "CreateBatch"));
                restRequest.WithHeaders(customRequestHeaders);
                ClearCustomRequestHeaders();

                result = restRequest.As <BatchStatus>().Result;
                if (result == null)
                {
                    result = new DetailedResponse <BatchStatus>();
                }
            }
            catch (AggregateException ae)
            {
                throw ae.Flatten();
            }

            return(result);
        }
        /// <summary>
        /// Query a project.
        ///
        /// By using this method, you can construct queries. For details, see the [Discovery
        /// documentation](https://cloud.ibm.com/docs/services/discovery-data?topic=discovery-data-query-concepts).
        /// </summary>
        /// <param name="projectId">The ID of the project. This information can be found from the deploy page of the
        /// Discovery administrative tooling.</param>
        /// <param name="queryLong">An object that represents the query to be submitted. (optional)</param>
        /// <returns><see cref="QueryResponse" />QueryResponse</returns>
        public DetailedResponse <QueryResponse> Query(string projectId, List <string> collectionIds = null, string filter = null, string query = null, string naturalLanguageQuery = null, string aggregation = null, long?count = null, List <string> _return = null, long?offset = null, string sort = null, bool?highlight = null, bool?spellingSuggestions = null, QueryLargeTableResults tableResults = null, QueryLargeSuggestedRefinements suggestedRefinements = null, QueryLargePassages passages = null)
        {
            if (string.IsNullOrEmpty(projectId))
            {
                throw new ArgumentNullException("`projectId` is required for `Query`");
            }
            else
            {
                projectId = Uri.EscapeDataString(projectId);
            }

            if (string.IsNullOrEmpty(VersionDate))
            {
                throw new ArgumentNullException("versionDate cannot be null.");
            }

            DetailedResponse <QueryResponse> result = null;

            try
            {
                IClient client = this.Client;
                SetAuthentication();

                var restRequest = client.PostAsync($"{this.Endpoint}/v2/projects/{projectId}/query");

                restRequest.WithArgument("version", VersionDate);
                restRequest.WithHeader("Accept", "application/json");
                restRequest.WithHeader("Content-Type", "application/json");

                JObject bodyObject = new JObject();
                if (collectionIds != null && collectionIds.Count > 0)
                {
                    bodyObject["collection_ids"] = JToken.FromObject(collectionIds);
                }
                if (!string.IsNullOrEmpty(filter))
                {
                    bodyObject["filter"] = filter;
                }
                if (!string.IsNullOrEmpty(query))
                {
                    bodyObject["query"] = query;
                }
                if (!string.IsNullOrEmpty(naturalLanguageQuery))
                {
                    bodyObject["natural_language_query"] = naturalLanguageQuery;
                }
                if (!string.IsNullOrEmpty(aggregation))
                {
                    bodyObject["aggregation"] = aggregation;
                }
                if (count != null)
                {
                    bodyObject["count"] = JToken.FromObject(count);
                }
                if (_return != null && _return.Count > 0)
                {
                    bodyObject["return"] = JToken.FromObject(_return);
                }
                if (offset != null)
                {
                    bodyObject["offset"] = JToken.FromObject(offset);
                }
                if (!string.IsNullOrEmpty(sort))
                {
                    bodyObject["sort"] = sort;
                }
                if (highlight != null)
                {
                    bodyObject["highlight"] = JToken.FromObject(highlight);
                }
                if (spellingSuggestions != null)
                {
                    bodyObject["spelling_suggestions"] = JToken.FromObject(spellingSuggestions);
                }
                if (tableResults != null)
                {
                    bodyObject["table_results"] = JToken.FromObject(tableResults);
                }
                if (suggestedRefinements != null)
                {
                    bodyObject["suggested_refinements"] = JToken.FromObject(suggestedRefinements);
                }
                if (passages != null)
                {
                    bodyObject["passages"] = JToken.FromObject(passages);
                }
                var httpContent = new StringContent(JsonConvert.SerializeObject(bodyObject), Encoding.UTF8, HttpMediaType.APPLICATION_JSON);
                restRequest.WithBodyContent(httpContent);

                restRequest.WithHeaders(Common.GetSdkHeaders("discovery", "v2", "Query"));
                restRequest.WithHeaders(customRequestHeaders);
                ClearCustomRequestHeaders();

                result = restRequest.As <QueryResponse>().Result;
                if (result == null)
                {
                    result = new DetailedResponse <QueryResponse>();
                }
            }
            catch (AggregateException ae)
            {
                throw ae.Flatten();
            }

            return(result);
        }
Пример #25
0
        /// <summary>
        /// Create model.
        ///
        /// Uploads Translation Memory eXchange (TMX) files to customize a translation model.
        ///
        /// You can either customize a model with a forced glossary or with a corpus that contains parallel sentences.
        /// To create a model that is customized with a parallel corpus <b>and</b> a forced glossary, proceed in two
        /// steps: customize with a parallel corpus first and then customize the resulting model with a glossary.
        /// Depending on the type of customization and the size of the uploaded corpora, training can range from minutes
        /// for a glossary to several hours for a large parallel corpus. You can upload a single forced glossary file
        /// and this file must be less than <b>10 MB</b>. You can upload multiple parallel corpora tmx files. The
        /// cumulative file size of all uploaded files is limited to <b>250 MB</b>. To successfully train with a
        /// parallel corpus you must have at least <b>5,000 parallel sentences</b> in your corpus.
        ///
        /// You can have a <b>maxium of 10 custom models per language pair</b>.
        /// </summary>
        /// <param name="baseModelId">The model ID of the model to use as the base for customization. To see available
        /// models, use the `List models` method. Usually all IBM provided models are customizable. In addition, all
        /// your models that have been created via parallel corpus customization, can be further customized with a
        /// forced glossary.</param>
        /// <param name="forcedGlossary">A TMX file with your customizations. The customizations in the file completely
        /// overwrite the domain translaton data, including high frequency or high confidence phrase translations. You
        /// can upload only one glossary with a file size less than 10 MB per call. A forced glossary should contain
        /// single words or short phrases. (optional)</param>
        /// <param name="parallelCorpus">A TMX file with parallel sentences for source and target language. You can
        /// upload multiple parallel_corpus files in one request. All uploaded parallel_corpus files combined, your
        /// parallel corpus must contain at least 5,000 parallel sentences to train successfully. (optional)</param>
        /// <param name="name">An optional model name that you can use to identify the model. Valid characters are
        /// letters, numbers, dashes, underscores, spaces and apostrophes. The maximum length is 32 characters.
        /// (optional)</param>
        /// <returns><see cref="TranslationModel" />TranslationModel</returns>
        public DetailedResponse <TranslationModel> CreateModel(string baseModelId, System.IO.MemoryStream forcedGlossary = null, System.IO.MemoryStream parallelCorpus = null, string name = null)
        {
            if (string.IsNullOrEmpty(baseModelId))
            {
                throw new ArgumentNullException("`baseModelId` is required for `CreateModel`");
            }

            if (string.IsNullOrEmpty(VersionDate))
            {
                throw new ArgumentNullException("versionDate cannot be null.");
            }

            DetailedResponse <TranslationModel> result = null;

            try
            {
                var formData = new MultipartFormDataContent();

                if (forcedGlossary != null)
                {
                    var forcedGlossaryContent = new ByteArrayContent(forcedGlossary.ToArray());
                    System.Net.Http.Headers.MediaTypeHeaderValue contentType;
                    System.Net.Http.Headers.MediaTypeHeaderValue.TryParse("application/octet-stream", out contentType);
                    forcedGlossaryContent.Headers.ContentType = contentType;
                    formData.Add(forcedGlossaryContent, "forced_glossary", "filename");
                }

                if (parallelCorpus != null)
                {
                    var parallelCorpusContent = new ByteArrayContent(parallelCorpus.ToArray());
                    System.Net.Http.Headers.MediaTypeHeaderValue contentType;
                    System.Net.Http.Headers.MediaTypeHeaderValue.TryParse("application/octet-stream", out contentType);
                    parallelCorpusContent.Headers.ContentType = contentType;
                    formData.Add(parallelCorpusContent, "parallel_corpus", "filename");
                }

                IClient client = this.Client;
                SetAuthentication();

                var restRequest = client.PostAsync($"{this.Endpoint}/v3/models");

                restRequest.WithArgument("version", VersionDate);
                restRequest.WithHeader("Accept", "application/json");
                if (!string.IsNullOrEmpty(baseModelId))
                {
                    restRequest.WithArgument("base_model_id", baseModelId);
                }
                if (!string.IsNullOrEmpty(name))
                {
                    restRequest.WithArgument("name", name);
                }
                restRequest.WithBodyContent(formData);

                restRequest.WithHeaders(Common.GetSdkHeaders("language_translator", "v3", "CreateModel"));
                restRequest.WithHeaders(customRequestHeaders);
                ClearCustomRequestHeaders();

                result = restRequest.As <TranslationModel>().Result;
                if (result == null)
                {
                    result = new DetailedResponse <TranslationModel>();
                }
            }
            catch (AggregateException ae)
            {
                throw ae.Flatten();
            }

            return(result);
        }
        /// <summary>
        /// Get Autocomplete Suggestions.
        ///
        /// Returns completion query suggestions for the specified prefix.
        /// </summary>
        /// <param name="projectId">The ID of the project. This information can be found from the deploy page of the
        /// Discovery administrative tooling.</param>
        /// <param name="prefix">The prefix to use for autocompletion. For example, the prefix `Ho` could autocomplete
        /// to `Hot`, `Housing`, or `How do I upgrade`. Possible completions are.</param>
        /// <param name="collectionIds">Comma separated list of the collection IDs. If this parameter is not specified,
        /// all collections in the project are used. (optional)</param>
        /// <param name="field">The field in the result documents that autocompletion suggestions are identified from.
        /// (optional)</param>
        /// <param name="count">The number of autocompletion suggestions to return. (optional)</param>
        /// <returns><see cref="Completions" />Completions</returns>
        public DetailedResponse <Completions> GetAutocompletion(string projectId, string prefix, List <string> collectionIds = null, string field = null, long?count = null)
        {
            if (string.IsNullOrEmpty(projectId))
            {
                throw new ArgumentNullException("`projectId` is required for `GetAutocompletion`");
            }
            else
            {
                projectId = Uri.EscapeDataString(projectId);
            }
            if (string.IsNullOrEmpty(prefix))
            {
                throw new ArgumentNullException("`prefix` is required for `GetAutocompletion`");
            }

            if (string.IsNullOrEmpty(VersionDate))
            {
                throw new ArgumentNullException("versionDate cannot be null.");
            }

            DetailedResponse <Completions> result = null;

            try
            {
                IClient client = this.Client;
                SetAuthentication();

                var restRequest = client.GetAsync($"{this.Endpoint}/v2/projects/{projectId}/autocompletion");

                restRequest.WithArgument("version", VersionDate);
                restRequest.WithHeader("Accept", "application/json");
                if (!string.IsNullOrEmpty(prefix))
                {
                    restRequest.WithArgument("prefix", prefix);
                }
                if (collectionIds != null && collectionIds.Count > 0)
                {
                    restRequest.WithArgument("collection_ids", string.Join(",", collectionIds.ToArray()));
                }
                if (!string.IsNullOrEmpty(field))
                {
                    restRequest.WithArgument("field", field);
                }
                if (count != null)
                {
                    restRequest.WithArgument("count", count);
                }

                restRequest.WithHeaders(Common.GetSdkHeaders("discovery", "v2", "GetAutocompletion"));
                restRequest.WithHeaders(customRequestHeaders);
                ClearCustomRequestHeaders();

                result = restRequest.As <Completions>().Result;
                if (result == null)
                {
                    result = new DetailedResponse <Completions>();
                }
            }
            catch (AggregateException ae)
            {
                throw ae.Flatten();
            }

            return(result);
        }
Пример #27
0
        public void Tone_Success_With_ToneInput()
        {
            IClient client = CreateClient();

            #region response
            var response = new DetailedResponse <ToneAnalysis>()
            {
                Result = new ToneAnalysis()
                {
                    SentencesTone = new List <SentenceAnalysis>()
                    {
                        new SentenceAnalysis()
                        {
                            SentenceId     = 0,
                            InputFrom      = 0,
                            InputTo        = 0,
                            Text           = "string",
                            ToneCategories = new List <ToneCategory>()
                            {
                                new ToneCategory()
                                {
                                    CategoryName = "string",
                                    CategoryId   = "string",
                                    Tones        = new List <ToneScore>()
                                    {
                                        new ToneScore()
                                        {
                                            ToneName = "string",
                                            ToneId   = "string",
                                            Score    = 0
                                        }
                                    }
                                }
                            }
                        }
                    },
                    DocumentTone = new DocumentAnalysis()
                    {
                        ToneCategories = new List <ToneCategory>()
                        {
                            new ToneCategory()
                            {
                                CategoryName = "string",
                                CategoryId   = "string",
                                Tones        = new List <ToneScore>()
                                {
                                    new ToneScore()
                                    {
                                        ToneName = "string",
                                        ToneId   = "string",
                                        Score    = 0
                                    }
                                }
                            }
                        }
                    }
                }
            };
            #endregion

            IRequest request = Substitute.For <IRequest>();

            client.PostAsync(Arg.Any <string>())
            .Returns(request);

            request.WithHeader(Arg.Any <string>(), Arg.Any <string>())
            .Returns(request);
            request.WithArgument(Arg.Any <string>(), Arg.Any <bool>())
            .Returns(request);
            request.WithArgument(Arg.Any <string>(), Arg.Any <List <string> >())
            .Returns(request);
            request.WithBody <ToneInput>(Arg.Any <ToneInput>())
            .Returns(request);
            request.As <ToneAnalysis>()
            .Returns(Task.FromResult(response));

            ToneAnalyzerService service = new ToneAnalyzerService(client);
            service.VersionDate = "2016-05-19";
            service.UserName    = "******";
            service.Password    = "******";

            ToneInput toneInput = new ToneInput()
            {
                Text = Arg.Any <string>()
            };

            var analyzeTone = service.Tone(toneInput, "text/html");

            //client.Received().PostAsync(Arg.Any<string>());
            Assert.IsNotNull(analyzeTone);
            Assert.IsNotNull(analyzeTone.Result.DocumentTone);
            Assert.IsNotNull(analyzeTone.Result.DocumentTone.ToneCategories);
            Assert.IsTrue(analyzeTone.Result.DocumentTone.ToneCategories.Count >= 1);
            Assert.IsNotNull(analyzeTone.Result.SentencesTone);
            Assert.IsTrue(analyzeTone.Result.SentencesTone.Count >= 1);
            Assert.IsNotNull(analyzeTone.Result.SentencesTone[0].ToneCategories);
            Assert.IsTrue(analyzeTone.Result.SentencesTone[0].SentenceId == 0);
            Assert.IsTrue(analyzeTone.Result.SentencesTone[0].Text == "string");
            Assert.IsTrue(analyzeTone.Result.SentencesTone[0].ToneCategories.Count >= 1);
            Assert.IsTrue(analyzeTone.Result.SentencesTone[0].ToneCategories[0].CategoryId == "string");
            Assert.IsTrue(analyzeTone.Result.SentencesTone[0].ToneCategories[0].CategoryName == "string");
            Assert.IsNotNull(analyzeTone.Result.SentencesTone[0].ToneCategories[0].Tones);
            Assert.IsTrue(analyzeTone.Result.SentencesTone[0].ToneCategories[0].Tones.Count >= 1);
            Assert.IsTrue(analyzeTone.Result.SentencesTone[0].ToneCategories[0].Tones[0].ToneName == "string");
            Assert.IsTrue(analyzeTone.Result.SentencesTone[0].ToneCategories[0].Tones[0].ToneId == "string");
            Assert.IsTrue(analyzeTone.Result.SentencesTone[0].ToneCategories[0].Tones[0].Score == 0);
        }
        /// <summary>
        /// Query system notices.
        ///
        /// Queries for notices (errors or warnings) that might have been generated by the system. Notices are generated
        /// when ingesting documents and performing relevance training.
        /// </summary>
        /// <param name="projectId">The ID of the project. This information can be found from the deploy page of the
        /// Discovery administrative tooling.</param>
        /// <param name="filter">A cacheable query that excludes documents that don't mention the query content. Filter
        /// searches are better for metadata-type searches and for assessing the concepts in the data set.
        /// (optional)</param>
        /// <param name="query">A query search returns all documents in your data set with full enrichments and full
        /// text, but with the most relevant documents listed first. (optional)</param>
        /// <param name="naturalLanguageQuery">A natural language query that returns relevant documents by utilizing
        /// training data and natural language understanding. (optional)</param>
        /// <param name="count">Number of results to return. The maximum for the **count** and **offset** values
        /// together in any one query is **10000**. (optional)</param>
        /// <param name="offset">The number of query results to skip at the beginning. For example, if the total number
        /// of results that are returned is 10 and the offset is 8, it returns the last two results. The maximum for the
        /// **count** and **offset** values together in any one query is **10000**. (optional)</param>
        /// <returns><see cref="QueryNoticesResponse" />QueryNoticesResponse</returns>
        public DetailedResponse <QueryNoticesResponse> QueryNotices(string projectId, string filter = null, string query = null, string naturalLanguageQuery = null, long?count = null, long?offset = null)
        {
            if (string.IsNullOrEmpty(projectId))
            {
                throw new ArgumentNullException("`projectId` is required for `QueryNotices`");
            }
            else
            {
                projectId = Uri.EscapeDataString(projectId);
            }

            if (string.IsNullOrEmpty(VersionDate))
            {
                throw new ArgumentNullException("versionDate cannot be null.");
            }

            DetailedResponse <QueryNoticesResponse> result = null;

            try
            {
                IClient client = this.Client;
                SetAuthentication();

                var restRequest = client.GetAsync($"{this.Endpoint}/v2/projects/{projectId}/notices");

                restRequest.WithArgument("version", VersionDate);
                restRequest.WithHeader("Accept", "application/json");
                if (!string.IsNullOrEmpty(filter))
                {
                    restRequest.WithArgument("filter", filter);
                }
                if (!string.IsNullOrEmpty(query))
                {
                    restRequest.WithArgument("query", query);
                }
                if (!string.IsNullOrEmpty(naturalLanguageQuery))
                {
                    restRequest.WithArgument("natural_language_query", naturalLanguageQuery);
                }
                if (count != null)
                {
                    restRequest.WithArgument("count", count);
                }
                if (offset != null)
                {
                    restRequest.WithArgument("offset", offset);
                }

                restRequest.WithHeaders(Common.GetSdkHeaders("discovery", "v2", "QueryNotices"));
                restRequest.WithHeaders(customRequestHeaders);
                ClearCustomRequestHeaders();

                result = restRequest.As <QueryNoticesResponse>().Result;
                if (result == null)
                {
                    result = new DetailedResponse <QueryNoticesResponse>();
                }
            }
            catch (AggregateException ae)
            {
                throw ae.Flatten();
            }

            return(result);
        }
Пример #29
0
        public void ToneChat_Success_With_ToneChatInput()
        {
            IClient client = CreateClient();

            #region response
            var response = new DetailedResponse <UtteranceAnalyses>()
            {
                Result = new UtteranceAnalyses()
                {
                    UtterancesTone = new List <UtteranceAnalysis>()
                    {
                        new UtteranceAnalysis()
                        {
                            UtteranceId   = 100,
                            UtteranceText = "utteranceText",
                            Tones         = new List <ToneChatScore>()
                            {
                                new ToneChatScore()
                                {
                                    ToneName = "string",
                                    ToneId   = ToneChatScore.ToneIdEnumValue.SAD,
                                    Score    = 0
                                }
                            }
                        }
                    }
                }
            };
            #endregion

            var utterances = new List <Utterance>()
            {
                new Utterance()
                {
                    Text = "utteranceText",
                    User = "******"
                }
            };

            IRequest request = Substitute.For <IRequest>();

            client.PostAsync(Arg.Any <string>())
            .Returns(request);

            request.WithArgument(Arg.Any <string>(), Arg.Any <string>())
            .Returns(request);
            request.WithHeader(Arg.Any <string>(), Arg.Any <string>())
            .Returns(request);
            request.WithBodyContent(Arg.Any <StringContent>())
            .Returns(request);
            request.As <UtteranceAnalyses>()
            .Returns(Task.FromResult(response));

            ToneAnalyzerService service = new ToneAnalyzerService(client);
            service.VersionDate = versionDate;

            var result = service.ToneChat(utterances);

            Assert.IsNotNull(result);
            client.Received().PostAsync(Arg.Any <string>());
            Assert.IsTrue(result.Result.UtterancesTone.Count >= 1);
            Assert.IsTrue(result.Result.UtterancesTone[0].Tones.Count >= 1);
            Assert.IsTrue(result.Result.UtterancesTone[0].Tones[0].ToneName == "string");
        }
        /// <summary>
        /// Update a document.
        ///
        /// Replace an existing document or add a document with a specified **document_id**. Starts ingesting a document
        /// with optional metadata.
        ///
        /// If the document is uploaded to a collection that has it's data shared with another collection, the
        /// **X-Watson-Discovery-Force** header must be set to `true`.
        ///
        /// **Note:** When uploading a new document with this method it automatically replaces any document stored with
        /// the same **document_id** if it exists.
        ///
        /// **Note:** This operation only works on collections created to accept direct file uploads. It cannot be used
        /// to modify a collection that conects to an external source such as Microsoft SharePoint.
        /// </summary>
        /// <param name="projectId">The ID of the project. This information can be found from the deploy page of the
        /// Discovery administrative tooling.</param>
        /// <param name="collectionId">The ID of the collection.</param>
        /// <param name="documentId">The ID of the document.</param>
        /// <param name="file">The content of the document to ingest. The maximum supported file size when adding a file
        /// to a collection is 50 megabytes, the maximum supported file size when testing a confiruration is 1 megabyte.
        /// Files larger than the supported size are rejected. (optional)</param>
        /// <param name="filename">The filename for file. (optional)</param>
        /// <param name="fileContentType">The content type of file. (optional)</param>
        /// <param name="metadata">The maximum supported metadata file size is 1 MB. Metadata parts larger than 1 MB are
        /// rejected. Example:  ``` {
        ///   "Creator": "Johnny Appleseed",
        ///   "Subject": "Apples"
        /// } ```. (optional)</param>
        /// <param name="xWatsonDiscoveryForce">When `true`, the uploaded document is added to the collection even if
        /// the data for that collection is shared with other collections. (optional, default to false)</param>
        /// <returns><see cref="DocumentAccepted" />DocumentAccepted</returns>
        public DetailedResponse <DocumentAccepted> UpdateDocument(string projectId, string collectionId, string documentId, System.IO.MemoryStream file = null, string filename = null, string fileContentType = null, string metadata = null, bool?xWatsonDiscoveryForce = null)
        {
            if (string.IsNullOrEmpty(projectId))
            {
                throw new ArgumentNullException("`projectId` is required for `UpdateDocument`");
            }
            else
            {
                projectId = Uri.EscapeDataString(projectId);
            }
            if (string.IsNullOrEmpty(collectionId))
            {
                throw new ArgumentNullException("`collectionId` is required for `UpdateDocument`");
            }
            else
            {
                collectionId = Uri.EscapeDataString(collectionId);
            }
            if (string.IsNullOrEmpty(documentId))
            {
                throw new ArgumentNullException("`documentId` is required for `UpdateDocument`");
            }
            else
            {
                documentId = Uri.EscapeDataString(documentId);
            }

            if (string.IsNullOrEmpty(VersionDate))
            {
                throw new ArgumentNullException("versionDate cannot be null.");
            }

            DetailedResponse <DocumentAccepted> result = null;

            try
            {
                var formData = new MultipartFormDataContent();

                if (file != null)
                {
                    var fileContent = new ByteArrayContent(file.ToArray());
                    System.Net.Http.Headers.MediaTypeHeaderValue contentType;
                    System.Net.Http.Headers.MediaTypeHeaderValue.TryParse(fileContentType, out contentType);
                    fileContent.Headers.ContentType = contentType;
                    formData.Add(fileContent, "file", filename);
                }

                if (metadata != null)
                {
                    var metadataContent = new StringContent(metadata, Encoding.UTF8, HttpMediaType.TEXT_PLAIN);
                    metadataContent.Headers.ContentType = null;
                    formData.Add(metadataContent, "metadata");
                }

                IClient client = this.Client;
                SetAuthentication();

                var restRequest = client.PostAsync($"{this.Endpoint}/v2/projects/{projectId}/collections/{collectionId}/documents/{documentId}");

                restRequest.WithArgument("version", VersionDate);
                restRequest.WithHeader("Accept", "application/json");

                if (xWatsonDiscoveryForce != null)
                {
                    restRequest.WithHeader("X-Watson-Discovery-Force", (bool)xWatsonDiscoveryForce ? "true" : "false");
                }
                restRequest.WithBodyContent(formData);

                restRequest.WithHeaders(Common.GetSdkHeaders("discovery", "v2", "UpdateDocument"));
                restRequest.WithHeaders(customRequestHeaders);
                ClearCustomRequestHeaders();

                result = restRequest.As <DocumentAccepted>().Result;
                if (result == null)
                {
                    result = new DetailedResponse <DocumentAccepted>();
                }
            }
            catch (AggregateException ae)
            {
                throw ae.Flatten();
            }

            return(result);
        }