|
| 1 | +using Microsoft.Extensions.AI; |
| 2 | +using SixLabors.ImageSharp; |
| 3 | +using SixLabors.ImageSharp.Formats; |
| 4 | +using SixLabors.ImageSharp.Processing; |
| 5 | + |
| 6 | +namespace DotCraft.Agents; |
| 7 | + |
| 8 | +internal static class ModelImageInputPreparer |
| 9 | +{ |
| 10 | + internal const string CouldNotProcessPlaceholder = "image content omitted because it could not be processed"; |
| 11 | + internal const string TooLargePlaceholder = "image content omitted because it exceeded the supported size limit"; |
| 12 | + |
| 13 | + private const int MaxInputBytes = 64 * 1024 * 1024; |
| 14 | + private const int MaxDimension = 2048; |
| 15 | + private const int PatchSize = 32; |
| 16 | + private const int MaxPatches = 2500; |
| 17 | + |
| 18 | + public static bool IsImageMediaType(string? mediaType) => |
| 19 | + mediaType?.StartsWith("image/", StringComparison.OrdinalIgnoreCase) == true; |
| 20 | + |
| 21 | + public static bool IsSupportedRemoteImageMediaType(string? mediaType) => |
| 22 | + IsSupportedProviderImageMediaType(NormalizeMediaType(mediaType)); |
| 23 | + |
| 24 | + public static PreparedModelImageInput Prepare(DataContent source) |
| 25 | + { |
| 26 | + if (!IsImageMediaType(source.MediaType)) |
| 27 | + return PreparedModelImageInput.Placeholder(CouldNotProcessPlaceholder); |
| 28 | + |
| 29 | + if (source.Data.Length == 0 || source.Data.Length > MaxInputBytes) |
| 30 | + return PreparedModelImageInput.Placeholder(TooLargePlaceholder); |
| 31 | + |
| 32 | + var bytes = source.Data.ToArray(); |
| 33 | + try |
| 34 | + { |
| 35 | + var detectedFormat = Image.DetectFormat(bytes); |
| 36 | + var detectedMediaType = NormalizeMediaType(detectedFormat.DefaultMimeType); |
| 37 | + var info = Image.Identify(bytes); |
| 38 | + if (info == null || info.Width <= 0 || info.Height <= 0) |
| 39 | + return PreparedModelImageInput.Placeholder(CouldNotProcessPlaceholder); |
| 40 | + |
| 41 | + var targetSize = CalculateTargetSize(info.Width, info.Height); |
| 42 | + var canPreserveSource = CanPreserveSourceBytes(detectedMediaType); |
| 43 | + if (canPreserveSource && targetSize.Width == info.Width && targetSize.Height == info.Height) |
| 44 | + return PreparedModelImageInput.Image(CopyMetadata(source, new DataContent(bytes, detectedMediaType))); |
| 45 | + |
| 46 | + using var image = Image.Load(bytes); |
| 47 | + if (targetSize.Width != image.Width || targetSize.Height != image.Height) |
| 48 | + { |
| 49 | + image.Mutate(context => context.Resize(targetSize.Width, targetSize.Height)); |
| 50 | + } |
| 51 | + |
| 52 | + var outputMediaType = canPreserveSource ? detectedMediaType : "image/png"; |
| 53 | + using var output = new MemoryStream(); |
| 54 | + SaveImage(image, output, outputMediaType); |
| 55 | + return PreparedModelImageInput.Image(CopyMetadata(source, new DataContent(output.ToArray(), outputMediaType))); |
| 56 | + } |
| 57 | + catch (Exception ex) when (IsImagePreparationException(ex)) |
| 58 | + { |
| 59 | + return PreparedModelImageInput.Placeholder(CouldNotProcessPlaceholder); |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + private static Size CalculateTargetSize(int width, int height) |
| 64 | + { |
| 65 | + var scale = 1.0; |
| 66 | + var maxSide = Math.Max(width, height); |
| 67 | + if (maxSide > MaxDimension) |
| 68 | + scale = Math.Min(scale, MaxDimension / (double)maxSide); |
| 69 | + |
| 70 | + var patchBudgetPixels = MaxPatches * PatchSize * PatchSize; |
| 71 | + var pixelCount = (long)width * height; |
| 72 | + if (pixelCount > patchBudgetPixels) |
| 73 | + scale = Math.Min(scale, Math.Sqrt(patchBudgetPixels / (double)pixelCount)); |
| 74 | + |
| 75 | + var targetWidth = Math.Max(1, (int)Math.Floor(width * scale)); |
| 76 | + var targetHeight = Math.Max(1, (int)Math.Floor(height * scale)); |
| 77 | + |
| 78 | + while (CountPatches(targetWidth, targetHeight) > MaxPatches) |
| 79 | + { |
| 80 | + scale *= 0.98; |
| 81 | + targetWidth = Math.Max(1, (int)Math.Floor(width * scale)); |
| 82 | + targetHeight = Math.Max(1, (int)Math.Floor(height * scale)); |
| 83 | + } |
| 84 | + |
| 85 | + return new Size(targetWidth, targetHeight); |
| 86 | + } |
| 87 | + |
| 88 | + private static long CountPatches(int width, int height) => |
| 89 | + ((long)(width + PatchSize - 1) / PatchSize) * ((height + PatchSize - 1) / PatchSize); |
| 90 | + |
| 91 | + private static bool CanPreserveSourceBytes(string mediaType) => |
| 92 | + string.Equals(mediaType, "image/png", StringComparison.OrdinalIgnoreCase) || |
| 93 | + string.Equals(mediaType, "image/jpeg", StringComparison.OrdinalIgnoreCase) || |
| 94 | + string.Equals(mediaType, "image/webp", StringComparison.OrdinalIgnoreCase); |
| 95 | + |
| 96 | + private static bool IsSupportedProviderImageMediaType(string mediaType) => |
| 97 | + CanPreserveSourceBytes(mediaType) || |
| 98 | + string.Equals(mediaType, "image/gif", StringComparison.OrdinalIgnoreCase); |
| 99 | + |
| 100 | + private static void SaveImage(Image image, Stream output, string mediaType) |
| 101 | + { |
| 102 | + switch (mediaType) |
| 103 | + { |
| 104 | + case "image/jpeg": |
| 105 | + image.SaveAsJpeg(output); |
| 106 | + break; |
| 107 | + case "image/webp": |
| 108 | + image.SaveAsWebp(output); |
| 109 | + break; |
| 110 | + default: |
| 111 | + image.SaveAsPng(output); |
| 112 | + break; |
| 113 | + } |
| 114 | + } |
| 115 | + |
| 116 | + private static DataContent CopyMetadata(DataContent source, DataContent prepared) |
| 117 | + { |
| 118 | + if (source.AdditionalProperties is not { Count: > 0 } additionalProperties) |
| 119 | + return prepared; |
| 120 | + |
| 121 | + prepared.AdditionalProperties ??= new AdditionalPropertiesDictionary(); |
| 122 | + foreach (var (key, value) in additionalProperties) |
| 123 | + prepared.AdditionalProperties[key] = value; |
| 124 | + return prepared; |
| 125 | + } |
| 126 | + |
| 127 | + private static bool IsImagePreparationException(Exception ex) => |
| 128 | + ex is ArgumentException |
| 129 | + or InvalidImageContentException |
| 130 | + or ImageFormatException |
| 131 | + or NotSupportedException |
| 132 | + or UnknownImageFormatException; |
| 133 | + |
| 134 | + private static string NormalizeMediaType(string? mediaType) => |
| 135 | + string.IsNullOrWhiteSpace(mediaType) |
| 136 | + ? "application/octet-stream" |
| 137 | + : mediaType.Trim().ToLowerInvariant(); |
| 138 | + |
| 139 | + internal sealed record PreparedModelImageInput(DataContent? Content, string? PlaceholderText) |
| 140 | + { |
| 141 | + public bool HasImage => Content != null; |
| 142 | + |
| 143 | + public static PreparedModelImageInput Image(DataContent content) => new(content, null); |
| 144 | + |
| 145 | + public static PreparedModelImageInput Placeholder(string text) => new(null, text); |
| 146 | + } |
| 147 | +} |
0 commit comments