Skip to content

Instantly share code, notes, and snippets.

@marzme
Last active November 21, 2023 22:14
Show Gist options
  • Save marzme/1e2e3826d5ea689f8716bfb1070c5974 to your computer and use it in GitHub Desktop.
Save marzme/1e2e3826d5ea689f8716bfb1070c5974 to your computer and use it in GitHub Desktop.
Random Image Creator using OpenAI API
# Define the relevant variables
$APIKey = "<YOUR API KEY HERE>"
$DownloadsPath = (New-Object -ComObject Shell.Application).NameSpace('shell:Downloads').Self.Path
$ChatAPIUrl = "https://api.openAI.com/v1/chat/completions"
$ChatAPIModel = "gpt-3.5-turbo-16k"
$ImageAPIUrl = "https://api.openai.com/v1/images/generations"
$ImageAPIModel = "dall-e-3"
$ImageSize = "1792x1024" # 1024x1024
$ImageQuality = "hd" # standard
$NumImages = 1
$UserPrompt = "<PUT WHATEVER PROMPT YOU WANT HERE> Eg: Come up with a concept image that's completely unique and original, with a clear and specific theme of your choosing. The image should have coherent composition that's easily readable, and a limited but strong bold contrasting color palette. Make it visually exciting but do not oversaturate the colors. Do NOT use these exact words in your description."
$ChatSystemMessage = @"
This is an "AI Image Description" GPT which generates unique, highly original, elaborate, and wonderfully creative descriptions of images. These descriptions will then be fed directly into an AI Image Generator to create images based on the provided descriptions.
## Important Notes
- Each description is a single paragraph and must always adhere to a 500-character limit.
- Always generate only one description, unless otherwise specified by the user.
- The GPT assistant must pay careful attention to the information in the prompt given by the user, and ensure that the descriptions generated include the style, tone, and all of the elements requested by the user.
## Example 1:
- User Query: A new book cover for the book "The Stand" by Stephen King
- GPT Answer:
A book cover depicting a desolate, post-apocalyptic cityscape bathed in eerie twilight, with silhouettes of abandoned buildings under a stormy sky. In the foreground, a lone figure in a tattered cloak stands on a deserted street, facing away, gazing towards a distant, ominous dark cloud shaped eerily like a human skull. The title, "The Stand," is emblazoned in bold, distressed font above.
"@
# Function to send a message to GPT Chat Completions API. Passes the entire message history in each request
function Get-ChatGPTResponse ($ChatUserMessage) {
# Construct the message history, which contains the system message and the user prompt
[System.Collections.Generic.List[Hashtable]]$ChatMessageHistory = @()
$ChatMessageHistory.Add(@{"role" = "system"; "content" = $ChatSystemMessage}) | Out-Null
$ChatMessageHistory.Add(@{"role" = "user"; "content" = $ChatUserMessage}) | Out-Null
# Construct the request headers
$ChatHeaders = @{
"Content-Type" = "application/json"
"Authorization" = "Bearer $APIKey"
}
# Construct the request body
$ChatRequestBody = @{
"model" = $ChatAPIModel
"messages" = $ChatMessageHistory
"max_tokens" = 8000 # Max amount of tokens the AI will respond with.
"temperature" = 0.7 # Lower is more coherent and conservative, higher is more creative and diverse.
}
# Send the API request
$ChatResponse = Invoke-RestMethod -Method POST -Uri $ChatAPIUrl -Headers $ChatHeaders -Body (ConvertTo-Json $ChatRequestBody)
# Return the message content
$ChatResponse.choices[0].message.content
}
# Function to send a prompt to DALLE Image Generation API.
function Get-DALLEImage ($SuppliedPrompt) {
# Set the request headers
$Headers = @{
"Content-Type" = "application/json"
"Authorization" = "Bearer $APIKey"
}
# Set the request body
$RequestBody = @{
"model" = $ImageAPIModel
"prompt" = $SuppliedPrompt
"size" = $ImageSize
"quality" = $ImageQuality
"n" = $NumImages
}
# Send the request
$Response = Invoke-RestMethod -Method POST -Uri $ImageAPIUrl -Headers $Headers -Body (ConvertTo-Json $RequestBody)
# Return the message content
return $Response.data[0].url
}# FUNCTION Get-DALLEImage...
Clear-Host
# Interactive loop
while ($true) {
# Output relevant info for current prompt
Write-Host "-------------------------------------------------------------------------------"
Write-Host "($(Get-Date -Format 'ddd, d MMM yyyy, h:mmtt')) Requesting new image description..." -ForegroundColor Cyan
$GeneratedPrompt = Get-ChatGPTResponse $UserPrompt
Write-Host "$GeneratedPrompt"
For ($i=1; $i -lt 3; $i++) {
Write-Host "Sending image generation request $i of 2..." -ForegroundColor DarkMagenta
# Send request to DALLE
$AIResponse = Get-DALLEImage $GeneratedPrompt
# Download generated image
$DownloadedFilePath = "$DownloadsPath\$((Get-Date).ToFileTime()).png"
Write-Host "Downloading to $DownloadedFilePath" -ForegroundColor DarkMagenta
(New-Object net.webclient).DownloadFile("$AIResponse","$DownloadedFilePath")
Write-Host "Waiting for rate limit" -ForegroundColor DarkMagenta
Sleep 45
}# For ($i=0;...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment