openvibers/openvibe.markets servervision.js

vision.js

main 3.9 KB · 66 lines · javascript

1'use strict';
2/**
3 * Search by photo (plan §L.1: "photograph a thing → Vision names it → Markets finds it everywhere"). OpenVibe.Vision's
4 * ask (POST /api/v1/ask, capability vision.image.ask, Network #1118) names what a picture shows as a short shopping
5 * search; Markets searches those words. Markets keeps nothing of the picture; Vision keeps its hash and the answer's
6 * words, with no person attached (Markets has no sign-in).
7 *
8 * createVision({ visionUrl, networkUrl, clientId, clientSecret, fetchImpl }) → { ready, name(dataUrl) }
9 * name → { ok: true, query } | { ok: false, error } (error is said to the person as it is)
10 * queryOf(text) → the words to search, or null when the picture shows nothing to buy
11 */
12const QUESTION = 'What product is in this picture? Answer with only a short shopping search for it: the brand, the model and what it is, at most eight words. If it is not something people buy, answer exactly: none';
13
14function queryOf(text) {
15 const line = String(text || '').split('\n').map((l) => l.trim()).find(Boolean) || '';
16 const q = line.replace(/^["'“”‘’`*\-\s]+|["'“”‘’`*.\s]+$/g, '').replace(/\s+/g, ' ').slice(0, 80).trim();
17 if (!q || /^none\b/i.test(q) || q.length < 2) return null;
18 return q;
19}
20
21function createVision({ visionUrl, networkUrl, clientId = 'markets', clientSecret, fetchImpl = globalThis.fetch, timeoutMs = 30000 } = {}) {
22 const base = String(visionUrl || '').replace(/\/+$/, '');
23 const net = String(networkUrl || '').replace(/\/+$/, '');
24 const ready = Boolean(base && net && clientSecret);
25 let token = null;
26 let until = 0;
27
28 async function tokenNow() {
29 if (token && Date.now() < until) return token;
30 const res = await fetchImpl(`${net}/oauth/token`, {
31 method: 'POST', redirect: 'error', signal: AbortSignal.timeout(10000),
32 headers: { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' },
33 body: new URLSearchParams({ grant_type: 'client_credentials', client_id: clientId, client_secret: clientSecret, audience: 'openvibe.vision', scope: 'vision.image.ask' }).toString(),
34 });
35 const body = await res.json().catch(() => null);
36 if (!res.ok || !body || !body.access_token) throw new Error(`token ${res.status}`);
37 token = body.access_token;
38 until = Date.now() + Math.max(30, (Number(body.expires_in) || 300) - 30) * 1000;
39 return token;
40 }
41
42 async function name(dataUrl) {
43 if (!ready) return { ok: false, error: 'Search by photo is not set up here yet.' };
44 if (!/^data:image\/(jpeg|png|webp);base64,[A-Za-z0-9+/=]+$/.test(String(dataUrl || ''))) return { ok: false, error: 'That is not a photo Markets can read (JPEG, PNG or WebP).' };
45 try {
46 const res = await fetchImpl(`${base}/api/v1/ask`, {
47 method: 'POST', redirect: 'error', signal: AbortSignal.timeout(timeoutMs),
48 headers: { 'content-type': 'application/json', accept: 'application/json', authorization: `Bearer ${await tokenNow()}` },
49 body: JSON.stringify({ task: 'identify', question: QUESTION, image: dataUrl, mode: 'auto' }),
50 });
51 if (res.status === 401 || res.status === 403) { token = null; until = 0; }
52 const body = await res.json().catch(() => null);
53 if (!res.ok || !body || !body.answer) return { ok: false, error: 'OpenVibe Vision could not look at the photo just now.' };
54 const query = queryOf(body.answer.text);
55 if (!query) return { ok: false, error: 'That photo does not seem to show something to buy. Try a closer shot of the thing itself, or type its name.' };
56 return { ok: true, query };
57 } catch {
58 return { ok: false, error: 'OpenVibe Vision did not answer in time. Try again, or type its name.' };
59 }
60 }
61
62 return { ready, name };
63}
64
65module.exports = { createVision, queryOf, QUESTION };
66