Exemplo n.º 1
0
        public JsonResult GetItemRecommendations(string itemId, List <string> recentViewedProductList, string recommedType, string modelId, int noOfItems, string userId)
        {
            var resp = new List <RecommendationResult>();

            if (recommedType == RecommendationTypes.RecentView.ToString())
            {
                if (recentViewedProductList != null && !recentViewedProductList.Any())
                {
                    return(JsonSuccess("", JsonRequestBehavior.AllowGet));
                }
                resp = (from o in recentViewedProductList select new RecommendationResult {
                    RecommendedItemId = o
                }).ToList();
            }
            else
            {
                _recommendationSettings = _sessionContext.CurrentSiteConfig.RecommendationSettings;
                _recommendationClient   = new RecommendationsAPI(new Uri(_recommendationSettings.ApiEndPoint));

                _recommendationClient.HttpClient.DefaultRequestHeaders.Add("x-api-key", _recommendationSettings.RecommederKey);
                // string userId = string.Empty;
                string visitorId = string.Empty;
                if (string.IsNullOrEmpty(userId))
                {
                    userId = string.Empty;

                    if (_sessionContext.CurrentUser != null)
                    {
                        userId = _sessionContext.CurrentUser.UserId.ToString();
                    }
                    else
                    {
                        visitorId = _sessionContext.DeviceId;
                    }
                }


                if (string.IsNullOrEmpty(modelId))
                {
                    modelId = GetRecommendationModelId(recommedType);
                }
                var modelGuId = Guid.Empty;
                Guid.TryParse(modelId, out modelGuId);
                var usageEvent = new List <UsageEvent>();
                if (recommedType == RecommendationTypes.Basket.ToString())
                {
                    var basket = _basketApi.GetBasketData("")?.Result;
                    if (basket != null && basket.LineItems != null && basket.LineItems.Any())
                    {
                        itemId = string.Join(",", basket.LineItems.Select(x => x.ProductId));
                    }
                }
                if (!string.IsNullOrEmpty(itemId))
                {
                    if (modelGuId == Guid.Empty)
                    {
                        resp = _recommendationClient.Models.GetItemRecommendationsFromDefaultModel(itemId, noOfItems)?.ToList();
                    }

                    else
                    {
                        resp = _recommendationClient.Models.GetItemRecommendations(modelGuId, itemId, noOfItems)?.ToList();
                    }
                }
                else
                {
                    if (modelGuId == Guid.Empty)
                    {
                        resp = _recommendationClient.Models.GetPersonalizedRecommendationsFromDefaultModel(usageEvent, userId != string.Empty ? userId : visitorId, noOfItems)?.ToList();
                    }
                    else
                    {
                        resp = _recommendationClient.Models.GetPersonalizedRecommendations(modelGuId, usageEvent, userId != string.Empty ? userId : visitorId, noOfItems)?.ToList();
                    }
                }
            }


            if (resp != null && resp.Count > 0)
            {
                SearchRequestModel criteria = new SearchRequestModel
                {
                    Filters = new List <SearchFilter>()
                };
                foreach (var data in resp)
                {
                    var searchFilter = new SearchFilter
                    {
                        Key   = "recordId",
                        Value = data.RecommendedItemId
                    };
                    criteria.Filters.Add(searchFilter);
                }
                var response = _productApi.GetProducts(criteria);
                if (response != null && response.Result != null)
                {
                    return(JsonSuccess(response.Result.Results, JsonRequestBehavior.AllowGet));
                }
            }
            return(JsonSuccess("", JsonRequestBehavior.AllowGet));
        }
Exemplo n.º 2
0
        static void Main(string[] args)
        {
            // Modify the lines below based on the values you received when the site was configured.
            // Note that the connection string is only needed by the sample because it uploads some sample
            // data to create a recommendation model.
            string recommendationsEndPointUri = "https://yoursite.azurewebsites.net";
            string apiAdminKey      = "your Admin key goes here";
            string connectionString = @"DefaultEndpointsProtocol=https;AccountName=yoursite;AccountKey=theAccountKeyProvidedToYouAtConfigurationTime";

            // Blob storage locations. You may modify these locations to point to your real data.
            string blobContainerName                     = "sample-data";
            string catalogFileRelativeLocation           = "demoCatalog.csv";
            string usageFolderRelativeLocation           = "usageFiles";
            string evaluationUsageFolderRelativeLocation = null;


            // Copy some sample data for training to the blob storage location.
            // If you are using your own data, and the data is already uploaded to blob storage,
            // this step may not be necessary.
            Console.WriteLine("Copying sample training data to blob storage...");
            CopySampleFilesToBlobStorage(connectionString, blobContainerName, catalogFileRelativeLocation, usageFolderRelativeLocation);

            // Create an instance that allows us to work with the models.
            // Note that you can "train" recommendation models only with the modeling key,
            // You can score models with either the modeling key or the scoring key.
            var webApp = new RecommendationsAPI(new Uri(recommendationsEndPointUri));

            // Add the api key header to all requests
            webApp.HttpClient.DefaultRequestHeaders.Add("x-api-key", apiAdminKey);

            // Create a models class.
            var models = new Models(webApp);

            // Set to a specific model Id if you would like to skip the training phase.
            Guid?modelId = null;

            if (!modelId.HasValue)
            {
                // Let's train the model.

                // Set the training parameters
                var modelParameters = new ModelParameters(
                    description: "Sample created model",
                    blobContainerName: blobContainerName,
                    catalogFileRelativeLocation: catalogFileRelativeLocation,
                    usageFolderRelativeLocation: usageFolderRelativeLocation,
                    evaluationUsageFolderRelativeLocation: evaluationUsageFolderRelativeLocation,
                    supportThreshold: 3,
                    cooccurrenceUnit: CooccurrenceUnit.User,
                    similarityFunction: SimilarityFunction.Jaccard,
                    enableColdItemPlacement: false,
                    enableColdToColdRecommendations: false,
                    enableUserAffinity: true,
                    allowSeedItemsInRecommendations: true,
                    enableBackfilling: true,
                    decayPeriodInDays: 30);

                Console.WriteLine("Training a new model.");
                Model model = (models.CreateModel(modelParameters)) as Model;

                Console.WriteLine("Waiting for model " + model.Id + "to complete training. ");
                modelId = model.Id;

                do
                {
                    Thread.Sleep(5000);
                    model = models.GetModel(modelId.Value);

                    Console.WriteLine("Model " + model.Id + " status: " + model.ModelStatus + ":" + model.ModelStatusMessage);
                }while (model.ModelStatus != ModelStatus.Completed &&
                        model.ModelStatus != ModelStatus.Failed);

                Console.WriteLine("Model " + model.Id + " completed with status " + model.ModelStatus);

                // Get model status.
                if (model.ModelStatus != ModelStatus.Completed)
                {
                    Console.WriteLine("Model training aborted.");
                    return;
                }
            }

            // Scoring Example 1: Let's get some recommendations for item with ID 6480764
            string itemId = "DHF-00881";

            Console.WriteLine("\n\nRecommendations for Item " + itemId + ":");
            var results = models.GetItemRecommendations(modelId.Value, "6480764");

            foreach (var result in results)
            {
                Console.WriteLine("\t Recommendation Id: " + result.RecommendedItemId + " Score:" + result.Score);
            }


            // Scoring Example 2: Let's get some recommendations from the default model.
            Console.WriteLine("\n\nRecommendations for Item from default model " + itemId + ":");
            // First, ensure this model is the default model.
            models.SetDefaultModel(modelId.Value);
            // Now that it is the default model, we can request recommendations using the default model
            results = models.GetItemRecommendationsFromDefaultModel("6480764");
            foreach (var result in results)
            {
                Console.WriteLine("\t Recommendation Id: " + result.RecommendedItemId + " Score:" + result.Score);
            }

            // Scoring Example 3: Let's get personalized recommendations.
            // Assume a customer has done two recent transactions -- she purchased item  DHF-01550
            // on February 1st 2017, and purchased item DHF-01333 the previous day.
            Console.WriteLine("\n\nPersonalized recommendations for user with 2 transactions:");
            var events = new List <UsageEvent>
            {
                new UsageEvent
                {
                    ItemId    = "DHF-01550",
                    EventType = EventType.Purchase,
                    Timestamp = new DateTime(2017, 2, 1)
                },
                new UsageEvent
                {
                    ItemId    = "DHF-01333",
                    EventType = EventType.Purchase,
                    Timestamp = new DateTime(2017, 1, 31)
                }
            };

            results = models.GetPersonalizedRecommendationsFromDefaultModel(events);
            foreach (var result in results)
            {
                Console.WriteLine("\t Recommendation Id: " + result.RecommendedItemId + " Score:" + result.Score);
            }

            Console.WriteLine("\nPress any key to close application.");
            Console.ReadKey();
        }
Exemplo n.º 3
0
        static void Main()
        {
            // modify the lines below based on the values you received when the site was configured.
            // note that the connection string is only needed by the sample because it uploads some sample
            // data to create a recommendation model.
            string recommendationsEndPointUri = "https://yoursite.azurewebsites.net";
            string apiAdminKey      = "your admin key goes here";
            string connectionString = @"DefaultEndpointsProtocol=https;AccountName=yoursite;AccountKey=theAccountKeyProvidedToYouAtConfigurationTime";

            // create recommendations client that allows us to work with the recommendations API
            var recommendationsClient = new RecommendationsAPI(new Uri(recommendationsEndPointUri));

            // add the api key header to all requests.
            // note that you can "train" recommendation models only with the modeling key,
            // you can score models with either the modeling key or the scoring key.
            recommendationsClient.HttpClient.DefaultRequestHeaders.Add("x-api-key", apiAdminKey);

            // comment out this line and use a pre-trained model Id if you would like to skip the training phase.
            Guid modelId = TrainModelUsingSampleData(recommendationsClient, connectionString);

            #region Scoring Example 1: Getting some recommendations for item with ID DHF-01159

            string itemId = "DHF-01159";
            Console.WriteLine($"Getting recommendations for item '{itemId}' using model '{modelId}':");
            IList <RecommendationResult> results = recommendationsClient.Models.GetItemRecommendations(modelId, itemId);
            PrintRecommendationResults(results);

            #endregion

            #region Scoring Example 2: Getting some recommendations from the default model

            // First, ensure this model is the default model.
            Console.WriteLine($"\t Setting model '{modelId}' as the default model");
            recommendationsClient.Models.SetDefaultModel(modelId);

            // Now that it is the default model, we can request recommendations using the default model
            Console.WriteLine($"Getting recommendations for item '{itemId}' using the default model:");
            results = recommendationsClient.Models.GetItemRecommendationsFromDefaultModel(itemId);
            PrintRecommendationResults(results);

            #endregion

            #region Scoring Example 3: Getting personalized recommendations

            // assuming some user had done two recent transactions -- she purchased item DAF-00448
            // on February 1st 2017, and purchased item DHF-01333 the previous day.
            var events = new List <UsageEvent>
            {
                new UsageEvent
                {
                    ItemId    = "DAF-00448",
                    EventType = EventType.Purchase,
                    Timestamp = new DateTime(2017, 2, 1)
                },
                new UsageEvent
                {
                    ItemId    = "DHF-01333",
                    EventType = EventType.Purchase,
                    Timestamp = new DateTime(2017, 1, 31)
                }
            };

            Console.WriteLine("Getting personalized recommendations for user with 2 transactions:");
            results = recommendationsClient.Models.GetPersonalizedRecommendationsFromDefaultModel(events);
            PrintRecommendationResults(results);

            #endregion

            Console.WriteLine();
            Console.WriteLine("Press any key to close application.");
            Console.ReadLine();
        }