@esquadrao/cli 1.7.1 → 1.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +33 -7
- package/assets/broll-catalog.json +11905 -0
- package/assets/studio-ui/index.html +512 -0
- package/bin/cli.js +10 -1
- package/package.json +4 -3
- package/scripts/cutout.py +83 -15
- package/scripts/dag_validator.js +38 -3
- package/scripts/lint.js +47 -7
- package/scripts/merkle_verify.js +6 -1
- package/skill-media-producer/SKILL.md +32 -0
- package/skill-media-producer/references/composicoes-especiais.md +1 -1
- package/skill-media-producer/references/configuracao-inicial.md +4 -10
- package/skill-media-producer/references/llm-agent-guide.md +31 -8
- package/src/binaries.js +74 -0
- package/src/commands/onboard.js +11 -16
- package/src/commands/setup.js +22 -20
- package/src/commands/studio.js +48 -1
- package/src/studio/jobTelemetry.js +239 -0
- package/src/studio/planSummary.js +76 -0
- package/src/studio/previewCache.js +90 -0
- package/src/studio/server.js +457 -0
- package/src/studio/stateDir.js +132 -0
package/scripts/cutout.py
CHANGED
|
@@ -30,6 +30,26 @@ def has_audio(path: str) -> bool:
|
|
|
30
30
|
return False
|
|
31
31
|
|
|
32
32
|
|
|
33
|
+
def fg_height_for(requested, out_h: int, src_w: int, src_h: int) -> int:
|
|
34
|
+
"""Altura do primeiro plano composto.
|
|
35
|
+
|
|
36
|
+
Entrada vertical entra em tela cheia (não encolhe as laterais); horizontal
|
|
37
|
+
mantém o recorte de 1000 px do protótipo. --fg-height explícito manda.
|
|
38
|
+
"""
|
|
39
|
+
if requested is None:
|
|
40
|
+
requested = out_h if src_w > 0 and src_h >= src_w else min(1000, out_h)
|
|
41
|
+
return max(1, min(requested, out_h))
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def erode_kernel(min_side: int) -> int:
|
|
45
|
+
"""Núcleo de erosão ~4,5% do lado menor (49 px em 1080p), sempre ímpar.
|
|
46
|
+
|
|
47
|
+
GC_FGD fica estritamente dentro da silhueta; o halo de 15-50 px do u2net
|
|
48
|
+
permanece como GC_PR_FGD para o GrabCut refinar.
|
|
49
|
+
"""
|
|
50
|
+
return max(31, int(min_side * 0.045) | 1)
|
|
51
|
+
|
|
52
|
+
|
|
33
53
|
def main() -> int:
|
|
34
54
|
ap = argparse.ArgumentParser()
|
|
35
55
|
ap.add_argument('--input', required=True)
|
|
@@ -38,7 +58,7 @@ def main() -> int:
|
|
|
38
58
|
ap.add_argument('--fps', type=float, default=15.0)
|
|
39
59
|
ap.add_argument('--width', type=int, default=1080)
|
|
40
60
|
ap.add_argument('--height', type=int, default=1920)
|
|
41
|
-
ap.add_argument('--fg-height', type=int, default=
|
|
61
|
+
ap.add_argument('--fg-height', type=int, default=None)
|
|
42
62
|
ap.add_argument('--fg-y', type=int, default=None)
|
|
43
63
|
ap.add_argument('--model', default='u2net_human_seg')
|
|
44
64
|
ap.add_argument('--crf', type=int, default=20)
|
|
@@ -87,7 +107,11 @@ def main() -> int:
|
|
|
87
107
|
raise RuntimeError('falha ao ler frame do pack de fundo')
|
|
88
108
|
return cv2.resize(bg, (args.width, args.height), interpolation=cv2.INTER_AREA)
|
|
89
109
|
|
|
90
|
-
fg_h =
|
|
110
|
+
fg_h = fg_height_for(
|
|
111
|
+
args.fg_height, args.height,
|
|
112
|
+
int(cap.get(cv2.CAP_PROP_FRAME_WIDTH) or 0),
|
|
113
|
+
int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT) or 0),
|
|
114
|
+
)
|
|
91
115
|
fg_y = args.height - fg_h if args.fg_y is None else max(0, min(args.fg_y, args.height - fg_h))
|
|
92
116
|
|
|
93
117
|
audio = has_audio(args.input)
|
|
@@ -108,19 +132,34 @@ def main() -> int:
|
|
|
108
132
|
'-shortest', '-movflags', '+faststart', args.output,
|
|
109
133
|
]
|
|
110
134
|
|
|
111
|
-
|
|
112
|
-
session = new_session(args.model)
|
|
113
|
-
ff = subprocess.Popen(cmd, stdin=subprocess.PIPE)
|
|
114
|
-
started = time.time()
|
|
135
|
+
ff = None
|
|
115
136
|
written = 0
|
|
116
|
-
|
|
137
|
+
success = False
|
|
138
|
+
started = time.time()
|
|
117
139
|
try:
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
140
|
+
print(f'Carregando modelo {args.model} (primeira execução pode baixar ~176 MB)...', file=sys.stderr, flush=True)
|
|
141
|
+
session = new_session(args.model)
|
|
142
|
+
ff = subprocess.Popen(cmd, stdin=subprocess.PIPE)
|
|
143
|
+
|
|
144
|
+
src_idx = 0
|
|
145
|
+
last = None
|
|
146
|
+
while written < out_frames:
|
|
147
|
+
# Amostragem sequencial: grab avança sem decodificar. Seek por
|
|
148
|
+
# CAP_PROP_POS_MSEC erra em H.264 com B-frames e trunca o vídeo.
|
|
149
|
+
target = int(round(written * src_fps / args.fps))
|
|
150
|
+
while src_idx < target:
|
|
151
|
+
if not cap.grab():
|
|
152
|
+
break
|
|
153
|
+
src_idx += 1
|
|
154
|
+
if last is not None and src_idx > target:
|
|
155
|
+
frame = last # fps de saída acima do da origem: repete o quadro
|
|
156
|
+
else:
|
|
157
|
+
ok, frame = cap.read()
|
|
158
|
+
if not ok:
|
|
159
|
+
break
|
|
160
|
+
src_idx += 1
|
|
161
|
+
last = frame
|
|
162
|
+
bg = read_bg(written)
|
|
124
163
|
cut = remove(
|
|
125
164
|
Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)),
|
|
126
165
|
session=session,
|
|
@@ -134,7 +173,8 @@ def main() -> int:
|
|
|
134
173
|
# da cabeça); sem refino, esse fundo vira um halo escuro no composto.
|
|
135
174
|
mask = (fg[:, :, 3] > 127).astype(np.uint8) * 255
|
|
136
175
|
try:
|
|
137
|
-
|
|
176
|
+
k_erode = erode_kernel(min(frame.shape[:2]))
|
|
177
|
+
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (k_erode, k_erode))
|
|
138
178
|
core = cv2.erode(mask, kernel)
|
|
139
179
|
outside = cv2.bitwise_not(cv2.dilate(mask, kernel))
|
|
140
180
|
gc = np.full(mask.shape, cv2.GC_PR_BGD, np.uint8)
|
|
@@ -171,15 +211,43 @@ def main() -> int:
|
|
|
171
211
|
written += 1
|
|
172
212
|
if written % 100 == 0:
|
|
173
213
|
print(f'{written}/{out_frames} frames — {time.time() - started:.1f}s', file=sys.stderr, flush=True)
|
|
214
|
+
|
|
215
|
+
if written == 0:
|
|
216
|
+
print('nenhum frame da entrada foi decodificado', file=sys.stderr)
|
|
217
|
+
return 1
|
|
218
|
+
if written < out_frames:
|
|
219
|
+
print(f'decodificação interrompida em {written}/{out_frames} frames', file=sys.stderr)
|
|
220
|
+
return 1
|
|
174
221
|
ff.stdin.close()
|
|
175
222
|
rc = ff.wait()
|
|
176
223
|
if rc != 0:
|
|
177
224
|
print(f'ffmpeg falhou (exit {rc})', file=sys.stderr)
|
|
178
|
-
return
|
|
225
|
+
return 1
|
|
226
|
+
success = True
|
|
227
|
+
except KeyboardInterrupt:
|
|
228
|
+
print('cutout interrompido pelo usuário', file=sys.stderr)
|
|
229
|
+
return 130
|
|
179
230
|
except BrokenPipeError:
|
|
180
231
|
print('ffmpeg encerrou antes do fim dos frames', file=sys.stderr)
|
|
181
232
|
return 1
|
|
233
|
+
except Exception as exc: # noqa: BLE001 — falha do motor vira exit != 0
|
|
234
|
+
print(f'falha no cutout: {exc}', file=sys.stderr)
|
|
235
|
+
return 1
|
|
182
236
|
finally:
|
|
237
|
+
if ff is not None:
|
|
238
|
+
try:
|
|
239
|
+
ff.stdin.close()
|
|
240
|
+
except (OSError, BrokenPipeError, ValueError):
|
|
241
|
+
pass
|
|
242
|
+
if ff.poll() is None:
|
|
243
|
+
ff.terminate()
|
|
244
|
+
try:
|
|
245
|
+
ff.wait(timeout=5)
|
|
246
|
+
except subprocess.TimeoutExpired:
|
|
247
|
+
ff.kill()
|
|
248
|
+
ff.wait()
|
|
249
|
+
if not success:
|
|
250
|
+
Path(args.output).unlink(missing_ok=True)
|
|
183
251
|
cap.release()
|
|
184
252
|
pack.release()
|
|
185
253
|
|
package/scripts/dag_validator.js
CHANGED
|
@@ -4,9 +4,39 @@ import { resolve } from 'node:path';
|
|
|
4
4
|
import { fileURLToPath } from 'node:url';
|
|
5
5
|
import process from 'node:process';
|
|
6
6
|
|
|
7
|
+
const INVALID_INPUT = 'DAG must be an array of tasks or an object with a tasks array';
|
|
8
|
+
|
|
7
9
|
// ponytail: in-memory Kahn algorithm; upgrade to streaming DAG for 100k+ nodes
|
|
8
|
-
export function validateDAG(
|
|
9
|
-
|
|
10
|
+
export function validateDAG(input = []) {
|
|
11
|
+
const tasks = Array.isArray(input) ? input : (Array.isArray(input?.tasks) ? input.tasks : null);
|
|
12
|
+
if (!tasks) return { valid: false, cycles: [], missing_dependencies: [], waves: [], errors: [INVALID_INPUT] };
|
|
13
|
+
|
|
14
|
+
const errors = [];
|
|
15
|
+
const seen = new Set();
|
|
16
|
+
tasks.forEach((t, i) => {
|
|
17
|
+
if (!t || typeof t !== 'object' || Array.isArray(t)) {
|
|
18
|
+
errors.push(`Task ${i}: must be an object`);
|
|
19
|
+
return;
|
|
20
|
+
}
|
|
21
|
+
if (typeof t.id !== 'string' || t.id.trim().length === 0) {
|
|
22
|
+
errors.push(`Task ${i}: id must be a non-empty string`);
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
if (seen.has(t.id)) errors.push(`Task ${i}: duplicate id "${t.id}"`);
|
|
26
|
+
seen.add(t.id);
|
|
27
|
+
if (t.depends_on === undefined) return;
|
|
28
|
+
if (!Array.isArray(t.depends_on)) {
|
|
29
|
+
errors.push(`Task "${t.id}": depends_on must be an array of strings`);
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
t.depends_on.forEach((dep) => {
|
|
33
|
+
if (typeof dep !== 'string' || dep.trim().length === 0) {
|
|
34
|
+
errors.push(`Task "${t.id}": depends_on must contain non-empty strings`);
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
if (errors.length > 0) return { valid: false, cycles: [], missing_dependencies: [], waves: [], errors };
|
|
10
40
|
|
|
11
41
|
const inDegree = new Map();
|
|
12
42
|
const dependents = new Map();
|
|
@@ -48,7 +78,7 @@ export function validateDAG(tasks = []) {
|
|
|
48
78
|
const valid = processed === tasks.length && missing_dependencies.length === 0;
|
|
49
79
|
const cycles = valid ? [] : tasks.filter((t) => (inDegree.get(t.id) || 0) > 0).map((t) => t.id);
|
|
50
80
|
|
|
51
|
-
return { valid, cycles, missing_dependencies, waves };
|
|
81
|
+
return { valid, cycles, missing_dependencies, waves, errors };
|
|
52
82
|
}
|
|
53
83
|
|
|
54
84
|
export default validateDAG;
|
|
@@ -66,6 +96,11 @@ Validates DAG acyclicity and computes topological execution waves.`);
|
|
|
66
96
|
process.exit(0);
|
|
67
97
|
}
|
|
68
98
|
|
|
99
|
+
if (!process.argv[2] && process.stdin.isTTY) {
|
|
100
|
+
console.error('Usage: node scripts/dag_validator.js <tasks.json> (or pipe JSON via stdin)');
|
|
101
|
+
process.exit(1);
|
|
102
|
+
}
|
|
103
|
+
|
|
69
104
|
try {
|
|
70
105
|
const raw = process.argv[2] ? readFileSync(process.argv[2], 'utf8') : readFileSync(0, 'utf8');
|
|
71
106
|
const result = validateDAG(JSON.parse(raw));
|
package/scripts/lint.js
CHANGED
|
@@ -1,14 +1,16 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import fs from 'node:fs';
|
|
3
3
|
import path from 'node:path';
|
|
4
|
-
import
|
|
4
|
+
import os from 'node:os';
|
|
5
5
|
import process from 'node:process';
|
|
6
|
+
import { execFileSync } from 'node:child_process';
|
|
6
7
|
import { fileURLToPath } from 'node:url';
|
|
7
8
|
|
|
8
9
|
const repoRoot = fileURLToPath(new URL('..', import.meta.url));
|
|
9
10
|
const targetDirs = ['bin', 'src', 'scripts', 'tests'];
|
|
10
11
|
|
|
11
|
-
|
|
12
|
+
// ponytail: synchronous recursive walk; upgrade to stream/worker pipeline for repos >100k files
|
|
13
|
+
function collectFiles(dir, suffix) {
|
|
12
14
|
const fullPath = path.join(repoRoot, dir);
|
|
13
15
|
if (!fs.existsSync(fullPath)) return [];
|
|
14
16
|
const entries = fs.readdirSync(fullPath, { withFileTypes: true });
|
|
@@ -16,18 +18,20 @@ function collectJsFiles(dir) {
|
|
|
16
18
|
for (const entry of entries) {
|
|
17
19
|
const entryPath = path.join(fullPath, entry.name);
|
|
18
20
|
if (entry.isDirectory()) {
|
|
19
|
-
|
|
20
|
-
|
|
21
|
+
if (['node_modules', '__pycache__', '.git'].includes(entry.name)) continue;
|
|
22
|
+
files.push(...collectFiles(path.relative(repoRoot, entryPath), suffix));
|
|
23
|
+
} else if (entry.isFile() && entry.name.endsWith(suffix)) {
|
|
21
24
|
files.push(entryPath);
|
|
22
25
|
}
|
|
23
26
|
}
|
|
24
27
|
return files;
|
|
25
28
|
}
|
|
26
29
|
|
|
27
|
-
const
|
|
30
|
+
const jsFiles = targetDirs.flatMap((dir) => collectFiles(dir, '.js'));
|
|
31
|
+
const pyFiles = targetDirs.flatMap((dir) => collectFiles(dir, '.py'));
|
|
28
32
|
|
|
29
33
|
let failed = 0;
|
|
30
|
-
for (const file of
|
|
34
|
+
for (const file of jsFiles) {
|
|
31
35
|
try {
|
|
32
36
|
execFileSync(process.execPath, ['--check', file], { stdio: 'inherit' });
|
|
33
37
|
} catch {
|
|
@@ -35,9 +39,45 @@ for (const file of allJsFiles) {
|
|
|
35
39
|
}
|
|
36
40
|
}
|
|
37
41
|
|
|
42
|
+
function findPython() {
|
|
43
|
+
for (const cmd of ['python3', 'python']) {
|
|
44
|
+
try {
|
|
45
|
+
execFileSync(cmd, ['--version'], { stdio: 'ignore' });
|
|
46
|
+
return cmd;
|
|
47
|
+
} catch {}
|
|
48
|
+
}
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const python = pyFiles.length > 0 ? findPython() : null;
|
|
53
|
+
if (python) {
|
|
54
|
+
// py_compile grava bytecode; o prefixo mantém a árvore limpa.
|
|
55
|
+
const pycache = path.join(os.tmpdir(), 'esquadrao-lint-pycache');
|
|
56
|
+
for (const file of pyFiles) {
|
|
57
|
+
try {
|
|
58
|
+
execFileSync(python, ['-m', 'py_compile', file], {
|
|
59
|
+
stdio: 'inherit',
|
|
60
|
+
env: { ...process.env, PYTHONPYCACHEPREFIX: pycache },
|
|
61
|
+
});
|
|
62
|
+
} catch {
|
|
63
|
+
failed++;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
38
68
|
if (failed > 0) {
|
|
39
69
|
console.error(`Lint check failed: ${failed} file(s) with syntax errors.`);
|
|
40
70
|
process.exit(1);
|
|
41
71
|
}
|
|
42
72
|
|
|
43
|
-
|
|
73
|
+
if (pyFiles.length > 0 && !python && process.env.CI) {
|
|
74
|
+
console.error(`Lint check failed: Python interpreter not found; cannot validate ${pyFiles.length} .py file(s).`);
|
|
75
|
+
process.exit(1);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
console.log(`Lint passed: verified ${jsFiles.length} files with node --check.`);
|
|
79
|
+
if (python) {
|
|
80
|
+
console.log(`Lint passed: verified ${pyFiles.length} Python files with py_compile.`);
|
|
81
|
+
} else if (pyFiles.length > 0) {
|
|
82
|
+
console.warn(`Lint skipped: Python interpreter not found; ${pyFiles.length} .py file(s) not checked.`);
|
|
83
|
+
}
|
package/scripts/merkle_verify.js
CHANGED
|
@@ -14,7 +14,7 @@ export function canonicalStringify(val) {
|
|
|
14
14
|
}
|
|
15
15
|
|
|
16
16
|
export function computeBlockHash(block) {
|
|
17
|
-
if (!block || typeof block !== 'object') return '';
|
|
17
|
+
if (!block || typeof block !== 'object' || Array.isArray(block)) return '';
|
|
18
18
|
const { hash: _, ...payload } = block;
|
|
19
19
|
return createHash('sha256').update(canonicalStringify(payload)).digest('hex');
|
|
20
20
|
}
|
|
@@ -71,6 +71,11 @@ Validates cryptographic hash continuity and payload integrity across blocks.`);
|
|
|
71
71
|
process.exit(0);
|
|
72
72
|
}
|
|
73
73
|
|
|
74
|
+
if (!process.argv[2] && process.stdin.isTTY) {
|
|
75
|
+
console.error('Usage: node scripts/merkle_verify.js <ledger.json> (or pipe JSON via stdin)');
|
|
76
|
+
process.exit(1);
|
|
77
|
+
}
|
|
78
|
+
|
|
74
79
|
try {
|
|
75
80
|
const raw = process.argv[2] ? readFileSync(process.argv[2], 'utf8') : readFileSync(0, 'utf8');
|
|
76
81
|
const result = verifyLedger(JSON.parse(raw));
|
|
@@ -69,6 +69,8 @@ O usuário escolhe uma pasta no computador para ser seu repositório/workspace p
|
|
|
69
69
|
# Dentro da pasta do seu projeto/workspace
|
|
70
70
|
esquadrao setup
|
|
71
71
|
```
|
|
72
|
+
> **Persistência de Perfil:** O perfil do workspace fica em `<workspace>/.esquadrao/profile.json` (espelho em `studio.json`). Sem `--dest`, o CLI descobre o workspace subindo a partir do diretório atual até encontrar `studio.json`.
|
|
73
|
+
|
|
72
74
|
> **Acervo de Apoio:** Os packs de vídeos e imagens adquiridos na plataforma devem ser descompactados e mantidos dentro dessa mesma pasta de trabalho (ex.: `./packs/`), garantindo acesso imediato aos agentes para cortes e B-rolls.
|
|
73
75
|
|
|
74
76
|
### Passo 4: Inicialização do Estúdio
|
|
@@ -119,6 +121,35 @@ esquadrao studio auto-clip ./caminho/meu-video.mp4 --dest ./workspace --json
|
|
|
119
121
|
|
|
120
122
|
> **Templates de legenda:** o catálogo canônico tem nove presets em [`references/caption-templates.md`](references/caption-templates.md), disponíveis no CLI 1.5.0 via `--caption-template <id>` ou `captions[].template`. `--caption-style impact|word|full` permanece como legado.
|
|
121
123
|
|
|
124
|
+
### Acompanhamento visual no navegador (`studio serve` — CLI-15)
|
|
125
|
+
|
|
126
|
+
> **Confirme a versão antes de oferecer.** O subcomando existe desde o CLI-15; em instalações anteriores, `esquadrao studio serve --help` falha e você deve usar o caminho de terminal descrito no fim desta seção.
|
|
127
|
+
|
|
128
|
+
**Ofereça assim:**
|
|
129
|
+
|
|
130
|
+
```bash
|
|
131
|
+
# Sobe o companion local no workspace atual (porta padrão 4310; abre o navegador)
|
|
132
|
+
esquadrao studio serve --dest ./workspace
|
|
133
|
+
|
|
134
|
+
# Sem abrir o navegador (para o usuário abrir a URL impressa) ou em porta alternativa
|
|
135
|
+
esquadrao studio serve --dest ./workspace --no-open --port 4310
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
- **O que o usuário vê:** os **nove templates de legenda** com preview de 5 s, os packs descritos no catálogo `.esquadrao/broll-catalog.json` (campo `pack`, `description` e `tags`), o job em andamento e o vídeo final aprovado pelo QA.
|
|
139
|
+
- **Modo híbrido:** a LLM continua executando `import`, `auto-clip`, `render` e `batch` no terminal; o servidor apenas observa. A UI pode disparar **um job por vez**, no workspace autorizado.
|
|
140
|
+
- **Estágios exibidos:** `queued` → `importing` → `detecting_silence` → `transcribing` → `planning` → `rendering` → `qa` → `done`/`failed`/`canceled`, com resumo humano do `EditPlan` e logs sem credenciais.
|
|
141
|
+
- **Segurança, diga em uma frase:** roda só em `127.0.0.1`, com token efêmero e allowlist de workspaces; não abre porta para a rede, não usa nuvem e não lê `OPENAI_API_KEY`, Supabase ou Stripe. Nunca peça ao usuário para expor a porta, criar túnel ou colar chaves para "habilitar a tela".
|
|
142
|
+
|
|
143
|
+
**Se a instalação for anterior ao CLI-15, entregue o mesmo acompanhamento por texto:**
|
|
144
|
+
|
|
145
|
+
```bash
|
|
146
|
+
esquadrao studio caption-templates --json # os nove presets e parâmetros
|
|
147
|
+
cat ./workspace/.esquadrao/broll-catalog.json # packs e descrições para escolher B-roll
|
|
148
|
+
esquadrao studio render ./workspace/packages/editplan.json --dest ./workspace --json
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
Peça ao usuário para abrir o MP4 em `artifacts/` e relate estágio, artefato e resultado do QA em texto.
|
|
152
|
+
|
|
122
153
|
---
|
|
123
154
|
|
|
124
155
|
## 3. Modelos Canônicos de EditPlan v1 (Prontos para LLM sem Alucinação)
|
|
@@ -315,6 +346,7 @@ esquadrao studio auto-clip ./caminho/meu-video.mp4 --dest ./workspace --json
|
|
|
315
346
|
- **Split permanente:** `auto-clip --broll <pack> --layout split_bottom --overlay-duration full` mantém o orador no topo e o pack na base durante todo o clipe; o pack é repetido em loop e o áudio original é preservado.
|
|
316
347
|
- O layout `split_top` está implementado desde 1.7.0: orador na metade inferior e pack na metade superior, com loop (CLI-06).
|
|
317
348
|
- **Recorte de pessoa com troca de fundo:** disponível em `studio cutout <video> --background <pack> --python <interpretador>`, como experimental. Requer Python com `rembg`, `onnxruntime`, `opencv-python-headless`, `numpy` e Pillow; ~18–20 min de CPU por 60 s em 15 fps. Não prometa tempo real nem qualidade de estúdio. Detalhes em [`references/composicoes-especiais.md`](./references/composicoes-especiais.md).
|
|
349
|
+
- **Cutout não é layout:** `overlays[].layout` aceita exclusivamente `fullscreen`, `pip`, `split_bottom` e `split_top`. Recorte de pessoa é o subcomando separado `studio cutout`, com `--background`; nunca escreva `layout: "cutout"` em um EditPlan nem prometa corte de pessoa via `--layout`.
|
|
318
350
|
7. **Verificação Técnica Independente:** Sempre execute `studio qa` com `--plan` para validar integridade antes de concluir a tarefa.
|
|
319
351
|
8. **Renderização em Lote:** Para múltiplos planos, use `esquadrao studio batch <dir> --dest <workspace> --json`; o comando renderiza em sequência e agrega o QA (CLI-07).
|
|
320
352
|
9. **Onboarding Real:** O comando `esquadrao onboard --mode podcast_clip` usa o pipeline real de `auto-clip`; os modos `dark` e `edit_only` continuam gerando planos guiados.
|
|
@@ -96,4 +96,4 @@ Critérios de aceite:
|
|
|
96
96
|
|
|
97
97
|
- Split: `podpah-neymar-split-pack.mp4` (protótipo externo, 60 s, 1080×1920) e teste `split_bottom full loops a short b-roll`.
|
|
98
98
|
- Cutout: `podpah-neymar-cutout-pack.mp4` (protótipo externo, 60 s, 1080×1920, cor corrigida) e teste de contrato do comando.
|
|
99
|
-
- Suíte:
|
|
99
|
+
- Suíte: 129 testes (127 aprovados + 2 skips condicionais), lint em 50 arquivos.
|
|
@@ -4,22 +4,16 @@ Guia para Windows / PowerShell: instalar, escolher proporção, configurar corte
|
|
|
4
4
|
|
|
5
5
|
## 1. Pré-requisitos e instalação
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
Basta Node.js 18 ou superior. O FFmpeg e o ffprobe vêm embutidos no pacote: não instale
|
|
8
|
+
nada por `winget`/`choco`, não edite o PATH e não abra outro terminal.
|
|
8
9
|
|
|
9
10
|
```powershell
|
|
10
11
|
node --version
|
|
11
12
|
npm --version
|
|
12
|
-
|
|
13
|
-
ffprobe -version
|
|
13
|
+
npx @esquadrao/cli setup
|
|
14
14
|
```
|
|
15
15
|
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
```powershell
|
|
19
|
-
winget install --id Gyan.FFmpeg -e
|
|
20
|
-
```
|
|
21
|
-
|
|
22
|
-
Abra um novo PowerShell após instalar para atualizar o PATH.
|
|
16
|
+
O `setup` confirma o ambiente e mostra se o FFmpeg embutido está disponível.
|
|
23
17
|
|
|
24
18
|
Se você já tem o repositório clonado, defina o caminho absoluto para `bin\cli.js`:
|
|
25
19
|
|
|
@@ -24,16 +24,12 @@ Envie uma mensagem amigável e direta coletando as decisões essenciais:
|
|
|
24
24
|
> *3. Qual é o arquivo de vídeo que vamos usar de fonte?"*
|
|
25
25
|
|
|
26
26
|
### Fase 2: Checagem de Ambiente
|
|
27
|
-
Antes de criar arquivos,
|
|
27
|
+
Antes de criar arquivos, confirme apenas o Node.js:
|
|
28
28
|
```bash
|
|
29
29
|
node -v
|
|
30
|
-
|
|
31
|
-
ffprobe -version
|
|
30
|
+
esquadrao setup --json
|
|
32
31
|
```
|
|
33
|
-
|
|
34
|
-
- **Windows:** `winget install Gyan.FFmpeg`
|
|
35
|
-
- **macOS:** `brew install ffmpeg`
|
|
36
|
-
- **Linux:** `sudo apt update && sudo apt install -y ffmpeg`
|
|
32
|
+
O FFmpeg e o ffprobe vêm embutidos no pacote (`ffmpeg-static` 5.2.0 e `ffprobe-static`) e são resolvidos automaticamente. **Nunca instrua o usuário a instalar FFmpeg**, usar `sudo`, `brew`, `winget` ou `apt`: o `setup` reporta a origem resolvida (`bundled`, `cache` ou `system`).
|
|
37
33
|
|
|
38
34
|
### Fase 3: Preparação do Workspace
|
|
39
35
|
Execute no terminal:
|
|
@@ -116,13 +112,39 @@ O comando emite o resumo com total de silêncio expurgado, quantidade de cortes
|
|
|
116
112
|
>
|
|
117
113
|
> **Templates de legenda:** existem nove presets documentados em [`caption-templates.md`](caption-templates.md), disponíveis via `--caption-template <id>` ou `captions[].template`. `--caption-style impact|word|full` permanece como legado.
|
|
118
114
|
|
|
115
|
+
### Fase de Acompanhamento Visual (`studio serve` — CLI-15)
|
|
116
|
+
|
|
117
|
+
> **Checagem antes de oferecer:** rode `esquadrao studio serve --help`. Se o comando não existir, a instalação é anterior ao CLI-15; use a alternativa de terminal abaixo e não descreva uma UI ausente.
|
|
118
|
+
|
|
119
|
+
Conduza o usuário em uma frase objetiva:
|
|
120
|
+
|
|
121
|
+
```bash
|
|
122
|
+
# Abre o companion local no navegador, observando o workspace atual
|
|
123
|
+
esquadrao studio serve --dest ./workspace
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
- **Templates:** a página mostra os **nove presets** com preview de 5 s; o usuário escolhe o ID e você aplica em `--caption-template <id>` ou `captions[].template`.
|
|
127
|
+
- **Packs:** navegue pelo `.esquadrao/broll-catalog.json` (campos `pack`, `filename`, `duration_ms`, `description`, `tags`) e proponha 2 a 4 cenas coerentes com a fala; não invente nomes de arquivo.
|
|
128
|
+
- **Ao vivo:** você segue rodando `auto-clip`, `render` ou `batch` no terminal; a tela acompanha os estágios `queued` → `importing` → `detecting_silence` → `transcribing` → `planning` → `rendering` → `qa` → `done`/`failed`/`canceled`, com resumo do plano e o MP4 final.
|
|
129
|
+
- **Limites que você deve declarar:** bind exclusivo em `127.0.0.1`, token efêmero, allowlist de workspaces, **1 job por vez** pela UI, sem Next.js, banco ou nuvem, e sem leitura de `OPENAI_API_KEY`, Supabase ou Stripe. Nunca sugira túnel, `0.0.0.0` ou colar chaves para "liberar" a tela.
|
|
130
|
+
|
|
131
|
+
**Em instalações anteriores ao CLI-15, entregue o mesmo acompanhamento por texto:**
|
|
132
|
+
|
|
133
|
+
```bash
|
|
134
|
+
esquadrao studio caption-templates --json # lista os nove templates
|
|
135
|
+
# leia ./workspace/.esquadrao/broll-catalog.json para escolher packs
|
|
136
|
+
esquadrao studio render ./workspace/packages/editplan.json --dest ./workspace --json
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
Depois informe: estágio concluído, caminho do artefato e resultado do QA. Não descreva uma UI que não existe.
|
|
140
|
+
|
|
119
141
|
---
|
|
120
142
|
|
|
121
143
|
## 3. Matriz de Tratamento de Erros Comuns
|
|
122
144
|
|
|
123
145
|
| Erro Observado | Causa Raiz | Ação Corretiva Determinística |
|
|
124
146
|
| :--- | :--- | :--- |
|
|
125
|
-
| `ffmpeg is not installed` | Binário
|
|
147
|
+
| `ffmpeg is not installed` | Binário embutido não resolvido (pacote corrompido ou instalação parcial) | Reinstalar o pacote (`npm install -g @esquadrao/cli`) e rodar `esquadrao setup`; nunca instalar FFmpeg no sistema. |
|
|
126
148
|
| `out_ms exceeds asset duration` | Ponto de saída além do arquivo | Obter duração real com `studio import` e recalcular `out_ms`. |
|
|
127
149
|
| `Missing audio stream in artifact` | Fonte sem áudio ou falha de mix | Garantir `anullsrc` para vídeo mudo ou verificar se o arquivo original tem áudio. |
|
|
128
150
|
| `Caption special characters error` | Caracteres `%` ou `'` na legenda | O motor trata com `\%` e `\'`. Não usar tags HTML em legendas. |
|
|
@@ -163,6 +185,7 @@ Para evitar que o corte fique monótono ("cabeça falante"), a LLM insere B-roll
|
|
|
163
185
|
- **`layout: "pip"` (Picture-in-Picture):** Quando o orador estiver apontando para um objeto ou reagindo a algo.
|
|
164
186
|
- **`layout: "split_top"` (Entregue em 1.7.0):** Orador embaixo e B-roll em cima, com loop. Use `--overlay-duration full` para manter o pack durante todo o clipe.
|
|
165
187
|
- **Recorte de pessoa / cutout (experimental / CLI-14):** `studio cutout --background <pack> --python <interpretador>` remove o fundo e compõe o pack atrás do orador. Exige Python com `rembg`/OpenCV e custa ~18–20 min de CPU por 60 s em 15 fps; não prometa tempo real. Consulte [`composicoes-especiais.md`](./composicoes-especiais.md).
|
|
188
|
+
- **Cutout não é um layout de overlay:** `overlays[].layout` só aceita `fullscreen`, `pip`, `split_bottom` e `split_top`. Nunca emita `layout: "cutout"`; recorte de pessoa é sempre o subcomando separado `studio cutout`.
|
|
166
189
|
|
|
167
190
|
### Passo 4: Trilha Sonora com Ducking
|
|
168
191
|
Importe a música de fundo e configure a atenuação de volume:
|
package/src/binaries.js
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
// Resolve ffmpeg/ffprobe sem exigir instalação manual nem edição de PATH.
|
|
2
|
+
//
|
|
3
|
+
// Ordem: variável de ambiente -> cache do usuário -> binário embutido no pacote
|
|
4
|
+
// (optionalDependencies ffmpeg-static/ffprobe-static) -> PATH do sistema.
|
|
5
|
+
// O diretório encontrado é injetado no PATH do processo, então todo spawn
|
|
6
|
+
// existente continua funcionando sem mudanças.
|
|
7
|
+
|
|
8
|
+
import fs from 'node:fs';
|
|
9
|
+
import os from 'node:os';
|
|
10
|
+
import path from 'node:path';
|
|
11
|
+
import { createRequire } from 'node:module';
|
|
12
|
+
|
|
13
|
+
const require = createRequire(import.meta.url);
|
|
14
|
+
const EXE = process.platform === 'win32' ? '.exe' : '';
|
|
15
|
+
const TARGET = `${process.platform}-${process.arch}`;
|
|
16
|
+
|
|
17
|
+
export const BINARY_CACHE = path.join(os.homedir(), '.esquadrao', 'bin', TARGET);
|
|
18
|
+
|
|
19
|
+
const ENV_KEYS = { ffmpeg: 'ESQUADRAO_FFMPEG', ffprobe: 'ESQUADRAO_FFPROBE' };
|
|
20
|
+
|
|
21
|
+
function fromPackage(name) {
|
|
22
|
+
try {
|
|
23
|
+
if (name === 'ffmpeg') {
|
|
24
|
+
const resolved = require('ffmpeg-static');
|
|
25
|
+
return typeof resolved === 'string' && fs.existsSync(resolved) ? resolved : null;
|
|
26
|
+
}
|
|
27
|
+
const resolved = require('ffprobe-static');
|
|
28
|
+
return resolved?.path && fs.existsSync(resolved.path) ? resolved.path : null;
|
|
29
|
+
} catch {
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Caminho utilizável para um binário, com a origem da resolução. */
|
|
35
|
+
export function resolveBinary(name) {
|
|
36
|
+
if (!ENV_KEYS[name]) throw new Error(`Binário desconhecido: ${name}`);
|
|
37
|
+
|
|
38
|
+
const override = process.env[ENV_KEYS[name]];
|
|
39
|
+
if (override && fs.existsSync(override)) return { path: override, source: 'env' };
|
|
40
|
+
|
|
41
|
+
const cached = path.join(BINARY_CACHE, `${name}${EXE}`);
|
|
42
|
+
if (fs.existsSync(cached)) return { path: cached, source: 'cache' };
|
|
43
|
+
|
|
44
|
+
const bundled = fromPackage(name);
|
|
45
|
+
if (bundled) return { path: bundled, source: 'bundled' };
|
|
46
|
+
|
|
47
|
+
return { path: name, source: 'path' };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Injeta os binários embutidos no PATH do processo. Silencioso e idempotente. */
|
|
51
|
+
export function ensureBundledPath() {
|
|
52
|
+
const dirs = new Set();
|
|
53
|
+
for (const name of ['ffmpeg', 'ffprobe']) {
|
|
54
|
+
const { path: binary, source } = resolveBinary(name);
|
|
55
|
+
if (source !== 'path') dirs.add(path.dirname(binary));
|
|
56
|
+
}
|
|
57
|
+
if (dirs.size === 0) return null;
|
|
58
|
+
|
|
59
|
+
const prefix = [...dirs].join(path.delimiter);
|
|
60
|
+
if (!process.env.PATH?.startsWith(prefix)) {
|
|
61
|
+
process.env.PATH = `${prefix}${path.delimiter}${process.env.PATH || ''}`;
|
|
62
|
+
}
|
|
63
|
+
return prefix;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Relatório curto para `setup`/`doctor`, sem executar os binários. */
|
|
67
|
+
export function binaryReport() {
|
|
68
|
+
return Object.fromEntries(
|
|
69
|
+
['ffmpeg', 'ffprobe'].map((name) => {
|
|
70
|
+
const resolved = resolveBinary(name);
|
|
71
|
+
return [name, resolved.source === 'path' ? { source: 'system', path: null } : resolved];
|
|
72
|
+
})
|
|
73
|
+
);
|
|
74
|
+
}
|
package/src/commands/onboard.js
CHANGED
|
@@ -9,6 +9,7 @@ import { stdin as defaultInput, stdout as defaultOutput } from 'node:process';
|
|
|
9
9
|
import {
|
|
10
10
|
checkBinary,
|
|
11
11
|
findSystemFont,
|
|
12
|
+
findWorkspaceDir,
|
|
12
13
|
run as studioRun,
|
|
13
14
|
buildCaptionFilters,
|
|
14
15
|
buildClipFilters,
|
|
@@ -16,15 +17,10 @@ import {
|
|
|
16
17
|
} from './studio.js';
|
|
17
18
|
import { tryAutoInstallFfmpeg } from './setup.js';
|
|
18
19
|
import { validateEditPlan } from '../roles/mediaProducer.js';
|
|
20
|
+
import { startJobTelemetry } from '../studio/jobTelemetry.js';
|
|
19
21
|
|
|
20
|
-
export function getFfmpegInstallInstructions(
|
|
21
|
-
|
|
22
|
-
return 'winget install Gyan.FFmpeg (or: choco install ffmpeg)';
|
|
23
|
-
}
|
|
24
|
-
if (platform === 'darwin') {
|
|
25
|
-
return 'brew install ffmpeg';
|
|
26
|
-
}
|
|
27
|
-
return 'sudo apt install ffmpeg (Debian/Ubuntu) or your package manager';
|
|
22
|
+
export function getFfmpegInstallInstructions() {
|
|
23
|
+
return 'o FFmpeg já vem embutido no Esquadrão. Rode "esquadrao setup" para restaurá-lo.';
|
|
28
24
|
}
|
|
29
25
|
|
|
30
26
|
export function detectEnvironment() {
|
|
@@ -34,21 +30,17 @@ export function detectEnvironment() {
|
|
|
34
30
|
}
|
|
35
31
|
|
|
36
32
|
let hasFfmpeg = checkBinary('ffmpeg') && checkBinary('ffprobe');
|
|
37
|
-
|
|
38
|
-
if (!hasFfmpeg) {
|
|
39
|
-
autoInstalledFfmpeg = tryAutoInstallFfmpeg();
|
|
40
|
-
hasFfmpeg = checkBinary('ffmpeg') && checkBinary('ffprobe');
|
|
41
|
-
}
|
|
33
|
+
if (!hasFfmpeg) hasFfmpeg = tryAutoInstallFfmpeg();
|
|
42
34
|
|
|
43
35
|
if (!hasFfmpeg) {
|
|
44
36
|
const missing = [!checkBinary('ffmpeg') && 'ffmpeg', !checkBinary('ffprobe') && 'ffprobe'].filter(Boolean).join(' and ');
|
|
45
37
|
throw new Error(
|
|
46
|
-
`${missing}
|
|
38
|
+
`${missing} não foi encontrado. ${getFfmpegInstallInstructions()}`
|
|
47
39
|
);
|
|
48
40
|
}
|
|
49
41
|
|
|
50
42
|
const font = findSystemFont();
|
|
51
|
-
return { nodeVersion: process.versions.node, ffmpeg: true,
|
|
43
|
+
return { nodeVersion: process.versions.node, ffmpeg: true, font };
|
|
52
44
|
}
|
|
53
45
|
|
|
54
46
|
export function loadProfile(dir) {
|
|
@@ -289,6 +281,9 @@ Options:
|
|
|
289
281
|
return;
|
|
290
282
|
}
|
|
291
283
|
|
|
284
|
+
const telemetry = startJobTelemetry({ command: 'onboard', argv: positionals.slice(0, 4), workspace: flags.dest || null });
|
|
285
|
+
telemetry?.stage('importing');
|
|
286
|
+
|
|
292
287
|
// 1. Environment Detection
|
|
293
288
|
let env;
|
|
294
289
|
try {
|
|
@@ -344,7 +339,7 @@ Options:
|
|
|
344
339
|
try {
|
|
345
340
|
// 2. Directory Resolution
|
|
346
341
|
let targetDir = flags.dest || positionals[0];
|
|
347
|
-
const cwdProfile = loadProfile(
|
|
342
|
+
const cwdProfile = loadProfile(findWorkspaceDir());
|
|
348
343
|
|
|
349
344
|
if (!targetDir && cwdProfile?.default_dir) {
|
|
350
345
|
targetDir = cwdProfile.default_dir;
|