Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Product recommendation ML updated #984

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
14 changes: 14 additions & 0 deletions SimplCommerce.sln
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SimplCommerce.Module.Paymen
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SimplCommerce.Module.PaymentCashfree", "src\Modules\SimplCommerce.Module.PaymentCashfree\SimplCommerce.Module.PaymentCashfree.csproj", "{E30CF10F-FABF-4917-8BEB-CB81E4CE2C92}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SimplCommerce.AI.Recommendation", "src\SimplCommerce.AI.Recommendation\SimplCommerce.AI.Recommendation.csproj", "{632EECD7-C8FD-460B-A8D0-F01FD4DA3C38}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SimplCommerce.Module.Checkouts", "src\Modules\SimplCommerce.Module.Checkouts\SimplCommerce.Module.Checkouts.csproj", "{4473538D-2BFA-4C53-B642-0D0DC4F16863}"
EndProject
Global
Expand Down Expand Up @@ -698,6 +699,18 @@ Global
{E30CF10F-FABF-4917-8BEB-CB81E4CE2C92}.Release|x64.Build.0 = Release|Any CPU
{E30CF10F-FABF-4917-8BEB-CB81E4CE2C92}.Release|x86.ActiveCfg = Release|Any CPU
{E30CF10F-FABF-4917-8BEB-CB81E4CE2C92}.Release|x86.Build.0 = Release|Any CPU
{632EECD7-C8FD-460B-A8D0-F01FD4DA3C38}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{632EECD7-C8FD-460B-A8D0-F01FD4DA3C38}.Debug|Any CPU.Build.0 = Debug|Any CPU
{632EECD7-C8FD-460B-A8D0-F01FD4DA3C38}.Debug|x64.ActiveCfg = Debug|Any CPU
{632EECD7-C8FD-460B-A8D0-F01FD4DA3C38}.Debug|x64.Build.0 = Debug|Any CPU
{632EECD7-C8FD-460B-A8D0-F01FD4DA3C38}.Debug|x86.ActiveCfg = Debug|Any CPU
{632EECD7-C8FD-460B-A8D0-F01FD4DA3C38}.Debug|x86.Build.0 = Debug|Any CPU
{632EECD7-C8FD-460B-A8D0-F01FD4DA3C38}.Release|Any CPU.ActiveCfg = Release|Any CPU
{632EECD7-C8FD-460B-A8D0-F01FD4DA3C38}.Release|Any CPU.Build.0 = Release|Any CPU
{632EECD7-C8FD-460B-A8D0-F01FD4DA3C38}.Release|x64.ActiveCfg = Release|Any CPU
{632EECD7-C8FD-460B-A8D0-F01FD4DA3C38}.Release|x64.Build.0 = Release|Any CPU
{632EECD7-C8FD-460B-A8D0-F01FD4DA3C38}.Release|x86.ActiveCfg = Release|Any CPU
{632EECD7-C8FD-460B-A8D0-F01FD4DA3C38}.Release|x86.Build.0 = Release|Any CPU
{4473538D-2BFA-4C53-B642-0D0DC4F16863}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4473538D-2BFA-4C53-B642-0D0DC4F16863}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4473538D-2BFA-4C53-B642-0D0DC4F16863}.Debug|x64.ActiveCfg = Debug|Any CPU
Expand Down Expand Up @@ -764,6 +777,7 @@ Global
{1A8B6FA0-8341-4D27-9B71-57F70AB37571} = {0A27C140-4CCB-40DD-BE48-F5DE16D1177B}
{14586564-62CC-4117-AC1B-858ED53C2D6C} = {7EFA2FA7-32DD-4047-B021-50E77A83D714}
{E30CF10F-FABF-4917-8BEB-CB81E4CE2C92} = {7EFA2FA7-32DD-4047-B021-50E77A83D714}
{632EECD7-C8FD-460B-A8D0-F01FD4DA3C38} = {C9BFDDC4-5671-47A3-B57D-197C2A51FA8A}
{4473538D-2BFA-4C53-B642-0D0DC4F16863} = {7EFA2FA7-32DD-4047-B021-50E77A83D714}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using SimplCommerce.AI.Recommendation;
using SimplCommerce.AI.Recommendation.Models;
using SimplCommerce.Infrastructure.Data;
using SimplCommerce.Module.Catalog.Areas.Catalog.ViewModels;
using SimplCommerce.Module.Catalog.Models;
Expand All @@ -24,18 +26,21 @@ public class ProductController : Controller
private readonly IMediator _mediator;
private readonly IProductPricingService _productPricingService;
private readonly IContentLocalizationService _contentLocalizationService;
private readonly IRecommendationService _recommendationService;

public ProductController(IRepository<Product> productRepository,
IMediaService mediaService,
IMediator mediator,
IProductPricingService productPricingService,
IContentLocalizationService contentLocalizationService)
IContentLocalizationService contentLocalizationService,
IRecommendationService recommendationService)
{
_productRepository = productRepository;
_mediaService = mediaService;
_mediator = mediator;
_productPricingService = productPricingService;
_contentLocalizationService = contentLocalizationService;
_recommendationService = recommendationService;
}

[HttpGet("product/product-overview")]
Expand Down Expand Up @@ -116,6 +121,7 @@ public async Task<IActionResult> ProductDetail(long id)
MapRelatedProductToProductVm(product, model);
MapProductOptionToProductVm(product, model);
MapProductImagesToProductVm(product, model);
MapRecommendProductsToVm(model);

await _mediator.Publish(new EntityViewed { EntityId = product.Id, EntityTypeId = "Product" });
_productRepository.SaveChanges();
Expand Down Expand Up @@ -218,5 +224,31 @@ private void MapRelatedProductToProductVm(Product product, ProductDetail model)
}
}
}

private void MapRecommendProductsToVm(ProductDetail model)
{
var top5 = (from m in _productRepository.Query().Where(x => x.IsPublished && x.IsVisibleIndividually && x.Id != model.Id)
.Include(x => x.OptionValues)
.Include(x => x.ThumbnailImage)
.Include(x => x.Medias).ThenInclude(m => m.Media)
.AsEnumerable()
let p = _recommendationService.Predict(
new ProductInfo()
{
ProductID = model.Id,
CombinedProductID = (uint)m.Id
})
orderby p.Score descending
select (Product: m, Score: p.Score)).Take(4);

foreach (var dict in top5)
{
var productThumbnail = ProductThumbnail.FromProduct(dict.Product);
productThumbnail.Name = _contentLocalizationService.GetLocalizedProperty(nameof(Product), productThumbnail.Id, nameof(productThumbnail.Name), productThumbnail.Name);
productThumbnail.ThumbnailUrl = _mediaService.GetThumbnailUrl(productThumbnail.ThumbnailImage);
productThumbnail.CalculatedProductPrice = _productPricingService.CalculateProductPrice(productThumbnail);
model.RecommendProducts.Add(productThumbnail);
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,8 @@ into g

public IList<ProductThumbnail> RelatedProducts { get; set; } = new List<ProductThumbnail>();

public IList<ProductThumbnail> RecommendProducts { get; set; } = new List<ProductThumbnail>();

public IList<ProductThumbnail> CrossSellProducts { get; set; } = new List<ProductThumbnail>();

public Brand Brand { get; set; }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,20 @@

@await Component.InvokeAsync("ProductRecentlyViewed", new { productId = Model.Id })

@if (Model.RecommendProducts.Any())
{
<!-- Recommended Products -->
<h2 class="p-t-25 p-b-25">@Localizer["Recommended Products"]</h2>
<div class="row product-list">
@foreach (var product in Model.RecommendProducts)
{
<div class="col-xs-6 col-md-3">
<partial name="_ProductThumbnail" model="product" />
</div>
}
</div>
}

<div>
<h3>@Localizer["Customer reviews"]</h3>
@await Component.InvokeAsync("Review", new { entityId = Model.Id, entityTypeId = "Product" })
Expand Down
3 changes: 3 additions & 0 deletions src/Modules/SimplCommerce.Module.Catalog/ModuleInitializer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,22 @@
using SimplCommerce.Module.Catalog.Events;
using SimplCommerce.Module.Catalog.Services;
using SimplCommerce.Module.Core.Events;
using SimplCommerce.AI.Recommendation;

namespace SimplCommerce.Module.Catalog
{
public class ModuleInitializer : IModuleInitializer
{
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IRecommendationService, RecommendationService>();
services.AddTransient<IProductTemplateProductAttributeRepository, ProductTemplateProductAttributeRepository>();
services.AddTransient<INotificationHandler<ReviewSummaryChanged>, ReviewSummaryChangedHandler>();
services.AddTransient<IBrandService, BrandService>();
services.AddTransient<ICategoryService, CategoryService>();
services.AddTransient<IProductPricingService, ProductPricingService>();
services.AddTransient<IProductService, ProductService>();
services.AddHostedService<RecommendationTrainingBackgroundService>();

GlobalConfiguration.RegisterAngularModule("simplAdmin.catalog");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\SimplCommerce.AI.Recommendation\SimplCommerce.AI.Recommendation.csproj" />
<ProjectReference Include="..\..\SimplCommerce.Infrastructure\SimplCommerce.Infrastructure.csproj" />
<ProjectReference Include="..\SimplCommerce.Module.Core\SimplCommerce.Module.Core.csproj" />
<ProjectReference Include="..\SimplCommerce.Module.Tax\SimplCommerce.Module.Tax.csproj" />
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using MediatR;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using SimplCommerce.Infrastructure.Data;
using SimplCommerce.Module.Orders.Models;

namespace SimplCommerce.Module.Orders.Events
{
public class OrderCreatedCreateDataRecomendationHandler : INotificationHandler<OrderCreated>
{
private readonly ILogger _logger;
private readonly IRepository<OrderHistory> _orderHistoryRepository;
private static string dataPath = Path.Combine(Environment.CurrentDirectory, "MLData/data.txt");

public OrderCreatedCreateDataRecomendationHandler(
IRepository<OrderHistory> orderHistoryRepository,
ILoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger<OrderCreatedCreateDataRecomendationHandler>();
_orderHistoryRepository = orderHistoryRepository;
}

public async Task Handle(OrderCreated notification, CancellationToken cancellationToken)
{
try
{
if (notification.Order != null
&& notification.Order.OrderItems != null && notification.Order.OrderItems.Count > 1)
{
StringBuilder sb = new StringBuilder();
for (var i = 0; i < notification.Order.OrderItems.Count - 1; i++)
{
var item = notification.Order.OrderItems[i];
for (var i2 = i + 1; i2 <= i + 2; i2++)
{
if (i2 < notification.Order.OrderItems.Count)
{
var item2 = notification.Order.OrderItems[i2];
if (item.ProductId != item2.ProductId)
{
sb.AppendLine(string.Format("{0}\t{1}", item.ProductId, item2.ProductId));
}
}
}
}
await File.AppendAllTextAsync(dataPath, sb.ToString());
}
}
catch (Exception ex)
{
_logger.LogError(ex, $"Failed executing event handler {GetType().Name}: {ex.Message}");
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ public void ConfigureServices(IServiceCollection services)
services.AddTransient<INotificationHandler<OrderCreated>, OrderCreatedCreateOrderHistoryHandler>();
services.AddTransient<INotificationHandler<OrderCreated>, OrderCreatedClearCartHandler>();
//services.AddTransient<INotificationHandler<AfterOrderCreated>, AfterOrderCreatedSendEmailHanlder>();
services.AddTransient<INotificationHandler<OrderCreated>, OrderCreatedCreateDataRecomendationHandler>();

GlobalConfiguration.RegisterAngularModule("simplAdmin.orders");
}
Expand Down
11 changes: 11 additions & 0 deletions src/SimplCommerce.AI.Recommendation/IRecommendationService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using Microsoft.ML;
using SimplCommerce.AI.Recommendation.Models;

namespace SimplCommerce.AI.Recommendation
{
public interface IRecommendationService
{
void BuildRecommendationModel();
ProductPrediction Predict(ProductInfo product);
}
}
10 changes: 10 additions & 0 deletions src/SimplCommerce.AI.Recommendation/Models/ProductInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
using Microsoft.ML.Data;

namespace SimplCommerce.AI.Recommendation.Models
{
public class ProductInfo
{
[LoadColumn(0)] public float ProductID { get; set; }
[LoadColumn(1)] public float CombinedProductID { get; set; }
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
namespace SimplCommerce.AI.Recommendation.Models
{
public class ProductPrediction
{
public float Score { get; set; }
}
}