-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.ts
More file actions
323 lines (291 loc) · 10.2 KB
/
Copy pathscript.ts
File metadata and controls
323 lines (291 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
import { complete } from './llm'
import { extractJson } from './json'
import { systemPrompt, userPrompt } from './prompts'
import { defaultTrackForMood } from './music'
import { filmSeedFromName } from './film'
import { clamp, shortId } from './utils'
import {
VIDEO_FPS,
type DemoBrief,
type LlmConfig,
type Scene,
type SceneType,
type VideoScript,
} from './types'
/**
* Turning a brief into a scene-by-scene script.
*
* Two ways to get one, and which you used is never hidden from you:
*
* writeScript() — your model writes it.
* buildOutline() — a deterministic outline built from the brief, no model.
*
* The version this grew from had the same pair, but `generateScript` caught
* any model failure, logged it to a server console nobody reads, and returned
* the template as though the model had written it. You got a worse script and
* no way to know. Here the failure is returned to the caller and the outline
* is something you pick on purpose.
*
* Scene *durations* are computed here in either case, never by the model.
* Asking a language model for frame counts produces a film that is 8 seconds
* or 4 minutes long depending on its mood.
*/
// ---------------------------------------------------------------------------
// Timing
// ---------------------------------------------------------------------------
const WORDS_PER_SECOND = 2.6 // measured against the ElevenLabs default voice
const MIN_SCENE_SECONDS = 2.2
const MAX_SCENE_SECONDS = 7
const BASE_SECONDS: Record<SceneType, number> = {
intro: 3,
problem: 3.2,
feature: 4,
stat: 3,
testimonial: 4,
cta: 3.2,
outro: 2.8,
}
export function durationFor(voiceover: string | undefined, type: SceneType): number {
const words = voiceover ? voiceover.trim().split(/\s+/).filter(Boolean).length : 0
const spoken = words / WORDS_PER_SECOND
const seconds = clamp(
Math.max(BASE_SECONDS[type], spoken + 0.8),
MIN_SCENE_SECONDS,
MAX_SCENE_SECONDS,
)
return Math.round(seconds * VIDEO_FPS)
}
/** Scale every scene proportionally so the total lands near the target length. */
export function fitToTarget(scenes: Scene[], targetSeconds: number): Scene[] {
const total = scenes.reduce((n, s) => n + s.durationInFrames, 0)
if (total === 0) return scenes
// Bounded so a wildly over- or under-written script bends toward the target
// without collapsing scenes into subliminal flashes.
const factor = clamp((targetSeconds * VIDEO_FPS) / total, 0.6, 1.6)
return scenes.map((s) => ({
...s,
durationInFrames: Math.max(
Math.round(s.durationInFrames * factor),
Math.round(MIN_SCENE_SECONDS * VIDEO_FPS),
),
}))
}
function assemble(brief: DemoBrief, scenes: Scene[]): VideoScript {
const fitted = fitToTarget(scenes, brief.targetDurationSeconds)
return {
productName: brief.productName,
tagline: brief.tagline || scenes.find((s) => s.type === 'intro')?.subheading || '',
themeId: brief.themeId,
aspectRatio: '16:9',
music: brief.music,
scenes: fitted,
fps: VIDEO_FPS,
totalDurationInFrames: fitted.reduce((n, s) => n + s.durationInFrames, 0),
// The seed is derived from the product name, so regenerating a script for
// the same product lays the film out the same way.
film: { mode: 'flow', bpm: 118, seed: filmSeedFromName(brief.productName) },
}
}
/** Fill in a music track if the brief only chose a mood. */
function withResolvedMusic(brief: DemoBrief): DemoBrief {
if (brief.music.trackId) return brief
return {
...brief,
music: {
...brief.music,
trackId: defaultTrackForMood(brief.music.mood)?.id ?? null,
},
}
}
// ---------------------------------------------------------------------------
// The outline — no model involved
// ---------------------------------------------------------------------------
/**
* A complete, usable script assembled from the brief alone.
*
* This exists so flowy renders a real film on a machine with no model
* configured at all, and so there is something to diff a model's output
* against. It is not a teaser for a paid tier.
*/
export function buildOutline(brief: DemoBrief, screenshotAssetIds: string[]): VideoScript {
const resolved = withResolvedMusic(brief)
const features = resolved.features.filter(Boolean).slice(0, 4)
const audience = resolved.audience?.trim() || 'modern teams'
const scenes: Scene[] = []
scenes.push({
id: shortId('sc'),
type: 'intro',
durationInFrames: 0,
heading: resolved.productName,
subheading: resolved.tagline || `Built for ${audience}.`,
voiceover: `Meet ${resolved.productName}. ${
resolved.tagline || `The ${audience} way to get more done.`
}`,
})
scenes.push({
id: shortId('sc'),
type: 'problem',
durationInFrames: 0,
heading: 'The old way is broken',
subheading:
resolved.description.split('.')[0]?.trim() || 'Too many tools. Too little time.',
voiceover: `${audience} lose hours a week to tools that fight them. There is a better way.`,
})
if (features.length === 0) {
scenes.push({
id: shortId('sc'),
type: 'feature',
durationInFrames: 0,
heading: 'Everything in one place',
subheading: resolved.description.slice(0, 90) || 'One clean, fast workspace.',
screenshotAssetId: screenshotAssetIds[0] ?? null,
voiceover: `${resolved.productName} brings your whole workflow into one place.`,
})
} else {
features.forEach((feature, i) => {
const [title, ...rest] = feature.split(/[:\-–—]/)
const detail = rest.join(' ').trim()
scenes.push({
id: shortId('sc'),
type: 'feature',
durationInFrames: 0,
heading: title.trim(),
subheading: detail || 'Everything you need, in one place.',
screenshotAssetId: screenshotAssetIds[i % Math.max(screenshotAssetIds.length, 1)] ?? null,
voiceover: `${title.trim()} — ${detail || 'so you can move faster'}.`,
})
})
}
scenes.push({
id: shortId('sc'),
type: 'cta',
durationInFrames: 0,
heading: `Try ${resolved.productName}`,
subheading: 'Get started today.',
voiceover: `Ready to see it for yourself? Start with ${resolved.productName} today.`,
})
scenes.push({
id: shortId('sc'),
type: 'outro',
durationInFrames: 0,
heading: resolved.productName,
subheading: resolved.tagline || '',
voiceover: '',
})
return assemble(
resolved,
scenes.map((s) => ({ ...s, durationInFrames: durationFor(s.voiceover, s.type) })),
)
}
// ---------------------------------------------------------------------------
// The model path
// ---------------------------------------------------------------------------
interface RawScene {
type?: unknown
heading?: unknown
subheading?: unknown
statValue?: unknown
statLabel?: unknown
quoteText?: unknown
quoteAuthor?: unknown
voiceover?: unknown
screenshotIndex?: unknown
}
const VALID_TYPES = new Set<SceneType>([
'intro',
'problem',
'feature',
'stat',
'testimonial',
'cta',
'outro',
])
function str(value: unknown): string | undefined {
return typeof value === 'string' && value.trim() ? value.trim() : undefined
}
/**
* Turn whatever the model returned into scenes, discarding what cannot be
* used rather than letting it through to the renderer.
*
* A 7B model will occasionally emit `"type": "features"` or a scene with no
* voiceover at all. Both used to reach the composition, where an unknown type
* renders as an empty stage — a silent black gap in the middle of the film
* with nothing in any log to explain it.
*/
export function scenesFromModel(
raw: RawScene[],
screenshotAssetIds: string[],
): Scene[] {
let nextShot = 0
return raw.flatMap((s): Scene[] => {
const type = str(s.type) as SceneType | undefined
if (!type || !VALID_TYPES.has(type)) return []
const voiceover = str(s.voiceover) ?? ''
const heading = str(s.heading)
const statValue = str(s.statValue)
const quoteText = str(s.quoteText)
// A scene with nothing to say and nothing to show is a gap, not a scene.
if (!voiceover && !heading && !statValue && !quoteText) return []
let screenshotAssetId: string | null = null
if (type === 'feature' && screenshotAssetIds.length > 0) {
const index = s.screenshotIndex
screenshotAssetId =
typeof index === 'number' && Number.isInteger(index)
? screenshotAssetIds[index] ?? screenshotAssetIds[0] ?? null
: // No index given — take the next unused upload, so a model that
// ignores the field does not leave every screenshot on the floor
// in favour of a generated placeholder board.
screenshotAssetIds[nextShot++] ?? null
}
return [
{
id: shortId('sc'),
type,
durationInFrames: durationFor(voiceover, type),
heading,
subheading: str(s.subheading),
stat: statValue ? { value: statValue, label: str(s.statLabel) ?? '' } : undefined,
quote: quoteText
? { text: quoteText, author: str(s.quoteAuthor) ?? '' }
: undefined,
screenshotAssetId,
voiceover,
},
]
})
}
export class EmptyScriptError extends Error {
constructor(model: string) {
super(
`${model} replied, but none of its scenes were usable. ` +
`Try a larger model, or use the built-in outline.`,
)
this.name = 'EmptyScriptError'
}
}
/**
* Ask the model for a script. Throws on failure — the caller shows the reason.
*/
export async function writeScript(
brief: DemoBrief,
screenshotAssetIds: string[],
cfg: LlmConfig,
): Promise<VideoScript> {
const resolved = withResolvedMusic(brief)
const text = await complete(
[
{ role: 'system', content: systemPrompt() },
{ role: 'user', content: userPrompt(resolved, screenshotAssetIds.length) },
],
cfg,
{ temperature: 0.7, maxTokens: 4000 },
)
const parsed = extractJson<{ tagline?: unknown; scenes?: unknown }>(text)
const rawScenes = Array.isArray(parsed?.scenes) ? (parsed.scenes as RawScene[]) : []
const scenes = scenesFromModel(rawScenes, screenshotAssetIds)
if (scenes.length === 0) throw new EmptyScriptError(cfg.model)
return assemble(
{ ...resolved, tagline: str(parsed?.tagline) ?? resolved.tagline },
scenes,
)
}