Exemplo n.º 1
0
        /// <summary>Snippet for BatchPredict</summary>
        public void BatchPredictRequestObject()
        {
            // Snippet: BatchPredict(BatchPredictRequest, CallSettings)
            // Create client
            PredictionServiceClient predictionServiceClient = PredictionServiceClient.Create();
            // Initialize request argument(s)
            BatchPredictRequest request = new BatchPredictRequest
            {
                ModelName    = ModelName.FromProjectLocationModel("[PROJECT]", "[LOCATION]", "[MODEL]"),
                InputConfig  = new BatchPredictInputConfig(),
                OutputConfig = new BatchPredictOutputConfig(),
                Params       = { { "", "" }, },
            };
            // Make the request
            Operation <BatchPredictResult, OperationMetadata> response = predictionServiceClient.BatchPredict(request);

            // Poll until the returned long-running operation is complete
            Operation <BatchPredictResult, OperationMetadata> completedResponse = response.PollUntilCompleted();
            // Retrieve the operation result
            BatchPredictResult 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 <BatchPredictResult, OperationMetadata> retrievedResponse = predictionServiceClient.PollOnceBatchPredict(operationName);

            // Check if the retrieved long-running operation has completed
            if (retrievedResponse.IsCompleted)
            {
                // If it has completed, then access the result
                BatchPredictResult retrievedResult = retrievedResponse.Result;
            }
            // End snippet
        }
Exemplo n.º 2
0
        /// <summary>Snippet for BatchPredict</summary>
        public void BatchPredict()
        {
            // Snippet: BatchPredict(ModelName,BatchPredictInputConfig,BatchPredictOutputConfig,IDictionary<string, string>,CallSettings)
            // Create client
            PredictionServiceClient predictionServiceClient = PredictionServiceClient.Create();
            // Initialize request argument(s)
            ModelName name = new ModelName("[PROJECT]", "[LOCATION]", "[MODEL]");
            BatchPredictInputConfig      inputConfig  = new BatchPredictInputConfig();
            BatchPredictOutputConfig     outputConfig = new BatchPredictOutputConfig();
            IDictionary <string, string> @params      = new Dictionary <string, string>();
            // Make the request
            Operation <BatchPredictResult, OperationMetadata> response =
                predictionServiceClient.BatchPredict(name, inputConfig, outputConfig, @params);

            // Poll until the returned long-running operation is complete
            Operation <BatchPredictResult, OperationMetadata> completedResponse =
                response.PollUntilCompleted();
            // Retrieve the operation result
            BatchPredictResult 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 <BatchPredictResult, OperationMetadata> retrievedResponse =
                predictionServiceClient.PollOnceBatchPredict(operationName);

            // Check if the retrieved long-running operation has completed
            if (retrievedResponse.IsCompleted)
            {
                // If it has completed, then access the result
                BatchPredictResult retrievedResult = retrievedResponse.Result;
            }
            // End snippet
        }
        /// <summary>Snippet for BatchPredict</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public void BatchPredict()
        {
            // Create client
            PredictionServiceClient predictionServiceClient = PredictionServiceClient.Create();
            // Initialize request argument(s)
            string name = "projects/[PROJECT]/locations/[LOCATION]/models/[MODEL]";
            BatchPredictInputConfig      inputConfig  = new BatchPredictInputConfig();
            BatchPredictOutputConfig     outputConfig = new BatchPredictOutputConfig();
            IDictionary <string, string> @params      = new Dictionary <string, string> {
                { "", "" },
            };
            // Make the request
            Operation <BatchPredictResult, OperationMetadata> response = predictionServiceClient.BatchPredict(name, inputConfig, outputConfig, @params);

            // Poll until the returned long-running operation is complete
            Operation <BatchPredictResult, OperationMetadata> completedResponse = response.PollUntilCompleted();
            // Retrieve the operation result
            BatchPredictResult 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 <BatchPredictResult, OperationMetadata> retrievedResponse = predictionServiceClient.PollOnceBatchPredict(operationName);

            // Check if the retrieved long-running operation has completed
            if (retrievedResponse.IsCompleted)
            {
                // If it has completed, then access the result
                BatchPredictResult retrievedResult = retrievedResponse.Result;
            }
        }
 /// <summary>Snippet for RawPredict</summary>
 public void RawPredict()
 {
     // Snippet: RawPredict(string, HttpBody, CallSettings)
     // Create client
     PredictionServiceClient predictionServiceClient = PredictionServiceClient.Create();
     // Initialize request argument(s)
     string   endpoint = "projects/[PROJECT]/locations/[LOCATION]/endpoints/[ENDPOINT]";
     HttpBody httpBody = new HttpBody();
     // Make the request
     HttpBody response = predictionServiceClient.RawPredict(endpoint, httpBody);
     // End snippet
 }
 /// <summary>Snippet for RawPredict</summary>
 public void RawPredictResourceNames()
 {
     // Snippet: RawPredict(EndpointName, HttpBody, CallSettings)
     // Create client
     PredictionServiceClient predictionServiceClient = PredictionServiceClient.Create();
     // Initialize request argument(s)
     EndpointName endpoint = EndpointName.FromProjectLocationEndpoint("[PROJECT]", "[LOCATION]", "[ENDPOINT]");
     HttpBody     httpBody = new HttpBody();
     // Make the request
     HttpBody response = predictionServiceClient.RawPredict(endpoint, httpBody);
     // End snippet
 }
        /// <summary>Snippet for Predict</summary>
        public void PredictRequestObject()
        {
            // Snippet: Predict(PredictRequest, CallSettings)
            // Create client
            PredictionServiceClient predictionServiceClient = PredictionServiceClient.Create();
            // Initialize request argument(s)
            PredictRequest request = new PredictRequest
            {
                PlacementName = PlacementName.FromProjectLocationCatalogEventStorePlacement("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]", "[PLACEMENT]"),
                UserEvent     = new UserEvent(),
                Filter        = "",
                DryRun        = false,
                Params        = { { "", new Value() }, },
                Labels        = { { "", "" }, },
            };
            // Make the request
            PagedEnumerable <PredictResponse, PredictResponse.Types.PredictionResult> response = predictionServiceClient.Predict(request);

            // Iterate over all response items, lazily performing RPCs as required
            foreach (PredictResponse.Types.PredictionResult item in response)
            {
                // Do something with each item
                Console.WriteLine(item);
            }

            // Or iterate over pages (of server-defined size), performing one RPC per page
            foreach (PredictResponse page in response.AsRawResponses())
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (PredictResponse.Types.PredictionResult item in page)
                {
                    // Do something with each item
                    Console.WriteLine(item);
                }
            }

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int pageSize = 10;
            Page <PredictResponse.Types.PredictionResult> singlePage = response.ReadPage(pageSize);

            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (PredictResponse.Types.PredictionResult item in singlePage)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
            // End snippet
        }
Exemplo n.º 7
0
 /// <summary>Snippet for Predict</summary>
 public void Predict()
 {
     // Snippet: Predict(string, IEnumerable<Value>, Value, CallSettings)
     // Create client
     PredictionServiceClient predictionServiceClient = PredictionServiceClient.Create();
     // Initialize request argument(s)
     string endpoint = "projects/[PROJECT]/locations/[LOCATION]/endpoints/[ENDPOINT]";
     IEnumerable <Value> instances = new Value[] { new Value(), };
     Value parameters = new Value();
     // Make the request
     PredictResponse response = predictionServiceClient.Predict(endpoint, instances, parameters);
     // End snippet
 }
Exemplo n.º 8
0
 /// <summary>Snippet for Predict</summary>
 public void PredictResourceNames()
 {
     // Snippet: Predict(EndpointName, IEnumerable<Value>, Value, CallSettings)
     // Create client
     PredictionServiceClient predictionServiceClient = PredictionServiceClient.Create();
     // Initialize request argument(s)
     EndpointName        endpoint  = EndpointName.FromProjectLocationEndpoint("[PROJECT]", "[LOCATION]", "[ENDPOINT]");
     IEnumerable <Value> instances = new Value[] { new Value(), };
     Value parameters = new Value();
     // Make the request
     PredictResponse response = predictionServiceClient.Predict(endpoint, instances, parameters);
     // End snippet
 }
Exemplo n.º 9
0
 /// <summary>Snippet for Predict</summary>
 /// <remarks>
 /// This snippet has been automatically generated for illustrative purposes only.
 /// It may require modifications to work in your environment.
 /// </remarks>
 public void Predict()
 {
     // Create client
     PredictionServiceClient predictionServiceClient = PredictionServiceClient.Create();
     // Initialize request argument(s)
     string         name    = "projects/[PROJECT]/locations/[LOCATION]/models/[MODEL]";
     ExamplePayload payload = new ExamplePayload();
     IDictionary <string, string> @params = new Dictionary <string, string> {
         { "", "" },
     };
     // Make the request
     PredictResponse response = predictionServiceClient.Predict(name, payload, @params);
 }
 /// <summary>Snippet for Predict</summary>
 /// <remarks>
 /// This snippet has been automatically generated for illustrative purposes only.
 /// It may require modifications to work in your environment.
 /// </remarks>
 public void PredictResourceNames()
 {
     // Create client
     PredictionServiceClient predictionServiceClient = PredictionServiceClient.Create();
     // Initialize request argument(s)
     ModelName      name    = ModelName.FromProjectLocationModel("[PROJECT]", "[LOCATION]", "[MODEL]");
     ExamplePayload payload = new ExamplePayload();
     IDictionary <string, string> @params = new Dictionary <string, string> {
         { "", "" },
     };
     // Make the request
     PredictResponse response = predictionServiceClient.Predict(name, payload, @params);
 }
Exemplo n.º 11
0
 /// <summary>Snippet for Predict</summary>
 public void Predict()
 {
     // Snippet: Predict(ModelName,ExamplePayload,IDictionary<string, string>,CallSettings)
     // Create client
     PredictionServiceClient predictionServiceClient = PredictionServiceClient.Create();
     // Initialize request argument(s)
     ModelName      name    = new ModelName("[PROJECT]", "[LOCATION]", "[MODEL]");
     ExamplePayload payload = new ExamplePayload();
     IDictionary <string, string> @params = new Dictionary <string, string>();
     // Make the request
     PredictResponse response = predictionServiceClient.Predict(name, payload, @params);
     // End snippet
 }
Exemplo n.º 12
0
 /// <summary>Snippet for Predict</summary>
 /// <remarks>
 /// This snippet has been automatically generated for illustrative purposes only.
 /// It may require modifications to work in your environment.
 /// </remarks>
 public void PredictRequestObject()
 {
     // Create client
     PredictionServiceClient predictionServiceClient = PredictionServiceClient.Create();
     // Initialize request argument(s)
     PredictRequest request = new PredictRequest
     {
         ModelName = ModelName.FromProjectLocationModel("[PROJECT]", "[LOCATION]", "[MODEL]"),
         Payload   = new ExamplePayload(),
         Params    = { { "", "" }, },
     };
     // Make the request
     PredictResponse response = predictionServiceClient.Predict(request);
 }
 /// <summary>Snippet for RawPredict</summary>
 public void RawPredictRequestObject()
 {
     // Snippet: RawPredict(RawPredictRequest, CallSettings)
     // Create client
     PredictionServiceClient predictionServiceClient = PredictionServiceClient.Create();
     // Initialize request argument(s)
     RawPredictRequest request = new RawPredictRequest
     {
         EndpointAsEndpointName = EndpointName.FromProjectLocationEndpoint("[PROJECT]", "[LOCATION]", "[ENDPOINT]"),
         HttpBody = new HttpBody(),
     };
     // Make the request
     HttpBody response = predictionServiceClient.RawPredict(request);
     // End snippet
 }
Exemplo n.º 14
0
 /// <summary>Snippet for Predict</summary>
 public void Predict_RequestObject()
 {
     // Snippet: Predict(PredictRequest,CallSettings)
     // Create client
     PredictionServiceClient predictionServiceClient = PredictionServiceClient.Create();
     // Initialize request argument(s)
     PredictRequest request = new PredictRequest
     {
         ModelName = new ModelName("[PROJECT]", "[LOCATION]", "[MODEL]"),
         Payload   = new ExamplePayload(),
     };
     // Make the request
     PredictResponse response = predictionServiceClient.Predict(request);
     // End snippet
 }
Exemplo n.º 15
0
 /// <summary>Snippet for Predict</summary>
 public void PredictRequestObject()
 {
     // Snippet: Predict(PredictRequest, CallSettings)
     // Create client
     PredictionServiceClient predictionServiceClient = PredictionServiceClient.Create();
     // Initialize request argument(s)
     PredictRequest request = new PredictRequest
     {
         EndpointAsEndpointName = EndpointName.FromProjectLocationEndpoint("[PROJECT]", "[LOCATION]", "[ENDPOINT]"),
         Instances  = { new Value(), },
         Parameters = new Value(),
     };
     // Make the request
     PredictResponse response = predictionServiceClient.Predict(request);
     // End snippet
 }
Exemplo n.º 16
0
 /// <summary>Snippet for Predict</summary>
 public void PredictRequestObject()
 {
     // Snippet: Predict(PredictRequest, CallSettings)
     // Create client
     PredictionServiceClient predictionServiceClient = PredictionServiceClient.Create();
     // Initialize request argument(s)
     PredictRequest request = new PredictRequest
     {
         Name    = "",
         Payload = new ExamplePayload(),
         Params  = { { "", "" }, },
     };
     // Make the request
     PredictResponse response = predictionServiceClient.Predict(request);
     // End snippet
 }
        /// <summary>Snippet for Predict</summary>
        public void Predict()
        {
            // Snippet: Predict(string, UserEvent, string, int?, CallSettings)
            // Create client
            PredictionServiceClient predictionServiceClient = PredictionServiceClient.Create();
            // Initialize request argument(s)
            string    name      = "projects/[PROJECT]/locations/[LOCATION]/catalogs/[CATALOG]/eventStores/[EVENT_STORE]/placements/[PLACEMENT]";
            UserEvent userEvent = new UserEvent();
            // Make the request
            PagedEnumerable <PredictResponse, PredictResponse.Types.PredictionResult> response = predictionServiceClient.Predict(name, userEvent);

            // Iterate over all response items, lazily performing RPCs as required
            foreach (PredictResponse.Types.PredictionResult item in response)
            {
                // Do something with each item
                Console.WriteLine(item);
            }

            // Or iterate over pages (of server-defined size), performing one RPC per page
            foreach (PredictResponse page in response.AsRawResponses())
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (PredictResponse.Types.PredictionResult item in page)
                {
                    // Do something with each item
                    Console.WriteLine(item);
                }
            }

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int pageSize = 10;
            Page <PredictResponse.Types.PredictionResult> singlePage = response.ReadPage(pageSize);

            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (PredictResponse.Types.PredictionResult item in singlePage)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
            // End snippet
        }
 /// <summary>Snippet for Explain</summary>
 public void ExplainRequestObject()
 {
     // Snippet: Explain(ExplainRequest, CallSettings)
     // Create client
     PredictionServiceClient predictionServiceClient = PredictionServiceClient.Create();
     // Initialize request argument(s)
     ExplainRequest request = new ExplainRequest
     {
         EndpointAsEndpointName = EndpointName.FromProjectLocationEndpoint("[PROJECT]", "[LOCATION]", "[ENDPOINT]"),
         Instances               = { new Value(), },
         DeployedModelId         = "",
         Parameters              = new Value(),
         ExplanationSpecOverride = new ExplanationSpecOverride(),
     };
     // Make the request
     ExplainResponse response = predictionServiceClient.Explain(request);
     // End snippet
 }
Exemplo n.º 19
0
 /// <summary>Snippet for Predict</summary>
 public void PredictRequestObject()
 {
     // Snippet: Predict(PredictRequest, CallSettings)
     // Create client
     PredictionServiceClient predictionServiceClient = PredictionServiceClient.Create();
     // Initialize request argument(s)
     PredictRequest request = new PredictRequest
     {
         Placement    = "",
         UserEvent    = new UserEvent(),
         PageSize     = 0,
         PageToken    = "",
         Filter       = "",
         ValidateOnly = false,
         Params       = { { "", new Value() }, },
         Labels       = { { "", "" }, },
     };
     // Make the request
     PredictResponse response = predictionServiceClient.Predict(request);
     // End snippet
 }
Exemplo n.º 20
0
        private void predict(string projectId, string locationId, string modelId, List <Value> values)
        {
            // Initialize client that will be used to send requests. This client only needs to be created
            // once, and can be reused for multiple requests. After completing all of your requests, call
            // the "close" method on the client to safely clean up any remaining background resources.
            PredictionServiceClient client = PredictionServiceClient.Create();

            //// Get the full path of the model.
            //ModelName name = new ModelName(projectId, locationId, modelId);
            ////.of(projectId, "us-central1", modelId);

            //Google.Cloud.AutoML.V1.ro Row row = Row.newBuilder().addAllValues(values).build();
            //ExamplePayload payload = ExamplePayload.newBuilder().setRow(row).build();

            // Feature importance gives you visibility into how the features in a specific prediction
            // request informed the resulting prediction. For more info, see:
            // https://cloud.google.com/automl-tables/docs/features#local
            //PredictRequest request = PredictRequest. newBuilder()
            //        .setName(name.toString())
            //        .setPayload(payload)
            //        .putParams("feature_importance", "true")
            //        .build();

            //PredictResponse response = client.Predict(request);

            //System.out.println("Prediction results:");
            //foreach (AnnotationPayload annotationPayload in response.getPayloadList()) {
            //TablesAnnotation tablesAnnotation = annotationPayload.getTables();
            //System.out.format("Classification label: %s%n", tablesAnnotation.getValue().getStringValue());
            //System.out.format("Classification score: %.3f%n", tablesAnnotation.getScore());
            // Get features of top importance
            //tablesAnnotation
            //    .getTablesModelColumnInfoList()
            //    .forEach(
            //        info ->
            //            System.out.format(
            //                "\tColumn: %s - Importance: %.2f%n",
            //                info.getColumnDisplayName(), info.getFeatureImportance()));
            //}
        }
Exemplo n.º 21
0
        private void prediction()
        {
            try
            {
                ExamplePayload payload = new ExamplePayload()
                {
                    //TextSnippet = new TextSnippet()
                    //{
                    //    Content = "{\"payload\":{\"row\":{\"values\":[\"3795.67486950037\",\"0.0\",\"30.0\"]}}}"
                    //}
                };


                PredictionServiceClient predictionServiceClient = PredictionServiceClient.Create();

                PredictRequest request = new PredictRequest
                {
                    ModelName = ModelName.FromProjectLocationModel("thermal-creek-272919", "us-central1", "TBL5828849788421931008"),
                    Payload   = payload,
                    //model_path = client.model_path('thermal-creek-272919', 'us-central1', 'TBL5828849788421931008')

                    Params = { { "feature_importance", "false" } },
                };

                var response = predictionServiceClient.Predict(request);
            }
            catch (Exception ex)
            {
                throw;
            }
            //mockGrpcClient.Setup(x => x.Predict(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);

            //PredictionServiceClient client = new PredictionServiceClientImpl(mockGrpcClient.Object, null);

            //PredictResponse response = client.Predict(request);
        }
        public ActionResult <ServiceResponse> Post([Bind("Url")][FromBody] ServiceRequest request)
        {
            // Boilerpipe.net code below
            string html     = "";
            string headline = "";
            string source   = "";
            string text     = "";
            string img      = "";

            try
            {
                if (Uri.IsWellFormedUriString(request.Url, UriKind.Absolute))
                {
                    using (WebClient webClient = new WebClient())
                    {
                        html = webClient.DownloadString(request.Url);
                    }
                    text     = RemoveSpecialCharacters(CommonExtractors.LargestContentExtractor.GetText(html));
                    headline = RemoveSpecialCharacters(Regex.Match(html, @"\<title\b[^>]*\>\s*(?<Title>[\s\S]*?)\</title\>",
                                                                   RegexOptions.IgnoreCase).Groups["Title"].Value);

                    var domainParser = new DomainParser(new WebTldRuleProvider());
                    var domainName   = domainParser.Get(request.Url);
                    source = domainName.RegistrableDomain;

                    img = "http://" + FetchLinksFromSource(html)[0].AbsolutePath;
                }
                else
                {
                    return(BadRequest(new ServiceResponse
                    {
                        Success = false,
                        Error = "Bad URL."
                    }));
                }

                // Google Cloud API code below
                var credential = GoogleCredential.FromJson(ServiceAccountJSON)
                                 .CreateScoped(LanguageServiceClient.DefaultScopes);
                var channel = new Grpc.Core.Channel(
                    AutoMlClient.DefaultEndpoint.ToString(),
                    credential.ToChannelCredentials());
                PredictionServiceClient client = PredictionServiceClient.Create(channel);

                string modelFullId = ModelName.Format("partem-1579924523879", "us-central1", "TCN7494917767758348288");

                PredictRequest predictRequest = new PredictRequest
                {
                    Name    = modelFullId,
                    Payload = new ExamplePayload
                    {
                        TextSnippet = new TextSnippet
                        {
                            Content  = text,
                            MimeType = "text/plain"
                        }
                    }
                };

                PredictResponse response = client.Predict(predictRequest);

                var leftPerc  = response.Payload.First(x => x.DisplayName == "left").Classification.Score;
                var rightPerc = response.Payload.First(x => x.DisplayName == "right").Classification.Score;
                return(Ok(new ServiceResponse
                {
                    LeftPercentage = leftPerc,
                    RightPercentage = rightPerc,
                    CenterPercentage = 1 - Math.Abs(leftPerc - rightPerc),

                    Headline = headline,
                    Source = source,
                    Image = img,

                    Success = true,
                }));
            }
            catch (Exception ex)
            {
                return(BadRequest(new ServiceResponse
                {
                    Success = false,
                    Error = "An error has occured. Please try again later."
                }));
            }
        }