#!/usr/bin/env node /** * insert-drama.js — 独立脚本:将 classic 类型剧本数据插入数据库 + 生成 bundle.json 上传 OSS * * 用法: * node insert-drama.js * 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 或 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); });