InstantSplat / example_api_usage.ts
Long Hoang
Use Supabase for outputs and add Python/TS API clients
1575924
/**
* Example usage of the InstantSplat TypeScript API client
*
* Run with: npx tsx example_api_usage.ts
*/
import { processImages, completeWorkflow } from "./api_client.js";
// Example 1: Simple usage - Get GLB URL
async function example1() {
console.log("\n=== Example 1: Get GLB URL ===\n");
const result = await processImages(
["test01/IMG_8533.jpeg", "test01/IMG_8534.jpeg", "test01/IMG_8535.jpeg"],
"your-username/InstantSplat" // or use env var
);
if (result.status === "success") {
console.log("✅ Success!");
console.log("GLB URL:", result.glb_url);
console.log("PLY URL:", result.ply_url);
} else {
console.error("❌ Error:", result.error);
}
}
// Example 2: Complete workflow - Process and download
async function example2() {
console.log("\n=== Example 2: Complete Workflow ===\n");
const localPath = await completeWorkflow(
["test01/IMG_8533.jpeg", "test01/IMG_8534.jpeg", "test01/IMG_8535.jpeg"],
"./my_models", // output directory
"your-username/InstantSplat"
);
if (localPath) {
console.log("🎉 Model saved to:", localPath);
} else {
console.error("Failed to process or download model");
}
}
// Example 3: Batch processing multiple scenes
async function example3() {
console.log("\n=== Example 3: Batch Processing ===\n");
const scenes = [
["scene1_img1.jpg", "scene1_img2.jpg", "scene1_img3.jpg"],
["scene2_img1.jpg", "scene2_img2.jpg", "scene2_img3.jpg"],
];
const results = [];
for (let i = 0; i < scenes.length; i++) {
console.log(`\nProcessing scene ${i + 1}/${scenes.length}...`);
const result = await processImages(
scenes[i],
"your-username/InstantSplat"
);
results.push({
scene: i + 1,
...result
});
// Rate limiting - be nice to the server
await new Promise(resolve => setTimeout(resolve, 2000));
}
// Summary
console.log("\n=== Batch Processing Summary ===\n");
results.forEach(r => {
if (r.status === "success") {
console.log(`Scene ${r.scene}: ✅ ${r.glb_url}`);
} else {
console.log(`Scene ${r.scene}: ❌ ${r.error}`);
}
});
}
// Example 4: With error handling and retries
async function example4() {
console.log("\n=== Example 4: With Retries ===\n");
async function processWithRetry(
images: string[],
maxRetries: number = 3
) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
console.log(`Attempt ${attempt}/${maxRetries}...`);
const result = await processImages(
images,
"your-username/InstantSplat"
);
if (result.status === "success") {
return result;
}
console.log(`Failed: ${result.error}`);
if (attempt < maxRetries) {
const delay = Math.pow(2, attempt) * 1000; // exponential backoff
console.log(`Retrying in ${delay}ms...`);
await new Promise(resolve => setTimeout(resolve, delay));
}
}
throw new Error("All retry attempts failed");
}
try {
const result = await processWithRetry([
"test01/IMG_8533.jpeg",
"test01/IMG_8534.jpeg",
"test01/IMG_8535.jpeg"
]);
console.log("✅ Success after retry!");
console.log("GLB URL:", result.glb_url);
} catch (error) {
console.error("❌ Failed after all retries:", error);
}
}
// Example 5: Integration with Express.js API
function example5Code() {
return `
// Express.js API endpoint example
import express from 'express';
import { processImages } from './api_client';
const app = express();
app.post('/api/process-images', async (req, res) => {
try {
const { images } = req.body; // Array of image paths or URLs
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
});
}
} catch (error) {
res.status(500).json({
success: false,
error: String(error)
});
}
});
app.listen(3000, () => {
console.log('API running on http://localhost:3000');
});
`;
}
// Example 6: React component integration
function example6Code() {
return `
// React component example
import { useState } from 'react';
import { processImages } from './api_client';
function InstantSplatUploader() {
const [loading, setLoading] = useState(false);
const [result, setResult] = useState(null);
const handleSubmit = async (files: File[]) => {
setLoading(true);
try {
// Convert files to paths or upload them first
const imagePaths = files.map(f => f.path);
const result = await processImages(
imagePaths,
process.env.NEXT_PUBLIC_INSTANTSPLAT_SPACE
);
setResult(result);
} catch (error) {
console.error(error);
} finally {
setLoading(false);
}
};
return (
<div>
{loading && <p>Processing...</p>}
{result?.status === 'success' && (
<div>
<h3>Your 3D Model:</h3>
<a href={result.glb_url}>Download GLB</a>
<a href={result.ply_url}>Download PLY</a>
</div>
)}
{result?.status === 'error' && (
<p>Error: {result.error}</p>
)}
</div>
);
}
`;
}
// Run examples
async function main() {
console.log("InstantSplat API - TypeScript Examples");
console.log("=" .repeat(80));
// Uncomment the examples you want to run:
// await example1(); // Simple usage
// await example2(); // Complete workflow
// await example3(); // Batch processing
// await example4(); // With retries
// Code examples (not executable):
console.log("\n=== Example 5: Express.js Integration ===");
console.log(example5Code());
console.log("\n=== Example 6: React Component ===");
console.log(example6Code());
console.log("\n💡 Uncomment the examples in main() to run them!");
}
// Run if this file is executed directly (ES module compatible)
const isMainModule = import.meta.url === `file://${process.argv[1]}`;
if (isMainModule) {
main().catch(console.error);
}
export {
example1,
example2,
example3,
example4
};