Trying to translate video post but doesn'T work

Bambarbiakirgudu

Regular Member
Joined
Nov 9, 2016
Messages
358
Reaction score
63
------

I'm using the 'wp mass embedder' plugin from wp-script to upload videos to my site. I wrote a code that uses the OpenAI API to translate videos into German. The goal is to perform the translation process via a button we added to the WordPress admin panel. When I press the button, the script says 'translation completed', but when I check, the titles and tags of the videos are not translated. I thought it might be related to the API rate limit, but I'm not sure. What do you think could be the reason?

Here is the PHP code:

```php
// Add a menu button for the translation function
function add_translate_menu() {
// Adds a new item to the WordPress admin menu
add_menu_page(
'Add Video Translation', // Menu title
'Video Translation', // Display name in the menu
'manage_options', // Required capability to see the menu
'add-translate', // Menu slug
'run_translate_function' // Function to run when clicking the button
);
}
add_action('admin_menu', 'add_translate_menu');

// This function is executed when the admin clicks the menu button
function run_translate_function() {
// Get all posts of type 'video'
$args = array(
'post_type' => 'video', // Retrieve only 'video' post type entries
'posts_per_page' => -1, // Get all posts
'post_status' => 'publish' // Only published posts
);

$videos = get_posts($args); // Retrieve all video posts

$total_videos = count($videos); // Count the total number of videos
$translated_videos = 0; // Initialize translated video counter

echo '<div class="wrap"><h1>Video Translation</h1>';
echo '<p>Translation process has started. Do not close this page until it is complete.</p>';
echo '<ul id="translation-progress">';

foreach ($videos as $video) {
$post_id = $video->ID; // Get the video post ID

// Get the original title and tags
$original_title = get_the_title($post_id);
$original_tags = wp_get_post_tags($post_id, array('fields' => 'names'));

// OpenAI API key for authentication
$api_key = 'YOUR_OPENAI_API_KEY'; // Replace with your actual API key

// Perform the translation
$translated_title = translate_with_openai($original_title, $api_key);
$translated_tags = translate_with_openai(implode(', ', $original_tags), $api_key);

// Update the post with the translated title
wp_update_post(array(
'ID' => $post_id,
'post_title' => $translated_title, // Set the translated title
));

// Update the post with the translated tags
wp_set_post_tags($post_id, explode(', ', $translated_tags), false); // Update tags

// Display the progress to the user
$translated_videos++;
echo '<li>Video ID ' . $post_id . ' successfully translated. (' . $translated_videos . '/' . $total_videos . ')</li>';

// Flush the output buffer to update the progress
ob_flush();
flush();

// Pause for 2 seconds to avoid exceeding the rate limit
sleep(2);
}

echo '</ul>';
echo '<p>All videos have been successfully translated!</p></div>';
}

// Function to handle the actual translation using the OpenAI API
function translate_with_openai($text, $api_key, $target_language = 'de') {
$url = 'https://api.openai.com/v1/chat/completions';

// Prepare the data for the API request
$data = array(
'model' => 'gpt-4', // Using GPT-4 for better translation
'messages' => array(
array('role' => 'user', 'content' => "Please translate the following to {$target_language}: {$text}") // Translation prompt
),
'max_tokens' => 1000, // Max tokens to generate
'temperature' => 0.7, // Control the randomness of the output
);

// Initialize cURL to make the API request
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Authorization: ' . 'Bearer ' . $api_key // Authenticate with OpenAI API key
));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); // Send the request data

$result = curl_exec($ch); // Execute the request
$curl_error = curl_error($ch); // Capture any cURL errors
curl_close($ch); // Close the cURL session

// Handle cURL errors if any
if ($curl_error) {
error_log('cURL Error: ' . $curl_error); // Log the error for debugging
return 'Translation failed: cURL error.'; // Return a failure message
}

// Decode the API response
$response = json_decode($result, true);

// Check if the translation was successful and return the result
if (isset($response['choices'][0]['message']['content'])) {
return trim($response['choices'][0]['message']['content']); // Return the translated text
} else {
error_log('OpenAI Error: ' . json_encode($response)); // Log API errors
return 'Translation failed.'; // Return a failure message
}
}
 
Back
Top