AI Brand Control - Feature explained

AI Brand Control - Feature explained

1. Core Service Actions

This section describes the main actions provided by the Brand Control service, focusing on the three key operations that drive the brand compliance workflow.

1.1 Criteria Generation

Purpose

Automatically generate brand criteria from reference materials (images, documents, websites) using AI analysis. This eliminates the manual work of defining evaluation criteria by extracting them directly from existing brand assets.

How It Works

API Endpoint: POST /api/wedia/brandcontrol/brandguideline/criteria/generate

Parameters:

  • id (required): Brand guideline ID

Process Flow:

  1. Reference Collection

    • Loads the brand guideline and retrieves all associated brand references

    • Groups references by type: images, documents, websites

    • Validates that at least one reference exists

  2. Request Construction

    • Builds a GenerateCriteriaRequest with:

      • Brand guideline ID and version

      • Separate sections for images, documents, and websites

      • Specific prompts for each reference type from PromptService:

        • brandcontrol_criteria_generation: Main criteria generation prompt

        • brandcontrol_images_summary: Image analysis prompt

        • brandcontrol_documents_summary: Document analysis prompt

        • brandcontrol_websites_summary: Website analysis prompt

  3. AI Analysis (via MediaCloud/Gemini)

    • Sends the request to AwsCloudService.generateCriteria()

    • Gemini AI analyzes all references and generates structured criteria

    • Returns a JSON array of criteria with:

      • name, category, label, description

      • importance (CRITICAL, HIGH, LOW)

      • weight (0-100)

      • style_token, avoid_token (optional)

      • source (reference to source material)

  4. Database Persistence

    • Acquires a lock on the brand guideline

    • Deletes existing criteria (if any)

    • Creates new brandcriterion objects for each generated criterion

    • Links them to the parent brand guideline

    • Releases the lock

Execution Mode: Asynchronous via criteriaGenerationPool (1 thread, queue size 10)

Duration: 4-6 minutes typical processing time

Impact

  • Database Changes:

    • Deletes all existing criteria for the brand guideline

    • Creates new brandcriterion child objects

    • Brand guideline version remains unchanged

  • Analytics Events:

    • criteria_generation_requested: When task is submitted

    • criteria_generation_done: When generation completes successfully

  • Observable Side Effects:

    • Thread pool usage (occupies 1 slot in criteriaGenerationPool)

    • Criteria become available for scoring operations

    • Any existing asset scores remain valid (criteria IDs change, but old reports are preserved)

  • Error Scenarios:

    • No references: Returns 400 Bad Request

    • Service unavailable: Returns 503 if BrandControlService or AwsCloudService not configured

    • Generation failure: Logged but no client notification (async nature)


1.2 Asset Scoring

Purpose

Evaluate an asset's compliance with a brand guideline by scoring it against all defined criteria. Produces a detailed report showing which criteria pass or fail, with specific observations and correction suggestions.

How It Works

API Endpoint: POST /api/wedia/brandcontrol/score

Parameters:

  • objectType (required): Asset object type

  • objectId (required): Asset object ID

  • brandGuidelineId (required): Brand guideline to score against

Process Flow:

  1. Validation Phase

    • Verifies the asset exists and has a valid binary file

    • Checks the binary is an image type

    • Validates the brand guideline exists and is accessible by the user

    • Verifies user has view rights on the guideline (SecurityManager.canDataView())

  2. Pre-Scoring Update

    • Acquires a lock on the asset

    • Sets brandscore to -1 (indicates scoring in progress)

    • Saves the asset

    • Returns HTTP 200 immediately with {"status": "running"}

  3. Asynchronous Scoring (via scoringPool)

    • Reloads the asset in the background thread

    • Extracts the binary file path and calculates SHA-256 hash

    • Retrieves the scoring prompt (brandcontrol_score_asset)

    • Loads all criteria from the brand guideline

    • Builds a ScoreAssetRequest with:

      • Asset binary path

      • Brand guideline ID and version

      • User prompt from PromptService

      • Complete list of criteria (as CriterionDTO objects)

  4. AI Scoring (via MediaCloud/Gemini)

    • Sends the request to AwsCloudService.ScoreAsset()

    • Gemini evaluates the asset against each criterion

    • Returns a JSON response with:

      • Overall score (0-100)

      • timestamp (ISO 8601 format)

      • scores array with per-criterion results:

        • id: Criterion ID

        • status: PASS or FAIL

        • observation: What was detected

        • expected: What should be present (from criterion description)

        • correction_instruction: How to fix (if FAIL)

  5. Result Persistence

    • Acquires a lock on the asset

    • Reloads the asset to ensure fresh data

    • Constructs enriched report with metadata:

      • metadata: promptId, promptVersion, promptContentHash, assetHash

      • scores: Array of criterion evaluations

    • Updates asset fields:

      • brandguideline: Links to the guideline

      • brandscore: Final score (0-100)

      • brandscoredate: Scoring timestamp

      • brandscorereport: Full JSON report

    • Saves with forced security validation

    • Releases the lock

Execution Mode: Asynchronous via scoringPool (5 threads, queue size 100)

Duration: Varies (typically 5-30 seconds depending on criteria count and API latency)

Impact

  • Database Changes:

    • Updates 4 fields on the asset: brandguideline, brandscore, brandscoredate, brandscorereport

    • Overwrites any previous scoring results

  • Analytics Events:

    • scoring_requested: When scoring task is submitted

    • scoring_done: When scoring completes successfully

    • scoring_error: When scoring fails (includes error details)

  • Observable Side Effects:

    • Thread pool usage (occupies 1 slot in scoringPool)

    • Asset becomes locked briefly during updates

    • Score status changes: -1 (running) → 0-100 (done) or -2 (unscored or error)

  • Triggering Conditions:

    • Manual API call

    • Automatic via TempItemScoringBusinessService (for AI-generated images)

    • Automatic via MassImportItemScoringBusinessService (for bulk imports)

  • Error Scenarios:

    • No binary: Warning logged, scoring skipped

    • Not an image: Warning logged, scoring skipped

    • No access to guideline: Warning logged, scoring skipped

    • Lock timeout: Warning logged, scoring skipped

    • Scoring API failure: Score set to -2, error details in report

    • HTTP errors: Mapped to specific error codes (400, 401, 403, 429, 500, 503, etc.)


1.3 Generate Corrected Version

Purpose

Create an AI-generated corrected version of a non-compliant asset by addressing specific failed criteria while preserving aspects that passed. Uses the existing scoring report to guide the image generation process.

How It Works

API Endpoint: POST /api/wedia/brandcontrol/images/compliance/refine

Parameters:

  • objectType (required): Asset object type

  • objectId (required): Asset object ID

  • brandGuidelineId (required): Brand guideline used for scoring

  • criteriaList (required): Comma-separated list of criterion IDs to fix

  • context (optional): Free-text context to guide generation

Process Flow:

  1. Validation Phase

    • Verifies the asset exists and has a valid scoring report

    • Checks that the scoring report is up-to-date using checkScoreStatus():

      • Compares current prompt version/hash with report metadata

      • Returns 412 Precondition Failed if obsolete

    • Validates all requested criteria belong to the specified brand guideline

    • Ensures at least one valid criterion is selected

  2. Prompt Construction

    • Loads the correction prompt (brandcontrol_compliance_refine)

    • Parses the existing scoring report (BrandScoreReport)

    • Builds two criteria fragments using BrandControlUtils:

      • Failed criteria fragment (from criteriaList):

        - Color Palette - BRAND Expected: Use primary blue (#0066CC) Problem: Using off-brand purple tone Fix: Replace purple elements with brand blue
      • Passed criteria fragment (all other criteria):

        - Logo Placement: Logo correctly positioned in top-right - Typography: Font family matches brand guidelines
    • Replaces placeholders in user prompt:

      • ${FAILED_CRITERIA}: Criteria to fix

      • ${PASSED_CRITERIA}: Criteria to preserve

      • ${CONTEXT}: User-provided context

    • Builds system prompt with style/avoid tokens from ALL criteria:

      • ${STYLE_TOKENS}: Comma-separated style tokens

      • ${AVOID_TOKENS}: Comma-separated avoid tokens

  3. Task Creation

    • Creates a Task object with:

      • User ID (from CTSurfer)

      • Final prompt (user + system)

      • Object type and ID (source asset)

      • Brand guideline ID

    • Saves task to PromptService with status PENDING

    • Returns HTTP 200 immediately with task ID

  4. Asynchronous Generation (via NanoBananaService)

    • Updates task status to RUNNING

    • Calls NanoBananaService.TextAndImageToImage():

      • Uses source asset image as base

      • Applies text prompt for corrections

      • Generates new image variant

    • Creates a temporary image object (genaitempimage) with:

      • Task ID as the object name

      • Generated file as binary

      • User ID for ownership

    • Updates task status to DONE

  5. Post-Generation Scoring (Automatic)

    • TempItemScoringBusinessService trigger fires on temp image creation

    • Extracts task ID from the temp image name

    • Retrieves brand guideline ID from the task

    • Automatically submits the generated image for scoring

    • New score allows validation of the correction

Execution Mode: Asynchronous via PromptService.submitAiVariationsTask()

Duration: Varies (typically 10-60 seconds depending on image complexity)

Impact

  • Database Changes:

    • Creates a Task object in PromptService

    • Creates a temporary image object (genaitempimage or similar)

    • Automatically triggers scoring of the generated image

    • Source asset remains unchanged

  • Analytics Events:

    • bc_genai_correction_requested: When correction task is submitted

    • bc_genai_correction_done: When generation completes successfully

    • scoring_requested: When auto-scoring is triggered (via temp image trigger)

    • scoring_done: When generated image scoring completes

  • Observable Side Effects:

    • Task moves through statuses: PENDING → RUNNING → DONE or ERROR

    • Generated file saved to protected/aivariations/generated_images/{taskId}/

    • Temporary object automatically scored against same brand guideline

    • User can compare original score vs. corrected score

  • Integration Points:

    • NanoBananaService: Image generation via Gemini Imagen

    • PromptService: Task lifecycle management

    • TempItemScoringBusinessService: Automatic scoring trigger

    • BrandControlUtils: Prompt fragment construction

  • Error Scenarios:

    • No scoring report: 412 Precondition Failed

    • Obsolete report: 412 Precondition Failed (prompt version mismatch)

    • Invalid criteria: 400 Bad Request (criteria don't belong to guideline)

    • NanoBananaService unavailable: 500 Internal Server Error

    • Gemini API errors: Task status set to ERROR with specific reason code

      • Client errors (400, 401, 403, 404, 429): invalid_argument, unauthenticated, etc.

      • Server errors (500, 503, 504): internal_service_error, service_unavailable, etc.


2. Thread Pools and Asynchronous Execution

Brand Control uses asynchronous processing for AI-powered operations to provide immediate API responses while long-running tasks execute in the background. Two dedicated thread pools are initialized during service startup via ThreadPoolManager.

2.1 BrandControlScoring Pool

Purpose: Handle asset scoring operations

Configuration:

  • Pool name: BrandControlScoring

  • Worker threads: 5 (fixed size, min=5, max=5)

  • Queue capacity: 100 pending tasks

  • Thread timeout: Core threads can timeout when idle

  • Lifecycle: Shuts down when engine stops

Capacity:

  • 5 concurrent operations

  • Up to 100 operations waiting in queue

  • Total: 105 tasks can be handled before rejection

2.2 BrandControlCriteriaGeneration Pool

Purpose: Handle criteria generation from reference materials

Configuration:

  • Pool name: BrandControlCriteriaGeneration

  • Worker threads: 1 (sequential processing, min=1, max=1)

  • Queue capacity: 10 pending tasks

  • Thread timeout: Core thread can timeout when idle

  • Lifecycle: Shuts down when engine stops

Capacity:

  • 1 operation at a time (sequential)

  • Up to 10 operations waiting in queue

  • Total: 11 tasks can be handled before rejection

Rationale for single thread:

  • Criteria generation is a heavy AI operation involving multiple Gemini API calls

  • Sequential processing prevents overwhelming the Gemini API

  • Most use cases involve one-time setup or infrequent updates

2.3 Execution Model

Both pools follow the same execution pattern:

  1. API receives request → validates parameters

  2. API submits task to pool → returns immediately (HTTP 200/202)

  3. Worker thread picks up task → executes operation

  4. Operation calls Gemini via MC2 → waits for AI response

  5. Worker updates database → saves results

  6. Worker logs completion → emits analytics event

Key characteristics:

  • Non-blocking: API returns immediately, processing happens asynchronously

  • FIFO queue: Tasks executed in order of submission

  • Rejection policy: If queue is full, new tasks are rejected with exception

  • Error handling: Errors logged and recorded in database (scoring) or logged only (criteria generation)


3. Automatic Scoring Triggers

Brand Control provides automatic scoring triggers (business services) that evaluate assets without manual API calls. These triggers enable proactive compliance detection during asset creation and import workflows.

3.1 MassImportItemScoringBusinessService

Purpose: Automatically score assets during bulk import operations

Trigger condition:

  • Fires during mass import workflows when new assets are created

  • Executes after asset binary upload and metadata assignment

Execution logic:

  1. Detects asset creation during mass import

  2. Checks if the asset has a brandguideline child link already assigned

  3. If guideline link exists, submits automatic scoring

  4. Uses the linked brand guideline for evaluation

Conditions for execution:

  • Brand Control must be configured

  • Asset must have a brandguideline child relationship set

  • Asset must have a valid binary file

  • Binary must be an image type (binary.isImage() returns true)

  • Mass import context must be active

Result:

  • Assets automatically scored during import:

    • brandscore: Populated with compliance score

    • brandscoredate: Import timestamp

    • brandscorereport: Full scoring report

  • Non-compliant assets can be flagged or routed to review queues

3.2 TempItemScoringBusinessService

Purpose: Automatically score AI-generated images immediately after creation

Trigger condition:

  • Fires when a new object with tag genai_temp_image is created

  • Executes during the object creation workflow (post-save hook)

Execution logic:

  1. Detects the creation of a genai_temp_image object

  2. Extracts the task ID from the object name (naming convention: task ID used as object name)

  3. Retrieves the associated Task object from PromptService

  4. Reads the brandGuidelineId from the task metadata

  5. Submits automatic scoring: BrandControlService.submitAssetScoringTask(tempImage, brandGuidelineId, surfer)

Conditions for execution:

  • Brand Control must be configured (BrandControlService.isConfigured() returns true)

  • Object must have the genai_temp_image tag

  • Task must exist in PromptService with a valid brandGuidelineId

  • Temp image must have a valid binary file

Result:

  • Temp image fields automatically populated:

    • brandscore: Set to -1 during scoring, then 0-100 or -2

    • brandscoredate: Timestamp of scoring completion

    • brandscorereport: Full scoring report with metadata

    • brandguideline: Link to the brand guideline used

3.3 Trigger Behavior Summary

Trigger

When

Condition

Guideline Source

Typical Duration

Trigger

When

Condition

Guideline Source

Typical Duration

TempItemScoringBusinessService

GenAI image created

Object has genai_temp_image tag

From task metadata

10-35 seconds

MassImportItemScoringBusinessService

Asset imported

Asset has brandguideline link

From asset relationship

10-35 seconds

Common characteristics:

  • Both triggers use the same scoring pool (BrandControlScoring, 5 threads)

  • Both skip scoring if conditions not met (logged as warning, no error)

  • Both set brandscore=-1 immediately and update asynchronously

  • Both emit analytics events (scoring_requested, scoring_done, scoring_error)

Disabling triggers:

  • Triggers automatically disabled if BrandControlService.isConfigured() returns false

  • No configuration option to disable individual triggers

  • To prevent automatic scoring: don't assign brandguideline relationships or don't use genai_temp_image tag



4. Score Obsolescence Detection

4.1 Purpose

Detect when stored compliance scores become invalid due to prompt changes. Ensures assets are evaluated with current criteria and prevents using outdated scores for GenAI correction operations.

4.2 How It Works

Score Metadata

During scoring, metadata is stored in brandscorereport:

{ "metadata": { "promptId": "prompt_001", "promptVersion": 3, "promptContentHash": "a7f9c3e...", // SHA-256 of prompt content "assetHash": "sha256:9f4e2b..." // SHA-256 of asset binary }, "scores": [...] }

Prompt Content Hash

Hash calculated from: userPrompt + "|" + systemPrompt + "|" + fragments + "|" + aiModel

Includes: Content that affects scoring results
Excludes: Metadata (name, timestamps, activation status)

Obsolescence Check

API Endpoint: GET /api/wedia/brandcontrol/score/status?objectType={type}&objectId={id}

Process:

  1. Load current scoring report

  2. Retrieve current brandcontrol_score_asset prompt

  3. Calculate current hash

  4. Compare with stored hash

Response:

{ "isObsolete": false, "reason": null, "currentPromptVersion": 3, "currentPromptHash": "a7f9c3e...", "reportPromptVersion": 3, "reportPromptHash": "a7f9c3e..." }

4.3 Obsolescence Reasons

Reason

Description

Reason

Description

prompt_content_changed

Hash mismatch between current and stored prompt

no_score

Asset never scored

legacy_format

Old array format (pre-metadata)

invalid_format

Corrupt JSON

missing_hash

No hash in metadata

prompt_not_found

Scoring prompt deleted

Resolution: Re-score the asset

4.4 Impact on Operations

Manual scoring (POST /score):

  • No validation, always overwrites existing score

  • Use to update obsolete scores

GenAI correction (POST /images/compliance/refine):

  • Strict validation: Requires up-to-date score

  • Returns HTTP 412 Precondition Failed if:

    • No scoring report exists (no_score_report)

    • Score is obsolete (obsolete_score_report)

Rationale: Correction prompts use specific criterion observations; obsolete scores could generate incorrect corrections.

4.5 Common Scenarios

Change

Effect

Hash Changes?

Scores Obsolete?

Change

Effect

Hash Changes?

Scores Obsolete?

Update prompt content

Evaluation logic changes

✓ Yes

✓ Yes

Increment prompt version (same content)

Version number increases

✗ No

✗ No

Change AI model

Different evaluation behavior

✓ Yes

✓ Yes

Add criterion to guideline

Scores incomplete (missing new criterion)

✗ No

✗ No*

*Hash-based detection won't flag this; re-scoring recommended but not enforced.

4.6 Recommended Workflow

User selects asset for correction ↓ GET /score/status ↓ If isObsolete=true: → Display: "Score outdated, re-scoring required" → Trigger: POST /score → Wait for completion ↓ If isObsolete=false: → Proceed: POST /images/compliance/refine