//private async Task<ProductSet> GetProductSets(ProductSearchClient client, int pageSize)
        //{
        //    var request = new ListProductSetsRequest
        //    {
        //        ParentAsLocationName = new LocationName(this.options.Value.ProjectId, this.options.Value.LocationId),
        //        PageSize = pageSize,
        //    };

        //    return await client.ListProductSets(request);
        //}

        private async Task <Product> CreateProduct(ProductSearchClient client, CreateProductOptions opts)
        {
            var request = new CreateProductRequest
            {
                // A resource that represents Google Cloud Platform location.
                ParentAsLocationName = new LocationName(opts.ProjectID, opts.ComputeRegion),
                // Set product category and product display name
                Product = new Product
                {
                    DisplayName     = opts.DisplayName,
                    ProductCategory = opts.ProductCategory,
                    Description     = opts.Description ?? string.Empty,
                },
                ProductId = opts.ProductID
            };

            foreach (var label in opts.ProductLabels)
            {
                request.Product.ProductLabels.Add(new KeyValue {
                    Key = label.Key, Value = label.Value
                });
            }

            // The response is the product with the `name` field populated.
            var product = await client.CreateProductAsync(request);

            return(product);
        }
        public async Task DeleteTarget(string targetSetId, string targetId)
        {
            GoogleCredential cred = this.CreateCredentials();
            var channel           = new Channel(ProductSearchClient.DefaultEndpoint.Host, ProductSearchClient.DefaultEndpoint.Port, cred.ToChannelCredentials());

            try
            {
                var client  = ProductSearchClient.Create(channel);
                var storage = await StorageClient.CreateAsync(cred);

                IEnumerable <Google.Cloud.Vision.V1.ReferenceImage> referenceImages = await this.GetReferenceImages(client, targetId, 100);

                await Task.WhenAll(referenceImages.Select(async r =>
                {
                    await this.DeleteReferenceImage(client, targetId, r.ReferenceImageName.ReferenceImageId);
                    await this.DeleteFile(storage, this.options.Value.StorageBucketName, r.ReferenceImageName.ReferenceImageId);
                }));

                await this.RemoveProductFromProductSet(client, targetSetId, targetId);

                await this.DeleteProduct(client, targetId);
            }
            finally
            {
                await channel.ShutdownAsync();
            }
        }
        // [END vision_product_search_create_reference_image]

        // [START vision_product_search_list_reference_images]
        private static int ListReferenceImagesOfProduct(ListReferenceImagesOptions opts)
        {
            var client  = ProductSearchClient.Create();
            var request = new ListReferenceImagesRequest
            {
                // Get the full path of the product.
                ParentAsProductName = new ProductName(opts.ProjectID,
                                                      opts.ComputeRegion,
                                                      opts.ProductID)
            };

            var referenceImages = client.ListReferenceImages(request);

            foreach (var referenceImage in referenceImages)
            {
                var referenceImageID = referenceImage.Name.Split("/").Last();
                Console.WriteLine($"Reference image name: {referenceImage.Name}");
                Console.WriteLine($"Reference image id: {referenceImageID}");
                Console.WriteLine($"Reference image URI: {referenceImage.Uri}");
                Console.WriteLine("Reference image bounding polygons:");
                Console.WriteLine($"\t{referenceImage.BoundingPolys.ToString()}");
            }

            return(0);
        }
예제 #4
0
        // [END vision_product_search_create_product]

        // [START vision_product_search_list_products]
        private static int ListProducts(ListProductsOptions opts)
        {
            var client  = ProductSearchClient.Create();
            var request = new ListProductsRequest
            {
                // A resource that represents Google Cloud Platform location.
                ParentAsLocationName = new LocationName(opts.ProjectID,
                                                        opts.ComputeRegion)
            };

            var products = client.ListProducts(request);

            foreach (var product in products)
            {
                var productId = product.Name.Split("/").Last();
                Console.WriteLine($"\nProduct name: {product.Name}");
                Console.WriteLine($"Product id: {productId}");
                Console.WriteLine($"Product display name: {product.DisplayName}");
                Console.WriteLine($"Product category: {product.ProductCategory}");
                Console.WriteLine($"Product labels:");
                foreach (var label in product.ProductLabels)
                {
                    Console.WriteLine($"\tLabel: {label.ToString()}");
                }
            }
            return(0);
        }
예제 #5
0
        // [END vision_product_search_add_product_to_product_set]

        // [START vision_product_search_list_products_in_product_set]
        private static int ListProductsInProductSet(ListProductsInProductSetOptions opts)
        {
            var client  = ProductSearchClient.Create();
            var request = new ListProductsInProductSetRequest
            {
                // Get the full path of the product set.
                ProductSetName = new ProductSetName(opts.ProjectID,
                                                    opts.ComputeRegion,
                                                    opts.ProductSetId)
            };

            var products = client.ListProductsInProductSet(request);

            Console.WriteLine("Products in product set:");
            foreach (var product in products)
            {
                Console.WriteLine($"Product name: {product.Name}");
                Console.WriteLine($"Product id: {product.Name.Split("/").Last()}");
                Console.WriteLine($"Product display name: {product.DisplayName}");
                Console.WriteLine($"Product description: {product.Description}");
                Console.WriteLine($"Product category: {product.ProductCategory}");
                Console.WriteLine($"Product labels:");
                foreach (var label in product.ProductLabels)
                {
                    Console.WriteLine($"Label: {label}");
                }
            }

            return(0);
        }
        public async Task <IEnumerable <Target> > GetTargets(string targetSetId, int page, int pageSize)
        {
            GoogleCredential cred = this.CreateCredentials();
            var channel           = new Channel(ProductSearchClient.DefaultEndpoint.Host, ProductSearchClient.DefaultEndpoint.Port, cred.ToChannelCredentials());

            try
            {
                var client = ProductSearchClient.Create(channel);

                ListProductsInProductSetRequest request = new ListProductsInProductSetRequest
                {
                    ProductSetName = new ProductSetName(this.options.Value.ProjectId, this.options.Value.LocationId, targetSetId),
                    PageSize       = pageSize,
                };

                PagedAsyncEnumerable <ListProductsInProductSetResponse, Product> response = client.ListProductsInProductSetAsync(request);
                IEnumerable <Product> products = await response.AsAsyncEnumerable().ToArray();

                IEnumerable <Target> targets = await Task.WhenAll(products.Select(p => this.LoadReferenceImagesAndMapToTarget(client, p, pageSize)));

                return(targets);
            }
            finally
            {
                await channel.ShutdownAsync();
            }
        }
예제 #7
0
        // [END vision_product_search_list_products]

        // [START vision_product_search_get_product]
        private static int GetProduct(GetProductOptions opts)
        {
            var client  = ProductSearchClient.Create();
            var request = new GetProductRequest
            {
                // Get the full path of the product.
                ProductName = new ProductName(opts.ProjectID,
                                              opts.ComputeRegion,
                                              opts.ProductID)
            };

            var product = client.GetProduct(request);

            var productId = product.Name.Split("/").Last();

            Console.WriteLine($"\nProduct name: {product.Name}");
            Console.WriteLine($"Product id: {productId}");
            Console.WriteLine($"Product display name: {product.DisplayName}");
            Console.WriteLine($"Product category: {product.ProductCategory}");
            Console.WriteLine($"Product labels:");
            foreach (var label in product.ProductLabels)
            {
                Console.WriteLine($"\tLabel: {label.ToString()}");
            }
            return(0);
        }
        public async Task <Target> GetTarget(string targetId)
        {
            var client = await ProductSearchClient.CreateAsync();

            Product product = await this.GetProduct(client, targetId);

            return(await this.LoadReferenceImagesAndMapToTarget(client, product, 100));
        }
 public JsonResult Refresh()
 {
     using (var product = new ProductSearchClient())
     {
         var refresh = product.RemoveRedisCacheKey("Product", "KeywordBrandCache");
         return(Json(refresh.Result));
     }
 }
        //public async Task<Target> CreateTarget(string displayName, string description, IReadOnlyDictionary<string, string> labels, byte[] referenceImageBinaries)
        //{
        //    GoogleCredential cred = this.CreateCredentials();
        //    var channel = new Channel(ProductSearchClient.DefaultEndpoint.Host, ProductSearchClient.DefaultEndpoint.Port, cred.ToChannelCredentials());

        //    try
        //    {
        //        var client = ProductSearchClient.Create(channel);
        //        var storage = await StorageClient.CreateAsync(cred);

        //        string productId = Guid.NewGuid().ToString();
        //        var createProductOptions = new CreateProductOptions
        //        {
        //            ProjectID = this.options.Value.ProjectId,
        //            ComputeRegion = this.options.Value.LocationId,
        //            ProductID = productId,
        //            ProductCategory = "apparel",
        //            DisplayName = displayName,
        //            Description = description,
        //            ProductLabels = labels,
        //        };
        //        Product product = await this.CreateProduct(client, createProductOptions);

        //        var addProductOptions = new AddProductToProductSetOptions
        //        {
        //            ProjectID = this.options.Value.ProjectId,
        //            ComputeRegion = this.options.Value.LocationId,
        //            ProductID = product.ProductName.ProductId,
        //            ProductSetId = this.options.Value.ProductSetId,
        //        };
        //        await this.AddProductToProductSet(client, addProductOptions);

        //        string referenceImageId = Guid.NewGuid().ToString();
        //        await this.UploadFile(storage, this.options.Value.StorageBucketName, referenceImageId, referenceImageBinaries);

        //        var createReferenceImageOptions = new CreateReferenceImageOptions
        //        {
        //            ProjectID = this.options.Value.ProjectId,
        //            ComputeRegion = this.options.Value.LocationId,
        //            ProductID = product.ProductName.ProductId,
        //            ReferenceImageID = referenceImageId,
        //            ReferenceImageURI = $"gs://{this.options.Value.StorageBucketName}/{referenceImageId}",
        //        };
        //        Google.Cloud.Vision.V1.ReferenceImage referenceImage = await this.CreateReferenceImage(client, createReferenceImageOptions);

        //        Target target = this.mapper.Map<Target>(product);
        //        target.ReferenceImages = new ReferenceImage[] { this.mapper.Map<ReferenceImage>(referenceImage) };

        //        return target;
        //    }
        //    finally
        //    {
        //        await channel.ShutdownAsync();
        //    }
        //}

        //public async Task DeleteTarget(string targetSetId, string targetId)
        //{
        //    GoogleCredential cred = this.CreateCredentials();
        //    var channel = new Channel(ProductSearchClient.DefaultEndpoint.Host, ProductSearchClient.DefaultEndpoint.Port, cred.ToChannelCredentials());

        //    try
        //    {
        //        var client = ProductSearchClient.Create(channel);
        //        var storage = await StorageClient.CreateAsync(cred);

        //        IEnumerable<Google.Cloud.Vision.V1.ReferenceImage> referenceImages = await this.GetReferenceImages(client, targetId, 100);
        //        await Task.WhenAll(referenceImages.Select(async r =>
        //        {
        //            await this.DeleteReferenceImage(client, targetId, r.ReferenceImageName.ReferenceImageId);
        //            await this.DeleteFile(storage, this.options.Value.StorageBucketName, r.ReferenceImageName.ReferenceImageId);
        //        }));

        //        await this.RemoveProductFromProductSet(client, targetSetId, targetId);
        //        await this.DeleteProduct(client, targetId);

        //    }
        //    finally
        //    {
        //        await channel.ShutdownAsync();
        //    }
        //}

        //public async Task<TargetSearchResults> QuerySimilarTargets(byte[] image)
        //{
        //    GoogleCredential cred = this.CreateCredentials();
        //    var channel = new Channel(ProductSearchClient.DefaultEndpoint.Host, ProductSearchClient.DefaultEndpoint.Port, cred.ToChannelCredentials());

        //    try
        //    {
        //        var imageAnnotatorClient = ImageAnnotatorClient.Create(channel);

        //        var options = new GetSimilarProductsOptions
        //        {
        //            ProjectID = this.options.Value.ProjectId,
        //            ComputeRegion = this.options.Value.LocationId,
        //            ProductSetId = this.options.Value.ProductSetId,
        //            ProductCategory = "apparel",
        //            Filter = string.Empty,
        //            ImageBinaries = image,
        //        };

        //        return await this.GetSimilarProductsFile(imageAnnotatorClient, options);
        //    }
        //    catch (AnnotateImageException e)
        //    {
        //        this.logger.LogError(e, "The google cloud image recognition service threw an error.");
        //        return new TargetSearchResults
        //        {
        //            Results = new TargetSearchResultEntry[0],
        //        };
        //    }
        //    finally
        //    {
        //        await channel.ShutdownAsync();
        //    }
        //}

        //private async Task<ProductSet> CreateProductSet(ProductSearchClient client, CreateProductSetsOptions opts)
        //{
        //    // Create a product set with the product set specification in the region.
        //    var request = new CreateProductSetRequest
        //    {
        //        // A resource that represents Google Cloud Platform location
        //        ParentAsLocationName = new LocationName(opts.ProjectID, opts.ComputeRegion),
        //        ProductSetId = opts.ProductSetId,
        //        ProductSet = new ProductSet
        //        {
        //            DisplayName = opts.ProductSetDisplayName
        //        }
        //    };

        //    // The response is the product set with the `name` populated
        //    var response = await client.CreateProductSetAsync(request);

        //    return response;
        //}


        ////private async Task<ProductSet> GetProductSets(ProductSearchClient client, int pageSize)
        ////{
        ////    var request = new ListProductSetsRequest
        ////    {
        ////        ParentAsLocationName = new LocationName(this.options.Value.ProjectId, this.options.Value.LocationId),
        ////        PageSize = pageSize,
        ////    };

        ////    return await client.ListProductSets(request);
        ////}

        //private async Task<Product> CreateProduct(ProductSearchClient client, CreateProductOptions opts)
        //{
        //    var request = new CreateProductRequest
        //    {
        //        // A resource that represents Google Cloud Platform location.
        //        ParentAsLocationName = new LocationName(opts.ProjectID, opts.ComputeRegion),
        //        // Set product category and product display name
        //        Product = new Product
        //        {
        //            DisplayName = opts.DisplayName,
        //            ProductCategory = opts.ProductCategory,
        //            Description = opts.Description ?? string.Empty,
        //        },
        //        ProductId = opts.ProductID
        //    };

        //    foreach (var label in opts.ProductLabels)
        //    {
        //        request.Product.ProductLabels.Add(new KeyValue { Key = label.Key, Value = label.Value });
        //    }

        //    // The response is the product with the `name` field populated.
        //    var product = await client.CreateProductAsync(request);

        //    return product;
        //}

        private async Task <Product> GetProduct(ProductSearchClient client, string productId)
        {
            var request = new GetProductRequest
            {
                ProductName = new ProductName(this.options.Value.ProjectId, this.options.Value.LocationId, productId),
            };

            return(await client.GetProductAsync(request));
        }
        private async Task DeleteReferenceImage(ProductSearchClient client, string productId, string referenceImageId)
        {
            var request = new DeleteReferenceImageRequest
            {
                ReferenceImageName = new ReferenceImageName(this.options.Value.ProjectId, this.options.Value.LocationId, productId, referenceImageId)
            };

            await client.DeleteReferenceImageAsync(request);
        }
        private async Task DeleteProduct(ProductSearchClient client, string productId)
        {
            var request = new DeleteProductRequest
            {
                ProductName = new ProductName(this.options.Value.ProjectId, this.options.Value.LocationId, productId),
            };

            await client.DeleteProductAsync(request);
        }
        //private async Task DeleteProduct(ProductSearchClient client, string productId)
        //{
        //    var request = new DeleteProductRequest
        //    {
        //        ProductName = new ProductName(this.options.Value.ProjectId, this.options.Value.LocationId, productId),
        //    };

        //    await client.DeleteProductAsync(request);
        //}

        //private async Task AddProductToProductSet(ProductSearchClient client, AddProductToProductSetOptions opts)
        //{
        //    var request = new AddProductToProductSetRequest
        //    {
        //        // Get the full path of the products
        //        ProductAsProductName = new ProductName(opts.ProjectID, opts.ComputeRegion, opts.ProductID),
        //        // Get the full path of the product set.
        //        ProductSetName = new ProductSetName(opts.ProjectID, opts.ComputeRegion, opts.ProductSetId),
        //    };

        //    await client.AddProductToProductSetAsync(request);
        //}

        //private async Task RemoveProductFromProductSet(ProductSearchClient client, string productSetId, string productId)
        //{
        //    var request = new RemoveProductFromProductSetRequest
        //    {
        //        ProductSetName = new ProductSetName(this.options.Value.ProjectId, this.options.Value.LocationId, productSetId),
        //        ProductAsProductName = new ProductName(this.options.Value.ProjectId, this.options.Value.LocationId, productId),
        //    };

        //    await client.RemoveProductFromProductSetAsync(request);
        //}

        //private async Task<Google.Cloud.Vision.V1.ReferenceImage> CreateReferenceImage(ProductSearchClient client, CreateReferenceImageOptions opts)
        //{
        //    var request = new CreateReferenceImageRequest
        //    {
        //        // Get the full path of the product.
        //        ParentAsProductName = new ProductName(opts.ProjectID, opts.ComputeRegion, opts.ProductID),
        //        ReferenceImageId = opts.ReferenceImageID,
        //        // Create a reference image.
        //        ReferenceImage = new Google.Cloud.Vision.V1.ReferenceImage
        //        {
        //            Uri = opts.ReferenceImageURI
        //        }
        //    };

        //    var referenceImage = await client.CreateReferenceImageAsync(request);

        //    return referenceImage;
        //}

        //private async Task DeleteReferenceImage(ProductSearchClient client, string productId, string referenceImageId)
        //{
        //    var request = new DeleteReferenceImageRequest
        //    {
        //        ReferenceImageName = new ReferenceImageName(this.options.Value.ProjectId, this.options.Value.LocationId, productId, referenceImageId)
        //    };

        //    await client.DeleteReferenceImageAsync(request);
        //}

        //private async Task UploadFile(StorageClient storage, string bucketName, string objectName, byte[] image)
        //{
        //    using (var stream = new MemoryStream(image))
        //    {
        //        await storage.UploadObjectAsync(bucketName, objectName, null, stream);
        //    }
        //}

        //private async Task DeleteFile(StorageClient storage, string bucketName, string objectName)
        //{
        //    await storage.DeleteObjectAsync(bucketName, objectName);
        //}

        //private GoogleCredential CreateCredentials()
        //{
        //    return GoogleCredential.FromFile(this.options.Value.CredentialsFile);
        //}

        //private async Task<TargetSearchResults> GetSimilarProductsFile(ImageAnnotatorClient imageAnnotatorClient, GetSimilarProductsOptions opts)
        //{
        //    // Create annotate image request along with product search feature.
        //    Image image = Image.FromBytes(opts.ImageBinaries);

        //    // Product Search specific parameters
        //    var productSearchParams = new ProductSearchParams
        //    {
        //        ProductSetAsProductSetName = new ProductSetName(opts.ProjectID,
        //                                                        opts.ComputeRegion,
        //                                                        opts.ProductSetId),
        //        ProductCategories = { opts.ProductCategory },
        //        Filter = opts.Filter
        //    };

        //    // Search products similar to the image.
        //    ProductSearchResults results = await imageAnnotatorClient.DetectSimilarProductsAsync(image, productSearchParams);
        //    return this.mapper.Map<TargetSearchResults>(results);
        //}

        private async Task <Target> LoadReferenceImagesAndMapToTarget(ProductSearchClient client, Product product, int pageSize)
        {
            IEnumerable <Google.Cloud.Vision.V1.ReferenceImage> referenceImages = await this.GetReferenceImages(client, product, pageSize);

            Target target = this.mapper.Map <Target>(product);

            target.ReferenceImages = this.mapper.Map <IEnumerable <ReferenceImage> >(referenceImages);

            return(target);
        }
        private async Task RemoveProductFromProductSet(ProductSearchClient client, string productSetId, string productId)
        {
            var request = new RemoveProductFromProductSetRequest
            {
                ProductSetName       = new ProductSetName(this.options.Value.ProjectId, this.options.Value.LocationId, productSetId),
                ProductAsProductName = new ProductName(this.options.Value.ProjectId, this.options.Value.LocationId, productId),
            };

            await client.RemoveProductFromProductSetAsync(request);
        }
        public async Task <Target> CreateTarget(string displayName, string description, IReadOnlyDictionary <string, string> labels, byte[] referenceImageBinaries)
        {
            GoogleCredential cred = this.CreateCredentials();
            var channel           = new Channel(ProductSearchClient.DefaultEndpoint.Host, ProductSearchClient.DefaultEndpoint.Port, cred.ToChannelCredentials());

            try
            {
                var client  = ProductSearchClient.Create(channel);
                var storage = await StorageClient.CreateAsync(cred);

                string productId            = Guid.NewGuid().ToString();
                var    createProductOptions = new CreateProductOptions
                {
                    ProjectID       = this.options.Value.ProjectId,
                    ComputeRegion   = this.options.Value.LocationId,
                    ProductID       = productId,
                    ProductCategory = "apparel",
                    DisplayName     = displayName,
                    Description     = description,
                    ProductLabels   = labels,
                };
                Product product = await this.CreateProduct(client, createProductOptions);

                var addProductOptions = new AddProductToProductSetOptions
                {
                    ProjectID     = this.options.Value.ProjectId,
                    ComputeRegion = this.options.Value.LocationId,
                    ProductID     = product.ProductName.ProductId,
                    ProductSetId  = this.options.Value.ProductSetId,
                };
                await this.AddProductToProductSet(client, addProductOptions);

                string referenceImageId = Guid.NewGuid().ToString();
                await this.UploadFile(storage, this.options.Value.StorageBucketName, referenceImageId, referenceImageBinaries);

                var createReferenceImageOptions = new CreateReferenceImageOptions
                {
                    ProjectID         = this.options.Value.ProjectId,
                    ComputeRegion     = this.options.Value.LocationId,
                    ProductID         = product.ProductName.ProductId,
                    ReferenceImageID  = referenceImageId,
                    ReferenceImageURI = $"gs://{this.options.Value.StorageBucketName}/{referenceImageId}",
                };
                Google.Cloud.Vision.V1.ReferenceImage referenceImage = await this.CreateReferenceImage(client, createReferenceImageOptions);

                Target target = this.mapper.Map <Target>(product);
                target.ReferenceImages = new ReferenceImage[] { this.mapper.Map <ReferenceImage>(referenceImage) };

                return(target);
            }
            finally
            {
                await channel.ShutdownAsync();
            }
        }
 public JsonResult GetSuggest(string keyWord)
 {
     using (var client = new ProductSearchClient())
     {
         var result = client.SearchSuggest(keyWord);
         if (result.Success)
         {
             return(Json(result.Result.Keys.ToList(), JsonRequestBehavior.AllowGet));
         }
     }
     return(Json("", JsonRequestBehavior.AllowGet));
 }
        private async Task AddProductToProductSet(ProductSearchClient client, AddProductToProductSetOptions opts)
        {
            var request = new AddProductToProductSetRequest
            {
                // Get the full path of the products
                ProductAsProductName = new ProductName(opts.ProjectID, opts.ComputeRegion, opts.ProductID),
                // Get the full path of the product set.
                ProductSetName = new ProductSetName(opts.ProjectID, opts.ComputeRegion, opts.ProductSetId),
            };

            await client.AddProductToProductSetAsync(request);
        }
예제 #18
0
 public void Execute(IJobExecutionContext context)
 {
     try
     {
         var sw = new Stopwatch();
         sw.Start();
         var userDatas       = ProductCacheDal.GetProductRecommendByUserId();
         var defaultDatas    = ProductCacheDal.GetCommonRecommend();
         var needRefreshPids = userDatas.Union(defaultDatas).Distinct().ToList();
         var referData       = DateTime.Now.Subtract(TimeSpan.FromHours(1));
         if (!needRefreshPids.Any())
         {
             Logger.Info("bi推荐产品刷新到esjob执行,并没有找到需要更新的数据");
         }
         else
         {
             Logger.Info($"bi推荐产品刷新到esjob开始执行,一共{needRefreshPids.Count}个产品");
             using (var client = new CacheClient())
             {
                 foreach (var pids in needRefreshPids.Split(1).Select(r => r.ToList()))
                 {
                     var switcher = ProductCacheDal.SelectRuntimeSwitchBySwitchName();
                     if (switcher == "run")
                     {
                         var esresult = client.RefreshProductRecommendEsCacheByPids(pids);
                         if (!esresult.Success || !esresult.Result)
                         {
                             Logger.Error($"调用bi推荐产品刷新到es接口失败", esresult.Exception.InnerException);
                         }
                     }
                     else
                     {
                         return;
                     }
                 }
             }
             using (var client = new ProductSearchClient())
             {
                 var delResult = client.DeleteOldProductEs(referData, ExpiredEsDataType.Recommend);
                 if (!delResult.Success || !delResult.Result)
                 {
                     Logger.Error($"调用bi推荐产品删除es过期数据接口失败", delResult.Exception.InnerException);
                 }
             }
         }
         sw.Stop();
         Logger.Info($"bi推荐产品刷新到esjob执行结束,耗时{sw.ElapsedMilliseconds}");
     }
     catch (Exception ex)
     {
         Logger.Error("bi推荐产品刷新到es失败", ex);
     }
 }
예제 #19
0
        public ProductSearchClient CreateProductSearchClient()
        {
            var path       = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, System.AppDomain.CurrentDomain.RelativeSearchPath ?? "");
            var credential = GoogleCredential.FromFile($"{path}\\token.json")
                             .CreateScoped(ProductSearchClient.DefaultScopes);
            var channel = new Grpc.Core.Channel(
                ProductSearchClient.DefaultEndpoint.ToString(),
                credential.ToChannelCredentials());

            var imageAnnotatorClient = ProductSearchClient.Create(channel);

            return(imageAnnotatorClient);
        }
        public void Execute(IJobExecutionContext context)
        {
            Logger.Info($"开始刷新Suggest");
            var client      = new ProductSearchClient();
            var suggestList = ProductCacheDal.SelectSuggestWord(brash);

            foreach (var oneList in suggestList)
            {
                var response = client.SearchKeywordsResultNumber(oneList.Select(_ => _.Keyword).Distinct().ToList());
                if (!response.Success)
                {
                    client   = new ProductSearchClient();
                    response = client.SearchKeywordsResultNumber(oneList.Select(_ => _.Keyword).ToList()); if (response.Success)
                    {
                        if (!response.Success)
                        {
                            Logger.Error($"服务调用失败");
                            return;
                        }
                    }
                }

                if (response.Result == null)
                {
                    Logger.Warn($"服务返回null;{response.ErrorMessage}");
                    continue;
                }

                var upUnActive = ProductCacheDal.UpdateSuggestActive(
                    response.Result.Where(_ => _.Value == 0).Select(_ => _.Key).ToList()
                    , false);

                var upActive = ProductCacheDal.UpdateSuggestActive(
                    response.Result.Where(_ => _.Value > 0).Select(_ => _.Key).ToList()
                    , true);

                if (!upUnActive)
                {
                    Logger.Warn($"数据库更新失败upUnActive;");
                    continue;
                }
                if (!upActive)
                {
                    Logger.Warn($"数据库更新失败upActive;");
                    continue;
                }
            }
            Logger.Info($"刷新Suggest完成;通知刷新 RebuildSuggest");
            TuhuNotification.SendNotification("ProductModify", new { type = "RebuildSuggest" });
        }
예제 #21
0
        private async Task <IEnumerable <string> > ListReferenceImagesOfProduct(ProductSearchClient client, string productID)
        {
            var request = new ListReferenceImagesRequest
            {
                ParentAsProductName = new ProductName(_projectInfo.ProjectID,
                                                      _projectInfo.ComputeRegion,
                                                      productID)
            };

            var res = client.ListReferenceImagesAsync(request);

            var results = await res.ToList();

            return(results.Select(x => x.Uri.Replace("gs://", "https://storage.googleapis.com/")));
        }
예제 #22
0
        // [END vision_product_search_update_product_labels]

        // [START vision_product_search_delete_product]
        private static int DeleteProduct(DeleteProductOptions opts)
        {
            var client  = ProductSearchClient.Create();
            var request = new DeleteProductRequest
            {
                // Get the full path of the product.
                ProductName = new ProductName(opts.ProjectID,
                                              opts.ComputeRegion,
                                              opts.ProductID)
            };

            client.DeleteProduct(request);
            Console.WriteLine("Product deleted.");

            return(0);
        }
        // [END vision_product_search_get_reference_image]

        // [START vision_product_search_delete_reference_image]
        private static int DeleteReferenceImage(DeleteReferenceImageOptions opts)
        {
            var client  = ProductSearchClient.Create();
            var request = new DeleteReferenceImageRequest
            {
                // Get the full path of the reference image.
                ReferenceImageName = new ReferenceImageName(opts.ProjectID,
                                                            opts.ComputeRegion,
                                                            opts.ProductID,
                                                            opts.ReferenceImageID)
            };

            client.DeleteReferenceImage(request);
            Console.WriteLine("Reference image deleted from product.");
            return(0);
        }
        public async Task <Target> GetTarget(string targetId)
        {
            GoogleCredential cred = this.CreateCredentials();
            var channel           = new Channel(ProductSearchClient.DefaultEndpoint.Host, ProductSearchClient.DefaultEndpoint.Port, cred.ToChannelCredentials());

            try
            {
                var     client  = ProductSearchClient.Create(channel);
                Product product = await this.GetProduct(client, targetId);

                return(await this.LoadReferenceImagesAndMapToTarget(client, product, 100));
            }
            finally
            {
                await channel.ShutdownAsync();
            }
        }
        public async Task GetTargetSets()
        {
            GoogleCredential cred = this.CreateCredentials();
            var channel           = new Channel(ProductSearchClient.DefaultEndpoint.Host, ProductSearchClient.DefaultEndpoint.Port, cred.ToChannelCredentials());

            try
            {
                var client = ProductSearchClient.Create(channel);
                // var productSet = await this.GetProductSets(client, 100);

                // productSet.
            }
            finally
            {
                await channel.ShutdownAsync();
            }
        }
        // [END vision_product_search_get_product_set]

        // [START vision_product_search_delete_product_set]
        private static object DeleteProductSet(DeleteProductSetOptions opts)
        {
            var client = ProductSearchClient.Create();
            var request = new DeleteProductSetRequest
            {
                // Get the full path of the product set.
                ProductSetName = new ProductSetName(opts.ProjectID,
                                                    opts.ComputeRegion,
                                                    opts.ProductSetId)
            };

            // Delete the product set.
            client.DeleteProductSet(request);

            Console.WriteLine("Product set deleted.");
            return 0;
        }
예제 #27
0
        // [END vision_product_search_get_product]

        // [START vision_product_search_update_product_labels]
        private static int UpdateProductLabels(UpdateProductLabelsOptions opts)
        {
            var client  = ProductSearchClient.Create();
            var request = new UpdateProductRequest
            {
                Product = new Product
                {
                    // Get the name of the product
                    ProductName = new ProductName(opts.ProjectID,
                                                  opts.ComputeRegion,
                                                  opts.ProductID),
                    // Set the product name, product label, and product display
                    // name. Multiple labels are also supported.
                    ProductLabels =
                    {
                        new Product.Types.KeyValue
                        {
                            Key   = opts.Labels.Split(",").First(),
                            Value = opts.Labels.Split(",").Last()
                        }
                    }
                },
                // Updating only the product_labels field here.
                UpdateMask = new FieldMask
                {
                    Paths = { "product_labels" }
                }
            };

            // This overwrites the product_labels.
            var product = client.UpdateProduct(request);

            var productId = product.Name.Split("/").Last();

            Console.WriteLine($"\nProduct name: {product.Name}");
            Console.WriteLine($"Product id: {productId}");
            Console.WriteLine($"Product display name: {product.DisplayName}");
            Console.WriteLine($"Product category: {product.ProductCategory}");
            Console.WriteLine($"Product labels:");
            foreach (var label in product.ProductLabels)
            {
                Console.WriteLine($"\tLabel: {label.ToString()}");
            }
            return(0);
        }
예제 #28
0
        GetTiresByFilter(SearchProductRequest filter, string[] filterPropertys)
        {
            try
            {
                using (var searchClient = new ProductSearchClient())
                {
                    var searchResult = await searchClient.QueryTireListFilterValuesAsync(filter, filterPropertys.ToList());

                    searchResult.ThrowIfException(true);
                    return(searchResult?.Result);
                }
            }
            catch (Exception ex)
            {
                _logger.Error($"查询轮胎列表失败 {JsonConvert.SerializeObject(filter)}", ex);
                return(null);
            }
        }
예제 #29
0
        /// <summary>
        /// 查询商品信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task <PagedModel <string> > SearchProduct(SearchProductRequest query)
        {
            try
            {
                using (var searchClient = new ProductSearchClient())
                {
                    var searchResult = await searchClient.SearchProductAsync(query);

                    searchResult.ThrowIfException(true);
                    return(searchResult?.Result);
                }
            }
            catch (Exception ex)
            {
                _logger.Error($"查询商品信息失败 {JsonConvert.SerializeObject(query)}", ex);
                return(null);
            }
        }
        //public async Task GetTargetSets()
        //{
        //    GoogleCredential cred = this.CreateCredentials();
        //    var channel = new Channel(ProductSearchClient.DefaultEndpoint.Host, ProductSearchClient.DefaultEndpoint.Port, cred.ToChannelCredentials());

        //    try
        //    {
        //        var client = ProductSearchClient.Create(channel);
        //        // var productSet = await this.GetProductSets(client, 100);

        //        // productSet.

        //    }
        //    finally
        //    {
        //        await channel.ShutdownAsync();
        //    }
        //}

        //public async Task CreateTargetSet(string targetSetId, string displayName)
        //{
        //    GoogleCredential cred = this.CreateCredentials();
        //    var channel = new Channel(ProductSearchClient.DefaultEndpoint.Host, ProductSearchClient.DefaultEndpoint.Port, cred.ToChannelCredentials());

        //    try
        //    {
        //        var client = ProductSearchClient.Create(channel);

        //        var createProductSetOptions = new CreateProductSetsOptions
        //        {
        //            ProjectID = this.options.Value.ProjectId,
        //            ComputeRegion = this.options.Value.LocationId,
        //            ProductSetId = targetSetId,
        //            ProductSetDisplayName = displayName,
        //        };
        //        var productSet = await this.CreateProductSet(client, createProductSetOptions);
        //    }
        //    finally
        //    {
        //        await channel.ShutdownAsync();
        //    }
        //}

        public async Task <IEnumerable <Target> > GetTargets(string targetSetId, int skip = 0, int take = 10)
        {
            var client = await ProductSearchClient.CreateAsync();

            var request = new ListProductsInProductSetRequest
            {
                ProductSetName = new ProductSetName(this.options.Value.ProjectId, this.options.Value.LocationId, targetSetId),
                PageSize       = take,
            };

            PagedAsyncEnumerable <ListProductsInProductSetResponse, Product> response = client.ListProductsInProductSetAsync(request);
            var page = await response.ReadPageAsync(take);

            IEnumerable <Product> products = page.ToArray();
            IEnumerable <Target>  targets  = await Task.WhenAll(products.Select(p => this.LoadReferenceImagesAndMapToTarget(client, p, 10)));

            return(targets);
        }