View Source Image Generation Kino App

Mix.install([
  {:openai_ex, "~> 0.8.5"},
  {:kino, "~> 0.13.2"}
])

alias OpenaiEx
alias OpenaiEx.Images

Simple Kino UI

openai = System.fetch_env!("LB_OPENAI_API_KEY") |> OpenaiEx.new()

set default parameters for image generation, and define a function to fetch generated images from a URL.

size = "256x256"
n = 4

fetch_blob = fn url ->
  Finch.build(:get, url) |> Finch.request!(OpenaiEx.Finch) |> Map.get(:body)
end

Prompt / Response UI

text_input = Kino.Input.textarea("Describe Image")

form = Kino.Control.form([text: text_input], submit: "Generate")
frame = Kino.Frame.new()

Kino.listen(form, fn %{data: %{text: prompt}} ->
  Kino.Frame.render(frame, Kino.Text.new("Running..."))

  res_urls =
    openai
    |> Images.generate!(%{
      prompt: prompt,
      n: n,
      size: size
    })
    #   |> IO.inspect()
    |> Map.get("data")
    |> Enum.map(fn x -> x["url"] end)

  res_urls
  |> Enum.map(fn x -> x |> fetch_blob.() |> Kino.Image.new("image/png") end)
  |> Kino.Layout.grid(columns: 2)
  |> then(&Kino.Frame.render(frame, &1))
end)

Kino.Layout.grid([form, frame], boxed: true, gap: 16)