forked from microsoft/Generative-AI-for-beginners-dotnet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImageGenerator.cs
More file actions
75 lines (63 loc) · 2.68 KB
/
Copy pathImageGenerator.cs
File metadata and controls
75 lines (63 loc) · 2.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using System.ComponentModel;
using System.Text;
using System.Text.Json;
using OpenAI;
using OpenAI.Images;
using System.ClientModel;
#pragma warning disable OPENAI001
namespace MAF_ImageGen_02;
public static class ImageGenerator
{
[Description("Generates an image from a prompt. Returns the absolute path to the saved image file.")]
public static async Task<string> GenerateImageFromPrompt(
[Description("The prompt to generate the image from.")]
string imageGenerationPrompt)
{
var builder = Host.CreateApplicationBuilder();
var config = builder.Configuration
.AddEnvironmentVariables()
.AddUserSecrets<Program>()
.Build();
// You will need to set these environment variables or edit the following values.
var endpoint = config["AzureOpenAI:Endpoint"] ?? throw new InvalidOperationException(
"Missing 'AzureOpenAI:Endpoint'. Run: dotnet user-secrets set \"AzureOpenAI:Endpoint\" \"https://<your-resource>.openai.azure.com/\"");
var deployment = config["FLUX_DEPLOYMENT_NAME"] ?? throw new InvalidOperationException(
"Missing 'FLUX_DEPLOYMENT_NAME'. Run: dotnet user-secrets set \"FLUX_DEPLOYMENT_NAME\" \"<your-flux-deployment>\"");
var apiKey = config["AZURE_OPENAI_API_KEY"] ?? throw new InvalidOperationException(
"Missing 'AZURE_OPENAI_API_KEY'. Run: dotnet user-secrets set \"AZURE_OPENAI_API_KEY\" \"<your-api-key>\"");
// Ensure endpoint ends with /openai/v1/
if (!endpoint.EndsWith("/openai/v1/"))
{
if (endpoint.EndsWith('/'))
{
endpoint += "openai/v1/";
}
else
{
endpoint += "/openai/v1/";
}
}
ImageClient client = new(
credential: new ApiKeyCredential(apiKey),
model: deployment,
options: new OpenAIClientOptions()
{
Endpoint = new Uri(endpoint),
}
);
ImageGenerationOptions options = new()
{
Size = GeneratedImageSize.W1024xH1024,
};
GeneratedImage image = await client.GenerateImageAsync(imageGenerationPrompt, options);
BinaryData bytes = image.ImageBytes;
var outputDir = Path.Combine(Environment.CurrentDirectory, "generated-images");
Directory.CreateDirectory(outputDir);
var fileName = $"image_{DateTime.UtcNow:yyyyMMdd_HHmmssfff}.jpg";
var filePath = Path.Combine(outputDir, fileName);
File.WriteAllBytes(filePath, bytes.ToArray());
return filePath;
}
}