AI 가 쓴 이미지 대체 텍스트를 규칙으로 검사하기
HTML 의 img alt 를 파이썬으로 뽑아 누락·빈 값·파일명·「image of」·긴 값을 검사하고, 걸린 것만 주변 문단과 함께 AI 에게 다시 쓰게 하는 방법입니다.
alt 를 AI 에게 맡기면 alt="Image of a chart" 같은 값이 섞여 나옵니다. 빈 alt 는 오류가 아닐 때도 있어서, 검사는 「비었으면 실패」로 끝나지 않습니다. 글자 수만 세는 비슷한 검사는 메타 설명 길이·중복 검사에 있습니다.
[1] 규칙을 정하기 전에 W3C 이미지 결정 트리를 읽습니다. 스크립트가 판단할 수 있는 것과 없는 것이 여기서 갈립니다.
| 이미지 | 트리가 권하는 alt |
|---|---|
| 장식용 | 빈 alt 속성 |
| 링크·버튼 안, 이미지 없이는 이해가 어려운 경우 | 링크의 목적지나 동작을 전달 |
| 단순한 사진·그래픽 | 의미를 전하는 짧은 설명 |
| 그래프 같은 복잡한 정보 | 그 정보를 페이지의 다른 곳에 함께 적음 |
| 근처 본문과 겹치는 내용 | 빈 alt 속성 |
같은 사이트의 팁 페이지는 「image」·「icon」·「picture」 같은 단어는 보통 넣을 필요가 없다고 하고, alt 는 이미지 목적을 가장 간결하게 설명한 글이어야 한다고 합니다. 길이 상한 숫자는 두 페이지 어디에도 없습니다. 아래 125자는 팀 규칙이고 바꿔도 됩니다.
[2] 시험용 HTML 을 만듭니다. 일부러 문제를 넣은 9개 이미지입니다. 문단과 파일명은 모두 지어낸 것입니다.
<!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] 검사 스크립트를 만듭니다. 표준 라이브러리의 html.parser 만 씁니다. 빈 alt 는 이미지가 텍스트 없는 링크 안에 있을 때만 실패로 봅니다. 그 밖의 빈 alt 는 장식용일 수 있어서 통과시키고, 사람이 훑어볼 몫으로 남깁니다.
#!/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] 실행합니다. -I 는 현재 폴더의 모듈을 끌어오지 않게 하는 격리 모드입니다.
$ 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 1divider.png 의 빈 alt 는 통과했습니다. 장식용이 맞는지는 스크립트가 알 수 없습니다.
[5] 걸린 이미지의 정보를 한 줄씩 적습니다. 이미지를 AI 에게 직접 보여 주는 대신 무엇이 찍혔는지 메모를 줍니다. 두 번의 실행에서 이 메모는 같게 두고, 주변 문단과 링크 정보를 넣느냐만 바꿉니다. 이 시험에서는 summit.jpg·crossing.jpg 를 뺀 6개만 보냈습니다.
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] 프롬프트 두 개를 만듭니다. 규칙 부분은 같습니다. 두 번째에만 ctx.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. $ 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] 두 결과를 비교합니다. 6개 중 4개는 글자까지 같거나 거의 같았고, 링크 안 이미지 2개가 달랐습니다.
| src | 문맥 없음(A) | 문맥 있음(B) |
|---|---|---|
pdf-icon.svg | Map (PDF) | Download the trail map (PDF) |
closed.png | Closures | Trail 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… |
링크 문구는 B 쪽이 주변 문장(「Download the … trail map」)과 페이지 주제(트레일)를 따라갔습니다. 문맥이 있으면 좋아진다고 일반화하기에는 표본이 6개뿐이고 한 번씩만 돌렸습니다. 사진 설명은 두 실행이 사실상 같았습니다. 메모에 있는 내용 이상은 쓰지 않았기 때문입니다.
[8] 결과를 HTML 에 되돌려 다시 검사합니다. 아래 스크립트는 src 가 같은 <img> 의 alt 를 바꾸거나 없으면 넣습니다.
#!/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)$ 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남은 둘은 AI 에게 보내지 않은 것입니다. 이 숫자가 0 이 되어도 끝난 것은 아닙니다. 규칙 검사는 alt="Closures" 도, 엉뚱한 설명도 통과시킵니다. 설명이 이미지와 맞는지, 근처 본문과 같은 말을 되풀이하지 않는지(트리는 이 경우 빈 alt 를 권합니다)는 사람이 봅니다.