string, 'prompt' => string ). */ function aatg_build_prompt( $post_ID, $with_title, $phase = 'manual' ) { $context = implode( "\n", aatg_get_image_context_lines( $post_ID, $phase ) ); $alt_instruction = 'Write a single alt text for this image that serves both screen-reader accessibility (WCAG 1.1.1) and SEO. Lead with the main subject, then add only essential context. Where accurate, naturally include the most relevant descriptive keyword, but never keyword-stuff. If the image contains meaningful text (a sign, label, infographic or logo wordmark), transcribe it. Do not say it is an image, picture or photograph, and mention a style such as monochrome only when the image is about that style (for example an art print). Do not repeat or include any page title. Use clear, specific, human language: aim for 60–110 characters and never exceed 125.'; /** * Filter the alt-text instruction. * * @param string $alt_instruction Instruction text (without the context block). * @param int $post_ID Attachment ID. * @param string $context Context lines joined by newlines. */ $alt_instruction = apply_filters( 'aatg_alt_text_prompt', $alt_instruction, $post_ID, $context ); $prompt = ''; if ( '' !== $context ) { $prompt .= "Context about this image:\n" . $context . "\n\n" . AATG_CONTEXT_RULE . "\n\n"; } if ( $with_title ) { $title_instruction = "Write a concise, SEO-friendly title for the image. Lead with its primary subject, use natural human-readable language with relevant keywords (never keyword-stuff), and avoid filler words like 'image', 'photo' or 'picture'. Plain text, about 50–70 characters."; /** * Filter the image-title instruction. * * @param string $title_instruction Instruction text (without the context block). * @param int $post_ID Attachment ID. * @param string $context Context lines joined by newlines. */ $title_instruction = apply_filters( 'aatg_image_title_prompt', $title_instruction, $post_ID, $context ); $prompt .= 'Alt text: ' . $alt_instruction . "\n\n" . 'Title: ' . $title_instruction . "\n\n" . 'Reply with only a JSON object in this exact shape: {"alt_text": "...", "title": "..."}'; } else { $prompt .= $alt_instruction . "\n\nOutput only the alt text."; } $system = aatg_language_system_message(); if ( '' !== $system && $with_title ) { $system .= ' Keep the JSON keys in English.'; } return array( 'system' => $system, 'prompt' => $prompt, ); } /** * Tidy model output: drop "Alt text:" labels and wrapping or stray leading quotes. * * @param string $text Raw text. * @return string */ function aatg_clean_output( $text ) { $text = trim( aatg_valid_utf8( $text ) ); $text = trim( (string) preg_replace( '/^(alt[\s-]*text|title)\s*:\s*/i', '', $text ) ); if ( preg_match( '/^["“‘\'`](.*)["”’\'`]$/us', $text, $m ) ) { $text = $m[1]; } $text = (string) preg_replace( '/^["“]\s*/u', '', $text ); return sanitize_text_field( $text ); } /** * Balanced {…} substrings in text, in order, ignoring braces inside JSON strings. * * @param string $text Text. * @return string[] */ function aatg_find_json_objects( $text ) { $objects = array(); $depth = 0; $start = 0; $in_str = false; $escaped = false; $length = strlen( $text ); for ( $i = 0; $i < $length; $i++ ) { $char = $text[ $i ]; if ( $in_str ) { if ( $escaped ) { $escaped = false; } elseif ( '\\' === $char ) { $escaped = true; } elseif ( '"' === $char ) { $in_str = false; } continue; } if ( '"' === $char && $depth > 0 ) { $in_str = true; } elseif ( '{' === $char ) { if ( 0 === $depth ) { $start = $i; } $depth++; } elseif ( '}' === $char && $depth > 0 ) { $depth--; if ( 0 === $depth ) { $objects[] = substr( $text, $start, $i - $start + 1 ); } } } return $objects; } /** * First string value for any of the given keys. * * @param array $data Decoded JSON. * @param string[] $keys Keys in order of preference. * @return string|null */ function aatg_json_string( array $data, array $keys ) { foreach ( $keys as $key ) { if ( isset( $data[ $key ] ) && is_string( $data[ $key ] ) ) { return $data[ $key ]; } } return null; } /** * Parse a model reply into alt text and title. * * Accepts a JSON object (optionally in a code fence or surrounded by chatter, * with common alternative key names). A JSON object without any alt text gives * '' rather than raw JSON; text with no JSON object is treated as plain alt text. * * @param string $raw Model text. * @param bool $with_title Whether a title was requested. * @return array array( 'alt_text' => string, 'title' => string ). */ function aatg_parse_generation( $raw, $with_title ) { $text = trim( (string) preg_replace( '/^```[a-z]*\s*|\s*```$/i', '', trim( (string) $raw ) ) ); $alt = $text; $title = ''; $had_json = false; foreach ( aatg_find_json_objects( $text ) as $candidate ) { $json = json_decode( $candidate, true ); if ( ! is_array( $json ) ) { continue; } $had_json = true; $found_alt = aatg_json_string( $json, array( 'alt_text', 'alt', 'altText', 'alt-text', 'alttext' ) ); if ( null !== $found_alt ) { $alt = $found_alt; $title = (string) aatg_json_string( $json, array( 'title', 'image_title', 'imageTitle' ) ); break; } } if ( $had_json && $alt === $text ) { $alt = ''; // JSON came back, but none of it was alt text. } return array( 'alt_text' => aatg_clean_output( $alt ), 'title' => $with_title ? aatg_clean_output( $title ) : '', ); } /** * Ask the selected model for alt text (and optionally a title). Saves nothing. * * @param int $post_ID Attachment ID. * @param bool $with_title Whether to ask for a title too. * @param array|null $metadata Attachment metadata (pass it during upload). * @param string $phase 'upload', 'manual' or 'bulk'. * @return array|WP_Error array( 'alt_text' => string, 'title' => string ). */ function aatg_request_generation( $post_ID, $with_title, $metadata = null, $phase = 'manual' ) { $provider = aatg_get_provider(); if ( is_wp_error( $provider ) ) { return $provider; } $image = aatg_prepare_image( $post_ID, $metadata ); if ( is_wp_error( $image ) ) { return $image; } $prompt = aatg_build_prompt( $post_ID, $with_title, $phase ); $raw = $provider->generate( array( 'system' => $prompt['system'], 'prompt' => $prompt['prompt'], 'image' => $image, 'detail' => 'high' === get_option( 'aatg_image_detail', 'low' ) ? 'high' : 'low', 'max_tokens' => 2048, 'context' => $with_title ? 'alt text and title' : 'alt text', ) ); if ( is_wp_error( $raw ) ) { return $raw; } $parsed = aatg_parse_generation( $raw, $with_title ); if ( '' === $parsed['alt_text'] ) { return new WP_Error( 'aatg_empty_response', /* translators: %s = provider name */ sprintf( __( '%s did not return any alt text.', 'ai-auto-alt-text-generator' ), $provider->label() ) ); } return $parsed; } /** * Save alt text through the 1.x filter and action. * * @param int $post_ID Attachment ID. * @param string $alt Alt text. * @return string Saved alt text. */ function aatg_save_alt_text( $post_ID, $alt ) { /** * Filter the generated alt text before it is saved. * * @param string $alt_text Generated alt text. * @param int $post_ID Attachment ID. */ $alt = apply_filters( 'aatg_generated_alt_text', $alt, $post_ID ); update_post_meta( $post_ID, '_wp_attachment_image_alt', $alt ); /** * Fires after alt text has been generated and saved. * * @param int $post_ID Attachment ID. * @param string $alt_text Saved alt text. */ do_action( 'aatg_after_alt_text_generated', $post_ID, $alt ); return $alt; } /** * Save a title through the 1.x filter and action. * * @param int $post_ID Attachment ID. * @param string $title Title. * @return string Saved title. */ function aatg_save_title( $post_ID, $title ) { /** * Filter the generated image title before it is saved. * * @param string $title_text Generated title. * @param int $post_ID Attachment ID. */ $title = apply_filters( 'aatg_generated_title', $title, $post_ID ); wp_update_post( array( 'ID' => $post_ID, 'post_title' => $title, ) ); /** * Fires after an image title has been generated and saved. * * @param int $post_ID Attachment ID. * @param string $title_text Saved title. */ do_action( 'aatg_after_title_generated', $post_ID, $title ); return $title; } /** * Generate and save alt text and (when auto-title is on) a title in one request. * * @param int $post_ID Attachment ID. * @param array|null $metadata Attachment metadata (pass it during upload). * @param string $phase 'upload', 'manual' or 'bulk'. * @return array|WP_Error array( 'alt_text' => string, 'title' => string|null, 'warning' => string|null ). */ function aatg_generate_text_and_title( $post_ID, $metadata = null, $phase = 'manual' ) { $with_title = 'on' === get_option( 'aatg_auto_title', 'on' ); $parsed = aatg_request_generation( $post_ID, $with_title, $metadata, $phase ); if ( is_wp_error( $parsed ) ) { return $parsed; } $result = array( 'alt_text' => aatg_save_alt_text( $post_ID, $parsed['alt_text'] ), 'title' => null, 'warning' => null, ); if ( $with_title ) { if ( '' === $parsed['title'] ) { $result['warning'] = __( 'The model did not return a title, so the existing title was kept.', 'ai-auto-alt-text-generator' ); } else { $result['title'] = aatg_save_title( $post_ID, $parsed['title'] ); } } /** * Fires after a full generation pass (alt text and optional title) completes. * * Used internally to dispatch outgoing webhooks; also available to integrators. * * @param int $post_ID Attachment ID. * @param array $result Result array with 'alt_text', 'title', 'warning' keys. */ do_action( 'aatg_after_generation', $post_ID, $result ); return $result; } /** * Generate and save alt text only (kept from 1.x). * * @param int $post_ID Attachment ID. * @return string|WP_Error Saved alt text. */ function aatg_generate_alt_text( $post_ID ) { $parsed = aatg_request_generation( $post_ID, false ); if ( is_wp_error( $parsed ) ) { return $parsed; } return aatg_save_alt_text( $post_ID, $parsed['alt_text'] ); } /** * Generate and save a title only (kept from 1.x). * * @param int $post_ID Attachment ID. * @return string|WP_Error Saved title. */ function aatg_generate_image_title( $post_ID ) { $parsed = aatg_request_generation( $post_ID, true ); if ( is_wp_error( $parsed ) ) { return $parsed; } if ( '' === $parsed['title'] ) { return new WP_Error( 'aatg_empty_response', __( 'The model did not return a title.', 'ai-auto-alt-text-generator' ) ); } return aatg_save_title( $post_ID, $parsed['title'] ); } /** * Trim a leading double-quote character from generated text (kept from 1.x). * * @param string $text Text. * @return string */ function aatg_trim_leading_quote( $text ) { $text = ltrim( $text ); if ( strpos( $text, '"' ) === 0 ) { $text = ltrim( substr( $text, 1 ) ); } return $text; } /** * Return a system message instructing the model to write in the selected language. * For en_US we return an empty string to preserve current behaviour. */ function aatg_language_system_message() { $code = get_option( 'aatg_language', 'en_US' ); switch ( $code ) { case 'en_GB': return 'Write all outputs in English (UK) using British spellings.'; case 'es_ES': case 'es_MX': return 'Write all outputs in Spanish.'; case 'fr_FR': return 'Write all outputs in French.'; case 'de_DE': return 'Write all outputs in German.'; case 'it_IT': return 'Write all outputs in Italian.'; case 'pt_PT': return 'Write all outputs in European Portuguese.'; case 'pt_BR': return 'Write all outputs in Brazilian Portuguese.'; case 'nl_NL': return 'Write all outputs in Dutch.'; case 'sv_SE': return 'Write all outputs in Swedish.'; case 'da_DK': return 'Write all outputs in Danish.'; case 'fi_FI': return 'Write all outputs in Finnish.'; case 'no_NO': return 'Write all outputs in Norwegian.'; case 'pl_PL': return 'Write all outputs in Polish.'; case 'cs_CZ': return 'Write all outputs in Czech.'; case 'tr_TR': return 'Write all outputs in Turkish.'; case 'ru_RU': return 'Write all outputs in Russian.'; case 'ja_JP': return 'Write all outputs in Japanese.'; case 'ko_KR': return 'Write all outputs in Korean.'; case 'zh_CN': return 'Write all outputs in Simplified Chinese.'; case 'zh_TW': return 'Write all outputs in Traditional Chinese.'; case 'ar' : return 'Write all outputs in Arabic.'; case 'hi_IN': return 'Write all outputs in Hindi.'; default: return ''; // en_US or unknown → no change } }