validator = new OutputValidator(); $this->callRunner = new FormulaCallRunner(); $this->specBuilder = new PromptSpecBuilder(); $this->fields = new FieldCatalog(); } /** * @inheritDoc */ public function generate( array $ctx, StructuredCallerInterface $caller ): array { return $this->run( $ctx, $caller, null, null ); } /** * @inheritDoc */ public function regenerateUnit( array $ctx, array $previous, string $unit_id, StructuredCallerInterface $caller ): array { $images = (array) ( $ctx['images'] ?? array() ); $found = false; foreach ( $images as $image ) { if ( 'att_' . (int) $image['attachmentId'] === $unit_id ) { $found = true; break; } } if ( ! $found ) { return $previous; } return $this->run( $ctx, $caller, $unit_id, $previous ); } /** * @param array $ctx Execution context. * @param StructuredCallerInterface $caller Structured AI caller. * @param string|null $only_unit_id Set only when regenerating one image. * @param array|null $previous regenerateUnit()'s previous slice. * @return array{units:array,outputs:array,checks:array,conflicts:array,findings:array,sourcesUsed:array,eligibility:array,usage:array,providerError:array|null} */ private function run( array $ctx, StructuredCallerInterface $caller, ?string $only_unit_id, ?array $previous ): array { $definition = $ctx['definition']; $structure = $definition['structure']; $images = (array) ( $ctx['images'] ?? array() ); $is_vision = 'vision' === ( $structure['context'] ?? 'product_data' ); $max_chars = (int) ( $structure['maxChars'] ?? 125 ); $rules = isset( $structure['rules'] ) && is_array( $structure['rules'] ) ? $structure['rules'] : array(); $instruction = (string) ( $structure['instruction'] ?? '' ); if ( '' === $instruction ) { $instruction = (string) ( $ctx['runOptions']['additionalInstruction'] ?? '' ); } $product = $ctx['product']; $allowed_fields = isset( $definition['sources']['productFields'] ) ? array_values( (array) $definition['sources']['productFields'] ) : array(); $product_context = ( new ProductContextBuilder( $this->fields ) )->build( $product, $allowed_fields ); $product_id = method_exists( $product, 'get_id' ) ? (int) $product->get_id() : 0; $keyword = trim( (string) $product->get_name() ); $has_featured_image = (int) $product->get_image_id() > 0; $image_contexts = array(); foreach ( $images as $image ) { $attachment_id = (int) $image['attachmentId']; $image_contexts[ $attachment_id ] = ( new AttachmentContextBuilder( $this->fields ) )->build( $attachment_id, $product_id, (int) ( $image['position'] ?? 0 ), array_column( $this->fields->forScope( 'image' ), 'ref' ) ); } $usage = $this->callRunner->emptyUsage(); $findings = array(); $banned = $this->specBuilder->mergedBanned( $ctx, $definition ); $voice = $this->specBuilder->compileVoice( $ctx, array() ); $language = LanguageResolver::resolve( $ctx, $definition ); $ai_note = (string) ( $ctx['aiNote'] ?? '' ); $instructions = StructureInstructions::enabled( $definition ); list( $resolved, $wanted_ids ) = $this->resolveReusedFromPrevious( $images, $only_unit_id, $previous ); if ( ! empty( $wanted_ids ) ) { if ( $is_vision ) { $this->runVisionCalls( $caller, $ctx, $definition, $wanted_ids, $images, $image_contexts, $product_context, $language, $voice, $banned, $ai_note, $instruction, $instructions, $rules, $max_chars, $keyword, $resolved, $usage, $findings ); } else { $this->runProductDataCall( $caller, $ctx, $definition, $wanted_ids, $image_contexts, $product_context, $language, $voice, $banned, $ai_note, $instruction, $instructions, $rules, $max_chars, $keyword, $resolved, $usage, $findings ); } } $this->applyVaryAcrossImages( $caller, $ctx, $is_vision, $images, $image_contexts, $product_context, $language, $voice, $banned, $ai_note, $instruction, $instructions, $rules, $max_chars, $keyword, $resolved, $usage, $findings, $only_unit_id ); return $this->assemble( $images, $has_featured_image, $resolved, $is_vision, $max_chars, $rules, $banned, $keyword, $usage, $findings, $only_unit_id, $previous ); } /** * @param array[] $images ctx['images']. * @param string|null $only_unit_id Set only when regenerating one image. * @param array|null $previous regenerateUnit()'s previous slice. * @return array{0:array,1:int[]} [resolved by attachment id, attachment ids still wanting a fresh call]. */ private function resolveReusedFromPrevious( array $images, ?string $only_unit_id, ?array $previous ): array { $resolved = array(); $wanted = array(); foreach ( $images as $image ) { $attachment_id = (int) $image['attachmentId']; $unit_id = 'att_' . $attachment_id; if ( null !== $only_unit_id && $unit_id !== $only_unit_id && null !== $previous ) { $prev_unit = $this->findUnit( (array) $previous['units'], $unit_id ); if ( null !== $prev_unit ) { $resolved[ $attachment_id ] = array( 'status' => $prev_unit['status'], 'reason' => $prev_unit['reason'], 'text' => $prev_unit['text'], 'isVision' => $this->wasVisionReviewed( $prev_unit ), 'requested' => (bool) ( $prev_unit['requestedFromProvider'] ?? true ) ); continue; } } $wanted[] = $attachment_id; } return array( $resolved, $wanted ); } /** * Whether a previously rendered unit carried the vision-review finding * (its own findings are not echoed onto the unit; this only has access * to the unit itself, so a reused unit's mode is read back from the * (unit-local) flag this generator itself writes - see assemble()). * * @param array $prev_unit Previously rendered unit. * @return bool */ private function wasVisionReviewed( array $prev_unit ): bool { return 'image' === ( $prev_unit['kind'] ?? '' ) && 'vision' === ( $prev_unit['mode'] ?? '' ); } /** * ONE shared structured call for every wanted image's alt text * (`product_data` context), with at most one targeted retry. * * @param StructuredCallerInterface $caller Structured AI caller. * @param array $ctx Execution context. * @param array $definition Normalized BlueprintDefinition. * @param int[] $wanted_ids Attachment ids needing a fresh call. * @param array $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 string[] $instructions StructureInstructions::enabled()'s result. * @param array $rules ImageAltStructure.rules. * @param int $max_chars Hard character limit. * @param string $keyword The product name, for the keywordOnce usage check. * @param array &$resolved Resolved-by-attachment-id accumulator, updated in place. * @param array &$usage Usage accumulator, updated in place. * @param array &$findings Findings accumulator, updated in place. * @return void */ private function runProductDataCall( StructuredCallerInterface $caller, array $ctx, array $definition, array $wanted_ids, array $image_contexts, array $product_context, string $language, array $voice, array $banned, string $ai_note, string $instruction, array $instructions, array $rules, int $max_chars, string $keyword, array &$resolved, array &$usage, array &$findings ): void { $deadline = isset( $ctx['deadline'] ) ? (float) $ctx['deadline'] : ( microtime( true ) + 60.0 ); $budget = isset( $ctx['maxCalls'] ) ? max( 1, (int) $ctx['maxCalls'] ) : 3; $compiled = ImageAltPrompting::compileBatchRequest( $wanted_ids, $image_contexts, $product_context, $language, $voice, $banned, $ai_note, $instruction, $rules, $max_chars, array(), $instructions ); $first = $this->callRunner->call( $caller, $ctx, $compiled, min( 2, $budget ), $deadline ); $this->callRunner->mergeUsage( $usage, $first ); $calls_used = $first['calls']; $by_id = array(); if ( $first['ok'] ) { $match = $this->validator->matchUnits( $first['decoded']['images'] ?? array(), array_map( static function ( $id ) { return 'att_' . $id; }, $wanted_ids ) ); $findings = array_merge( $findings, $match['findings'] ); foreach ( $match['byId'] as $unit_id => $raw ) { $by_id[ (int) str_replace( 'att_', '', $unit_id ) ] = $raw; } } else { $findings = ProviderFailureSupport::recordTerminalFailure( $findings, (array) ( $first['error'] ?? array() ) ); } $retry_ids = $this->idsNeedingRetry( $wanted_ids, $by_id, $banned ); $retry_result = null; if ( ! empty( $retry_ids ) && $this->callRunner->canRetry( $budget, $calls_used, $deadline ) ) { $retry_notes = array_fill_keys( array_map( static function ( $id ) { return 'att_' . $id; }, $retry_ids ), __( 'missing, empty, or still used a banned phrase', 'ai-product-tools' ) ); $retry_compiled = ImageAltPrompting::compileBatchRequest( $retry_ids, $image_contexts, $product_context, $language, $voice, $banned, $ai_note, $instruction, $rules, $max_chars, $retry_notes, $instructions ); $retry_result = $this->callRunner->call( $caller, $ctx, $retry_compiled, 1, $deadline, $first['provider'], $first['model'] ); $this->callRunner->mergeUsage( $usage, $retry_result ); if ( $retry_result['ok'] ) { $retry_match = $this->validator->matchUnits( $retry_result['decoded']['images'] ?? array(), array_map( static function ( $id ) { return 'att_' . $id; }, $retry_ids ) ); $findings = array_merge( $findings, $retry_match['findings'] ); foreach ( $retry_match['byId'] as $unit_id => $raw ) { $by_id[ (int) str_replace( 'att_', '', $unit_id ) ] = $raw; } } else { $findings = ProviderFailureSupport::recordTerminalFailure( $findings, (array) ( $retry_result['error'] ?? array() ) ); } } $to_unit_ids = static function ( array $attachment_ids ) { return array_map( static function ( $id ) { return 'att_' . $id; }, $attachment_ids ); }; $failure_messages = ProviderFailureSupport::unitFailureMessages( $first, $to_unit_ids( $wanted_ids ), $retry_result, $to_unit_ids( $retry_ids ) ); foreach ( $wanted_ids as $attachment_id ) { $raw = $by_id[ $attachment_id ] ?? null; $unit_id = 'att_' . $attachment_id; $resolved[ $attachment_id ] = $this->resolveImage( $unit_id, null !== $raw ? (string) ( $raw['alt'] ?? '' ) : null, false, $rules, $max_chars, $keyword, $definition, $banned, $findings, $failure_messages[ $unit_id ] ?? null ); } } /** * One structured call PER wanted image (`vision` context): the first * call always happens for every wanted image regardless of the shared * budget (see class docblock); only the per-image retry that follows is * budget-gated. * * @param StructuredCallerInterface $caller Structured AI caller. * @param array $ctx Execution context. * @param array $definition Normalized BlueprintDefinition. * @param int[] $wanted_ids Attachment ids needing a fresh call. * @param array[] $images ctx['images']. * @param array $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 string[] $instructions StructureInstructions::enabled()'s result. * @param array $rules ImageAltStructure.rules. * @param int $max_chars Hard character limit. * @param string $keyword The product name, for the keywordOnce usage check. * @param array &$resolved Resolved-by-attachment-id accumulator, updated in place. * @param array &$usage Usage accumulator, updated in place. * @param array &$findings Findings accumulator, updated in place. * @return void */ private function runVisionCalls( StructuredCallerInterface $caller, array $ctx, array $definition, array $wanted_ids, array $images, array $image_contexts, array $product_context, string $language, array $voice, array $banned, string $ai_note, string $instruction, array $instructions, array $rules, int $max_chars, string $keyword, array &$resolved, array &$usage, array &$findings ): void { $deadline = isset( $ctx['deadline'] ) ? (float) $ctx['deadline'] : ( microtime( true ) + 60.0 ); $budget = isset( $ctx['maxCalls'] ) ? max( 1, (int) $ctx['maxCalls'] ) : 3; $url_by_id = array(); foreach ( $wanted_ids as $attachment_id ) { $url = (string) wp_get_attachment_url( $attachment_id ); $url_by_id[ $attachment_id ] = $url; if ( '' === $url ) { $findings[] = $this->validator->finding( 'aipt_blueprint_provider_error', 'review', __( 'Could not resolve this image file.', 'ai-product-tools' ), 'att_' . $attachment_id ); $resolved[ $attachment_id ] = array( 'status' => 'needs_review', 'reason' => __( 'Could not resolve this image file.', 'ai-product-tools' ), 'text' => '', 'isVision' => true, 'requested' => false ); continue; } $compiled = ImageAltPrompting::compileSingleImageRequest( $attachment_id, $url, $image_contexts[ $attachment_id ] ?? array(), $product_context, $language, $voice, $banned, $ai_note, $instruction, $rules, $max_chars, array(), $instructions ); $result = $this->callRunner->call( $caller, $ctx, $compiled, 1, $deadline ); $this->callRunner->mergeUsage( $usage, $result ); $raw = null; if ( $result['ok'] ) { $match = $this->validator->matchUnits( $result['decoded']['images'] ?? array(), array( 'att_' . $attachment_id ) ); $findings = array_merge( $findings, $match['findings'] ); $raw = $match['byId'][ 'att_' . $attachment_id ] ?? null; } else { $findings = ProviderFailureSupport::recordTerminalFailure( $findings, (array) ( $result['error'] ?? array() ), 'att_' . $attachment_id ); } $unit_id = 'att_' . $attachment_id; $needs_retry = $this->idsNeedingRetry( array( $attachment_id ), array( $attachment_id => $raw ), $banned ); $retry_result = null; if ( ! empty( $needs_retry ) && $this->callRunner->canRetry( $budget, $usage['aiCalls'], $deadline ) ) { $retry_compiled = ImageAltPrompting::compileSingleImageRequest( $attachment_id, $url, $image_contexts[ $attachment_id ] ?? array(), $product_context, $language, $voice, $banned, $ai_note, $instruction, $rules, $max_chars, array( $unit_id => __( 'missing, empty, or still used a banned phrase', 'ai-product-tools' ) ), $instructions ); $retry_result = $this->callRunner->call( $caller, $ctx, $retry_compiled, 1, $deadline, $result['provider'] ?? '', $result['model'] ?? '' ); $this->callRunner->mergeUsage( $usage, $retry_result ); if ( $retry_result['ok'] ) { $retry_match = $this->validator->matchUnits( $retry_result['decoded']['images'] ?? array(), array( $unit_id ) ); $findings = array_merge( $findings, $retry_match['findings'] ); $raw = $retry_match['byId'][ $unit_id ] ?? $raw; } else { $findings = ProviderFailureSupport::recordTerminalFailure( $findings, (array) ( $retry_result['error'] ?? array() ), $unit_id ); } } $failure_message = ProviderFailureSupport::unitFailureMessages( $result, array( $unit_id ), $retry_result, array( $unit_id ) )[ $unit_id ] ?? null; $resolved[ $attachment_id ] = $this->resolveImage( $unit_id, null !== $raw ? (string) ( $raw['alt'] ?? '' ) : null, true, $rules, $max_chars, $keyword, $definition, $banned, $findings, $failure_message ); } unset( $images, $url_by_id ); } /** * @param int[] $ids Attachment ids checked. * @param array $by_id Matched raw payloads (or null), keyed by attachment id. * @param string[] $banned Merged banned phrases. * @return int[] */ private function idsNeedingRetry( array $ids, array $by_id, array $banned ): array { $retry = array(); foreach ( $ids as $id ) { $raw = $by_id[ $id ] ?? null; if ( null === $raw || ! is_array( $raw ) || ! isset( $raw['alt'] ) ) { $retry[] = $id; continue; } $clean = FormulaText::cleanOne( $this->validator, (string) $raw['alt'] ); if ( ! $clean['ok'] || ! empty( $this->validator->findBannedPhrases( $clean['text'], $banned ) ) ) { $retry[] = $id; } } return $retry; } /** * Apply the deterministic `noImageOf` strip, the `maxChars` word * -boundary trim, and the too-short-after-trim review flag to one * image's raw AI answer (or resolve a missing/failed answer through * `rules.requiredFailure`, same precedence every other formula * generator uses). * * @param string $unit_id Unit id ("att_"). * @param string|null $raw_text Raw AI answer, or null when missing. * @param bool $is_vision Whether this image was described by a vision call. * @param array $rules ImageAltStructure.rules. * @param int $max_chars Hard character limit. * @param string $keyword The product name, for the keywordOnce usage check. * @param array $definition Normalized BlueprintDefinition. * @param string[] $banned Merged banned phrases. * @param array &$findings Findings accumulator, updated in place. * @param string|null $provider_message The classified provider message responsible for this image still being missing, when `$raw_text` is null because its own call failed; null otherwise (see ProviderFailureSupport::unitFailureMessages()). * @return array{status:string,reason:string,text:string,isVision:bool} */ private function resolveImage( string $unit_id, ?string $raw_text, bool $is_vision, array $rules, int $max_chars, string $keyword, array $definition, array $banned, array &$findings, ?string $provider_message = null ): array { $clean = null !== $raw_text ? FormulaText::cleanOne( $this->validator, $raw_text ) : array( 'ok' => false, 'text' => '' ); if ( ! $clean['ok'] ) { $message = ( null === $raw_text && null !== $provider_message ) ? $provider_message : __( 'The AI did not return alt text for this image.', 'ai-product-tools' ); $required_failure = (string) ( $definition['rules']['requiredFailure'] ?? 'review' ); if ( 'partial' === $required_failure ) { $findings[] = $this->validator->finding( 'unit_failed_dropped', 'warning', $message, $unit_id ); return array( 'status' => 'skipped_missing_data', 'reason' => $message, 'text' => '', 'isVision' => $is_vision, 'requested' => true ); } $findings[] = $this->validator->finding( 'unit_failed', 'review', $message, $unit_id ); return array( 'status' => 'needs_review', 'reason' => $message, 'text' => '', 'isVision' => $is_vision, 'requested' => true ); } $text = $clean['text']; if ( ! empty( $rules['noImageOf'] ) ) { $stripped = preg_replace( '/^(?:image|picture|photo)\s+of\s+/iu', '', $text, 1, $removed ); if ( $removed > 0 && null !== $stripped ) { $findings[] = $this->validator->finding( 'image_of_opening_removed', 'info', __( 'Removed a leading "image of" phrase.', 'ai-product-tools' ), $unit_id ); $text = $stripped; } } if ( ! empty( $rules['keywordOnce'] ) && '' !== $keyword && SeoMetaAssembly::countOccurrences( $text, $keyword ) > 1 ) { $findings[] = $this->validator->finding( 'keyword_used_multiple_times', 'warning', __( 'This alt text mentions the product name more than once.', 'ai-product-tools' ), $unit_id ); } $still_banned = $this->validator->findBannedPhrases( $text, $banned ); if ( ! empty( $still_banned ) ) { /* translators: %s: comma-separated banned phrases still present after the retry. */ $findings[] = $this->validator->finding( 'banned_phrase', 'review', sprintf( __( 'This alt text still uses a banned phrase: %s.', 'ai-product-tools' ), implode( ', ', $still_banned ) ), $unit_id ); } $trim = FormulaText::trimToWordBoundary( $text, $max_chars ); if ( $trim['trimmed'] ) { $findings[] = $this->validator->finding( 'trimmed_at_word', 'warning', __( 'Shortened to fit the character limit.', 'ai-product-tools' ), $unit_id ); $text = $trim['text']; } if ( $is_vision ) { $findings[] = $this->validator->finding( 'vision_observed', 'review', __( 'AI-observed, check before applying.', 'ai-product-tools' ), $unit_id ); } $status = mb_strlen( $text, 'UTF-8' ) < self::MIN_USEFUL_LENGTH ? 'needs_review' : 'included'; $reason = ''; if ( 'needs_review' === $status ) { $reason = __( 'The alt text is very short; review before applying.', 'ai-product-tools' ); $findings[] = $this->validator->finding( 'alt_too_short', 'review', $reason, $unit_id ); } return array( 'status' => $status, 'reason' => $reason, 'text' => $text, 'isVision' => $is_vision, 'requested' => true ); } /** * `varyAcrossImages`: detect near-duplicate alt texts across every * resolved image, retry the flagged images once (one shared call for * `product_data`, one call per flagged image for `vision`), then warn * for any pair still alike afterward. * * @param StructuredCallerInterface $caller Structured AI caller. * @param array $ctx Execution context. * @param bool $is_vision Whether this generation uses vision. * @param array[] $images ctx['images']. * @param array $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 string[] $instructions StructureInstructions::enabled()'s result. * @param array $rules ImageAltStructure.rules. * @param int $max_chars Hard character limit. * @param string $keyword The product name, for the keywordOnce usage check. * @param array &$resolved Resolved-by-attachment-id, updated in place. * @param array &$usage Usage accumulator, updated in place. * @param array &$findings Findings accumulator, updated in place. * @param string|null $only_unit_id Set only when regenerating one image: restricts which * flagged ids get REWRITTEN to this one (pair detection * below still runs over every resolved image). * @return void */ private function applyVaryAcrossImages( StructuredCallerInterface $caller, array $ctx, bool $is_vision, array $images, array $image_contexts, array $product_context, string $language, array $voice, array $banned, string $ai_note, string $instruction, array $instructions, array $rules, int $max_chars, string $keyword, array &$resolved, array &$usage, array &$findings, ?string $only_unit_id ): void { if ( empty( $rules['varyAcrossImages'] ) ) { return; } $texts = array(); foreach ( $resolved as $attachment_id => $entry ) { if ( in_array( $entry['status'], array( 'included', 'needs_review' ), true ) && '' !== $entry['text'] ) { $texts[ $attachment_id ] = $entry['text']; } } $pairs = ImageAltPrompting::findNearDuplicatePairs( $texts, $keyword ); if ( empty( $pairs ) ) { return; } $flagged_ids = array_values( array_unique( array_merge( ...array_map( 'array_values', $pairs ) ) ) ); if ( null !== $only_unit_id ) { $flagged_ids = array_values( array_filter( $flagged_ids, static function ( $attachment_id ) use ( $only_unit_id ) { return 'att_' . $attachment_id === $only_unit_id; } ) ); } $deadline = isset( $ctx['deadline'] ) ? (float) $ctx['deadline'] : ( microtime( true ) + 60.0 ); $budget = isset( $ctx['maxCalls'] ) ? max( 1, (int) $ctx['maxCalls'] ) : 3; if ( ! empty( $flagged_ids ) && $this->callRunner->canRetry( $budget, $usage['aiCalls'], $deadline ) ) { $definition = $ctx['definition']; if ( $is_vision ) { foreach ( $flagged_ids as $attachment_id ) { if ( ! $this->callRunner->canRetry( $budget, $usage['aiCalls'], $deadline ) ) { break; } $url = (string) wp_get_attachment_url( $attachment_id ); if ( '' === $url ) { continue; } $note = array( 'att_' . $attachment_id => __( 'too similar to another image\'s alt text; vary the wording', 'ai-product-tools' ) ); $compiled = ImageAltPrompting::compileSingleImageRequest( $attachment_id, $url, $image_contexts[ $attachment_id ] ?? array(), $product_context, $language, $voice, $banned, $ai_note, $instruction, $rules, $max_chars, $note, $instructions ); $result = $this->callRunner->call( $caller, $ctx, $compiled, 1, $deadline ); $this->callRunner->mergeUsage( $usage, $result ); if ( $result['ok'] ) { $match = $this->validator->matchUnits( $result['decoded']['images'] ?? array(), array( 'att_' . $attachment_id ) ); $raw = $match['byId'][ 'att_' . $attachment_id ] ?? null; if ( null !== $raw ) { $findings = $this->clearUnitFindings( $findings, 'att_' . $attachment_id ); $resolved[ $attachment_id ] = $this->resolveImage( 'att_' . $attachment_id, (string) ( $raw['alt'] ?? '' ), true, $rules, $max_chars, $keyword, $definition, $banned, $findings ); } } else { $findings = ProviderFailureSupport::recordTerminalFailure( $findings, (array) ( $result['error'] ?? array() ), 'att_' . $attachment_id ); } } } else { $notes = array_fill_keys( array_map( static function ( $id ) { return 'att_' . $id; }, $flagged_ids ), __( 'too similar to another image\'s alt text; vary the wording', 'ai-product-tools' ) ); $compiled = ImageAltPrompting::compileBatchRequest( $flagged_ids, $image_contexts, $product_context, $language, $voice, $banned, $ai_note, $instruction, $rules, $max_chars, $notes, $instructions ); $result = $this->callRunner->call( $caller, $ctx, $compiled, 1, $deadline ); $this->callRunner->mergeUsage( $usage, $result ); if ( $result['ok'] ) { $match = $this->validator->matchUnits( $result['decoded']['images'] ?? array(), array_map( static function ( $id ) { return 'att_' . $id; }, $flagged_ids ) ); foreach ( $flagged_ids as $attachment_id ) { $raw = $match['byId'][ 'att_' . $attachment_id ] ?? null; if ( null !== $raw ) { $findings = $this->clearUnitFindings( $findings, 'att_' . $attachment_id ); $resolved[ $attachment_id ] = $this->resolveImage( 'att_' . $attachment_id, (string) ( $raw['alt'] ?? '' ), false, $rules, $max_chars, $keyword, $definition, $banned, $findings ); } } } else { $findings = ProviderFailureSupport::recordTerminalFailure( $findings, (array) ( $result['error'] ?? array() ) ); } } } $texts_after = array(); foreach ( $resolved as $attachment_id => $entry ) { if ( in_array( $entry['status'], array( 'included', 'needs_review' ), true ) && '' !== $entry['text'] ) { $texts_after[ $attachment_id ] = $entry['text']; } } foreach ( ImageAltPrompting::findNearDuplicatePairs( $texts_after, $keyword ) as $pair ) { /* translators: %1$s: the first image's unit id. %2$s: the second image's unit id. */ $findings[] = $this->validator->finding( 'vary_across_images', 'warning', sprintf( __( 'This image\'s alt text reads very similarly to "%1$s" and "%2$s".', 'ai-product-tools' ), 'att_' . $pair[0], 'att_' . $pair[1] ), 'att_' . $pair[0] ); } unset( $images ); } /** * Drop a unit's own prior findings before {@see self::resolveImage()} * resolves it again (`applyVaryAcrossImages()`'s rewrite), so a * `banned_phrase`/`alt_too_short` review finding from the pre-retry text * cannot outlive a now-clean answer, and `trimmed_at_word`/`vision_observed` * cannot be counted twice for the same image. A provider-failure * finding for this unit is kept: it is identified by its * `data.providerFailure` marker (the one {@see ProviderFailureSupport} * itself sets), never by comparing finding codes, because * `recordTerminalFailure()` normally reuses the ORIGINAL error's own * code rather than a fixed provider-error string. * * @param array $findings Findings accumulated so far. * @param string $unit_id Unit id ("att_") about to be re-resolved. * @return array Findings with that unit's own non-provider-failure findings removed. */ private function clearUnitFindings( array $findings, string $unit_id ): array { return array_values( array_filter( $findings, static function ( $finding ) use ( $unit_id ) { return ( $finding['unitId'] ?? '' ) !== $unit_id || ! empty( $finding['data']['providerFailure'] ); } ) ); } /** * Build units/checks and assemble the generator-specific * GenerationResult slice. * * @param array[] $images ctx['images']. * @param bool $has_featured_image Whether the parent product has a featured image (see {@see self::galleryLabel()}). * @param array $resolved Final resolved-by-attachment-id. * @param bool $is_vision Whether this generation uses vision. * @param int $max_chars Hard character limit. * @param array $rules ImageAltStructure.rules. * @param string[] $banned Merged banned phrases. * @param string $keyword The product name, for the keywordOnce usage check. * @param array $usage Usage accumulator. * @param array $findings Findings accumulated during generation. * @param string|null $only_unit_id Set only when regenerating one image. * @param array|null $previous regenerateUnit()'s previous slice, when regenerating. * @return array{units:array,outputs:array,checks:array,conflicts:array,findings:array,sourcesUsed:array,eligibility:array,usage:array,providerError:array|null} */ private function assemble( array $images, bool $has_featured_image, array $resolved, bool $is_vision, int $max_chars, array $rules, array $banned, string $keyword, array $usage, array $findings, ?string $only_unit_id, ?array $previous = null ): array { $units = array(); $alt = array(); $existing_alt = array(); $all_text_parts = array(); $previous_baseline = is_array( $previous['outputs']['existingAlt'] ?? null ) ? $previous['outputs']['existingAlt'] : array(); foreach ( $images as $image ) { $attachment_id = (int) $image['attachmentId']; $unit_id = 'att_' . $attachment_id; $entry = $resolved[ $attachment_id ] ?? array( 'status' => 'failed', 'reason' => '', 'text' => '', 'isVision' => $is_vision, 'requested' => true ); if ( in_array( $entry['status'], array( 'included', 'needs_review' ), true ) && '' !== $entry['text'] ) { $reused = null !== $only_unit_id && $unit_id !== $only_unit_id && array_key_exists( (string) $attachment_id, $previous_baseline ); $alt[ (string) $attachment_id ] = $entry['text']; $existing_alt[ (string) $attachment_id ] = $reused ? (string) $previous_baseline[ (string) $attachment_id ] : ( function_exists( 'get_post_meta' ) ? (string) get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ) : '' ); $all_text_parts[] = $entry['text']; } $units[] = array( 'id' => $unit_id, 'kind' => 'image', 'type' => ! empty( $image['isFeatured'] ) ? 'featured_image' : 'gallery_image', 'name' => ! empty( $image['isFeatured'] ) ? __( 'Featured image', 'ai-product-tools' ) : $this->galleryLabel( $image, $has_featured_image ), 'mode' => $entry['isVision'] ? 'vision' : 'ai', 'format' => 'paragraph', 'status' => $entry['status'], 'reason' => $entry['reason'], 'heading' => '', 'html' => '', 'text' => $entry['text'], 'items' => array(), 'rows' => array(), 'wordCount' => TextMetrics::wordCount( $entry['text'] ), 'charCount' => TextMetrics::charCount( $entry['text'] ), 'itemCount' => 0, 'missingFields' => array(), 'usedFallback' => false, 'regenerated' => null !== $only_unit_id && $unit_id === $only_unit_id, 'sourceRefs' => $entry['isVision'] ? array() : array( 'product' ), 'findings' => array(), 'requestedFromProvider' => (bool) ( $entry['requested'] ?? true ), ); } $checks = array(); $trimmed_count = count( array_filter( $findings, static function ( $f ) { return 'trimmed_at_word' === ( $f['code'] ?? '' ); } ) ); $checks[] = FormulaChecks::row( 'length', __( 'Length', 'ai-product-tools' ), 0 === $trimmed_count ? 'pass' : 'warn', 0 === $trimmed_count /* translators: %d: hard character limit. */ ? sprintf( __( 'All images are at or under %d characters.', 'ai-product-tools' ), $max_chars ) /* translators: %1$d: number of images shortened. %2$d: hard character limit. */ : sprintf( _n( '%1$d image was shortened to fit %2$d characters.', '%1$d images were shortened to fit %2$d characters.', $trimmed_count, 'ai-product-tools' ), $trimmed_count, $max_chars ) ); if ( ! empty( $rules['noImageOf'] ) ) { $image_of_count = count( array_filter( $findings, static function ( $f ) { return 'image_of_opening_removed' === ( $f['code'] ?? '' ); } ) ); } else { $image_of_count = count( array_filter( $all_text_parts, static function ( $text ) { return 1 === preg_match( '/^(?:image|picture|photo)\s+of\s+/iu', $text ); } ) ); } $checks[] = FormulaChecks::row( 'image_of_openings', __( '"Image of" openings', 'ai-product-tools' ), 'pass', /* translators: %d: number of leading "image of" phrases found. */ sprintf( __( '%d found.', 'ai-product-tools' ), $image_of_count ) ); $checks[] = $this->keywordUsageCheckAcrossImages( $keyword, $rules, $findings ); $checks[] = $is_vision ? FormulaChecks::row( 'visible_details', __( 'Visible details', 'ai-product-tools' ), 'warn', __( 'Described by the vision model, review before applying.', 'ai-product-tools' ) ) : FormulaChecks::row( 'visible_details', __( 'Visible details', 'ai-product-tools' ), 'skip', __( 'Not described, images were not analysed.', 'ai-product-tools' ) ); foreach ( $units as $unit ) { if ( ! in_array( $unit['status'], array( 'included', 'fallback', 'needs_review' ), true ) ) { $checks[] = ( new Checks() )->statusNote( $unit['id'], $unit['name'], $unit['status'], $unit['reason'] ); } } $checker = new Checks(); $checks[] = $checker->bannedPhrases( $this->validator->findBannedPhrases( implode( ' ', $all_text_parts ), $banned ) ); $provider_error = ProviderFailureSupport::providerErrorFromFindings( $findings ); $provider_error = ProviderFailureSupport::carryForwardProviderError( $units, $provider_error, $previous ); $findings = ProviderFailureSupport::applyAiOutcomeRules( $units, $findings, $provider_error ); $eligibility = $checker->eligibility( $findings, array() ); return array( 'units' => $units, 'outputs' => array( 'alt' => $alt, 'existingAlt' => $existing_alt ), 'checks' => $checks, 'conflicts' => array(), 'findings' => $findings, 'sourcesUsed' => array(), 'eligibility' => $eligibility, 'usage' => $usage, 'providerError' => $provider_error, ); } /** * Label a non-featured image's position among the product's GALLERY * images only (1-based), never the overall 0-based `position` a * featured image would also occupy slot 0 of. * * `$image['position']` (set by `AttachmentContextBuilder::imagesForProduct()`) * is the authoritative 0-based position among ALL of the product's * images (featured first, when one exists), so it is used here instead * of the image's own index within `$images` - the latter is only * accurate when `$images` holds every one of the product's images in * order, which is false for an "attachment" subject's single-image * `$images` array (see `ExecutionContextBuilder::loadAttachmentSubject()`). * * A non-featured image can never legitimately sit at position 0 when * the product DOES have a featured image (position 0 always belongs to * it): seeing that combination means this image's position was not * actually resolved from the product's real image list - that * attachment-subject path falls back to exactly this shape when the * requested attachment could not be matched - so no number is shown * rather than a misleading "Gallery 0". * * @param array{position?:int} $image One ctx['images'] entry. * @param bool $has_featured_image See {@see self::run()}. * @return string */ private function galleryLabel( array $image, bool $has_featured_image ): string { $position = (int) ( $image['position'] ?? 0 ); if ( $has_featured_image && 0 === $position ) { return __( 'Gallery image', 'ai-product-tools' ); } $gallery_number = $has_featured_image ? $position : $position + 1; /* translators: %d: 1-based position among the product's gallery images (the featured image, if any, is never counted). */ return sprintf( __( 'Gallery %d', 'ai-product-tools' ), $gallery_number ); } /** * "Mention the keyword once" check, measured per image (item 4.9/10.6): * unlike SEO Meta's single title+description pair, Image Alt generates N * independent texts, so the row must roll up from each image's own, * already-correct {@see self::resolveImage()} measurement (the * `keyword_used_multiple_times` finding, one per over-using image) the * same way the neighboring `length`/`image_of_openings` checks already * roll up from per-image findings, rather than counting the keyword * again against every image's alt text concatenated together (which * would warn even when each image is individually compliant). * * @param string $keyword The product name, for the keywordOnce usage check. * @param array $rules ImageAltStructure.rules. * @param array $findings Findings accumulated during generation. * @return array */ private function keywordUsageCheckAcrossImages( string $keyword, array $rules, array $findings ): array { if ( '' === $keyword ) { return FormulaChecks::row( 'keyword_usage', __( 'Keyword usage', 'ai-product-tools' ), 'skip', __( 'No keyword configured.', 'ai-product-tools' ) ); } if ( empty( $rules['keywordOnce'] ) ) { return FormulaChecks::row( 'keyword_usage', __( 'Keyword usage', 'ai-product-tools' ), 'pass', __( 'Not checked - the "mention it once" rule is off.', 'ai-product-tools' ) ); } $violation_count = count( array_filter( $findings, static function ( $finding ) { return 'keyword_used_multiple_times' === ( $finding['code'] ?? '' ); } ) ); return FormulaChecks::row( 'keyword_usage', __( 'Keyword usage', 'ai-product-tools' ), 0 === $violation_count ? 'pass' : 'warn', 0 === $violation_count ? __( 'Every image mentions it at most once.', 'ai-product-tools' ) /* translators: %d: number of images that mention the keyword more than once. */ : sprintf( _n( '%d image mentions it more than once.', '%d images mention it more than once.', $violation_count, 'ai-product-tools' ), $violation_count ) ); } /** * @param array[] $units Rendered units. * @param string $id Unit id. * @return array|null */ private function findUnit( array $units, string $id ): ?array { foreach ( $units as $unit ) { if ( ( $unit['id'] ?? '' ) === $id ) { return $unit; } } return null; } }