Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added support for ImageEdit Request #135

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 32 additions & 15 deletions OpenAI_API/EndpointBase.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
using Newtonsoft.Json;
using OpenAI_API.Moderation;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Mime;
using System.Security.Authentication;
using System.Text;
using System.Threading.Tasks;
Expand Down Expand Up @@ -119,21 +122,35 @@ private async Task<HttpResponseMessage> HttpRequestRaw(string url = null, HttpMe

if (postData != null)
{
if (postData is HttpContent)
{
req.Content = postData as HttpContent;
}
else
{
string jsonContent = JsonConvert.SerializeObject(postData, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore });
var stringContent = new StringContent(jsonContent, UnicodeEncoding.UTF8, "application/json");
req.Content = stringContent;
}
}
response = await client.SendAsync(req, streaming ? HttpCompletionOption.ResponseHeadersRead : HttpCompletionOption.ResponseContentRead);

if (response.IsSuccessStatusCode)
{
if (postData is HttpContent)
{
req.Content = postData as HttpContent;
response = await client.SendAsync(req, streaming ? HttpCompletionOption.ResponseHeadersRead : HttpCompletionOption.ResponseContentRead);
}
else if (postData is OpenAI_API.Images.ImageEditRequest)
{
var data = postData as Images.ImageEditRequest;
byte[] byes_array = File.ReadAllBytes(data.Image);

MultipartFormDataContent formData = new MultipartFormDataContent
{
{ new ByteArrayContent(byes_array, 0, byes_array.Length), "image", "image.png"},
{ new StringContent(data.Prompt), "prompt" },
};

response = await client.PostAsync(url, formData);
}
else
{
string jsonContent = JsonConvert.SerializeObject(postData, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore });
var stringContent = new StringContent(jsonContent, UnicodeEncoding.UTF8, "application/json");
req.Content = stringContent;
response = await client.SendAsync(req, streaming ? HttpCompletionOption.ResponseHeadersRead : HttpCompletionOption.ResponseContentRead);
}
}

if (response.IsSuccessStatusCode)
{
return response;
}
else
Expand Down
17 changes: 17 additions & 0 deletions OpenAI_API/Images/IImageEditEndpoint.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
using System.Threading.Tasks;

namespace OpenAI_API.Images
{
/// <summary>
/// An interface for <see cref="IImageEditEndpoint"/>. Given a prompt, the model will generate a new image.
/// </summary>
public interface IImageEditEndpoint
{
/// <summary>
/// Ask the API to Creates an image given a prompt.
/// </summary>
/// <param name="request">Request to be send</param>
/// <returns>Asynchronously returns the image result. Look in its <see cref="Data.Url"/> </returns>
Task<ImageResult> EditImageAsync(ImageEditRequest request);
}
}
36 changes: 36 additions & 0 deletions OpenAI_API/Images/ImageEditEndpoint.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using OpenAI_API.Models;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace OpenAI_API.Images
{
/// <summary>
/// Given a prompt, the model will generate a new image.
/// </summary>
public class ImageEditEndpoint : EndpointBase, IImageEditEndpoint
{
/// <summary>
/// The name of the endpoint, which is the final path segment in the API URL. For example, "image".
/// </summary>
protected override string Endpoint { get { return "images/edits"; } }

/// <summary>
/// Constructor of the api endpoint. Rather than instantiating this yourself, access it through an instance of <see cref="OpenAIAPI"/> as <see cref="OpenAIAPI.ImageGenerations"/>.
/// </summary>
/// <param name="api"></param>
internal ImageEditEndpoint(OpenAIAPI api) : base(api) { }


/// <summary>
/// Ask the API to Creates an image given a prompt.
/// </summary>
/// <param name="request">Request to be send</param>
/// <returns>Asynchronously returns the image result. Look in its <see cref="Data.Url"/> </returns>
public async Task<ImageResult> EditImageAsync(ImageEditRequest request)
{
return await HttpPost<ImageResult>(postData: request);
}
}
}
90 changes: 90 additions & 0 deletions OpenAI_API/Images/ImageEditRequest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
using Newtonsoft.Json;
using OpenAI_API.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace OpenAI_API.Images
{
/// <summary>
/// Represents a request to the Images API. Mostly matches the parameters in <see href="https://platform.openai.com/docs/api-reference/images/create">the OpenAI docs</see>, although some have been renamed or expanded into single/multiple properties for ease of use.
/// </summary>
public class ImageEditRequest
{
/// <summary>
/// The image to edit. Must be a valid PNG file, less than 4MB, and square. If mask is not provided, image must have transparency, which will be used as the mask.
/// </summary>
[JsonProperty("image")]
public string Image { get; set; }

/// <summary>
/// An additional image whose fully transparent areas (e.g. where alpha is zero) indicate where image should be edited. Must be a valid PNG file, less than 4MB, and have the same.
/// </summary>
[JsonProperty("mask")]
public string Mask { get; set; }

/// <summary>
/// A text description of the desired image(s). The maximum length is 1000 characters.
/// </summary>
[JsonProperty("prompt")]
public string Prompt { get; set; }


[JsonProperty("n")]
public int? NumOfImages { get; set; } = 1;

/// <summary>
/// The size of the generated images. Must be one of 256x256, 512x512, or 1024x1024. Defauls to 1024x1024
/// </summary>
[JsonProperty("size"), JsonConverter(typeof(ImageSize.ImageSizeJsonConverter))]
public ImageSize Size { get; set; }

/// <summary>
/// The format in which the generated images are returned. Must be one of url or b64_json. Defaults to Url.
/// </summary>
[JsonProperty("response_format"), JsonConverter(typeof(ImageResponseFormat.ImageResponseJsonConverter))]
public ImageResponseFormat ResponseFormat { get; set; }

/// <summary>
/// A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. Optional.
/// </summary>
[JsonProperty("user")]
public string User { get; set; }


/// <summary>
/// Cretes a new, empty <see cref="ImageGenerationRequest"/>
/// </summary>
public ImageEditRequest()
{

}

/// <summary>
/// Creates a new <see cref="ImageEditRequest"/> with the specified parameters
/// </summary>
/// <param name="image"></param>
/// <param name="prompt">A text description of the desired image(s). The maximum length is 1000 characters.</param>
/// <param name="numOfImages">How many different choices to request for each prompt. Defaults to 1.</param>
/// <param name="size">The size of the generated images. Must be one of 256x256, 512x512, or 1024x1024.</param>
/// <param name="user">A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse.</param>
/// <param name="responseFormat">The format in which the generated images are returned. Must be one of url or b64_json.</param>
public ImageEditRequest(
string image,
string prompt,
int? numOfImages = 1,
ImageSize size = null,
string user = null,
ImageResponseFormat responseFormat = null)
{
this.Image = image;
this.Prompt = prompt;
this.NumOfImages = numOfImages;
this.User = user;
this.Size = size ?? ImageSize._1024;
this.ResponseFormat = responseFormat ?? ImageResponseFormat.Url;
}

}
}
10 changes: 8 additions & 2 deletions OpenAI_API/OpenAIAPI.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ public OpenAIAPI(APIAuthentication apiKeys = null)
Chat = new ChatEndpoint(this);
Moderation = new ModerationEndpoint(this);
ImageGenerations = new ImageGenerationEndpoint(this);
ImageEdit= new ImageEditEndpoint(this);
}

/// <summary>
Expand Down Expand Up @@ -100,6 +101,11 @@ public static OpenAIAPI ForAzure(string YourResourceName, string deploymentId, A
/// <summary>
/// The API lets you do operations with images. Given a prompt and/or an input image, the model will generate a new image.
/// </summary>
public IImageGenerationEndpoint ImageGenerations { get; }
}
public IImageGenerationEndpoint ImageGenerations { get; }

/// <summary>
/// The API lets you do operations with images. Given a prompt and an input image, the model will edit a new image.
/// </summary>
public IImageEditEndpoint ImageEdit { get; }
}
}
76 changes: 76 additions & 0 deletions OpenAI_Tests/ImageEditEndpointTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
using NUnit.Framework;
using OpenAI_API.Images;
using OpenAI_API.Moderation;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;

namespace OpenAI_Tests
{
public class ImageEditEndpointTests
{
[SetUp]
public void Setup()
{
OpenAI_API.APIAuthentication.Default = new OpenAI_API.APIAuthentication(Environment.GetEnvironmentVariable("TEST_OPENAI_SECRET_KEY"));
}

private string GetImage(string path)
{
byte[] imageArray = System.IO.File.ReadAllBytes(path);
string base64ImageRepresentation = Convert.ToBase64String(imageArray);
return base64ImageRepresentation;
}

[Test]
public void EditImage()
{
string imageFilepath = Path.Combine(AppContext.BaseDirectory, "images\\EditImage.png");
string prompt = "add flowers, digital art";

Assert.That(File.Exists(imageFilepath));
EditImage(imageFilepath, prompt);
}

private void EditImage(string imageFilepath, string prompt)
{
var api = new OpenAI_API.OpenAIAPI();

Assert.IsNotNull(api.ImageEdit);
Assert.IsTrue(File.Exists(imageFilepath));
var imageEditRequest = new ImageEditRequest(imageFilepath, prompt, 1, ImageSize._256);

ImageResult results = null;

try
{
results = api.ImageEdit.EditImageAsync(imageEditRequest).Result;
}
catch (Exception ex)
{
}

Assert.IsNotNull(results);
if (results.CreatedUnixTime.HasValue)
{
Assert.NotZero(results.CreatedUnixTime.Value);
Assert.NotNull(results.Created);
Assert.Greater(results.Created.Value, new DateTime(2018, 1, 1));
Assert.Less(results.Created.Value, DateTime.Now.AddDays(1));
}
else
{
Assert.Null(results.Created);
}

Assert.NotZero(results.Data.Count);
Assert.NotNull(results.Data.First().Url);
Assert.That(results.Data.First().Url.Length > 0);
Assert.That(results.Data.First().Url.StartsWith("https://"));
}
}
}
7 changes: 7 additions & 0 deletions OpenAI_Tests/OpenAI_Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,13 @@
<None Update="fine-tuning-data.jsonl">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="images\EditImage.png">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>

<ItemGroup>
<Folder Include="images\" />
</ItemGroup>

</Project>
Binary file added OpenAI_Tests/images/EditImage.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.