AWS Builder Center
Weekend Creative Challenge: Haiku Lens

Weekend Creative Challenge: Haiku Lens

A photograph goes in, a haiku comes out on a tanzaku card. Amazon Bedrock writes the poem; a kana dictionary counts the beats.



Vision & What the App Does

I wanted the app to hand you something you would actually keep.
A caption generator tells you what is in your photo, which you already know, because you took it. A haiku does something else. It picks one small thing out of the frame and holds it still.
So Haiku Lens takes a photograph and gives back a poem: three lines of Japanese in 5-7-5, an English rendering, and a kigo (季語), the seasonal word that anchors every haiku to a time of year. Then it paints the photo and the poem onto a tanzaku card, the narrow strip of paper you hang poems on in Japan. The Japanese runs top to bottom down the right-hand side, the way it should. The English sits on the left. The accent colour is lifted out of the photograph itself, so a snowy harbour prints in slate blue and a maple path prints in rust. One button and the card comes down as a PNG.
Your photo is sent once and never stored. It exists for the length of a single request.

I am Japanese, which mattered more than I expected. I could read every draft the model produced, and a good number of them were nonsense. That is most of the story below.

How I Built It

Step 1: Decide the contract before writing anything

One endpoint.  POST /api/haiku  takes  {"image": "data:image/jpeg;base64,..."}  and returns the poem, the reading, the romaji, the mora counts and the kigo. The browser shrinks every photo to 1024 px before upload, which keeps the request well under the 6 MB Lambda Function URL limit and makes the model faster into the bargain.

Step 2: One CloudFront distribution, two origins

 /*  goes to a private S3 bucket holding the page.  /api/*  goes to a Lambda Function URL. Both origins sit behind an Origin Access Control, so neither is reachable from the internet directly, and because the API lives on the same host as the page, the browser never issues a CORS preflight at all.
This is where I lost my first hour. Every request through CloudFront came back  403 AccessDeniedException , with nothing in the Lambda log, because the function was never invoked. OAC in front of a Lambda Function URL needs two permissions for the CloudFront service principal, not one, and CDK's  FunctionUrlOrigin.withOriginAccessControl()  grants only the first (aws-cdk-lib 2.265.0):
// CDK gives you lambda:InvokeFunctionUrl. You have to add this one yourself.
poet.addPermission('AllowCloudFrontInvokeFunction', {
principal: new iam.ServicePrincipal('cloudfront.amazonaws.com'),
action: 'lambda:InvokeFunction',
sourceArn: `arn:aws:cloudfront::${this.account}:distribution/${distribution.distributionId}`,
});
I confirmed it by adding that one permission with  aws lambda add-permission  and watching the identical request turn into a 200.

Step 3: Make the model lay out the sound before the writing

Ask any model for a haiku and you get three lines that look like a haiku. Count the mora, the beats Japanese metre is built from, and they are wrong most of the time. My very first poem opened with 石段に散る, which the model was certain was five beats. It is seven.
What helped most was making it enumerate:
{"mora": ["ゆ","く","な","つ","や"], "ja": "ゆく夏や"}
Enumerating is not counting, but it is close enough that the drafts arrived much nearer the target.

Step 4: Count the beats in Python, not in the prompt

The Lambda function runs each line through pykakasi, a kana dictionary that turns kanji into readings, counts the mora, and if the poem does not come to 5-7-5 it sends the poem straight back with the numbers attached:
A kana dictionary read your draft aloud:
line 1: 秋の道 → あきのみち = 5 mora (ok)
line 2: 石畳を踏みしめて → いしだたみをふみしめて = 11 mora (needs 7)
line 3: 積もりけり → つもりけり = 5 mora (ok)

Rewrite so the dictionary reading comes to 5 / 7 / 5.
Up to two revisions, then it ships whatever came closest and labels it 字余り (jiamari, "extra beats"), which is a thing poets have done for four centuries.

Step 5: The trap, which I fell into three times

The dictionary is not perfect, so I softened the rule: let the model state how it intends each line to be read, and if that reading is close enough to the dictionary's, believe it.
Metre compliance shot up to 100%. The poems fell apart. One of them was 鉄鉄鉄る, which is not words, and which the model calmly insisted was seven beats.
I tightened the rule instead of dropping it, twice, and it leaked both times. The last leak was a poem ending 待つ夏かな, six beats, which the model declared read まつばらは, five. That is not a reading. It is not even close. The card printed it in romaji, on the front, where any Japanese reader would see it immediately.
So the appeal is gone. pykakasi is the sole judge:
def scan_poem(japanese, claimed):
"""Measure the metre from the dictionary, never from the poet's own claim."""
readings, romaji, mora, declared = [], [], [], []
for line, claim in zip(japanese, claimed):
reading = kana_of(line) # what a reader would actually say
readings.append(reading)
romaji.append(romaji_of(line))
mora.append(count_mora(reading))
declared.append(kana_of(claim) if claim else "") # kept only to quote back
return {"reading": readings, "romaji": romaji, "mora": mora, "_declared": declared}
The model's intended reading is still collected, but only to quote back at it during a revision, where showing the gap between what it meant and what it wrote genuinely helps.

Step 6: Draw the card in the browser

No image generation, no server-side rendering. The photo is already in a canvas from the resize step, so the card is drawn there too: the photo, then the Japanese written vertically character by character (with ー rotated and small kana nudged up and right, the way vertical Japanese type behaves), then the English, then a kigo stamp. The accent colour comes from sampling the photo down to 40x40 and picking the bin that scores highest on frequency times saturation, so a single red roof in a grey photo can still win.

Step 7: The model bake-off, which taught me the real lesson

Four photographs, two passes each. Eight attempts per model, same prompt, same pipeline.
Model
Landed 5-7-5
The Japanese
Claude Sonnet 4.6
7 / 8
best of the four by some distance
Amazon Nova 2 Lite
7 / 8
invented words, wrong season
Amazon Nova Pro
6 / 8
readable, often strained
Claude Haiku 4.5
4 / 8
good Japanese, weakest metre here
Look at the top two. Nova 2 Lite ties for first on the only number I had, and it is the worst poet in the room. It reaches seven beats with strings like はかのこともろ, which is not Japanese at all, and it labelled a street full of cherry blossom 「ゆく夏や」, departing summer. My metre check cannot see any of that. It counts beats. A poem made of syllables that mean nothing counts perfectly.
So I shipped Sonnet 4.6, which writes lines I would keep. 夏草や/レールかがやき/丘のかな, over a photo of an empty summer platform: summer grasses, the rails catching light, and the far hill.

AWS Services Used / Architecture Overview


Service
Role
Amazon Bedrock
 us.anthropic.claude-sonnet-4-6  reads the photograph and writes the poem, through the Converse API.  stability.stable-image-ultra-v1:1  painted the four sample photos, so the demo needs no stock photo licence
AWS Lambda
Python 3.13, 512 MB, 60 s, reserved concurrency 10. Calls Bedrock, counts the mora with pykakasi, runs the revision loop
Amazon CloudFront
One host, two origins. Both locked down with Origin Access Control
Amazon S3
The static page. Private, reachable only through CloudFront
AWS IAM
Function URL set to  AWS_IAM ; the Lambda role holds  bedrock:InvokeModel  scoped to the inference profile and its foundation model
AWS CDK
The whole stack, one  cdk deploy , no Docker
Request flow:
┌──────────── AWS · us-west-2 ─────────────┐
│ │
│ ┌─ /* ─────▶ S3 (private, OAC only) │
browser ──POST──▶ CloudFront │
resize 1024px │ └─ /api/* ──▶ Lambda ──photo──▶ Bedrock │
sha256 the body │ (Function URL, ◀─draft─ │
draw the card │ IAM auth, OAC) │
│ │ │
│ metre off ──────┘ │
│ send it back with the numbers, │
│ up to twice │
└──────────────────────────────────────────┘
Everything is serverless and sits inside Free Tier plus new-account credits. End to end, a photo comes back as a poem in roughly 7 to 16 seconds, most of that spent in revision rounds.

What I Learned

A POST body through OAC needs  x-amz-content-sha256 . Lambda Function URLs do not accept unsigned payloads, so the caller has to supply the hex SHA-256 of the request body. In the browser that is four lines:
async function sha256Hex(text) {
if (!globalThis.crypto?.subtle) return null;
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text));
return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('');
}
Do not map 403 to  index.html . I had the standard SPA error-page rewrite on the distribution, which meant my broken API endpoint was cheerfully returning the homepage with a 200. That turned a ten-minute debug into an hour. If one distribution serves both a page and an API, leave  errorResponses  alone.
Pure-Python dependencies do not need Docker. pykakasi is pure Python, so the Lambda bundle builds with local  pip  through CDK's  bundling.local  hook, with the Docker command kept only as the fallback.  cdk deploy  stays a single command on any machine with Python on it.
And the one that is not an AWS lesson. Give a model a number to hit and it will hit the number, whatever it has to break to get there. Every concession I made, every "well, the dictionary is not perfect either", came back as a poem that scanned beautifully and meant nothing. Whatever automatic score you build will be gameable in exactly this way. Someone still has to read the output.

Honest Trade-Offs

I would rather name the corners I cut than hide them.
The revision loop makes up to three Bedrock calls per photo, which is why a poem can take sixteen seconds. Cutting to two rounds would halve the worst case at the cost of more 字余り. For a toy, I chose the metre.
pykakasi has no morphological analyser behind it, so it reads 紅葉 as こうよう where a haiku almost certainly means もみじ. A real fix is MeCab or Sudachi with a proper dictionary, which is a 50 MB layer and a different weekend.
There is no per-IP rate limiting. What there is instead is  reservedConcurrentExecutions: 10  on the function, which caps how much Bedrock a busy weekend can buy. Crude, but it bounds the bill.
The card uses whatever Japanese serif the visitor's system has (Hiragino Mincho, Yu Mincho, Noto Serif JP). Embedding a webfont would guarantee the look but costs megabytes.

Link to App or Repo


  • There are four sample photographs on the landing page if you have not got one handy, so you can see it work without uploading anything. Press "Ask again" on the same photo and you will get a different poem: the first draft runs at temperature 0.75, and the revisions cool to 0.45.
To deploy your own copy you need Bedrock model access in  us-west-2 , then  cd infra && npm install && npx cdk deploy . No Docker required.
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article