← Back
Editing: class-ai-generator.php
<?php defined( 'ABSPATH' ) || exit; class ADM_Alt_AI_Generator { private static $unsupported_ext = [ 'svg', 'ico', 'bmp', 'tiff', 'tif' ]; private static $logo_keywords = [ 'logo', 'brand', 'badge', 'seal', 'emblem', 'mark', 'icon-brand' ]; public static function generate( array $item ): array { $api_key = get_option( 'adm_alt_claude_key', '' ); if ( ! $api_key ) { return [ 'status' => 'error', 'error_msg' => 'Claude API key not configured.' ]; } $att_id = (int) ( $item['attachment_id'] ?? 0 ); $url = $item['image_url'] ?? ''; if ( ! $att_id && ! $url ) { return [ 'status' => 'error', 'error_msg' => 'No attachment ID or image URL.' ]; } // ── Get file path from attachment ID (local disk read — bypasses firewalls) ── $file_path = $att_id ? get_attached_file( $att_id ) : null; // Determine extension if ( $file_path && file_exists( $file_path ) ) { $ext = strtolower( pathinfo( $file_path, PATHINFO_EXTENSION ) ); } else { $ext = strtolower( pathinfo( parse_url( $url, PHP_URL_PATH ), PATHINFO_EXTENSION ) ); } if ( in_array( $ext, self::$unsupported_ext, true ) ) { return [ 'status' => 'decorative', 'new_alt' => '' ]; } $media_type = self::media_type( $ext ); $is_logo = self::is_logo( $file_path ?: $url ); $page_title = sanitize_text_field( $item['page_title'] ?? '' ); $location = sanitize_text_field( $item['location_hint'] ?? '' ); // ── Read image as base64 from local disk ────────────────────────────── $image_source = null; if ( $file_path && file_exists( $file_path ) ) { $raw = file_get_contents( $file_path ); if ( $raw !== false && strlen( $raw ) > 0 ) { $image_source = [ 'type' => 'base64', 'media_type' => $media_type, 'data' => base64_encode( $raw ), ]; } } // Fallback: try URL source if local file not found if ( ! $image_source ) { if ( ! $url ) { return [ 'status' => 'error', 'error_msg' => 'Image file not found on server and no URL available.' ]; } $image_source = [ 'type' => 'url', 'url' => $url, ]; } // Always use the unified prompt — it handles logo detection visually $prompt = self::unified_prompt( $page_title, $location, $is_logo ); $body = [ 'model' => 'claude-haiku-4-5-20251001', 'max_tokens' => 150, 'messages' => [ [ 'role' => 'user', 'content' => [ [ 'type' => 'image', 'source' => $image_source ], [ 'type' => 'text', 'text' => $prompt ], ], ], ], ]; $response = wp_remote_post( 'https://api.anthropic.com/v1/messages', [ 'headers' => [ 'x-api-key' => $api_key, 'anthropic-version' => '2023-06-01', 'content-type' => 'application/json', ], 'body' => wp_json_encode( $body ), 'timeout' => 60, ] ); if ( is_wp_error( $response ) ) { return [ 'status' => 'error', 'error_msg' => $response->get_error_message() ]; } $code = wp_remote_retrieve_response_code( $response ); $data = json_decode( wp_remote_retrieve_body( $response ), true ); if ( $code === 429 ) { return [ 'status' => 'error', 'error_msg' => 'Rate limit — will retry.' ]; } if ( $code !== 200 ) { $msg = $data['error']['message'] ?? "API error $code"; return [ 'status' => 'error', 'error_msg' => $msg ]; } $alt = trim( $data['content'][0]['text'] ?? '' ); $alt = self::sanitise_alt( $alt ); if ( ! $alt ) { return [ 'status' => 'decorative', 'new_alt' => '' ]; } return [ 'status' => 'applied', 'new_alt' => $alt ]; } private static function is_logo( string $path_or_url ): bool { $basename = strtolower( basename( $path_or_url ) ); foreach ( self::$logo_keywords as $kw ) { if ( strpos( $basename, $kw ) !== false ) return true; } return false; } private static function unified_prompt( string $page_title, string $location, bool $filename_suggests_logo ): string { $ctx = $page_title ? "Page context: {$page_title}." : ''; $loc = $location ? "Business location: {$location}." : ''; $logo_hint = $filename_suggests_logo ? "NOTE: The filename suggests this may be a logo or brand mark — check carefully." : ''; return <<<PROMPT You are writing SEO alt text for a dental practice website image. {$ctx} {$loc} {$logo_hint} STEP 1 — Classify the image into ONE of these categories: A) LOGO — A brand logo, wordmark, icon, badge, seal, or emblem containing a company name or brand symbol (e.g. a dental practice name, a dental association badge, an insurance provider logo, a software brand icon). Even if small or simple, if it has a brand name or recognisable brand symbol → it is a logo. B) DECORATIVE — A background texture, abstract shape, gradient, solid colour block, divider, pattern, blank space, or purely ornamental graphic with no informational content. C) CONTENT — A real photo or meaningful illustration (people, procedures, equipment, rooms, before/after teeth, etc.). STEP 2 — Based on category: - If A (LOGO): respond with exactly "[Brand Name] logo." — replace [Brand Name] with the actual brand name visible in the image. Nothing else. - If B (DECORATIVE): respond with exactly the word: DECORATIVE - If C (CONTENT): write an alt text following ALL these rules: 1. Under 125 characters total. 2. End with a period. 3. Do NOT start with "image of", "picture of", "photo of". 4. Do NOT use quotation marks. 5. Use dental-context language where relevant (dentist, patient, smile, teeth, dental chair, treatment, etc.). 6. Normal sentence style — not hyphenated words. 7. Be specific about what is shown. Respond with ONLY the final alt text, DECORATIVE, or "[Brand Name] logo." — no explanation, no category label. PROMPT; } private static function sanitise_alt( string $raw ): string { $trimmed = strtoupper( trim( $raw ) ); // Decorative — empty alt if ( $trimmed === 'DECORATIVE' ) { return ''; } // Old-style LOGO response with no brand name — empty alt if ( $trimmed === 'LOGO' ) { return ''; } $alt = trim( $raw, '"\'`' ); // Ensure ends with period if ( $alt && substr( $alt, -1 ) !== '.' ) { $alt .= '.'; } // Hard-truncate to 125 chars if ( mb_strlen( $alt ) > 125 ) { $alt = rtrim( mb_substr( $alt, 0, 124 ) ) . '.'; } return $alt; } private static function media_type( string $ext ): string { $map = [ 'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'png' => 'image/png', 'webp' => 'image/webp', 'gif' => 'image/gif', ]; return $map[ $ext ] ?? 'image/jpeg'; } }
Save File
Cancel