davideisinger.com

My personal website
Log | Files | Refs | README

image_alt_text.rb (1099B)


      1 require "open3"
      2 require "tmpdir"
      3 
      4 module ImageAltText
      5   PROMPT = "Write concise accessibility alt text for this image. " \
      6     "Describe the relevant visible content plainly and objectively. " \
      7     "Avoid jokes, wordplay, commentary, and unsupported assumptions. " \
      8     "Return only the alt text, as plain text in a single paragraph, without quotation marks or Markdown."
      9 
     10   def self.generate(image)
     11     Dir.mktmpdir("image-alt-text-") do |directory|
     12       response = File.join(directory, "response.txt")
     13       output, status = Open3.capture2e(
     14         "codex", "exec", "--sandbox", "read-only", "--ephemeral",
     15         "--output-last-message", response, "--image", File.expand_path(image), "--", PROMPT
     16       )
     17       raise "Alt text generation failed:\n#{output}" unless status.success?
     18       raise "Alt text output was missing." unless File.file?(response)
     19 
     20       alt = File.read(response).strip.gsub(/\s+/, " ")
     21       raise "Alt text output was empty." if alt.empty?
     22       raise "Alt text contained shortcode delimiters." if alt.include?("{{") || alt.include?("}}")
     23 
     24       alt
     25     end
     26   end
     27 end