video-product-finder/scripts/run.ts

136 lines
4.2 KiB
TypeScript

#!/usr/bin/env bun
import { resolve } from 'path';
import type { Command } from '../src/types.ts';
import { run } from '../src/index.ts';
import { createSkillClient } from '../src/auth-cli.ts';
const SKILL_NAME = 'video-product-snapshot';
// Load .env from skill root (does not override existing env vars)
loadDotenv(resolve(import.meta.dir, '../.env'));
function loadDotenv(path: string): void {
let raw: string;
try { raw = require('fs').readFileSync(path, 'utf-8'); } catch { return; }
for (const line of raw.split('\n')) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith('#')) continue;
const eq = trimmed.indexOf('=');
if (eq < 0) continue;
const key = trimmed.slice(0, eq).trim();
const val = trimmed.slice(eq + 1).trim().replace(/^["']|["']$/g, '');
if (key && !(key in process.env)) process.env[key] = val;
}
}
function printUsage(): void {
console.error(`Usage:
bun scripts/run.ts [--api-base=<url>] <command> [args...] [--dry-run]
Commands:
session
Get auth session token
detect <video-path> [options]
Extract frames and detect ecommerce product snapshots
Options:
--interval=<seconds> Frame sampling interval (default: 1)
--max-frames=<n> Max frames to analyze (default: 60)
--output-dir=<dir> Where to save snapshots (default: next to video)
--min-confidence=<0-1> Minimum detection confidence (default: 0.7)
search <image-path>
Search for products using an image via the ecom image-search API
detect-and-search <video-path> [options]
Detect best product snapshot from video then run image search + rerank
rerank --image-results=<json> [--description=<text>] [--keyword=<text>] [--top=<n>]
Filter image search results using keyword intersection
Config: ~/.openclaw/.env (CLIENT_KEY), skill .env (VISION_API_KEY)
`);
}
async function reportHook(
hookUrl: string,
hookToken: string | undefined,
payload: object,
): Promise<void> {
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
if (hookToken) headers['Authorization'] = `Bearer ${hookToken}`;
await fetch(hookUrl, { method: 'POST', headers, body: JSON.stringify(payload) });
}
async function main(): Promise<void> {
const positionals: string[] = [];
let dryRun = false;
for (const arg of process.argv.slice(2)) {
if (arg === '--dry-run') {
dryRun = true;
} else if (arg.startsWith('--api-base=')) {
process.env.API_BASE = arg.slice('--api-base='.length).trim();
} else if (arg === '-h' || arg === '--help') {
printUsage(); process.exit(0);
} else {
positionals.push(arg);
}
}
if (positionals.length < 1) { printUsage(); process.exit(1); }
const command = positionals[0] as Command;
// Exchange CLIENT_KEY for session — gives us hookUrl for telemetry
let hookUrl: string | undefined;
let hookToken: string | undefined;
try {
const client = createSkillClient({ dryRun });
const session = await client.session();
hookUrl = session.hookUrl;
hookToken = session.hookToken;
} catch {
// Auth failure is non-fatal for telemetry; skill still runs
}
const startMs = Date.now();
let result: Awaited<ReturnType<typeof run>>;
try {
result = await run(command, positionals.slice(1), dryRun);
} catch (err) {
const error = err instanceof Error ? err.message : String(err);
const failed = { status: 'failed' as const, command, dryRun, error };
console.log(JSON.stringify(failed, null, 2));
if (hookUrl && !dryRun) {
reportHook(hookUrl, hookToken, {
skill: SKILL_NAME, command, status: 'failed',
durationMs: Date.now() - startMs, error,
}).catch(() => {});
}
process.exit(1);
}
console.log(JSON.stringify(result, null, 2));
if (hookUrl && !dryRun) {
reportHook(hookUrl, hookToken, {
skill: SKILL_NAME,
command,
status: result.status,
durationMs: Date.now() - startMs,
error: (result as any).error,
}).catch(() => {});
}
}
main().catch((err) => {
console.error(JSON.stringify({
status: 'failed',
error: err instanceof Error ? err.message : String(err),
}, null, 2));
process.exit(1);
});