Skip to content

doc(BaiduOcr): update sample code#8075

Merged
ArgoZhang merged 1 commit into
mainfrom
dev-ocr
Jun 1, 2026
Merged

doc(BaiduOcr): update sample code#8075
ArgoZhang merged 1 commit into
mainfrom
dev-ocr

Conversation

@ArgoZhang
Copy link
Copy Markdown
Member

@ArgoZhang ArgoZhang commented Jun 1, 2026

Link issues

fixes #8074

Summary By Copilot

Regression?

  • Yes
  • No

Risk

  • High
  • Medium
  • Low

Verification

  • Manual (required)
  • Automated

Packaging changes reviewed?

  • Yes
  • No
  • N/A

☑️ Self Check before Merge

⚠️ Please check all items below before review. ⚠️

  • Doc is updated/provided or not needed
  • Demo is updated/provided or not needed
  • Merge the latest code from the main branch

Summary by Sourcery

Update the Baidu OCR sample to use fully localized UI text and validation while expanding the configuration example.

Enhancements:

  • Localize all Baidu OCR sample labels, button text, placeholders, and toast messages via resource keys.
  • Replace attribute-based validation on the invoice form with IValidatableObject-based validation that uses localized error messages.

Documentation:

  • Refresh the Baidu OCR sample documentation to include service registration and clearer configuration steps.

Copilot AI review requested due to automatic review settings June 1, 2026 02:17
@bb-auto bb-auto Bot added the documentation Improvements or additions to documentation label Jun 1, 2026
@bb-auto bb-auto Bot added this to the v10.7.0 milestone Jun 1, 2026
@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented Jun 1, 2026

Reviewer's Guide

Updates the Baidu OCR sample to be fully localizable, refines the step-by-step sample code, improves toast messaging, and replaces data-annotation-based validation with localized, model-level validation logic, along with corresponding locale resource updates.

Sequence diagram for localized model-level validation in BaiduOcr verify flow

sequenceDiagram
    actor User
    participant BaiduOcr
    participant ValidateForm
    participant InvoiceForm
    participant IStringLocalizer_BaiduOcr

    User->>BaiduOcr: Submit Verify form
    BaiduOcr->>ValidateForm: ValidateForm.OnValidSubmit
    ValidateForm->>InvoiceForm: Validate
    InvoiceForm->>IStringLocalizer_BaiduOcr: indexer InvoiceCodeRequiredError
    IStringLocalizer_BaiduOcr-->>InvoiceForm: Localized message
    InvoiceForm-->>ValidateForm: IEnumerable ValidationResult
    alt [model is valid]
        ValidateForm->>BaiduOcr: Invoke Verify(EditContext)
        BaiduOcr->>BaiduOcr: OcrService.VerifyInvoiceAsync(...)
    else [model has errors]
        ValidateForm-->>User: Display localized validation messages
    end
Loading

File-Level Changes

Change Details Files
Make Baidu OCR sample UI and instructional text fully localizable and improve sample configuration/usage steps.
  • Switch various hard-coded Chinese labels, button texts, and helper texts to use Localizer string keys throughout the BaiduOcr.razor sample.
  • Adjust the step flow to introduce a new service registration step and reorder step labels for clarity.
  • Replace a localized MarkupString usage with plain localized text where HTML markup is not needed.
src/BootstrapBlazor.Server/Components/Samples/BaiduOcr.razor
Localize toast messages and improve verification result handling in the Baidu OCR code-behind.
  • Replace hard-coded toast titles and messages with Localizer-based strings for both invoice recognition and verification flows.
  • Provide a localized fallback message for unknown verification errors.
src/BootstrapBlazor.Server/Components/Samples/BaiduOcr.razor.cs
Replace attribute-based validation on the invoice form with localized, model-level validation logic.
  • Change InvoiceForm to implement IValidatableObject and remove hard-coded Chinese Required attributes.
  • Implement Validate method that uses IStringLocalizer to generate localized validation error messages per field.
src/BootstrapBlazor.Server/Components/Samples/BaiduOcr.razor.cs
Update localization resource files to supply the new Baidu OCR-related keys and messages.
  • Add or adjust en-US resources for all new Baidu OCR labels, placeholders, button texts, toast titles, messages, and validation errors.
  • Add or adjust zh-CN resources to mirror the new keys and provide Chinese translations.
src/BootstrapBlazor.Server/Locales/en-US.json
src/BootstrapBlazor.Server/Locales/zh-CN.json

Assessment against linked issues

Issue Objective Addressed Explanation
#8074 Update the BaiduOcr documentation/sample component to reflect the current recommended usage and configuration steps.
#8074 Improve and localize the BaiduOcr sample UI text, including labels, button text, toast messages, and validation messages.

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Copy Markdown
Contributor

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

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

Hey - I've found 1 issue, and left some high level feedback:

  • In InvoiceForm, InvoiceType and TotalAmount are marked [NotNull] but are not validated in Validate; either add explicit validation rules for them or remove [NotNull] where the field is intended to be optional (e.g., TotalAmount).
  • The placeholder for TotalAmount (AmountPlaceHolder) suggests the field can be empty, but the [NotNull] annotation and method signature (VerifyInvoiceAsync last parameter) imply it is required; consider aligning the validation and annotations with the intended API behavior to avoid inconsistent UX.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In `InvoiceForm`, `InvoiceType` and `TotalAmount` are marked `[NotNull]` but are not validated in `Validate`; either add explicit validation rules for them or remove `[NotNull]` where the field is intended to be optional (e.g., `TotalAmount`).
- The placeholder for `TotalAmount` (`AmountPlaceHolder`) suggests the field can be empty, but the `[NotNull]` annotation and method signature (`VerifyInvoiceAsync` last parameter) imply it is required; consider aligning the validation and annotations with the intended API behavior to avoid inconsistent UX.

## Individual Comments

### Comment 1
<location path="src/BootstrapBlazor.Server/Components/Samples/BaiduOcr.razor.cs" line_range="88" />
<code_context>
         }
     }

-    private class InvoiceForm
+    private class InvoiceForm : IValidatableObject
     {
</code_context>
<issue_to_address>
**issue (complexity):** Consider extracting a reusable helper and using a data-driven loop in `InvoiceForm.Validate` to handle required-field checks and localized messages instead of repeating similar `if` blocks for each property.

You can keep the `IValidatableObject` approach and localized messages, but reduce duplication and cognitive load by extracting a small helper and using a data-driven pattern:

```csharp
private class InvoiceForm : IValidatableObject
{
    [NotNull] public string? InvoiceCode { get; set; }
    [NotNull] public string? InvoiceNum { get; set; }
    [NotNull] public string? InvoiceDate { get; set; }
    [NotNull] public string? InvoiceType { get; set; }
    [NotNull] public string? CheckCode { get; set; }
    [NotNull] public string? TotalAmount { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        var localizer = validationContext.GetRequiredService<IStringLocalizer<BaiduOcr>>();

        foreach (var result in ValidateRequired(
            localizer,
            (InvoiceCode, "InvoiceCodeRequiredError", nameof(InvoiceCode)),
            (InvoiceNum, "InvoiceNumRequiredError", nameof(InvoiceNum)),
            (InvoiceDate, "InvoiceDateRequiredError", nameof(InvoiceDate)),
            (CheckCode, "CheckCodeRequiredError", nameof(CheckCode))
        ))
        {
            yield return result;
        }
    }

    private static IEnumerable<ValidationResult> ValidateRequired(
        IStringLocalizer<BaiduOcr> localizer,
        params (string? Value, string ErrorKey, string MemberName)[] fields
    )
    {
        foreach (var (value, errorKey, memberName) in fields)
        {
            if (string.IsNullOrWhiteSpace(value))
            {
                yield return new ValidationResult(
                    localizer[errorKey],
                    new[] { memberName }
                );
            }
        }
    }
}
```

This keeps the same behavior (localized messages via `IStringLocalizer<BaiduOcr>` and `IValidatableObject`) but removes the repeated `if (string.IsNullOrWhiteSpace(...)) yield return new ValidationResult(...)` blocks and centralizes the pattern in a single helper.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

}
}

private class InvoiceForm
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

issue (complexity): Consider extracting a reusable helper and using a data-driven loop in InvoiceForm.Validate to handle required-field checks and localized messages instead of repeating similar if blocks for each property.

You can keep the IValidatableObject approach and localized messages, but reduce duplication and cognitive load by extracting a small helper and using a data-driven pattern:

private class InvoiceForm : IValidatableObject
{
    [NotNull] public string? InvoiceCode { get; set; }
    [NotNull] public string? InvoiceNum { get; set; }
    [NotNull] public string? InvoiceDate { get; set; }
    [NotNull] public string? InvoiceType { get; set; }
    [NotNull] public string? CheckCode { get; set; }
    [NotNull] public string? TotalAmount { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        var localizer = validationContext.GetRequiredService<IStringLocalizer<BaiduOcr>>();

        foreach (var result in ValidateRequired(
            localizer,
            (InvoiceCode, "InvoiceCodeRequiredError", nameof(InvoiceCode)),
            (InvoiceNum, "InvoiceNumRequiredError", nameof(InvoiceNum)),
            (InvoiceDate, "InvoiceDateRequiredError", nameof(InvoiceDate)),
            (CheckCode, "CheckCodeRequiredError", nameof(CheckCode))
        ))
        {
            yield return result;
        }
    }

    private static IEnumerable<ValidationResult> ValidateRequired(
        IStringLocalizer<BaiduOcr> localizer,
        params (string? Value, string ErrorKey, string MemberName)[] fields
    )
    {
        foreach (var (value, errorKey, memberName) in fields)
        {
            if (string.IsNullOrWhiteSpace(value))
            {
                yield return new ValidationResult(
                    localizer[errorKey],
                    new[] { memberName }
                );
            }
        }
    }
}

This keeps the same behavior (localized messages via IStringLocalizer<BaiduOcr> and IValidatableObject) but removes the repeated if (string.IsNullOrWhiteSpace(...)) yield return new ValidationResult(...) blocks and centralizes the pattern in a single helper.

Copy link
Copy Markdown
Contributor

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 updates the Baidu OCR sample in the server demo to fully localize its UI/UX text (labels, placeholders, toast messages, and option lists) and refresh the usage documentation flow (service registration → options configuration → injection → usage). It also replaces attribute-based required validation with IValidatableObject so validation messages can be localized via resource keys.

Changes:

  • Expanded en-US / zh-CN locale entries for the BaiduOcr sample (labels, placeholders, option list items, toast texts).
  • Updated the BaiduOcr sample UI to use localized strings everywhere and added a service registration snippet.
  • Updated the invoice verify form model to validate via IValidatableObject and use localized validation messages.

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 5 comments.

File Description
src/BootstrapBlazor.Server/Locales/zh-CN.json Adds BaiduOcr localized UI strings and updates usage steps for Chinese locale.
src/BootstrapBlazor.Server/Locales/en-US.json Adds BaiduOcr localized UI strings and updates usage steps for English locale.
src/BootstrapBlazor.Server/Components/Samples/BaiduOcr.razor.cs Localizes toast text and switches invoice form required checks to IValidatableObject with localized error keys.
src/BootstrapBlazor.Server/Components/Samples/BaiduOcr.razor Uses localized labels/placeholders throughout and updates the usage steps to include service registration.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +108 to +115
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var localizer = validationContext.GetRequiredService<IStringLocalizer<BaiduOcr>>();

if (string.IsNullOrWhiteSpace(InvoiceCode))
{
yield return new ValidationResult(localizer["InvoiceCodeRequiredError"], [nameof(InvoiceCode)]);
}
Comment on lines +949 to +954
"VatInvoiceToastSuccess": "VAT invoice recognized successfully!",
"VatInvoiceToastTitle": "VAT Invoice",
"VerifyButtonText": "Verify",
"VerifyVatInvoiceIntro": "Call the invoice verification method <code>VerifyInvoiceAsync</code> on the <code>IBaiduOcr</code> service. When the returned <code>InvoiceVerifyResult</code> has <code>Valid</code> set to <code>true</code>, the invoice is valid.",
"VerifyVatInvoiceTitle": "VAT Invoice Verification",
"VerifyVatToastTitle": "VAT Verification"
Comment on lines +949 to +954
"VatInvoiceToastSuccess": "增值税发票识别成功!",
"VatInvoiceToastTitle": "增值税发票",
"VerifyButtonText": "验证",
"VerifyVatInvoiceIntro": "通过调用 <code>IBaiduOcr</code> 服务实例的发票验真方法 <code>VerifyInvoiceAsync</code> 返回 <code>InvoiceVerifyResult</code> 其属性 <code>Valid</code> 为 <code>true</code> 时为真",
"VerifyVatInvoiceTitle": "增值税验真"
"VerifyVatInvoiceTitle": "增值税验真",
"VerifyVatToastTitle": "增值税验真"
Comment on lines +902 to 903
"BaiduOcrStep1": "1. Register the service",
"BaiduOcrStep1Desc": "Update the <code>appsettings.json</code> file with the following configuration. Please register on <a href=\"https://ai.baidu.com/ai-doc/index/OCR\" target=\"\">Baidu AI Open Platform</a> and apply for relevant parameter values.",
Comment on lines 901 to 903
"BaiduOcrIntro": "使用方法",
"BaiduOcrStep1": "1. 配置 <code>BaiduOcrOption</code>",
"BaiduOcrStep1": "1. 注入服务",
"BaiduOcrStep1Desc": "更新 <code>appsettings.json</code> 文件,配置如下:相关参数值请在 <a href=\"https://ai.baidu.com/ai-doc/index/OCR\" target=\"\">百度 AI 开放平台</a> 注册后开通申请",
@codecov
Copy link
Copy Markdown

codecov Bot commented Jun 1, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (cc9ac4f) to head (a58f6c1).

Additional details and impacted files
@@            Coverage Diff            @@
##              main     #8075   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files          766       766           
  Lines        34171     34171           
  Branches      4700      4700           
=========================================
  Hits         34171     34171           
Flag Coverage Δ
BB 100.00% <ø> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@ArgoZhang ArgoZhang merged commit 022f9f8 into main Jun 1, 2026
7 checks passed
@ArgoZhang ArgoZhang deleted the dev-ocr branch June 1, 2026 05:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

doc(BaiduOcr): update sample code

2 participants