ai_alt_text 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,136 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AiAltText
4
+ # Core of the gem: image in, alt text out. Has no Rails dependency.
5
+ class Describer
6
+ # A generated alt text with details about how it was made.
7
+ Result = Data.define(:text, :decorative, :provider, :model, :input_tokens, :output_tokens,
8
+ :cost, :duration, :prompt_version)
9
+
10
+ TRANSIENT_ERRORS = [
11
+ RubyLLM::RateLimitError, RubyLLM::OverloadedError, RubyLLM::ServerError,
12
+ RubyLLM::ServiceUnavailableError, RubyLLM::ConnectionError
13
+ ].freeze
14
+ # Fail fast: a stuck call should not hold a background worker for minutes.
15
+ # The job retries with its own backoff. Overridable via c.ruby_llm_options.
16
+ RUBY_LLM_DEFAULTS = { request_timeout: 60, max_retries: 1 }.freeze
17
+ AUTH_ERRORS = [RubyLLM::UnauthorizedError, RubyLLM::ForbiddenError, RubyLLM::PaymentRequiredError].freeze
18
+
19
+ class << self
20
+ # Set by AiAltText::Testing.stub! to bypass the provider. Receives the prepared
21
+ # image and context, returns a Result.
22
+ attr_accessor :stub
23
+ end
24
+
25
+ # @param config [Configuration]
26
+ # @param preparer [ImagePreparer, nil] defaults to one built from +config+
27
+ def initialize(config = AiAltText.configuration, preparer: nil)
28
+ @config = config
29
+ @preparer = preparer || ImagePreparer.new(max_dimension: config.max_image_dimension, logger: config.logger)
30
+ end
31
+
32
+ # @param source [String, Pathname, IO, ActiveStorage::Blob, ActiveStorage::Attachment]
33
+ # @param context [String, nil] where the image is used, to guide what matters
34
+ # @param model [String, nil] overrides the configured model
35
+ # @param provider [Symbol, String, nil] overrides the configured provider
36
+ # @return [Result]
37
+ # @raise [ConfigurationError, UnsupportedFormatError, GenerationError, TransientError]
38
+ def call(source, context: nil, model: nil, provider: nil)
39
+ return stubbed(source, context) if self.class.stub
40
+
41
+ provider, model = resolve!(provider, model)
42
+ started = monotonic_now
43
+ response = @preparer.prepare(source) { |image| ask(build_chat(provider, model), context, image) }
44
+ build_result(response, provider, model, monotonic_now - started).tap { |result| log(result) }
45
+ end
46
+
47
+ private
48
+
49
+ def stubbed(source, context)
50
+ @preparer.prepare(source) { |image| self.class.stub.call(image, context) }
51
+ end
52
+
53
+ def resolve!(provider, model)
54
+ provider = (provider || @config.provider)&.to_sym
55
+ @config.validate!(provider: provider)
56
+ [provider, resolve_model(provider, model)]
57
+ end
58
+
59
+ def resolve_model(provider, model)
60
+ model ||= @config.model if provider == @config.provider
61
+ model ||= DefaultModels.for(provider)
62
+ return model if model
63
+
64
+ raise ConfigurationError, "No default model for #{provider}. Choose a vision-capable model: " \
65
+ "AiAltText.configure { |c| c.model = \"...\" }"
66
+ end
67
+
68
+ def build_chat(provider, model)
69
+ context = RubyLLM.context { |ruby_llm| apply_credentials(ruby_llm, provider) }
70
+ check_requirements!(context.config, provider)
71
+ context.chat(model: model, provider: provider).with_instructions(
72
+ Prompt.instructions(max_length: @config.max_length, locale: @config.locale, override: @config.prompt)
73
+ )
74
+ rescue RubyLLM::ModelNotFoundError => e
75
+ raise ConfigurationError, "Model #{model.inspect} was not found for #{provider} (#{e.message}). " \
76
+ "Check the model ID or leave c.model unset to use the default."
77
+ end
78
+
79
+ def apply_credentials(ruby_llm, provider)
80
+ RUBY_LLM_DEFAULTS.merge(@config.ruby_llm_options).each { |key, value| ruby_llm.public_send("#{key}=", value) }
81
+ key_option = Providers.api_key_option(provider)
82
+ ruby_llm.public_send("#{key_option}=", @config.api_key) if key_option && provider == @config.provider
83
+ end
84
+
85
+ def check_requirements!(ruby_llm_config, provider)
86
+ missing = Providers.provider_class(provider).configuration_requirements.reject do |opt|
87
+ ruby_llm_config.public_send(opt)
88
+ end
89
+ return if missing.empty?
90
+
91
+ raise ConfigurationError, "Missing #{missing.join(", ")} for #{provider}. Set c.api_key for your " \
92
+ "configured provider, or pass other credentials through c.ruby_llm_options."
93
+ end
94
+
95
+ def ask(chat, context, image)
96
+ attachment = RubyLLM::Attachment.new(image.io, filename: image.filename, mime_type: image.mime_type)
97
+ chat.ask(Prompt.user_message(context: context), with: attachment)
98
+ rescue *AUTH_ERRORS => e
99
+ raise ConfigurationError, "The provider rejected the request (#{e.class.name.split("::").last}). " \
100
+ "Check that your API key (c.api_key) is valid and has access to this model."
101
+ rescue *TRANSIENT_ERRORS => e
102
+ raise TransientError, "Temporary provider failure: #{e.message}"
103
+ rescue RubyLLM::Error => e
104
+ raise GenerationError, "Alt text generation failed: #{e.message}"
105
+ end
106
+
107
+ def build_result(response, provider, model, duration)
108
+ cleaned = Sanitizer.call(response.content, max_length: @config.max_length)
109
+ tokens = response.tokens
110
+ Result.new(
111
+ text: cleaned.text, decorative: cleaned.decorative, provider: provider, model: response.model || model,
112
+ input_tokens: tokens&.input, output_tokens: tokens&.output, cost: cost_of(response),
113
+ duration: duration, prompt_version: Prompt::VERSION
114
+ )
115
+ end
116
+
117
+ def cost_of(response)
118
+ response.cost&.total
119
+ rescue StandardError
120
+ nil
121
+ end
122
+
123
+ def log(result)
124
+ cost = result.cost ? format("$%.6f", result.cost) : "unknown"
125
+ @config.logger.info(
126
+ "[ai_alt_text] generated provider=#{result.provider} model=#{result.model} " \
127
+ "input_tokens=#{result.input_tokens} output_tokens=#{result.output_tokens} cost=#{cost} " \
128
+ "duration=#{format("%.2f", result.duration)}s decorative=#{result.decorative}"
129
+ )
130
+ end
131
+
132
+ def monotonic_now
133
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
134
+ end
135
+ end
136
+ end
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "store"
4
+ require_relative "model"
5
+ require_relative "human_text"
6
+ require_relative "helper"
7
+ require_relative "backfill"
8
+
9
+ module AiAltText
10
+ # Hooks the gem into Rails: the model macro, the view helper, the job
11
+ # (app/jobs) and Rails.logger. The core never loads this file without Rails.
12
+ class Engine < ::Rails::Engine
13
+ initializer "ai_alt_text.version_check" do
14
+ if ::Rails.gem_version < Gem::Version.new("7.1")
15
+ warn "[ai_alt_text] Rails #{::Rails.version} is not supported. Use Rails 7.1 or newer."
16
+ end
17
+ end
18
+
19
+ initializer "ai_alt_text.logger" do
20
+ AiAltText::Configuration.default_logger = ::Rails.logger
21
+ end
22
+
23
+ initializer "ai_alt_text.active_record" do
24
+ ActiveSupport.on_load(:active_record) { extend AiAltText::Model::ClassMethods }
25
+ end
26
+
27
+ initializer "ai_alt_text.action_view" do
28
+ ActiveSupport.on_load(:action_view) { include AiAltText::Helper }
29
+ end
30
+ end
31
+ end
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AiAltText
4
+ # Base class for every error raised by this gem.
5
+ class Error < StandardError; end
6
+
7
+ # Raised when the gem is misconfigured. The message says how to fix it.
8
+ class ConfigurationError < Error; end
9
+
10
+ # Raised when an image is not JPEG, PNG, GIF or WebP, or is too large to send.
11
+ class UnsupportedFormatError < Error; end
12
+
13
+ # Raised when an image is too large to send and cannot be resized
14
+ # because the image_processing gem is not available.
15
+ class ImageTooLargeError < UnsupportedFormatError; end
16
+
17
+ # Raised when the provider fails or returns unusable alt text.
18
+ class GenerationError < Error; end
19
+
20
+ # A GenerationError worth retrying later: rate limits, overload, timeouts.
21
+ class TransientError < GenerationError; end
22
+ end
@@ -0,0 +1,50 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AiAltText
4
+ # View helper that renders an image with its stored alt text. It never calls
5
+ # the LLM and never raises while working out the alt text.
6
+ module Helper
7
+ # @example
8
+ # <%= ai_alt_image_tag @product.photo, class: "hero" %>
9
+ #
10
+ # @param source [ActiveStorage::Attached::One, ActiveStorage::Attachment]
11
+ # @param options [Hash] passed to image_tag; an explicit :alt always wins
12
+ # @return [ActiveSupport::SafeBuffer] the img tag, or "" when nothing is attached
13
+ def ai_alt_image_tag(source, options = {})
14
+ attachment, record = Helper.resolve(source)
15
+ return "".html_safe if attachment.nil? && source.respond_to?(:attached?)
16
+
17
+ options = options.dup
18
+ options[:alt] = attachment ? Helper.alt_for(attachment, record) : "" unless options.key?(:alt)
19
+ image_tag(source, options)
20
+ end
21
+
22
+ module_function
23
+
24
+ def resolve(source)
25
+ if source.respond_to?(:attachment) && source.respond_to?(:record)
26
+ [source.attachment, source.record]
27
+ elsif source.is_a?(ActiveStorage::Attachment)
28
+ [source, source.record]
29
+ end
30
+ end
31
+
32
+ def alt_for(attachment, record)
33
+ stored = Store.for(AiAltText.configuration).read(attachment, record: record)
34
+ return stored["text"].to_s if stored&.key?("text")
35
+
36
+ fallback(attachment, record)
37
+ rescue StandardError => e
38
+ AiAltText.configuration.logger.warn("[ai_alt_text] Alt text lookup failed (#{e.class}); using \"\".")
39
+ ""
40
+ end
41
+
42
+ def fallback(attachment, record)
43
+ setting = AiAltText.configuration.helper_fallback
44
+ return setting.call(attachment).to_s if setting.respond_to?(:call)
45
+ return "" unless setting == :context
46
+
47
+ Model.context_for(record, attachment.name).to_s
48
+ end
49
+ end
50
+ end
@@ -0,0 +1,81 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AiAltText
4
+ # Human-written alt text set through <name>_alt_text=. It is held on the record
5
+ # until save, then stored with source "human" so generation never overwrites it.
6
+ module HumanText
7
+ module_function
8
+
9
+ # Reads pending human text first, then stored text via the block.
10
+ def read(record, name)
11
+ pending = pending(record, name)
12
+ return pending[:current] if pending.key?(:current)
13
+
14
+ store = Store.for(AiAltText.configuration)
15
+ texts = Model.attachments(record, name).map do |attachment|
16
+ next pending[attachment.id] if pending.key?(attachment.id)
17
+
18
+ yield(attachment, store) if attachment.persisted?
19
+ end
20
+ Model.many?(record, name) ? texts : texts.first
21
+ end
22
+
23
+ # nil clears stored alt text so it can be generated again; "" marks the image decorative.
24
+ def assign(record, name, value)
25
+ return pending(record, name).merge!(by_attachment_id!(record, name, value)) if Model.many?(record, name)
26
+
27
+ # The attachment may be assigned after this (ActiveRecord assigns Hash values
28
+ # last), so it is resolved at save time.
29
+ pending(record, name)[:current] = value
30
+ end
31
+
32
+ # Called from after_save, once attachments have ids.
33
+ def save(record, name)
34
+ pending = pending(record, name)
35
+ return if pending.empty?
36
+
37
+ current = Model.attachments(record, name)
38
+ pending.each do |key, text|
39
+ attachment = key == :current ? current.first : current.find { |a| a.id == key }
40
+ attachment ? write(attachment, record, text) : warn_unattached(record, name)
41
+ end
42
+ pending.clear
43
+ end
44
+
45
+ def write(attachment, record, text)
46
+ store = Store.for(AiAltText.configuration)
47
+ return store.delete(attachment, record: record) if text.nil?
48
+
49
+ store.write(attachment, { "text" => text.to_s, "source" => "human", "decorative" => text.to_s.empty?,
50
+ "updated_at" => Time.now.utc.iso8601 }, record: record)
51
+ end
52
+
53
+ def by_attachment_id!(record, name, value)
54
+ unless value.is_a?(Hash)
55
+ raise ArgumentError,
56
+ "#{name}_alt_text= takes a Hash of attachment (or attachment id) => text."
57
+ end
58
+
59
+ ids = Model.attachments(record, name).map(&:id)
60
+ value.to_h do |key, text|
61
+ id = key.is_a?(ActiveStorage::Attachment) ? key.id : Integer(key)
62
+ raise ArgumentError, "Attachment #{id} does not belong to #{record.class.name}##{name}." unless ids.include?(id)
63
+
64
+ [id, text]
65
+ end
66
+ end
67
+
68
+ def warn_unattached(record, name)
69
+ AiAltText.configuration.logger.warn(
70
+ "[ai_alt_text] Ignored #{name}_alt_text on #{record.class.name}##{record.id}: nothing attached."
71
+ )
72
+ end
73
+
74
+ # Unsaved human text for this attachment name: { attachment_id or :current => text }.
75
+ def pending(record, name)
76
+ all = record.instance_variable_get(:@ai_alt_text_human) ||
77
+ record.instance_variable_set(:@ai_alt_text_human, {})
78
+ all[name] ||= {}
79
+ end
80
+ end
81
+ end
@@ -0,0 +1,150 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "pathname"
4
+ require "stringio"
5
+ require "tempfile"
6
+
7
+ module AiAltText
8
+ # Turns a path, IO, or ActiveStorage blob/attachment into image bytes that
9
+ # are safe to send: a supported format, resized when possible. Never fetches
10
+ # URLs and never hands RubyLLM a storage link.
11
+ class ImagePreparer
12
+ # An image ready to send. +io+ is only valid inside the {#prepare} block.
13
+ Prepared = Data.define(:io, :mime_type, :filename)
14
+
15
+ SIGNATURES = {
16
+ "image/jpeg" => ->(head) { head.start_with?("\xFF\xD8\xFF".b) },
17
+ "image/png" => ->(head) { head.start_with?("\x89PNG\r\n\x1A\n".b) },
18
+ "image/gif" => ->(head) { head.start_with?("GIF87a", "GIF89a") },
19
+ "image/webp" => ->(head) { head.start_with?("RIFF") && head[8, 4] == "WEBP" }
20
+ }.freeze
21
+ OUTPUT_FORMATS = { "image/jpeg" => "jpeg", "image/png" => "png", "image/gif" => "png",
22
+ "image/webp" => "webp" }.freeze
23
+
24
+ # Largest original sent unresized. Anthropic accepts up to 5 MB per image after
25
+ # base64 encoding, which is about 3.75 MB of raw bytes.
26
+ MAX_UNPROCESSED_BYTES = 3_750_000
27
+
28
+ # @return [ImageProcessor, nil] see {ImageProcessor.detect}
29
+ def self.default_processor
30
+ return @default_processor if defined?(@default_processor)
31
+
32
+ @default_processor = ImageProcessor.detect
33
+ end
34
+
35
+ # @param max_dimension [Integer] longest side in pixels after resizing
36
+ # @param processor [#call, nil, :auto] resizer; :auto detects image_processing
37
+ # @param max_unprocessed_bytes [Integer] largest original sent without resizing
38
+ # @param logger [Logger, nil]
39
+ def initialize(max_dimension:, processor: :auto, max_unprocessed_bytes: MAX_UNPROCESSED_BYTES, logger: nil)
40
+ @max_dimension = max_dimension
41
+ @processor = processor == :auto ? self.class.default_processor : processor
42
+ @max_unprocessed_bytes = max_unprocessed_bytes
43
+ @logger = logger
44
+ end
45
+
46
+ # Yields the prepared image and deletes any temp files afterwards.
47
+ #
48
+ # @param source [String, Pathname, IO, ActiveStorage::Blob, ActiveStorage::Attachment]
49
+ # @yieldparam image [Prepared]
50
+ # @return [Object] the block's result
51
+ # @raise [UnsupportedFormatError] for formats other than JPEG, PNG, GIF and WebP
52
+ # @raise [ImageTooLargeError] when the image is too big and cannot be resized
53
+ # @raise [ArgumentError] for URLs, missing files, and unknown source types
54
+ def prepare(source)
55
+ filename, declared_type = describe_source(source)
56
+ check_unprocessed_size!(source.byte_size) if blob?(source) && @processor.nil?
57
+ bytes = read_bytes(source)
58
+ mime_type = detect_type(bytes, declared_type)
59
+ with_resized(bytes, mime_type) do |data, type|
60
+ yield Prepared.new(io: StringIO.new(data), mime_type: type, filename: filename)
61
+ end
62
+ end
63
+
64
+ private
65
+
66
+ def blob?(source)
67
+ source.respond_to?(:download) && source.respond_to?(:byte_size)
68
+ end
69
+
70
+ def describe_source(source)
71
+ case source
72
+ when String, Pathname then [File.basename(local_path!(source)), nil]
73
+ else
74
+ return [source.filename.to_s, source.content_type] if blob?(source)
75
+ return [File.basename(source.path), nil] if source.respond_to?(:read) && source.respond_to?(:path)
76
+ return ["image", nil] if source.respond_to?(:read)
77
+
78
+ raise ArgumentError, "Unsupported image source #{source.class}. Pass a file path, an IO, " \
79
+ "or an ActiveStorage blob or attachment."
80
+ end
81
+ end
82
+
83
+ def local_path!(source)
84
+ path = source.to_s
85
+ if path.match?(%r{\A[a-z][a-z0-9+.-]*://}i)
86
+ raise ArgumentError, "URLs are not supported. Download the image yourself and pass the file or IO."
87
+ end
88
+ raise ArgumentError, "File not found: #{path}" unless File.file?(path)
89
+
90
+ path
91
+ end
92
+
93
+ def read_bytes(source)
94
+ case source
95
+ when String, Pathname then File.binread(source.to_s)
96
+ else
97
+ return source.download.b if blob?(source)
98
+
99
+ source.rewind if source.respond_to?(:rewind)
100
+ source.read.to_s.b
101
+ end
102
+ end
103
+
104
+ def detect_type(bytes, declared_type)
105
+ head = bytes[0, 16]
106
+ type = SIGNATURES.find { |_, matches| matches.call(head) }&.first
107
+ return type if type
108
+
109
+ found = declared_type ? " (#{declared_type})" : ""
110
+ raise UnsupportedFormatError, "Unsupported image format#{found}. Supported formats: JPEG, PNG, GIF, WebP."
111
+ end
112
+
113
+ def with_resized(bytes, mime_type)
114
+ resized = resize(bytes, mime_type) if @processor
115
+ if resized
116
+ data = bytes_of(resized)
117
+ return yield(data, detect_type(data, nil))
118
+ end
119
+
120
+ check_unprocessed_size!(bytes.bytesize)
121
+ yield bytes, mime_type
122
+ ensure
123
+ resized&.close!
124
+ end
125
+
126
+ def resize(bytes, mime_type)
127
+ Tempfile.create(["ai_alt_text_source", ".img"], binmode: true) do |source|
128
+ source.write(bytes)
129
+ source.flush
130
+ @processor.call(source.path, max_dimension: @max_dimension, format: OUTPUT_FORMATS[mime_type])
131
+ end
132
+ rescue StandardError => e
133
+ @logger&.warn("[ai_alt_text] Image resizing failed (#{e.class}); trying the original image.")
134
+ nil
135
+ end
136
+
137
+ def bytes_of(file)
138
+ file.rewind
139
+ file.read.b
140
+ end
141
+
142
+ def check_unprocessed_size!(size)
143
+ return if size <= @max_unprocessed_bytes
144
+
145
+ raise ImageTooLargeError,
146
+ "Image is #{(size / 1_000_000.0).round(1)} MB, too large to send without resizing. " \
147
+ "Add the image_processing gem (with libvips or ImageMagick) so images can be resized."
148
+ end
149
+ end
150
+ end
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AiAltText
4
+ # Resizes images through the optional image_processing gem.
5
+ class ImageProcessor
6
+ # @return [ImageProcessor, nil] a processor backed by libvips, or ImageMagick
7
+ # when libvips is missing; nil when image_processing is not installed
8
+ def self.detect
9
+ require "image_processing"
10
+ new(vips_available? ? ImageProcessing::Vips : ImageProcessing::MiniMagick)
11
+ rescue LoadError
12
+ nil
13
+ end
14
+
15
+ def self.vips_available?
16
+ require "vips"
17
+ true
18
+ rescue LoadError, StandardError
19
+ false
20
+ end
21
+ private_class_method :vips_available?
22
+
23
+ # @param backend [Module] ImageProcessing::Vips or ImageProcessing::MiniMagick
24
+ def initialize(backend)
25
+ @backend = backend
26
+ end
27
+
28
+ # @param path [String] source image path
29
+ # @param max_dimension [Integer] longest side in pixels
30
+ # @param format [String] output format, e.g. "png"
31
+ # @return [Tempfile] the resized image; the caller deletes it
32
+ def call(path, max_dimension:, format:)
33
+ @backend.source(path).resize_to_limit(max_dimension, max_dimension).convert(format).call
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,109 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AiAltText
4
+ # The +generates_alt_text_for+ macro for ActiveRecord models.
5
+ module Model
6
+ # Macro added to every ActiveRecord model.
7
+ module ClassMethods
8
+ # Generates alt text in the background whenever the attachment changes.
9
+ #
10
+ # @example
11
+ # has_one_attached :photo
12
+ # generates_alt_text_for :photo, context: -> { name }
13
+ #
14
+ # Adds +photo_alt_text+, +photo_alt_text=+ (human text, saved with the record)
15
+ # and +regenerate_photo_alt_text+. For has_many_attached the reader returns an
16
+ # Array and the writer takes a Hash of attachment (or attachment id) => text.
17
+ #
18
+ # @param name [Symbol] a has_one_attached or has_many_attached name
19
+ # @param context [String, Symbol, Proc, nil] text describing where the image is
20
+ # used: a String, a method name, or a lambda evaluated on the record
21
+ # @param if [Symbol, Proc, nil] only generate when this is truthy
22
+ # @param unless [Symbol, Proc, nil] skip generation when this is truthy
23
+ def generates_alt_text_for(name, context: nil, if: nil, unless: nil)
24
+ name = name.to_sym
25
+ unless reflect_on_attachment(name)
26
+ raise ArgumentError, "#{self.name} has no attachment :#{name}. Declare has_one_attached :#{name} " \
27
+ "(or has_many_attached) before generates_alt_text_for."
28
+ end
29
+
30
+ Model.register(self, name, context: context, if: binding.local_variable_get(:if),
31
+ unless: binding.local_variable_get(:unless))
32
+ Model.define_accessors(self, name)
33
+ end
34
+ end
35
+
36
+ module_function
37
+
38
+ def register(klass, name, **options)
39
+ unless klass.respond_to?(:ai_alt_text_attachments)
40
+ klass.class_attribute :ai_alt_text_attachments, instance_writer: false, default: {}
41
+ end
42
+ klass.ai_alt_text_attachments = klass.ai_alt_text_attachments.merge(name => options)
43
+ klass.after_save do
44
+ (@ai_alt_text_pending ||= Set.new) << name if attachment_changes.key?(name.to_s)
45
+ HumanText.save(self, name)
46
+ end
47
+ klass.after_commit(on: %i[create update]) do
48
+ Model.enqueue_after_commit(self, name) if @ai_alt_text_pending&.delete?(name)
49
+ end
50
+ end
51
+
52
+ def define_accessors(klass, name)
53
+ klass.define_method(:"#{name}_alt_text") { Model.alt_text_for(self, name) }
54
+ klass.define_method(:"#{name}_alt_text=") { |value| HumanText.assign(self, name, value) }
55
+ klass.define_method(:"regenerate_#{name}_alt_text") { Model.enqueue(self, name, regenerate: true) }
56
+ end
57
+
58
+ # Runs inside the host app's save: a failure here must never break the upload.
59
+ def enqueue_after_commit(record, name)
60
+ enqueue(record, name, regenerate: false) if wanted?(record, name)
61
+ rescue StandardError => e
62
+ AiAltText.configuration.logger.error(
63
+ "[ai_alt_text] Could not enqueue alt text for #{record.class.name}##{name}: #{e.class}: #{e.message}"
64
+ )
65
+ end
66
+
67
+ # @return [Boolean] whether generation is enabled and the if:/unless: conditions allow it
68
+ def wanted?(record, name)
69
+ options = record.ai_alt_text_attachments.fetch(name)
70
+ AiAltText.configuration.enabled &&
71
+ (options[:if].nil? || evaluate(record, options[:if])) &&
72
+ (options[:unless].nil? || !evaluate(record, options[:unless]))
73
+ end
74
+
75
+ def enqueue(record, name, regenerate:)
76
+ attachments(record, name).each { |attachment| GenerateJob.perform_later(attachment, regenerate: regenerate) }
77
+ end
78
+
79
+ def attachments(record, name)
80
+ attached = record.public_send(name)
81
+ many?(record, name) ? attached.attachments.to_a : [attached.attachment].compact
82
+ end
83
+
84
+ # Attached::One forwards unknown methods to the blob, so duck typing on
85
+ # #attachments is unreliable; ask the reflection instead.
86
+ def many?(record, name)
87
+ record.class.reflect_on_attachment(name).macro == :has_many_attached
88
+ end
89
+
90
+ def alt_text_for(record, name)
91
+ HumanText.read(record, name) { |attachment, store| store.read(attachment, record: record)&.fetch("text", nil) }
92
+ end
93
+
94
+ # @return [String, nil] the context declared for this attachment, evaluated on the record
95
+ def context_for(record, name)
96
+ options = record.class.try(:ai_alt_text_attachments)&.fetch(name.to_sym, nil)
97
+ options && evaluate(record, options[:context])&.to_s
98
+ end
99
+
100
+ # Resolves a String, Symbol (method name) or Proc against the record.
101
+ def evaluate(record, value)
102
+ case value
103
+ when Symbol then record.public_send(value)
104
+ when Proc then value.arity.zero? ? record.instance_exec(&value) : value.call(record)
105
+ else value
106
+ end
107
+ end
108
+ end
109
+ end