Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -442,6 +442,20 @@ const result = await extractTextFromFile('document.pdf', {
});
```

### Hindsight Inference

Iris also runs on [Hindsight Inference](https://inference.hindsight.vectorize.io), with the same API.
Point any client at its base URL and use a Hindsight Inference API key; no organization ID is needed
(the key identifies it):

```bash
export VECTORIZE_IRIS_BASE_URL="https://inference.hindsight.vectorize.io/v1"
export VECTORIZE_TOKEN="hsk_..." # your Hindsight Inference API key
```

Or per call: `base_url=` (Python), `baseUrl:` (Node.js), `--base-url` (CLI, or `base_url` in
`~/.vectorize-iris/credentials`). Requires Python SDK 0.2.0, Node.js SDK 0.2.0 or CLI 0.2.0.

## Documentation

For detailed documentation, API reference, and advanced features:
Expand Down
14 changes: 14 additions & 0 deletions nodejs-api/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,19 @@ export VECTORIZE_TOKEN="your-token"
export VECTORIZE_ORG_ID="your-org-id"
```

### Hindsight Inference

Iris also runs on [Hindsight Inference](https://inference.hindsight.vectorize.io). The API is the same;
point the SDK at its base URL and use a Hindsight Inference API key. No organization ID is needed (the
key identifies it):

```bash
export VECTORIZE_IRIS_BASE_URL="https://inference.hindsight.vectorize.io/v1"
export VECTORIZE_TOKEN="hsk_..." # your Hindsight Inference API key
```

Or per call: `extractTextFromFile('document.pdf', { apiToken: 'hsk_...', baseUrl: 'https://inference.hindsight.vectorize.io/v1' })`.

### Basic Usage

```typescript
Expand Down Expand Up @@ -370,6 +383,7 @@ Extract text from a buffer.
interface ExtractionOptions {
apiToken?: string; // Override env var
orgId?: string; // Override env var
baseUrl?: string; // API root (env VECTORIZE_IRIS_BASE_URL); no orgId needed
pollInterval?: number; // ms between checks (default: 2000)
timeout?: number; // max ms to wait (default: 300000)
type?: 'iris'; // Extraction type
Expand Down
2 changes: 1 addition & 1 deletion nodejs-api/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@vectorize-io/iris",
"version": "0.1.3",
"version": "0.2.0",
"description": "Simple text extraction from files using Vectorize Iris",
"repository": {
"type": "git",
Expand Down
72 changes: 48 additions & 24 deletions nodejs-api/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,19 +30,45 @@ export class VectorizeIrisError extends Error {
}
}

const DEFAULT_API_URL = 'https://api.vectorize.io';

/**
* The token and the API root requests go to. With a base URL (option or VECTORIZE_IRIS_BASE_URL)
* requests go to it as given and no organization ID is needed (Hindsight Inference takes it from
* the key); without one, to https://api.vectorize.io/v1/org/{orgId}.
*/
export function resolveEndpoint(
apiToken: string | undefined = process.env.VECTORIZE_TOKEN,
orgId: string | undefined = process.env.VECTORIZE_ORG_ID,
baseUrl: string | undefined = process.env.VECTORIZE_IRIS_BASE_URL
): { apiToken: string; baseUrl: string } {
if (baseUrl) {
if (!apiToken) {
throw new VectorizeIrisError('Missing credentials. Set VECTORIZE_TOKEN or pass apiToken in options.');
}
return { apiToken, baseUrl: baseUrl.replace(/\/+$/, '') };
}
if (!apiToken || !orgId) {
throw new VectorizeIrisError(
'Missing credentials. Set VECTORIZE_TOKEN and VECTORIZE_ORG_ID ' +
'environment variables or pass them in options.'
);
}
return { apiToken, baseUrl: `${DEFAULT_API_URL}/v1/org/${orgId}` };
}

/**
* Internal function to extract from file buffer
*/
async function _extractFromBuffer(
fileBuffer: Buffer,
fileName: string,
apiToken: string,
orgId: string,
baseUrl: string,
pollInterval: number,
timeout: number,
options: ExtractionOptions
): Promise<ExtractionResultData> {
const baseUrl = `https://api.vectorize.io/v1/org/${orgId}`;
const headers = {
'Authorization': `Bearer ${apiToken}`,
'Content-Type': 'application/json'
Expand Down Expand Up @@ -198,27 +224,26 @@ export async function extractText(
options: ExtractionOptions = {}
): Promise<ExtractionResultData> {
const {
apiToken = process.env.VECTORIZE_TOKEN,
orgId = process.env.VECTORIZE_ORG_ID,
apiToken,
orgId,
baseUrl,
pollInterval = 2000,
timeout = 300000,
type = 'iris',
...extractionOptions
} = options;

// Validate credentials
if (!apiToken || !orgId) {
throw new VectorizeIrisError(
'Missing credentials. Set VECTORIZE_TOKEN and VECTORIZE_ORG_ID ' +
'environment variables or pass them in options.'
);
}
const endpoint = resolveEndpoint(
apiToken ?? process.env.VECTORIZE_TOKEN,
orgId ?? process.env.VECTORIZE_ORG_ID,
baseUrl ?? process.env.VECTORIZE_IRIS_BASE_URL
);

return _extractFromBuffer(
fileBuffer,
fileName,
apiToken,
orgId,
endpoint.apiToken,
endpoint.baseUrl,
pollInterval,
timeout,
{ type, ...extractionOptions }
Expand Down Expand Up @@ -265,21 +290,20 @@ export async function extractTextFromFile(
options: ExtractionOptions = {}
): Promise<ExtractionResultData> {
const {
apiToken = process.env.VECTORIZE_TOKEN,
orgId = process.env.VECTORIZE_ORG_ID,
apiToken,
orgId,
baseUrl,
pollInterval = 2000,
timeout = 300000,
type = 'iris',
...extractionOptions
} = options;

// Validate credentials
if (!apiToken || !orgId) {
throw new VectorizeIrisError(
'Missing credentials. Set VECTORIZE_TOKEN and VECTORIZE_ORG_ID ' +
'environment variables or pass them in options.'
);
}
const endpoint = resolveEndpoint(
apiToken ?? process.env.VECTORIZE_TOKEN,
orgId ?? process.env.VECTORIZE_ORG_ID,
baseUrl ?? process.env.VECTORIZE_IRIS_BASE_URL
);

// Validate file exists
try {
Expand All @@ -295,8 +319,8 @@ export async function extractTextFromFile(
return _extractFromBuffer(
fileBuffer,
fileName,
apiToken,
orgId,
endpoint.apiToken,
endpoint.baseUrl,
pollInterval,
timeout,
{ type, ...extractionOptions }
Expand Down
8 changes: 7 additions & 1 deletion nodejs-api/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,14 @@ export interface ExtractionResult {
export interface ExtractionOptions {
/** Vectorize access token (defaults to VECTORIZE_TOKEN env var) */
apiToken?: string;
/** Organization ID (defaults to VECTORIZE_ORG_ID env var) */
/** Organization ID (defaults to VECTORIZE_ORG_ID env var); not needed with baseUrl */
orgId?: string;
/**
* API root that /files and /extraction hang off (defaults to the VECTORIZE_IRIS_BASE_URL env var,
* then https://api.vectorize.io/v1/org/{orgId}). For Hindsight Inference, where the key identifies
* the organization: https://inference.hindsight.vectorize.io/v1
*/
baseUrl?: string;
/** Milliseconds between status checks (default: 2000) */
pollInterval?: number;
/** Maximum milliseconds to wait for extraction (default: 300000) */
Expand Down
94 changes: 94 additions & 0 deletions nodejs-api/tests/baseUrl.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
/**
* Where requests go: api.vectorize.io/v1/org/{orgId} by default, or a base URL as given (Hindsight
* Inference, where the organization comes from the key and isn't in the path).
*/

import fetch from 'node-fetch';
import { extractText, resolveEndpoint, VectorizeIrisError } from '../src/index';

jest.mock('node-fetch');
const mockFetch = fetch as jest.MockedFunction<typeof fetch>;

const HINDSIGHT = 'https://inference.hindsight.vectorize.io/v1';
const UPLOAD_URL = 'https://storage.example.com/signed';
const DONE = {
ready: true,
data: { success: true, text: 'hello', chunks: ['hello'], metadata: null, usage: { irisPages: 1 }, error: null },
};

function reply(body: unknown, status = 200) {
return { ok: status < 400, status, json: async () => body, text: async () => JSON.stringify(body) } as never;
}

function fakeApi(): Array<{ method: string; url: string; auth?: string }> {
const calls: Array<{ method: string; url: string; auth?: string }> = [];
mockFetch.mockImplementation((async (url: string, init?: { method?: string; headers?: Record<string, string> }) => {
const method = init?.method ?? 'GET';
calls.push({ method, url, auth: init?.headers?.Authorization });
if (method === 'PUT') return reply({});
if (url.endsWith('/files')) return reply({ fileId: 'f1', uploadUrl: UPLOAD_URL });
if (url.endsWith('/extraction')) return reply({ message: 'Extraction started.', extractionId: 'e1' });
return reply(DONE);
}) as never);
return calls;
}

beforeEach(() => {
jest.clearAllMocks();
delete process.env.VECTORIZE_TOKEN;
delete process.env.VECTORIZE_ORG_ID;
delete process.env.VECTORIZE_IRIS_BASE_URL;
});

describe('resolveEndpoint', () => {
it('defaults to api.vectorize.io with the org', () => {
expect(resolveEndpoint('t', 'org-1', undefined)).toEqual({
apiToken: 't',
baseUrl: 'https://api.vectorize.io/v1/org/org-1',
});
});

it('uses a base URL as given, with no org', () => {
expect(resolveEndpoint('hsk_x', undefined, `${HINDSIGHT}/`)).toEqual({ apiToken: 'hsk_x', baseUrl: HINDSIGHT });
});

it('still needs the org without a base URL', () => {
expect(() => resolveEndpoint('t', undefined, undefined)).toThrow(/VECTORIZE_ORG_ID/);
});

it('always needs a token', () => {
expect(() => resolveEndpoint(undefined, undefined, HINDSIGHT)).toThrow(VectorizeIrisError);
});
});

describe('extractText', () => {
it('sends every call to the Hindsight base URL, without an org', async () => {
const calls = fakeApi();
const result = await extractText(Buffer.from('%PDF'), 'a.pdf', {
apiToken: 'hsk_x',
baseUrl: HINDSIGHT,
pollInterval: 0,
});
expect(result.text).toBe('hello');
expect(calls.filter((c) => c.method !== 'PUT').map((c) => [c.method, c.url])).toEqual([
['POST', `${HINDSIGHT}/files`],
['POST', `${HINDSIGHT}/extraction`],
['GET', `${HINDSIGHT}/extraction/e1`],
]);
expect(calls.filter((c) => c.method !== 'PUT').every((c) => c.auth === 'Bearer hsk_x')).toBe(true);
});

it('reads the base URL and key from the environment', async () => {
process.env.VECTORIZE_TOKEN = 'hsk_x';
process.env.VECTORIZE_IRIS_BASE_URL = HINDSIGHT;
const calls = fakeApi();
await extractText(Buffer.from('%PDF'), 'a.pdf', { pollInterval: 0 });
expect(calls[0].url).toBe(`${HINDSIGHT}/files`);
});

it('is unchanged by default', async () => {
const calls = fakeApi();
await extractText(Buffer.from('%PDF'), 'a.pdf', { apiToken: 't', orgId: 'org-1', pollInterval: 0 });
expect(calls[0].url).toBe('https://api.vectorize.io/v1/org/org-1/files');
});
});
13 changes: 13 additions & 0 deletions python-api/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,19 @@ export VECTORIZE_TOKEN="your-token"
export VECTORIZE_ORG_ID="your-org-id"
```

### Hindsight Inference

Iris also runs on [Hindsight Inference](https://inference.hindsight.vectorize.io). The API is the same;
point the SDK at its base URL and use a Hindsight Inference API key. No organization ID is needed (the
key identifies it):

```bash
export VECTORIZE_IRIS_BASE_URL="https://inference.hindsight.vectorize.io/v1"
export VECTORIZE_TOKEN="hsk_..." # your Hindsight Inference API key
```

Or per call: `extract_text_from_file("document.pdf", api_token="hsk_...", base_url="https://inference.hindsight.vectorize.io/v1")`.

### Basic Usage

```python
Expand Down
2 changes: 1 addition & 1 deletion python-api/pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "vectorize-iris"
version = "0.1.0"
version = "0.2.0"
description = "Simple text extraction from files using Vectorize Iris"
readme = "README.md"
requires-python = ">=3.10"
Expand Down
Loading
Loading