01 / START HERE
What we're building.
UCENTH Vision Intelligence is a browser-based visual intelligence project. You show it an object, a person in context, or a document, and it tells you what it sees, then talks with you about it. It combines:
- HTML, CSS and JavaScript for the interface, with no framework and no build step.
- Browser camera APIs (getUserMedia and canvas) to capture one clean frame.
- Node.js as a small local server that owns the cloud credentials.
- Gemini multimodal AI for identification, document analysis and follow-up answers.
- Cloud Text-to-Speech (the Charon voice) so answers are spoken.
- Chrome speech recognition so you can ask by voice.
- Web Audio and WebGL for a particle presence that moves with real sound.
- PDF.js and mammoth to read PDF and Word files safely.
Everything runs on your machine except the model calls, which go from your Node server to Google. The source is MIT licensed; Google's hosted models are a separate, paid service.
This project exists to teach. Each capability is written so that it can be understood, and reused, on its own. If you only want the camera, or only the document pipeline, the lessons under Build your own show how.
02 / THE BIG PICTURE
How UCENTH Vision Intelligence works.
The browser never talks to Google directly. It sends a captured frame, a file or a question to the local Node server; the server authenticates with Google, asks Gemini for structured JSON, validates it and returns only what the page needs. Voice works the same way: recognized text goes to the server, the answer comes back as text, and the server asks Cloud Text-to-Speech for audio that the browser plays.
- You open the camera or upload a file.
- The scanner waits for a still object and captures one frame.
- The frame (or file) goes to
server.js. - The server validates it and calls Gemini with a schema.
- Gemini returns JSON: object, person or document.
- The page renders the result; Charon introduces it.
- You ask questions by voice; answers are spoken and shown.
03 / THE FILES
Project structure.
Every important file, in the order you might read them.
ucenth-vision-intelligence/ │ ├── index.html The scanner page. Structural comments explain each region. ├── style.css Layout, tokens, responsive result layout. ├── appearance.css / .js Light/dark theme tokens and the confirmation chime. ├── script.js Camera → stability → capture → /api/identify → result. ├── voice.js / voice.css Hands-free conversation: listen, think, speak, timeouts. ├── document.js / .css Document result, Original / English viewer, page navigation. ├── server.js Local HTTP server: allowlisted files, routes, validation. │ ├── lib/ │ ├── stability.js Motion-based "hold still" detection (no ML). │ ├── identity-prompt.js The identification prompt and JSON schema. │ ├── gemini.js Gemini call with ADC; validates structured output. │ ├── conversation.js Follow-up answers and Charon speech. │ ├── voice-routes.js /api/follow-up and /api/speech with bounds. │ ├── document.js Magic bytes, PDF.js, mammoth, one bounded analysis. │ ├── document-routes.js /api/document, raw body, in memory. │ └── particle-presence.js WebGL2 particles driven by an AnalyserNode. │ ├── public/assets/ Images the server may serve: the brand mark and icons (brand/), favicon.ico, site.webmanifest. ├── test/ Unit tests (node --test) and Chrome tests (Playwright). ├── scripts/ Release allowlist, secret scan, ZIP preparation. ├── how-to.html This guide (how-to.css, how-to.js). ├── .env.example The only setting you need: your project ID. └── README.md · ARCHITECTURE.md · LICENSE · THIRD-PARTY-NOTICES.md
Open script.js and search for the word
generation. Count how many places check it. That
single counter is what stops an old scan from overwriting a new one.
04 / INSTALL
Run it locally.
You need a computer with a webcam, current Google Chrome, Node.js 22.19 or newer (release testing used Node 26.5.0 on Windows), a Google account, and a Google Cloud project with billing. Cloud inference can incur charges; set a billing budget alert.
1. Get the source
Download the ZIP from the UCENTH website or GitHub, or clone:
git clone https://github.com/Ucenth/ucenth-vision-intelligence.git
cd ucenth-vision-intelligence
Open a terminal in the folder that contains package.json.
On Windows, right-click a blank area of the folder and choose
Open in Terminal.
2. Install Node.js and the dependencies
Install an LTS release from nodejs.org, reopen the terminal, then:
node --version
npm ci
npm ci installs the exact versions in
package-lock.json. If PowerShell refuses
npm.ps1, use npm.cmd; there is no need to
change your execution policy.
3. Create a Google Cloud project and enable two APIs
- Sign in to Google Cloud Console, create or pick a project, and copy its Project ID (not the display name).
- Link a billing account.
- Install the Google Cloud CLI and reopen the terminal.
Run the following one command at a time, in order. The commands are
shown for Windows PowerShell; on macOS or Linux type
gcloud wherever you see gcloud.cmd.
Replace YOUR_PROJECT_ID with the Project ID you copied.
Step 3a — Sign in to the CLI
gcloud.cmd auth login
A browser window opens. Sign in with the Google account that owns
the project. Back in the terminal you should see
You are now logged in as [you@example.com].
Step 3b — See the projects your account can use
gcloud.cmd projects list
The CLI prints one line per project with three columns:
PROJECT_ID, NAME and
PROJECT_NUMBER. Only the first column is what
UCENTH Vision Intelligence needs. The name is a friendly label you can change
at any time and the number is an internal identifier; the
Project ID is the permanent, unique ID that
commands, .env and billing all refer to. Find the
project you created in step 1 and copy its PROJECT_ID exactly.
If the list is empty, create a project in the console first.
Step 3c — Tell the CLI which project to use
gcloud.cmd config set project YOUR_PROJECT_ID
Expected: Updated property [core/project]. If it says
the project was not found, check that you pasted the Project ID,
not the project name.
Step 3d — Check whether the Agent Platform API is already enabled
aiplatform.googleapis.com is the service ID of the
Agent Platform API (its older name in the console
was Vertex AI API). It serves Gemini. This command lists it only if
it is enabled:
gcloud.cmd services list --enabled --filter="config.name:aiplatform.googleapis.com"
If you see a line like
aiplatform.googleapis.com Agent Platform API it is
already enabled and you can skip to step 3g. If the output is
Listed 0 items. it is not enabled yet.
Step 3e — Enable the Agent Platform API
gcloud.cmd services enable aiplatform.googleapis.com
Expected: Operation "operations/…" finished successfully.
This can take up to a minute. A "permission denied" error means
your account cannot enable services on this project; ask the
project owner for the Service Usage Admin role.
A billing error means the project has no billing account linked
yet (step 2 above).
Step 3f — Confirm it is enabled
Run the check again; the API must now be listed:
gcloud.cmd services list --enabled --filter="config.name:aiplatform.googleapis.com"Step 3g — Check the Text-to-Speech API (the Charon voice)
texttospeech.googleapis.com serves the Charon voice.
Same check:
gcloud.cmd services list --enabled --filter="config.name:texttospeech.googleapis.com"
If it prints texttospeech.googleapis.com Cloud Text-to-Speech API
it is enabled; skip to step 4. If it prints
Listed 0 items. continue.
Step 3h — Enable the Text-to-Speech API
gcloud.cmd services enable texttospeech.googleapis.comStep 3i — Confirm both APIs together
gcloud.cmd services list --enabled --filter="config.name:(aiplatform.googleapis.com OR texttospeech.googleapis.com)"You should now see two lines, one for each API. That is the proof the project is ready; nothing needs to be enabled in the console.
Prefer the console instead of the terminal?
With your project selected at the top of the console, open Agent Platform API in the API Library and choose Enable, then do the same for the Cloud Text-to-Speech API. The button and the command do exactly the same thing.
4. Sign in for the application (ADC)
ADC (Application Default Credentials) is Google's mechanism for letting server-side code authenticate without placing credentials in your project files. The CLI stores a token in your user profile; Google's SDK finds it automatically.
Windows PowerShell
gcloud.cmd auth application-default login
gcloud.cmd auth application-default set-quota-project YOUR_PROJECT_ID
macOS / Linux
gcloud auth application-default login
gcloud auth application-default set-quota-project YOUR_PROJECT_ID
Why are there two sign-ins?
gcloud auth login authorizes the CLI commands you type.
gcloud auth application-default login authorizes
applications that use ADC, such as this Node server. See
Google's local ADC guide.
5. Create .env and start
Windows PowerShell
Copy-Item .env.example .envmacOS / Linux
cp .env.example .envEdit .env so it contains your own Project ID (file content, not a command):
GOOGLE_CLOUD_PROJECT=your-project-id
PORT=3000npm start
Open http://localhost:3000 in
Chrome. Do not double-click index.html: the page needs
its local server. Press Ctrl+C in the terminal to stop.
npm run dev restarts Node when server files change.
6. Your first scan
- Choose Open Camera and allow camera access.
- Keep the frame empty for a moment (calibration).
- Bring a book, bottle, phone or keyboard into the center and hold still for 3 · 2 · 1.
- Read the result. Allow the microphone when Charon asks what you would like to know.
- Ask a question, then stay quiet for five seconds and watch the conversation pause.
Pasting an access token or a service-account JSON into
.env. This project needs neither. ADC keeps the
credential outside the repository, where Git cannot commit it.
05 / CAMERA
Access the webcam.
What this does
Asks the browser for the camera and shows the live stream in a <video> element.
Why we need it
Browsers only grant camera access from a secure context (localhost or HTTPS) and after a user gesture, so the request runs from the Open Camera click. The stream stays inside the browser; nothing leaves until a frame is captured.
const media = await navigator.mediaDevices.getUserMedia({
audio: false,
video: {
width: { ideal: 1280 },
height: { ideal: 960 },
facingMode: "environment",
},
});
if (token !== generation) {
media.getTracks().forEach((t) => t.stop());
return;
}
stream = media;
video.srcObject = media;
await video.play();
What happens next
A timer starts calling analyzeFrame() ten times a second.
The token !== generation check matters: if the user
pressed Stop while the permission prompt was open, the late stream is
closed immediately instead of switching the camera back on.
Forgetting to stop the tracks. Setting video.srcObject = null
hides the picture, but the camera light stays on until every track's
stop() is called (see stopStream()).
06 / CAMERA
Detect a stable object.
What this does
Decides when something has been placed in the frame and held still enough to photograph.
Why we need it
A scanner that captures on a button press needs two hands. Instead, each frame's center crop is drawn into a 48×48 canvas, converted to grayscale, and compared with the previous frame and with the empty baseline. No machine learning: just arithmetic that any laptop runs at ten frames a second.
const motion = difference(frame, this.previous);
const entered = difference(frame, this.baseline) > 0.055;
this.previous = frame.slice();
const drift = this.anchor ? difference(frame, this.anchor) : 0;
// Allow small hand tremor and sensor noise; substantial motion or sustained
// displacement from the lock anchor still cancels the countdown.
if (!entered || motion > 0.065 || drift > 0.11) {
const cancelled = this.countdownAt !== null;
this.stableSince = null;
this.countdownAt = null;
this.anchor = null;
return { state: entered ? "moving" : "waiting", cancelled };
}
if (this.stableSince === null) {
this.stableSince = time;
this.anchor = frame.slice();
}
const elapsed = time - this.stableSince;
if (elapsed < 400) return { state: "found" };
if (elapsed < 1100) return { state: "steady" };
if (this.countdownAt === null) this.countdownAt = time;
const remaining = 3 - Math.floor((time - this.countdownAt) / 700);
return remaining > 0
? { state: "locking", remaining }
: { state: "capture" };
What happens next
The states become the labels you see (SHOW ME AN OBJECT, HOLD STEADY,
LOCKING 3 · 2 · 1) and capture triggers the photograph.
Change the countdown from 3 seconds to 5. In
lib/stability.js, the countdown is
3 - Math.floor((time - this.countdownAt) / 700): three
steps of 700 ms. Change 3 to 5 (and the
unit test in test/core.test.js that expects
[3, 2, 1]), then run npm test.
07 / CAMERA
Capture a frame.
What this does
Copies one frame of the video onto a canvas and turns it into a JPEG.
Why we need it
A <video> element cannot be uploaded. A canvas gives
actual pixels that toDataURL() can encode as JPEG. The
request starts before the visual scan effect is drawn, so the
effect can never alter what Gemini receives.
capture
.getContext("2d")
.drawImage(source, ...region, 0, 0, capture.width, capture.height);
const image = capture.toDataURL("image/jpeg", 0.88);
mark("capture-encoded", {
width: capture.width,
height: capture.height,
sourceWidth: region[2],
sourceHeight: region[3],
bytes: Math.round((image.length - 23) * 0.75),
});
capture.hidden = false;
video.hidden = true;
$("empty-state").hidden = true;
// Send the untouched captured frame before scan effects or optional visual work.
const token = generation;
controller = new AbortController();
timeout = setTimeout(() => controller?.abort(), 30000);
const pendingResponse = fetch("/api/identify", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ image }),
signal: controller.signal,
});
mark("upload-start");
pendingResponse.catch(() => {}); // Still awaited below; avoid an unhandled rejection if an effect throws.
stopStream();
What happens next
The camera is released, the scan animation plays on #edges,
and when the response arrives displayResult() routes it to
the object, person or document presentation.
- getUserMedia()
- <video>
- stability detection
- 3 · 2 · 1
- canvas.drawImage()
- JPEG
- Node backend
- Gemini
08 / AI
Connect Gemini safely.
The most important lesson in this project. Compare the two shapes:
Because browser code is visible to every visitor. Putting cloud
credentials in script.js would expose them to anyone who
opens DevTools, and they could run up your bill. The Node server is
the only process that authenticates with Google.
Code
if (!process.env.GOOGLE_CLOUD_PROJECT?.trim())
throw new Error(
"Google project configuration is missing; check credentials setup.",
);
client ||= new GoogleGenAI({
enterprise: true,
project: process.env.GOOGLE_CLOUD_PROJECT,
location: "global",
apiVersion: "v1beta1",
httpOptions: { timeout: 25000, retryOptions: { attempts: 1 } },
});
There is no key in this code. GoogleGenAI discovers your
ADC sign-in on the machine. The timeout and single attempt mean a hung
request cannot bill twice.
Putting a Gemini API key directly in frontend JavaScript, or committing a .env file that contains one.
09 / AI
Send an image to Gemini.
What this does
The server decodes the upload to prove it is a real image, then sends the original bytes to Gemini with the prompt and schema.
const response = await withOneRetry(() =>
client.models.generateContent({
model: "gemini-3.8-flash",
contents: [
{
role: "user",
parts: [
{
text: `${prompt} Do not use external search; evidence_urls must be empty. Keep likely_product at the broader family when the exact model is uncertain. Do not infer publisher, ingredients, performance specifications or other facts absent from the image.`,
},
{ inlineData: { mimeType, data: content.toString("base64") } },
],
},
],
config: {
systemInstruction,
responseMimeType: "application/json",
responseJsonSchema: schema,
temperature: 0.1,
maxOutputTokens: 4096,
thinkingConfig: { thinkingLevel: "LOW" },
},
}),
);
const finishReason = response.candidates?.[0]?.finishReason;
if (finishReason !== "STOP")
throw new Error(`Incomplete identity response (${finishReason || "no candidate"})`);
return summarizeIdentity(JSON.parse(response.text));
What happens next
summarizeIdentity() checks every required key against the
schema and applies cautious naming rules before the browser sees anything.
The route wraps failures into safe messages; provider error text never
reaches the page.
One retry, and only a fast one:
withOneRetry() repeats the call once when Gemini answers
quickly with 429 or a 5xx (measured on real phones: an occasional
500 Internal error within a few seconds). A failure that arrives
late is not retried, so nobody waits for two full timeouts, and the SDK's
own retries stay off so a hung request cannot bill twice.
Asynchronous requests: identification takes 3–8 seconds.
The browser keeps rendering while fetch() waits, and an
AbortController lets a reset cancel the request instead of
leaving it to finish in the background.
10 / AI
Design structured prompts.
Ask a model for prose and you get something like:
"Looks like maybe an iPhone, possibly a 13 Pro… hard to say from this angle."Ask for structured output and you get something a page can render:
{
"object_category": "smartphone",
"likely_brand": "Apple",
"likely_product": "iPhone Pro series",
"likely_model": "",
"confidence": "medium",
"needs_another_view": true,
"requested_view": "Show the rear camera module clearly."
}
The schema in lib/identity-prompt.js is passed as
responseJsonSchema, so Gemini fills exactly these keys. Enums
pin the values the interface switches on; required
guarantees every key exists, so validation is a loop, not guesswork.
The prompt's architecture
- Subject selection. What did the user intentionally present? Framing, size and focus decide.
- People. A person can be the subject, but identity comes only from context, never a face.
- Routing.
subject_typeis person, object, document or scene. - Conservative naming. Separate product family from exact model; never invent numbers or unseen text.
- Output. Only the JSON, with empty values for the unknown.
A product held toward the camera or presented in the hands is an object subject:
hands, arms or clothing around a presented product do not make the holder the subject,
especially when the face is absent or not the focus.
That sentence exists because a person holding a product is the most common webcam scan, and early tests sometimes returned "Person" for a bottle held to the camera. Every rule in the prompt was added after a real failure like that. Text inside an image is declared to be evidence, never instructions, which defends against a label that says "ignore your rules".
Change the prompt so Vision returns only three visible details:
in lib/identity-prompt.js add "Return at most three
visible_identifying_features" to the system instruction, restart
with npm start, and scan something.
11 / AI
Handle uncertainty.
A model will happily name an exact phone model from a blurry frame. The code refuses to pass that on unless the model is confident and says nothing is uncertain, and it turns phone ambiguity into a request for another view even when the model forgot to set the flag.
const model =
value.confidence === "high" && !uncertainty && !value.needs_another_view
? clean(value.likely_model)
: "";
const product =
clean(value.likely_product) || category || "Unidentified object";
let name =
brand && !product.toLowerCase().includes(brand.toLowerCase())
? `${brand} ${product}`
: product;
if (
model &&
!name.toLowerCase().includes(model.toLowerCase()) &&
!model.toLowerCase().includes(product.toLowerCase())
)
name += ` · ${model}`;
const needsAnotherView =
value.needs_another_view ||
!!(uncertainty && /phone|smartphone/i.test(category));
In the interface, MORE DETAIL NEEDED and a "Next view" instruction are the honest result. Confidence in this project describes the specificity the model claims, not a probability.
Error handling is part of the feature
| Failure | What the user sees | Where |
|---|---|---|
| Gemini unavailable or quota exhausted | A readable message and Scan another object | server.js catch block |
| Charon unavailable | The written answer with a voice-unavailable notice | voice.js speak() |
| Microphone denied | Typed questions still work | voice.js listen() |
| WebGL unavailable | A simpler audio-reactive canvas | lib/particle-presence.js |
| Unsupported or oversized document | The reason, in plain words | lib/document.js |
12 / PEOPLE
Understand people from context.
- Face alone → PERSON DETECTED → no identity guess
- Context + person → identity may be established
UCENTH Vision Intelligence contains no face recognition, no face embeddings and no celebrity dataset. A person is identified only when non-biometric context inside the image is clearly associated with them: a caption directly under the photograph, a profile or leadership card, an article heading, a name badge. A name that merely appears somewhere on a screenshot is not enough, and with several names or several people nothing is assigned to faces.
// A person's name survives only with an explicit non-biometric source and evidence.
const person = value.subject_type === "person";
const identityName = person ? clean(value.person_identity_name) : "";
const identityEvidence = person ? clean(value.person_identity_evidence) : "";
const identitySource =
person && value.person_identity_source !== "none" ? value.person_identity_source : "none";
const identityEstablished =
person &&
value.person_identity_established === true &&
!!identityName &&
identitySource !== "none" &&
!!identityEvidence;
Even if the model writes a name, it is dropped unless it also names the
source (caption, visible text or page context) and quotes the evidence.
During a conversation, if you say "this is Jensen Huang", that name becomes
user-provided context (identitySource: "user_context")
for later answers; it is never promoted to a verified identity.
Identifying strangers from their faces is a privacy harm and, in many places, unlawful. Reading a caption is what a human would do. The distinction is enforced in code, not just requested in the prompt.
13 / DOCUMENTS
Read PDFs.
- PDF with selectable text → PDF.js extracts the text locally
- PDF with scanned pages → the PDF is attached so Gemini reads the pages
- DOCX → mammoth → structured text
- Camera / JPG / PNG → Gemini decides it is a document
Why not screenshot every file? Because a text PDF already contains its text. Extracting it locally is instant, free, and lets a 60-page file travel as text instead of 60 images. Only pages that have no text (scans) need the model's reading.
const task = pdfjs.getDocument({
data: new Uint8Array(buffer),
isEvalSupported: false,
disableFontFace: true,
useSystemFonts: false,
stopAtErrors: true,
verbosity: 0,
});
Limits protect cost and memory: 15 MB, 60 pages, at most 25 scanned pages, about 200,000 characters. Larger files receive a clear message rather than a silent cut.
14 / DOCUMENTS
Read Word documents.
A .docx file is an Open XML package: a ZIP
archive containing XML parts such as word/document.xml.
mammoth reads that XML and produces simple HTML. UCENTH Vision Intelligence extracts
headings, paragraphs, lists and tables, and reduces the HTML to plain text
with structure markers a model understands.
try {
result = await mammoth.convertToHtml(
{ buffer },
{ convertImage: mammoth.images.imgElement(async () => ({ src: "" })) },
);
} catch {
return {
error:
"This Word file could not be read. Save it as .docx and try again.",
};
}
const text = htmlToText(result.value);
What is deliberately not executed: macros, OLE objects,
scripts and embedded programs. mammoth never runs them, and embedded images
are dropped by that imgElement callback.
15 / DOCUMENTS
Translate documents.
- Original document
- Language detection (name + BCP-47 code)
- English? YES → no translation
- English? NO → English translation, original preserved
The original is always kept: it is the truth, and a translation is an
interpretation. The viewer shows Original and English as tabs. Direction
and language follow the text shown: an Arabic original renders
dir="rtl", its English translation dir="ltr".
CJK languages get a font stack with full glyph coverage.
// Direction and language follow the text actually shown; translations are never mirrored.
panel.setAttribute("dir", english ? "ltr" : data.language.direction);
panel.setAttribute("lang", english ? "en" : data.language.code);
panel.dataset.script = english ? "" : LANGUAGE_FONT(data.language.code);
Translation is bounded (about 20,000 characters in the first pass) and further pages can be requested in conversation. Numbers, dates and negations are checked in the real-document test suite, because a translation that drops a "not" is worse than none.
16 / VOICE
Recognize speech.
- Microphone
- Chrome speech recognition
- Recognized text
- UCENTH server (/api/follow-up)
- Gemini
Chrome's SpeechRecognition API turns speech into text. Be
honest with your users: it may send microphone audio to Google's speech
service. It is not offline speech recognition, and
UCENTH Vision Intelligence never claims it is. The app itself has no microphone-upload
endpoint and never records audio.
const recognition = new Recognition();
c.recognition = recognition;
recognition.lang = "en-US";
recognition.interimResults = true;
recognition.continuous = true;
Desktop Chrome tolerates a second getUserMedia() stream (for the
particle analyser) alongside SpeechRecognition. Android and iOS do not: the
recogniser then hears nothing or fails. So on phones listenNative()
opens no stream and the particles use a restrained listening pulse driven by
recognition events. Browsers without a usable native recogniser (iOS Chrome,
some Safari sessions) record a short clip with MediaRecorder and send it to
/api/transcribe, where Gemini transcribes it in memory; the loop
and the interface stay identical.
Speech is confirmed by the recognizer's own classifier (held for 200 ms) or by a transcript, never by microphone volume, so a loud room does not look like a question.
17 / VOICE
Generate Charon voice.
- Gemini answer (text)
- /api/speech → Cloud Text-to-Speech, voice en-US-Chirp3-HD-Charon
- WAV audio (LINEAR16)
- Browser: decodeAudioData() → playback
const response = await client.request({
url: "https://texttospeech.googleapis.com/v1/text:synthesize",
method: "POST",
timeout: 20000,
retry: false,
headers: { "x-goog-user-project": process.env.GOOGLE_CLOUD_PROJECT },
data: {
input: { text },
voice: { languageCode: "en-US", name: VOICE },
audioConfig: { audioEncoding: "LINEAR16" },
},
});
if (!response.data.audioContent)
throw new Error("Speech audio unavailable");
return Buffer.from(response.data.audioContent, "base64");
Charon was chosen after measuring real latency: about 3.3 s on first use
and a warm median of about 1.7 s, faster and more natural than the
alternatives tried. Uncompressed WAV is requested because
decodeAudioData() handles it instantly, which matters for the
timing below. Charon speaks identifications, summaries and answers; it
never reads a whole document aloud.
18 / VOICE
Build hands-free conversation.
- LISTENING
- USER SPEAKING
- THINKING (Gemini answers, Charon prepares)
- VISION SPEAKING (text revealed as audio starts)
- LISTENING again, or CONVERSATION PAUSED after 5 s of silence
Why recognition is off while Charon speaks
If the microphone stayed open, the speakers would play Charon's voice straight back into speech recognition, which would transcribe it as a new question, answer it, and loop forever. So the microphone is released before playback and reopened only after playback ends plus a short echo guard.
activate(c);
stopMic(c);
setAudioSession("playback");
const play = (buffer) => {
c.outputAnalyser = audioContext.createAnalyser();
c.outputAnalyser.fftSize = 2048;
c.outputAnalyser.smoothingTimeConstant = 0.65;
c.outputAnalyser.connect(audioContext.destination);
c.playback = audioContext.createBufferSource();
c.playback.buffer = buffer;
c.playback.connect(c.outputAnalyser);
c.particles.connect(c.outputAnalyser, "charon");
c.playback.onended = () => {
if (!valid(c, turn)) return;
c.playback.disconnect();
c.playback = null;
c.outputAnalyser?.disconnect();
c.outputAnalyser = null;
c.particles.disconnect();
mark("playback-end");
returnToListening(c, turn);
};
c.playback.start();
};
c.ui.answer.textContent = text;
c.pendingAnswer = null;
state(c, "VISION_SPEAKING");
play(audio);
mark("playback-start", { contextState: audioContext.state, audioSession: navigator.audioSession?.type || "none" });
// Output probe: iOS can leave a context that says "running" but renders nothing
// (seen physically: answer shown, no sound, playback never ending). A short way
// into playback the analyser must show signal; exact zeros end the turn at once so
// the written answer stands and listening continues, instead of a silent wait.
const probeAt = Math.min(600, Math.max(120, audio.duration * 500));
const probe = () => {
c.playbackProbe = setTimeout(async () => {
if (!valid(c, turn) || !c.playback || !c.outputAnalyser) return;
const data = new Float32Array(c.outputAnalyser.fftSize);
c.outputAnalyser.getFloatTimeDomainData(data);
let sum = 0;
for (const v of data) sum += v * v;
const rms = Math.sqrt(sum / data.length);
diag("playback", { rms: +rms.toFixed(4), contextState: audioContext.state, audioSession: navigator.audioSession?.type || "none", probeAt: Math.round(probeAt), recovered: c.playbackRecovered });
if (rms > 0 || c.playbackRecovered) return;
// Nothing is being rendered. Rebuilding the context is not an option here (a
// context created outside a tap stays suspended on iOS until the next tap), so
// the written answer stands, the turn ends now instead of after a silent clip,
// and listening continues.
c.playbackRecovered = true;
diag("playback.silent", { contextState: audioContext.state });
c.playback.onended = null;
try {
c.playback.stop();
} catch {}
c.playback.disconnect();
c.playback = null;
c.outputAnalyser.disconnect();
c.outputAnalyser = null;
c.particles.disconnect();
mark("playback-end", { silent: true });
returnToListening(c, turn);
}, probeAt);
};
probe();
The five-second timeout
After Charon finishes, LISTENING waits up to five seconds for genuine speech to start. If none comes, recognition and the microphone tracks are stopped and the state becomes CONVERSATION PAUSED. It does not restart on its own. This is about resources (an open microphone costs CPU and battery), privacy (a microphone should not stay open indefinitely) and experience (users should know when they are being listened to). Once speech starts the timer is cancelled, so a long question is never cut off.
State management prevents races
Every conversation has a turn counter, and every async continuation
checks valid(c, turn) first. Reset during THINKING? The old
Gemini answer arrives, fails the check, and is ignored. Charon audio for a
previous object returns late? Ignored. This is the same idea as
generation in script.js, and it is cheaper and
safer than trying to cancel everything.
Leaving speech recognition active while text-to-speech plays.
19 / VISUALS
Build the particle presence.
The presence is 12,000 points on a sphere, uploaded to the GPU once. Each frame a vertex shader moves every point according to four audio values and time, so the CPU does almost nothing. Positions follow a Fibonacci spiral, which spreads points evenly over a sphere.
float bass=sqrt(uAudio.y),voice=sqrt(uAudio.z),air=sqrt(uAudio.w),energy=uAudio.x;
float broad=sin(n.x*3.1+n.y*2.0+t*.65)*cos(n.z*2.7-t*.4);
float flow=sin(n.y*6.0+n.x*3.0-t*1.1)*cos(n.z*4.0+t*.6);
float fine=sin(n.x*25.0+n.z*17.0+t*2.1)*sin(n.y*19.0-t*1.7);
float base=.055*sin(n.y*4.0+n.z*3.0+t*.23)+.035*cos(n.x*5.0-t*.18);
float deformation=base+uMotion*(bass*.52*broad+voice*.38*flow+air*.11*fine);
float breath=uMotion*.008*sin(t*.75);
p*=1.0+deformation+breath+energy*mix(.025,.09,uMotion);
sqrt() flattens loud peaks so quiet speech still moves the
field. Bass drives a broad swell, the voice band rolling folds, the air
band fine shimmer; a twist and shear make speech fold the sphere rather
than inflate it. Quality tiers cap the pixel ratio, particle count and frame
rate (60 desktop, 30 mobile and low power, 20 with reduced motion), and a
Canvas 2D fallback keeps a real loudness response without WebGL.
Change the particle density. In lib/particle-presence.js,
resize() sets points to 12000 on desktop and
6000 on mobile. Try 4000 and 20000 and watch the FPS in the metrics event.
20 / VISUALS
Connect particles to real audio.
- Microphone or Charon audio
- Web Audio API
- AnalyserNode
- Frequency and amplitude data
- WebGL particle deformation
analyser.getFloatTimeDomainData(timeData);
analyser.getFloatFrequencyData(freqData);
let sum = 0;
for (const v of timeData) sum += v * v;
const rms = Math.sqrt(sum / timeData.length);
maxRms = Math.max(maxRms, rms);
const band = (lo, hi) => {
const hz = context.sampleRate / analyser.fftSize;
let sum = 0,
n = 0;
for (
let i = Math.ceil(lo / hz);
i < Math.min(freqData.length, Math.floor(hi / hz));
i++
) {
sum += Math.pow(10, freqData[i] / 10);
n++;
}
return Math.sqrt(sum / Math.max(n, 1));
};
const gain = activeSource === "microphone" ? 2.5 : 1;
raw = [
clamp(rms * 6 * gain),
clamp(band(70, 260) * 14 * gain),
clamp(band(260, 2500) * 25 * gain),
clamp(band(2500, 8500) * 42 * gain),
];
The microphone stream is connected to an AnalyserNode but not to the speakers, so it can be measured without feedback. Charon's decoded buffer plays through its own AnalyserNode into the speakers. The particles therefore react to what is actually happening, not to a canned animation, and a noise gate measured in the first 450 ms keeps a quiet room from looking like speech.
21 / SECURITY
Protect API credentials.
- Credentials live only on the server, discovered through ADC. No key in any file.
.envholds a project ID, not a secret, and is still ignored by Git.- The server serves an explicit allowlist of files.
lib/, tests and.envare 404. - It binds to 127.0.0.1 and checks Host and Origin, so other websites in your browser cannot use it.
- A strict Content-Security-Policy allows scripts only from the same origin.
res.setHeader(
"Content-Security-Policy",
"default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data: blob:; connect-src 'self'; media-src 'self' blob:; frame-ancestors 'none'; base-uri 'none'; form-action 'none'",
);
const host = req.headers.host;
if (!allowedHosts.test(host || ""))
return json(res, 403, { error: "This host is not served here." });
allowedHosts defaults to localhost; a hosted deployment passes its own
pattern, and the scheme (http locally, https behind a proxy) comes from the
request, so the same code serves both. CORS, briefly: browsers block cross-origin requests by
default, and this server sends no Access-Control-Allow-Origin
header, so a page on another origin cannot read its responses. The
Origin and Sec-Fetch-Site checks add a second layer.
22 / SECURITY
Validate uploaded files.
A file extension and the browser's declared MIME type are labels anyone can change. The real format is in the first bytes, the magic bytes:
if (buffer.length > 4 && buffer.subarray(0, 5).toString("latin1") === "%PDF-")
return "pdf";
if (
buffer.length > 3 &&
buffer[0] === 0xff &&
buffer[1] === 0xd8 &&
buffer[2] === 0xff
)
return "image";
if (
buffer.length > 7 &&
buffer
.subarray(0, 8)
.equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))
)
return "image";
if (
buffer.length > 3 &&
buffer[0] === 0x50 &&
buffer[1] === 0x4b &&
buffer[2] === 0x03 &&
buffer[3] === 0x04
) {
// A DOCX is a ZIP whose central directory names word/document.xml.
const tail = buffer
.subarray(Math.max(0, buffer.length - 512 * 1024))
.toString("latin1");
if (tail.includes("word/document.xml")) return "docx";
}
return null;
validateFile() then requires the detected format to agree with
both the declared type and the extension, and applies a per-format size
limit. Images are additionally decoded with sharp to prove they are images.
The file name is only ever displayed; it is never used as a path.
Trusting a file because its extension says .pdf.
23 / SECURITY
Handle untrusted documents.
- PDF script evaluation is disabled (
isEvalSupported: false), and PDF.js is used only to count pages and extract text; no rendering or scripting sandbox is loaded. - Word macros and embedded objects are never executed. mammoth reads XML; that is all.
- In-memory processing. The upload is a raw request body buffered up to the limit, parsed and forgotten. No temporary files exist, so nothing can be served or left behind.
- Limits on size, page count, scanned pages and text length stop a hostile 400-page file from reaching the model.
- Untrusted text. Extracted text is passed to Gemini labelled as data, and the prompt says it is never an instruction.
- No fetching. Links inside documents are never followed.
Everything the browser displays is set with textContent,
never innerHTML, so text from a document or a model cannot
inject markup into the page.
24 / BUILD YOUR OWN
Reuse Gemini in your project.
Minimum architecture: frontend → your backend → Gemini.
Camera mini-lesson (frontend only)
This is the capture feature on its own. It needs no server until the last line.
<video id="cam" autoplay playsinline muted></video>
<canvas id="shot" hidden></canvas>
<button id="go">Open camera</button> <button id="snap">Capture</button>
<script type="module">
const cam = document.getElementById("cam"), shot = document.getElementById("shot");
document.getElementById("go").onclick = async () => {
cam.srcObject = await navigator.mediaDevices.getUserMedia({ video: true });
};
document.getElementById("snap").onclick = async () => {
shot.width = cam.videoWidth; shot.height = cam.videoHeight;
shot.getContext("2d").drawImage(cam, 0, 0);
const image = shot.toDataURL("image/jpeg", 0.88);
cam.srcObject.getTracks().forEach((t) => t.stop());
const result = await fetch("/api/identify", { method: "POST",
headers: { "Content-Type": "application/json" }, body: JSON.stringify({ image }) }).then((r) => r.json());
console.log(result);
};
</script>
Gemini mini-lesson (backend)
One route that receives the image and returns structured JSON. Adapted from server.js and lib/gemini.js.
import http from "node:http";
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({ enterprise: true, project: process.env.GOOGLE_CLOUD_PROJECT, location: "global" });
const schema = { type: "object", properties: { name: { type: "string" }, confidence: { type: "string", enum: ["high", "medium", "low"] } }, required: ["name", "confidence"] };
http.createServer(async (req, res) => {
if (req.method !== "POST" || req.url !== "/api/identify") { res.writeHead(404); return res.end(); }
let body = ""; for await (const chunk of req) body += chunk;
const data = JSON.parse(body).image.split(",")[1]; // strip the data-URL prefix
const r = await ai.models.generateContent({
model: "gemini-3.8-flash",
contents: [{ role: "user", parts: [{ text: "Name the object. Return JSON." }, { inlineData: { mimeType: "image/jpeg", data } }] }],
config: { responseMimeType: "application/json", responseJsonSchema: schema, temperature: 0.1 },
});
res.writeHead(200, { "Content-Type": "application/json" });
res.end(r.text);
}).listen(3000, "127.0.0.1");
Run it with node --env-file=.env server.mjs after the same ADC
sign-in as UCENTH Vision Intelligence. In a real project add what server.js
adds: size limits, image decoding, origin checks, safe errors and a static
allowlist.
25 / BUILD YOUR OWN
Reuse voice in your project.
Pattern: speech recognition → question → backend → response → TTS.
const Recognition = window.SpeechRecognition || window.webkitSpeechRecognition;
const audioContext = new AudioContext(); // create inside a click handler
async function askByVoice() {
const recognition = new Recognition();
recognition.lang = "en-US";
recognition.onresult = async (event) => {
const question = event.results[0][0].transcript;
recognition.abort(); // mic off before we speak
const { answer } = await fetch("/api/ask", { method: "POST",
headers: { "Content-Type": "application/json" }, body: JSON.stringify({ question }) }).then((r) => r.json());
const wav = await fetch("/api/speech", { method: "POST",
headers: { "Content-Type": "application/json" }, body: JSON.stringify({ text: answer }) }).then((r) => r.arrayBuffer());
const source = audioContext.createBufferSource();
source.buffer = await audioContext.decodeAudioData(wav);
source.connect(audioContext.destination);
source.onended = () => setTimeout(askByVoice, 900); // echo guard, then listen again
source.start();
};
recognition.start();
}
The server side is lib/conversation.js: createSpeech()
is reusable as it is, and createFollowUp() shows how to give a
question context. Add a speech-start timeout so the microphone never stays
open indefinitely, and tell users that recognition may use Google's service.
26 / BUILD YOUR OWN
Reuse document intelligence.
Pattern: PDF/DOCX → extraction → Gemini → structured analysis. No scanner required.
import { readFile } from "node:fs/promises";
import { validateFile, createDocumentAnalyzer } from "./lib/document.js";
const buffer = await readFile(process.argv[2]);
const check = validateFile({ buffer, mimeType: "application/pdf", name: process.argv[2] });
if (check.error) throw new Error(check.error);
const analyze = createDocumentAnalyzer();
const result = await analyze({ kind: check.kind, buffer, mimeType: "application/pdf", name: process.argv[2] });
console.log(result.documentType, result.language.primary, result.summary);
console.log(result.fields); // grounded key details
console.log(result.pages[0].english || result.pages[0].original);
lib/document.js has no dependency on the browser or the
scanner. extractPdf(), extractDocx() and
sniff() are also useful on their own, for example in a script
that indexes a folder of files.
27 / BUILD YOUR OWN
Ideas to experiment with.
- Particle mini-lesson. Create an AnalyserNode from any
<audio>element (audioContext.createMediaElementSource()) and pass it tocreateParticlePresence(host).connect(analyser, "charon"). No Gemini needed. - Add a document type. Extend
typeNamesinlib/document.jswith, say, "menu" fields, and add a fixture totest/document-real.js. - Change the voice language. Cloud Text-to-Speech has many voices; change
VOICEandlanguageCodeinlib/conversation.jsandrecognition.langinvoice.js. - Make the countdown adaptive. Shorten it when the object has been steady for longer.
- Log token use.
/api/documentalready returnsusage; show it in the details disclosure to make costs visible. - Write a test first. Copy a case from
test/voice-browser.jsand make it fail before you changevoice.js.
Reading code teaches what it does. Changing it teaches why it is the way it is. The tests will tell you when you have broken something.
28 / REFERENCE
Environment variables.
| Variable | Meaning |
|---|---|
GOOGLE_CLOUD_PROJECT | Your Google Cloud Project ID. Required. Read by the SDKs and sent as the quota project. |
PORT | Local port, default 3000. The server always binds to 127.0.0.1. |
GOOGLE_APPLICATION_CREDENTIALS | Optional absolute path to a service-account JSON. Not needed with ADC sign-in; if set, it overrides ADC. |
npm start runs node --use-system-ca --env-file=.env server.js:
the system certificate store is enabled for managed networks and the
.env file is loaded without any extra dependency.
Costs, honestly
Each identification, document analysis, follow-up and speech request is billed to your project. Measured during release testing: one photographed page used about 1,900 input and 450–700 output tokens; a 12-page text PDF about 2,750 input and 650 output. Check Gemini pricing and Text-to-Speech pricing. The local server allows one active request and a small number per minute so a stuck loop cannot run up a bill.
Production versus this educational edition
This open-source learning edition is complete and runs on your own machine.
The hosted UCENTH service may apply its own usage limits and abuse controls
to protect shared cloud resources; those operational controls are not part of
this source, and this guide does not teach how to bypass them. The small local
limits you see in server.js exist to protect your own billing.
29 / REFERENCE
Troubleshooting.
gcloud.ps1 or npm.ps1 cannot be loaded
Use gcloud.cmd or npm.cmd in PowerShell. Reopen the terminal after installing the CLI. Do not weaken the execution policy.
“Identification is not ready”
Check the ADC sign-in, GOOGLE_CLOUD_PROJECT, that both APIs are enabled, and billing. Restart Node after editing .env. If GOOGLE_APPLICATION_CREDENTIALS is set, it overrides ADC.
“Identification could not complete” or a timeout
Check your connection and Google service status, then retry once. The app returns its own safe message rather than raw provider errors. Never paste credential files or tokens into an issue.
Quota exhausted or scan limit reached
The local server allows one active request and six identifications per minute. A Google quota or billing error needs the project's quota and billing settings.
Camera blocked, missing or busy
Allow Camera for localhost in Chrome site settings and in the operating system. Close other apps using the webcam, then choose Scan another object.
Voice unavailable or the microphone was denied
Allow the microphone for localhost. If Charon fails, the written answer still appears and typing keeps working. Check that texttospeech.googleapis.com is enabled.
This PDF or Word file is not supported
Limits: PDF 15 MB and 60 pages (25 scanned), Word 10 MB, about 200,000 characters of text. Encrypted PDFs and legacy .doc files are not read. The message names the reason.
Certificate verification fails on a managed network
Ask your administrator for the trusted CA bundle and follow Google's proxy and certificate guide. Node already uses the system certificate store; do not disable TLS verification.
.env missing, port busy or install fails
Create .env from the template. If port 3000 is busy, set another PORT and use the address Node prints. For install failures check the Node version, network access and Sharp installation help.
30 / REFERENCE
Architecture.
Three browser modules and one server, connected by DOM events and four HTTP
routes. ARCHITECTURE.md in the source folder documents the
details: request shapes, limits, the state machine and the test strategy.
| Route | Input | Output |
|---|---|---|
POST /api/identify | JSON with a JPEG/PNG data URL (≤ 2 MB) | Structured identification (object, person or document routing) |
POST /api/document | Raw PDF, DOCX, JPEG or PNG body | Type, language, summary, fields, pages with original and English text |
POST /api/follow-up | Question, identification, image and/or document context, recent history | Answer text plus a user-supplied name if stated |
POST /api/speech | Answer text (≤ 1,800 characters) | WAV audio in the Charon voice |
Privacy summary
One captured frame, uploaded files and their extracted text, recognized questions and answer text go to Google's services; live video never does, and raw microphone audio is never recorded by the app (Chrome's recognition may process it). Everything is held in memory for the session and cleared by Scan another object. Think before uploading highly sensitive documents.
Tests
npm test
npm run test:browser
npm run release:check
Unit tests run the real routes with fake model functions and no billing.
Chrome tests drive the interface with mocked responses. Two opt-in suites
(test:person, test:document) call live Gemini with
synthetic fixtures generated at run time.
Open source, by UCENTH
UCENTH Vision Intelligence is an open-source educational project by UCENTH — Universal Central Host, released under the MIT License. Dependencies keep their own licenses; see third-party notices. View source on GitHub · Report an issue