|
| 1 | +import Foundation |
| 2 | +import FoundationModels |
| 3 | +import UIKit |
| 4 | +import WordPressShared |
| 5 | + |
| 6 | +/// Alt text generation for media items. |
| 7 | +/// |
| 8 | +/// Generates concise, descriptive, and accessible alt text for images based on |
| 9 | +/// visual analysis and available metadata. |
| 10 | +/// |
| 11 | +/// Example usage: |
| 12 | +/// ```swift |
| 13 | +/// let generator = ImageAltTextGenerator() |
| 14 | +/// let altText = try await generator.generate(metadata: metadata) |
| 15 | +/// ``` |
| 16 | +@available(iOS 26, *) |
| 17 | +public struct ImageAltTextGenerator { |
| 18 | + public var options: GenerationOptions |
| 19 | + |
| 20 | + public init(options: GenerationOptions = GenerationOptions(temperature: 0.7)) { |
| 21 | + self.options = options |
| 22 | + } |
| 23 | + |
| 24 | + /// Generates alt text for a media item. |
| 25 | + /// |
| 26 | + /// - Parameter metadata: The media metadata to use for generation |
| 27 | + /// - Returns: Generated alt text |
| 28 | + /// - Throws: If metadata is insufficient or generation fails |
| 29 | + public func generate(metadata: MediaMetadata) async throws -> String { |
| 30 | + guard metadata.hasContent else { |
| 31 | + throw NSError(domain: "IntelligenceService", code: -1, userInfo: [ |
| 32 | + NSLocalizedDescriptionKey: "Insufficient metadata to generate alt text. Please add a filename, title, or description first." |
| 33 | + ]) |
| 34 | + } |
| 35 | + |
| 36 | + let startTime = CFAbsoluteTimeGetCurrent() |
| 37 | + let session = makeSession() |
| 38 | + let prompt = makePrompt(metadata: metadata) |
| 39 | + |
| 40 | + let response = try await session.respond(to: prompt, options: options) |
| 41 | + |
| 42 | + WPLogInfo("ImageAltTextGenerator executed in \((CFAbsoluteTimeGetCurrent() - startTime) * 1000) ms") |
| 43 | + |
| 44 | + return response.content.trimmingCharacters(in: .whitespacesAndNewlines) |
| 45 | + } |
| 46 | + |
| 47 | + /// Generates alt text for an image with automatic Vision analysis. |
| 48 | + /// |
| 49 | + /// This convenience method automatically analyzes the image using Vision framework |
| 50 | + /// and generates alt text based on the analysis combined with provided metadata. |
| 51 | + /// |
| 52 | + /// - Parameters: |
| 53 | + /// - cgImage: The image to analyze and generate alt text for |
| 54 | + /// - metadata: Additional metadata (filename, title, etc.). The imageAnalysis field will be populated automatically. |
| 55 | + /// - Returns: Generated alt text |
| 56 | + /// - Throws: If image analysis or generation fails |
| 57 | + public func generate(cgImage: CGImage, metadata: MediaMetadata = MediaMetadata()) async throws -> String { |
| 58 | + let imageAnalysis = try await IntelligenceService.analyzeImage(cgImage) |
| 59 | + |
| 60 | + let metadataWithAnalysis = MediaMetadata( |
| 61 | + filename: metadata.filename, |
| 62 | + title: metadata.title, |
| 63 | + caption: metadata.caption, |
| 64 | + description: metadata.description, |
| 65 | + altText: metadata.altText, |
| 66 | + fileType: metadata.fileType, |
| 67 | + dimensions: metadata.dimensions, |
| 68 | + imageAnalysis: imageAnalysis |
| 69 | + ) |
| 70 | + |
| 71 | + return try await generate(metadata: metadataWithAnalysis) |
| 72 | + } |
| 73 | + |
| 74 | + /// Generates alt text for an image with automatic Vision analysis. |
| 75 | + /// |
| 76 | + /// This convenience method automatically analyzes the image using Vision framework |
| 77 | + /// and generates alt text based on the analysis combined with provided metadata. |
| 78 | + /// |
| 79 | + /// - Parameters: |
| 80 | + /// - image: The UIImage to analyze and generate alt text for |
| 81 | + /// - metadata: Additional metadata (filename, title, etc.). The imageAnalysis field will be populated automatically. |
| 82 | + /// - Returns: Generated alt text |
| 83 | + /// - Throws: If the image cannot be converted to CGImage, or if analysis/generation fails |
| 84 | + public func generate(image: UIImage, metadata: MediaMetadata = MediaMetadata()) async throws -> String { |
| 85 | + guard let cgImage = image.cgImage else { |
| 86 | + throw NSError(domain: "IntelligenceService", code: -2, userInfo: [ |
| 87 | + NSLocalizedDescriptionKey: "Unable to convert UIImage to CGImage" |
| 88 | + ]) |
| 89 | + } |
| 90 | + return try await generate(cgImage: cgImage, metadata: metadata) |
| 91 | + } |
| 92 | + |
| 93 | + /// Generates alt text for image data with automatic Vision analysis. |
| 94 | + /// |
| 95 | + /// This convenience method automatically analyzes the image using Vision framework |
| 96 | + /// and generates alt text based on the analysis combined with provided metadata. |
| 97 | + /// |
| 98 | + /// - Parameters: |
| 99 | + /// - imageData: The image data to analyze and generate alt text for |
| 100 | + /// - metadata: Additional metadata (filename, title, etc.). The imageAnalysis field will be populated automatically. |
| 101 | + /// - Returns: Generated alt text |
| 102 | + /// - Throws: If the data cannot be converted to an image, or if analysis/generation fails |
| 103 | + public func generate(imageData: Data, metadata: MediaMetadata = MediaMetadata()) async throws -> String { |
| 104 | + guard let image = UIImage(data: imageData) else { |
| 105 | + throw NSError(domain: "IntelligenceService", code: -3, userInfo: [ |
| 106 | + NSLocalizedDescriptionKey: "Unable to create UIImage from data" |
| 107 | + ]) |
| 108 | + } |
| 109 | + return try await generate(image: image, metadata: metadata) |
| 110 | + } |
| 111 | + |
| 112 | + // MARK: - Session & Prompt Building |
| 113 | + |
| 114 | + /// Creates a language model session configured for alt text generation. |
| 115 | + /// |
| 116 | + /// - Returns: Configured session with instructions |
| 117 | + public func makeSession() -> LanguageModelSession { |
| 118 | + LanguageModelSession( |
| 119 | + model: .init(guardrails: .permissiveContentTransformations), |
| 120 | + instructions: Self.instructions |
| 121 | + ) |
| 122 | + } |
| 123 | + |
| 124 | + /// Instructions for the language model on how to generate alt text. |
| 125 | + public static var instructions: String { |
| 126 | + """ |
| 127 | + You are helping a WordPress user generate alt text for an image. |
| 128 | + Alt text should be concise, descriptive, and accessible for screen readers. |
| 129 | +
|
| 130 | + **Parameters** |
| 131 | + - IMAGE_ANALYSIS: Visual analysis of the actual image content (MOST IMPORTANT) |
| 132 | + - FILENAME: the image filename |
| 133 | + - FILE_TYPE: the file type/extension |
| 134 | + - DIMENSIONS: the image dimensions |
| 135 | + - TITLE: the image title (if available) |
| 136 | + - CAPTION: the image caption (if available) |
| 137 | + - DESCRIPTION: the image description (if available) |
| 138 | +
|
| 139 | + **Requirements** |
| 140 | + - Generate concise alt text (1-2 sentences, max 125 characters) |
| 141 | + - Prioritize IMAGE_ANALYSIS when describing what's in the image |
| 142 | + - Focus on what the image depicts, not decorative elements |
| 143 | + - Use simple, clear language |
| 144 | + - Do not include phrases like "image of" or "picture of" |
| 145 | + - Only output the alt text, nothing else |
| 146 | + """ |
| 147 | + } |
| 148 | + |
| 149 | + /// Builds the prompt for generating alt text. |
| 150 | + /// |
| 151 | + /// - Parameter metadata: The media metadata |
| 152 | + /// - Returns: Formatted prompt string ready for the language model |
| 153 | + public func makePrompt(metadata: MediaMetadata) -> String { |
| 154 | + var contextParts: [String] = [] |
| 155 | + |
| 156 | + if let imageAnalysis = metadata.imageAnalysis, !imageAnalysis.isEmpty { |
| 157 | + contextParts.append("IMAGE_ANALYSIS: '\(imageAnalysis)'") |
| 158 | + } |
| 159 | + if let filename = metadata.filename, !filename.isEmpty { |
| 160 | + contextParts.append("FILENAME: '\(filename)'") |
| 161 | + } |
| 162 | + if let fileType = metadata.fileType, !fileType.isEmpty { |
| 163 | + contextParts.append("FILE_TYPE: '\(fileType)'") |
| 164 | + } |
| 165 | + if let dimensions = metadata.dimensions, !dimensions.isEmpty { |
| 166 | + contextParts.append("DIMENSIONS: '\(dimensions)'") |
| 167 | + } |
| 168 | + if let title = metadata.title, !title.isEmpty { |
| 169 | + contextParts.append("TITLE: '\(title)'") |
| 170 | + } |
| 171 | + if let caption = metadata.caption, !caption.isEmpty { |
| 172 | + contextParts.append("CAPTION: '\(caption)'") |
| 173 | + } |
| 174 | + if let description = metadata.description, !description.isEmpty { |
| 175 | + contextParts.append("DESCRIPTION: '\(description)'") |
| 176 | + } |
| 177 | + |
| 178 | + return """ |
| 179 | + Generate alt text for an image with the following information: |
| 180 | +
|
| 181 | + \(contextParts.joined(separator: "\n")) |
| 182 | + """ |
| 183 | + } |
| 184 | +} |
| 185 | + |
| 186 | +@available(iOS 26, *) |
| 187 | +extension IntelligenceService { |
| 188 | + /// Generates alt text for a media item based on available metadata. |
| 189 | + /// |
| 190 | + /// - Parameter metadata: The media metadata to use for generation |
| 191 | + /// - Returns: Generated alt text |
| 192 | + /// - Throws: If metadata is insufficient or generation fails |
| 193 | + public func generateAltText(metadata: MediaMetadata) async throws -> String { |
| 194 | + try await ImageAltTextGenerator().generate(metadata: metadata) |
| 195 | + } |
| 196 | +} |
0 commit comments