Skip to content

Instantly share code, notes, and snippets.

@copypastedeveloper
Last active April 10, 2024 16:49
Show Gist options
  • Select an option

  • Save copypastedeveloper/7bc538687957e5e8124f1562f135cfc9 to your computer and use it in GitHub Desktop.

Select an option

Save copypastedeveloper/7bc538687957e5e8124f1562f135cfc9 to your computer and use it in GitHub Desktop.
feet with with .net goes kinda hard
namespace FeetWithWith;
public class FootMan : IMakeFeet
{
readonly HttpClient _httpClient;
readonly string _apiKey; // Your OpenAI API key
readonly string _dalleApiUrl = "https://api.openai.com/v1/images/generations";
readonly string _gptApiUrl = "https://api.openai.com/v1/completions";
public FootMan(string apiKey)
{
_httpClient = new HttpClient();
_apiKey = apiKey;
// Configure the HttpClient for OpenAI API
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _apiKey);
}
public async Task<byte[]> Imagine()
{
var randomObject = await GenerateRandomObject();
var description = $"an image of feet with {randomObject}";
var imageBytes = await GenerateImage(description);
return imageBytes;
}
async Task<string> GenerateRandomObject()
{
var prompt = "Provide a random object to pair with feet in an image:";
var requestData = new
{
model = "gpt-3.5-turbo",
prompt = prompt,
temperature = 0.7,
max_tokens = 60
};
var content = new StringContent(JsonSerializer.Serialize(requestData), System.Text.Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync(_gptApiUrl, content);
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync();
var responseJson = JsonSerializer.Deserialize<JsonElement>(responseBody);
var objectDescription = responseJson.GetProperty("choices")[0].GetProperty("text").GetString().Trim();
return objectDescription;
}
async Task<byte[]> GenerateImage(string description)
{
var requestData = new
{
prompt = $"{description} -- BUT ALWAYS INCLUDE 2 FEET CENTERED IN THE FOREGROUND.",
n = 1, // Number of images to generate
size = "1024x1024" // Image size
};
var content = new StringContent(JsonSerializer.Serialize(requestData), System.Text.Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync(_dalleApiUrl, content);
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync();
var imageInfo = JsonSerializer.Deserialize<GeneratedImageResponse>(responseBody);
var imageUrl = imageInfo?.Data?.Urls?[0];
return await _httpClient.GetByteArrayAsync(imageUrl);
}
class GeneratedImageResponse
{
public GeneratedImageData Data { get; set; }
}
class GeneratedImageData
{
public string[] Urls { get; set; }
}
}
public interface IMakeFeet
{
Task<byte[]> Imagine();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment