Skip to content

Commit a689c6a

Browse files
authored
Merge pull request #18 from soniasriv/add-automotive-inventory-videos
Add automotive-inventory-videos example
2 parents 0855b5f + e7209f7 commit a689c6a

10 files changed

Lines changed: 493 additions & 0 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ Clone this repository, or open the directory of the example you want. Each examp
77
## Examples
88

99
- [agency-client-social-videos](examples/agency-client-social-videos) renders one short vertical video per agency client from that client's own photos and video clips, ending on a card in the client's brand color. The Edit JSON is built in code, one clip per media item.
10+
- [automotive-inventory-videos](examples/automotive-inventory-videos) renders one vertical video per vehicle in a dealer inventory from a JSON feed: the photos in sequence with a pan or zoom on each, and an animated specification card. The Edit JSON is built in code, one clip per photo.
1011
- [bulk-csv-videos](examples/bulk-csv-videos) renders one video per row of a CSV from a single template with merge fields, tracked in a resumable manifest, with an optional AI step where Claude writes each row's headline and image prompt. Companion code for [Generate videos in bulk with an API and an AI agent](https://shotstack.io/learn/bulk-create-videos-from-csv-and-ai/).
1112
- [elevenlabs-voiceover-video](examples/elevenlabs-voiceover-video) narrates a video in an ElevenLabs voice, cloned from your own sample if you want, uploads the audio through the Ingest API and renders a captioned video.
1213
- [first-render](examples/first-render) the very basics: submit an Edit, poll the render status, and print the output URL, in Node.js and Python. Start here if you are new to the API. Companion code for [Render your first video with the Shotstack API](https://shotstack.io/learn/render-your-first-video-shotstack-api/).
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
# Your Shotstack sandbox API key: https://dashboard.shotstack.io/register
2+
SHOTSTACK_API_KEY=
3+
4+
# Optional. stage (sandbox, default) or v1 (production). Use the key from the same environment.
5+
# Both keys are in the dashboard under API Keys: https://dashboard.shotstack.io/
6+
SHOTSTACK_ENV=
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
.env
2+
renders.jsonl
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
# Automotive inventory videos
2+
3+
Render one vertical video for each vehicle in a dealer inventory. Each vehicle record has a stock
4+
id, specifications, a price and a list of photos. The script builds the Edit JSON in code, with
5+
one clip for each photo, so the video is as long as the vehicle has photos. You get one
6+
1080 x 1920 MP4 per vehicle, and a file that records which render belongs to which stock id.
7+
8+
## Requirements
9+
10+
- A [Shotstack account](https://dashboard.shotstack.io/register) and your **sandbox** API key
11+
- Node.js 20 or later
12+
13+
Sandbox renders are watermarked. Your account needs at least one credit to use the sandbox.
14+
15+
## Setup
16+
17+
```bash
18+
git clone https://github.com/shotstack/shotstack-cookbook.git
19+
cd shotstack-cookbook/examples/automotive-inventory-videos
20+
```
21+
22+
Copy the environment file. Add your sandbox key to `.env`.
23+
24+
```bash
25+
cp .env.example .env
26+
```
27+
28+
Load the file into your shell. Do this in each new terminal:
29+
30+
```bash
31+
set -a
32+
source .env
33+
set +a
34+
```
35+
36+
## Run
37+
38+
Submit one render per vehicle:
39+
40+
```bash
41+
node render.mjs
42+
```
43+
44+
Then check them:
45+
46+
```bash
47+
node status.mjs
48+
```
49+
50+
Run `status.mjs` again until each render shows `done`.
51+
52+
## What happens
53+
54+
`render.mjs` reads `vehicles.json` and checks that each vehicle has every field and at least one
55+
photo. It reports every problem it finds, then stops. For each vehicle it builds an Edit JSON and
56+
submits one render. The video shows the photos in sequence, 3.2 seconds each, cropped to fill the
57+
vertical frame. Each photo dissolves into the next, and the pan or zoom changes from one photo to the next. A
58+
vehicle with one or two photos gets at least six seconds. A card with the year, make, model, trim,
59+
price, odometer, transmission and fuel type slides in at the bottom. The dealer name is at the
60+
top. A music track plays under the whole video. The script appends one line per render to
61+
`renders.jsonl` and ends with the count of submitted renders.
62+
63+
`status.mjs` reads `renders.jsonl` and checks each render once. A `done` render prints its video
64+
URL.
65+
66+
The card and the dealer name are `html5` assets. The script writes the vehicle data into their
67+
HTML before the render. The sample has one vehicle. Add a record to `vehicles.json` for each vehicle you want to render.
68+
Photo URLs must be public HTTPS URLs. To change the layout, edit `edit.mjs`.
69+
70+
`renders.jsonl` only appends. Delete the file to start a new batch.
71+
72+
To render in production, set `SHOTSTACK_ENV=v1` and put your production key in `.env`.
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
const API_KEY = process.env.SHOTSTACK_API_KEY;
2+
const ENV = process.env.SHOTSTACK_ENV || 'stage';
3+
const API = `https://api.shotstack.io/edit/${ENV}`;
4+
const TIMEOUT_MS = 30_000;
5+
6+
export function fail(message) {
7+
console.error(message);
8+
process.exit(1);
9+
}
10+
11+
export function requireConfig() {
12+
if (!API_KEY) {
13+
fail('Set SHOTSTACK_API_KEY before you run this script.');
14+
}
15+
16+
if (!['stage', 'v1'].includes(ENV)) {
17+
fail('SHOTSTACK_ENV must be stage or v1.');
18+
}
19+
}
20+
21+
// A rejected key or a dead network fails every record the same way. The
22+
// caller stops the batch at the first one instead of printing a line per record.
23+
function stopBatch(message) {
24+
return Object.assign(new Error(message), { fatal: true });
25+
}
26+
27+
async function apiError(response) {
28+
const text = await response.text();
29+
30+
try {
31+
const body = JSON.parse(text);
32+
return (
33+
body.errors?.[0]?.detail ?? body.response?.error ?? body.message ?? text
34+
);
35+
} catch {
36+
return text;
37+
}
38+
}
39+
40+
async function request(path, options, label) {
41+
let response;
42+
43+
try {
44+
response = await fetch(`${API}${path}`, {
45+
...options,
46+
headers: {
47+
Accept: 'application/json',
48+
'Content-Type': 'application/json',
49+
'x-api-key': API_KEY
50+
},
51+
signal: AbortSignal.timeout(TIMEOUT_MS)
52+
});
53+
} catch {
54+
throw stopBatch(
55+
`${label}: the network request failed. Check your connection and run again.`
56+
);
57+
}
58+
59+
if (response.status === 401 || response.status === 403) {
60+
throw stopBatch(
61+
`${label}: the API rejected the key (${response.status}). Check SHOTSTACK_API_KEY and SHOTSTACK_ENV.`
62+
);
63+
}
64+
65+
if (!response.ok) {
66+
throw new Error(`${label}: ${response.status} ${await apiError(response)}`);
67+
}
68+
69+
return (await response.json()).response;
70+
}
71+
72+
export async function submitRender(edit, label) {
73+
const { id } = await request(
74+
'/render',
75+
{ method: 'POST', body: JSON.stringify(edit) },
76+
label
77+
);
78+
79+
if (!id) {
80+
throw new Error(`${label}: the render response did not contain an id.`);
81+
}
82+
83+
return id;
84+
}
85+
86+
export function getRender(renderId, label) {
87+
return request(`/render/${renderId}`, { method: 'GET' }, label);
88+
}
Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
const MUSIC_URL =
2+
'https://shotstack-assets.s3.amazonaws.com/music/unminus/ambition.mp3';
3+
const SECONDS_PER_PHOTO = 3.2;
4+
const MIN_LENGTH = 6;
5+
const EFFECTS = ['zoomIn', 'slideUp', 'zoomOut', 'slideDown'];
6+
7+
const escapeHtml = value =>
8+
String(value).replace(
9+
/[&<>"']/g,
10+
character =>
11+
({
12+
'&': '&amp;',
13+
'<': '&lt;',
14+
'>': '&gt;',
15+
'"': '&quot;',
16+
"'": '&#39;'
17+
})[character]
18+
);
19+
20+
// The specification card is an html5 asset. The vehicle data is written into
21+
// the markup here, so the card can change shape per dealer without a template.
22+
function specCard(vehicle, length) {
23+
const title = escapeHtml(`${vehicle.year} ${vehicle.make} ${vehicle.model}`);
24+
const chips = [vehicle.odometer, vehicle.transmission, vehicle.fuel]
25+
.map(
26+
(text, index) =>
27+
`<span class="chip" id="chip${index}">${escapeHtml(text)}</span>`
28+
)
29+
.join('');
30+
31+
return {
32+
asset: {
33+
type: 'html5',
34+
html: `<div class="card" id="card"><div class="title">${title}</div><div class="trim">${escapeHtml(vehicle.trim)}</div><div class="price">${escapeHtml(vehicle.price)}</div><div class="row">${chips}</div></div>`,
35+
css: 'html,body{margin:0;padding:0;width:960px;height:420px;overflow:hidden;background:transparent;font-family:system-ui,sans-serif}.card{box-sizing:border-box;width:960px;height:420px;padding:40px 48px;background:rgba(10,15,30,0.86);border-radius:32px;color:#fff;opacity:0;transform:translateY(24px)}.title{font-size:60px;font-weight:800;letter-spacing:-1px;line-height:1.05}.trim{margin-top:10px;font-size:34px;color:#cbd5e1}.price{margin-top:22px;font-size:72px;font-weight:800;color:#facc15;line-height:1}.row{display:flex;gap:14px;margin-top:26px}.chip{font-size:28px;padding:10px 20px;border-radius:999px;background:rgba(255,255,255,0.14);color:#e2e8f0;white-space:nowrap;opacity:0;transform:translateY(12px)}',
36+
js: "const tl=gsap.timeline();tl.to('#card',{opacity:1,y:0,duration:0.6,ease:'power3.out'},0).to(['#chip0','#chip1','#chip2'],{opacity:1,y:0,duration:0.6,ease:'power3.out',stagger:0.13},0.3);"
37+
},
38+
start: 0.5,
39+
length: length - 0.5,
40+
width: 960,
41+
height: 420,
42+
position: 'bottom',
43+
offset: { y: 0.05 }
44+
};
45+
}
46+
47+
function dealerBadge(vehicle, length) {
48+
return {
49+
asset: {
50+
type: 'html5',
51+
html: `<div class="badge">${escapeHtml(vehicle.dealer)}</div>`,
52+
css: 'html,body{margin:0;padding:0;width:960px;height:110px;overflow:hidden;background:transparent;font-family:system-ui,sans-serif}.badge{box-sizing:border-box;display:inline-block;height:110px;line-height:110px;padding:0 44px;border-radius:55px;background:rgba(10,15,30,0.7);color:#fff;font-size:42px;font-weight:700}'
53+
},
54+
start: 0,
55+
length,
56+
width: 960,
57+
height: 110,
58+
position: 'top',
59+
offset: { y: -0.04 }
60+
};
61+
}
62+
63+
// One clip per photo, alternating between two tracks so each photo
64+
// dissolves into the next instead of dipping to black. An odd photo sits on
65+
// the upper track: it fades in over the photo below, then fades out to reveal
66+
// the next photo, which already plays underneath. OVERLAP matches the length
67+
// of the fade transition.
68+
const OVERLAP = 1;
69+
70+
function photoClips(photos, secondsPerPhoto) {
71+
const upper = [];
72+
const lower = [];
73+
74+
photos.forEach((src, index) => {
75+
const isLast = index === photos.length - 1;
76+
const clip = {
77+
asset: { type: 'image', src },
78+
start: index * secondsPerPhoto,
79+
length: secondsPerPhoto + (isLast ? 0 : OVERLAP),
80+
fit: 'crop',
81+
effect: EFFECTS[index % EFFECTS.length]
82+
};
83+
84+
if (index % 2 === 1) {
85+
clip.transition = isLast ? { in: 'fade' } : { in: 'fade', out: 'fade' };
86+
upper.push(clip);
87+
} else {
88+
if (index === 0) clip.transition = { in: 'fade' };
89+
lower.push(clip);
90+
}
91+
});
92+
93+
return { upper, lower };
94+
}
95+
96+
export function buildEdit(vehicle) {
97+
// A vehicle with one photo still gets a video long enough to read the card.
98+
const secondsPerPhoto = Math.max(
99+
SECONDS_PER_PHOTO,
100+
MIN_LENGTH / vehicle.photos.length
101+
);
102+
const length = secondsPerPhoto * vehicle.photos.length;
103+
const photos = photoClips(vehicle.photos, secondsPerPhoto);
104+
105+
return {
106+
timeline: {
107+
background: '#000000',
108+
tracks: [
109+
{ clips: [specCard(vehicle, length)] },
110+
{ clips: [dealerBadge(vehicle, length)] },
111+
{ clips: photos.upper },
112+
{ clips: photos.lower },
113+
{
114+
clips: [
115+
{
116+
asset: {
117+
type: 'audio',
118+
src: MUSIC_URL,
119+
volume: 0.3,
120+
effect: 'fadeOut'
121+
},
122+
start: 0,
123+
length: 'end'
124+
}
125+
]
126+
}
127+
]
128+
},
129+
output: { format: 'mp4', size: { width: 1080, height: 1920 } }
130+
};
131+
}
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
import { readFile } from 'node:fs/promises';
2+
import { fail, requireConfig, submitRender } from './api.mjs';
3+
import { buildEdit } from './edit.mjs';
4+
import { recordRender } from './renders.mjs';
5+
6+
const REQUIRED_FIELDS = [
7+
'stockId',
8+
'year',
9+
'make',
10+
'model',
11+
'trim',
12+
'price',
13+
'odometer',
14+
'transmission',
15+
'fuel',
16+
'dealer'
17+
];
18+
19+
requireConfig();
20+
21+
let vehicles;
22+
23+
try {
24+
vehicles = JSON.parse(
25+
await readFile(new URL('./vehicles.json', import.meta.url), 'utf8')
26+
);
27+
} catch (error) {
28+
fail(`Could not read vehicles.json: ${error.message}`);
29+
}
30+
31+
if (!Array.isArray(vehicles) || vehicles.length === 0) {
32+
fail('vehicles.json must contain an array with at least one vehicle.');
33+
}
34+
35+
const problems = [];
36+
37+
vehicles.forEach((vehicle, index) => {
38+
const label = vehicle.stockId ?? `vehicle ${index + 1}`;
39+
40+
for (const field of REQUIRED_FIELDS) {
41+
if (vehicle[field] === undefined || vehicle[field] === '') {
42+
problems.push(`${label}: ${field} is required.`);
43+
}
44+
}
45+
46+
if (!Array.isArray(vehicle.photos) || vehicle.photos.length === 0) {
47+
problems.push(`${label}: photos must contain at least one HTTPS URL.`);
48+
return;
49+
}
50+
51+
for (const photo of vehicle.photos) {
52+
if (!/^https:\/\//.test(photo)) {
53+
problems.push(`${label}: photo ${photo} must be an HTTPS URL.`);
54+
}
55+
}
56+
});
57+
58+
if (problems.length > 0) {
59+
fail(problems.join('\n'));
60+
}
61+
62+
let submitted = 0;
63+
64+
for (const vehicle of vehicles) {
65+
try {
66+
const edit = buildEdit(vehicle);
67+
const renderId = await submitRender(edit, vehicle.stockId);
68+
69+
await recordRender({
70+
renderId,
71+
stockId: vehicle.stockId,
72+
submittedAt: new Date().toISOString()
73+
});
74+
75+
console.log(`${vehicle.stockId} → ${renderId}`);
76+
submitted += 1;
77+
} catch (error) {
78+
if (error.fatal) {
79+
fail(error.message);
80+
}
81+
82+
console.error(error.message);
83+
process.exitCode = 1;
84+
}
85+
}
86+
87+
console.log(`${submitted}/${vehicles.length} submitted`);

0 commit comments

Comments
 (0)