Generate Image by Using PowerShell and DALL on macOS
This article explains how to use PowerShell on macOS to create an image from a text prompt using the OpenAI model called DALL-E-2.
Table of Contents
- Use Case
- Precondition
- Implementation
Use Case
Image can be generated by using PowerShell directly.
As the PowerShell console can not display the image, browser will be automatically opened to show the image.
i.e., Running following commands, your browser will be opened and a image will be shown, the image is similar like that one from the top of this article.
Precondition
- Install PowerShell on macOS
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
brew install powershell/tap/powershell
2. Get your OpenAI API Key from https://platform.openai.com/
Implementation
We implemented two PowerShell Scripts.
The SetOpenAIKey.ps1 can set OpenAI API KEY as environment variable, the variable will be available in the same PowerShell session. i.e., once your close the terminal, you need run it again.
The DTS_OpenAI_DALL.ps1 can accept your prompt, generate the image and show it in a browser.
# SetOpenAIKey.ps1
param(
[Parameter(Mandatory=$true)]
[string]$apiKey
)
$env:OPENAI_API_KEY = $apiKey
Write-Output "OpenAI API key set successfully"
# DTS_OpenAI_DALL.ps1
param(
[string]$prompt = "Welcome to the world of AI"
)
# Check if the API key is already stored in the environment variables
if (-not $env:OPENAI_API_KEY) {
# If not, ask the user to input it
$env:OPENAI_API_KEY = Read-Host -Prompt "Input your OpenAI API key"
}
$body = @{
model = "dall-e-2"
prompt = $prompt
n = 1
size = "1024x1024"
} | ConvertTo-Json
$headers = @{
"Content-Type" = "application/json"
"Authorization" = "Bearer $env:OPENAI_API_KEY"
}
$response = Invoke-RestMethod -Uri "https://api.openai.com/v1/images/generations" -Method Post -Body $body -Headers $headers
Start-Process $response.data[0].url
Then, please run following command to test it.
# Open terminal and go to your project path
# Run following command please
chmod +x *.ps1
pwsh
./SetOpenAIKey.ps1 REPLACE_YOUR_OPENAI_API_KEY_HERE
./DTS_OpenAI_DALL.ps1 -prompt "Snowboarding on a mountain on a snowy day."
I hope you enjoyed today’s content.
You are welcome to connect with me on medium and datatec.studio.
Your claps 👏 keep me continue writing high-quality articles. Thank you!