用 API 自动完成文件本地化

上传源文件,启动文档任务,再将译文下载到独立的输出目录。

如果文件由你的后端管理,且翻译流程需要与后端的存储系统协同,请使用文档 API。本示例将 messages/en.json 翻译成德语和法语。CLI 可在本地项目中执行相同的文件操作。

你需要 Node.js 22 或更高版本、一个组织、一个已配置模型的引擎,以及具有翻译访问权限的 API 密钥。首次运行时,请将翻译配置为无需人工审核;待文件处理的完整流程跑通后,再添加审核。

准备源文件 #

创建 messages/en.json:

json
{
  "title": "Account settings",
  "save": "Save changes"
}

用你自己的值设置以下环境变量:

sh
export LINGO_API_KEY="YOUR_API_KEY"
export LINGO_ORGANIZATION_ID="YOUR_ORGANIZATION_ID"
export LINGO_ENGINE_ID="YOUR_ENGINE_ID"
export LINGO_REQUEST_ID="account-settings-v1-de-fr"

针对同一源文件和配置重试时,请保持请求 ID 不变。提交新版本时,请更换请求 ID。

上传、启动并获取结果 #

将此程序保存为 translate-file.mjs:

js
import { createHash } from "node:crypto";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { setTimeout as delay } from "node:timers/promises";

const origin = "https://api.lingo.dev";
const {
  LINGO_API_KEY: apiKey,
  LINGO_ORGANIZATION_ID: orgId,
  LINGO_ENGINE_ID: engineId,
  LINGO_REQUEST_ID: requestId,
} = process.env;
if (!apiKey || !orgId || !engineId || !requestId) throw new Error("Set the four LINGO environment variables");

async function request(path, options = {}) {
  const response = await fetch(new URL(path, origin), {
    ...options,
    headers: { "X-API-Key": apiKey, ...options.headers },
    signal: AbortSignal.timeout(30_000),
  });
  if (!response.ok) throw new Error(`HTTP ${response.status}: ${await response.text()}`);
  return response;
}

const bytes = await readFile("messages/en.json");
const address = createHash("sha256").update(bytes).digest("hex");
let job = await (
  await request(`/v2/organizations/${encodeURIComponent(orgId)}/localization/jobs`, {
    method: "POST",
    headers: { "Content-Type": "application/json", "Idempotency-Key": requestId },
    body: JSON.stringify({
      engineId,
      sourceLocale: "en",
      targetLocales: ["de", "fr"],
      documents: [{ key: "messages/en.json", format: { type: "json" }, source: address }],
    }),
  })
).json();

await writeFile("file-job.json", JSON.stringify({ id: job.id, requestId, source: address }, null, 2));
for (const upload of job.uploads) {
  await request(upload.uploadUrl, {
    method: "PUT",
    headers: { "Content-Type": "application/octet-stream" },
    body: bytes,
  });
}
job = await (
  await request(`/v2/localization/jobs/${encodeURIComponent(job.id)}/start`, {
    method: "POST",
  })
).json();

const deadline = Date.now() + 120_000;
while (["Pending", "Running"].includes(job.status._tag)) {
  if (Date.now() >= deadline) throw new Error(`Keep job ${job.id} and check again later`);
  await delay(2000);
  job = await (await request(`/v2/localization/jobs/${encodeURIComponent(job.id)}`)).json();
}

await mkdir("translated", { recursive: true });
for (const { locale, status } of job.documents[0].targets) {
  if (status._tag !== "Completed") {
    throw new Error(`Inspect job ${job.id}: ${locale} is ${status._tag}`);
  }
  const output = await request(status.downloadUrl);
  await writeFile(`translated/${locale}.json`, new Uint8Array(await output.arrayBuffer()));
  console.log(`Saved translated/${locale}.json`);
}

运行 node translate-file.mjs,然后检查 translated/de.json 和 translated/fr.json。两个文件都应保留源文件中的键,并包含对应语言的内容。程序将输出文件与应用文件分开保存,方便你在替换已接受的内容前先进行审核。

恢复任务,避免重复创建 #

file-job.json 记录远程标识和源文件哈希值。如果上传或启动请求的响应丢失,请获取该任务,上传剩余的文件产物,再次发送启动请求。使用原始幂等键再次发送创建请求,也会返回同一个任务。

轮询超时不会取消任务。请继续查询已记录的任务,不要仅因本地程序停止等待就创建新任务。

本示例会在遇到第一个未完成的目标或失败的请求时停止。已保存的文件仍保留在 translated/ 中。要继续,请获取 file-job.json 中记录的任务,并使用各个已完成目标的 downloadUrl 值下载结果;参见任务状态和结果。下载失败无需创建新的翻译任务。

添加增量更新 #

提交下一版本时,请在提供新源文件地址的同时提供 previousSource 和 previousTranslations。上传成功前,请保留每个被引用的文件产物的字节数据。你提供的上一版目标文件应包含已接受的人工修改。

翻译文档介绍了相关字段和复用规则。发布前,请将任务使用的源文件版本与当前源文件进行比较,并检查目标文件在提交后是否有修改。构建翻译工作流介绍了这一验收步骤。