Skip to content

Check uploaded product image in Boilerplate using AI (#11004) #11005

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

Merged
merged 2 commits into from
Jun 22, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,11 @@ public partial class AttachmentController : AppControllerBase, IAttachmentContro
[AutoInject] private IBlobStorage blobStorage = default!;
[AutoInject] private UserManager<User> userManager = default!;

//#if (signalR == true || database == "PostgreSQL")
[AutoInject] private IServiceProvider serviceProvider = default!;
[AutoInject] private ILogger<AttachmentController> logger = default!;
//#endif

//#if (signalR == true)
[AutoInject] private IHubContext<AppHub> appHubContext = default!;
//#endif
Expand Down Expand Up @@ -54,18 +59,9 @@ public async Task<IActionResult> UploadProductPrimaryImage(Guid productId, IForm
[AllowAnonymous]
[HttpGet("{attachmentId}/{kind}")]
[AppResponseCache(MaxAge = 3600 * 24 * 7, UserAgnostic = true)]
public async Task<IActionResult> GetAttachment(Guid attachmentId, AttachmentKind kind, CancellationToken cancellationToken)
public async Task<IActionResult> GetAttachment(Guid attachmentId, AttachmentKind kind, CancellationToken cancellationToken = default)
{
var filePath = kind switch
{
//#if (module == "Sales" || module == "Admin")
AttachmentKind.ProductPrimaryImageMedium => $"{AppSettings.ProductImagesDir}{attachmentId}_{kind}.webp",
//#endif
AttachmentKind.UserProfileImageSmall => $"{AppSettings.UserProfileImagesDir}{attachmentId}_{kind}.webp",
_ => throw new NotImplementedException()
};

filePath = Environment.ExpandEnvironmentVariables(filePath);
var filePath = GetFilePath(attachmentId, kind);

if (await blobStorage.ExistsAsync(filePath, cancellationToken) is false)
throw new ResourceNotFoundException();
Expand All @@ -85,7 +81,7 @@ public async Task DeleteUserProfilePicture(CancellationToken cancellationToken)
}

//#if (module == "Sales" || module == "Admin")
[HttpDelete("{productId}")]
[HttpDelete("{productId}"), Authorize(Policy = AppFeatures.AdminPanel.ManageProductCatalog)]
public async Task DeleteProductPrimaryImage(Guid productId, CancellationToken cancellationToken)
{
await DeleteAttachment(productId, [AttachmentKind.ProductPrimaryImageMedium, AttachmentKind.ProductPrimaryImageOriginal], cancellationToken);
Expand Down Expand Up @@ -163,20 +159,9 @@ private async Task<IActionResult> UploadAttachment(Guid attachmentId, Attachment
{
Id = attachmentId,
Kind = kind,
Path = kind switch
{
AttachmentKind.UserProfileImageOriginal => $"{AppSettings.UserProfileImagesDir}{attachmentId}_{kind}{Path.GetExtension(file.FileName)}",
AttachmentKind.UserProfileImageSmall => $"{AppSettings.UserProfileImagesDir}{attachmentId}_{kind}.webp",
//#if (module == "Sales" || module == "Admin")
AttachmentKind.ProductPrimaryImageOriginal => $"{AppSettings.ProductImagesDir}{attachmentId}_{kind}{Path.GetExtension(file.FileName)}",
AttachmentKind.ProductPrimaryImageMedium => $"{AppSettings.ProductImagesDir}{attachmentId}_{kind}.webp",
//#endif
_ => throw new NotImplementedException()
}
Path = GetFilePath(attachmentId, kind, file.FileName),
};

attachment.Path = Environment.ExpandEnvironmentVariables(attachment.Path);

if (await blobStorage.ExistsAsync(attachment.Path, cancellationToken))
{
await blobStorage.DeleteAsync(attachment.Path, cancellationToken);
Expand All @@ -191,6 +176,8 @@ private async Task<IActionResult> UploadAttachment(Guid attachmentId, Attachment
_ => (false, 0, 0)
};

byte[]? imageBytes = null;

if (imageResizeContext.NeedsResize)
{
using MagickImage sourceImage = new(file.OpenReadStream());
Expand All @@ -200,7 +187,7 @@ private async Task<IActionResult> UploadAttachment(Guid attachmentId, Attachment

sourceImage.Resize(new MagickGeometry(imageResizeContext.Width, imageResizeContext.Height));

await blobStorage.WriteAsync(attachment.Path, sourceImage.ToByteArray(MagickFormat.WebP), cancellationToken: cancellationToken);
await blobStorage.WriteAsync(attachment.Path, imageBytes = sourceImage.ToByteArray(MagickFormat.WebP), cancellationToken: cancellationToken);
}
else
{
Expand All @@ -211,8 +198,29 @@ private async Task<IActionResult> UploadAttachment(Guid attachmentId, Attachment
await DbContext.SaveChangesAsync(cancellationToken);

//#if (module == "Sales" || module == "Admin")
if (attachment.Kind is AttachmentKind.ProductPrimaryImageOriginal)
if (attachment.Kind is AttachmentKind.ProductPrimaryImageMedium)
{
//#if (signalR == true || database == "PostgreSQL")
if (serviceProvider.GetService<IChatClient>() is IChatClient chatClient)
{
string responseText = (await chatClient.GetResponseAsync([
new ChatMessage(ChatRole.System, "Respond with EXACTLY one word: 'Yes' if the image contains a car, 'No' if it does not. Do NOT describe the image, explain, or add any other text. Violating this will result in an invalid response."),
new ChatMessage(ChatRole.User, "Is this an image of a car?")
{
Contents = [new DataContent(imageBytes, "image/webp")]
}], cancellationToken: cancellationToken, options: new() { Temperature = 0 })).Text.Trim().ToLower();

if (responseText is "no")
{
return BadRequest(Localizer[nameof(AppStrings.ImageNotCarError)].ToString());
}
else if (responseText is not "yes")
{
logger.LogWarning("Unexpected AI response for car detection: {Response}", responseText);
}
}
//#endif

var product = await DbContext.Products.FindAsync([attachment.Id], cancellationToken);
if (product is not null) // else means product is being added to the database.
{
Expand All @@ -223,7 +231,7 @@ private async Task<IActionResult> UploadAttachment(Guid attachmentId, Attachment
}
//#endif

if (kind is AttachmentKind.UserProfileImageOriginal)
if (kind is AttachmentKind.UserProfileImageSmall)
{
var user = await userManager.FindByIdAsync(User.GetUserId().ToString());
user!.HasProfilePicture = true;
Expand All @@ -240,4 +248,22 @@ private async Task<IActionResult> UploadAttachment(Guid attachmentId, Attachment

return Ok();
}

private string GetFilePath(Guid attachmentId, AttachmentKind kind, string? fileName = null)
{
var filePath = kind switch
{
//#if (module == "Sales" || module == "Admin")
AttachmentKind.ProductPrimaryImageMedium => $"{AppSettings.ProductImagesDir}{attachmentId}_{kind}.webp",
AttachmentKind.ProductPrimaryImageOriginal => $"{AppSettings.ProductImagesDir}{attachmentId}_{kind}{Path.GetExtension(fileName)}",
//#endif
AttachmentKind.UserProfileImageSmall => $"{AppSettings.UserProfileImagesDir}{attachmentId}_{kind}.webp",
AttachmentKind.UserProfileImageOriginal => $"{AppSettings.UserProfileImagesDir}{attachmentId}_{kind}{Path.GetExtension(fileName)}",
_ => throw new NotImplementedException()
};

filePath = Environment.ExpandEnvironmentVariables(filePath);

return filePath;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -1346,4 +1346,7 @@
<data name="ImageTooSmall" xml:space="preserve">
<value>تصویر خیلی کوچک است. حداقل ابعاد مورد نیاز {0}x{1} است، اما ابعاد فعلی {2}x{3} است.</value>
</data>
<data name="ImageNotCarError" xml:space="preserve">
<value>تصویر ارائه شده حاوی ماشین نیست.</value>
</data>
</root>
Original file line number Diff line number Diff line change
Expand Up @@ -1352,4 +1352,7 @@ After reaching {0}, extra sign-ins will have reduced functions.</value>
<data name="ImageTooSmall" xml:space="preserve">
<value>Image's too small. Minimum required dimensions are {0}x{1}, but the current dimensions are {2}x{3}.</value>
</data>
<data name="ImageNotCarError" xml:space="preserve">
<value>The provided image does not contain a car.</value>
</data>
</root>
Loading