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

Conversation

ysmoradi
Copy link
Member

@ysmoradi ysmoradi commented Jun 21, 2025

closes #11004

Summary by CodeRabbit

  • New Features
    • Added AI-based validation for product image uploads to ensure the image contains a car; uploads are rejected with a clear error message if not.
  • Bug Fixes
    • Improved handling of file paths for attachments to ensure consistency and reliability.
  • Documentation
    • Added new localized error messages for image validation failures in English and Persian.
  • Security
    • Enhanced authorization for deleting product images, requiring appropriate permissions.

@ysmoradi ysmoradi requested a review from Copilot June 21, 2025 15:57
Copy link

coderabbitai bot commented Jun 21, 2025

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The changes refactor attachment file path generation into a helper method, introduce AI-based validation for uploaded product images to check for cars, update localization resources for error messaging, and adjust authorization and state update logic for image uploads and deletions.

Changes

File(s) Change Summary
.../Boilerplate.Server.Api/Controllers/AttachmentController.cs Refactored file path logic into GetFilePath, added AI-based image validation, updated authorization and state handling.
.../Resources/AppStrings.resx
.../Resources/AppStrings.fa.resx
Added new localized error string "ImageNotCarError" for English and Farsi.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant AttachmentController
    participant AIChatClient
    participant FileSystem
    participant ProductState

    Client->>AttachmentController: UploadAttachment (ProductPrimaryImageMedium)
    AttachmentController->>FileSystem: Save uploaded image
    alt AIChatClient available
        AttachmentController->>AIChatClient: Send image, ask "Is this a car?"
        AIChatClient-->>AttachmentController: "Yes" or "No"
        alt Response is "No"
            AttachmentController-->>Client: Return error "ImageNotCarError"
        else Response is "Yes"
            AttachmentController->>ProductState: Update product image state
            AttachmentController-->>Client: Return success
        end
    else AIChatClient not available
        AttachmentController->>ProductState: Update product image state
        AttachmentController-->>Client: Return success
    end
Loading

Assessment against linked issues

Objective Addressed Explanation
AI-based validation of uploaded product images (#11004)
Localized error message for invalid image (not a car) (#11004)
Refactor/reuse of file path logic for attachments (#11004)
Proper authorization for deleting product images (#11004)

Poem

In fields of code where images roam,
A clever bunny checks each home—
"Is this a car?" the AI asks,
Only true autos pass the tasks.
With error strings in every tongue,
The upload song is sung!
🐇✨

✨ Finishing Touches
🧪 Generate Unit Tests
  • Create PR with Unit Tests
  • Post Copyable Unit Tests in Comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai auto-generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@Copilot Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This PR adds a new error message to indicate when an uploaded image does not contain a car and integrates an AI chat client to validate product images. In addition, it updates the resource files with the new message and refactors file path generation in the attachment controller.

  • Added "ImageNotCarError" resource text in both English and Farsi resource files.
  • Modified the attachment controller to use a helper method (GetFilePath) and integrate a chat client check for car images.
  • Updated endpoint attributes to improve access control and parameter handling.

Reviewed Changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 1 comment.

File Description
src/Templates/Boilerplate/Bit.Boilerplate/src/Shared/Resources/AppStrings.resx Added new error message for images without a car.
src/Templates/Boilerplate/Bit.Boilerplate/src/Shared/Resources/AppStrings.fa.resx Added Farsi translation for the new error message.
src/Templates/Boilerplate/Bit.Boilerplate/src/Server/Boilerplate.Server.Api/Controllers/AttachmentController.cs Refactored file path generation, adjusted endpoint parameters, and integrated AI image validation.
Comments suppressed due to low confidence (1)

src/Templates/Boilerplate/Bit.Boilerplate/src/Server/Boilerplate.Server.Api/Controllers/AttachmentController.cs:250

  • The use of Path.GetExtension(fileName) may throw a NullReferenceException if fileName is null; consider adding a validation or a default value for fileName when the extension is required.
            AttachmentKind.ProductPrimaryImageOriginal => $"{AppSettings.ProductImagesDir}{attachmentId}_{kind}{Path.GetExtension(fileName)}",

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🔭 Outside diff range comments (1)
src/Templates/Boilerplate/Bit.Boilerplate/src/Server/Boilerplate.Server.Api/Controllers/AttachmentController.cs (1)

178-194: Fix potential null reference in AI validation

The imageBytes variable is only assigned when the image needs resizing. If ProductPrimaryImageOriginal is uploaded (which doesn't need resizing), imageBytes will be null when passed to the AI validation, causing a null reference exception.

 byte[]? imageBytes = null;

 if (imageResizeContext.NeedsResize)
 {
     using MagickImage sourceImage = new(file.OpenReadStream());

     if (sourceImage.Width < imageResizeContext.Width || sourceImage.Height < imageResizeContext.Height)
         return BadRequest(Localizer[nameof(AppStrings.ImageTooSmall), imageResizeContext.Width, imageResizeContext.Height, sourceImage.Width, sourceImage.Height].ToString());

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

     await blobStorage.WriteAsync(attachment.Path, imageBytes = sourceImage.ToByteArray(MagickFormat.WebP), cancellationToken: cancellationToken);
 }
 else
 {
+    using var stream = file.OpenReadStream();
+    using var memoryStream = new MemoryStream();
+    await stream.CopyToAsync(memoryStream, cancellationToken);
+    imageBytes = memoryStream.ToArray();
     await blobStorage.WriteAsync(attachment.Path, file.OpenReadStream(), cancellationToken: cancellationToken);
 }

Also applies to: 209-209

🧹 Nitpick comments (1)
src/Templates/Boilerplate/Bit.Boilerplate/src/Server/Boilerplate.Server.Api/Controllers/AttachmentController.cs (1)

200-214: Consider adding configuration and monitoring

For production readiness, consider:

  1. Adding a configuration flag to enable/disable AI validation
  2. Implementing metrics to track AI validation success/failure rates
  3. Adding a fallback mechanism when AI service is unavailable
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Knowledge Base: Disabled due to Reviews > Disable Knowledge Base setting

📥 Commits

Reviewing files that changed from the base of the PR and between 892295c and 6e5fa51.

📒 Files selected for processing (3)
  • src/Templates/Boilerplate/Bit.Boilerplate/src/Server/Boilerplate.Server.Api/Controllers/AttachmentController.cs (9 hunks)
  • src/Templates/Boilerplate/Bit.Boilerplate/src/Shared/Resources/AppStrings.fa.resx (1 hunks)
  • src/Templates/Boilerplate/Bit.Boilerplate/src/Shared/Resources/AppStrings.resx (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build and test
🔇 Additional comments (6)
src/Templates/Boilerplate/Bit.Boilerplate/src/Shared/Resources/AppStrings.resx (1)

1355-1357: LGTM!

The new error message resource is clear and appropriate for the AI-based car detection feature.

src/Templates/Boilerplate/Bit.Boilerplate/src/Shared/Resources/AppStrings.fa.resx (1)

1349-1351: LGTM!

The Persian translation is consistent with the English version and appropriate for the feature.

src/Templates/Boilerplate/Bit.Boilerplate/src/Server/Boilerplate.Server.Api/Controllers/AttachmentController.cs (4)

22-24: Service locator pattern is acceptable here

The conditional injection of IServiceProvider is appropriate given that IChatClient may not always be registered. This allows graceful degradation when AI validation is not available.


83-83: Excellent security improvement!

Adding authorization to the DeleteProductPrimaryImage endpoint is crucial. Product catalog management operations should always be protected.


200-200: Logical improvement in state update conditions

Changing the conditions to use the resized image kinds (Medium/Small) instead of Original is correct, as these are the versions that are validated and displayed to users.

Also applies to: 226-226


244-260: Excellent refactoring!

The GetFilePath helper method effectively centralizes the file path generation logic, reducing code duplication and improving maintainability. The use of Environment.ExpandEnvironmentVariables is appropriate for handling environment-specific paths.

@ysmoradi ysmoradi merged commit 23e294e into bitfoundation:develop Jun 22, 2025
3 checks passed
@ysmoradi ysmoradi deleted the 11004 branch June 22, 2025 13:28
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Boilerplate project template should validate uploaded product images using AI
1 participant