Ocriva Logo

Documents

Resources

เอกสารอ้างอิง method ครบถ้วนสำหรับ resource upload, templates, projects, processing history และ batch

sdkresourcesreferenceapi

Published: 4/1/2026

Resources

OcrivaClient เปิดให้ใช้งาน resource object ทั้งหมด 5 รายการ แต่ละ resource รวม API method ที่เกี่ยวข้องไว้ด้วยกัน และจัดการ serialization, authentication และ error mapping ให้คุณโดยอัตโนมัติ

ResourcePropertyDescription
Uploadclient.uploadอัปโหลดไฟล์สำหรับการประมวลผล OCR
Templatesclient.templatesสร้างและจัดการ extraction template
Projectsclient.projectsดึงข้อมูล project ที่เข้าถึงได้
Processing Historyclient.processingHistoryเข้าถึงผลลัพธ์และสถิติ OCR
Batchclient.batchอัปโหลดและติดตามหลายไฟล์พร้อมกัน

Upload

อัปโหลดไฟล์

อัปโหลดไฟล์เดียวสำหรับการประมวลผล OCR SDK รองรับ browser File, Blob หรือ Node.js Buffer / Uint8Array

async file(
  file: File | Blob | Uint8Array,
  params: UploadFileParams,
): Promise<UploadResponse>

Parameters

ParameterTypeRequiredDescription
fileFile | Blob | Uint8ArrayYesไฟล์ binary ที่จะอัปโหลด
params.fileNamestringYesชื่อที่แสดงของไฟล์
params.fileTypeFileTypeYesประเภทหลัก: 'pdf', 'image' หรือ 'document'
params.fileSizestringYesขนาดไฟล์ในหน่วยไบต์ในรูปแบบ string
params.mimeTypestringYesMIME type เช่น 'application/pdf'
params.projectIdstringYesProject ที่จะเชื่อมกับการอัปโหลดนี้
params.templateIdstringNoTemplate ที่จะใช้ระหว่างการประมวลผล
params.batchIdstringNoเพิ่มไฟล์นี้เข้า batch ที่มีอยู่แล้ว
params.uploadTypestringNohint ประเภทการอัปโหลด (optional)
params.metadataRecord<string, unknown>Nometadata แบบ key-value ที่กำหนดเอง

Examples

อัปโหลด File object จาก browser <input>:

import { OcrivaClient } from '@ocriva/sdk';
 
const client = new OcrivaClient({ apiKey: process.env.OCRIVA_API_KEY! });
 
async function handleFileInput(file: File) {
  const result = await client.upload.file(file, {
    fileName: file.name,
    fileType: 'pdf',
    fileSize: String(file.size),
    mimeType: file.type,
    projectId: 'proj_abc123',
  });
 
  console.log('Upload ID:', result.id);
  console.log('Status:', result.status);
}

อัปโหลด Buffer ใน Node.js:

import { readFileSync } from 'node:fs';
 
const buffer = readFileSync('./receipt.jpg');
 
const result = await client.upload.file(buffer, {
  fileName: 'receipt.jpg',
  fileType: 'image',
  fileSize: String(buffer.byteLength),
  mimeType: 'image/jpeg',
  projectId: 'proj_abc123',
  templateId: 'tmpl_xyz789',
});

อัปโหลด Blob พร้อม custom metadata:

const response = await fetch('https://example.com/document.pdf');
const blob = await response.blob();
 
const result = await client.upload.file(blob, {
  fileName: 'document.pdf',
  fileType: 'pdf',
  fileSize: String(blob.size),
  mimeType: 'application/pdf',
  projectId: 'proj_abc123',
  metadata: { source: 'crm', customerId: 'cust_999' },
});

Response shape (UploadResponse)

{
  id: string;
  fileName: string;
  fileUrl: string;
  publicUrl: string;
  filePath: string;
  fileSize: string;
  mimeType: string;
  status: 'uploaded' | 'processing' | 'completed' | 'failed';
  templateId?: string;
  projectId: string;
  uploadedAt: string;
  userId: string;
  organizationId?: string;
  bucketName?: string;
}

Templates

รายการ Templates

แสดงรายการ template ทั้งหมดที่ token ปัจจุบันเข้าถึงได้

async list(params?: ListTemplatesParams): Promise<Template[]>

Parameters

ParameterTypeRequiredDescription
params.projectIdstringNoกรองตาม project ID
params.pagenumberNoหมายเลขหน้า (เริ่มต้นที่ 1)
params.limitnumberNoจำนวน item ต่อหน้า
// List all templates
const templates = await client.templates.list();
 
// Filter by project with pagination
const page1 = await client.templates.list({
  projectId: 'proj_abc123',
  page: 1,
  limit: 20,
});
 
console.log(`Found ${page1.length} templates`);

สร้าง Template

สร้าง extraction template ใหม่

async create(params: CreateTemplateParams): Promise<Template>

Parameters

ParameterTypeRequiredDescription
params.namestringYesชื่อ template
params.descriptionstringYesคำอธิบาย template
params.templateSchemaRecord<string, unknown>YesJSON schema ที่กำหนดฟิลด์ที่จะดึงข้อมูล
params.projectIdstringYesProject ที่ template นี้เป็นของ
params.instructionsstringNoคำแนะนำ AI assistant ที่กำหนดเอง
const template = await client.templates.create({
  name: 'Invoice Template',
  description: 'Extracts line items, totals, and vendor information from invoices',
  projectId: 'proj_abc123',
  templateSchema: {
    type: 'object',
    properties: {
      invoiceNumber: { type: 'string', description: 'Invoice number' },
      vendorName: { type: 'string', description: 'Vendor or supplier name' },
      totalAmount: { type: 'number', description: 'Total invoice amount' },
      dueDate: { type: 'string', description: 'Payment due date (YYYY-MM-DD)' },
      lineItems: {
        type: 'array',
        items: {
          type: 'object',
          properties: {
            description: { type: 'string' },
            quantity: { type: 'number' },
            unitPrice: { type: 'number' },
          },
        },
      },
    },
  },
  instructions: 'Extract all monetary values as numbers without currency symbols.',
});
 
console.log('Template ID:', template.templateId);

อัปเดต Template

อัปเดต template ที่มีอยู่ ทุกฟิลด์ยกเว้น projectId เป็น optional

async update(id: string, params: UpdateTemplateParams): Promise<Template>

Parameters

ParameterTypeRequiredDescription
idstringYesTemplate ID ที่จะอัปเดต
params.projectIdstringYesProject ID (ใช้กำหนดขอบเขตการอัปเดต)
params.namestringNoชื่อ template ใหม่
params.descriptionstringNoคำอธิบายใหม่
params.templateSchemaRecord<string, unknown>NoJSON schema ที่อัปเดต
params.instructionsstringNoคำแนะนำ AI ที่อัปเดต
// Partial update — only change the instructions
const updated = await client.templates.update('tmpl_xyz789', {
  projectId: 'proj_abc123',
  instructions: 'Always return amounts in USD. If currency is not USD, convert it.',
});

ลบ Template

Soft-delete template โดย template จะไม่ active และไม่สามารถใช้กับการอัปโหลดใหม่ได้

async delete(id: string): Promise<void>
await client.templates.delete('tmpl_xyz789');
// Returns void — no response body

อัปโหลด Data File

แนบไฟล์ข้อมูล (JSON, Markdown หรือ plain text) เข้ากับ template AI ใช้ไฟล์นี้เป็น context เพิ่มเติมระหว่างการดึงข้อมูล

async uploadFile(templateId: string, file: File | Blob): Promise<Template>
import { readFileSync } from 'node:fs';
 
// Attach a reference schema as a Markdown file
const mdContent = readFileSync('./field-guide.md');
const blob = new Blob([mdContent], { type: 'text/markdown' });
 
const updatedTemplate = await client.templates.uploadFile('tmpl_xyz789', blob);
console.log('Attached files:', updatedTemplate.templateId);

ลบ Data File

ลบไฟล์ข้อมูลที่แนบออกจาก template

async deleteFile(templateId: string, fileId: string): Promise<Template>
const updatedTemplate = await client.templates.deleteFile(
  'tmpl_xyz789',
  'file_abc456',
);

Projects

รายการ Projects

แสดงรายการ project ที่ token ปัจจุบันเข้าถึงได้

  • Project token: คืน project เดียวที่ token ผูกไว้
  • Organization token: คืน project ทั้งหมดใน organization
async list(params?: ListProjectsParams): Promise<Project[]>

Parameters

ParameterTypeRequiredDescription
params.projectIdstringNoกรองเฉพาะ project ที่ระบุ (สำหรับ organization token)
// List all accessible projects
const projects = await client.projects.list();
 
for (const project of projects) {
  console.log(`${project.id}: ${project.name} (active: ${project.isActive})`);
}
 
// Scope to one project using an organization token
const filtered = await client.projects.list({ projectId: 'proj_abc123' });

Response shape (Project)

{
  id: string;
  name: string;
  description?: string;
  organizationId: string;
  isActive: boolean;
  createdAt: string;
  updatedAt: string;
}

Processing History

รายการประวัติการประมวลผล

แสดงรายการ processing history record พร้อมตัวกรองและ pagination ตามต้องการ

async list(
  params?: ListProcessingHistoryParams,
): Promise<PaginatedResponse<ProcessingHistory>>

Parameters

ParameterTypeRequiredDescription
params.projectIdstringNoProject ID (จำเป็นสำหรับ organization token)
params.statusProcessingStatusNoกรองตาม status
params.templateIdstringNoกรองตาม template
params.priorityProcessingPriorityNoกรองตาม priority
params.searchstringNoค้นหาตามชื่อไฟล์หรือชื่อ template
params.fromDatestringNoตัวกรองวันเริ่มต้น (YYYY-MM-DD)
params.toDatestringNoตัวกรองวันสิ้นสุด (YYYY-MM-DD)
params.batchIdstringNoกรองตาม batch ID
params.pagenumberNoหมายเลขหน้า (เริ่มต้นที่ 1)
params.limitnumberNoจำนวน item ต่อหน้า
// List completed records for a project
const result = await client.processingHistory.list({
  projectId: 'proj_abc123',
  status: 'completed',
  page: 1,
  limit: 50,
});
 
console.log(`Page ${result.pagination.page} of ${result.pagination.pages}`);
console.log(`Total records: ${result.pagination.total}`);
 
for (const record of result.data) {
  console.log(`${record.id}: ${record.fileName} — ${record.status}`);
}
 
// Filter by date range
const recent = await client.processingHistory.list({
  projectId: 'proj_abc123',
  fromDate: '2026-03-01',
  toDate: '2026-03-31',
});
 
// Filter by template
const byTemplate = await client.processingHistory.list({
  projectId: 'proj_abc123',
  templateId: 'tmpl_xyz789',
  status: 'failed',
});

ดูรายละเอียด

ดึง processing history record เดียวตาม ID

async get(id: string, projectId?: string): Promise<ProcessingHistory>
const record = await client.processingHistory.get(
  'hist_abc123',
  'proj_abc123', // required for organization tokens
);
 
console.log('Status:', record.status);
console.log('Result:', record.processingResult);

Export ผลลัพธ์

ดาวน์โหลดผลลัพธ์การประมวลผลในรูปแบบ Blob ตามรูปแบบที่ระบุ

async getResult(id: string, params?: ExportResultParams): Promise<Blob>

Parameters

ParameterTypeRequiredDescription
idstringYesID ของ processing history record
params.formatstringNoรูปแบบ output: 'json', 'text', 'xml', 'html', 'csv', 'pdf', 'docx'
params.projectIdstringNoProject ID (จำเป็นสำหรับ organization token)
// Download as JSON and parse
const blob = await client.processingHistory.getResult('hist_abc123', {
  format: 'json',
  projectId: 'proj_abc123',
});
const data = JSON.parse(await blob.text());
console.log(data);
 
// Download as PDF and save to disk (Node.js)
import { writeFileSync } from 'node:fs';
 
const pdfBlob = await client.processingHistory.getResult('hist_abc123', {
  format: 'pdf',
  projectId: 'proj_abc123',
});
const arrayBuffer = await pdfBlob.arrayBuffer();
writeFileSync('./result.pdf', Buffer.from(arrayBuffer));
 
// Download as CSV
const csvBlob = await client.processingHistory.getResult('hist_abc123', {
  format: 'csv',
  projectId: 'proj_abc123',
});
const csv = await csvBlob.text();
console.log(csv);

ดูสถิติ

ดึงสถิติการประมวลผลแบบรวมสำหรับ project

async stats(params: { projectId: string }): Promise<ProcessingHistoryStats>
const stats = await client.processingHistory.stats({
  projectId: 'proj_abc123',
});
 
console.log('Total:', stats.total);
console.log('Pending:', stats.pending);
console.log('Processing:', stats.processing);
console.log('Completed:', stats.completed);
console.log('Failed:', stats.failed);

Response shape (ProcessingHistoryStats)

{
  total: number;
  pending: number;
  processing: number;
  completed: number;
  failed: number;
}

Batch

ใช้ batch resource เพื่ออัปโหลดและติดตามหลายไฟล์ในรูปแบบ job เดียว แต่ละไฟล์ประมวลผลแยกกัน โดย batch record ติดตามความคืบหน้าโดยรวมและช่วยให้คุณ export ผลลัพธ์ทั้งหมดได้ในครั้งเดียว

อัปโหลด Batch

อัปโหลดหลายไฟล์เป็น batch เดียว รองรับสูงสุด 50 ไฟล์ต่อ call

async upload(
  files: (File | Blob)[],
  params: BatchUploadParams,
): Promise<Batch>

Parameters

ParameterTypeRequiredDescription
files(File | Blob)[]YesArray ของไฟล์ที่จะอัปโหลด (สูงสุด 50)
params.projectIdstringYesProject ที่จะเชื่อมกับ batch นี้
params.templateIdstringNoTemplate ที่จะใช้กับทุกไฟล์
params.namestringNoชื่อ batch (สร้างอัตโนมัติหากไม่ระบุ)
params.metadataRecord<string, unknown>Nometadata แบบ key-value ที่กำหนดเอง
import { readFileSync } from 'node:fs';
 
const files = ['invoice-01.pdf', 'invoice-02.pdf', 'invoice-03.pdf'].map(
  (name) => {
    const buffer = readFileSync(`./${name}`);
    return new File([buffer], name, { type: 'application/pdf' });
  },
);
 
const batch = await client.batch.upload(files, {
  projectId: 'proj_abc123',
  templateId: 'tmpl_xyz789',
  name: 'March Invoices',
  metadata: { month: 'march', year: '2026' },
});
 
console.log('Batch ID:', batch.id);
console.log('Total files:', batch.totalFiles);
console.log('Status:', batch.status);

รายการ Batches

แสดงรายการ batch พร้อมตัวกรองและ pagination ตามต้องการ

async list(params?: ListBatchParams): Promise<PaginatedResponse<Batch>>

Parameters

ParameterTypeRequiredDescription
params.projectIdstringNoProject ID (จำเป็นสำหรับ organization token)
params.statusBatchStatusNoกรองตาม status
params.pagenumberNoหมายเลขหน้า (เริ่มต้นที่ 1)
params.limitnumberNoจำนวน item ต่อหน้า
const result = await client.batch.list({
  projectId: 'proj_abc123',
  status: 'completed',
  page: 1,
  limit: 10,
});
 
console.log(`Total batches: ${result.pagination.total}`);
for (const batch of result.data) {
  console.log(`${batch.id}: ${batch.name} — ${batch.progress}% complete`);
}

รายละเอียด Batch

ดึง batch เดียวตาม ID พร้อมความคืบหน้าปัจจุบัน

async get(batchId: string): Promise<Batch>
const batch = await client.batch.get('batch_abc123');
 
console.log('Status:', batch.status);
console.log('Progress:', batch.progress, '%');
console.log(`${batch.completedFiles} / ${batch.totalFiles} files done`);
console.log('Failed:', batch.failedFiles);

Response shape (Batch)

{
  id: string;
  name: string;
  projectId: string;
  organizationId: string;
  userId: string;
  templateId?: string;
  templateName?: string;
  totalFiles: number;
  completedFiles: number;
  failedFiles: number;
  status: BatchStatus; // 'uploading' | 'processing' | 'completed' | 'partially_failed' | 'failed'
  uploadIds: string[];
  processingHistoryIds: string[];
  progress: number; // 0–100
  metadata?: Record<string, unknown>;
  createdAt: string;
  updatedAt: string;
}

Export ผลลัพธ์ Batch

Export ผลลัพธ์การประมวลผลที่เสร็จแล้วทั้งหมดของ batch เป็นไฟล์เดียว

async exportResults(batchId: string, params: ExportBatchParams): Promise<Blob>

Parameters

ParameterTypeRequiredDescription
batchIdstringYesBatch ID
params.formatstringYesรูปแบบ export: 'json', 'csv', 'text', 'xml', 'pdf', 'docx'
// Export as JSON and parse
const blob = await client.batch.exportResults('batch_abc123', {
  format: 'json',
});
const results = JSON.parse(await blob.text());
console.log(`Exported ${results.length} results`);
 
// Export as CSV and save (Node.js)
import { writeFileSync } from 'node:fs';
 
const csvBlob = await client.batch.exportResults('batch_abc123', {
  format: 'csv',
});
writeFileSync('./batch-results.csv', Buffer.from(await csvBlob.arrayBuffer()));