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:
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
Request Construction
Builds a
GenerateCriteriaRequestwith: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 promptbrandcontrol_images_summary: Image analysis promptbrandcontrol_documents_summary: Document analysis promptbrandcontrol_websites_summary: Website analysis prompt
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,descriptionimportance(CRITICAL, HIGH, LOW)weight(0-100)style_token,avoid_token(optional)source(reference to source material)
Database Persistence
Acquires a lock on the brand guideline
Deletes existing criteria (if any)
Creates new
brandcriterionobjects for each generated criterionLinks 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
brandcriterionchild objectsBrand guideline version remains unchanged
Analytics Events:
criteria_generation_requested: When task is submittedcriteria_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
BrandControlServiceorAwsCloudServicenot configuredGeneration 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 typeobjectId(required): Asset object IDbrandGuidelineId(required): Brand guideline to score against
Process Flow:
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())
Pre-Scoring Update
Acquires a lock on the asset
Sets
brandscoreto-1(indicates scoring in progress)Saves the asset
Returns HTTP 200 immediately with
{"status": "running"}
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
ScoreAssetRequestwith:Asset binary path
Brand guideline ID and version
User prompt from
PromptServiceComplete list of criteria (as
CriterionDTOobjects)
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)scoresarray with per-criterion results:id: Criterion IDstatus: PASS or FAILobservation: What was detectedexpected: What should be present (from criterion description)correction_instruction: How to fix (if FAIL)
Result Persistence
Acquires a lock on the asset
Reloads the asset to ensure fresh data
Constructs enriched report with metadata:
metadata:promptId,promptVersion,promptContentHash,assetHashscores: Array of criterion evaluations
Updates asset fields:
brandguideline: Links to the guidelinebrandscore: Final score (0-100)brandscoredate: Scoring timestampbrandscorereport: 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,brandscorereportOverwrites any previous scoring results
Analytics Events:
scoring_requested: When scoring task is submittedscoring_done: When scoring completes successfullyscoring_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 reportHTTP 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 typeobjectId(required): Asset object IDbrandGuidelineId(required): Brand guideline used for scoringcriteriaList(required): Comma-separated list of criterion IDs to fixcontext(optional): Free-text context to guide generation
Process Flow:
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
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 bluePassed 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
Task Creation
Creates a
Taskobject with:User ID (from CTSurfer)
Final prompt (user + system)
Object type and ID (source asset)
Brand guideline ID
Saves task to
PromptServicewith statusPENDINGReturns HTTP 200 immediately with task ID
Asynchronous Generation (via NanoBananaService)
Updates task status to
RUNNINGCalls
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
Post-Generation Scoring (Automatic)
TempItemScoringBusinessServicetrigger fires on temp image creationExtracts 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
Taskobject inPromptServiceCreates a temporary image object (
genaitempimageor similar)Automatically triggers scoring of the generated image
Source asset remains unchanged
Analytics Events:
bc_genai_correction_requested: When correction task is submittedbc_genai_correction_done: When generation completes successfullyscoring_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→DONEorERRORGenerated 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 ImagenPromptService: Task lifecycle managementTempItemScoringBusinessService: Automatic scoring triggerBrandControlUtils: 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:
BrandControlScoringWorker 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:
BrandControlCriteriaGenerationWorker 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:
API receives request → validates parameters
API submits task to pool → returns immediately (HTTP 200/202)
Worker thread picks up task → executes operation
Operation calls Gemini via MC2 → waits for AI response
Worker updates database → saves results
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:
Detects asset creation during mass import
Checks if the asset has a
brandguidelinechild link already assignedIf guideline link exists, submits automatic scoring
Uses the linked brand guideline for evaluation
Conditions for execution:
Brand Control must be configured
Asset must have a
brandguidelinechild relationship setAsset 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 scorebrandscoredate: Import timestampbrandscorereport: 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_imageis createdExecutes during the object creation workflow (post-save hook)
Execution logic:
Detects the creation of a
genai_temp_imageobjectExtracts the task ID from the object name (naming convention: task ID used as object name)
Retrieves the associated
Taskobject fromPromptServiceReads the
brandGuidelineIdfrom the task metadataSubmits 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_imagetagTask must exist in
PromptServicewith a validbrandGuidelineIdTemp image must have a valid binary file
Result:
Temp image fields automatically populated:
brandscore: Set to-1during scoring, then0-100or-2brandscoredate: Timestamp of scoring completionbrandscorereport: Full scoring report with metadatabrandguideline: Link to the brand guideline used
3.3 Trigger Behavior Summary
Trigger | When | Condition | Guideline Source | Typical Duration |
|---|---|---|---|---|
| GenAI image created | Object has | From task metadata | 10-35 seconds |
| Asset imported | Asset has | 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=-1immediately and update asynchronouslyBoth emit analytics events (
scoring_requested,scoring_done,scoring_error)
Disabling triggers:
Triggers automatically disabled if
BrandControlService.isConfigured()returns falseNo configuration option to disable individual triggers
To prevent automatic scoring: don't assign
brandguidelinerelationships or don't usegenai_temp_imagetag
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:
Load current scoring report
Retrieve current
brandcontrol_score_assetpromptCalculate current hash
Compare with stored hash
Response:
{
"isObsolete": false,
"reason": null,
"currentPromptVersion": 3,
"currentPromptHash": "a7f9c3e...",
"reportPromptVersion": 3,
"reportPromptHash": "a7f9c3e..."
}4.3 Obsolescence Reasons
Reason | Description |
|---|---|
| Hash mismatch between current and stored prompt |
| Asset never scored |
| Old array format (pre-metadata) |
| Corrupt JSON |
| No hash in metadata |
| 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? |
|---|---|---|---|
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