Translate
工作流概述
这是一个包含15个节点的复杂工作流,主要用于自动化处理各种任务。
工作流源代码
{
"id": "vssVsRO0FW6InbaY",
"meta": {
"instanceId": "12aa4b47b8cf3d835676e10b2bf760a80a1ff52932c9898603f7b21fc5376f59",
"templateCredsSetupCompleted": true
},
"name": "Translate",
"tags": [],
"nodes": [
{
"id": "7e55613e-c304-47cb-a017-2d912014ea8e",
"name": "Split Out",
"type": "n8n-nodes-base.splitOut",
"position": [
1180,
140
],
"parameters": {
"options": {},
"fieldToSplitOut": "txt"
},
"typeVersion": 1
},
{
"id": "1ab3e545-e7a1-4b3d-a190-d38cb55ebf96",
"name": "Google Translate",
"type": "n8n-nodes-base.googleTranslate",
"position": [
1620,
140
],
"parameters": {
"text": "={{ JSON.stringify($json.parts.secondPart) }}",
"translateTo": "={{ $json.language }}"
},
"credentials": {
"googleTranslateOAuth2Api": {
"id": "ssWzCSWk0cvCXZtz",
"name": "Google Translate account"
}
},
"typeVersion": 2
},
{
"id": "07de7be3-5477-4e6c-b709-f632a3d5f162",
"name": "Aggregate",
"type": "n8n-nodes-base.aggregate",
"position": [
520,
340
],
"parameters": {
"options": {},
"aggregate": "aggregateAllItemData"
},
"typeVersion": 1
},
{
"id": "cbe5892e-3661-42fb-a850-1e0448a53e0a",
"name": "Edit Fields",
"type": "n8n-nodes-base.set",
"position": [
960,
340
],
"parameters": {
"options": {},
"assignments": {
"assignments": [
{
"id": "498c663a-f372-40fb-9ac9-79f7a60875cc",
"name": "complete_text",
"type": "string",
"value": "={{ $json.complete_text }}"
},
{
"id": "34f3bc06-151d-4819-b6b8-515cf9c05c60",
"name": "file",
"type": "object",
"value": "={{$('Receive SRT File to Translate').first().json}}"
}
]
}
},
"typeVersion": 3.4
},
{
"id": "a4e1cc2e-bd2f-4cf7-af03-73e43cda83d3",
"name": "Convert to File",
"type": "n8n-nodes-base.convertToFile",
"position": [
1400,
340
],
"parameters": {
"options": {
"fileName": "={{ $json['Upload SRT file'].filename.replaceAll('.srt',` ${$('Prep Parts for Translate').first().json.language}.srt`)}}",
"mimeType": "={{ $json['Upload SRT file'].mimetype }}"
},
"operation": "toBinary",
"sourceProperty": "=data",
"binaryPropertyName": "file"
},
"typeVersion": 1.1
},
{
"id": "380bc679-4e08-4d5d-a263-d3d873f4f38f",
"name": "Split SRT Lines",
"type": "n8n-nodes-base.code",
"position": [
960,
140
],
"parameters": {
"mode": "runOnceForEachItem",
"jsCode": "let text = $json.data
delete $json.base64
delete $json.binary
// Split by single newlines
const lines = text.split('\n')
// Create an array to hold grouped subtitle entries
let subtitleGroups = []
let currentGroup = []
// Process each line
for (let i = 0; i < lines.length; i++) {
const line = lines[i].trim()
// If line is empty and we have content in currentGroup,
// it's the end of a subtitle entry
if (line === '' && currentGroup.length > 0) {
subtitleGroups.push(currentGroup.join('\n'))
currentGroup = []
}
// If line is not empty, add to current group
else if (line !== '') {
currentGroup.push(line)
}
}
// Add the last group if it has content
if (currentGroup.length > 0) {
subtitleGroups.push(currentGroup.join('\n'))
}
// Remove any quotes at the beginning and end of the first and last entries
if (subtitleGroups.length > 0) {
subtitleGroups[0] = subtitleGroups[0].replace(/^\"/, '')
subtitleGroups[subtitleGroups.length - 1] = subtitleGroups[subtitleGroups.length - 1].replace(/\"$/, '')
}
// Store the result
$input.item.json.txt = subtitleGroups
return $input.item;"
},
"typeVersion": 2
},
{
"id": "08215886-05f6-4ecc-9c1f-55c0e4cb6194",
"name": "Generate Binary",
"type": "n8n-nodes-base.code",
"position": [
1180,
340
],
"parameters": {
"mode": "runOnceForEachItem",
"jsCode": "function encodeBase64(text) {
try {
// For browser environments
if (typeof window !== 'undefined') {
// First, create a UTF-8 encoded string
const utf8String = encodeURIComponent(text)
.replace(/%([0-9A-F]{2})/g, (_, hex) => {
return String.fromCharCode(parseInt(hex, 16));
});
// Then encode to Base64
return btoa(utf8String);
}
// For Node.js environments
else if (typeof Buffer !== 'undefined') {
return Buffer.from(text).toString('base64');
}
throw new Error('Environment not supported for Base64 encoding');
} catch (error) {
console.error('Error encoding to Base64:', error);
return null;
}
}
let data = encodeBase64($json.complete_text);
console.log(data)
let file = $json.file
file.data = data;
let paddingCount = 0;
if (data.endsWith('==')) paddingCount = 2;
else if (data.endsWith('=')) paddingCount = 1;
// Calculate the decoded size (in bytes)
file.size = Math.floor(data.length * 3 / 4) - paddingCount;
return file"
},
"typeVersion": 2
},
{
"id": "299122c1-61d1-4ce4-81b9-ce15d22cd49c",
"name": "Prep Parts for Translate",
"type": "n8n-nodes-base.code",
"position": [
1400,
140
],
"parameters": {
"mode": "runOnceForEachItem",
"jsCode": "function splitBySecondNewline(text) {
// Find the position of the first newline
const firstNewlinePos = text.indexOf('\n');
if (firstNewlinePos === -1) {
return { firstPart: text, secondPart: '' }; // No newlines found
}
// Find the position of the second newline
const secondNewlinePos = text.indexOf('\n', firstNewlinePos + 1);
if (secondNewlinePos === -1) {
return { firstPart: text, secondPart: '' }; // Only one newline found
}
// Split the string at the second newline
const firstPart = text.substring(0, secondNewlinePos);
const secondPart = text.substring(secondNewlinePos + 1);
return { firstPart, secondPart };
}
let lang = $('Receive SRT File to Translate').first().json['Translate to Language']
return {
parts: splitBySecondNewline($json.txt),
language: lang
}"
},
"typeVersion": 2
},
{
"id": "8a810ef3-febe-42f7-91c9-6c82dddcc93a",
"name": "Clean Translations & Group Titles",
"type": "n8n-nodes-base.code",
"position": [
300,
340
],
"parameters": {
"mode": "runOnceForEachItem",
"jsCode": "let translated = $json.translatedText.replaceAll(\"\\n\",\"\n\").replaceAll('"',\"\").replaceAll(''',\"'\");
function splitIntoTwoLines(text, maxLength = 40) {
// If text already contains a newline or is short enough, return as is
if (text.includes('\n') || text.length <= maxLength) {
return text;
}
// Find the last space before or at the maxLength
let splitIndex = text.lastIndexOf(' ', maxLength);
// If no space was found (rare case with very long words)
if (splitIndex === -1) {
splitIndex = maxLength; // Force split at maxLength
}
// Split the text and join with a newline
const firstLine = text.substring(0, splitIndex);
const secondLine = text.substring(splitIndex + 1); // +1 to skip the space
return firstLine + '\n' + secondLine;
}
// Add a new field called 'myNewField' to the JSON of the item
$input.item.json.complete = `${$('Prep Parts for Translate').item.json.parts.firstPart}\n` + splitIntoTwoLines(translated)
return $input.item;"
},
"typeVersion": 2
},
{
"id": "15b2781c-4b6f-43e7-9ca9-6d6114e5fdab",
"name": "Join completed text with double new line",
"type": "n8n-nodes-base.code",
"position": [
740,
340
],
"parameters": {
"mode": "runOnceForEachItem",
"jsCode": "let texts = $json.data.map(item=>{
return item.complete
})
$input.item.json.complete_text = texts.join('\n\n')
return $input.item;"
},
"typeVersion": 2
},
{
"id": "c43efbb6-3fe8-4aa3-8d65-ed3064bcc948",
"name": "Respond with file",
"type": "n8n-nodes-base.form",
"position": [
1620,
340
],
"webhookId": "b783b857-21b3-41a3-85da-2dbf2d85da54",
"parameters": {
"options": {},
"operation": "completion",
"respondWith": "returnBinary",
"completionTitle": "Done",
"inputDataFieldName": "file"
},
"typeVersion": 1
},
{
"id": "13103a23-3b1a-46d1-9731-c281ff1cac06",
"name": "Receive SRT File to Translate",
"type": "n8n-nodes-base.formTrigger",
"position": [
300,
140
],
"webhookId": "8f3c089f-4cbe-4994-9d0e-d86518ef855c",
"parameters": {
"options": {
"appendAttribution": false
},
"formTitle": "upload srt",
"formFields": {
"values": [
{
"fieldType": "dropdown",
"fieldLabel": "Translate to Language",
"fieldOptions": {
"values": [
{
"option": "EN"
},
{
"option": "JP"
}
]
},
"requiredField": true
},
{
"fieldType": "file",
"fieldLabel": "Upload SRT file",
"multipleFiles": false,
"requiredField": true,
"acceptFileTypes": ".srt"
}
]
},
"responseMode": "lastNode"
},
"typeVersion": 2.2
},
{
"id": "7e0f06f4-1e9d-436f-9310-325214e74bb9",
"name": "Sticky Note",
"type": "n8n-nodes-base.stickyNote",
"position": [
280,
-280
],
"parameters": {
"width": 760,
"height": 300,
"content": "## Required Credentials
https://docs.n8n.io/integrations/builtin/credentials/google/
## Selecting Language
You can update the form to include your preferred language code (that you are translating to), by updating the dropdown field with a new option.
Or update the Google Translate node language option back to 'fixed' and select your desired language. This will ignore the form option, but is safe to do."
},
"typeVersion": 1
},
{
"id": "29f9621e-3756-48ee-b6f0-e26a9f7aa247",
"name": "Extract text from Binary File",
"type": "n8n-nodes-base.extractFromFile",
"position": [
740,
140
],
"parameters": {
"options": {},
"operation": "text",
"binaryPropertyName": "Upload_SRT_file"
},
"typeVersion": 1
},
{
"id": "0924754e-6d1f-4d82-bb58-f64ebeac7b05",
"name": "Expose Binary",
"type": "n8n-nodes-base.code",
"position": [
520,
140
],
"parameters": {
"mode": "runOnceForEachItem",
"jsCode": "// Add a new field called 'myNewField' to the JSON of the item
$input.item.json.binary = $binary;
return $input.item;"
},
"typeVersion": 2
}
],
"active": true,
"pinData": {
"Receive SRT File to Translate": [
{
"json": {
"formMode": "production",
"submittedAt": "2025-04-20T05:46:13.787-04:00",
"Upload SRT file": {
"size": 7748,
"filename": "example_file.srt",
"mimetype": "application/octet-stream"
},
"Translate to Language": "EN"
}
}
]
},
"settings": {
"executionOrder": "v1"
},
"versionId": "824adb39-806e-4d28-8e41-efd9f2e179a8",
"connections": {
"Aggregate": {
"main": [
[
{
"node": "Join completed text with double new line",
"type": "main",
"index": 0
}
]
]
},
"Split Out": {
"main": [
[
{
"node": "Prep Parts for Translate",
"type": "main",
"index": 0
}
]
]
},
"Edit Fields": {
"main": [
[
{
"node": "Generate Binary",
"type": "main",
"index": 0
}
]
]
},
"Expose Binary": {
"main": [
[
{
"node": "Extract text from Binary File",
"type": "main",
"index": 0
}
]
]
},
"Convert to File": {
"main": [
[
{
"node": "Respond with file",
"type": "main",
"index": 0
}
]
]
},
"Generate Binary": {
"main": [
[
{
"node": "Convert to File",
"type": "main",
"index": 0
}
]
]
},
"Split SRT Lines": {
"main": [
[
{
"node": "Split Out",
"type": "main",
"index": 0
}
]
]
},
"Google Translate": {
"main": [
[
{
"node": "Clean Translations & Group Titles",
"type": "main",
"index": 0
}
]
]
},
"Prep Parts for Translate": {
"main": [
[
{
"node": "Google Translate",
"type": "main",
"index": 0
}
]
]
},
"Extract text from Binary File": {
"main": [
[
{
"node": "Split SRT Lines",
"type": "main",
"index": 0
}
]
]
},
"Receive SRT File to Translate": {
"main": [
[
{
"node": "Expose Binary",
"type": "main",
"index": 0
}
]
]
},
"Clean Translations & Group Titles": {
"main": [
[
{
"node": "Aggregate",
"type": "main",
"index": 0
}
]
]
},
"Join completed text with double new line": {
"main": [
[
{
"node": "Edit Fields",
"type": "main",
"index": 0
}
]
]
}
}
}
功能特点
- 自动检测新邮件
- AI智能内容分析
- 自定义分类规则
- 批量处理能力
- 详细的处理日志
技术分析
节点类型及作用
- Splitout
- Googletranslate
- Aggregate
- Set
- Converttofile
复杂度评估
配置难度:
维护难度:
扩展性:
实施指南
前置条件
- 有效的Gmail账户
- n8n平台访问权限
- Google API凭证
- AI分类服务订阅
配置步骤
- 在n8n中导入工作流JSON文件
- 配置Gmail节点的认证信息
- 设置AI分类器的API密钥
- 自定义分类规则和标签映射
- 测试工作流执行
- 配置定时触发器(可选)
关键参数
| 参数名称 | 默认值 | 说明 |
|---|---|---|
| maxEmails | 50 | 单次处理的最大邮件数量 |
| confidenceThreshold | 0.8 | 分类置信度阈值 |
| autoLabel | true | 是否自动添加标签 |
最佳实践
优化建议
- 定期更新AI分类模型以提高准确性
- 根据邮件量调整处理批次大小
- 设置合理的分类置信度阈值
- 定期清理过期的分类规则
安全注意事项
- 妥善保管API密钥和认证信息
- 限制工作流的访问权限
- 定期审查处理日志
- 启用双因素认证保护Gmail账户
性能优化
- 使用增量处理减少重复工作
- 缓存频繁访问的数据
- 并行处理多个邮件分类任务
- 监控系统资源使用情况
故障排除
常见问题
邮件未被正确分类
检查AI分类器的置信度阈值设置,适当降低阈值或更新训练数据。
Gmail认证失败
确认Google API凭证有效且具有正确的权限范围,重新进行OAuth授权。
调试技巧
- 启用详细日志记录查看每个步骤的执行情况
- 使用测试邮件验证分类逻辑
- 检查网络连接和API服务状态
- 逐步执行工作流定位问题节点
错误处理
工作流包含以下错误处理机制:
- 网络超时自动重试(最多3次)
- API错误记录和告警
- 处理失败邮件的隔离机制
- 异常情况下的回滚操作