Skip to content

Commit a39c281

Browse files
Added Dall-E API examples
1 parent 966e325 commit a39c281

16 files changed

Lines changed: 705 additions & 0 deletions

Misc/Dall-E/README.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
# Fun with Dall-E
2+
3+
This repo contains a series of small apps designed to interface with the Dall-E API in different platforms, and generate images using text prompts. The examples correspond to the tutorial videos on `Fun with Dall-E` at **ParametricCamp**: [https://www.youtube.com/playlist?list=PLx3k0RGeXZ_zs3az0Z2BnpTIPH2lxQfFX](https://www.youtube.com/playlist?list=PLx3k0RGeXZ_zs3az0Z2BnpTIPH2lxQfFX)
4+
5+
Most of these examples were developed in Novemeber 2022. The API might have changed, make sure to check the documentation.
6+
7+
See the videos for instruction on how to setup and run the examples.
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
<?xml version="1.0" encoding="utf-8" ?>
2+
<configuration>
3+
<startup>
4+
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
5+
</startup>
6+
</configuration>
Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Drawing;
4+
using System.IO;
5+
using System.Linq;
6+
using System.Net;
7+
using System.Text;
8+
using System.Threading.Tasks;
9+
10+
using Newtonsoft.Json;
11+
12+
namespace dalle_api
13+
{
14+
internal class Program
15+
{
16+
static void Main(string[] args)
17+
{
18+
19+
string url = "https://api.openai.com/v1/images/generations";
20+
string bearerToken = Environment.GetEnvironmentVariable("OPENAI_API_KEY");
21+
//string body = "{\"prompt\": \"an isometric view of a miniature city, tilt shift, bokeh, voxel, vray render, high detail\",\"n\": 2,\"size\": \"1024x1024\"}";
22+
string body = "{\"prompt\": \"an isometric view of a miniature city, tilt shift, bokeh, voxel, vray render, high detail\",\"n\": 2,\"size\": \"256x256\",\"response_format\":\"b64_json\"}";
23+
24+
// Prepare data for the POST request
25+
var data = Encoding.ASCII.GetBytes(body);
26+
Console.WriteLine(data);
27+
28+
var request = (HttpWebRequest) WebRequest.Create(url);
29+
request.Method = "POST";
30+
request.ContentType = "application/json";
31+
request.ContentLength = data.Length;
32+
33+
// Authentication
34+
if (bearerToken != null)
35+
{
36+
ServicePointManager.Expect100Continue = true;
37+
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
38+
39+
request.PreAuthenticate = true;
40+
request.Headers.Add("Authorization", "Bearer " + bearerToken);
41+
}
42+
else
43+
{
44+
request.Credentials = CredentialCache.DefaultCredentials;
45+
}
46+
47+
// Perform request
48+
using (var stream = request.GetRequestStream())
49+
{
50+
stream.Write(data, 0, data.Length);
51+
}
52+
53+
// Retrieve response
54+
var response = (HttpWebResponse)request.GetResponse();
55+
Console.WriteLine("Request response: " + response.StatusCode);
56+
57+
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
58+
//Console.WriteLine(responseString);
59+
60+
61+
// Deserialize JSON
62+
dynamic responseJson = JsonConvert.DeserializeObject<dynamic>(responseString);
63+
64+
////Console.WriteLine(responseJson);
65+
//Console.WriteLine(responseJson.created);
66+
//Console.WriteLine(responseJson.data);
67+
//Console.WriteLine(responseJson.data[0].url);
68+
//Console.WriteLine(responseJson.data[1].url);
69+
70+
for (int i =0; i < responseJson.data.Count; i++)
71+
{
72+
string base64 = responseJson.data[i].b64_json;
73+
//Console.WriteLine(base64);
74+
75+
Bitmap img = Base64StringToBitmap(base64);
76+
77+
long unixTime = ((DateTimeOffset)DateTime.Now).ToUnixTimeSeconds();
78+
string filename = string.Format("image_{0}_{1}.png", unixTime, i);
79+
80+
img.Save(filename);
81+
Console.WriteLine("Saving image to " + filename);
82+
}
83+
84+
Console.ReadKey();
85+
}
86+
87+
// From https://softwarebydefault.com/2013/03/01/base64-strings-bitmap/
88+
public static Bitmap Base64StringToBitmap(string base64String)
89+
{
90+
Bitmap bmpReturn = null;
91+
92+
byte[] byteBuffer = Convert.FromBase64String(base64String);
93+
MemoryStream memoryStream = new MemoryStream(byteBuffer);
94+
95+
memoryStream.Position = 0;
96+
97+
bmpReturn = (Bitmap)Bitmap.FromStream(memoryStream);
98+
99+
memoryStream.Close();
100+
memoryStream = null;
101+
byteBuffer = null;
102+
103+
return bmpReturn;
104+
}
105+
}
106+
}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
using System.Reflection;
2+
using System.Runtime.CompilerServices;
3+
using System.Runtime.InteropServices;
4+
5+
// General Information about an assembly is controlled through the following
6+
// set of attributes. Change these attribute values to modify the information
7+
// associated with an assembly.
8+
[assembly: AssemblyTitle("dalle-api")]
9+
[assembly: AssemblyDescription("")]
10+
[assembly: AssemblyConfiguration("")]
11+
[assembly: AssemblyCompany("")]
12+
[assembly: AssemblyProduct("dalle-api")]
13+
[assembly: AssemblyCopyright("Copyright © 2022")]
14+
[assembly: AssemblyTrademark("")]
15+
[assembly: AssemblyCulture("")]
16+
17+
// Setting ComVisible to false makes the types in this assembly not visible
18+
// to COM components. If you need to access a type in this assembly from
19+
// COM, set the ComVisible attribute to true on that type.
20+
[assembly: ComVisible(false)]
21+
22+
// The following GUID is for the ID of the typelib if this project is exposed to COM
23+
[assembly: Guid("e86c7d60-d2af-440f-b85b-78dd52e7e43b")]
24+
25+
// Version information for an assembly consists of the following four values:
26+
//
27+
// Major Version
28+
// Minor Version
29+
// Build Number
30+
// Revision
31+
//
32+
// You can specify all the values or you can default the Build and Revision Numbers
33+
// by using the '*' as shown below:
34+
// [assembly: AssemblyVersion("1.0.*")]
35+
[assembly: AssemblyVersion("1.0.0.0")]
36+
[assembly: AssemblyFileVersion("1.0.0.0")]
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
<?xml version="1.0" encoding="utf-8"?>
2+
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
3+
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
4+
<PropertyGroup>
5+
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
6+
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
7+
<ProjectGuid>{E86C7D60-D2AF-440F-B85B-78DD52E7E43B}</ProjectGuid>
8+
<OutputType>Exe</OutputType>
9+
<RootNamespace>dalle_api</RootNamespace>
10+
<AssemblyName>dalle-api</AssemblyName>
11+
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
12+
<FileAlignment>512</FileAlignment>
13+
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
14+
<Deterministic>true</Deterministic>
15+
</PropertyGroup>
16+
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
17+
<PlatformTarget>AnyCPU</PlatformTarget>
18+
<DebugSymbols>true</DebugSymbols>
19+
<DebugType>full</DebugType>
20+
<Optimize>false</Optimize>
21+
<OutputPath>bin\Debug\</OutputPath>
22+
<DefineConstants>DEBUG;TRACE</DefineConstants>
23+
<ErrorReport>prompt</ErrorReport>
24+
<WarningLevel>4</WarningLevel>
25+
</PropertyGroup>
26+
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
27+
<PlatformTarget>AnyCPU</PlatformTarget>
28+
<DebugType>pdbonly</DebugType>
29+
<Optimize>true</Optimize>
30+
<OutputPath>bin\Release\</OutputPath>
31+
<DefineConstants>TRACE</DefineConstants>
32+
<ErrorReport>prompt</ErrorReport>
33+
<WarningLevel>4</WarningLevel>
34+
</PropertyGroup>
35+
<ItemGroup>
36+
<Reference Include="Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
37+
<HintPath>packages\Newtonsoft.Json.13.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
38+
</Reference>
39+
<Reference Include="System" />
40+
<Reference Include="System.Core" />
41+
<Reference Include="System.Drawing" />
42+
<Reference Include="System.Xml.Linq" />
43+
<Reference Include="System.Data.DataSetExtensions" />
44+
<Reference Include="Microsoft.CSharp" />
45+
<Reference Include="System.Data" />
46+
<Reference Include="System.Net.Http" />
47+
<Reference Include="System.Xml" />
48+
</ItemGroup>
49+
<ItemGroup>
50+
<Compile Include="Program.cs" />
51+
<Compile Include="Properties\AssemblyInfo.cs" />
52+
</ItemGroup>
53+
<ItemGroup>
54+
<None Include="App.config" />
55+
<None Include="packages.config" />
56+
</ItemGroup>
57+
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
58+
</Project>
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
2+
Microsoft Visual Studio Solution File, Format Version 12.00
3+
# Visual Studio Version 17
4+
VisualStudioVersion = 17.3.32922.545
5+
MinimumVisualStudioVersion = 10.0.40219.1
6+
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "dalle-api", "dalle-api.csproj", "{E86C7D60-D2AF-440F-B85B-78DD52E7E43B}"
7+
EndProject
8+
Global
9+
GlobalSection(SolutionConfigurationPlatforms) = preSolution
10+
Debug|Any CPU = Debug|Any CPU
11+
Release|Any CPU = Release|Any CPU
12+
EndGlobalSection
13+
GlobalSection(ProjectConfigurationPlatforms) = postSolution
14+
{E86C7D60-D2AF-440F-B85B-78DD52E7E43B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15+
{E86C7D60-D2AF-440F-B85B-78DD52E7E43B}.Debug|Any CPU.Build.0 = Debug|Any CPU
16+
{E86C7D60-D2AF-440F-B85B-78DD52E7E43B}.Release|Any CPU.ActiveCfg = Release|Any CPU
17+
{E86C7D60-D2AF-440F-B85B-78DD52E7E43B}.Release|Any CPU.Build.0 = Release|Any CPU
18+
EndGlobalSection
19+
GlobalSection(SolutionProperties) = preSolution
20+
HideSolutionNode = FALSE
21+
EndGlobalSection
22+
GlobalSection(ExtensibilityGlobals) = postSolution
23+
SolutionGuid = {CDFEF583-76F7-48BC-8258-77F11BE7D2A3}
24+
EndGlobalSection
25+
EndGlobal
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<?xml version="1.0" encoding="utf-8"?>
2+
<packages>
3+
<package id="Newtonsoft.Json" version="13.0.1" targetFramework="net472" />
4+
</packages>
9.69 MB
Binary file not shown.
10.9 KB
Binary file not shown.
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
const { Configuration, OpenAIApi } = require("openai");
2+
const fs = require('fs');
3+
const commandLineArgs = require('command-line-args');
4+
5+
const optionDefinitions = [
6+
{ name: 'prompt', alias: 'p', type: String, defaultValue: "an isometric view of a miniature city, tilt shift, bokeh, voxel, vray render, high detail" },
7+
{ name: 'number', alias: 'n', type: Number, defaultValue: 1 },
8+
{ name: 'size', alias: 's', type: Number, defaultValue: 256 },
9+
];
10+
11+
const options = commandLineArgs(optionDefinitions);
12+
13+
const key = process.env.OPENAI_API_KEY;
14+
15+
const configuration = new Configuration({
16+
apiKey: key
17+
});
18+
const openai = new OpenAIApi(configuration);
19+
20+
21+
const predict = async function () {
22+
const response = await openai.createImage({
23+
prompt: options.prompt,
24+
n: options.number,
25+
size: `${options.size}x${options.size}`,
26+
response_format: 'b64_json',
27+
});
28+
29+
return response.data;
30+
}
31+
32+
33+
predict()
34+
.then(
35+
response => {
36+
const now = Date.now();
37+
for (let i = 0; i < response.data.length; i++) {
38+
const b64 = response.data[i]['b64_json'];
39+
const buffer = Buffer.from(b64, "base64");
40+
const filename = `image_${now}_${i}.png`;
41+
console.log("Writing image " + filename);
42+
fs.writeFileSync(filename, buffer);
43+
}
44+
}
45+
)
46+

0 commit comments

Comments
 (0)