Μετάβαση στο περιεχόμενο

Black Friday: Έκπτωση 70% στα ετήσια προγράμματα, 50% στον πρώτο σας μήνα. Λήγει στις Κυριακή 6 Δεκεμβρίου.

Δείτε τις τιμέςΔείτε τις τιμές
Lingivio
Δοκιμάστε δωρεάνΣτον πίνακα ελέγχου

Τεκμηρίωση αναφοράς για προγραμματιστές

REST API

Τρία βήματα: μεταφορτώστε ένα αρχείο, ξεκινήστε μια μετάφραση, κάντε λήψη του αποτελέσματος. Ο κώδικάς σας μπορεί να κάνει ό,τι κάνει η εφαρμογή.

Βασικό URL

Η πρόσβαση στο API ξεκινά από το πρόγραμμα Business. Σε οποιοδήποτε άλλο πρόγραμμα, ένα κλειδί επιτρέπει τη σύνδεση και την ανάγνωση του GET /v1/me. Κάθε άλλο τελικό σημείο απαντά με plan.api_access_required και ονομάζει το πρόγραμμα που την περιλαμβάνει.

Σε αυτή τη σελίδα

Έλεγχος ταυτότητας

Δημιουργήστε ένα κλειδί στις Ρυθμίσεις → Κλειδιά API. Το κλειδί εμφανίζεται μία φορά και δεν μπορεί να ανακτηθεί. Στείλτε το ως διακριτικό bearer σε κάθε αίτημα. Οι εξής ενέργειες ανακαλούν κάθε κλειδί του λογαριασμού και αντικαθιστούν το μυστικό υπογραφής webhook: η επαναφορά κωδικού πρόσβασης, η αλλαγή κωδικού πρόσβασης που αποσυνδέει τις άλλες συσκευές σας (κάθε αλλαγή από τις Ρυθμίσεις το κάνει) και ένα αίτημα που αποσυνδέει άλλη συσκευή ή όλες τις συσκευές. Δημιουργήστε νέο κλειδί μετά. Αν αποσυνδέσετε μόνο τη συσκευή που χρησιμοποιείτε, τα κλειδιά παραμένουν έγκυρα.

JavaScript
const res = await fetch('https://api.lingivio.com/v1/me', {
  headers: { Authorization: `Bearer ${process.env.LINGIVIO_KEY}` },
});
console.log(res.status, await res.json());
TypeScript
const res: Response = await fetch('https://api.lingivio.com/v1/me', {
  headers: { Authorization: `Bearer ${process.env.LINGIVIO_KEY}` },
});
console.log(res.status, await res.json());
Python
import os
import httpx

res = httpx.get(
    "https://api.lingivio.com/v1/me",
    headers={"Authorization": f"Bearer {os.environ['LINGIVIO_KEY']}"},
)
print(res.status_code, res.json())
Ruby
require "json"
require "net/http"

uri = URI("https://api.lingivio.com/v1/me")
req = Net::HTTP::Get.new(uri, "Authorization" => "Bearer #{ENV.fetch("LINGIVIO_KEY")}")
res = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https") { |http| http.request(req) }
puts res.code, JSON.parse(res.body)
Go
package main

import (
	"fmt"
	"io"
	"net/http"
	"os"
)

func main() {
	req, _ := http.NewRequest("GET", "https://api.lingivio.com/v1/me", nil)
	req.Header.Set("Authorization", "Bearer "+os.Getenv("LINGIVIO_KEY"))
	res, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)
	fmt.Println(res.StatusCode, string(body))
}
cURL
curl https://api.lingivio.com/v1/me -H "Authorization: Bearer $LINGIVIO_KEY"

Γρήγορη εκκίνηση

Αντιγράψτε αυτόν τον κώδικα όπως είναι. Μεταφορτώνει ένα PDF και διαβάζει τον επαληθευμένο τύπο του, τη γλώσσα που εντοπίστηκε και το κόστος σε πιστώσεις. Στη συνέχεια μεταφράζει το PDF με παράλληλη προβολή στη γλώσσα Ιαπωνικά, ελέγχει περιοδικά μέχρι την ολοκλήρωση και πραγματοποιεί λήψη του αποτελέσματος.

JavaScript
// Node 18+, Bun or Deno — save as translate.mjs and run `node translate.mjs`.
import { readFile, writeFile } from 'node:fs/promises';

const API = 'https://api.lingivio.com';
const auth = { Authorization: `Bearer ${process.env.LINGIVIO_KEY}` };

// 1. Upload. The answer carries the verified content type, the detected source language and the
//    real credit count, so you can price the job before you start it.
const form = new FormData();
form.append('file', new Blob([await readFile('report.pdf')]), 'report.pdf');
const file = await fetch(`${API}/v1/files`, { method: 'POST', headers: auth, body: form })
  .then((r) => r.json());
if (!file.id) throw new Error(JSON.stringify(file.error));
console.log(file.content_type, file.detected_source_language, file.credits);

// 2. Translate. The same Idempotency-Key and body return the SAME translation, billed once.
let job = await fetch(`${API}/v1/translations`, {
  method: 'POST',
  headers: { ...auth, 'content-type': 'application/json', 'Idempotency-Key': crypto.randomUUID() },
  body: JSON.stringify({ file_id: file.id, target_language: 'ja', side_by_side: true }),
}).then((r) => r.json());

// 3. Poll while the job is IN PROGRESS, on REAL segment counts. Every other answer ends the loop:
//    done, failed, canceled, needs_review — or no status at all (an error answer).
const IN_PROGRESS = ['pending', 'queued', 'dispatched', 'running', 'cancel_requested'];
while (IN_PROGRESS.includes(job.status)) {
  await new Promise((resolve) => setTimeout(resolve, 3000));
  job = await fetch(`${API}/v1/translations/${job.id}`, { headers: auth }).then((r) => r.json());
  if (job.progress) console.log(job.progress.done, '/', job.progress.total);
}
// Only a finished job has an output; `error.class` is stable and machine-readable.
if (job.status !== 'done') throw new Error(`${job.status ?? 'no status'}: ${JSON.stringify(job.error)}`);

// 4. Download
const out = await fetch(`${API}/v1/translations/${job.id}/output`, { headers: auth });
await writeFile('report.ja.pdf', Buffer.from(await out.arrayBuffer()));
TypeScript
// TypeScript on Node 18+ (tsx), Bun or Deno — save as translate.ts and run `npx tsx translate.ts`.
import { readFile, writeFile } from 'node:fs/promises';

const API = 'https://api.lingivio.com';
const auth = { Authorization: `Bearer ${process.env.LINGIVIO_KEY}` };

interface ApiError { class: string; retryable: boolean; credit_action: string }
interface PublicFile { id: string; content_type: string; detected_source_language: string | null; credits: number | null }
interface PublicTranslation {
  id: string;
  status: string;
  progress: { done: number; total: number } | null;
  error: ApiError | null;
}

// 1. Upload: the answer is the verified file, with its real credit count.
const form = new FormData();
form.append('file', new Blob([await readFile('report.pdf')]), 'report.pdf');
const upload = await fetch(`${API}/v1/files`, { method: 'POST', headers: auth, body: form });
const file = (await upload.json()) as PublicFile & { error?: ApiError };
if (!upload.ok) throw new Error(file.error?.class);
console.log(file.content_type, file.detected_source_language, file.credits);

// 2. Translate (idempotent: a retry with the same key and body is billed once)
let job = (await fetch(`${API}/v1/translations`, {
  method: 'POST',
  headers: { ...auth, 'content-type': 'application/json', 'Idempotency-Key': crypto.randomUUID() },
  body: JSON.stringify({ file_id: file.id, target_language: 'ja', side_by_side: true }),
}).then((r) => r.json())) as Partial<PublicTranslation>;

// 3. Poll while the job is IN PROGRESS. Every other answer ends the loop: done, failed, canceled,
//    needs_review — or no status at all (an error answer).
const IN_PROGRESS: string[] = ['pending', 'queued', 'dispatched', 'running', 'cancel_requested'];
while (job.status !== undefined && IN_PROGRESS.includes(job.status)) {
  await new Promise((resolve) => setTimeout(resolve, 3000));
  job = (await fetch(`${API}/v1/translations/${job.id}`, { headers: auth }).then((r) => r.json())) as PublicTranslation;
  if (job.progress) console.log(job.progress.done, '/', job.progress.total);
}
if (job.status !== 'done') throw new Error(`${job.status ?? 'no status'}: ${JSON.stringify(job.error)}`);

// 4. Download
const out = await fetch(`${API}/v1/translations/${job.id}/output`, { headers: auth });
await writeFile('report.ja.pdf', new Uint8Array(await out.arrayBuffer()));
Python
# Python 3.9+ with httpx (pip install httpx).
import os
import time
import uuid
import httpx

API = "https://api.lingivio.com"
auth = {"Authorization": f"Bearer {os.environ['LINGIVIO_KEY']}"}

with httpx.Client(base_url=API, headers=auth, timeout=120) as http:
    # 1. Upload: the answer carries the verified type, the source language and the real credits.
    with open("report.pdf", "rb") as fh:
        file = (
            http.post("/v1/files", files={"file": ("report.pdf", fh)})
            .raise_for_status()
            .json()
        )
    print(file["content_type"], file["detected_source_language"], file["credits"])

    # 2. Translate (idempotent: a retry with the same key and body is billed once)
    job = (
        http.post(
            "/v1/translations",
            headers={"Idempotency-Key": str(uuid.uuid4())},
            json={"file_id": file["id"], "target_language": "ja", "side_by_side": True},
        )
        .raise_for_status()
        .json()
    )

    # 3. Poll while the job is IN PROGRESS, on REAL segment counts. Every other answer ends the
    #    loop: done, failed, canceled, needs_review — or no status at all (an error answer).
    IN_PROGRESS = {"pending", "queued", "dispatched", "running", "cancel_requested"}
    while job.get("status") in IN_PROGRESS:
        time.sleep(3)
        job = http.get(f"/v1/translations/{job['id']}").json()
        if job.get("progress"):
            print(job["progress"]["done"], "/", job["progress"]["total"])
    # Only a finished job has an output; error.class is stable and machine-readable.
    if job.get("status") != "done":
        raise RuntimeError(f"{job.get('status', 'no status')}: {job.get('error')}")

    # 4. Download
    out = http.get(f"/v1/translations/{job['id']}/output").raise_for_status()
    with open("report.ja.pdf", "wb") as fh:
        fh.write(out.content)
Ruby
# Ruby 3+, standard library only.
require "json"
require "net/http"
require "securerandom"

API = URI("https://api.lingivio.com")
KEY = ENV.fetch("LINGIVIO_KEY")

def call(request)
  request["Authorization"] = "Bearer #{KEY}"
  Net::HTTP.start(API.host, API.port, use_ssl: API.scheme == "https") { |http| http.request(request) }
end

# 1. Upload: the answer carries the verified type, the source language and the real credits.
upload = Net::HTTP::Post.new("/v1/files")
upload.set_form([["file", File.open("report.pdf", "rb"), { filename: "report.pdf" }]], "multipart/form-data")
file = JSON.parse(call(upload).body)
raise file["error"].to_s unless file["id"]
puts [file["content_type"], file["detected_source_language"], file["credits"]].join(" ")

# 2. Translate (idempotent: a retry with the same key and body is billed once)
start = Net::HTTP::Post.new("/v1/translations", "content-type" => "application/json",
                            "Idempotency-Key" => SecureRandom.uuid)
start.body = JSON.generate(file_id: file["id"], target_language: "ja", side_by_side: true)
job = JSON.parse(call(start).body)

# 3. Poll while the job is IN PROGRESS. Every other answer ends the loop: done, failed, canceled,
#    needs_review — or no status at all (an error answer).
IN_PROGRESS = ["pending", "queued", "dispatched", "running", "cancel_requested"]
while IN_PROGRESS.include?(job["status"])
  sleep 3
  job = JSON.parse(call(Net::HTTP::Get.new("/v1/translations/#{job["id"]}")).body)
  puts "#{job["progress"]["done"]} / #{job["progress"]["total"]}" if job["progress"]
end
raise "#{job["status"] || "no status"}: #{job["error"]}" if job["status"] != "done"

# 4. Download
out = call(Net::HTTP::Get.new("/v1/translations/#{job["id"]}/output"))
File.binwrite("report.ja.pdf", out.body)
Go
// Go 1.21+, standard library only: go run translate.go
package main

import (
	"bytes"
	"crypto/rand"
	"encoding/json"
	"fmt"
	"io"
	"mime/multipart"
	"net/http"
	"os"
	"slices"
	"time"
)

const api = "https://api.lingivio.com"

var key = os.Getenv("LINGIVIO_KEY")

type translation struct {
	ID       string                     `json:"id"`
	Status   string                     `json:"status"`
	Progress *struct{ Done, Total int } `json:"progress"`
	Error    json.RawMessage            `json:"error"`
}

func call(method, path, contentType string, body io.Reader, headers map[string]string) *http.Response {
	req, _ := http.NewRequest(method, api+path, body)
	req.Header.Set("Authorization", "Bearer "+key)
	if contentType != "" {
		req.Header.Set("Content-Type", contentType)
	}
	for k, v := range headers {
		req.Header.Set(k, v)
	}
	res, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	return res
}

func decode(res *http.Response, into any) {
	defer res.Body.Close()
	if err := json.NewDecoder(res.Body).Decode(into); err != nil {
		panic(err)
	}
}

func main() {
	// 1. Upload: the answer carries the verified type, the source language and the real credits.
	var form bytes.Buffer
	mw := multipart.NewWriter(&form)
	part, _ := mw.CreateFormFile("file", "report.pdf")
	pdf, _ := os.ReadFile("report.pdf")
	part.Write(pdf)
	mw.Close()
	var file struct {
		ID                     string          `json:"id"`
		ContentType            string          `json:"content_type"`
		DetectedSourceLanguage string          `json:"detected_source_language"`
		Credits                int             `json:"credits"`
		Error                  json.RawMessage `json:"error"`
	}
	decode(call("POST", "/v1/files", mw.FormDataContentType(), &form, nil), &file)
	if file.ID == "" {
		panic(string(file.Error))
	}
	fmt.Println(file.ContentType, file.DetectedSourceLanguage, file.Credits)

	// 2. Translate (idempotent: a retry with the same key and body is billed once)
	idem := make([]byte, 16)
	rand.Read(idem)
	body, _ := json.Marshal(map[string]any{"file_id": file.ID, "target_language": "ja", "side_by_side": true})
	var job translation
	decode(call("POST", "/v1/translations", "application/json", bytes.NewReader(body),
		map[string]string{"Idempotency-Key": fmt.Sprintf("%x", idem)}), &job)

	// 3. Poll while the job is IN PROGRESS. Every other answer ends the loop: done, failed,
	//    canceled, needs_review — or no status at all (an error answer).
	inProgress := []string{"pending", "queued", "dispatched", "running", "cancel_requested"}
	for slices.Contains(inProgress, job.Status) {
		time.Sleep(3 * time.Second)
		id := job.ID
		job = translation{}
		decode(call("GET", "/v1/translations/"+id, "", nil, nil), &job)
		if job.Progress != nil {
			fmt.Println(job.Progress.Done, "/", job.Progress.Total)
		}
	}
	if job.Status != "done" {
		panic(fmt.Sprintf("%q: %s", job.Status, job.Error))
	}

	// 4. Download
	res := call("GET", "/v1/translations/"+job.ID+"/output", "", nil, nil)
	defer res.Body.Close()
	out, _ := os.Create("report.ja.pdf")
	defer out.Close()
	io.Copy(out, res.Body)
}
cURL
# 1. Create a key in Settings → API keys (Business and Enterprise plans), then:
export KEY="llk_your_key_here"
export API="https://api.lingivio.com"

# 2. Upload the file. The response carries the VERIFIED content type, the detected
#    source language and the real credit count — so you can price the job first.
#    (`page_count` is the same number under its old, misleading name; prefer `credits`.)
FILE=$(curl -s -X POST "$API/v1/files" \
  -H "Authorization: Bearer $KEY" \
  -F "file=@report.pdf")
echo "$FILE" | jq '{id, content_type, detected_source_language, credits}'
FILE_ID=$(echo "$FILE" | jq -r .id)

# 3. Start the translation. Idempotency-Key makes a retry safe: the same key with the
#    same body returns the SAME translation and is billed once.
JOB=$(curl -s -X POST "$API/v1/translations" \
  -H "Authorization: Bearer $KEY" \
  -H "Idempotency-Key: $(uuidgen)" \
  -H "content-type: application/json" \
  -d '{"file_id":"'"$FILE_ID"'","target_language":"ja","side_by_side":true}')
JOB_ID=$(echo "$JOB" | jq -r .id) # null if refused: "$JOB" then names the error class

# 4. Poll while the job is IN PROGRESS. progress.done / progress.total are REAL segment counts.
#    Every other answer ends the loop: done, failed, canceled, needs_review — or no status at all
#    (an error answer: the job was refused, expired, or the key was revoked).
IN_PROGRESS=" pending queued dispatched running cancel_requested "
STATUS=$(echo "$JOB" | jq -r '.status // empty')
while [ -n "$STATUS" ] && [[ "$IN_PROGRESS" == *" $STATUS "* ]]; do
  sleep 3
  JOB=$(curl -s "$API/v1/translations/$JOB_ID" -H "Authorization: Bearer $KEY")
  STATUS=$(echo "$JOB" | jq -r '.status // empty')
done

# 5. Download — only a finished job has an output. Anything else: the answer names the error class.
if [ "$STATUS" = done ]; then
  curl -s "$API/v1/translations/$JOB_ID/output" -H "Authorization: Bearer $KEY" -o report.ja.pdf
else
  echo "$JOB" | jq '{status, error}'
fi

Μεγάλα αρχεία

Πάνω από 25 MiB, μεταφορτώστε σε μέρη. Κάθε μέρος εκτός από το τελευταίο πρέπει να έχει ακριβώς το μέγεθος min_part_bytes που αναφέρει η συνεδρία. Αν στείλετε ξανά έναν αριθμό μέρους, το αντίστοιχο μέρος αντικαθίσταται. Μια μεταφόρτωση που διακόπηκε συνεχίζεται και δεν ξεκινά από την αρχή.

JavaScript
// Files above 25 MiB use the resumable path. Node 18+, Bun or Deno (ES module).
import { open, stat } from 'node:fs/promises';

const API = 'https://api.lingivio.com';
const auth = { Authorization: `Bearer ${process.env.LINGIVIO_KEY}` };
const { size } = await stat('scan.pdf');

const session = await fetch(`${API}/v1/files/uploads`, {
  method: 'POST',
  headers: { ...auth, 'content-type': 'application/json' },
  body: JSON.stringify({ filename: 'scan.pdf', bytes: size }),
}).then((r) => r.json());

// Every part but the last is exactly min_part_bytes. Re-sending a part number replaces it.
const fh = await open('scan.pdf');
for (let n = 1, offset = 0; offset < size; n++, offset += session.min_part_bytes) {
  const length = Math.min(session.min_part_bytes, size - offset);
  const { buffer } = await fh.read(Buffer.alloc(length), 0, length, offset);
  const res = await fetch(`${API}/v1/files/uploads/${session.upload_id}/parts/${n}`, {
    method: 'PUT',
    headers: { ...auth, 'content-type': 'application/octet-stream' },
    body: buffer,
  });
  if (!res.ok) throw new Error(`part ${n}: ${res.status}`);
}
await fh.close();

const file = await fetch(`${API}/v1/files/uploads/${session.upload_id}/complete`, {
  method: 'POST',
  headers: auth,
}).then((r) => r.json());
console.log(file.id, file.credits);
TypeScript
// Files above 25 MiB use the resumable path. TypeScript on Node 18+ (tsx), Bun or Deno.
import { open, stat } from 'node:fs/promises';

const API = 'https://api.lingivio.com';
const auth = { Authorization: `Bearer ${process.env.LINGIVIO_KEY}` };
const { size } = await stat('scan.pdf');

interface UploadSession { upload_id: string; min_part_bytes: number; max_parts: number }

const session = (await fetch(`${API}/v1/files/uploads`, {
  method: 'POST',
  headers: { ...auth, 'content-type': 'application/json' },
  body: JSON.stringify({ filename: 'scan.pdf', bytes: size }),
}).then((r) => r.json())) as UploadSession;

// Every part but the last is exactly min_part_bytes. Re-sending a part number replaces it.
const fh = await open('scan.pdf');
for (let n = 1, offset = 0; offset < size; n++, offset += session.min_part_bytes) {
  const length = Math.min(session.min_part_bytes, size - offset);
  const { buffer } = await fh.read(new Uint8Array(length), 0, length, offset);
  const res = await fetch(`${API}/v1/files/uploads/${session.upload_id}/parts/${n}`, {
    method: 'PUT',
    headers: { ...auth, 'content-type': 'application/octet-stream' },
    body: buffer,
  });
  if (!res.ok) throw new Error(`part ${n}: ${res.status}`);
}
await fh.close();

const file = (await fetch(`${API}/v1/files/uploads/${session.upload_id}/complete`, {
  method: 'POST',
  headers: auth,
}).then((r) => r.json())) as { id: string; credits: number | null };
console.log(file.id, file.credits);
Python
# Files above 25 MiB use the resumable path.
import os
import httpx

API = "https://api.lingivio.com"
auth = {"Authorization": f"Bearer {os.environ['LINGIVIO_KEY']}"}

with httpx.Client(base_url=API, headers=auth, timeout=120) as http:
    size = os.path.getsize("scan.pdf")
    session = (
        http.post("/v1/files/uploads", json={"filename": "scan.pdf", "bytes": size})
        .raise_for_status()
        .json()
    )
    # Every part but the last is exactly min_part_bytes. Re-sending a part number replaces it.
    with open("scan.pdf", "rb") as fh:
        number = 1
        while chunk := fh.read(session["min_part_bytes"]):
            http.put(
                f"/v1/files/uploads/{session['upload_id']}/parts/{number}",
                content=chunk,
                headers={"content-type": "application/octet-stream"},
            ).raise_for_status()
            number += 1
    file = http.post(f"/v1/files/uploads/{session['upload_id']}/complete").raise_for_status().json()
    print(file["id"], file["credits"])
Ruby
# Files above 25 MiB use the resumable path. Ruby 3+, standard library only.
require "json"
require "net/http"

API = URI("https://api.lingivio.com")
KEY = ENV.fetch("LINGIVIO_KEY")

def call(request)
  request["Authorization"] = "Bearer #{KEY}"
  Net::HTTP.start(API.host, API.port, use_ssl: API.scheme == "https") { |http| http.request(request) }
end

start = Net::HTTP::Post.new("/v1/files/uploads", "content-type" => "application/json")
start.body = JSON.generate(filename: "scan.pdf", bytes: File.size("scan.pdf"))
session = JSON.parse(call(start).body)

# Every part but the last is exactly min_part_bytes. Re-sending a part number replaces it.
File.open("scan.pdf", "rb") do |fh|
  number = 1
  while (chunk = fh.read(session["min_part_bytes"]))
    put = Net::HTTP::Put.new("/v1/files/uploads/#{session["upload_id"]}/parts/#{number}",
                             "content-type" => "application/octet-stream")
    put.body = chunk
    res = call(put)
    raise "part #{number}: #{res.code}" unless res.is_a?(Net::HTTPSuccess)
    number += 1
  end
end

file = JSON.parse(call(Net::HTTP::Post.new("/v1/files/uploads/#{session["upload_id"]}/complete")).body)
puts file["id"], file["credits"]
Go
// Files above 25 MiB use the resumable path. Go 1.21+, standard library only.
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
)

const api = "https://api.lingivio.com"

var key = os.Getenv("LINGIVIO_KEY")

func call(method, path, contentType string, body io.Reader) *http.Response {
	req, _ := http.NewRequest(method, api+path, body)
	req.Header.Set("Authorization", "Bearer "+key)
	if contentType != "" {
		req.Header.Set("Content-Type", contentType)
	}
	res, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	return res
}

func main() {
	data, _ := os.ReadFile("scan.pdf")
	start, _ := json.Marshal(map[string]any{"filename": "scan.pdf", "bytes": len(data)})
	var session struct {
		UploadID     string `json:"upload_id"`
		MinPartBytes int    `json:"min_part_bytes"`
	}
	res := call("POST", "/v1/files/uploads", "application/json", bytes.NewReader(start))
	json.NewDecoder(res.Body).Decode(&session)
	res.Body.Close()

	// Every part but the last is exactly min_part_bytes. Re-sending a part number replaces it.
	for n, offset := 1, 0; offset < len(data); n, offset = n+1, offset+session.MinPartBytes {
		end := min(offset+session.MinPartBytes, len(data))
		path := fmt.Sprintf("/v1/files/uploads/%s/parts/%d", session.UploadID, n)
		res := call("PUT", path, "application/octet-stream", bytes.NewReader(data[offset:end]))
		res.Body.Close()
		if res.StatusCode >= 300 {
			panic(fmt.Sprintf("part %d: %d", n, res.StatusCode))
		}
	}

	res = call("POST", "/v1/files/uploads/"+session.UploadID+"/complete", "", nil)
	defer res.Body.Close()
	var file struct {
		ID      string `json:"id"`
		Credits int    `json:"credits"`
	}
	json.NewDecoder(res.Body).Decode(&file)
	fmt.Println(file.ID, file.Credits)
}
cURL
# Files above 25 MiB use the resumable path.
SESSION=$(curl -s -X POST "$API/v1/files/uploads" \
  -H "Authorization: Bearer $KEY" -H "content-type: application/json" \
  -d '{"filename":"scan.pdf","bytes":'$(wc -c < scan.pdf)'}')
UPLOAD_ID=$(echo "$SESSION" | jq -r .upload_id)
PART=$(echo "$SESSION" | jq -r .min_part_bytes)

split -b "$PART" scan.pdf part-
i=1
for f in part-*; do
  curl -s -X PUT "$API/v1/files/uploads/$UPLOAD_ID/parts/$i" \
    -H "Authorization: Bearer $KEY" -H "content-type: application/octet-stream" \
    --data-binary "@$f" > /dev/null
  i=$((i + 1))
done

curl -s -X POST "$API/v1/files/uploads/$UPLOAD_ID/complete" -H "Authorization: Bearer $KEY"

Υποστηριζόμενες γλώσσες και μορφές

Δύο δημόσια σημεία πρόσβασης παραθέτουν όσα δέχεται το API, ώστε μια διασύνδεση να μη χρειάζεται ποτέ να τα ενσωματώνει στατικά στον κώδικα. Το GET /v1/formats παραθέτει κάθε μορφή μεταφόρτωσης με τις επεκτάσεις αρχείων της, το όριο μεγέθους της σε κάθε πρόγραμμα και τον κανόνα με τον οποίο χρεώνεται. Το GET /v1/languages παραθέτει κάθε γλώσσα προορισμού με το αγγλικό και το εγγενές όνομά της, το σύστημα γραφής της και τις μορφές που τη δέχονται· προσθέστε ?format=pdf για να κρατήσετε μόνο τις γλώσσες στις οποίες μπορεί να μεταφραστεί ένα PDF. Κανένα δεν χρειάζεται κλειδί API και οι δύο απαντήσεις μπορούν να αποθηκευτούν προσωρινά.

JavaScript
// Public and cacheable: no API key needed.
const API = 'https://api.lingivio.com';

const formats = await fetch(`${API}/v1/formats`).then((r) => r.json());
for (const f of formats.data) console.log(f.format, f.extensions.join(','), f.max_bytes);

// The target languages a PDF can be translated into (drop ?format= for every language).
const languages = await fetch(`${API}/v1/languages?format=pdf`).then((r) => r.json());
for (const l of languages.data) console.log(l.code, l.name, l.native_name, l.script);
TypeScript
// Public and cacheable: no API key needed.
const API = 'https://api.lingivio.com';

interface Format { format: string; extensions: string[]; max_bytes: number }
interface Language { code: string; name: string; native_name: string; script: string; formats: string[] }

const formats = (await fetch(`${API}/v1/formats`).then((r) => r.json())) as { data: Format[] };
for (const f of formats.data) console.log(f.format, f.extensions.join(','), f.max_bytes);

// The target languages a PDF can be translated into (drop ?format= for every language).
const languages = (await fetch(`${API}/v1/languages?format=pdf`).then((r) => r.json())) as { data: Language[] };
for (const l of languages.data) console.log(l.code, l.name, l.native_name, l.script);
Python
# Public and cacheable: no API key needed.
import httpx

API = "https://api.lingivio.com"

for f in httpx.get(f"{API}/v1/formats").raise_for_status().json()["data"]:
    print(f["format"], ",".join(f["extensions"]), f["max_bytes"])

# The target languages a PDF can be translated into (drop ?format= for every language).
languages = httpx.get(f"{API}/v1/languages", params={"format": "pdf"}).raise_for_status().json()
for lang in languages["data"]:
    print(lang["code"], lang["name"], lang["native_name"], lang["script"])
Ruby
# Public and cacheable: no API key needed.
require "json"
require "net/http"

API = "https://api.lingivio.com"

JSON.parse(Net::HTTP.get(URI("#{API}/v1/formats")))["data"].each do |f|
  puts [f["format"], f["extensions"].join(","), f["max_bytes"]].join(" ")
end

# The target languages a PDF can be translated into (drop ?format= for every language).
JSON.parse(Net::HTTP.get(URI("#{API}/v1/languages?format=pdf")))["data"].each do |lang|
  puts [lang["code"], lang["name"], lang["native_name"], lang["script"]].join(" ")
end
Go
// Public and cacheable: no API key needed.
package main

import (
	"encoding/json"
	"fmt"
	"net/http"
)

const api = "https://api.lingivio.com"

func get(path string, into any) {
	res, err := http.Get(api + path)
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()
	if err := json.NewDecoder(res.Body).Decode(into); err != nil {
		panic(err)
	}
}

func main() {
	var formats struct {
		Data []struct {
			Format     string   `json:"format"`
			Extensions []string `json:"extensions"`
			MaxBytes   int64    `json:"max_bytes"`
		} `json:"data"`
	}
	get("/v1/formats", &formats)
	for _, f := range formats.Data {
		fmt.Println(f.Format, f.Extensions, f.MaxBytes)
	}

	// The target languages a PDF can be translated into (drop ?format= for every language).
	var languages struct {
		Data []struct {
			Code       string `json:"code"`
			Name       string `json:"name"`
			NativeName string `json:"native_name"`
			Script     string `json:"script"`
		} `json:"data"`
	}
	get("/v1/languages?format=pdf", &languages)
	for _, l := range languages.Data {
		fmt.Println(l.Code, l.Name, l.NativeName, l.Script)
	}
}
cURL
# Public and cacheable: no API key needed.
API="https://api.lingivio.com"

curl -s "$API/v1/formats" | jq -r '.data[] | "\(.format) \(.extensions | join(",")) \(.max_bytes)"'

# The target languages a PDF can be translated into (drop ?format= for every language).
curl -s "$API/v1/languages?format=pdf" | jq -r '.data[] | "\(.code) \(.name) \(.native_name) \(.script)"'

Τεκμηρίωση αναφοράς τελικών σημείων

Κάθε λειτουργία του API, από το ίδιο έγγραφο OpenAPI που διαβάζει η γεννήτρια κώδικα πελάτη σας. Οι διαδρομές είναι σχετικές με το παραπάνω βασικό URL.

Files

POST /v1/files Δέχεται Idempotency-Key

Upload a file (single shot)

Upload a document as multipart/form-data with the bytes in a file part. The response carries the file's VALIDATED content type (read from the bytes, not the extension), its detected source language and its real billing page count, so a job can be priced before it is started. Bodies above 25 MiB must use the resumable path (POST /v1/files/uploads).

Σώμα αιτήματος

multipart/form-data

Αποκρίσεις

  • 201 the stored file PublicFile
  • 400 malformed request
  • 403 a plan without API access, or an unconfirmed address ErrorEnvelope
  • 409 the idempotency key is in use for a different body (`idempotency_conflict`) or by a request still running (`idempotency_in_progress`); or the file was deleted while it was being stored (`upload_expired`): nothing is kept, the key is released, and a retry under the same key is a fresh upload
  • 413 over a size or storage limit ErrorEnvelope
  • 415 unsupported format, or the bytes are not what the name claims ErrorEnvelope
  • 422 corrupt, encrypted or rejected content ErrorEnvelope
  • 429 rate limited
POST /v1/files/uploads

Start a resumable upload

Begin a multi-part upload for a large input. Upload each part with PUT /v1/files/uploads/{uploadId}/parts/{number}, then POST .../complete. Every part except the last must be exactly min_part_bytes.

Σώμα αιτήματος

application/json

Αποκρίσεις

  • 201 the open session PublicUploadSession
  • 400 malformed request
  • 403 a plan without API access, or an unconfirmed address ErrorEnvelope
  • 413 over a size or storage limit ErrorEnvelope
  • 415 unsupported format ErrorEnvelope
  • 429 rate limited
PUT /v1/files/uploads/{uploadId}/parts/{number}

Upload one part

Store one part of a resumable upload. The body is the raw bytes of the part. Re-uploading a part number REPLACES it, so an interrupted client resends only what is missing. The parts together may not exceed the session's declared_bytes.

Παράμετροι

  • uploadId string διαδρομή υποχρεωτική
  • number string διαδρομή υποχρεωτική

Σώμα αιτήματος

application/octet-stream

Αποκρίσεις

  • 200 the stored part
  • 400 bad part number, or an empty body
  • 404 no such session for this caller
  • 409 the session is closed or expired, its reserved file was already removed, or the same part number is still being stored (`part_in_flight`)
  • 413 the parts would exceed the declared size ErrorEnvelope
POST /v1/files/uploads/{uploadId}/complete

Complete a resumable upload

Assemble the parts, run the content-based intake gate, count pages and detect the source language. Safe to retry: a completed session answers with the file it produced.

Παράμετροι

  • uploadId string διαδρομή υποχρεωτική

Αποκρίσεις

  • 201 the stored file PublicFile
  • 404 no such session for this caller
  • 409 no parts, the part sizes are invalid, a part is still being stored (`part_in_flight`), or the session expired (its reserved file was removed)
  • 413 over a size limit, or larger than the declared size ErrorEnvelope
  • 415 the bytes are not what the name claims ErrorEnvelope
  • 422 corrupt, encrypted or rejected content ErrorEnvelope
DELETE /v1/files/uploads/{uploadId}

Abandon a resumable upload

Abort the R2 upload and release the reserved file id. Idempotent.

Παράμετροι

  • uploadId string διαδρομή υποχρεωτική

Αποκρίσεις

  • 200 aborted
  • 404 no such session for this caller
GET /v1/files

List uploaded files

The caller's files that are still inside the 24h retention window, newest first.

Αποκρίσεις

  • 200 a page of files
  • 403 a plan without API access, or an unconfirmed address ErrorEnvelope
GET /v1/files/{id}

Read one file

Fetch a file's metadata. A file belonging to another account answers 404 — never 403 — so an id cannot be used to probe other tenants.

Παράμετροι

  • id string διαδρομή υποχρεωτική

Αποκρίσεις

  • 200 the file PublicFile
  • 404 no such file for this caller
DELETE /v1/files/{id}

Delete a file early

Remove the stored bytes before the 24h retention deadline. The row survives while a translation still references it, so job history stays intact. Deleting a file still being uploaded in parts ends that upload: the parts already sent are discarded and the upload session answers upload_closed.

Παράμετροι

  • id string διαδρομή υποχρεωτική

Αποκρίσεις

  • 200 deleted
  • 404 no such file for this caller

Translations

POST /v1/translations Δέχεται Idempotency-Key

Translate an uploaded file

Start an asynchronous translation of a file uploaded through POST /v1/files. Credits are reserved from the engine's own page count — never from anything in this request. Send Idempotency-Key to make a retry safe: a replay resolves to the job the first call created and bills once. Attach a callback_url to be told when the job finishes instead of polling: this API POSTs one JSON notification per terminal state (done, failed, canceled) to that https URL, signed Lingivio-Signature: ts=<epoch seconds>;h1=<hex HMAC-SHA256 of "${ts}:${rawBody}"> with your account's signing secret, and identified by a stable Lingivio-Event-Id — verify the signature, reject a timestamp outside your own tolerance, and dedupe on the event id, because a retry repeats the same id and the same bytes. Delivery is retried on a bounded backoff until your endpoint answers 2xx.

Σώμα αιτήματος

application/json PublicTranslationRequest

Αποκρίσεις

  • 201 the queued translation PublicTranslation
  • 400 malformed request, or an unsupported target language
  • 402 not enough page credits
  • 403 a plan without API access, or an unconfirmed address ErrorEnvelope
  • 404 no such file or glossary for this caller
  • 409 the idempotency key is in use for a different body
  • 413 over the per-job page ceiling ErrorEnvelope
  • 422 the document could not be processed ErrorEnvelope
  • 429 rate limited, or the concurrency limit is reached
  • 503 translation is paused, or the page count is unavailable
POST /v1/translations/batches Δέχεται Idempotency-Key

Translate several files as one batch

Start translations for up to 20 already-uploaded files as ONE act. The credits for the whole batch are reserved atomically, so a batch can never half-run out of credits partway through; members are held pending and start as the plan's concurrency allows, so a batch queues behind the limit instead of bypassing it. A file that fails its own gate is reported in rejected and costs nothing — it never fails the batch. Send Idempotency-Key to make a retry safe: a replay resolves to the batch the first call created and bills once.

Σώμα αιτήματος

application/json PublicTranslationBatchRequest

Αποκρίσεις

  • 201 the created batch PublicTranslationBatch
  • 400 malformed request, or more than 20 files
  • 402 not enough page credits for the whole batch
  • 403 a plan without API access, or an unconfirmed address ErrorEnvelope
  • 409 the idempotency key is in use for a different body
  • 422 no file in the batch could be processed
  • 429 rate limited
  • 503 translation is paused
GET /v1/translations/batches/{id}/output

Download a batch as a zip

Stream every FINISHED member of the batch as one zip archive. X-Batch-Files reports how many members the archive contains and X-Batch-Total how many the batch has, so a partial download is visible without unzipping it.

Παράμετροι

  • id string διαδρομή υποχρεωτική

Αποκρίσεις

  • 200 the archive
  • 404 no such batch for this caller
  • 409 no member of the batch has finished yet
GET /v1/translations/batches/{id}

Read one batch

Per-file status, per-file error class and REAL per-file segment counts. There is deliberately no single batch status: progress carries the counts and each entry carries its own outcome, because one word over N documents cannot be honest.

Παράμετροι

  • id string διαδρομή υποχρεωτική

Αποκρίσεις

  • 200 the batch PublicTranslationBatch
  • 404 no such batch for this caller
GET /v1/translations

List translations

The caller's translations, newest first, with status, page counts and error class.

Αποκρίσεις

  • 200 a page of translations
  • 403 a plan without API access, or an unconfirmed address ErrorEnvelope
GET /v1/translations/{id}/output

Download the translated document

Stream the finished document. ?variant=dual serves the bilingual side-by-side PDF when the job produced one (output.variants says whether it did).

Παράμετροι

  • id string διαδρομή υποχρεωτική
  • variant mono | dual ερώτημα προαιρετική which output to download

Αποκρίσεις

  • 200 the translated document
  • 404 no such translation, or that variant was not produced
  • 409 the translation has not finished
POST /v1/translations/{id}/cancel

Cancel a translation

Stop a translation that has not finished. A queued job is cancelled immediately; a running one enters cancel_requested and holds its reserve until the engine confirms compute stopped. Retrying a cancel is not an error.

Παράμετροι

  • id string διαδρομή υποχρεωτική

Αποκρίσεις

  • 200 the updated translation PublicTranslation
  • 404 no such translation for this caller
  • 409 the translation is already finished
DELETE /v1/translations/{id}

Delete a translation's documents early

Remove a finished translation's documents before the 24h retention deadline: every translated output at once, and the original upload by the rules DELETE /v1/files/{id} applies — it stays while another translation of the same upload is still running. The translation itself stays as history and reports output.available: false. A translation that has not finished is refused with job_in_flight — cancel it first. Idempotent: a repeat answers with the time of the first delete.

Παράμετροι

  • id string διαδρομή υποχρεωτική

Αποκρίσεις

  • 200 deleted
  • 403 a plan without API access, or an unconfirmed address ErrorEnvelope
  • 404 no such translation for this caller
  • 409 the translation has not finished, a cancel included (`job_in_flight`, with its current `status`)
GET /v1/translations/{id}

Read one translation

Status and REAL segment progress. progress.done/progress.total are the engine's own counts — there is no synthesised percentage.

Παράμετροι

  • id string διαδρομή υποχρεωτική

Αποκρίσεις

  • 200 the translation PublicTranslation
  • 404 no such translation for this caller

Discovery

GET /v1/languages

List the supported target languages

Every language a translation can be asked for, with its English and native names, its ISO 15924 script and writing direction, and the file formats it is a valid target_language for. Regional variants (pt-br, zh-hant) follow their base language and are supported wherever it is. The source language is detected from the document; source_language on a translation overrides it. Public: no key or plan is needed, and the answer may be cached.

Παράμετροι

  • format string ερώτημα προαιρετική only the languages a file of this format can be translated into — a format or an extension as GET /v1/formats lists it (`pdf`, `jpeg`). An unknown one is refused with `file.unsupported_format`.

Αποκρίσεις

  • 200 the target languages PublicLanguageList
  • 415 the `format` filter names no supported format ErrorEnvelope
GET /v1/formats

List the supported file formats

Every file format an upload can be in: the extensions it is recognised by, its size ceiling, how it is counted in credits, the target languages it takes, and for each plan whether the plan includes it and the largest such file the plan accepts. Read from the tables the api enforces at upload, so a format listed here is one POST /v1/files accepts. Public: no key or plan is needed, and the answer may be cached.

Αποκρίσεις

  • 200 the file formats PublicFormatList

Κλάσεις σφαλμάτων

Κάθε αποτυχία περιλαμβάνει μια σταθερή κλάση, μια ένδειξη δυνατότητας επανάληψης και την κατάσταση των δεσμευμένων πιστώσεών σας. Διακλαδώστε τη ροή βάσει της κλάσης, ποτέ βάσει του κειμένου του μηνύματος.

Κλάση Κατάσταση Δυνατότητα επανάληψης Πιστώσεις
file.too_large 413 Όχι release
file.too_many_pages 413 Όχι release
file.unsupported_format 415 Όχι release
file.type_mismatch 415 Όχι release
file.corrupt 422 Όχι release
file.password_protected 422 Όχι release
file.zip_bomb 422 Όχι release
file.malware_detected 422 Όχι release
file.pagination_unavailable 422 Όχι release
file.too_complex 422 Όχι release
storage.quota_exceeded 413 Όχι release
content.policy_violation 422 Όχι release
scan.unavailable 503 Ναι release
account.suspended 403 Όχι release
account.onboarding_required 403 Όχι none
pdf.no_text_layer 422 Όχι release
pdf.too_many_scanned_pages 413 Όχι release
pdf.encrypted 422 Όχι release
ocr.failed 422 Όχι release
llm.provider_down 503 Ναι hold
llm.provider_unavailable 503 Ναι release
llm.invalid_response 502 Όχι release
verify.invariant_failed 422 Όχι release
engine.timeout 504 Ναι hold
engine.oom 500 Ναι hold
engine.unexpected 500 Όχι hold
privacy.export_rate_limited 429 Ναι none
privacy.deletion_confirmation_failed 400 Όχι none
privacy.consent_invalid 400 Όχι none
auth.email_unverified 403 Όχι none
auth.captcha_required 400 Ναι none
auth.captcha_failed 403 Ναι none
auth.verification_token_invalid 400 Όχι none
auth.verification_token_expired 410 Ναι none
auth.account_link_denied 403 Όχι none
auth.api_key_not_accepted 403 Όχι none
email.send_failed 502 Ναι none
plan.api_access_required 403 Όχι none
plan.format_not_included 403 Όχι none
plan.file_too_large 413 Όχι none
plan.batch_not_included 403 Όχι none
plan.team_not_included 403 Όχι none
plan.mcp_access_required 403 Όχι none
credits.partial_unavailable 402 Όχι none
spend.ceiling_reached 503 Ναι none
spend.unavailable 503 Ναι none
ops.dispatch_halted 503 Ναι release
webhook.callback_url_invalid 400 Όχι none
team.invite_email_invalid 400 Όχι none
team.invite_disposable_address 400 Όχι none
team.invite_own_address 409 Όχι none
team.invitee_already_member 409 Όχι none
team.seat_limit_reached 409 Όχι none
team.invite_invalid 410 Όχι none
team.invite_email_mismatch 403 Όχι none
team.already_in_team 409 Όχι none
team.seats_exceed_plan 409 Όχι none
team.not_found 404 Όχι none
team.invite_rate_limited 429 Ναι none
team.workspace_unavailable 403 Όχι none
billing.subscription_set_to_end 409 Όχι none
billing.code_invalid 400 Όχι none
billing.code_use_at_checkout 409 Όχι none
billing.code_new_subscription_only 409 Όχι none
billing.code_price_changed 409 Όχι none
billing.comp_unavailable 409 Όχι none
billing.comp_active 409 Όχι none
glossary.language_mismatch 422 Όχι none

Όρια ρυθμού αιτημάτων

Τα όρια ισχύουν ανά κλειδί, σε σταθερό χρονικό παράθυρο 60 δευτερολέπτων. Κάθε απόκριση περιλαμβάνει X-RateLimit-Limit και X-RateLimit-Remaining. Μια απόκριση 429 περιλαμβάνει Retry-After. Δύο κλειδιά σε έναν λογαριασμό έχουν δύο ξεχωριστά όρια.

Ταυτοδυναμία

Στείλτε Idempotency-Key σε κάθε POST. Το ίδιο κλειδί με το ίδιο σώμα επιστρέφει τον πόρο που δημιούργησε η πρώτη κλήση και χρεώνεται ακριβώς μία φορά. Το ίδιο κλειδί με διαφορετικό σώμα απορρίπτεται με 409. Τα κλειδιά διατηρούνται για 24 ώρες.

Διαχείριση εκδόσεων

Το /v1 είναι σταθερό. Νέα πεδία, νέες προαιρετικές παράμετροι και νέες κλάσεις σφαλμάτων μπορούν να εμφανιστούν οποιαδήποτε στιγμή. Αγνοήστε ό,τι δεν αναγνωρίζετε. Μια ασύμβατη αλλαγή λαμβάνει νέο πρόθεμα. Το /v1 συνεχίζει τότε να εξυπηρετείται για τουλάχιστον 12 μήνες, με κεφαλίδα Sunset σε κάθε απόκριση.

Μηχανικά αναγνώσιμη προδιαγραφή

Το έγγραφο OpenAPI 3.1 δημιουργείται από τα ίδια σχήματα βάσει των οποίων επικυρώνει ο διακομιστής. Δώστε το στη γεννήτρια κώδικα πελάτη σας.

Λήψη openapi.json

Δοκιμάστε το

Μεταφορτώστε ένα πραγματικό έγγραφο με το δικό σας κλειδί και παρακολουθήστε την πραγματική ακολουθία αιτημάτων. Τίποτα εδώ δεν είναι προσομοίωση.
Αυτό εκτελεί μια πραγματική μετάφραση και δαπανά πραγματικές πιστώσεις από το υπόλοιπό σας.
1. ΚλειδίΤο κλειδί σας παραμένει μόνο σε αυτή την καρτέλα του προγράμματος περιήγησης. Δεν αποθηκεύεται ποτέ, δεν τοποθετείται ποτέ στη γραμμή διευθύνσεων και δεν αποστέλλεται πουθενά εκτός από το API.
2. ΜεταφόρτωσηPOST /v1/files — η απόκριση σας ενημερώνει για τον επαληθευμένο τύπο, τη γλώσσα που εντοπίστηκε και το κόστος σε πιστώσεις.
3. ΜετάφρασηPOST /v1/translations — ασύγχρονα, με κλειδί ταυτοδυναμίας ώστε η επανάληψη να μην μπορεί να προκαλέσει διπλή χρέωση.

Λάβετε νέα του προϊόντος μέσω email

Νέες γλώσσες και τύποι αρχείων, συμβουλές μετάφρασης και ενημερώσεις για προγραμματιστές.

Εγγραφή

Τα cookies για ανάλυση και εξατομικευμένες διαφημίσεις λειτουργούν μόνο αν τα αποδεχτείτε. Πολιτική cookies