From dd0dcbc271c3ec3e8e9da7c07e87e6ea167fb3b4 Mon Sep 17 00:00:00 2001 From: Clipcat-ai Date: Thu, 3 Dec 2026 00:24:58 +0000 Subject: [PATCH 1/9] feat(video): a crop of the user's product picture may be the picture that is sent, and every picture is looked at for a face popost video product crop records who looked at a product picture and found no person's face in it (--no-face-confirmed agent|user), and with --box makes a crop of the user's picture the picture that is sent; the original stays beside it with its hash. A picture nobody looked at is an error of the sheet, so nothing that shows the product is priced, uploaded or made before that. Replaces the rule that only the user's unchanged file may be a product picture. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Clipcat-ai --- skills/popost/src/video/commands/product.ts | 79 +++++++++++++++++-- skills/popost/src/video/product/sheet.ts | 50 ++++++++++-- skills/popost/tests/video/product-fixtures.ts | 5 +- .../popost/tests/video/product-review.test.ts | 30 ++++++- .../popost/tests/video/product-sheet.test.ts | 39 +++++++-- 5 files changed, 181 insertions(+), 22 deletions(-) diff --git a/skills/popost/src/video/commands/product.ts b/skills/popost/src/video/commands/product.ts index 4e1ac85..f62fbf3 100644 --- a/skills/popost/src/video/commands/product.ts +++ b/skills/popost/src/video/commands/product.ts @@ -1,6 +1,7 @@ /** * `popost video product`: the user's product in a selling video. init copies the pictures the user gave into the - * project, byte for byte, and writes the skeleton of the product sheet (production/product.json); check validates + * project, byte for byte, and writes the skeleton of the product sheet (production/product.json); crop records who + * looked at a picture for a person's face and, with --box, makes a crop of it the picture that is sent; check validates * the sheet, prints the product block every request that shows the product is sent with, the one line of inferred * facts the user confirms, and how the product check of the made files stands (--deliver: what still stands between * the project and its delivery); confirm records the user's answer; sheet puts the user's picture beside frames of a @@ -16,7 +17,8 @@ import { error } from '../project/check-common'; import type { Problem } from '../types'; import { receiptFile, type ProductReceipt, type ReferenceLimits } from '../product/requests'; import { ASPECTS, buildCheckSheets, deliveryProblems, recordVerdict, reviewStatus } from '../product/review'; -import { confirmationOf, confirmLine, FACT_HELP, inferredFacts, inferredHash, PRODUCT_DIR, PRODUCT_FILE, productBlock, readProductSheet, skeleton, type Product, type ProductPicture, type ProductSheet } from '../product/sheet'; +import { runFfmpeg, runFfmpegOk } from '../media/ffmpeg'; +import { confirmationOf, confirmLine, FACE_FIX, FACT_HELP, inferredFacts, inferredHash, PRODUCT_DIR, PRODUCT_FILE, productBlock, readProductSheet, skeleton, type Product, type ProductPicture, type ProductSheet } from '../product/sheet'; import { platform } from './generate'; import { command, userPath, VideoCommandError, type Commands } from './shared'; @@ -72,11 +74,11 @@ const takePicture = async (rt: Runtime, dir: string, id: string, given: string, }; const init = command( - 'starts the product sheet (production/product.json) from the pictures the user gave: each is copied into the project unchanged and the facts are left to fill in. Run it before any clip or picture is generated whenever the user supplies a product', + 'starts the product sheet (production/product.json) from the pictures the user gave: each is copied into the project unchanged and the facts are left to fill in. Run it before any clip or picture is generated whenever the user supplies a product; then look at every picture and run product crop', { positionals: [PROJECT], options: [ - { flag: '--picture', kind: 'append', required: true, metavar: 'FILE', help: 'a picture of the product as the user gave it; repeat for every picture they gave (all of them go with every clip that shows the product)' }, + { flag: '--picture', kind: 'append', required: true, metavar: 'FILE', help: 'a picture of the product as the user gave it; repeat for every picture they gave (each goes, whole or cropped to the product, with every clip that shows the product)' }, { flag: '--id', metavar: 'ID', default: 'product', help: 'the id requests name the product by ("products": [""]); give each product of a video its own' }, ], }, @@ -97,7 +99,72 @@ const init = command( await writeJson(rt, rt.path.join(dir, PRODUCT_FILE), { version: 1, products: [...sheet.products.filter((p) => p.id !== id), product] }); printJson(rt, { ok: true, sheet: rt.path.join(dir, PRODUCT_FILE), product: id, pictures: pictures.map((p) => p.file), fill: FACT_HELP, - next: 'Open each picture, then fill in every fact of ' + PRODUCT_FILE + ': the user\'s own words first ("from": "user" with "quote"), what they did not say from the picture ("from": "picture") or from how such a product is used ("from": "usage"); "names" (what requests call it) and "constant" (what must be the same in every frame, each said as what is there). Remove "material" or "parts" when the product has none. Then: popost video product check ' + args.req('project'), + look: FACE_FIX, + next: 'Open each picture. First say what you saw of people in it (look): a picture is not sent before that. Then fill in every fact of ' + PRODUCT_FILE + ': the user\'s own words first ("from": "user" with "quote"), what they did not say from the picture ("from": "picture") or from how such a product is used ("from": "usage"); "names" (what requests call it) and "constant" (what must be the same in every frame, each said as what is there). Remove "material" or "parts" when the product has none. Then: popost video product check ' + args.req('project'), + }); + }, + (args) => args.string('project'), +); + +const BOX = /^(\d+),(\d+),(\d+),(\d+)$/; +/** The size of a picture, as ffmpeg reads it. */ +const sizeOf = async (rt: Runtime, file: string): Promise<{ width: number; height: number }> => { + const m = (await runFfmpeg(rt, ['-i', file])).stderr.match(/Video: [^\n]*?, (\d{1,5})x(\d{1,5})[ ,[\n]/); + if (!m) throw new VideoCommandError('The size of ' + file + ' could not be read; is it a picture ffmpeg can open?'); + return { width: Number(m[1]), height: Number(m[2]) }; +}; +/** The smallest side a crop may have: below it a model is shown too little of the product. */ +const MIN_CROP = 64; + +const crop = command( + 'records that someone looked at a product picture and found no person\'s face in the picture that is sent (--no-face-confirmed agent|user); with --box x,y,width,height a crop of the user\'s picture becomes the picture that is sent (the whole product in it, a face, player controls or other things left out) and the original stays beside it with its hash. A picture is sent to no model before this. --box needs ffmpeg', + { + positionals: [PROJECT], + options: [ + { flag: '--picture', required: true, metavar: 'FILE', help: 'the picture, as product init listed it (a path in the project; the original of an earlier crop works too)' }, + { flag: '--id', metavar: 'ID', help: 'the product, when two products list a file of that name' }, + { flag: '--box', metavar: 'X,Y,W,H', help: 'the rectangle of the user\'s original to keep, in its pixels from the top left: it holds the whole product and no face' }, + { flag: '--no-face-confirmed', required: true, choices: ['agent', 'user'], help: 'who looked at the picture that is sent (after the crop) and saw no person\'s face in it: "agent" when you opened it yourself; "user" for the user\'s own answer when you cannot look at pictures' }, + { flag: '--note', metavar: 'TEXT', help: 'what was seen, or the user\'s words' }, + ], + }, + async (args, rt) => { + const dir = userPath(rt, args.req('project')); + const sheet = await rawSheet(rt, dir); + const given = args.req('picture').replace(/\\/g, '/').replace(/^\.\//, ''); + const named = (f: string | undefined): boolean => f !== undefined && (f === given || rt.path.resolve(dir, f) === userPath(rt, args.req('picture'))); + const found = sheet.products.flatMap((p) => (args.string('id') && p.id !== args.string('id') ? [] : p.pictures.flatMap((x, i) => (named(x.file) || named(x.original?.file) ? [{ p, i, x }] : [])))); + if (found.length !== 1) throw new VideoCommandError(found.length ? '"' + given + '" is a picture of several products: say which with --id.' : '"' + given + '" is not a picture of the product sheet. It lists: ' + sheet.products.flatMap((p) => p.pictures.map((x) => x.file)).join(', ') + '.'); + const { p, i, x } = found[0] as (typeof found)[number]; + const by = args.req('no-face-confirmed') === 'user' ? 'user' as const : 'agent' as const; + const note = args.string('note')?.replace(/\s+/g, ' ').trim(); + if (by === 'user' && !note) throw new VideoCommandError('--no-face-confirmed user records the user\'s own answer: give their words with --note.'); + const face = { none: true as const, by, ...(note ? { note } : {}), at: rt.now().toISOString() }; + const box = args.string('box'); + let next: ProductPicture = { ...x, face }; + if (box !== undefined) { + const m = BOX.exec(box.replace(/\s+/g, '')); + if (!m) throw new VideoCommandError('--box is x,y,width,height in pixels of the user\'s picture, such as 120,340,600,900; it is "' + box + '".'); + const [bx, by2, width, height] = m.slice(1).map(Number) as [number, number, number, number]; + const original = x.original ?? { file: x.file, sha256: x.sha256 }; + const from = rt.path.resolve(dir, original.file); + const size = await sizeOf(rt, from); + if (width < MIN_CROP || height < MIN_CROP || bx + width > size.width || by2 + height > size.height) + throw new VideoCommandError('The box ' + box + ' does not fit: the picture is ' + size.width + 'x' + size.height + ', and a crop is at least ' + MIN_CROP + ' pixels on each side and lies inside it. Choose a box that holds the whole product.'); + const file = PRODUCT_DIR + '/' + p.id + '-' + String(i + 1).padStart(2, '0') + '.crop.png'; + await rt.fs.mkdir(rt.path.join(dir, PRODUCT_DIR)); + await runFfmpegOk(rt, ['-y', '-loglevel', 'error', '-i', from, '-vf', 'crop=' + width + ':' + height + ':' + bx + ':' + by2 + ':exact=1', '-frames:v', '1', rt.path.join(dir, file)]); + next = { ...(x.also ? { also: x.also } : {}), file, sha256: sha256(await rt.fs.readFile(rt.path.join(dir, file))), original, crop: { x: bx, y: by2, width, height }, face }; + } + const product: Product = { ...p, pictures: p.pictures.map((old, k) => (k === i ? next : old)) }; + // The picture that is sent changed: what the user confirmed before was about another picture. + const { confirmation: _asked, ...rest } = sheet; + await writeJson(rt, rt.path.join(dir, PRODUCT_FILE), { ...(box !== undefined ? rest : sheet), products: sheet.products.map((old) => (old.id === p.id ? product : old)) }); + printJson(rt, { + ok: true, product: p.id, picture: next.file, ...(next.original ? { original: next.original.file, crop: next.crop } : {}), face: { none: true, by }, + next: box !== undefined + ? 'Open ' + next.file + ': it must show the whole product (nothing of it cut off) and no person\'s face. If it does not, run this again with another --box. The user sees this crop in the input sheet before anything is generated (popost video inputs show).' + : 'Recorded. The user sees this picture in the input sheet before anything is generated (popost video inputs show).', }); }, (args) => args.string('project'), @@ -230,4 +297,4 @@ const review = command( (args) => args.string('project'), ); -export const productCommands: Commands = { init, check, confirm, sheet, review }; +export const productCommands: Commands = { init, crop, check, confirm, sheet, review }; diff --git a/skills/popost/src/video/product/sheet.ts b/skills/popost/src/video/product/sheet.ts index b4427e2..a438eb8 100644 --- a/skills/popost/src/video/product/sheet.ts +++ b/skills/popost/src/video/product/sheet.ts @@ -10,8 +10,12 @@ * inferred: they are shown to the user in one line with the plan and its cost, and paid generation waits for the * answer (confirmation, bound to the inferred facts by a hash: an edited fact is asked about again). * - * The pictures are the files the user gave, byte for byte (sha256 kept): never a crop, a cut-out, a redraw or a - * selection of them. A crop made to look closer is for looking, not a reference. + * A picture is the user's file, byte for byte (sha256 kept), or a crop of it (popost video product crop): the picture + * that is sent is then the crop, and the original stays beside it with its hash. A crop shows the whole product and + * removes what must not be sent with it: above all a person's face (a screenshot of someone holding the product), also + * player controls or other products. It is a plain rectangle of the user's pixels: never a cut-out, a redraw, a + * retouch or a re-compressed copy. No program here can tell a face, so every picture carries who looked ("face"): the + * agent that opened it, or the user when the agent cannot see pictures. A picture nobody looked at is not sent. */ import { sha256 } from '../../core/util'; import { sniffImageMime } from '../../providers/api'; @@ -30,8 +34,20 @@ export const FACT_SOURCES: readonly FactSource[] = ['user', 'picture', 'usage']; /** One fact of the product: what holds, and where it comes from. quote: the user's own words, for from "user". */ export interface Fact { value: string; from: FactSource; quote?: string } -/** A picture of the product as the user gave it. also: what else is in it (a person, a screen), never taken from it. */ -export interface ProductPicture { file: string; sha256: string; also?: string } +/** Who looked at the picture that is sent and found no person's face in it. */ +export interface FaceLook { none: true; by: 'agent' | 'user'; note?: string; at?: string } + +/** + * A picture of the product as it is sent: the user's file, or a crop of it (original: the user's file and its hash; + * crop: the rectangle taken from it, in its pixels). also: what else is in it (a hand, a screen), never taken from it. + * face: who looked and found no person's face in the picture that is sent; without it the picture is not sent. + */ +export interface ProductPicture { + file: string; sha256: string; also?: string; + original?: { file: string; sha256: string }; + crop?: { x: number; y: number; width: number; height: number }; + face?: FaceLook; +} /** A still composed from a real picture (the picture placed on a ground or in a hand, its product pixels unchanged): the first frame of a clip that starts on the product. */ export interface ProductStill { file: string; sha256: string; made: string } @@ -182,10 +198,27 @@ const fileProblems = async (rt: Runtime, dir: string, entry: unknown, at: string if (!bytes) return [error(at + '.file', what + ' "' + entry.file + '" does not exist in the project.', 'Put the file the user gave there (popost video product init --picture copies it), or remove the entry.')]; if (!sniffImageMime(bytes.subarray(0, 16))) return [error(at + '.file', '"' + entry.file + '" is not a real PNG, JPEG or WebP picture.', 'Use the picture file the user gave.')]; if (typeof entry.sha256 !== 'string' || entry.sha256.toLowerCase() !== sha256(bytes)) - return [error(at + '.sha256', what + ' "' + entry.file + '" is not the file that was recorded: its bytes changed, or no hash was written.', 'A product picture is the user\'s file, unchanged: restore it (never crop, cut out, redraw or re-compress it), or run popost video product init again with the user\'s original.')]; + return [error(at + '.sha256', what + ' "' + entry.file + '" is not the file that was recorded: its bytes changed, or no hash was written.', 'A product picture is the user\'s file or a crop made by popost video product crop: restore it (never cut out, redraw, retouch or re-compress it), or run popost video product init again with the user\'s original.')]; return []; }; +export const FACE_FIX = 'Open the picture. No person\'s face in it: popost video product crop --picture --no-face-confirmed agent. A face in it (a screenshot of someone holding the product): popost video product crop --picture --box x,y,width,height --no-face-confirmed agent, with a box that holds the whole product and leaves the face out; a picture in which the two cannot be separated is not used, and the user is asked for another. When you cannot look at pictures, ask the user and record their answer with --no-face-confirmed user.'; + +/** What is wrong with a product picture beyond its file: the original of a crop, and who looked for a face. */ +const pictureProblems = async (rt: Runtime, dir: string, pic: Record, at: string): Promise => { + const out: Problem[] = []; + if (pic.original !== undefined || pic.crop !== undefined) { + const c = pic.crop; + if (!isRecord(pic.original) || !isRecord(c) || !['x', 'y', 'width', 'height'].every((k) => Number.isInteger(c[k]) && (c[k] as number) >= 0)) + out.push(error(at + '.crop', 'A cropped product picture names the user\'s original and the rectangle taken from it.', 'Run popost video product crop --picture --box x,y,width,height; do not write "original" or "crop" by hand.')); + else out.push(...(await fileProblems(rt, dir, pic.original, at + '.original', 'The user\'s original of the cropped picture'))); + } + const f = pic.face; + if (!(isRecord(f) && f.none === true && (f.by === 'agent' || f.by === 'user'))) + out.push(error(at + '.face', 'Nobody has said that the product picture "' + String(pic.file) + '" shows no person\'s face. A picture with a face in it (the user\'s screenshot of someone else, a model in a shop photo) is never sent to a video model, and no program here can tell: someone has to look.', FACE_FIX)); + return out; +}; + const productProblems = async (rt: Runtime, dir: string, p: unknown, at: string): Promise => { if (!isRecord(p)) return [error(at, 'A product is an object with its id, names, pictures and facts.', 'Run popost video product init --picture for the skeleton.')]; const out: Problem[] = []; @@ -194,8 +227,11 @@ const productProblems = async (rt: Runtime, dir: string, p: unknown, at: string) out.push(...lines(p, 'constant', at, 'what must be the same in every frame', 'Write each as what is there: "the long cone tip stays on, uncapped", "the wordmark runs down the front".')); if (Array.isArray(p.constant)) for (const [i, line] of p.constant.entries()) if (typeof line === 'string' && /^\s*(no|not|never|don't|do not|without|不要|不能|禁止)\b/i.test(line)) out.push(warning(at + '.constant[' + i + ']', 'This line says what must not be there ("' + tidy(line) + '"); a model draws what a prompt names.', 'Say what is there instead: not "no pump", but "the tip is a long bare cone".')); - if (!Array.isArray(p.pictures) || !p.pictures.length) out.push(error(at + '.pictures', 'A product has at least one picture: the file(s) the user gave, all of them.', 'Run popost video product init --picture [--picture ...]; without a picture from the user there is no product sheet, and the user is asked for one.')); - else for (const [i, pic] of p.pictures.entries()) out.push(...await fileProblems(rt, dir, pic, at + '.pictures[' + i + ']', 'The product picture')); + if (!Array.isArray(p.pictures) || !p.pictures.length) out.push(error(at + '.pictures', 'A product has at least one picture: the file(s) the user gave, each whole or cropped to the product.', 'Run popost video product init --picture [--picture ...]; without a picture from the user there is no product sheet, and the user is asked for one.')); + else for (const [i, pic] of p.pictures.entries()) { + const found = await fileProblems(rt, dir, pic, at + '.pictures[' + i + ']', 'The product picture'); + out.push(...found, ...(found.length || !isRecord(pic) ? [] : await pictureProblems(rt, dir, pic, at + '.pictures[' + i + ']'))); + } if (p.stills !== undefined) { if (!Array.isArray(p.stills)) out.push(error(at + '.stills', '"stills" lists pictures composed from a real product picture.', 'Write [{ "file": "assets/product/on-desk.png", "sha256": "...", "made": "how it was composed" }], or remove it.')); else for (const [i, still] of p.stills.entries()) { diff --git a/skills/popost/tests/video/product-fixtures.ts b/skills/popost/tests/video/product-fixtures.ts index bb79f6b..d7ecfbf 100644 --- a/skills/popost/tests/video/product-fixtures.ts +++ b/skills/popost/tests/video/product-fixtures.ts @@ -15,12 +15,15 @@ export const FRONT = tinyPng([20, 90, 160]); export const BACK = tinyPng([160, 90, 20]); export const HOST = tinyPng([180, 140, 120]); +/** Someone looked at the picture and saw no person's face in it. */ +export const LOOKED = { none: true, by: 'agent' }; + export const fact = (value: string, from: 'user' | 'picture' | 'usage' = 'picture') => ({ value, from, ...(from === 'user' ? { quote: 'the user said: ' + value } : {}) }); /** A flask, read from two pictures: its capacity is the user's, the rest inferred. */ export const flask = (more: Json = {}): Json => ({ id: 'flask', names: ['Northwind', 'flask', 'bottle'], - pictures: [{ file: 'assets/product/flask-01.png', sha256: sha256(FRONT) }, { file: 'assets/product/flask-02.png', sha256: sha256(BACK) }], + pictures: [{ file: 'assets/product/flask-01.png', sha256: sha256(FRONT), face: LOOKED }, { file: 'assets/product/flask-02.png', sha256: sha256(BACK), face: LOOKED }], constant: ['the screw cap with its steel loop stays on unless it is being opened', 'the wordmark runs down the front'], what: fact('a Northwind 500 ml insulated steel flask', 'user'), label: fact('NORTHWIND 500'), diff --git a/skills/popost/tests/video/product-review.test.ts b/skills/popost/tests/video/product-review.test.ts index e21946a..2bf5ea8 100644 --- a/skills/popost/tests/video/product-review.test.ts +++ b/skills/popost/tests/video/product-review.test.ts @@ -21,7 +21,7 @@ const project = async (name: string): Promise => { const dir = rt.path.join(rt.cwd, name); await rt.fs.writeFile(rt.path.join(dir, 'assets/product/flask-01.png'), PICTURE); await rt.fs.writeFile(rt.path.join(dir, 'production/product.json'), JSON.stringify({ version: 1, products: [{ - id: 'flask', names: ['flask'], pictures: [{ file: 'assets/product/flask-01.png', sha256: sha256(PICTURE) }], constant: ['the cap stays on'], + id: 'flask', names: ['flask'], pictures: [{ file: 'assets/product/flask-01.png', sha256: sha256(PICTURE), face: { none: true, by: 'agent' } }], constant: ['the cap stays on'], what: fact('a steel flask'), label: fact('NORTHWIND'), shape: fact('a straight cylinder'), size: fact('24 cm tall'), sizeAnchor: fact('longer than a hand'), colour: fact('dark blue'), use: fact('unscrew and drink'), quantity: fact('1 flask'), }] })); return dir; @@ -35,6 +35,34 @@ const cli = async (...argv: string[]): Promise<{ code: number; data: Json }> => return { code: r.code, data: JSON.parse(r.stdout) as Json }; }; +describe.skipIf(!ffmpeg)('a crop of the user\'s picture as the picture that is sent', () => { + it('keeps the original with its hash, sends the crop, and refuses a box that does not fit', async () => { + const dir = await project('crop'); + const shot = rt.path.join(dir, 'assets/product/shot.png'); + await runFfmpegOk(rt, ['-y', '-loglevel', 'error', '-f', 'lavfi', '-i', 'testsrc=s=400x300', '-frames:v', '1', shot]); + await rt.fs.writeFile(rt.path.join(dir, 'production/product.json'), JSON.stringify({ version: 1, products: [{ id: 'flask', names: ['flask'], pictures: [{ file: 'assets/product/shot.png', sha256: sha256(await rt.fs.readFile(shot)) }], constant: ['the cap stays on'], + what: fact('a steel flask'), label: fact('NORTHWIND'), shape: fact('a straight cylinder'), size: fact('24 cm tall'), sizeAnchor: fact('longer than a hand'), colour: fact('dark blue'), use: fact('unscrew and drink'), quantity: fact('1 flask') }], confirmation: { by: 'user', quote: 'yes', facts: 'x', at: 'now' } })); + expect((await cli('crop', dir, '--picture', 'assets/product/shot.png', '--box', '300,200,200,200', '--no-face-confirmed', 'agent')).code).toBe(2); + expect((await cli('crop', dir, '--picture', 'assets/product/shot.png', '--box', '0,0,20,20', '--no-face-confirmed', 'agent')).code).toBe(2); + const made = await cli('crop', dir, '--picture', 'assets/product/shot.png', '--box', '100,50,200,220', '--no-face-confirmed', 'agent'); + expect(made.data).toMatchObject({ ok: true, picture: 'assets/product/flask-01.crop.png', original: 'assets/product/shot.png', crop: { x: 100, y: 50, width: 200, height: 220 } }); + const sheet = JSON.parse(await rt.fs.readText(rt.path.join(dir, 'production/product.json'))) as Json; + const picture = sheet.products[0].pictures[0]; + expect(picture.original).toEqual({ file: 'assets/product/shot.png', sha256: sha256(await rt.fs.readFile(shot)) }); + expect(picture.sha256).toBe(sha256(await rt.fs.readFile(rt.path.join(dir, picture.file)))); + expect(await probe(rt, rt.path.join(dir, picture.file))).toMatchObject({ width: 200, height: 220 }); + // The picture that is sent changed, so an earlier answer of the user no longer stands. + expect(sheet.confirmation).toBeUndefined(); + expect((await cli('check', dir)).data.products[0].pictures).toEqual(['assets/product/flask-01.crop.png']); + // Cropping again starts from the user's original, named by either file. + const again = await cli('crop', dir, '--picture', 'assets/product/flask-01.crop.png', '--box', '0,0,400,300', '--no-face-confirmed', 'agent'); + expect(again.data).toMatchObject({ original: 'assets/product/shot.png', crop: { width: 400, height: 300 } }); + // An original that changed is refused like any picture that changed. + await rt.fs.writeFile(shot, PICTURE); + expect(JSON.stringify((await cli('check', dir)).data.problems)).toContain('original of the cropped picture'); + }); +}); + describe('what stands between a project and its delivery', () => { const line = (more: Partial): ReviewLine => ({ file: 'assets/hold.mp4', products: ['flask'], status: 'unchecked', used: true, ...more }); diff --git a/skills/popost/tests/video/product-sheet.test.ts b/skills/popost/tests/video/product-sheet.test.ts index f59d302..63e7653 100644 --- a/skills/popost/tests/video/product-sheet.test.ts +++ b/skills/popost/tests/video/product-sheet.test.ts @@ -7,7 +7,7 @@ import { sha256 } from '../../src/core/util'; import { mentions, withProducts, type ProductRequest } from '../../src/video/product/requests'; import { confirmLine, inferredFacts, productBlock, productBody, readProductSheet, type Product } from '../../src/video/product/sheet'; import { cli, type Json } from '../image-helpers'; -import { BACK, fact, flask, FRONT, messages, P, setup, sheetOf, writeSheet } from './product-fixtures'; +import { BACK, fact, flask, FRONT, LOOKED, messages, P, setup, sheetOf, writeSheet } from './product-fixtures'; describe('the product sheet', () => { it('init copies the user\'s pictures unchanged, writes the skeleton, and check lists every fact still to fill', async () => { @@ -23,23 +23,48 @@ describe('the product sheet', () => { expect(checked.code).toBe(2); const wrong = messages(checked.data).join('\n'); for (const key of ['names', 'constant', 'what.value', 'label.value', 'shape.value', 'size.value', 'sizeAnchor.value', 'colour.value', 'use.value', 'material.value', 'parts.value']) expect(wrong).toContain('products[0].' + key); - expect((checked.data.problems as Json[]).filter((p) => String(p.at).includes('pictures'))).toEqual([]); + // Nobody has looked at the pictures yet: each is refused until someone says there is no face in it. + const unseen = (checked.data.problems as Json[]).filter((p) => String(p.at).includes('pictures')); + expect(unseen.map((p) => p.at)).toEqual(['products[0].pictures[0].face', 'products[0].pictures[1].face']); + expect(unseen[0].message).toContain('never sent to a video model'); + expect(unseen[0].fix).toContain('--box x,y,width,height'); + expect(unseen[0].fix).toContain('ask the user'); + await cli(rt, 'video', 'product', 'crop', '/work/q', '--picture', 'assets/product/flask-01.png', '--no-face-confirmed', 'agent'); + // The user's own answer needs their words. + expect((await cli(rt, 'video', 'product', 'crop', '/work/q', '--picture', 'assets/product/flask-02.png', '--no-face-confirmed', 'user')).code).toBe(2); + await cli(rt, 'video', 'product', 'crop', '/work/q', '--picture', 'assets/product/flask-02.png', '--no-face-confirmed', 'user', '--note', 'no one is in it'); + const looked = await cli(rt, 'video', 'product', 'check', '/work/q'); + expect((looked.data.problems as Json[]).filter((p) => String(p.at).includes('pictures'))).toEqual([]); + const kept = JSON.parse(await rt.fs.readText('/work/q/production/product.json')) as Json; + expect(kept.products[0].pictures[1].face).toMatchObject({ none: true, by: 'user', note: 'no one is in it' }); + }); + + it('a list that shows the product is refused while a picture of it has not been looked at for a face', async () => { + const { rt, stub } = await setup(); + await writeSheet(rt, [flask({ pictures: [{ file: 'assets/product/flask-01.png', sha256: sha256(FRONT) }] })]); + await rt.fs.writeFile(P + '/requests.json', JSON.stringify([{ file: 'assets/hold.mp4', prompt: 'a hand lifts the flask', seconds: 5, cast: [], products: ['flask'] }])); + const before = stub.requests.length; + const paid = await cli(rt, 'video', 'materials', P + '/requests.json', '--out', P, '--confirm', '--max-credits', '100'); + expect(paid.code).toBe(2); + expect(messages(paid.data).join('\n')).toContain('pictures[0].face'); + // Nothing of the picture left the machine: no upload, no quote. + expect(stub.requests.slice(before).filter((r) => r.path.includes('/videos/uploads') || r.path.includes('/videos/quote'))).toEqual([]); }); it('refuses a picture that is missing, changed or outside the project, a user fact without their words, and names two products share', async () => { const { rt } = await setup(); const problemsOf = async (products: Json[]): Promise => { await writeSheet(rt, products); return (await readProductSheet(rt, P)).problems.filter((p) => p.level === 'error').map((p) => p.at + ' ' + p.message).join('\n'); }; expect(await problemsOf([flask()])).toBe(''); - expect(await problemsOf([flask({ pictures: [{ file: 'assets/product/none.png', sha256: sha256(FRONT) }] })])).toContain('does not exist'); - expect(await problemsOf([flask({ pictures: [{ file: '../front.png', sha256: sha256(FRONT) }] })])).toContain('outside the project'); - expect(await problemsOf([flask({ pictures: [{ file: 'assets/product/flask-01.png', sha256: sha256(BACK) }] })])).toContain('its bytes changed'); + expect(await problemsOf([flask({ pictures: [{ file: 'assets/product/none.png', sha256: sha256(FRONT), face: LOOKED }] })])).toContain('does not exist'); + expect(await problemsOf([flask({ pictures: [{ file: '../front.png', sha256: sha256(FRONT), face: LOOKED }] })])).toContain('outside the project'); + expect(await problemsOf([flask({ pictures: [{ file: 'assets/product/flask-01.png', sha256: sha256(BACK), face: LOOKED }] })])).toContain('its bytes changed'); expect(await problemsOf([flask({ pictures: [] })])).toContain('at least one picture'); expect(await problemsOf([flask({ what: { value: 'a flask', from: 'user' } })])).toContain('without their words'); expect(await problemsOf([flask({ size: { value: 'about 24 cm', from: 'picture', quote: 'x' } })])).toContain('carries a quote'); expect(await problemsOf([flask({ quantity: fact('a few') })])).toContain('quantity starts with how many'); expect(await problemsOf([flask({ shape: undefined })])).toContain('products[0].shape'); - const twin = flask({ id: 'flask-red', pictures: [{ file: 'assets/product/flask-02.png', sha256: sha256(BACK) }] }); - const both = await problemsOf([flask({ pictures: [{ file: 'assets/product/flask-01.png', sha256: sha256(FRONT) }] }), twin]); + const twin = flask({ id: 'flask-red', pictures: [{ file: 'assets/product/flask-02.png', sha256: sha256(BACK), face: LOOKED }] }); + const both = await problemsOf([flask({ pictures: [{ file: 'assets/product/flask-01.png', sha256: sha256(FRONT), face: LOOKED }] }), twin]); expect(both).toContain('Two products are called "Northwind"'); await writeSheet(rt, [flask({ size: fact('quite small'), constant: ['no straw'] })]); expect((await readProductSheet(rt, P)).problems.map((p) => p.level + ' ' + p.at)).toEqual(['warning products[0].constant[0]', 'warning products[0].size.value']); From 29cc5cefecb8c409d3e3325ebe6ce80b40221542 Mon Sep 17 00:00:00 2001 From: Clipcat-ai Date: Thu, 3 Dec 2026 00:51:43 +0000 Subject: [PATCH 2/9] feat(link): resolve Reddit share links on the user's machine before submitting A share link (/r//s/, /u//s/) carries no post id and only redirects to the post; the platform's servers can be refused that redirect while the user's machine gets it. link parse and inspiration add now follow it locally (https, reddit.com hosts only, at most 5 hops of 10 s, no cookies) and submit the /comments/ link, printed as resolvedUrl (also by --dry-run). When the walk fails the original link is submitted unchanged and the platform's answer applies. Nothing is charged for resolving, and nothing is requested before the fee is authorized. Behaviour change for the server side: the JSON of link parse / inspiration add gains resolvedUrl; --dry-run of a share link makes the redirect request. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Clipcat-ai --- skills/popost/SOURCE-MANIFEST.sha256 | 6 +- skills/popost/references/post-bundle.md | 4 +- skills/popost/src/providers/link-resolve.ts | 90 ++++++++++++++++ skills/popost/src/providers/link.ts | 24 ++++- skills/popost/tests/link-resolve.test.ts | 109 ++++++++++++++++++++ 5 files changed, 226 insertions(+), 7 deletions(-) create mode 100644 skills/popost/src/providers/link-resolve.ts create mode 100644 skills/popost/tests/link-resolve.test.ts diff --git a/skills/popost/SOURCE-MANIFEST.sha256 b/skills/popost/SOURCE-MANIFEST.sha256 index 9adc1c9..da86ee4 100644 --- a/skills/popost/SOURCE-MANIFEST.sha256 +++ b/skills/popost/SOURCE-MANIFEST.sha256 @@ -588,7 +588,7 @@ cf4147c9b98ed0f136ce8ee1bbbd980db77e1358aeb5b85cacf6fb2d4f097798 references/ima e299b21c239eb401f9eff1116f909d931c8a9743b052b6b65e51afd57aff33f8 references/imagery.md 38439175e90f1e5e85ac47cbbcb72d4df3084d2524a55891a81b06c02a7a53b4 references/onboarding.md d8aa84ab56fd0ff7085e74e05a47298f8b23c321cd752be7bdb871bd00c481f7 references/platform-adaptation.md -0ea04ec878c7929f0fe873613787ed0f7ceb71041b051ffb98086a75d0077577 references/post-bundle.md +fd7a822c72b51144fcea0124211e8feec9b76396b7b71459bbb7732e850f4495 references/post-bundle.md 14a91cb8341c096fdfd5edc0005cc1acdd2787badc8d6267019955a8d8970380 references/project-manifest.md 203a65b53a8391f834acd681971f763e4906e340f1d34b0a7ff9393b3f00489a references/providers.md a7b4b60f6023ef5655b940908b5b4a66142fa693e4e157d5e95f1af40be43f6d references/quality-review.md @@ -740,9 +740,10 @@ ed3aa393cda96bb2235ae5fd9cc3f5a4cf7e06a93bdc6b361d54d79b308ce617 src/providers/ e0acd44e5f8507e73325b409240a5b8a13108be028ec1c8dfb9c82cfc6714a95 src/providers/inspiration.ts 9696d3cffce4e1f3b22e016b52863a0cae28efffdec6900e34a87fd28d131fec src/providers/ledger.ts c32186d2eaa04d68012d42a27af39c57835667664a7995fe576fc1622fc5796c src/providers/link-bundle.ts +bf470886a21872279e996460f4d14ea55e2f2363dd47c6110eb8f11afe5556b6 src/providers/link-resolve.ts 2e7364ead9f9af2afaccce914084b16cf067f80622b46c2a848d947d3698ee8f src/providers/link-task.ts 6ec8ec0780c0d9fab557102522d3fa32720ee4b7a6e724204c8ed7a111ad5dbc src/providers/link-video.ts -f9dea3309e7c669ef81413a7d33811e238476ae63169eee10e8bb78413abdbe8 src/providers/link.ts +37903191d2516081d39c45a02f372ce4d535eb3a5975dabefb8e6f7939420cdd src/providers/link.ts 0dbd7fad49ebdaf462b8eed9f77e73d90f0bf28fbdf42b6df6dcca582a7057a8 src/providers/manual-host.ts 4fac7cd9846ef58768c53be123e4672ca5bd437caf35195b7a37afdd132ae0e8 src/providers/paths.ts d533efd4ea0cd8e4ca9af39cab7206b7d0494932aa50379bb64a2f8a82dfc017 src/providers/popost-async.ts @@ -2106,6 +2107,7 @@ dfcfae410de5bae46e869a03236275f579806975bb19624cc98a06f78c907a7a tests/image-in 9298aee69a4f41406fb4a3a819d90338d78eebe6236a8da6aa41147be2c1bf9d tests/instagram-template-search.test.ts b8e4def0214b4956c2d0b1303b36ae8d7b11a5cf6abe6d3c33438f8d497b9ad1 tests/install.test.ts cf04f003f5d55c2310f90c061fb8f0d8b563217db06fba12c892dcd4b7d3684f tests/link-platforms.test.ts +d2d9d2951e09d33586313aad3dbad087918c1f64552d97ebd741e5b6db69e627 tests/link-resolve.test.ts 3e07be12ec9492c54e04a6ba0db899c9bdb8376406da728933f4ee242ad53045 tests/link.test.ts 1572bab4e564a30537be5073ee5294538899c78935057b5eb7e4597459edc2f2 tests/node-secret.test.ts a3d39e7e688a45bc2be1d75feb1884c8fc0299309b6f9dff423fd3b0d932c3db tests/package.test.ts diff --git a/skills/popost/references/post-bundle.md b/skills/popost/references/post-bundle.md index 0a98ac0..55a22cb 100644 --- a/skills/popost/references/post-bundle.md +++ b/skills/popost/references/post-bundle.md @@ -44,11 +44,13 @@ link parse --confirm --max-credits N [--note "备注"] [--out DIR] [--time link status [--out DIR] [--timeout 900] [--no-download] [--no-video] [--config PRIVATE_CONFIG] ``` +Reddit share links (`/r//s/`) are resolved on the user's machine first: the CLI follows their redirects (free, reddit.com only) and submits the full `/comments/` link, shown as `resolvedUrl` (also by `--dry-run`); if that fails the original link is submitted unchanged. + 1. Run `link quote` (free read-only platform tariff/balance query), show the parsing charge separately from image fees and obtain authorization. `--dry-run` only describes the request locally; it does not query a price. Then submit with `--confirm --max-credits N`. 2. 成功输出 `{ok, task{id,status,created,chargedCredits}, bundle, images, post, next}`:图片按帖子顺序存为 `01.jpg`、`02.webp`…(类型取自文件头),和 `postbundle.json` 一起放在 `--out`(默认 `inputs/link-<任务 id 前 8 位>/`)。bundle 的 `resources[].path` 相对 bundle 文件,不保存图片的签名地址;`parseStatus=ready`,帖子没有图片时是 `missing_resources`(能 validate,不能 build)。`next` 是接着跑的 `validate`、`import`;复刻时再用 `attach-bundle` 登记为工程来源。 视频帖(`post.kind=video`)的图片只有封面;原视频另存为 `video.mp4`(`.mov`、`.webm`,类型取自文件头),输出里是 `video`,bundle 里是 `resources` 中 `kind=video` 的一项(不进 `pageOrder`)。这一步不另扣积分;`--no-video` 跳过。平台给不出视频(YouTube、哔哩哔哩、微信视频号,或平台已不再提供这条视频)、或下载失败时解析照样成功,输出带 `videoMissing{code,error}`(如 `LINK_VIDEO_UNAVAILABLE`):bundle 只有封面和文字,要做视频分析时再请用户提供视频文件或录屏;下载失败可重跑 `link status` 再取。 3. 链接已在用户的灵感库里时直接复用:`task.created=false`、`chargedCredits=0`。平台解析时已把这条帖子存入「我的灵感」,不要再对这个 bundle 跑 `inspiration import`,那会重复保存。 -4. 任务失败输出 `{ok:false, code, error, task}`,退出码 1,The platform attempts a refund; `chargedCredits` is the current net charge. A positive value on a failed task means refund pending, not refunded. Query status to reconcile.常见 code:`LINK_UNSUPPORTED`(不是五平台的帖子链接)、`LINK_POST_NOT_FOUND`(帖子不存在或不公开)、`LINK_PARSE_FAILED`、`LINK_IMAGES_FAILED`、`LINK_PARSE_UNAVAILABLE`。`LINK_UNSUPPORTED`、`INSUFFICIENT_CREDITS`、`RATE_LIMITED` 在建任务前就拒绝,没有任务,也没扣积分。 +4. 任务失败输出 `{ok:false, code, error, task}`,退出码 1,The platform attempts a refund; `chargedCredits` is the current net charge. A positive value on a failed task means refund pending, not refunded. Query status to reconcile.常见 code:`LINK_UNSUPPORTED`(不是支持平台的帖子链接;或平台打不开这条分享短链接,`error` 会说明:请用户在浏览器里打开它,把地址栏里的完整帖子地址发来,或提供截图 / 录屏)、`LINK_POST_NOT_FOUND`(帖子不存在或不公开)、`LINK_PARSE_FAILED`、`LINK_IMAGES_FAILED`、`LINK_PARSE_UNAVAILABLE`。`LINK_UNSUPPORTED`、`INSUFFICIENT_CREDITS`、`RATE_LIMITED` 在建任务前就拒绝,没有任务,也没扣积分。 5. 等待:每 2 秒查询一次,最长 `--timeout` 秒(默认 900 秒;平台约 15 分钟仍未完成的任务会判失败);个别查询失败(网络、5xx)会容忍,连续 5 次失败才停;被限流时按平台给的时间等待后再查,不算失败。超时、停止等待或命令被打断时,解析可能仍在平台进行:用输出里的 `popost link status ` 继续等待并下载,它不会新建任务、也不会再扣积分。图片下载失败时已下载的保留,同样重跑 `link status`(图片地址每次查询都会重新签发)。`--no-download` 不下载,只打印帖子和图片地址,地址是短期签名链接。 6. 建任务的请求超时或断连,结果不确定(`UNCERTAIN`):不自动重试,先告诉用户。重新运行同一条命令是安全的:同一链接的任务仍在进行时会并入同一个任务、不重复扣;已保存的链接直接返回、也不再扣。 diff --git a/skills/popost/src/providers/link-resolve.ts b/skills/popost/src/providers/link-resolve.ts new file mode 100644 index 0000000..2122650 --- /dev/null +++ b/skills/popost/src/providers/link-resolve.ts @@ -0,0 +1,90 @@ +/** + * Share links the CLI resolves on the user's own machine before a link is submitted to the platform. + * + * A share link carries no post id: it only redirects to the post. Some sites refuse the platform's servers that + * redirect while a request from the user's machine gets it, so the CLI follows the redirects here and submits the post + * link it ends at. Nothing is charged for this and nothing but the link itself is requested: https only, only hosts of + * the same site, at most MAX_HOPS redirects of HOP_TIMEOUT_MS each, no cookies, response bodies discarded. When the + * walk fails for any reason the original link is submitted unchanged and the platform's own answer applies. + */ +import type { Runtime } from '../runtime'; + +export const MAX_HOPS = 5; +export const HOP_TIMEOUT_MS = 10_000; +/** Reddit answers 403 to a request without a User-Agent. */ +const USER_AGENT = 'Mozilla/5.0 (compatible; link-preview)'; + +interface LocalShareRule { + /** The site's domain: the link and every redirect must be on it or a sub-domain of it. */ + readonly domain: string; + readonly isShareLink: (url: URL) => boolean; + /** The post link to submit when `url` is a post page, else null (keep following). */ + readonly postLink: (url: URL) => string | null; +} + +const REDDIT_SHARE = /^\/(?:r|u|user)\/[A-Za-z0-9_-]{1,32}\/s\/[A-Za-z0-9]{4,32}\/?$/i; +const REDDIT_POST = /^\/(?:(?:r|u|user)\/[A-Za-z0-9_-]{1,32}\/)?comments\/[A-Za-z0-9]{1,12}(?:\/[^/]*)?/i; + +/** One entry per site whose share links are resolved locally. */ +const LOCAL_SHARE_RULES: readonly LocalShareRule[] = [ + { + domain: 'reddit.com', + isShareLink: (url) => REDDIT_SHARE.test(url.pathname), + // /r//comments/// without the tracking query the redirect adds + postLink: (url) => { + const path = REDDIT_POST.exec(url.pathname)?.[0]; + return path ? `https://${url.hostname}${path.replace(/\/$/, '')}/` : null; + }, + }, +]; + +const onDomain = (url: URL, domain: string): boolean => { + const host = url.hostname.toLowerCase(); + return url.protocol === 'https:' && (host === domain || host.endsWith(`.${domain}`)); +}; + +const parse = (raw: string, base?: URL): URL | null => { + try { + return new URL(raw, base); + } catch { + return null; + } +}; + +const ruleFor = (url: URL): LocalShareRule | undefined => LOCAL_SHARE_RULES.find((rule) => onDomain(url, rule.domain) && rule.isShareLink(url)); + +/** Where the hop redirects to, or null (not a redirect, refused, network error, timeout). */ +const nextHop = async (rt: Runtime, current: URL): Promise<URL | null> => { + try { + const response = await rt.fetch(current.href, { + method: 'GET', + redirect: 'manual', + credentials: 'omit', + headers: { 'User-Agent': USER_AGENT, Accept: 'text/html' }, + signal: AbortSignal.timeout(HOP_TIMEOUT_MS), + }); + void response.body?.cancel().catch(() => undefined); + const location = response.headers.get('location'); + return response.status >= 300 && response.status < 400 && location ? parse(location, current) : null; + } catch { + return null; + } +}; + +/** + * The post link a share link leads to, or null when `link` is not a share link resolved locally or the walk did not + * reach a post (refused, failed, left the site, too many redirects). + */ +export const resolveShareLink = async (rt: Runtime, link: string): Promise<string | null> => { + const start = parse(link.replace(/^http:\/\//i, 'https://')); + const rule = start && ruleFor(start); + if (!start || !rule) return null; + let current: URL | null = start; + for (let hop = 0; hop < MAX_HOPS; hop++) { + current = await nextHop(rt, current); + if (!current || !onDomain(current, rule.domain)) return null; + const post = rule.postLink(current); + if (post) return post; + } + return null; +}; diff --git a/skills/popost/src/providers/link.ts b/skills/popost/src/providers/link.ts index fddd4ea..86c4414 100644 --- a/skills/popost/src/providers/link.ts +++ b/skills/popost/src/providers/link.ts @@ -16,7 +16,12 @@ * * Credentials and base URL are those of the popost channel (the key from `POPOST_API_KEY` or the one `popost auth set` * saved, `popost.baseUrl` / `POPOST_BASE_URL`); - * the key is read when a request is sent and is scrubbed from everything printed. `--dry-run` needs neither network nor key. + * the key is read when a request is sent and is scrubbed from everything printed. `--dry-run` sends nothing to the + * platform and needs no key. + * + * A share link that only redirects to its post (link-resolve.ts: Reddit's `/r/<sub>/s/<code>`) is first followed on this + * machine, free of charge, and the post link it leads to is submitted in its place and printed as `resolvedUrl` (also by + * `--dry-run`); when that fails the original link is submitted unchanged. */ import { printJson, writeJson } from '../core/util'; import { msg } from '../i18n'; @@ -27,6 +32,7 @@ import { isRecord, type JsonRecord } from './base'; import { loadConfig, providerConfig } from './cli-config'; import { AmbiguousSubmitError, CliReject, ImageProviderError, LOCAL_ERROR_CODES, PopostApiError } from './errors'; import { badResponse, buildBundle, downloadPictures, planPost, remoteView, type PostPlan } from './link-bundle'; +import { resolveShareLink } from './link-resolve'; import { downloadVideo, type SavedVideo } from './link-video'; import { MAX_POLL_FAILURES, TASK_ID, taskOf, waitForTask, type LinkTask } from './link-task'; import { resolvePath } from './paths'; @@ -70,6 +76,8 @@ interface Outcome { interface State { id: string | null; task: LinkTask | null; + /** the post link submitted in place of the share link that was given */ + resolvedUrl?: string; } const shellArg = (text: string): string => (/^[\w@%+=:,./-]+$/.test(text) ? text : `'${text.replace(/'/g, `'\\''`)}'`); @@ -292,7 +300,7 @@ const failureOf = (error: unknown): Failure | null => { const report = async (rt: Runtime, call: LinkOptions, state: State, work: (cfg: JsonRecord) => Promise<Outcome>): Promise<number> => { let secrets: string[] = []; const show = (value: JsonRecord, code: number): number => { - printJson(rt, scrub(value, secrets), true); + printJson(rt, scrub({ ...value, ...(state.resolvedUrl ? { resolvedUrl: state.resolvedUrl } : {}) }, secrets), true); return code; }; try { @@ -313,9 +321,16 @@ const report = async (rt: Runtime, call: LinkOptions, state: State, work: (cfg: export const parseLink = (rt: Runtime, call: ParseCall): Promise<number> => { const state: State = { id: null, task: null }; return report(rt, call, state, async (cfg) => { - const body = parseBody(call); + const given = parseBody(call); const client = makeClient(rt, cfg); - if (call.dryRun) return { exit: 0, body: dryRunOf(rt, client, body, call) }; + /** The body to send: a share link resolved on this machine is replaced by the post link it leads to. */ + const submitted = async (): Promise<JsonRecord> => { + const resolved = await resolveShareLink(rt, String(given.url)); + if (!resolved) return given; + state.resolvedUrl = resolved; + return { ...given, url: resolved }; + }; + if (call.dryRun) return { exit: 0, body: dryRunOf(rt, client, await submitted(), call) }; const quoteCommand = call.libraryOnly ? 'inspiration quote' : 'link quote'; if (!call.confirm) throw badArgs( @@ -328,6 +343,7 @@ export const parseLink = (rt: Runtime, call: ParseCall): Promise<number> => { throw badArgs( msg(`--max-credits must be the authorized non-negative integer ceiling from ${quoteCommand}.`, `--max-credits 必须是 ${quoteCommand} 报价后用户授权的非负整数上限。`), ); + const body = await submitted(); const created = await createTask(client, body); state.id = created.id; state.task = created; diff --git a/skills/popost/tests/link-resolve.test.ts b/skills/popost/tests/link-resolve.test.ts new file mode 100644 index 0000000..c142c12 --- /dev/null +++ b/skills/popost/tests/link-resolve.test.ts @@ -0,0 +1,109 @@ +/** + * Share links resolved on the user's machine (providers/link-resolve.ts): `link parse` / `inspiration add` follow a + * Reddit share link's redirects with the runtime's fetch and submit the post link it leads to. The site is a fake + * fetch; the platform is the in-memory fake of the open API. + */ +import { describe, expect, it } from 'vitest'; +import type { FetchHandler } from '../src/testing/memory'; +import { cli, err, newScene, ok, BASE_URL } from './image-helpers'; + +const SHARE = 'https://www.reddit.com/r/aww/s/8f7eKqYppb'; +const POST = 'https://www.reddit.com/r/aww/comments/1yaynge/a_title/'; +const TASK = '5f0c9a1e-3b7d-4c52-9a41-2d6e8f7b1c03'; +const CONFIRM = ['--confirm', '--max-credits', '9']; + +type Site = (request: Request) => Response; +const redirect = (location: string): Response => new Response(null, { status: 301, headers: { location } }); + +/** The platform fake plus `site` for every request that is not the platform's; records the site's requests. */ +const scene = async (site: Site) => { + const hops: Request[] = []; + const s = await newScene({ + env: { POPOST_PROVIDER_CONFIG: '/work/no-config.json' }, + fetchHandler: + (stub): FetchHandler => + (request) => { + if (request.url.startsWith(BASE_URL)) return stub.fetch(request); + hops.push(request); + return site(request); + }, + }); + const failed = { id: TASK, status: 'failed', created: true, chargedCredits: 0, createdAt: '2026-12-03T00:00:00Z', updatedAt: '2026-12-03T00:00:01Z', error: { code: 'LINK_UNSUPPORTED', message: 'open it in your browser and paste the full address' } }; + s.stub.set('POST', '/links/parse', () => ok({ task: { ...failed, status: 'pending', error: undefined } })); + s.stub.set('GET', '/links/parse', (req) => (req.query.id === TASK ? ok({ task: failed }) : err(404, 'LINK_IMPORT_NOT_FOUND', 'unknown'))); + const rt = { ...s.rt, sleep: async () => undefined }; + const submittedUrls = (): unknown[] => s.stub.calls('POST', '/links/parse').map((call) => call.json?.url); + return { ...s, rt, hops, submittedUrls }; +}; + +describe('a Reddit share link in link parse / inspiration add', () => { + it('resolves and submits the canonical link', async () => { + const t = await scene(() => redirect(`${POST}?share_id=abc&utm_source=share&utm_medium=web`)); + const { data } = await cli(t.rt, 'link', 'parse', SHARE, ...CONFIRM); + expect(t.submittedUrls()).toEqual([POST]); + expect(data.resolvedUrl).toBe(POST); + expect(t.hops).toHaveLength(1); + const hop = t.hops[0]!; + expect(hop.url).toBe(SHARE); + expect(hop.redirect).toBe('manual'); + expect(hop.headers.get('user-agent')).toBeTruthy(); + expect(hop.headers.get('cookie')).toBeNull(); + expect(hop.headers.get('authorization')).toBeNull(); + + const library = await scene(() => redirect('/user/someone/comments/1y97aoz/')); + const added = await cli(library.rt, 'inspiration', 'add', 'http://old.reddit.com/u/someone/s/agwdmFCKwP', ...CONFIRM); + expect(library.hops[0]!.url).toBe('https://old.reddit.com/u/someone/s/agwdmFCKwP'); + expect(library.submittedUrls()).toEqual(['https://old.reddit.com/user/someone/comments/1y97aoz/']); + expect(added.data.resolvedUrl).toBe('https://old.reddit.com/user/someone/comments/1y97aoz/'); + }); + + it('a refused hop falls back to the original', async () => { + for (const site of [() => new Response('blocked', { status: 403 }), () => { throw new TypeError('fetch failed'); }, () => new Response('home', { status: 200 })] as Site[]) { + const t = await scene(site); + const { code, data } = await cli(t.rt, 'link', 'parse', SHARE, ...CONFIRM); + expect(t.submittedUrls()).toEqual([SHARE]); + expect(data).not.toHaveProperty('resolvedUrl'); + // the platform's own answer then applies + expect(code).toBe(1); + expect(data).toMatchObject({ ok: false, code: 'LINK_UNSUPPORTED', error: 'open it in your browser and paste the full address' }); + } + }); + + it('a redirect to a foreign host is not followed', async () => { + const t = await scene((request) => (request.url === SHARE ? redirect('https://evil.example/r/aww/comments/1yaynge/') : redirect(POST))); + const { data } = await cli(t.rt, 'link', 'parse', SHARE, ...CONFIRM); + expect(t.hops.map((hop) => hop.url)).toEqual([SHARE]); + expect(t.submittedUrls()).toEqual([SHARE]); + expect(data).not.toHaveProperty('resolvedUrl'); + + const plain = await scene(() => redirect('http://www.reddit.com/r/aww/comments/1yaynge/')); + await cli(plain.rt, 'link', 'parse', SHARE, ...CONFIRM); + expect(plain.hops).toHaveLength(1); + expect(plain.submittedUrls()).toEqual([SHARE]); + }); + + it('stops after five redirects that never reach a post', async () => { + const t = await scene(() => redirect('https://www.reddit.com/r/aww/')); + await cli(t.rt, 'link', 'parse', SHARE, ...CONFIRM); + expect(t.hops).toHaveLength(5); + expect(t.submittedUrls()).toEqual([SHARE]); + }); + + it('--dry-run shows the resolved link without sending', async () => { + const t = await scene(() => redirect(POST)); + const { code, data } = await cli(t.rt, 'link', 'parse', SHARE, '--dry-run'); + expect(code).toBe(0); + expect(data).toMatchObject({ ok: true, dryRun: true, resolvedUrl: POST, request: { body: { url: POST } } }); + expect(t.stub.requests).toEqual([]); + }); + + it('asks the site nothing for a link that is not a share link, or before the fee is authorized', async () => { + const t = await scene(() => redirect(POST)); + await cli(t.rt, 'link', 'parse', POST, ...CONFIRM); + await cli(t.rt, 'link', 'parse', 'https://v.redd.it/5jc29dfuyr4i1', ...CONFIRM); + expect(t.submittedUrls()).toEqual([POST, 'https://v.redd.it/5jc29dfuyr4i1']); + const unconfirmed = await cli(t.rt, 'link', 'parse', SHARE); + expect(unconfirmed.code).toBe(2); + expect(t.hops).toHaveLength(0); + }); +}); From 31a0fb6b2f5192d863b37a76c35ecd1fd84f136b Mon Sep 17 00:00:00 2001 From: Clipcat-ai <a2888409@gmail.com> Date: Thu, 3 Dec 2026 00:56:33 +0000 Subject: [PATCH 3/9] feat(video): the sentences the program adds to a prompt follow the project's language A project stores the language its user writes in (production/language.json, --lang at product init or inputs show). For a model that takes prompts in the user's language (promptLanguage absent or "user" in the model list) the product block, the cast, anchor, speech and sound sentences are Chinese in a zh project and English for every other language; for a model that says promptLanguage "en" they stay English. A project without a stored language gets the same strings as before, byte for byte: prompts, receipts and request keys do not change. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Signed-off-by: Clipcat-ai <a2888409@gmail.com> --- skills/popost/src/video/commands/cast.ts | 5 +- skills/popost/src/video/commands/product.ts | 6 ++- skills/popost/src/video/generate/cast.ts | 24 ++++++++- skills/popost/src/video/generate/dialogue.ts | 7 +++ skills/popost/src/video/generate/index.ts | 30 ++++++++--- skills/popost/src/video/generate/speech.ts | 6 ++- skills/popost/src/video/product/sheet.ts | 17 ++++++ skills/popost/src/video/prompt-lang.ts | 54 ++++++++++++++++++++ skills/popost/src/video/sound/modes.ts | 8 +++ skills/popost/src/video/voice/sample.ts | 5 +- 10 files changed, 148 insertions(+), 14 deletions(-) create mode 100644 skills/popost/src/video/prompt-lang.ts diff --git a/skills/popost/src/video/commands/cast.ts b/skills/popost/src/video/commands/cast.ts index 9914c14..553f33a 100644 --- a/skills/popost/src/video/commands/cast.ts +++ b/skills/popost/src/video/commands/cast.ts @@ -1,4 +1,5 @@ import { printJson } from '../../core/util'; +import { readProjectLang, withPromptLang } from '../prompt-lang'; import { castPrompt, castVisualInstruction, completeCast, readCast } from '../generate/cast'; import { finalizeSpeech } from '../generate/speech'; import { command, userPath, VideoCommandError, type Commands } from './shared'; @@ -8,13 +9,13 @@ const prepare = command('prepare optional identity image jobs from cast.json; mu options: [{flag:'--requests',metavar:'FILE',help:'material request list; count each role’s appearances before deciding which images are needed'}], }, async (args, rt) => { try { - const dir = userPath(rt, args.req('project')), cast = await readCast(rt, dir); + const dir = userPath(rt, args.req('project')), cast = await readCast(rt, dir), lang = await readProjectLang(rt, dir); const file=args.string('requests'); const requests=file ? JSON.parse(await rt.fs.readText(userPath(rt,file))) as {cast?:string[]}[] : []; if(!Array.isArray(requests))throw new Error('Requests must be a JSON list.'); const required=(id:string,shots?:string[]):boolean=>file ? requests.filter(r=>r.cast?.includes(id)).length>1 : (shots?.length??0)>1; printJson(rt, { ok: true, channel: 'host', direct:cast.roles.filter(role=>!required(role.id,role.shots)&&(!role.identity||role.identity==='new')&&!role.image).map(role=>({id:role.id,description:role.description,...(role.visual?{visual:role.visual,instruction:castVisualInstruction(role)}:{}),method:'Define this new single-appearance '+(role.visual?'character':'person')+' directly in the video prompt.'})), - jobs: cast.roles.filter(role=>required(role.id,role.shots)&&(!role.identity||role.identity==='new')&&!role.image).map(role => ({ id: role.id, identity: role.identity ?? 'new', ...(role.visual?{visual:role.visual}:{}), prompt: castPrompt(role), completed: !!role.image, + jobs: cast.roles.filter(role=>required(role.id,role.shots)&&(!role.identity||role.identity==='new')&&!role.image).map(role => ({ id: role.id, identity: role.identity ?? 'new', ...(role.visual?{visual:role.visual}:{}), prompt: withPromptLang(lang, 'user', () => castPrompt(role)), completed: !!role.image, references: role.identity === 'new' ? [] : role.image ? [role.image] : [], next: 'Generate with the host image tool, inspect the real output, then video cast complete.' })) }); } catch (e) { throw new VideoCommandError(String(e)); } }); diff --git a/skills/popost/src/video/commands/product.ts b/skills/popost/src/video/commands/product.ts index f62fbf3..511047a 100644 --- a/skills/popost/src/video/commands/product.ts +++ b/skills/popost/src/video/commands/product.ts @@ -18,6 +18,7 @@ import type { Problem } from '../types'; import { receiptFile, type ProductReceipt, type ReferenceLimits } from '../product/requests'; import { ASPECTS, buildCheckSheets, deliveryProblems, recordVerdict, reviewStatus } from '../product/review'; import { runFfmpeg, runFfmpegOk } from '../media/ffmpeg'; +import { keepProjectLang, readProjectLang, withPromptLang } from '../prompt-lang'; import { confirmationOf, confirmLine, FACE_FIX, FACT_HELP, inferredFacts, inferredHash, PRODUCT_DIR, PRODUCT_FILE, productBlock, readProductSheet, skeleton, type Product, type ProductPicture, type ProductSheet } from '../product/sheet'; import { platform } from './generate'; import { command, userPath, VideoCommandError, type Commands } from './shared'; @@ -80,12 +81,14 @@ const init = command( options: [ { flag: '--picture', kind: 'append', required: true, metavar: 'FILE', help: 'a picture of the product as the user gave it; repeat for every picture they gave (each goes, whole or cropped to the product, with every clip that shows the product)' }, { flag: '--id', metavar: 'ID', default: 'product', help: 'the id requests name the product by ("products": ["<id>"]); give each product of a video its own' }, + { flag: '--lang', metavar: 'CODE', help: 'the language the user is writing in (en, zh, ja, ...), stored in the project: write the facts in it, and the product block follows it (Chinese for zh, English otherwise)' }, ], }, async (args, rt) => { const dir = userPath(rt, args.req('project')); const id = args.req('id'); if (!/^[a-z0-9][a-z0-9_-]{0,63}$/.test(id)) throw new VideoCommandError('--id is lower-case letters, digits, - and _ ("serum", "bag-black"); it is "' + id + '".'); + await keepProjectLang(rt, dir, args.string('lang')).catch((e: unknown) => { throw new VideoCommandError(e instanceof Error ? e.message : String(e)); }); const sheet = await rawSheet(rt, dir); const old = sheet.products.find((p) => p.id === id); const pictures: ProductPicture[] = [...(old?.pictures ?? [])]; @@ -186,6 +189,7 @@ const check = command( const sheet = loaded.sheet; const state = sheet ? confirmationOf(sheet) : undefined; const final = args.string('final'); + const lang = await readProjectLang(rt, dir); const review = sheet ? await reviewStatus(rt, dir, final ? await fileOf(rt, dir, final) : undefined) : []; const deliver: Problem[] = args.flag('deliver') && sheet ? [...deliveryProblems(review), ...(state === 'open' ? [error(PRODUCT_FILE, 'The user never confirmed what was read from the product picture. ' + confirmLine(sheet), 'Show them that line now and record the answer with popost video product confirm.')] : [])] @@ -194,7 +198,7 @@ const check = command( printJson(rt, { ok: !problems.some((p) => p.level === 'error'), sheet: rt.path.join(dir, PRODUCT_FILE), ...(sheet ? { - products: sheet.products.map((p) => ({ id: p.id, names: p.names, pictures: p.pictures.map((x) => x.file), block: productBlock(p, p.pictures.map((_x, i) => i + 1)) })), + products: sheet.products.map((p) => ({ id: p.id, names: p.names, pictures: p.pictures.map((x) => x.file), block: withPromptLang(lang, 'user', () => productBlock(p, p.pictures.map((_x, i) => i + 1))) })), inferred: inferredFacts(sheet), confirmation: state, ...(state === 'open' ? { confirm: confirmLine(sheet), next: 'Show the user the "confirm" line with the plan and its cost. A correction goes into the sheet as "from": "user" with their words; then popost video product confirm <project> --quote "<their answer>".' } : {}), ...(state === 'unattended' ? { note: 'The inferred facts were never confirmed by the user (unattended: ' + sheet.confirmation?.quote + '). Say so in the delivery notes, with the "inferred" list.' } : {}), ...(review.length ? { review } : {}), diff --git a/skills/popost/src/video/generate/cast.ts b/skills/popost/src/video/generate/cast.ts index dbbd7be..bf6a69c 100644 --- a/skills/popost/src/video/generate/cast.ts +++ b/skills/popost/src/video/generate/cast.ts @@ -1,3 +1,4 @@ +import { pl } from '../prompt-lang'; import type { Runtime } from '../../runtime'; import { sha256 } from '../../core/util'; import { sniffImageMime } from '../../providers/api'; @@ -65,6 +66,16 @@ export const castVisualInstruction = (role: CastRole): string => { if (!v) return ''; const traits = v.archetype; const known = (v.evidence ?? []).filter((e) => e.kind !== 'unknown'); + if (pl('', 'zh')) return (v.medium ? ' 视觉媒介:' + v.medium + '。' : ' 保持已有依据的视觉媒介;不要把插画、动画或 3D 转成摄影。') + + (v.style?.length ? ' 视觉风格:' + v.style.join(';') + '。' : '') + + (v.realism === 'natural-human' ? ' 摄影级真人质感:一个有辨识度、可信的个体,面部有细微自然的不对称。健康、未经修饰的皮肤在当前景别下保留细小毛孔、细绒毛、轻微的肤色变化,以及与年龄相符的眼周和唇部纹理。这些细节在表情变化和不同镜头之间保持一致,皮肤的高光和阴影符合场景光线。保持选定的年龄和面部结构;不要美颜磨皮、蜡质皮肤、夸张的毛孔、额外的年龄感或凭空添加的明显瑕疵。' : '') + + (traits ? ' 形象类型:' + [traits.ageFeel && '年龄感:' + traits.ageFeel, traits.build && '身材比例:' + traits.build, + traits.wardrobe && '服装类别:' + traits.wardrobe, traits.presence && '气质和状态:' + traits.presence, + traits.facialStyle && '大致的面部风格:' + traits.facialStyle].filter(Boolean).join(';') + '。' : '') + + (known.length ? ' 视觉依据:' + known.map((e) => e.detail).join(';') + '。' : '') + + (role.identity === 'user' || role.identity === 'reference' ? ' 保持选定的角色以及用户明确要求的改动。' : + ' 除非用户要求改动,保持观察到的年龄感、身材比例、服装类别和状态。新身份改变的是面部身份,不是这些特征。不要凭空换成更年轻、更年长、更瘦或更胖的类型。') + + (v.evidence?.some((e) => e.kind === 'unknown') ? ' 未确认的视觉依据不是事实;在声称与参考一致之前先确认。' : ''); return (v.medium ? ' Visual medium: ' + v.medium + '.' : ' Keep the evidenced visual medium; do not convert illustration, animation or 3D to photography.') + (v.style?.length ? ' Visual style: ' + v.style.join('; ') + '.' : '') + (v.realism === 'natural-human' ? ' Photographic human realism: a distinctive, believable individual with subtle natural facial asymmetry. Healthy unretouched skin retains fine pores, fine facial hair, slight tonal variation and age-appropriate eye and lip texture at the visible shot scale. Preserve these details through expression changes and across shots, with physically plausible skin highlights and shadows under the scene lighting. Keep the selected age and facial structure; avoid beauty-filter smoothing, waxy skin, exaggerated pores, added age or invented prominent blemishes.' : '') + @@ -76,7 +87,14 @@ export const castVisualInstruction = (role: CastRole): string => { ' Unless the user requests a change, retain the observed age impression, body proportions, wardrobe category and presentation energy. A new identity changes facial identity, not these traits. Do not invent a younger, older, thinner or heavier archetype.') + (v.evidence?.some((e) => e.kind === 'unknown') ? ' Unresolved visual evidence is not a fact; resolve it before claiming a reference match.' : ''); }; -export const castPrompt = (role: CastRole): string => +export const castPrompt = (role: CastRole): string => pl(castPromptEn(role), + (role.visual?.framing === 'portrait' ? '按指定的视觉媒介和风格,生成一张干净的头肩角色身份肖像,脸部大、清晰可辨、对焦准确,纯色背景。' : + role.visual ? '按指定的视觉媒介和风格,生成一张干净的角色身份参考图,全身,脸部清晰可辨,纯色背景。' : + '生成一张干净的摄影风格角色身份参考图,全身,脸部清晰可辨,中性光线,纯色背景。') + role.description + castVisualInstruction(role) + + (role.identity === 'reference' ? ' 只保留用户明确要求的身份。' : role.identity === 'user' ? ' 保持用户提供的角色。' : + ' 创造一个独特的虚构个体,有自己的面部结构和五官。描述给出的是形象类型,绝不是参考视频创作者的身份。不要复现真实的参考人物。') + + ' 不要文字、水印、拼贴或额外的' + (role.visual ? '角色' : '人物') + '。之后的所有镜头都保持这个身份和服装。'); +const castPromptEn = (role: CastRole): string => (role.visual?.framing === 'portrait' ? 'Create a single clean head-and-shoulders character identity portrait in the specified visual medium and style, with the face large, clearly readable and in focus, on a plain background. ' : role.visual ? 'Create a single clean character identity reference in the specified visual medium and style, full body and a clearly readable face, on a plain background. ' : 'Create a single clean photographic character identity reference, full body and a clearly readable face, neutral lighting and plain background. ') + role.description + castVisualInstruction(role) + @@ -142,14 +160,16 @@ export const castImages = async (rt: Runtime, dir: string, ids: string[], uses: const recurring = uses.has(id) ? (uses.get(id) ?? 0) > 1 : (role.shots?.length ?? 0) > 1; if (!role.image && !recurring && (!role.identity || role.identity === 'new')) { const subject = role.visual ? 'character' : 'person'; + if (pl('', 'zh')) { lines.push(id + ':创造一个独特的虚构' + (role.visual ? '角色' : '人物') + ',描述为' + role.description + '。只对应所要求的形象类型和气质,面部比例和五官是原创的。没有提供任何参考身份。在这个生成片段里从头到尾保持这同一个' + (role.visual ? '角色' : '人物') + '。' + castVisualInstruction(role)); continue; } lines.push(id + ': create one distinct fictional ' + subject + ' described as ' + role.description + '. Match only the requested archetype and mood, with original facial proportions and features. No reference identity is being supplied. Keep this one ' + subject + ' consistent throughout this generated clip.' + castVisualInstruction(role)); continue; } if (!role.image || !role.sha256 || !role.provenance) throw new Error('Recurring or user-selected cast role "' + id + '" has no completed identity image. Run video cast prepare, generate/import the real image, then video cast complete.'); const bytes = await rt.fs.readFile(inside(rt, dir, role.image)); if (sha256(bytes) !== role.sha256) throw new Error('Cast image for "' + id + '" changed. Complete the new image before generating clips.'); - images.push(role.image); lines.push(id + ': ' + role.description + castVisualInstruction(role)); + images.push(role.image); lines.push(id + pl(': ', ':') + role.description + castVisualInstruction(role)); } + if (pl('', 'zh')) return { images, instruction: (images.length ? '最后 ' + images.length + ' 张参考图是锁定的出镜人物。' : '这是只出现一次的出镜人物,直接为本次视频生成定义。') + lines.join(';') + '。保持所描述的身份、脸、身材、发型和服装。不要引入参考视频的创作者或别的演员。' }; return { images, instruction: (images.length ? 'The final ' + images.length + ' reference image(s) are the locked cast. ' : 'This is a single-appearance cast, defined directly for video generation. ') + lines.join('; ') + '. Preserve the described identity, face, build, hair and wardrobe. Do not introduce a reference creator or a different actor.' }; }; const current = await render(cast); diff --git a/skills/popost/src/video/generate/dialogue.ts b/skills/popost/src/video/generate/dialogue.ts index 4c1346c..45b1785 100644 --- a/skills/popost/src/video/generate/dialogue.ts +++ b/skills/popost/src/video/generate/dialogue.ts @@ -8,6 +8,7 @@ * where the reference's did. Seconds written by hand ("at", "to") are for a project without a template's beats only. * Everything here is checked before a clip is paid for. Pure. */ +import { pl } from '../prompt-lang'; import { OVERRUN, spokenChars, type Pace } from '../retarget/pace'; import { error } from '../project/check-common'; import type { Problem } from '../types'; @@ -212,8 +213,14 @@ export const NO_MUSIC = ' No background music and no score in this clip: only th const stamp = (seconds: number): string => seconds.toFixed(1); /** The dialogue block of a prompt: the language in plain words, native lip-synced speech, each line with its time, and what must not be heard or seen. English whatever the lines' language; the lines are verbatim. */ +/** NO_MUSIC in the language of the prompt. */ +export const noMusic = (): string => pl(NO_MUSIC, ' 本片段没有背景音乐,也没有配乐:只有场景的环境声、音效和对白。视频的音乐是单独的一条音轨。'); + export const dialoguePrompt = (d: TimedDialogue): string => { const speakers = [...new Set(d.lines.map((l) => l.speaker))]; + if (pl('', 'zh')) return ' 对白:用' + languageName(d.language) + '原生说出,与画面同时录制并对好口型,' + (speakers.length === 1 ? speakers[0] + '的嘴' : '每个说话人的嘴') + '与' + (speakers.length === 1 ? '台词' : '各自的台词') + '完全同步。台词的时间线,从片段开始算起,单位为秒:' + + d.lines.map((l) => stamp(l.at) + '-' + stamp(l.to) + ' 秒 ' + l.speaker + ' 说 ' + JSON.stringify(l.text)).join(';') + + '。这些时间之外没有人说话,两句台词之间嘴保持闭合。没有其他对白,没有旁白,没有字幕或屏幕文字,没有配音,也没有翻译后的语音。生成的语音就是最终音频,之后不会被替换。'; const lines = d.lines.map((l) => stamp(l.at) + '-' + stamp(l.to) + ' s ' + l.speaker + ' says ' + JSON.stringify(l.text)).join('; '); return ' Dialogue: native speech in ' + languageName(d.language) + ', recorded with the picture and lip-synced, the mouth of ' + (speakers.length === 1 ? speakers[0] : 'each speaker') + ' moving exactly with ' + (speakers.length === 1 ? 'the' : 'their own') + ' words. Timeline of the lines, in seconds from the start of the clip: ' + lines + '. Nobody speaks outside these times, and mouths rest closed between the lines. No other dialogue, no narrator, no captions or on-screen text, no dubbing and no translated speech. The generated speech is the final audio and is not replaced afterwards.'; diff --git a/skills/popost/src/video/generate/index.ts b/skills/popost/src/video/generate/index.ts index 439415e..eaa94d2 100644 --- a/skills/popost/src/video/generate/index.ts +++ b/skills/popost/src/video/generate/index.ts @@ -37,7 +37,8 @@ import { sha256 } from '../../core/util'; import { requestHash, startPlan, unplannedNext, type UnplannedClip } from './approved'; import { castImages, personPrompt, readCast } from './cast'; import { finalizeSpeech, isVisibleSpeech, speakersOf, speechAudio, speechPrompt, type SentSpeech, type VisibleSpeech } from './speech'; -import { coverageProblems, dialogueProblems, isDialogue, NO_MUSIC, timedDialogue, type BeatTimes } from './dialogue'; +import { coverageProblems, dialogueProblems, isDialogue, noMusic, timedDialogue, type BeatTimes } from './dialogue'; +import { pl, readProjectLang, withPromptLang, type PromptPolicy } from '../prompt-lang'; import { readClipRecord } from './approved'; import { voiceProfile, type VoiceProfile } from '../voice/profile'; import { audioSeconds } from '../voice/index'; @@ -240,6 +241,9 @@ const extOf = (file: string): string => { return dot > 0 ? base.slice(dot) : ''; }; +/** The name of a requested file among the inputs the user confirms (inputs/record.ts): "clip:assets/a.mp4", "picture:assets/a.png". */ +export const inputKey = (file: string): string => (VIDEOS.includes(extOf(file).toLowerCase()) ? 'clip:' : 'picture:') + file.replace(/\\/g, '/').replace(/^\.\//, ''); + const kindOf = (file: string): GenerateKind | undefined => { const ext = extOf(file).toLowerCase(); return VIDEOS.includes(ext) ? 'video' : PICTURES.includes(ext) ? 'image' : undefined; @@ -421,6 +425,13 @@ const NOTHING_ADDED = 'add nothing from it that the description above does not a * look the same, so it holds for a clip of a product alone as for one of a person: it never asks for a person. */ export const anchorSentence = (n: number, source: AnchorSource, person?: AnchorPicture['person']): string => { + if (pl('', 'zh')) { + if (source === 'character') { + const who = [person?.name, person?.description].map((s) => s?.replace(/\s+/g, ' ').trim()).filter(Boolean).join(':').slice(0, 400); + return '@image' + n + ' 是这条视频里的人物' + (who ? '(' + who + ')' : '') + '。本片段中出现人物时就是这个人,脸、发型和身材相同;上面的描述没有要求的人物不要添加。'; + } + return (source === 'clip' ? '@image' + n + ' 是同一条视频另一个片段的一帧。' : '@image' + n + ' 展示的是这条视频各片段中保持不变的人或物。') + '本片段与它共有的内容(人物及其服装、商品、场所)要和图中完全一样;上面的描述没有要求的内容,不要从图中添加。'; + } if (source === 'character') { const who = [person?.name, person?.description].map((s) => s?.replace(/\s+/g, ' ').trim()).filter(Boolean).join(': ').slice(0, 400); return '@image' + n + ' is the person of this video' + (who ? ' (' + who + ')' : '') + '. When a person appears in this clip it is that person, with the same face, hair and build; add no person the description above does not ask for.'; @@ -433,7 +444,7 @@ export const anchorSentence = (n: number, source: AnchorSource, person?: AnchorP const anchored = (r: MaterialRequest, picture: string, source: AnchorSource, person?: AnchorPicture['person'], product = false): MaterialRequest => { const images = [...(r.images ?? []), picture]; // The anchor may be a generated frame: the product is held to the user's own pictures, never to it. - return { ...r, images, prompt: r.prompt.trim() + ' ' + anchorSentence(images.length, source, person) + (product ? ' The product follows its own pictures named above, not @image' + images.length + '.' : '') }; + return { ...r, images, prompt: r.prompt.trim() + ' ' + anchorSentence(images.length, source, person) + (product ? pl(' The product follows its own pictures named above, not @image' + images.length + '.', '商品以上面指明的商品图片为准,不以 @image' + images.length + ' 为准。') : '') }; }; const readNotes = (rt: Runtime, dir: string): Promise<Record<string, string>> => @@ -504,11 +515,16 @@ const afterFailure = (message: string): string => * to (approved.ts). o.plan (materials --confirm): the clips of * this list become the agreed clips when the project has none yet. */ -export const makeMaterials = async (rt: Runtime, o: { requests: MaterialRequest[]; dir: string; generator: Generator; anchor?: boolean; picture?: AnchorPicture; plan?: boolean; /** The product rules' view of the run: the model's reference limits, and whether files are paid for now (product/requests.ts). */ product?: { limits?: ReferenceLimits; unread?: string; paying?: boolean }; times?: BeatTimes; music?: boolean; modes?: ModeContext; submitOnly?: boolean; onStep?: (file: string, done: number, total: number) => void }): Promise<MaterialsReport> => { +export const makeMaterials = async (rt: Runtime, o: MaterialsRun): Promise<MaterialsReport> => + withPromptLang(o.lang ?? (await readProjectLang(rt, o.dir)), o.policy ?? 'user', () => makeMaterialsIn(rt, o)); + +type MaterialsRun = Parameters<typeof makeMaterialsIn>[1] & { /** The language of the program's own prompt sentences; default: the project's (production/language.json). */ lang?: string; /** How the model in use takes prompts (prompt-lang.ts); default "user". */ policy?: PromptPolicy }; + +const makeMaterialsIn = async (rt: Runtime, o: { requests: MaterialRequest[]; dir: string; generator: Generator; anchor?: boolean; picture?: AnchorPicture; plan?: boolean; /** The product rules' view of the run: the model's reference limits, and whether files are paid for now (product/requests.ts). */ product?: { limits?: ReferenceLimits; unread?: string; paying?: boolean }; times?: BeatTimes; music?: boolean; modes?: ModeContext; submitOnly?: boolean; onStep?: (file: string, done: number, total: number) => void }): Promise<MaterialsReport> => { const replication = await materialReplicationProblems(rt, o.dir, o.requests); if (replication.problems.some(p => p.level === 'error')) return { materials: [], credits: 0, chargedCredits: 0, problems: replication.problems }; - if (replication.forbidNewSpeech) o = { ...o, requests: o.requests.map(r => ({ ...r, prompt: r.prompt + ' Do not add dialogue, voice-over, spoken narration or lip-synced speech. Preserve the requested music, effects and ambience; absence of narration does not mean silence.' })) }; - else if (replication.forbidNewNarration) o = { ...o, requests: o.requests.map(r => ({ ...r, prompt: r.prompt + ' Do not add a voice-over or narrator. Preserve only the planned source-role dialogue, music/vocals, effects and ambience.' })) }; + if (replication.forbidNewSpeech) o = { ...o, requests: o.requests.map(r => ({ ...r, prompt: r.prompt + pl(' Do not add dialogue, voice-over, spoken narration or lip-synced speech. Preserve the requested music, effects and ambience; absence of narration does not mean silence.', ' 不要添加对白、画外音、旁白或对口型的语音。保留所要求的音乐、音效和环境声;没有旁白不等于没有声音。') })) }; + else if (replication.forbidNewNarration) o = { ...o, requests: o.requests.map(r => ({ ...r, prompt: r.prompt + pl(' Do not add a voice-over or narrator. Preserve only the planned source-role dialogue, music/vocals, effects and ambience.', ' 不要添加画外音或旁白。只保留计划中的原角色对白、音乐/人声、音效和环境声。') })) }; const before = Array.isArray(o.requests) && o.times ? await saidBefore(rt, o.dir, o.requests) : undefined; const problems = await checkRequests(rt, o.requests, o.dir, {selectedIdentity:!!o.picture, ...(o.times ? { times: o.times } : {}), ...(before ? { covered: before } : {}), clipMusic: await clipMusicExceptions(rt, o.dir)}); if (problems.length) return { materials: [], credits: 0, chargedCredits: 0, problems }; @@ -661,11 +677,11 @@ export const makeMaterials = async (rt: Runtime, o: { requests: MaterialRequest[ const references = Object.fromEntries(LISTS.flatMap((k) => (r[k]?.length ? [[k, (r[k] ?? []).map(at)]] : []))); const start = priceOnly ? undefined : asked.continues ? await lastFrameOf(rt, o.dir, asked.continues) : asked.firstFrame ? at(asked.firstFrame) : undefined; const frames = { ...(start ? { firstFrame: start } : {}), ...(start && asked.lastFrame ? { lastFrame: at(asked.lastFrame) } : {}) }; - const tail = mode ? sound.tailOf(original, mode) : separateMusic && kind === 'video' ? NO_MUSIC : ''; + const tail = mode ? sound.tailOf(original, mode) : separateMusic && kind === 'video' ? noMusic() : ''; const request: GenerateRequest = { prompt: r.prompt + (sent ? speechPrompt(sent) : '') + tail, ...(mode === 'silent' ? { audio: false as const } : {}), ...(r.seconds ? { seconds: r.seconds } : {}), ...(r.aspect ? { aspect: r.aspect } : {}), ...references, ...frames, ...(priceOnly ? { priceOnly: true as const } : {}) }; // The project (its task, for pictures too) and, for a clip, which agreed clip it is. // POPOST_GEN_WHAT: the clip in the request's own words, for the agreed list and the user (not the sentences added here). - const agreement: Record<string, string> = { POPOST_GEN_PROJECT: o.dir, ...(kind === 'video' ? { POPOST_GEN_FILE: original.file, POPOST_GEN_REQUEST: requestHash(rt, original), POPOST_GEN_WHAT: original.prompt } : {}), ...(o.submitOnly ? { POPOST_GEN_NO_WAIT: '1' } : {}) }; + const agreement: Record<string, string> = { POPOST_GEN_PROJECT: o.dir, POPOST_GEN_INPUT: inputKey(original.file), ...(kind === 'video' ? { POPOST_GEN_FILE: original.file, POPOST_GEN_REQUEST: requestHash(rt, original), POPOST_GEN_WHAT: original.prompt } : {}), ...(o.submitOnly ? { POPOST_GEN_NO_WAIT: '1' } : {}) }; const made = await o.generator.make(kind, request, partial, agreement); const charged = made.chargedCredits ?? made.credits; if(made.credits!==undefined)entry={...entry,credits:made.credits}; diff --git a/skills/popost/src/video/generate/speech.ts b/skills/popost/src/video/generate/speech.ts index 93366d3..12219a7 100644 --- a/skills/popost/src/video/generate/speech.ts +++ b/skills/popost/src/video/generate/speech.ts @@ -1,3 +1,4 @@ +import { pl } from '../prompt-lang'; import type { Runtime } from '../../runtime'; import { sha256 } from '../../core/util'; import { programsOf, toolCommand, withTempDir } from '../host'; @@ -22,7 +23,10 @@ export const isVisibleSpeech = (value: unknown): value is VisibleSpeech => isDia export const speakersOf = (speech: VisibleSpeech | SentSpeech): string[] => 'lines' in speech ? [...new Set(speech.lines.map((l) => l.speaker))] : [speech.speaker]; /** The final audio a lip-synced clip is made to (the first form only). */ export const speechAudio = (speech: VisibleSpeech | SentSpeech | undefined): string | undefined => (speech && !('lines' in speech) ? speech.audio : undefined); -export const speechPrompt = (speech: SentSpeech): string => 'lines' in speech ? dialoguePrompt(speech) : speech.mode === 'native' +export const speechPrompt = (speech: SentSpeech): string => 'lines' in speech ? dialoguePrompt(speech) : pl(plainSpeechPrompt(speech), speech.mode === 'native' + ? ' 出镜说话人 ' + speech.speaker + ' 一字不差地说:' + JSON.stringify(speech.text) + '。同步生成可见的口型和原生语音,停顿自然;没有其他对白、音乐、字幕、翻译配音,也没有无声的嘴部动作。生成的语音就是最终音频,之后不会被替换。' + : ' 出镜说话人 ' + speech.speaker + ' 表演给定的对白。最终的声音另行确定,成片会按那段音频做口型同步。'); +const plainSpeechPrompt = (speech: PlainSpeech): string => speech.mode === 'native' ? ' Visible speaker ' + speech.speaker + ' says exactly: ' + JSON.stringify(speech.text) + '. Generate synchronized visible articulation and native speech audio together, with natural pauses; no other dialogue, music, captions, translated dubbing or silent mouth motion. The generated speech audio is authoritative and will not be replaced afterwards.' : ' Visible speaker ' + speech.speaker + ' performs the supplied dialogue. The final voice is fixed separately and the result will pass through lip synchronization to that exact audio.'; diff --git a/skills/popost/src/video/product/sheet.ts b/skills/popost/src/video/product/sheet.ts index a438eb8..1c9dfc7 100644 --- a/skills/popost/src/video/product/sheet.ts +++ b/skills/popost/src/video/product/sheet.ts @@ -17,6 +17,7 @@ * retouch or a re-compressed copy. No program here can tell a face, so every picture carries who looked ("face"): the * agent that opened it, or the user when the agent cannot see pictures. A picture nobody looked at is not sent. */ +import { pl } from '../prompt-lang'; import { sha256 } from '../../core/util'; import { sniffImageMime } from '../../providers/api'; import { isRecord } from '../../providers/base'; @@ -133,6 +134,18 @@ export const confirmLine = (sheet: ProductSheet): string => { */ export const productBody = (p: Product): string => { const label = tidy(p.label.value); + if (pl('', 'zh')) return [ + '它是' + clause(p.what.value) + '。', + label.toLowerCase() === NO_LABEL ? '它上面没有印任何文字。' : '它上面印的文字,一字不差:“' + label + '”。', + '形状:' + clause(p.shape.value) + '。', + '尺寸:' + clause(p.size.value) + ';' + clause(p.sizeAnchor.value) + '。', + (p.material ? '颜色和材质:' + clause(p.colour.value) + ';' + clause(p.material.value) : '颜色:' + clause(p.colour.value)) + '。', + ...(p.parts ? ['部件:' + clause(p.parts.value) + '。'] : []), + '用法:' + clause(p.use.value) + '。', + '数量:' + clause(p.quantity.value) + '。', + '每一帧都保持不变:' + p.constant.map(clause).join(';') + '。', + '无论出现在哪里,从第一帧到最后一帧它都是这同一件物品,轮廓、比例、相对手和身体的大小、印刷文字、颜色、部件和数量都相同。', + ].join(''); return [ 'It is ' + clause(p.what.value) + '.', label.toLowerCase() === NO_LABEL ? 'Nothing is printed on it.' : 'Printed on it, exactly: "' + label + '".', @@ -149,6 +162,7 @@ export const productBody = (p: Product): string => { const imageNames = (indexes: readonly number[]): string => { const names = indexes.map((n) => '@image' + n); + if (pl('', 'zh')) return names.join('、'); return names.length <= 2 ? names.join(' and ') : names.slice(0, -1).join(', ') + ' and ' + names[names.length - 1]; }; @@ -159,6 +173,9 @@ const imageNames = (indexes: readonly number[]): string => { */ export const productBlock = (p: Product, indexes: readonly number[]): string => { const one = indexes.length === 1; + if (pl('', 'zh')) return (indexes.length + ? '商品“' + p.id + '”:' + imageNames(indexes) + '是用户自己提供的商品图片。只从图片中取商品本身,图片里的其他内容(人物、背景、屏幕上的文字)一概不取。' + : '商品“' + p.id + '”:就是本片段第一帧里的那件商品。') + productBody(p); const lead = indexes.length ? 'Product "' + p.id + '": ' + imageNames(indexes) + (one ? ' is the user\'s own picture' : ' are the user\'s own pictures') + ' of it. Take the product from ' + (one ? 'it' : 'them') + ' and nothing else that is in ' + (one ? 'that picture' : 'those pictures') + ' (a person, a background, text on a screen).' : 'Product "' + p.id + '": it is the product in the first frame of this clip.'; diff --git a/skills/popost/src/video/prompt-lang.ts b/skills/popost/src/video/prompt-lang.ts new file mode 100644 index 0000000..6c84710 --- /dev/null +++ b/skills/popost/src/video/prompt-lang.ts @@ -0,0 +1,54 @@ +/** + * The language of the sentences the program itself adds to a prompt (the product block, the cast and anchor + * sentences, the lines about speech and sound). A project stores the language the user writes in + * (production/language.json, set once with --lang); the agent writes its prompts, the product facts and the voice + * script in it. For a model that takes prompts in the user's language (the default; `promptLanguage` in the model + * list is absent or "user") the program's own sentences follow: Chinese for zh, English for every other language. For + * a model whose list entry says `promptLanguage: "en"` the prompt is sent in English and the user is shown a version + * in their language beside it (inputs/display). + * + * A project without a stored language gets the English sentences, byte for byte as before: its prompts, receipts and + * request keys do not change. Fixed tokens are never translated: @imageN, ids, file names, quoted text. + */ +import { AsyncLocalStorage } from 'node:async_hooks'; +import { writeJson } from '../core/util'; +import { isRecord } from '../providers/base'; +import type { Runtime } from '../runtime'; + +export const LANGUAGE_FILE = 'production/language.json'; +const LANG = /^[a-z]{2,3}(-[A-Za-z0-9]{2,8})*$/; + +/** How a model wants its prompts: in the user's language, or in English. */ +export type PromptPolicy = 'user' | 'en'; + +const scope = new AsyncLocalStorage<'zh' | undefined>(); + +/** Whether a language code is Chinese (zh, zh-CN, zh-Hant). */ +export const isChinese = (lang: string | undefined): boolean => (lang ?? '').toLowerCase().startsWith('zh'); + +/** Runs body with the program's prompt sentences in the language of `lang` under `policy`: Chinese only for zh and "user". */ +export const withPromptLang = <T>(lang: string | undefined, policy: PromptPolicy, body: () => T): T => scope.run(isChinese(lang) && policy === 'user' ? 'zh' : undefined, body); + +/** A sentence the program adds to a prompt: English unless the scope is Chinese. */ +export const pl = (en: string, zh: string): string => (scope.getStore() === 'zh' ? zh : en); + +/** The language the project's user writes in, or undefined when none was stored. */ +export const readProjectLang = async (rt: Runtime, dir: string): Promise<string | undefined> => { + const data: unknown = await rt.fs.readText(rt.path.join(dir, LANGUAGE_FILE)).then((t) => JSON.parse(t) as unknown, () => undefined); + return isRecord(data) && typeof data.lang === 'string' && LANG.test(data.lang) ? data.lang : undefined; +}; + +/** Stores --lang for the project; undefined leaves what is there. Returns the language in force. */ +export const keepProjectLang = async (rt: Runtime, dir: string, given: string | undefined): Promise<string | undefined> => { + const lang = given?.trim(); + if (!lang) return readProjectLang(rt, dir); + if (!LANG.test(lang)) throw new Error('--lang is a language code such as en, zh, ja or pt-BR; it is "' + lang + '".'); + if ((await readProjectLang(rt, dir)) !== lang) { + await rt.fs.mkdir(rt.path.join(dir, 'production')); + await writeJson(rt, rt.path.join(dir, LANGUAGE_FILE), { version: 1, lang }); + } + return lang; +}; + +/** The policy of a model of the platform's list: `promptLanguage: "en"`, else "user". */ +export const policyOf = (model: unknown): PromptPolicy => (isRecord(model) && model.promptLanguage === 'en' ? 'en' : 'user'); diff --git a/skills/popost/src/video/sound/modes.ts b/skills/popost/src/video/sound/modes.ts index f00435e..babb0be 100644 --- a/skills/popost/src/video/sound/modes.ts +++ b/skills/popost/src/video/sound/modes.ts @@ -6,6 +6,7 @@ * prompt, and it is kept beside the clip (<file>.mode.json) for the mix. Music made inside a clip is the exception: * only an exhibit has it by its mode; any other clip has it only on a basis recorded in the project's music plan. */ +import { pl } from '../prompt-lang'; import type { Runtime } from '../../runtime'; import { error } from '../project/check-common'; import { SOUND_MODES, type Problem, type SoundMode } from '../types'; @@ -58,6 +59,13 @@ const NO_MUSIC_SENTENCE = 'No background music and no score in this clip: the mu * sentence about music out. An exhibit is left free: it is the thing shown, with whatever sound it has. */ export const soundTail = (mode: SoundMode, o: { music?: ClipMusicBasis } = {}): string => { + if (pl('', 'zh')) { + const none = o.music ? '' : '本片段没有背景音乐,也没有配乐:视频的音乐是单独的一条音轨。'; + if (mode === 'speech') return ' 声音:说话人的声音是本片段的主体,清晰、贴近,下面是场景里安静的环境声。' + none; + if (mode === 'ambience') return ' 声音:只有场景的环境声和画面中发生的事情的声音。没有人说话:没有对白,没有旁白,没有人声。' + none; + if (mode === 'silent') return ' 本片段不使用自带的声音:没有人对着镜头说话,嘴保持闭合或背对镜头。'; + return ''; + } const music = o.music ? '' : ' ' + NO_MUSIC_SENTENCE; if (mode === 'speech') return ' Sound: the speaker\'s voice is the lead of this clip, clear and close, over the quiet ambient sound of the scene.' + music; if (mode === 'ambience') return ' Sound: only the ambient sound of the scene and the sounds of what happens in it. Nobody speaks: no dialogue, no narrator, no voice.' + music; diff --git a/skills/popost/src/video/voice/sample.ts b/skills/popost/src/video/voice/sample.ts index 0cc5558..214fe4f 100644 --- a/skills/popost/src/video/voice/sample.ts +++ b/skills/popost/src/video/voice/sample.ts @@ -7,6 +7,7 @@ * file of the user's, from an approved clip, or has the registered voice speak a neutral line (a paid line of speech, * priced and agreed like any other). WAV, one channel: what the video models take as a reference sound. */ +import { pl } from '../prompt-lang'; import { sha256 } from '../../core/util'; import type { Runtime } from '../../runtime'; import { runFfmpegOk } from '../media/ffmpeg'; @@ -44,7 +45,9 @@ export const sampleStart = (silences: readonly (readonly [number, number])[], se }; /** The sentence that names the reference sounds of a clip's speakers: "host's voice is @audio1; guest's voice is @audio2". */ -export const VOICE_NAMED = (speakers: readonly string[], first: number): string => +export const VOICE_NAMED = (speakers: readonly string[], first: number): string => pl(VOICE_NAMED_EN(speakers, first), + ' ' + speakers.map((s, i) => s + '的声音是 @audio' + (first + i)).join(';') + ':' + (speakers.length === 1 ? '它' : '每一段') + '只确定声音的身份和音色。台词用' + (speakers.length === 1 ? '这个声音' : '这些声音') + '说出,绝不说参考录音里的话,并且这个声音在每个片段里保持一致。'); +const VOICE_NAMED_EN = (speakers: readonly string[], first: number): string => ' ' + speakers.map((s, i) => 'The voice of ' + s + ' is @audio' + (first + i)).join('; ') + ': ' + (speakers.length === 1 ? 'it defines' : 'each defines') + ' the voice\'s identity and timbre only. The lines are spoken with ' + (speakers.length === 1 ? 'that voice' : 'those voices') + ', never with the words of the reference recording, and the voice stays the same through every clip.'; From d3f24cf56f009d67b6dee817803e081e977e00b7 Mon Sep 17 00:00:00 2001 From: Clipcat-ai <a2888409@gmail.com> Date: Thu, 3 Dec 2026 00:56:34 +0000 Subject: [PATCH 4/9] feat(video): the user confirms the inputs before anything is paid for popost video inputs show gathers, without paying, what a paid run would send: every prompt as materials composes it, the product picture as sent, the cast's pictures, each clip's references, the voice with its lines, a free sample and free price quotes; it writes the input sheet picture and a summary for one message to the user. inputs confirm records the answer with a hash of each item shown, and confirms the product's inferred facts with it. materials, generate (for a file of a project) and the paid voice commands stop with exit code 3 and confirm.reason "inputs" until then; a changed request, picture or voice line is asked about again, alone. --unattended records a batch nobody watches. For a model that is sent English, inputs translate stores the user's-language version shown first, bound to the sent text. Behaviour change for hosts: a paid materials run now needs the confirmation (or --unattended). Open API calls are unchanged; clips are priced with the existing free quote. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Signed-off-by: Clipcat-ai <a2888409@gmail.com> --- skills/popost/src/commands/video.ts | 3 +- skills/popost/src/video/commands/generate.ts | 15 +- skills/popost/src/video/commands/inputs.ts | 219 ++++++++++++ skills/popost/src/video/commands/loop.ts | 4 +- skills/popost/src/video/commands/materials.ts | 36 +- skills/popost/src/video/commands/shared.ts | 5 + skills/popost/src/video/commands/template.ts | 9 +- .../src/video/commands/voice-profile.ts | 4 +- .../popost/src/video/generate/cloud-image.ts | 11 +- skills/popost/src/video/generate/cloud.ts | 18 + skills/popost/src/video/inputs/collect.ts | 205 +++++++++++ skills/popost/src/video/inputs/record.ts | 175 ++++++++++ skills/popost/src/video/inputs/sheet.ts | 99 ++++++ skills/popost/src/video/inputs/summary.ts | 166 +++++++++ skills/popost/src/video/product/requests.ts | 2 +- skills/popost/tests/video/inputs.test.ts | 325 ++++++++++++++++++ .../popost/tests/video/loop-commands.test.ts | 4 +- .../tests/video/product-materials.test.ts | 18 +- skills/popost/tests/video/spending.test.ts | 12 +- 19 files changed, 1309 insertions(+), 21 deletions(-) create mode 100644 skills/popost/src/video/commands/inputs.ts create mode 100644 skills/popost/src/video/inputs/collect.ts create mode 100644 skills/popost/src/video/inputs/record.ts create mode 100644 skills/popost/src/video/inputs/sheet.ts create mode 100644 skills/popost/src/video/inputs/summary.ts create mode 100644 skills/popost/tests/video/inputs.test.ts diff --git a/skills/popost/src/commands/video.ts b/skills/popost/src/commands/video.ts index 83b16f4..d3e5eeb 100644 --- a/skills/popost/src/commands/video.ts +++ b/skills/popost/src/commands/video.ts @@ -13,6 +13,7 @@ import { castCommands, speechCommands } from '../video/commands/cast'; import { productCommands } from '../video/commands/product'; import { voiceProfileCommands } from '../video/commands/voice-profile'; import { elementsCommands } from '../video/commands/elements'; +import { inputsCommands } from '../video/commands/inputs'; import { generateCommands } from '../video/commands/generate'; import { loopCommands, loopGroups } from '../video/commands/loop'; import { makeCommands, makeGroups } from '../video/commands/make'; @@ -29,7 +30,7 @@ import { runSubcommand, type Subcommand } from '../workflow/subcommands'; const PROG = 'popost video'; const COMMANDS: Commands = { ...mediaCommands, ...cleanCommands, ...makeCommands, ...readCommands, ...loopCommands, ...generateCommands, ...sourceCommands, ...clipCommands, ...speechCommands, 'speech-check': speechCheck }; -const GROUPS: Readonly<Record<string, Commands>> = { ...makeGroups, ...readGroups, ...loopGroups, elements: elementsCommands, cast: castCommands, product: productCommands, voice: voiceProfileCommands, music: musicCommands, sfx: sfxCommands, 'speech-kind': speechKindCommands, replication: replicationCommands }; +const GROUPS: Readonly<Record<string, Commands>> = { ...makeGroups, ...readGroups, ...loopGroups, elements: elementsCommands, cast: castCommands, product: productCommands, inputs: inputsCommands, voice: voiceProfileCommands, music: musicCommands, sfx: sfxCommands, 'speech-kind': speechKindCommands, replication: replicationCommands }; /** The groups appear in the command list (help, usage errors) as commands that take a command of their own. */ const groupEntry = (commands: Commands): Subcommand => ({ diff --git a/skills/popost/src/video/commands/generate.ts b/skills/popost/src/video/commands/generate.ts index b04c3bf..ee898fe 100644 --- a/skills/popost/src/video/commands/generate.ts +++ b/skills/popost/src/video/commands/generate.ts @@ -20,7 +20,9 @@ import type { Runtime } from '../../runtime'; import type { Subcommand } from '../../workflow/subcommands'; import { cloudSettings, GenerateError, listModels, makeClip } from '../generate/cloud'; import { makePicture } from '../generate/cloud-image'; -import { CONFIRM_EXIT, ConfirmNeeded, PENDING_EXIT, StillMaking, type GenerateRequest } from '../generate/index'; +import { CONFIRM_EXIT, ConfirmNeeded, inputKey, PENDING_EXIT, StillMaking, type GenerateRequest } from '../generate/index'; +import { projectOf } from '../generate/approved'; +import { confirmBlock, readInputs } from '../inputs/record'; import { CREDIT_OPTIONS, ceilingOf } from './credits'; import { userPath, VideoCommandError, type Commands } from './shared'; @@ -96,6 +98,17 @@ const run = async (args: ParsedArgs, rt: Runtime): Promise<number> => { // The project the file is for (--project, the one materials names, else the one around the output file): what this // call charges joins the project's line on the account page. const inside = s.gate.project ? inProject(rt, s.gate.project, 'video') : await aroundPath(rt, target); + // A file of a project is paid for only once the user has seen it among the inputs (inputs/record.ts); materials checks the whole list first. + const home = s.gate.project ?? (await projectOf(rt, target)); + if (home && !asked.priceOnly && (s.yes || s.maxCredits !== undefined)) { + const key = rt.env.POPOST_GEN_INPUT?.trim() || inputKey(rt.path.relative(home, target).split(rt.path.sep).join('/')); + const record = await readInputs(rt, home); + if (record.confirmed?.items[key] === undefined && !(await rt.fs.stat(target))) { + printJson(rt, confirmBlock(rt, home, record, [key], home)); + rt.stderr('The user has not confirmed the inputs of ' + key + '; nothing was made or charged. Show them the input sheet and the summary (popost video inputs show), then popost video inputs confirm.\n'); + return CONFIRM_EXIT; + } + } if (kind === 'video') printJson(rt, await makeClip(inside, (await platform(inside)).client, s, asked, target)); else printJson(rt, await makePicture(inside, s, found.config, asked, target)); return 0; diff --git a/skills/popost/src/video/commands/inputs.ts b/skills/popost/src/video/commands/inputs.ts new file mode 100644 index 0000000..87fde37 --- /dev/null +++ b/skills/popost/src/video/commands/inputs.ts @@ -0,0 +1,219 @@ +/** + * `popost video inputs`: what the user confirms before anything is paid for (inputs/record.ts). show gathers what a + * paid run of the request list would send (every prompt as sent, the product picture as sent, the cast's pictures, + * each clip's references, the voice with its lines and a sample) with its price, and writes the input sheet picture + * and the summary; voice writes the voice plan; translate stores the user's-language version of a text that is sent + * in English; confirm records the user's answer for exactly what was shown. Nothing here is paid: prices are free + * quotes, and a voice sample is the platform's own preview or none. + */ +import { printJson, writeJson } from '../../core/util'; +import { withLang } from '../../i18n'; +import { BrowserUnavailableError } from '../../render/browser'; +import type { Runtime } from '../../runtime'; +import { readUserJson } from '../../workflow/io'; +import type { MaterialRequest } from '../generate/index'; +import { hasMusicTrack } from '../music/provenance'; +import { gather } from '../inputs/collect'; +import { currentInputs, INPUTS_DIR, INPUTS_FILE, pendingOf, readInputs, readVoicePlan, VOICE_PLAN_FILE, writeInputs, type PlannedVoice } from '../inputs/record'; +import { writeSheets } from '../inputs/sheet'; +import { summarize, summaryText, textHash, withDisplay, type Summary } from '../inputs/summary'; +import { confirmationOf, confirmLine, inferredFacts, inferredHash, PRODUCT_FILE, readProductSheet } from '../product/sheet'; +import { isChinese, keepProjectLang, readProjectLang } from '../prompt-lang'; +import { spokenLinesOf } from '../retarget/speak'; +import type { RetargetPlan } from '../retarget/index'; +import { loadTemplate } from '../template/save'; +import { beatTimesOf } from '../template/speech-rules'; +import { characterOf, givenAnchor } from './materials'; +import { command, userPath, VideoCommandError, type Commands } from './shared'; + +const PROJECT = { name: 'project', help: 'the video project directory' } as const; +const LANG = { flag: '--lang', metavar: 'CODE', help: 'the language the user is writing in (en, zh, ja, ...): stored in the project; the labels of the sheet and the summary follow it (English or Chinese), and so do the sentences the program adds to a prompt' } as const; +const SUMMARY_JSON = INPUTS_DIR + '/summary.json'; +const SUMMARY_MD = INPUTS_DIR + '/summary.md'; + +/** The labels' language: the project's, Chinese or English; without one, the language of the command line. */ +const labelled = <T>(lang: string | undefined, body: () => T): T => (lang ? withLang(isChinese(lang) ? 'zh' : 'en', body) : body()); + +/** A path as the record keeps it: inside the project when it is there, else absolute. */ +const kept = (rt: Runtime, dir: string, file: string): string => { + const rel = rt.path.relative(rt.path.resolve(dir), file); + return rel && !rel.startsWith('..') && !rt.path.isAbsolute(rel) ? rel.split(rt.path.sep).join('/') : file; +}; + +const writeSummary = async (rt: Runtime, dir: string, s: Summary): Promise<void> => { + await rt.fs.mkdir(rt.path.join(dir, INPUTS_DIR)); + await writeJson(rt, rt.path.join(dir, SUMMARY_JSON), s); + await rt.fs.writeFile(rt.path.join(dir, SUMMARY_MD), labelled(s.lang, () => summaryText(s))); +}; + +const show = command( + 'gathers everything a paid run would send to a model, without paying: every prompt as sent, the product picture as sent (the crop), the cast\'s pictures, each clip\'s reference pictures and frames, the voice with its lines and a free sample, with free price quotes. Writes the input sheet picture(s) and a summary (production/inputs/) for ONE message to the user; paid commands wait for popost video inputs confirm', + { + positionals: [PROJECT], + options: [ + { flag: '--requests', metavar: 'FILE', help: 'the material request list popost video materials will be run with; left out for a video with only a voice' }, + { flag: '--template', metavar: 'DIR', help: 'as for materials: the template the clips are for' }, + { flag: '--anchor-image', metavar: 'FILE', help: 'as for materials' }, + { flag: '--character', metavar: 'ID', help: 'as for materials' }, + { flag: '--no-anchor', kind: 'flag', help: 'as for materials' }, + { flag: '--anchor', kind: 'flag', help: 'as for materials' }, + LANG, + ], + }, + async (args, rt) => { + const dir = userPath(rt, args.req('project')); + const lang = await keepProjectLang(rt, dir, args.string('lang')).catch((e: unknown) => { throw new VideoCommandError(e instanceof Error ? e.message : String(e)); }); + const given = args.string('requests'); + const requests = given === undefined ? [] : ((await readUserJson(rt, given)) as MaterialRequest[]); + if (!Array.isArray(requests)) throw new VideoCommandError('--requests is the JSON list popost video materials takes.'); + const template = args.string('template'); + const pkg = template === undefined ? undefined : await loadTemplate(rt, userPath(rt, template)); + const [image, character] = [args.string('anchor-image'), args.string('character')]; + const picture = image !== undefined ? await givenAnchor(rt, dir, image) : character !== undefined ? await characterOf(rt, dir, character) : undefined; + const g = await gather(rt, dir, { requests, ...(picture ? { picture } : {}), ...(args.flag('no-anchor') ? { anchor: false } : args.flag('anchor') ? { anchor: true } : {}), ...(pkg ? { times: beatTimesOf(pkg) } : {}), music: await hasMusicTrack(rt, dir), ...(lang ? { lang } : {}) }) + .catch((e: unknown) => { throw new VideoCommandError(e instanceof Error ? e.message : String(e)); }); + if (g.problems.some((p) => p.level === 'error')) { + printJson(rt, { ok: false, error: 'The list has errors, so nothing can be shown to the user yet; nothing was made or charged.', problems: g.problems }); + return 2; + } + if (!g.clips.length && !g.voices.length && !g.products.length) throw new VideoCommandError('There is nothing to show: give --requests <the request list>, or write the voice plan first (popost video inputs voice).'); + const current = await currentInputs(rt, dir, { requests, ...(picture ? { anchor: picture.file } : {}) }); + const record = await readInputs(rt, dir); + const sheet = (await readProductSheet(rt, dir)).sheet; + const draft = summarize(g, { ...(lang ? { lang } : {}), ...(record.display ? { display: record.display } : {}), ...(record.confirmed ? { confirmed: record.confirmed.items } : {}), items: current.items, ...(sheet && inferredFacts(sheet).length ? { inferred: labelled(lang, () => confirmLine(sheet)) } : {}), sheets: [] }); + let sheets: string[] = []; + let noSheet: string | undefined; + try { + sheets = await labelled(lang, () => writeSheets(rt, dir, INPUTS_DIR, draft)); + } catch (e) { + if (rt.signal?.aborted) throw e; + noSheet = 'No input sheet picture was drawn' + (e instanceof BrowserUnavailableError ? ': this machine has no browser to draw it with' : '') + ' (' + (e instanceof Error ? e.message : String(e)) + '). Show the user each picture the summary names instead, with its caption.'; + } + const summary: Summary = { ...draft, sheets, ...(noSheet ? { notes: [...draft.notes, noSheet] } : {}) }; + await writeSummary(rt, dir, summary); + const texts = Object.fromEntries([...summary.items.map((i) => [i.key, textHash(i.prompt.sent)] as const), ...summary.voices.map((v) => [v.key, textHash(v.script.sent)] as const)]); + // A text in the user's language whose sent text changed is no longer a version of it. + const display = Object.fromEntries(Object.entries(record.display ?? {}).filter(([k, d]) => texts[k] === d.sent)); + await writeInputs(rt, dir, { ...record, version: 1, display, shown: { at: rt.now().toISOString(), ...(given !== undefined ? { requests: kept(rt, dir, userPath(rt, given)) } : {}), ...(picture ? { anchor: picture.file } : {}), ...(lang ? { lang } : {}), items: current.items, texts, sheets, summary: SUMMARY_MD, ...(summary.displayMissing.length ? { missing: summary.displayMissing } : {}) } }); + const needed = [...current.toMake, ...summary.voices.map((v) => v.key), ...summary.products.map((p) => p.key)]; + const pending = pendingOf(record, current, needed); + printJson(rt, { + ok: true, sheets: sheets.map((f) => rt.path.join(dir, f)), summary: rt.path.join(dir, SUMMARY_MD), data: rt.path.join(dir, SUMMARY_JSON), + ...(lang ? { lang } : {}), promptLanguage: summary.policy, totals: summary.totals, pending, ...(summary.displayMissing.length ? { displayMissing: summary.displayMissing } : {}), + voiceSamples: summary.voices.map((v) => ({ speaker: v.speaker, ...(v.sample ? { file: rt.path.join(dir, v.sample.file), from: v.sample.from } : { none: v.note ?? 'no free sample', ...(v.paidSample ? { paidSample: v.paidSample } : {}) }) })), + ...(summary.notes.length ? { notes: summary.notes } : {}), ...(g.problems.length ? { problems: g.problems } : {}), + next: (summary.displayMissing.length + ? 'First write the user\'s-language version of each text in "displayMissing" (the model is sent English; the user reads their own language first): popost video inputs translate ' + args.req('project') + ' --item <key> --text "<a faithful translation>" (or --file <a JSON object of key to text>), then run this command again. ' + : '') + + (pending.length + ? 'Show the user, in ONE message: the input sheet picture(s), the text of the summary file (every prompt as sent, the voice and its script; let them hear the voice sample), and the cost. Wait for their answer; then popost video inputs confirm ' + args.req('project') + ' --quote "<their words>". A correction goes into the list, the product sheet or the voice plan first, and this command runs again: only what changed is asked about. Nothing was made or charged.' + : 'The user has confirmed all of this as it stands: the paid commands can run within the agreed budget.'), + }); + return 0; + }, + (args) => args.string('project'), +); + +const voice = command( + 'writes one voice of the voice plan (production/voice-plan.json): who speaks, with which voice, how fast, and the lines. The user is shown it by inputs show, and the paid voice commands speak only what the plan says', + { + positionals: [PROJECT], + options: [ + { flag: '--speaker', required: true, metavar: 'ID', help: 'who speaks: "narrator", or the speaker id of popost video voice use|add' }, + { flag: '--voice', metavar: 'VOICE', help: 'the voice: popost:default-female, popost:default-male, popost:<id> (popost video voice list), or the name your own speaker takes; default: the fill\'s, else the voice registered for the speaker' }, + { flag: '--speed', kind: 'number', metavar: 'N', help: 'the speed (default 1, or the fill\'s)' }, + { flag: '--language', metavar: 'CODE', help: 'the language of the lines' }, + { flag: '--line', kind: 'append', metavar: 'TEXT', help: 'a line it speaks; repeat in order' }, + { flag: '--fill', metavar: 'FILE', help: 'the fill or plan whose captions are the narration (as template fill --speak and retarget --speak read them), with its "voice" and "speed"' }, + ], + }, + async (args, rt) => { + const dir = userPath(rt, args.req('project')); + const fill = args.string('fill') ? ((await readUserJson(rt, args.req('fill'))) as RetargetPlan) : undefined; + const lines = [...(fill ? spokenLinesOf(fill) : []), ...args.list('line')].map((l) => l.trim()).filter(Boolean); + const speaker = args.req('speaker'); + const registered: unknown = await rt.fs.readText(rt.path.join(dir, 'voices.json')).then((t) => JSON.parse(t) as unknown, () => undefined); + const provider = (registered as { speakers?: { id?: string; providerVoice?: string }[] } | undefined)?.speakers?.find((s) => s.id === speaker)?.providerVoice; + const chosen = args.string('voice') ?? fill?.voice ?? provider; + if (!chosen) throw new VideoCommandError('Say which voice speaks: --voice popost:default-female (popost video voice list shows the voices), or register one for "' + speaker + '" first (popost video voice use).'); + const speed = args.number('speed') ?? fill?.speed; + const entry: PlannedVoice = { speaker, voice: chosen, ...(speed !== undefined ? { speed } : {}), ...(args.string('language') ? { language: args.req('language') } : {}), lines }; + const plan = (await readVoicePlan(rt, dir).catch(() => undefined)) ?? { version: 1 as const, voices: [] }; + await rt.fs.mkdir(rt.path.join(dir, 'production')); + await writeJson(rt, rt.path.join(dir, VOICE_PLAN_FILE), { version: 1, voices: [...plan.voices.filter((v) => v.speaker !== speaker), entry] }); + printJson(rt, { ok: true, plan: rt.path.join(dir, VOICE_PLAN_FILE), voice: entry, next: 'popost video inputs show ' + args.req('project') + ' [--requests <list>]: the user is shown this voice with its lines and a sample before anything is spoken. Lines changed later go into the plan again.' }); + }, + (args) => args.string('project'), +); + +const translate = command( + 'stores the user\'s-language version of a text that is sent to a model in English (a prompt of a model whose promptLanguage is "en"), or of a script in another language than the user writes: the user is shown it first, with the sent text underneath. Bound to the sent text: a changed prompt asks for it again', + { + positionals: [PROJECT], + options: [ + { flag: '--item', metavar: 'KEY', help: 'the key inputs show listed under "displayMissing" (clip:assets/hold.mp4, voice:narrator)' }, + { flag: '--text', metavar: 'TEXT', help: 'a faithful version of the sent text in the user\'s language: everything it says, nothing added' }, + { flag: '--file', metavar: 'FILE', help: 'a JSON object of key to text, for several at once' }, + { flag: '--lang', metavar: 'CODE', help: 'the language of the text; default: the project\'s (--lang of inputs show)' }, + ], + }, + async (args, rt) => { + const dir = userPath(rt, args.req('project')); + const record = await readInputs(rt, dir); + if (!record.shown) throw new VideoCommandError('Run popost video inputs show <project> first: a version in the user\'s language belongs to a text that is sent.'); + const lang = args.string('lang') ?? (await readProjectLang(rt, dir)); + if (!lang) throw new VideoCommandError('Say the language of the text with --lang <code> (the language the user is writing in).'); + const one = args.string('item'); + const map: unknown = args.string('file') ? await readUserJson(rt, args.req('file')) : one !== undefined && args.string('text') !== undefined ? { [one]: args.req('text') } : undefined; + if (!map || typeof map !== 'object' || Array.isArray(map)) throw new VideoCommandError('Give --item <key> --text "<the text>", or --file <a JSON object of key to text>.'); + const display = { ...(record.display ?? {}) }; + for (const [key, text] of Object.entries(map as Record<string, unknown>)) { + const sent = record.shown.texts[key]; + if (sent === undefined) throw new VideoCommandError('"' + key + '" is not a text of the inputs that were shown. They are: ' + Object.keys(record.shown.texts).join(', ') + '.'); + if (typeof text !== 'string' || !text.trim()) throw new VideoCommandError('The text for "' + key + '" is empty.'); + display[key] = { sent, lang, text: text.trim() }; + } + await writeInputs(rt, dir, { ...record, display }); + const data: unknown = await rt.fs.readText(rt.path.join(dir, SUMMARY_JSON)).then((t) => JSON.parse(t) as unknown, () => undefined); + const summary = data ? withDisplay(data as Summary, display) : undefined; + if (summary) await writeSummary(rt, dir, summary); + const missing = summary?.displayMissing ?? []; + await writeInputs(rt, dir, { ...record, display, shown: { ...record.shown, ...(missing.length ? { missing } : { missing: [] }) } }); + printJson(rt, { ok: true, stored: Object.keys(map), summary: rt.path.join(dir, SUMMARY_MD), displayMissing: missing, next: missing.length ? 'Still owed: ' + missing.join(', ') + '.' : 'The summary now shows the user\'s-language version first and the sent text underneath. Run popost video inputs show again to redraw the sheet\'s captions, then show the user.' }); + }, + (args) => args.string('project'), +); + +const confirm = command( + 'records the user\'s answer to the inputs that inputs show built (the sheet and the summary, shown with the cost in one message), bound to exactly what was shown: the paid commands then run; an input changed later is asked about again. Also confirms the inferred facts of the product sheet: the user is asked once', + { + positionals: [PROJECT], + options: [ + { flag: '--quote', metavar: 'TEXT', help: 'the user\'s own words agreeing to what they were shown' }, + { flag: '--unattended', metavar: 'TEXT', help: 'nobody can be asked (a batch the user commissioned to run without questions): who authorised going on, in their words. The delivery notes say that the inputs were not confirmed' }, + ], + }, + async (args, rt) => { + const dir = userPath(rt, args.req('project')); + const [quote, unattended] = [args.string('quote')?.trim(), args.string('unattended')?.trim()]; + if (!!quote === !!unattended) throw new VideoCommandError('Give --quote "<the user\'s answer>", or --unattended "<who authorised running without questions>": one of them, with the actual words.'); + const record = await readInputs(rt, dir); + const shown = record.shown; + if (!shown) throw new VideoCommandError('Nothing was shown yet: run popost video inputs show <project> --requests <list>, show the user the sheet and the summary, then record their answer.'); + const requests = shown.requests ? ((await readUserJson(rt, rt.path.resolve(dir, shown.requests))) as MaterialRequest[]) : []; + const current = await currentInputs(rt, dir, { requests, ...(shown.anchor ? { anchor: shown.anchor } : {}) }); + const changed = Object.keys({ ...shown.items, ...current.items }).filter((k) => shown.items[k] !== current.items[k]); + if (changed.length) throw new VideoCommandError('The inputs changed since they were shown (' + changed.join(', ') + '): the user\'s answer is about what they saw. Run popost video inputs show again, show the user what changed, then record their answer.'); + if (quote && shown.missing?.length) throw new VideoCommandError('The user was not shown ' + shown.missing.join(', ') + ' in their own language: write it with popost video inputs translate, run inputs show again and show them, then record their answer.'); + const by = quote ? 'user' as const : 'unattended' as const; + const at = rt.now().toISOString(); + await writeInputs(rt, dir, { ...record, confirmed: { by, quote: quote ?? unattended ?? '', at, items: shown.items } }); + // The product's inferred facts were in the same message: one answer covers them. + const sheet = (await readProductSheet(rt, dir)).sheet; + if (sheet && inferredFacts(sheet).length && confirmationOf(sheet) !== 'confirmed') await writeJson(rt, rt.path.join(dir, PRODUCT_FILE), { ...sheet, confirmation: { by, quote: quote ?? unattended ?? '', facts: inferredHash(sheet), at } }); + printJson(rt, { ok: true, confirmed: Object.keys(shown.items), by, record: rt.path.join(dir, INPUTS_FILE), ...(by === 'unattended' ? { note: 'The user did not see these inputs (unattended: ' + unattended + '). Say so in the delivery notes.' } : {}), next: 'Run the paid commands within the agreed budget (--confirm --max-credits <left>). A request, picture or voice line changed later is asked about again, alone.' }); + }, + (args) => args.string('project'), +); + +export const inputsCommands: Commands = { show, voice, translate, confirm }; diff --git a/skills/popost/src/video/commands/loop.ts b/skills/popost/src/video/commands/loop.ts index eeb5f35..de384a0 100644 --- a/skills/popost/src/video/commands/loop.ts +++ b/skills/popost/src/video/commands/loop.ts @@ -4,6 +4,7 @@ * readback (a render read back against its project), look (pictures to open), and the groups template and eval. Each * prints one JSON document; problems a caller can fix come back with exit code 2. */ +import { holdVoice } from '../inputs/record'; import type { ParsedArgs, PositionalSpec } from '../../args'; import { isFile, printJson } from '../../core/util'; import type { Runtime } from '../../runtime'; @@ -23,7 +24,7 @@ import { planMessages, planRules } from '../plan/prompt'; import { pictureUrl } from '../scene/pictures'; import { roughTokens } from '../describe/index'; import { reflowMeasure, retarget, type RetargetPlan } from '../retarget/index'; -import { speakRetarget, spokenPrice, VOICE_FILE, WORDS_FILE } from '../retarget/speak'; +import { speakRetarget, spokenLinesOf, spokenPrice, VOICE_FILE, WORDS_FILE } from '../retarget/speak'; import { transcriptionPrice } from '../speech/hosted'; import { commandTranscriber, NO_TRANSCRIBER, transcriberKind } from '../speech/index'; import { keptFor } from '../eval/readback-run'; @@ -246,6 +247,7 @@ const retargetCommand = command( return 2; } // The lines a popost.ai voice speaks are priced before anything is written: without --confirm the price is all there is. + if (args.flag('speak') && speaksHosted(rt, given.voice)) await holdVoice(rt, outDir, args.req('out'), args.flag('confirm'), { ...(given.voice ? { voice: given.voice } : {}), lines: spokenLinesOf(given, dialogue) }); const wallet = args.flag('speak') ? await walletFor(rt, args, await spokenPrice(rt, given, dialogue)) : undefined; await rt.fs.mkdir(outDir); if (askedVoice && speech && !factsOfSpeech(speech).kinds.includes('narration') && voiceWanted(given, { speak: args.flag('speak') }).length) await recordVoiceAsked(rt, outDir, askedVoice); diff --git a/skills/popost/src/video/commands/materials.ts b/skills/popost/src/video/commands/materials.ts index 993d8b8..1d2d6ae 100644 --- a/skills/popost/src/video/commands/materials.ts +++ b/skills/popost/src/video/commands/materials.ts @@ -7,8 +7,11 @@ * not one of them is blocked (reason "unplanned") until its exact key is covered by user authorization and applied * with --approve-unplanned <key>; existing commission authorization can supply that coverage. */ +import { confirmBlock, currentInputs, pendingOf, readInputs, writeInputs } from '../inputs/record'; +import { promptPolicy } from '../inputs/collect'; +import { isChinese, readProjectLang } from '../prompt-lang'; import { errorText } from '../../core/error-text'; -import { isFile, printJson } from '../../core/util'; +import { isFile, printJson, writeJson } from '../../core/util'; import { scrub } from '../../providers/secrets'; import type { Runtime } from '../../runtime'; import { readUserJson } from '../../workflow/io'; @@ -27,7 +30,7 @@ import { beatTimesOf } from '../template/speech-rules'; import { modeContextOf } from '../sound/modes'; import type { ClipMusicUse } from '../generate/clip-sound'; import { castPictureCount, productRequestProblems } from '../product/requests'; -import { readProductSheet } from '../product/sheet'; +import { confirmationOf, inferredHash, PRODUCT_FILE, readProductSheet } from '../product/sheet'; import { builtInGenerator, referenceLimits } from './product'; const errorsIn = (problems: readonly Problem[]): number => problems.filter((p) => p.level === 'error').length; @@ -35,7 +38,7 @@ const errorsIn = (problems: readonly Problem[]): number => problems.filter((p) = const PICTURE_EXT = ['.png', '.jpg', '.jpeg', '.webp']; /** --anchor-image: the caller's picture as a path in the project; a file from elsewhere is copied to assets/anchor-image.<ext>. */ -const givenAnchor = async (rt: Runtime, dir: string, given: string): Promise<AnchorPicture> => { +export const givenAnchor = async (rt: Runtime, dir: string, given: string): Promise<AnchorPicture> => { const from = userPath(rt, given); const ext = rt.path.extname(from).toLowerCase(); if (!PICTURE_EXT.includes(ext) || !(await isFile(rt, from))) throw new VideoCommandError('--anchor-image is a PNG, JPEG or WebP picture that exists; "' + given + '" is not. Give the path of the picture every clip should keep to.'); @@ -48,7 +51,7 @@ const givenAnchor = async (rt: Runtime, dir: string, given: string): Promise<Anc }; /** --character: a character of the user's popost.ai library, its picture downloaded into the project. A key never reaches the message. */ -const characterOf = async (rt: Runtime, dir: string, id: string): Promise<AnchorPicture> => { +export const characterOf = async (rt: Runtime, dir: string, id: string): Promise<AnchorPicture> => { let secrets: string[] = []; try { const found = await platform(rt); @@ -159,6 +162,7 @@ export const materials = command( { flag: '--character', metavar: 'ID', help: 'a character of your popost.ai character library as the anchor: its picture is downloaded into the project and every clip keeps that person' }, ...CREDIT_OPTIONS, { flag: '--approve-unplanned', kind: 'append', metavar: 'KEY', help: 'apply user authorization to this exact clip outside the recorded plan (key from confirm.clip); reuse existing scope/account/budget and repair coverage when valid, otherwise obtain authorization first; repeat only for covered keys' }, + { flag: '--unattended', metavar: 'TEXT', help: 'nobody can be asked (a batch the user commissioned to run without questions): who authorised going on without showing the inputs, in their words. Recorded as such; the delivery notes say so' }, { flag: '--no-wait', kind: 'flag', help: 'send every clip and picture that can be sent and return at once: they are made on popost.ai at the same time while you do the other steps; "pending" lists them. Run the same command again to pick them up (and to send the clips queued after them); nothing is paid twice. Without it the command sends them all and waits until they are there' }, ], }, @@ -192,11 +196,33 @@ export const materials = command( const wallet = max !== undefined ? new Wallet(max) : undefined; // Without a budget the built-in generator only prices the list; anything else makes files now. const pricedOnly = wallet === undefined && builtInGenerator(rt) && !rt.env.POPOST_GEN_MAX_CREDITS && !/\s--yes\b/.test(rt.env.POPOST_GEN_CMD ?? ''); + // Before anything is paid for the user has seen what is sent (inputs/record.ts): every file still to make, as it stands. + if (!pricedOnly && Array.isArray(requests) && !errorsIn(sheet.problems)) { + const current = await currentInputs(rt, dir, { requests, ...(picture ? { anchor: picture.file } : {}) }); + const needed = [...current.toMake, ...(picture && current.toMake.length ? ['anchor'] : [])]; + const unattended = args.string('unattended')?.trim(); + let record = await readInputs(rt, dir); + if (unattended && pendingOf(record, current, needed).length) { + record = { ...record, confirmed: { by: 'unattended', quote: unattended, at: rt.now().toISOString(), items: { ...(record.confirmed?.items ?? {}), ...Object.fromEntries(needed.map((k) => [k, current.items[k] ?? ''])) } } }; + await writeInputs(rt, dir, record); + } + // Nobody to ask: what was read from the product picture goes unconfirmed too, and is said at delivery. + if (unattended && sheet.sheet && confirmationOf(sheet.sheet) === 'open') + await writeJson(rt, rt.path.join(dir, PRODUCT_FILE), { ...sheet.sheet, confirmation: { by: 'unattended', quote: unattended, facts: inferredHash(sheet.sheet), at: rt.now().toISOString() } }); + const pending = pendingOf(record, current, needed); + if (pending.length) { + printJson(rt, { ok: false, ...confirmBlock(rt, dir, record, pending, args.req('out')) }); + return CONFIRM_EXIT; + } + } const noWait = args.flag('no-wait'); + const lang = await readProjectLang(rt, dir); + // Only a Chinese project asks how the model takes prompts: every other language gets the English sentences either way. + const policy = isChinese(lang) ? (await promptPolicy(rt)).policy : 'user'; const musicTrack = await hasMusicTrack(rt, dir); const r = await allRuns(rt, () => makeMaterials(rt, { requests, dir, generator: payingPending(budgeted(generator, wallet, args.list('approve-unplanned')), wallet), plan: wallet !== undefined, submitOnly: true, - product: { ...limits, paying: !pricedOnly }, + product: { ...limits, paying: !pricedOnly }, policy, // The template's beats give spoken lines their times; a video with a music track of its own gets clips without music. ...(times ? { times } : {}), ...(modes ? { modes } : {}), music: musicTrack, ...(off ? { anchor: false } : args.flag('anchor') ? { anchor: true } : {}), ...(picture ? { picture } : {}), diff --git a/skills/popost/src/video/commands/shared.ts b/skills/popost/src/video/commands/shared.ts index ac7abe5..7de1c8f 100644 --- a/skills/popost/src/video/commands/shared.ts +++ b/skills/popost/src/video/commands/shared.ts @@ -3,6 +3,7 @@ * (or the model driving the CLI) can fix into `{"ok": false, "error": …}` with exit code 2. Anything else is a bug and * is left to the generic handler in `main.ts` (exit code 1). */ +import { InputsPending } from '../inputs/record'; import type { OptionSpec, ParsedArgs, PositionalSpec } from '../../args'; import { fail, printJson } from '../../core/util'; import { BrowserUnavailableError } from '../../render/browser'; @@ -56,6 +57,10 @@ export const command = ( printJson(rt, { ok: false, confirm: error.confirm, next: error.next }); return CONFIRM_EXIT; } + if (error instanceof InputsPending) { + printJson(rt, { ok: false, ...error.block }); + return CONFIRM_EXIT; + } if (!expected(error)) throw error; return fail(rt, failureText(error)); } finally { diff --git a/skills/popost/src/video/commands/template.ts b/skills/popost/src/video/commands/template.ts index f5497b7..be57eb0 100644 --- a/skills/popost/src/video/commands/template.ts +++ b/skills/popost/src/video/commands/template.ts @@ -13,7 +13,9 @@ import { budgetProblems, paceBudgets } from '../plan/ask'; import { repairMessage } from '../plan/prompt'; import { seeShots } from '../plan/see'; import type { RetargetPlan } from '../retarget/index'; -import { spokenPrice, VOICE_FILE, WORDS_FILE } from '../retarget/speak'; +import { spokenLinesOf, spokenPrice, VOICE_FILE, WORDS_FILE } from '../retarget/speak'; +import { holdVoice } from '../inputs/record'; +import { speaksHosted } from '../voice/index'; import { CREDIT_OPTIONS, walletFor } from './credits'; import type { Transcript } from '../speech/types'; import { checkFill } from '../template/check'; @@ -264,7 +266,10 @@ const fill = command( ]; if (errorsIn(before).length) return refused(rt, 'The fill has ' + errorsIn(before).length + ' error(s); nothing was written. Correct them and run it again.', before); // The lines a popost.ai voice speaks are priced before anything is written: without --confirm the price is all there is. - const wallet = speak ? await walletFor(rt, args, await spokenPrice(rt, plan, await dialogueOf(rt, pkg, plan, assetsDir ?? outDir, voiceAsked))) : undefined; + const dialogue = speak ? await dialogueOf(rt, pkg, plan, assetsDir ?? outDir, voiceAsked) : []; + // A popost.ai voice speaks only the voice and the lines the user confirmed among the inputs (inputs/record.ts). + if (speak && speaksHosted(rt, plan.voice)) await holdVoice(rt, outDir, args.req('out'), args.flag('confirm'), { ...(plan.voice ? { voice: plan.voice } : {}), lines: spokenLinesOf(plan, dialogue) }); + const wallet = speak ? await walletFor(rt, args, await spokenPrice(rt, plan, dialogue)) : undefined; const r = await fillPackage(rt, pkg, { fill: plan, outDir, speak, ...(args.flag('keep-length') ? { hold: true } : {}), ...(args.flag('keep-pauses') ? { keepPauses: true } : {}), ...(fitTempo ? { fitTempo } : {}), ...(assetsDir ? { assetsDir } : {}), ...(wallet ? { wallet } : {}), ...(voiceAsked ? { voiceAsked } : {}) }); if (!r.project) return refused(rt, 'The fill has ' + errorsIn(r.problems).length + ' error(s); nothing was written. Correct them and run it again.', r.problems); const wantsVoice = voiceWanted(plan, { speak }).length > 0; diff --git a/skills/popost/src/video/commands/voice-profile.ts b/skills/popost/src/video/commands/voice-profile.ts index 2af69d4..e0427f2 100644 --- a/skills/popost/src/video/commands/voice-profile.ts +++ b/skills/popost/src/video/commands/voice-profile.ts @@ -1,3 +1,4 @@ +import { holdVoice, InputsPending } from '../inputs/record'; import { printJson } from '../../core/util'; import { downloadVoiceAudio, hostedVoicePage, quoteHostedVoice, selectHostedVoice, speechPrice } from '../voice/hosted'; import { PriceNotAgreed } from '../wallet'; @@ -33,10 +34,11 @@ const speak=command('generate final dialogue or voice-over from the same registe try{ const project=userPath(rt,args.req('project'));const profile=await voiceProfile(rt,project,args.req('speaker')); const hosted=profile?.providerVoice?.startsWith('popost:'); + if(hosted)await holdVoice(rt,project,args.req('project'),args.flag('confirm'),{speaker:args.req('speaker'),voice:profile!.providerVoice!,lines:[args.req('text')]}); // A popost.ai voice is priced first: without --confirm the price is printed with exit code 3 and nothing is charged. const wallet=hosted?await walletFor(rt,args,await speechPrice(rt,[args.req('text')],profile!.providerVoice)):undefined; const said=await speakProfile(rt,project,args.req('speaker'),args.req('text'),userPath(rt,args.req('out')),wallet);printJson(rt,{ok:true,audio:args.req('out'),receipt:args.req('out')+'.voice.json',...(said.words?{words:args.req('out')+'.words.json'}:{}),chargedCredits:wallet?.spent??0});} - catch(e){if(e instanceof PriceNotAgreed||e instanceof VideoCommandError)throw e;throw new VideoCommandError(String(e));} + catch(e){if(e instanceof PriceNotAgreed||e instanceof VideoCommandError||e instanceof InputsPending)throw e;throw new VideoCommandError(String(e));} },(args)=>args.string('project')); const complete=command('import real speech from the host voice service and bind it to the shared speaker profile',{ positionals:[{name:'project',help:'project directory'}],options:[ diff --git a/skills/popost/src/video/generate/cloud-image.ts b/skills/popost/src/video/generate/cloud-image.ts index aa07b38..5d73515 100644 --- a/skills/popost/src/video/generate/cloud-image.ts +++ b/skills/popost/src/video/generate/cloud-image.ts @@ -23,7 +23,7 @@ import { sleep } from '../../providers/time'; import type { Runtime } from '../../runtime'; import { runFfmpegOk } from '../media/ffmpeg'; import { agreeToPrice, GenerateError, requestKey, RETRY_HINT, type CloudSettings } from './cloud'; -import { StillMaking, type GenerateRequest } from './index'; +import { StillMaking, type GenerateRequest, type PriceToConfirm } from './index'; const PICTURE_TYPES: Readonly<Record<string, string>> = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp' }; /** How often a picture that is being made is looked at while a call waits for it. */ @@ -136,6 +136,15 @@ const pickUp = async (rt: Runtime, s: CloudSettings, provider: PopostProvider, s throw new GenerateError('The picture is still being made on popost.ai after ' + Math.round(GENERATION_TIMEOUT_SEC / 60) + ' minutes (task ' + (sent.task ?? taskId) + '). Run the same command again later to pick it up: it is not paid twice.'); }; +/** What a picture would cost (POST /images/quote, free): nothing is sent to a model and nothing is charged. */ +export const pricePicture = async (rt: Runtime, s: CloudSettings, config: JsonRecord, request: GenerateRequest): Promise<PriceToConfirm> => { + const provider = new PopostProvider(rt, { config: s.imageModel ? withModel(config, s.imageModel) : config }); + const aspect = request.aspect ?? '1:1'; + const refs = await Promise.all((request.images ?? []).map(async (value) => ({ kind: 'local', value, sha256: await sha256File(rt, value) }))); + const quote = (await provider.quote({ model: s.imageModel ?? null, aspect, count: 1, refs })) as PopostQuote; + return { credits: quote.totalCredits, model: quote.model, aspectRatio: aspect, balance: quote.balance }; +}; + /** Makes the picture a request asks for at out, on popost.ai; resolves with what it cost and what this call charged. */ export const makePicture = async (rt: Runtime, s: CloudSettings, config: JsonRecord, request: GenerateRequest, out: string): Promise<MadePicture> => { if (request.firstFrame !== undefined || request.lastFrame !== undefined) throw new GenerateError('Only a clip starts from a frame; a picture takes reference pictures ("images"). Nothing was sent.', 2); diff --git a/skills/popost/src/video/generate/cloud.ts b/skills/popost/src/video/generate/cloud.ts index ed98e11..b27e733 100644 --- a/skills/popost/src/video/generate/cloud.ts +++ b/skills/popost/src/video/generate/cloud.ts @@ -558,6 +558,24 @@ export const makeClip = async (rt: Runtime, client: PopostClient, s: CloudSettin return { ...(typeof done.credits === 'number' ? { credits: done.credits } : {}), chargedCredits: charged, key }; }; +/** + * What a clip would cost, and nothing else: its references are uploaded as for any quote (free), the request is priced + * (POST /videos/quote), no task is looked up, made or waited for, and nothing is charged whatever the settings say. + */ +export const priceClip = async (rt: Runtime, client: PopostClient, s: CloudSettings, request: GenerateRequest): Promise<PriceToConfirm> => { + const seconds = request.seconds ?? DEFAULT_SECONDS; + const refs = await readReferences(rt, request); + const facts = request.audio === false || refs.some((r) => r.kind === 'audio') ? await modelFacts(client, s.videoModel) : undefined; + checkReferenceSounds(refs, facts); + const silent = request.audio === false && facts?.audioOptional === true; + // A record of its own: pricing never touches the record of the clip that is made later. + const key = 'price-' + sha256(JSON.stringify([s.videoModel ?? null, s.resolution ?? null, seconds, request.aspect ?? null, silent, refs.map((r) => [r.kind, r.frame ?? '', r.sha256])])); + const file = recordFile(rt, key); + const uploaded = await ensureUploads(rt, client, refs, await readRecord(rt, file, key), file); + const sent = await ensureQuote(rt, client, specOf(s, request, seconds, refs, uploaded, silent), uploaded, file); + return (sent.quote as Quote).price; +}; + /** GET /videos/models: the models a clip can be made with, and the one used when POPOST_VIDEO_MODEL is unset. */ export const listModels = async (client: PopostClient): Promise<JsonRecord> => { const data = await client.request('GET', '/videos/models'); diff --git a/skills/popost/src/video/inputs/collect.ts b/skills/popost/src/video/inputs/collect.ts new file mode 100644 index 0000000..140e536 --- /dev/null +++ b/skills/popost/src/video/inputs/collect.ts @@ -0,0 +1,205 @@ +/** + * What `popost video inputs show` gathers, without paying: every request of the list as materials would send it (the + * same code composes it: makeMaterials with a generator that records the request and answers with its price instead + * of making anything), the product pictures as they are sent, the cast with its pictures, and the voices with their + * lines, a sample and a price. Prices come from the platform's free quotes; a generator of the user's own has none. + */ +import { errorText } from '../../core/error-text'; +import { isRecord } from '../../providers/base'; +import { scrub } from '../../providers/secrets'; +import type { Runtime } from '../../runtime'; +import { platform } from '../commands/generate'; +import { builtInGenerator } from '../commands/product'; +import { readCast } from '../generate/cast'; +import { cloudSettings, priceClip } from '../generate/cloud'; +import { pricePicture } from '../generate/cloud-image'; +import { ConfirmNeeded, inputKey, makeMaterials, type AnchorPicture, type GenerateRequest, type Generator, type MaterialRequest, type PriceToConfirm } from '../generate/index'; +import type { BeatTimes } from '../generate/dialogue'; +import { accountBalance } from '../hosted-api'; +import { readProductSheet } from '../product/sheet'; +import { policyOf, type PromptPolicy } from '../prompt-lang'; +import type { Problem } from '../types'; +import { downloadVoiceAudio, quoteHostedVoice, selectHostedVoice, speechPrice } from '../voice/hosted'; +import { speaksHosted } from '../voice/index'; +import { readVoices } from '../voice/profile'; +import { INPUTS_DIR, readVoicePlan, voiceKey, type PlannedVoice } from './record'; + +/** A picture that goes to a model with a request, and what it is there. */ +export interface SentPicture { file: string; role: 'product' | 'cast' | 'reference' | 'first frame' | 'last frame' | 'anchor'; name: string } + +export interface ShownClip { + key: string; + kind: 'video' | 'image'; + file: string; + /** The request's own words, and the whole prompt as it is sent (product block, cast and sound sentences included). */ + what: string; + prompt: string; + seconds?: number; + aspect?: string; + model?: string; + resolution?: string; + /** null: no price is known (a generator of the user's own, or the quote could not be read: priceNote says). */ + credits: number | null; + priceNote?: string; + pictures: SentPicture[]; + sounds: string[]; + clips: string[]; + products: string[]; + cast: string[]; + notes: string[]; +} + +export interface ShownVoice { + key: string; + speaker: string; + voice: string; + /** The voice on the platform, when it is one. */ + id?: string; + name?: string; + language?: string; + speed: number; + lines: string[]; + credits: number | null; + priceNote?: string; + /** A recording the user can hear, in the project, and where it comes from; none when there is none without paying. */ + sample?: { file: string; from: string }; + /** No free sample: the cheapest paid one, one sentence, with its price, for the user to ask for. */ + paidSample?: { text: string; credits: number | null; command: string }; + note?: string; +} + +export interface Gathered { + problems: Problem[]; + policy: PromptPolicy; + model?: string; + products: { key: string; id: string; what: string; pictures: { file: string; original?: string; crop?: string; face: string }[]; confirm?: string }[]; + cast: { key: string; id: string; description: string; picture?: string; note?: string }[]; + anchor?: { file: string; note: string }; + clips: ShownClip[]; + kept: string[]; + voices: ShownVoice[]; + balance?: number; + notes: string[]; +} + +const oneLine = (text: string): string => text.replace(/\s*\n\s*/g, ' ').trim(); +const rel = (rt: Runtime, dir: string, file: string): string => rt.path.relative(rt.path.resolve(dir), rt.path.resolve(dir, file)).split(rt.path.sep).join('/'); + +/** How the model in use takes prompts, from the platform's list; "user" when it does not say or cannot be read. */ +export const promptPolicy = async (rt: Runtime): Promise<{ policy: PromptPolicy; model?: string }> => { + if (!builtInGenerator(rt)) return { policy: 'user' }; + try { + const data = await (await platform(rt)).client.request('GET', '/videos/models'); + const wanted = rt.env.POPOST_VIDEO_MODEL?.trim() || (isRecord(data) && typeof data.default === 'string' ? data.default : undefined); + const model = isRecord(data) && Array.isArray(data.models) ? data.models.find((m) => isRecord(m) && m.id === wanted) : undefined; + return { policy: policyOf(model), ...(wanted ? { model: wanted } : {}) }; + } catch { + return { policy: 'user' }; + } +}; + +interface Recorded { kind: 'video' | 'image'; request: GenerateRequest; price?: PriceToConfirm; priceNote?: string } + +/** A generator that makes nothing: it keeps each request as sent and answers with the price a free quote gives. */ +const recorder = (rt: Runtime, seen: Map<string, Recorded>): Generator => ({ + make: async (kind, request, _out, env = {}) => { + const entry: Recorded = { kind, request }; + seen.set(env.POPOST_GEN_INPUT ?? '', entry); + if (!builtInGenerator(rt)) entry.priceNote = 'not known here: the generator is a tool of your own (POPOST_GEN_CMD)'; + else { + let secrets: string[] = []; + try { + const found = await platform(rt); + secrets = found.secrets; + const s = cloudSettings(rt, { yes: false }); + entry.price = kind === 'video' ? await priceClip(rt, found.client, s, request) : await pricePicture(rt, s, found.config, request); + } catch (e) { + entry.priceNote = 'could not be read (' + oneLine(scrub(errorText(e), secrets)).slice(0, 200) + '); popost video materials without --confirm prices the list'; + } + } + throw new ConfirmNeeded(entry.price ?? { credits: 0 }, 'priced for the input sheet; nothing was made'); + }, +}); + +const sentence = (text: string): string => (/^[^.!?。!?]{1,120}[.!?。!?]?/.exec(text.trim())?.[0] ?? text.trim().slice(0, 120)).trim(); + +const voiceOf = async (rt: Runtime, dir: string, v: PlannedVoice): Promise<ShownVoice> => { + const lines = v.lines.map((l) => l.trim()).filter(Boolean); + const base: ShownVoice = { key: voiceKey(v.speaker), speaker: v.speaker, voice: v.voice, ...(v.language ? { language: v.language } : {}), speed: v.speed ?? 1, lines, credits: null }; + const registered = (await readVoices(rt, dir).catch(() => undefined))?.speakers.find((s) => s.id === v.speaker); + const own = registered && (await rt.fs.stat(rt.path.resolve(dir, registered.reference))) ? { file: registered.reference, from: registered.providerVoice ? 'the platform\'s own preview of this voice, kept when the voice was chosen' : 'the recording the user registered for this speaker' } : undefined; + if (!speaksHosted(rt, v.voice)) return { ...base, ...(own ? { sample: own } : {}), priceNote: 'not known here: the lines are spoken by a tool of your own', ...(own ? {} : { note: 'No sample of this voice can be had without speaking a line: the user hears it first in the result of your own speaker.' }) }; + try { + const voice = await selectHostedVoice(rt, v.voice); + const items = lines.length ? await speechPrice(rt, lines, v.voice, v.speed ?? 1) : []; + const shown: ShownVoice = { ...base, id: voice.id, name: voice.name, language: v.language ?? voice.language, credits: items.reduce((n, i) => n + i.credits, 0), ...(lines.length ? {} : { priceNote: 'no lines in the plan yet' }) }; + if (own) return { ...shown, sample: own }; + if (voice.sampleUrl) { + const file = INPUTS_DIR + '/voice-' + v.speaker.replace(/[^A-Za-z0-9_-]/g, '_') + '-sample.wav'; + await rt.fs.mkdir(rt.path.join(dir, INPUTS_DIR)); + const got = await downloadVoiceAudio(rt, voice.sampleUrl, rt.path.join(dir, file)).then(() => true, () => false); + if (got) return { ...shown, sample: { file, from: 'the platform\'s own preview of this voice (free)' } }; + } + const text = sentence(lines[0] ?? ''); + const credits = text ? await quoteHostedVoice(rt, voice.id, text).catch(() => null) : null; + return { ...shown, paidSample: { text, credits, command: 'popost video voice quote --voice ' + voice.id + ' --text "<one sentence>"' }, note: 'This voice has no free preview. Nothing was spoken: a sample costs credits, and the user may ask for one.' }; + } catch (e) { + return { ...base, ...(own ? { sample: own } : {}), priceNote: 'could not be read (' + oneLine(errorText(e)).slice(0, 160) + ')', note: 'The voice could not be looked up on the platform; popost video voice list shows the voices.' }; + } +}; + +/** Everything a paid run of this list would send, and what it would cost; nothing is made or charged. */ +export const gather = async (rt: Runtime, dir: string, o: { requests: MaterialRequest[]; picture?: AnchorPicture; anchor?: boolean; times?: BeatTimes; music?: boolean; lang?: string }): Promise<Gathered> => { + const { policy, model } = o.requests.length ? await promptPolicy(rt) : { policy: 'user' as const }; + const seen = new Map<string, Recorded>(); + const report = o.requests.length + ? await makeMaterials(rt, { requests: o.requests, dir, generator: recorder(rt, seen), plan: false, submitOnly: true, product: { paying: false }, policy, ...(o.lang ? { lang: o.lang } : {}), ...(o.times ? { times: o.times } : {}), ...(o.music !== undefined ? { music: o.music } : {}), ...(o.anchor !== undefined ? { anchor: o.anchor } : {}), ...(o.picture ? { picture: o.picture } : {}) }) + : undefined; + // The recorder's own answer is not a problem of the list: every file "waits for its price". + const problems = (report?.problems ?? []).filter((p) => !(p.level === 'error' && /^It was not made: it costs/.test(p.message))); + const sheet = (await readProductSheet(rt, dir)).sheet; + const cast = await readCast(rt, dir).catch(() => undefined); + const productPictures = new Map((sheet?.products ?? []).flatMap((p) => p.pictures.map((x) => [x.file, p.id] as const))); + const castPictures = new Map((cast?.roles ?? []).flatMap((r) => (r.image ? [[r.image, r.id] as const] : []))); + const clips: ShownClip[] = []; + const kept: string[] = []; + for (const r of o.requests) { + const key = inputKey(r.file); + const sent = seen.get(key); + if (!sent) { if (await rt.fs.stat(rt.path.resolve(dir, r.file))) kept.push(r.file); continue; } + const q = sent.request; + const anchor = o.picture?.file; + const pictures: SentPicture[] = (q.images ?? []).map((f, i) => { + const file = rel(rt, dir, f); + const role = productPictures.has(file) ? 'product' : castPictures.has(file) ? 'cast' : file === anchor ? 'anchor' : 'reference'; + return { file, role, name: '@image' + (i + 1) + (role === 'product' ? ' ' + productPictures.get(file) : role === 'cast' ? ' ' + castPictures.get(file) : '') }; + }); + for (const [k, role] of [['firstFrame', 'first frame'], ['lastFrame', 'last frame']] as const) if (r[k]) pictures.push({ file: r[k] as string, role, name: role }); + const notes = [ + ...(r.continues ? ['starts from the last frame of ' + r.continues + ', taken once that clip is made'] : []), + ...(report?.materials.find((m) => m.file === r.file)?.waiting ? ['a frame of the first clip of the list is added as its last reference picture once that clip is made, with a sentence that points at it'] : []), + ]; + clips.push({ + key, kind: sent.kind, file: r.file, what: r.prompt, prompt: q.prompt, + ...(q.seconds ?? sent.price?.seconds ? { seconds: q.seconds ?? sent.price?.seconds } : {}), ...(q.aspect ?? sent.price?.aspectRatio ? { aspect: q.aspect ?? sent.price?.aspectRatio } : {}), + ...(sent.price?.model ? { model: sent.price.model } : {}), ...(sent.price?.resolution ? { resolution: sent.price.resolution } : {}), + credits: sent.price ? sent.price.credits : null, ...(sent.priceNote ? { priceNote: sent.priceNote } : {}), + pictures, sounds: (q.audios ?? []).map((f) => rel(rt, dir, f)), clips: (q.videos ?? []).map((f) => rel(rt, dir, f)), products: r.products ?? [], cast: r.cast ?? [], notes, + }); + } + const used = new Set(o.requests.flatMap((r) => r.cast ?? [])); + const plan = await readVoicePlan(rt, dir); + const voices = await Promise.all((plan?.voices ?? []).map((v) => voiceOf(rt, dir, v))); + const priced = [...seen.values()].map((s) => s.price?.balance).find((b): b is number => typeof b === 'number'); + const balance = priced ?? (voices.some((v) => v.id) ? await accountBalance(rt) : undefined); + return { + problems, policy, ...(model ? { model } : {}), + products: (sheet?.products ?? []).map((p) => ({ + key: 'product:' + p.id, id: p.id, what: p.what.value, + pictures: p.pictures.map((x) => ({ file: x.file, ...(x.original ? { original: x.original.file } : {}), ...(x.crop ? { crop: x.crop.x + ',' + x.crop.y + ',' + x.crop.width + ',' + x.crop.height } : {}), face: 'no face, looked at by the ' + (x.face?.by ?? 'agent') })), + })), + cast: (cast?.roles ?? []).filter((r) => !o.requests.length || used.has(r.id)).map((r) => ({ key: 'cast:' + r.id, id: r.id, description: r.description, ...(r.image ? { picture: r.image } : { note: 'no picture: this person is described in the prompt of the one clip they are in' }) })), + ...(o.picture ? { anchor: { file: o.picture.file, note: o.picture.person ? 'the character every clip keeps' + (o.picture.person.name ? ' (' + o.picture.person.name + ')' : '') : 'the picture every clip keeps to' } } : {}), + clips, kept, voices, ...(balance !== undefined ? { balance } : {}), notes: report?.notes ?? [], + }; +}; diff --git a/skills/popost/src/video/inputs/record.ts b/skills/popost/src/video/inputs/record.ts new file mode 100644 index 0000000..b741542 --- /dev/null +++ b/skills/popost/src/video/inputs/record.ts @@ -0,0 +1,175 @@ +/** + * What the user confirms before anything is paid for: the inputs of a video. Before the first paid generation the + * user is shown, in one message, the cost and everything that was prepared as the input of a model: every prompt as it + * will be sent, the product picture exactly as it will be sent, the cast's pictures, the frames and references of + * each clip, and the voice with its script (popost video inputs show). Their answer is recorded with a hash of each + * item that was shown (production/inputs.json). Paid work on an item that was not shown, or that changed since, is + * refused with exit code 3 and a `confirm` block until the user has seen it: a changed request, reference picture, + * product picture, cast picture or voice plan asks again for that item only. + * + * An item's hash is built from what decides the text and the files that are sent: the request as written with the + * model and resolution of the environment, the bytes of every file it names, the product's pictures, facts and block, + * each cast role with its picture, the voice with its speed and lines. It needs no network, so every paid command + * can check it. + */ +import { sha256, writeJson } from '../../core/util'; +import { isRecord } from '../../providers/base'; +import type { Runtime } from '../../runtime'; +import { requestHash } from '../generate/approved'; +import { inputKey, type MaterialRequest } from '../generate/index'; +import { PRODUCT_FILE, inferredFacts, productBody, readProductSheet, type ProductSheet } from '../product/sheet'; + +export const INPUTS_FILE = 'production/inputs.json'; +export const VOICE_PLAN_FILE = 'production/voice-plan.json'; +/** Where the input sheet, the summary and the voice samples go. */ +export const INPUTS_DIR = 'production/inputs'; + +/** One voice of the video: who speaks, in which voice, how fast, and the lines it will say. */ +export interface PlannedVoice { speaker: string; voice: string; speed?: number; language?: string; lines: string[] } +export interface VoicePlan { version: 1; voices: PlannedVoice[] } + +/** A text shown to the user in their language beside the text that is sent; sent: the hash of the text it renders. */ +export interface DisplayText { sent: string; lang: string; text: string } + +export interface InputsRecord { + version: 1; + /** What the last `inputs show` built: the items with their hashes, the sent texts' hashes, and where the list was read from. */ + shown?: { at: string; requests?: string; anchor?: string; lang?: string; items: Record<string, string>; texts: Record<string, string>; sheets: string[]; summary: string; missing?: string[] }; + /** The user's answer (or who authorised going on unattended), with the items it was given for. */ + confirmed?: { by: 'user' | 'unattended'; quote: string; at: string; items: Record<string, string> }; + display?: Record<string, DisplayText>; +} + +export const readInputs = async (rt: Runtime, dir: string): Promise<InputsRecord> => { + const data: unknown = await rt.fs.readText(rt.path.join(dir, INPUTS_FILE)).then((t) => JSON.parse(t) as unknown, () => undefined); + return isRecord(data) && data.version === 1 ? (data as unknown as InputsRecord) : { version: 1 }; +}; + +export const writeInputs = async (rt: Runtime, dir: string, record: InputsRecord): Promise<void> => { + await rt.fs.mkdir(rt.path.join(dir, 'production')); + await writeJson(rt, rt.path.join(dir, INPUTS_FILE), record); +}; + +export const readVoicePlan = async (rt: Runtime, dir: string): Promise<VoicePlan | undefined> => { + const text = await rt.fs.readText(rt.path.join(dir, VOICE_PLAN_FILE)).catch(() => undefined); + if (text === undefined) return undefined; + let data: unknown; + try { data = JSON.parse(text) as unknown; } catch { data = undefined; } + const ok = isRecord(data) && Array.isArray(data.voices) && data.voices.every((v) => isRecord(v) && typeof v.speaker === 'string' && typeof v.voice === 'string' && Array.isArray(v.lines) && v.lines.every((l) => typeof l === 'string')); + if (!ok) throw new Error(VOICE_PLAN_FILE + ' is { "version": 1, "voices": [{ "speaker", "voice", "speed"?, "language"?, "lines": ["..."] }] }; write it with popost video inputs voice.'); + return data as unknown as VoicePlan; +}; + +const tidy = (text: string): string => text.replace(/\s+/g, ' ').trim(); +const hashOf = (value: unknown): string => sha256(JSON.stringify(value)); +const bytesHash = (rt: Runtime, dir: string, file: string): Promise<string | null> => rt.fs.readFile(rt.path.resolve(dir, file)).then(sha256, () => null); + +export const voiceKey = (speaker: string): string => 'voice:' + speaker; +export const voiceHash = (v: PlannedVoice): string => hashOf([v.voice, v.speed ?? 1, v.language ?? null, v.lines.map(tidy).filter(Boolean)]); + +const productHash = (sheet: ProductSheet, id: string): string | null => { + const p = sheet.products.find((x) => x.id === id); + return p ? hashOf([p.pictures.map((x) => [x.file, x.sha256, x.original?.sha256 ?? null]), (p.stills ?? []).map((x) => x.sha256), productBody(p), inferredFacts(sheet).filter((f) => f.product === id).map((f) => [f.fact, f.value])]) : null; +}; + +/** The cast of a project as written (cast.json), without what a strict re-make adds to it: enough to tell a change. */ +const castRoles = async (rt: Runtime, dir: string): Promise<Record<string, unknown>[]> => { + const data: unknown = await rt.fs.readText(rt.path.join(dir, 'cast.json')).then((t) => JSON.parse(t) as unknown, () => undefined); + return isRecord(data) && Array.isArray(data.roles) ? data.roles.filter(isRecord) : []; +}; + +export interface CurrentInputs { + /** Every item of the project as it stands, by key, with its hash. */ + items: Record<string, string>; + /** The keys of the requested files that do not exist yet: what a paid run would make. */ + toMake: string[]; +} + +const FILES = ['images', 'videos', 'audios'] as const; + +/** + * The inputs of a project as they stand: its products, cast and voices, the anchor picture when one is given, and + * every request of the list (when one is given) with all it depends on. + */ +export const currentInputs = async (rt: Runtime, dir: string, o: { requests?: readonly MaterialRequest[]; anchor?: string } = {}): Promise<CurrentInputs> => { + const items: Record<string, string> = {}; + const sheet = (await readProductSheet(rt, dir)).sheet; + for (const p of sheet?.products ?? []) items['product:' + p.id] = productHash(sheet as ProductSheet, p.id) ?? ''; + const roles = await castRoles(rt, dir); + for (const r of roles) if (typeof r.id === 'string') items['cast:' + r.id] = hashOf([r, typeof r.image === 'string' ? await bytesHash(rt, dir, r.image) : null]); + for (const v of (await readVoicePlan(rt, dir).catch(() => undefined))?.voices ?? []) items[voiceKey(v.speaker)] = voiceHash(v); + const anchor = o.anchor ? await bytesHash(rt, dir, o.anchor) : null; + if (o.anchor) items.anchor = hashOf([anchor]); + const toMake: string[] = []; + for (const r of (Array.isArray(o.requests) ? o.requests : []) as MaterialRequest[]) { + if (!r || typeof r !== 'object' || typeof r.file !== 'string') continue; + const named = [...FILES.flatMap((k) => (Array.isArray(r[k]) ? (r[k] as string[]) : [])), r.firstFrame, r.lastFrame].filter((f): f is string => typeof f === 'string'); + const files = await Promise.all(named.map(async (f) => [f, await bytesHash(rt, dir, f)])); + const key = inputKey(r.file); + items[key] = hashOf([requestHash(rt, r), files, (r.products ?? []).map((id: string) => items['product:' + id] ?? null), (r.cast ?? []).map((id: string) => items['cast:' + id] ?? null), anchor]); + if (!(await rt.fs.stat(rt.path.resolve(dir, r.file)))) toMake.push(key); + } + return { items, toMake }; +}; + +/** The keys among `needed` whose item was not confirmed as it stands. */ +export const pendingOf = (record: InputsRecord, current: CurrentInputs, needed: readonly string[]): string[] => + needed.filter((k) => current.items[k] === undefined || record.confirmed?.items[k] !== current.items[k]); + +/** The `confirm` block of exit code 3: what to show the user and how to record their answer. */ +export const confirmBlock = (rt: Runtime, dir: string, record: InputsRecord, pending: readonly string[], project: string): { confirm: Record<string, unknown>; next: string } => { + const shown = record.shown; + const fresh = shown !== undefined && pending.every((k) => shown.items[k] !== undefined); + const again = 'popost video inputs show ' + project + (shown?.requests ? ' --requests ' + shown.requests : ' --requests <the request list>'); + return { + confirm: { + reason: 'inputs', pending: [...pending], + ...(fresh ? { sheets: shown.sheets.map((f) => rt.path.join(dir, f)), summary: rt.path.join(dir, shown.summary) } : {}), + ...(record.confirmed ? { confirmedBefore: Object.keys(record.confirmed.items).filter((k) => !pending.includes(k)) } : {}), + }, + next: 'Nothing was made or charged: the user has not confirmed these inputs as they stand (' + pending.join(', ') + '). ' + + (fresh ? '' : 'Build the input sheet and the summary first: ' + again + '. ') + + 'Show the user the input sheet picture(s) and the summary in ONE message together with the cost (model, resolution, seconds, aspect ratio, count, credits, balance) and wait for their answer; then popost video inputs confirm ' + project + ' --quote "<the user\'s words>" and run this command again. Only for a batch the user commissioned to run with nobody to ask: popost video inputs confirm ' + project + ' --unattended "<who authorised that, in their words>". Never write an answer the user did not give.', + }; +}; + +/** Whether a project has anything that makes the paid voice commands wait for the user: inputs that were shown, a voice plan, or a product sheet. */ +export const gatesVoice = async (rt: Runtime, dir: string): Promise<boolean> => + (await Promise.all([INPUTS_FILE, VOICE_PLAN_FILE, PRODUCT_FILE].map((f) => rt.fs.stat(rt.path.join(dir, f))))).some(Boolean); + +/** + * What stands between a paid voice command and its work: undefined when the voice (and the lines, when given) are in + * the voice plan the user confirmed, else the pending keys and why. A project that never showed inputs, has no voice + * plan and no product sheet is not held (a video that is only narrated). + */ +export const voicePending = async (rt: Runtime, dir: string, o: { voice?: string; speaker?: string; lines?: readonly string[] }): Promise<{ pending: string[]; why: string } | undefined> => { + if (!(await gatesVoice(rt, dir))) return undefined; + const plan = await readVoicePlan(rt, dir); + const entry = plan?.voices.find((v) => (o.speaker !== undefined && v.speaker === o.speaker) || (o.voice !== undefined && v.voice === o.voice)) ?? (o.voice === undefined && o.speaker === undefined && plan?.voices.length === 1 ? plan.voices[0] : undefined); + const what = o.voice ?? o.speaker ?? 'the default voice'; + if (!entry) return { pending: [voiceKey(o.speaker ?? '?')], why: 'The voice ' + what + ' is not in the voice plan (' + VOICE_PLAN_FILE + '), so the user was not shown who speaks. Write it with popost video inputs voice <project> --speaker <id> --voice ' + (o.voice ?? '<voice>') + ' --line "<each line>" (or --fill <fill.json>).' }; + const key = voiceKey(entry.speaker); + if (o.voice !== undefined && entry.voice !== o.voice) return { pending: [key], why: 'The voice plan says ' + entry.speaker + ' speaks with ' + entry.voice + ', and this command speaks with ' + o.voice + '. Correct the plan (popost video inputs voice) or the command.' }; + const planned = new Set(entry.lines.map(tidy)); + const extra = (o.lines ?? []).map(tidy).filter((l) => l && !planned.has(l)); + if (extra.length) return { pending: [key], why: extra.length + ' line(s) of this command are not in the voice plan the user was shown (first: "' + (extra[0] ?? '').slice(0, 80) + '"). Write the lines as they are now into the plan (popost video inputs voice ... --fill <fill.json> or --line), then show the user the voice again.' }; + const record = await readInputs(rt, dir); + return record.confirmed?.items[key] === voiceHash(entry) ? undefined : { pending: [key], why: 'The user has not confirmed the voice of ' + entry.speaker + ' (' + entry.voice + ') with its lines as they stand.' }; +}; + +/** A paid command stopped before its work: the user has not confirmed these inputs. Printed as { ok: false, confirm, next } with exit code 3. */ +export class InputsPending extends Error { + override name = 'InputsPending'; + constructor(readonly block: { confirm: Record<string, unknown>; next: string }) { + super('The user has not confirmed the inputs; nothing was made or charged.'); + } +} + +/** Stops a paid voice command (paying: it was run with --confirm) whose voice or lines the user has not confirmed. */ +export const holdVoice = async (rt: Runtime, dir: string, project: string, paying: boolean, o: { voice?: string; speaker?: string; lines?: readonly string[] }): Promise<void> => { + if (!paying) return; + const held = await voicePending(rt, dir, o); + if (!held) return; + const block = confirmBlock(rt, dir, await readInputs(rt, dir), held.pending, project); + throw new InputsPending({ confirm: { ...block.confirm, why: held.why }, next: held.why + ' ' + block.next }); +}; diff --git a/skills/popost/src/video/inputs/sheet.ts b/skills/popost/src/video/inputs/sheet.ts new file mode 100644 index 0000000..c541d83 --- /dev/null +++ b/skills/popost/src/video/inputs/sheet.ts @@ -0,0 +1,99 @@ +/** + * The input sheet: one picture (or a few, for a long list) that shows the user what goes to the models before any of + * it is paid for. On top the product pictures exactly as they are sent (the crop, when one was made), the cast with + * their pictures and names, and the voice; below, one row per clip or picture with its caption (file, what it shows, + * seconds, aspect ratio, resolution, model, credits) and every picture sent with it. Drawn by the local browser from + * an HTML page that holds only the project's own files as data: URLs: nothing is fetched. + */ +import { escapeHtml } from '../../core/util'; +import { msg } from '../../i18n'; +import { sniffImageMime } from '../../providers/api'; +import { hasBrokenImage, openOfflineContext, settlePage, withBrowser } from '../../render/offline'; +import type { Runtime } from '../../runtime'; +import type { Summary, SummaryItem } from './summary'; + +/** How many clips or pictures one sheet holds; the first sheet also holds the product, the cast and the voice. */ +export const ROWS_A_SHEET = 6; +const WIDTH = 1600; +const FONTS = '"Helvetica Neue", Arial, "Noto Sans CJK SC", "PingFang SC", "Microsoft YaHei", sans-serif'; + +const CSS = '*{margin:0;padding:0;box-sizing:border-box}' + + 'body{width:' + WIDTH + 'px;background:#f4f4f2;color:#16181b;font-family:' + FONTS + ';font-size:20px;line-height:1.35;padding:28px}' + + 'h1{font-size:30px;margin-bottom:6px}h2{font-size:22px;margin:22px 0 10px;border-bottom:2px solid #16181b;padding-bottom:4px}' + + '.sum{font-size:20px;color:#3b4046}.row{display:flex;gap:14px;flex-wrap:wrap;align-items:flex-start}' + + '.tile{width:236px}.tile .box{width:236px;height:236px;background:#fff;border:3px solid #9aa0a8;display:flex;align-items:center;justify-content:center}' + + '.tile img{max-width:100%;max-height:100%;display:block}.tile.product .box{border-color:#e8a020;border-width:5px}.tile.cast .box{border-color:#2f6fd0;border-width:5px}' + + '.tile .cap{font-size:16px;margin-top:4px;overflow-wrap:anywhere}.tile .role{font-weight:700}' + + '.card{background:#fff;border:1px solid #c9cdd3;padding:12px 14px;margin-bottom:12px}.card .head{font-weight:700;font-size:21px}' + + '.card .spec{color:#3b4046;margin:2px 0 6px}.card .what{margin-bottom:8px;display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;overflow:hidden}' + + '.note{font-size:16px;color:#6a4b00}.none{font-size:16px;color:#6b7079}'; + +const short = (text: string, n: number): string => (text.length > n ? text.slice(0, n - 1).trimEnd() + '…' : text); + +/** The page of one sheet. data: the bytes of every picture it shows, by its path in the project. */ +export const sheetHtml = (s: Summary, rows: readonly SummaryItem[], first: boolean, page: string, data: ReadonlyMap<string, Uint8Array>): string => { + const img = (file: string): string => { + const bytes = data.get(file); + const mime = bytes ? sniffImageMime(bytes.subarray(0, 16)) : undefined; + return bytes && mime ? '<img alt="" src="data:' + mime + ';base64,' + Buffer.from(bytes).toString('base64') + '">' : '<span class="none">' + escapeHtml(msg('not a picture that can be shown', '无法显示的图片')) + '</span>'; + }; + const tile = (kind: string, file: string, role: string, caption: string): string => + '<div class="tile ' + kind + '"><div class="box">' + img(file) + '</div><div class="cap"><span class="role">' + escapeHtml(role) + '</span> ' + escapeHtml(caption) + '</div></div>'; + const t = s.totals; + const out: string[] = ['<h1>' + escapeHtml(msg('Inputs to confirm', '待确认的输入内容')) + ' ' + escapeHtml(page) + '</h1>', + '<div class="sum">' + escapeHtml(t.clips + msg(' clip(s), ', ' 个视频片段,') + t.seconds + msg(' s', ' 秒') + ' · ' + t.pictures + msg(' picture(s)', ' 张图片') + ' · ' + s.voices.length + msg(' voice(s)', ' 个配音') + ' · ' + msg('total ', '合计 ') + t.credits + msg(' credits', ' 积分') + + (t.unpriced ? msg(' + ' + t.unpriced + ' unpriced', ' + ' + t.unpriced + ' 项未定价') : '') + (t.balance !== undefined ? ' · ' + msg('balance ', '余额 ') + t.balance : '')) + '</div>']; + if (first && s.products.length) { + out.push('<h2>' + escapeHtml(msg('Product: the picture exactly as it is sent', '商品:实际发送的图片')) + '</h2><div class="row">'); + for (const p of s.products) for (const x of p.pictures) out.push(tile('product', x.file, p.id, x.original ? msg('crop of ', '裁剪自 ') + x.original : msg('the user\'s picture, whole', '用户原图,未裁剪'))); + out.push('</div>'); + } + if (first && (s.cast.length || s.anchor)) { + out.push('<h2>' + escapeHtml(msg('People', '出镜人物')) + '</h2><div class="row">'); + for (const c of s.cast) out.push(c.picture ? tile('cast', c.picture, c.id, short(c.description, 90)) : '<div class="tile cast"><div class="box"><span class="none">' + escapeHtml(msg('described in the prompt, no picture', '仅在提示词中描述,无图片')) + '</span></div><div class="cap"><span class="role">' + escapeHtml(c.id) + '</span> ' + escapeHtml(short(c.description, 90)) + '</div></div>'); + if (s.anchor) out.push(tile('cast', s.anchor.file, msg('anchor', '锚定图'), s.anchor.note)); + out.push('</div>'); + } + if (first && s.voices.length) { + out.push('<h2>' + escapeHtml(msg('Voice', '配音')) + '</h2>'); + for (const v of s.voices) out.push('<div class="card"><div class="head">' + escapeHtml(v.speaker + ': ' + (v.name ?? v.voice)) + '</div><div class="spec">' + escapeHtml([v.language, msg('speed ', '语速 ') + v.speed, v.lines.length + msg(' line(s)', ' 句台词'), v.credits === null ? '' : v.credits + msg(' credits', ' 积分')].filter(Boolean).join(' · ')) + '</div>' + + '<div class="what">' + escapeHtml(short(v.script.display ?? v.lines.join(' / '), 260)) + '</div><div class="note">' + escapeHtml(v.sample ? msg('listen: ', '试听:') + v.sample.file : msg('no free sample', '没有免费试听')) + '</div></div>'); + } + if (rows.length) out.push('<h2>' + escapeHtml(msg('Clips and pictures to generate', '待生成的视频片段和图片')) + '</h2>'); + for (const i of rows) { + const spec = [i.kind === 'video' && i.seconds !== undefined ? i.seconds + msg(' s', ' 秒') : '', i.aspect ?? '', i.resolution ?? '', i.model ?? '', i.credits === null ? msg('price unknown', '价格未知') : i.credits + msg(' credits', ' 积分')].filter(Boolean).join(' · '); + out.push('<div class="card"><div class="head">' + escapeHtml(i.file) + '</div><div class="spec">' + escapeHtml(spec) + '</div><div class="what">' + escapeHtml(short(i.prompt.display ?? i.what, 300)) + '</div><div class="row">' + + (i.pictures.length ? i.pictures.map((p) => tile(p.role === 'product' ? 'product' : p.role === 'cast' ? 'cast' : '', p.file, p.name, p.role === 'product' || p.role === 'cast' ? '' : p.role)).join('') : '<span class="none">' + escapeHtml(msg('no picture is sent with it: made from the prompt alone', '不随请求发送图片:仅凭提示词生成')) + '</span>') + + '</div>' + i.notes.map((n) => '<div class="note">' + escapeHtml(n) + '</div>').join('') + '</div>'); + } + return '<!doctype html><html><head><meta charset="utf-8"><style>' + CSS + '</style></head><body>' + out.join('') + '</body></html>'; +}; + +/** Writes the sheets of a summary into `outDir` (in the project) and returns their paths in the project. Needs the local browser. */ +export const writeSheets = async (rt: Runtime, dir: string, outDir: string, s: Summary): Promise<string[]> => { + const files = new Set([...s.products.flatMap((p) => p.pictures.map((x) => x.file)), ...s.cast.flatMap((c) => (c.picture ? [c.picture] : [])), ...(s.anchor ? [s.anchor.file] : []), ...s.items.flatMap((i) => i.pictures.map((p) => p.file))]); + const data = new Map<string, Uint8Array>(); + for (const f of files) { const bytes = await rt.fs.readFile(rt.path.resolve(dir, f)).catch(() => undefined); if (bytes) data.set(f, bytes); } + const pages = Math.max(1, Math.ceil(s.items.length / ROWS_A_SHEET)); + const written: string[] = []; + await rt.fs.mkdir(rt.path.resolve(dir, outDir)); + await withBrowser(rt, async (browser) => { + const { context } = await openOfflineContext(rt, browser, rt.cwd, { scale: 1 }); + try { + for (let k = 0; k < pages; k++) { + const page = await context.newPage(); + await page.setViewportSize({ width: WIDTH, height: 900 }); + await page.setContent(sheetHtml(s, s.items.slice(k * ROWS_A_SHEET, (k + 1) * ROWS_A_SHEET), k === 0, pages > 1 ? (k + 1) + '/' + pages : '', data), { waitUntil: 'load', timeout: 30_000 }); + await settlePage(page); + if (await hasBrokenImage(page)) throw new Error('A picture of the input sheet could not be decoded; check the product, cast and reference pictures of the list.'); + const file = outDir + '/input-sheet' + (pages > 1 ? '-' + (k + 1) : '') + '.jpg'; + await rt.fs.writeFile(rt.path.resolve(dir, file), await page.screenshot({ type: 'jpeg', quality: 82, fullPage: true, animations: 'disabled' })); + written.push(file); + await page.close(); + } + } finally { + await context.close(); + } + }); + return written; +}; diff --git a/skills/popost/src/video/inputs/summary.ts b/skills/popost/src/video/inputs/summary.ts new file mode 100644 index 0000000..2ffdae3 --- /dev/null +++ b/skills/popost/src/video/inputs/summary.ts @@ -0,0 +1,166 @@ +/** + * The summary of the inputs, for the agent's one message to the user: per clip or picture the prompt as it is sent, + * its references by name, the model, resolution, seconds, aspect ratio and credits; the voice with its lines; totals. + * As data (summary.json) and as text ready to paste (summary.md). Labels are English or Chinese (`--lang`). + * + * Two versions of a text. A model that takes prompts in the user's language is sent what the user reads: one text. + * A model whose prompts are English (`promptLanguage: "en"` in the model list) is sent English, and a user who writes + * another language is shown a faithful version in their language first, with the sent text underneath. The program + * cannot translate: the agent supplies that version (popost video inputs translate), bound to the hash of the sent + * text, so a changed prompt asks for it again; until then the summary marks it as missing. + */ +import { sha256 } from '../../core/util'; +import { msg } from '../../i18n'; +import type { PromptPolicy } from '../prompt-lang'; +import type { Gathered, ShownClip, ShownVoice } from './collect'; +import type { DisplayText } from './record'; + +/** The script most of a text is written in: enough to tell whether it can be the user's language. */ +export const scriptOf = (text: string): 'han' | 'kana' | 'hangul' | 'cyrillic' | 'arabic' | 'latin' => { + const count = (re: RegExp): number => (text.match(re) ?? []).length; + const letters = count(/\p{L}/gu) || 1; + if (count(/[぀-ヿ]/g) / letters > 0.1) return 'kana'; + if (count(/[가-힯]/g) / letters > 0.3) return 'hangul'; + if (count(/\p{Script=Han}/gu) / letters > 0.3) return 'han'; + if (count(/\p{Script=Cyrillic}/gu) / letters > 0.3) return 'cyrillic'; + if (count(/\p{Script=Arabic}/gu) / letters > 0.3) return 'arabic'; + return 'latin'; +}; + +const SCRIPT_OF_LANG: Readonly<Record<string, string>> = { zh: 'han', yue: 'han', ja: 'kana', ko: 'hangul', ru: 'cyrillic', uk: 'cyrillic', bg: 'cyrillic', ar: 'arabic', fa: 'arabic' }; + +/** + * Whether a text sent in English needs a version in the user's language beside it: never for an English user; for any + * other language unless the text is already written in that language's own script. + */ +export const needsDisplay = (text: string, lang: string | undefined, policy: PromptPolicy): boolean => { + const base = (lang ?? '').toLowerCase().split('-')[0] ?? ''; + if (policy !== 'en' || !base || base === 'en' || !text.trim()) return false; + return SCRIPT_OF_LANG[base] !== scriptOf(text); +}; + +/** Whether a text is plainly not in the user's language: written in another script than that language uses. */ +export const otherScript = (text: string, lang: string | undefined): boolean => { + const base = (lang ?? '').toLowerCase().split('-')[0] ?? ''; + return Boolean(base) && Boolean(text.trim()) && (SCRIPT_OF_LANG[base] ?? 'latin') !== scriptOf(text); +}; + +/** A text as the user is shown it: `display` first when there is one, `sent` always; displayMissing: a version in the user's language is owed. */ +export interface ShownText { sent: string; display?: string; displayMissing?: true } + +export const textHash = (text: string): string => sha256(text); + +/** The version in the user's language of a sent text: the stored one while it renders this very text in this language. */ +export const shownText = (sent: string, lang: string | undefined, policy: PromptPolicy, stored: DisplayText | undefined, script = false): ShownText => { + if (!(script ? otherScript(sent, lang) : needsDisplay(sent, lang, policy))) return { sent }; + return stored && stored.sent === textHash(sent) && stored.lang === lang && stored.text.trim() ? { sent, display: stored.text } : { sent, displayMissing: true }; +}; + +export interface SummaryItem extends Omit<ShownClip, 'prompt'> { prompt: ShownText; confirmed: boolean } +export interface SummaryVoice extends Omit<ShownVoice, 'lines'> { lines: string[]; script: ShownText; confirmed: boolean } + +export interface Summary { + version: 1; + lang?: string; + policy: PromptPolicy; + model?: string; + products: (Gathered['products'][number] & { confirmed: boolean })[]; + /** The facts of the product the user did not state, in one line, to correct or agree to. */ + inferred?: string; + cast: (Gathered['cast'][number] & { confirmed: boolean })[]; + anchor?: Gathered['anchor']; + items: SummaryItem[]; + kept: string[]; + voices: SummaryVoice[]; + totals: { clips: number; pictures: number; seconds: number; credits: number; unpriced: number; balance?: number }; + sheets: string[]; + /** The keys whose text in the user's language is still owed. */ + displayMissing: string[]; + notes: string[]; +} + +export const summarize = (g: Gathered, o: { lang?: string; display?: Readonly<Record<string, DisplayText>>; confirmed?: Readonly<Record<string, string>>; items: Readonly<Record<string, string>>; inferred?: string; sheets: string[] }): Summary => { + const done = (key: string): boolean => o.confirmed?.[key] !== undefined && o.confirmed[key] === o.items[key]; + const items = g.clips.map(({ prompt, ...c }): SummaryItem => ({ ...c, prompt: shownText(prompt, o.lang, g.policy, o.display?.[c.key]), confirmed: done(c.key) })); + // A script in another language than the user writes (an English advertisement for a Chinese user) is shown in both too. + const voices = g.voices.map((v): SummaryVoice => ({ ...v, script: shownText(v.lines.join('\n'), o.lang, g.policy, o.display?.[v.key], true), confirmed: done(v.key) })); + // Under "user" the prompt is what the user reads: one written in another script than their language is said, not translated. + const stray = g.policy === 'user' ? g.clips.filter((c) => otherScript(c.what, o.lang)).map((c) => c.file) : []; + const priced = [...items.map((i) => i.credits), ...voices.map((v) => v.credits)]; + return { + version: 1, ...(o.lang ? { lang: o.lang } : {}), policy: g.policy, ...(g.model ? { model: g.model } : {}), + products: g.products.map((p) => ({ ...p, confirmed: done(p.key) })), ...(o.inferred ? { inferred: o.inferred } : {}), + cast: g.cast.map((c) => ({ ...c, confirmed: done(c.key) })), ...(g.anchor ? { anchor: g.anchor } : {}), + items, kept: g.kept, voices, + totals: { + clips: items.filter((i) => i.kind === 'video').length, pictures: items.filter((i) => i.kind === 'image').length, + seconds: items.reduce((n, i) => n + (i.kind === 'video' ? i.seconds ?? 0 : 0), 0), + credits: priced.reduce((n: number, c) => n + (c ?? 0), 0), unpriced: priced.filter((c) => c === null).length, + ...(g.balance !== undefined ? { balance: g.balance } : {}), + }, + sheets: o.sheets, displayMissing: [...items.filter((i) => i.prompt.displayMissing).map((i) => i.key), ...voices.filter((v) => v.script.displayMissing).map((v) => v.key)], + notes: [...g.notes, ...(stray.length ? ['The prompt of ' + stray.join(', ') + ' is not written in the language of the conversation (' + o.lang + '). This model takes prompts in the user\'s language, and the user confirms the prompt as it is sent: write it in their language (model ids, file names, brand names and text printed on the product stay as they are).'] : [])], + }; +}; + +/** The summary with the display texts as they are stored now (after `inputs translate`). */ +export const withDisplay = (s: Summary, display: Readonly<Record<string, DisplayText>>): Summary => { + const items = s.items.map((i) => ({ ...i, prompt: shownText(i.prompt.sent, s.lang, s.policy, display[i.key]) })); + const voices = s.voices.map((v) => ({ ...v, script: shownText(v.script.sent, s.lang, s.policy, display[v.key], true) })); + return { ...s, items, voices, displayMissing: [...items.filter((i) => i.prompt.displayMissing).map((i) => i.key), ...voices.filter((v) => v.script.displayMissing).map((v) => v.key)] }; +}; + +const credits = (n: number | null, note?: string): string => (n === null ? msg('price ', '价格') + (note ?? msg('unknown', '未知')) : n + msg(' credits', ' 积分')); +const state = (ok: boolean): string => (ok ? msg('confirmed', '已确认') : msg('to confirm', '待确认')); +const quoted = (text: string): string => text.split('\n').map((l) => '> ' + l).join('\n'); + +const textBlock = (t: ShownText, label: string): string[] => t.display + ? [quoted(t.display), '', msg('As sent to the model (' + label + '):', '实际发送给模型的原文(' + label + '):'), quoted(t.sent)] + : [...(t.displayMissing ? [msg('**[A version in the user\'s language is missing: write one with `popost video inputs translate` before showing this.]**', '**[缺少用户语言的版本:展示前先用 `popost video inputs translate` 写入。]**'), ''] : []), quoted(t.sent)]; + +/** The summary as text for the agent's message. */ +export const summaryText = (s: Summary): string => { + const out: string[] = ['# ' + msg('Inputs to confirm before anything is generated', '生成前请确认的输入内容'), '']; + const t = s.totals; + out.push(msg('**Total: ', '**合计:') + t.credits + msg(' credits', ' 积分') + '**' + (t.unpriced ? msg(' (plus ' + t.unpriced + ' item(s) without a known price)', '(另有 ' + t.unpriced + ' 项价格未知)') : '') + + ' · ' + t.clips + msg(' clip(s), ', ' 个视频片段,') + t.seconds + msg(' s', ' 秒') + ' · ' + t.pictures + msg(' picture(s)', ' 张图片') + ' · ' + s.voices.length + msg(' voice(s)', ' 个配音') + + (t.balance !== undefined ? ' · ' + msg('balance ', '余额 ') + t.balance : ''), ''); + if (s.sheets.length) out.push(msg('Input sheet (show it with this text): ', '输入总览图(与本文一起展示):') + s.sheets.join(', '), ''); + if (s.products.length) { + out.push('## ' + msg('Product', '商品'), ''); + for (const p of s.products) { + out.push('- **' + p.id + '** (' + state(p.confirmed) + '): ' + p.what); + for (const x of p.pictures) out.push(' - ' + msg('picture sent: ', '发送的图片:') + x.file + (x.original ? msg(' (a crop of ', '(裁剪自 ') + x.original + msg(', box ', ',区域 ') + x.crop + msg(')', ')') : msg(' (the user\'s picture, whole)', '(用户原图,未裁剪)'))); + } + if (s.inferred) out.push('', s.inferred); + out.push(''); + } + if (s.cast.length || s.anchor) { + out.push('## ' + msg('People', '出镜人物'), ''); + for (const c of s.cast) out.push('- **' + c.id + '** (' + state(c.confirmed) + '): ' + c.description + (c.picture ? ' · ' + msg('picture: ', '图片:') + c.picture : ' · ' + (c.note ?? ''))); + if (s.anchor) out.push('- ' + s.anchor.note + ': ' + s.anchor.file); + out.push(''); + } + if (s.items.length) out.push('## ' + msg('Clips and pictures to generate', '待生成的视频片段和图片'), ''); + s.items.forEach((i, n) => { + const spec = [i.model ? msg('model ', '模型 ') + i.model : '', i.resolution ?? '', i.seconds !== undefined && i.kind === 'video' ? i.seconds + msg(' s', ' 秒') : '', i.aspect ?? '', credits(i.credits, i.priceNote)].filter(Boolean).join(' · '); + out.push('### ' + (n + 1) + '. ' + i.file + ' (' + state(i.confirmed) + ')', '', spec, ''); + if (i.pictures.length) out.push(msg('Pictures sent with it: ', '随请求发送的图片:') + i.pictures.map((p) => p.name + ' = ' + p.file + ' (' + p.role + ')').join('; ')); + if (i.sounds.length) out.push(msg('Sounds sent with it: ', '随请求发送的声音:') + i.sounds.join(', ')); + if (i.clips.length) out.push(msg('Clips sent with it: ', '随请求发送的视频:') + i.clips.join(', ')); + for (const note of i.notes) out.push(msg('Note: ', '说明:') + note); + out.push('', msg('Prompt:', '提示词:'), ...textBlock(i.prompt, 'prompt'), ''); + }); + if (s.kept.length) out.push(msg('Already made, not generated again: ', '已有文件,不会重新生成:') + s.kept.join(', '), ''); + if (s.voices.length) out.push('## ' + msg('Voice', '配音'), ''); + for (const v of s.voices) { + out.push('- **' + v.speaker + '** (' + state(v.confirmed) + '): ' + (v.name ? v.name + ' (' + v.voice + (v.id ? ', id ' + v.id : '') + ')' : v.voice) + (v.language ? ' · ' + v.language : '') + ' · ' + msg('speed ', '语速 ') + v.speed + ' · ' + credits(v.credits, v.priceNote)); + if (v.sample) out.push(' - ' + msg('Listen: ', '试听:') + v.sample.file + ' (' + v.sample.from + ')'); + if (v.paidSample) out.push(' - ' + msg('No free sample. A one-sentence sample ("', '没有免费试听。一句话的试听(“') + v.paidSample.text + msg('") would cost ', '”)需要 ') + (v.paidSample.credits ?? '?') + msg(' credits; made only if you ask for it.', ' 积分;只有你要求时才会生成。')); + if (v.note) out.push(' - ' + v.note); + if (v.lines.length) out.push('', msg('Script:', '台词:'), ...textBlock(v.script, 'script'), ''); + } + if (s.notes.length) out.push('## ' + msg('Notes', '说明'), '', ...s.notes.map((n) => '- ' + n), ''); + out.push(msg('Reply yes to go on, or say what to change. Nothing has been generated or charged.', '回复“可以”即开始生成,或告诉我要改什么。目前没有生成任何内容,也没有扣费。')); + return out.join('\n') + '\n'; +}; diff --git a/skills/popost/src/video/product/requests.ts b/skills/popost/src/video/product/requests.ts index 195514c..ae8af09 100644 --- a/skills/popost/src/video/product/requests.ts +++ b/skills/popost/src/video/product/requests.ts @@ -163,7 +163,7 @@ export const productRequestProblems = async (rt: Runtime, requests: readonly unk if (!sheet) return [...out, error(PRODUCT_FILE, 'The product sheet has errors, so no request can be held to it and nothing that shows the product is made.', 'Fix them (popost video product check <project> lists them), then run this again.')]; const unconfirmed = (): Problem => { const make = policy.paying ? error : warning; - return (make(PRODUCT_FILE, 'The user has not confirmed what was read from the product picture. ' + confirmLine(sheet), 'Show the user that one line with the plan and its cost; then popost video product confirm <project> --quote "<their answer>" (a correction goes into the sheet first, as "from": "user" with their words).' + (policy.paying ? ' Nothing was made or charged.' : ' Paid generation waits for it.'))); + return (make(PRODUCT_FILE, 'The user has not confirmed what was read from the product picture. ' + confirmLine(sheet), 'It is part of the one message that shows the user the inputs and the cost (popost video inputs show); their answer is recorded once, with popost video inputs confirm <project> --quote "<their answer>" (a correction goes into the sheet first, as "from": "user" with their words).' + (policy.paying ? ' Nothing was made or charged.' : ' Paid generation waits for it.'))); }; const known = sheet.products.map((p) => p.id); let anyShown = false; diff --git a/skills/popost/tests/video/inputs.test.ts b/skills/popost/tests/video/inputs.test.ts new file mode 100644 index 0000000..2b9a0aa --- /dev/null +++ b/skills/popost/tests/video/inputs.test.ts @@ -0,0 +1,325 @@ +/** + * The inputs the user confirms before anything is paid for: what `popost video inputs show` gathers (every prompt as + * sent, the product and cast pictures, each clip's references, the voice with a free sample, free prices), the gate + * of the paid commands (exit code 3 until the user confirmed exactly what was shown; a change asks again for what + * changed), --unattended, and the two ways a model takes prompts. In memory, against the in-memory popost.ai: nothing + * is paid. The sheet picture is drawn with Chrome (skipped without it). + */ +import { describe, expect, it } from 'vitest'; +import { sha256 } from '../../src/core/util'; +import { findChromium, launchChromium } from '../../src/render/browser'; +import type { TestRuntime } from '../../src/testing/memory'; +import { anchorSentence } from '../../src/video/generate/index'; +import { readInputs, voicePending } from '../../src/video/inputs/record'; +import { sheetHtml, writeSheets } from '../../src/video/inputs/sheet'; +import { needsDisplay, otherScript, type Summary } from '../../src/video/inputs/summary'; +import { productBlock } from '../../src/video/product/sheet'; +import { withPromptLang } from '../../src/video/prompt-lang'; +import { cli, ok, ORIGIN, tinyPng, type Json, type PopostStub } from '../image-helpers'; +import { wav } from './hosted-fake'; +import { fact, flask, HOST, P, setup, sheetOf, writeSheet } from './product-fixtures'; +import { MODEL } from './video-api-fake'; + +const VOICE = { id: 'v-anna', name: 'Anna', description: '', language: 'en', official: true, sampleUrl: ORIGIN + '/files/anna.wav', defaultFor: 'female', cloneState: 'ready' }; +const LINES = ['Meet the flask that keeps up.', 'Cold for a whole day.']; +const REQUESTS: Json[] = [ + { file: 'assets/hold.mp4', prompt: 'the presenter lifts the flask to the camera', seconds: 5, aspect: '9:16', cast: ['host'], products: ['flask'] }, + { file: 'assets/street.mp4', prompt: 'a wet street at dusk, slow push-in', seconds: 5, aspect: '9:16', cast: [], products: [] }, +]; + +/** The platform's voices on the stub: the catalog, free quotes (2 credits a line) and a preview file. speech: every call that would be paid. */ +const voices = (stub: PopostStub, voice: Json = VOICE): void => { + stub.files.set('anna.wav', wav({ seconds: 1 })); + stub.set('GET', '/voices', () => ok({ items: [voice], total: 1 })); + stub.set('POST', '/voices/quote', () => ok({ credits: 2 })); +}; + +const project = async (env: Record<string, string | undefined> = {}) => { + const s = await setup(env); + await writeSheet(s.rt); + await s.rt.fs.writeFile(P + '/assets/cast/host.png', HOST); + await s.rt.fs.writeFile(P + '/cast.json', JSON.stringify({ version: 1, roles: [{ id: 'host', description: 'A fictional presenter in a grey coat', identity: 'new', image: 'assets/cast/host.png', sha256: sha256(HOST), provenance: 'image_gen' }] })); + await s.rt.fs.writeFile(P + '/requests.json', JSON.stringify(REQUESTS)); + voices(s.stub); + await cli(s.rt, 'video', 'inputs', 'voice', P, '--speaker', 'narrator', '--voice', 'popost:default-female', '--language', 'en', ...LINES.flatMap((l) => ['--line', l])); + return s; +}; +const show = (rt: TestRuntime, ...more: string[]) => cli(rt, 'video', 'inputs', 'show', P, '--requests', P + '/requests.json', '--no-anchor', ...more); +const materials = (rt: TestRuntime, ...more: string[]) => cli(rt, 'video', 'materials', P + '/requests.json', '--out', P, '--no-anchor', '--confirm', '--max-credits', '100', ...more); +const summaryOf = async (rt: TestRuntime): Promise<Summary> => JSON.parse(await rt.fs.readText(P + '/production/inputs/summary.json')) as Summary; +const paid = (stub: PopostStub): string[] => stub.requests.filter((r) => r.method === 'POST' && ['/videos/generations', '/voices/speech', '/images/tasks', '/images/generations'].some((p) => r.path.endsWith(p))).map((r) => r.path); + +describe('popost video inputs show', () => { + it('gathers every prompt as sent, the pictures by name, model, spec and credits, and the voice with a free sample, without a paid call', async () => { + const { rt, stub, api } = await project(); + const shown = await show(rt); + expect(shown.code).toBe(0); + expect(shown.data.pending.sort()).toEqual(['clip:assets/hold.mp4', 'clip:assets/street.mp4', 'product:flask', 'voice:narrator']); + const s = await summaryOf(rt); + const [hold, street] = s.items; + // The prompt is the one materials sends: the request's words, the product block of the sheet, the cast sentence. + expect(hold?.prompt.sent.startsWith('the presenter lifts the flask to the camera Product "flask": @image1 and @image2 are the user\'s own pictures of it.')).toBe(true); + expect(hold?.prompt.sent).toContain(productBlock((await sheetOf(rt)).products[0]!, [1, 2])); + expect(hold?.prompt.sent).toContain('The final 1 reference image(s) are the locked cast. host: A fictional presenter in a grey coat'); + expect(hold?.pictures).toEqual([ + { file: 'assets/product/flask-01.png', role: 'product', name: '@image1 flask' }, { file: 'assets/product/flask-02.png', role: 'product', name: '@image2 flask' }, { file: 'assets/cast/host.png', role: 'cast', name: '@image3 host' }, + ]); + expect(hold).toMatchObject({ kind: 'video', seconds: 5, aspect: '9:16', model: MODEL.id, credits: expect.any(Number), confirmed: false }); + expect(hold?.resolution).toBeTruthy(); + expect(street?.pictures).toEqual([]); + expect(s.products[0]).toMatchObject({ id: 'flask', pictures: [{ file: 'assets/product/flask-01.png' }, { file: 'assets/product/flask-02.png' }] }); + expect(s.inferred).toContain('Read from your product picture'); + expect(s.cast).toEqual([expect.objectContaining({ id: 'host', picture: 'assets/cast/host.png' })]); + // The voice: which one, its lines, what it costs, and the platform's own preview to listen to. + expect(s.voices[0]).toMatchObject({ speaker: 'narrator', id: 'v-anna', name: 'Anna', language: 'en', speed: 1, lines: LINES, credits: 4, sample: { file: 'production/inputs/voice-narrator-sample.wav' } }); + expect((await rt.fs.readFile(P + '/production/inputs/voice-narrator-sample.wav')).length).toBeGreaterThan(44); + expect(s.totals).toMatchObject({ clips: 2, seconds: 10, pictures: 0, credits: (hold?.credits ?? 0) + (street?.credits ?? 0) + 4, unpriced: 0 }); + const text = await rt.fs.readText(P + '/production/inputs/summary.md'); + for (const part of ['assets/hold.mp4', 'model ' + MODEL.id, '9:16', '5 s', hold?.credits + ' credits', '@image3 host = assets/cast/host.png (cast)', 'Anna (popost:default-female, id v-anna)', '> Meet the flask that keeps up.', 'Listen: production/inputs/voice-narrator-sample.wav']) expect(text).toContain(part); + // Nothing was made, sent to a model or charged. + expect(paid(stub)).toEqual([]); + expect(api.ledger).toEqual([]); + expect(await rt.fs.stat(P + '/assets/hold.mp4')).toBeNull(); + }); + + it('names the cheapest paid sample with its price, and speaks nothing, for a voice without a free preview', async () => { + const { rt, stub } = await project(); + voices(stub, { ...VOICE, sampleUrl: '' }); + await show(rt); + const v = (await summaryOf(rt)).voices[0]; + expect(v?.sample).toBeUndefined(); + expect(v?.paidSample).toMatchObject({ text: 'Meet the flask that keeps up.', credits: 2 }); + expect(await rt.fs.readText(P + '/production/inputs/summary.md')).toContain('No free sample. A one-sentence sample ("Meet the flask that keeps up.") would cost 2 credits'); + expect(paid(stub)).toEqual([]); + }); + + it('puts the product, the cast and each clip\'s references on the sheet page', async () => { + const { rt } = await project(); + await show(rt); + const s = await summaryOf(rt); + const data = new Map<string, Uint8Array>([['assets/product/flask-01.png', tinyPng()], ['assets/product/flask-02.png', tinyPng()], ['assets/cast/host.png', HOST]]); + const html = sheetHtml(s, s.items, true, '', data); + for (const part of ['Product: the picture exactly as it is sent', 'class="tile product"', 'class="tile cast"', 'A fictional presenter in a grey coat', 'narrator: Anna', 'assets/hold.mp4', '@image3 host', 'no picture is sent with it', '5 s · 9:16']) expect(html).toContain(part); + expect(html.match(/<img /g)?.length).toBe(6); + expect(html).not.toContain('http'); + }); +}); + +describe('the gate of the paid commands', () => { + it('refuses with exit code 3 until the user confirmed what was shown, then passes, then asks again for what changed only', async () => { + const { rt, stub } = await project(); + const early = await materials(rt); + expect(early.code).toBe(3); + expect(early.data.confirm).toMatchObject({ reason: 'inputs', pending: ['clip:assets/hold.mp4', 'clip:assets/street.mp4'] }); + expect(early.data.next).toContain('popost video inputs show'); + expect(paid(stub)).toEqual([]); + await show(rt); + const shown = await materials(rt); + expect(shown.code).toBe(3); + expect(shown.data.confirm.summary).toBe(P + '/production/inputs/summary.md'); + expect(shown.data.next).toContain('popost video inputs confirm ' + P + ' --quote'); + // The answer is the user's, in their words, for exactly what was shown. + expect((await cli(rt, 'video', 'inputs', 'confirm', P)).code).toBe(2); + const yes = await cli(rt, 'video', 'inputs', 'confirm', P, '--quote', 'yes, go ahead'); + expect(yes.data).toMatchObject({ ok: true, by: 'user' }); + // One answer: the inferred facts of the product sheet are confirmed with it. + expect((await sheetOf(rt)).confirmation).toMatchObject({ by: 'user', quote: 'yes, go ahead' }); + const made = await materials(rt); + expect(made.code).toBe(0); + expect(made.data.made).toBe(2); + + // A changed request: that clip alone is asked about again. + await rt.fs.rm(P + '/assets/hold.mp4'); + await rt.fs.rm(P + '/assets/street.mp4'); + await rt.fs.writeFile(P + '/requests.json', JSON.stringify([REQUESTS[0], { ...REQUESTS[1], prompt: 'a dry street at noon' }])); + const changed = await materials(rt); + expect(changed.code).toBe(3); + expect(changed.data.confirm.pending).toEqual(['clip:assets/street.mp4']); + expect(changed.data.confirm.confirmedBefore).toContain('clip:assets/hold.mp4'); + // An answer for what was shown before the change does not count. + expect((await cli(rt, 'video', 'inputs', 'confirm', P, '--quote', 'yes')).code).toBe(2); + expect((await show(rt)).data.pending).toEqual(['clip:assets/street.mp4']); + await cli(rt, 'video', 'inputs', 'confirm', P, '--quote', 'fine'); + // The inputs are confirmed; what stops the changed clip now is the money rule of the agreed clips, not the inputs. + expect((await materials(rt)).data.confirm.reason).toBe('unplanned'); + + // A changed reference picture: the clip that is sent with it is asked about again, the other is not. + await rt.fs.rm(P + '/assets/hold.mp4'); + await rt.fs.rm(P + '/assets/street.mp4'); + const other = tinyPng([1, 2, 3]); + await rt.fs.writeFile(P + '/assets/cast/host.png', other); + await rt.fs.writeFile(P + '/cast.json', JSON.stringify({ version: 1, roles: [{ id: 'host', description: 'A fictional presenter in a grey coat', identity: 'new', image: 'assets/cast/host.png', sha256: sha256(other), provenance: 'image_gen' }] })); + expect((await materials(rt)).data.confirm.pending).toEqual(['clip:assets/hold.mp4']); + }); + + it('holds the paid voice commands to the voice and the lines the user confirmed', async () => { + const { rt } = await project(); + const ref = wav({ seconds: 2 }); + await rt.fs.writeFile(P + '/assets/voices/narrator.wav', ref); + await rt.fs.writeFile(P + '/voices.json', JSON.stringify({ version: 1, speakers: [{ id: 'narrator', reference: 'assets/voices/narrator.wav', sha256: sha256(ref), mode: 'audio-first', providerVoice: 'popost:default-female' }] })); + const speak = (text: string) => cli(rt, 'video', 'voice', 'speak', P, '--speaker', 'narrator', '--text', text, '--out', P + '/assets/line.wav', '--confirm', '--max-credits', '10'); + const early = await speak(LINES[0]!); + expect(early.code).toBe(3); + expect(early.data.confirm).toMatchObject({ reason: 'inputs', pending: ['voice:narrator'] }); + await show(rt); + await cli(rt, 'video', 'inputs', 'confirm', P, '--quote', 'yes'); + expect(await voicePending(rt, P, { speaker: 'narrator', voice: 'popost:default-female', lines: [LINES[0]!] })).toBeUndefined(); + // Another line, or another voice, is not what the user was shown. + const off = await speak('A line nobody saw.'); + expect(off.code).toBe(3); + expect(off.data.confirm.why).toContain('not in the voice plan the user was shown'); + expect((await voicePending(rt, P, { voice: 'popost:default-male' }))?.why).toContain('not in the voice plan'); + // A changed plan asks again for the voice, and for nothing else. + await cli(rt, 'video', 'inputs', 'voice', P, '--speaker', 'narrator', '--voice', 'popost:default-female', '--line', 'A new first line.'); + expect((await voicePending(rt, P, { speaker: 'narrator' }))?.pending).toEqual(['voice:narrator']); + expect((await show(rt)).data.pending).toEqual(['voice:narrator']); + }); + + it('--unattended records who authorised going on without the user, and says so', async () => { + const { rt } = await project(); + const made = await materials(rt, '--unattended', 'the owner: run the nightly batch without asking'); + expect(made.code).toBe(0); + expect(made.data.made).toBe(2); + expect((await readInputs(rt, P)).confirmed).toMatchObject({ by: 'unattended', quote: 'the owner: run the nightly batch without asking' }); + expect((await sheetOf(rt)).confirmation?.by).toBe('unattended'); + // The same through inputs confirm, for the voice of a batch. + const noted = await cli(rt, 'video', 'inputs', 'confirm', P, '--unattended', 'the owner said so'); + expect(noted.code).toBe(2); + await show(rt); + const again = await cli(rt, 'video', 'inputs', 'confirm', P, '--unattended', 'the owner said so'); + expect(again.data).toMatchObject({ by: 'unattended' }); + expect(again.data.note).toContain('did not see these inputs'); + }); + + it('the built-in generator, called on its own in a project, makes only a file the user confirmed', async () => { + const { rt, stub } = await project(); + await rt.fs.writeFile(P + '/request.json', JSON.stringify({ prompt: 'a wet street at dusk', seconds: 5 })); + const alone = await cli(rt, 'video', 'generate', 'video', P + '/request.json', P + '/assets/other.mp4', '--project', P, '--confirm', '--max-credits', '50'); + expect(alone.code).toBe(3); + expect(alone.data.confirm).toMatchObject({ reason: 'inputs', pending: ['clip:assets/other.mp4'] }); + expect(paid(stub)).toEqual([]); + }); +}); + +describe('the language of prompts', () => { + const zhFlask = flask({ what: fact('一只 Northwind 500 毫升保温钢瓶', 'user') }); + const zhRequests = [{ ...REQUESTS[0], prompt: '主持人把保温瓶举到镜头前' }, { ...REQUESTS[1], prompt: '黄昏时分潮湿的街道,镜头缓慢推进' }]; + const zhProject = async (model: Json = {}) => { + const s = await project(); + s.stub.set('GET', '/videos/models', () => ok({ models: [{ ...MODEL, ...model }], default: MODEL.id })); + await writeSheet(s.rt, [zhFlask]); + await s.rt.fs.writeFile(P + '/requests.json', JSON.stringify(zhRequests)); + return s; + }; + + it('a model that takes the user\'s language is sent Chinese sentences in a Chinese project, and the user reads exactly what is sent', async () => { + const { rt, stub } = await zhProject(); + await cli(rt, 'video', 'inputs', 'voice', P, '--speaker', 'narrator', '--voice', 'popost:default-female', '--line', '认识一下这只跟得上你的保温瓶。'); + const shown = await show(rt, '--lang', 'zh'); + expect(shown.data).toMatchObject({ lang: 'zh', promptLanguage: 'user' }); + expect(shown.data.displayMissing).toBeUndefined(); + const s = await summaryOf(rt); + const sent = s.items[0]?.prompt.sent ?? ''; + expect(sent).toContain('主持人把保温瓶举到镜头前 商品“flask”:@image1、@image2是用户自己提供的商品图片。'); + expect(sent).toContain('它上面印的文字,一字不差:“NORTHWIND 500”。'); + expect(sent).toContain('最后 1 张参考图是锁定的出镜人物。host:A fictional presenter in a grey coat'); + for (const english of ['Take the product from', 'Printed on it', 'The same in every frame', 'reference image(s) are the locked cast', 'Sound:', 'No background music']) expect(sent).not.toContain(english); + expect(s.items[0]?.prompt.display).toBeUndefined(); + // The labels of the summary follow the language too. + const text = await rt.fs.readText(P + '/production/inputs/summary.md'); + expect(text).toContain('# 生成前请确认的输入内容'); + expect(text).toContain('提示词:'); + // The paid run sends the same sentences: the language is the project's, not the command's. + await cli(rt, 'video', 'inputs', 'confirm', P, '--quote', '可以'); + expect((await materials(rt)).code).toBe(0); + const prompts = stub.requests.filter((r) => r.path.endsWith('/videos/generations') && r.method === 'POST').map((r) => String(r.json?.prompt)); + expect(prompts.some((p) => p.includes('商品“flask”:@image1、@image2是用户自己提供的商品图片。'))).toBe(true); + expect(prompts.join('\n')).not.toContain('Take the product from'); + // A prompt left in English is said: this model is sent what the user reads. + await rt.fs.writeFile(P + '/requests.json', JSON.stringify([zhRequests[0], REQUESTS[1]])); + await rt.fs.rm(P + '/assets/street.mp4'); + expect(JSON.stringify((await show(rt)).data.notes)).toContain('assets/street.mp4 is not written in the language of the conversation (zh)'); + }); + + it('an English project, and a project without a stored language, are sent the English sentences as before', async () => { + const plain = await project(); + await show(plain.rt); + const before = (await summaryOf(plain.rt)).items[0]?.prompt.sent; + expect(await plain.rt.fs.stat(P + '/production/language.json')).toBeNull(); + const en = await project(); + await show(en.rt, '--lang', 'en'); + expect((await summaryOf(en.rt)).items[0]?.prompt.sent).toBe(before); + expect(before).toBe('the presenter lifts the flask to the camera ' + productBlock((await sheetOf(plain.rt)).products[0]!, [1, 2]) + ' The final 1 reference image(s) are the locked cast. host: A fictional presenter in a grey coat. Preserve the described identity, face, build, hair and wardrobe. Do not introduce a reference creator or a different actor. Sound: only the ambient sound of the scene and the sounds of what happens in it. Nobody speaks: no dialogue, no narrator, no voice. No background music and no score in this clip: the music of the video is a separate track.'); + // Outside a Chinese scope every sentence is the English one, byte for byte; any other language gets English too. + const p = (await sheetOf(plain.rt)).products[0]!; + for (const lang of [undefined, 'en', 'ja', 'de']) expect(withPromptLang(lang, 'user', () => [productBlock(p, [1]), anchorSentence(2, 'clip')].join('|'))).toBe([productBlock(p, [1]), anchorSentence(2, 'clip')].join('|')); + expect(withPromptLang('zh', 'user', () => anchorSentence(2, 'clip'))).toContain('@image2 是同一条视频另一个片段的一帧。'); + expect(withPromptLang('zh', 'en', () => anchorSentence(2, 'clip'))).toBe(anchorSentence(2, 'clip')); + }); + + it('a model that takes English is sent English, and a Chinese user is shown their own language first: missing until written, and again after the prompt changes', async () => { + const { rt } = await zhProject({ promptLanguage: 'en' }); + await writeSheet(rt); + await rt.fs.writeFile(P + '/requests.json', JSON.stringify(REQUESTS)); + const shown = await show(rt, '--lang', 'zh'); + expect(shown.data.promptLanguage).toBe('en'); + expect(shown.data.displayMissing).toEqual(['clip:assets/hold.mp4', 'clip:assets/street.mp4', 'voice:narrator']); + expect(shown.data.next).toContain('popost video inputs translate'); + const first = await summaryOf(rt); + // The program's own sentences stay English for this model, whatever the user's language. + expect(first.items[0]?.prompt.sent).toContain('Take the product from them'); + expect(first.items[0]?.prompt).toMatchObject({ displayMissing: true }); + expect(await rt.fs.readText(P + '/production/inputs/summary.md')).toContain('缺少用户语言的版本'); + // The user is not asked before they can read it. + expect((await cli(rt, 'video', 'inputs', 'confirm', P, '--quote', '可以')).code).toBe(2); + await rt.fs.writeFile(P + '/zh.json', JSON.stringify({ 'clip:assets/hold.mp4': '主持人把保温瓶举到镜头前。(商品说明:……)', 'voice:narrator': '认识一下这只跟得上你的保温瓶。\n整整一天保持冰凉。' })); + await cli(rt, 'video', 'inputs', 'translate', P, '--file', P + '/zh.json'); + const one = await cli(rt, 'video', 'inputs', 'translate', P, '--item', 'clip:assets/street.mp4', '--text', '黄昏时分潮湿的街道,镜头缓慢推进'); + expect(one.data.displayMissing).toEqual([]); + const text = await rt.fs.readText(P + '/production/inputs/summary.md'); + // The user's language first, then the sent text underneath. + const own = text.indexOf('> 黄昏时分潮湿的街道,镜头缓慢推进'); + const label = text.indexOf('实际发送给模型的原文(prompt):', own); + expect(own).toBeGreaterThan(0); + expect(label).toBeGreaterThan(own); + expect(text.indexOf('> a wet street at dusk, slow push-in', label)).toBeGreaterThan(label); + expect(text.indexOf('> a wet street at dusk, slow push-in')).toBeGreaterThan(label); + expect((await show(rt)).data.displayMissing).toBeUndefined(); + // The answer is bound to the sent text alone: writing a translation did not change what is confirmed. + const hashes = (await readInputs(rt, P)).shown?.items; + expect((await cli(rt, 'video', 'inputs', 'confirm', P, '--quote', '可以')).code).toBe(0); + expect((await readInputs(rt, P)).confirmed?.items).toEqual(hashes); + // A changed sent prompt: its translation no longer renders it. + await rt.fs.writeFile(P + '/requests.json', JSON.stringify([REQUESTS[0], { ...REQUESTS[1], prompt: 'a dry street at noon' }])); + const again = await show(rt); + expect(again.data.displayMissing).toEqual(['clip:assets/street.mp4']); + expect((await readInputs(rt, P)).display?.['clip:assets/street.mp4']).toBeUndefined(); + expect((await readInputs(rt, P)).display?.['clip:assets/hold.mp4']?.text).toContain('主持人'); + }); + + it('tells when a text needs a second version', () => { + expect(needsDisplay('a wet street', 'zh', 'en')).toBe(true); + expect(needsDisplay('a wet street', 'de', 'en')).toBe(true); + expect(needsDisplay('a wet street', 'en', 'en')).toBe(false); + expect(needsDisplay('潮湿的街道', 'zh', 'en')).toBe(false); + expect(needsDisplay('a wet street', 'zh', 'user')).toBe(false); + expect(otherScript('Meet the flask.', 'zh')).toBe(true); + expect(otherScript('Meet the flask.', 'de')).toBe(false); + expect(otherScript('认识一下保温瓶', 'en')).toBe(true); + }); +}); + +const chrome = findChromium(process.env); +describe.skipIf(!chrome)('the input sheet picture, with Chrome', () => { + it('draws one JPEG with the product, the cast and each clip', async () => { + const { rt } = await project(); + await show(rt); + const s = await summaryOf(rt); + const drawing: TestRuntime = { ...rt, launchBrowser: () => launchChromium(process.env) }; + const files = await writeSheets(drawing, P, 'production/inputs', s); + expect(files).toEqual(['production/inputs/input-sheet.jpg']); + const bytes = await rt.fs.readFile(P + '/production/inputs/input-sheet.jpg'); + expect([bytes[0], bytes[1]]).toEqual([0xff, 0xd8]); + expect(bytes.length).toBeGreaterThan(20_000); + }); +}); diff --git a/skills/popost/tests/video/loop-commands.test.ts b/skills/popost/tests/video/loop-commands.test.ts index 8d6f16b..e12cd71 100644 --- a/skills/popost/tests/video/loop-commands.test.ts +++ b/skills/popost/tests/video/loop-commands.test.ts @@ -209,7 +209,9 @@ describe('popost video materials, retarget and readback', () => { expect(String(json().error)).toContain('set POPOST_GEN_CMD to a tool of yours'); await put('gen.mjs', GEN); const making = withEnv({ POPOST_GEN_CMD: process.execPath + ' ' + at('gen.mjs') }); - expect((await runCli(making, ['video', 'materials', 'requests.json', '--out', 'made'])).code).toBe(0); + // A generator of the user's own makes files at once: the user sees the inputs first (inputs.test.ts), or the run says nobody could be asked. + expect((await runCli(making, ['video', 'materials', 'requests.json', '--out', 'made'])).code).toBe(3); + expect((await runCli(making, ['video', 'materials', 'requests.json', '--out', 'made', '--unattended', 'a test batch'])).code).toBe(0); expect(json()).toMatchObject({ ok: true, made: 1, kept: 0, failed: 0, credits: 20, notes: at('made/materials.json') }); expect(await read('made/assets/logo.png')).toBe('image:a red logo'); }); diff --git a/skills/popost/tests/video/product-materials.test.ts b/skills/popost/tests/video/product-materials.test.ts index 80359e8..3691d0b 100644 --- a/skills/popost/tests/video/product-materials.test.ts +++ b/skills/popost/tests/video/product-materials.test.ts @@ -124,6 +124,8 @@ describe('a paid run with a product sheet', () => { { file: 'assets/street.mp4', prompt: 'a wet street at dusk', seconds: 5, cast: [], products: [] }, ]; const materials = (rt: TestRuntime, ...more: string[]) => cli(rt, 'video', 'materials', P + '/requests.json', '--out', P, ...more); + /** These runs are about the reference pictures: the inputs gate (inputs.test.ts) is passed as a batch nobody watches. */ + const SEEN = ['--unattended', 'a test of the reference order']; it('prices the list, stops before paying until the inferred facts are confirmed, then sends every product clip with the user\'s pictures and the same block', async () => { const { rt, stub, api } = await setup(); @@ -135,10 +137,14 @@ describe('a paid run with a product sheet', () => { // Pricing uploads the references (a quote names them); the stopped run sends nothing more and pays nothing. const before = stub.requests.length; const stopped = await materials(rt, '--no-anchor', '--confirm', '--max-credits', '100'); - expect([stopped.code, api.balance, stub.calls('POST', '/videos/generations').length, stub.requests.length - before]).toEqual([2, 500, 0, 1]); - expect(messages(stopped.data)[0]).toContain('Nothing was made or charged'); + expect([stopped.code, api.balance, stub.calls('POST', '/videos/generations').length, stub.requests.length - before]).toEqual([3, 500, 0, 1]); + expect(stopped.data.confirm.reason).toBe('inputs'); + expect(stopped.data.next).toContain('Nothing was made or charged'); - await cli(rt, 'video', 'product', 'confirm', P, '--quote', 'yes'); + // One answer for the inputs and for what was read from the product picture. + await cli(rt, 'video', 'inputs', 'show', P, '--requests', P + '/requests.json', '--no-anchor'); + await cli(rt, 'video', 'inputs', 'confirm', P, '--quote', 'yes'); + expect((await sheetOf(rt)).confirmation).toMatchObject({ by: 'user', quote: 'yes' }); const made = await materials(rt, '--no-anchor', '--confirm', '--max-credits', '100'); expect(made.data).toMatchObject({ ok: true, made: 3, chargedCredits: 75 }); // The user's two pictures were uploaded as they are, once each by content, and each product clip references both. @@ -176,7 +182,7 @@ describe('a paid run with a product sheet', () => { await cli(rt, 'video', 'product', 'confirm', P, '--quote', 'yes'); await rt.fs.writeFile(P + '/assets/place.png', HOST); await list(rt, requests.slice(0, 2)); - const roomy = await materials(rt, '--anchor-image', P + '/assets/place.png', '--confirm', '--max-credits', '100'); + const roomy = await materials(rt, '--anchor-image', P + '/assets/place.png', '--confirm', '--max-credits', '100', ...SEEN); expect(roomy.data).toMatchObject({ ok: true, made: 2 }); const first = stub.calls('POST', '/videos/generations')[0]?.json as Json; expect(first.references.images.length).toBe(3); @@ -189,7 +195,7 @@ describe('a paid run with a product sheet', () => { await tight.rt.fs.writeFile(P + '/assets/place.png', HOST); await list(tight.rt, requests.slice(0, 2)); tight.stub.set('GET', '/videos/models', () => ok({ models: [{ ...MODEL, maxReferenceImages: 2 }], default: 'video-a' })); - const full = await materials(tight.rt, '--anchor-image', P + '/assets/place.png', '--confirm', '--max-credits', '100'); + const full = await materials(tight.rt, '--anchor-image', P + '/assets/place.png', '--confirm', '--max-credits', '100', ...SEEN); expect(full.data).toMatchObject({ ok: true, made: 2 }); expect((full.data.notes as string[]).join('\n')).toContain('assets/hold.mp4: made without the anchor picture: the video model takes 2 reference pictures'); for (const q of tight.stub.calls('POST', '/videos/generations')) { @@ -202,7 +208,7 @@ describe('a paid run with a product sheet', () => { await cli(same.rt, 'video', 'product', 'confirm', P, '--quote', 'yes'); await list(same.rt, requests.slice(0, 2)); await same.rt.fs.writeFile('/work/given-front.png', FRONT); - await materials(same.rt, '--anchor-image', '/work/given-front.png', '--confirm', '--max-credits', '100'); + await materials(same.rt, '--anchor-image', '/work/given-front.png', '--confirm', '--max-credits', '100', ...SEEN); expect(same.stub.calls('POST', '/videos/generations').map((q) => (q.json as Json).references.images.length)).toEqual([2, 2]); }); }); diff --git a/skills/popost/tests/video/spending.test.ts b/skills/popost/tests/video/spending.test.ts index fbc02ca..1b5d44a 100644 --- a/skills/popost/tests/video/spending.test.ts +++ b/skills/popost/tests/video/spending.test.ts @@ -55,7 +55,8 @@ const list = async (rt: TestRuntime, requests: Json[]): Promise<void> => { await rt.fs.writeFile(PROJECT + '/requests.json', JSON.stringify(requests)); }; -const materials = (rt: TestRuntime, ...more: string[]) => cli(rt, 'video', 'materials', PROJECT + '/requests.json', '--out', PROJECT, '--no-anchor', ...more); +/** A paid run here is about the money: the inputs gate (inputs.test.ts) is passed as a batch nobody watches. */ +const materials = (rt: TestRuntime, ...more: string[]) => cli(rt, 'video', 'materials', PROJECT + '/requests.json', '--out', PROJECT, '--no-anchor', ...more, ...(more.includes('--confirm') ? ['--unattended', 'a test of the budget'] : [])); const record = async (rt: TestRuntime): Promise<Json> => JSON.parse(await rt.fs.readText(RECORD)); @@ -128,6 +129,11 @@ describe('a clip that is not among the agreed clips', () => { expect((await materials(rt, '--confirm', '--max-credits', '50')).code).toBe(0); await rt.fs.writeFile('/work/req.json', JSON.stringify({ prompt: 'a lamp', seconds: 5 })); const make = (...more: string[]) => cli(rt, 'video', 'generate', 'video', '/work/req.json', PROJECT + '/assets/lamp.mp4', '--confirm', '--max-credits', '100', ...more); + // A file of the project the user was never shown is not made, whatever the budget (inputs.test.ts). + expect((await make()).data.confirm).toMatchObject({ reason: 'inputs', pending: ['clip:assets/lamp.mp4'] }); + await rt.fs.writeFile(PROJECT + '/lamp.json', JSON.stringify([{ file: 'assets/lamp.mp4', prompt: 'a lamp', seconds: 5, cast: [] }])); + await cli(rt, 'video', 'inputs', 'show', PROJECT, '--requests', PROJECT + '/lamp.json', '--no-anchor'); + await cli(rt, 'video', 'inputs', 'confirm', PROJECT, '--unattended', 'a test of the agreed clips'); const asked = await make(); expect(asked.code).toBe(3); expect(asked.data.confirm).toMatchObject({ credits: 25, reason: 'unplanned', clip: { file: 'assets/lamp.mp4', what: 'a lamp', seconds: 5 } }); @@ -214,6 +220,10 @@ describe('one budget for the whole video', () => { await list(rt, TWO); const clips = await materials(rt, '--confirm', '--max-credits', String(60 - 2)); expect(clips).toMatchObject({ code: 0, data: { made: 2, chargedCredits: 50 } }); + // The project now keeps what its user was shown (inputs.test.ts): the voice and this line join it, as a batch nobody watches. + await cli(rt, 'video', 'inputs', 'voice', PROJECT, '--speaker', 'host', '--line', 'This line is long enough to cost ten credits, which is more than the eight credits that are left.'); + await cli(rt, 'video', 'inputs', 'show', PROJECT); + await cli(rt, 'video', 'inputs', 'confirm', PROJECT, '--unattended', 'a test of the budget'); // 8 are left; a line of 10 credits is asked about, and nothing is spoken or charged. const long = await speak('This line is long enough to cost ten credits, which is more than the eight credits that are left.', 60 - 2 - 50); expect(long.code).toBe(3); From 95afc06dc8b419242515d0889114d49d67f00bb9 Mon Sep 17 00:00:00 2001 From: Clipcat-ai <a2888409@gmail.com> Date: Thu, 3 Dec 2026 00:56:34 +0000 Subject: [PATCH 5/9] docs(video): one message before the first paid generation: cost, input sheet and summary Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Signed-off-by: Clipcat-ai <a2888409@gmail.com> --- skills/popost/references/onboarding.md | 1 + skills/popost/references/video-performers.md | 2 + skills/popost/references/video-product.md | 56 +++++++++++++------ skills/popost/references/video-step-1-read.md | 15 +++-- .../popost/references/video-step-3-content.md | 2 +- .../popost/references/video-step-6-voice.md | 10 ++++ skills/popost/references/video-tools.md | 18 ++++++ skills/popost/references/video.md | 21 +++++++ 8 files changed, 102 insertions(+), 23 deletions(-) diff --git a/skills/popost/references/onboarding.md b/skills/popost/references/onboarding.md index 5f44df3..3a47349 100644 --- a/skills/popost/references/onboarding.md +++ b/skills/popost/references/onboarding.md @@ -86,6 +86,7 @@ Suggested Chinese guidance, only when the user chooses API Key: “创建 API Ke 1. Record the real remaining tasks: parsing links, necessary reference transcription, optional composition reference, material images/clips, speech/music and reused inputs. Page count and total video duration are not new-generation counts. Do not charge Popost model credits for local planning or rendering. 2. Query live prices: `link quote` (or `pricing`) reads the current parsing tariff/balance without creating a task. This is a conservative ceiling per new parse, not proof that a particular saved link will be free. `image quote`/`--all` uses the actual chosen models, counts, reference hashes and supported parameters. `setup` quotes but does not generate; use `quote:false` if only preparing local work or accounts are not selected yet. Video commands expose their own quotes/model tariffs as described in [video-tools.md](video-tools.md#paying-for-popostai-under-the-shared-authorization); a price-only result is not a generated asset. 3. Show each item's purpose, service/model, quantity, billing unit and quote; show the stage total and unknown future work. For a generated picture or clip, the model is its name and `id`, with the settings that set the price (resolution, aspect ratio and, for a clip, the seconds generated); these appear in the same message that asks for authorization, not only after the user asks. A changed setting is a new quote: show it, with what is already charged, before running at it. Do not add another provider's currency to Popost credits. Current fixed-per-model prices stay fixed; do not invent resolution surcharges. + For a video, before its first paid generation, this is one message: the cost with the input sheet and the summary of `popost video inputs show` (every prompt as sent, the product and cast pictures, the voice and a sample), and the user's yes is recorded with `popost video inputs confirm` ([video.md](video.md), "Inputs first"). Do not ask for the budget, the product facts and the inputs in three turns. 4. Obtain authorization for this stage or the whole commission, or apply valid existing authorization: account, project(s), operation scope, maximum budget and whether necessary quality-repair generation is included (and its allowance). Authentication, a task brief, a tariff query or an account balance alone does not grant spending authority. Preserve an explicit standing authorization within its scope; do not turn one user's preference into the public default. Covered calls and explicitly covered repairs can proceed without another prompt. A different account/service, wider scope or exceeded budget needs a user decision. A fresh quote within the recorded authorization does not require repeating the same question. Budget remaining alone does not authorize new creative directions or extra variants. 5. Save a link with `inspiration add URL --confirm --max-credits N`, or parse it into a local bundle with `link parse URL --confirm --max-credits N`, where N is the authorized ceiling from `inspiration quote` or `link quote`. Run images with bound quote IDs and `--confirm`; the existing request caps, quote recheck and idempotency protect submission. Never execute a parse just to learn its price. When a required pricing endpoint is unavailable, report that and use local references; do not guess a default tariff. 6. Record actual charges and usable results. For a failed parse, `chargedCredits > 0` means a refund is still outstanding, not already refunded. Unknown charge/result states stay reserved until reconciled. Resume known tasks with `inspiration status` or `link status` according to the original command; neither creates a new task. Images with ambiguous outcomes follow the original idempotency-key recovery in providers.md. diff --git a/skills/popost/references/video-performers.md b/skills/popost/references/video-performers.md index ae1437b..3c72e74 100644 --- a/skills/popost/references/video-performers.md +++ b/skills/popost/references/video-performers.md @@ -71,6 +71,8 @@ popost video voice speak project --speaker host --text "Final words" --out proje `voice speak` also writes `project/assets/line.wav.words.json` when the platform returns word times (it prints `words`): the time of each Chinese character or Latin word, in seconds from the start of the WAV. `template fill --speak` and `retarget --speak` with a `popost:` voice time the captions word by word with these times, so they need no transcriber for it. +Before any paid generation the user sees who is in the video and hears who speaks: `popost video inputs show` puts every cast role's picture with its name on the input sheet (a role without a picture is shown by its description), and the voice with its script and a sample in the summary (video.md, "Inputs first"). A cast picture or a voice line changed afterwards is shown again. + `use` downloads the real preview and binds the platform voice id to the project profile. Official voices are already cloned; personal uploads are cloned on first actual speech use and the platform reuses that mapping afterwards. Listing, selection and quoting do not clone or charge. Speech is paid as images are, within the one budget of the video (`video.md`, money rule): the voice-over is in the cost overview (a `voice quote` of the script), and `voice speak` runs with `--confirm --max-credits <left>` and prints `chargedCredits`. Without `--confirm`, or above `--max-credits`, it speaks nothing and ends with exit code 3 and the price; ask the user only when the price is more than what is left. Each command enforces its own ceiling; there is no server-side or project-file budget. The resulting WAV and receipt are real synthesis results. Use this exact audio for voice-over, and for visible lip-sync shots where a lip-sync tool is configured. A hand-assembled narration (lines of `voice speak` mixed with other tools) is never a video's `"sound"` or an audio track: narration is the fill's `"voice"`, spoken by `template fill --speak`, and only for a reference with narration or a user who asked for one. For template narration and `plan --voice`, pass `popost:default-male`, `popost:default-female` or `popost:VOICE_ID`, and add `--confirm --max-credits <left>` to `plan --voice`, `template fill --speak` and `retarget --speak`: each prices all its lines first (a narration is spoken in takes of consecutive lines, one price a take; and the pace-calibration sentence, once per voice) and counts its ceiling down take by take. Pace calibration synthesizes audio even with `--dry`; it is not a free preview. A custom `POPOST_TTS_CMD` stays selected unless the voice explicitly starts with `popost:`. Repeating the same text, speed and output path uses the same operation key; an unknown result must be reconciled before making a new paid attempt. diff --git a/skills/popost/references/video-product.md b/skills/popost/references/video-product.md index 05bc797..924595f 100644 --- a/skills/popost/references/video-product.md +++ b/skills/popost/references/video-product.md @@ -8,8 +8,8 @@ picture draws a product of its own. A viewer who is sold one thing and shown ano Product first. Before any clip or picture is generated: -1. Write the product sheet from the user's pictures and words. -2. Show the user what you inferred, in one line, with the plan and its cost. +1. Write the product sheet from the user's pictures and words, and look at every picture for a person's face. +2. Show the user what you inferred and the picture that will be sent, with the plan and its cost, in one message. 3. Plan each shot by how the product's identity is carried in it. 4. Mark every request that shows the product; the pictures and the product block go with it by themselves. 5. After generation, check the product in every clip and in the finished video, by eye. @@ -21,9 +21,28 @@ popost video product init project --picture <file the user gave> [--picture <ano ``` It copies every picture into `project/assets/product/` byte for byte and writes the skeleton of -`project/production/product.json`. The pictures are the user's files as they sent them, **all of them**: never a -crop, a cut-out, a redraw, a re-compressed copy or a choice among them. A crop made to read a label is for your own -looking and stays out of the sheet. One product per `--id`; a video with two products runs `init` twice. +`project/production/product.json`. One product per `--id`; a video with two products runs `init` twice. Give `--lang +<code>` with the language the user writes in, and write the facts in it. + +**The picture that is sent.** A user's picture is often a screenshot: someone else holding the product, a video +player's controls, other products beside it. What goes to a model is the user's picture whole, or a crop of it: + +```bash +popost video product crop project --picture assets/product/flask-01.png --no-face-confirmed agent # sent whole +popost video product crop project --picture assets/product/flask-01.png --box 120,340,600,900 --no-face-confirmed agent # a crop is sent +``` + +- Open every picture. A person's face in it: crop it out. A picture with a face is never sent to a model; when the + product cannot be separated from the face, do not use that picture and ask the user for another. +- The crop shows the **whole** product, nothing of it cut off, with a little room around it. `--box` is + `x,y,width,height` in pixels of the user's picture. It is a plain rectangle of their pixels: never a cut-out, a + redraw, a retouch or a re-compressed copy. The original stays in the project with its hash (`"original"`). +- `--no-face-confirmed agent` says that you looked at the picture that is sent and saw no face. No program here can + tell a face, so this is your statement; the sheet has an error for every picture without it, and nothing that shows + the product is priced, uploaded or made before. When you cannot look at pictures, ask the user and record their + answer: `--no-face-confirmed user --note "<their words>"`. +- All the pictures the user gave go with every clip, each whole or cropped; do not choose among them. The user sees + the picture exactly as it is sent, on the input sheet, before anything is generated. Open each picture, then fill in every fact. Each fact says where it comes from: @@ -67,25 +86,27 @@ Open each picture, then fill in every fact. Each fact says where it comes from: - Invent nothing: no variant, flavour, size, accessory, packaging or label text the user's pictures and words do not show. When a fact cannot be read and the user did not say it, ask. -`popost video product check project` validates the sheet (every picture is the recorded file, every fact filled, +`popost video product check project` validates the sheet (every picture is the recorded file and was looked at, every fact filled, nothing shared between two products) and prints each product's `block`: the text every request that shows it is sent with. It is built from the sheet alone, so it is the same in every clip. Whether two free-text facts contradict each other the program cannot tell: read the block once as a whole before showing it. ## 2. The user confirms what was inferred -`product check` prints `confirm`: one line with every fact that is not the user's. Put that line into the message -that shows the plan and its cost (step 1), so the user corrects or agrees in the same answer. A correction goes into -the sheet as `"from": "user"` with their words. Then: +`product check` prints `confirm`: one line with every fact that is not the user's. It is part of the one message +that shows the user the inputs and the cost (video.md, "Inputs first"): `popost video inputs show` puts the line into +the summary and the picture as it is sent on the input sheet, so the user corrects or agrees in the same answer. A +correction goes into the sheet as `"from": "user"` with their words. Then: ```bash -popost video product confirm project --quote "<the user's answer>" +popost video inputs confirm project --quote "<the user's answer>" ``` -Paid generation of anything that shows the product waits for it (`materials` prices the list before, and stops -with an error after). The answer is bound to the facts: a fact edited later is asked about again. When nobody can be -asked (a batch the user commissioned to run without questions), `--unattended "<who authorised that, in their words>"` -records it, and the delivery notes list the inferred facts as unconfirmed. Never write an answer the user did not give. +It records the answer for the inputs and for these facts at once. Paid generation of anything that shows the product +waits for it. The answer is bound to what was shown: a fact, a picture or a crop changed later is asked about again. +When nobody can be asked (a batch the user commissioned to run without questions), `--unattended "<who authorised +that, in their words>"` records it, and the delivery notes list the inferred facts as unconfirmed. Never write an +answer the user did not give. (`popost video product confirm` still records the facts alone.) ## 3. Plan the shots: real picture first @@ -125,7 +146,8 @@ to the prompt, and keeps what was sent in `<clip>.product.json`. A clip from a f takes them (`popost video generate --models`, `maxReferenceImages`), or make the shot from the real picture (section 3). A picture is never left out to make a request fit; - a product clip whose `"firstFrame"` is not one of the user's pictures or a listed still; -- a sheet with errors; and, once the list is to be paid for, inferred facts the user has not confirmed. +- a sheet with errors (a picture nobody looked at for a face is one); and, once the list is to be paid for, inputs + or inferred facts the user has not confirmed. Reference pictures have an order when a model takes few: the product's pictures, then the cast's identity pictures, then the request's own `"images"`, then the shared anchor frame. The anchor is left out with a note when there is no @@ -169,6 +191,6 @@ changes action and at each clip boundary: drift shows there first. `--passed|--failed --by user --note "<their words>"`. Never present such a video as checked. A verdict belongs to the bytes that were looked at: a clip made again, or a new render, is unchecked until its own -sheet is built and judged. The delivery notes say, for the product: how many pictures the user gave and that all -went with every product clip, which shots use the real picture and which are generated, the verdict of each check, +sheet is built and judged. The delivery notes say, for the product: how many pictures the user gave, which were +cropped, and that all went with every product clip, which shots use the real picture and which are generated, the verdict of each check, what was regenerated or replaced, and any inferred fact the user did not confirm. diff --git a/skills/popost/references/video-step-1-read.md b/skills/popost/references/video-step-1-read.md index 6f8ac86..087bf83 100644 --- a/skills/popost/references/video-step-1-read.md +++ b/skills/popost/references/video-step-1-read.md @@ -131,7 +131,11 @@ can be part narration, part on camera. It writes `timeline.md` again: read its b beat a person says; sung words and fragments are no beats). `template save` refuses a reference whose kind is unconfirmed. -The cost overview and the one budget, now that the reference is read (leave out what this video does not use): +The cost overview, now that the reference is read (leave out what this video does not use). It is not a question +of its own: it goes to the user in the one message that also shows the inputs (`popost video inputs show`; video.md, +"Inputs first"), once the product sheet, the cast, the voice plan and the request list are written. None of that +costs anything, so prepare it first; the user answers once, for the budget and for what is sent. Ask for a budget +alone only when paid work must run before the list can exist, and then only for that work. - Voice-over, only when the kinds include `narration`: `popost video voice quote --voice default-male --text "<a script as long as the reference's narration>"` (an estimate until the lines are written), and a little for pace @@ -143,7 +147,7 @@ The cost overview and the one budget, now that the reference is read (leave out facts; [video-product.md](video-product.md)) and put the `confirm` line of `popost video product check project` into this overview: what you read from their picture and from how such a product is used, for them to correct or agree to in the same answer. Say which shots use their real picture and which are generated with it as reference. - Record the answer with `popost video product confirm`; paid generation of product shots waits for it. + `inputs show` puts that line into the summary, and `popost video inputs confirm` records the answer for it too. - The transcription already paid (`chargedCredits` of `describe`). - The music plan: `popost video music plan --project project --reading ref` proposes it from the reading of the reference's sound (one bed: the user's file first; else the reference's own music, kept as it is, when nobody speaks @@ -153,8 +157,8 @@ The cost overview and the one budget, now that the reference is read (leave out its music, ask for their own file first. When it says generated music is not available, say that one line and plan without a generated bed. -Show the remaining items, estimated total and balance, including any proposed quality-repair allowance, in the one -message that asks for the budget. The user must not have to ask which model or settings the money buys: for every +Show the remaining items, estimated total and balance, including any proposed quality-repair allowance, in that one +message, above the input sheet and the summary (which carries the prompts, the pictures and the voice). The user must not have to ask which model or settings the money buys: for every generated clip or picture that message names the model (its name and its `id` from `popost video generate --models`), the resolution, the length of each generated clip (the seconds the model makes, which can differ from the finished cut: say "an 8 s clip for a 7.5 s video" when they differ), the aspect ratio, how many, how it is billed (per second @@ -170,7 +174,8 @@ the user decides what to do: never turn a speaking person into silent footage wi Done when: you have opened every picture of `ref/`, `popost video elements check ref` prints `"ok": true` (every shot has an entry that says its layout, how it begins and ends as its frames show it, and which layers are the -platform's or the author's), the speech kind is confirmed, and the user agreed a budget (or no paid work is planned). +platform's or the author's), the speech kind is confirmed, and the cost overview is drafted for the one message +that shows the inputs (or no paid work is planned). Before saving a new replication template, run `popost video replication init ref --reference reference.mp4`, complete `replication.json` from the actual source video/audio, and run diff --git a/skills/popost/references/video-step-3-content.md b/skills/popost/references/video-step-3-content.md index 50391e0..5a23a74 100644 --- a/skills/popost/references/video-step-3-content.md +++ b/skills/popost/references/video-step-3-content.md @@ -80,7 +80,7 @@ the `box` of each element from `--outline` (`<skill>/references/video-scenes.md` the middle and nothing covers it. Otherwise zoom closer or hide what covers it, and record again. A shot of filmed material that no file of the user's shows can be generated when `generate` is set (step 0): write -the requests and run `popost video materials requests.json --out project --template template --confirm --max-credits <left> --no-wait` +the requests, show the user what will be sent (`popost video inputs voice project --speaker narrator --voice <voice> --fill fill.json` when the video has a voice, then `popost video inputs show project --requests requests.json --template template --lang <code>`; ONE message with the cost, the sheet and the summary; `popost video inputs confirm project --quote "<their words>"`; video.md, "Inputs first") and run `popost video materials requests.json --out project --template template --confirm --max-credits <left> --no-wait` (`video-tools.md`, "Generated clips": the request, the price, what it prints). The clips are made on popost.ai while you build the rest; run the same command again to pick them up before they are placed (nothing is paid twice). A shot in which a person says an on-camera beat is a clip with `"speech"`: the lines, who says each, their language and the beat each re-makes; the diff --git a/skills/popost/references/video-step-6-voice.md b/skills/popost/references/video-step-6-voice.md index 2d6cdac..acd1200 100644 --- a/skills/popost/references/video-step-6-voice.md +++ b/skills/popost/references/video-step-6-voice.md @@ -9,6 +9,16 @@ popost video preflight project popost video template check template --fill fill.json --assets project --pace <budgets.pace> --fit-tempo 1.12 ``` +The voice was shown to the user with the other inputs before anything was paid (video.md, "Inputs first"): `popost +video inputs voice project --speaker narrator --voice <voice> --fill fill.json` writes the voice plan (voice, speed, +lines), `inputs show` adds the voice's name, its script, its price and a sample the user can hear. The sample is the +platform's own preview of the voice (free; `production/inputs/voice-<speaker>-sample.wav`) or the recording +registered for the speaker; a voice without one gets no sample, and the summary names what a one-sentence sample +would cost so that the user can ask for it. Nothing is spoken to build the confirmation. `template fill --speak`, +`retarget --speak` and `voice speak` with `--confirm` speak only the voice and the lines of the confirmed plan: when +a line changed (shortened to fit, corrected), write the plan again, run `inputs show` and show the user the voice +alone. + `preflight` is `check --layout` and `scene check` in one call and, for a strict replication, what `replication check --artifact` finds before there is a video (the contract, `replication.plan.json` against the compiled timeline, `replication.audio.json`): it prints every problem at once, so correct them all and run it once more. Run it again diff --git a/skills/popost/references/video-tools.md b/skills/popost/references/video-tools.md index 86e093b..9d66124 100644 --- a/skills/popost/references/video-tools.md +++ b/skills/popost/references/video-tools.md @@ -320,6 +320,24 @@ that exists is never made again, so running it twice costs once, and what each f `project/materials.json`. Paid generation follows the money rule ("Paying for popost.ai") and the agreed clips ("The built-in generator"). +**The user sees the inputs first.** A paid run starts only once the user confirmed what is sent (video.md, "Inputs +first"); until then `materials` (and `generate` for a file of a project, and the paid voice commands) print +`{ "ok": false, "confirm": { "reason": "inputs", "pending": [...], "sheets": [...], "summary": "..." }, "next": "..." }` +and exit with 3, nothing charged: + +```bash +popost video inputs voice project --speaker narrator --voice popost:default-female --fill fill.json # the voice plan, when the video has a voice +popost video inputs show project --requests requests.json [--template template] [--lang zh] # free: sheet, summary, voice sample +popost video inputs confirm project --quote "<the user's words>" # after they answered the one message +``` + +`show` takes the anchor options of `materials` (`--anchor-image`, `--character`, `--no-anchor`) and composes every +request with the code `materials` sends it with; it writes `production/inputs/input-sheet.jpg` (needs the local +browser; without one it names the pictures to show one by one), `summary.md` to paste and `summary.json`. Prices are +the platform's free quotes (the reference pictures of a clip are uploaded for its quote, as `materials` without +`--confirm` does); a generator of your own has no price here. Keys name the items: `clip:<file>`, `picture:<file>`, +`product:<id>`, `cast:<id>`, `voice:<speaker>`, `anchor`. A file that exists is not asked about. + ```json [{ "file": "assets/walk.mp4", "prompt": "a woman walks briskly through a market, handheld, the camera follows", "seconds": 5, "aspect": "9:16", "images": ["assets/market.png"], "note": "the walk through the market" }] diff --git a/skills/popost/references/video.md b/skills/popost/references/video.md index b366e6d..a3e360f 100644 --- a/skills/popost/references/video.md +++ b/skills/popost/references/video.md @@ -23,6 +23,27 @@ keep their previous behavior; an approved repair uses a separate project and doe [video-sound.md](video-sound.md); before placing effects, read [video-sfx.md](video-sfx.md). These production checks remain required when onboarding or authorization has already been completed. +- Inputs first: before the first paid generation of a video, show the user everything that was prepared as the + input of a model and wait for their yes. `popost video inputs show project --requests requests.json --lang <the + language the user writes in>` builds it without paying: the input sheet (one picture: the product picture exactly + as it is sent, each person's picture with their name, every clip's reference pictures and frames, with captions) + and a summary (every prompt as it is sent, model, resolution, seconds, aspect ratio, credits; the voice, its script + and a sample to hear; the total). Send both in ONE message with the cost, and record the answer with `popost video + inputs confirm project --quote "<their words>"`. That one answer is the budget, the inputs and what was read from + the product picture: the user is asked once. `materials`, `generate` and the paid voice commands refuse with exit + code 3 and `confirm.reason: "inputs"` until then; a request, picture or voice line changed later is asked about + again, alone (run `inputs show` again). Only for a batch the user commissioned to run with nobody to ask: + `--unattended "<who authorised that, in their words>"`, and the delivery notes say the inputs were not confirmed. +- Language of prompts: write every clip and picture prompt, the facts of the product sheet and the voice script in + the language the user is writing in, and pass it once as `--lang <code>` (`product init` or `inputs show`; it is + stored in the project). The user then confirms exactly the text that is sent. The few sentences the program adds to + a prompt (product block, cast, anchor, speech and sound) are Chinese for `zh` and English for every other language. + Never translated: model ids, aspect ratios, file names, text printed on the product, brand names, quoted on-screen + text. A model whose entry in `popost video generate --models` says `"promptLanguage": "en"` is the exception: write + its prompts in English, and give the user a faithful version in their language first with the sent text underneath + (`popost video inputs translate project --item <key> --text "..."`; `inputs show` lists what is missing under + `displayMissing`, and a changed prompt asks for its version again). The same for a script in another language than + the user writes. Without `--lang` nothing changes: English sentences, one text. - Money: apply one commission authorization, with a budget for this video or an allocation inside an authorized batch. Popost voice-over, transcription, generated clips/pictures and music are paid when used; quotes are read-only. Cover any necessary paid reference analysis before it runs, within existing authorization or a separately agreed From 52ba1b89f44b5307df1481081acb12437618f4fa Mon Sep 17 00:00:00 2001 From: Clipcat-ai <a2888409@gmail.com> Date: Thu, 3 Dec 2026 00:56:39 +0000 Subject: [PATCH 6/9] chore(skill): SOURCE-MANIFEST for the input confirmation Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Signed-off-by: Clipcat-ai <a2888409@gmail.com> --- skills/popost/SOURCE-MANIFEST.sha256 | 73 +++++++++++++++------------- 1 file changed, 40 insertions(+), 33 deletions(-) diff --git a/skills/popost/SOURCE-MANIFEST.sha256 b/skills/popost/SOURCE-MANIFEST.sha256 index 9adc1c9..e9634da 100644 --- a/skills/popost/SOURCE-MANIFEST.sha256 +++ b/skills/popost/SOURCE-MANIFEST.sha256 @@ -586,7 +586,7 @@ d27b4dd0b10f7b13bbbfc6224af90a644dd95f5cd095435faaf31fe44a193b6f references/fon 6f9b20c5812c31b049963ecda109f27ebc278d8942d8c537c050140b383a0e7e references/host-editor.md cf4147c9b98ed0f136ce8ee1bbbd980db77e1358aeb5b85cacf6fb2d4f097798 references/image-workflow.md e299b21c239eb401f9eff1116f909d931c8a9743b052b6b65e51afd57aff33f8 references/imagery.md -38439175e90f1e5e85ac47cbbcb72d4df3084d2524a55891a81b06c02a7a53b4 references/onboarding.md +ee6d1c1c26132daee70e5a6b956d78852c1929cc026b918cba5401dee9a04b41 references/onboarding.md d8aa84ab56fd0ff7085e74e05a47298f8b23c321cd752be7bdb871bd00c481f7 references/platform-adaptation.md 0ea04ec878c7929f0fe873613787ed0f7ceb71041b051ffb98086a75d0077577 references/post-bundle.md 14a91cb8341c096fdfd5edc0005cc1acdd2787badc8d6267019955a8d8970380 references/project-manifest.md @@ -609,24 +609,24 @@ b8919045e2d5d6105a42a9e572c53acf538b2ec2fb8fec38803f6c47bfa79195 references/vid 73aaedadcdcfb393f934c0569de5f1dd48f49b82e06e0f3ea63d5c05a6025622 references/video-examples/template-demo/template.json cfe3a22c6f3fd09b25560f112513228de6ce196632c5c4139e9be259bccce50a references/video-motion.md 823de26535e88b1736d732d093036cd778e5c47b4b4a9a92d8a81a8640d3b5f0 references/video-native-observation.md -e5a6a9cf8fe602300be6db3a3aa7f9cd3ff663ac9e93588d9c61875d293706ed references/video-performers.md -b0ef03635ce3f83313d1c2347ffc099b1adf6f84d244dad73bc1937050e6cc35 references/video-product.md +46eb400a633d45e54768ca3ba61d41912f9f1f759f9695653376b8fa215a7729 references/video-performers.md +103c879a144b6c1860f9ca5fbd50d7dbc31210f305fbd7da51fa9386dcc81095 references/video-product.md 856b3f9b3872e571f7d4505f92584086d4f8d1abec4231bda3487a1a18465426 references/video-project.md d64eda959f59688eacf19915e20b60beb828cc92a74f94e14ffd0acfa5b7f832 references/video-replication.md d7220eaae4866c29c855720d42cff15d78adcae6acdb55a722a0a62ba74defb5 references/video-scenes.md 9b964b1bb3691c0a013d884fd5e3e1830ff106e5ccc0e9b9ff7ffded5f1fdcc6 references/video-sfx.md 6a82171339793a9d9da0a270de3cffe180da2dcbacd2e6b07fe6f6dd61e92329 references/video-sound.md a12a4139218b56530e73cb8c534e50d1cab8ecf41666fbb3fd83aa92ed2da5d5 references/video-step-0-machine.md -2f7d91e3375f110744cef11294c201ac1cc92d31a605b484cc5e4b97c89de11d references/video-step-1-read.md +d1ca3bbb9c4d086bda392ad1a0c092e0ed6bac24e9c09fddb00a66e1b26124cd references/video-step-1-read.md 46635b1729ea0cdd7020748ac1543e80244a314a11fc6b3271ffa4c4191f8007 references/video-step-2-structure.md -8c6254092b29c5834a0551af2ab3f040b74d26a5baee9417688249eec580a447 references/video-step-3-content.md +69a4612cd5dbffcb029e06f5b40acb91184965b023363d5ccd457a3b59b48c0c references/video-step-3-content.md 8697c23ce280c7a74c059e20cba370403c9c7424ac759e3f4b803e36300e5c14 references/video-step-4-lines.md a74f894b8f8652ed7e24bfbc1cbd9050b231c1d624e76810d3961b0c9e1ba08e references/video-step-5-scenes.md -ee63a0f5e5cc1230b3895d243897995c23fc3f711d1572e077e70cca26998749 references/video-step-6-voice.md +26cd8f5142b1958dbb02ae28766ce62e13336b1209cc0a58e674c8a0f9eb6514 references/video-step-6-voice.md 8287e464d2cb2baee59eabe14fe7617279d916f25881fc8f03957ac828933bda references/video-step-7-deliver.md aa60b78da67f9a29492aae836c2e6d336805c212301539e88e651aab5b21b061 references/video-templates.md -6ccb2fbc2298eb6e3d43b489394c0f2307238a8c94d639f605ff6bd2b1ea9904 references/video-tools.md -8b1713cb55b9c4f55e6db2b9c643273ab6a4e0737258a3a2d1707496dbda73e2 references/video.md +e4c537eac454e758a6db70cb1aba4bc885572aac74efd17cfaf91936b7facd79 references/video-tools.md +0eb8c1d8a8e569bc43baaebb34e1bad341a3bce03d8d9d7902b84894353d9268 references/video.md 9ce62b5d799a1e415a153348ae87740665998e9e97c7c34e47ae35adff2d50bc src/args.ts 6722276f8e90bbda70f169453e2671a529f7f57af17e03f9f74324a837ff2041 src/broken-pipe.ts 8c7adbc0a8e6a39aaa9eb624f9e145d98c062b95ea3022911f8f94fa94f11afe src/cli.ts @@ -658,7 +658,7 @@ e6d2ecd78fdbb49fb770fe179b872123d1f937ada79e6b09f3260d203735710a src/commands/a 0fdff5ff8b5b31317ab6c671210e03c06256e2c7bf85618566041c7ac6190ee4 src/commands/template.ts 513e2ec1ef5223a0650b5d821a3d5a3e1760337b80945a918a28a79731fd5128 src/commands/update.ts 58caeb8839f155f4d34de5349eafcab7a97abd5a28332d2f87c0611bd38f6a5e src/commands/usage.ts -d0d795e131cad9e0f9cdc785676b3ede4ddaa93e4d3d232c27558f7a2155b152 src/commands/video.ts +b25266aa53ff9236c41c42983e81f57762b5bf419e5e9f7e31ade21215f978ee src/commands/video.ts 1fd9320fe4a07c005153262fd6c28b7e5ffdaeb8ef609beaf3bfd3b9dbe95e25 src/commands/workflow.ts 6a34d6d7230f08cf542f5c429b647950743198f7c5b0addab8da88f075f38632 src/core/error-text.ts 3b15431209f7cc0c44f9e0d9b5a0918853153bbeca9137cd79410ee70b0fb1d9 src/core/errors.ts @@ -792,7 +792,7 @@ f98b2d85f0f12f260053a3ada68ed38003d0e2f1c8f39357c8f240738edfd37a src/video/capt d5ce6d64cbd2b4c5833200d105a983c03b04252c0a4bba0464fd59388d7c8a5a src/video/capture/index.ts ba6bb104589a7307e0c2a6f497e471e4223bc5e218839b456b248f4c116570e8 src/video/capture/stage.ts e52a80b6fda3af3b434f5a3936445213b7dad6985725d728d7f6fd0b2e7408bd src/video/capture/steps.ts -fb25ab777966fed81bdb4146757d6653671e0a6adf34fb0b799fa8e93fc8fed2 src/video/commands/cast.ts +ba5af9667563c0733d36bf9f5f21fa0eaf1da5592253eb6ef545201c8ccc51f3 src/video/commands/cast.ts eb5f4ea2e1d13d8766675a34059436df405297e08611046c6655cea8e4084469 src/video/commands/clean.ts 888c02481257af8feae0dbb46c9ef0174646debf8a973fa4cf7bb4b7928ef8af src/video/commands/clips.ts c86b61a6f192acd0bf7c0ba2ea3d668a57e56a3fedcbadfef879450e709abc73 src/video/commands/compare-scope.ts @@ -800,28 +800,29 @@ c86b61a6f192acd0bf7c0ba2ea3d668a57e56a3fedcbadfef879450e709abc73 src/video/comm a797f7bae8cb5f2cc895bd1b8fc5078f753909fc60ddb8a44217e11e09f0a3e4 src/video/commands/elements.ts 5a1c21cf0693d00ba64608af1b4ceffa0544615ce3d486a2639689c2ae7d7f9c src/video/commands/eval.ts c979cdc2b342fe1fe8057ce26f6288f0b8d34c9792419efc171d6323ea4fdfab src/video/commands/example.ts -addae35a81d4d10f7b484be613367b72268b67191d360260feb20536f048713d src/video/commands/generate.ts +898a99f161fd6cdeccdb0b4b6a2d6b1f0e58ae82fe783d69e652a64a22b9ccb1 src/video/commands/generate.ts +7577d25bd1b7217111d8f2e267e800ed56326b3a3ba8ea5b8fe3e1d6ed46517c src/video/commands/inputs.ts 095c56a85bc5743658317fe5009193c18f551a5506d2031eb225fb4d561fb1d5 src/video/commands/loop-shared.ts -754d0442abb07f97cdb5284bd57c351abd87cd13c3d7938d6a95fb26ff709adf src/video/commands/loop.ts +f38e00096d820bb3eb60d894a2e2c92e2292fef678654cebc753adca7885feb4 src/video/commands/loop.ts e0df23efe8d9eb0caaac956bfcb3264030b5d6c698fbce90afbdde056a95f773 src/video/commands/make.ts -58d51546448d7c80873e547563aa7eb36f4778ff2d6a6e57eac04701f7017d9f src/video/commands/materials.ts +7a20f4370bc97c790d2da502436ebbab2ea26d83b94e03ec1ce0e5688ac73273 src/video/commands/materials.ts 2ceba4aec37bb222fb626b600fd74df0f502c61bdc1d02b6bde1d81a4e017735 src/video/commands/measure.ts 3206fe5ec809867d231d8265fe0cc2058ee384633141d7cd008df9d7df0f0a11 src/video/commands/media.ts ac39d164e831a1fec8bdf8fb7dbb68c90cf3a8d2ab2edead5c8948e59b0ede13 src/video/commands/music-plan.ts 2630b256dba4db4088ee2f58ea39e0c07f703500ed8f29fc40a9e7461172291f src/video/commands/music.ts -5e703ff2fec6ac50d62e3052512ca556ad95d9e880431dda6e21139ba1682750 src/video/commands/product.ts +20b710ddb5d78936d4e1f6a25003b0275dff23e2fa6f4be708507bc1457148aa src/video/commands/product.ts f1638f5a2ecfb5f59adc6213949544826df3480c856431f756f22159a705a458 src/video/commands/read.ts 6275946ff5084ecac7103ec4f9dc6821189a9f031f31fc3db61ae0a61e7428a5 src/video/commands/replication-books.ts 65648504bce5d878269974e91b89332f609f72716b7a3ba25ee6413d460be640 src/video/commands/replication.ts c734138a7ca94b0570f385f2559f092b53c7b1c9eaa50b6d4bd5dd4aab5e6f7e src/video/commands/sfx-extract.ts ab3bf6ede426b26aac2df98895fa3e1ab9088972bd532323608a9405901f28dd src/video/commands/sfx-place.ts e456e0774393a996b864436cf2c1d057b7fcad6615e532ef58b5eb6b663fc834 src/video/commands/sfx.ts -1c23b689b17f8431bd023669fcec1894abbc698d9330ef187742b64173a90193 src/video/commands/shared.ts +9bf757c86d4055e535a232acb78b85f65667ca538301157cdf0b95244d4fdeaa src/video/commands/shared.ts 81fe4413f5bb61f53f5ab1c60f04771abba856e3e39e2bc872081b786ebb3ab4 src/video/commands/source.ts 701e28be1d6920387bf7d183a5d0776d7077275d49d9e13a615c7d39926a0b18 src/video/commands/speech-check.ts 1426ec9de690ddecfc2014e0d704a10c57cdbef70d2ba71184e5c5e2844ee48f src/video/commands/speech-kind.ts -2b20c317286fefd32227d359410578814e82c2de9a3821448a4bb98de99309da src/video/commands/template.ts -34d7204632244e29876cf73b388b323ed4a7e4e506617115bcdbd2125acd16e6 src/video/commands/voice-profile.ts +2541058e3e7f952712a334a9492d38ec666a888f7dcf1e792f70f41a273d0cf8 src/video/commands/template.ts +36f37e5512ece2c5576da0848c18c8d1e2e0a972d1e60295d6c01d0398ebcc37 src/video/commands/voice-profile.ts a9313923177d77c510905b2475c09bbff8dce3598702c0d537be0729f2926db6 src/video/commands/voice-sample.ts 0910b28d466960050ad960c8b56b43fa5487953de06d341be483adffd6e20b21 src/video/compile/footage.ts a2308c56ec4325ae70809ba9e45233fe547a37938d520bbf992518b5348b162d src/video/compile/index.ts @@ -869,18 +870,22 @@ c338f9be5833666f969dfe6bcf3566b712f1abac896af5770a6d8422fb057e6c src/video/eval 84b3d30f0ae2bba07137671f850e5f703cdfbf23fd2ebed465596b2243546e35 src/video/eval/readback.ts 13d7f4a54b56b7e0f9d6cc9bcd3263f1dc64f88a8a397318d1cc613a35a08f62 src/video/eval/roundtrip.ts 725483e05c55d29b55d4710705dc5d7ba90f638a1fa18e9acd5c9653bf8d6442 src/video/generate/approved.ts -77134c464084077f17dfa8fa50c0d57995dee1700d83585ffc52cf0c78f2c177 src/video/generate/cast.ts +7caea3dd79e1eab9707f75fa1577a55098ba8a4a03e03c503585479c6127907b src/video/generate/cast.ts b0afdadb19e13034c97c41d76f4d993bf938b5d64eb50426b711804216b79dfb src/video/generate/character.ts 05b138218b2a4bfb91b9f03a9fb08c336001d30a25691779999683c8e243019a src/video/generate/clip-sound.ts -79f99cbfc98ac4df02a91760cd25d3d4f56fee490eb3ea4321358a556c83b42c src/video/generate/cloud-image.ts -3cfa38de55f666e50d88467be8e41f3327c9f1b91792cc2d307e417496489fbd src/video/generate/cloud.ts -0642ddaf2ef46459ae3d266d4646a87b04c2b11732374b140e6e48f55b8d56c0 src/video/generate/dialogue.ts -c7c447b6f11e0a057c561d7c24301572b3dcf683f27411fc0bb9928863345eae src/video/generate/index.ts +a2aaedfd6e2c45fe019e0bb6230be7e72a332bb654ae20cd6e43b31c512d9f4c src/video/generate/cloud-image.ts +9cd26f50f3222031fee40c7657be0dea0e6a76fe063274c4b18e4b59d91e69b9 src/video/generate/cloud.ts +ecc26785962bcaba92747968d2d7596c789d56b3951de08ee71613926f81478c src/video/generate/dialogue.ts +dd2434a93cfb8c7226bf907412bacf65d23f2b70e4e97559704920671f8c4ea8 src/video/generate/index.ts ea7dc15810148e1012286c24b9307ec7093624f899088a45be56cd39624a110a src/video/generate/provenance.ts 84ad146c516ccb2790649ae8e12bfa632a5b9bb240d0f2282628455050104e87 src/video/generate/speech-lock.ts -83295f3dab0bdeff5f6ce2351df27d34512092bf8a607773981fa22952d0460e src/video/generate/speech.ts +adee4e4cec198f3a9d618cc2d3950c05ec4d508566e5bdf93fc158cba42c6b30 src/video/generate/speech.ts 3f47a8154f5dbee102d2ce5384af6f041bfc14eff46555079d8757363094901f src/video/host.ts 9a7aa437579f181f46621d7731574091417e5b6cfe0c2401520a468502082e02 src/video/hosted-api.ts +a83ea4d45210b7a0f77dac38b992cd059234828d4c6c3931a36b384ed8643544 src/video/inputs/collect.ts +ddafaa0358b1755684cc15f82ef9896baa9492591f3390b4c714b71f63357444 src/video/inputs/record.ts +ff51f4f9099c3f0166bb5518dd9aabe4649971e56fd95e0d01fb28f60e73c8b1 src/video/inputs/sheet.ts +24afdfa0c89d97ec195f29ce45d7620fdefce4a320ee7436007bb5ba552b05c8 src/video/inputs/summary.ts 9e025503c204f6b5c19c29836a9c709eb1b12f5257a739baa16d23736fcb8ebe src/video/look/index.ts bccadaca409e5a4dae8d6e8e787d372788253b87389833e6f5afb7d1e411620a src/video/look/like.ts ce6f0d6e67c14ea365a239f98e4a8e6c34b5bc24c680521a8367d7b12e337874 src/video/look/sheets.ts @@ -1016,9 +1021,9 @@ f31e90f373029ec6edf1e4fedbfcf890d360db776ece2779785f7dd5d4579e67 src/video/prev 7ab919d585552f3e893695dbee54f8032619ebf0b4d9dac97d13b73866cdd820 src/video/preview/studio-data.ts d53d3396c4beae3c8c84fe2ded909a62f9a42706f84e601b9c9a5162e43547d2 src/video/preview/thumbnails.ts 99cea536c874205409a477052856725dbc1a99c19ba7ed0f9911039f8536d279 src/video/preview/watch.ts -8aeafb5d7c6fbb2e6f3e77d0dd912efe8999e1425c57bb82379e0dd7fb0bc477 src/video/product/requests.ts +46ab494461a7561d5b85559fdcf2f72c03be41ecfa957743a5b6fade96473ce8 src/video/product/requests.ts 1c6b3f3a857b943a4154939fd5ce6fdae17f4c528c7fe25903599ea40ffc6e1d src/video/product/review.ts -0e27f06470c62ffbb4931fa051165f0972d839304a58f08045499e9aff2e7f63 src/video/product/sheet.ts +0cf96d202ade9540f5734132cf86127f8c4ec251d643082527a2f269e495fda7 src/video/product/sheet.ts 611c19ad71c88124f3c38eb485d881349263eac31361f7199995f42f40602c0e src/video/progress.ts bd146cd5b38dba1c8526dda4436725af0a87d81882f20824e1a199e0c7f83f1b src/video/project/check-camera.ts 500aaf0b58ee220ce72429404afd3ed89c5073c5379da4dfab647e9ee3993651 src/video/project/check-caption.ts @@ -1035,6 +1040,7 @@ cbc6ac71c18dce70bb571b5277b6bab324f653939ef9ab8034bca738cb2ae2c1 src/video/proj a50165be45e5d475393e3611ed7d48e8886865047bf618eeeb6860dc363ad8d0 src/video/project/schema.ts 39454f2ede4665be880fcb18e192e7626c0265a3cf9051e9c788df95d9a7c726 src/video/project/suggest.ts 45c520c73cc65f350f2a4effb4fb1a917c7938b3b2e0fad8e74afe6855ebd0dd src/video/project/words.ts +0c3e98006b9481ed2d48903641d181add41d30029fc7f87a172666a23091535b src/video/prompt-lang.ts 664293faae578d415a3a32bcc56f0fe3a0c758d77662e519f352a9f2f02dcf0a src/video/render/browser-step.ts fef34b41d08b0831d5d9ea0b4425ce3bdcf5216103396642d821aaf58ddb8cb0 src/video/render/chunked.ts 18149099d755c864df9c6a7b8c30ed5a2a8ab2a996a273348af2f59df4505bdb src/video/render/chunks.ts @@ -1106,7 +1112,7 @@ df111194176f64d6bba4ed0882a7b732bab6e9b7804f69dd8038ee5ac23b8372 src/video/sfx/ f2796a3cda54fcc3ee3a264be60aff3d44f004240b7df2137b3f159e2a1aa306 src/video/sound/analysis.ts 2204a8f320a357792720e9153b0b08bbddeed31c648c49443e91baaf22637cd0 src/video/sound/breaks.ts f28fc7be1a4d2150078a9f9f85cc54bf2fbc52766e09d0bae37029081d692260 src/video/sound/measure.ts -3a08d59e059bd0cbb1d3c49c6c2e914c2ffc793c273560e0d0736e9b669cac5d src/video/sound/modes.ts +b8c75e44d96a7708852d11e021f68a6f4ff2413fb3ca3e938b6f46ee9702298b src/video/sound/modes.ts 2a4a5ba88a77c6319dfc250b8db31569f4a6e564932a15ecef635fa2e3af1f0e src/video/sound/pcm.ts 640f6eca7881024449a14b0ff26803c2a0086f1aa6cdc7e89e9b8b193173266a src/video/sound/reading.ts e6ed79a089b264b1074d714527e3fd930268dd33aaeb901c32108a84a8c39c1f src/video/sound/speech-check.ts @@ -1172,7 +1178,7 @@ c5c11de4539c365984d9dba80c6de0c1cc95d72d167191b4b2475f2a58d64ab8 src/video/voic 1d43862a3138e6d80c7c08dad2b287d860fe795fd69d67df9f9ba3a912f89d4d src/video/voice/index.ts b39eba0a6937c571d80ad52e8aec372f50fa87eb1e24ca1695ea60e06be666c4 src/video/voice/pace.ts 5a8709a86fd08ec90de7e6d407ea860b1e3a6e5b35c82c31fdbf247ee99f4a9e src/video/voice/profile.ts -1ce1af8b17fd9768ba05b62dff7da2ea6e1ef85f860a89942f76d9cd802fb203 src/video/voice/sample.ts +37c349847aaf3e379edc3d2141b20d9963016401fcc2e6458194bcab6a6b53ad src/video/voice/sample.ts 260fa3ed0e6636275c96d2c46a967aa8a8bc11dac64c114c5b63c12ccbba2e78 src/video/wallet.ts 4bafd7f9005d2db847471ccc825aa94b0ab48289c924a2d40f33078ee8fa904d src/video/work.ts 2295c00c13d1287c573c266479125d8442a480766b87aa9427c41520c6838a6b src/workflow/build.ts @@ -2166,12 +2172,13 @@ a5d7139cb80a3c166a071bfe1167e2a7373b41e4a71f1af461f7b696cf312837 tests/video/ge 5404e10d4696de8354ecd298ae69319f45cd0e6c16c9db125a323f78c09d3c8f tests/video/hosted-transcription.test.ts 39578673199c27345ff720783fb77398a0877f9b08cdc6fa8e27680573d4ab5e tests/video/hosted-voice-words.test.ts 8fce58bd322d2797ae4c540b3a114329fea3f70e9e9b6c4aa53ecc98d9c475e2 tests/video/hosted-voice.test.ts +b29e2265f254f01dd15f8b86e42935a801ada82b8b1af024d5581091c10938d8 tests/video/inputs.test.ts d9053008e4cc2c6106d277895e1178cf15aaba8e2d14dc8dd3cbccd738d1cf90 tests/video/legibility.test.ts 8bf96469410ecc25455f49cf3ff8b8dd4d85f84a88be3174c7bcda1343f6126c tests/video/loop-align.test.ts 6c261892967e4310ec6449da7b9bdc048108f93e761b15d8f37f9dca74772927 tests/video/loop-beats-plan.test.ts 2168c0d52e442d45e6c3a9e4cb57a9d0cd3f90c1ad68744e21442f2ca02aed89 tests/video/loop-beats.test.ts 2470e9489f5a47190869bd88bc6138044069afb8e66c77ca50ffd796153de0fa tests/video/loop-caption-marks.test.ts -f9b6f1fa31e6644b4c2cef02b109a80b349ad28ffd2d2e4216b25edc5f9aea0e tests/video/loop-commands.test.ts +741acb7aa33e0b91c1378434acd66f5a21816da3f6ca8f9921da5b70dcf9e0b2 tests/video/loop-commands.test.ts c9a32f8be39a781021a2a20bd34f63267832690e0d732339b69f508922ef2ddc tests/video/loop-eval.test.ts 76ea1247a760faadc65f2af6d965bb173be181dcbd5e969f13f730dc4f1e0bd8 tests/video/loop-generate.test.ts e0e311587c004cd8fd8fd344940e8ce0a63fdc7ef61af72d74a0fef82e23c265 tests/video/loop-look.test.ts @@ -2240,10 +2247,10 @@ cdbbbc9a0ef9c112c23b34b03a84c3807de4b28cf92969edb2afb27a6c91db02 tests/video/pr 60741070dda478cfbeacbdce7bd5dd8668aee4992340cf5b288cde4a558f0825 tests/video/preview-studio-editing.test.ts befefa8d15567e7d62415abc589c64df76e495589e4ad1254793f65e9163c995 tests/video/preview-studio-linking.test.ts a5ffe9538b825c251722121ce1ce23cd5339cca0ff583e060f3e09084ea64d8d tests/video/preview-timeline-edit.test.ts -8095dc5a383f60130872ab23b8ce1a51219feb795fb9171277eff7307ece46ed tests/video/product-fixtures.ts -fcefbbbc81a6fd832ec2cbafafa3f7844c20447392373e13d90b68fbba987bb0 tests/video/product-materials.test.ts -5de04f64f06d45f6ee3b4e8797e9f8b1fd9a09aadb02c79a5e27915b168eedf9 tests/video/product-review.test.ts -ed0ee467b68f2d09fe53c66e3c69d7aa99681ac56bd699a5c798cb99a93db42a tests/video/product-sheet.test.ts +2dd873e6765856d2e4a79e88c4861d89e2fad3aabc92a83b1eb275ca94c94cf7 tests/video/product-fixtures.ts +1ff48728b111b2a8a402b50446fc67e1a65a9a168ce2b6a933f8979d27bc9c8a tests/video/product-materials.test.ts +0fa8247f7712d3c3b66a87bdb023b003fbf32b0881a8b08a1ce7544bbbcd53cc tests/video/product-review.test.ts +d3c15cc8d399718ce417ed50ae16e4db6862f42e7b812f6f7a798a69ccfbf238 tests/video/product-sheet.test.ts 60c2c23efed59387de7446383d722cca35a2ee3a9e7e6f08175feac9c3a2310c tests/video/read-aim.test.ts 2d408b85ac0e311b3f79da09630cdc27841ae4f5effd7719000b77085925f8fc tests/video/read-boundaries.test.ts 42e405fa0c71deea33c4e3e5e13f5d5f6e58e987fe7a537ff6b994671d5828a9 tests/video/read-camera.test.ts @@ -2324,7 +2331,7 @@ c5b9c97b2b662f1a9a8103ed439a5c586dcd978cc1aa7474a910412db320c5ad tests/video/sp 61e7fe7ed894b93c83dda0f00308be61d6d2faf3b870bd30638fbd3e4f231fed tests/video/speech-observed-integration.test.ts 4557f09eca386b118042dac388d29f1ee2a44bd78133cd835a111383f4a48454 tests/video/speech-observed.test.ts cbd37d976f22a70042cc08bae60013e12e659ce6fe651bb4517f55cfa058283d tests/video/speech-rules.test.ts -9af7708d49f16d515b8cb94a8da3121f35346fc849edb19d3236c60840e857e2 tests/video/spending.test.ts +5a0808e75ae572caf36aa7b949a2578563aa0ee9debd3fdc3101e85c23e51a1b tests/video/spending.test.ts 3cd0dc32b648cf3fc45fef009483638701c8a3fb9d94f3208cd8cd9a23cf0c34 tests/video/studio.test.ts 3586168f1032028183aad01c87501be1ec9f9f7eb4b9100077ec7bf3ce7c8163 tests/video/submit-retry.test.ts c0cf580f3dff4084edca56e2adfa10cf25211107684a35fa67793a122e83565e tests/video/unrecovered.test.ts From 014c3f735117dc8e5904f8f7b4b8d2625f90d9a8 Mon Sep 17 00:00:00 2001 From: Clipcat-ai <a2888409@gmail.com> Date: Thu, 3 Dec 2026 01:27:35 +0000 Subject: [PATCH 7/9] feat(link): resolve every redirect-only share link on the user's machine first MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `link parse` / `inspiration add` already followed Reddit share links locally and submitted the post link they lead to. The same now applies to every short link the platform resolves by following redirects: X `t.co`, Weibo `t.cn` (and mapp.api.weibo.cn/fx pages), Bilibili `b23.tv` and its mirrors, LinkedIn `lnkd.in` and Lemon8 `v.lemon8-app.com`. - Each platform has its own host allowlist and post-link pattern; the submitted link has no tracking query. https only, at most 5 hops of 10 s, manual redirects, a User-Agent, no cookies. - A hop may also be an HTML page that stands for a redirect (meta refresh, `location.replace("…")` / `location = "…"`, a link in <noscript>); only the first 64 KB are read. t.co serves this form to browsers. - Unchanged: nothing is requested before the fee is authorized, the result is printed as `resolvedUrl` (also by --dry-run), and any failure submits the original link so the platform follows it. - PLATFORM_HOSTS: t.co is an X host, the b23.tv mirrors are Bilibili hosts. Server side: popost.ai recognises t.co links and follows the same hop forms. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Signed-off-by: Clipcat-ai <a2888409@gmail.com> --- skills/popost/SOURCE-MANIFEST.sha256 | 12 +- skills/popost/references/post-bundle.md | 2 +- skills/popost/src/providers/link-resolve.ts | 245 +++++++++++++++++--- skills/popost/src/providers/link.ts | 7 +- skills/popost/src/workflow/post-bundle.ts | 4 +- skills/popost/tests/link-resolve.test.ts | 225 +++++++++++++++++- skills/popost/tests/post-bundle.test.ts | 2 + 7 files changed, 451 insertions(+), 46 deletions(-) diff --git a/skills/popost/SOURCE-MANIFEST.sha256 b/skills/popost/SOURCE-MANIFEST.sha256 index da86ee4..356abca 100644 --- a/skills/popost/SOURCE-MANIFEST.sha256 +++ b/skills/popost/SOURCE-MANIFEST.sha256 @@ -588,7 +588,7 @@ cf4147c9b98ed0f136ce8ee1bbbd980db77e1358aeb5b85cacf6fb2d4f097798 references/ima e299b21c239eb401f9eff1116f909d931c8a9743b052b6b65e51afd57aff33f8 references/imagery.md 38439175e90f1e5e85ac47cbbcb72d4df3084d2524a55891a81b06c02a7a53b4 references/onboarding.md d8aa84ab56fd0ff7085e74e05a47298f8b23c321cd752be7bdb871bd00c481f7 references/platform-adaptation.md -fd7a822c72b51144fcea0124211e8feec9b76396b7b71459bbb7732e850f4495 references/post-bundle.md +4f47d0aa803ca5115bb7e1268ab9ef6f710060a070854416cbb1804303244dfe references/post-bundle.md 14a91cb8341c096fdfd5edc0005cc1acdd2787badc8d6267019955a8d8970380 references/project-manifest.md 203a65b53a8391f834acd681971f763e4906e340f1d34b0a7ff9393b3f00489a references/providers.md a7b4b60f6023ef5655b940908b5b4a66142fa693e4e157d5e95f1af40be43f6d references/quality-review.md @@ -740,10 +740,10 @@ ed3aa393cda96bb2235ae5fd9cc3f5a4cf7e06a93bdc6b361d54d79b308ce617 src/providers/ e0acd44e5f8507e73325b409240a5b8a13108be028ec1c8dfb9c82cfc6714a95 src/providers/inspiration.ts 9696d3cffce4e1f3b22e016b52863a0cae28efffdec6900e34a87fd28d131fec src/providers/ledger.ts c32186d2eaa04d68012d42a27af39c57835667664a7995fe576fc1622fc5796c src/providers/link-bundle.ts -bf470886a21872279e996460f4d14ea55e2f2363dd47c6110eb8f11afe5556b6 src/providers/link-resolve.ts +e4870a2c729d5c14530e6952e527382b46a1bdb74fde4ae7d62aa6c3e9ae8f27 src/providers/link-resolve.ts 2e7364ead9f9af2afaccce914084b16cf067f80622b46c2a848d947d3698ee8f src/providers/link-task.ts 6ec8ec0780c0d9fab557102522d3fa32720ee4b7a6e724204c8ed7a111ad5dbc src/providers/link-video.ts -37903191d2516081d39c45a02f372ce4d535eb3a5975dabefb8e6f7939420cdd src/providers/link.ts +2adf9960419235b20a955abb873a5380214cfac83c22f4a170b261662c1484e3 src/providers/link.ts 0dbd7fad49ebdaf462b8eed9f77e73d90f0bf28fbdf42b6df6dcca582a7057a8 src/providers/manual-host.ts 4fac7cd9846ef58768c53be123e4672ca5bd437caf35195b7a37afdd132ae0e8 src/providers/paths.ts d533efd4ea0cd8e4ca9af39cab7206b7d0494932aa50379bb64a2f8a82dfc017 src/providers/popost-async.ts @@ -1182,7 +1182,7 @@ b39eba0a6937c571d80ad52e8aec372f50fa87eb1e24ca1695ea60e06be666c4 src/video/voic 04349a368cd7cbc006e7d75ef356eac8cc4273e9e003a2a8155c939c92b4d2bc src/workflow/errors.ts 0e55c0531670c725458ed3506ef96e3155dadb827eaa400cec9abcadc271c43a src/workflow/io.ts 2dad03a0107fd2f95102933ac1fa41d0f2925c2e119d96ed94079cd6ffd5dab3 src/workflow/page-check.ts -05cce4206de6c6b6537144a871e3e804c0c66c82eb3cc9c066ee182b886eb415 src/workflow/post-bundle.ts +cf7d862a908fd02e3fef2b75d1ef7f2c2fa53e8bd05eae318f21253dcc16a434 src/workflow/post-bundle.ts c353b7e124ca4e8b5630a008c367ed65789b4567e6f9a12ef9400a34e6954546 src/workflow/project-bundle.ts 8d9c5855088a8dab6c0057d8335993d6d9c143ad5a8e398f67518fe7a27b9765 src/workflow/review.ts 13cb07bfd000a8c3ad85b7582d8015277cc4a008e40274116bd5a8213610eddc src/workflow/series-plan.ts @@ -2107,13 +2107,13 @@ dfcfae410de5bae46e869a03236275f579806975bb19624cc98a06f78c907a7a tests/image-in 9298aee69a4f41406fb4a3a819d90338d78eebe6236a8da6aa41147be2c1bf9d tests/instagram-template-search.test.ts b8e4def0214b4956c2d0b1303b36ae8d7b11a5cf6abe6d3c33438f8d497b9ad1 tests/install.test.ts cf04f003f5d55c2310f90c061fb8f0d8b563217db06fba12c892dcd4b7d3684f tests/link-platforms.test.ts -d2d9d2951e09d33586313aad3dbad087918c1f64552d97ebd741e5b6db69e627 tests/link-resolve.test.ts +70770c4e7067f2067cde0c60d5cab7dfeb194270221812365ee3e749f365077a tests/link-resolve.test.ts 3e07be12ec9492c54e04a6ba0db899c9bdb8376406da728933f4ee242ad53045 tests/link.test.ts 1572bab4e564a30537be5073ee5294538899c78935057b5eb7e4597459edc2f2 tests/node-secret.test.ts a3d39e7e688a45bc2be1d75feb1884c8fc0299309b6f9dff423fd3b0d932c3db tests/package.test.ts 483afe9810f6ab8fda50272e79a1a0795ccecad46ccf8bb6fb51d3cc1f4bc4e7 tests/page-check.test.ts eca36d02f9e97642f6b9f379b10f189b1267c28cbe7f779be75f06fbd0a30095 tests/paid-gate.test.ts -3b40603da57ce1b9d1774347ecabddcb92ae0f607252ced69ec67382167199f1 tests/post-bundle.test.ts +5013f648268c8e9f7372c1f3fe3aa61783a2e428d640adb09f0be17119d179b0 tests/post-bundle.test.ts b86da1de70dd77e5cd209fc7b1d0fbd4625196857b115007f7568d53a65da7df tests/pricing.test.ts 284ddec9021c3aad6ad724d8e4181d8d6a8c59791b0c242a1b15351f1ca5eb04 tests/provider-custom.test.ts d06256a4210d18ba1461d733105c65c6bb893d31714bf1a608bb1a3a531570f6 tests/provider-mock.test.ts diff --git a/skills/popost/references/post-bundle.md b/skills/popost/references/post-bundle.md index 55a22cb..17dc6a9 100644 --- a/skills/popost/references/post-bundle.md +++ b/skills/popost/references/post-bundle.md @@ -44,7 +44,7 @@ link parse <URL> --confirm --max-credits N [--note "备注"] [--out DIR] [--time link status <task id> [--out DIR] [--timeout 900] [--no-download] [--no-video] [--config PRIVATE_CONFIG] ``` -Reddit share links (`/r/<sub>/s/<code>`) are resolved on the user's machine first: the CLI follows their redirects (free, reddit.com only) and submits the full `/comments/<id>` link, shown as `resolvedUrl` (also by `--dry-run`); if that fails the original link is submitted unchanged. +Short share links that only redirect to their post are resolved on the user's machine first: Reddit `/r/<sub>/s/<code>`, X `t.co`, Weibo `t.cn`, Bilibili `b23.tv` (and its mirrors), LinkedIn `lnkd.in`, Lemon8 `v.lemon8-app.com`. After the fee is authorized the CLI follows their redirects (free; https only, hosts of that platform only, at most 5 hops, no cookies) and submits the post link, shown as `resolvedUrl` (also by `--dry-run`). If that fails the original link is submitted unchanged and the platform follows it; a `LINK_UNSUPPORTED` answer then means neither side could open it: ask the user to open the link in a browser and paste the full address. A `t.co` link that leads to another site is not a post link. Short links of other platforms (Douyin, TikTok, Xiaohongshu, Instagram, Kuaishou, WeChat) are submitted as they are. 1. Run `link quote` (free read-only platform tariff/balance query), show the parsing charge separately from image fees and obtain authorization. `--dry-run` only describes the request locally; it does not query a price. Then submit with `--confirm --max-credits N`. 2. 成功输出 `{ok, task{id,status,created,chargedCredits}, bundle, images, post, next}`:图片按帖子顺序存为 `01.jpg`、`02.webp`…(类型取自文件头),和 `postbundle.json` 一起放在 `--out`(默认 `inputs/link-<任务 id 前 8 位>/`)。bundle 的 `resources[].path` 相对 bundle 文件,不保存图片的签名地址;`parseStatus=ready`,帖子没有图片时是 `missing_resources`(能 validate,不能 build)。`next` 是接着跑的 `validate`、`import`;复刻时再用 `attach-bundle` 登记为工程来源。 diff --git a/skills/popost/src/providers/link-resolve.ts b/skills/popost/src/providers/link-resolve.ts index 2122650..6854781 100644 --- a/skills/popost/src/providers/link-resolve.ts +++ b/skills/popost/src/providers/link-resolve.ts @@ -1,48 +1,150 @@ /** * Share links the CLI resolves on the user's own machine before a link is submitted to the platform. * - * A share link carries no post id: it only redirects to the post. Some sites refuse the platform's servers that - * redirect while a request from the user's machine gets it, so the CLI follows the redirects here and submits the post - * link it ends at. Nothing is charged for this and nothing but the link itself is requested: https only, only hosts of - * the same site, at most MAX_HOPS redirects of HOP_TIMEOUT_MS each, no cookies, response bodies discarded. When the - * walk fails for any reason the original link is submitted unchanged and the platform's own answer applies. + * A share link carries no post id: it only redirects to the post. The platform follows such links from its servers, and + * some sites refuse those requests while a request from the user's machine gets through, so the CLI follows the + * redirects here first and submits the post link it ends at. Nothing is charged for this and nothing but the link + * itself is requested: https only, only hosts of the same site, at most MAX_HOPS hops of HOP_TIMEOUT_MS each, no + * cookies. A hop is a 3xx with a Location header, or an HTML page that stands for one (meta refresh, + * `location.replace("…")`, a link in `<noscript>`; at most the first HTML_HOP_MAX_BYTES of it are read); every other + * response body is discarded. When the walk fails for any reason the original link is submitted unchanged and the + * platform resolves it (or says why it cannot). + * + * The table mirrors the platform's own rules for the same links; short links the platform hands to its data source + * (Douyin, TikTok, Xiaohongshu, Instagram, Kuaishou, WeChat) are not resolved here. */ import type { Runtime } from '../runtime'; export const MAX_HOPS = 5; export const HOP_TIMEOUT_MS = 10_000; +export const HTML_HOP_MAX_BYTES = 64 * 1024; /** Reddit answers 403 to a request without a User-Agent. */ const USER_AGENT = 'Mozilla/5.0 (compatible; link-preview)'; interface LocalShareRule { - /** The site's domain: the link and every redirect must be on it or a sub-domain of it. */ - readonly domain: string; - readonly isShareLink: (url: URL) => boolean; - /** The post link to submit when `url` is a post page, else null (keep following). */ - readonly postLink: (url: URL) => string | null; + readonly platform: string; + /** Domains (and their sub-domains) the link and every hop must be on. */ + readonly hosts: readonly string[]; + /** Whether `url` (https, on `hosts`) is a share link to resolve; a link that already names its post is not. */ + readonly isShareLink: (url: URL, host: string) => boolean; + /** The post link to submit when `url` is a post page, without tracking parameters, else null (keep following). */ + readonly postLink: (url: URL, host: string) => string | null; } +const hostIs = (host: string, domain: string): boolean => host === domain || host.endsWith(`.${domain}`); +const onHosts = (host: string, domains: readonly string[]): boolean => domains.some((domain) => hostIs(host, domain)); +/** `https://<host><path>` with no query, fragment or trailing slash. */ +const bare = (host: string, path: string): string => `https://${host}${path.replace(/\/+$/, '')}`; + const REDDIT_SHARE = /^\/(?:r|u|user)\/[A-Za-z0-9_-]{1,32}\/s\/[A-Za-z0-9]{4,32}\/?$/i; const REDDIT_POST = /^\/(?:(?:r|u|user)\/[A-Za-z0-9_-]{1,32}\/)?comments\/[A-Za-z0-9]{1,12}(?:\/[^/]*)?/i; -/** One entry per site whose share links are resolved locally. */ -const LOCAL_SHARE_RULES: readonly LocalShareRule[] = [ - { - domain: 'reddit.com', - isShareLink: (url) => REDDIT_SHARE.test(url.pathname), - // /r/<sub>/comments/<id>/<title>/ without the tracking query the redirect adds - postLink: (url) => { - const path = REDDIT_POST.exec(url.pathname)?.[0]; - return path ? `https://${url.hostname}${path.replace(/\/$/, '')}/` : null; - }, +const reddit: LocalShareRule = { + platform: 'reddit', + hosts: ['reddit.com'], + isShareLink: (url) => REDDIT_SHARE.test(url.pathname), + // /r/<sub>/comments/<id>/<title>/ without the tracking query the redirect adds + postLink: (url, host) => { + const path = REDDIT_POST.exec(url.pathname)?.[0]; + return path ? `${bare(host, path)}/` : null; }, -]; +}; -const onDomain = (url: URL, domain: string): boolean => { - const host = url.hostname.toLowerCase(); - return url.protocol === 'https:' && (host === domain || host.endsWith(`.${domain}`)); +const X_SHORT = /^\/[A-Za-z0-9]{4,40}\/?$/; +const X_STATUS = /^\/(?:(?<handle>[A-Za-z0-9_]{1,15})|i(?:\/web)?)\/status(?:es)?\/(?<id>\d{1,25})(?:\/|$)/; + +/** t.co wraps every link posted on X; only one that leads to a post is resolved. */ +const x: LocalShareRule = { + platform: 'x', + hosts: ['t.co', 'x.com', 'twitter.com'], + isShareLink: (url, host) => host === 't.co' && X_SHORT.test(url.pathname), + postLink: (url, host) => { + const groups = host === 't.co' ? undefined : X_STATUS.exec(url.pathname)?.groups; + return groups?.id ? `https://x.com/${groups.handle ? `${groups.handle}/status` : 'i/status'}/${groups.id}` : null; + }, }; +const WEIBO_SHORT = /^\/[A-Za-z0-9]{5,20}\/?$/; +const WEIBO_FX = /^\/fx\/[\w-]+\.html$/; +/** /detail/<id>, /status/<id>, /<uid>/<id>: the id is 12 to 20 digits or its 7 to 12 character base-62 form */ +const WEIBO_POST = /^\/(?:detail|status|\d{4,20})\/(?:\d{12,20}|[A-Za-z0-9]{7,12})\/?$/; +const WEIBO_ID = /^\d{12,20}$/; + +const weibo: LocalShareRule = { + platform: 'weibo', + hosts: ['t.cn', 'weibo.com', 'weibo.cn'], + isShareLink: (url, host) => + (host === 't.cn' && WEIBO_SHORT.test(url.pathname)) || (host === 'mapp.api.weibo.cn' && WEIBO_FX.test(url.pathname)), + postLink: (url, host) => { + if (host === 't.cn') return null; + if (WEIBO_POST.test(url.pathname)) return bare(host, url.pathname); + const shared = host === 'share.api.weibo.cn' && url.pathname.startsWith('/share/') ? url.searchParams.get('weibo_id') : null; + return shared && WEIBO_ID.test(shared) ? `https://m.weibo.cn/detail/${shared}` : null; + }, +}; + +const BILIBILI_SHORT_HOSTS: readonly string[] = ['b23.tv', 'bili2233.cn', 'bili22.cn', 'bili23.cn', 'bili33.cn']; +const BILIBILI_MAIN_HOSTS: ReadonlySet<string> = new Set(['bilibili.com', 'www.bilibili.com', 'm.bilibili.com']); +/** "BV" + 10 base-58 characters, or "av" + digits: a short link with such a path already names its video. */ +const BILIBILI_VIDEO_ID = /^(?:[Bb][Vv][1-9A-HJ-NP-Za-km-z]{10}|[Aa][Vv]\d{1,16})$/; +const BILIBILI_VIDEO = /^\/(?:s\/)?video\/([^/?#]+)/; +const BILIBILI_OPUS = /^\/(?:opus|dynamic)\/(\d{1,20})(?:\/|$)/; +const BILIBILI_T = /^\/(?:h5\/dynamic\/detail\/)?(\d{1,20})(?:\/|$)/; + +const bilibiliVideo = (id: string | null | undefined): string | null => + id && BILIBILI_VIDEO_ID.test(id) ? `https://www.bilibili.com/video/${/^bv/i.test(id) ? `BV${id.slice(2)}` : `av${id.slice(2)}`}` : null; +const bilibiliOpus = (id: string | undefined): string | null => (id ? `https://www.bilibili.com/opus/${id}` : null); + +const bilibili: LocalShareRule = { + platform: 'bilibili', + hosts: ['bilibili.com', ...BILIBILI_SHORT_HOSTS], + isShareLink: (url, host) => { + const code = url.pathname.split('/')[1] ?? ''; + return onHosts(host, BILIBILI_SHORT_HOSTS) && code !== '' && !BILIBILI_VIDEO_ID.test(code); + }, + postLink: (url, host) => { + if (onHosts(host, BILIBILI_SHORT_HOSTS)) return bilibiliVideo(url.pathname.split('/')[1]); + if (host === 't.bilibili.com') return bilibiliOpus(BILIBILI_T.exec(url.pathname)?.[1]); + if (!BILIBILI_MAIN_HOSTS.has(host)) return null; + return ( + bilibiliVideo(BILIBILI_VIDEO.exec(url.pathname)?.[1]) ?? + bilibiliOpus(BILIBILI_OPUS.exec(url.pathname)?.[1]) ?? + bilibiliVideo(url.searchParams.get('bvid')) + ); + }, +}; + +const LINKEDIN_SHORT = /^\/[\w-]+\/?$/; +const LINKEDIN_POST = /^\/(?:feed\/update\/urn:li:(?:activity|share|ugcPost):\d{18,20}|posts\/[\w.%-]+-activity-\d{18,20}(?:-[\w-]+)?|pulse\/[\w%-]+)\/?$/; + +const linkedin: LocalShareRule = { + platform: 'linkedin', + hosts: ['lnkd.in', 'linkedin.com'], + isShareLink: (url, host) => host === 'lnkd.in' && LINKEDIN_SHORT.test(url.pathname), + postLink: (url, host) => { + const path = url.pathname.replace(/%3a/gi, ':'); + return host !== 'lnkd.in' && LINKEDIN_POST.test(path) ? bare('www.linkedin.com', path) : null; + }, +}; + +const LEMON8_SHORT = /^\/(?:al|s)\/[\w-]{4,64}\/?$/; +const LEMON8_POST = /^\/(?:[a-z]{2}(?:-[a-z]{2})?\/)?(?:@|%40)([\w.-]{1,64})\/(\d{18,20})\/?$/i; + +const lemon8: LocalShareRule = { + platform: 'lemon8', + hosts: ['lemon8-app.com'], + isShareLink: (url, host) => host === 'v.lemon8-app.com' && LEMON8_SHORT.test(url.pathname), + postLink: (url, host) => { + const match = host === 'v.lemon8-app.com' ? null : LEMON8_POST.exec(url.pathname); + return match?.[1] && match[2] ? `https://www.lemon8-app.com/@${encodeURIComponent(match[1])}/${match[2]}` : null; + }, +}; + +/** One entry per site whose share links are resolved locally. */ +const LOCAL_SHARE_RULES: readonly LocalShareRule[] = [reddit, x, weibo, bilibili, linkedin, lemon8]; + +const hostOf = (url: URL): string => url.hostname.toLowerCase(); + const parse = (raw: string, base?: URL): URL | null => { try { return new URL(raw, base); @@ -51,18 +153,99 @@ const parse = (raw: string, base?: URL): URL | null => { } }; -const ruleFor = (url: URL): LocalShareRule | undefined => LOCAL_SHARE_RULES.find((rule) => onDomain(url, rule.domain) && rule.isShareLink(url)); +const ruleFor = (url: URL): LocalShareRule | undefined => { + const host = hostOf(url); + return url.protocol === 'https:' ? LOCAL_SHARE_RULES.find((rule) => onHosts(host, rule.hosts) && rule.isShareLink(url, host)) : undefined; +}; + +const ENTITIES: Readonly<Record<string, string>> = { amp: '&', quot: '"', apos: "'", lt: '<', gt: '>' }; + +const decodeEntities = (value: string): string => + value.replace(/&(?:#x([0-9a-f]{1,6})|#(\d{1,7})|([a-z]{2,4}));/gi, (whole: string, hex?: string, dec?: string, name?: string) => { + if (name) return ENTITIES[name.toLowerCase()] ?? whole; + const code = Number.parseInt(hex ?? dec ?? '', hex ? 16 : 10); + return code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : whole; + }); + +const attributeOf = (tag: string, name: string): string | null => { + const match = new RegExp(`[\\s"']${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s"'>]+))`, 'i').exec(tag); + const value = match?.[1] ?? match?.[2] ?? match?.[3]; + return value === undefined ? null : decodeEntities(value).trim(); +}; + +/** content="0;URL=https://…" (the url may be quoted, "url=" may be missing) */ +const REFRESH_CONTENT = /^\s*\d+(?:\.\d+)?\s*[;,]\s*(?:url\s*=\s*)?(["']?)(.+?)\1\s*$/i; +const JS_LOCATION = /\blocation(?:\.replace\(\s*|(?:\.href)?\s*=\s*)(?:"((?:[^"\\\n]|\\.)*)"|'((?:[^'\\\n]|\\.)*)')/; + +const metaRefreshOf = (html: string): string | null => { + for (const [tag] of html.matchAll(/<meta\b[^>]*>/gi)) { + if (attributeOf(tag, 'http-equiv')?.toLowerCase() !== 'refresh') continue; + const target = REFRESH_CONTENT.exec(attributeOf(tag, 'content') ?? '')?.[2]; + if (target) return target; + } + return null; +}; + +/** The string literal of a `location.replace("…")` / `location(.href) = "…"`, unescaped (\/, \uXXXX, \xXX). */ +const jsLocationOf = (html: string): string | null => { + const match = JS_LOCATION.exec(html); + const literal = match?.[1] ?? match?.[2]; + if (!literal) return null; + return literal.replace(/\\(?:u([0-9a-fA-F]{4})|x([0-9a-fA-F]{2})|(.))/g, (_whole: string, unicode?: string, hex?: string, char?: string) => + char === undefined ? String.fromCharCode(Number.parseInt(unicode ?? hex ?? '', 16)) : char, + ); +}; + +const noscriptLinkOf = (html: string): string | null => { + for (const [, inner] of html.matchAll(/<noscript\b[^>]*>([\s\S]*?)<\/noscript>/gi)) { + const anchor = /<a\b[^>]*>/i.exec(inner ?? '')?.[0]; + const href = anchor ? attributeOf(anchor, 'href') : null; + if (href) return href; + } + return null; +}; + +/** + * Where an HTML page sends its reader, or null: a meta refresh, then a `location.replace("…")` / `location = "…"` with + * a string literal, then a link inside `<noscript>`. Nothing else is read as a redirect. + */ +export const htmlRedirectTarget = (html: string): string | null => metaRefreshOf(html) ?? jsLocationOf(html) ?? noscriptLinkOf(html); + +/** The start of the body as text, at most `maxBytes` of it; the rest is not downloaded. */ +const readHead = async (response: Response, maxBytes: number): Promise<string> => { + const reader = response.body?.getReader(); + if (!reader) return ''; + const decoder = new TextDecoder(); + let text = ''; + let bytes = 0; + try { + while (bytes < maxBytes) { + const { done, value } = await reader.read(); + if (done) break; + const chunk = value.subarray(0, maxBytes - bytes); + bytes += chunk.byteLength; + text += decoder.decode(chunk, { stream: true }); + } + } finally { + void reader.cancel().catch(() => undefined); + } + return text; +}; -/** Where the hop redirects to, or null (not a redirect, refused, network error, timeout). */ +/** Where the hop leads (a 3xx Location, or the redirect an HTML page stands for), or null (neither, refused, network error, timeout). */ const nextHop = async (rt: Runtime, current: URL): Promise<URL | null> => { try { const response = await rt.fetch(current.href, { method: 'GET', redirect: 'manual', credentials: 'omit', - headers: { 'User-Agent': USER_AGENT, Accept: 'text/html' }, + headers: { 'User-Agent': USER_AGENT, Accept: 'text/html', 'Accept-Encoding': 'identity' }, signal: AbortSignal.timeout(HOP_TIMEOUT_MS), }); + if (response.status >= 200 && response.status < 300 && /html/i.test(response.headers.get('content-type') ?? '')) { + const target = htmlRedirectTarget(await readHead(response, HTML_HOP_MAX_BYTES)); + return target ? parse(target, current) : null; + } void response.body?.cancel().catch(() => undefined); const location = response.headers.get('location'); return response.status >= 300 && response.status < 400 && location ? parse(location, current) : null; @@ -73,17 +256,17 @@ const nextHop = async (rt: Runtime, current: URL): Promise<URL | null> => { /** * The post link a share link leads to, or null when `link` is not a share link resolved locally or the walk did not - * reach a post (refused, failed, left the site, too many redirects). + * reach a post (refused, failed, left the site, too many hops). */ export const resolveShareLink = async (rt: Runtime, link: string): Promise<string | null> => { - const start = parse(link.replace(/^http:\/\//i, 'https://')); + const start = parse(link.trim().replace(/^http:\/\//i, 'https://')); const rule = start && ruleFor(start); if (!start || !rule) return null; let current: URL | null = start; for (let hop = 0; hop < MAX_HOPS; hop++) { current = await nextHop(rt, current); - if (!current || !onDomain(current, rule.domain)) return null; - const post = rule.postLink(current); + if (!current || current.protocol !== 'https:' || !onHosts(hostOf(current), rule.hosts)) return null; + const post = rule.postLink(current, hostOf(current)); if (post) return post; } return null; diff --git a/skills/popost/src/providers/link.ts b/skills/popost/src/providers/link.ts index 86c4414..57642c1 100644 --- a/skills/popost/src/providers/link.ts +++ b/skills/popost/src/providers/link.ts @@ -19,9 +19,10 @@ * the key is read when a request is sent and is scrubbed from everything printed. `--dry-run` sends nothing to the * platform and needs no key. * - * A share link that only redirects to its post (link-resolve.ts: Reddit's `/r/<sub>/s/<code>`) is first followed on this - * machine, free of charge, and the post link it leads to is submitted in its place and printed as `resolvedUrl` (also by - * `--dry-run`); when that fails the original link is submitted unchanged. + * A share link that only redirects to its post (link-resolve.ts: Reddit's `/r/<sub>/s/<code>`, X's `t.co`, Weibo's + * `t.cn`, Bilibili's `b23.tv`, LinkedIn's `lnkd.in`, Lemon8's `v.lemon8-app.com`) is first followed on this machine, + * free of charge, and the post link it leads to is submitted in its place and printed as `resolvedUrl` (also by + * `--dry-run`); when that fails the original link is submitted unchanged and the platform follows it. */ import { printJson, writeJson } from '../core/util'; import { msg } from '../i18n'; diff --git a/skills/popost/src/workflow/post-bundle.ts b/skills/popost/src/workflow/post-bundle.ts index 077268d..914b83d 100644 --- a/skills/popost/src/workflow/post-bundle.ts +++ b/skills/popost/src/workflow/post-bundle.ts @@ -43,12 +43,12 @@ export const PLATFORM_HOSTS: Readonly<Record<Platform, readonly string[]>> = { tiktok: ['tiktok.com'], xiaohongshu: ['xiaohongshu.com', 'xhslink.com'], instagram: ['instagram.com'], - x: ['x.com', 'twitter.com'], + x: ['x.com', 'twitter.com', 't.co'], youtube: ['youtube.com', 'youtu.be', 'youtube-nocookie.com'], threads: ['threads.com', 'threads.net'], linkedin: ['linkedin.com', 'lnkd.in'], reddit: ['reddit.com', 'redd.it'], - bilibili: ['bilibili.com', 'b23.tv'], + bilibili: ['bilibili.com', 'b23.tv', 'bili2233.cn', 'bili22.cn', 'bili23.cn', 'bili33.cn'], lemon8: ['lemon8-app.com'], kuaishou: ['kuaishou.com', 'kuaishou.cn', 'chenzhongtech.com', 'gifshow.com'], wechat: ['weixin.qq.com'], diff --git a/skills/popost/tests/link-resolve.test.ts b/skills/popost/tests/link-resolve.test.ts index c142c12..edad2bb 100644 --- a/skills/popost/tests/link-resolve.test.ts +++ b/skills/popost/tests/link-resolve.test.ts @@ -1,10 +1,11 @@ /** - * Share links resolved on the user's machine (providers/link-resolve.ts): `link parse` / `inspiration add` follow a - * Reddit share link's redirects with the runtime's fetch and submit the post link it leads to. The site is a fake - * fetch; the platform is the in-memory fake of the open API. + * Share links resolved on the user's machine (providers/link-resolve.ts): `link parse` / `inspiration add` follow the + * redirects of a share link (Reddit, X, Weibo, Bilibili, LinkedIn, Lemon8) with the runtime's fetch and submit the post + * link it leads to. The site is a fake fetch; the platform is the in-memory fake of the open API. */ import { describe, expect, it } from 'vitest'; import type { FetchHandler } from '../src/testing/memory'; +import { htmlRedirectTarget } from '../src/providers/link-resolve'; import { cli, err, newScene, ok, BASE_URL } from './image-helpers'; const SHARE = 'https://www.reddit.com/r/aww/s/8f7eKqYppb'; @@ -107,3 +108,221 @@ describe('a Reddit share link in link parse / inspiration add', () => { expect(t.hops).toHaveLength(0); }); }); + +interface Case { + readonly platform: string; + readonly share: string; + /** Where the site redirects the share link, tracking parameters included. */ + readonly target: string; + /** What is submitted instead. */ + readonly post: string; + /** A host of the same site the walk may pass through. */ + readonly via: string; + /** Links that already name their post: submitted as they are, nothing requested. */ + readonly untouched: readonly string[]; +} + +const CASES: readonly Case[] = [ + { + platform: 'reddit', + share: SHARE, + target: `${POST}?share_id=abc&utm_source=share`, + post: POST, + via: 'https://old.reddit.com/over18', + untouched: [POST, 'https://redd.it/1yaynge'], + }, + { + platform: 'x', + share: 'https://t.co/DTc4cHspt8', + target: 'https://twitter.com/NASA/status/1863000000000000001/photo/1?s=20&t=abc', + post: 'https://x.com/NASA/status/1863000000000000001', + via: 'https://x.com/i/redirect', + untouched: ['https://x.com/NASA/status/1863000000000000001', 'https://twitter.com/i/web/status/1863000000000000001'], + }, + { + platform: 'weibo', + share: 'https://t.cn/A6qHeVlf', + target: 'https://weibo.com/5819018196/OCT5GxFOU?refer_flag=1001030103_&type=comment', + post: 'https://weibo.com/5819018196/OCT5GxFOU', + via: 'https://passport.weibo.com/visitor', + untouched: ['https://weibo.com/5819018196/OCT5GxFOU', 'https://m.weibo.cn/detail/5092682368025584'], + }, + { + platform: 'bilibili', + share: 'https://b23.tv/AbCd123', + target: 'https://www.bilibili.com/video/BV1GJ411x7h7/?share_source=copy_web&vd_source=abc', + post: 'https://www.bilibili.com/video/BV1GJ411x7h7', + via: 'https://m.bilibili.com/redirect', + untouched: ['https://www.bilibili.com/video/BV1GJ411x7h7', 'https://b23.tv/BV1GJ411x7h7', 'https://b23.tv/av170001'], + }, + { + platform: 'linkedin', + share: 'https://lnkd.in/gJ4pUZ7', + target: 'https://www.linkedin.com/posts/creator_document-activity-7529220987423182848-abcd?utm_source=share&utm_medium=member_desktop', + post: 'https://www.linkedin.com/posts/creator_document-activity-7529220987423182848-abcd', + via: 'https://www.linkedin.com/redir/redirect', + untouched: ['https://www.linkedin.com/posts/creator_document-activity-7529220987423182848-abcd'], + }, + { + platform: 'lemon8', + share: 'https://v.lemon8-app.com/al/OgTtgvsFsr', + target: 'https://www.lemon8-app.com/@creator/7581476112027484686?region=us&share_platform=copy', + post: 'https://www.lemon8-app.com/@creator/7581476112027484686', + via: 'https://www.lemon8-app.com/redirect', + untouched: ['https://www.lemon8-app.com/@creator/7581476112027484686'], + }, +]; + +const page = (body: string): Response => new Response(body, { status: 200, headers: { 'content-type': 'text/html; charset=utf-8' } }); +/** What t.co answers a browser: a meta refresh inside noscript and a location.replace with escaped slashes. */ +const refreshPage = (target: string): Response => + page( + `<head><noscript><META http-equiv="refresh" content="0;URL=${target.replace(/&/g, '&')}"></noscript><title>${target}` + + ``, + ); + +describe.each(CASES)('a $platform share link', (item) => { + it('follows a chain of 3xx redirects on the site and submits the post link', async () => { + const t = await scene((request) => (request.url === item.share ? redirect(item.via) : redirect(item.target))); + const { data } = await cli(t.rt, 'link', 'parse', item.share, ...CONFIRM); + expect(t.hops.map((hop) => hop.url)).toEqual([item.share, item.via]); + expect(t.submittedUrls()).toEqual([item.post]); + expect(data.resolvedUrl).toBe(item.post); + for (const hop of t.hops) { + expect(hop.redirect).toBe('manual'); + expect(hop.headers.get('user-agent')).toBeTruthy(); + expect(hop.headers.get('cookie')).toBeNull(); + expect(hop.headers.get('authorization')).toBeNull(); + } + }); + + it('follows a page that stands for a redirect (meta refresh, location.replace)', async () => { + const meta = await scene(() => refreshPage(item.target)); + const { data } = await cli(meta.rt, 'inspiration', 'add', item.share.replace('https://', 'http://'), ...CONFIRM); + expect(meta.hops.map((hop) => hop.url)).toEqual([item.share]); + expect(meta.submittedUrls()).toEqual([item.post]); + expect(data.resolvedUrl).toBe(item.post); + + const js = await scene(() => page(``)); + await cli(js.rt, 'link', 'parse', item.share, ...CONFIRM); + expect(js.submittedUrls()).toEqual([item.post]); + }); + + it('never follows a redirect or a page to a foreign host or to plain http', async () => { + const foreign = new URL(item.target); + foreign.hostname = 'evil.example'; + for (const site of [() => redirect(foreign.href), () => refreshPage(foreign.href), () => redirect(item.target.replace('https://', 'http://'))] as Site[]) { + const t = await scene((request) => (request.url === item.share ? site(request) : redirect(item.target))); + const { data } = await cli(t.rt, 'link', 'parse', item.share, ...CONFIRM); + expect(t.hops.map((hop) => hop.url)).toEqual([item.share]); + expect(t.submittedUrls()).toEqual([item.share]); + expect(data).not.toHaveProperty('resolvedUrl'); + } + }); + + it('falls back to the original link when the walk fails', async () => { + const sites: Site[] = [ + () => new Response('blocked', { status: 403 }), + () => new Response('gone', { status: 404 }), + () => { throw new TypeError('fetch failed'); }, + () => page('a page with no redirect'), + () => page(`${' '.repeat(64 * 1024)}`), + () => new Response(``, { status: 200, headers: { 'content-type': 'application/json' } }), + ]; + for (const site of sites) { + const t = await scene(site); + const { code, data } = await cli(t.rt, 'link', 'parse', item.share, ...CONFIRM); + expect(t.hops).toHaveLength(1); + expect(t.submittedUrls()).toEqual([item.share]); + expect(data).not.toHaveProperty('resolvedUrl'); + // the platform's own answer then applies + expect(code).toBe(1); + expect(data).toMatchObject({ ok: false, code: 'LINK_UNSUPPORTED' }); + } + }); + + it('gives up after five hops', async () => { + const t = await scene(() => redirect(item.via)); + await cli(t.rt, 'link', 'parse', item.share, ...CONFIRM); + expect(t.hops).toHaveLength(5); + expect(t.submittedUrls()).toEqual([item.share]); + }); + + it('does not touch a link that already names its post', async () => { + const t = await scene(() => redirect(item.target)); + for (const link of item.untouched) await cli(t.rt, 'link', 'parse', link, ...CONFIRM); + expect(t.hops).toHaveLength(0); + expect(t.submittedUrls()).toEqual([...item.untouched]); + }); + + it('asks the site nothing before the fee is authorized; --dry-run resolves without contacting the platform', async () => { + const t = await scene(() => redirect(item.target)); + const unconfirmed = await cli(t.rt, 'link', 'parse', item.share); + expect(unconfirmed.code).toBe(2); + expect(t.hops).toHaveLength(0); + const { code, data } = await cli(t.rt, 'link', 'parse', item.share, '--dry-run'); + expect(code).toBe(0); + expect(data).toMatchObject({ ok: true, dryRun: true, resolvedUrl: item.post, request: { body: { url: item.post } } }); + expect(t.stub.requests).toEqual([]); + }); +}); + +describe('share links of other shapes', () => { + it('a t.co link that leads to another site is submitted as it is', async () => { + const t = await scene(() => redirect('https://go.nasa.gov/3X5ccG6')); + await cli(t.rt, 'link', 'parse', 'https://t.co/DTc4cHspt8', ...CONFIRM); + expect(t.hops).toHaveLength(1); + expect(t.submittedUrls()).toEqual(['https://t.co/DTc4cHspt8']); + }); + + it('resolves Bilibili mirrors and dynamics, Weibo share pages, LinkedIn feed links', async () => { + const pairs: readonly (readonly [string, string, string])[] = [ + ['https://bili2233.cn/AbCd123', 'https://m.bilibili.com/opus/1012345678901234567?spm_id_from=333', 'https://www.bilibili.com/opus/1012345678901234567'], + ['https://b23.tv/AbCd123', 'https://t.bilibili.com/1012345678901234567?share_source=x', 'https://www.bilibili.com/opus/1012345678901234567'], + ['https://b23.tv/AbCd123', 'https://www.bilibili.com/video/av170001?p=1', 'https://www.bilibili.com/video/av170001'], + ['https://t.cn/A6qHeVlf', 'https://share.api.weibo.cn/share/123,5092682368025584.html?weibo_id=5092682368025584', 'https://m.weibo.cn/detail/5092682368025584'], + ['https://mapp.api.weibo.cn/fx/0123abcd.html', 'https://m.weibo.cn/status/5092682368025584?from=page', 'https://m.weibo.cn/status/5092682368025584'], + ['https://lnkd.in/gJ4pUZ7', 'https://www.linkedin.com/feed/update/urn%3Ali%3Aactivity%3A7529220987423182848/?utm=1', 'https://www.linkedin.com/feed/update/urn:li:activity:7529220987423182848'], + ['https://t.co/DTc4cHspt8', 'https://x.com/i/web/status/1863000000000000001', 'https://x.com/i/status/1863000000000000001'], + ]; + for (const [share, target, post] of pairs) { + const t = await scene(() => redirect(target)); + await cli(t.rt, 'link', 'parse', share, ...CONFIRM); + expect(t.submittedUrls(), share).toEqual([post]); + } + }); + + it('a page that is not a post on the site is not submitted (profile, home)', async () => { + const pairs: readonly (readonly [string, string])[] = [ + ['https://t.co/DTc4cHspt8', 'https://x.com/NASA'], + ['https://t.cn/A6qHeVlf', 'https://weibo.com/u/5819018196'], + ['https://b23.tv/AbCd123', 'https://space.bilibili.com/123456'], + ['https://lnkd.in/gJ4pUZ7', 'https://www.linkedin.com/company/test'], + ['https://v.lemon8-app.com/s/OgTtgvsFsr', 'https://www.lemon8-app.com/@creator'], + ]; + for (const [share, target] of pairs) { + const t = await scene((request) => (request.url === share ? redirect(target) : new Response('page', { status: 200 }))); + await cli(t.rt, 'link', 'parse', share, ...CONFIRM); + expect(t.submittedUrls(), share).toEqual([share]); + } + }); +}); + +describe('htmlRedirectTarget', () => { + it.each([ + ['', '/next'], + ["", 'https://a.example/p?x=1&y=2'], + ['', 'https://a.example/p?x=1&y=2'], + ["", 'https://a.example/p'], + ['', 'https://a.example/p'], + ])('%s', (html, target) => { + expect(htmlRedirectTarget(html)).toBe(target); + }); + + it.each(['', 'home', '', 'a plain link', ''])( + 'finds nothing in %s', + (html) => { + expect(htmlRedirectTarget(html)).toBeNull(); + }, + ); +}); diff --git a/skills/popost/tests/post-bundle.test.ts b/skills/popost/tests/post-bundle.test.ts index 84552b7..74570ab 100644 --- a/skills/popost/tests/post-bundle.test.ts +++ b/skills/popost/tests/post-bundle.test.ts @@ -57,6 +57,7 @@ describe('pending ticket', () => { ['https://www.iesdouyin.com/share/note/1', 'douyin'], ['https://www.instagram.com/p/x/', 'instagram'], ['https://twitter.com/a/status/1', 'x'], + ['https://t.co/DTc4cHspt8', 'x'], ['https://www.youtube.com/watch?v=AbCdEfGhIj0', 'youtube'], ['https://youtu.be/AbCdEfGhIj0', 'youtube'], ['https://m.youtube.com/shorts/AbCdEfGhIj0', 'youtube'], @@ -68,6 +69,7 @@ describe('pending ticket', () => { ['https://redd.it/1y99q4v', 'reddit'], ['https://www.bilibili.com/video/BV1M1421t7hT', 'bilibili'], ['https://b23.tv/AbCdEf1', 'bilibili'], + ['https://bili2233.cn/AbCdEf1', 'bilibili'], ['https://www.lemon8-app.com/@a/7581476112027484686', 'lemon8'], ['https://www.kuaishou.com/short-video/3xvkh7sx8ci4yx4', 'kuaishou'], ['https://v.kuaishou.com/cNYP0Z', 'kuaishou'], From d326a3796bc55b2a00bbfa43bba010fff0620bc4 Mon Sep 17 00:00:00 2001 From: Clipcat-ai Date: Thu, 3 Dec 2026 02:00:38 +0000 Subject: [PATCH 8/9] docs(link): only the coverOnly platforms (now YouTube) come without the video file popost.ai now stores a Bilibili video (Bilibili's own 720p MP4 with sound) and a WeChat Channels video with the post, so the Skill no longer names them as cover-only: every place points to the coverOnly list of `popost link platforms` instead. A saved post's video now counts in the account's storage, so a full account is one more reason for videoMissing (STORAGE_FULL). Co-Authored-By: Claude Opus 5.5 Signed-off-by: Clipcat-ai --- skills/popost/SKILL.md | 2 +- skills/popost/SOURCE-MANIFEST.sha256 | 12 ++++++------ skills/popost/references/onboarding.md | 2 +- skills/popost/references/post-bundle.md | 4 ++-- skills/popost/references/video-step-1-read.md | 4 ++-- skills/popost/src/commands/link.ts | 4 ++-- skills/popost/src/providers/link-video.ts | 2 +- 7 files changed, 15 insertions(+), 15 deletions(-) diff --git a/skills/popost/SKILL.md b/skills/popost/SKILL.md index 73aace6..d202ca3 100644 --- a/skills/popost/SKILL.md +++ b/skills/popost/SKILL.md @@ -45,7 +45,7 @@ Prepare only what the next operation needs: an inspiration save needs no rendere Whenever you tell the user which social platforms' links work (introducing popost, a first inspiration save, a link that was refused), run `popost link platforms` and name exactly the platforms it lists, with its `coverOnly` note: popost.ai adds and removes platforms, so a list from memory, this page or a README goes out of date. It is free and needs no account. -For a production reference link, read [post-bundle.md](references/post-bundle.md), quote the selected service, and parse only under fee authorization. Reuse a successful parse: it already saves the inspiration. Retrieve only the actual available content; a YouTube or Bilibili parse currently gives cover/title/description, not video bytes. Obtain a readable video before analyzing its shots or motion. Missing source content is a concrete input/service gap; thumbnails do not stand in for an unseen video. Local videos, images, screenshots and supplied text need no link parsing. +For a production reference link, read [post-bundle.md](references/post-bundle.md), quote the selected service, and parse only under fee authorization. Reuse a successful parse: it already saves the inspiration. Retrieve only the actual available content; a parse on a `coverOnly` platform of `popost link platforms` (now YouTube) gives cover/title/description, not video bytes. Obtain a readable video before analyzing its shots or motion. Missing source content is a concrete input/service gap; thumbnails do not stand in for an unseen video. Local videos, images, screenshots and supplied text need no link parsing. ## Services and spending diff --git a/skills/popost/SOURCE-MANIFEST.sha256 b/skills/popost/SOURCE-MANIFEST.sha256 index ca4964a..58f826b 100644 --- a/skills/popost/SOURCE-MANIFEST.sha256 +++ b/skills/popost/SOURCE-MANIFEST.sha256 @@ -1,5 +1,5 @@ fbc16146b510a188d8591dde877e9a8892ebe67e2436ce36737b8ab40b781fff LICENSE -50fda2d895b2b053a716380e72169024b6ceb0a1a5f60ab75904962c566500ec SKILL.md +31870d60ec2b2d81a1ce7276a6ec8d30c2a0fb36b0517c10092ee4019023df16 SKILL.md 79b1a246fc4493c0a976e2936ae892e42bd221a73fed4a3f1c4d44276d0f1f4f THIRD_PARTY_NOTICES 82eb5512d1618d91a1bf41f13aabe5bae9738deaad0a808b5eb7d6f928f6e171 agents/openai.yaml e8ce43dcfb49481444e6bbb92c6c5cfed7bd5ee1adfcae3d7cfe6daa135d575e assets/canvas/THIRD_PARTY_LICENSES.txt @@ -586,9 +586,9 @@ d27b4dd0b10f7b13bbbfc6224af90a644dd95f5cd095435faaf31fe44a193b6f references/fon 6f9b20c5812c31b049963ecda109f27ebc278d8942d8c537c050140b383a0e7e references/host-editor.md cf4147c9b98ed0f136ce8ee1bbbd980db77e1358aeb5b85cacf6fb2d4f097798 references/image-workflow.md e299b21c239eb401f9eff1116f909d931c8a9743b052b6b65e51afd57aff33f8 references/imagery.md -ee6d1c1c26132daee70e5a6b956d78852c1929cc026b918cba5401dee9a04b41 references/onboarding.md +55f4dd067c57cd3cb3b8268105e8bf4180e9ff51313aa83223a7b6982a73c67a references/onboarding.md d8aa84ab56fd0ff7085e74e05a47298f8b23c321cd752be7bdb871bd00c481f7 references/platform-adaptation.md -4f47d0aa803ca5115bb7e1268ab9ef6f710060a070854416cbb1804303244dfe references/post-bundle.md +773fb8ba3bbfcf336ec1e05fcbef358b85384bf2828010ebc78f4ead2b78a9fe references/post-bundle.md 14a91cb8341c096fdfd5edc0005cc1acdd2787badc8d6267019955a8d8970380 references/project-manifest.md 203a65b53a8391f834acd681971f763e4906e340f1d34b0a7ff9393b3f00489a references/providers.md a7b4b60f6023ef5655b940908b5b4a66142fa693e4e157d5e95f1af40be43f6d references/quality-review.md @@ -617,7 +617,7 @@ d7220eaae4866c29c855720d42cff15d78adcae6acdb55a722a0a62ba74defb5 references/vid 9b964b1bb3691c0a013d884fd5e3e1830ff106e5ccc0e9b9ff7ffded5f1fdcc6 references/video-sfx.md 6a82171339793a9d9da0a270de3cffe180da2dcbacd2e6b07fe6f6dd61e92329 references/video-sound.md a12a4139218b56530e73cb8c534e50d1cab8ecf41666fbb3fd83aa92ed2da5d5 references/video-step-0-machine.md -d1ca3bbb9c4d086bda392ad1a0c092e0ed6bac24e9c09fddb00a66e1b26124cd references/video-step-1-read.md +709efdc7b1a7865108ba7b2fac8de039bc4128330c862bb888116433ad70ac63 references/video-step-1-read.md 46635b1729ea0cdd7020748ac1543e80244a314a11fc6b3271ffa4c4191f8007 references/video-step-2-structure.md 69a4612cd5dbffcb029e06f5b40acb91184965b023363d5ccd457a3b59b48c0c references/video-step-3-content.md 8697c23ce280c7a74c059e20cba370403c9c7424ac759e3f4b803e36300e5c14 references/video-step-4-lines.md @@ -648,7 +648,7 @@ e6d2ecd78fdbb49fb770fe179b872123d1f937ada79e6b09f3260d203735710a src/commands/a 255131a1f372f393f5003b069465ba94d3eaf6b864989ca80a4fd786f16070d9 src/commands/inspiration.ts 3839d349b0468dc852947846bfe803adda0e49a0983a570519405a2ba8315b8a src/commands/install.ts 1d8ffe0eb7d19c1506ccf695e2f6c8b034232914d14c2987ef5f504daa1f0f6a src/commands/link-platforms.ts -740b48fa6b6535820518d95d147c66c98c8123ba17511919a86edff3e98dc052 src/commands/link.ts +1ff27e0e9604f065bcb5dcff7c7ced20606434c1e1af35ef77623084b51a362c src/commands/link.ts 567988c02ef98d5985ed7d194d0cc401521772e0ada81b0c9a206e2405a15df8 src/commands/post-bundle.ts 7971793ca7e64178d27c84aca23c72399b0fc9b70a8e2ef5bd24c0151647e756 src/commands/pricing.ts 23937624f5a4ee474eacb2302312a8f42a4d27f00fec301b37f7aba531d99f72 src/commands/provider.ts @@ -742,7 +742,7 @@ e0acd44e5f8507e73325b409240a5b8a13108be028ec1c8dfb9c82cfc6714a95 src/providers/ c32186d2eaa04d68012d42a27af39c57835667664a7995fe576fc1622fc5796c src/providers/link-bundle.ts e4870a2c729d5c14530e6952e527382b46a1bdb74fde4ae7d62aa6c3e9ae8f27 src/providers/link-resolve.ts 2e7364ead9f9af2afaccce914084b16cf067f80622b46c2a848d947d3698ee8f src/providers/link-task.ts -6ec8ec0780c0d9fab557102522d3fa32720ee4b7a6e724204c8ed7a111ad5dbc src/providers/link-video.ts +850ce37ef54920d6658e38f8a7a97e9c77ac15329a48b814a1a1d6b2b4f74c33 src/providers/link-video.ts 2adf9960419235b20a955abb873a5380214cfac83c22f4a170b261662c1484e3 src/providers/link.ts 0dbd7fad49ebdaf462b8eed9f77e73d90f0bf28fbdf42b6df6dcca582a7057a8 src/providers/manual-host.ts 4fac7cd9846ef58768c53be123e4672ca5bd437caf35195b7a37afdd132ae0e8 src/providers/paths.ts diff --git a/skills/popost/references/onboarding.md b/skills/popost/references/onboarding.md index 3a47349..35f4e40 100644 --- a/skills/popost/references/onboarding.md +++ b/skills/popost/references/onboarding.md @@ -66,7 +66,7 @@ Missing optional tools are not a broken core install. Determine whether the curr ## Reference and generation are separate choices - Local videos, pictures/screenshots and supplied text are immediately usable. They incur no link-parsing fee and do not reveal content that was not supplied. -- Popost parses supported social links into the media/title/body actually available for that post type. Which platforms are supported changes on popost.ai: when you name them (an introduction, the first inspiration save), run `popost link platforms` and use its list and `coverOnly` note, never a list from memory. Explain this service value, not just "downloading a link". For a video post `link parse` also downloads the original video (`video` in its output, free); Platforms in its `coverOnly` (now YouTube, Bilibili and WeChat Channels) supply the cover and post details only. Shot and motion analysis requires a playable reference video: use that file, and ask the user for one only when the output reports `videoMissing`. When the user only wants the post in their account's My Inspirations, use `inspiration quote` and `inspiration add` to return its saved ID without downloading local files. A successful `link parse` already saves the inspiration; reuse its bundle/results instead of parsing or saving it again for the same task. +- Popost parses supported social links into the media/title/body actually available for that post type. Which platforms are supported changes on popost.ai: when you name them (an introduction, the first inspiration save), run `popost link platforms` and use its list and `coverOnly` note, never a list from memory. Explain this service value, not just "downloading a link". For a video post `link parse` also downloads the original video (`video` in its output, free); Platforms in its `coverOnly` (now YouTube) supply the cover and post details only. Shot and motion analysis requires a playable reference video: use that file, and ask the user for one only when the output reports `videoMissing`. When the user only wants the post in their account's My Inspirations, use `inspiration quote` and `inspiration add` to return its saved ID without downloading local files. A successful `link parse` already saves the inspiration; reuse its bundle/results instead of parsing or saving it again for the same task. - Recommend Popost's integrated hosted services for supported parsing, image/video generation, transcription, speech and music when needed. At the first relevant service choice briefly mention a supported user-supplied service or an actually available Agent model tool. Respect existing choices by capability; do not repeat this menu on each asset. Image host/custom execution is documented in [providers.md](providers.md), video adapters in [video-tools.md](video-tools.md); do not promise a generic image channel can execute video generation. - BYOK and host tools may charge independently. Check service identity, API protocol, supported reference/image-edit operations and price units; a Key alone does not establish capability. Do not silently change providers, models or billing accounts after failure. - Assess a no-generation route when requested. Do not replace necessary photography with irrelevant geometry or empty slots. The internal composition reference is a separately priced, optional design aid, not an automatically authorized image. diff --git a/skills/popost/references/post-bundle.md b/skills/popost/references/post-bundle.md index 17dc6a9..12ed687 100644 --- a/skills/popost/references/post-bundle.md +++ b/skills/popost/references/post-bundle.md @@ -36,7 +36,7 @@ inspiration import --file bundle.json [--note "为什么收藏"] [--dry-run] [-- ## 解析帖子链接(link parse) -`popost link parse ` 让 popost.ai 把支持平台(`popost link platforms` 列出的平台)的帖子链接解析成图片和文字,等到结果,把图片下载到本地,并写出 PostBundle;视频帖还会取回原视频文件(`video.mp4`,不另扣积分),用于分镜、字幕和声音分析(YouTube、哔哩哔哩和微信视频号只有封面和帖子信息)。需要先连接账户(运行 `popost auth login`;开发者也可使用环境变量 `POPOST_API_KEY` 或 `popost auth set` 保存的 Key;凭据与地址同官方通道,见 [providers.md](providers.md));没有 Key 时仍走上面的 `ticket` 和本地参考。Before submission run `link quote` for the current tariff and show the stage ceiling. Obtain fee authorization, then pass `--confirm --max-credits N`. The server rechecks the actual deduction against N; saved/active results may cost less. `task.chargedCredits` is the current net actual charge, not an advance quote. If the pricing service is unavailable, do not guess a price or parse to find it; use local reference images. +`popost link parse ` 让 popost.ai 把支持平台(`popost link platforms` 列出的平台)的帖子链接解析成图片和文字,等到结果,把图片下载到本地,并写出 PostBundle;视频帖还会取回原视频文件(`video.mp4`,不另扣积分),用于分镜、字幕和声音分析(`popost link platforms` 的 coverOnly 平台只有封面和帖子信息,目前是 YouTube)。需要先连接账户(运行 `popost auth login`;开发者也可使用环境变量 `POPOST_API_KEY` 或 `popost auth set` 保存的 Key;凭据与地址同官方通道,见 [providers.md](providers.md));没有 Key 时仍走上面的 `ticket` 和本地参考。Before submission run `link quote` for the current tariff and show the stage ceiling. Obtain fee authorization, then pass `--confirm --max-credits N`. The server rechecks the actual deduction against N; saved/active results may cost less. `task.chargedCredits` is the current net actual charge, not an advance quote. If the pricing service is unavailable, do not guess a price or parse to find it; use local reference images. ```text link quote [--config PRIVATE_CONFIG] @@ -48,7 +48,7 @@ Short share links that only redirect to their post are resolved on the user's ma 1. Run `link quote` (free read-only platform tariff/balance query), show the parsing charge separately from image fees and obtain authorization. `--dry-run` only describes the request locally; it does not query a price. Then submit with `--confirm --max-credits N`. 2. 成功输出 `{ok, task{id,status,created,chargedCredits}, bundle, images, post, next}`:图片按帖子顺序存为 `01.jpg`、`02.webp`…(类型取自文件头),和 `postbundle.json` 一起放在 `--out`(默认 `inputs/link-<任务 id 前 8 位>/`)。bundle 的 `resources[].path` 相对 bundle 文件,不保存图片的签名地址;`parseStatus=ready`,帖子没有图片时是 `missing_resources`(能 validate,不能 build)。`next` 是接着跑的 `validate`、`import`;复刻时再用 `attach-bundle` 登记为工程来源。 - 视频帖(`post.kind=video`)的图片只有封面;原视频另存为 `video.mp4`(`.mov`、`.webm`,类型取自文件头),输出里是 `video`,bundle 里是 `resources` 中 `kind=video` 的一项(不进 `pageOrder`)。这一步不另扣积分;`--no-video` 跳过。平台给不出视频(YouTube、哔哩哔哩、微信视频号,或平台已不再提供这条视频)、或下载失败时解析照样成功,输出带 `videoMissing{code,error}`(如 `LINK_VIDEO_UNAVAILABLE`):bundle 只有封面和文字,要做视频分析时再请用户提供视频文件或录屏;下载失败可重跑 `link status` 再取。 + 视频帖(`post.kind=video`)的图片只有封面;原视频另存为 `video.mp4`(`.mov`、`.webm`,类型取自文件头),输出里是 `video`,bundle 里是 `resources` 中 `kind=video` 的一项(不进 `pageOrder`)。这一步不另扣积分;`--no-video` 跳过。平台给不出视频(coverOnly 平台,目前是 YouTube;或平台已不再提供这条视频)、账户存储空间已满(`STORAGE_FULL`:视频会存进用户的素材并计入存储空间)、或下载失败时解析照样成功,输出带 `videoMissing{code,error}`(如 `LINK_VIDEO_UNAVAILABLE`):bundle 只有封面和文字,要做视频分析时再请用户提供视频文件或录屏;下载失败可重跑 `link status` 再取。 3. 链接已在用户的灵感库里时直接复用:`task.created=false`、`chargedCredits=0`。平台解析时已把这条帖子存入「我的灵感」,不要再对这个 bundle 跑 `inspiration import`,那会重复保存。 4. 任务失败输出 `{ok:false, code, error, task}`,退出码 1,The platform attempts a refund; `chargedCredits` is the current net charge. A positive value on a failed task means refund pending, not refunded. Query status to reconcile.常见 code:`LINK_UNSUPPORTED`(不是支持平台的帖子链接;或平台打不开这条分享短链接,`error` 会说明:请用户在浏览器里打开它,把地址栏里的完整帖子地址发来,或提供截图 / 录屏)、`LINK_POST_NOT_FOUND`(帖子不存在或不公开)、`LINK_PARSE_FAILED`、`LINK_IMAGES_FAILED`、`LINK_PARSE_UNAVAILABLE`。`LINK_UNSUPPORTED`、`INSUFFICIENT_CREDITS`、`RATE_LIMITED` 在建任务前就拒绝,没有任务,也没扣积分。 5. 等待:每 2 秒查询一次,最长 `--timeout` 秒(默认 900 秒;平台约 15 分钟仍未完成的任务会判失败);个别查询失败(网络、5xx)会容忍,连续 5 次失败才停;被限流时按平台给的时间等待后再查,不算失败。超时、停止等待或命令被打断时,解析可能仍在平台进行:用输出里的 `popost link status ` 继续等待并下载,它不会新建任务、也不会再扣积分。图片下载失败时已下载的保留,同样重跑 `link status`(图片地址每次查询都会重新签发)。`--no-download` 不下载,只打印帖子和图片地址,地址是短期签名链接。 diff --git a/skills/popost/references/video-step-1-read.md b/skills/popost/references/video-step-1-read.md index 087bf83..ed9f6e2 100644 --- a/skills/popost/references/video-step-1-read.md +++ b/skills/popost/references/video-step-1-read.md @@ -3,8 +3,8 @@ Step 1 of [making a video](video.md), whose rules for every step hold here; before it: [step 0, What the machine has](video-step-0-machine.md); after it: [step 2, Keep its structure](video-step-2-structure.md). Put the reference at `reference.mp4` (`cp` a local file, `curl -L -o reference.mp4 `, or, for a post link, -the `video` file `popost link parse` printed: it fetches a video post's original file, except on YouTube, Bilibili and -WeChat Channels; only when it reports `videoMissing` ask the user for the file or a screen recording), then: +the `video` file `popost link parse` printed: it fetches a video post's original file, except on the `coverOnly` +platforms of `popost link platforms` (now YouTube); only when it reports `videoMissing` ask the user for the file or a screen recording), then: ```bash popost video describe reference.mp4 --out ref --project project --confirm --max-credits diff --git a/skills/popost/src/commands/link.ts b/skills/popost/src/commands/link.ts index 1cbe40a..a9f820a 100644 --- a/skills/popost/src/commands/link.ts +++ b/skills/popost/src/commands/link.ts @@ -67,8 +67,8 @@ export const main: CommandMain = (argv, rt) => parse: { spec: { description: msg( - `Have popost.ai parse a social post link (${platformNameList('or')}), wait for the result, download the pictures and write a PostBundle (postbundle.v1). A video post also gets its original video file (video.mp4, free) for shot, subtitle and sound analysis; YouTube, Bilibili and WeChat Channels give the cover and post details only. Get the live price with link quote first, then submit with --confirm --max-credits N, the ceiling the user authorized; the actual net charge is task.chargedCredits; a link already saved is reused without a new charge. The parsed post is also saved to My Inspirations.`, - `让 popost.ai 解析一条社媒帖子链接(${platformNameList('or')}),等待结果,把图片下载到本地并写出 PostBundle(postbundle.v1)。视频帖还会取回原视频文件(video.mp4,不另扣积分),用于分镜、字幕和声音分析;YouTube、哔哩哔哩和微信视频号只有封面和帖子信息。先 link quote 查询动态价格,再带 --confirm --max-credits N 按已授权上限提交;实际净扣见 task.chargedCredits;已保存过的链接直接复用、不再扣。解析结果同时存入「我的灵感」。`, + `Have popost.ai parse a social post link (${platformNameList('or')}), wait for the result, download the pictures and write a PostBundle (postbundle.v1). A video post also gets its original video file (video.mp4, free) for shot, subtitle and sound analysis; the coverOnly platforms of link platforms (now YouTube) give the cover and post details only. Get the live price with link quote first, then submit with --confirm --max-credits N, the ceiling the user authorized; the actual net charge is task.chargedCredits; a link already saved is reused without a new charge. The parsed post is also saved to My Inspirations.`, + `让 popost.ai 解析一条社媒帖子链接(${platformNameList('or')}),等待结果,把图片下载到本地并写出 PostBundle(postbundle.v1)。视频帖还会取回原视频文件(video.mp4,不另扣积分),用于分镜、字幕和声音分析;link platforms 里 coverOnly 的平台(目前是 YouTube)只有封面和帖子信息。先 link quote 查询动态价格,再带 --confirm --max-credits N 按已授权上限提交;实际净扣见 task.chargedCredits;已保存过的链接直接复用、不再扣。解析结果同时存入「我的灵感」。`, ), positionals: [{ name: 'url', help: msg('the post link (http/https)', '帖子链接(http/https)') }], options: [ diff --git a/skills/popost/src/providers/link-video.ts b/skills/popost/src/providers/link-video.ts index 3af0790..a0d42be 100644 --- a/skills/popost/src/providers/link-video.ts +++ b/skills/popost/src/providers/link-video.ts @@ -4,7 +4,7 @@ * resource, the reference that shot, subtitle and sound analysis read. The type comes from the file header, never from * the URL or the server's word. * - * A missing video never fails the parse: platforms that give only the cover (YouTube, Bilibili, WeChat Channels), links + * A missing video never fails the parse: platforms that give only the cover (`coverOnly` in `link platforms`, now YouTube), links * the platform no longer serves or a failed download leave the pictures and text, and the outcome says why, so the agent * asks the user for the file instead of guessing. In the web Agent (image posts only) the platform refuses video * endpoints with VIDEO_GENERATION_DISABLED: then the parse quietly has no video, as a picture post would. From 1f014b4ab539199adf9394aa52ab0479077dedad Mon Sep 17 00:00:00 2001 From: Clipcat-ai Date: Thu, 3 Dec 2026 02:00:55 +0000 Subject: [PATCH 9/9] chore(release): popost 4.6.12 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Clipcat-ai --- package-lock.json | 2 +- skills/popost/SKILL.md | 2 +- skills/popost/SOURCE-MANIFEST.sha256 | 6 +++--- skills/popost/package.json | 2 +- skills/popost/src/version.ts | 2 +- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/package-lock.json b/package-lock.json index 9910061..7f39290 100644 --- a/package-lock.json +++ b/package-lock.json @@ -4872,7 +4872,7 @@ } }, "skills/popost": { - "version": "4.6.11", + "version": "4.6.12", "license": "SEE LICENSE IN LICENSE", "dependencies": { "fflate": "^0.8.3", diff --git a/skills/popost/SKILL.md b/skills/popost/SKILL.md index d202ca3..b5eac89 100644 --- a/skills/popost/SKILL.md +++ b/skills/popost/SKILL.md @@ -1,7 +1,7 @@ --- name: popost metadata: - version: "4.6.11" + version: "4.6.12" description: Reproduce reference videos with new content; create, reproduce and edit social image posts; save supported social links to My Inspirations. Use for video remakes, single-image posts, carousels, editable canvas/Studio projects and inspiration saving from TikTok, Instagram, X, Xiaohongshu, Douyin, YouTube, Threads, LinkedIn, Reddit, Bilibili, Lemon8, Kuaishou, WeChat or Weibo links, local media and written briefs. Retrieve only the source content supported by the selected link service. --- diff --git a/skills/popost/SOURCE-MANIFEST.sha256 b/skills/popost/SOURCE-MANIFEST.sha256 index 58f826b..19528f0 100644 --- a/skills/popost/SOURCE-MANIFEST.sha256 +++ b/skills/popost/SOURCE-MANIFEST.sha256 @@ -1,5 +1,5 @@ fbc16146b510a188d8591dde877e9a8892ebe67e2436ce36737b8ab40b781fff LICENSE -31870d60ec2b2d81a1ce7276a6ec8d30c2a0fb36b0517c10092ee4019023df16 SKILL.md +bbdee969fc467864c6668277244ee28909c1ead3b61e47ccf4a177e5f8aec1d3 SKILL.md 79b1a246fc4493c0a976e2936ae892e42bd221a73fed4a3f1c4d44276d0f1f4f THIRD_PARTY_NOTICES 82eb5512d1618d91a1bf41f13aabe5bae9738deaad0a808b5eb7d6f928f6e171 agents/openai.yaml e8ce43dcfb49481444e6bbb92c6c5cfed7bd5ee1adfcae3d7cfe6daa135d575e assets/canvas/THIRD_PARTY_LICENSES.txt @@ -576,7 +576,7 @@ bce3debe65da546823ddeea754db40e2f3d7742478d334b305c173cff3249ae4 assets/video/s 8e82ff4d770bcebb67d465668ab9317e0bd9bae5caa8997ac0ea595027bf426f bundles/build-video.mjs add100275e15938519d8b2200572e8f72fbb66df9910f0c82e930db7713dd5e5 bundles/deck-entry.ts bb05a83f6f76ce79481e0d7b3a347c5661c0b41af9ebb995c9892ad4bb99e195 bundles/tsconfig.json -f1d339d321132e601b8b16524887a01ac752700c055aa0460ec31783384d1bad package.json +39c4e9d05d742209958558a40a38f3f0f3a44f660c61d189bc06f5171851dc57 package.json c6310dd52f3fc3dc4064f5134573698ffb0d7f6c6d4bd6580c018adb40f99b87 references/asset-architecture.md 75c9ae67c4191ea153b56776aae996f22dee5da835eaac93be69149b8d593d96 references/create.md 9abcc16dc4730041c71a08007f3744fe89f0009893598d0b4fd42939b75c5483 references/design-system.md @@ -784,7 +784,7 @@ d96c6f4f1506976346df992f26e3ffb2ccc6de31412f7c5ec57693e8d2ad7ab9 src/update/rep dc2da337b1005fee9f8dd7869ee6caba4e891b68f282c07af64d0ad5f71fa8d9 src/update/session.ts 00ebeaf3169473927dd4b2fd6bcf0fb6a5fb3a0102f211f10c57a8a1e3bbd363 src/update/state.ts 62dbd2d9e890bcbc3336cec661c830add57fd9c8100277c0784ec28ad881fe2d src/update/verify.ts -b6275d445765e5c149329520f42f0d50d400aec740dc1114fdc683c9b135be08 src/version.ts +29ee14dfcec37e78ed3ce70d28320ab51e1dbad24a331cb2b80419babcc1be2d src/version.ts 6180d119a25333c2e32a03c1c4d5aca390b2abe13824a1c7337062e44bfe9efd src/video/align/index.ts 9810398a64a74127471c0d2eea5b1969c3e20b78f570971d6a4e7a10a630f180 src/video/cache/frames.ts 9eb21a722635102adfe3341a1df74535e21ab73a6325ea37a26b1816346d8800 src/video/cache/holds.ts diff --git a/skills/popost/package.json b/skills/popost/package.json index 000a503..e1f4f6c 100644 --- a/skills/popost/package.json +++ b/skills/popost/package.json @@ -1,6 +1,6 @@ { "name": "popost", - "version": "4.6.11", + "version": "4.6.12", "description": "popost Skill and CLI: reproduce videos, create and reproduce image posts, edit canvas and Studio projects, and save social inspiration links in coding agents such as Codex and Claude Code.", "license": "SEE LICENSE IN LICENSE", "author": "CLIPCAT AI LTD", diff --git a/skills/popost/src/version.ts b/skills/popost/src/version.ts index 0ca97a1..ebd3d36 100644 --- a/skills/popost/src/version.ts +++ b/skills/popost/src/version.ts @@ -1,2 +1,2 @@ /** The CLI version; equals `metadata.version` in SKILL.md and is sent to popost.ai as `x-popost-client-version`. */ -export const VERSION = '4.6.11'; +export const VERSION = '4.6.12';