Skip to content

Instantly share code, notes, and snippets.

@hitode909
Created January 19, 2024 15:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hitode909/3b3834200e7c78c68ef2601f18550892 to your computer and use it in GitHub Desktop.
Save hitode909/3b3834200e7c78c68ef2601f18550892 to your computer and use it in GitHub Desktop.
Automatic Desktop Image Generator via OpenAI
#! /usr/bin/ruby
require 'net/http'
require 'json'
require 'uri'
require 'fileutils'
# Replace with your actual API key
API_KEY = ENV['OPENAPI_KEY']
def generate_theme
# Set up the request to search for the latest news in Japan
uri = URI.parse("https://api.openai.com/v1/chat/completions")
request = Net::HTTP::Post.new(uri)
request.content_type = "application/json"
request["Authorization"] = "Bearer #{API_KEY}"
request.body = JSON.dump({
"model" => "gpt-4",
"messages" => [
{ "role": "system", "content": "リビングルームに飾るための、独創的な絵のお題を考えてください。タイトルと内容、画風の参考とするための、画家やアーティスト名、スタイルを生成してください。CGやデジタルイラストも避けて、絵の具を使った表現にしてください。ゴッホは見飽きたので避けてください。世界各国の民族的なスタイルも取り入れてください。インターネットなど、現代テクノロジーのモチーフも織り交ぜてください。応答は英語で、結果は1行で、1件だけ出力してください。" }
],
})
p request.body
# Send the request and get the response
response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http|
http.request(request)
end
# Parse the response
result = JSON.parse(response.body)
p result
if result["choices"] && !result["choices"].empty?
summary = result["choices"][0]["message"]["content"]
return summary
end
end
def generate_image(theme, iterate_count)
# DALL-E 3 API URLの設定
uri = URI.parse("https://api.openai.com/v1/images/generations")
# HTTPリクエストの設定
request = Net::HTTP::Post.new(uri)
request.content_type = "application/json"
request["Authorization"] = "Bearer #{API_KEY}"
request.body = JSON.dump({
"prompt" => theme,
# "prompt" => "Oil Painting, #{theme}",
"model" => "dall-e-3",
"size" => "1792x1024",
"quality" => "hd",
"n" => 1,
"style" => "natural",
})
# HTTPリクエストの実行とレスポンスの取得
response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http|
http.request(request)
end
# レスポンスの解析
result = JSON.parse(response.body)
p result
# 画像URLの取得とダウンロード
if result["data"] && !result["data"].empty?
description = result["data"][0]["revised_prompt"]
puts description
image_url = result["data"][0]["url"]
image_uri = URI.parse(image_url)
output_dir = File.expand_path("~/Pictures/ai-art")
filename = "#{output_dir}/#{File.basename(theme[0..200])}_#{iterate_count}.png"
Net::HTTP.start(image_uri.host, image_uri.port, use_ssl: image_uri.scheme == 'https') do |http|
resp = http.get(image_uri)
File.open(filename, "wb") do |file|
file.write(resp.body)
end
end
puts "Image downloaded successfully as '#{theme}'"
system(
"mogrify",
"-set", "comment", "#{theme}\n\n#{description}",
filename
)
return filename
else
puts "No image found in the response"
return nil
end
end
def generate_caption(theme, filename)
system(
*%w(convert
-font Helvetica
-pointsize 24
-fill white
-stroke gray
-strokewidth 1
-gravity SouthWest
-weight 800
-annotate 0x0+10+10
),
theme,
filename,
"output/#{File.basename(theme[0..100])}-caption.png"
)
end
def collect_old_files
Dir.glob(File.expand_path("~/Pictures/ai-art/*"))
end
def move_old_files(files)
files.each{|file|
FileUtils.mv(file, File.expand_path("~/Pictures/ai-art-all/"))
}
end
old_files = collect_old_files
theme = generate_theme
puts theme
filename = generate_image(theme, 1)
if filename
move_old_files(old_files)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment