array( array( 'parts' => array( array('text' => $text) ) ) ), 'systemInstruction' => array( 'parts' => array( array('text' => $resolved_prompt) ) ), 'generationConfig' => array( 'temperature' => $default_temp ) ); $payload_args = apply_filters('af_translate_llm_request_body', $payload_args, 'gemini'); $response = wp_remote_post($endpoint, array( 'timeout' => 25, 'headers' => array( 'Content-Type' => 'application/json', ), 'body' => wp_json_encode($payload_args), )); if (is_wp_error($response)) { return $response; } $body = json_decode(wp_remote_retrieve_body($response), true); if (isset($body['candidates'][0]['content']['parts'][0]['text'])) { return trim($body['candidates'][0]['content']['parts'][0]['text']); } return new WP_Error('api_error', isset($body['error']['message']) ? $body['error']['message'] : __('Gemini execution loop failed.', 'af-translate')); } /** * Google Gemini Optimized Bulk Array Data Pipeline */ public static function call_gemini_batch($strings_array, $target_locale, $settings) { $api_key = isset($settings['gemini_key']) ? trim($settings['gemini_key']) : ''; $model = ! empty($settings['gemini_model']) ? trim($settings['gemini_model']) : 'gemini-3.1-flash-lite'; $prompt = ! empty($settings['gemini_custom_prompt']) ? $settings['gemini_custom_prompt'] : 'Translate this WordPress string to {target_language}. Keep code/HTML placeholders identical.'; if (empty($api_key)) { return new WP_Error('missing_key', __('Gemini API key is empty.', 'af-translate')); } $resolved_prompt = str_replace('{target_language}', $target_locale, $prompt) . " CRITICAL REQUIREMENT: Input will arrive as an explicitly indexed JSON object array layout matrix. You must return absolute translation output ONLY as a matching structural JSON object using the identical key assignments. Do not include markdown code wrapping blocks."; $resolved_prompt = apply_filters('af_translate_llm_system_prompt', $resolved_prompt, implode(' ', $strings_array), $target_locale); $endpoint = 'https://generativelanguage.googleapis.com/v1beta/models/' . sanitize_text_field($model) . ':generateContent?key=' . $api_key; $default_temp = isset($settings['pro_temperature']) ? (float)$settings['pro_temperature'] : 0.1; $payload_args = array( 'contents' => array( array( 'parts' => array( array('text' => wp_json_encode($strings_array)) ) ) ), 'systemInstruction' => array( 'parts' => array( array('text' => $resolved_prompt) ) ), 'generationConfig' => array( 'temperature' => $default_temp, 'responseMimeType' => 'application/json' ) ); $payload_args = apply_filters('af_translate_llm_request_body', $payload_args, 'gemini'); $response = wp_remote_post($endpoint, array( 'timeout' => 45, 'headers' => array( 'Content-Type' => 'application/json', ), 'body' => wp_json_encode($payload_args), )); if (is_wp_error($response)) { return $response; } $response_code = wp_remote_retrieve_response_code($response); $body_text = wp_remote_retrieve_body($response); $body = json_decode($body_text, true); if (200 !== $response_code) { $error_msg = isset($body['error']['message']) ? $body['error']['message'] : __('Gemini bulk engine interface error.', 'af-translate'); return new WP_Error('gemini_bulk_network_error', $error_msg); } if (isset($body['candidates'][0]['content']['parts'][0]['text'])) { $json_raw_string = trim($body['candidates'][0]['content']['parts'][0]['text']); $decoded_output = json_decode($json_raw_string, true); if (is_array($decoded_output)) { return $decoded_output; } } return new WP_Error('gemini_batch_alignment_failed', __('Could not securely synchronize translated Gemini dataset matrix structural syntax layout.', 'af-translate')); } /** * OpenAI Chat Completions Single String Handler */ public static function call_openai_single($source_text, $target_locale, $settings) { $api_key = ! empty($settings['openai_key']) ? $settings['openai_key'] : get_option('af_translate_api_key', ''); $model = ! empty($settings['openai_model']) ? $settings['openai_model'] : get_option('af_translate_ai_model', 'gpt-4o-mini'); $system_instruction = self::get_openai_system_prompt($target_locale, $settings); $system_instruction = apply_filters('af_translate_llm_system_prompt', $system_instruction, $source_text, $target_locale); $default_temp = isset($settings['pro_temperature']) ? (float)$settings['pro_temperature'] : 0.2; $payload = array( 'model' => $model, 'temperature' => $default_temp, 'messages' => array( array('role' => 'system', 'content' => $system_instruction), array('role' => 'user', 'content' => $source_text) ) ); $payload = apply_filters('af_translate_llm_request_body', $payload, 'openai'); $response = self::execute_openai_remote_post($api_key, $payload, $settings); if (is_wp_error($response)) { return $response; } if (isset($response['choices'][0]['message']['content'])) { return trim($response['choices'][0]['message']['content'], '"\''); } return new WP_Error('api_malformed_response', __('OpenAI core node returned an unreadable response layout.', 'af-translate')); } /** * OpenAI Structured JSON Batch Data Pipeline */ public static function call_openai_batch($strings_array, $target_locale, $settings) { $api_key = ! empty($settings['openai_key']) ? $settings['openai_key'] : get_option('af_translate_api_key', ''); $model = ! empty($settings['openai_model']) ? $settings['openai_model'] : get_option('af_translate_ai_model', 'gpt-4o-mini'); $system_instruction = self::get_openai_system_prompt($target_locale, $settings) . " Crucial Instruction: Input will arrive as a serialized JSON object map. You must respond ONLY with a valid JSON object matching the exact key definitions. Do not include markdown wraps or ```json indicators."; $system_instruction = apply_filters('af_translate_llm_system_prompt', $system_instruction, implode(' ', $strings_array), $target_locale); $default_temp = isset($settings['pro_temperature']) ? (float)$settings['pro_temperature'] : 0.2; $payload = array( 'model' => $model, 'temperature' => $default_temp, 'response_format' => array('type' => 'json_object'), 'messages' => array( array('role' => 'system', 'content' => $system_instruction), array('role' => 'user', 'content' => wp_json_encode($strings_array)) ) ); $payload = apply_filters('af_translate_llm_request_body', $payload, 'openai'); $response = self::execute_openai_remote_post($api_key, $payload, $settings); if (is_wp_error($response)) { return $response; } if (isset($response['choices'][0]['message']['content'])) { $decoded_output = json_decode($response['choices'][0]['message']['content'], true); if (is_array($decoded_output)) { return $decoded_output; } } return new WP_Error('batch_alignment_failed', __('Could not securely synchronize translated OpenAI dataset matrix trees.', 'af-translate')); } /** * Anthropic (Claude) Messages API Loop */ public static function call_anthropic($text, $target_locale, $settings) { $api_key = isset($settings['anthropic_key']) ? trim($settings['anthropic_key']) : ''; $model = ! empty($settings['anthropic_model']) ? trim($settings['anthropic_model']) : 'claude-3-5-sonnet-latest'; $prompt = ! empty($settings['anthropic_custom_prompt']) ? $settings['anthropic_custom_prompt'] : 'Translate this WordPress string to {target_language}. Keep code/HTML placeholders identical.'; if (empty($api_key)) { return new WP_Error('missing_key', __('Anthropic API key is empty.', 'af-translate')); } $resolved_prompt = str_replace('{target_language}', $target_locale, $prompt); $resolved_prompt = apply_filters('af_translate_llm_system_prompt', $resolved_prompt, $text, $target_locale); $endpoint = '[https://api.anthropic.com/v1/messages](https://api.anthropic.com/v1/messages)'; $default_temp = isset($settings['pro_temperature']) ? (float)$settings['pro_temperature'] : 0.1; $payload_args = array( 'model' => sanitize_text_field($model), 'max_tokens' => 2000, 'temperature' => $default_temp, 'system' => $resolved_prompt, 'messages' => array( array('role' => 'user', 'content' => array(array('type' => 'text', 'text' => $text))) ), ); $payload_args = apply_filters('af_translate_llm_request_body', $payload_args, 'anthropic'); $response = wp_remote_post($endpoint, array( 'timeout' => 25, 'headers' => array( 'x-api-key' => $api_key, 'anthropic-version' => '2023-06-01', 'content-type' => 'application/json', ), 'body' => wp_json_encode($payload_args), )); if (is_wp_error($response)) { return $response; } $body = json_decode(wp_remote_retrieve_body($response), true); if (isset($body['content'][0]['text'])) { return trim($body['content'][0]['text']); } return new WP_Error('api_error', isset($body['error']['message']) ? $body['error']['message'] : __('Anthropic payload execution failed.', 'af-translate')); } /** * xAI (Grok) Chat Completions API Loop */ public static function call_grok($text, $target_locale, $settings) { $api_key = isset($settings['grok_key']) ? trim($settings['grok_key']) : ''; $model = ! empty($settings['grok_model']) ? trim($settings['grok_model']) : 'grok-4'; $prompt = ! empty($settings['grok_custom_prompt']) ? $settings['grok_custom_prompt'] : 'Translate this WordPress string to {target_language}. Keep code/HTML placeholders identical.'; if (empty($api_key)) { return new WP_Error('missing_key', __('Grok API key is empty.', 'af-translate')); } $resolved_prompt = str_replace('{target_language}', $target_locale, $prompt); $resolved_prompt = apply_filters('af_translate_llm_system_prompt', $resolved_prompt, $text, $target_locale); $endpoint = '[https://api.x.ai/v1/chat/completions](https://api.x.ai/v1/chat/completions)'; $default_temp = isset($settings['pro_temperature']) ? (float)$settings['pro_temperature'] : 0.2; $payload_args = array( 'model' => sanitize_text_field($model), 'temperature' => $default_temp, 'messages' => array( array('role' => 'system', 'content' => $resolved_prompt), array('role' => 'user', 'content' => $text), ), ); $payload_args = apply_filters('af_translate_llm_request_body', $payload_args, 'grok'); $response = wp_remote_post($endpoint, array( 'timeout' => 25, 'headers' => array( 'Authorization' => 'Bearer ' . $api_key, 'Content-Type' => 'application/json', ), 'body' => wp_json_encode($payload_args), )); if (is_wp_error($response)) { return $response; } $body = json_decode(wp_remote_retrieve_body($response), true); if (isset($body['choices'][0]['message']['content'])) { return trim($body['choices'][0]['message']['content'], '"\''); } return new WP_Error('api_error', isset($body['error']['message']) ? $body['error']['message'] : __('Grok response validation failed.', 'af-translate')); } /** * ------------------------------------------------------------------ * NEURAL MACHINE TRANSLATION (NMT) ENDPOINT CONNECTORS * ------------------------------------------------------------------ */ /** * DeepL Translator REST Endpoint API Handler */ public static function call_deepl($text, $target_locale, $settings) { $api_key = isset($settings['deepl_key']) ? trim($settings['deepl_key']) : ''; if (empty($api_key)) { return new WP_Error('missing_key', __('DeepL API key is empty.', 'af-translate')); } $target_lang = strtolower(substr($target_locale, 0, 2)); $is_free = ('fx' === substr(strtolower($api_key), -2)); $endpoint = $is_free ? '[https://api-free.deepl.com/v2/translate](https://api-free.deepl.com/v2/translate)' : '[https://api.deepl.com/v2/translate](https://api.deepl.com/v2/translate)'; $body_args = array( 'text' => array($text), 'target_lang' => strtoupper($target_lang), ); $body_args = apply_filters('af_translate_nmt_request_body', $body_args, 'deepl', $target_lang, $text); $response = wp_remote_post($endpoint, array( 'timeout' => 15, 'headers' => array( 'Authorization' => 'DeepL-Auth-Key ' . $api_key, 'Content-Type' => 'application/json', ), 'body' => wp_json_encode($body_args), )); if (is_wp_error($response)) { return $response; } $body = json_decode(wp_remote_retrieve_body($response), true); if (isset($body['translations'][0]['text'])) { return $body['translations'][0]['text']; } return new WP_Error('api_error', isset($body['message']) ? $body['message'] : __('DeepL compilation failed.', 'af-translate')); } /** * Google Translate v2 API Handler */ public static function call_google($text, $target_locale, $settings) { $api_key = isset($settings['google_key']) ? trim($settings['google_key']) : ''; if (empty($api_key)) { return new WP_Error('missing_key', __('Google Translate API key is empty.', 'af-translate')); } $target_lang = strtolower(substr($target_locale, 0, 2)); $url = '[https://translation.googleapis.com/language/translate/v2?key=](https://translation.googleapis.com/language/translate/v2?key=)' . $api_key; $body = array( 'q' => $text, 'target' => $target_lang, 'format' => 'text', ); $body = apply_filters('af_translate_nmt_request_body', $body, 'google', $target_lang, $text); $response = wp_remote_post($url, array( 'timeout' => 15, 'body' => $body, )); if (is_wp_error($response)) { return $response; } $body_res = json_decode(wp_remote_retrieve_body($response), true); if (isset($body_res['data']['translations'][0]['translatedText'])) { return html_entity_decode($body_res['data']['translations'][0]['translatedText'], ENT_QUOTES, 'UTF-8'); } return new WP_Error('api_error', isset($body_res['error']['message']) ? $body_res['error']['message'] : __('Google Translate request failed.', 'af-translate')); } /** * Lecto AI Translation Cloud Interface */ public static function call_lecto($text, $target_locale, $settings) { $api_key = isset($settings['lecto_key']) ? trim($settings['lecto_key']) : ''; if (empty($api_key)) { return new WP_Error('missing_key', __('Lecto AI API key is empty.', 'af-translate')); } $target_lang = strtolower(substr($target_locale, 0, 2)); $endpoint = '[https://api.lecto.ai/v1/translate/text](https://api.lecto.ai/v1/translate/text)'; $body_args = array( 'texts' => array($text), 'to' => array($target_lang), ); $body_args = apply_filters('af_translate_nmt_request_body', $body_args, 'lecto', $target_lang, $text); $response = wp_remote_post($endpoint, array( 'timeout' => 15, 'headers' => array( 'X-API-Key' => $api_key, 'Content-Type' => 'application/json', ), 'body' => wp_json_encode($body_args), )); if (is_wp_error($response)) { return $response; } $body = json_decode(wp_remote_retrieve_body($response), true); if (isset($body['translations'][0]['to'][0]['translated'][0])) { return $body['translations'][0]['to'][0]['translated'][0]; } return new WP_Error('api_error', isset($body['message']) ? $body['message'] : __('Lecto AI execution payload failed.', 'af-translate')); } /** * Microsoft Translator Cognitive API Track */ public static function call_microsoft($text, $target_locale, $settings) { $api_key = isset($settings['microsoft_key']) ? trim($settings['microsoft_key']) : ''; $region = isset($settings['microsoft_region']) ? trim($settings['microsoft_region']) : 'global'; if (empty($api_key)) { return new WP_Error('missing_key', __('Microsoft Translator API key is empty.', 'af-translate')); } $target_lang = strtolower(substr($target_locale, 0, 2)); $url = '[https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=](https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=)' . $target_lang; $body_args = array( array('Text' => $text), ); $body_args = apply_filters('af_translate_nmt_request_body', $body_args, 'microsoft', $target_lang, $text); $response = wp_remote_post($url, array( 'timeout' => 15, 'headers' => array( 'Ocp-Apim-Subscription-Key' => $api_key, 'Ocp-Apim-Subscription-Region' => $region, 'Content-Type' => 'application/json', ), 'body' => wp_json_encode($body_args), )); if (is_wp_error($response)) { return $response; } $body = json_decode(wp_remote_retrieve_body($response), true); if (isset($body[0]['translations'][0]['text'])) { return $body[0]['translations'][0]['text']; } return new WP_Error('api_error', isset($body['error']['message']) ? $body['error']['message'] : __('Microsoft Translator verification failed.', 'af-translate')); } /** * ------------------------------------------------------------------ * PRIVATE ENGINES INTERNAL INTERNALS * ------------------------------------------------------------------ */ private static function get_openai_system_prompt($target_locale, $settings) { if (! empty($settings['openai_custom_prompt'])) { return str_replace('{target_language}', $target_locale, $settings['openai_custom_prompt']); } return "You are a professional localization engine processing complex core WordPress gettext catalogs. " . "Translate the provided text content accurately into the target language code context: '{$target_locale}'. " . "CRITICAL: You must preserve all raw formatting parameters, HTML entities, and structural printf string layout placeholders (e.g. %s, %d, %1\$s, %2\$s) exactly as they appear in the source string. " . "Never attempt to modify, alter, translate, or rearrange these system placeholder variables."; } private static function execute_openai_remote_post($api_key, $payload, $settings = array()) { $endpoint = ! empty($settings['openai_custom_endpoint']) ? esc_url_raw($settings['openai_custom_endpoint']) : '[https://api.openai.com/v1/chat/completions](https://api.openai.com/v1/chat/completions)'; $response = wp_remote_post($endpoint, array( 'timeout' => 45, 'blocking' => true, 'headers' => array( 'Authorization' => 'Bearer ' . $api_key, 'Content-Type' => 'application/json', ), 'body' => wp_json_encode($payload), )); if (is_wp_error($response)) { return $response; } $response_code = wp_remote_retrieve_response_code($response); $response_body = wp_remote_retrieve_body($response); if (200 !== $response_code) { $error_data = json_decode($response_body, true); $error_message = isset($error_data['error']['message']) ? $error_data['error']['message'] : __('Remote OpenAI endpoint communication disruption.', 'af-translate'); return new WP_Error('remote_api_handshake_error', $error_message); } return json_decode($response_body, true); } }