Skip to content

Agent skills that give coding agents taste: art direction, reference images and a browser check instead of generic AI pages

taste-skill v2: require real pictures, footage and motion

Leonxlnx9da1763c950b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f4b1c86..928ebc7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -34,6 +34,16 @@ Agents with no photographs used to draw everything in SVG. `scripts/assets.mjs`
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.
+### Pictures, footage and motion are required
+
+Testing showed agents skip pictures and motion when nothing forces them: ten pages built with the first v2 carried no real pictures at all and almost no motion. The inspector now enforces both:
+
+- `few-pictures` (fail): fewer than four real pictures on the page (photographs, archival images, footage, raster artwork; for software, cropped interface fragments). SVG drawings do not count. `no-real-pictures` and `no-footage` warn when a page has fewer than two real photographs or no video.
+- `still-page` (fail under 8, warn under 16): counts the distinct elements that actually move while the page loads and is scrolled, from CSS animations, transitions, Web Animations and script-driven transforms.
+- `assets.mjs --video` finds open-licence footage (Wikimedia Commons, the Internet Archive, NASA) for a muted looping clip.
+
+The motion guidance changed with it: one loud signature move, plus a choreographed entrance for the parts of every section, feedback on every control, and one moving picture. The old "one moment and nothing else" budget is gone; identical fade-ups on every block are still banned.
+
### 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`, `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`.
diff --git a/skills/taste-skill/README.md b/skills/taste-skill/README.md
index c1c4bd9..a98ba12 100644
--- a/skills/taste-skill/README.md
+++ b/skills/taste-skill/README.md
@@ -39,7 +39,8 @@ SKILL.md the run, the house rules, the laws
references/ copy, type, colour, layout, imagery, motion, critique, tells, research
scripts/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 them
+ Chicago, the Met) and, with --video, real footage (Wikimedia Commons, Internet
+ Archive, NASA); --get downloads with the credit, --credits prints them
scripts/lint.mjs static scan for banned patterns and stock phrases
scripts/inspect.mjs render, measure, photograph
scripts/lib/ zero-dependency Chrome DevTools client, the in-page probe, the rules
@@ -68,6 +69,10 @@ a repository under `.claude/skills/`.
- 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).
+- `assets.mjs --video` finds short clips of the subject's world, takes a 720p-or-smaller rendition,
+ refuses files over 25 MB unless `--max-mb` is passed, and saves a poster frame with each clip; how
+ to use one on a page (muted loop, poster, stopped under reduced motion) is in
+ `references/imagery.md` §11.
- 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).
diff --git a/skills/taste-skill/SKILL.md b/skills/taste-skill/SKILL.md
index ebff03b..91d114a 100644
--- a/skills/taste-skill/SKILL.md
+++ b/skills/taste-skill/SKILL.md
@@ -211,7 +211,14 @@ not finished. Order of work:
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.
+ **The floor, which the inspector checks:** at least four real pictures on the page, usually six to
+ twelve (photographs, archival images, maps, engravings, footage, raster artwork; for software, its
+ cropped interface fragments count too). SVG drawings do not count toward the floor: draw what no
+ picture exists of, and still carry real pictures. Add one moving picture wherever an honest clip
+ exists: search it with `assets.mjs --video "<query>"` and use it as a muted loop with a poster
+ frame. Models skip pictures and footage because finding them is work; the page fails without them.
+
+ `references/imagery.md` covers searching, licences and credits, video, drawing, crops and treatments.
5. **The live thing** from step 4, built into the section where it proves the claim (often the hero
or 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
@@ -251,17 +258,29 @@ Judge only the pictures. If a problem is visible in a screenshot, it is real, wh
### 9. Move
-Only now add motion: the single signature move named on the sheet, plus press, hover and focus
-feedback. One exception: a move that changes the colour or the layout of whole screens (colour by
-chapter, a pinned story) is part of the composition, so build it in step 6 and let every look round
-see it. `references/motion.md` has the budget, the tokens and tested recipes. Then run the inspector
-once more and check every screenshot for content that failed to appear.
+Now build the motion layer. It is required, and it is more than one fade: the inspector counts the
+elements that really move while the page loads and is scrolled, and fails a page under eight (it warns
+under sixteen). The layer has four parts:
+
+1. **The signature move** named on the sheet: one, done well.
+2. **An entrance for the parts of every section:** the heading, then the text, then the picture,
+ staggered by 60–90ms, rising 16–32px with opacity, triggered once as the section enters. Not one
+ fade for the whole block, and never content that stays hidden if the script fails.
+3. **Feedback on every control:** press, hover and focus on buttons, links, cards and the live thing.
+4. **One moving picture:** a found clip as a muted loop, a slow scale or drift on a photograph, or a
+ scroll-linked move on the hero picture.
+
+Transform and opacity only; every move has a `prefers-reduced-motion` fallback that keeps the content
+and drops the travel. A move that changes the colour or the layout of whole screens (colour by
+chapter, a pinned story) is part of the composition, so build it in step 6 and let every look round see
+it. `references/motion.md` has the tokens and tested recipes. Then run the inspector once more and check
+every screenshot for content that failed to appear.
### 10. Report
Tell 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;
-every found picture with its title, creator, licence and source page (`assets.mjs --credits` prints
+every found picture and clip 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.
diff --git a/skills/taste-skill/library/directions.json b/skills/taste-skill/library/directions.json
index cde68b7..f7f82e1 100644
--- a/skills/taste-skill/library/directions.json
+++ b/skills/taste-skill/library/directions.json
@@ -420,7 +420,7 @@
"dark-neutral",
"mono-accent"
],
- "imagery": "No photographs needed. The interface fragments are the imagery: build them carefully with real labels, real numbers and sensible states (one hovered, one selected). Give them the product's true radii and spacing.",
+ "imagery": "The interface fragments are the main imagery: build them carefully with real labels, real numbers and sensible states (one hovered, one selected). Around them, two or three real pictures of the customer's world (found with scripts/assets.mjs), never stock of people at laptops.",
"sectionTags": [
"ui-led",
"quiet"
@@ -436,8 +436,7 @@
"opl-uni",
"opl-kontu"
],
- "allow": [],
- "photos": false
+ "allow": []
},
{
"id": "quiet-instrument",
@@ -469,7 +468,7 @@
"light-neutral",
"mono-accent"
],
- "imagery": "Small and precise: a cropped interface detail, a single object photograph at column width, or nothing. Never a large hero image.",
+ "imagery": "Precise rather than loud: cropped interface details at true size, and real photographs of the customer's world held to the column width, each doing one job. One short looping clip can sit at column width too. Never a large stock hero image.",
"sectionTags": [
"quiet",
"ui-led",
@@ -485,8 +484,7 @@
"opl-bueno-fyi",
"aww-gil-huybrecht"
],
- "allow": [],
- "photos": false
+ "allow": []
},
{
"id": "hero-object",
@@ -1041,7 +1039,7 @@
"technical"
],
"needs": [],
- "idea": "No images at all. The page is made only of words, colour and space, and it has to be good enough that nobody misses the pictures. This is the honest answer when a subject has nothing worth photographing: instead of inventing illustrations, set what you have to say as well as it can be set. The typography carries a point of view through scale (one enormous statement, everything else small), through measure (a narrow, bookish column or a full-width line), and through one committed colour.",
+ "idea": "The first screen is made only of words, colour and space, good enough that nobody misses a picture there. Pictures arrive later, large and few, as relief from the type. This is the honest answer when a subject has nothing worth photographing: instead of inventing illustrations, set what you have to say as well as it can be set. The typography carries a point of view through scale (one enormous statement, everything else small), through measure (a narrow, bookish column or a full-width line), and through one committed colour.",
"composition": "First screen: the statement, two lines at most, set at 9–14vw and occupying the full width with tight leading, positioned in the upper two-thirds. One supporting sentence at 20–24px sits bottom-left on the same margin and the single action sits bottom-right on the same baseline. No navigation bar; two or three links in a top corner. Sections that follow are typographic set pieces, each different: a list of five to eight capabilities set at 4–6vw one per line; a paragraph at 28–36px in a 28ch column pushed to the right half; a pair of large numerals with a sentence each; a single quotation filling a colour field. Each section uses a different horizontal position (left, right, full) so the page has movement without imagery.",
"typography": "This direction lives or dies on the face and its settings. Display at tight tracking and leading; text sizes few and far apart (for example 15, 22, 34 and the display size). Use real typographic detail: proper quotes, balanced line breaks, hung punctuation where it helps.",
"typeClasses": [
@@ -1059,7 +1057,7 @@
"light-neutral",
"dark-neutral"
],
- "imagery": "None. Do not add icons, shapes, patterns or abstract graphics to compensate. If a section feels empty, make its type larger or cut the section.",
+ "imagery": "The first screen has no picture. Further down, real pictures of the subject's world (found with scripts/assets.mjs) arrive large and few: a full-bleed photograph between two type sections, a looping clip in one band, an archival image beside a list. Do not add icons, shapes, patterns or abstract graphics to compensate for anything.",
"sectionTags": [
"type-led",
"poster",
@@ -1075,7 +1073,6 @@
"opl-statements",
"aww-nothin"
],
- "allow": [],
- "photos": false
+ "allow": []
}
]
\ No newline at end of file
diff --git a/skills/taste-skill/references/critique.md b/skills/taste-skill/references/critique.md
index e0c49f4..8f955f6 100644
--- a/skills/taste-skill/references/critique.md
+++ b/skills/taste-skill/references/critique.md
@@ -38,7 +38,9 @@ sheets. Make each pass on its own; do not blend them.
7. **Colour.** Name the proportions: which colour holds most of the surface, which supports, where is
the accent? An accent that appears in ten places means nothing. One that appears on the single
action and one detail means "here".
-8. **Images.** Is every image doing a job (showing the thing, setting the place, proving the claim)?
+8. **Images.** Count the real pictures: are there at least four, and is there a moving one? A page of
+ drawings only, or of type only, looks unfinished next to one with real photographs and footage.
+ Is every image doing a job (showing the thing, setting the place, proving the claim)?
Do the crops share ratios? Is anything a grey box, a stretched photo, a fake screen made of bars?
Does the photography share one light and one grade, or is it a stock mix?
9. **Sameness.** Write one word for each section's layout (split, list, full-bleed, grid, statement,
@@ -110,6 +112,10 @@ These override the arithmetic.
a screenshot: overall cannot exceed **6.5**, whatever else is true.
- Pass 3 fails (the page could belong to anyone): creativity cannot exceed **6**.
- The idea passes for the nearest competitor (pass 14): creativity cannot exceed **7**.
+- Fewer than four real pictures (photographs, archival images, footage; drawings do not count):
+ design cannot exceed **6.5**.
+- A page that barely moves (the inspector's `still-page`), or motion that is one identical fade on
+ every block: design cannot exceed **7**.
- No live thing (pass 14): creativity cannot exceed **7.5**.
- Any placeholder (grey box, lorem, "Image here"): content cannot exceed **5**.
- Two or more desktop screens that are mostly empty ground, or a page whose running text is small and
diff --git a/skills/taste-skill/references/imagery.md b/skills/taste-skill/references/imagery.md
index d1a604e..d66fb16 100644
--- a/skills/taste-skill/references/imagery.md
+++ b/skills/taste-skill/references/imagery.md
@@ -16,6 +16,7 @@ how to crop and place them, and what to do when there are none.
8. Drawing the subject
9. Type and colour alone
10. Markup and credits
+11. Video
## 1. What the study measured
@@ -165,7 +166,8 @@ Treatments stay within section 6: untouched, greyscale for the whole set, or mul
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.
+source (no network), draw, and say so in the report. For moving pictures, the same script searches
+real footage with `--video` (section 11).
## 4. The dealt photographs
@@ -309,3 +311,67 @@ The credits, as `--credits` prints them, in the footer:
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.
+
+## 11. Video
+
+A moving picture of the subject's world can carry a section the way a photograph does: the river at
+the end of the street, the roaster's drum turning, a timber frame going up. `assets.mjs --video`
+searches real footage without keys: Wikimedia Commons (every video there comes with web-sized
+transcodes; the best source for short clips), the Internet Archive's Prelinger Archives (industrial,
+educational, city and home films from the 1920s to the 1970s, mostly public domain and mostly long)
+and NASA (the Earth from orbit, launches, aircraft, laboratories). The rest of the Internet Archive is
+left out: anyone can upload there, and the licence claims are unchecked.
+
+```bash
+node <skill>/scripts/assets.mjs "coffee roasting" --video
+node <skill>/scripts/assets.mjs "river" --video --source commons,nasa --orientation landscape
+node <skill>/scripts/assets.mjs --get commons:49769620 # the clip, a poster frame, the credit
+```
+
+It takes a rendition of 720p or smaller (`--res` changes that), lists short clips first, prints each
+clip's length and file size, and flags anything over 25 MB or longer than a minute. `--get` refuses a
+clip over 25 MB unless you pass `--max-mb`, and saves the source's still frame beside it as the
+poster (Commons and NASA; the archive's own stills are too small). An archive film of ten minutes is
+too heavy as it stands: trim a few seconds from it with ffmpeg if it is installed, or choose a
+shorter clip. Licences, credits and honesty work exactly as for pictures (section 3).
+
+**Choosing a clip.**
+
+- **Short:** 5 to 20 seconds that loop without a visible jump: water, smoke, a turning drum, traffic,
+ leaves, a crowd from far away. Watch it to the end before choosing.
+- **Light:** under about 5 MB for a section and 10 MB for a hero. 720p is plenty behind type.
+- **Clean:** no slate, title card, logo, watermark or burned-in caption. NASA and archive films often
+ open with a slate, and the source's poster frame may be that slate. No recognisable person who could
+ be taken for the client's staff or customers.
+- **Never the client's own:** a found clip of a roastery is not this roastery.
+- **One per page, two at most.** A page of moving tiles is noise.
+
+**On the page.**
+
+- Muted, looping, inline, with a poster and a fixed size, as `--get` prints it:
+ `<video autoplay muted loop playsinline preload="metadata" poster="assets/river-poster.jpg"
+ width="854" height="480" aria-hidden="true"><source src="assets/river.webm" type="video/webm"></video>`.
+ No sound and no controls on a decorative loop. `aria-hidden` because it is decoration: whatever the
+ clip says that matters belongs in the text beside it.
+- The poster shows before the clip plays, on slow connections and under reduced motion, so it must
+ work as a picture on its own. If the source's still is a slate or a blur, take a frame from the clip
+ yourself or use a found picture.
+- Under `prefers-reduced-motion: reduce`, stop it and show the poster:
+
+ ```html
+ <script>
+ const calm = matchMedia('(prefers-reduced-motion: reduce)');
+ for (const v of document.querySelectorAll('video[autoplay]')) {
+ const sync = () => { if (calm.matches) { v.removeAttribute('autoplay'); v.pause(); v.load(); } else { v.play().catch(() => {}); } };
+ sync(); calm.addEventListener('change', sync);
+ }
+ </script>
+ ```
+
+- Crop and place it like a photograph (sections 5 and 6): `object-fit: cover`, one ratio, square
+ corners, no frame, a ground-coloured `background-color` while it loads.
+- Never under body text. A headline over a clip gets the same neutral scrim as text on a photograph,
+ and nothing lies on top of a headline or a statement.
+- It is motion: let it be the page's one moving thing, or sit in a section where nothing else moves.
+- Credit it with the pictures: `--credits` prints one footer line for both ("Pictures and footage:")
+ and the list for the report, with each clip's length.
diff --git a/skills/taste-skill/references/motion.md b/skills/taste-skill/references/motion.md
index 5ea9fbd..0655472 100644
--- a/skills/taste-skill/references/motion.md
+++ b/skills/taste-skill/references/motion.md
@@ -15,19 +15,27 @@ Read this before adding any animation. The static page must already be finished
## 1. The budget
-A marketing page gets **one signature moment** and a layer of **quiet feedback**. That is the whole
-budget.
+A page that does not move reads as a mock-up; the inspector counts what moves while the page loads and
+scrolls, and fails it under eight elements. The motion layer has four parts:
-- The signature moment is the thing a visitor would describe an hour later: the headline that rises
+- **One signature moment:** the thing a visitor would describe an hour later: the headline that rises
out of a mask, the image that opens like a shutter, the wordmark that scales with the scroll. The
- direction sheet from `draw.mjs` names one. Build that one well.
-- Feedback is what makes the page feel alive under the hand: buttons that give on press, links that
- answer the pointer, a menu that opens from where it was clicked.
-- Everything else arrives without ceremony. A paragraph does not need an entrance.
-
-Why so strict: fade-and-slide-up on every section with identical timing is the single most cited motion
-tell of generated pages, and curated gallery sites almost never do it. Uniform motion says nobody
-decided anything. One protected moment says somebody did.
+ direction sheet from `draw.mjs` names one. Build that one well; it is the only move allowed to be
+ loud.
+- **Section entrances, choreographed per section:** the parts of each section arrive in reading order
+ (heading, text, picture, details), staggered 60–90ms, rising 16–32px with opacity, once. Vary the
+ manner with the content instead of stamping one preset everywhere: a list arrives row by row, a
+ picture opens from a mask or settles from a slight scale, a figure counts up once, a statement rises
+ line by line.
+- **Feedback under the hand:** buttons that give on press, links that answer the pointer, cards and
+ pictures that respond on hover, a menu that opens from where it was clicked.
+- **One moving picture:** a found clip as a muted loop with a poster frame, a slow drift or scale on
+ a large photograph, or a scroll-linked move on the hero picture.
+
+What is still banned: the same fade-and-slide-up with the same timing on every block, which is the most
+cited motion tell of generated pages; motion that hides content until a script runs, with no fallback;
+bounce and elastic easing; anything that animates layout properties. Uniform motion says nobody decided
+anything; choreographed motion with one protected moment says somebody did.
## 2. Four questions before any animation
diff --git a/skills/taste-skill/scripts/assets.mjs b/skills/taste-skill/scripts/assets.mjs
index 71a4094..4f9c5b1 100644
--- a/skills/taste-skill/scripts/assets.mjs
+++ b/skills/taste-skill/scripts/assets.mjs
@@ -14,14 +14,19 @@
// [--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]
+// node assets.mjs "<query>" --video search for real footage instead (same options, plus
+// [--res 720] the largest rendition to pick, by its short side
+// [--max-mb 25] clips over this are flagged, and --get refuses them
+// node assets.mjs --get <ref>[,<ref>...] [--to assets] [--name <file name>] [--width 1920] [--res 720] [--max-mb 25]
// 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';
+// Image 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). Video sources: Wikimedia Commons (with its web-sized webm
+// transcodes), the Internet Archive (its curated Prelinger Archives of films, public domain or Creative
+// Commons) and the NASA Image and Video Library. Zero dependencies, no API keys. Node 18+ (built-in fetch).
+import { readFileSync, writeFileSync, existsSync, mkdirSync, createWriteStream, unlinkSync } from 'node:fs';
import { join, resolve, relative } from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -29,12 +34,15 @@ 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)' },
+ openverse: { media: 'image', name: 'Openverse', note: 'one index over Flickr, Wikimedia Commons, museums and libraries' },
+ commons: { media: 'both', name: 'Wikimedia Commons', note: 'archival photographs, old maps, scans of prints and books, places as they look now', videoNote: 'video files with web-sized webm transcodes: places, crafts, processes, nature' },
+ aic: { media: 'image', name: 'Art Institute of Chicago', note: 'public-domain paintings, prints, photographs and textiles, served large' },
+ met: { media: 'image', name: 'The Metropolitan Museum of Art', note: 'public-domain objects, prints, drawings and photographs (Open Access)' },
+ archive: { media: 'video', name: 'Internet Archive', note: 'the Prelinger Archives: industrial, educational, city and home films from the 1920s to the 1970s, mostly long' },
+ nasa: { media: 'video', name: 'NASA Image and Video Library', note: 'footage of the Earth, space, aircraft, launches and laboratories' },
};
-const SOURCE_ALIAS = { all: Object.keys(SOURCES), museums: ['aic', 'met'], wikimedia: ['commons'], artic: ['aic'], chicago: ['aic'], metmuseum: ['met'] };
+const SOURCE_ALIAS = { museums: ['aic', 'met'], wikimedia: ['commons'], artic: ['aic'], chicago: ['aic'], metmuseum: ['met'], ia: ['archive'], internetarchive: ['archive'] };
+const VIDEO_TYPES = { 'video/mp4': 'mp4', 'video/webm': 'webm' }; // what every current browser plays; Ogg Theora and QuickTime are left out
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' };
@@ -54,16 +62,22 @@ const USAGE = `Find real, openly licensed pictures of the subject's world, downl
--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} "<query>" --video [options] real footage: Wikimedia Commons, Internet Archive, NASA
+ --source all|commons|archive|nasa
+ --res <p> largest rendition to pick, by its short side, default 720
+ --max-mb <n> clips over this are flagged and --get refuses them, default 25
+ --min-width <px> default 640 for video
+ ${CMD} --get <ref>[,<ref>...] [--to assets] [--name <file name>] [--width 1920] [--res 720] [--max-mb 25]
${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").`;
+words best ("fig", "harbour"). For footage, name the action or the process: "coffee roasting", "timber
+construction", "river", "city street night".`;
// ---------- 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 VALUED = new Set(['source', 'sources', 'license', 'licence', 'orientation', 'min-width', 'width', 'limit', 'get', 'to', 'name', 'type', 'res', 'max-mb']);
+const FLAGS = new Set(['no-check', 'json', 'credits', 'help', 'video']);
const args = {}; const words = [];
const argv = process.argv.slice(2);
for (let i = 0; i < argv.length; i++) {
@@ -86,14 +100,20 @@ function number(key, def, min, max) {
if (!Number.isFinite(n) || n < min || n > max) fail(`--${key} must be a number from ${min} to ${max}.`);
return Math.round(n);
}
+if (args.type !== undefined && !['image', 'images', 'video', 'videos'].includes(String(args.type).toLowerCase())) fail('--type is image or video.');
+const VIDEO = Boolean(args.video) || /^videos?$/i.test(String(args.type || ''));
function pickSources(value) {
+ const media = VIDEO ? 'video' : 'image';
+ const usable = Object.keys(SOURCES).filter((k) => SOURCES[k].media === media || SOURCES[k].media === 'both');
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.`);
+ const found = s === 'all' ? usable : SOURCE_ALIAS[s] || (SOURCES[s] ? [s] : null);
+ if (!found) fail(`Unknown source "${s}". ${VIDEO ? 'Video' : 'Image'} sources: ${usable.join(', ')}${VIDEO ? '' : ', museums (aic and met)'}, all.`);
+ const wrong = found.filter((x) => !usable.includes(x));
+ if (wrong.length) fail(`${wrong.join(', ')} has no ${media === 'video' ? 'video' : 'still images'} here. ${VIDEO ? 'Video' : 'Image'} sources: ${usable.join(', ')}.`);
for (const x of found) if (!out.includes(x)) out.push(x);
}
- return out.length ? out : Object.keys(SOURCES);
+ return out.length ? out : usable;
}
function pickLicences(value) {
const v = String(value).toLowerCase().trim();
@@ -116,9 +136,12 @@ 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),
+ minWidth: number('min-width', VIDEO ? 640 : 1000, 0, 20000),
width: number('width', 1920, 200, 4000),
limit: number('limit', 5, 1, 20),
+ video: VIDEO,
+ res: number('res', 720, 144, 2160),
+ maxMb: number('max-mb', 25, 1, 2000),
check: !args['no-check'],
to: resolve(String(args.to || 'assets')),
toArg: args.to ? ` --to ${args.to}` : '',
@@ -148,7 +171,7 @@ function slug(s) {
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 loose = (s) => String(s).toLowerCase().normalize('NFKD').replace(/\p{M}/gu, '').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);
@@ -198,21 +221,44 @@ function dims(b) {
}
return {};
}
+// Width, height and duration from the head of an MP4 whose index comes first (what web renditions use).
+function mp4Info(b) {
+ const out = {}; let i = -1; let area = 0;
+ while ((i = b.indexOf('tkhd', i + 1)) > 3) { // one per track; the video track is the one with a size
+ const end = i - 4 + b.readUInt32BE(i - 4);
+ if (end <= b.length && end - (i - 4) >= 84) { const w = b.readUInt32BE(end - 8) >>> 16; const h = b.readUInt32BE(end - 4) >>> 16; if (w * h > area) { area = w * h; out.w = w; out.h = h; } }
+ }
+ const m = b.indexOf('mvhd');
+ if (m > 3 && m + 36 <= b.length) {
+ const v1 = b[m + 4] === 1; const scale = b.readUInt32BE(m + (v1 ? 24 : 16)); const d = v1 ? Number(b.readBigUInt64BE(m + 28)) : b.readUInt32BE(m + 20);
+ if (scale && d) out.duration = d / scale;
+ }
+ return out;
+}
+const clock = (s) => { if (!s && s !== 0) return null; const t = Math.round(s); return `${Math.floor(t / 60)}:${String(t % 60).padStart(2, '0')}`; };
// 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) {
+// Does the file load, is it something a browser shows, and how large is it? Reads only the first
+// 128 KB of an image, or 512 KB of a video (enough for an MP4's size and duration).
+async function probe(url, ms = 15000, video = false, again = true) {
const ac = new AbortController(); const timer = setTimeout(() => ac.abort(), ms);
+ const want = video ? 524288 : 131072;
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 headers = video ? { 'User-Agent': UA, Accept: 'video/*' } : imageHeaders(url);
+ const r = await fetch(url, { headers: { ...headers, Range: `bytes=0-${want - 1}` }, signal: ac.signal, redirect: 'follow' });
+ if (!r.ok) {
+ r.body?.cancel().catch(() => {});
+ if (r.status >= 500 && again) { clearTimeout(timer); await sleep(1000); return probe(url, ms, video, false); } // file servers stumble now and then
+ 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' }; }
+ if (!(video ? VIDEO_TYPES : WEB_TYPES)[type]) { r.body?.cancel().catch(() => {}); return { ok: false, why: type ? `not a web ${video ? 'video' : '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; }
+ while (n < want) { 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)) };
+ const head = Buffer.concat(chunks);
+ return { ok: true, type, bytes, ...(video ? (type === 'video/mp4' ? mp4Info(head) : {}) : dims(head)) };
} catch (e) {
return { ok: false, why: e.name === 'AbortError' ? 'timed out' : e.cause?.code || e.message };
} finally { clearTimeout(timer); }
@@ -248,7 +294,28 @@ function credit(it) {
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 };
+ return { ref: `${source}:${id}`, source, media: 'image', 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, estimated: false, duration: null, poster: null, alt: null, notes: [], hint: null };
+}
+// Licence code and version from a licence URL (Creative Commons licences and marks).
+function licenceFromUrl(u) {
+ const s = String(u || '').toLowerCase();
+ if (/publicdomain\/zero/.test(s)) return { code: 'cc0', version: '1.0' };
+ if (/publicdomain\/mark|publicdomain\/?$|\/publicdomain\b/.test(s)) return { code: 'pd', version: null };
+ const m = s.match(/creativecommons\.org\/licenses\/(by(?:-nc)?(?:-sa|-nd)?)\/(\d\.\d)/);
+ return m ? { code: m[1], version: m[2] } : { code: 'other', version: null };
+}
+// Of the renditions a source offers, the largest whose short side is at most `res` (720p by default),
+// in a format every browser plays. If all are larger, the smallest one.
+function pickRendition(list, res) {
+ const playable = list.filter((r) => r.url && VIDEO_TYPES[r.type]);
+ const side = (r) => (r.w && r.h ? Math.min(r.w, r.h) : Infinity);
+ const fit = playable.filter((r) => side(r) <= res).sort((a, b) => side(b) - side(a) || (a.bytes ?? 1e15) - (b.bytes ?? 1e15));
+ return fit[0] || playable.sort((a, b) => side(a) - side(b) || (a.bytes ?? 1e15) - (b.bytes ?? 1e15))[0] || null;
+}
+function useRendition(it, pick, largest) {
+ Object.assign(it, { media: 'video', image: pick.url, mime: pick.type, imageWidth: pick.w || null, imageHeight: pick.h || null, bytes: pick.bytes || null, estimated: Boolean(pick.estimated), duration: it.duration || pick.duration || null });
+ if (largest) { it.width = largest.w || it.width; it.height = largest.h || it.height; }
+ return it;
}
// ---------- Openverse ----------
@@ -408,6 +475,113 @@ function fromMet(x) {
return it;
}
+// ---------- video: Wikimedia Commons ----------
+async function searchCommonsVideo(q, opts) {
+ const j = await getJson(commonsApi({ generator: 'search', gsrnamespace: '6', gsrsearch: `${q} filetype:video`, gsrlimit: '30', ...commonsInfo(1280), prop: 'imageinfo|videoinfo', viprop: 'derivatives' }));
+ 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((pg) => fromCommonsVideo(pg, opts)).filter(Boolean) };
+}
+function fromCommonsVideo(pg, opts) {
+ const it = fromCommons(pg); const ii = pg?.imageinfo?.[0];
+ if (!it || !ii) return null;
+ it.poster = it.image !== it.original ? it.image : null; // for a video file, the thumbnail is a still frame
+ it.duration = Number(ii.duration) || null;
+ // the original plus the transcodes Commons makes of every video (240p to 1080p webm); sizes from their bit rates
+ const renditions = (pg.videoinfo?.[0]?.derivatives || []).map((d) => {
+ const url = noQuery(d.src); const original = !/\/transcoded\//.test(url);
+ return { url, type: String(d.type || '').split(';')[0].trim(), w: Number(d.width) || null, h: Number(d.height) || null,
+ bytes: original ? Number(ii.size) || null : d.bandwidth && it.duration ? Math.round((d.bandwidth * it.duration) / 8) : null, estimated: !original };
+ });
+ const pick = pickRendition(renditions, opts.res);
+ return pick ? useRendition(it, pick, { w: ii.width, h: ii.height }) : null;
+}
+
+// ---------- video: Internet Archive ----------
+const first = (v) => (Array.isArray(v) ? v[0] : v);
+const seconds = (s) => {
+ if (s === undefined || s === null || s === '') return null;
+ if (/^\d+(\.\d+)?$/.test(String(s))) return Number(s);
+ const p = String(s).split(':').map(Number); return p.length > 1 && p.every(Number.isFinite) ? p.reduce((a, x) => a * 60 + x, 0) : null;
+};
+// Only the Prelinger Archives: curated industrial, educational, advertising and home films, mostly in the
+// public domain. The rest of the archive's films are uploads by anyone, and their licence claims go
+// unchecked (an upload called "... all rights reserved" can carry a public-domain mark), so they are left out.
+const ARCHIVE_LICENCE = { cc0: '*publicdomain\\/zero*', pd: '*publicdomain*', by: '*licenses\\/by\\/*', 'by-sa': '*licenses\\/by-sa\\/*', 'by-nc': '*licenses\\/by-nc\\/*', 'by-nd': '*licenses\\/by-nd\\/*', 'by-nc-sa': '*licenses\\/by-nc-sa\\/*', 'by-nc-nd': '*licenses\\/by-nc-nd\\/*' };
+async function searchArchive(q, opts) {
+ const words = queryWords(q);
+ const licences = opts.licences.includes('other') ? '' : ` AND licenseurl:(${[...new Set(opts.licences.map((l) => ARCHIVE_LICENCE[l]))].join(' OR ')})`;
+ const p = new URLSearchParams({ q: `(${(words.length ? words : [q]).join(' AND ')}) AND mediatype:(movies) AND collection:(prelinger)${licences}`, rows: '40', output: 'json' });
+ for (const f of ['identifier', 'licenseurl']) p.append('fl[]', f);
+ const j = await getJson(`https://archive.org/advancedsearch.php?${p}`, 30000);
+ if (j.error) throw new Error(`its search is failing right now (${short(text(j.error), 80)}); try again later`);
+ const docs = j.response?.docs || [];
+ const allowed = docs.filter((d) => opts.licences.includes(licenceFromUrl(first(d.licenseurl)).code));
+ const metas = await mapLimit(allowed.slice(0, opts.limit * 2 + 4), 6, (d) => getJson(`https://archive.org/metadata/${encodeURIComponent(d.identifier)}`, 20000).catch(() => null));
+ return { total: j.response?.numFound ?? null, skippedLicence: docs.length - allowed.length, items: metas.map((m) => fromArchive(m, opts)).filter(Boolean) };
+}
+function fromArchive(m, opts) {
+ const md = m?.metadata; if (!md?.identifier || !Array.isArray(m.files)) return null;
+ const id = md.identifier;
+ const fileUrl = (name) => `https://archive.org/download/${encodeURIComponent(id)}/${String(name).split('/').map(encodeURIComponent).join('/')}`;
+ const isVideo = (f) => /\.(mp4|m4v|webm|mpe?g|avi|mov|ogv|mkv|wmv|flv)$/i.test(f.name || '');
+ // an item can hold several films: keep the first original and the web copies made from it
+ const originals = m.files.filter((f) => f.source === 'original' && isVideo(f));
+ const stem = originals[0] ? originals[0].name.replace(/\.[^.]+$/, '') : null;
+ const family = m.files.filter((f) => isVideo(f) && (!stem || f.name.startsWith(stem)));
+ const renditions = family.filter((f) => /\.(mp4|webm)$/i.test(f.name)).map((f) => ({ url: fileUrl(f.name), type: /\.webm$/i.test(f.name) ? 'video/webm' : 'video/mp4', w: Number(f.width) || null, h: Number(f.height) || null, bytes: Number(f.size) || null, duration: seconds(f.length) }));
+ const pick = pickRendition(renditions, opts.res); if (!pick) return null;
+ const largest = family.reduce((a, f) => ((Number(f.width) || 0) > (a.w || 0) ? { w: Number(f.width), h: Number(f.height) } : a), { w: pick.w, h: pick.h });
+ const lic = licenceFromUrl(first(md.licenseurl));
+ const it = base('archive', id);
+ Object.assign(it, {
+ title: text(first(md.title)) || id, creator: text(first(md.creator)), date: text(first(md.date) || first(md.year)) || null, about: text(first(md.description)) || null,
+ license: lic.code, licenseVersion: lic.version, licenseUrl: first(md.licenseurl) || null, page: `https://archive.org/details/${id}`,
+ original: fileUrl((originals[0] || family[0]).name), duration: pick.duration || seconds(first(md.runtime)),
+ poster: null, // the archive's own stills are about 160 pixels wide: too small to stand in for a clip
+ });
+ // the same film is often stored in several formats; different names mean different films
+ const films = new Set(originals.map((f) => f.name.split('/').pop().split('.')[0])).size;
+ if (films > 1) it.notes.push(`This item holds ${films} films; the first is shown. The page lists the others.`);
+ return useRendition(it, pick, largest);
+}
+
+// ---------- video: NASA Image and Video Library ----------
+const nasaUrl = (u) => (u ? encodeURI(String(u).replace(/^http:/, 'https:')).replace(/%25([0-9a-f]{2})/gi, '%$1') : null);
+async function searchNasa(q, opts) {
+ const j = await getJson(`https://images-api.nasa.gov/search?${new URLSearchParams({ q, media_type: 'video', page_size: String(Math.min(100, opts.limit * 3 + 6)) })}`);
+ // its search matches any word anywhere; keep the clips whose own title, description or keywords carry the query
+ const wanted = queryWords(q);
+ const rows = (j.collection?.items || []).filter((x) => { const d = x.data?.[0] || {}; return onSubject(wanted, [d.title, d.description, ...(d.keywords || [])].join(' ')); }).slice(0, opts.limit * 2 + 4);
+ const items = await mapLimit(rows, 6, async (x) => fromNasa(x, await getJson(nasaUrl(x.href), 15000).catch(() => null), opts));
+ return { total: j.collection?.metadata?.total_hits ?? null, items: items.filter(Boolean) };
+}
+function fromNasa(x, files, opts) {
+ const d = x?.data?.[0]; if (!d?.nasa_id || !Array.isArray(files)) return null;
+ const find = (suffix) => files.find((f) => String(f).endsWith(suffix));
+ // NASA makes the same renditions of every video; these are their 16:9 sizes, and the check reads the real ones
+ const renditions = [['~large.mp4', 1920, 1080], ['~medium.mp4', 1280, 720], ['~small.mp4', 640, 360], ['~mobile.mp4', 320, 180]]
+ .filter(([s]) => find(s)).map(([s, w, h]) => ({ url: nasaUrl(find(s)), type: 'video/mp4', w, h }));
+ const pick = pickRendition(renditions, opts.res); if (!pick) return null;
+ const it = base('nasa', encodeURIComponent(d.nasa_id));
+ Object.assign(it, {
+ title: text(d.title) || d.nasa_id, creator: text(d.photographer || d.secondary_creator) || `NASA${d.center ? ' ' + d.center : ''}`,
+ date: String(d.date_created || '').slice(0, 10) || null, about: text(d.description) || null,
+ license: 'pd', licenseName: 'public domain (NASA)', licenseUrl: 'https://www.nasa.gov/nasa-brand-center/images-and-media/',
+ page: `https://images.nasa.gov/details/${encodeURIComponent(d.nasa_id)}`, original: nasaUrl(find('~orig.mp4')) || pick.url,
+ poster: nasaUrl(find('~large.jpg') || find('~medium.jpg') || find('~thumb.jpg')),
+ });
+ it.notes.push('NASA footage is generally free of copyright in the US. Never use NASA logos or suggest NASA endorses the client; check the page for third-party material.');
+ return useRendition(it, pick, renditions[0]);
+}
+function videoNotes(it, opts) {
+ const n = [];
+ const smaller = it.imageWidth && it.imageHeight && Math.min(it.imageWidth, it.imageHeight) > 480;
+ if (it.bytes && it.bytes > opts.maxMb * 1048576) n.push(`Over ${opts.maxMb} MB (${it.estimated ? 'about ' : ''}${size(it.bytes)}): too heavy for a page, and --get refuses it unless you pass --max-mb. ${smaller ? 'Try --res 480, or a shorter clip.' : 'Choose a shorter clip.'}`);
+ if (it.duration && it.duration > 60) n.push(`Long (${clock(it.duration)}): a loop on a page wants 5 to 20 seconds. Prefer a shorter clip, or trim one with ffmpeg if it is installed.`);
+ return n;
+}
+
// ---------- search ----------
function fits(it, opts, skipped) {
const W = it.width || it.imageWidth; const H = it.height || it.imageHeight;
@@ -416,16 +590,20 @@ function fits(it, opts, skipped) {
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 runners = opts.video ? { commons: searchCommonsVideo, archive: searchArchive, nasa: searchNasa } : { openverse: searchOpenverse, commons: searchCommons, aic: searchAic, met: searchMet };
+ // a slow service never holds the whole search: each source gets 45 s, the 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: [] }; }
}));
+ // short clips first, then longer ones, then anything over the size cap; the source's own order within each
+ const cap = opts.maxMb * 1048576;
+ const rank = (it) => (it.media !== 'video' ? 0 : it.bytes && it.bytes > cap ? 4 : !it.duration ? 3 : it.duration <= 30 ? 0 : it.duration <= 90 ? 1 : it.duration <= 300 ? 2 : 3);
+ const byRank = (a, b) => rank(a) - rank(b);
const seen = new Set();
for (const r of results) {
- r.skipped = { licence: 0, small: 0, shape: 0, dead: 0, alike: 0 };
+ r.skipped = { licence: r.skippedLicence || 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; }
@@ -435,31 +613,35 @@ async function search(query, opts) {
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
+ }).sort(byRank).slice(0, opts.limit + 4); // a few spares for files 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;
+ const video = it.media === 'video';
+ const p = await probe(it.image, video ? 15000 : 12000, video); 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;
+ if (p.ok && p.bytes) { it.bytes = p.bytes; it.estimated = false; }
+ if (p.ok && p.duration) it.duration = p.duration;
}), 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.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))).sort(byRank);
}
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 },
+ console.log(JSON.stringify({ query, options: { media: opts.video ? 'video' : 'image', sources: opts.sources, licences: opts.licences, orientation: opts.orientation, minWidth: opts.minWidth, width: opts.width, res: opts.video ? opts.res : undefined, maxMb: opts.video ? opts.maxMb : undefined, 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));
+ items: r.items.map(({ check, ...it }) => ({ ...it, licenseLabel: licenceLabel(it), licenseUrl: licenceUrl(it), creditRequired: creditRequired(it), credit: credit(it), notes: [...it.notes, ...licenceNotes(it), ...(it.media === 'video' ? videoNotes(it, opts) : [])] })) })) }, 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(' · ')}`);
+ const filters = opts.video
+ ? [`licences ${opts.licences.join(', ')}`, `at least ${opts.minWidth}px wide`, opts.orientation, `renditions up to ${opts.res}p`, `flagged over ${opts.maxMb} MB`, opts.check ? 'every file checked' : 'files not checked']
+ : [`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'];
+ console.log(`ASSETS${opts.video ? ' · VIDEO' : ''} · "${query}" · ${filters.filter(Boolean).join(' · ')}`);
for (const r of results) {
const src = SOURCES[r.key];
console.log('');
@@ -469,7 +651,7 @@ async function search(query, opts) {
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}`);
+ console.log(`${(opts.video && src.videoNote) || src.note}`);
for (const it of r.items) {
console.log('');
console.log(`${it.ref} ${short(it.title, 100)}${it.date ? ` (${short(it.date, 30)})` : ''}`);
@@ -478,14 +660,21 @@ async function search(query, opts) {
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}`);
+ if (it.media === 'video') {
+ const facts = [pixels, it.duration ? clock(it.duration) : 'length unknown', it.bytes ? `${it.estimated ? 'about ' : ''}${size(it.bytes)}` : null, VIDEO_TYPES[it.mime]];
+ console.log(` file ${it.image}`);
+ console.log(` size ${facts.filter(Boolean).join(', ')}${largest}${sh ? `; ${sh}` : ''}`);
+ if (it.poster) console.log(` poster ${it.poster}`);
+ } else {
+ 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}`);
+ for (const n of [...(it.media === 'video' ? videoNotes(it, opts) : []), ...it.notes, ...licenceNotes(it), ...(it.hint ? [it.hint] : [])]) console.log(` note ${n}`);
}
}
console.log('');
@@ -494,36 +683,61 @@ async function search(query, opts) {
console.log('pictures instead (references/imagery.md) and say in your report that the open collections could not be searched.');
return 1;
}
+ if (!shown && opts.video) {
+ console.log('Nothing usable came back. Name the action or the process ("coffee roasting", "timber framing", "river"); use fewer');
+ console.log('words; try a smaller --min-width or another --source. A page does not need video: a still picture or a drawing is fine.');
+ 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.');
+ if (opts.video) console.log('Next. Watch before you choose: --get downloads the clip and a poster frame into the project and records the credit.');
+ else 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.');
+ console.log(`These ${opts.video ? 'clips' : '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 []; } }
+// A file name in the target folder that is free, or already belongs to this same picture.
+function targetFile(opts, stem, ext, ref, credits) {
+ let file = join(opts.to, `${stem}.${ext}`);
+ for (let k = 2; existsSync(file) && credits.find((c) => c.file === rel(file))?.ref !== ref; k++) file = join(opts.to, `${stem}-${k}.${ext}`);
+ return file;
+}
+function recordCredit(opts, credits, entry) { writeFileSync(creditsPath(opts), JSON.stringify([...credits.filter((c) => c.file !== entry.file), entry], null, 1)); }
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 m = String(ref).match(/^(openverse|commons|aic|met|archive|nasa):(.+)$/);
+ if (!m) throw new Error('a ref looks like openverse:<id>, commons:<id>, aic:<id>, met:<id>, archive:<id> or nasa:<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 === 'commons') {
+ // the same ref form serves pictures and videos; the record says which
+ const j = await getJson(commonsApi({ pageids: id, ...commonsInfo(opts.width), iiprop: 'url|size|mime|mediatype|extmetadata', prop: 'imageinfo|videoinfo', viprop: 'derivatives' }));
+ const pg = j.query?.pages?.[0]; const ii = pg?.imageinfo?.[0];
+ it = ii && (ii.mediatype === 'VIDEO' || /^video\//.test(ii.mime || '')) ? fromCommonsVideo(pg, opts) : fromCommons(pg);
+ }
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 if (src === 'archive') it = fromArchive(await getJson(`https://archive.org/metadata/${encodeURIComponent(id)}`, 30000), opts);
+ else if (src === 'nasa') {
+ const j = await getJson(`https://images-api.nasa.gov/search?${new URLSearchParams({ nasa_id: decodeURIComponent(id), media_type: 'video' })}`);
+ const x = j.collection?.items?.[0];
+ it = x ? fromNasa(x, await getJson(nasaUrl(x.href), 15000), opts) : null;
+ }
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 (!it || !it.image) throw new Error(`no usable ${['archive', 'nasa'].includes(src) ? 'video (no rendition a browser plays, or the record is gone)' : '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.`);
+ if (it.media === 'video') return getVideo(it, src, id, opts);
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}).`); }
@@ -537,16 +751,15 @@ async function getOne(ref, opts) {
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}`);
+ const file = targetFile(opts, stem, ext, it.ref, credits);
writeFileSync(file, buf);
const entry = {
- file: rel(file), ref: it.ref, title: it.title, creator: it.creator || null, creatorUrl: it.creatorUrl, date: it.date,
+ file: rel(file), media: 'image', 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));
+ recordCredit(opts, credits, entry);
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}`);
@@ -555,6 +768,60 @@ async function getOne(ref, opts) {
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}`);
}
+// A clip: check its size against the cap first, stream it to disk (stopping at the cap), then save a still
+// frame from the source as its poster.
+async function getVideo(it, src, id, opts) {
+ const cap = opts.maxMb * 1048576;
+ const head = await probe(it.image, 20000, true);
+ if (!head.ok) throw new Error(`the video did not load (${head.why}).`);
+ const side = it.imageWidth && it.imageHeight ? Math.min(it.imageWidth, it.imageHeight) : 0;
+ if (head.bytes && head.bytes > cap) throw new Error(`the clip is ${size(head.bytes)}, over the ${opts.maxMb} MB cap. ${side > 480 ? 'Try --res 480 for a smaller rendition, or a shorter clip' : 'Choose a shorter clip'}; pass --max-mb ${Math.ceil(head.bytes / 1048576) + 1} only if the page really needs this one.`);
+ mkdirSync(opts.to, { recursive: true });
+ const credits = readCredits(opts);
+ const stem = slug(args.name || it.title) || `${src}-${slug(decodeURIComponent(id)).slice(0, 12)}`;
+ const file = targetFile(opts, stem, VIDEO_TYPES[head.type], it.ref, credits);
+ let r;
+ try { r = await fetch(it.image, { headers: { 'User-Agent': UA, Accept: 'video/*' }, signal: AbortSignal.timeout(600000) }); }
+ catch (e) { throw new Error(`the video did not download (${e.name === 'TimeoutError' ? 'timed out' : e.cause?.code || e.message}).`); }
+ if (!r.ok) throw new Error(`the video did not load (HTTP ${r.status}).`);
+ const out = createWriteStream(file); const first512 = []; let kept = 0; let n = 0;
+ try {
+ const reader = r.body.getReader();
+ for (;;) {
+ const { done, value } = await reader.read(); if (done) break;
+ n += value.length;
+ if (n > cap) { reader.cancel().catch(() => {}); throw new Error(`the clip passed the ${opts.maxMb} MB cap while downloading; choose a shorter clip or pass a larger --max-mb.`); }
+ if (kept < 524288) { first512.push(value); kept += value.length; }
+ if (!out.write(value)) await new Promise((res) => out.once('drain', res));
+ }
+ await new Promise((res, rej) => out.end((e) => (e ? rej(e) : res())));
+ } catch (e) { out.destroy(); try { unlinkSync(file); } catch {} throw e; }
+ if (!n) { try { unlinkSync(file); } catch {} throw new Error('the video was empty.'); }
+ const info = head.type === 'video/mp4' ? mp4Info(Buffer.concat(first512)) : {};
+ const w = info.w || it.imageWidth; const h = info.h || it.imageHeight; const duration = info.duration || it.duration;
+ let poster = null;
+ if (it.poster) {
+ try {
+ const pr = await fetch(it.poster, { headers: imageHeaders(it.poster), signal: AbortSignal.timeout(60000) });
+ const pt = (pr.headers.get('content-type') || '').split(';')[0].trim().toLowerCase();
+ if (pr.ok && WEB_TYPES[pt]) { poster = file.replace(/\.[^.]+$/, `-poster.${WEB_TYPES[pt]}`); writeFileSync(poster, Buffer.from(await pr.arrayBuffer())); }
+ } catch { poster = null; }
+ }
+ const entry = {
+ file: rel(file), media: 'video', poster: poster ? rel(poster) : null, 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, video: it.image, width: w || null, height: h || null, duration: duration ? Math.round(duration * 10) / 10 : null, bytes: n,
+ credit: credit(it), notes: [...it.notes, ...licenceNotes(it), ...videoNotes({ ...it, bytes: n, duration }, opts)], saved: new Date().toISOString(),
+ };
+ recordCredit(opts, credits, entry);
+ console.log(`Saved ${entry.file}${w ? ` · ${w} × ${h}` : ''}${duration ? ` · ${clock(duration)}` : ''} · ${size(n)}`);
+ console.log(` poster ${entry.poster || 'none from the source: export a still frame yourself, or use a found picture'}`);
+ console.log(` page ${it.page}`);
+ console.log(` credit ${entry.credit}`);
+ console.log(` markup <video autoplay muted loop playsinline preload="metadata"${entry.poster ? ` poster="${esc(entry.poster)}"` : ''}${w ? ` width="${w}" height="${h}"` : ''} aria-hidden="true"><source src="${esc(entry.file)}" type="${head.type}"></video>`);
+ console.log(' (a silent loop is decoration: pause it or show the poster under prefers-reduced-motion; references/imagery.md "Video")');
+ for (const x of entry.notes) console.log(` note ${x}`);
+}
async function getAll(refs, opts) {
let failed = 0;
for (const ref of refs) {
@@ -562,7 +829,7 @@ async function getAll(refs, opts) {
console.log('');
}
if (failed < refs.length) {
- console.log(`Credits are recorded in ${rel(creditsPath(opts))}. Look at each picture before using it.`);
+ console.log(`Credits are recorded in ${rel(creditsPath(opts))}. Look at each picture and watch each clip before using it.`);
console.log(`Print the footer credits and the report list with: ${CMD} --credits${opts.toArg}`);
}
return failed ? 1 : 0;
@@ -579,11 +846,13 @@ function printCredits(opts) {
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)}`;
};
+ const media = new Set(uniq.map((c) => c.media || 'image'));
+ const label = media.size > 1 ? 'Pictures and footage' : media.has('video') ? 'Footage' : 'Pictures';
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('running text). Remove anything the page no longer uses, here and in credits.json.\n');
+ console.log(`<p class="credits">${label}: ${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)'}`);
+ for (const c of uniq) console.log(`- ${c.file}${c.media === 'video' && c.duration ? ` (video, ${clock(c.duration)})` : ''}: ${c.credit}. ${c.page}${c.creditRequired ? '' : ' (no credit required)'}`);
return 0;
}
diff --git a/skills/taste-skill/scripts/draw.mjs b/skills/taste-skill/scripts/draw.mjs
index 552c456..dc4b533 100644
--- a/skills/taste-skill/scripts/draw.mjs
+++ b/skills/taste-skill/scripts/draw.mjs
@@ -477,6 +477,7 @@ function render(s) {
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);
+ p(); p('**Floor (the inspector checks it):** at least four real pictures on the page, usually six to twelve; SVG drawings do not count. One moving picture where an honest clip exists: `node <skill>/scripts/assets.mjs --video "<query>"`, used as a muted loop with a poster frame. Whatever this direction says about pictures, it is carried out with real ones.');
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})`);
@@ -491,7 +492,7 @@ function render(s) {
p('add `?grayscale` to desaturate. ' + (s.imagery === 'interface' ? 'Use at most two.' : 'Use three to six of them, not all eight.') + ' Always set `width`, `height`, `alt` and `loading="lazy"` (not on the hero image).');
if (s.photos.others?.length) p(`Other sets that fit this brief: ${s.photos.others.join(', ')} — \`node draw.mjs --photos <set>\` prints one in full; \`--photos list\` shows all sets. Taking photographs from another set is your call and is not a redraw; keep them to one light and one treatment.`);
} else if (d.photos === false) {
- p(); p('This direction uses no photographs. Do not add any.');
+ p(); p('This direction does not lead with photographs; it still carries the picture floor below, with real pictures placed where the direction allows them.');
}
p();
const adjust = (bp) => { const n = adjustments(bp, s); if (n.length) { p(); p('Adjusted for this page:'); for (const x of n) p(`- ${x}`); } };
@@ -505,7 +506,7 @@ function render(s) {
p(`### ${i + 1}. ${sec.role} — ${sec.name} (${sec.shape})`); p(sec.blueprint); if (sec.mobile) p(`On a phone: ${sec.mobile}`); adjust(sec);
});
p();
- if (s.motion) { p(`## 8. Motion — ${s.motion.name}`); p(s.motion.description); p('Recipes and limits: references/motion.md. This is the only showpiece; everything else is quiet feedback.'); p(); }
+ if (s.motion) { p(`## 8. Motion — ${s.motion.name}`); p(s.motion.description); p('This is the signature move, the one loud moment. Around it the page still needs the rest of the motion layer (SKILL.md step 9): an entrance for the parts of every section, feedback on every control, and one moving picture. The inspector fails a page that barely moves. Recipes: references/motion.md.'); p(); }
if (d.richness) { p('## 9. Where the richness comes from'); p(d.richness); p(); }
if (d.pitfalls) { p('## 10. How this direction goes wrong'); p(d.pitfalls); p(); }
if (s.references?.length) {
diff --git a/skills/taste-skill/scripts/inspect.mjs b/skills/taste-skill/scripts/inspect.mjs
index 1b68408..1c5b6cc 100644
--- a/skills/taste-skill/scripts/inspect.mjs
+++ b/skills/taste-skill/scripts/inspect.mjs
@@ -60,6 +60,22 @@ const browser = await Browser.launch();
const helper = await browser.newPage({ width: 1600, height: 1000 });
const report = { url: server ? target : url, at: new Date().toISOString(), allow, viewports: [], findings: [], images: [] };
+const MOTION_MIN = 8, MOTION_GOOD = 16; // distinct moving elements over load + one scroll through the page
+// Runs in the page before any of its own scripts: counts the distinct elements that actually move while
+// the page loads and is scrolled (CSS animations, CSS transitions, Web Animations, and script-driven
+// transform/opacity changes such as GSAP), so a page that never moves can be told from one that does.
+const MOTION_RECORDER = `(() => {
+ const seen = new WeakSet(); const c = { elements: 0, css: 0, transitions: 0, scripted: 0 };
+ const note = (t, k) => { if (!(t instanceof Element) || seen.has(t)) return; seen.add(t); c.elements++; c[k]++; };
+ addEventListener('animationstart', (e) => note(e.target, 'css'), true);
+ addEventListener('transitionrun', (e) => note(e.target, 'transitions'), true);
+ const watch = () => new MutationObserver((list) => { for (const m of list) { const s = m.target.getAttribute && m.target.getAttribute('style') || ''; if (/transform|translate|opacity|scale|rotate|clip-path/.test(s)) note(m.target, 'scripted'); } })
+ .observe(document.documentElement, { attributes: true, attributeFilter: ['style'], subtree: true });
+ if (document.documentElement) watch(); else addEventListener('DOMContentLoaded', watch);
+ window.__motionSample = () => { for (const a of document.getAnimations ? document.getAnimations() : []) { const t = a.effect && a.effect.target; if (t) note(t, a.constructor && a.constructor.name === 'CSSTransition' ? 'transitions' : 'css'); } };
+ window.__motion = () => { window.__motionSample(); const v = [...document.querySelectorAll('video')]; return { ...c, videos: v.length, playingVideos: v.filter((x) => x.autoplay || !x.paused).length }; };
+})();`;
+
async function sheet(frames, cols, cellW, cellH, path) {
const rows = Math.ceil(frames.length / cols);
await helper.setViewport({ width: cols * cellW, height: rows * cellH, dsf: 1 });
@@ -76,6 +92,7 @@ try {
const h = HEIGHT[w] || Math.round(w * 0.625);
const label = name(w);
const page = await browser.newPage({ width: w, height: h, dsf: 1, mobile: w < 600 });
+ await page.send('Page.addScriptToEvaluateOnNewDocument', { source: MOTION_RECORDER }).catch(() => {});
const how = await page.goto(url, { timeoutMs: 30000, settleMs: 600 });
await page.eval('document.fonts.ready.then(() => true)').catch(() => {});
await sleep(1400); // let the load choreography finish before judging the first screen
@@ -93,7 +110,9 @@ try {
await sleep(650);
frames.push(await page.screenshot({ quality: 78 }));
frameChecks.push(await page.eval(frame).catch(() => null));
+ await page.eval('window.__motionSample && window.__motionSample()').catch(() => {});
}
+ const motion = await page.eval('window.__motion ? window.__motion() : null').catch(() => null);
// re-measure after everything has revealed (catches content that only exists post-reveal)
await page.eval(`window.scrollTo({ top: 0, behavior: 'instant' })`).catch(() => {});
await sleep(350);
@@ -124,8 +143,14 @@ try {
frameChecks.forEach((f, i) => { for (const t of f?.big || []) { const r = runs.get(t) || { start: i, last: i - 1, best: 0 }; if (r.last === i - 1) r.last = i; else { r.start = i; r.last = i; } r.best = Math.max(r.best, r.last - r.start + 1); runs.set(t, r); } });
const longPins = [...runs.entries()].filter(([, r]) => r.best >= 3);
if (w >= 1100 && longPins.length && !allow.includes('long-pin')) findings.push({ level: 'WARN', id: 'long-pin', width: w, message: `The same large text stays on screen for ${Math.max(...longPins.map(([, r]) => r.best))} screens in a row: ` + longPins.slice(0, 2).map(([t]) => `"${t}"`).join('; '), fix: 'A pinned element earns two screens, and something must change at each. Shorten the run or give every screen its own content.' });
+ // a page that barely moves: counted from what really animated while it loaded and was scrolled
+ if (w >= 1100 && motion && !allow.includes('still-page')) {
+ const moving = motion.elements + motion.playingVideos * 4;
+ if (moving < MOTION_MIN) findings.push({ level: 'FAIL', id: 'still-page', width: w, message: `Only ${motion.elements} element(s) moved while the page loaded and scrolled${motion.playingVideos ? ` (plus ${motion.playingVideos} playing video)` : ''}.`, fix: 'Build the motion layer (SKILL.md step 9, references/motion.md): the signature move, an entrance for the parts of every section, feedback on every control, and one moving picture. Transform and opacity only, with a reduced-motion fallback.' });
+ else if (moving < MOTION_GOOD) findings.push({ level: 'WARN', id: 'still-page', width: w, message: `Little motion: ${motion.elements} element(s) moved while the page loaded and scrolled.`, fix: 'Give every section an entrance for its parts (not one fade of the whole block) and add one moving picture: a looping clip or a slow move on a photograph.' });
+ }
if (w >= 1100 && empty.length >= 2 && !allow.includes('empty-screens')) findings.push({ level: 'FAIL', id: 'empty-screens', width: w, message: `${empty.length} of ${frameChecks.length} desktop screens are almost empty ground (under 20% of the screen holds text, a picture or a colour field): screens ${empty.map(({ i }) => i + 1).join(', ')}.`, fix: 'An empty screen is a rest only once per page. Elsewhere it means the section is underbuilt: set its content larger, give it the full information, put it on a colour field, or cut it.' });
- report.viewports.push({ width: w, height: h, load: how, screens: frames.length, filled: frameChecks.map((f) => f?.filled ?? null), metrics: m, consoleErrors: page.consoleErrors.slice(0, 5) });
+ report.viewports.push({ width: w, height: h, load: how, screens: frames.length, filled: frameChecks.map((f) => f?.filled ?? null), motion, metrics: m, consoleErrors: page.consoleErrors.slice(0, 5) });
report.findings.push(...findings);
report.images.push({ viewport: label, width: w, fold, pages: sheets });
await page.close();
diff --git a/skills/taste-skill/scripts/lib/probe.mjs b/skills/taste-skill/scripts/lib/probe.mjs
index 9791f66..1739967 100644
--- a/skills/taste-skill/scripts/lib/probe.mjs
+++ b/skills/taste-skill/scripts/lib/probe.mjs
@@ -399,6 +399,23 @@ export function probe() {
// data-ui is for cropped interface fragments, not for wrapping the page
const uiAbuse = [...document.querySelectorAll('[data-ui]')].some((el) => el.querySelector('h1') || el.getBoundingClientRect().height > H * 1.6 || el === document.body);
const uiFragments = document.querySelectorAll('[data-ui]').length;
+ // pictures that were not drawn by the page's own code: photographs, footage, raster artwork.
+ // Inline SVG and .svg files do not count; cropped interface fragments (data-ui) are counted apart.
+ const svgSrc = (u) => /\.svg(\?|#|$)|^data:image\/svg/i.test(u || '');
+ let realPictures = 0, videoCount = 0; const pictureSamples = [];
+ for (const el of all) {
+ if (el.closest('[data-ui]') || el.closest('svg')) continue;
+ const r = el.getBoundingClientRect(); if (r.width < 120 || r.height < 90 || r.width * r.height < 160 * 120) continue;
+ if (el.tagName === 'IMG') {
+ const src = el.currentSrc || el.src;
+ if (el.naturalWidth > 0 && !svgSrc(src)) { realPictures++; if (pictureSamples.length < 8) pictureSamples.push(src.split('/').pop().slice(0, 48)); }
+ continue;
+ }
+ if (el.tagName === 'VIDEO') { realPictures++; videoCount++; continue; }
+ const bg = getComputedStyle(el).backgroundImage;
+ if (bg && bg.includes('url(')) { const u = (bg.match(/url\(["']?([^"')]+)/) || [])[1]; if (!svgSrc(u)) realPictures++; }
+ }
+ const uiPictures = [...document.querySelectorAll('[data-ui]')].filter((el) => { const r = el.getBoundingClientRect(); return r.width >= 300 && r.height >= 200; }).length;
// which elements push the page wider than the viewport (the deepest ones that are not clipped by an ancestor)
let overflowCulprits = [];
if (document.documentElement.scrollWidth > W + 2) {
@@ -420,7 +437,7 @@ export function probe() {
viewport: { w: W, h: H },
page: { height: pageH, screens: round(pageH / H, 1), words: bodyText.split(/\s+/).filter(Boolean).length,
img: document.images.length, video: document.querySelectorAll('video').length, canvas: document.querySelectorAll('canvas').length, svg: document.querySelectorAll('svg').length, sections: document.querySelectorAll('section').length,
- horizontalOverflow: doc.scrollWidth > W + 2 ? doc.scrollWidth - W : 0, overflowCulprits, uiFragments, uiAbuse, blendText, sideScrollers, brokenImages, emoji: [...new Set(emoji)].slice(0, 10) },
+ horizontalOverflow: doc.scrollWidth > W + 2 ? doc.scrollWidth - W : 0, overflowCulprits, uiFragments, uiAbuse, realPictures, videoCount, uiPictures, pictureSamples, blendText, sideScrollers, brokenImages, emoji: [...new Set(emoji)].slice(0, 10) },
hero: heroOut, h1,
headings: headingStats.slice(0, 40),
headingSummary: { count: headingStats.length, maxLines: Math.max(0, ...headingStats.map((h) => h.lines)), over2Lines: headingStats.filter((h) => h.lines > 2 && h.kind !== 'statement').length, statements: headingStats.filter((h) => h.kind === 'statement').length, centered: headingStats.filter((h) => h.align === 'center').length, medianWords: below.length ? below.map((h) => h.words).sort((a, b) => a - b)[Math.floor(below.length / 2)] : null, mixedFontHeadings: headingStats.filter((h) => h.mixedFonts).length },
diff --git a/skills/taste-skill/scripts/lib/rules.mjs b/skills/taste-skill/scripts/lib/rules.mjs
index 652c9bd..a2dada2 100644
--- a/skills/taste-skill/scripts/lib/rules.mjs
+++ b/skills/taste-skill/scripts/lib/rules.mjs
@@ -107,6 +107,13 @@ export function judge(m, { width = m.viewport.w, allow = [] } = {}) {
else if (m.type.body && m.type.body.size < 16 && !mobile) add('WARN', 'body-size', `Body text is ${m.type.body.size}px.`, 'Body copy 16–20px.');
if (m.type.body?.contrast && m.type.body.contrast < 7) add('WARN', 'grey-body', `The running text is a soft grey on its ground (${m.type.body.contrast}:1).`, 'Set body copy in the full ink (7:1 or more). Keep the muted ink for secondary notes; pages read thin and unfinished when everything is grey.');
if (m.buttons.inHero === 0) add('WARN', 'first-action', `No visible button in the first ${mobile ? 'phone ' : ''}screen.`, mobile ? 'On a phone the first screen still holds the headline, the supporting sentence and the action; move navigation into one row or a menu so it does not push them down.' : 'Give the one primary action a real button in the first screen (a filled or solid-bordered control, 44px or taller), not only a link in the navigation.');
+ // Models skip pictures when nothing makes them: the page must carry real ones (see SKILL.md, imagery).
+ if (width >= 1100 && m.page.realPictures != null) {
+ const pics = m.page.realPictures + m.page.uiPictures;
+ if (pics < 4) add('FAIL', 'few-pictures', `Only ${pics} picture(s) on the page (${m.page.realPictures} photographs, footage or raster images, ${m.page.uiPictures} interface fragments). Drawings in SVG do not count.`, 'Find real pictures of the subject\'s world with scripts/assets.mjs (photographs, archival images, maps, engravings, footage), download them to assets/ and give them room: a hero picture, one per section that has a subject, a full-width band. At least four, usually six to twelve.');
+ else if (m.page.realPictures < 2) add('WARN', 'no-real-pictures', `Only ${m.page.realPictures} real photograph(s) or clip(s); the rest are interface fragments.`, 'Add two or more real pictures of the customer\'s world from scripts/assets.mjs, not stock of people at laptops.');
+ if (!m.page.videoCount) add('WARN', 'no-footage', 'No video anywhere on the page.', 'Look for one honest clip with scripts/assets.mjs --video (the place, the material, the process) and use it as a muted loop with a poster frame. Defend its absence only if no clip fits the subject.');
+ }
if (m.page.sideScrollers) add('WARN', 'side-scroll', `${m.page.sideScrollers} row(s) scroll sideways with content past their edge.`, 'Jurors and most visitors read a row cut at the edge as clipped, not as scrollable. Wrap it onto more lines, or end it inside the grid.');
if (m.page.blendText) add('WARN', 'blend-text', `${m.page.blendText} text element(s) use mix-blend-mode difference or exclusion.`, 'Over anything but black, white or grey, blended text takes random hues (blue on orange, lilac on green) that jurors read as a glitch. Use a solid ink chosen for the ground, or keep the blended text over neutral grounds only.');
if (m.type.measureChars && m.type.measureChars > 88 && !mobile) add('WARN', 'measure', `Longest paragraph runs about ${m.type.measureChars} characters per line.`, 'Cap paragraphs at 45–75 characters (max-width: 60ch).');
@@ -127,4 +134,4 @@ export function judge(m, { width = m.viewport.w, allow = [] } = {}) {
return out;
}
-export const RULE_IDS = ['headline-lines', 'statement-length', 'focal-point', 'hero-words', 'mixed-font-headline', 'eyebrow', 'mono', 'numbering', 'micro-label', 'emoji', 'gradient', 'gradient-text', 'shadow', 'text-shadow', 'button-fx', 'hairline', 'outlined-box', 'dashed', 'glass', 'icon-cards', 'card-rows', 'pill-nav', 'palette-claude', 'palette-terracotta', 'palette-cream', 'palette-purple', 'default-link', 'contrast', 'font-count', 'font-fallback', 'size-count', 'body-size', 'measure', 'small-text', 'all-centred', 'ui-wrapper', 'overflow', 'broken-image', 'no-hero', 'first-action', 'grey-body', 'blend-text', 'covered-text', 'clipped-text', 'pinned-over-picture', 'empty-screens', 'long-pin', 'side-scroll'];
+export const RULE_IDS = ['headline-lines', 'statement-length', 'focal-point', 'hero-words', 'mixed-font-headline', 'eyebrow', 'mono', 'numbering', 'micro-label', 'emoji', 'gradient', 'gradient-text', 'shadow', 'text-shadow', 'button-fx', 'hairline', 'outlined-box', 'dashed', 'glass', 'icon-cards', 'card-rows', 'pill-nav', 'palette-claude', 'palette-terracotta', 'palette-cream', 'palette-purple', 'default-link', 'contrast', 'font-count', 'font-fallback', 'size-count', 'body-size', 'measure', 'small-text', 'all-centred', 'ui-wrapper', 'overflow', 'broken-image', 'no-hero', 'first-action', 'grey-body', 'blend-text', 'covered-text', 'clipped-text', 'pinned-over-picture', 'empty-screens', 'long-pin', 'side-scroll', 'few-pictures', 'no-real-pictures', 'no-footage', 'still-page'];