Tutorials
Automated Multilingual Pipeline
Build an end-to-end automated document translation worker using Node.js or Python.
In this recipe, you'll see how to upload a file from disk, start an asynchronous translation job, and poll until the job finishes, handling idempotency and error checks.
Complete Node.js Script
import * as fs from "node:fs";
import { randomUUID } from "node:crypto";
const API_KEY = process.env.TRANSPERA_API_KEY!;
const API_BASE = "https://transpera-api-dev-vv55i7vbvq-el.a.run.app";
async function translateDocument(filePath: string, targetLanguage: string) {
const fileName = filePath.split("/").pop()!;
// 1. Get signed upload URL
const uploadInit = await fetch(`${API_BASE}/v1/uploads`, {
method: "POST",
headers: { "authorization": `Bearer ${API_KEY}`, "content-type": "application/json" },
body: JSON.stringify({ fileName, contentType: "application/pdf" })
}).then(r => r.json());
// 2. Upload file bytes
await fetch(uploadInit.url, {
method: "PUT",
headers: { "content-type": "application/pdf" },
body: fs.readFileSync(filePath)
});
// 3. Dispatch translate job
const jobRes = await fetch(`${API_BASE}/v1/jobs`, {
method: "POST",
headers: {
"authorization": `Bearer ${API_KEY}`,
"content-type": "application/json",
"idempotency-key": randomUUID()
},
body: JSON.stringify({
operation: "document.translate",
input: { uploadId: uploadInit.uploadId, targetLanguage, tone: "professional" }
})
}).then(r => r.json());
console.log("Job queued:", jobRes.job.id);
// 4. Poll until completed
while (true) {
await new Promise(res => setTimeout(res, 3000));
const status = await fetch(`${API_BASE}/v1/jobs/${jobRes.job.id}`, {
headers: { "authorization": `Bearer ${API_KEY}` }
}).then(r => r.json());
console.log("Status:", status.job.status);
if (status.job.status === "succeeded") {
console.log("Translation finished! Charged:", status.job.chargedCredits);
break;
}
if (status.job.status === "failed") {
throw new Error("Job failed: " + status.job.errorCode);
}
}
}