Bottom Linear Gradient  Lines image

Article

7 min

read

Detecting Visitors in the Browser for a Voice AI Agent

Who's there, without asking the AI

Adam Kalsey

Adam Kalsey

EVP, Product

Detecting Visitors in the Browser

In this article

Share

Angular Gradient Image

Build it free.

Create a space and ship your first call flow in minutes.

Subscribe

Tags

Voice AI

AI Agents

Developer Tutorials

You're reading part 5 of a tutorial on building a talking jack-o'-lantern with SignalWire. If you're new, start with part 1. Part 4 taught the pumpkin to see the people in front of it, but it still has to know when they arrive and leave. In this part the pumpkin's page watches the camera itself and decides who's standing on the stage, a patch of ground in front of the prop. It tells the live call when a group steps up or walks away.

The agent could watch for people with its own vision, but it would be too slow. A vision model takes 200 milliseconds or more to read a frame, and it only looks when the agent decides to. On a busy sidewalk, a kid can step up, say "trick or treat," and leave before the agent's next look. A small person detector in the browser checks the camera several times a second. Each check takes a few milliseconds, so it catches people before they leave.

Run a person detector in the browser

The page uses the object detector from Google's MediaPipe with the EfficientDet-Lite0 model, which returns a box around each person it finds. I limit it to one category, people, and drop anything it's less than 40% sure of. It runs on the GPU through WebGL where it can and on the CPU everywhere else. It ran fine on an older Chromebook and a Raspberry Pi; you don't need to throw much hardware at this.

for (const delegate of ["GPU", "CPU"]) {
  try {
    this.detector = await ObjectDetector.createFromOptions(files, {
      baseOptions: { modelAssetPath: MODEL, delegate },
      runningMode: "VIDEO",
      scoreThreshold: 0.4,
      categoryAllowlist: ["person"],
    });
    this.delegate = delegate;
    return;
  } catch (e) {
    if (delegate === "CPU") throw e;
  }
}
for (const delegate of ["GPU", "CPU"]) {
  try {
    this.detector = await ObjectDetector.createFromOptions(files, {
      baseOptions: { modelAssetPath: MODEL, delegate },
      runningMode: "VIDEO",
      scoreThreshold: 0.4,
      categoryAllowlist: ["person"],
    });
    this.delegate = delegate;
    return;
  } catch (e) {
    if (delegate === "CPU") throw e;
  }
}
for (const delegate of ["GPU", "CPU"]) {
  try {
    this.detector = await ObjectDetector.createFromOptions(files, {
      baseOptions: { modelAssetPath: MODEL, delegate },
      runningMode: "VIDEO",
      scoreThreshold: 0.4,
      categoryAllowlist: ["person"],
    });
    this.delegate = delegate;
    return;
  } catch (e) {
    if (delegate === "CPU") throw e;
  }
}
for (const delegate of ["GPU", "CPU"]) {
  try {
    this.detector = await ObjectDetector.createFromOptions(files, {
      baseOptions: { modelAssetPath: MODEL, delegate },
      runningMode: "VIDEO",
      scoreThreshold: 0.4,
      categoryAllowlist: ["person"],
    });
    this.delegate = delegate;
    return;
  } catch (e) {
    if (delegate === "CPU") throw e;
  }
}

The detector looks for whole bodies, because masks defeat face detection and plenty of visitors wear one. On a fast machine it runs every 250 milliseconds. On a slower one, the page times each detection and backs off to about two and a half times that, up to once a second.

Decide who's on stage

A webcam sees a lot more than the people talking to the pumpkin, including the sidewalk, the street, and families walking past to the next house. The page only cares about who has stopped in front of the prop. I mark a patch of ground in front of the pumpkin as the stage by dragging a rectangle over the camera view. A person is on stage when their feet are inside it and they've stopped moving. A show starts when someone is on stage, and it ends when most of the people who started it have gone.

Feet work better than size. The camera is wide and sees well past the yard, so a tall adult on the sidewalk can look as big as a child up close. The bottom center of each person's box is where their feet are, and that point has to land inside the stage.

const feet = { x: c.x, y: Math.min(1, track.box.y + track.box.h) };
const { zoneLeft, zoneRight, zoneTop, zoneBottom } = this.s;
const inFront =
  t - track.lastSeen < 500 &&
  track.box.h >= this.s.minHeight &&
  feet.x >= Math.min(zoneLeft, zoneRight) &&
  feet.x <= Math.max(zoneLeft, zoneRight) &&
  feet.y >= Math.min(zoneTop, zoneBottom) &&
  feet.y <= Math.max(zoneTop, zoneBottom);
const still = anchor >= 0 && drift <= this.s.maxDrift * (span / 1000);
const onStage = inFront && still;
const feet = { x: c.x, y: Math.min(1, track.box.y + track.box.h) };
const { zoneLeft, zoneRight, zoneTop, zoneBottom } = this.s;
const inFront =
  t - track.lastSeen < 500 &&
  track.box.h >= this.s.minHeight &&
  feet.x >= Math.min(zoneLeft, zoneRight) &&
  feet.x <= Math.max(zoneLeft, zoneRight) &&
  feet.y >= Math.min(zoneTop, zoneBottom) &&
  feet.y <= Math.max(zoneTop, zoneBottom);
const still = anchor >= 0 && drift <= this.s.maxDrift * (span / 1000);
const onStage = inFront && still;
const feet = { x: c.x, y: Math.min(1, track.box.y + track.box.h) };
const { zoneLeft, zoneRight, zoneTop, zoneBottom } = this.s;
const inFront =
  t - track.lastSeen < 500 &&
  track.box.h >= this.s.minHeight &&
  feet.x >= Math.min(zoneLeft, zoneRight) &&
  feet.x <= Math.max(zoneLeft, zoneRight) &&
  feet.y >= Math.min(zoneTop, zoneBottom) &&
  feet.y <= Math.max(zoneTop, zoneBottom);
const still = anchor >= 0 && drift <= this.s.maxDrift * (span / 1000);
const onStage = inFront && still;
const feet = { x: c.x, y: Math.min(1, track.box.y + track.box.h) };
const { zoneLeft, zoneRight, zoneTop, zoneBottom } = this.s;
const inFront =
  t - track.lastSeen < 500 &&
  track.box.h >= this.s.minHeight &&
  feet.x >= Math.min(zoneLeft, zoneRight) &&
  feet.x <= Math.max(zoneLeft, zoneRight) &&
  feet.y >= Math.min(zoneTop, zoneBottom) &&
  feet.y <= Math.max(zoneTop, zoneBottom);
const still = anchor >= 0 && drift <= this.s.maxDrift * (span / 1000);
const onStage = inFront && still;

The page measures stillness by comparing where a person is now with their newest position that's at least half a second old. Browser timers fire anywhere from 190 to 310 milliseconds apart when asked for 250, so a check comparing only neighboring frames could miss someone walking past. Someone on stage when a show starts is in its cast. Anyone who steps up later joins the audience without restarting anything, and someone who never stops is a passerby. For testing, the page draws each box over the video in its own color: orange for the cast, yellow for the audience, and grey for passersby. That shows me at a glance how the page sees each person, so I can adjust the stage.

Tell people apart in the dark

The detector finds people, but it doesn't know who they are from one frame to the next. When a new group steps into the spots the last group left, the page has to recognize them as different people. Each box gets an appearance signature for that, made of the average color of its top half and its bottom half, six numbers in all.

At night that falls apart, because everything is close to black and everyone's colors look the same. I scale each frame so the whole picture averages mid-grey before taking the colors. A witch and a skeleton still come out different after the scaling, even when the raw pixels are nearly identical. Next year I'll light the stage better, perhaps with infrared lights and an infrared camera.

export function frameGain(pixels) {
  return 0.5 / Math.max(stats(pixels).mean, 0.02);
}
export function frameGain(pixels) {
  return 0.5 / Math.max(stats(pixels).mean, 0.02);
}
export function frameGain(pixels) {
  return 0.5 / Math.max(stats(pixels).mean, 0.02);
}
export function frameGain(pixels) {
  return 0.5 / Math.max(stats(pixels).mean, 0.02);
}

The page also watches for the whole picture changing at once, as when someone bumps the camera. Real people walking in and out never change that much of the frame together. When it happens, the page forgets everyone and ends the current show, and whoever is on stage afterward starts the next one.

Tell the call

When a show starts or ends, the page posts "arrived" or "left" to my server, along with each cast member's measurements and signature. Only numbers leave the page; the pictures stay on the pumpkin's computer. Before posting, the page waits for the pumpkin to stop talking, because a message into the call cuts off whatever the pumpkin is saying. The page knows when the pumpkin is talking because its mic gate, which you'll see in part 6, is muting the microphone.

#report(event) {
  this.reports = this.reports.then(() => this.#whenQuiet()).then(() => this.#send(event));
}

async #whenQuiet() {
  const started = performance.now();
  while (this.isTalking() && performance.now() - started < QUIET_WAIT_MS) {
    await new Promise((resolve) => setTimeout(resolve, 100));
  }
}
#report(event) {
  this.reports = this.reports.then(() => this.#whenQuiet()).then(() => this.#send(event));
}

async #whenQuiet() {
  const started = performance.now();
  while (this.isTalking() && performance.now() - started < QUIET_WAIT_MS) {
    await new Promise((resolve) => setTimeout(resolve, 100));
  }
}
#report(event) {
  this.reports = this.reports.then(() => this.#whenQuiet()).then(() => this.#send(event));
}

async #whenQuiet() {
  const started = performance.now();
  while (this.isTalking() && performance.now() - started < QUIET_WAIT_MS) {
    await new Promise((resolve) => setTimeout(resolve, 100));
  }
}
#report(event) {
  this.reports = this.reports.then(() => this.#whenQuiet()).then(() => this.#send(event));
}

async #whenQuiet() {
  const started = performance.now();
  while (this.isTalking() && performance.now() - started < QUIET_WAIT_MS) {
    await new Promise((resolve) => setTimeout(resolve, 100));
  }
}

The server turns each event into a system message in the live call with our REST API's calling.ai_message. The "arrived" message asks for a greeting that suits anyone, a look, and a call to notice_visitors, the tool that reports who's there. That way the pumpkin greets new people the moment they arrive.

SCENE_MESSAGES = {
    "arrived": f"New visitors have just stepped up in front of you. Acknowledge them at once "
               f"with {FIRST_LINE}; in the same reply, look at them with get_visual_input "
               f"and call notice_visitors.",
    "left": "The people you were talking to have walked away. Call visitors_left (in gentle "
            "mode, visitors_left_gently).",
}
SCENE_MESSAGES = {
    "arrived": f"New visitors have just stepped up in front of you. Acknowledge them at once "
               f"with {FIRST_LINE}; in the same reply, look at them with get_visual_input "
               f"and call notice_visitors.",
    "left": "The people you were talking to have walked away. Call visitors_left (in gentle "
            "mode, visitors_left_gently).",
}
SCENE_MESSAGES = {
    "arrived": f"New visitors have just stepped up in front of you. Acknowledge them at once "
               f"with {FIRST_LINE}; in the same reply, look at them with get_visual_input "
               f"and call notice_visitors.",
    "left": "The people you were talking to have walked away. Call visitors_left (in gentle "
            "mode, visitors_left_gently).",
}
SCENE_MESSAGES = {
    "arrived": f"New visitors have just stepped up in front of you. Acknowledge them at once "
               f"with {FIRST_LINE}; in the same reply, look at them with get_visual_input "
               f"and call notice_visitors.",
    "left": "The people you were talking to have walked away. Call visitors_left (in gentle "
            "mode, visitors_left_gently).",
}

Everything the server sends into the call goes through one queue, so an "arrived" right after a "left" can't overtake it and land first.

Hold a "left" for a moment

In the dark, the detector loses people for a second or two at a time. A lone visitor standing still could drop out of detection, come back, and get greeted as a brand new show every fifteen seconds. A person hovering at the edge of the frame could legitimately leave and return every half second. So my server holds each "left" for 8 seconds before telling the call. If the same people step back up in that time, it cancels the "left" and the show goes on as if nothing happened.

The hold doesn't slow down a new group. When someone steps up while a "left" is held, the server compares their signatures with the group that left. If they're different people, the old show ends at once and the new one starts with a greeting right away.

if event == "arrived" and call_id and held_left["timer"] and not same_people(body.get("people")):
    # Someone else stepped up while the last group's "left" was held: a
    # new group, not the old one back.
    cancel_held_left()
if event == "arrived" and call_id and held_left["timer"] and not same_people(body.get("people")):
    # Someone else stepped up while the last group's "left" was held: a
    # new group, not the old one back.
    cancel_held_left()
if event == "arrived" and call_id and held_left["timer"] and not same_people(body.get("people")):
    # Someone else stepped up while the last group's "left" was held: a
    # new group, not the old one back.
    cancel_held_left()
if event == "arrived" and call_id and held_left["timer"] and not same_people(body.get("people")):
    # Someone else stepped up while the last group's "left" was held: a
    # new group, not the old one back.
    cancel_held_left()

What else the boxes give

Each box carries a height, the distance from feet to head as a fraction of the frame. Everyone on stage stands at about the same distance from the camera, so their heights compare fairly. A person about half the height of the tallest one in their group is probably a small child. That measurement goes into global_data.stage_hint, where the age gate from part 4 reads it. Over the night, the server also learns which heights mean a small child.

Traps to avoid

Don't ask the model to notice arrivals. The agent only looks at the camera when it decides to, and a look takes hundreds of milliseconds. Detect people in your own code and push the event into the call.

Don't act too fast. Detection flickers, especially in the dark. Hold a departure for a few seconds, and compare whoever steps up in that time with the people who left.

Don't send a message into the call while the agent is talking. It cuts the agent off mid-word. Wait for quiet, then send.

Next

The pumpkin can see, talk, and tell who's in front of it, but it still sounds like a stock text-to-speech voice. In part 6 I give it a voice of its own, with audio effects that run in the browser.

The series

  1. The system and the call.

  2. The agent: a personality and three modes, as contexts and steps.

  3. Tools: what the AI calls on my server, and why its material lives in code.

  4. Vision: letting the agent see, and checking the camera before any decision that matters.

  5. The stage: detecting who is standing in front of the pumpkin, in the browser (this post).

  6. The voice: audio effects in the browser.

  7. Pacing and state: the server keeps score.

  8. The operator: a person with a phone who can overrule the agent.

  9. Testing it, and running it for a whole night.

Bottom Linear Gradient  Lines image

The Communications Stack for What's Next

APIs built for speed. Infrastructure built for scale. AI built in from day one.

The Communications Stack for What's Next

APIs built for speed. Infrastructure built for scale. AI built in from day one.

The Communications Stack for What's Next

APIs built for speed. Infrastructure built for scale. AI built in from day one.

The Communications Stack for What's Next

APIs built for speed. Infrastructure built for scale. AI built in from day one.