/* "FIND …" — asking the knowledge graph out loud.
*
* Press the microphone, say the sentence, it acts and switches off. One
* sentence per press: nothing is held open, nothing listens while somebody is
* talking about something else, and the microphone is released the moment the
* graph window closes.
*
* ── why the matching is the hard part ──
* Every name that matters here is invented. Speech recognition is trained on
* English, so "NEUMotion" comes back as "new motion", "NEUCity" as "new city"
* or "neo city", "NEUSLM" as "new SLM" or "new slim", and "RoadPlus" as "road
* plus". A literal string comparison would fail on almost every sentence a
* person actually says. So nothing here compares strings directly:
*
* 1. the transcript is flattened — lowercased, punctuation dropped, and the
* dozen ways a recogniser writes "NEU" all folded to one;
* 2. the eight chapters are matched first, through an alias list;
* 3. failing that, every item on the ball is scored against the words, and
* anything that scores is kept.
*
* ── the verb, and why it stays ──
* You say "find NEUMotion". The greeting is optional — "hey NEU, find …" still
* works — but SOMETHING has to mark where the name begins, or "the NEUMotion
* results were good" is indistinguishable from an instruction. `find` earns
* its place as the word that says "what follows is the thing I want", and
* show / search / filter / open / go to all count as the same word.
*
* Nothing listens between presses, which is what makes one required verb
* enough: the microphone is only ever open for the one sentence you asked it
* to hear.
*/
(function () {
'use strict';
var stage = document.querySelector('[data-graphstage]');
var btn = document.querySelector('[data-gmic]');
var say = document.querySelector('[data-gmicsay]');
var out = document.querySelector('[data-gvoice]');
if (!stage || !btn || !out) return;
var SR = window.SpeechRecognition || window.webkitSpeechRecognition;
/* A microphone needs a secure page. On plain http:// anywhere other than
localhost the browser refuses outright, so the button stays hidden rather
than sitting there looking pressable. */
if (!SR || !window.isSecureContext) return;
btn.hidden = false;
/* ---------- hearing NEU ----------
Every spelling a recogniser has been observed to produce for the syllable,
folded to one so the alias table below only has to be written once. */
var NEUISH = /\b(neu|new|nu|nue|knew|neo|noo|gnu|nyu)\b[\s-]*/g;
function flat(s) {
return String(s)
.toLowerCase()
.replace(/[^\w\s]/g, ' ') // punctuation the recogniser adds
.replace(/\s+/g, ' ')
.trim();
}
/* "new motion" and "neumotion" and "neo-motion" all become "neumotion" */
function fold(s) {
return flat(s).replace(NEUISH, 'neu').replace(/\s+/g, ' ').trim();
}
/* ---------- the eight ----------
Built from the graph's own pillar list, so a chapter renamed in Backstage
is heard by its new name without anybody editing this file. The extra
aliases are the mishearings that folding alone does not catch. */
var DATA = (stage._voice && stage._voice.data) || { pillars: [], items: [] };
var EXTRA = {
neucity: ['city', 'roads', 'road'],
neunature: ['nature', 'plants', 'forest'],
neumotion: ['motion', 'movement', 'pose'],
neufactory: ['factory', 'factories', 'safety'],
/* the initials get read aloud as a word as often as as letters */
neuslm: ['slm', 'slim', 'neuslim', 'new slim', 'neu s l m',
'language model', 'small language model',
'doc', 'docs', 'neudoc', 'new doc', 'neu doc', 'document', 'documents'],
neutalents: ['talents', 'talent', 'students', 'training'],
neustudio: ['studio', 'film', 'video'],
neustory: ['story', 'news', 'awards'],
};
/* Words that carry no aim: "find THE NEUMotion CHAPTER" is asking for the
same thing as "find NEUMotion". */
var FILLER = /^(the|a|an|our|chapter|chapters|page|section|pillar|dots|stuff)$/;
function core(s) {
return fold(s).split(' ').filter(function (w) { return w && !FILLER.test(w); }).join(' ');
}
var jam = function (s) { return s.replace(/\s/g, ''); };
/* A chapter has to be named WHOLE.
*
* This used to accept a chapter whose alias appeared anywhere inside what
* was said, and "roadplus" contains "road" — so asking for RoadPlus, the
* one thing the microphone exists to find, greyed the ball down to all
* fourteen NEUCity dots instead. Matching the whole phrase keeps "road" for
* NEUCity and lets "roadplus" fall through to the things on the ball, which
* is where it belongs.
*
* `loose` is the last resort, tried only after the items have had their go.
*/
function chapterFor(said, loose) {
var f = core(said);
if (!f) return null;
var hits = [];
(DATA.pillars || []).forEach(function (p) {
var names = [p.slug, p.name].concat(EXTRA[p.slug] || []).map(core);
var hit = names.some(function (n) {
if (!n) return false;
if (loose) return f.indexOf(n) > -1;
/* spaces are the recogniser's guess, not information: "neu s l m",
"neu slm" and "neuslm" are one word said three ways */
return f === n || jam(f) === jam(n);
});
if (hit) hits.push(p);
});
/* "find neu" on its own matches all eight, which is not an answer —
treat it as no answer at all and let the item search have a go. */
return hits.length && hits.length < (DATA.pillars || []).length ? hits : null;
}
/* ---------- everything else on the ball ----------
Score each item against the words that were said. A word has to be worth
saying — "the", "a", "of" match everything and mean nothing — so short
and common words are dropped before scoring. */
var STOP = /^(a|an|the|of|and|or|for|to|in|on|at|by|is|it|its|with|from|all|about|me|show|things?)$/;
function itemsFor(said) {
var f = fold(said);
var words = f.split(' ').filter(function (w) { return w.length > 2 && !STOP.test(w); });
if (!words.length) return [];
var scored = [];
(DATA.items || []).forEach(function (it) {
var hay = fold(it.label || '') + ' ' + fold(it.when || '');
var score = 0;
/* the whole phrase inside the title is worth more than the words
scattered through it — "road plus" beats an item that merely says
"road" somewhere */
if (f && hay.indexOf(f) > -1) score += 10;
/* run the words together too: "road plus" is how the recogniser writes
RoadPlus, and the title spells it as one word */
var jammed = words.join('');
if (jammed.length > 3 && hay.replace(/\s/g, '').indexOf(jammed) > -1) score += 8;
words.forEach(function (w) { if (hay.indexOf(w) > -1) score += 1; });
if (score) scored.push({ it: it, score: score });
});
if (!scored.length) return [];
/* keep only what scored as well as the best of them — a search for
RoadPlus should not also return everything containing the word "AI" */
scored.sort(function (a, b) { return b.score - a.score; });
var top = scored[0].score;
return scored.filter(function (s) { return s.score >= top; }).map(function (s) { return s.it; });
}
/* ---------- the sentence ----------
"find X" — that is the whole requirement. The greeting is optional rather
than gone: "hey NEU, find X" still works for anyone who has learnt it, and
saying it no longer costs you the search when the recogniser mishears the
NEU. Only the verb is required, and only because something has to mark
where the name begins. */
var PHRASE = new RegExp(
'^(?:\\s*(?:hey|hi|ok|okay)\\s+' +
'(?:neu|new|nu|nue|knew|neo|noo|gnu|nyu|neon|neuron)\\b[\\s,.!]*)?' +
'(?:please\\s+)?' +
'(?:find|show|search|filter|go\\s+to|open)\\s+' +
'(?:me\\s+)?' +
'(.+)$', 'i'
);
function parse(transcript) {
var m = flat(transcript).match(PHRASE);
return m ? m[1].trim() : null;
}
/* ---------- saying what happened ---------- */
var TIP = 'Say: “Find NEUMotion” — or the name of anything on the ball.';
function tell(kind, html) {
out.hidden = false;
out.className = 'gvoice is-' + kind;
out.innerHTML = html;
}
function hush() { out.hidden = true; out.innerHTML = ''; }
function esc(s) {
return String(s).replace(/[&<>"]/g, function (c) {
return { '&': '&', '<': '<', '>': '>', '"': '"' }[c];
});
}
function act(heard) {
var asked = parse(heard);
if (!asked) {
tell('miss', 'Heard: “' + esc(heard) + '” — but it has to start with ' +
'Find…
' + TIP + '');
return;
}
/* "show all" / "everything" puts the ball back */
if (/^(all|everything|show all|the lot|reset|clear)$/.test(fold(asked))) {
stage._voice.clear();
tell('ok', '“' + esc(asked) + '” — everything is back on the ball.');
return;
}
/* Named a chapter outright — the most specific answer, so it goes first. */
var chapters = chapterFor(asked);
if (chapters) return toChapters(chapters, asked);
/* Named a thing on the ball. */
var hits = itemsFor(asked);
if (hits.length) {
stage._voice.items(hits.map(function (i) { return i.id; }), asked);
tell('ok', '“' + esc(asked) + '” → ' + hits.length +
(hits.length === 1 ? ' thing' : ' things') + ' on the ball');
return;
}
/* Named neither, but a chapter's word is in there somewhere — "find road"
when nothing is called that. Better than shrugging. */
var near = chapterFor(asked, true);
if (near) return toChapters(near, asked);
tell('miss', 'Nothing matches “' + esc(asked) + '”.
' + TIP + '');
}
function toChapters(chapters, asked) {
stage._voice.chapters(chapters.map(function (p) { return p.slug; }));
tell('ok', '“' + esc(asked) + '” → ' +
chapters.map(function (p) { return esc(p.name); }).join(' + '));
}
/* ---------- the microphone ---------- */
var rec = null, listening = false;
function stop() {
listening = false;
btn.classList.remove('is-live');
if (say) say.textContent = 'Find…';
if (rec) { try { rec.abort(); } catch (e) {} rec = null; }
}
function start() {
if (listening) { stop(); return; }
rec = new SR();
rec.lang = 'en-US';
rec.continuous = false; // one sentence, then it lets go
rec.interimResults = true; // so the words appear as they are said
rec.maxAlternatives = 3;
listening = true;
btn.classList.add('is-live');
if (say) say.textContent = 'Listening…';
tell('live', 'Listening… ' + TIP + '');
rec.onresult = function (e) {
var last = e.results[e.results.length - 1];
var heard = last[0].transcript;
if (!last.isFinal) {
tell('live', 'Listening… “' + esc(heard) + '”');
return;
}
/* Chrome offers a few readings of the same audio. Take the first one
that carries the wake phrase rather than only the likeliest — the
top-ranked transcript is often the one that "corrected" NEU into
something more ordinary. */
var best = heard;
for (var i = 0; i < last.length; i++) {
if (parse(last[i].transcript)) { best = last[i].transcript; break; }
}
stop();
act(best);
};
rec.onerror = function (e) {
stop();
if (e.error === 'not-allowed' || e.error === 'service-not-allowed') {
tell('miss', 'The microphone is blocked.
Allow it for this ' +
'site in the browser’s address bar, then press the microphone again.');
} else if (e.error === 'no-speech') {
tell('miss', 'Did not hear anything.
' + TIP + '');
} else if (e.error === 'network') {
tell('miss', 'Speech needs the internet.
The browser sends the ' +
'audio away to turn it into words. The chapter buttons work offline.');
} else if (e.error !== 'aborted') {
tell('miss', 'The microphone stopped. (' + esc(e.error) + ')');
}
};
rec.onend = function () { if (listening) stop(); };
try {
rec.start();
} catch (err) {
stop();
tell('miss', 'Could not start the microphone. ' + esc(err.message) + '');
}
}
btn.addEventListener('click', start);
/* The whole path a sentence takes after the microphone has finished with it.
Exposed so the matching can be exercised with a typed sentence — feeding
it "hey new, find road plus" proves the real thing, because it is the
same function the microphone calls. */
stage._heard = act;
/* THE MICROPHONE BELONGS TO THIS WINDOW.
Closing the graph — by the ×, the scrim, or Escape — has to release it, or
the page is left holding a live microphone for a panel nobody is looking
at. Watching `hidden` covers every way out at once, including any added
later, which a listener per close button would not. */
new MutationObserver(function () {
if (stage.hidden) { stop(); hush(); }
}).observe(stage, { attributes: true, attributeFilter: ['hidden'] });
document.addEventListener('visibilitychange', function () {
if (document.hidden) stop();
});
})();