insert-drama.js
24.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
#!/usr/bin/env node
/**
* insert-drama.js — 独立脚本:将 classic 类型剧本数据插入数据库 + 生成 bundle.json 上传 OSS
*
* 用法:
* node insert-drama.js <json文件路径>
* echo '{"name":...}' | node insert-drama.js --stdin
*
* JSON 格式:
* {
* "name": "剧本名称",
* "title": "显示标题(可带 emoji)",
* "subtitle": "副标题",
* "description": "剧本简介",
* "systemPrompt": "用于 AI 续写的系统提示词",
* "isPublic": true,
* "userId": 1,
* "language": "zh",
* "tags": "搞笑,职场",
* "characters": [
* {
* "name": "角色名",
* "gender": "male",
* "voiceId": "zh_male_m191_uranus_bigtts",
* "voiceIdEn": "en_male_tim_uranus_bigtts"
* }
* ],
* "script": [
* {
* "character": "角色名",
* "dialogue": "台词",
* "avatar": "happy.png",
* "instruction": "用开心的语气说",
* "action": "none",
* "position": "left"
* }
* ]
* }
*/
const path = require('path');
const fs = require('fs');
// 加载 .env 文件(优先级:--env 参数 > 环境变量 DRAMA_ENV_PATH > 脚本同目录 .env)
function loadEnv() {
const envArgIdx = process.argv.indexOf('--env');
const candidates = [
envArgIdx !== -1 ? path.resolve(process.argv[envArgIdx + 1]) : null,
process.env.DRAMA_ENV_PATH ? path.resolve(process.env.DRAMA_ENV_PATH) : null,
path.resolve(__dirname, '.env'),
].filter(Boolean);
for (const envPath of candidates) {
if (fs.existsSync(envPath)) {
const envContent = fs.readFileSync(envPath, 'utf-8');
for (const line of envContent.split('\n')) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith('#')) continue;
const eqIdx = trimmed.indexOf('=');
if (eqIdx === -1) continue;
const key = trimmed.slice(0, eqIdx).trim();
const val = trimmed.slice(eqIdx + 1).trim();
if (!process.env[key]) process.env[key] = val;
}
console.log(`已加载配置: ${envPath}`);
return;
}
}
console.log('未找到 .env 文件,使用环境变量或默认值');
}
loadEnv();
const { Sequelize, DataTypes } = require('sequelize');
// ---------- DB 连接 ----------
const sequelize = new Sequelize(
process.env.DB_NAME || 'shadiao_drama',
process.env.DB_USER || 'root',
process.env.DB_PASSWORD || '',
{
host: process.env.DB_HOST || '127.0.0.1',
port: parseInt(process.env.DB_PORT || '3306', 10),
dialect: 'mysql',
logging: false,
timezone: '+08:00',
define: { charset: 'utf8mb4', collate: 'utf8mb4_unicode_ci' },
}
);
// ---------- Model 定义(与项目 schema 对齐) ----------
const Drama = sequelize.define('Drama', {
id: { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true },
dramaKey: { type: DataTypes.STRING(50), allowNull: false, unique: true, field: 'drama_key' },
name: { type: DataTypes.STRING(100), allowNull: false },
title: { type: DataTypes.STRING(100), allowNull: true },
subtitle: { type: DataTypes.STRING(200), allowNull: true },
description: { type: DataTypes.TEXT, allowNull: true },
nameEn: { type: DataTypes.STRING(100), field: 'name_en', allowNull: true },
titleEn: { type: DataTypes.STRING(100), field: 'title_en', allowNull: true },
subtitleEn: { type: DataTypes.STRING(200), field: 'subtitle_en', allowNull: true },
descriptionEn: { type: DataTypes.TEXT, field: 'description_en', allowNull: true },
i18nData: { type: DataTypes.JSON, allowNull: true, field: 'i18n_data' },
coverUrl: { type: DataTypes.STRING(500), allowNull: true, field: 'cover_url' },
backgroundUrl: { type: DataTypes.STRING(500), allowNull: true, field: 'background_url' },
bgmUrl: { type: DataTypes.STRING(500), allowNull: true, field: 'bgm_url' },
originalIdea: { type: DataTypes.TEXT, allowNull: true, field: 'original_idea' },
originalStyle: { type: DataTypes.STRING(200), allowNull: true, field: 'original_style' },
systemPrompt: { type: DataTypes.TEXT, allowNull: true, field: 'system_prompt' },
status: { type: DataTypes.TINYINT, defaultValue: 1 },
userId: { type: DataTypes.INTEGER, allowNull: true, field: 'user_id' },
isPublic: { type: DataTypes.BOOLEAN, defaultValue: true, field: 'is_public' },
type: { type: DataTypes.STRING(30), defaultValue: 'classic' },
emojiPack: { type: DataTypes.STRING(50), defaultValue: 'default', field: 'emoji_pack' },
vrmConfig: { type: DataTypes.TEXT, allowNull: true, field: 'vrm_config' },
tags: { type: DataTypes.STRING(255), allowNull: true },
score: { type: DataTypes.DECIMAL(10, 2), defaultValue: 0 },
language: { type: DataTypes.STRING(10), defaultValue: 'en' },
rootEpisodeId: { type: DataTypes.INTEGER, allowNull: true, field: 'root_episode_id' },
}, { tableName: 'dramas', timestamps: true, underscored: true });
const DramaCharacter = sequelize.define('DramaCharacter', {
id: { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true },
dramaId: { type: DataTypes.INTEGER, allowNull: false, field: 'drama_id' },
characterName: { type: DataTypes.STRING(50), allowNull: false, field: 'character_name' },
characterNameEn: { type: DataTypes.STRING(50), field: 'character_name_en', allowNull: true },
i18nData: { type: DataTypes.JSON, allowNull: true, field: 'i18n_data' },
bodyUrl: { type: DataTypes.STRING(500), allowNull: true, field: 'body_url' },
faceOffsetTop: { type: DataTypes.STRING(20), allowNull: true, field: 'face_offset_top' },
faceOffsetLeft: { type: DataTypes.STRING(20), allowNull: true, field: 'face_offset_left' },
faceOffsetWidth: { type: DataTypes.STRING(20), allowNull: true, field: 'face_offset_width' },
voiceId: { type: DataTypes.STRING(100), allowNull: true, field: 'voice_id' },
voiceIdEn: { type: DataTypes.STRING(100), allowNull: true, field: 'voice_id_en' },
isDefault: { type: DataTypes.TINYINT, defaultValue: 0, field: 'is_default' },
emojiPackId: { type: DataTypes.INTEGER, allowNull: true, field: 'emoji_pack_id' },
usageCount: { type: DataTypes.INTEGER, defaultValue: 0, field: 'usage_count' },
avatarGenerated: { type: DataTypes.TINYINT, defaultValue: 0, field: 'avatar_generated' },
}, { tableName: 'drama_characters', timestamps: false, underscored: true });
const DramaEmotion = sequelize.define('DramaEmotion', {
id: { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true },
dramaId: { type: DataTypes.INTEGER, allowNull: false, field: 'drama_id' },
avatarKey: { type: DataTypes.STRING(50), allowNull: false, field: 'avatar_key' },
faceUrl: { type: DataTypes.STRING(500), allowNull: true, field: 'face_url' },
emotionName: { type: DataTypes.STRING(30), allowNull: true, field: 'emotion_name' },
emotionScale: { type: DataTypes.INTEGER, defaultValue: 3, field: 'emotion_scale' },
isDefault: { type: DataTypes.TINYINT, defaultValue: 0, field: 'is_default' },
characterName: { type: DataTypes.STRING(50), allowNull: true, field: 'character_name' },
}, { tableName: 'drama_emotions', timestamps: false, underscored: true });
const DramaScript = sequelize.define('DramaScript', {
id: { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true },
dramaId: { type: DataTypes.INTEGER, allowNull: false, field: 'drama_id' },
seq: { type: DataTypes.INTEGER, allowNull: false },
characterName: { type: DataTypes.STRING(50), allowNull: false, field: 'character_name' },
avatar: { type: DataTypes.STRING(50), allowNull: true },
dialogue: { type: DataTypes.TEXT, allowNull: false },
action: { type: DataTypes.STRING(30), allowNull: true },
position: { type: DataTypes.STRING(10), allowNull: true },
sfx: { type: DataTypes.STRING(100), allowNull: true },
instruction: { type: DataTypes.STRING(255), allowNull: true },
audio: { type: DataTypes.STRING(500), allowNull: true },
i18nData: { type: DataTypes.JSON, allowNull: true, field: 'i18n_data' },
}, { tableName: 'drama_scripts', timestamps: false, underscored: true });
// ---------- 默认表情配置 ----------
const DEFAULT_EMOJI_BASE = 'https://shadiao-drama.oss-cn-beijing.aliyuncs.com/dramas/zhenhuan_chuan/emojis';
const DEFAULT_EMOJIS = [
{ key: 'normal.png', name: '正常', emotion: 'neutral', scale: 3 },
{ key: 'happy.png', name: '开心', emotion: 'happy', scale: 4 },
{ key: 'very_happy.png', name: '非常开心', emotion: 'happy', scale: 5 },
{ key: 'angry.png', name: '生气', emotion: 'angry', scale: 4 },
{ key: 'sad.png', name: '伤心', emotion: 'sad', scale: 4 },
{ key: 'cry.png', name: '哭', emotion: 'sad', scale: 5 },
{ key: 'shock.png', name: '惊讶', emotion: 'surprised', scale: 5 },
{ key: 'smirk.png', name: '撇嘴', emotion: 'happy', scale: 3 },
{ key: 'speechless.png', name: '无语', emotion: 'neutral', scale: 2 },
];
// ---------- 音色情绪兼容映射 ----------
const COMMON_EMOTIONS = ['happy', 'sad', 'angry', 'surprised', 'fear', 'hate', 'excited', 'coldness', 'neutral'];
function validateEmotion(speaker, emotion) {
if (!emotion || emotion === 'neutral') return emotion;
return COMMON_EMOTIONS.includes(emotion) ? emotion : 'neutral';
}
// ---------- 构建默认表情记录 ----------
function buildEmotionRecords(dramaId, characters, defaultVoice) {
const records = [];
// 共享默认表情(characterName=null,作为 fallback)
for (const emo of DEFAULT_EMOJIS) {
const validEmotion = validateEmotion(defaultVoice, emo.emotion) || 'neutral';
records.push({
dramaId,
avatarKey: emo.key,
faceUrl: `${DEFAULT_EMOJI_BASE}/${encodeURIComponent(emo.name)}.png`,
emotionName: validEmotion,
emotionScale: emo.scale,
isDefault: 0,
characterName: null,
});
}
records.push({
dramaId,
avatarKey: '_default',
faceUrl: `${DEFAULT_EMOJI_BASE}/${encodeURIComponent('正常')}.png`,
emotionName: 'neutral',
emotionScale: 3,
isDefault: 1,
characterName: null,
});
return records;
}
// ---------- 多语言支持 ----------
const SUPPORTED_LOCALES = ['en', 'ja', 'es', 'pt', 'id', 'zh'];
/**
* 构建完整 i18nData:合并基础语言 + Claude 生成的翻译
* 格式与 server/services/i18n-worker.js 保持一致
*/
function buildI18nData(data, baseLang, insertedChars, insertedScripts) {
const i18nData = {};
// 剧本级翻译
const dramaFields = {
name: data.name,
title: data.title || data.name,
subtitle: data.subtitle || '',
desc: data.description || '',
sysPrompt: data.systemPrompt || '',
};
const i18nInput = data.i18n || {};
for (const [key, baseValue] of Object.entries(dramaFields)) {
const translations = { [baseLang]: baseValue };
if (i18nInput[key]) {
for (const [lang, val] of Object.entries(i18nInput[key])) {
if (val && String(val).trim()) translations[lang] = val;
}
}
i18nData[key] = translations;
}
// 角色名翻译: char_${dbId}_name
const characters = data.characters || [];
for (let i = 0; i < characters.length; i++) {
const char = characters[i];
const dbRecord = insertedChars[i]; // 按顺序对应(_default 在最后)
if (!dbRecord || dbRecord.isDefault) continue;
const charId = dbRecord.id;
const translations = { [baseLang]: char.name };
if (char.nameI18n) {
for (const [lang, val] of Object.entries(char.nameI18n)) {
if (val && String(val).trim()) translations[lang] = val;
}
}
i18nData[`char_${charId}_name`] = translations;
}
// 台词翻译: script_${dbId}_dia
const scriptLines = data.script || [];
for (let i = 0; i < scriptLines.length; i++) {
const line = scriptLines[i];
const dbRecord = insertedScripts[i];
if (!dbRecord) continue;
const scriptId = dbRecord.id;
const translations = { [baseLang]: line.dialogue };
if (line.dialogueI18n) {
for (const [lang, val] of Object.entries(line.dialogueI18n)) {
if (val && String(val).trim()) translations[lang] = val;
}
}
i18nData[`script_${scriptId}_dia`] = translations;
}
return i18nData;
}
// ---------- 构建 bundle.json(与 drama-bundler.js 逻辑对齐,支持多语言) ----------
function buildBundle(drama, charRecords, emotionRecords, scriptRecords) {
const i18n = drama.i18nData || {};
// 对齐 server/services/drama-bundler.js extractTranslations 逻辑
const extractTranslations = (fieldKey, baseEnValue, baseRootValue) => {
const transMap = {};
if (baseEnValue) transMap['en'] = baseEnValue;
if (baseRootValue) transMap['zh'] = baseRootValue;
// i18nData 中的翻译覆盖
if (i18n[fieldKey]) {
for (const [lang, val] of Object.entries(i18n[fieldKey])) {
if (val && String(val).trim().length > 0) {
transMap[lang] = val;
}
}
}
return transMap;
};
const bundle = {
meta: {
id: drama.dramaKey,
dbId: drama.id,
status: drama.status,
type: 'classic',
createdAt: drama.createdAt,
},
metadata: {
title: extractTranslations('title', null, drama.title),
subtitle: extractTranslations('subtitle', null, drama.subtitle),
description: extractTranslations('desc', null, drama.description),
tags: drama.tags ? { [drama.language || 'zh']: drama.tags.split(',') } : {},
cover_url: drama.coverUrl,
background_url: drama.backgroundUrl,
},
config: {
system_prompt: extractTranslations('sysPrompt', null, drama.systemPrompt),
default_bgm: drama.bgmUrl || null,
vrm_config: null,
},
characters: {},
scripts: [],
};
// 全局表情(characterName=null)
const globalEmotions = emotionRecords.filter(e => !e.characterName);
if (globalEmotions.length > 0) {
bundle.config.global_faces = {};
for (const e of globalEmotions) {
bundle.config.global_faces[e.avatarKey] = {
face_url: e.faceUrl,
emotion: e.emotionName,
scale: e.emotionScale,
};
}
}
// 角色
for (const char of charRecords) {
const charKey = char.isDefault ? '_default' : char.characterName;
const cid = char.id;
const faces = {};
const charEmotions = emotionRecords.filter(
e => e.characterName === charKey || e.characterName === char.characterName
);
for (const e of charEmotions) {
faces[e.avatarKey] = {
face_url: e.faceUrl,
emotion: e.emotionName,
scale: e.emotionScale,
};
}
// 复刻音色 S_* 全语言共用同一 voiceId
const voiceId = char.voiceId || null;
let voiceIdMap = null;
if (voiceId) {
if (voiceId.startsWith('S_')) {
// 复刻音色:所有语言共用
voiceIdMap = {};
for (const lang of SUPPORTED_LOCALES) {
voiceIdMap[lang] = voiceId;
}
} else {
// 传统音色:zh + en 分开
voiceIdMap = { zh: voiceId };
if (char.voiceIdEn) voiceIdMap['en'] = char.voiceIdEn;
}
}
bundle.characters[charKey] = {
id: cid,
name: char.isDefault ? null : extractTranslations(`char_${cid}_name`, null, char.characterName),
voice_id: voiceIdMap,
body_url: char.bodyUrl,
face_offset: {
top: char.faceOffsetTop,
left: char.faceOffsetLeft,
width: char.faceOffsetWidth,
},
faces,
};
}
// 台词
for (const sc of scriptRecords) {
const sid = sc.id;
bundle.scripts.push({
id: sid,
seq: sc.seq,
character: sc.characterName,
avatar: sc.avatar,
dialogue: extractTranslations(`script_${sid}_dia`, null, sc.dialogue),
audio_url: {},
action: sc.action,
position: sc.position,
sfx: sc.sfx,
instruction: sc.instruction,
});
}
return bundle;
}
// ---------- OSS 上传 ----------
function getOSSClient() {
const OSS = require('ali-oss');
return new OSS({
region: process.env.OSS_REGION,
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
bucket: process.env.OSS_BUCKET,
});
}
function getPublicUrl(key) {
const endpoint = process.env.OSS_ENDPOINT || `https://${process.env.OSS_REGION}.aliyuncs.com`;
const bucket = process.env.OSS_BUCKET;
return `https://${bucket}.${endpoint.replace('https://', '')}/${key}`;
}
async function uploadBundleToOSS(dramaKey, bundleData) {
const ossOk = process.env.OSS_REGION && process.env.OSS_ACCESS_KEY_ID
&& process.env.OSS_ACCESS_KEY_SECRET && process.env.OSS_BUCKET;
if (!ossOk) {
console.log('[Bundle] OSS 未配置,跳过上传');
return null;
}
const client = getOSSClient();
const buffer = Buffer.from(JSON.stringify(bundleData, null, 2), 'utf-8');
const ossKey = `dramas/${dramaKey}/bundle.json`;
const result = await client.put(ossKey, buffer, {
headers: { 'Content-Type': 'application/json' },
});
return getPublicUrl(result.name);
}
// ---------- 主逻辑 ----------
async function main() {
let jsonStr;
if (process.argv.includes('--stdin')) {
jsonStr = '';
for await (const chunk of process.stdin) {
jsonStr += chunk;
}
} else if (process.argv[2]) {
const filePath = path.resolve(process.argv[2]);
if (!fs.existsSync(filePath)) {
console.error(`文件不存在: ${filePath}`);
process.exit(1);
}
jsonStr = fs.readFileSync(filePath, 'utf-8');
} else {
console.error('用法: node insert-drama.js <json文件> 或 node insert-drama.js --stdin');
process.exit(1);
}
let data;
try {
data = JSON.parse(jsonStr);
} catch (e) {
console.error('JSON 解析失败:', e.message);
process.exit(1);
}
const { name, title, subtitle, description, systemPrompt, isPublic, userId, characters, script, tags, language } = data;
if (!name || !script || !Array.isArray(script) || script.length === 0) {
console.error('缺少必要字段: name, script');
process.exit(1);
}
if (!characters || !Array.isArray(characters) || characters.length === 0) {
console.error('缺少必要字段: characters');
process.exit(1);
}
await sequelize.authenticate();
console.log('数据库连接成功');
const t = await sequelize.transaction();
let drama;
let insertedChars;
let insertedEmotions;
let insertedScripts;
try {
const dramaKey = `user_${userId || 1}_${Date.now().toString(36)}`;
// 1. 创建 Drama 记录
drama = await Drama.create({
dramaKey,
name,
title: title || name,
subtitle: subtitle || '',
description: description || '',
coverUrl: data.coverUrl || '',
backgroundUrl: data.backgroundUrl || '',
bgmUrl: data.bgmUrl || '',
systemPrompt: systemPrompt || '',
status: 1,
userId: userId || null,
isPublic: isPublic !== false,
type: 'classic',
emojiPack: 'default',
tags: tags || null,
language: language || 'zh',
}, { transaction: t });
// 2. 创建角色记录
const charRecords = characters.map(char => ({
dramaId: drama.id,
characterName: char.name,
bodyUrl: char.bodyUrl || '',
faceOffsetTop: char.faceOffset?.top || '8%',
faceOffsetLeft: char.faceOffset?.left || '35%',
faceOffsetWidth: char.faceOffset?.width || '30%',
voiceId: char.voiceId || '',
voiceIdEn: char.voiceIdEn || '',
isDefault: char.isDefault ? 1 : 0,
emojiPackId: null,
usageCount: 0,
avatarGenerated: 0,
}));
// 添加 _default 角色(复用第一个角色的配置)
const firstChar = characters[0];
charRecords.push({
dramaId: drama.id,
characterName: '_default',
bodyUrl: firstChar.bodyUrl || '',
faceOffsetTop: firstChar.faceOffset?.top || '8%',
faceOffsetLeft: firstChar.faceOffset?.left || '35%',
faceOffsetWidth: firstChar.faceOffset?.width || '30%',
voiceId: firstChar.voiceId || '',
voiceIdEn: firstChar.voiceIdEn || '',
isDefault: 1,
emojiPackId: null,
usageCount: 0,
avatarGenerated: 0,
});
insertedChars = await DramaCharacter.bulkCreate(charRecords, { transaction: t });
// 3. 创建表情记录
const defaultVoice = characters[0]?.voiceId || '';
const emotionRecordData = buildEmotionRecords(drama.id, characters, defaultVoice);
insertedEmotions = await DramaEmotion.bulkCreate(emotionRecordData, { transaction: t });
// 4. 创建台词记录
const scriptRecords = script.map((line, i) => ({
dramaId: drama.id,
seq: i,
characterName: line.character,
avatar: line.avatar || 'normal.png',
dialogue: line.dialogue,
action: line.action || 'none',
position: line.position || 'left',
sfx: line.sfx || null,
instruction: line.instruction || null,
audio: null,
}));
insertedScripts = await DramaScript.bulkCreate(scriptRecords, { transaction: t });
await t.commit();
console.log(`\n剧本创建成功!`);
console.log(` ID: ${drama.id}`);
console.log(` Key: ${drama.dramaKey}`);
console.log(` 名称: ${name}`);
console.log(` 角色数: ${characters.length}`);
console.log(` 台词数: ${script.length}`);
// 5. 构建 i18nData 并更新 Drama 记录
const baseLang = language || 'zh';
const i18nData = buildI18nData(data, baseLang, insertedChars, insertedScripts);
await Drama.update({ i18nData }, { where: { id: drama.id } });
drama.i18nData = i18nData;
const i18nLangs = new Set();
for (const translations of Object.values(i18nData)) {
for (const lang of Object.keys(translations)) i18nLangs.add(lang);
}
console.log(` 多语言: ${[...i18nLangs].join(', ')}`);
// 6. 生成并上传 bundle.json(含多语言)
console.log(`\n正在生成 bundle.json...`);
try {
const dramaData = { ...drama.dataValues, i18nData };
const bundleData = buildBundle(
dramaData,
insertedChars.map(c => c.dataValues),
insertedEmotions.map(e => e.dataValues),
insertedScripts.map(s => s.dataValues),
);
const bundleUrl = await uploadBundleToOSS(drama.dramaKey, bundleData);
if (bundleUrl) {
console.log(` Bundle 上传成功: ${bundleUrl}`);
} else {
// 未配置 OSS 时写到本地
const localPath = `/tmp/bundle_${drama.dramaKey}.json`;
fs.writeFileSync(localPath, JSON.stringify(bundleData, null, 2), 'utf-8');
console.log(` Bundle 已写入本地: ${localPath}`);
}
} catch (bundleErr) {
console.error(` Bundle 生成/上传失败(不影响剧本数据): ${bundleErr.message}`);
}
// 输出 JSON 结果供调用方解析
console.log(`\n__RESULT__${JSON.stringify({ id: drama.id, dramaKey: drama.dramaKey, name })}__END__`);
} catch (err) {
await t.rollback();
console.error('插入失败:', err.message);
process.exit(1);
} finally {
await sequelize.close();
}
}
main().catch(err => {
console.error('执行失败:', err);
process.exit(1);
});