GrepBoard/Manuals
605 manuals ·

Check AI-written image alt text with a rule script

·Tested on Claude Sonnet (sonnet alias) · Claude Code · Python 3.12 · Ubuntu 24.04 · 2026-10 · W3C WAI images tutorial·Test scope ↓·8 steps

Extract img alt values with Python, flag missing, empty-in-link, file-name, "image of" and overlong ones, then have AI rewrite only those using the nearby text.

Ask an AI for alt text and values like alt="Image of a chart" slip through. An empty alt is sometimes correct, so "empty means fail" is the wrong check. For a similar script that only counts characters, see checking meta descriptions for length and duplicates.

[1] Read the W3C images decision tree before writing rules. It shows what a script can judge and what it cannot.

Imagealt the tree recommends
Decorativean empty alt attribute
In a link or button, hard to understand without the imagecommunicate the destination or action
Simple photo or graphica brief description that conveys the meaning
Graph or other complex informationput the information elsewhere on the page
Content redundant to nearby textan empty alt attribute

The site's tips page says there is usually no need to include words like "image", "icon" or "picture", and that alt should be the most concise description of the image's purpose. Neither page gives a character limit. The 125 below is a team rule; change it freely.

[2] Create a test page with nine images and deliberate problems. The text and file names are made up.

page.html
<!doctype html><html lang="en"><body><header><a href="/"><img src="logo.svg" alt=""></a></header><h1>Winter trail report</h1><p>The ridge loop reopened on 12 December after a rockfall near the second hut. Snow depth at the summit is 40 cm, and the creek crossing is frozen.</p><img src="IMG_4821.jpg" alt="IMG_4821.jpg"><p>Water levels at the lower gauge peaked at 3.2 m in November and fell back below 1 m by the first week of December.</p><img src="gauge.png" alt="Image of a chart"><img src="hut.jpg"><figure><img src="summit.jpg" alt="Photo of a snowy summit with a wooden marker and two hikers in red jackets standing beside it while clouds clear behind them and the valley below fills with morning light and long shadows"><figcaption>Summit marker, 12 December</figcaption></figure><p>Download the <a href="map.pdf"><img src="pdf-icon.svg" alt="icon"></a> trail map.</p><a href="/closures/"><img src="closed.png" alt=""></a><img src="divider.png" alt=""><img src="crossing.jpg" alt="Picture of picture of the frozen creek crossing"></body></html>

[3] Write the checker. It uses only html.parser from the standard library. An empty alt fails only when the image sits in a link with no text of its own. Other empty values may be decorative, so they pass and are left for a human to scan.

check_alt.py
#!/usr/bin/env python3"""usage: check_alt.py page.html [MAX] — missing alt, empty alt in a link, filename, 'image of', length"""import re, sysfrom html.parser import HTMLParser MAX = int(sys.argv[2]) if len(sys.argv) > 2 else 125PREFIX = re.compile(r"^\s*(image|picture|photo|graphic|icon)\b(\s+of)?", re.I)FILE = re.compile(r"\.(jpe?g|png|gif|webp|svg)$|^img[_-]?\d+", re.I) class P(HTMLParser):    def __init__(self):        super().__init__()        self.in_a = 0        self.a_text = ""        self.pending = []   # (line, attrs) of imgs inside the current <a>        self.rows = []    def handle_starttag(self, tag, attrs):        a = dict(attrs)        if tag == "a":            self.in_a += 1; self.a_text = ""; self.pending = []        if tag == "img":            self.rows.append([self.getpos()[0], a, self.in_a > 0])            if self.in_a: self.pending.append(self.rows[-1])    def handle_data(self, data):        if self.in_a: self.a_text += data.strip()    def handle_endtag(self, tag):        if tag == "a" and self.in_a:            self.in_a -= 1            for r in self.pending:                r.append(bool(self.a_text))   # link has its own text            self.pending = [] p = P(); p.feed(open(sys.argv[1], encoding="utf-8").read())bad = 0for r in p.rows:    line, a, in_a = r[0], r[1], r[2]    link_text = r[3] if len(r) > 3 else False    errs = []    if "alt" not in a:        errs.append("no alt attribute")    else:        alt = " ".join(a["alt"].split())        if alt == "" and in_a and not link_text:            errs.append("empty alt, link has no text")        if alt:            if FILE.search(alt): errs.append("looks like a file name")            if PREFIX.match(alt): errs.append("starts with image/picture/photo/icon")            if len(alt) > MAX: errs.append(f"length {len(alt)} > {MAX}")    src = a.get("src", "?")    print(f"line {line} {src} {'FAIL ' + '; '.join(errs) if errs else 'ok'}")    bad += bool(errs)print(f"{len(p.rows)} images, {bad} failed")sys.exit(1 if bad else 0)

[4] Run it. -I is isolated mode, so Python does not import modules from the current folder.

console
$ python3 -I check_alt.py page.html; echo "exit $?"line 3 logo.svg FAIL empty alt, link has no textline 6 IMG_4821.jpg FAIL looks like a file nameline 8 gauge.png FAIL starts with image/picture/photo/iconline 9 hut.jpg FAIL no alt attributeline 10 summit.jpg FAIL starts with image/picture/photo/icon; length 187 > 125line 11 pdf-icon.svg FAIL starts with image/picture/photo/iconline 12 closed.png FAIL empty alt, link has no textline 13 divider.png okline 14 crossing.jpg FAIL starts with image/picture/photo/icon9 images, 8 failedexit 1

The empty alt on divider.png passed. The script cannot tell whether it really is decorative.

[5] Write one line of notes per flagged image. Instead of showing the AI the pictures, give it notes on what each picture shows. The notes stay identical in both runs; only the surrounding text and link info change. This test sent six images, leaving out summit.jpg and crossing.jpg.

images.txt
logo.svg | site logo, the word "Trailnote" with a small mountain mark | inside a link to /IMG_4821.jpg | photo of a wooden footbridge over a creek, ice on both banks | no linkgauge.png | line chart, water level at the lower gauge by week, Nov peak 3.2 m, below 1 m in the first week of December | no linkhut.jpg | photo of the second hut, boulders lying across the path in front of it | no linkpdf-icon.svg | small red PDF file icon | inside a link to map.pdf, link has no other textclosed.png | red round sign with the word CLOSED | inside a link to /closures/, link has no other text

[6] Build two prompts. The rules are the same. Only the second one gets ctx.txt (the three nearby paragraphs and the page title).

rules.txt
Write alt text for each image below. Rules:- Under 100 characters.- Do not start with "image of", "photo of" or "picture of".- Describe only what the notes say. Do not invent details.- For an image alone inside a link, describe where the link goes.- Output one JSON object per line: {"src": "...", "alt": "..."}. No other text, no code fences. 
console
$ cat rules.txt > pA.txt; echo "Images (src | what the picture shows | placement):" >> pA.txt; cat images.txt >> pA.txt$ cat rules.txt ctx.txt > pB.txt; echo >> pB.txt; echo "Images (src | what the picture shows | placement):" >> pB.txt; cat images.txt >> pB.txt$ claude -p --model sonnet --max-turns 1 < pA.txt > outA.jsonl$ claude -p --model sonnet --max-turns 1 < pB.txt > outB.jsonl

[7] Compare. Of the six, four came out identical or nearly so; the two images inside links differed.

srcNo context (A)With context (B)
pdf-icon.svgMap (PDF)Download the trail map (PDF)
closed.pngClosuresTrail closures
gauge.png…weekly lower gauge water level: peak 3.2 m in November……weekly water level at the lower gauge: 3.2 m peak in November…

For the link images, B followed the surrounding sentence ("Download the … trail map") and the page topic. Six images, one run each, is too few to claim context always helps. The photo descriptions were practically the same in both runs, because the model stuck to the notes.

[8] Put the results back and re-check. The script below replaces the alt of the <img> with the same src, or adds one.

apply_alt.py
#!/usr/bin/env python3"""usage: apply_alt.py page.html alts.jsonl > fixed.html — replace or add alt for each src"""import sys, json, re, htmlpage = open(sys.argv[1], encoding="utf-8").read()for line in open(sys.argv[2], encoding="utf-8"):    if not line.strip(): continue    r = json.loads(line)    pat = re.compile(r'<img src="%s"( alt="[^"]*")?' % re.escape(r["src"]))    page = pat.sub(lambda m: '<img src="%s" alt="%s"' % (r["src"], html.escape(r["alt"], quote=True)), page)sys.stdout.write(page)
console
$ python3 -I apply_alt.py page.html outB.jsonl > fixed.html$ python3 -I check_alt.py fixed.html | grep -v ' ok$'line 10 summit.jpg FAIL starts with image/picture/photo/icon; length 187 > 125line 14 crossing.jpg FAIL starts with image/picture/photo/icon9 images, 2 failed

The two left were never sent to the AI. Reaching zero does not mean done: the checker passes alt="Closures" and it would pass a wrong description just as well. A person still checks that the text matches the image, and that it does not repeat the nearby text (the tree recommends an empty alt in that case).

#alt-text#accessibility#python