Agent skills that give coding agents taste: art direction, reference images and a browser check instead of generic AI pages
JavaScript agent-skillsai-agentsanti-slopclaude-codecodexcursordesign-systemfrontendlanding-pageui-designweb-design
taste-skill v2: real pictures from open collections (scripts/assets.mjs)
Leonxlnxd1a14056699c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4690d39..f4b1c86 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -17,20 +17,26 @@ All notable changes to taste-skill live here. The repo follows SemVer-ish discip## v2 - the new default for `taste-skill`-v2 is not an edit of the earlier files. It is a new skill built from a study of 247 curated sites (One Page Love and Awwwards Sites of the Day), and it is a folder, not a single `SKILL.md`: instructions, nine reference files, a library and three zero-dependency scripts.+v2 is not an edit of the earlier files. It is a new skill built from a study of 247 curated sites (One Page Love and Awwwards Sites of the Day), and it is a folder, not a single `SKILL.md`: instructions, nine reference files, a library and four zero-dependency scripts.### How it works1. **Inventory.** Before any design, the agent lists what only this client has: the name and what it means, the street, the numbers, the one constraint.2. **Draw.** `scripts/draw.mjs` deals three of 20 researched directions; the agent picks the one that can carry something from the inventory, and the script deals the rest from the library (48 hero compositions, 172 section compositions, 44 type systems of free fonts, 56 palettes, 420 photographs, 11 motions, 181 studied reference sites). Under every dealt blueprint it prints where that blueprint disagrees with the house rules.3. **Idea and one live thing.** One sentence tying the client's own material to the direction's device, checked against the nearest competitor, plus one thing the visitor can do on the page.-4. **Build** with full content; when there are no photographs, the subject is drawn in code.+4. **Build** with full content; when there are no photographs of its own, real pictures of the subject's world come from open collections (`scripts/assets.mjs`), and only what no honest picture exists of is drawn in code.5. **Gate.** `scripts/lint.mjs` scans the source; `scripts/inspect.mjs` opens the page in a real browser at 1440 / 768 / 390, measures it and fails it on: eyebrow labels, monospace outside code, 01/02/03 numbering, hairlines and outlined boxes, gradients, resting shadows, cream-and-terracotta or violet palettes, headlines over two lines, text under 13px, no focal point on the first screen, near-empty screens, text covered or cut off, sideways overflow.6. **Look.** The agent critiques its own screenshots with an Awwwards-weighted rubric and fixes the top three problems, up to three rounds.+### Real pictures from open collections++Agents with no photographs used to draw everything in SVG. `scripts/assets.mjs` searches Openverse, Wikimedia Commons, the Art Institute of Chicago and The Metropolitan Museum of Art without API keys and prints, for each find, a direct image URL, the source page, its size, creator, licence and a one-line credit. By default it keeps only licences that allow commercial use (CC0, public domain, CC BY, CC BY-SA) and checks that every image it prints loads; `--source`, `--license`, `--orientation` and `--min-width` narrow the search. `--get <ref>` downloads a picture into the project's `assets/` and records its credit in `assets/credits.json`; `--credits` prints the footer credit line and the list for the report.++The imagery order is now: the project's own; generated; **real pictures of the subject's world found in open collections** (its street in old postcards, old maps, its materials, engravings of its trade, museum objects of its kind); drawn in code, for what no honest picture exists of; the dealt atmosphere photographs; type and colour alone. A found picture is never presented as the client's own product, room, dish, person or team, and every one is credited on the page and listed in the report. The direction sheet suggests first queries built from the brief (`"ghent postcard"`, `"ghent old map"`), and `references/imagery.md` §3 covers what to search for, what makes a good find, creative uses and the licences.+### Requirements-Node 22+ and an installed Chrome, Edge or Chromium for the inspector (nothing is installed; it drives the browser over the DevTools protocol). `draw.mjs` and `lint.mjs` run on Node 18+. Working files go to `.taste-skill/` in the project; the draw history lives in `~/.taste-skill/history.json`.+Node 22+ and an installed Chrome, Edge or Chromium for the inspector (nothing is installed; it drives the browser over the DevTools protocol). `draw.mjs`, `lint.mjs` and `assets.mjs` run on Node 18+; `assets.mjs` needs network access and no API keys. Working files go to `.taste-skill/` in the project; the draw history lives in `~/.taste-skill/history.json`.### How it was tested@@ -38,7 +44,7 @@ Five rounds of blind comparisons on six briefs: a fresh agent built each page wi### Cost-A full run with the look-and-fix loop takes an agent roughly 30 to 45 minutes and a few hundred thousand tokens, most of it drawing pictures when a project has no photographs.+A full run with the look-and-fix loop takes an agent roughly 30 to 45 minutes and a few hundred thousand tokens, most of it finding or drawing pictures when a project has no photographs.---diff --git a/skills/taste-skill/README.md b/skills/taste-skill/README.mdindex 6b07333..c1c4bd9 100644--- a/skills/taste-skill/README.md+++ b/skills/taste-skill/README.md@@ -16,8 +16,11 @@ render before calling the work done.where it disagrees with the house rules. Recent draws are remembered so projects do not repeat.3. **Idea and live thing.** One sentence tying the client's own material to the direction's device,checked against the nearest competitor, and one thing the visitor can do on the page.-4. **Build** from the sheet, words first, full content, drawings of the subject when there are no- photographs.+4. **Build** from the sheet, words first, full content. When the project has no photographs of its+ own, `scripts/assets.mjs` finds real pictures of the subject's world in open collections (its+ street in old postcards, old maps, its materials, engravings of its trade, museum objects of its+ kind), downloads them into the project and records their credits; the subject is drawn in code+ only where no honest picture exists.5. **Gate.** `scripts/lint.mjs` (source) and `scripts/inspect.mjs` (real browser, 1440 / 768 / 390)measure the house rules: headlines of two lines or fewer, no eyebrow labels, no monospace, no01/02/03, no thin rules, no gradients, no resting shadows, no cream-and-terracotta, no violet, and@@ -35,6 +38,8 @@ Five rounds of blind tests against a no-skill baseline and another design skillSKILL.md the run, the house rules, the lawsreferences/ copy, type, colour, layout, imagery, motion, critique, tells, researchscripts/draw.mjs deal options / a direction / reprint / redraw; --alternatives, --photos, --site+scripts/assets.mjs search open image collections (Openverse, Wikimedia Commons, Art Institute of+ Chicago, the Met); --get downloads with the credit, --credits prints themscripts/lint.mjs static scan for banned patterns and stock phrasesscripts/inspect.mjs render, measure, photographscripts/lib/ zero-dependency Chrome DevTools client, the in-page probe, the rules@@ -47,8 +52,9 @@ evals/evals.json six briefs for testing the skill against a no-skill bas## RequirementsNode 22 or newer and an installed Chrome, Edge or Chromium for `inspect.mjs` (it drives the browser-over the DevTools protocol with Node's built-in WebSocket; nothing is installed). `draw.mjs` and-`lint.mjs` run on Node 18+. Set `CHROME_PATH` if the browser is somewhere unusual.+over the DevTools protocol with Node's built-in WebSocket; nothing is installed). `draw.mjs`,+`lint.mjs` and `assets.mjs` run on Node 18+; `assets.mjs` needs network access and no API keys. Set+`CHROME_PATH` if the browser is somewhere unusual.## Install@@ -59,9 +65,12 @@ a repository under `.claude/skills/`.- Photographs in the library are served by Lorem Picsum from Unsplash, under the Unsplash licence.They are placeholders for atmosphere; replace them with the project's own pictures.+- Pictures found with `assets.mjs` keep their own licences. By default it offers only CC0, public+ domain, CC BY and CC BY-SA, and `--get` records the title, creator, licence and source of every+ download in `assets/credits.json`. The page must carry the credits (`--credits` prints them).- Fonts are loaded from Google Fonts and Fontshare. Check each face's licence for your use.- The scores in `references/research.md` are model judgements from screenshots, not Awwwards scores.- The draw history lives in `~/.taste-skill/history.json` (set `TASTE_SKILL_HISTORY` to move it).Delete it to reset.- A build takes an agent roughly 30–45 minutes and a few hundred thousand tokens with the full- look-and-fix loop; most of that is drawing pictures when a project has no photographs.+ look-and-fix loop; most of that is finding or drawing pictures when a project has no photographs.diff --git a/skills/taste-skill/SKILL.md b/skills/taste-skill/SKILL.mdindex 2a4a8d2..ebff03b 100644--- a/skills/taste-skill/SKILL.md+++ b/skills/taste-skill/SKILL.md@@ -24,12 +24,12 @@ This skill replaces those defaults with decisions, in four ways:One warning learned in testing. Taking the ornaments away is only half the job; a page that has lost itslabels, rules and cards and gained nothing in their place reads as thin, and blind jurors rightly prefera richer page with tells over an empty page without them. The other half is substance: type set-larger, whole fields of colour, pictures made for this subject, and every section carrying its full-content. The skill is built to give you that; do not trade it for restraint.+larger, whole fields of colour, real pictures of this subject's world (found or drawn), and every+section carrying its full content. The skill is built to give you that; do not trade it for restraint.In the commands below `<skill>` is this skill's folder. Run them from the project's root, so theworking files land in `.taste-skill/` there. The scripts need Node 22+ and an installed Chrome, Edge-or Chromium, and install nothing.+or Chromium, and install nothing. `assets.mjs` also needs network access; it uses no API keys.## The run@@ -40,7 +40,9 @@ Do these in order. Steps 1–5 take a few minutes and decide whether the page isFind out what is real: the subject, the audience, the one thing the page must get someone to do, thestack, any existing brand (colours, fonts, logo), and above all **what imagery truly exists**: theproject's own photographs or product shots, a real interface that can be shown, an image generation-tool you can call, or nothing. Do not plan around pictures you do not have.+tool you can call, or nothing. Do not plan around pictures you do not have. Nothing of its own is+rarely nothing at all: the subject's city, street, materials and history are in open archives and+museums, free to use with a credit (step 6, `scripts/assets.mjs`).If the request is vague, decide and state your reading in one line instead of asking. Ask only when amissing fact blocks the work (for example, no product name).@@ -54,7 +56,8 @@ appointment); its materials and colours; its rituals and hours (the oven lit atseven); the printed things of its world (a timetable, a label, a ticket, a sign). This list is wherethe idea comes from in step 4. In blind tests, the page that won each brief was built from an item onsuch a list (the client's name and what it means, the street it stands in, the one constraint that-makes it what it is), and the pages that lost had a good composition with a category idea.+makes it what it is), and the pages that lost had a good composition with a category idea. The list+is also your picture search: each place, material and printed thing on it is a query for step 6.### 2. Write the argument@@ -90,7 +93,8 @@ node <skill>/scripts/draw.mjs <the same arguments, without --options> --directiothat can make them), `product-ui` (real screenshots), `illustration`, `video`. Leave it out if youhave none: the draw then avoids compositions that depend on them and the sheet says how to fillpicture slots honestly (software shows its own interface built in HTML; a product with no photographs- uses shape, type and atmosphere, never a fake product shot).+ is drawn and set among real pictures of its world, never a fake product shot). Pictures you will+ find in the open collections are not the project's own; leave them out of `--have`.- `--keep palette,type`: when the brand already fixes colours or typefaces. The draw then deals onlythe composition, and you map the brand's values onto the roles.@@ -186,12 +190,28 @@ not finished. Order of work:subject. Neighbouring sections must not share a layout. **Carry the idea into every section,**pricing, FAQ and footer included: the commonest failure in the study, even among good sites, is adistinctive first screen followed by stock blocks.-4. **Imagery,** in this order of preference: the project's own; generated, if you have a tool;- **drawn in code from the subject itself** (its objects, its tiles, its windows, its map, its- product's interface, made as one consistent flat graphic language in the palette's real colours);- the photographs dealt on the sheet, only where an honestly generic picture fits (the sea for a sea- house), never as a stand-in for the subject; type and colour alone. `references/imagery.md` covers- drawing, crops and treatments.+4. **Imagery,** in this order of preference:+ 1. the project's own;+ 2. generated, if you have an image tool;+ 3. **real pictures of the subject's world from the open collections,** whenever an honest one+ exists. Search them with `node <skill>/scripts/assets.mjs "<query>"` (Openverse, Wikimedia+ Commons, the Art Institute of Chicago and the Met; only licences that allow commercial use, by+ default). Search the inventory, not the category: its street in old postcards, an old map of the+ neighbourhood, its material up close, its trade in engravings, a museum object of its kind, a+ botanical plate, a star chart. Use them large and with intent: one archival photograph as the+ hero, an engraving enlarged into the page's motif, the real map of the street as the contact+ section. Look at each before choosing; `--get <ref>` downloads it into `assets/` and records+ its source and licence, and `--credits` prints the credit line for the footer. A found picture+ shows the world around the client and is never presented as the client's own product, room,+ dish, person or team;+ 4. **drawn in code from the subject itself,** for what no honest picture exists of (its objects,+ its tiles, its windows, its product's interface, made as one consistent flat graphic language in+ the palette's real colours);+ 5. the photographs dealt on the sheet, only where an honestly generic picture fits (the sea for a+ sea house), never as a stand-in for the subject;+ 6. type and colour alone.++ `references/imagery.md` covers searching, licences and credits, drawing, crops and treatments.5. **The live thing** from step 4, built into the section where it proves the claim (often the heroor the booking), with real content, a thumb-sized phone version and a plain fallback.6. **Fullness.** Look at each desktop screen as a poster: one dominant thing and the content it@@ -240,9 +260,11 @@ once more and check every screenshot for content that failed to appear.### 10. ReportTell the user, briefly: the direction dealt (name and seed) and any redraws with reasons; the idea-sentence and the live thing; the final scores from your last critique round and what still falls short; which bundled-photographs are in use (so they can be replaced) and any sample content that must be swapped before-launch. Do not claim a check you did not run.+sentence and the live thing; the final scores from your last critique round and what still falls short;+every found picture with its title, creator, licence and source page (`assets.mjs --credits` prints+the list) and where its credit sits on the page; which bundled photographs and which drawings stand in+for photography (so they can be replaced); and any sample content that must be swapped before launch.+Do not claim a check you did not run.## House rules@@ -269,7 +291,7 @@ These hold on every build, whatever the direction. `inspect.mjs` measures them.Three places keep their own conventions and are left alone by the inspector: real code in`<pre>`/`<code>` (monospace is correct there), real tables and form fields (they may have lines), anda real interface fragment whose root carries the attribute `data-ui` (the product's own borders and-menus; see `references/imagery.md` §6).+menus; see `references/imagery.md` §7).Why these, honestly. Some are what the study measured: among the 247 sites, those the panel scored7.5 or higher used icon feature cards 1% of the time against 28% for sites under 6.5, pill badges 14%@@ -315,7 +337,10 @@ Short form. Numbers are from the study unless marked as house style.- Same crop ratios, same treatment, square corners unless the direction says otherwise (73% of thestudied sites leave media square).- No image is better than a placeholder, an icon, or an abstract shape. A picture drawn for this- subject, in its colours and with care, is better than either.+ subject, in its colours and with care, is better than either. A real picture of its world, found+ and credited, is better still.+- Every found picture is downloaded into the project, credited on the page and listed in the report.+ None is presented as the client's own.- Nothing ever lies on top of a headline or a statement (the inspector fails it).**Components**@@ -347,6 +372,9 @@ launch. Never fake a payment form.**No Chrome or Node 22.** Run `lint.mjs` (Node 18+), take screenshots with whatever browser tool youhave, and critique those. Say in the report that the inspector could not run.+**No network.** If `assets.mjs` reaches no source, draw the pictures and say in the report that the+open collections could not be searched.+## Files| File | Read it when |@@ -355,12 +383,13 @@ have, and critique those. Say in the report that the inspector could not run.| `references/type.md` | Setting type: scales, tracking, measure, loading fonts, pairing. || `references/colour.md` | Applying the palette: roles, proportions, tone steps, dark pages, contrast. || `references/layout.md` | Grid, margins, rhythm, section variety, navigation, footer, the phone composition. |-| `references/imagery.md` | Choosing, cropping and treating pictures; what to do with none. |+| `references/imagery.md` | Choosing, finding, crediting, cropping and treating pictures; what to do with none. || `references/motion.md` | Step 9. Budget, tokens, recipes, reduced motion. || `references/critique.md` | Step 8. How to look, how to score, what to fix first. || `references/tells.md` | The dated registry of generated-page tells and what each is replaced by. || `references/research.md` | The study: method, numbers, what the best and worst sites do. Cite it, do not guess. || `scripts/draw.mjs` | Deals and reprints the direction; `--photos`, `--site <id>` for more references. |+| `scripts/assets.mjs` | Step 6: searches open collections for real pictures of the subject's world; `--get` downloads with the credit, `--credits` prints them. || `scripts/lint.mjs` · `scripts/inspect.mjs` | The gate. || `assets/base.css` · `assets/base.js` | An optional neutral foundation to build on. || `library/` | The data the draw reads: directions, heroes, sections, type systems, palettes, photographs, studied sites, motions. Do not read it whole; use the script. |diff --git a/skills/taste-skill/references/imagery.md b/skills/taste-skill/references/imagery.mdindex 30d53fb..d1a604e 100644--- a/skills/taste-skill/references/imagery.md+++ b/skills/taste-skill/references/imagery.md@@ -1,20 +1,21 @@# ImageryPictures are where generated pages most obviously give up: a grey box, an icon in a square, a fake-dashboard, an abstract blob. This file is how to decide what the pictures are, how to crop and place-them, and what to do when there are none.+dashboard, an abstract blob. This file is how to decide what the pictures are, where to find real ones,+how to crop and place them, and what to do when there are none.## Contents1. What the study measured2. Decide what imagery exists-3. The dealt photographs-4. Cropping and placing-5. Treatment-6. Showing software-7. Drawing the subject-8. Type and colour alone-9. Markup+3. Real pictures from the open collections+4. The dealt photographs+5. Cropping and placing+6. Treatment+7. Showing software+8. Drawing the subject+9. Type and colour alone+10. Markup and credits## 1. What the study measured@@ -41,20 +42,132 @@ In order of preference:2. **Images you can generate** with an image tool in this session. Write prompts as a photographer'sbrief: subject, angle, light, background, crop ratio, and "no text". Generate the hero first andmake the rest match its light.-3. **Pictures you draw in code from the subject itself** (section 7): the product's own objects as- flat shapes, the place's tiles and windows, a map of its streets, the document a tool produces, the- interface of a piece of software. In testing, pages that drew their subject with care beat pages- that borrowed unrelated photographs every time, and beat pages that showed nothing.-4. **The photographs dealt on the direction sheet.** Real photographs of places, light, texture and+3. **Real pictures of the subject's world from the open collections** (section 3). Archives,+ museums and photographers have published millions of pictures anyone may use with a credit: the+ client's city and street in old postcards, maps of its neighbourhood, its materials, its trade in+ engravings, museum objects of its kind. Whenever an honest one exists, it beats a drawing of the+ same thing: it is real, it has detail no drawing in a page's budget reaches, and it carries history.+ Honest means nobody could take it for the client's own product, room, dish, person or team.+4. **Pictures you draw in code from the subject itself** (section 8), for what no honest picture+ exists of: the product's own objects as flat shapes, the place's tiles and windows, a map of its+ streets, the document a tool produces, the interface of a piece of software. In testing, pages that+ drew their subject with care beat pages that borrowed unrelated photographs every time, and beat+ pages that showed nothing.+5. **The photographs dealt on the direction sheet.** Real photographs of places, light, texture andweather. Use them only where an honestly generic picture fits (the open sea for a house on the sea,fog for a quiet retreat). They cannot stand in for a specific product, dish, room, person orscreen: a foggy motorway on a restaurant page reads as stock at once, and jurors notice.-5. **Type and colour alone,** done on purpose (section 8).+6. **Type and colour alone,** done on purpose (section 9).Tell `draw.mjs` the truth with `--have`. If you have no product photographs and no image tool, do not-pass `product-photo`; the draw will avoid the directions that depend on showing the object.+pass `product-photo`; the draw will avoid the directions that depend on showing the object. Pictures+found in the open collections are not the project's own: do not pass `photography` for them.-## 3. The dealt photographs+## 3. Real pictures from the open collections++`scripts/assets.mjs` searches four open sources without keys and prints, for each find, a direct image+URL, the page it comes from, its size, its creator, its licence and a credit line:++- **Openverse**: one index over Flickr, Wikimedia Commons, museums and libraries.+- **Wikimedia Commons**: archival photographs, old maps, scans of prints and books, places as they+ look now.+- **The Art Institute of Chicago** and **The Metropolitan Museum of Art**: public-domain paintings,+ prints, drawings, photographs, textiles and objects, in large scans.++```bash+node <skill>/scripts/assets.mjs "ghent postcard"+node <skill>/scripts/assets.mjs "fig" --source museums --orientation portrait+node <skill>/scripts/assets.mjs "basalt texture" --min-width 2400 --source openverse,commons+node <skill>/scripts/assets.mjs --get commons:36649959,met:707892 # download, record the credits+node <skill>/scripts/assets.mjs --credits # footer line and report list+```++By default it keeps only licences that allow commercial use (CC0, public domain, CC BY, CC BY-SA) and+pictures at least 1000 pixels wide, and checks that every image it prints actually loads.+`--license pd` keeps only pictures that need no credit; `--orientation`, `--min-width` and `--limit`+narrow the list; `--source` picks the sources; `--json` gives the raw results. Each result has a ref+(`commons:36649959`) that `--get` takes.++**What to search for.** The inventory (SKILL.md step 1), not the category: "bakery" finds other+people's bakeries. The subject's world is specific:++- **Its place:** the city, the street, the harbour, the valley, in old postcards and photographs+ ("ghent postcard", "rotterdam harbour 1920") and as it looks today ("gent korenmarkt").+- **Its maps:** the street plan, the chart of its bay, the geology of its valley ("ghent old map",+ "nautical chart lisbon").+- **Its materials,** close enough to read as a surface: the stone of its quay, the grain of its oak,+ its glaze, its tiles ("azulejo tiles", "basalt cobblestones", "oak grain").+- **Its trade's history:** the old tools, the craft in engravings and trade catalogues, patent+ drawings ("bread oven engraving", "potter's wheel", "bicycle patent drawing").+- **Museum objects of its kind,** with `--source museums`: a coffee set from about 1810 for a studio+ that makes coffee sets, a woodblock print of a wave for a surf school, a porcelain plate painted+ with figs for a fig orchard.+- **Scientific imagery:** botanical and zoological plates ("botanical engraving fig"), star charts,+ microscope photographs, satellite views of its coast, geological sections.++Search in the place's own words (azulejo, not "blue tile"; Korenmarkt, not "market square"), add a+medium (postcard, engraving, old map, lithograph, aerial photograph) or a decade, and try two or three+queries per idea. The museum sources match best on one or two words ("fig", "harbour", "teapot").++**What makes a good find.**++- It belongs to this subject's world and would not fit the nearest competitor's page.+- It still reads at the crop the slot needs. Look at it before deciding: `--get` downloads it, then+ open the file. A title is not a picture.+- It is large enough: twice the width it is shown at for anything full-bleed (the script prints the+ largest size available). A 1024-pixel Flickr photograph is a half-width picture at most.+- It belongs to one family with the others on the page: all engravings, or all photographs from one+ era, or all close surfaces in one light. A 1900 postcard beside a modern stock photograph beside a+ botanical plate reads as a scrapbook.+- No watermark, no burned-in text or logo, no frame or scanner edge you cannot crop away, and no+ recognisable living person who could be taken for the client's staff or customers.++**Use it creatively.** Found pictures are material, not decoration:++- **One archival photograph as the hero,** full-bleed: the street as it was a century ago, behind the+ name of the business that stands in it today, with the year in the caption.+- **A museum engraving enlarged until its line becomes texture,** cropped tight and returning at+ different scales as the page's one motif (the whole fig plate in the hero, a single leaf of it+ beside the menu).+- **An engraving or a map on white paper set with `mix-blend-mode: multiply` on the page's colour+ field,** so the ink sits on the ground (section 6).+- **The real map of the street as the contact section,** the door marked, the north and the scale+ taken from the original.+- **A material close-up as a whole field:** the quay's stone behind the opening hours.+- **A run of old postcards or plates as the gallery,** one size, one treatment.++Treatments stay within section 6: untouched, greyscale for the whole set, or multiply on a field.++**Stay honest.**++- **A found picture is never the client's own.** It may show the client's city, its materials, its+ history, the kind of thing it makes; it may never stand in for the client's product, room, dish,+ person, team or customers. If a visitor could take it for the client's own (a bakery counter, a+ plate of pasta, a smiling barista, a guest room), do not use it.+- **Caption from the source** when a caption helps: what it is and when, as the archive describes it+ ("Gand, unloading a steamer, 1905"). Never write a caption that ties it to the client.+- **Record and credit every picture.** `--get` writes the source, creator, licence and page of each+ download to `assets/credits.json`. CC BY and CC BY-SA require a credit with the title, the creator,+ a link to the source and a link to the licence; `--credits` prints them as one line of HTML for+ the footer (section 10). Public-domain pictures need no credit; give one anyway.+- **Respect the licence.** CC BY-SA: an altered version (recoloured, combined with other pictures)+ must be shared under the same licence. Non-commercial (NC) and no-derivatives (ND) licences are out+ for a client's site, which is why the script leaves them out unless asked. Read the `note` lines:+ some pictures carry personality rights or a trademark, are public domain only in the United States,+ or come with an archive's statement instead of a licence.+- **Download, do not hotlink.** Save what you use into the project: `--get` puts it in `assets/` at+ 1920 pixels wide (pass `--width 1280` for a picture shown at half the screen, `--width 3840` for a+ very large hero where the source has it). The page then works offline, does not break when an+ archive moves a file, and does not load from someone else's server. Every licence the script+ allows by default permits copying.+- **List them in the report:** file, title, creator, licence, source page, and where the credit sits.+ `--credits` prints that list too.++If two or three honest queries per idea find nothing that fits, draw (section 8). A drawing made for+the subject is better than a found picture that is merely nearby. If the script cannot reach any+source (no network), draw, and say so in the report.++## 4. The dealt photographs- The sheet lists eight from one set so they share a subject and a light. Use three to six.- Each line says where the calm area is. Put text there or keep text off the image.@@ -66,7 +179,7 @@ pass `product-photo`; the draw will avoid the directions that depend on showing- These are photographs from Unsplash served by Lorem Picsum under the Unsplash licence. List the idsyou used in your report; they are meant to be replaced by the project's own pictures.-## 4. Cropping and placing+## 5. Cropping and placing- **Choose a small set of ratios and stick to them:** for example 4:5 for portraits, 16:10 forlandscapes and 1:1 for details. Random ratios look like a stock dump.@@ -84,7 +197,7 @@ pass `product-photo`; the draw will avoid the directions that depend on showing- **Captions** are one short line in the small size and soft ink under the image, left-aligned to itsedge. Most images need none.-## 5. Treatment+## 6. TreatmentOne treatment for the whole page:@@ -102,7 +215,7 @@ tilted "polaroid" frames with shadows.For text on a photograph, a neutral scrim covering only the text area: a solid block at 40–55% black,or a fade from 55% black to transparent over the lower third. Never a coloured overlay.-## 6. Showing software+## 7. Showing software- Build a real fragment of the interface in HTML at its true size, with believable content, instead ofa shrunken screenshot or a decorative mock-up. Crop to the part that makes the point: one control,@@ -119,9 +232,11 @@ or a fade from 55% black to transparent over the lower third. Never a coloured otell it apart from page styles.- If the user supplies real screenshots, show them large and uncropped at least once.-## 7. Drawing the subject+## 8. Drawing the subject-When nothing real can be photographed, draw it, and draw it well. Inline SVG and CSS are enough.+When nothing real can be photographed and the open collections hold no honest picture of it, draw it,+and draw it well. Inline SVG and CSS are enough. Drawings and found pictures can share a page: the+found ones show the world around the client, the drawings show the client's own things.- **Draw the subject's own things,** not decoration: the stool's three legs and the grain of its seat,the enamel sign over the bakery door, the hut's two windows and its stove pipe, the street plan, the@@ -148,7 +263,7 @@ When nothing real can be photographed, draw it, and draw it well. Inline SVG and- **Not this:** gradient-shaded 3D-looking blobs, isometric clip art, generic line illustrations ofpeople at laptops, abstract floating shapes, icons in squares. Those are the generated look.-## 8. Type and colour alone+## 9. Type and colour aloneThis is a legitimate design, not a gap to disguise. Only 7 of the studied sites use no imagery at all,and they hold their own: a median panel score of 7.5 against 7.2 for the whole set.@@ -160,16 +275,37 @@ and they hold their own: a median panel score of 7.5 against 7.2 for the whole s- Do not add: icons in squares, abstract gradients, dot grids, wave dividers, floating shapes, emoji,generic line illustrations, or an empty box where a picture "will go".-## 9. Markup+## 10. Markup and credits++A found picture, downloaded into the project with `--get`, used as the hero:++```html+<img src="assets/fig-engraving.jpg" width="1920" height="2807" fetchpriority="high" decoding="async"+ alt="Hand-coloured engraving of a fig cut open, with its flowers and seeds, in black, pink and green">+```++A dealt photograph further down the page:```html<img src="https://picsum.photos/id/626/2400/1500" width="2400" height="1500"alt="Red and white lighthouse in a turquoise sea below a chalk cliff" loading="lazy" decoding="async">```+The credits, as `--credits` prints them, in the footer:++```html+<p class="credits">Pictures: <a href="https://commons.wikimedia.org/wiki/File:Fig_(Ficus_carica_L.);_57_segments_of_flowers_and_fruits_at_Wellcome_V0043000.jpg">“Fig (Ficus carica L.): 57 segments of flowers and fruits”</a>, <a href="https://creativecommons.org/publicdomain/mark/1.0/">public domain</a>, via Wikimedia Commons.</p>+```+- Always `width` and `height` (or `aspect-ratio` in CSS) so nothing jumps while loading.- `loading="lazy"` on everything except the hero image, which gets `fetchpriority="high"`.-- `alt` describes the picture in plain words. Decorative repeats get `alt=""`.+- `alt` describes the picture in plain words. Decorative repeats get `alt=""`. The script's suggested+ alt is the archive's title; rewrite it to say what the picture shows.- A coloured `background-color` on the image container (the ground or surface tone) so the layout iswhole before the image arrives.+- The credit line is part of the footer's design, at full contrast, with its links. Set it at the body+ size; one step smaller only on a page with plenty of running text, because a long credit line in+ small type can become the page's most common text size and fail the inspector's body-size check.+ One line for all pictures; no credit captions laid over the pictures themselves. Credit only the+ pictures the page still uses.- A broken image fails the inspector. Check every picture in the screenshots.diff --git a/skills/taste-skill/references/tells.md b/skills/taste-skill/references/tells.mdindex 0296263..875d4a9 100644--- a/skills/taste-skill/references/tells.md+++ b/skills/taste-skill/references/tells.md@@ -44,7 +44,7 @@ inspector fails the page; **warned** means it flags it and you need a reason.| Bento grid of rounded tiles as the feature section | warned as card rows | A composed section; tiles only in the dense-tiles direction, filled, strict sizes || Near-black ground with one neon accent and a glow | banned via shadow, gradient | A dealt dark palette, no glow || Floating rounded pill navigation with blur | warned | A plain bar |-| Fake dashboard hero built from grey bars and donut charts | no rule; see imagery.md §6 | A real interface fragment, or no image |+| Fake dashboard hero built from grey bars and donut charts | no rule; see imagery.md §7 | A real interface fragment, or no image || Decorative status dot ("Available for work", pulsing "live") | lint: bounce | Remove || Fade-and-rise on every section | no rule; see motion.md | One signature move |diff --git a/skills/taste-skill/scripts/assets.mjs b/skills/taste-skill/scripts/assets.mjsnew file mode 100644index 0000000..71a4094--- /dev/null+++ b/skills/taste-skill/scripts/assets.mjs@@ -0,0 +1,596 @@+#!/usr/bin/env node+// tasteskill / assets: find real, openly licensed pictures of the subject's world, and keep their credits.+//+// A page without photographs of its own does not have to draw everything. Archives, museums and open+// collections hold the subject's city and street, its maps, its materials, its trade's history and the+// museum objects of its kind, free to use with a credit. This searches them without keys and prints what+// an agent needs to use a picture honestly: a direct image URL, the page it comes from, its size, its+// creator, its licence and a one-line credit. Then it downloads the chosen ones into the project and+// records their credits, so the page works offline and credits every picture.+//+// node assets.mjs "<query>" search every source, licences safe for commercial use+// [--source all|openverse|commons|aic|met|museums] one or several, comma-separated+// [--license safe|pd|all|cc0,pd,by,by-sa,...] safe = CC0, public domain, CC BY, CC BY-SA+// [--orientation landscape|portrait|square] [--min-width 1000] [--width 1920] [--limit 5]+// [--no-check] skip checking that each image loads (faster)+// [--json] machine-readable results+// node assets.mjs --get <ref>[,<ref>...] [--to assets] [--name <file name>] [--width 1920]+// download into the project and record the credit+// node assets.mjs --credits [--to assets] print the credits for the footer and the report+//+// Sources: Openverse (api.openverse.org: Flickr, Wikimedia Commons, museums and libraries in one index),+// Wikimedia Commons, the Art Institute of Chicago (public-domain works over IIIF) and The Metropolitan+// Museum of Art (Open Access). Zero dependencies, no API keys. Node 18+ (built-in fetch).+import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';+import { join, resolve, relative } from 'node:path';+import { fileURLToPath } from 'node:url';++const UA = 'taste-skill-assets/2.0 (+https://github.com/Leonxlnx/taste-skill)';+const SELF = fileURLToPath(import.meta.url).split('\\').join('/');+const CMD = `node ${/\s/.test(SELF) ? `"${SELF}"` : SELF}`;+const SOURCES = {+ openverse: { name: 'Openverse', note: 'one index over Flickr, Wikimedia Commons, museums and libraries' },+ commons: { name: 'Wikimedia Commons', note: 'archival photographs, old maps, scans of prints and books, places as they look now' },+ aic: { name: 'Art Institute of Chicago', note: 'public-domain paintings, prints, photographs and textiles, served large' },+ met: { name: 'The Metropolitan Museum of Art', note: 'public-domain objects, prints, drawings and photographs (Open Access)' },+};+const SOURCE_ALIAS = { all: Object.keys(SOURCES), museums: ['aic', 'met'], wikimedia: ['commons'], artic: ['aic'], chicago: ['aic'], metmuseum: ['met'] };+const LICENCES = ['cc0', 'pd', 'by', 'by-sa', 'by-nc', 'by-nd', 'by-nc-sa', 'by-nc-nd', 'other'];+const SAFE = ['cc0', 'pd', 'by', 'by-sa'];+const LICENCE_ALIAS = { pdm: 'pd', 'public-domain': 'pd', publicdomain: 'pd', 'cc-by': 'by', 'cc-by-sa': 'by-sa', 'cc-zero': 'cc0' };+const WEB_TYPES = { 'image/jpeg': 'jpg', 'image/png': 'png', 'image/webp': 'webp', 'image/gif': 'gif', 'image/avif': 'avif', 'image/svg+xml': 'svg' };+const PROVIDERS = { flickr: 'Flickr', wikimedia: 'Wikimedia Commons', met: 'The Metropolitan Museum of Art', nypl: 'New York Public Library', rawpixel: 'rawpixel', stocksnap: 'StockSnap', clevelandmuseum: 'Cleveland Museum of Art', brooklynmuseum: 'Brooklyn Museum', sciencemuseum: 'Science Museum Group', europeana: 'Europeana', geographorguk: 'Geograph Britain and Ireland', inaturalist: 'iNaturalist', wordpress: 'WordPress Photo Directory' };+const AIC_FIELDS = ['id', 'title', 'artist_title', 'artist_display', 'date_display', 'image_id', 'thumbnail', 'medium_display', 'artwork_type_title', 'is_public_domain'];+const AIC_HEADERS = { 'AIC-User-Agent': UA };++const USAGE = `Find real, openly licensed pictures of the subject's world, download them, keep their credits.++ ${CMD} "<query>" [options]+ --source all|openverse|commons|aic|met|museums comma-separated; default all+ --license safe|pd|all|cc0,pd,by,by-sa,... default safe: CC0, public domain, CC BY, CC BY-SA+ --orientation landscape|portrait|square+ --min-width <px> smallest acceptable full width, default 1000+ --width <px> width of the image URL to use or download, default 1920+ --limit <n> results per source, default 5 (at most 20)+ --no-check do not check that every image loads (faster, less reliable)+ --json machine-readable results+ ${CMD} --get <ref>[,<ref>...] [--to assets] [--name <file name>] [--width 1920]+ ${CMD} --credits [--to assets]++Queries work best in the subject's own words and a medium: "ghent postcard", "ghent old map", "azulejo tiles",+"botanical engraving fig", "rotterdam harbour 1920", "basalt texture". The museum sources match one or two+words best ("fig", "harbour").`;++// ---------- arguments ----------+const VALUED = new Set(['source', 'sources', 'license', 'licence', 'orientation', 'min-width', 'width', 'limit', 'get', 'to', 'name']);+const FLAGS = new Set(['no-check', 'json', 'credits', 'help']);+const args = {}; const words = [];+const argv = process.argv.slice(2);+for (let i = 0; i < argv.length; i++) {+ const a = argv[i];+ if (a === '-h') { args.help = true; continue; }+ if (!a.startsWith('--')) { words.push(a); continue; }+ const eq = a.indexOf('=');+ const key = a.slice(2, eq === -1 ? undefined : eq);+ if (VALUED.has(key)) {+ const v = eq === -1 ? argv[++i] : a.slice(eq + 1);+ if (v === undefined || v === '' || (eq === -1 && v.startsWith('--'))) fail(`--${key} needs a value.`);+ args[key] = v;+ } else if (FLAGS.has(key)) args[key] = true;+ else fail(`Unknown option --${key}.`);+}+function fail(message) { console.error(`${message}\n\n${USAGE}`); process.exit(2); }+function number(key, def, min, max) {+ if (args[key] === undefined) return def;+ const n = Number(args[key]);+ if (!Number.isFinite(n) || n < min || n > max) fail(`--${key} must be a number from ${min} to ${max}.`);+ return Math.round(n);+}+function pickSources(value) {+ const out = [];+ for (const s of String(value).toLowerCase().split(',').map((x) => x.trim()).filter(Boolean)) {+ const found = SOURCE_ALIAS[s] || (SOURCES[s] ? [s] : null);+ if (!found) fail(`Unknown source "${s}". Sources: ${Object.keys(SOURCES).join(', ')}, museums (aic and met), all.`);+ for (const x of found) if (!out.includes(x)) out.push(x);+ }+ return out.length ? out : Object.keys(SOURCES);+}+function pickLicences(value) {+ const v = String(value).toLowerCase().trim();+ if (v === 'safe') return SAFE;+ if (v === 'pd') return ['cc0', 'pd'];+ if (v === 'all' || v === 'any') return LICENCES;+ const out = v.split(',').map((x) => x.trim()).filter(Boolean).map((x) => LICENCE_ALIAS[x] || x);+ const bad = out.filter((x) => !LICENCES.includes(x));+ if (bad.length || !out.length) fail(`Unknown licence "${bad.join(', ') || v}". Use safe, pd, all, or a list of: ${LICENCES.join(', ')}.`);+ return out;+}+function pickOrientation(value) {+ if (value === undefined) return null;+ const v = String(value).toLowerCase();+ const o = { landscape: 'landscape', wide: 'landscape', horizontal: 'landscape', portrait: 'portrait', tall: 'portrait', vertical: 'portrait', square: 'square' }[v];+ if (!o) fail('--orientation is landscape, portrait or square.');+ return o;+}+const o = {+ sources: pickSources(args.source ?? args.sources ?? 'all'),+ licences: pickLicences(args.license ?? args.licence ?? 'safe'),+ orientation: pickOrientation(args.orientation),+ minWidth: number('min-width', 1000, 0, 20000),+ width: number('width', 1920, 200, 4000),+ limit: number('limit', 5, 1, 20),+ check: !args['no-check'],+ to: resolve(String(args.to || 'assets')),+ toArg: args.to ? ` --to ${args.to}` : '',+};++// ---------- small helpers ----------+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));+const short = (s, n) => { const t = String(s || ''); return t.length > n ? t.slice(0, n - 1).replace(/[\s,;:.-]+$/, '') + '…' : t; };+const noQuery = (u) => (u ? String(u).split('?')[0] : u);+const rel = (p) => relative(process.cwd(), p).split('\\').join('/') || '.';+const size = (bytes) => (bytes >= 1048576 ? `${(bytes / 1048576).toFixed(1)} MB` : `${Math.max(1, Math.round(bytes / 1024))} KB`);+const shape = (w, h) => (!w || !h ? null : w / h >= 1.15 ? 'landscape' : w / h <= 0.87 ? 'portrait' : 'square');+const esc = (s) => String(s ?? '').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');+function text(v) {+ if (v === undefined || v === null) return '';+ return String(v).replace(/<(style|script)\b[\s\S]*?<\/\1>/gi, ' ').replace(/<[^>]*>/g, ' ').replace(/ /g, ' ').replace(/"/g, '"').replace(/�?39;|'/g, "'")+ .replace(/</g, '<').replace(/>/g, '>').replace(/&#(\d+);/g, (_, n) => String.fromCodePoint(Number(n))).replace(/&/g, '&')+ .replace(/\s+/g, ' ').trim();+}+function keyOf(u) { let s = noQuery(u) || ''; try { s = decodeURIComponent(s); } catch {} return s.toLowerCase().replace(/^https?:\/\//, '').replace(/ /g, '_'); }+function slug(s) {+ return String(s || '').normalize('NFKD').replace(/[\u0300-\u036f]/g, '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '')+ .split('-').slice(0, 7).join('-').slice(0, 60).replace(/-+$/, '');+}+// The words of a query that carry meaning, and whether a record's own description holds them+// (all of them, or all but one of three or more). Used to keep the museum sources on the subject.+function queryWords(q) { return String(q).toLowerCase().split(/[^\p{L}\p{N}]+/u).filter((w) => w && !['the', 'a', 'an', 'of', 'in', 'on', 'at', 'and', 'or', 'for', 'with', 'from', 'to', 'by'].includes(w)); }+function onSubject(wanted, description) {+ if (!wanted.length) return true;+ const loose = (s) => String(s).toLowerCase().normalize('NFKD').replace(/[̀-ͯ]/g, '').replace(/our\b/g, 'or'); // harbour = harbor+ const hay = loose(description);+ const hits = wanted.filter((w) => { const x = loose(w); return hay.includes(x) || (x.length > 4 && hay.includes(x.replace(/(es|s)$/, ''))); }).length;+ return hits >= (wanted.length >= 3 ? wanted.length - 1 : wanted.length);+}+async function mapLimit(items, n, fn) {+ const out = new Array(items.length); let next = 0;+ await Promise.all(Array.from({ length: Math.min(n, items.length) }, async () => { while (next < items.length) { const k = next++; out[k] = await fn(items[k], k); } }));+ return out;+}+async function getJson(url, ms = 20000, headers = {}) {+ for (let attempt = 1; ; attempt++) {+ let r;+ try { r = await fetch(url, { headers: { 'User-Agent': UA, Accept: 'application/json', ...headers }, signal: AbortSignal.timeout(ms) }); }+ catch (e) {+ const timedOut = e.name === 'TimeoutError' || e.name === 'AbortError';+ if (!timedOut && attempt < 2) { await sleep(800); continue; }+ throw new Error(timedOut ? `no answer within ${Math.round(ms / 1000)} s` : `could not connect (${e.cause?.code || e.message})`);+ }+ if ([502, 503, 504].includes(r.status) && attempt < 2) { await sleep(1200); continue; }+ if (r.status === 429) throw new Error('rate limited (HTTP 429): wait a minute, or search another --source');+ if (r.status === 410) throw new Error('this API endpoint has been retired (HTTP 410); assets.mjs needs updating for it');+ if (!r.ok) throw new Error(`HTTP ${r.status}${r.status >= 500 ? ', the service is having trouble' : ''}`);+ try { return await r.json(); } catch { throw new Error('the answer was not JSON'); }+ }+}+// Width and height from the first bytes of a JPEG, PNG, GIF or WebP file.+function dims(b) {+ if (!b || b.length < 26) return {};+ if (b[0] === 0x89 && b.toString('ascii', 1, 4) === 'PNG') return { w: b.readUInt32BE(16), h: b.readUInt32BE(20) };+ if (b.toString('ascii', 0, 3) === 'GIF') return { w: b.readUInt16LE(6), h: b.readUInt16LE(8) };+ if (b.toString('ascii', 0, 4) === 'RIFF' && b.toString('ascii', 8, 12) === 'WEBP' && b.length >= 30) {+ const f = b.toString('ascii', 12, 16);+ if (f === 'VP8X') return { w: 1 + b.readUIntLE(24, 3), h: 1 + b.readUIntLE(27, 3) };+ if (f === 'VP8L') { const bits = b.readUInt32LE(21); return { w: 1 + (bits & 0x3fff), h: 1 + ((bits >>> 14) & 0x3fff) }; }+ if (f === 'VP8 ') return { w: b.readUInt16LE(26) & 0x3fff, h: b.readUInt16LE(28) & 0x3fff };+ }+ if (b[0] === 0xff && b[1] === 0xd8) {+ let i = 2;+ while (i + 9 < b.length) {+ if (b[i] !== 0xff) { i++; continue; }+ const m = b[i + 1];+ if (m === 0xff) { i++; continue; }+ if (m === 0x01 || (m >= 0xd0 && m <= 0xd8)) { i += 2; continue; }+ if (m >= 0xc0 && m <= 0xcf && m !== 0xc4 && m !== 0xc8 && m !== 0xcc) return { w: b.readUInt16BE(i + 7), h: b.readUInt16BE(i + 5) };+ i += 2 + b.readUInt16BE(i + 2);+ }+ }+ return {};+}+// The Art Institute's image server turns away scripts that do not name themselves in this header.+const imageHeaders = (url) => ({ 'User-Agent': UA, Accept: 'image/*', ...(/^https?:\/\/[^/]*artic\.edu\//.test(url) ? AIC_HEADERS : {}) });+// Does the image load, is it a web image, and how large is it? Reads only the first 128 KB.+async function probe(url, ms = 15000) {+ const ac = new AbortController(); const timer = setTimeout(() => ac.abort(), ms);+ try {+ const r = await fetch(url, { headers: { ...imageHeaders(url), Range: 'bytes=0-131071' }, signal: ac.signal, redirect: 'follow' });+ if (!r.ok) { r.body?.cancel().catch(() => {}); return { ok: false, why: `HTTP ${r.status}` }; }+ const type = (r.headers.get('content-type') || '').split(';')[0].trim().toLowerCase();+ if (!WEB_TYPES[type]) { r.body?.cancel().catch(() => {}); return { ok: false, why: type ? `not a web image (${type})` : 'no content type' }; }+ const reader = r.body.getReader(); const chunks = []; let n = 0;+ while (n < 131072) { const { done, value } = await reader.read(); if (done) break; chunks.push(value); n += value.length; }+ reader.cancel().catch(() => {});+ const bytes = r.status === 206 ? Number((r.headers.get('content-range') || '').split('/')[1]) || null : Number(r.headers.get('content-length')) || null;+ return { ok: true, type, bytes, ...dims(Buffer.concat(chunks)) };+ } catch (e) {+ return { ok: false, why: e.name === 'AbortError' ? 'timed out' : e.cause?.code || e.message };+ } finally { clearTimeout(timer); }+}++// ---------- licences and credits ----------+function licenceLabel(it) {+ if (it.licenseName) return it.licenseName; // set where the plain code would mislead: museums, informal statements, unusual licences+ if (it.license === 'cc0') return 'CC0';+ if (it.license === 'pd') return 'public domain';+ if (it.license === 'other') return 'licence on the source page';+ return `CC ${it.license.toUpperCase()}${it.licenseVersion ? ' ' + it.licenseVersion : ''}`;+}+function licenceUrl(it) {+ if (it.licenseUrl) return String(it.licenseUrl).replace(/^http:/, 'https:');+ if (it.license === 'cc0') return 'https://creativecommons.org/publicdomain/zero/1.0/';+ if (it.license === 'pd') return 'https://creativecommons.org/publicdomain/mark/1.0/';+ if (it.license.startsWith('by')) return `https://creativecommons.org/licenses/${it.license}/${it.licenseVersion || '4.0'}/`;+ return null;+}+const creditRequired = (it) => it.license !== 'cc0' && it.license !== 'pd';+function licenceNotes(it) {+ const n = [];+ if (/-sa$/.test(it.license)) n.push('Share-alike: an altered version (recoloured, combined with other pictures) must be shared under the same licence.');+ if (/-nc/.test(it.license)) n.push('Non-commercial only: not for a business, a shop or a client site.');+ if (/-nd$/.test(it.license)) n.push('No derivatives: show it whole and unaltered, no crops or treatments.');+ if (it.license === 'other') n.push('A licence outside the usual set: read the source page before using it.');+ return n;+}+function credit(it) {+ const by = it.creator && !/^(unknown|anonymous)\b/i.test(it.creator) ? ` by ${short(it.creator, 60)}` : '';+ const date = (it.source === 'aic' || it.source === 'met') && it.date ? `, ${short(it.date, 30)}` : '';+ return `"${short(it.title, 90)}"${by}${date}, ${licenceLabel(it)}, via ${it.via}`;+}+function base(source, id) {+ return { ref: `${source}:${id}`, source, via: SOURCES[source].name, title: '', creator: '', creatorUrl: null, date: null, kind: null, about: null, license: 'other', licenseVersion: null, licenseName: null, licenseUrl: null, page: null, image: null, original: null, smaller: null, width: null, height: null, imageWidth: null, imageHeight: null, bytes: null, alt: null, notes: [], hint: null };+}++// ---------- Openverse ----------+async function searchOpenverse(q, opts) {+ const lic = opts.licences.filter((l) => l !== 'other').map((l) => (l === 'pd' ? 'pdm' : l));+ if (!lic.length) return { total: 0, items: [], note: 'Openverse filters by Creative Commons licences and marks only.' };+ const call = (large) => {+ const p = new URLSearchParams({ q, license: lic.join(','), page_size: '20' });+ if (opts.orientation) p.set('aspect_ratio', { landscape: 'wide', portrait: 'tall', square: 'square' }[opts.orientation]);+ if (large) p.set('size', 'large');+ return getJson(`https://api.openverse.org/v1/images/?${p}`, 30000);+ };+ // Its default order is led by 1024px Flickr files. Ask for the large ones first, and fill up from the rest only if needed.+ const first = await call(true);+ let rows = first.results || []; let total = first.result_count ?? null;+ if (rows.filter((r) => !r.width || r.width >= opts.minWidth).length < opts.limit + 2) {+ const rest = await call(false).catch(() => null);+ if (rest) { total = rest.result_count ?? total; rows = [...rows, ...(rest.results || []).filter((r) => !rows.some((x) => x.id === r.id))]; }+ }+ const items = rows.map(fromOpenverse).filter((it) => it.image);+ await wikimediaSizes(items, opts.width);+ return { total, items };+}+function fromOpenverse(r) {+ const it = base('openverse', r.id);+ const via = r.source || r.provider;+ Object.assign(it, {+ via: PROVIDERS[via] || (String(via || '').startsWith('smithsonian') ? 'Smithsonian' : via ? String(via).replace(/_/g, ' ') : 'Openverse'),+ title: text(r.title).replace(/^File:/, '').replace(/\.(jpe?g|png|tiff?|gif|webp)$/i, '') || 'Untitled', creator: text(r.creator), creatorUrl: r.creator_url || null,+ license: r.license === 'pdm' ? 'pd' : String(r.license || 'other'), licenseVersion: r.license_version || null, licenseUrl: r.license_url || null,+ page: r.foreign_landing_url || r.detail_url, image: r.url, original: r.url,+ width: r.width || null, height: r.height || null, imageWidth: r.width || null, imageHeight: r.height || null,+ });+ if (!LICENCES.includes(it.license)) it.license = 'other';+ return it;+}+// Openverse points at Wikimedia originals, which can be 10 MB or a TIFF. Swap in a web-sized rendition.+async function wikimediaSizes(items, width) {+ const wm = items.filter((it) => /^https?:\/\/upload\.wikimedia\.org\/wikipedia\/commons\/[0-9a-f]\/[0-9a-f]{2}\//.test(it.original || ''));+ if (!wm.length) return;+ const title = (it) => { let n = noQuery(it.original).split('/').pop(); try { n = decodeURIComponent(n); } catch {} return 'File:' + n.replace(/_/g, ' '); };+ const j = await getJson(commonsApi({ titles: wm.map(title).join('|'), prop: 'imageinfo', iiprop: 'url|size|mime', iiurlwidth: String(width) })).catch(() => null);+ if (!j?.query) return;+ const normal = new Map((j.query.normalized || []).map((n) => [n.from, n.to]));+ const info = new Map((j.query.pages || []).map((pg) => [pg.title, pg.imageinfo?.[0]]));+ for (const it of wm) { const t = title(it); const ii = info.get(normal.get(t) || t); if (ii) applyThumb(it, ii); }+}++// ---------- Wikimedia Commons ----------+function commonsApi(params) { return `https://commons.wikimedia.org/w/api.php?${new URLSearchParams({ action: 'query', format: 'json', formatversion: '2', origin: '*', ...params })}`; }+function commonsInfo(width) {+ return { prop: 'imageinfo', iiprop: 'url|size|mime|extmetadata', iiurlwidth: String(width), iiextmetadatalanguage: 'en',+ iiextmetadatafilter: 'ObjectName|Artist|LicenseShortName|License|LicenseUrl|Restrictions|DateTimeOriginal|ImageDescription' };+}+async function searchCommons(q, opts) {+ let s = `${q} filetype:bitmap`;+ if (opts.minWidth > 1) s += ` filew:>${opts.minWidth - 1}`;+ const j = await getJson(commonsApi({ generator: 'search', gsrnamespace: '6', gsrsearch: s, gsrlimit: '30', ...commonsInfo(opts.width) }));+ if (j.error) throw new Error(j.error.info || 'the search failed');+ const pages = (j.query?.pages || []).sort((a, b) => (a.index ?? 0) - (b.index ?? 0));+ return { total: null, items: pages.map(fromCommons).filter(Boolean) };+}+function fromCommons(pg) {+ const ii = pg?.imageinfo?.[0]; if (!ii) return null;+ const m = (k) => text(ii.extmetadata?.[k]?.value);+ const lic = commonsLicence(m('License'), m('LicenseShortName'));+ const it = base('commons', pg.pageid);+ Object.assign(it, {+ title: m('ObjectName').replace(/\s*\b(?:title|label) QS:.*$/s, '') || pg.title.replace(/^File:/, '').replace(/\.[a-z0-9]+$/i, ''), creator: m('Artist'),+ date: m('DateTimeOriginal').replace(/\s*\bdate QS:.*$/s, '').replace(/^(\d{4}-\d{2}-\d{2})[ T]\d{2}:\d{2}.*$/, '$1') || null, about: m('ImageDescription') || null,+ license: lic.code, licenseVersion: lic.version, licenseName: lic.name, licenseUrl: m('LicenseUrl') || null, page: ii.descriptionurl,+ });+ applyThumb(it, ii);+ if (lic.informal) it.notes.push('Not a formal licence: the archive that published it states it knows of no copyright restrictions.');+ if (it.about && it.about.toLowerCase().startsWith(it.title.toLowerCase()) && it.about.length < it.title.length + 12) it.about = null;+ const restrictions = m('Restrictions');+ if (restrictions) it.notes.push(`Restrictions named on the source page (${restrictions}): personality rights, a trademark or similar. Read it before use.`);+ if (/^pd-us/i.test(m('License'))) it.notes.push('Public domain in the United States; check the source page before using it elsewhere.');+ return it;+}+function commonsLicence(license, shortName) {+ const l = String(license || '').toLowerCase(); const s = String(shortName || '').toLowerCase();+ const version = (shortName.match(/\b(\d\.\d)\b/) || l.match(/(\d\.\d)/) || [])[1] || null;+ if (/^cc0|^cc-zero/.test(l) || /^cc0/.test(s)) return { code: 'cc0', version: '1.0' };+ if (/^pd|public domain/.test(l) || /public domain/.test(s)) return { code: 'pd', version: null };+ // Flickr Commons and similar archives: no formal licence, the institution states it knows of no copyright+ if (/^no (known copyright )?restrictions/.test(s)) return { code: 'pd', version: null, name: 'no known copyright restrictions', informal: true };+ const cc = l.match(/^cc-(by(?:-nc)?(?:-sa|-nd)?)(?:-|$)/) || s.match(/^cc (by(?:-nc)?(?:-sa|-nd)?)\b/);+ if (cc) return { code: cc[1], version };+ return { code: 'other', version: null, name: shortName || license || null };+}+// Commons serves thumbnails only at standard widths (1280, 1920, 3840...); the API picks the step.+function applyThumb(it, ii) {+ it.width = ii.width || it.width; it.height = ii.height || it.height; it.original = noQuery(ii.url) || it.original;+ const tw = Number(String(ii.thumburl || '').split('?')[0].match(/(\d+)px-[^/]*$/)?.[1]) || 0;+ if (ii.thumburl && tw && ii.width && (tw < ii.width || (ii.mime && !WEB_TYPES[ii.mime]))) {+ it.image = noQuery(ii.thumburl); it.imageWidth = Math.min(tw, ii.width); it.imageHeight = ii.height ? Math.round((ii.height * it.imageWidth) / ii.width) : null;+ } else { it.image = it.original; it.imageWidth = ii.width || null; it.imageHeight = ii.height || null; }+}++// ---------- Art Institute of Chicago ----------+async function searchAic(q, opts) {+ const wanted = queryWords(q);+ const run = (match) => getJson(`https://api.artic.edu/api/v1/artworks/search?params=${encodeURIComponent(JSON.stringify({+ query: { bool: {+ // the long description field is left out on purpose: it matches almost anything+ must: [{ multi_match: { query: wanted.join(' ') || q, type: 'cross_fields', fields: ['title^3', 'subject_titles^2', 'term_titles^2', 'classification_titles', 'medium_display', 'artist_title', 'place_of_origin', 'date_display'], ...match } }],+ filter: [{ term: { is_public_domain: true } }, { exists: { field: 'image_id' } }],+ } },+ fields: AIC_FIELDS, limit: 30,+ }))}`, 20000, AIC_HEADERS);+ // every word must match; with three words or more, one may be missing. Looser than that returns noise.+ let j = await run({ operator: 'and' });+ if (!(j.data || []).length && wanted.length >= 3) j = await run({ operator: 'or', minimum_should_match: wanted.length - 1 });+ const iiif = j.config?.iiif_url || 'https://www.artic.edu/iiif/2';+ return { total: j.pagination?.total ?? null, items: (j.data || []).map((d) => fromAic(d, iiif, opts.width)).filter(Boolean) };+}+function fromAic(d, iiif, width) {+ if (!d?.image_id || d.is_public_domain === false) return null;+ const it = base('aic', d.id);+ const W = d.thumbnail?.width || null; const H = d.thumbnail?.height || null;+ const cap = W ? Math.min(W, 3000) : 3000; const w = Math.min(width, cap);+ Object.assign(it, {+ title: text(d.title) || 'Untitled', creator: text(d.artist_title) || text(String(d.artist_display || '').split('\n')[0]),+ date: text(d.date_display) || null, kind: [d.artwork_type_title, d.medium_display].filter(Boolean).map(text).join(', ') || null,+ license: 'cc0', licenseVersion: '1.0', licenseName: 'public domain (CC0)', licenseUrl: 'https://creativecommons.org/publicdomain/zero/1.0/',+ page: `https://www.artic.edu/artworks/${d.id}`, image: `${iiif}/${d.image_id}/full/${w},/0/default.jpg`, original: `${iiif}/${d.image_id}/full/${cap},/0/default.jpg`,+ width: W && H ? cap : null, height: W && H ? Math.round((H * cap) / W) : null, imageWidth: W && H ? w : null, imageHeight: W && H ? Math.round((H * w) / W) : null,+ alt: text(d.thumbnail?.alt_text) || null,+ });+ it.hint = 'Download it with --get: the museum\'s image server answers browsers and this script, and refuses plain curl or wget.';+ return it;+}++// ---------- The Met ----------+async function searchMet(q, opts) {+ const s = await getJson(`https://collectionapi.metmuseum.org/public/collection/v1.1/search?${new URLSearchParams({ q, hasImages: 'true', limit: String(Math.min(40, opts.limit * 4 + 8)), offset: '0' })}`);+ const ids = (s.objectIDs || []).slice(0, opts.limit * 4 + 8);+ const objects = await mapLimit(ids, 8, (id) => getJson(`https://collectionapi.metmuseum.org/public/collection/v1/objects/${id}`, 15000).catch(() => null));+ // The museum's search reads every field of a record, so much of what it returns is off the subject.+ // Keep the objects whose own name, material, maker, place or tags carry the words of the query.+ const wanted = queryWords(q);+ const about = (x) => [x.title, x.objectName, x.medium, x.classification, x.culture, x.period, x.artistDisplayName, x.department, x.city, x.country, x.region, x.objectDate, ...(x.tags || []).map((t) => t.term)].filter(Boolean).join(' ');+ return { total: s.total ?? null, items: objects.filter((x) => x && onSubject(wanted, about(x))).map(fromMet).filter(Boolean) };+}+function fromMet(x) {+ if (!x || !x.isPublicDomain || !x.primaryImage) return null;+ const it = base('met', x.objectID);+ const fix = (u) => (u ? encodeURI(u).replace(/%25([0-9a-f]{2})/gi, '%$1') : null);+ Object.assign(it, {+ title: text(x.title) || text(x.objectName) || 'Untitled', creator: text(x.artistDisplayName) || (x.culture ? `${text(x.culture)} maker` : ''),+ date: text(x.objectDate) || null, kind: [x.objectName || x.classification, x.medium].filter(Boolean).map(text).join(', ') || null,+ license: 'cc0', licenseVersion: '1.0', licenseName: 'public domain (CC0)', licenseUrl: 'https://creativecommons.org/publicdomain/zero/1.0/',+ page: x.objectURL || `https://www.metmuseum.org/art/collection/search/${x.objectID}`,+ image: fix(x.primaryImage), original: fix(x.primaryImage), smaller: x.primaryImageSmall && x.primaryImageSmall !== x.primaryImage ? fix(x.primaryImageSmall) : null,+ });+ return it;+}++// ---------- search ----------+function fits(it, opts, skipped) {+ const W = it.width || it.imageWidth; const H = it.height || it.imageHeight;+ if (W && W < opts.minWidth) { skipped.small++; return false; }+ if (opts.orientation && W && H && shape(W, H) !== opts.orientation) { skipped.shape++; return false; }+ return true;+}+async function search(query, opts) {+ const runners = { openverse: searchOpenverse, commons: searchCommons, aic: searchAic, met: searchMet };+ // a slow service never holds the whole search: each source gets 45 s, the image check 30 s+ const deadline = (ms, message) => new Promise((_, reject) => setTimeout(() => reject(new Error(message)), ms).unref());+ const results = await Promise.all(opts.sources.map(async (key) => {+ try { return { key, ...(await Promise.race([runners[key](query, opts), deadline(45000, 'no complete answer within 45 s; try again or search another --source')])) }; }+ catch (e) { return { key, error: e.message, items: [] }; }+ }));+ const seen = new Set();+ for (const r of results) {+ r.skipped = { licence: 0, small: 0, shape: 0, dead: 0, alike: 0 };+ const titles = new Map();+ r.items = r.items.filter((it) => {+ if (!opts.licences.includes(it.license)) { r.skipped.licence++; return false; }+ const k = keyOf(it.original || it.image); if (seen.has(k)) return false; seen.add(k);+ if (!fits(it, opts, r.skipped)) return false;+ // one scanned book can fill a whole page of results: keep two pictures per title+ const t = it.title.toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim().slice(0, 32); const n = (titles.get(t) || 0) + 1; titles.set(t, n);+ if (t && n > 2) { r.skipped.alike++; return false; }+ return true;+ }).slice(0, opts.limit + 4); // a few spares for images that turn out not to load+ }+ if (opts.check) {+ await Promise.race([mapLimit(results.flatMap((r) => r.items), 8, async (it) => {+ const p = await probe(it.image, 12000); it.check = p;+ if (p.ok && p.w && p.h) {+ it.imageWidth = p.w; it.imageHeight = p.h;+ if (!it.width || it.image === it.original) { it.width = p.w; it.height = p.h; }+ }+ if (p.ok && p.bytes) it.bytes = p.bytes;+ }), new Promise((r) => setTimeout(r, 30000).unref())]);+ for (const r of results) r.items = r.items.filter((it) => (it.check?.ok ? fits(it, opts, r.skipped) : (r.skipped.dead++, (r.skipped.why = it.check?.why || 'not checked within 30 s'), false)));+ }+ for (const r of results) r.items = r.items.slice(0, opts.limit);+ const shown = results.reduce((n, r) => n + r.items.length, 0);++ if (args.json) {+ console.log(JSON.stringify({ query, options: { sources: opts.sources, licences: opts.licences, orientation: opts.orientation, minWidth: opts.minWidth, width: opts.width, limit: opts.limit, checked: opts.check },+ sources: results.map((r) => ({ source: r.key, name: SOURCES[r.key].name, total: r.total ?? null, error: r.error || null, skipped: r.skipped,+ items: r.items.map(({ check, ...it }) => ({ ...it, licenseLabel: licenceLabel(it), licenseUrl: licenceUrl(it), creditRequired: creditRequired(it), credit: credit(it), notes: [...it.notes, ...licenceNotes(it)] })) })) }, null, 1));+ return shown ? 0 : 1;+ }++ const filters = [`licences ${opts.licences.join(', ')}`, `at least ${opts.minWidth}px wide`, opts.orientation, `image URLs ${opts.width}px wide where the source can size them`, opts.check ? 'every image checked' : 'images not checked'].filter(Boolean);+ console.log(`ASSETS · "${query}" · ${filters.join(' · ')}`);+ for (const r of results) {+ const src = SOURCES[r.key];+ console.log('');+ if (r.error) { console.log(`## ${src.name}: could not search it (${r.error})`); continue; }+ const dropped = [r.skipped.small && `${r.skipped.small} narrower than ${opts.minWidth}px`, r.skipped.shape && `${r.skipped.shape} not ${opts.orientation}`, r.skipped.licence && `${r.skipped.licence} under other licences`, r.skipped.alike && `${r.skipped.alike} more with the same title`, r.skipped.dead && `${r.skipped.dead} did not load (${r.skipped.why})`].filter(Boolean);+ const count = r.total != null ? `${r.total} matches, ${r.items.length} shown` : `${r.items.length} shown`;+ console.log(`## ${src.name}: ${r.items.length ? count : 'nothing usable'}${dropped.length ? ` (dropped: ${dropped.join(', ')})` : ''}`);+ if (r.note) console.log(r.note);+ if (!r.items.length) continue;+ console.log(`${src.note}`);+ for (const it of r.items) {+ console.log('');+ console.log(`${it.ref} ${short(it.title, 100)}${it.date ? ` (${short(it.date, 30)})` : ''}`);+ if (it.kind) console.log(` what ${short(it.kind, 110)}`);+ if (it.about) console.log(` about ${short(it.about, 150)}`);+ const pixels = it.imageWidth && it.imageHeight ? `${it.imageWidth} × ${it.imageHeight}` : 'size unknown';+ const largest = it.width && it.height && it.width !== it.imageWidth ? `; largest ${it.width} × ${it.height}` : '';+ const sh = shape(it.width || it.imageWidth, it.height || it.imageHeight);+ console.log(` image ${it.image}`);+ console.log(` size ${pixels}${it.bytes ? `, ${size(it.bytes)}` : ''}${largest}${sh ? `; ${sh}` : ''}`);+ if (it.smaller) console.log(` smaller ${it.smaller}`);+ console.log(` page ${it.page}`);+ const lu = licenceUrl(it);+ console.log(` licence ${licenceLabel(it)}${lu ? ` (${lu})` : ''}; ${creditRequired(it) ? 'credit required' : 'no credit required, credit anyway'}`);+ console.log(` credit ${credit(it)}`);+ for (const n of [...it.notes, ...licenceNotes(it), ...(it.hint ? [it.hint] : [])]) console.log(` note ${n}`);+ }+ }+ console.log('');+ if (results.every((r) => r.error)) {+ console.log('No source could be reached. Check the network and try again; if this machine has no internet access, draw the');+ console.log('pictures instead (references/imagery.md) and say in your report that the open collections could not be searched.');+ return 1;+ }+ if (!shown) {+ console.log('Nothing usable came back. Try fewer words; the place\'s own name for things ("azulejo", not "blue tile"); the place and a');+ console.log('medium ("ghent postcard", "ghent old map", "ghent engraving"); a decade ("rotterdam harbour 1920"); a smaller --min-width;');+ console.log('or another --source. The museum sources match one or two words best ("fig", "harbour"). If nothing honest exists, draw it.');+ return 1;+ }+ console.log('Next. Look before you choose: --get downloads into the project and records the credit; open the file to see it.');+ console.log(` ${CMD} --get <ref>[,<ref>...]${o.toArg}`);+ console.log(` ${CMD} --credits${o.toArg} the footer credit line and the list for your report`);+ console.log('These pictures show the subject\'s world. Never present one as the client\'s own product, room, dish, person or team.');+ return 0;+}++// ---------- get ----------+function creditsPath(opts) { return join(opts.to, 'credits.json'); }+function readCredits(opts) { try { const j = JSON.parse(readFileSync(creditsPath(opts), 'utf8')); return Array.isArray(j) ? j : []; } catch { return []; } }+async function getOne(ref, opts) {+ const m = String(ref).match(/^(openverse|commons|aic|met):(.+)$/);+ if (!m) throw new Error('a ref looks like openverse:<id>, commons:<id>, aic:<id> or met:<id>, as a search prints it.');+ const [, src, id] = m;+ let it;+ if (src === 'openverse') { it = fromOpenverse(await getJson(`https://api.openverse.org/v1/images/${encodeURIComponent(id)}/`, 30000)); await wikimediaSizes([it], opts.width); }+ else if (src === 'commons') { const j = await getJson(commonsApi({ pageids: id, ...commonsInfo(opts.width) })); it = fromCommons(j.query?.pages?.[0]); }+ else if (src === 'aic') { const j = await getJson(`https://api.artic.edu/api/v1/artworks/${encodeURIComponent(id)}?fields=${AIC_FIELDS.join(',')}`, 20000, AIC_HEADERS); it = fromAic(j.data, j.config?.iiif_url || 'https://www.artic.edu/iiif/2', opts.width); }+ else {+ it = fromMet(await getJson(`https://collectionapi.metmuseum.org/public/collection/v1/objects/${encodeURIComponent(id)}`));+ if (it?.smaller) { const s = await probe(it.smaller); if (s.ok && s.w >= opts.width * 0.9) it.image = it.smaller; }+ }+ if (!it || !it.image) throw new Error('no usable image (not public domain, or the record has no picture).');+ if (!opts.licences.includes(it.license)) throw new Error(`its licence is ${licenceLabel(it)}, outside the ones allowed (${opts.licences.join(', ')}). Pass --license all to take it anyway, and say why in your report.`);+ let r;+ try { r = await fetch(it.image, { headers: imageHeaders(it.image), signal: AbortSignal.timeout(90000) }); }+ catch (e) { throw new Error(`the image did not download (${e.name === 'TimeoutError' ? 'timed out' : e.cause?.code || e.message}).`); }+ if (!r.ok) throw new Error(`the image did not load (HTTP ${r.status}).`);+ const type = (r.headers.get('content-type') || '').split(';')[0].trim().toLowerCase();+ const ext = WEB_TYPES[type];+ if (!ext) throw new Error(`the file is ${type || 'of no stated type'}, not a web image.`);+ const buf = Buffer.from(await r.arrayBuffer());+ if (!buf.length) throw new Error('the image was empty.');+ const d = dims(buf);+ mkdirSync(opts.to, { recursive: true });+ const credits = readCredits(opts);+ const stem = slug(args.name || it.title) || `${src}-${slug(id).slice(0, 12)}`;+ let file = join(opts.to, `${stem}.${ext}`);+ for (let k = 2; existsSync(file) && credits.find((c) => c.file === rel(file))?.ref !== it.ref; k++) file = join(opts.to, `${stem}-${k}.${ext}`);+ writeFileSync(file, buf);+ const entry = {+ file: rel(file), ref: it.ref, title: it.title, creator: it.creator || null, creatorUrl: it.creatorUrl, date: it.date,+ license: licenceLabel(it), licenseCode: it.license, licenseUrl: licenceUrl(it), creditRequired: creditRequired(it),+ page: it.page, via: it.via, image: it.image, width: d.w || it.imageWidth, height: d.h || it.imageHeight, bytes: buf.length,+ credit: credit(it), notes: [...it.notes, ...licenceNotes(it)], saved: new Date().toISOString(),+ };+ writeFileSync(creditsPath(opts), JSON.stringify([...credits.filter((c) => c.file !== entry.file), entry], null, 1));+ const alt = it.alt || it.title;+ console.log(`Saved ${entry.file}${entry.width ? ` · ${entry.width} × ${entry.height}` : ''} · ${size(buf.length)}`);+ console.log(` page ${it.page}`);+ console.log(` credit ${entry.credit}`);+ console.log(` markup <img src="${esc(entry.file)}"${entry.width ? ` width="${entry.width}" height="${entry.height}"` : ''} alt="${esc(short(alt, 120))}" loading="lazy" decoding="async">`);+ console.log(' (rewrite the alt to say what the picture shows; drop loading="lazy" on the hero image)');+ for (const n of entry.notes) console.log(` note ${n}`);+}+async function getAll(refs, opts) {+ let failed = 0;+ for (const ref of refs) {+ try { await getOne(ref, opts); } catch (e) { failed++; console.error(`Could not get ${ref}: ${e.message}`); }+ console.log('');+ }+ if (failed < refs.length) {+ console.log(`Credits are recorded in ${rel(creditsPath(opts))}. Look at each picture before using it.`);+ console.log(`Print the footer credits and the report list with: ${CMD} --credits${opts.toArg}`);+ }+ return failed ? 1 : 0;+}++// ---------- credits ----------+function printCredits(opts) {+ const list = readCredits(opts);+ const uniq = list.filter((c, i) => list.findIndex((x) => x.ref === c.ref) === i && existsSync(resolve(c.file)));+ if (!uniq.length) { console.log(`No pictures recorded in ${rel(creditsPath(opts))} yet. Download them with --get <ref> first.`); return 1; }+ const html = (c) => {+ const by = c.creator && !/^(unknown|anonymous)\b/i.test(c.creator) ? ` by ${esc(short(c.creator, 60))}` : '';+ const date = /^(aic|met):/.test(c.ref) && c.date ? `, ${esc(short(c.date, 30))}` : '';+ const lic = c.licenseUrl ? `<a href="${esc(c.licenseUrl)}">${esc(c.license)}</a>` : esc(c.license);+ return `<a href="${esc(c.page)}">“${esc(short(c.title, 90))}”</a>${by}${date}, ${lic}, via ${esc(c.via)}`;+ };+ console.log('Footer credits (HTML). Full contrast, keep the links, body size (one step smaller only on a page with plenty of');+ console.log('running text). Remove any picture the page no longer uses, here and in credits.json.\n');+ console.log(`<p class="credits">Pictures: ${uniq.map(html).join('; ')}.</p>`);+ console.log('\nFor your report:\n');+ for (const c of uniq) console.log(`- ${c.file}: ${c.credit}. ${c.page}${c.creditRequired ? '' : ' (no credit required)'}`);+ return 0;+}++// ---------- run ----------+if (args.help) { console.log(USAGE); process.exit(0); }+if (args.credits) process.exit(printCredits(o));+if (args.get) process.exit(await getAll(String(args.get).split(',').map((s) => s.trim()).filter(Boolean), o));+const query = words.join(' ').trim();+if (!query) fail('Give a search query, for example: node assets.mjs "ghent postcard"');+process.exit(await search(query, o));diff --git a/skills/taste-skill/scripts/draw.mjs b/skills/taste-skill/scripts/draw.mjsindex 20998cf..552c456 100644--- a/skills/taste-skill/scripts/draw.mjs+++ b/skills/taste-skill/scripts/draw.mjs@@ -26,6 +26,8 @@ import { homedir } from 'node:os';const HERE = dirname(fileURLToPath(import.meta.url));const LIB = join(HERE, '..', 'library');+const ASSETS_PATH = join(HERE, 'assets.mjs').split('\\').join('/');+const ASSETS_CMD = `node ${/\s/.test(ASSETS_PATH) ? `"${ASSETS_PATH}"` : ASSETS_PATH}`;const load = (name) => JSON.parse(readFileSync(join(LIB, name + '.json'), 'utf8'));const argv = process.argv.slice(2);@@ -186,7 +188,7 @@ if (opt('redraw')) {console.log(`## \`${d.id}\` — ${d.name}`);console.log(`Idea engine: ${d.idea.split(/(?<=\.)\s/).slice(0, 2).join(' ')}`);console.log(`Composition: ${d.composition.split(/(?<=\.)\s/).slice(0, 2).join(' ')}`);- if (d.needsPictures) console.log('Needs: many pictures. Without photographs every one of them is a drawing you make.');+ if (d.needsPictures) console.log('Needs: many pictures. Without photographs of its own, each is a real picture of the subject\'s world found with scripts/assets.mjs, or a drawing you make.');console.log('');}process.exit(0);@@ -303,10 +305,37 @@ function dealPhotos(dir, input) {.map((ph) => (mode === 'no-product-photo' && matches(ph) ? { ...ph, lookalike: true } : ph));return { set: chosen.id, title: chosen.set.title, note: chosen.set.note, treatment: dir.photoTreatment || null, others: scored.filter((x) => x.id !== chosen.id).slice(0, 4).map((x) => x.id), photos: ranked.slice(0, mode === 'interface' ? 4 : 8) };}+function briefStop() {+ return new Set(['with', 'that', 'this', 'from', 'page', 'site', 'website', 'landing', 'their', 'they', 'have', 'will', 'your', 'about', 'into', 'make', 'build', 'create', 'design', 'small', 'based', 'called', 'named', 'which', 'where', 'what', 'need', 'want', 'like', 'also', 'some', 'very', 'more', 'most', 'just', 'than', 'then', 'them', 'and', 'the', 'for', 'one', 'hand', 'handmade', 'made', 'batch', 'ship', 'ships', 'week', 'within', 'across', 'euro', 'euros', 'cost', 'price', 'open', 'only', 'each', 'every', 'there', 'images', 'photos', 'photograph', 'static', 'html']);+}function briefWords(brief) {- const stop = new Set(['with', 'that', 'this', 'from', 'page', 'site', 'website', 'landing', 'their', 'they', 'have', 'will', 'your', 'about', 'into', 'make', 'build', 'create', 'design', 'small', 'based', 'called', 'named', 'which', 'where', 'what', 'need', 'want', 'like', 'also', 'some', 'very', 'more', 'most', 'just', 'than', 'then', 'them', 'and', 'the', 'for', 'one', 'hand', 'handmade', 'made', 'batch', 'ship', 'ships', 'week', 'within', 'across', 'euro', 'euros', 'cost', 'price', 'open', 'only', 'each', 'every', 'there', 'images', 'photos', 'photograph', 'static', 'html']);+ const stop = briefStop();return [...new Set(String(brief || '').toLowerCase().split(/[^a-z]+/).filter((w) => w.length >= 4 && !stop.has(w)).map((w) => w.replace(/(ies|es|s)$/, '')))].filter((w) => w.length >= 4);}+// First queries for scripts/assets.mjs, built from the brief: the place in old postcards and maps, then the+// subject itself. In testing "<place> postcard" and "<place> old map" found archival material far more+// reliably than a place and a year. A start only: the better queries come from the builder's inventory.+function assetQueries(input) {+ const brief = String(input.brief || '');+ const notPlace = /^(?:january|february|march|april|may|june|july|august|september|october|november|december|monday|tuesday|wednesday|thursday|friday|saturday|sunday)s?$/i;+ const placeRe = /(?:^|[\s,(])(?:in|at|near|from|on|above|below|beside|outside|off|over)\s+(\p{Lu}[\p{L}'’-]*(?:\s+(?:\p{Lu}[\p{L}'’-]*|de|da|do|dos|das|di|del|van|von|der|den))*)/gu;+ const place = [...brief.matchAll(placeRe)].map((m) => m[1].trim()).find((p) => !notPlace.test(p.split(/\s+/)[0]));+ const stop = briefStop();+ const generic = new Set(['seat', 'seats', 'room', 'rooms', 'minute', 'minutes', 'hour', 'hours', 'night', 'nights', 'year', 'years', 'people', 'family', 'local', 'short', 'best', 'making', 'selling', 'serving', 'offering', 'business', 'company', 'brand', 'shop', 'store', 'studio', 'service', 'services', 'dinner', 'lunch', 'breakfast', 'included', 'online', 'modern']);+ // the subject: the last plain words of the first noun phrase ("a 38-seat Italian restaurant in ..." gives "restaurant")+ const words = brief.split(/\s+/).filter(Boolean); const phrase = [];+ for (let k = words.findIndex((w) => /^an?$/i.test(w)) + 1; k < words.length; k++) {+ if (/^(?:in|at|on|for|from|with|near|above|below|by|that|which|who|of|and|to)$/i.test(words[k])) break;+ phrase.push(words[k].replace(/[,.;:()!?]+$/, ''));+ if (/[,.;:()!?]$/.test(words[k])) break;+ }+ const plain = phrase.filter((w) => /^\p{Ll}{3,}$/u.test(w) && !stop.has(w) && !generic.has(w));+ const subject = plain.slice(-2).join(' ') || (input.sector !== 'other' ? input.sector.replace(/-/g, ' ') : null);+ const out = [];+ if (place) out.push(`${place.toLowerCase()} postcard`, `${place.toLowerCase()} old map`);+ if (subject) out.push(subject.toLowerCase());+ return [...new Set(out)];+}// Blueprints written for showing software (an interface fragment is their picture).function softwareOnly(x) { return (x.directions || [])[0] === 'product-performs' || (x.tags || []).includes('ui-led') || /data-ui|interface fragment/i.test(x.blueprint || ''); }// Blueprints were measured on real sites and carry that site's sizes, greys, faces, colours and corners.@@ -436,19 +465,26 @@ function render(s) {p('}'); p('```'); p(c.note); if (d.colour) p(d.colour); p();} else { p('## 4. Colour'); p('Kept from the brand. ' + (d.colour || '')); p(); }p('## 5. Imagery');+ // where to look for real pictures of the subject's world, with first queries built from the brief+ const qs = assetQueries(s.input);+ const find = qs.length+ ? `\`${ASSETS_CMD} "${qs[0]}"\`${qs.length > 1 ? `, then ${qs.slice(1).map((q) => `"${q}"`).join(' and ')}` : ''}, then queries from your inventory (its street, its materials, its trade's tools and history)`+ : `\`${ASSETS_CMD} "<a place, material or object from your inventory>"\``;const MODE = {- interface: '**This subject is software and there are no screenshots, so its pictures are its own interface.** Wherever this sheet says photograph, image or object, build a believable fragment of the product in HTML at real size (real labels, numbers that add up, one item hovered or selected), put the attribute `data-ui` on its root, and crop or scale it the way the blueprint treats a photograph: a full-bleed close crop, a tile, the fixed half of a split. Where a fragment makes no sense, use a flat colour field with type on it. Never a fake dashboard of grey bars, never a device frame.',- 'no-product-photo': '**There are no photographs of the product and none can be faked.** Wherever this sheet calls for a picture of the object, draw the object: its pieces as flat shapes in inline SVG, large, in one graphic language and in the colours that make it worth buying (a glaze, a finish, a material), never grey placeholders (references/imagery.md §7). Type at scale and full colour fields carry the rest. Atmosphere photographs (hands, the workshop, the materials) only where they plainly do not pretend to be the product. In your report, say that product photography is needed and which drawings it will replace.',- atmosphere: '**The project has no photographs of its own yet.** First choice: draw the subject\'s own things in code, large, in one flat graphic language and the palette\'s real colours (its tiles, its windows, its street, its objects; see references/imagery.md §7). Second: the dealt photographs, only where an honestly generic picture fits (the sea, the weather, a material), never one a visitor could take for the thing itself (this room, this dish, this person) and never an unrelated scene. One treatment for all of them. If this direction is built on photographs, plan a small set of drawings (four to six) with detail, and reuse them at different crops and scales instead of drawing a new picture for every slot; keep them as `<symbol>` + `<use>` or generate them with a small script so the page stays light. List every photograph and every drawing that stands in for photography in your report.',- own: '**Use the images that belong to the project in every picture slot.** The dealt photographs are only a fallback for slots the project cannot fill.',+ interface: '**This subject is software and there are no screenshots, so its pictures are its own interface.** Wherever this sheet says photograph, image or object, build a believable fragment of the product in HTML at real size (real labels, numbers that add up, one item hovered or selected), put the attribute `data-ui` on its root, and crop or scale it the way the blueprint treats a photograph: a full-bleed close crop, a tile, the fixed half of a split. Where a fragment makes no sense, use a flat colour field with type on it. Never a fake dashboard of grey bars, never a device frame. If the product works on something physical (ships, plants, buildings, a city), one real picture of that world can carry a section: find it with `' + ASSETS_CMD + ' "<that world>"`, download it with `--get`, credit it on the page, and never let it pass for the product or its customers.',+ 'no-product-photo': '**There are no photographs of the product and none can be faked.** Wherever this sheet calls for a picture of the object, draw the object: its pieces as flat shapes in inline SVG, large, in one graphic language and in the colours that make it worth buying (a glaze, a finish, a material), never grey placeholders (references/imagery.md §8). **Around the object, use real pictures of its world** from the open collections: its material up close, its town in old postcards, its craft in engravings, a museum piece of the same kind, never one a visitor could take for the product itself (references/imagery.md §3). Start with ' + find + '. Download what you use with `--get` and credit every one on the page (`--credits` prints the footer line). Type at scale and full colour fields carry the rest; the dealt photographs only where they plainly do not pretend to be the product. In your report, say that product photography is needed and which drawings it will replace, and list every found picture with its source and licence.',+ atmosphere: '**The project has no photographs of its own yet.** First choice: **real pictures of the subject\'s world from the open collections**: its city and street in old postcards and photographs, an old map of the neighbourhood, its materials up close, its trade in engravings, museum objects of its kind (references/imagery.md §3). Start with ' + find + '. Download what you use into the project with `--get` and credit every one on the page (`--credits` prints the footer line). They show the world around the client, never the client\'s own room, dish, product, person or team. Second, for what no honest picture exists of: draw the subject\'s own things in code, large, in one flat graphic language and the palette\'s real colours (its tiles, its windows, its objects; references/imagery.md §8). Third: the dealt photographs, only where an honestly generic picture fits (the sea, the weather, a material), never one a visitor could take for the thing itself and never an unrelated scene. One treatment for all of them. If this direction is built on photographs, plan the set before building (four to six pictures of one family) and reuse them at different crops and scales instead of finding or drawing a new picture for every slot; keep drawings as `<symbol>` + `<use>` or generate them with a small script so the page stays light. List every found picture (with its source and licence), every dealt photograph and every drawing that stands in for photography in your report.',+ own: '**Use the images that belong to the project in every picture slot.** For slots they cannot fill, real pictures of the subject\'s world from the open collections come next (start with ' + find + '; credit them on the page), then the dealt photographs.',};p(MODE[s.imagery || 'atmosphere']); p(); p(d.imagery);if (s.photos) {p();p(s.imagery === 'interface' ? `Optional atmosphere, two at most, from the "${s.photos.title || s.photos.set}" set (${s.photos.note}). The page does not need them.` : `Photographs dealt for this build, from the "${s.photos.title || s.photos.set}" set (${s.photos.note})`);p('Order of preference for imagery: (1) the project\'s own photographs and product shots; (2) images you generate, if an image tool is');- p('available; (3) these. They are real photographs (Unsplash licence, served by picsum.photos) of places, light and texture. They are');- p('atmosphere, never a stand-in for a specific product, dish, person or interface. List the ones you use in your report so they can be replaced.');+ p('available; (3) real pictures of the subject\'s world found in the open collections (assets.mjs, downloaded and credited on the page);');+ p('(4) drawings of the subject in code; (5) these. They are real photographs (Unsplash licence, served by picsum.photos) of places, light and');+ p('texture. They are atmosphere, never a stand-in for a specific product, dish, person or interface. List the ones you use in your report so');+ p('they can be replaced.');if (s.photos.treatment) p(`Treatment: ${s.photos.treatment}`);for (const ph of s.photos.photos) p(`- \`https://picsum.photos/id/${ph.id}/1600/1000\` — ${ph.alt} · ${ph.tone} tone · ${(ph.colours || []).join(', ')}${ph.mono ? ' · black-and-white' : ''}${ph.lookalike ? ' · **could be taken for the product: never use it as the product**' : ''}${ph.calm && ph.calm !== 'none' ? ` · calm area: ${ph.calm}` : ''} · native ${ph.ratio >= 1.15 ? 'landscape' : ph.ratio <= 0.87 ? 'portrait' : 'square'} · photo: ${ph.by}`);p('The last two path numbers are width and height: request the exact crop you render (`/1200/1500` for a 4:5 portrait, `/2400/1350` for a hero) and');