0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

RubyからOpenAI APIをたたいてDALL-E!を呼ぶ

Last updated at Posted at 2023-03-07

RubyからChatGPTを呼ぶ記事はいくつかあるけど、DALL-Eを呼ぶ記事がなさそうなので書いた。
GTK4を利用している。確認していないけれど、WindowsやmacOSでも動くんじゃなかろうか。

動作には、ruby-openai と、gtk4 が必要。

require 'gtk4'
require 'openai'
require 'open-uri'

client = OpenAI::Client.new(access_token: ENV['OPENAI_ACCESS_TOKEN'])

app = Gtk::Application.new('org.example.myapp', :flags_none)
app.signal_connect 'activate' do |a|
  window = Gtk::ApplicationWindow.new(a)
  window.title = 'DALL-E!'
  window.set_default_size 600, 600
  vbox = Gtk::Box.new(:vertical)
  window.child = vbox
  hbox = Gtk::Box.new(:horizontal)
  vbox.append(hbox)
  entry = Gtk::Entry.new
  entry.hexpand = true
  hbox.append(entry)
  image = Gtk::Image.new
  image.vexpand = true
  button = Gtk::Button.new(label: 'Go')
  button.signal_connect('clicked') do
    loader = GdkPixbuf::PixbufLoader.new
    response = client.images.generate(
      parameters: { prompt: entry.text, size: '512x512' }
    )
    url = response.dig('data', 0, 'url')
    data = URI.open(url).read
    loader.write(data)
    pixbuf = loader.pixbuf
    loader.close
    image.from_pixbuf = pixbuf
  end
  save_button = Gtk::Button.new(label: 'Save')
  save_button.signal_connect('clicked') do
    image.paintable.save_to_png("output.png")
  end
  hbox.append(button)
  hbox.append(save_button)
  vbox.append(image)
  window.show
end

app.run

エラー処理とか一切していない。。。
この記事は以上です。

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?