@coreviz/sdk 1.0.1 → 1.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -10,16 +10,19 @@ npm install @coreviz/sdk
10
10
 
11
11
  ## Configuration
12
12
 
13
- To use the AI features, you need a CoreViz API key.
14
- Set the `COREVIZ_API_KEY` environment variable in your project.
13
+ To use the AI features, you need to instantiate the `CoreViz` class with your API key.
15
14
 
16
- ```bash
17
- export COREVIZ_API_KEY=your_api_key_here
15
+ ```typescript
16
+ import { CoreViz } from '@coreviz/sdk';
17
+
18
+ const coreviz = new CoreViz({
19
+ apiKey: process.env.COREVIZ_API_KEY // or 'your_api_key_here'
20
+ });
18
21
  ```
19
22
 
20
23
  ## API Reference
21
24
 
22
- ### `describe(image)`
25
+ ### `coreviz.describe(image)`
23
26
 
24
27
  Generates a detailed text description of an image.
25
28
 
@@ -32,13 +35,11 @@ Generates a detailed text description of an image.
32
35
  **Example:**
33
36
 
34
37
  ```typescript
35
- import { describe } from '@coreviz/sdk';
36
-
37
- const description = await describe('https://example.com/image.jpg');
38
+ const description = await coreviz.describe('https://example.com/image.jpg');
38
39
  console.log(description);
39
40
  ```
40
41
 
41
- ### `tag(image, options)`
42
+ ### `coreviz.tag(image, options)`
42
43
 
43
44
  Analyzes an image and returns relevant tags or classifications based on a prompt.
44
45
 
@@ -57,9 +58,7 @@ Analyzes an image and returns relevant tags or classifications based on a prompt
57
58
  **Example:**
58
59
 
59
60
  ```typescript
60
- import { tag } from '@coreviz/sdk';
61
-
62
- const result = await tag('base64_image_string...', {
61
+ const result = await coreviz.tag('base64_image_string...', {
63
62
  prompt: "Is this indoor or outdoor?",
64
63
  options: ["indoor", "outdoor"],
65
64
  multiple: false
@@ -67,7 +66,7 @@ const result = await tag('base64_image_string...', {
67
66
  console.log(result.tags); // ["indoor"]
68
67
  ```
69
68
 
70
- ### `edit(image, options)`
69
+ ### `coreviz.edit(image, options)`
71
70
 
72
71
  Modifies an image based on a text prompt using generative AI.
73
72
 
@@ -85,17 +84,15 @@ Modifies an image based on a text prompt using generative AI.
85
84
  **Example:**
86
85
 
87
86
  ```typescript
88
- import { edit } from '@coreviz/sdk';
89
-
90
- const editedImage = await edit('https://example.com/photo.jpg', {
87
+ const editedImage = await coreviz.edit('https://example.com/photo.jpg', {
91
88
  prompt: "Make it look like a painting",
92
89
  aspectRatio: "1:1"
93
90
  });
94
91
  ```
95
92
 
96
- ### `resize(input, maxWidth?, maxHeight?)`
93
+ ### `coreviz.resize(input, maxWidth?, maxHeight?)`
97
94
 
98
- Utility function to resize images client-side or server-side before processing.
95
+ Utility function to resize images client-side or server-side before processing. Also available as a standalone import.
99
96
 
100
97
  **Parameters:**
101
98
  - `input` (string | File): The image to resize.
@@ -108,9 +105,8 @@ Utility function to resize images client-side or server-side before processing.
108
105
  **Example:**
109
106
 
110
107
  ```typescript
111
- import { resize } from '@coreviz/sdk';
112
-
113
- const resized = await resize(myFileObject, 800, 600);
108
+ const resized = await coreviz.resize(myFileObject, 800, 600);
109
+ // or import { resize } from '@coreviz/sdk';
114
110
  ```
115
111
 
116
112
  ## License
@@ -0,0 +1,41 @@
1
+ export interface CoreVizConfig {
2
+ apiKey?: string;
3
+ token?: string;
4
+ }
5
+ export interface DescribeOptions {
6
+ }
7
+ export interface EditOptions {
8
+ prompt: string;
9
+ aspectRatio?: 'match_input_image' | '1:1' | '16:9' | '9:16' | '4:3' | '3:4';
10
+ outputFormat?: 'jpg' | 'png';
11
+ model?: 'flux-kontext-max' | 'google/nano-banana' | 'seedream-4';
12
+ }
13
+ export interface TagOptions {
14
+ prompt: string;
15
+ options?: string[];
16
+ multiple?: boolean;
17
+ }
18
+ export interface TagResponse {
19
+ tags: string[];
20
+ raw?: unknown;
21
+ }
22
+ export interface EmbedOptions {
23
+ type?: 'image' | 'text';
24
+ mode?: 'api' | 'local';
25
+ }
26
+ export interface EmbedResponse {
27
+ embedding: number[];
28
+ }
29
+ export declare class CoreViz {
30
+ private apiKey?;
31
+ private token?;
32
+ constructor(config?: CoreVizConfig);
33
+ private getHeaders;
34
+ private handleResponse;
35
+ describe(image: string, options?: DescribeOptions): Promise<string>;
36
+ edit(image: string, options: EditOptions): Promise<string>;
37
+ tag(image: string, options: TagOptions): Promise<TagResponse>;
38
+ embed(input: string, options?: EmbedOptions): Promise<EmbedResponse>;
39
+ private embedLocal;
40
+ resize(input: string | File, maxWidth?: number, maxHeight?: number): Promise<string>;
41
+ }
@@ -0,0 +1,197 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.CoreViz = void 0;
37
+ const resize_1 = require("./resize");
38
+ class CoreViz {
39
+ constructor(config = {}) {
40
+ this.apiKey = config.apiKey || (typeof process !== 'undefined' ? process.env.COREVIZ_API_KEY : undefined);
41
+ this.token = config.token;
42
+ }
43
+ getHeaders() {
44
+ const headers = {
45
+ 'Content-Type': 'application/json',
46
+ };
47
+ if (this.token) {
48
+ headers['Authorization'] = `Bearer ${this.token}`;
49
+ }
50
+ else {
51
+ headers['x-api-key'] = this.apiKey || "";
52
+ }
53
+ return headers;
54
+ }
55
+ async handleResponse(response) {
56
+ if (response.status === 402) {
57
+ throw new Error('Insufficient credits');
58
+ }
59
+ if (!response.ok) {
60
+ throw new Error(`Request failed (${response.status})`);
61
+ }
62
+ const data = await response.json();
63
+ if (data.error) {
64
+ throw new Error(data.error);
65
+ }
66
+ return data;
67
+ }
68
+ async describe(image, options) {
69
+ try {
70
+ const resizedImage = await (0, resize_1.resize)(image);
71
+ const headers = this.getHeaders();
72
+ const response = await fetch(`https://lab.coreviz.io/api/ai/describe`, {
73
+ method: 'POST',
74
+ headers,
75
+ body: JSON.stringify({ image: resizedImage }),
76
+ });
77
+ const data = await this.handleResponse(response);
78
+ return data.description;
79
+ }
80
+ catch (err) {
81
+ throw err instanceof Error ? err : new Error("An unexpected error occurred.");
82
+ }
83
+ }
84
+ async edit(image, options) {
85
+ try {
86
+ const resizedImage = await (0, resize_1.resize)(image);
87
+ const headers = this.getHeaders();
88
+ const response = await fetch(`https://lab.coreviz.io/api/ai/edit`, {
89
+ method: 'POST',
90
+ headers,
91
+ body: JSON.stringify({
92
+ image: resizedImage,
93
+ prompt: options.prompt,
94
+ aspectRatio: options.aspectRatio || 'match_input_image',
95
+ outputFormat: options.outputFormat || 'jpg',
96
+ model: options.model || 'flux-kontext-max',
97
+ }),
98
+ });
99
+ const data = await this.handleResponse(response);
100
+ return data.result;
101
+ }
102
+ catch (err) {
103
+ throw err instanceof Error ? err : new Error("An unexpected error occurred.");
104
+ }
105
+ }
106
+ async tag(image, options) {
107
+ try {
108
+ const resizedImage = await (0, resize_1.resize)(image);
109
+ const headers = this.getHeaders();
110
+ const response = await fetch("https://lab.coreviz.io/api/ai/tag", {
111
+ method: 'POST',
112
+ headers,
113
+ body: JSON.stringify({
114
+ image: resizedImage,
115
+ prompt: options.prompt,
116
+ options: options.options && options.options.length > 0 ? options.options : undefined,
117
+ multiple: options.multiple ?? true,
118
+ }),
119
+ });
120
+ const data = await this.handleResponse(response);
121
+ const tags = Array.isArray(data.tags)
122
+ ? data.tags
123
+ : Array.isArray(data.result)
124
+ ? data.result
125
+ : typeof data.tag === 'string'
126
+ ? [data.tag]
127
+ : [];
128
+ return {
129
+ tags,
130
+ raw: data,
131
+ };
132
+ }
133
+ catch (err) {
134
+ throw err instanceof Error ? err : new Error("An unexpected error occurred.");
135
+ }
136
+ }
137
+ async embed(input, options) {
138
+ const mode = options?.mode || 'api';
139
+ if (mode === 'local') {
140
+ return this.embedLocal(input, options);
141
+ }
142
+ try {
143
+ const headers = this.getHeaders();
144
+ let body = {};
145
+ // Determine type
146
+ let isImage = false;
147
+ if (options?.type) {
148
+ isImage = options.type === 'image';
149
+ }
150
+ else {
151
+ // Heuristic: Check if input starts with data:image or http
152
+ // Assuming http/https implies image URL in this context unless specified otherwise
153
+ isImage = input.startsWith('data:image') || input.startsWith('http://') || input.startsWith('https://');
154
+ }
155
+ if (isImage) {
156
+ const resizedImage = await (0, resize_1.resize)(input);
157
+ body.image = resizedImage;
158
+ }
159
+ else {
160
+ body.text = input;
161
+ }
162
+ const response = await fetch("https://lab.coreviz.io/api/ai/embed", {
163
+ method: 'POST',
164
+ headers,
165
+ body: JSON.stringify(body),
166
+ });
167
+ const data = await this.handleResponse(response);
168
+ return data;
169
+ }
170
+ catch (err) {
171
+ throw err instanceof Error ? err : new Error("An unexpected error occurred.");
172
+ }
173
+ }
174
+ async embedLocal(input, options) {
175
+ try {
176
+ // Dynamic import to avoid loading transformers if not used
177
+ const { pipeline } = await Promise.resolve().then(() => __importStar(require('@huggingface/transformers')));
178
+ // Initialize the pipeline with the specified model
179
+ // This will automatically download and cache the model if not present
180
+ const extractor = await pipeline('feature-extraction', 'Xenova/clip-vit-large-patch14');
181
+ // Generate embeddings
182
+ // transformers.js handles text strings, image URLs, and image paths automatically
183
+ const output = await extractor(input, { pooling: 'mean', normalize: true });
184
+ // Convert Float32Array to regular array
185
+ // @ts-ignore - Output type inference might fail with dynamic import
186
+ const embedding = Array.from(output.data);
187
+ return { embedding };
188
+ }
189
+ catch (err) {
190
+ throw err instanceof Error ? err : new Error("Local embedding failed: " + String(err));
191
+ }
192
+ }
193
+ async resize(input, maxWidth, maxHeight) {
194
+ return (0, resize_1.resize)(input, maxWidth, maxHeight);
195
+ }
196
+ }
197
+ exports.CoreViz = CoreViz;
package/dist/describe.js CHANGED
@@ -19,6 +19,9 @@ async function describe(image, options) {
19
19
  headers,
20
20
  body: JSON.stringify({ image: resizedImage }),
21
21
  });
22
+ if (response.status === 402) {
23
+ throw new Error('Insufficient credits');
24
+ }
22
25
  if (!response.ok) {
23
26
  throw new Error(`Failed to describe image (${response.status})`);
24
27
  }
@@ -29,7 +32,6 @@ async function describe(image, options) {
29
32
  return data.description;
30
33
  }
31
34
  catch (err) {
32
- console.error('Error in describeImage:', err);
33
35
  throw err instanceof Error ? err : new Error("An unexpected error occurred.");
34
36
  }
35
37
  }
package/dist/edit.js CHANGED
@@ -25,6 +25,9 @@ async function edit(image, options) {
25
25
  model: options.model || 'flux-kontext-max',
26
26
  }),
27
27
  });
28
+ if (response.status === 402) {
29
+ throw new Error('Insufficient credits');
30
+ }
28
31
  if (!response.ok) {
29
32
  throw new Error(`Failed to edit image (${response.status})`);
30
33
  }
@@ -35,7 +38,6 @@ async function edit(image, options) {
35
38
  return data.result;
36
39
  }
37
40
  catch (err) {
38
- console.error('Error in editImage:', err);
39
41
  throw err instanceof Error ? err : new Error("An unexpected error occurred.");
40
42
  }
41
43
  }
package/dist/index.d.ts CHANGED
@@ -1,6 +1,4 @@
1
- import { describe, DescribeOptions } from './describe';
1
+ import { CoreViz, CoreVizConfig, DescribeOptions, EditOptions, TagOptions, TagResponse, EmbedOptions, EmbedResponse } from './coreviz';
2
2
  import { resize } from './resize';
3
- import { edit, EditOptions } from './edit';
4
- import { tag, TagOptions, TagResponse } from './tag';
5
- export { describe, resize, edit, tag };
6
- export type { EditOptions, TagOptions, TagResponse, DescribeOptions };
3
+ export { CoreViz, resize };
4
+ export type { CoreVizConfig, DescribeOptions, EditOptions, TagOptions, TagResponse, EmbedOptions, EmbedResponse };
package/dist/index.js CHANGED
@@ -1,11 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.tag = exports.edit = exports.resize = exports.describe = void 0;
4
- const describe_1 = require("./describe");
5
- Object.defineProperty(exports, "describe", { enumerable: true, get: function () { return describe_1.describe; } });
3
+ exports.resize = exports.CoreViz = void 0;
4
+ const coreviz_1 = require("./coreviz");
5
+ Object.defineProperty(exports, "CoreViz", { enumerable: true, get: function () { return coreviz_1.CoreViz; } });
6
6
  const resize_1 = require("./resize");
7
7
  Object.defineProperty(exports, "resize", { enumerable: true, get: function () { return resize_1.resize; } });
8
- const edit_1 = require("./edit");
9
- Object.defineProperty(exports, "edit", { enumerable: true, get: function () { return edit_1.edit; } });
10
- const tag_1 = require("./tag");
11
- Object.defineProperty(exports, "tag", { enumerable: true, get: function () { return tag_1.tag; } });
package/dist/tag.js CHANGED
@@ -24,6 +24,9 @@ async function tag(image, options) {
24
24
  multiple: options.multiple ?? true,
25
25
  }),
26
26
  });
27
+ if (response.status === 402) {
28
+ throw new Error('Insufficient credits');
29
+ }
27
30
  if (!response.ok) {
28
31
  throw new Error(`Failed to tag image (${response.status})`);
29
32
  }
@@ -44,7 +47,6 @@ async function tag(image, options) {
44
47
  };
45
48
  }
46
49
  catch (err) {
47
- console.error('Error in tagImage:', err);
48
50
  throw err instanceof Error ? err : new Error("An unexpected error occurred.");
49
51
  }
50
52
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@coreviz/sdk",
3
- "version": "1.0.1",
3
+ "version": "1.0.4",
4
4
  "description": "CoreViz SDK",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",