Example #1
0
        /// <summary>Snippet for CreateModelAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public async Task CreateModelRequestObjectAsync()
        {
            // Create client
            AutoMlClient autoMlClient = await AutoMlClient.CreateAsync();

            // Initialize request argument(s)
            CreateModelRequest request = new CreateModelRequest
            {
                ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
                Model = new Model(),
            };
            // Make the request
            Operation <Model, OperationMetadata> response = await autoMlClient.CreateModelAsync(request);

            // Poll until the returned long-running operation is complete
            Operation <Model, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();

            // Retrieve the operation result
            Model result = completedResponse.Result;

            // Or get the name of the operation
            string operationName = response.Name;
            // This name can be stored, then the long-running operation retrieved later by name
            Operation <Model, OperationMetadata> retrievedResponse = await autoMlClient.PollOnceCreateModelAsync(operationName);

            // Check if the retrieved long-running operation has completed
            if (retrievedResponse.IsCompleted)
            {
                // If it has completed, then access the result
                Model retrievedResult = retrievedResponse.Result;
            }
        }
Example #2
0
        /// <summary>Snippet for CreateModelAsync</summary>
        public async Task CreateModelRequestObjectAsync()
        {
            // Snippet: CreateModelAsync(CreateModelRequest, CallSettings)
            // Additional: CreateModelAsync(CreateModelRequest, CancellationToken)
            // Create client
            AutoMlClient autoMlClient = await AutoMlClient.CreateAsync();

            // Initialize request argument(s)
            CreateModelRequest request = new CreateModelRequest
            {
                Parent = "",
                Model  = new Model(),
            };
            // Make the request
            Operation <Model, OperationMetadata> response = await autoMlClient.CreateModelAsync(request);

            // Poll until the returned long-running operation is complete
            Operation <Model, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();

            // Retrieve the operation result
            Model result = completedResponse.Result;

            // Or get the name of the operation
            string operationName = response.Name;
            // This name can be stored, then the long-running operation retrieved later by name
            Operation <Model, OperationMetadata> retrievedResponse = await autoMlClient.PollOnceCreateModelAsync(operationName);

            // Check if the retrieved long-running operation has completed
            if (retrievedResponse.IsCompleted)
            {
                // If it has completed, then access the result
                Model retrievedResult = retrievedResponse.Result;
            }
            // End snippet
        }
 public virtual RecommendationModel CreateModel(CreateModelRequest request)
 {
     return(PolicyService.ExecuteRetryAndCapture400Errors(
                "RecommendationsService.CreateModel",
                ApiKeys.RecommendationsRetryInSeconds,
                () =>
     {
         var result = RecommendationsRepository.CreateModel(request);
         return result;
     },
                null));
 }
Example #4
0
        public virtual RecommendationModel CreateModel(CreateModelRequest request)
        {
            try
            {
                var result = Task.Run(async() => await RecommendationsRepository.CreateModelAsync(request)).Result;

                return(result);
            }
            catch (Exception ex)
            {
                Logger.Error("RecommendationsService.CreateModel failed", this, ex);
            }

            return(null);
        }
Example #5
0
        /// <summary>
        /// CreateModel接口的同步版本,部署模型,用以对外提供服务。有两种部署模式:`无服务器模式` 和 `集群模式`。`无服务器模式` 下,模型文件被部署到无服务器云函数,即 [SCF](https://cloud.tencent.com/product/scf),用户可以在其控制台上进一步操作。`集群模式` 下,模型文件被部署到 TI-A 的计算集群中。
        /// </summary>
        /// <param name="req">参考<see cref="CreateModelRequest"/></param>
        /// <returns>参考<see cref="CreateModelResponse"/>实例</returns>
        public CreateModelResponse CreateModelSync(CreateModelRequest req)
        {
            JsonResponseModel <CreateModelResponse> rsp = null;

            try
            {
                var strResp = this.InternalRequestSync(req, "CreateModel");
                rsp = JsonConvert.DeserializeObject <JsonResponseModel <CreateModelResponse> >(strResp);
            }
            catch (JsonSerializationException e)
            {
                throw new TencentCloudSDKException(e.Message);
            }
            return(rsp.Response);
        }
Example #6
0
        public virtual RecommendationModel CreateModel(CreateModelRequest request)
        {
            try
            {
                var result = RecommendationsRepository.CreateModel(request);

                return(result);
            }
            catch (Exception ex)
            {
                Logger.Error("RecommendationsService.CreateModel failed", this, ex);
            }

            return(null);
        }
Example #7
0
        protected override void ProcessRecord()
        {
            base.ProcessRecord();
            CreateModelRequest request;

            try
            {
                request = new CreateModelRequest
                {
                    CreateModelDetails = CreateModelDetails,
                    OpcRequestId       = OpcRequestId,
                    OpcRetryToken      = OpcRetryToken
                };

                response = client.CreateModel(request).GetAwaiter().GetResult();
                WriteOutput(response, response.Model);
                FinishProcessing(response);
            }
            catch (Exception ex)
            {
                TerminatingErrorDuringExecution(ex);
            }
        }
Example #8
0
        /// <summary>
        /// Uploads a TMX glossary file on top of a domain to customize a translation model.
        /// </summary>
        /// <param name="successCallback">The success callback.</param>
        /// <param name="failCallback">The fail callback.</param>
        /// <param name="baseModelId">Specifies the domain model that is used as the base for the training. To see current supported domain models, use the GET /v2/models parameter..</param>
        /// <param name="customModelName">The model name. Valid characters are letters, numbers, -, and _. No spaces.</param>
        /// <param name="forcedGlossaryFilePath">A TMX file with your customizations. The customizations in the file completely overwrite the domain data translation, including high frequency or high confidence phrase translations. You can upload only one glossary with a file size less than 10 MB per call.</param>
        /// <param name="parallelCorpusFilePath">A TMX file that contains entries that are treated as a parallel corpus instead of a glossary.</param>
        /// <param name="monolingualCorpusFilePath">A UTF-8 encoded plain text file that is used to customize the target language model.</param>
        /// <param name="customData">User defined custom string data.</param>
        /// <returns>True if the call succeeded, false if the call fails.</returns>
        public bool CreateModel(SuccessCallback <TranslationModel> successCallback, FailCallback failCallback, string baseModelId, string customModelName, string forcedGlossaryFilePath = default(string), string parallelCorpusFilePath = default(string), string monolingualCorpusFilePath = default(string), Dictionary <string, object> customData = null)
        {
            if (successCallback == null)
            {
                throw new ArgumentNullException("successCallback");
            }
            if (failCallback == null)
            {
                throw new ArgumentNullException("failCallback");
            }
            if (string.IsNullOrEmpty(baseModelId))
            {
                throw new ArgumentNullException("baseModelId");
            }
            if (string.IsNullOrEmpty(customModelName))
            {
                throw new ArgumentNullException("customModelName");
            }
            if (string.IsNullOrEmpty(forcedGlossaryFilePath) && string.IsNullOrEmpty(parallelCorpusFilePath) && string.IsNullOrEmpty(monolingualCorpusFilePath))
            {
                throw new ArgumentNullException("Either a forced glossary, parallel corpus or monolingual corpus is required to create a custom model.");
            }

            CreateModelRequest req = new CreateModelRequest();

            req.SuccessCallback        = successCallback;
            req.FailCallback           = failCallback;
            req.HttpMethod             = UnityWebRequest.kHttpVerbPOST;
            req.DisableSslVerification = DisableSslVerification;
            req.CustomData             = customData == null ? new Dictionary <string, object>() : customData;
            if (req.CustomData.ContainsKey(Constants.String.CUSTOM_REQUEST_HEADERS))
            {
                foreach (KeyValuePair <string, string> kvp in req.CustomData[Constants.String.CUSTOM_REQUEST_HEADERS] as Dictionary <string, string> )
                {
                    req.Headers.Add(kvp.Key, kvp.Value);
                }
            }
            req.Parameters["base_model_id"] = baseModelId;
            req.Parameters["name"]          = customModelName;
            req.OnResponse = OnCreateModelResponse;

            byte[] forcedGlossaryData    = null;
            byte[] parallelCorpusData    = null;
            byte[] monolingualCorpusData = null;

            if (!string.IsNullOrEmpty(forcedGlossaryFilePath))
            {
                try
                {
                    forcedGlossaryData = File.ReadAllBytes(forcedGlossaryFilePath);
                }
                catch (Exception e)
                {
                    Log.Debug("LanguageTranslator.CreateModel()", "There was an error loading the forced glossary file: {0}", e.Message);
                }
            }

            if (!string.IsNullOrEmpty(parallelCorpusFilePath))
            {
                try
                {
                    parallelCorpusData = File.ReadAllBytes(parallelCorpusFilePath);
                }
                catch (Exception e)
                {
                    Log.Debug("LanguageTranslator.CreateModel()", "There was an error loading the parallel corpus file: {0}", e.Message);
                }
            }

            if (!string.IsNullOrEmpty(monolingualCorpusFilePath))
            {
                try
                {
                    monolingualCorpusData = File.ReadAllBytes(monolingualCorpusFilePath);
                }
                catch (Exception e)
                {
                    Log.Debug("LanguageTranslator.CreateModel()", "There was an error loading the monolingual corpus file: {0}", e.Message);
                }
            }

            req.Forms = new Dictionary <string, RESTConnector.Form>();
            if (forcedGlossaryData != null)
            {
                req.Forms["forced_glossary"] = new RESTConnector.Form(forcedGlossaryData, Path.GetFileName(forcedGlossaryFilePath), "text/xml");
            }
            if (parallelCorpusData != null)
            {
                req.Forms["parallel_corpus"] = new RESTConnector.Form(parallelCorpusData);
            }
            if (monolingualCorpusData != null)
            {
                req.Forms["monolingual_corpus"] = new RESTConnector.Form(monolingualCorpusData);
            }

            RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v2/models");

            if (connector == null)
            {
                return(false);
            }

            return(connector.Send(req));
        }
        /// <summary>
        /// Uploads a TMX glossary file on top of a domain to customize a translation model.
        /// </summary>
        /// <param name="callback">The OnCreateModel callback.</param>
        /// <param name="baseModelId">Specifies the domain model that is used as the base for the training. To see current supported domain models, use the GET /v2/models parameter..</param>
        /// <param name="customModelName">The model name. Valid characters are letters, numbers, -, and _. No spaces.</param>
        /// <param name="forcedGlossaryFilePath">A TMX file with your customizations. The customizations in the file completely overwrite the domain data translation, including high frequency or high confidence phrase translations. You can upload only one glossary with a file size less than 10 MB per call.</param>
        /// <param name="parallelCorpusFilePath">A TMX file that contains entries that are treated as a parallel corpus instead of a glossary.</param>
        /// <param name="monolingualCorpusFilePath">A UTF-8 encoded plain text file that is used to customize the target language model.</param>
        /// <param name="customData">User defined custom string data.</param>
        /// <returns>True if the call succeeded, false if the call fails.</returns>
        public bool CreateModel(OnCreateModel callback, string baseModelId, string customModelName, string forcedGlossaryFilePath = default(string), string parallelCorpusFilePath = default(string), string monolingualCorpusFilePath = default(string), string customData = default(string))
        {
            if (callback == null)
            {
                throw new ArgumentNullException("callback");
            }
            if (string.IsNullOrEmpty(baseModelId))
            {
                throw new ArgumentNullException("baseModelId");
            }
            if (string.IsNullOrEmpty(customModelName))
            {
                throw new ArgumentNullException("customModelName");
            }
            if (string.IsNullOrEmpty(forcedGlossaryFilePath) && string.IsNullOrEmpty(parallelCorpusFilePath) && string.IsNullOrEmpty(monolingualCorpusFilePath))
            {
                throw new ArgumentNullException("Either a forced glossary, parallel corpus or monolingual corpus is required to create a custom model.");
            }

            CreateModelRequest req = new CreateModelRequest();

            req.Callback                    = callback;
            req.Data                        = customData;
            req.BaseModelId                 = baseModelId;
            req.CustomModelName             = customModelName;
            req.ForcedGlossaryFilePath      = forcedGlossaryFilePath;
            req.ParallelCorpusFilePath      = parallelCorpusFilePath;
            req.MonolingualCorpusFilePath   = monolingualCorpusFilePath;
            req.Parameters["base_model_id"] = baseModelId;
            req.Parameters["name"]          = customModelName;
            req.OnResponse                  = OnCreateModelResponse;

            byte[] forcedGlossaryData    = null;
            byte[] parallelCorpusData    = null;
            byte[] monolingualCorpusData = null;

            if (!string.IsNullOrEmpty(forcedGlossaryFilePath))
            {
                try
                {
                    forcedGlossaryData = File.ReadAllBytes(forcedGlossaryFilePath);
                }
                catch (Exception e)
                {
                    Log.Debug("LanguageTranslator", "There was an error loading the forced glossary file: {0}", e.Message);
                }
            }

            if (!string.IsNullOrEmpty(parallelCorpusFilePath))
            {
                try
                {
                    parallelCorpusData = File.ReadAllBytes(parallelCorpusFilePath);
                }
                catch (Exception e)
                {
                    Log.Debug("LanguageTranslator", "There was an error loading the parallel corpus file: {0}", e.Message);
                }
            }

            if (!string.IsNullOrEmpty(monolingualCorpusFilePath))
            {
                try
                {
                    monolingualCorpusData = File.ReadAllBytes(monolingualCorpusFilePath);
                }
                catch (Exception e)
                {
                    Log.Debug("LanguageTranslator", "There was an error loading the monolingual corpus file: {0}", e.Message);
                }
            }

            req.Forms = new Dictionary <string, RESTConnector.Form>();
            if (forcedGlossaryData != null)
            {
                req.Forms["forced_glossary"] = new RESTConnector.Form(forcedGlossaryData, Path.GetFileName(forcedGlossaryFilePath), "text/xml");
            }
            if (parallelCorpusData != null)
            {
                req.Forms["parallel_corpus"] = new RESTConnector.Form(parallelCorpusData);
            }
            if (monolingualCorpusData != null)
            {
                req.Forms["monolingual_corpus"] = new RESTConnector.Form(monolingualCorpusData);
            }

            RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v2/models");

            if (connector == null)
            {
                return(false);
            }

            return(connector.Send(req));
        }
            int OnExecute(IConsole console, IConfig config, IConfiguration appConfiguration, IMicrosoftCustomTranslatorAPIPreview10 sdk, IAccessTokenClient atc)
            {
                _sdk     = sdk;
                _atc     = atc;
                _console = console;

                // Populate the new model data
                var docIDs = new List <long?>();

                foreach (var docId in DocumentIDs.Split(','))
                {
                    docIDs.Add(Int64.Parse(docId));
                }
                var modelDefinition = new CreateModelRequest()
                {
                    Name          = Name,
                    DocumentIds   = docIDs,
                    IsTuningAuto  = true,
                    IsTestingAuto = true,
                    IsAutoDeploy  = true,
                    IsAutoTrain   = Train.HasValue ? true : false,
                    ProjectId     = new Guid(ProjectId)
                };

                if (!Json.HasValue)
                {
                    console.WriteLine("Creating model...");
                }

                CallApi(() => sdk.CreateModel(modelDefinition, atc.GetToken()));

                // CreateModel does not return the new model Id so we must query for it
                var res1 = CallApi <ModelsResponse>(() => sdk.GetProjectsByIdModels(new Guid(ProjectId), atc.GetToken(), 1, $"modelName eq {Name}"));

                if (res1 == null)
                {
                    return(-1);
                }

                if (res1.Models.Count == 0)
                {
                    if (!Json.HasValue)
                    {
                        console.WriteLine("Error: Model not created.");
                        return(-1);
                    }
                }
                else
                {
                    ModelInfo createdModel = res1.Models.FirstOrDefault((s) => s.Name == Name);
                    if (createdModel == null)
                    {
                        console.WriteLine("Error: Model not created.");
                        return(-1);
                    }

                    bool waitRequested = Wait && (modelDefinition.IsAutoTrain.HasValue && modelDefinition.IsAutoTrain.Value);
                    if (waitRequested)
                    {
                        CreateAndWait(() => sdk.GetModel(createdModel.Id, atc.GetToken()), createdModel.Id, true, (modelId) => IsTrained(modelId), Json.HasValue ? false : true);
                        createdModel = CallApi <ModelInfo>(() => sdk.GetModel(createdModel.Id, atc.GetToken()));
                    }

                    if (!Json.HasValue)
                    {
                        console.WriteLine($"{createdModel.Id,-10} {createdModel.Name,-50} {createdModel.ModelStatus}");
                    }
                    else
                    {
                        console.WriteLine(SafeJsonConvert.SerializeObject(createdModel, new Newtonsoft.Json.JsonSerializerSettings()
                        {
                            Formatting = Newtonsoft.Json.Formatting.Indented
                        }));
                    }
                }

                return(0);
            }
Example #11
0
        public async Task <RecommendationModel> CreateModelAsync(CreateModelRequest request)
        {
            var response = await SendPostAsync(modelsUrl, JsonConvert.SerializeObject(request));

            return(JsonConvert.DeserializeObject <RecommendationModel>(response));
        }
        public virtual async Task <RecommendationModel> CreateModelAsync(CreateModelRequest request)
        {
            var response = await RepositoryClient.SendJsonPostAsync(ApiKeys.Recommendations, modelsUrl, JsonConvert.SerializeObject(request));

            return(JsonConvert.DeserializeObject <RecommendationModel>(response));
        }