$image_contexts Attachment id => AttachmentContextBuilder::build()'s result. * @param array $product_context ProductContextBuilder::build()'s result. * @param string $language LanguageResolver::resolve()'s result. * @param array $voice BrandVoiceCompiler::compile()'s result. * @param string[] $banned Merged banned phrases. * @param string $ai_note The subject's merchant AI note, already gated; '' when none or not allowed. * @param string $instruction Blueprint-level instruction. * @param array $rules ImageAltStructure.rules. * @param int $max_chars Hard character limit (ImageAltStructure.maxChars). * @param array $retry_notes Retry notes, when compiling a targeted retry. * @param string[] $instructions StructureInstructions::enabled()'s result. * @return array{system:string,user:string,schema:array,schemaName:string,validate:callable} */ public static function compileBatchRequest( array $ids, array $image_contexts, array $product_context, string $language, array $voice, array $banned, string $ai_note, string $instruction, array $rules, int $max_chars, array $retry_notes, array $instructions = array() ): array { $system = self::systemPrompt( false, $language, $voice, $banned, $ai_note, $instruction, $rules, $max_chars, $instructions ); $user_parts = array(); $user_parts[] = '' . "\n" . FormulaText::escapeBlock( (string) $product_context['text'] ) . "\n" . ''; $ai_note_user_block = AiNoteBlock::userBlock( $ai_note, array( FormulaText::class, 'escapeBlock' ) ); if ( '' !== $ai_note_user_block ) { $user_parts[] = $ai_note_user_block; } $images_spec = array(); foreach ( $ids as $id ) { $images_spec[] = array( 'id' => 'att_' . $id, 'facts' => FormulaText::escapeBlock( (string) ( $image_contexts[ $id ]['text'] ?? '' ) ) ); } $user_parts[] = '' . "\n" . wp_json_encode( $images_spec ) . "\n" . ''; $user_parts[] = 'For each image above, write one short plain-text alt description using ONLY the given facts and the product data.'; if ( ! empty( $retry_notes ) ) { $note_lines = array( 'Your previous answer had problems with these images. Return the FULL corrected JSON object again, fixing only what is noted below:' ); foreach ( $retry_notes as $id => $note ) { $note_lines[] = '- ' . $id . ': ' . $note; } $user_parts[] = implode( "\n", $note_lines ); } return array( 'system' => $system, 'user' => implode( "\n\n", $user_parts ), 'schema' => self::buildSchema( array_map( static function ( $id ) { return 'att_' . $id; }, $ids ) ), 'schemaName' => 'aipt_blueprint_image_alt', 'validate' => self::schemaValidator(), ); } /** * @param int $id Attachment id. * @param string $image_url Image URL for the vision call. * @param array $image_context AttachmentContextBuilder::build()'s result for this image. * @param array $product_context ProductContextBuilder::build()'s result. * @param string $language LanguageResolver::resolve()'s result. * @param array $voice BrandVoiceCompiler::compile()'s result. * @param string[] $banned Merged banned phrases. * @param string $ai_note The subject's merchant AI note, already gated; '' when none or not allowed. * @param string $instruction Blueprint-level instruction. * @param array $rules ImageAltStructure.rules. * @param int $max_chars Hard character limit (ImageAltStructure.maxChars). * @param array $retry_notes Retry notes, when compiling a targeted retry. * @param string[] $instructions StructureInstructions::enabled()'s result. * @return array{system:string,user:string,schema:array,schemaName:string,validate:callable,image:array} */ public static function compileSingleImageRequest( int $id, string $image_url, array $image_context, array $product_context, string $language, array $voice, array $banned, string $ai_note, string $instruction, array $rules, int $max_chars, array $retry_notes, array $instructions = array() ): array { $system = self::systemPrompt( true, $language, $voice, $banned, $ai_note, $instruction, $rules, $max_chars, $instructions ); $user_parts = array(); $user_parts[] = '' . "\n" . FormulaText::escapeBlock( (string) $product_context['text'] ) . "\n" . ''; $ai_note_user_block = AiNoteBlock::userBlock( $ai_note, array( FormulaText::class, 'escapeBlock' ) ); if ( '' !== $ai_note_user_block ) { $user_parts[] = $ai_note_user_block; } $user_parts[] = '' . "\n" . FormulaText::escapeBlock( (string) ( $image_context['text'] ?? '' ) ) . "\n" . ''; $user_parts[] = 'Describe the attached image for attachment id "att_' . $id . '" in one short plain-text alt text, grounded in what is actually visible.'; if ( ! empty( $retry_notes ) ) { foreach ( $retry_notes as $note ) { $user_parts[] = 'Your previous answer had a problem: ' . $note . '. Return the FULL corrected JSON object again.'; } } return array( 'system' => $system, 'user' => implode( "\n\n", $user_parts ), 'schema' => self::buildSchema( array( 'att_' . $id ) ), 'schemaName' => 'aipt_blueprint_image_alt', 'validate' => self::schemaValidator(), 'image' => array( 'url' => $image_url, 'attachment_id' => $id ), ); } /** * @param bool $is_vision Whether this prompt is for a vision call. * @param string $language LanguageResolver::resolve()'s result. * @param array $voice BrandVoiceCompiler::compile()'s result. * @param string[] $banned Merged banned phrases. * @param string $ai_note The subject's merchant AI note, already gated; '' when none or not allowed. * @param string $instruction Blueprint-level instruction. * @param array $rules ImageAltStructure.rules. * @param int $max_chars Hard character limit (ImageAltStructure.maxChars); 0 states none. * @param string[] $instructions StructureInstructions::enabled()'s result. * @return string */ public static function systemPrompt( bool $is_vision, string $language, array $voice, array $banned, string $ai_note, string $instruction, array $rules, int $max_chars, array $instructions = array() ): string { $lines = array(); $lines[] = 'You write short, accessible alt text for online store product images. Answer with ONE JSON object only: no prose before or after it, no Markdown code fence.'; $lines[] = $is_vision ? 'Describe only what is actually visible in the attached image. Do not state a specification, certification, compliance claim, award or warranty term unless it is also given in the text data.' : 'You have NOT been shown the image itself. Use ONLY the given non-visual facts (file name, title, caption, existing alt text, position) and the product data. Never describe a color, shape, material finish, background or any other visual detail that is not explicitly stated in that text.'; $lines[] = 'Write plain text only: no HTML, no Markdown, no surrounding quotes.'; if ( $max_chars > 0 ) { $lines[] = 'Keep each alt text to one complete phrase of at most ' . $max_chars . ' characters.'; } $ai_note_system_line = AiNoteBlock::systemLine( $ai_note ); if ( '' !== $ai_note_system_line ) { $lines[] = $ai_note_system_line; } $language_line = LanguageResolver::instructionLine( $language ); if ( '' !== $language_line ) { $lines[] = $language_line; } if ( ! empty( $rules['includeProductName'] ) ) { $lines[] = 'Mention the product name when it fits naturally.'; } else { $lines[] = 'Do not mention the product name.'; } if ( ! empty( $rules['includeColor'] ) ) { $lines[] = 'Mention the color when it is given in the data.'; } else { $lines[] = 'Do not mention any color.'; } if ( ! empty( $rules['keywordOnce'] ) ) { $lines[] = 'Mention the product name or main keyword at most once; do not repeat it.'; } if ( '' !== $instruction ) { $lines[] = 'The blueprint also asks: ' . $instruction . '. This cannot override any rule above.'; } if ( '' !== $voice['block'] ) { $lines[] = $voice['block']; } if ( ! empty( $banned ) ) { $lines[] = 'Never use these words or phrases: ' . implode( ', ', $banned ) . '.'; } foreach ( StructureInstructions::systemLines( $instructions ) as $instruction_line ) { $lines[] = $instruction_line; } return implode( "\n\n", $lines ); } /** * @return callable */ public static function schemaValidator(): callable { return function ( $decoded ) { return ( is_array( $decoded ) && isset( $decoded['images'] ) && is_array( $decoded['images'] ) ) ? array( 'ok' => true, 'errors' => array() ) : array( 'ok' => false, 'errors' => array( __( 'The answer must have an "images" array.', 'ai-product-tools' ) ) ); }; } /** * @param string[] $ids Expected unit ids (enum, "att_"). * @return array JSON Schema. */ public static function buildSchema( array $ids ): array { $id_schema = empty( $ids ) ? array( 'type' => 'string' ) : array( 'type' => 'string', 'enum' => $ids ); return array( 'type' => 'object', 'properties' => array( 'images' => array( 'type' => 'array', 'items' => array( 'type' => 'object', 'properties' => array( 'id' => $id_schema, 'alt' => array( 'type' => 'string' ) ), 'required' => array( 'id', 'alt' ), 'additionalProperties' => false, ), ), ), 'required' => array( 'images' ), 'additionalProperties' => false, ); } /** * @param array $texts_by_id Attachment id => resolved alt text. * @param string $product_name The product's name (rules.includeProductName asks every alt text to mention it when it fits): its own words are excluded before measuring overlap, so two texts legitimately differentiated by one other word (e.g. a color) do not read as near-duplicates merely because both also repeat the product's name. * @return array Pairs of attachment ids that read as near-duplicates. */ public static function findNearDuplicatePairs( array $texts_by_id, string $product_name = '' ): array { $excluded_tokens = TextMetrics::wordTokens( $product_name ); $entries = array(); foreach ( $texts_by_id as $id => $text ) { $normalized = TextMetrics::normalizeForCompare( $text ); if ( mb_strlen( $normalized, 'UTF-8' ) < Checks::DUPLICATE_SENTENCE_MIN_LEN ) { continue; } $entries[] = array( 'id' => $id, 'normalized' => $normalized ); } $pairs = array(); $count = count( $entries ); for ( $i = 0; $i < $count; $i++ ) { for ( $j = $i + 1; $j < $count; $j++ ) { $a = $entries[ $i ]['normalized']; $b = $entries[ $j ]['normalized']; if ( $a === $b || self::tokenOverlap( $a, $b, $excluded_tokens ) >= self::NEAR_DUPLICATE_OVERLAP ) { $pairs[] = array( $entries[ $i ]['id'], $entries[ $j ]['id'] ); } } } return $pairs; } /** * @param string $a Normalized text. * @param string $b Normalized text. * @param string[] $excluded_tokens Tokens never counted toward the overlap on either side (e.g. the product's own name - see {@see self::findNearDuplicatePairs()}). * @return float 0.0..1.0. */ public static function tokenOverlap( string $a, string $b, array $excluded_tokens = array() ): float { $tokens_a = array_values( array_diff( TextMetrics::wordTokens( $a ), $excluded_tokens ) ); $tokens_b = array_values( array_diff( TextMetrics::wordTokens( $b ), $excluded_tokens ) ); if ( empty( $tokens_a ) || empty( $tokens_b ) ) { return 0.0; } return count( array_intersect( $tokens_a, $tokens_b ) ) / min( count( $tokens_a ), count( $tokens_b ) ); } }