Skip to content

Instantly share code, notes, and snippets.

@Pelirrojo
Last active October 15, 2024 10:25
Show Gist options
  • Save Pelirrojo/2e802798a956b70763cb2e28834a2708 to your computer and use it in GitHub Desktop.
Save Pelirrojo/2e802798a956b70763cb2e28834a2708 to your computer and use it in GitHub Desktop.
PHP Script to generate the SEO tags through AWS Bedrock with Claude Sonnet
<?php
// Ensure this script its used by consola or exit process
if (php_sapi_name() !== 'cli') {
die('This script can only be run from the command line.');
}
// Load SDK de AWS
require 'vendor/autoload.php';
use Aws\Exception\AwsException;
use Aws\BedrockRuntime\BedrockRuntimeClient;
// Database config (get all this data from wp-config.php)
$db_host = '<db_ip>:3306';
$db_name = '<db_name>';
$db_user = '<db_user>';
$db_pass = '<db_password>';
$table_prefix = 'wp_';
// AWS config (make sure to follow least privilege principle)
$aws_key = '********************';
$aws_secret = '****************************************';
$aws_region = 'us-east-1';
// Connect to datatase
$db = new mysqli($db_host, $db_user, $db_pass, $db_name);
if ($db->connect_error) {
die("Error de conexión: " . $db->connect_error);
}
// Configurar el cliente de AWS Bedrock
$client = new BedrockRuntimeClient([
'version' => 'latest',
'region' => $aws_region,
'credentials' => [
'key' => $aws_key,
'secret' => $aws_secret,
]
]);
// Auxiliary function to clean model repsonses
function cleanPrefix($str) {
$prefixes = ['Page Title: ', 'Meta Descripción: ', 'Focus Keyphrase: '];
foreach ($prefixes as $prefix) {
if (strpos($str, $prefix) === 0) {
return trim(substr($str, strlen($prefix)));
}
}
return trim($str);
}
// Function to generate SEO tags from content
function generateSEO($client, $url, $title, $content) {
$messages = [
[
'role' => 'user',
'content' => [
[
'type' => 'text',
'text' => "Generate the following SEO fields for a website based on the provided information:
URL: {$url}
Title: {$title}
Content: {$content}
The output must be:
1. Page Title (60 caracteres máximo, SEO Friendly):
2. Meta Descripción (160 caracteres máximo, SEO Friendly):
3. Focus Keyphrase:
Please provide only the requested fields without additional explanations."
]
]
]
];
try {
$result = $client->invokeModel([
'modelId' => 'anthropic.claude-3-sonnet-20240229-v1:0',
'contentType' => 'application/json',
'accept' => 'application/json',
'body' => json_encode([
'anthropic_version' => 'bedrock-2023-05-31',
'max_tokens' => 500,
'messages' => $messages
])
]);
$response = json_decode($result->get('body')->getContents(), true);
return $response['content'][0]['text'];
} catch (AwsException $e) {
echo "Error when invoking the Bedrock model: " . $e->getMessage() . "\n";
return false;
}
}
// Get all pages from database
$query = "SELECT ID, post_title, post_content, guid FROM {$table_prefix}posts WHERE post_type = 'page' AND post_status = 'publish'";
$result = $db->query($query);
if ($result === false) {
die("Error en la consulta: " . $db->error);
}
while ($row = $result->fetch_assoc()) {
$page_id = $row['ID'];
$title = $row['post_title'];
$content = strip_tags($row['post_content']);
$url = $row['guid'];
// Call model to obtain SEO Values
$seo_data = generateSEO($client, $url, $title, $content);
if ($seo_data === false) {
echo "Unable to generate SEO tags for page with ID: $page_id. Go to the next one...\n";
// Throttling
sleep(5);
continue;
}
// Parse response to extract fields
preg_match('/1\. (.+)/', $seo_data, $page_title_match);
preg_match('/2\. (.+)/', $seo_data, $meta_description_match);
preg_match('/3\. (.+)/', $seo_data, $focus_keyphrase_match);
$page_title = cleanPrefix($page_title_match[1] ?? '');
$meta_description = cleanPrefix($meta_description_match[1] ?? '');
$focus_keyphrase = cleanPrefix($focus_keyphrase_match[1] ?? '');
// Update SEO tags (the data model is for plugin: All in One SEO but can be easy updated)
$update_query = "UPDATE {$table_prefix}aioseo_posts
SET title = ?, description = ?, keyphrases = ?
WHERE post_id = ?";
$stmt = $db->prepare($update_query);
$keyphrases_json = json_encode(['focus' => ['keyphrase' => $focus_keyphrase]]);
$stmt->bind_param("sssi", $page_title, $meta_description, $keyphrases_json, $page_id);
$stmt->execute();
echo "SEO tags populated in page with ID: $page_id\n";
// Throttling
sleep(5);
}
$db->close();
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment