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.
- checksums.yaml +7 -0
- data/CHANGELOG.md +24 -0
- data/LICENSE.txt +21 -0
- data/README.md +336 -0
- data/app/jobs/ai_alt_text/generate_job.rb +69 -0
- data/lib/ai_alt_text/backfill.rb +102 -0
- data/lib/ai_alt_text/configuration.rb +101 -0
- data/lib/ai_alt_text/default_models.rb +23 -0
- data/lib/ai_alt_text/describer.rb +136 -0
- data/lib/ai_alt_text/engine.rb +31 -0
- data/lib/ai_alt_text/errors.rb +22 -0
- data/lib/ai_alt_text/helper.rb +50 -0
- data/lib/ai_alt_text/human_text.rb +81 -0
- data/lib/ai_alt_text/image_preparer.rb +150 -0
- data/lib/ai_alt_text/image_processor.rb +36 -0
- data/lib/ai_alt_text/model.rb +109 -0
- data/lib/ai_alt_text/prompt.rb +69 -0
- data/lib/ai_alt_text/providers.rb +30 -0
- data/lib/ai_alt_text/sanitizer.rb +65 -0
- data/lib/ai_alt_text/store.rb +138 -0
- data/lib/ai_alt_text/testing.rb +52 -0
- data/lib/ai_alt_text/version.rb +5 -0
- data/lib/ai_alt_text.rb +65 -0
- data/lib/generators/ai_alt_text/column/column_generator.rb +40 -0
- data/lib/generators/ai_alt_text/column/templates/migration.rb.tt +8 -0
- data/lib/generators/ai_alt_text/install/install_generator.rb +17 -0
- data/lib/generators/ai_alt_text/install/templates/ai_alt_text.rb +44 -0
- data/lib/tasks/ai_alt_text.rake +13 -0
- metadata +88 -0
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: 9653d687fc1e63038c64e3fe6ddccb6e5d4ec57d3fba4e197ea1bb5cd5a5eb39
|
|
4
|
+
data.tar.gz: 4372ab8675227d1826df449c9f9ef334786541afe12d10f7b59e3fecfb5bfb9b
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: d5106c540b8706594d2117bd777fbcf35a3c922f0425e34c21c8f98b3c0c2cafe1f72fc0df105cdb13aae86f9495570330e10dab14bc1419f141d3843efe7c34
|
|
7
|
+
data.tar.gz: e4dacbe0337fc638ba487743492c84c29b3143578c4b737c62b016506a27ef611eae86c2d7fce618209b133d69d64a0e5282c65ed0f1837e23cb12f99b2524c3
|
data/CHANGELOG.md
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project are documented here. This project follows
|
|
4
|
+
[Semantic Versioning](https://semver.org/).
|
|
5
|
+
|
|
6
|
+
## [0.1.0] - 2026-11-24
|
|
7
|
+
|
|
8
|
+
### Added
|
|
9
|
+
- `AiAltText.describe` and `AiAltText.generate` for alt text from file paths, IO objects,
|
|
10
|
+
and ActiveStorage blobs or attachments, with per-call `model:` and `provider:` overrides.
|
|
11
|
+
- Isolated `RubyLLM.context` per generation; the host app's global RubyLLM settings are
|
|
12
|
+
never changed. Fail-fast defaults: 60 second timeout, one retry.
|
|
13
|
+
- Default vision models for Anthropic, OpenAI and Gemini.
|
|
14
|
+
- Format detection (JPEG, PNG, GIF, WebP) and optional resizing through `image_processing`.
|
|
15
|
+
- Accessibility-focused prompt (version 1) and output sanitizer.
|
|
16
|
+
- Rails engine with the `generates_alt_text_for` model macro (`context:`, `if:`, `unless:`),
|
|
17
|
+
`<name>_alt_text` reader, human-text writer, and `regenerate_<name>_alt_text`.
|
|
18
|
+
- `has_many_attached` support.
|
|
19
|
+
- `AiAltText::GenerateJob`, enqueued after commit, with retries for transient provider errors.
|
|
20
|
+
- `:blob_metadata` and `:column` storage, never overwriting human-written alt text.
|
|
21
|
+
- `ai_alt_image_tag` view helper with a configurable fallback.
|
|
22
|
+
- Generators: `ai_alt_text:install` (initializer) and `ai_alt_text:column` (migration).
|
|
23
|
+
- `rails ai_alt_text:backfill` with `LIMIT`, `DRY_RUN`, batching and a cost estimate.
|
|
24
|
+
- `AiAltText::Testing` stub mode for host app test suites.
|
data/LICENSE.txt
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Jibran Usman
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in
|
|
13
|
+
all copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
21
|
+
THE SOFTWARE.
|
data/README.md
ADDED
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
# ai_alt_text
|
|
2
|
+
|
|
3
|
+
[](https://github.com/jibranusman95/ai_alt_text/actions/workflows/ci.yml)
|
|
4
|
+
|
|
5
|
+
Accessible alt text for your images, written by the vision model of your choice.
|
|
6
|
+
|
|
7
|
+
```html
|
|
8
|
+
<!-- Before -->
|
|
9
|
+
<img src="/rails/active_storage/blobs/.../boot.jpg">
|
|
10
|
+
|
|
11
|
+
<!-- After -->
|
|
12
|
+
<img src="/rails/active_storage/blobs/.../boot.jpg" alt="Brown leather hiking boot with red laces">
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## Quickstart
|
|
16
|
+
|
|
17
|
+
1. Add the gem and run the installer:
|
|
18
|
+
|
|
19
|
+
```sh
|
|
20
|
+
bundle add ai_alt_text
|
|
21
|
+
bin/rails g ai_alt_text:install
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
2. Set your provider and API key in `config/initializers/ai_alt_text.rb`.
|
|
25
|
+
|
|
26
|
+
3. Add one line to your model and use the helper in your views:
|
|
27
|
+
|
|
28
|
+
```ruby
|
|
29
|
+
class Product < ApplicationRecord
|
|
30
|
+
has_one_attached :photo
|
|
31
|
+
generates_alt_text_for :photo, context: -> { name }
|
|
32
|
+
end
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
```erb
|
|
36
|
+
<%= ai_alt_image_tag @product.photo, class: "hero" %>
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Every uploaded image now gets alt text, generated in a background job.
|
|
40
|
+
|
|
41
|
+
**You bring your own API key.** Images are sent to the provider you choose (OpenAI,
|
|
42
|
+
Anthropic, Gemini, or any other provider [RubyLLM](https://rubyllm.com) supports) and
|
|
43
|
+
are billed to your account.
|
|
44
|
+
|
|
45
|
+
## Contents
|
|
46
|
+
|
|
47
|
+
- [Installation](#installation)
|
|
48
|
+
- [Configuration](#configuration)
|
|
49
|
+
- [Providers and models](#providers-and-models)
|
|
50
|
+
- [Rails usage](#rails-usage)
|
|
51
|
+
- [Standalone usage](#standalone-usage)
|
|
52
|
+
- [Storage modes](#storage-modes)
|
|
53
|
+
- [Backfilling existing images](#backfilling-existing-images)
|
|
54
|
+
- [Testing your app](#testing-your-app)
|
|
55
|
+
- [Privacy](#privacy)
|
|
56
|
+
- [Cost](#cost)
|
|
57
|
+
- [Limitations](#limitations)
|
|
58
|
+
|
|
59
|
+
## Installation
|
|
60
|
+
|
|
61
|
+
Requires Ruby 3.2+. The Rails integration supports Rails 7.1 and newer; the core works
|
|
62
|
+
in any Ruby app.
|
|
63
|
+
|
|
64
|
+
```ruby
|
|
65
|
+
gem "ai_alt_text"
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
To resize large images before sending them (recommended), also install
|
|
69
|
+
[image_processing](https://github.com/janko/image_processing) with libvips or
|
|
70
|
+
ImageMagick, as you would for ActiveStorage variants:
|
|
71
|
+
|
|
72
|
+
```ruby
|
|
73
|
+
gem "image_processing", "~> 1.2"
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
## Configuration
|
|
77
|
+
|
|
78
|
+
`bin/rails g ai_alt_text:install` creates this initializer. Only `provider` and
|
|
79
|
+
`api_key` are required. Settings are checked when alt text is generated, not at boot,
|
|
80
|
+
so a missing key never stops your app from starting.
|
|
81
|
+
|
|
82
|
+
```ruby
|
|
83
|
+
AiAltText.configure do |c|
|
|
84
|
+
c.provider = :anthropic
|
|
85
|
+
c.api_key = Rails.application.credentials.dig(:ai_alt_text, :api_key)
|
|
86
|
+
end
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
| Option | Default | Description |
|
|
90
|
+
| --- | --- | --- |
|
|
91
|
+
| `provider` | `nil` | Required. Any RubyLLM provider, such as `:openai`, `:anthropic`, `:gemini`. |
|
|
92
|
+
| `api_key` | `nil` | Required for providers that use a key. Applies to the configured provider. |
|
|
93
|
+
| `model` | `nil` | Model ID. `nil` uses a cheap vision model for the provider (see below). |
|
|
94
|
+
| `max_length` | `125` | Maximum alt text length in characters. |
|
|
95
|
+
| `locale` | `:en` | Language of the generated text, for example `:fr` or `"fr-CA"`. |
|
|
96
|
+
| `max_image_dimension` | `1024` | Longest side in pixels after resizing. |
|
|
97
|
+
| `storage` | `:blob_metadata` | `:blob_metadata` or `:column`. See [Storage modes](#storage-modes). |
|
|
98
|
+
| `queue` | `:default` | ActiveJob queue for generation jobs. |
|
|
99
|
+
| `enabled` | `true` | Kill switch for automatic generation and backfill. `AiAltText.describe` still works. |
|
|
100
|
+
| `prompt` | `nil` | Replaces the built-in prompt: a String, or a callable receiving `max_length:` and `locale:`. |
|
|
101
|
+
| `ruby_llm_options` | `{}` | Extra RubyLLM settings for the gem's isolated context. See below. |
|
|
102
|
+
| `helper_fallback` | `:context` | Alt used by `ai_alt_image_tag` before text exists: `:context`, `:empty`, or a callable receiving the attachment. |
|
|
103
|
+
| `logger` | `Rails.logger` | Where the one-line-per-generation log goes. |
|
|
104
|
+
|
|
105
|
+
The gem never changes your app's global RubyLLM configuration. It works in an isolated
|
|
106
|
+
`RubyLLM.context` that starts from your global settings and applies its own.
|
|
107
|
+
|
|
108
|
+
`ruby_llm_options` passes settings to that context. Use it for providers that need more
|
|
109
|
+
than one key, or to change timeouts. The gem defaults to `request_timeout: 60` and
|
|
110
|
+
`max_retries: 1` so a stuck call cannot hold a worker for minutes; the job retries on
|
|
111
|
+
its own schedule.
|
|
112
|
+
|
|
113
|
+
```ruby
|
|
114
|
+
c.provider = :bedrock
|
|
115
|
+
c.ruby_llm_options = {
|
|
116
|
+
bedrock_api_key: ENV["AWS_ACCESS_KEY_ID"],
|
|
117
|
+
bedrock_secret_key: ENV["AWS_SECRET_ACCESS_KEY"],
|
|
118
|
+
bedrock_region: "us-east-1"
|
|
119
|
+
}
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
## Providers and models
|
|
123
|
+
|
|
124
|
+
When `model` is `nil`, the gem uses a cheap, vision-capable default:
|
|
125
|
+
|
|
126
|
+
| Provider | Default model |
|
|
127
|
+
| --- | --- |
|
|
128
|
+
| `:anthropic` | `claude-haiku-5-5` |
|
|
129
|
+
| `:openai` | `gpt-6-luna` |
|
|
130
|
+
| `:gemini` | `gemini-2.5-flash-lite` |
|
|
131
|
+
|
|
132
|
+
Other providers have no default; set `c.model` to a model that accepts images. Model IDs
|
|
133
|
+
change often, so these defaults are reviewed on every release.
|
|
134
|
+
|
|
135
|
+
You can override the model or provider for a single call:
|
|
136
|
+
|
|
137
|
+
```ruby
|
|
138
|
+
AiAltText.describe(blob, model: "claude-sonnet-5-5")
|
|
139
|
+
AiAltText.describe(blob, provider: :openai) # uses OpenAI's default model
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
`c.api_key` belongs to the configured provider. A per-call provider takes its
|
|
143
|
+
credentials from `ruby_llm_options` or from your global `RubyLLM.configure`.
|
|
144
|
+
|
|
145
|
+
## Rails usage
|
|
146
|
+
|
|
147
|
+
### Declaring attachments
|
|
148
|
+
|
|
149
|
+
```ruby
|
|
150
|
+
class Product < ApplicationRecord
|
|
151
|
+
has_one_attached :photo
|
|
152
|
+
generates_alt_text_for :photo, context: -> { "Product photo for #{name}" }, if: :published?
|
|
153
|
+
end
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
- `context:` tells the model where the image appears, so it can decide what matters. It
|
|
157
|
+
takes a String, a Symbol (method name), or a lambda evaluated on the record.
|
|
158
|
+
- `if:` and `unless:` take a Symbol or a lambda.
|
|
159
|
+
- Generation runs in `AiAltText::GenerateJob` after the record is committed, never in the
|
|
160
|
+
web request. If enqueueing fails (for example, your queue is down), the error is logged
|
|
161
|
+
and your save still succeeds.
|
|
162
|
+
|
|
163
|
+
This adds:
|
|
164
|
+
|
|
165
|
+
```ruby
|
|
166
|
+
product.photo_alt_text # => "Brown leather hiking boot with red laces"
|
|
167
|
+
product.photo_alt_text = "My own" # human text, saved with the record
|
|
168
|
+
product.regenerate_photo_alt_text # enqueue a fresh generation
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
### Human-written alt text
|
|
172
|
+
|
|
173
|
+
Text you set yourself is stored with `source: "human"` and is never overwritten, not even
|
|
174
|
+
by `regenerate_photo_alt_text`. Assign `""` to mark an image decorative. Assign `nil` to
|
|
175
|
+
clear it so alt text can be generated again.
|
|
176
|
+
|
|
177
|
+
### has_many_attached
|
|
178
|
+
|
|
179
|
+
```ruby
|
|
180
|
+
class Gallery < ApplicationRecord
|
|
181
|
+
has_many_attached :images
|
|
182
|
+
generates_alt_text_for :images, context: :title
|
|
183
|
+
end
|
|
184
|
+
|
|
185
|
+
gallery.images_alt_text # => ["Front view of the tent", "Tent packed in its bag"]
|
|
186
|
+
gallery.update!(images_alt_text: { gallery.images.first => "Front view" }) # attachment or id
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
### The view helper
|
|
190
|
+
|
|
191
|
+
```erb
|
|
192
|
+
<%= ai_alt_image_tag @product.photo, class: "hero" %>
|
|
193
|
+
<%= ai_alt_image_tag @product.photo, alt: "Explicit text always wins" %>
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
The helper uses, in order: an explicit `alt:`, the stored alt text, then the fallback
|
|
197
|
+
(`helper_fallback`). It never calls the model and never raises; if anything goes wrong
|
|
198
|
+
it renders `alt=""`. It renders nothing when no image is attached. It does not change
|
|
199
|
+
Rails' `image_tag`.
|
|
200
|
+
|
|
201
|
+
## Standalone usage
|
|
202
|
+
|
|
203
|
+
The core has no Rails dependency.
|
|
204
|
+
|
|
205
|
+
```ruby
|
|
206
|
+
AiAltText.describe("cat.jpg") # => "Tabby cat asleep on a windowsill"
|
|
207
|
+
AiAltText.describe(File.open("boot.jpg"), context: "Product photo") # IO objects work too
|
|
208
|
+
AiAltText.describe(blob) # ActiveStorage blob or attachment
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
`describe` returns a String, or `""` for a decorative image. `AiAltText.generate` takes
|
|
212
|
+
the same arguments and returns a result with `text`, `decorative`, `model`,
|
|
213
|
+
`input_tokens`, `output_tokens`, `cost` and `duration`.
|
|
214
|
+
|
|
215
|
+
URLs are refused on purpose: fetching arbitrary URLs is a server-side request forgery
|
|
216
|
+
risk. Download the image yourself and pass the file or IO.
|
|
217
|
+
|
|
218
|
+
### Errors
|
|
219
|
+
|
|
220
|
+
All errors inherit from `AiAltText::Error`:
|
|
221
|
+
|
|
222
|
+
| Error | Raised when |
|
|
223
|
+
| --- | --- |
|
|
224
|
+
| `ConfigurationError` | Provider, key or model is missing or rejected. The message says how to fix it. |
|
|
225
|
+
| `UnsupportedFormatError` | The image is not JPEG, PNG, GIF or WebP. |
|
|
226
|
+
| `ImageTooLargeError` | A subclass of `UnsupportedFormatError`: the image is too big to send and `image_processing` is not installed. |
|
|
227
|
+
| `GenerationError` | The provider failed or returned unusable text. |
|
|
228
|
+
| `TransientError` | A subclass of `GenerationError`: rate limits, overload, timeouts. Worth retrying. |
|
|
229
|
+
|
|
230
|
+
In the background job, transient errors are retried with growing delays (5 attempts),
|
|
231
|
+
unusable output is retried once, unsupported formats are skipped with a log line, and
|
|
232
|
+
jobs for deleted records are discarded. Final failures are logged, not raised.
|
|
233
|
+
|
|
234
|
+
## Storage modes
|
|
235
|
+
|
|
236
|
+
Each image gets a small record:
|
|
237
|
+
|
|
238
|
+
```ruby
|
|
239
|
+
{ "text" => "...", "source" => "ai", "model" => "...", "generated_at" => "...", "decorative" => false }
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
**`:blob_metadata`** (default) stores it under `blob.metadata["ai_alt_text"]`. No
|
|
243
|
+
migration is needed. Alt text belongs to the blob, so a blob attached to several records
|
|
244
|
+
shares one alt text.
|
|
245
|
+
|
|
246
|
+
**`:column`** stores it in a JSON column on the owning record, so the same blob can have
|
|
247
|
+
different alt text in different places. Generate the column for each attachment:
|
|
248
|
+
|
|
249
|
+
```sh
|
|
250
|
+
bin/rails g ai_alt_text:column Product photo # adds products.photo_alt_text_data
|
|
251
|
+
bin/rails db:migrate
|
|
252
|
+
```
|
|
253
|
+
|
|
254
|
+
```ruby
|
|
255
|
+
c.storage = :column
|
|
256
|
+
```
|
|
257
|
+
|
|
258
|
+
## Backfilling existing images
|
|
259
|
+
|
|
260
|
+
```sh
|
|
261
|
+
bin/rails ai_alt_text:backfill MODEL=Product ATTACHMENT=photo DRY_RUN=1
|
|
262
|
+
bin/rails ai_alt_text:backfill MODEL=Product ATTACHMENT=photo LIMIT=500
|
|
263
|
+
```
|
|
264
|
+
|
|
265
|
+
The task finds images with no alt text, prints the count and a rough cost estimate, and
|
|
266
|
+
enqueues one job per image. It processes records in batches, skips unsupported formats,
|
|
267
|
+
and leaves existing alt text (AI or human) alone. `DRY_RUN=1` only prints the report.
|
|
268
|
+
|
|
269
|
+
## Testing your app
|
|
270
|
+
|
|
271
|
+
Your test suite should never call a provider. Turn on stub mode:
|
|
272
|
+
|
|
273
|
+
```ruby
|
|
274
|
+
# spec/rails_helper.rb or test/test_helper.rb
|
|
275
|
+
require "ai_alt_text/testing"
|
|
276
|
+
AiAltText::Testing.stub!(text: "Stubbed alt text")
|
|
277
|
+
```
|
|
278
|
+
|
|
279
|
+
Stub mode needs no API key. Images still go through format checks, so an SVG still
|
|
280
|
+
raises `UnsupportedFormatError`. You can also pass a callable, stub decorative images,
|
|
281
|
+
and inspect calls:
|
|
282
|
+
|
|
283
|
+
```ruby
|
|
284
|
+
AiAltText::Testing.stub!(text: ->(image, context) { "Alt for #{image.filename}" })
|
|
285
|
+
AiAltText::Testing.stub!(decorative: true)
|
|
286
|
+
AiAltText::Testing.calls # => [{ filename: "boot.jpg", mime_type: "image/jpeg", context: "..." }]
|
|
287
|
+
AiAltText::Testing.unstub!
|
|
288
|
+
```
|
|
289
|
+
|
|
290
|
+
## Privacy
|
|
291
|
+
|
|
292
|
+
- Images are sent to the provider you configure, as image data. Storage URLs are never
|
|
293
|
+
sent, so private buckets stay private.
|
|
294
|
+
- The prompt tells the model never to identify real people by name, never to guess
|
|
295
|
+
sensitive attributes such as race, ethnicity, health, religion or age, and never to
|
|
296
|
+
repeat sensitive data visible in the image, such as card numbers, ID numbers or
|
|
297
|
+
addresses. Models can still make mistakes.
|
|
298
|
+
- API keys, image bytes and base64 data are never logged.
|
|
299
|
+
- Generated alt text is a good default, not a guarantee. Review it for important images,
|
|
300
|
+
and set your own text with `photo_alt_text =` where it matters.
|
|
301
|
+
|
|
302
|
+
## Cost
|
|
303
|
+
|
|
304
|
+
Images are resized to `max_image_dimension` (1024 px by default) before sending, which
|
|
305
|
+
keeps token usage and cost low. The default models cost a fraction of a cent per image.
|
|
306
|
+
Each generation logs its token counts and cost, and the backfill task prints an estimate
|
|
307
|
+
before it runs.
|
|
308
|
+
|
|
309
|
+
## Limitations
|
|
310
|
+
|
|
311
|
+
- Alt text only. No captions, titles, or SEO text.
|
|
312
|
+
- JPEG, PNG, GIF and WebP only. SVG, HEIC, video and PDF are skipped.
|
|
313
|
+
- Images are never fetched from URLs.
|
|
314
|
+
- Without `image_processing`, images over 3.75 MB are skipped rather than sent unresized.
|
|
315
|
+
- Animated GIFs are described from their first frame when resized.
|
|
316
|
+
- With `:blob_metadata` storage, alt text is shared by every record using the same blob.
|
|
317
|
+
- Generated text depends on the model. It is usually good, but review important images.
|
|
318
|
+
|
|
319
|
+
## Development
|
|
320
|
+
|
|
321
|
+
```sh
|
|
322
|
+
bundle install
|
|
323
|
+
bundle exec rspec # no network access needed
|
|
324
|
+
bundle exec rubocop
|
|
325
|
+
BUNDLE_GEMFILE=gemfiles/rails_7_1.gemfile bundle exec rspec # other Rails versions
|
|
326
|
+
```
|
|
327
|
+
|
|
328
|
+
A live smoke test against a real provider runs only when you ask for it:
|
|
329
|
+
|
|
330
|
+
```sh
|
|
331
|
+
AI_ALT_TEXT_LIVE=1 AI_ALT_TEXT_PROVIDER=gemini AI_ALT_TEXT_API_KEY=... bundle exec rspec spec/ai_alt_text_live_spec.rb
|
|
332
|
+
```
|
|
333
|
+
|
|
334
|
+
## License
|
|
335
|
+
|
|
336
|
+
MIT. See [LICENSE.txt](LICENSE.txt).
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module AiAltText
|
|
4
|
+
# Generates and stores alt text for one attachment, outside the web request.
|
|
5
|
+
class GenerateJob < ActiveJob::Base
|
|
6
|
+
queue_as { AiAltText.configuration.queue }
|
|
7
|
+
|
|
8
|
+
# Handlers declared later win, so the TransientError subclass comes after GenerationError.
|
|
9
|
+
# Unusable output may be a one-off: try once more, then log and drop it.
|
|
10
|
+
retry_on AiAltText::GenerationError, wait: 5.seconds, attempts: 2 do |job, error|
|
|
11
|
+
job.give_up(error)
|
|
12
|
+
end
|
|
13
|
+
retry_on AiAltText::TransientError, wait: :polynomially_longer, attempts: 5 do |job, error|
|
|
14
|
+
job.give_up(error)
|
|
15
|
+
end
|
|
16
|
+
# The upload can still be in flight when the job starts.
|
|
17
|
+
retry_on ActiveStorage::FileNotFoundError, wait: 5.seconds, attempts: 3
|
|
18
|
+
discard_on ActiveJob::DeserializationError, ActiveRecord::RecordNotFound
|
|
19
|
+
|
|
20
|
+
# @param attachment [ActiveStorage::Attachment]
|
|
21
|
+
# @param regenerate [Boolean] replace existing AI text (human text is always kept)
|
|
22
|
+
def perform(attachment, regenerate: false)
|
|
23
|
+
config = AiAltText.configuration
|
|
24
|
+
return unless config.enabled
|
|
25
|
+
|
|
26
|
+
store = Store.for(config)
|
|
27
|
+
return if keep_existing?(store.read(attachment), regenerate)
|
|
28
|
+
|
|
29
|
+
store.write(attachment, generate(attachment, config), protect_human: true)
|
|
30
|
+
rescue UnsupportedFormatError => e
|
|
31
|
+
config.logger.info("[ai_alt_text] Skipped #{attachment.blob.filename}: #{e.message}")
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
# Logs a final failure instead of leaving it in the queue's failed jobs.
|
|
35
|
+
def give_up(error)
|
|
36
|
+
AiAltText.configuration.logger.error(
|
|
37
|
+
"[ai_alt_text] Gave up on attachment #{arguments.first.try(:id)} after #{executions} attempts: " \
|
|
38
|
+
"#{error.class}: #{error.message}"
|
|
39
|
+
)
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
private
|
|
43
|
+
|
|
44
|
+
def keep_existing?(existing, regenerate)
|
|
45
|
+
existing && (existing["source"] == "human" || !regenerate)
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
def generate(attachment, config)
|
|
49
|
+
analyze(attachment.blob)
|
|
50
|
+
context = Model.context_for(attachment.record, attachment.name)
|
|
51
|
+
record_for(Describer.new(config).call(attachment.blob, context: context))
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
# Analysis metadata is not needed for correctness; this just avoids racing
|
|
55
|
+
# ActiveStorage's AnalyzeJob on the blob's metadata column.
|
|
56
|
+
def analyze(blob)
|
|
57
|
+
blob.analyze unless blob.analyzed?
|
|
58
|
+
rescue StandardError => e
|
|
59
|
+
AiAltText.configuration.logger.warn("[ai_alt_text] Blob analysis failed (#{e.class}); continuing.")
|
|
60
|
+
end
|
|
61
|
+
|
|
62
|
+
def record_for(result)
|
|
63
|
+
{
|
|
64
|
+
"text" => result.text, "source" => "ai", "model" => result.model, "decorative" => result.decorative,
|
|
65
|
+
"generated_at" => Time.now.utc.iso8601, "prompt_version" => result.prompt_version
|
|
66
|
+
}
|
|
67
|
+
end
|
|
68
|
+
end
|
|
69
|
+
end
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module AiAltText
|
|
4
|
+
# Enqueues generation for existing images that have no alt text yet.
|
|
5
|
+
# Used by: rails ai_alt_text:backfill MODEL=Product ATTACHMENT=photo [LIMIT=100] [DRY_RUN=1]
|
|
6
|
+
class Backfill
|
|
7
|
+
SUPPORTED_TYPES = ImagePreparer::SIGNATURES.keys.freeze
|
|
8
|
+
# Rough per-image usage for the cost estimate: prompt plus a ~1024px image.
|
|
9
|
+
ESTIMATED_INPUT_TOKENS = 1_600
|
|
10
|
+
ESTIMATED_OUTPUT_TOKENS = 40
|
|
11
|
+
|
|
12
|
+
# @param model [String] model class name, e.g. "Product"
|
|
13
|
+
# @param attachment [String, Symbol] attachment name, e.g. "photo"
|
|
14
|
+
# @param limit [Integer, nil] maximum number of jobs to enqueue
|
|
15
|
+
# @param dry_run [Boolean] only report what would be enqueued
|
|
16
|
+
# @param batch_size [Integer] find_each batch size
|
|
17
|
+
# @param output [IO] where the report is printed
|
|
18
|
+
# @raise [ArgumentError] when the model or attachment does not exist
|
|
19
|
+
def initialize(model:, attachment:, limit: nil, dry_run: false, batch_size: 100, output: $stdout,
|
|
20
|
+
config: AiAltText.configuration)
|
|
21
|
+
@model = model.to_s.safe_constantize
|
|
22
|
+
unless @model.is_a?(Class) && @model < ActiveRecord::Base
|
|
23
|
+
raise ArgumentError, "MODEL=#{model} is not an ActiveRecord model."
|
|
24
|
+
end
|
|
25
|
+
unless @model.reflect_on_attachment(attachment)
|
|
26
|
+
raise ArgumentError,
|
|
27
|
+
"ATTACHMENT=#{attachment} is not an attachment on #{model}."
|
|
28
|
+
end
|
|
29
|
+
|
|
30
|
+
@attachment = attachment.to_s
|
|
31
|
+
@limit = limit
|
|
32
|
+
@dry_run = dry_run
|
|
33
|
+
@batch_size = batch_size
|
|
34
|
+
@output = output
|
|
35
|
+
@config = config
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
# @return [Integer] the number of images found (and enqueued unless dry run)
|
|
39
|
+
# @raise [ConfigurationError] when generation is disabled
|
|
40
|
+
def run
|
|
41
|
+
unless @config.enabled
|
|
42
|
+
raise ConfigurationError,
|
|
43
|
+
"AiAltText is disabled (c.enabled = false). Enable it to backfill."
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
ids = pending_ids
|
|
47
|
+
report(ids.size)
|
|
48
|
+
ids.each_slice(@batch_size) { |slice| enqueue(slice) } unless @dry_run
|
|
49
|
+
ids.size
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
private
|
|
53
|
+
|
|
54
|
+
def pending_ids
|
|
55
|
+
store = Store.for(@config)
|
|
56
|
+
ids = []
|
|
57
|
+
scope.find_each(batch_size: @batch_size) do |attachment|
|
|
58
|
+
next unless SUPPORTED_TYPES.include?(attachment.blob.content_type)
|
|
59
|
+
next if store.read(attachment)
|
|
60
|
+
|
|
61
|
+
ids << attachment.id
|
|
62
|
+
break if @limit && ids.size >= @limit
|
|
63
|
+
end
|
|
64
|
+
ids
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
def scope
|
|
68
|
+
ActiveStorage::Attachment.where(record_type: @model.base_class.name, name: @attachment).includes(:blob, :record)
|
|
69
|
+
end
|
|
70
|
+
|
|
71
|
+
def enqueue(ids)
|
|
72
|
+
ActiveStorage::Attachment.where(id: ids).find_each { |attachment| GenerateJob.perform_later(attachment) }
|
|
73
|
+
end
|
|
74
|
+
|
|
75
|
+
def report(count)
|
|
76
|
+
noun = count == 1 ? "image" : "images"
|
|
77
|
+
@output.puts "Found #{count} #{noun} without alt text for #{@model.name}##{@attachment}."
|
|
78
|
+
estimate = cost_estimate(count)
|
|
79
|
+
@output.puts estimate if estimate
|
|
80
|
+
@output.puts(@dry_run ? "Dry run: no jobs enqueued." : "Enqueuing #{count} jobs on the #{@config.queue} queue.")
|
|
81
|
+
end
|
|
82
|
+
|
|
83
|
+
def cost_estimate(count)
|
|
84
|
+
model = @config.model || DefaultModels.for(@config.provider)
|
|
85
|
+
per_image = cost_per_image(model)
|
|
86
|
+
return unless per_image
|
|
87
|
+
|
|
88
|
+
format("Estimated cost with %<model>s: ~$%<cost>.4f (rough: about %<in>d input and %<out>d output " \
|
|
89
|
+
"tokens per image).", model: model, cost: per_image * count,
|
|
90
|
+
in: ESTIMATED_INPUT_TOKENS, out: ESTIMATED_OUTPUT_TOKENS)
|
|
91
|
+
rescue StandardError
|
|
92
|
+
nil
|
|
93
|
+
end
|
|
94
|
+
|
|
95
|
+
def cost_per_image(model)
|
|
96
|
+
prices = RubyLLM.models.find(model, provider: @config.provider).pricing.text_tokens
|
|
97
|
+
return unless prices.input && prices.output
|
|
98
|
+
|
|
99
|
+
((ESTIMATED_INPUT_TOKENS * prices.input) + (ESTIMATED_OUTPUT_TOKENS * prices.output)) / 1_000_000.0
|
|
100
|
+
end
|
|
101
|
+
end
|
|
102
|
+
end
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "logger"
|
|
4
|
+
|
|
5
|
+
module AiAltText
|
|
6
|
+
# Settings for alt text generation. Set them with {AiAltText.configure}.
|
|
7
|
+
# Nothing is validated at boot; {#validate!} runs when a generation starts.
|
|
8
|
+
class Configuration
|
|
9
|
+
STORAGE_MODES = %i[blob_metadata column].freeze
|
|
10
|
+
|
|
11
|
+
attr_accessor :api_key, :model, :max_length, :locale, :max_image_dimension,
|
|
12
|
+
:storage, :queue, :enabled, :prompt, :ruby_llm_options, :helper_fallback
|
|
13
|
+
attr_reader :provider
|
|
14
|
+
attr_writer :logger
|
|
15
|
+
|
|
16
|
+
class << self
|
|
17
|
+
# Logger used when none is configured. The Rails engine sets it to Rails.logger.
|
|
18
|
+
attr_writer :default_logger
|
|
19
|
+
|
|
20
|
+
def default_logger
|
|
21
|
+
@default_logger ||= Logger.new($stderr, progname: "ai_alt_text")
|
|
22
|
+
end
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
def initialize
|
|
26
|
+
@provider = nil
|
|
27
|
+
@api_key = nil
|
|
28
|
+
@model = nil
|
|
29
|
+
@max_length = 125
|
|
30
|
+
@locale = :en
|
|
31
|
+
@max_image_dimension = 1024
|
|
32
|
+
@storage = :blob_metadata
|
|
33
|
+
@queue = :default
|
|
34
|
+
@enabled = true
|
|
35
|
+
@prompt = nil
|
|
36
|
+
@ruby_llm_options = {}
|
|
37
|
+
@helper_fallback = :context
|
|
38
|
+
@logger = nil
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
# @param value [Symbol, String, nil] a RubyLLM provider slug, e.g. :anthropic
|
|
42
|
+
def provider=(value)
|
|
43
|
+
@provider = value&.to_sym
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
# @return [Logger] the configured logger, Rails.logger in Rails apps, or stderr
|
|
47
|
+
def logger
|
|
48
|
+
@logger || self.class.default_logger
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
# Checks the settings needed to generate alt text.
|
|
52
|
+
#
|
|
53
|
+
# @param provider [Symbol] provider to check, defaults to the configured one.
|
|
54
|
+
# The API key is only required for the configured provider; other
|
|
55
|
+
# providers take credentials from +ruby_llm_options+ or RubyLLM's own config.
|
|
56
|
+
# @raise [ConfigurationError] with a message explaining the fix
|
|
57
|
+
# @return [true]
|
|
58
|
+
def validate!(provider: self.provider)
|
|
59
|
+
validate_provider!(provider)
|
|
60
|
+
validate_api_key! if provider == self.provider
|
|
61
|
+
validate_positive!(:max_length)
|
|
62
|
+
validate_positive!(:max_image_dimension)
|
|
63
|
+
return true if STORAGE_MODES.include?(storage)
|
|
64
|
+
|
|
65
|
+
raise ConfigurationError, "storage must be one of #{STORAGE_MODES.map(&:inspect).join(", ")}, " \
|
|
66
|
+
"got #{storage.inspect}."
|
|
67
|
+
end
|
|
68
|
+
|
|
69
|
+
def inspect
|
|
70
|
+
"#<#{self.class.name} provider=#{provider.inspect} model=#{model.inspect} " \
|
|
71
|
+
"api_key=#{api_key ? "[FILTERED]" : "nil"}>"
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
private
|
|
75
|
+
|
|
76
|
+
def validate_provider!(provider)
|
|
77
|
+
if provider.nil?
|
|
78
|
+
raise ConfigurationError, "AiAltText provider is not set. Add it in your initializer, " \
|
|
79
|
+
"for example: AiAltText.configure { |c| c.provider = :openai }"
|
|
80
|
+
end
|
|
81
|
+
return if Providers.known?(provider)
|
|
82
|
+
|
|
83
|
+
raise ConfigurationError, "Unknown provider #{provider.inspect}. " \
|
|
84
|
+
"Supported providers: #{Providers.names.join(", ")}."
|
|
85
|
+
end
|
|
86
|
+
|
|
87
|
+
def validate_api_key!
|
|
88
|
+
return if api_key || !Providers.api_key_option(provider)
|
|
89
|
+
|
|
90
|
+
raise ConfigurationError, "AiAltText API key is missing for #{provider}. Set it in your " \
|
|
91
|
+
"initializer: AiAltText.configure { |c| c.api_key = ... }"
|
|
92
|
+
end
|
|
93
|
+
|
|
94
|
+
def validate_positive!(name)
|
|
95
|
+
value = public_send(name)
|
|
96
|
+
return if value.is_a?(Integer) && value.positive?
|
|
97
|
+
|
|
98
|
+
raise ConfigurationError, "#{name} must be a positive integer, got #{value.inspect}."
|
|
99
|
+
end
|
|
100
|
+
end
|
|
101
|
+
end
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module AiAltText
|
|
4
|
+
# Cheap, vision-capable default model per provider, used when +c.model+ is nil.
|
|
5
|
+
#
|
|
6
|
+
# MAINTAINERS: model IDs change often. Review this list on every release
|
|
7
|
+
# against RubyLLM's registry (spec/ai_alt_text/default_models_spec.rb checks
|
|
8
|
+
# that each ID exists and accepts image input).
|
|
9
|
+
module DefaultModels
|
|
10
|
+
MODELS = {
|
|
11
|
+
anthropic: "claude-haiku-5-5",
|
|
12
|
+
openai: "gpt-6-luna",
|
|
13
|
+
# gemini-3.1-flash-lite returned 503 "high demand" in testing (2026-11); 2.5 is reliable.
|
|
14
|
+
gemini: "gemini-2.5-flash-lite"
|
|
15
|
+
}.freeze
|
|
16
|
+
|
|
17
|
+
# @param provider [Symbol, String]
|
|
18
|
+
# @return [String, nil] the default model ID, or nil when there is none
|
|
19
|
+
def self.for(provider)
|
|
20
|
+
MODELS[provider&.to_sym]
|
|
21
|
+
end
|
|
22
|
+
end
|
|
23
|
+
end
|