|
| 1 | +#pragma warning disable MEAI001 |
| 2 | +using System; |
| 3 | +using System.Collections.Generic; |
| 4 | +using System.Drawing; |
| 5 | +using System.Linq; |
| 6 | +using System.Threading; |
| 7 | +using System.Threading.Tasks; |
| 8 | +using GenerativeAI; |
| 9 | +using GenerativeAI.Core; |
| 10 | +using GenerativeAI.Types; |
| 11 | +using GenerativeAI.Clients; |
| 12 | +using GenerativeAI.Microsoft.Extensions; |
| 13 | +using Microsoft.Extensions.AI; |
| 14 | + |
| 15 | +namespace GenerativeAI.Microsoft; |
| 16 | + |
| 17 | +/// <summary> |
| 18 | +/// Implements Microsoft.Extensions.AI.IImageGenerator by creating an ImagenModel via GenAI.CreateImageModel |
| 19 | +/// and calling <see cref="GenerativeAI.Clients.ImagenModel.GenerateImagesAsync(GenerateImageRequest, CancellationToken)"/>. |
| 20 | +/// </summary> |
| 21 | +public sealed class GenerativeAIImagenGenerator : IImageGenerator |
| 22 | +{ |
| 23 | + /// <summary> |
| 24 | + /// Underlying ImagenModel instance created from the provided GenAI factory. |
| 25 | + /// </summary> |
| 26 | + public ImagenModel model { get; } |
| 27 | + |
| 28 | + /// <summary> |
| 29 | + /// Creates a new instance using an API key and optional model name. |
| 30 | + /// </summary> |
| 31 | + public GenerativeAIImagenGenerator(string apiKey, string modelName = GoogleAIModels.Imagen.Imagen3Generate002): |
| 32 | + this(new GoogleAi(apiKey), modelName) |
| 33 | + { } |
| 34 | + |
| 35 | + |
| 36 | + /// <summary> |
| 37 | + /// Creates a new instance using an existing <see cref="GenAI"/> factory and optional model name. |
| 38 | + /// </summary> |
| 39 | + public GenerativeAIImagenGenerator(GenAI genai, string modelName = GoogleAIModels.Imagen.Imagen3Generate002) |
| 40 | + { |
| 41 | +#if NET6_0_OR_GREATER |
| 42 | + ArgumentNullException.ThrowIfNull(genai); |
| 43 | +#else |
| 44 | + if (genai == null) throw new ArgumentNullException(nameof(genai)); |
| 45 | +#endif |
| 46 | + model = genai.CreateImageModel(modelName); |
| 47 | + } |
| 48 | + |
| 49 | + /// <inheritdoc/> |
| 50 | + public void Dispose() |
| 51 | + { } |
| 52 | + |
| 53 | + /// <inheritdoc/> |
| 54 | + public object? GetService(Type serviceType, object? serviceKey = null) |
| 55 | + { |
| 56 | + if (serviceKey == null && serviceType?.IsInstanceOfType(this) == true) |
| 57 | + return this; |
| 58 | + return null; |
| 59 | + } |
| 60 | + |
| 61 | + /// <inheritdoc/> |
| 62 | + public async Task<ImageGenerationResponse> GenerateAsync(ImageGenerationRequest request, |
| 63 | + ImageGenerationOptions? options = null, CancellationToken cancellationToken = default) |
| 64 | + { |
| 65 | +#if NET6_0_OR_GREATER |
| 66 | + ArgumentNullException.ThrowIfNull(request); |
| 67 | +#else |
| 68 | + if (request == null) throw new ArgumentNullException(nameof(request)); |
| 69 | +#endif |
| 70 | + |
| 71 | + var imgRequest = ToGenerateImageRequest(request, options); |
| 72 | + var resp = await model.GenerateImagesAsync(imgRequest, cancellationToken).ConfigureAwait(false); |
| 73 | + return ToImageGenerationResponse(resp); |
| 74 | + } |
| 75 | + |
| 76 | + // Convert Microsoft ImageGenerationRequest + options to a GenerateImageRequest |
| 77 | + private GenerateImageRequest ToGenerateImageRequest(ImageGenerationRequest request, ImageGenerationOptions? options) |
| 78 | + { |
| 79 | + var imgRequest = new GenerateImageRequest(); |
| 80 | + var instances = new List<ImageGenerationInstance>(); |
| 81 | + |
| 82 | + if (request.OriginalImages != null && request.OriginalImages.Any()) |
| 83 | + { |
| 84 | + instances.AddRange(request.OriginalImages.Select(content => new ImageGenerationInstance |
| 85 | + { |
| 86 | + Prompt = request.Prompt, |
| 87 | + Image = ConvertAiContentToImageSource(content) |
| 88 | + })); |
| 89 | + } |
| 90 | + else |
| 91 | + { |
| 92 | + instances.Add(new ImageGenerationInstance { Prompt = request.Prompt }); |
| 93 | + } |
| 94 | + |
| 95 | + ImageGenerationParameters parameters = options?.RawRepresentationFactory?.Invoke(this) as ImageGenerationParameters ?? new(); |
| 96 | + parameters.SampleCount = options?.Count ?? 1; |
| 97 | + |
| 98 | + if (options != null) |
| 99 | + { |
| 100 | + if (!string.IsNullOrEmpty(options.MediaType)) |
| 101 | + { |
| 102 | + parameters.OutputOptions = new OutputOptions { MimeType = options.MediaType }; |
| 103 | + } |
| 104 | + |
| 105 | + if (options.ImageSize.HasValue) |
| 106 | + { |
| 107 | + var sz = options.ImageSize.Value; |
| 108 | + parameters.AspectRatio = $"{sz.Width}:{sz.Height}"; |
| 109 | + |
| 110 | + } |
| 111 | + } |
| 112 | + |
| 113 | + return new GenerateImageRequest |
| 114 | + { |
| 115 | + Instances = instances, |
| 116 | + Parameters = parameters |
| 117 | + }; |
| 118 | + } |
| 119 | + |
| 120 | + // Convert model response to Microsoft ImageGenerationResponse |
| 121 | + private static ImageGenerationResponse ToImageGenerationResponse(GenerateImageResponse? resp) |
| 122 | + { |
| 123 | + var contents = new List<AIContent>(); |
| 124 | + if (resp?.Predictions != null) |
| 125 | + { |
| 126 | + foreach (var pred in resp.Predictions) |
| 127 | + { |
| 128 | + if (!string.IsNullOrEmpty(pred.BytesBase64Encoded)) |
| 129 | + { |
| 130 | + var data = Convert.FromBase64String(pred.BytesBase64Encoded); |
| 131 | + contents.Add(new DataContent(data, pred.MimeType ?? "image/png")); |
| 132 | + } |
| 133 | + } |
| 134 | + } |
| 135 | + |
| 136 | + return new ImageGenerationResponse(contents) { RawRepresentation = resp }; |
| 137 | + } |
| 138 | + |
| 139 | + private static ImageSource? ConvertAiContentToImageSource(AIContent content) |
| 140 | + { |
| 141 | + if (content == null) return null; |
| 142 | + |
| 143 | + if (content is DataContent dc) |
| 144 | + { |
| 145 | + return new ImageSource { BytesBase64Encoded = Convert.ToBase64String(dc.Data.ToArray()) }; |
| 146 | + } |
| 147 | + |
| 148 | + if (content is UriContent uc) |
| 149 | + { |
| 150 | + var uriVal = uc.Uri?.ToString(); |
| 151 | + |
| 152 | + // Only treat known GCS URIs as storage references for Imagen API. |
| 153 | + if (uriVal?.StartsWith("gs://", StringComparison.OrdinalIgnoreCase) == true || |
| 154 | + uriVal?.IndexOf("storage.googleapis.com", StringComparison.OrdinalIgnoreCase) >= 0) |
| 155 | + { |
| 156 | + return new ImageSource { GcsUri = uriVal }; |
| 157 | + } |
| 158 | + } |
| 159 | + |
| 160 | + return null; |
| 161 | + } |
| 162 | +} |
| 163 | +#pragma warning restore MEAI001 |
0 commit comments