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
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
# InstantSplat TypeScript API Client

Complete TypeScript/JavaScript client for InstantSplat API with full type safety.

## 🚀 Quick Start

### Installation

```bash
npm install @gradio/client @types/node ts-node tsx
```

### Basic Usage

```typescript
import { processImages } from "./api_client";

const result = await processImages(
  ["img1.jpg", "img2.jpg", "img3.jpg"],
  "your-username/InstantSplat"
);

if (result.status === "success") {
  console.log("GLB URL:", result.glb_url);
  console.log("PLY URL:", result.ply_url);
}
```

## 📦 Available Functions

### `processImages(imagePaths, spaceUrl?)`

Submit images and get back URLs.

```typescript
async function processImages(
  imagePaths: string[],
  spaceUrl?: string
): Promise<ProcessResult>
```

**Parameters:**
- `imagePaths`: Array of local image file paths
- `spaceUrl`: (Optional) HuggingFace Space URL or env var `INSTANTSPLAT_SPACE`

**Returns:**
```typescript
interface ProcessResult {
  status: "success" | "error";
  glb_url?: string;
  ply_url?: string;
  video_available?: boolean;
  error?: string;
  message?: string;
}
```

**Example:**
```typescript
const result = await processImages(
  ["img1.jpg", "img2.jpg", "img3.jpg"],
  "username/InstantSplat"
);

console.log(result.glb_url); // Supabase URL to GLB file
```

### `completeWorkflow(imagePaths, outputDir, spaceUrl?)`

Process images and download the GLB file.

```typescript
async function completeWorkflow(
  imagePaths: string[],
  outputDir?: string,
  spaceUrl?: string
): Promise<string | null>
```

**Parameters:**
- `imagePaths`: Array of image paths
- `outputDir`: Local directory for downloaded file (default: `./outputs`)
- `spaceUrl`: (Optional) Space URL

**Returns:** Local path to downloaded GLB file, or `null` on error

**Example:**
```typescript
const localPath = await completeWorkflow(
  ["img1.jpg", "img2.jpg", "img3.jpg"],
  "./my_models"
);

console.log("Model saved to:", localPath);
// Output: Model saved to: ./my_models/model.glb
```

### `downloadFile(url, outputPath)`

Download a file from URL.

```typescript
async function downloadFile(
  url: string,
  outputPath: string
): Promise<void>
```

## 🛠️ CLI Usage

### Using npx

```bash
npx tsx api_client.ts img1.jpg img2.jpg img3.jpg
```

### Using npm script

```bash
npm run api img1.jpg img2.jpg img3.jpg
```

### With environment variable

```bash
export INSTANTSPLAT_SPACE="username/InstantSplat"
npx tsx api_client.ts img1.jpg img2.jpg img3.jpg
```

## 📝 Examples

### Example 1: Simple Usage

```typescript
import { processImages } from "./api_client";

async function main() {
  const result = await processImages(
    ["image1.jpg", "image2.jpg", "image3.jpg"],
    "username/InstantSplat"
  );

  if (result.status === "success") {
    console.log("✅ GLB URL:", result.glb_url);
    console.log("✅ PLY URL:", result.ply_url);
  } else {
    console.error("❌ Error:", result.error);
  }
}

main();
```

### Example 2: With Error Handling

```typescript
import { processImages } from "./api_client";

async function processWithRetry(
  images: string[],
  maxRetries = 3
): Promise<ProcessResult> {
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    const result = await processImages(images);

    if (result.status === "success") {
      return result;
    }

    if (attempt < maxRetries) {
      const delay = Math.pow(2, attempt) * 1000;
      await new Promise(resolve => setTimeout(resolve, delay));
    }
  }

  throw new Error("All retries failed");
}
```

### Example 3: Batch Processing

```typescript
import { processImages } from "./api_client";

async function batchProcess(imageSets: string[][]) {
  const results = [];

  for (let i = 0; i < imageSets.length; i++) {
    console.log(`Processing set ${i + 1}/${imageSets.length}...`);
    
    const result = await processImages(imageSets[i]);
    results.push(result);

    // Rate limiting
    await new Promise(resolve => setTimeout(resolve, 2000));
  }

  return results;
}

const sets = [
  ["scene1_img1.jpg", "scene1_img2.jpg"],
  ["scene2_img1.jpg", "scene2_img2.jpg"],
];

const results = await batchProcess(sets);
```

### Example 4: Download and Use

```typescript
import { completeWorkflow } from "./api_client";

async function processAndDownload() {
  const modelPath = await completeWorkflow(
    ["img1.jpg", "img2.jpg", "img3.jpg"],
    "./models"
  );

  if (modelPath) {
    console.log(`Model ready at: ${modelPath}`);
    // Use the model file...
  }
}
```

## 🌐 Integration Examples

### Express.js API

```typescript
import express from "express";
import { processImages } from "./api_client";

const app = express();
app.use(express.json());

app.post("/api/process", async (req, res) => {
  const { images } = req.body;

  const result = await processImages(
    images,
    process.env.INSTANTSPLAT_SPACE
  );

  if (result.status === "success") {
    res.json({
      success: true,
      glb_url: result.glb_url,
      ply_url: result.ply_url
    });
  } else {
    res.status(500).json({
      success: false,
      error: result.error
    });
  }
});

app.listen(3000);
```

### Next.js API Route

```typescript
// pages/api/process.ts
import type { NextApiRequest, NextApiResponse } from "next";
import { processImages } from "../../api_client";

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  if (req.method !== "POST") {
    return res.status(405).json({ error: "Method not allowed" });
  }

  const { images } = req.body;

  const result = await processImages(
    images,
    process.env.INSTANTSPLAT_SPACE
  );

  if (result.status === "success") {
    res.status(200).json(result);
  } else {
    res.status(500).json(result);
  }
}
```

### React Hook

```typescript
import { useState } from "react";
import { processImages } from "./api_client";

function useInstantSplat() {
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState<ProcessResult | null>(null);

  const process = async (images: string[]) => {
    setLoading(true);
    try {
      const res = await processImages(images);
      setResult(res);
      return res;
    } finally {
      setLoading(false);
    }
  };

  return { process, loading, result };
}

// Usage in component:
function MyComponent() {
  const { process, loading, result } = useInstantSplat();

  const handleSubmit = () => {
    process(["img1.jpg", "img2.jpg", "img3.jpg"]);
  };

  return (
    <div>
      {loading && <p>Processing...</p>}
      {result?.glb_url && <a href={result.glb_url}>Download Model</a>}
    </div>
  );
}
```

### Vue.js Composable

```typescript
import { ref } from "vue";
import { processImages } from "./api_client";

export function useInstantSplat() {
  const loading = ref(false);
  const result = ref(null);

  const process = async (images: string[]) => {
    loading.value = true;
    try {
      result.value = await processImages(images);
    } finally {
      loading.value = false;
    }
  };

  return { process, loading, result };
}
```

## 📚 Type Definitions

```typescript
interface ProcessResult {
  status: "success" | "error";
  glb_url?: string;           // Supabase URL to GLB file
  ply_url?: string;           // Supabase URL to PLY file
  video_available?: boolean;  // Whether video was generated
  error?: string;             // Error message if status is "error"
  message?: string;           // Success message
}

interface InstantSplatResponse {
  video_path: string;    // [0] Path to video
  ply_url: string;       // [1] PLY URL
  ply_download: string;  // [2] PLY download
  ply_model: string;     // [3] PLY model
  glb_model: string;     // [4] GLB model path
  glb_url: string;       // [5] GLB URL (Supabase)
}
```

## ⚙️ Configuration

### Environment Variables

```bash
# .env
INSTANTSPLAT_SPACE=username/InstantSplat
```

### package.json Scripts

Add to your `package.json`:

```json
{
  "scripts": {
    "api": "npx tsx api_client.ts",
    "process": "npx tsx example_api_usage.ts"
  }
}
```

## 🔧 Troubleshooting

### "Cannot find module '@gradio/client'"

```bash
npm install @gradio/client
```

### "Cannot find name 'require'"

Add to your `tsconfig.json`:

```json
{
  "compilerOptions": {
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true
  }
}
```

### TypeScript errors

Make sure you have the types installed:

```bash
npm install --save-dev @types/node
```

### Import errors

If using ES modules, change imports:

```typescript
// CommonJS
const { processImages } = require("./api_client");

// ES Modules
import { processImages } from "./api_client.js";
```

## 📦 Building for Production

### Compile TypeScript

```bash
npx tsc api_client.ts
```

### Bundle with esbuild

```bash
npx esbuild api_client.ts --bundle --platform=node --outfile=dist/api_client.js
```

### Use in production

```typescript
// Import the compiled version
import { processImages } from "./dist/api_client.js";
```

## 🎯 Best Practices

1. **Rate Limiting**: Add delays between batch requests
2. **Error Handling**: Always wrap in try-catch
3. **Retries**: Implement exponential backoff
4. **Timeouts**: Set reasonable timeouts for large images
5. **Validation**: Check image files exist before uploading

## 📖 More Examples

See `example_api_usage.ts` for complete working examples including:
- Simple usage
- Complete workflow with download
- Batch processing
- Error handling with retries
- Express.js integration
- React component integration

## 🆘 Support

- Check `API_GUIDE.md` for general API documentation
- Check `API_QUICKSTART.md` for quick start guide
- Review `example_api_usage.ts` for working examples

## 🔗 Related Files

- `api_client.ts` - Main TypeScript client
- `api_client.py` - Python equivalent
- `example_api_usage.ts` - Usage examples
- `API_GUIDE.md` - Complete API documentation
- `API_QUICKSTART.md` - Quick start guide