@yoonion/mimi-seed-mcp 0.31.0 → 0.32.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 +3 -1
- package/assets/agent-guide.md +4 -3
- package/dist/i18n/tools-en/video.d.ts +16 -0
- package/dist/i18n/tools-en/video.js +16 -0
- package/dist/lib/telegram-approval.d.ts +4 -2
- package/dist/lib/telegram-approval.js +165 -14
- package/dist/lib/telegram-relay.d.ts +93 -0
- package/dist/lib/telegram-relay.js +234 -0
- package/dist/registers/video.js +73 -2
- package/dist/video/clips.d.ts +183 -0
- package/dist/video/clips.js +457 -0
- package/dist/video/narration.d.ts +94 -0
- package/dist/video/narration.js +270 -0
- package/dist/video/project.d.ts +1 -1
- package/dist/video/project.js +7 -4
- package/dist/video/providers.d.ts +3 -2
- package/dist/video/providers.js +3 -3
- package/dist/video/render.d.ts +7 -0
- package/dist/video/render.js +50 -3
- package/dist/video/schemas.d.ts +1 -0
- package/dist/video/schemas.js +1 -0
- package/dist/video/types.d.ts +2 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/tool-manifest.json +12 -4
|
@@ -0,0 +1,457 @@
|
|
|
1
|
+
// AI 영상 클립 — fal 큐 API 로 장면 클립을 요청하고, 상태 조회 때 결과를 받아 자산으로 등록한다.
|
|
2
|
+
//
|
|
3
|
+
// 설계: docs/design/media-generation-providers.md §4.2–§5, §9 Q1.
|
|
4
|
+
// - 요청 기록(.jobs/clip-<uuid>.json)은 제출 **전에** 쓴다. MCP 가 재시작돼도 이어서 조회할 수 있다.
|
|
5
|
+
// - 같은 (장면·모델·프롬프트·이미지) 요청이 이미 진행 중이거나 결과가 애매하면 resubmit 없이는 다시 보내지 않는다.
|
|
6
|
+
// fal 에는 중복 방지 키가 없어서, 눈먼 재시도가 두 번 과금되는 유일한 길이다.
|
|
7
|
+
// - 상태·결과 URL 은 fal 이 돌려준 값을 쓰고(경로를 직접 만들지 않는다), 호출 전마다 queue.fal.run 인지 확인한다.
|
|
8
|
+
// API 키가 다른 호스트로 새면 안 된다. 결과 파일 다운로드에는 키를 붙이지 않는다.
|
|
9
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
10
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, unlinkSync } from 'node:fs';
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
import { z } from 'zod';
|
|
13
|
+
import { catalog } from '#core/lang.js';
|
|
14
|
+
import { fetchWithTimeout, HTTP_TRANSFER_TIMEOUT_MS } from '../lib/http.js';
|
|
15
|
+
import { encodePathSegment } from '../lib/url-path.js';
|
|
16
|
+
import { readJson, writeJsonAtomic } from './files.js';
|
|
17
|
+
import { loadAssets, loadProject, registerAsset } from './project.js';
|
|
18
|
+
import { downloadLimited, hasMp4Signature, sanitizeExternalText } from './providers.js';
|
|
19
|
+
import { parseFile } from './schemas.js';
|
|
20
|
+
const M = catalog({
|
|
21
|
+
envRequired: '❌ FAL_KEY 환경변수가 필요합니다.',
|
|
22
|
+
badModel: (model) => `모델 경로 형식이 아닙니다 (예: <owner>/<model>/<task>): ${model}`,
|
|
23
|
+
unknownScene: (id) => `프로젝트에 없는 장면입니다: ${id}`,
|
|
24
|
+
noPrompt: (id) => `장면에 프롬프트가 없습니다. prompt 를 넘기거나 visualPrompt 를 채우세요: ${id}`,
|
|
25
|
+
badImage: (id) => `이미지 자산이 아니거나 파일이 없습니다: ${id}`,
|
|
26
|
+
imageTooLarge: (id, mb) => `이미지가 ${mb}MB 를 넘어 업로드할 수 없습니다: ${id}`,
|
|
27
|
+
imageType: (id) => `PNG·JPEG·WebP 이미지만 보낼 수 있습니다: ${id}`,
|
|
28
|
+
duplicate: (sceneId, jobId, status) => `같은 장면·모델·프롬프트 요청이 이미 있습니다 (${jobId}, ${status}). 두 번 과금될 수 있어 다시 보내지 않았습니다. ` +
|
|
29
|
+
`video_clip_status 로 먼저 확인하고, 그래도 새로 만들려면 resubmit=true 로 부르세요. 장면: ${sceneId}`,
|
|
30
|
+
submitFailed: (status, message) => `fal 요청 실패 (${status}): ${message}`,
|
|
31
|
+
submitUnclear: 'fal 이 요청을 받았는지 알 수 없습니다. fal 대시보드에서 확인한 뒤에만 resubmit=true 로 다시 보내세요.',
|
|
32
|
+
badQueueUrl: (url) => `fal 큐 주소가 아닙니다: ${url}`,
|
|
33
|
+
badResponse: 'fal 응답 형식이 예상과 다릅니다.',
|
|
34
|
+
jobNotFound: (id) => `클립 요청 기록이 없습니다: ${id}`,
|
|
35
|
+
pending: '제출 결과를 확인하지 못한 요청입니다. fal 대시보드에서 확인한 뒤 필요하면 resubmit=true 로 다시 보내세요.',
|
|
36
|
+
notFound: 'fal 에서 요청을 찾을 수 없습니다 (만료됐거나 다른 계정).',
|
|
37
|
+
noVideo: 'fal 결과에 영상 URL 이 없습니다.',
|
|
38
|
+
badOutputUrl: (host) => `허용되지 않은 결과 파일 주소입니다: ${host}`,
|
|
39
|
+
noLocation: '리디렉션 응답에 Location 헤더가 없습니다.',
|
|
40
|
+
tooManyRedirects: '결과 파일 리디렉션이 3회를 넘었습니다.',
|
|
41
|
+
downloadFailed: (status) => `결과 파일 다운로드 실패 (${status})`,
|
|
42
|
+
notMp4: '결과 파일이 MP4 가 아닙니다.',
|
|
43
|
+
license: (model) => `fal-hosted model output (${model}); use subject to fal and the model provider's terms`,
|
|
44
|
+
costUnknown: '알 수 없음 — fal 모델 페이지의 가격을 확인하세요',
|
|
45
|
+
acceptedUnusable: (id) => `fal 이 요청을 받았습니다 (request_id ${id}). 다시 보내면 두 번 과금됩니다 — 결과는 fal 대시보드에서 이 id 로 확인하세요.`,
|
|
46
|
+
manualDownload: (url) => `결과는 이미 만들어졌습니다. 파일을 직접 받아 video_add_local_asset 로 등록하세요: ${url}`,
|
|
47
|
+
}, {
|
|
48
|
+
envRequired: '❌ The FAL_KEY environment variable is required.',
|
|
49
|
+
badModel: (model) => `Not a model path (e.g. <owner>/<model>/<task>): ${model}`,
|
|
50
|
+
unknownScene: (id) => `Scene not in the project: ${id}`,
|
|
51
|
+
noPrompt: (id) => `The scene has no prompt. Pass prompt or fill visualPrompt: ${id}`,
|
|
52
|
+
badImage: (id) => `Not an image asset, or its file is missing: ${id}`,
|
|
53
|
+
imageTooLarge: (id, mb) => `The image is over ${mb}MB and cannot be uploaded: ${id}`,
|
|
54
|
+
imageType: (id) => `Only PNG, JPEG, and WebP images can be sent: ${id}`,
|
|
55
|
+
duplicate: (sceneId, jobId, status) => `A request for the same scene, model, and prompt already exists (${jobId}, ${status}). Not sent again, since that could charge twice. ` +
|
|
56
|
+
`Check it with video_clip_status first; to make a new one anyway, call with resubmit=true. Scene: ${sceneId}`,
|
|
57
|
+
submitFailed: (status, message) => `fal request failed (${status}): ${message}`,
|
|
58
|
+
submitUnclear: 'It is unknown whether fal received the request. Resend with resubmit=true only after checking the fal dashboard.',
|
|
59
|
+
badQueueUrl: (url) => `Not a fal queue URL: ${url}`,
|
|
60
|
+
badResponse: 'The fal response has an unexpected shape.',
|
|
61
|
+
jobNotFound: (id) => `No clip request record: ${id}`,
|
|
62
|
+
pending: 'The submit result was never confirmed. Check the fal dashboard, then resend with resubmit=true if needed.',
|
|
63
|
+
notFound: 'fal cannot find the request (expired, or another account).',
|
|
64
|
+
noVideo: 'The fal result has no video URL.',
|
|
65
|
+
badOutputUrl: (host) => `Output file URL not allowed: ${host}`,
|
|
66
|
+
noLocation: 'The redirect response has no Location header.',
|
|
67
|
+
tooManyRedirects: 'Output file redirects exceeded 3.',
|
|
68
|
+
downloadFailed: (status) => `Output file download failed (${status})`,
|
|
69
|
+
notMp4: 'The output file is not an MP4.',
|
|
70
|
+
license: (model) => `fal-hosted model output (${model}); use subject to fal and the model provider's terms`,
|
|
71
|
+
costUnknown: 'unknown — check the price on the fal model page',
|
|
72
|
+
acceptedUnusable: (id) => `fal accepted the request (request_id ${id}). Sending it again would charge twice — find the result in the fal dashboard by this id.`,
|
|
73
|
+
manualDownload: (url) => `The result was already generated. Download it yourself and register it with video_add_local_asset: ${url}`,
|
|
74
|
+
});
|
|
75
|
+
const QUEUE_ORIGIN = 'https://queue.fal.run';
|
|
76
|
+
const MAX_IMAGE_BYTES = 8 * 1024 * 1024;
|
|
77
|
+
const MAX_CLIP_BYTES = 200 * 1024 * 1024;
|
|
78
|
+
export const FAL_MODEL = /^[a-z0-9][a-z0-9._-]*(\/[a-z0-9][a-z0-9._-]*){1,5}$/;
|
|
79
|
+
const IMAGE_MIME = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp' };
|
|
80
|
+
export const clipJobSchema = z.object({
|
|
81
|
+
id: z.string().uuid(),
|
|
82
|
+
kind: z.literal('clip'),
|
|
83
|
+
provider: z.literal('fal'),
|
|
84
|
+
model: z.string().regex(FAL_MODEL),
|
|
85
|
+
sceneId: z.string().min(1).max(100),
|
|
86
|
+
prompt: z.string().min(1).max(10_000),
|
|
87
|
+
promptHash: z.string().regex(/^[a-f0-9]{64}$/),
|
|
88
|
+
imageAssetId: z.string().max(200).optional(),
|
|
89
|
+
imageSha256: z.string().regex(/^[a-f0-9]{64}$/).optional(),
|
|
90
|
+
durationSec: z.number().int().positive().max(60),
|
|
91
|
+
aspectRatio: z.string().max(10),
|
|
92
|
+
status: z.enum(['pending', 'submitted', 'running', 'succeeded', 'failed']),
|
|
93
|
+
providerRequestId: z.string().max(200).optional(),
|
|
94
|
+
statusUrl: z.string().url().optional(),
|
|
95
|
+
responseUrl: z.string().url().optional(),
|
|
96
|
+
outputUrl: z.string().url().optional(),
|
|
97
|
+
assetId: z.string().max(200).optional(),
|
|
98
|
+
error: z.string().max(5_000).optional(),
|
|
99
|
+
createdAt: z.string().datetime(),
|
|
100
|
+
updatedAt: z.string().datetime(),
|
|
101
|
+
});
|
|
102
|
+
function apiKey() {
|
|
103
|
+
const value = process.env.FAL_KEY?.trim();
|
|
104
|
+
if (!value)
|
|
105
|
+
throw new Error(M().envRequired);
|
|
106
|
+
return value;
|
|
107
|
+
}
|
|
108
|
+
function jobsDir(projectDir) {
|
|
109
|
+
return path.join(path.resolve(projectDir), '.jobs');
|
|
110
|
+
}
|
|
111
|
+
function clipJobPath(projectDir, jobId) {
|
|
112
|
+
return path.join(jobsDir(projectDir), `clip-${jobId}.json`);
|
|
113
|
+
}
|
|
114
|
+
function saveJob(projectDir, job) {
|
|
115
|
+
mkdirSync(jobsDir(projectDir), { recursive: true });
|
|
116
|
+
writeJsonAtomic(clipJobPath(projectDir, job.id), job);
|
|
117
|
+
return job;
|
|
118
|
+
}
|
|
119
|
+
function updateJob(projectDir, job, patch) {
|
|
120
|
+
return saveJob(projectDir, { ...job, ...patch, updatedAt: new Date().toISOString() });
|
|
121
|
+
}
|
|
122
|
+
function loadJob(projectDir, jobId) {
|
|
123
|
+
const filePath = clipJobPath(projectDir, jobId);
|
|
124
|
+
if (!existsSync(filePath))
|
|
125
|
+
throw new Error(M().jobNotFound(jobId));
|
|
126
|
+
return parseFile(clipJobSchema, readJson(filePath), filePath);
|
|
127
|
+
}
|
|
128
|
+
function listJobs(projectDir) {
|
|
129
|
+
const dir = jobsDir(projectDir);
|
|
130
|
+
if (!existsSync(dir))
|
|
131
|
+
return [];
|
|
132
|
+
const jobs = [];
|
|
133
|
+
for (const name of readdirSync(dir)) {
|
|
134
|
+
if (!/^clip-[0-9a-f-]{36}\.json$/.test(name))
|
|
135
|
+
continue;
|
|
136
|
+
const parsed = clipJobSchema.safeParse(readJson(path.join(dir, name)));
|
|
137
|
+
// 손상된 기록은 중복 검사에서만 빠진다 — 상태 조회는 loadJob 이 같은 파일을 엄격하게 읽어 오류를 낸다.
|
|
138
|
+
if (parsed.success)
|
|
139
|
+
jobs.push(parsed.data);
|
|
140
|
+
}
|
|
141
|
+
return jobs;
|
|
142
|
+
}
|
|
143
|
+
/** fal 이 돌려준 큐 URL 만 키와 함께 호출한다. */
|
|
144
|
+
export function assertQueueUrl(value) {
|
|
145
|
+
const url = new URL(value);
|
|
146
|
+
if (url.origin !== QUEUE_ORIGIN)
|
|
147
|
+
throw new Error(M().badQueueUrl(sanitizeExternalText(value, 200)));
|
|
148
|
+
return url;
|
|
149
|
+
}
|
|
150
|
+
/** 결과 파일 호스트 — fal CDN 과 fal 의 GCS 버킷만. */
|
|
151
|
+
export function assertOutputUrl(value) {
|
|
152
|
+
const url = new URL(value);
|
|
153
|
+
const host = url.hostname;
|
|
154
|
+
const allowed = url.protocol === 'https:' && (host === 'fal.media' || host.endsWith('.fal.media') ||
|
|
155
|
+
(host === 'storage.googleapis.com' && url.pathname.startsWith('/falserverless/')));
|
|
156
|
+
if (!allowed)
|
|
157
|
+
throw new Error(M().badOutputUrl(host));
|
|
158
|
+
return url;
|
|
159
|
+
}
|
|
160
|
+
export function planClips(input) {
|
|
161
|
+
if (!FAL_MODEL.test(input.model))
|
|
162
|
+
throw new Error(M().badModel(input.model));
|
|
163
|
+
const project = loadProject(input.projectDir);
|
|
164
|
+
const assets = new Map(loadAssets(input.projectDir).assets.map((asset) => [asset.id, asset]));
|
|
165
|
+
const scenes = new Map(project.scenes.map((scene) => [scene.id, scene]));
|
|
166
|
+
// 실패했어도 결과 URL 이 남은 요청은 이미 돈을 낸 것이다 — 다시 만들면 두 번 과금된다.
|
|
167
|
+
const existing = listJobs(input.projectDir).filter((job) => job.status !== 'failed' || job.outputUrl);
|
|
168
|
+
const clips = input.scenes.map((requested) => {
|
|
169
|
+
const scene = scenes.get(requested.sceneId);
|
|
170
|
+
if (!scene)
|
|
171
|
+
throw new Error(M().unknownScene(requested.sceneId));
|
|
172
|
+
const prompt = (requested.prompt ?? scene.visualPrompt).trim();
|
|
173
|
+
if (!prompt)
|
|
174
|
+
throw new Error(M().noPrompt(requested.sceneId));
|
|
175
|
+
let image;
|
|
176
|
+
if (requested.imageAssetId) {
|
|
177
|
+
const asset = assets.get(requested.imageAssetId);
|
|
178
|
+
if (!asset || asset.kind !== 'image' || !existsSync(asset.path))
|
|
179
|
+
throw new Error(M().badImage(requested.imageAssetId));
|
|
180
|
+
const mime = IMAGE_MIME[path.extname(asset.path).toLowerCase()];
|
|
181
|
+
if (!mime)
|
|
182
|
+
throw new Error(M().imageType(requested.imageAssetId));
|
|
183
|
+
const bytes = statSync(asset.path).size;
|
|
184
|
+
if (bytes > MAX_IMAGE_BYTES)
|
|
185
|
+
throw new Error(M().imageTooLarge(requested.imageAssetId, MAX_IMAGE_BYTES / 1024 / 1024));
|
|
186
|
+
image = { assetId: asset.id, path: asset.path, bytes, sha256: asset.sha256, mime };
|
|
187
|
+
}
|
|
188
|
+
// 정수 초 — fal 영상 모델은 대부분 정수 길이만 받는다. 모델별 형식은 input 으로 덮어쓴다.
|
|
189
|
+
const durationSec = Math.min(60, Math.max(1, Math.round(requested.durationSec ?? scene.durationSec)));
|
|
190
|
+
const promptHash = createHash('sha256').update(prompt).digest('hex');
|
|
191
|
+
const dup = existing.find((job) => job.sceneId === scene.id && job.model === input.model &&
|
|
192
|
+
job.promptHash === promptHash && job.imageSha256 === image?.sha256);
|
|
193
|
+
return {
|
|
194
|
+
sceneId: scene.id,
|
|
195
|
+
prompt,
|
|
196
|
+
promptHash,
|
|
197
|
+
durationSec,
|
|
198
|
+
aspectRatio: project.settings.aspectRatio,
|
|
199
|
+
image,
|
|
200
|
+
duplicateOf: dup ? { jobId: dup.id, status: dup.status } : undefined,
|
|
201
|
+
};
|
|
202
|
+
});
|
|
203
|
+
return { provider: 'fal', model: input.model, clips };
|
|
204
|
+
}
|
|
205
|
+
/** 미리보기 — 네트워크 호출 없음. 업로드되는 로컬 파일과 중복 요청을 드러낸다. */
|
|
206
|
+
export function previewClips(input) {
|
|
207
|
+
const plan = planClips(input);
|
|
208
|
+
return {
|
|
209
|
+
confirmed: false,
|
|
210
|
+
action: 'generate_clip',
|
|
211
|
+
provider: plan.provider,
|
|
212
|
+
model: plan.model,
|
|
213
|
+
estimatedCost: M().costUnknown,
|
|
214
|
+
clips: plan.clips.map((clip) => ({
|
|
215
|
+
sceneId: clip.sceneId,
|
|
216
|
+
prompt: clip.prompt,
|
|
217
|
+
durationSec: clip.durationSec,
|
|
218
|
+
aspectRatio: clip.aspectRatio,
|
|
219
|
+
uploadsLocalFile: clip.image ? { path: clip.image.path, bytes: clip.image.bytes, to: 'fal' } : undefined,
|
|
220
|
+
duplicateOf: clip.duplicateOf,
|
|
221
|
+
})),
|
|
222
|
+
extraInput: input.input,
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
function requestBody(clip, extra) {
|
|
226
|
+
const body = {
|
|
227
|
+
prompt: clip.prompt,
|
|
228
|
+
aspect_ratio: clip.aspectRatio,
|
|
229
|
+
duration: String(clip.durationSec),
|
|
230
|
+
};
|
|
231
|
+
if (clip.image) {
|
|
232
|
+
body.image_url = `data:${clip.image.mime};base64,${readFileSync(clip.image.path).toString('base64')}`;
|
|
233
|
+
}
|
|
234
|
+
return { ...body, ...(extra ?? {}) };
|
|
235
|
+
}
|
|
236
|
+
const queueStatus = z.object({
|
|
237
|
+
status: z.string().optional(),
|
|
238
|
+
request_id: z.string().optional(),
|
|
239
|
+
status_url: z.string().optional(),
|
|
240
|
+
response_url: z.string().optional(),
|
|
241
|
+
error: z.string().nullish(),
|
|
242
|
+
error_type: z.string().nullish(),
|
|
243
|
+
});
|
|
244
|
+
async function readBody(response) {
|
|
245
|
+
const text = await response.text();
|
|
246
|
+
try {
|
|
247
|
+
return { text, json: JSON.parse(text) };
|
|
248
|
+
}
|
|
249
|
+
catch {
|
|
250
|
+
// 오류 응답은 HTML·평문일 수 있다 — 본문 텍스트로 메시지를 만들고 JSON 형식 검사는 호출부가 한다.
|
|
251
|
+
return { text, json: undefined };
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
export async function submitClips(input) {
|
|
255
|
+
const plan = planClips(input);
|
|
256
|
+
const blocked = plan.clips.filter((clip) => clip.duplicateOf);
|
|
257
|
+
if (blocked.length && !input.resubmit) {
|
|
258
|
+
const first = blocked[0];
|
|
259
|
+
throw new Error(M().duplicate(first.sceneId, first.duplicateOf.jobId, first.duplicateOf.status));
|
|
260
|
+
}
|
|
261
|
+
const key = apiKey();
|
|
262
|
+
const modelPath = input.model.split('/').map(encodePathSegment).join('/');
|
|
263
|
+
const submitUrl = `${QUEUE_ORIGIN}/${modelPath}`;
|
|
264
|
+
const results = [];
|
|
265
|
+
for (const clip of plan.clips) {
|
|
266
|
+
const now = new Date().toISOString();
|
|
267
|
+
let job = saveJob(input.projectDir, {
|
|
268
|
+
id: randomUUID(),
|
|
269
|
+
kind: 'clip',
|
|
270
|
+
provider: 'fal',
|
|
271
|
+
model: input.model,
|
|
272
|
+
sceneId: clip.sceneId,
|
|
273
|
+
prompt: clip.prompt,
|
|
274
|
+
promptHash: clip.promptHash,
|
|
275
|
+
imageAssetId: clip.image?.assetId,
|
|
276
|
+
imageSha256: clip.image?.sha256,
|
|
277
|
+
durationSec: clip.durationSec,
|
|
278
|
+
aspectRatio: clip.aspectRatio,
|
|
279
|
+
status: 'pending',
|
|
280
|
+
createdAt: now,
|
|
281
|
+
updatedAt: now,
|
|
282
|
+
});
|
|
283
|
+
let response;
|
|
284
|
+
try {
|
|
285
|
+
response = await fetchWithTimeout(submitUrl, {
|
|
286
|
+
method: 'POST',
|
|
287
|
+
redirect: 'error',
|
|
288
|
+
headers: { Authorization: `Key ${key}`, 'Content-Type': 'application/json', Accept: 'application/json' },
|
|
289
|
+
body: JSON.stringify(requestBody(clip, input.input)),
|
|
290
|
+
});
|
|
291
|
+
}
|
|
292
|
+
catch (error) {
|
|
293
|
+
// 응답 전 실패 — fal 이 받았는지 모른다. pending 으로 남겨 중복 제출을 막고, 남은 장면은 보내지 않는다.
|
|
294
|
+
job = updateJob(input.projectDir, job, { error: `${M().submitUnclear} (${sanitizeExternalText(error.message, 300)})` });
|
|
295
|
+
results.push({ sceneId: clip.sceneId, clipJobId: job.id, status: job.status, error: job.error });
|
|
296
|
+
break;
|
|
297
|
+
}
|
|
298
|
+
const { text, json } = await readBody(response);
|
|
299
|
+
if (!response.ok) {
|
|
300
|
+
const message = M().submitFailed(response.status, sanitizeExternalText(text, 500));
|
|
301
|
+
// 4xx 는 받지 않은 요청이다(과금 없음). 5xx 는 처리 여부를 모르므로 pending 으로 남긴다.
|
|
302
|
+
job = updateJob(input.projectDir, job, response.status < 500
|
|
303
|
+
? { status: 'failed', error: message }
|
|
304
|
+
: { error: `${message} — ${M().submitUnclear}` });
|
|
305
|
+
results.push({ sceneId: clip.sceneId, clipJobId: job.id, status: job.status, error: job.error });
|
|
306
|
+
if (response.status >= 500)
|
|
307
|
+
break;
|
|
308
|
+
continue;
|
|
309
|
+
}
|
|
310
|
+
const parsed = queueStatus.safeParse(json);
|
|
311
|
+
const data = parsed.success ? parsed.data : {};
|
|
312
|
+
let urlProblem;
|
|
313
|
+
try {
|
|
314
|
+
assertQueueUrl(data.status_url ?? '');
|
|
315
|
+
assertQueueUrl(data.response_url ?? '');
|
|
316
|
+
}
|
|
317
|
+
catch (error) {
|
|
318
|
+
urlProblem = data.status_url && data.response_url ? error.message : M().badResponse;
|
|
319
|
+
}
|
|
320
|
+
if (!data.request_id || !data.status_url || !data.response_url || urlProblem) {
|
|
321
|
+
// fal 은 요청을 받았다(200). 요청 id 는 남기고 pending 으로 둔다 — 다시 보내면 두 번 과금된다.
|
|
322
|
+
// 이미 보낸 장면의 결과도 잃지 않게 던지지 않고 돌려준다.
|
|
323
|
+
const requestId = data.request_id?.slice(0, 200);
|
|
324
|
+
job = updateJob(input.projectDir, job, {
|
|
325
|
+
providerRequestId: requestId,
|
|
326
|
+
error: `${urlProblem ?? M().badResponse} ${requestId ? M().acceptedUnusable(requestId) : M().submitUnclear}`,
|
|
327
|
+
});
|
|
328
|
+
results.push({ sceneId: clip.sceneId, clipJobId: job.id, status: job.status, error: job.error });
|
|
329
|
+
break;
|
|
330
|
+
}
|
|
331
|
+
job = updateJob(input.projectDir, job, {
|
|
332
|
+
status: 'submitted',
|
|
333
|
+
providerRequestId: data.request_id,
|
|
334
|
+
statusUrl: data.status_url,
|
|
335
|
+
responseUrl: data.response_url,
|
|
336
|
+
error: undefined,
|
|
337
|
+
});
|
|
338
|
+
results.push({ sceneId: clip.sceneId, clipJobId: job.id, status: job.status });
|
|
339
|
+
}
|
|
340
|
+
return { provider: 'fal', model: input.model, jobs: results, next: 'video_clip_status' };
|
|
341
|
+
}
|
|
342
|
+
// ── status + download ─────────────────────────────────────────────────────
|
|
343
|
+
const falOutput = z.object({
|
|
344
|
+
video: z.object({ url: z.string() }).optional(),
|
|
345
|
+
videos: z.array(z.object({ url: z.string() })).optional(),
|
|
346
|
+
});
|
|
347
|
+
async function fetchOutput(value) {
|
|
348
|
+
let current = assertOutputUrl(value);
|
|
349
|
+
for (let redirects = 0; redirects <= 3; redirects += 1) {
|
|
350
|
+
// 키 없이 받는다 — 결과 파일은 서명된 공개 URL 이다.
|
|
351
|
+
const response = await fetchWithTimeout(current, { redirect: 'manual' }, HTTP_TRANSFER_TIMEOUT_MS);
|
|
352
|
+
if (![301, 302, 303, 307, 308].includes(response.status))
|
|
353
|
+
return response;
|
|
354
|
+
const location = response.headers.get('location');
|
|
355
|
+
if (!location)
|
|
356
|
+
throw new Error(M().noLocation);
|
|
357
|
+
await response.body?.cancel();
|
|
358
|
+
current = assertOutputUrl(new URL(location, current).toString());
|
|
359
|
+
}
|
|
360
|
+
throw new Error(M().tooManyRedirects);
|
|
361
|
+
}
|
|
362
|
+
async function downloadClip(projectDir, job) {
|
|
363
|
+
const response = await fetchOutput(job.outputUrl);
|
|
364
|
+
if (!response.ok)
|
|
365
|
+
throw new Error(M().downloadFailed(response.status));
|
|
366
|
+
const assetId = `fal-${job.id}`;
|
|
367
|
+
const destination = path.join(path.resolve(projectDir), 'assets', 'generated', `${assetId}.mp4`);
|
|
368
|
+
mkdirSync(path.dirname(destination), { recursive: true });
|
|
369
|
+
await downloadLimited(response, destination, MAX_CLIP_BYTES);
|
|
370
|
+
if (!hasMp4Signature(destination)) {
|
|
371
|
+
unlinkSync(destination);
|
|
372
|
+
throw new Error(M().notMp4);
|
|
373
|
+
}
|
|
374
|
+
// 자산 id 를 요청 id 에서 만든다 — 상태 조회가 겹쳐도 같은 자산을 덮어쓸 뿐 둘이 되지 않는다.
|
|
375
|
+
return registerAsset(projectDir, {
|
|
376
|
+
id: assetId,
|
|
377
|
+
kind: 'video',
|
|
378
|
+
sourceType: 'generated',
|
|
379
|
+
path: destination,
|
|
380
|
+
license: M().license(job.model),
|
|
381
|
+
allowedForRendering: true,
|
|
382
|
+
provider: `fal:${job.model}`,
|
|
383
|
+
prompt: job.prompt,
|
|
384
|
+
});
|
|
385
|
+
}
|
|
386
|
+
function assetById(projectDir, id) {
|
|
387
|
+
return id ? loadAssets(projectDir).assets.find((asset) => asset.id === id) : undefined;
|
|
388
|
+
}
|
|
389
|
+
export async function getClipStatus(projectDir, clipJobId) {
|
|
390
|
+
let job = loadJob(projectDir, clipJobId);
|
|
391
|
+
if (job.status === 'succeeded')
|
|
392
|
+
return { ...job, asset: assetById(projectDir, job.assetId) };
|
|
393
|
+
if (job.status === 'failed')
|
|
394
|
+
return job;
|
|
395
|
+
if (job.status === 'pending') {
|
|
396
|
+
return { ...job, hint: job.providerRequestId ? M().acceptedUnusable(job.providerRequestId) : M().pending };
|
|
397
|
+
}
|
|
398
|
+
if (!job.outputUrl) {
|
|
399
|
+
const key = apiKey();
|
|
400
|
+
const auth = { Authorization: `Key ${key}`, Accept: 'application/json' };
|
|
401
|
+
const statusResponse = await fetchWithTimeout(assertQueueUrl(job.statusUrl), { redirect: 'error', headers: auth });
|
|
402
|
+
const status = await readBody(statusResponse);
|
|
403
|
+
if (statusResponse.status === 404)
|
|
404
|
+
return updateJob(projectDir, job, { status: 'failed', error: M().notFound });
|
|
405
|
+
if (statusResponse.status === 202)
|
|
406
|
+
return updateJob(projectDir, job, { status: 'running' });
|
|
407
|
+
if (!statusResponse.ok)
|
|
408
|
+
throw new Error(M().submitFailed(statusResponse.status, sanitizeExternalText(status.text, 500)));
|
|
409
|
+
const parsed = queueStatus.safeParse(status.json);
|
|
410
|
+
if (!parsed.success)
|
|
411
|
+
throw new Error(M().badResponse);
|
|
412
|
+
if (parsed.data.status !== 'COMPLETED')
|
|
413
|
+
return updateJob(projectDir, job, { status: 'running' });
|
|
414
|
+
// fal 은 실패·취소도 COMPLETED 로 표시하고 error 를 붙인다.
|
|
415
|
+
if (parsed.data.error) {
|
|
416
|
+
return updateJob(projectDir, job, {
|
|
417
|
+
status: 'failed',
|
|
418
|
+
error: sanitizeExternalText(`${parsed.data.error_type ?? 'error'}: ${parsed.data.error}`, 2_000),
|
|
419
|
+
});
|
|
420
|
+
}
|
|
421
|
+
const resultResponse = await fetchWithTimeout(assertQueueUrl(job.responseUrl), { redirect: 'error', headers: auth });
|
|
422
|
+
const result = await readBody(resultResponse);
|
|
423
|
+
if (!resultResponse.ok) {
|
|
424
|
+
if (resultResponse.status === 400)
|
|
425
|
+
return updateJob(projectDir, job, { status: 'running' });
|
|
426
|
+
return updateJob(projectDir, job, {
|
|
427
|
+
status: 'failed',
|
|
428
|
+
error: M().submitFailed(resultResponse.status, sanitizeExternalText(result.text, 2_000)),
|
|
429
|
+
});
|
|
430
|
+
}
|
|
431
|
+
const output = falOutput.safeParse(result.json);
|
|
432
|
+
const url = output.success ? (output.data.video?.url ?? output.data.videos?.[0]?.url) : undefined;
|
|
433
|
+
if (!url) {
|
|
434
|
+
// 결과 원문을 남긴다 — fal 은 결과를 몇 분만 보관하므로, 모양이 달라도 사람이 파일을 찾을 수 있게.
|
|
435
|
+
return updateJob(projectDir, job, {
|
|
436
|
+
status: 'failed',
|
|
437
|
+
error: `${M().noVideo} ${sanitizeExternalText(result.text, 2_000)}`,
|
|
438
|
+
});
|
|
439
|
+
}
|
|
440
|
+
// 결과는 fal 에 몇 분만 남는다 — 검사·다운로드보다 URL 저장이 먼저다. 호스트가 허용 목록 밖이어도
|
|
441
|
+
// 이미 돈을 낸 결과이므로 URL 을 남겨 사람이 직접 받을 수 있게 한다.
|
|
442
|
+
const parsedUrl = z.string().url().safeParse(url);
|
|
443
|
+
if (!parsedUrl.success)
|
|
444
|
+
return updateJob(projectDir, job, { status: 'failed', error: `${M().noVideo} ${sanitizeExternalText(url, 500)}` });
|
|
445
|
+
job = updateJob(projectDir, job, { outputUrl: url });
|
|
446
|
+
try {
|
|
447
|
+
assertOutputUrl(url);
|
|
448
|
+
}
|
|
449
|
+
catch (error) {
|
|
450
|
+
return updateJob(projectDir, job, { status: 'failed', error: `${error.message} — ${M().manualDownload(url)}` });
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
const asset = await downloadClip(projectDir, job);
|
|
454
|
+
job = updateJob(projectDir, job, { status: 'succeeded', assetId: asset.id, error: undefined });
|
|
455
|
+
return { ...job, asset };
|
|
456
|
+
}
|
|
457
|
+
export const __testing = { requestBody, listJobs, clipJobPath };
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import type { VideoAsset } from './types.js';
|
|
2
|
+
export declare const DEFAULT_TTS_MODEL = "eleven_multilingual_v2";
|
|
3
|
+
export declare const VOICE_ID: RegExp;
|
|
4
|
+
export declare const TTS_MODEL_ID: RegExp;
|
|
5
|
+
export interface ListVoicesInput {
|
|
6
|
+
search?: string;
|
|
7
|
+
pageSize?: number;
|
|
8
|
+
nextPageToken?: string;
|
|
9
|
+
}
|
|
10
|
+
export declare function listVoices(input: ListVoicesInput): Promise<{
|
|
11
|
+
voices: {
|
|
12
|
+
voiceId: string;
|
|
13
|
+
name: string;
|
|
14
|
+
category: string | undefined;
|
|
15
|
+
labels: {
|
|
16
|
+
[k: string]: string;
|
|
17
|
+
};
|
|
18
|
+
description: string | undefined;
|
|
19
|
+
previewUrl: string | undefined;
|
|
20
|
+
}[];
|
|
21
|
+
hasMore: boolean;
|
|
22
|
+
nextPageToken: string | undefined;
|
|
23
|
+
untrustedExternalText: boolean;
|
|
24
|
+
}>;
|
|
25
|
+
export interface NarrationInput {
|
|
26
|
+
projectDir: string;
|
|
27
|
+
voiceId: string;
|
|
28
|
+
modelId?: string;
|
|
29
|
+
}
|
|
30
|
+
export interface NarrationSegmentPlan {
|
|
31
|
+
sceneId: string;
|
|
32
|
+
sceneSec: number;
|
|
33
|
+
text: string;
|
|
34
|
+
characters: number;
|
|
35
|
+
cached: boolean;
|
|
36
|
+
audioPath: string;
|
|
37
|
+
metaPath: string;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* 네트워크 없이 계획만 세운다 — 미리보기와 실행이 같은 장면 선택·캐시 판단을 쓰게.
|
|
41
|
+
* 과금 근거는 캐시되지 않은 장면의 글자 수다 (ElevenLabs 는 글자 수로 과금한다).
|
|
42
|
+
*/
|
|
43
|
+
export declare function planNarration(input: NarrationInput): {
|
|
44
|
+
voiceId: string;
|
|
45
|
+
modelId: string;
|
|
46
|
+
segments: NarrationSegmentPlan[];
|
|
47
|
+
billableCharacters: number;
|
|
48
|
+
cachedScenes: number;
|
|
49
|
+
};
|
|
50
|
+
/** MP3 = ID3 태그 또는 MPEG 프레임 동기 (0xFFE). */
|
|
51
|
+
export declare function hasMp3Signature(bytes: Buffer): boolean;
|
|
52
|
+
/** 응답에서 음성 길이(마지막 글자의 끝 시각)를 뽑는다. */
|
|
53
|
+
export declare function speechSecondsFrom(body: unknown): {
|
|
54
|
+
bytes: Buffer;
|
|
55
|
+
speechSec: number;
|
|
56
|
+
};
|
|
57
|
+
/**
|
|
58
|
+
* 장면별 음성을 장면 길이만큼 무음으로 채워 이어 붙이는 FFmpeg 인자.
|
|
59
|
+
* 내레이션이 없는 장면은 anullsrc 무음으로 자리를 채운다.
|
|
60
|
+
*/
|
|
61
|
+
export declare function buildNarrationMixArgs(scenes: Array<{
|
|
62
|
+
sceneSec: number;
|
|
63
|
+
audioPath?: string;
|
|
64
|
+
}>, outputPath: string): string[];
|
|
65
|
+
export declare function generateNarration(input: NarrationInput): Promise<{
|
|
66
|
+
registered: false;
|
|
67
|
+
overruns: {
|
|
68
|
+
sceneId: string;
|
|
69
|
+
speechSec: number;
|
|
70
|
+
sceneSec: number;
|
|
71
|
+
cached: boolean;
|
|
72
|
+
}[];
|
|
73
|
+
segments: {
|
|
74
|
+
sceneId: string;
|
|
75
|
+
speechSec: number;
|
|
76
|
+
sceneSec: number;
|
|
77
|
+
cached: boolean;
|
|
78
|
+
}[];
|
|
79
|
+
asset?: undefined;
|
|
80
|
+
totalDurationSec?: undefined;
|
|
81
|
+
next?: undefined;
|
|
82
|
+
} | {
|
|
83
|
+
registered: true;
|
|
84
|
+
asset: VideoAsset;
|
|
85
|
+
totalDurationSec: number;
|
|
86
|
+
segments: {
|
|
87
|
+
sceneId: string;
|
|
88
|
+
speechSec: number;
|
|
89
|
+
sceneSec: number;
|
|
90
|
+
cached: boolean;
|
|
91
|
+
}[];
|
|
92
|
+
next: string;
|
|
93
|
+
overruns?: undefined;
|
|
94
|
+
}>;
|