Add calculator and microphone conversation apps

Add symbolic math and graphing tools, dual-microphone audio processing, live captions, translation, speaker diarization, sentiment analysis, and searchable conversation history.

Extend Android voice and BLE support for microphone control, recording, transcoding, and on-device speaker identification, with coverage for calculator and microphone workflows.
This commit is contained in:
Kalani Helekunihi committed 2026-08-25 00:22:19 -05:00
1 parent ab963974e5
commit fe85846e6f
124 files changed
+22061 -58

No files matched your search

+137
View File
@@ -0,0 +1,137 @@
import { GrayImage, type UiFont } from "../../graphics/image";
import { getDefaultSmallFont } from "../../graphics/ui-fonts";
import { lineStep } from "../../ui/metrics";
import { GESTURE_DOUBLE_CLICK, GESTURE_SCROLL } from "../../ui/gestures";
import { Layer, type DashboardInputEvent, type LayerContext } from "../../ui/layers";
import { micSession, type CaptionLine, type MicSessionState } from "./mic-session";
/**
* On-glasses captions: each line is prefixed with the speaker's name (their
* id until tagged); foreign-language lines show the translation directly
* beneath the recognized original. Scroll reviews recent lines; the view
* snaps back to live on new speech.
*/
export class CaptionsLayer implements Layer {
private state: MicSessionState = micSession.getState();
private unsubscribe: (() => void) | null = null;
private scrollback = 0;
private lastLineCount = 0;
start(requestRender: () => void): void {
this.unsubscribe = micSession.onState((state) => {
if (state.captionLines.length !== this.lastLineCount) {
this.lastLineCount = state.captionLines.length;
this.scrollback = 0;
}
this.state = state;
requestRender();
});
}
paint(ctx: LayerContext): GrayImage {
const font = getDefaultSmallFont();
const { width, height } = ctx.stack.getBaseSize();
const image = new GrayImage(width, height, 0);
const state = this.state;
image.drawText(font, 12, 4, "Captions", 220);
if (!state.captionsActive) {
image.drawText(font, 12, 26, "Captions are off (enable in the Microphones menu).", 130);
}
const rows = this.buildRows(font, width - 36, state.captionLines);
const step = lineStep(font) + 1;
const bodyTop = 24;
const footerY = height - font.lineHeight - 4;
const visibleRows = Math.max(1, Math.floor((footerY - bodyTop) / step));
const maxScrollback = Math.max(0, rows.length - visibleRows);
this.scrollback = Math.min(this.scrollback, maxScrollback);
const firstRow = Math.max(0, rows.length - visibleRows - this.scrollback);
for (let index = firstRow; index < Math.min(rows.length, firstRow + visibleRows); index++) {
const row = rows[index]!;
const y = bodyTop + (index - firstRow) * step;
if (row.prefix) {
image.drawText(font, 16, y, row.prefix, row.prefixValue);
image.drawText(font, 16 + font.measureText(row.prefix), y, row.text, row.value);
} else {
image.drawText(font, 16 + row.indent, y, row.text, row.value);
}
}
image.drawText(
font,
12,
footerY,
`${GESTURE_SCROLL} history ${GESTURE_DOUBLE_CLICK} back` +
(this.scrollback > 0 ? ` (${this.scrollback} back)` : ""),
110,
);
return image;
}
private buildRows(
font: UiFont,
maxWidth: number,
lines: CaptionLine[],
): Array<{ prefix?: string; prefixValue: number; text: string; value: number; indent: number }> {
const rows: Array<{ prefix?: string; prefixValue: number; text: string; value: number; indent: number }> = [];
for (const line of lines) {
const prefix = `${line.speakerName}: `;
const prefixWidth = font.measureText(prefix);
const wrapped = wrapWords(font, line.text, maxWidth - prefixWidth);
wrapped.forEach((text, index) => {
rows.push({
prefix: index === 0 ? prefix : undefined,
prefixValue: line.isWearer ? 255 : 170,
text,
value: 230,
indent: index === 0 ? 0 : prefixWidth,
});
});
if (line.translation) {
for (const text of wrapWords(font, `→ ${line.translation}`, maxWidth - prefixWidth)) {
rows.push({ prefixValue: 0, text, value: 140, indent: prefixWidth });
}
}
}
return rows;
}
handleInput(event: DashboardInputEvent, ctx: LayerContext): void {
switch (event.type) {
case "scroll-up":
this.scrollback += 1;
return;
case "scroll-down":
this.scrollback = Math.max(0, this.scrollback - 1);
return;
case "double-click":
ctx.stack.pop();
return;
default:
return;
}
}
onRemoved(): void {
this.unsubscribe?.();
this.unsubscribe = null;
}
}
function wrapWords(font: UiFont, text: string, maxWidth: number): string[] {
const words = text.split(/\s+/).filter(Boolean);
const lines: string[] = [];
let line = "";
for (const word of words) {
const candidate = line ? `${line} ${word}` : word;
if (line && font.measureText(candidate) > maxWidth) {
lines.push(line);
line = word;
} else {
line = candidate;
}
}
if (line) lines.push(line);
return lines.length ? lines : [""];
}
+240
View File
@@ -0,0 +1,240 @@
import { Utils } from "@nativescript/core";
import { isLocalModelReady, streamLocalQwen } from "../../native/llama";
import type { LlmStreamHandle } from "../../assistant/llm-protocol";
import { parseConversationQuery } from "../../phone-ui/conversation-search";
declare const com: any;
/**
* Question answering over saved conversations with the on-phone LLM (the
* assistant's Qwen model). Retrieval-then-read: the question is parsed for
* date/emotion filters and keywords, matching transcript segments and
* session/speaker metadata are pulled from the conversation store, and the
* model answers strictly from that context. Everything stays on-device.
*/
// Qwen runs with a 4096-token context; leave room for the answer.
const MAX_CONTEXT_CHARS = 7000;
const MAX_KEYWORDS = 6;
const SEGMENTS_PER_KEYWORD = 30;
const RECENT_SEGMENT_LIMIT = 120;
const SESSION_LIMIT = 20;
const KEYWORD_STOPWORDS = new Set(
("the a an and or but of in on at to from with about for was were is are am be been did do does have has had " +
"what when where who whom whose which why how tell show me my i we us our you your they them their it its " +
"that this these those there anyone someone something anything talk talked talking say said saying speak spoke " +
"conversation conversations chat chats discussion discussions transcript transcripts recording recordings").split(" "),
);
export type ConversationAnswerCallbacks = {
onDelta?: (textSoFar: string) => void;
onDone: (answer: string, contextNote: string) => void;
onError: (message: string) => void;
};
export function conversationQaAvailable(): boolean {
return global.isAndroid && isLocalModelReady();
}
function store(): any {
const context = Utils.android.getApplicationContext();
return com.faceclaw.app.FaceclawConversationStore.getInstance(context);
}
type SegmentRow = {
id: number;
sessionId: number;
speakerId: number | null;
startedAt: number;
text: string;
translation: string;
emotion: string;
sentiment: number;
};
function parseSegments(json: string): SegmentRow[] {
return (JSON.parse(json) as Array<Record<string, unknown>>).map((row) => ({
id: Number(row.id),
sessionId: Number(row.sessionId ?? 0),
speakerId: row.speakerId === null ? null : Number(row.speakerId),
startedAt: Number(row.startedAt),
text: String(row.text ?? ""),
translation: String(row.translation ?? ""),
emotion: String(row.emotion ?? ""),
sentiment: Number(row.sentiment ?? 0),
}));
}
function keywords(text: string): string[] {
const seen = new Set<string>();
for (const raw of text.toLowerCase().split(/[^a-z0-9']+/)) {
const word = raw.trim();
if (word.length < 3 || KEYWORD_STOPWORDS.has(word)) continue;
seen.add(word);
if (seen.size >= MAX_KEYWORDS) break;
}
return [...seen];
}
function formatWhen(ms: number): string {
const date = new Date(ms);
const pad = (value: number) => String(value).padStart(2, "0");
return (
`${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ` +
`${pad(date.getHours())}:${pad(date.getMinutes())}`
);
}
/**
* Assemble the retrieval context: speaker roster (names, tags, wearer flag),
* session metadata, and the transcript lines most relevant to the question.
* Returns the context text plus a short human-readable note about coverage.
*/
function buildContext(question: string): { context: string; note: string } {
const filters = parseConversationQuery(question);
const filterJson: Record<string, unknown> = {};
if (filters.sinceMs !== null) filterJson.sinceMs = filters.sinceMs;
if (filters.untilMs !== null) filterJson.untilMs = filters.untilMs;
if (filters.emotion !== null) filterJson.emotion = filters.emotion;
const speakerNames = new Map<number, string>();
const speakerLines: string[] = [];
for (const row of JSON.parse(String(store().querySpeakers())) as Array<Record<string, unknown>>) {
const id = Number(row.id);
const name = String(row.name ?? "");
speakerNames.set(id, name);
const parts = [name];
if (row.isWearer) parts.push("(the wearer/user)");
if (row.tag) parts.push(`tag: ${String(row.tag)}`);
parts.push(`${Number(row.segmentCount ?? 0)} lines heard`);
speakerLines.push(`- ${parts.join(", ")}`);
}
const sessions = JSON.parse(
String(store().querySessions(JSON.stringify({ ...filterJson, limit: SESSION_LIMIT }))),
) as Array<Record<string, unknown>>;
const sessionTitles = new Map<number, string>();
const sessionLines: string[] = [];
for (const row of sessions) {
const id = Number(row.id);
const title = String(row.title ?? "") || `Conversation ${formatWhen(Number(row.startedAt))}`;
sessionTitles.set(id, title);
const who = ((row.speakers as Array<{ name?: unknown }>) ?? [])
.map((speaker) => String(speaker.name ?? ""))
.filter(Boolean)
.join(", ");
sessionLines.push(
`- [#${id}] ${title} — ${formatWhen(Number(row.startedAt))}, ${Number(row.segmentCount ?? 0)} lines` +
(who ? `, speakers: ${who}` : "") +
`, overall sentiment ${Number(row.avgSentiment ?? 0).toFixed(2)}`,
);
}
const terms = keywords(filters.text);
const segmentMap = new Map<number, SegmentRow>();
if (terms.length > 0) {
for (const term of terms) {
const rows = parseSegments(
String(
store().searchSegments(
JSON.stringify({ ...filterJson, query: term, limit: SEGMENTS_PER_KEYWORD }),
),
),
);
for (const row of rows) segmentMap.set(row.id, row);
}
}
if (segmentMap.size === 0) {
// No keyword hits (or no keywords): fall back to the filtered recents so
// summary-style questions still have material to read.
for (const row of parseSegments(
String(store().searchSegments(JSON.stringify({ ...filterJson, limit: RECENT_SEGMENT_LIMIT }))),
)) {
segmentMap.set(row.id, row);
}
}
const segments = [...segmentMap.values()].sort((a, b) => a.startedAt - b.startedAt);
const excerptLines: string[] = [];
let currentSession = -1;
for (const segment of segments) {
if (segment.sessionId !== currentSession) {
currentSession = segment.sessionId;
excerptLines.push(`\n## ${sessionTitles.get(currentSession) ?? `Conversation #${currentSession}`}`);
}
const speaker =
segment.speakerId !== null ? (speakerNames.get(segment.speakerId) ?? "Speaker") : "Speaker";
const emotion = segment.emotion && segment.emotion !== "neutral" ? ` [${segment.emotion}]` : "";
excerptLines.push(`[${formatWhen(segment.startedAt)}] ${speaker}${emotion}: ${segment.text}`);
if (segment.translation) excerptLines.push(` (translated: ${segment.translation})`);
}
let context =
`# Known speakers\n${speakerLines.join("\n") || "(none yet)"}\n\n` +
`# Conversations${filters.sinceMs !== null || filters.emotion !== null ? " (filtered by the question)" : ""}\n` +
`${sessionLines.join("\n") || "(none in range)"}\n\n` +
`# Transcript excerpts\n${excerptLines.join("\n") || "(no matching lines)"}`;
let truncated = false;
if (context.length > MAX_CONTEXT_CHARS) {
context = context.slice(0, MAX_CONTEXT_CHARS);
truncated = true;
}
const note =
`${sessions.length} conversation${sessions.length === 1 ? "" : "s"}, ` +
`${segments.length} transcript line${segments.length === 1 ? "" : "s"} consulted` +
(terms.length ? ` (keywords: ${terms.join(", ")})` : "") +
(truncated ? "; context truncated to fit the on-device model" : "");
return { context, note };
}
/**
* Ask the on-device model a question about saved conversations. Returns a
* cancel handle; the answer streams via onDelta and lands in onDone with a
* note describing what data was consulted.
*/
export function askConversations(
question: string,
callbacks: ConversationAnswerCallbacks,
): LlmStreamHandle {
if (!conversationQaAvailable()) {
setTimeout(
() =>
callbacks.onError(
"The on-phone model isn't downloaded yet — enable it under Settings > Assistant on the glasses.",
),
0,
);
return { cancel: () => {} };
}
let context: { context: string; note: string };
try {
context = buildContext(question);
} catch (error) {
setTimeout(() => callbacks.onError(`Could not read the conversation store: ${String(error)}`), 0);
return { cancel: () => {} };
}
return streamLocalQwen({
apiKey: "",
model: "local",
system:
"You answer questions about the user's saved conversations, captured by their smart glasses. " +
"Use ONLY the provided speaker roster, conversation list, and transcript excerpts. " +
"Cite conversations by their title and date when referencing them. " +
"If the provided data does not contain the answer, say so plainly rather than guessing. " +
"Transcript sentiment scores range -1 (very negative) to 1 (very positive); " +
"bracketed words after a speaker's name are detected emotional tones. " +
`Today's date is ${formatWhen(Date.now())}.`,
messages: [
{
role: "user",
content: `${context.context}\n\n# Question\n${question.trim()}`,
},
],
maxTokens: 400,
onTextDelta: (_delta, textSoFar) => callbacks.onDelta?.(textSoFar),
onDone: (result) => callbacks.onDone(result.text.trim(), context.note),
onError: (message) => callbacks.onError(message),
});
}
+312
View File
@@ -0,0 +1,312 @@
// Reference DSP for the G2 4-mic head array: two 2-mic temples, front mic
// near each hinge and rear mic at each tip. Beamform WITHIN each temple (shared clock), then FUSE
// the two per-temple bearings — never raw cross-temple delay-and-sum, because
// the temples sample on independent clocks.
//
// One substitution from classic GCC-PHAT: the FFT cross-spectrum is
// replaced by a direct time-domain normalized cross-correlation over
// -maxLag..+maxLag. For the lags this array needs (|lag| <= 16 at 16 kHz) the
// direct form is cheaper than an FFT round-trip and carries no FFT dependency;
// the parabolic-interpolated peak still yields sub-sample delay.
//
// Pure TypeScript; no platform imports. Hot paths are Float32Array in and out.
export type MicSide = "left" | "right";
export type MicPosition = "front" | "rear";
// ---------------------------------------------------------------------------
// Array geometry (metres, head-centred; x=right, y=forward, z=up)
export type Vec3 = { x: number; y: number; z: number };
export type MicGeometry = {
positions: Record<MicSide, Record<MicPosition, Vec3>>;
speedOfSound: number;
};
export const G2_DEFAULT_GEOMETRY: MicGeometry = {
positions: {
left: {
front: { x: -0.07, y: 0.05, z: 0 },
rear: { x: -0.08, y: -0.06, z: 0 },
},
right: {
front: { x: 0.07, y: 0.05, z: 0 },
rear: { x: 0.08, y: -0.06, z: 0 },
},
},
speedOfSound: 343,
};
// ---------------------------------------------------------------------------
// Bearing helpers
/** Azimuth in radians, 0 = straight ahead (device +y), positive to the right. */
export type Bearing = { azimuth: number };
export function bearingDegrees(bearing: Bearing): number {
return (bearing.azimuth * 180) / Math.PI;
}
export function bearingUnitVector(bearing: Bearing): Vec3 {
return { x: Math.sin(bearing.azimuth), y: Math.cos(bearing.azimuth), z: 0 };
}
function dot(a: Vec3, b: Vec3): number {
return a.x * b.x + a.y * b.y + a.z * b.z;
}
// ---------------------------------------------------------------------------
// Fractional delay (shared by the beamformer and by tests)
/** Linear-interpolating fractional delay (positive = later). */
export function fractionalDelay(x: Float32Array, samples: number): Float32Array {
const n = x.length;
if (Math.abs(samples) < 1e-4) return x.slice();
const out = new Float32Array(n);
const i0 = Math.floor(samples);
const frac = samples - i0;
for (let i = 0; i < n; i++) {
const j = i - i0;
const a = j >= 0 && j < n ? x[j]! : 0;
const b = j - 1 >= 0 && j - 1 < n ? x[j - 1]! : 0;
out[i] = a * (1 - frac) + b * frac;
}
return out;
}
// ---------------------------------------------------------------------------
// Delay-and-sum beamformer (per temple, 2 mics, shared clock)
export class DelaySumBeamformer {
constructor(
public readonly sampleRate: number,
public readonly geometry: MicGeometry = G2_DEFAULT_GEOMETRY,
) {}
/**
* Steer this temple's front/rear pair toward `target` (device-frame bearing)
* and return the summed beam, halved to preserve amplitude.
*/
beam(side: MicSide, front: Float32Array, rear: Float32Array, target: Bearing): Float32Array {
const n = Math.min(front.length, rear.length);
if (n === 0) return new Float32Array(0);
const d = bearingUnitVector(target);
const pF = this.geometry.positions[side].front;
const pR = this.geometry.positions[side].rear;
// Delay (samples) that aligns each mic's copy of a wavefront from `d`.
const tauF = (dot(pF, d) / this.geometry.speedOfSound) * this.sampleRate;
const tauR = (dot(pR, d) / this.geometry.speedOfSound) * this.sampleRate;
const ref = Math.min(tauF, tauR);
const sF = fractionalDelay(front, tauF - ref);
const sR = fractionalDelay(rear, tauR - ref);
const out = new Float32Array(n);
for (let i = 0; i < n; i++) out[i] = (sF[i]! + sR[i]!) * 0.5;
return out;
}
}
// ---------------------------------------------------------------------------
// Two-mic adaptive noise canceller (NLMS) for inter-mic ANC
/**
* Griffiths–Jim style: `primary` carries the steered speech, `reference` is a
* null-steered noise estimate (front−rear after alignment). An NLMS filter
* subtracts the correlated noise from the primary.
*/
export class InterMicNoiseCanceller {
private readonly weights: Float32Array;
private readonly history: Float32Array;
constructor(
private readonly taps: number = 32,
private readonly stepSize: number = 0.05,
) {
this.weights = new Float32Array(taps);
this.history = new Float32Array(taps);
}
process(primary: Float32Array, reference: Float32Array): Float32Array {
const n = Math.min(primary.length, reference.length);
const out = new Float32Array(n);
const { weights, history, taps } = this;
const eps = 1e-6;
for (let i = 0; i < n; i++) {
for (let k = taps - 1; k > 0; k--) history[k] = history[k - 1]!;
history[0] = reference[i]!;
let yhat = 0;
let energy = 0;
for (let k = 0; k < taps; k++) {
yhat += weights[k]! * history[k]!;
energy += history[k]! * history[k]!;
}
const e = primary[i]! - yhat;
out[i] = e;
const step = (this.stepSize * e) / (energy + eps);
for (let k = 0; k < taps; k++) weights[k] += step * history[k]!;
}
return out;
}
}
// ---------------------------------------------------------------------------
// TDOA via direct normalized cross-correlation (GCC-PHAT substitution)
/**
* Estimate the delay of `b` relative to `a` in samples: if `b` is a copy of
* `a` delayed by k samples, this returns approximately +k.
*
* Substitution note: classic GCC-PHAT whitens an FFT cross-spectrum. Here
* the lag search is tiny (|lag| <= maxLag, typically <= 16),
* so a direct time-domain normalized cross-correlation over the lag range is
* cheaper and dependency-free. The per-lag normalization by the overlapped
* segments' energies plays the whitening role of making the peak
* amplitude-invariant. The peak is refined by parabolic interpolation for
* sub-sample precision.
*/
export function gccPhatDelaySamples(a: Float32Array, b: Float32Array, maxLag: number): number {
const n = Math.min(a.length, b.length);
if (n === 0 || maxLag < 0) return 0;
const lagCount = 2 * maxLag + 1;
const corr = new Float32Array(lagCount);
let bestLag = 0;
let best = -Infinity;
for (let lag = -maxLag; lag <= maxLag; lag++) {
// Correlate a[i] against b[i + lag] over the overlapping span.
const start = Math.max(0, -lag);
const end = Math.min(n, n - lag);
let sum = 0;
let ea = 0;
let eb = 0;
for (let i = start; i < end; i++) {
const av = a[i]!;
const bv = b[i + lag]!;
sum += av * bv;
ea += av * av;
eb += bv * bv;
}
const r = sum / (Math.sqrt(ea * eb) + 1e-12);
corr[lag + maxLag] = r;
if (r > best) {
best = r;
bestLag = lag;
}
}
// Parabolic interpolation around the integer peak for sub-sample precision.
const idx = bestLag + maxLag;
if (idx > 0 && idx < lagCount - 1) {
const y0 = corr[idx - 1]!;
const y1 = corr[idx]!;
const y2 = corr[idx + 1]!;
const denom = y0 - 2 * y1 + y2;
if (Math.abs(denom) > 1e-12) {
const offset = (0.5 * (y0 - y2)) / denom;
if (Math.abs(offset) <= 1) return bestLag + offset;
}
}
return bestLag;
}
// ---------------------------------------------------------------------------
// Compass / IMU fusion: world-frame arc <-> device-frame steering
/**
* `compassHeading` is the world heading of the device +y axis (radians,
* 0 = north); `imuYaw` is a supplementary IMU trim (radians).
*/
export type HeadOrientation = { compassHeading: number; imuYaw: number };
/** Combined world→device rotation about vertical (compass anchored, IMU trims). */
function worldToDevice(head: HeadOrientation): number {
return -(head.compassHeading + head.imuYaw);
}
/** Rotate a world-frame target bearing into the device frame for steering. */
export function steerWorldToDevice(worldAzimuth: number, head: HeadOrientation): Bearing {
return { azimuth: worldAzimuth + worldToDevice(head) };
}
/** Convert a device-frame estimate back to world frame for display/fusion. */
export function deviceToWorld(deviceAzimuth: number, head: HeadOrientation): number {
return deviceAzimuth - worldToDevice(head);
}
/**
* Triangulate the two temples' world-frame bearings into a single estimate:
* a circular-mean-safe blend, weighted by each temple's confidence.
*/
export function fuseBearings(
left: number,
leftWeight: number,
right: number,
rightWeight: number,
): number {
const w = Math.max(1e-3, leftWeight + rightWeight);
const x = (Math.sin(left) * leftWeight + Math.sin(right) * rightWeight) / w;
const y = (Math.cos(left) * leftWeight + Math.cos(right) * rightWeight) / w;
return Math.atan2(x, y);
}
// ---------------------------------------------------------------------------
// Faceclaw integration utilities
/**
* Azimuth from an inter-mic delay, mirroring the firmware's approach:
* asin of the delay normalized by the acoustic travel time across the pair,
* clamped to ±90°.
*/
export function bearingFromTdoa(
delaySamples: number,
sampleRate: number,
micSpacingMeters: number,
): number {
const maxDelay = (micSpacingMeters / 343) * sampleRate;
if (maxDelay <= 0) return 0;
const normalized = Math.max(-1, Math.min(1, delaySamples / maxDelay));
return Math.asin(normalized);
}
/** Wrap an angle to (-π, π]. */
function wrapAngle(angle: number): number {
const twoPi = 2 * Math.PI;
let a = angle % twoPi;
if (a <= -Math.PI) a += twoPi;
else if (a > Math.PI) a -= twoPi;
return a;
}
/** Whether `azimuth` falls inside the arc, handling wraparound at ±π. */
export function angleInArc(azimuth: number, arcCenter: number, arcHalfWidth: number): boolean {
return Math.abs(wrapAngle(azimuth - arcCenter)) <= arcHalfWidth;
}
// ---------------------------------------------------------------------------
// Top-level per-temple pipeline
export class TempleAudioPipeline {
private readonly beamformer: DelaySumBeamformer;
private readonly anc = new InterMicNoiseCanceller();
enableANC = true;
constructor(
public readonly side: MicSide,
sampleRate: number,
geometry: MicGeometry = G2_DEFAULT_GEOMETRY,
) {
this.beamformer = new DelaySumBeamformer(sampleRate, geometry);
}
/**
* Process one frame's deinterleaved front/rear channels toward a
* device-frame target, returning the enhanced mono beam for this temple.
*/
process(front: Float32Array, rear: Float32Array, target: Bearing): Float32Array {
const beam = this.beamformer.beam(this.side, front, rear, target);
if (!this.enableANC) return beam;
// Null-steer reference: the difference channel carries off-axis noise.
const n = Math.min(front.length, rear.length);
const reference = new Float32Array(n);
for (let i = 0; i < n; i++) reference[i] = front[i]! - rear[i]!;
return this.anc.process(beam, reference);
}
}
+30
View File
@@ -0,0 +1,30 @@
import { type AppDefinition } from "../app-definition";
import {
createMicrophonesAppWindow,
MICROPHONES_SURFACE_ID,
MICROPHONES_WINDOW_ID,
} from "./microphones-app";
import { micSession } from "./mic-session";
/**
* The Microphones app: per-mic control and levels, the Sonic Radar
* (direction-of-arrival + beam-filtered listening), and live captions with
* speaker recognition, translation, and tone analysis. Saved conversations
* are reviewed in the phone UI.
*/
const microphonesApp: AppDefinition = {
appId: "microphones",
title: "Microphones",
icon: "mic",
boot: () => {
// Prune expired captions/recordings per the retention settings.
void micSession.applyRetentionSweep();
},
launch: async (ctx) => {
await ctx.launchInProcessApp(MICROPHONES_WINDOW_ID, MICROPHONES_SURFACE_ID, (options) =>
createMicrophonesAppWindow(options),
);
},
};
export default microphonesApp;
+80
View File
@@ -0,0 +1,80 @@
import { GrayImage } from "../../graphics/image";
import { getDefaultSmallFont } from "../../graphics/ui-fonts";
import { GESTURE_DOUBLE_CLICK } from "../../ui/gestures";
import { Layer, type DashboardInputEvent, type LayerContext } from "../../ui/layers";
import { micSession, type MicSessionState } from "./mic-session";
/**
* Live level meters, one per active microphone (a single mixed channel on
* stock firmware; up to four mics with the mic-control firmware), plus the
* firmware's signal-strength/DoA readout.
*/
export class LevelsLayer implements Layer {
private state: MicSessionState = micSession.getState();
private unsubscribe: (() => void) | null = null;
start(requestRender: () => void): void {
this.unsubscribe = micSession.onState((state) => {
this.state = state;
requestRender();
});
}
paint(ctx: LayerContext): GrayImage {
const font = getDefaultSmallFont();
const { width, height } = ctx.stack.getBaseSize();
const image = new GrayImage(width, height, 0);
const state = this.state;
image.drawText(font, 12, 6, "Microphone Levels", 220);
image.drawText(font, 12, 24, state.statusText, 110);
const barX = 130;
const barWidth = width - barX - 40;
const rowHeight = 26;
let y = 48;
const labels = state.levelLabels.length ? state.levelLabels : ["Glasses mic"];
labels.forEach((label, index) => {
const level = state.levels[index] ?? 0;
const enabled = state.levelsEnabled[index] ?? true;
image.drawText(font, 12, y + 3, enabled ? label : `${label} (off)`, enabled ? 190 : 90);
image.drawRect(barX, y, barWidth, 16, enabled ? 70 : 40);
const fill = Math.round((barWidth - 4) * level);
if (fill > 0) {
// A disabled mic still meters (dimly) so its signal can be checked
// before switching it back on.
image.fillRect(barX + 2, y + 2, fill, 12, !enabled ? 70 : level > 0.85 ? 255 : 190);
}
// Tick marks at -20 dB and -40 dB of the 60 dB meter range.
for (const fraction of [1 / 3, 2 / 3]) {
const tickX = barX + Math.round(barWidth * fraction);
image.drawLine(tickX, y + 16, tickX, y + 19, 60);
}
y += rowHeight;
});
y += 6;
if (state.doaDeviceDeg !== null) {
image.drawText(font, 12, y, `Direction of arrival: ${Math.round(state.doaDeviceDeg)}°`, 160);
y += 18;
}
image.drawText(font, 12, y, `Signal-strength ratio: ${state.ssr}`, 130);
y += 18;
const ancText = state.ancOn && state.ancEngine ? `on — ${state.ancEngine}` : "off";
image.drawText(font, 12, y, `Noise cancellation: ${ancText}`, 130);
image.drawText(font, 12, height - font.lineHeight - 4, `${GESTURE_DOUBLE_CLICK} back`, 110);
return image;
}
handleInput(event: DashboardInputEvent, ctx: LayerContext): void {
if (event.type === "double-click") {
ctx.stack.pop();
}
}
onRemoved(): void {
this.unsubscribe?.();
this.unsubscribe = null;
}
}
+195
View File
@@ -0,0 +1,195 @@
import { getStringSetting, setStringSetting } from "../../native/settings-store";
import { toJavaBytes } from "../../native/cloud-stt";
import { toUint8Array } from "../../util/array-util";
import {
MIC_LEASE_MS,
decodeMicStatus,
defaultMicConfig,
encodeMicControl,
templeActive,
type MicConfig,
type MicOp,
type MicSide,
type MicStatus,
} from "./mic-protocol";
declare const com: any;
/**
* Host-side controller for the CFW mic_control array: sends the same config
* to both temples (each temple is its own endpoint and its own 2-mic array),
* tracks per-temple field-104 status, and keeps the 90 s streaming lease
* renewed while capture is armed. Degrades cleanly on firmware without the
* feature: micControlSupported() is false and apply() refuses to arm.
*/
const CONFIG_SETTING_KEY = "microphones.array-config";
const LEASE_RENEW_MS = Math.floor(MIC_LEASE_MS / 3);
export type MicArrayStatuses = { left: MicStatus | null; right: MicStatus | null };
function activeCommunicator(): any {
if (!global.isAndroid) return null;
try {
return com.faceclaw.app.FaceclawBleCommunicator.getActive();
} catch {
return null;
}
}
/** True when the connected glasses advertise the CFW mic_control feature. */
export function micControlSupported(): boolean {
const communicator = activeCommunicator();
if (!communicator) return false;
try {
const caps = String(communicator.getFirmwareCapabilities() ?? "");
return caps.trim().split(/\s+/).includes("micctl");
} catch {
return false;
}
}
export function loadMicConfig(): MicConfig {
const raw = getStringSetting(CONFIG_SETTING_KEY, "");
if (!raw) return defaultMicConfig();
try {
const parsed = JSON.parse(raw) as Partial<MicConfig>;
const defaults = defaultMicConfig();
return {
...defaults,
...parsed,
hostMics: { ...defaults.hostMics, ...(parsed.hostMics ?? {}) },
};
} catch {
return defaultMicConfig();
}
}
export function saveMicConfig(config: MicConfig): void {
setStringSetting(CONFIG_SETTING_KEY, JSON.stringify(config));
}
class MicArrayController {
private readonly statusListeners = new Set<(statuses: MicArrayStatuses) => void>();
private statuses: MicArrayStatuses = { left: null, right: null };
// The Java listener proxy must stay referenced or it gets GC'd.
private statusProxy: any | null = null;
private proxyCommunicator: any | null = null;
private leaseTimer: ReturnType<typeof setInterval> | null = null;
private armed = false;
getStatuses(): MicArrayStatuses {
return this.statuses;
}
onStatus(listener: (statuses: MicArrayStatuses) => void): () => void {
this.statusListeners.add(listener);
listener(this.statuses);
return () => this.statusListeners.delete(listener);
}
/**
* True when both temples report the same active configuration; only then
* should cross-temple bearing fusion be trusted.
*/
arrayConsistent(): boolean {
const { left, right } = this.statuses;
if (!left || !right) return false;
return (
left.active &&
right.active &&
left.effectiveRateHz === right.effectiveRateHz &&
left.codec === right.codec &&
left.format === right.format
);
}
/**
* Push the config to the temples. Each active temple streams its full
* front+rear pair (per-mic selection happens host-side after the split);
* a temple whose mics are all toggled off gets STOP instead so its stream
* doesn't spend BLE bandwidth.
*/
apply(config: MicConfig): boolean {
const leftActive = templeActive(config, "left");
const rightActive = templeActive(config, "right");
if (leftActive || rightActive) {
if (!this.send("configure", config, "configure", rightActive, leftActive)) return false;
}
if (!leftActive || !rightActive) {
this.send("stop", undefined, "stop-disabled-temple", !rightActive, !leftActive);
}
saveMicConfig(config);
this.armed = config.armHardware && (leftActive || rightActive);
this.syncLeaseTimer();
return true;
}
query(): boolean {
return this.send("query", undefined, "query");
}
stopStreaming(): void {
this.armed = false;
this.syncLeaseTimer();
this.send("stop", undefined, "stop");
}
private renewLease(): void {
if (!this.armed) return;
this.send("renew", undefined, "renew");
}
private send(
op: MicOp,
config: MicConfig | undefined,
label: string,
rightTemple = true,
leftTemple = true,
): boolean {
const communicator = activeCommunicator();
if (!communicator) return false;
this.ensureStatusProxy(communicator);
try {
const record = encodeMicControl(op, config);
communicator.sendFaceclawMicControl(toJavaBytes(record), label, rightTemple, leftTemple);
return true;
} catch (error) {
console.warn(`mic control ${label} failed: ${error}`);
return false;
}
}
private ensureStatusProxy(communicator: any): void {
if (this.statusProxy && this.proxyCommunicator === communicator) return;
if (this.statusProxy && this.proxyCommunicator) {
try {
this.proxyCommunicator.removeMicStatusListener(this.statusProxy);
} catch {
// The old communicator instance may be gone after a reconnect.
}
}
this.statusProxy = new com.faceclaw.app.FaceclawMicStatusListener({
onMicStatus: (body: any, arm: string) => {
const status = decodeMicStatus(toUint8Array(body));
if (!status) return;
const side: MicSide = String(arm) === "L" ? "left" : "right";
this.statuses = { ...this.statuses, [side]: { ...status, side } };
this.statusListeners.forEach((listener) => listener(this.statuses));
},
});
this.proxyCommunicator = communicator;
communicator.addMicStatusListener(this.statusProxy);
}
private syncLeaseTimer(): void {
if (this.armed && !this.leaseTimer) {
this.leaseTimer = setInterval(() => this.renewLease(), LEASE_RENEW_MS);
} else if (!this.armed && this.leaseTimer) {
clearInterval(this.leaseTimer);
this.leaseTimer = null;
}
}
}
export const micArrayController = new MicArrayController();
+206
View File
@@ -0,0 +1,206 @@
import { Utils } from "@nativescript/core";
declare const com: any;
declare const java: any;
/**
* Download management for the Microphones app's on-device models, mirroring
* the Moonshine flow in app/native/asr-model.ts (FaceclawModelDownloader,
* resume + pinned sha256 per file):
*
* - Speaker embedding (WeSpeaker CAM++ English, 512-dim): voice-prints for
* caption attribution, wearer recognition, and re-diarization.
* - Pyannote segmentation 3.0: offline re-diarization of saved recordings.
*
* The caption ASR model itself is the shared Moonshine download managed by
* asr-model.ts; this module only adds the speaker models.
*/
export type MicModelId = "speaker-embedding" | "diarization-segmentation";
type MicModelFile = {
/** Local file name under the model directory. */
name: string;
/** Source file name in the mirror repo (may differ from the local name). */
remoteName: string;
sha256: string;
sizeBytes: number;
};
type MicModel = {
id: MicModelId;
label: string;
baseUrl: string;
files: MicModelFile[];
totalBytes: number;
};
// Hugging Face mirrors of the sherpa-onnx release assets (served per-file,
// sha256 pinned from the repos' LFS pointers).
export const MIC_MODELS: MicModel[] = [
{
id: "speaker-embedding",
label: "Speaker voices (WeSpeaker English)",
baseUrl: "https://huggingface.co/csukuangfj/speaker-embedding-models/resolve/main/",
files: [
{
name: "speaker-embedding.onnx",
remoteName: "wespeaker_en_voxceleb_CAM%2B%2B.onnx",
sha256: "c46fad10b5f81e1aa4a60c162714208577093655076c5450f8c469e522ec54ef",
sizeBytes: 29292684,
},
],
totalBytes: 29292684,
},
{
id: "diarization-segmentation",
label: "Speaker turns (pyannote segmentation)",
baseUrl: "https://huggingface.co/csukuangfj/sherpa-onnx-pyannote-segmentation-3-0/resolve/main/",
files: [
{
name: "segmentation.onnx",
remoteName: "model.onnx",
sha256: "220ad67ca923bef2fa91f2390c786097bf305bceb5e261d4af67b38e938e1079",
sizeBytes: 5992913,
},
],
totalBytes: 5992913,
},
];
export type MicModelState = {
status: "absent" | "downloading" | "ready";
bytesDownloaded: number;
totalBytes: number;
};
const downloaders = new Map<MicModelId, any>();
const progress = new Map<MicModelId, number>();
const stateListeners = new Set<(id: MicModelId, state: MicModelState) => void>();
function model(id: MicModelId): MicModel {
const found = MIC_MODELS.find((entry) => entry.id === id);
if (!found) throw new Error(`unknown mic model ${id}`);
return found;
}
function modelDirPath(id: MicModelId): string {
const context = Utils.android.getApplicationContext();
return `${context.getFilesDir().getAbsolutePath()}/faceclaw-mic-models/${id}`;
}
function filePath(id: MicModelId, file: MicModelFile): string {
return `${modelDirPath(id)}/${file.name}`;
}
function isFilePresent(id: MicModelId, file: MicModelFile): boolean {
try {
const javaFile = new java.io.File(filePath(id, file));
return javaFile.exists() && javaFile.length() > 0;
} catch {
return false;
}
}
export function isMicModelReady(id: MicModelId): boolean {
if (!global.isAndroid) return false;
return model(id).files.every((file) => isFilePresent(id, file));
}
/** Absolute path of a ready model's primary file, or null when absent. */
export function micModelPath(id: MicModelId): string | null {
if (!isMicModelReady(id)) return null;
return filePath(id, model(id).files[0]!);
}
export function micModelState(id: MicModelId): MicModelState {
if (downloaders.has(id)) {
return {
status: "downloading",
bytesDownloaded: progress.get(id) ?? 0,
totalBytes: model(id).totalBytes,
};
}
return {
status: isMicModelReady(id) ? "ready" : "absent",
bytesDownloaded: 0,
totalBytes: model(id).totalBytes,
};
}
export function onMicModelStateChanged(
listener: (id: MicModelId, state: MicModelState) => void,
): () => void {
stateListeners.add(listener);
return () => stateListeners.delete(listener);
}
function notifyStateChanged(id: MicModelId): void {
const state = micModelState(id);
stateListeners.forEach((listener) => listener(id, state));
}
export function startMicModelDownload(id: MicModelId): void {
if (!global.isAndroid || downloaders.has(id) || isMicModelReady(id)) return;
downloadNextFile(id);
notifyStateChanged(id);
}
function downloadNextFile(id: MicModelId): void {
const definition = model(id);
const nextFile = definition.files.find((file) => !isFilePresent(id, file));
if (!nextFile) {
downloaders.delete(id);
notifyStateChanged(id);
return;
}
const completedBytes = definition.files
.filter((file) => isFilePresent(id, file))
.reduce((sum, file) => sum + file.sizeBytes, 0);
const listener = new com.faceclaw.app.FaceclawModelDownloaderListener({
onProgress: (bytes: number, _total: number) => {
progress.set(id, completedBytes + Number(bytes));
notifyStateChanged(id);
},
onDone: () => {
downloadNextFile(id);
},
onError: (message: string) => {
console.error(`Mic model download failed (${id}/${nextFile.name}): ${message}`);
downloaders.delete(id);
notifyStateChanged(id);
},
});
const downloader = new com.faceclaw.app.FaceclawModelDownloader(
`${definition.baseUrl}${nextFile.remoteName}`,
filePath(id, nextFile),
nextFile.sha256,
nextFile.sizeBytes,
listener,
);
downloaders.set(id, downloader);
downloader.start();
}
export function cancelMicModelDownload(id: MicModelId): void {
const downloader = downloaders.get(id);
if (!downloader) return;
downloader.cancel();
downloaders.delete(id);
notifyStateChanged(id);
}
export function deleteMicModel(id: MicModelId): void {
if (!global.isAndroid) return;
cancelMicModelDownload(id);
try {
for (const file of model(id).files) {
new java.io.File(filePath(id, file)).delete();
new java.io.File(`${filePath(id, file)}.part`).delete();
}
new java.io.File(modelDirPath(id)).delete();
} catch (error) {
console.error(`Mic model delete failed: ${String(error)}`);
}
notifyStateChanged(id);
}
+297
View File
@@ -0,0 +1,297 @@
/**
* Wire codec for the CFW mic_control feature (g2flash `microphone-configurations`
* branch, EVENCFW/16, caps tokens micctl/micmc/micraw). Mirrors the contract
* header in g2flash patches/mic_control.c:
*
* field 103 (write) ['M','C', ver, op, <9 config bytes for CONFIGURE>]
* field 104 (read) 21-byte ['M','C', ver, active, src, chanMask, codec,
* fmt, rateLo, rateHi, brLo, brHi, flags, hwArmed,
* sideId, frames u32 LE, effRateLo, effRateHi]
* 'SM' stream frame 21-byte header ['S','M', ver, flags, seq16, tick32,
* nCh, rateDiv16, fmt, codec, angleS16, ssrS16,
* payLen16] + payload
*
* Per-temple: each arm is its own endpoint and its own 2-mic array (front
* mic near the hinge = chanMask bit0, rear mic near the touchpad = bit1);
* the same config goes to both temples. Stereo payloads arrive as two
* CONCATENATED channel blocks (front then rear), not interleaved. Sessions
* hold a 90 s lease; renew with op RENEW while streaming.
*
* Pure module: byte codecs only, no platform imports (the BLE plumbing lives
* in mic-control.ts).
*/
export const MIC_PROTOCOL_VERSION = 1;
export const MIC_LEASE_MS = 90_000;
export type MicOp = "configure" | "query" | "stop" | "renew";
const OP_CODES: Record<MicOp, number> = { configure: 1, query: 2, stop: 3, renew: 4 };
export type MicSource = "codec" | "pdm";
export type MicWireCodec = "lc3" | "raw";
export type MicSampleFormat = "pcm16" | "pcm24" | "pcm32";
export type MicSide = "left" | "right";
export type MicPosition = "front" | "rear";
export const MIC_FLAG_BEAMFORM = 0x01;
/**
* Gated: actually brings up the mic front end and streaming on the glasses.
* The firmware validation checklist calls for confirming the tap ABI on
* sacrificial hardware first, so the UI defaults this OFF and warns.
*/
export const MIC_FLAG_ARM_HW = 0x02;
export const SM_FLAG_TRUNCATED = 0x80;
export type MicConfig = {
source: MicSource;
/** bit0 = front mic, bit1 = rear mic (per temple). */
channelMask: number;
codec: MicWireCodec;
format: MicSampleFormat;
sampleRateHz: number;
lc3BitrateBps: number;
beamform: boolean;
armHardware: boolean;
/**
* Host-side per-microphone selection. Each temple streams its full
* front+rear stereo pair over BLE (wire channelMask stays 0b11); the phone
* splits the concatenated channels and this mask decides which of the four
* mics feed levels-for-use, beamforming, captions, and recording. A temple
* with both mics off is sent STOP so its stream doesn't waste bandwidth.
*/
hostMics: Record<MicChannelKey, boolean>;
};
/** One of the four physical microphones, as split on the host. */
export type MicChannelKey = "leftFront" | "leftRear" | "rightFront" | "rightRear";
export const MIC_CHANNEL_KEYS: readonly MicChannelKey[] = [
"leftFront",
"leftRear",
"rightFront",
"rightRear",
];
export function micChannelKey(side: MicSide, position: MicPosition): MicChannelKey {
if (side === "left") return position === "front" ? "leftFront" : "leftRear";
return position === "front" ? "rightFront" : "rightRear";
}
export function micChannelLabel(key: MicChannelKey): string {
switch (key) {
case "leftFront":
return "L front";
case "leftRear":
return "L rear";
case "rightFront":
return "R front";
case "rightRear":
return "R rear";
}
}
/** Whether a temple has any host-enabled microphone. */
export function templeActive(config: MicConfig, side: MicSide): boolean {
return side === "left"
? config.hostMics.leftFront || config.hostMics.leftRear
: config.hostMics.rightFront || config.hostMics.rightRear;
}
export function defaultMicConfig(): MicConfig {
return {
source: "pdm",
channelMask: 0b11,
codec: "raw",
format: "pcm16",
sampleRateHz: 16_000,
lc3BitrateBps: 0,
beamform: true,
armHardware: false,
hostMics: { leftFront: true, leftRear: true, rightFront: true, rightRear: true },
};
}
export function micEnabled(config: MicConfig, position: MicPosition): boolean {
return (config.channelMask & (position === "front" ? 0b01 : 0b10)) !== 0;
}
export function setMicEnabled(config: MicConfig, position: MicPosition, on: boolean): MicConfig {
const bit = position === "front" ? 0b01 : 0b10;
const channelMask = on ? config.channelMask | bit : config.channelMask & ~bit;
return { ...config, channelMask };
}
const SOURCE_CODES: Record<MicSource, number> = { codec: 0, pdm: 1 };
const CODEC_CODES: Record<MicWireCodec, number> = { lc3: 0, raw: 1 };
const FORMAT_CODES: Record<MicSampleFormat, number> = { pcm16: 0, pcm24: 1, pcm32: 2 };
export function bytesPerSample(format: MicSampleFormat): number {
return format === "pcm32" ? 4 : format === "pcm24" ? 3 : 2;
}
/** Encode the field-103 record body: ['M','C', ver, op, <payload>]. */
export function encodeMicControl(op: MicOp, config?: MicConfig): Uint8Array {
const header = [0x4d, 0x43, MIC_PROTOCOL_VERSION, OP_CODES[op]];
if (op !== "configure" || !config) {
return Uint8Array.from(header);
}
const rate = Math.round(Math.max(8_000, Math.min(48_000, config.sampleRateHz)) / 100);
const bitrate = Math.round(Math.max(0, Math.min(500_000, config.lc3BitrateBps)) / 100);
const flags =
(config.beamform ? MIC_FLAG_BEAMFORM : 0) | (config.armHardware ? MIC_FLAG_ARM_HW : 0);
return Uint8Array.from([
...header,
SOURCE_CODES[config.source],
config.channelMask & 0b11,
CODEC_CODES[config.codec],
FORMAT_CODES[config.format],
rate & 0xff,
(rate >> 8) & 0xff,
bitrate & 0xff,
(bitrate >> 8) & 0xff,
flags,
]);
}
export type MicStatus = {
active: boolean;
source: MicSource;
channelMask: number;
codec: MicWireCodec;
format: MicSampleFormat;
/** Requested rate, echoed back; the firmware always captures at 16 kHz. */
sampleRateHz: number;
lc3BitrateBps: number;
beamform: boolean;
armHardware: boolean;
hardwareArmed: boolean;
side: MicSide;
framesEmitted: number;
/** The rate actually in effect (16 kHz on current firmware). */
effectiveRateHz: number;
};
function le16(data: Uint8Array, offset: number): number {
return data[offset]! | (data[offset + 1]! << 8);
}
function sle16(data: Uint8Array, offset: number): number {
const value = le16(data, offset);
return value >= 0x8000 ? value - 0x10000 : value;
}
function le32(data: Uint8Array, offset: number): number {
return (
(data[offset]! | (data[offset + 1]! << 8) | (data[offset + 2]! << 16)) +
data[offset + 3]! * 0x1000000
);
}
const SOURCE_NAMES: MicSource[] = ["codec", "pdm"];
const CODEC_NAMES: MicWireCodec[] = ["lc3", "raw"];
const FORMAT_NAMES: MicSampleFormat[] = ["pcm16", "pcm24", "pcm32"];
/** Decode a field-104 status record body, or null when it isn't one. */
export function decodeMicStatus(body: Uint8Array): MicStatus | null {
if (body.length < 21 || body[0] !== 0x4d || body[1] !== 0x43 || body[2] !== MIC_PROTOCOL_VERSION) {
return null;
}
const flags = body[12]!;
return {
active: body[3] !== 0,
source: SOURCE_NAMES[body[4]!] ?? "pdm",
channelMask: body[5]! & 0b11,
codec: CODEC_NAMES[body[6]!] ?? "lc3",
format: FORMAT_NAMES[body[7]!] ?? "pcm16",
sampleRateHz: le16(body, 8) * 100,
lc3BitrateBps: le16(body, 10) * 100,
beamform: (flags & MIC_FLAG_BEAMFORM) !== 0,
armHardware: (flags & MIC_FLAG_ARM_HW) !== 0,
hardwareArmed: body[13] !== 0,
side: body[14] === 2 ? "left" : "right",
framesEmitted: le32(body, 15),
effectiveRateHz: le16(body, 19) * 100,
};
}
export type MicStreamFrame = {
/** Wraps at 2^16 (~13.6 min at ~80 fps); unwrap on the receiving side. */
sequence: number;
/** This temple's 1 ms OS tick — coarse L/R alignment only. */
deviceTickMs: number;
channelCount: number;
sampleRateHz: number;
format: MicSampleFormat;
codec: MicWireCodec;
/** On-temple TDOA bearing in signed degrees (0 unless beamform + stereo). */
angleDegrees: number;
/** Signal-strength ratio paired with the angle (confidence proxy). */
ssr: number;
truncated: boolean;
payload: Uint8Array;
};
export const SM_HEADER_BYTES = 21;
/** Decode an 'SM' multi-channel stream frame, or null when it isn't one. */
export function decodeMicStreamFrame(data: Uint8Array): MicStreamFrame | null {
if (
data.length < SM_HEADER_BYTES ||
data[0] !== 0x53 ||
data[1] !== 0x4d ||
data[2] !== MIC_PROTOCOL_VERSION
) {
return null;
}
const payLen = le16(data, 19);
const payload = data.subarray(SM_HEADER_BYTES, SM_HEADER_BYTES + payLen);
return {
sequence: le16(data, 4),
deviceTickMs: le32(data, 6),
channelCount: data[10]!,
sampleRateHz: le16(data, 11) * 100,
format: FORMAT_NAMES[data[13]!] ?? "pcm16",
codec: CODEC_NAMES[data[14]!] ?? "raw",
angleDegrees: sle16(data, 15),
ssr: sle16(data, 17),
truncated: (data[3]! & SM_FLAG_TRUNCATED) !== 0,
payload,
};
}
/**
* Split a raw PCM16 SM payload into per-channel Float32Arrays in [-1, 1].
* Channels arrive as CONCATENATED blocks (front then rear), matching the
* firmware's stereo callback, which dispatches two back-to-back extraction
* results rather than interleaving.
*/
export function splitConcatenatedPcm16(frame: MicStreamFrame): Float32Array[] | null {
if (frame.codec !== "raw" || frame.format !== "pcm16" || frame.channelCount < 1) {
return null;
}
const channels = frame.channelCount;
const bytesPerChannel = Math.floor(frame.payload.length / channels) & ~1;
const samplesPerChannel = bytesPerChannel / 2;
if (samplesPerChannel <= 0) return null;
const out: Float32Array[] = [];
for (let channel = 0; channel < channels; channel++) {
const base = channel * bytesPerChannel;
const samples = new Float32Array(samplesPerChannel);
for (let index = 0; index < samplesPerChannel; index++) {
const lo = frame.payload[base + index * 2]!;
const hi = frame.payload[base + index * 2 + 1]!;
let value = lo | (hi << 8);
if (value >= 0x8000) value -= 0x10000;
samples[index] = value / 32768;
}
out.push(samples);
}
return out;
}
/** The stock (non-CFW) 205-byte LC3 packet, for stream sniffing. */
export const STOCK_PACKET_BYTES = 205;
export function isStockAudioPacket(data: Uint8Array): boolean {
return data.length === STOCK_PACKET_BYTES;
}
File diff suppressed because it is too large. Load diff
+130
View File
@@ -0,0 +1,130 @@
import { ConfigSettingBoolean, ConfigSettingEnum } from "../../ui/dashboard-settings";
/**
* Microphones app settings. All stored through the shared settings store so
* the phone UI, glasses menus, and the session engine see the same values.
*/
export type RetentionPeriod = "none" | "1d" | "1w" | "1m" | "1q" | "1y" | "forever";
const RETENTION_VALUES: readonly RetentionPeriod[] = ["none", "1d", "1w", "1m", "1q", "1y", "forever"];
const RETENTION_LABELS: Record<RetentionPeriod, string> = {
none: "None",
"1d": "1 day",
"1w": "1 week",
"1m": "1 month",
"1q": "1 quarter",
"1y": "1 year",
forever: "Forever",
};
export function retentionLabel(period: RetentionPeriod): string {
return RETENTION_LABELS[period];
}
/**
* The deletion cutoff timestamp for a retention period as of now, or 0 when
* nothing should be deleted. "None" deletes everything already stored (and
* the session engine also skips persisting new data).
*/
export function retentionCutoffMs(period: RetentionPeriod, nowMs: number): number {
const day = 24 * 60 * 60 * 1000;
switch (period) {
case "none":
return nowMs;
case "1d":
return nowMs - day;
case "1w":
return nowMs - 7 * day;
case "1m":
return nowMs - 30 * day;
case "1q":
return nowMs - 91 * day;
case "1y":
return nowMs - 365 * day;
case "forever":
return 0;
}
}
export const captionsEnabledSetting = new ConfigSettingBoolean({
id: "microphones-captions",
label: "Captions",
description: "Live speech-to-text captions with speaker names, from the glasses microphones.",
storageKey: "microphones.captions-enabled",
defaultValue: false,
});
export const translateEnabledSetting = new ConfigSettingBoolean({
id: "microphones-translate",
label: "Translate",
description:
"Detect foreign languages in captions and show a translation to the phone's language beneath the original line.",
storageKey: "microphones.translate-enabled",
defaultValue: false,
});
export const saveCaptionsSetting = new ConfigSettingBoolean({
id: "microphones-save-captions",
label: "Save captions",
description: "Keep caption transcripts for later review in the phone app.",
storageKey: "microphones.save-captions",
defaultValue: true,
});
export const saveRecordingsSetting = new ConfigSettingBoolean({
id: "microphones-save-recordings",
label: "Save recordings",
description:
"Keep the audio of caption sessions (compressed to AAC) so transcripts can be replayed and re-analyzed.",
storageKey: "microphones.save-recordings",
defaultValue: false,
});
export const captionsRetentionSetting = new ConfigSettingEnum<RetentionPeriod>({
id: "microphones-captions-retention",
label: "Keep captions",
description: "How long saved captions are retained before automatic deletion.",
storageKey: "microphones.captions-retention",
defaultValue: "1m",
values: RETENTION_VALUES,
formatValue: retentionLabel,
});
export const recordingsRetentionSetting = new ConfigSettingEnum<RetentionPeriod>({
id: "microphones-recordings-retention",
label: "Keep recordings",
description: "How long saved recordings are retained before automatic deletion.",
storageKey: "microphones.recordings-retention",
defaultValue: "1w",
values: RETENTION_VALUES,
formatValue: retentionLabel,
});
export const beamFilterSetting = new ConfigSettingBoolean({
id: "microphones-beam-filter",
label: "Beam filter",
description:
"Only listen to sounds from the shaded direction on the Sonic Radar; audio from other directions is muted.",
storageKey: "microphones.beam-filter",
defaultValue: false,
});
export const ancEnabledSetting = new ConfigSettingBoolean({
id: "microphones-anc",
label: "Noise cancellation",
description:
"Cancel background noise in captured audio: spectral noise suppression on the phone, plus adaptive inter-mic cancellation when the 4-mic array is streaming.",
storageKey: "microphones.anc-enabled",
defaultValue: true,
});
export const wearerCommandsOnlySetting = new ConfigSettingBoolean({
id: "microphones-wearer-commands",
label: "My voice only",
description:
"Restrict voice command recognition to your own enrolled voice; other speakers are captioned but cannot trigger commands.",
storageKey: "microphones.wearer-commands-only",
defaultValue: false,
});
+512
View File
@@ -0,0 +1,512 @@
import { imageFromAsciiArt } from "../../graphics/image";
import { getDefaultSmallFont } from "../../graphics/ui-fonts";
import { appViewportSize } from "../../ui/shell/geometry";
import { LIST_ROW_TEXT_INSET } from "../../ui/metrics";
import {
MenuLayer,
TextPageLayer,
drawRightValueMenuItem,
drawSubmenuIndicator,
drawToggleMenuItem,
openModalMenu,
type MenuItem,
} from "../../ui/menu";
import { enumSettingMenuItem, toggleSettingMenuItem } from "../../ui/dashboard-settings";
import {
createInProcessWindow,
YieldAtRootLayer,
type InProcessAppOptions,
type InProcessWindow,
} from "../../ui/shell/in-process-window";
import { shell } from "../../ui/shell/shell";
import { isAsrModelReady, startAsrModelDownload, asrModelState } from "../../native/asr-model";
import { CaptionsLayer } from "./captions-layer";
import { LevelsLayer } from "./levels-layer";
import { RadarLayer } from "./radar-layer";
import { loadMicConfig, micArrayController, micControlSupported, saveMicConfig } from "./mic-control";
import { isMicModelReady, micModelState, startMicModelDownload } from "./mic-models";
import { micChannelLabel, type MicChannelKey, type MicConfig } from "./mic-protocol";
import { micSession } from "./mic-session";
import { speakerRegistry, type SpeakerProfile } from "./speakers";
import { formatRelativeTime } from "../../util/date-util";
import {
ancEnabledSetting,
beamFilterSetting,
captionsEnabledSetting,
captionsRetentionSetting,
recordingsRetentionSetting,
saveCaptionsSetting,
saveRecordingsSetting,
translateEnabledSetting,
wearerCommandsOnlySetting,
} from "./mic-settings";
export const MICROPHONES_WINDOW_ID = "microphones";
export const MICROPHONES_SURFACE_ID = "window:microphones";
const TRAY_ICON_ID = "microphones";
// 14x15 dual-mic glyph for the top-bar tray.
const TRAY_ICON = imageFromAsciiArt(
[
" ## ## ",
" # # # # ",
" # # # # ",
" # # # # ",
" # # # # ",
"# ## # # ## #",
" # # # # ",
" ## ## ",
" # # ",
" ### ### ",
],
220,
);
const MENU_LAYOUT = {
x: 8,
y: 8,
width: 292,
showBorder: false,
minHeight: 0,
maxHeight: appViewportSize("min").height - 16,
opaque: true,
};
function submenuItem(label: string, onSelect: MenuItem["onSelect"]): MenuItem {
return {
label,
onSelect,
render: ({ image, x, y, width, height, selected, disabled, text }) => {
const font = getDefaultSmallFont();
const value = disabled ? 70 : selected ? 255 : 200;
image.drawText(font, x, y + LIST_ROW_TEXT_INSET, text, value);
drawSubmenuIndicator(image, font, x, y, width, height, value);
},
};
}
/** Persist a config change and re-apply it live when the array is streaming. */
function updateMicConfig(mutate: (config: MicConfig) => MicConfig): void {
const updated = mutate(loadMicConfig());
saveMicConfig(updated);
if (micSession.getState().mode === "extended") {
micArrayController.apply(updated);
}
}
function micChannelToggleItem(
key: MicChannelKey,
description: string,
disabled: () => boolean,
): MenuItem {
return configToggleItem(
`${micChannelLabel(key)} mic`,
() => loadMicConfig().hostMics[key],
() => micSession.setMicChannelEnabled(key, !loadMicConfig().hostMics[key]),
disabled,
description,
);
}
function configToggleItem(
label: string,
isOn: () => boolean,
toggle: () => void,
disabled?: () => boolean,
description?: string,
): MenuItem {
return {
label,
description,
disabled,
onSelect: () => toggle(),
render: ({ image, x, y, width, selected }) => {
drawToggleMenuItem(image, getDefaultSmallFont(), x, y, width, label, isOn(), selected);
},
};
}
function configPickerItem<T extends string | number>(
label: string,
values: readonly T[],
format: (value: T) => string,
current: () => T,
apply: (value: T) => void,
disabled?: () => boolean,
description?: string,
): MenuItem {
return {
label,
description,
disabled,
onSelect: (ctx) => {
const items = values.map(
(value): MenuItem => ({
label: format(value) + (current() === value ? " *" : ""),
onSelect: (innerCtx) => {
apply(value);
innerCtx.stack.pop();
},
}),
);
openModalMenu(ctx, label, items, Math.max(0, values.indexOf(current())));
},
render: ({ image, x, y, width }) => {
drawRightValueMenuItem(image, getDefaultSmallFont(), x, y, width, label, format(current()));
},
};
}
function micSetupMenu(): MenuLayer {
const unsupported = () => !micControlSupported();
return new MenuLayer(
"Microphone setup",
[
{
label: "Array status",
description:
"Per-temple mic-control status. Requires the mic-control custom firmware (caps token micctl).",
onSelect: (ctx) => {
micArrayController.query();
const { left, right } = micArrayController.getStatuses();
const describe = (side: string, status: typeof left) =>
status
? `${side}: ${status.active ? "active" : "idle"}, mics ${status.channelMask & 1 ? "front" : ""}${
status.channelMask & 2 ? "+rear" : ""
}, ${status.effectiveRateHz / 1000} kHz, ${status.hardwareArmed ? "armed" : "not armed"}, ${
status.framesEmitted
} frames`
: `${side}: no status yet`;
const consistency = micArrayController.arrayConsistent()
? "Array consistent (L/R matched)."
: "Array not yet consistent.";
ctx.stack.push(
new TextPageLayer(
"Array status",
micControlSupported()
? `${describe("Left", left)}\n${describe("Right", right)}\n${consistency}`
: "The connected firmware does not advertise mic-control. Flash the microphone-configurations CFW build to control the four mics individually; on stock firmware the glasses stream one mixed channel with a firmware-computed direction of arrival.",
),
);
},
},
// Each temple streams its full front+rear pair; these four toggles are
// host-side selection over the split channels, so any combination of
// the four microphones can be used independently.
micChannelToggleItem("leftFront", "Enable the left temple's front microphone (near the hinge).", unsupported),
micChannelToggleItem("leftRear", "Enable the left temple's rear microphone (by the touchpad).", unsupported),
micChannelToggleItem("rightFront", "Enable the right temple's front microphone (near the hinge).", unsupported),
micChannelToggleItem("rightRear", "Enable the right temple's rear microphone (by the touchpad).", unsupported),
configPickerItem(
"Source",
["pdm", "codec"] as const,
(value) => (value === "pdm" ? "PDM mics" : "Codec DMIC"),
() => loadMicConfig().source,
(value) => updateMicConfig((config) => ({ ...config, source: value })),
unsupported,
"PDM streams one channel; the codec front end streams both mics of a temple.",
),
configPickerItem(
"Codec",
["raw", "lc3"] as const,
(value) => (value === "raw" ? "Raw PCM" : "LC3"),
() => loadMicConfig().codec,
(value) => updateMicConfig((config) => ({ ...config, codec: value })),
unsupported,
"Raw PCM preserves inter-mic phase for beamforming. (Current firmware always streams raw.)",
),
configPickerItem(
"Sample rate",
[8000, 16000, 24000, 32000, 48000] as const,
(value) => `${value / 1000} kHz`,
() => loadMicConfig().sampleRateHz,
(value) => updateMicConfig((config) => ({ ...config, sampleRateHz: value })),
unsupported,
"Requested capture rate per mic pair. Current firmware pins the effective rate at 16 kHz and echoes the request in the status.",
),
configPickerItem(
"LC3 bitrate",
[0, 16000, 32000, 48000, 64000] as const,
(value) => (value === 0 ? "Default" : `${value / 1000} kbps`),
() => loadMicConfig().lc3BitrateBps,
(value) => updateMicConfig((config) => ({ ...config, lc3BitrateBps: value })),
unsupported,
"Requested LC3 bitrate per mic pair (takes effect once the firmware's LC3 path lands).",
),
configToggleItem(
"Direction detection",
() => loadMicConfig().beamform,
() => updateMicConfig((config) => ({ ...config, beamform: !config.beamform })),
unsupported,
"Have each temple compute and stream its own sound direction (TDOA angle + signal strength).",
),
{
label: "4-mic capture (advanced)",
description:
"Arms the microphone hardware and multi-channel streaming on the glasses. Leave off until the firmware validation checklist has passed on this hardware.",
disabled: unsupported,
onSelect: (ctx) => {
const config = loadMicConfig();
if (config.armHardware) {
updateMicConfig((current) => ({ ...current, armHardware: false }));
micArrayController.stopStreaming();
return;
}
openModalMenu(ctx, "Arm mic hardware?", [
{
label: "Cancel",
onSelect: (innerCtx) => innerCtx.stack.pop(),
},
{
label: "Enable (validated hardware only)",
onSelect: (innerCtx) => {
updateMicConfig((current) => ({ ...current, armHardware: true }));
innerCtx.stack.pop();
},
},
]);
},
render: ({ image, x, y, width, selected }) => {
drawToggleMenuItem(
image,
getDefaultSmallFont(),
x,
y,
width,
"4-mic capture (advanced)",
loadMicConfig().armHardware,
selected,
);
},
},
],
MENU_LAYOUT,
);
}
function modelItem(
label: string,
ready: () => boolean,
stateText: () => string,
download: () => void,
): MenuItem {
return {
label,
onSelect: () => {
if (!ready()) download();
},
render: ({ image, x, y, width }) => {
drawRightValueMenuItem(image, getDefaultSmallFont(), x, y, width, label, stateText());
},
};
}
function voiceSpeakersMenu(): MenuLayer {
return new MenuLayer(
"Voice & speakers",
[
{
label: "Enroll my voice",
description:
"Speak a sentence after selecting; the next utterance becomes (or refreshes) your voice-print, used to label you in captions and to restrict commands to your voice.",
disabled: () => !micSession.getState().captionsActive,
onSelect: () => micSession.armWearerEnrollment(),
},
toggleSettingMenuItem(wearerCommandsOnlySetting),
modelItem(
"Speaker voice model",
() => isMicModelReady("speaker-embedding"),
() => {
const state = micModelState("speaker-embedding");
if (state.status === "ready") return "ready";
if (state.status === "downloading") {
return `${Math.round((state.bytesDownloaded / state.totalBytes) * 100)}%`;
}
return "download (28 MB)";
},
() => startMicModelDownload("speaker-embedding"),
),
modelItem(
"Caption ASR model",
isAsrModelReady,
() => {
const state = asrModelState();
if (state.status === "ready") return "ready";
if (state.status === "downloading") {
return `${Math.round((state.bytesDownloaded / state.totalBytes) * 100)}%`;
}
return "download (141 MB)";
},
startAsrModelDownload,
),
modelItem(
"Re-diarization model",
() => isMicModelReady("diarization-segmentation"),
() => {
const state = micModelState("diarization-segmentation");
if (state.status === "ready") return "ready";
if (state.status === "downloading") {
return `${Math.round((state.bytesDownloaded / state.totalBytes) * 100)}%`;
}
return "download (6 MB)";
},
() => startMicModelDownload("diarization-segmentation"),
),
],
MENU_LAYOUT,
);
}
/** The full contact card behind a People row (and behind the encounter popup). */
function speakerDetailBody(profile: SpeakerProfile): string {
const parts: string[] = [
`Last heard ${profile.lastHeardAt ? `${formatRelativeTime(profile.lastHeardAt)} ago` : "never"}.`,
];
if (profile.tag) parts.push(`Note: ${profile.tag}`);
if (profile.lastRecap) parts.push(`Last conversation: ${profile.lastRecap}`);
if (profile.actionItems.length) {
parts.push(`To do:\n${profile.actionItems.map((item) => `- ${item}`).join("\n")}`);
}
if (profile.facts.length) {
parts.push(`Facts:\n${profile.facts.map((fact) => `- ${fact}`).join("\n")}`);
}
if (parts.length === 1) {
parts.push(
"No conversation insights yet. A recap, action items, and remembered facts are " +
"generated when a captioned conversation with this person ends (requires the " +
"on-phone assistant model).",
);
}
return parts.join("\n\n");
}
/**
* People: the speaker-recognition contacts, most recently heard first — the
* review surface behind the encounter popup. Selecting a person shows when
* they were last heard, their note, the recap and action items of the last
* conversation, and the facts remembered about them.
*/
function peopleMenu(): MenuLayer {
const profiles = speakerRegistry.all().filter((profile) => !profile.isWearer);
const items: MenuItem[] = profiles.length
? profiles.map((profile) => ({
label: profile.name,
onSelect: (ctx) => {
ctx.stack.push(new TextPageLayer(profile.name, speakerDetailBody(profile)));
},
render: ({ image, x, y, width }) => {
drawRightValueMenuItem(
image,
getDefaultSmallFont(),
x,
y,
width,
profile.name,
profile.lastHeardAt ? `${formatRelativeTime(profile.lastHeardAt)} ago` : "",
);
},
}))
: [
{
label: "No people heard yet",
disabled: true,
onSelect: () => {},
},
];
return new MenuLayer("People", items, MENU_LAYOUT);
}
function storageMenu(): MenuLayer {
return new MenuLayer(
"Storage",
[
toggleSettingMenuItem(saveCaptionsSetting),
toggleSettingMenuItem(saveRecordingsSetting),
enumSettingMenuItem(captionsRetentionSetting),
enumSettingMenuItem(recordingsRetentionSetting),
{
label: "Review on phone",
description:
"Saved conversations, transcripts, speakers, and recordings are reviewed in the Faceclaw phone app: Conversations in the top-right menu.",
onSelect: (ctx) => {
ctx.stack.push(
new TextPageLayer(
"Review on phone",
"Open the Faceclaw app on your phone and choose Conversations from the top-right menu to search captions, filter by speaker, play linked recordings, rename/merge speakers, re-diarize sessions, and see the tone/sentiment graph of each conversation.",
),
);
},
},
],
MENU_LAYOUT,
);
}
export function createMicrophonesAppWindow(options: InProcessAppOptions): InProcessWindow {
const menu = new MenuLayer(
"Microphones",
[
submenuItem("Sonic Radar", (ctx) => {
const layer = new RadarLayer();
ctx.stack.push(layer);
layer.start(ctx.actions.requestRender);
}),
submenuItem("Levels", (ctx) => {
const layer = new LevelsLayer();
ctx.stack.push(layer);
layer.start(ctx.actions.requestRender);
}),
submenuItem("Captions view", (ctx) => {
const layer = new CaptionsLayer();
ctx.stack.push(layer);
layer.start(ctx.actions.requestRender);
}),
submenuItem("People", (ctx) => {
speakerRegistry.reload();
ctx.stack.push(peopleMenu());
}),
configToggleItem(
"Captions",
() => captionsEnabledSetting.get(),
() => micSession.setCaptionsEnabled(!captionsEnabledSetting.get()),
undefined,
captionsEnabledSetting.description,
),
toggleSettingMenuItem(translateEnabledSetting),
toggleSettingMenuItem(beamFilterSetting),
toggleSettingMenuItem(ancEnabledSetting),
submenuItem("Microphone setup", (ctx) => {
ctx.stack.push(micSetupMenu());
}),
submenuItem("Voice & speakers", (ctx) => {
ctx.stack.push(voiceSpeakersMenu());
}),
submenuItem("Storage", (ctx) => {
ctx.stack.push(storageMenu());
}),
],
MENU_LAYOUT,
);
const app = createInProcessWindow({
appId: "microphones",
windowId: MICROPHONES_WINDOW_ID,
title: "Microphones",
iconLetter: "Mi",
icon: "mic",
closeable: true,
actions: options.actions,
baseLayer: new YieldAtRootLayer(menu),
submitFrame: options.submitFrame,
setSurfaceVisible: options.setSurfaceVisible,
removeSurface: options.removeSurface,
onClosed: () => {
micSession.stop();
shell.setTrayIcon(TRAY_ICON_ID, null);
options.onClosed();
},
});
micSession.start();
shell.setTrayIcon(TRAY_ICON_ID, TRAY_ICON);
return app;
}
+688
View File
@@ -0,0 +1,688 @@
/**
* Known-first-names dataset: the 5,000 most common US first
* names per sex from the Social Security Administration baby-names data
* (births 1935-2024 summed), plus the British/Irish supplement the US list
* under-represents (Niamh, Callum, Isobel...). Deduplicated and normalized
* to 9,260 entries: lowercase, diacritics folded, punctuation dropped - the
* same key normalization lookups apply, so "Siobhán" and "Siobhan" reach
* the same entry.
*
* This is a POSITIVE signal only: membership means a word is almost
* certainly usable as a given name; absence means nothing (real names the
* SSA list misses must still pass). Callers use it to skip more expensive
* or more error-prone checks, never to reject a candidate.
*/
const RAW =
"aaden,aadhya,aadi,aadya,aaiden,aakash,aaliyah,aamir,aanya,aarav,aaren,aariv,aariz,aarna,aaron,aarron," +
"aarush,aarya,aaryan,aayan,aayden,aayush,abagail,abbas,abbey,abbi,abbie,abbigail,abbigale,abbott,abby," +
"abbygail,abdallah,abdiel,abdirahman,abdoulaye,abdul,abdulaziz,abdullah,abdullahi,abdulrahman,abdurrahman," +
"abe,abel,abelardo,abhinav,abhiram,abiel,abigael,abigail,abigale,abigayle,abimael,abisai,able,abner," +
"abraham,abrahan,abram,abran,abriana,abrianna,abriella,abrielle,abril,abubakar,abygail,acacia,ace," +
"achilles,acie,ada,adah,adair,adalberto,adalee,adaleigh,adalia,adalie,adalina,adaline,adalyn,adalynn," +
"adam,adamari,adamaris,adams,adan,adara,adarius,addalyn,addalynn,addelyn,addie,addilyn,addilynn,addison," +
"addisyn,addyson,adel,adela,adelaida,adelaide,adele,adelia,adelina,adeline,adelita,adell,adella,adelle," +
"adelyn,adelynn,adem,aden,adena,adham,adia,adian,adiel,adil,adilene,adilyn,adilynn,adin,adina,adira," +
"adison,aditi,aditya,adler,adley,adnan,adolfo,adolph,adolphus,adon,adonai,adonis,adora,adrain,adria," +
"adrian,adriana,adriane,adrianna,adrianne,adriano,adriel,adrien,adriene,adrienne,adrina,adryan,advaith," +
"advik,adyn,adyson,aedan,aeden,aerial,aeris,afton,agapito,agastya,agatha,agnes,agustin,ahaan,aharon," +
"ahmad,ahmari,ahmed,ahmir,ahren,ahron,ahuva,aida,aidan,aide,aiden,aidyn,aila,ailani,ailany,aileen," +
"ailyn,aime,aimee,aine,ainhoa,ainsley,aisha,aisling,aislinn,aislyn,aislynn,aitana,aiyana,aiyanna,aiyden," +
"aiza,aizen,aj,aja,ajani,ajay,akai,akash,akeem,akhil,akil,akilah,akira,akiva,akram,aksel,akshara,akshay," +
"al,alaia,alain,alaina,alaiya,alaiyah,alan,alana,alanah,alane,alani,alanis,alanna,alannah,alara,alaric," +
"alasdair,alasia,alastair,alaura,alaya,alayah,alayla,alayna,alaysha,alaysia,alba,albert,alberta,albertha," +
"alberto,albin,albino,aldair,alden,alder,aldo,aldon,alea,aleah,alec,alecia,aleczander,aleen,aleena," +
"aleesha,aleia,aleida,aleigha,aleisha,alejandra,alejandro,alek,aleksandar,aleksander,aleksandr,aleksandra," +
"alekzander,alen,alena,alene,alesha,aleshia,alesia,alessa,alessandra,alessandro,alessia,alessio,aleta," +
"aletha,alethea,alethia,alex,alexa,alexander,alexandra,alexandre,alexandrea,alexandria,alexandro,alexandros," +
"alexavier,alexei,alexi,alexia,alexie,alexis,alexsander,alexsandra,alexus,alexys,alexzander,alexzandria," +
"aleya,aleyah,aleyda,aleyna,alfie,alfonso,alfonza,alfonzo,alford,alfred,alfreda,alfredo,ali,alia,aliah," +
"aliana,alianna,alias,alice,alicia,alida,alijah,alina,aline,alisa,alise,alisha,alishia,alisia,alison," +
"alissa,alisson,alistair,alister,alita,alivia,alix,aliya,aliyah,aliyana,aliza,alizabeth,alize,allan," +
"allana,allegra,allen,allena,allene,alli,allie,allison,allissa,allisson,allister,alliyah,ally,allyn," +
"allysa,allyson,allyssa,alma,alon,alona,alondra,alonna,alonso,alonza,alonzo,alora,aloysius,alpha,alphonse," +
"alphonso,alphonzo,alston,alta,althea,alton,alva,alvaro,alvie,alvin,alvina,alvino,alvis,alya,alyana," +
"alyanna,alyce,alycia,alyna,alysa,alyse,alysha,alysia,alyson,alyssa,alyssia,alyvia,alyza,amaan,amada," +
"amadeo,amadeus,amado,amador,amadou,amaia,amaiya,amal,amalia,aman,amanda,amando,amani,amar,amara,amarah," +
"amare,amaree,amari,amaria,amariah,amarie,amarion,amaris,amaru,amauri,amaury,amaya,amayah,ambar,amber," +
"amberlee,amberly,amberlyn,ambria,ambrose,ambrosia,amee,ameen,ameena,ameer,ameera,ameerah,amelia,amelie," +
"amen,amer,amere,america,americo,amerie,ames,amethyst,ami,amia,amiah,amias,amie,amiee,amiel,amilcar," +
"amilia,amin,amina,aminah,aminata,amir,amira,amiracle,amirah,amiri,amit,amity,amiya,amiyah,ammar,ammie," +
"ammon,amna,amon,amor,amora,amos,amoura,amparo,amr,amy,amya,amyah,amyra,an,ana,anabel,anabella,anabelle," +
"anahi,anai,anaiah,anais,anaiya,anakin,analee,analeigh,anali,analia,analicia,analiese,analisa,analise," +
"analy,anamaria,anand,ananda,ananya,anas,anastacia,anastacio,anastasia,anastasios,anay,anaya,anayah," +
"anayeli,ander,anders,andersen,anderson,andi,andie,andon,andra,andrae,andre,andrea,andreana,andreas," +
"andree,andrei,andres,andrew,andrey,andrez,andria,andriana,andru,andy,aneesh,anel,anela,anessa,anette," +
"anfernee,angel,angela,angelena,angelene,angeles,angelia,angelic,angelica,angelie,angelika,angelina," +
"angeline,angelique,angelita,angella,angelle,angelo,angely,angelyn,angie,angus,ani,ania,aniah,anibal," +
"anika,anil,anirudh,anisa,anish,anisha,anissa,aniston,anita,anitra,aniya,aniyah,anja,anjali,anjanette," +
"anjel,anjelica,ann,anna,annabel,annabell,annabella,annabelle,annabeth,annah,annalee,annaleigh,annaliese," +
"annalisa,annalise,annalyse,annamae,annamaria,annamarie,annastasia,anne,anneliese,annelise,annemarie," +
"annetta,annette,annie,annika,anniston,annmarie,ansel,anselmo,ansh,ansley,anson,anthoney,anthoni,anthony," +
"antione,antionette,antoine,antoinette,anton,antone,antonella,antonette,antoni,antonia,antonina,antonino," +
"antonio,antony,antron,antuan,antwain,antwan,antwaun,antwoine,antwon,antwone,anuj,anushka,anwar,anya," +
"anyah,anyla,anylah,anyssa,aoife,apolinar,apollo,apolonio,april,apryl,ara,arabella,arabelle,araceli," +
"aracely,aram,aramis,aran,aranza,arash,arath,arav,araya,arcadio,arcelia,archer,archibald,archie,ardell," +
"arden,ardis,ardith,areli,arely,aren,ares,aretha,argenis,arham,ari,aria,ariadna,ariadne,ariah,arian," +
"ariana,ariane,arianna,arianne,arianny,aric,arica,arick,arie,ariel,ariela,ariella,arielle,aries,arik," +
"arika,arin,arion,arionna,aris,arisbeth,arissa,aristotle,arius,ariya,ariyah,ariyana,ariyanna,arizona," +
"arjun,arla,arlan,arland,arleen,arlen,arlena,arlene,arlet,arleth,arlette,arley,arlie,arlin,arline," +
"arlis,arlo,arlon,arlyn,armaan,arman,armand,armando,armani,armen,armida,armin,armon,armond,armondo," +
"armoni,arnaldo,arnav,arne,arnell,arnetta,arnie,arnita,arno,arnold,arnoldo,arnulfo,aron,arron,arrow," +
"arsenio,art,artem,artemio,artemis,arther,arthur,artie,artis,arturo,arun,arvid,arvil,arvin,arwen,arya," +
"aryah,aryan,aryana,aryanna,aryeh,aryn,asa,asad,asael,asaiah,asante,ash,asha,ashanti,ashby,ashely," +
"asher,ashia,ashlea,ashlee,ashlei,ashleigh,ashley,ashli,ashlie,ashlin,ashly,ashlyn,ashlynn,ashlynne," +
"ashraf,ashten,ashtin,ashton,ashtyn,ashwin,asia,asiah,asim,asiya,asiyah,aslan,asma,aspen,aspyn,aston," +
"astrid,asya,athan,athanasios,atharv,atharva,athena,atlas,atlee,atom,atreus,atreyu,atticus,aubree," +
"aubrey,aubri,aubriana,aubrianna,aubrie,aubriella,aubrielle,aubry,auden,audie,audra,audrea,audree," +
"audrey,audriana,audrianna,audrie,audrina,audry,august,augusta,augustin,augustine,augusto,augustus," +
"aundre,aundrea,aura,aurelia,aurelio,aurelius,aurora,austen,austin,auston,austyn,auther,author,authur," +
"autry,autum,autumn,ava,avah,avalon,avalyn,avalynn,avan,avani,avarie,avary,avaya,avayah,aven,averi," +
"averie,avery,avi,avia,avian,aviana,avianna,aviel,avigail,avin,avinash,avion,avis,aviva,avon,avraham," +
"avram,avril,avrohom,avyaan,avyan,awilda,axel,axell,axl,axle,axton,aya,ayaan,ayah,ayan,ayana,ayanna," +
"ayansh,aydan,ayden,aydin,ayesha,ayla,aylah,aylani,ayleen,aylin,ayman,ayoub,ayra,aysha,aysia,ayub," +
"ayush,ayva,ayvah,ayven,azaan,azael,azai,azaiah,azalea,azalia,azari,azaria,azariah,aziah,aziel,aziyah," +
"aziz,aziza,azlan,azrael,azriel,azucena,azul,azure,babette,baby,babyboy,babygirl,baila,bailee,baileigh," +
"bailey,bailie,bakari,baker,baldemar,baleigh,baltazar,bambi,bane,banks,barak,barb,barbara,barbie,barbra," +
"bari,barney,baron,barret,barrett,barrie,barrington,barron,barry,bart,bartholomew,bartley,barton,baruch," +
"bashir,basil,basilio,bastian,batsheva,baxter,baylee,bayleigh,baylen,bayley,baylie,baylor,bayron,bear," +
"beatrice,beatrix,beatriz,beau,beaux,becca,beck,beckam,beckett,beckham,becki,beckie,becky,belen,belinda," +
"bella,bellamy,belle,belva,ben,benaiah,benard,benedict,benicio,benigno,benita,benito,benjaman,benjamen," +
"benjamin,benjamine,benji,benjie,benjiman,bennet,bennett,bennie,benny,benson,bentlee,bentley,bently," +
"benton,benuel,benzion,berenice,berkeley,berkley,berlin,bernabe,bernadette,bernadine,bernard,bernardino," +
"bernardo,bernell,bernetta,bernice,bernie,berniece,bernita,berry,bert,berta,bertha,bertie,berton,bertram," +
"bertrand,beryl,bess,bessie,beth,bethanie,bethann,bethany,bethel,betsey,betsy,bette,bettie,bettina," +
"betty,bettye,beulah,beverlee,beverley,beverly,bexley,beyonce,bianca,bianka,bijan,bilal,bill,billi," +
"billie,billy,binyamin,binyomin,birdie,bishop,bjorn,blade,bladimir,blain,blaine,blair,blaire,blaise," +
"blaize,blake,blakely,blanca,blanche,blane,blas,blayke,blayne,blayze,blaze,blessing,bliss,blossom," +
"blythe,bo,boaz,bob,bobbi,bobbie,bobby,bobbye,bode,boden,bodhi,bodie,boe,bonifacio,bonita,bonnie,bonny," +
"booker,boone,boris,boruch,boston,bowen,bowie,boyce,boyd,bracha,brad,braden,bradford,bradlee,bradley," +
"bradly,bradon,brady,bradyn,braedan,braeden,braedon,braedyn,braelyn,braelynn,braiden,brain,bram,branch," +
"brandan,brandee,branden,brandi,brandie,brandin,brando,brandon,brandt,brandy,brandyn,brannon,branson," +
"brant,brantlee,brantley,branton,braulio,braven,braxten,braxton,braxtyn,brayan,braydan,brayden,braydin," +
"braydon,braylan,braylee,brayleigh,braylen,braylin,braylon,brayson,brayton,brea,breana,breann,breanna," +
"breanne,breck,brecken,breckin,bree,breeana,breeanna,brenda,brendan,brenden,brendon,brendyn,brenna," +
"brennan,brennen,brenner,brennon,brent,brentley,brently,brenton,breon,breona,breonna,bret,brett,bretton," +
"brevin,brewer,brexton,breyden,bria,brian,briana,brianda,briann,brianna,brianne,briant,briar,brice," +
"bricen,bridger,bridget,bridgett,bridgette,brie,brieanna,briella,brielle,brien,brienna,brigette,briggs," +
"brigham,brighton,brigid,brigitte,briley,brinda,brinlee,brinley,brion,briona,brionna,brisa,briseida," +
"briseyda,brison,brissa,bristol,britany,britnee,britney,britni,britny,britt,britta,brittaney,brittani," +
"brittanie,brittany,brittnay,brittnee,brittney,brittni,brittnie,brittny,britton,brixton,broc,brock," +
"broden,broderick,brodey,brodie,brodrick,brody,brogan,bronson,bronwen,bronwyn,bronx,brook,brooke,brookelyn," +
"brookelynn,brooklin,brooklyn,brooklynn,brooklynne,brooks,bruce,bruno,bryan,bryana,bryanna,bryant," +
"bryar,bryce,brycen,bryden,bryer,brylan,brylee,bryleigh,brylie,bryn,brynlee,brynleigh,brynley,brynn," +
"brynna,brynne,brynnlee,bryon,brysen,bryson,bryston,bryton,buck,buckley,bucky,bud,buddy,buffy,buford," +
"burke,burl,burley,burnell,burt,burton,buster,butch,byran,byron,cache,cade,caden,cadence,cady,cadyn," +
"caeden,caedmon,cael,caelan,caelyn,caesar,cage,cai,caiden,cailee,cailey,cailin,cailyn,cain,cainan," +
"caine,cairo,caison,caitlin,caitlyn,caitlynn,caius,cal,calan,calandra,calder,cale,caleb,caleigh,calen," +
"caley,cali,calin,calista,caliyah,calla,callahan,callan,calleigh,callen,calli,callie,calliope,callista," +
"callum,cally,calum,calvert,calvin,cam,camari,cambree,cambria,cambrie,camden,camdon,camdyn,camelia," +
"camellia,cameran,cameren,cameron,cameryn,cami,camie,camila,camilla,camille,camilo,cammie,campbell," +
"camren,camrin,camron,camryn,canaan,candace,candance,candelaria,candelario,candi,candice,candida,candido," +
"candie,candis,candra,candy,candyce,cannon,canon,canyon,capri,caprice,cara,cardell,caren,carey,cari," +
"caridad,carie,carin,carina,carisa,carissa,carl,carla,carlee,carleen,carleigh,carlene,carleton,carletta," +
"carley,carli,carlie,carlin,carlisle,carlito,carlo,carlos,carlotta,carlton,carly,carlyle,carlyn,carma," +
"carman,carmel,carmela,carmelita,carmella,carmello,carmelo,carmen,carmine,carnell,carol,carolann,carole," +
"carolee,carolina,caroline,carolyn,carolyne,carolynn,caron,carri,carrie,carrington,carrol,carroll," +
"carsen,carson,carsten,carsyn,carter,cartier,carver,cary,caryl,caryn,carys,casandra,case,casen,casey," +
"cash,cashton,casie,casimir,cason,casper,caspian,cass,cassandra,cassaundra,cassey,cassi,cassia,cassian," +
"cassidy,cassie,cassius,cassondra,cassy,castiel,cataleya,catalina,catarina,catarino,cate,catelyn,caterina," +
"cathal,catharine,catherine,cathey,cathi,cathie,cathleen,cathrine,cathryn,cathy,catina,catrina,catriona," +
"cattleya,cavan,cavin,cayde,cayden,caydence,cayla,cayleb,caylee,cayleigh,caylie,caylin,cayman,caysen," +
"cayson,ceasar,cecelia,cecil,cecile,cecilia,cecilio,cecily,cedar,cedric,cedrick,celena,celene,celeste," +
"celestina,celestine,celestino,celia,celina,celine,celso,cesar,chace,chad,chadd,chadrick,chadwick," +
"chaim,chaise,champ,chan,chana,chance,chancellor,chancey,chanda,chandler,chandra,chanel,chanell,chanelle," +
"channing,chanse,chantal,chante,chantel,chantell,chantelle,chantz,charis,charise,charisma,charissa," +
"charisse,charity,charla,charlee,charleen,charleigh,charlene,charles,charleston,charlette,charley," +
"charli,charlie,charline,charlize,charlotte,charlton,charly,charlyn,charmaine,charolette,chas,chase," +
"chasen,chasidy,chasity,chason,chassidy,chassity,chastity,chauncey,chauncy,chava,chaya,chayce,chayse," +
"chayton,chaz,chazz,che,chelsea,chelsee,chelsey,chelsi,chelsie,chelsy,chenoa,cher,cheree,cherelle," +
"cheri,cherie,cherilyn,cherise,cherish,cherlyn,cherokee,cherri,cherrie,cherry,cherryl,cheryl,cheryle," +
"cheryll,chesley,chesney,chester,chet,chevelle,chevy,cheyann,cheyanne,cheyenne,cheyne,chiara,chico," +
"china,chip,chiquita,chirstopher,chistopher,chloe,chloee,chole,chosen,chozen,chris,chrissy,christ," +
"christa,christain,christal,christan,christel,christen,christena,christene,christi,christian,christiana," +
"christiane,christianna,christie,christien,christin,christina,christine,christion,christofer,christoher," +
"christon,christop,christoper,christoph,christophe,christopher,christos,christpher,christy,chrystal," +
"chuck,chyanne,chyna,chynna,cian,ciana,cianna,ciara,ciaran,ciarra,cicely,cielo,cienna,ciera,cierra," +
"cillian,cinda,cindi,cindy,cinnamon,cinthia,cinthya,cipriano,cirilo,ciro,citlali,citlalli,citlaly," +
"cj,clair,claira,claire,clancy,clara,clarance,clare,clarence,claribel,clarice,clarisa,clarissa,clark," +
"clarke,claud,claude,claudette,claudia,claudie,claudine,claudio,clay,clayton,clem,clement,clemente," +
"clementine,cleo,cleon,cleopatra,cleophus,cleta,cletus,cleve,cleveland,cliff,clifford,cliffton,clifton," +
"clint,clinton,clive,cloe,cloey,clover,clovis,cloyd,clyde,coby,coco,coda,codey,codi,codie,cody,coen," +
"cohen,colbie,colby,colden,cole,coleen,coleman,coleson,coleton,colette,coley,colin,colleen,collette," +
"collier,collin,collins,colsen,colson,colston,colt,colten,colter,coltin,colton,coltyn,columbus,conan," +
"concepcion,concetta,conlan,conley,connell,conner,connie,connor,conor,conrad,conrado,constance,constantine," +
"constantino,consuela,consuelo,contessa,conway,cooper,copeland,cora,coral,coralee,coralie,coraline," +
"corban,corben,corbett,corbin,corby,corbyn,cord,cordarius,cordelia,cordell,cordero,coreen,coretta," +
"corey,cori,corie,corin,corina,corine,corinna,corinne,corissa,corliss,cormac,cornel,cornelia,cornelio," +
"cornelious,cornelius,cornell,correy,corrie,corrin,corrina,corrine,corry,cort,cortez,cortland,cortney," +
"corwin,cory,cosette,cosme,cosmo,coty,courtland,courtnee,courtney,courtnie,cove,coy,craig,crawford," +
"cree,creed,creighton,crew,cris,criselda,crispin,crissy,crista,cristal,cristen,cristhian,cristi,cristian," +
"cristiano,cristie,cristin,cristina,cristine,cristo,cristobal,cristofer,cristopher,cristy,croix,crosby," +
"cross,cru,crue,cruz,crysta,crystal,cuauhtemoc,cullen,curley,curran,curry,curt,curtis,curtiss,cutler," +
"cutter,cy,cydney,cylas,cyle,cyndi,cynthia,cypress,cyril,cyrus,dacia,dade,daelyn,daemon,daevon,dafne," +
"dafydd,dagan,dagoberto,dahlia,daija,daijah,dailyn,dain,daina,daisey,daisha,daisy,daivd,daja,dajah," +
"dajon,dajuan,dakarai,dakari,dakoda,dakota,dakotah,dalary,dale,dalen,daleyza,dalia,dalila,dalilah," +
"dallas,dallen,dallin,dalton,dalvin,dalyn,damani,damar,damarcus,damari,damario,damarion,damaris,damarius," +
"damein,damen,dameon,damian,damien,damion,damir,damon,damond,damone,damoni,damonte,dan,dana,danae," +
"dandre,dane,daneil,danelle,danette,dangelo,dani,dania,danial,danica,daniel,daniela,daniele,daniell," +
"daniella,danielle,danika,danilo,danisha,danita,daniyah,dann,danna,dannette,danni,dannie,danniel,dannielle," +
"danny,dante,danthony,dany,danya,danyel,danyell,danyelle,daphne,daquan,dara,darby,darcey,darci,darcie," +
"darcy,darek,darel,darell,daren,daria,darian,dariana,darick,dariel,darien,darin,dario,darion,darious," +
"daris,darius,darl,darla,darleen,darlene,darline,darlyn,darnel,darnell,darold,daron,darrel,darrell," +
"darren,darrian,darrick,darrien,darrin,darrion,darris,darrius,darron,darry,darryl,darryle,darryll," +
"darryn,darsh,dartagnan,darvin,darwin,daryl,daryle,daryll,daryn,dasean,dash,dasha,dashaun,dashawn," +
"dashiell,dashon,dasia,dathan,daulton,daunte,davante,dave,daven,daveon,davey,davi,davian,david,davida," +
"davidson,davie,davien,davin,davina,davion,davis,davon,davonta,davontae,davonte,davy,dawayne,dawn," +
"dawna,dawne,dawson,dawud,dax,daxon,daxton,dayana,dayanara,dayanna,dayla,daylan,dayle,daylen,daylin," +
"daylon,daymon,dayna,dayne,daysha,dayshawn,dayson,dayton,dayvon,dea,deacon,deagan,dean,deana,deandra," +
"deandre,deandrea,deane,deangelo,deann,deanna,deanne,deante,deanthony,deasia,deaundre,debbi,debbie," +
"debbra,debby,debi,debora,deborah,debra,debrah,decarlos,decker,declan,dede,dedra,dedric,dedrick,dee," +
"deeann,deeanna,deedee,deedra,deegan,deen,deena,deidra,deidre,deion,deirdre,deisy,deja,dejah,dejon," +
"dejuan,deklan,del,delaine,delainey,delana,delaney,delani,delanie,delano,delbert,delena,delfina,delfino," +
"delia,delicia,delila,delilah,delina,delinda,delisa,dell,della,delma,delmar,delmas,delmer,delois,deloise," +
"delon,delonte,delora,delores,deloris,delphine,delroy,delta,delton,delvin,delvon,delwin,demar,demarco," +
"demarcus,demari,demario,demarion,demarius,demarkus,demetra,demetri,demetria,demetric,demetrice,demetrio," +
"demetrios,demetrious,demetris,demetrius,demi,demian,demir,demitri,demitrius,demond,demonte,dempsey," +
"dena,denae,denali,deneen,denice,denim,denis,denise,denisha,denisse,denita,deniz,denna,dennie,dennis," +
"dennise,denny,denton,denver,denzel,denzell,denzil,deon,deondre,deonna,deonta,deontae,deontay,deonte," +
"dequan,derald,dereck,derek,dereon,derian,deric,derick,derik,derion,deron,derreck,derrek,derrel,derrell," +
"derric,derrick,derrik,derrion,derron,derry,derwin,deryl,desarae,desean,deshaun,deshawn,deshon,deshun," +
"desi,desirae,desiray,desire,desirea,desiree,desmon,desmond,dessie,destanie,destany,desteny,destin," +
"destinee,destiney,destini,destinie,destiny,destry,detra,detrick,dev,devan,devansh,devante,devaughn," +
"deven,devin,devion,devlin,devon,devona,devonna,devonta,devontae,devonte,devora,devorah,devyn,dewayne," +
"dewey,dewitt,dexter,deyanira,deysi,dezirae,dezmond,dhruv,dia,diamond,dian,diana,diandra,diane,diann," +
"dianna,dianne,diante,dick,dickie,didier,diedra,diedre,diego,diesel,dieter,dietrich,dijon,dilan,dillan," +
"dillard,dillion,dillon,dimas,dimitri,dimitrios,dimitrius,dina,dinah,dino,dion,diondre,dione,dionicio," +
"dionisio,dionna,dionne,dionte,dior,dirk,divine,divya,dixie,dixon,diya,djuan,dmitri,dock,dolan,dollie," +
"dolly,dolores,domanic,domenic,domenica,domenick,domenico,dominga,domingo,dominic,dominica,dominick," +
"dominik,dominique,dominque,domonic,domonick,domonique,don,dona,donal,donald,donato,donavan,donaven," +
"donavin,donavon,dondre,donell,donetta,donielle,donita,donivan,donn,donna,donnell,donnie,donny,donovan," +
"donta,dontae,dontavious,dontavius,dontay,donte,dontez,dontrell,donya,donzell,dora,doran,dorcas,doreen," +
"dorene,doretha,doretta,dori,dorian,dorie,dorien,dorinda,dorine,doris,dorman,dorothea,dorothy,dorris," +
"dorsey,dortha,dorthy,dottie,doug,douglas,douglass,dov,dovid,dovie,doyle,draco,drake,draven,drayden," +
"drayton,dream,dreama,drema,dresden,drew,drexel,dru,drucilla,drue,drusilla,duane,dudley,dujuan,duke," +
"dulce,duncan,duran,durand,durell,durrell,durward,durwood,dustan,dusten,dusti,dustin,duston,dusty," +
"dustyn,dutch,dutton,duwayne,dwain,dwaine,dwan,dwane,dwayne,dwight,dwyane,dyan,dyana,dyanna,dylan," +
"dyland,dylen,dyllan,dyllon,dylon,dymond,dynasty,dyson,eamon,eamonn,ean,earl,earle,earlene,earlie," +
"earline,early,earnest,earnestine,eartha,earvin,eason,easter,easton,eastyn,eathan,eben,ebenezer,eber," +
"ebonee,eboni,ebonie,ebony,echo,ed,eda,edan,edd,eddie,eddy,eden,eder,edgar,edgard,edgardo,edie,edin," +
"edison,edith,edmond,edmund,edmundo,edna,edric,edrick,edsel,edson,eduard,eduardo,edvin,edward,edwardo," +
"edwin,edwina,edythe,effie,efraim,efrain,efrem,efren,egan,egypt,ehren,eian,eiden,eileen,eilidh,eisley," +
"eitan,eithan,ela,eladio,elaina,elaine,elam,elan,elana,elani,elayna,elayne,elba,elbert,elda,elden," +
"elder,eldon,eldred,eldridge,eleana,eleanor,eleanora,eleanore,eleazar,elena,eleni,elexis,elgin,eli," +
"elia,eliah,eliam,elian,eliana,elianna,elias,eliazar,elicia,elida,elie,eliel,eliezer,eligio,elija," +
"elijah,elijiah,elimelech,elin,elina,elinor,elio,eliot,eliott,elisa,elisabeth,elise,eliseo,elisha," +
"elisheva,elisia,elissa,eliud,eliyahu,eliza,elizabet,elizabeth,elizebeth,ella,elle,ellen,ellena,ellery," +
"elli,ellia,elliana,ellianna,ellie,elliette,elliot,elliott,ellis,ellison,ellsworth,elly,ellyn,elma," +
"elmer,elmo,elmore,elnora,elodie,eloisa,eloise,elon,elora,elouise,elowen,elowyn,eloy,elroy,elsa,elsie," +
"elson,elspeth,elsy,elton,elva,elvia,elvin,elvira,elvis,elwin,elwood,elwyn,ely,elyana,elyas,elyjah," +
"elyse,elysia,elyssa,elzie,ema,emalee,emalyn,eman,emani,emanuel,emari,ember,emberlee,emberly,emberlyn," +
"emberlynn,emelia,emelie,emeline,emely,emelyn,emerald,emeri,emerie,emerson,emersyn,emery,emi,emil," +
"emile,emilee,emiley,emili,emilia,emiliana,emiliano,emilie,emilio,emily,emir,emma,emmalee,emmaleigh," +
"emmaline,emmalyn,emmalynn,emmanuel,emmarie,emme,emmeline,emmerson,emmet,emmett,emmi,emmie,emmit,emmitt," +
"emmy,emoni,emory,empress,emre,emrie,emry,emrys,ena,ender,enedina,enid,enmanuel,ennis,enoc,enoch,enos," +
"enrico,enrique,ensley,enzo,eoin,eowyn,ephraim,epifanio,era,erasmo,eren,eriberto,eric,erica,erich," +
"erick,ericka,erickson,erie,erik,erika,erin,erinn,eris,erlinda,erma,ermias,erna,ernest,ernestina,ernestine," +
"ernesto,ernie,ernst,eron,eros,errick,errol,erskine,ervin,erwin,eryk,eryn,erynn,esai,esau,esdras,esequiel," +
"esha,eshaan,eshan,esme,esmeralda,esperanza,essence,essie,esteban,estefani,estefania,estefany,estela," +
"estella,estelle,estephanie,ester,estevan,esther,eston,estrella,eternity,ethan,ethaniel,ethel,ethen," +
"ethyn,etienne,etta,eugene,eugenia,eugenie,eugenio,eula,eulalia,eulalio,eunice,eusebio,eva,evalina," +
"evalyn,evalynn,evan,evander,evangelina,evangeline,evangelos,evans,evaristo,eve,evelin,evelina,eveline," +
"evelyn,evelyne,evelynn,ever,everardo,everest,everett,everette,everlee,everleigh,everley,everly,evert," +
"evette,evie,evin,evon,evonne,evren,ewan,exavier,eyad,eyan,ezekial,ezekiel,ezell,ezequiel,ezio,ezra," +
"ezrah,ezriel,fabian,fabiana,fabio,fabiola,fabricio,fabrizio,fahad,faigy,faisal,faith,fallon,falon," +
"fannie,fanny,fantasia,farah,fares,farhan,farid,faris,faron,farrah,farrell,farris,fatima,fatimah,fatoumata," +
"faustino,fausto,favian,faviola,fawn,fay,faye,fayth,federico,felecia,felica,felice,felicia,feliciano," +
"felicity,felipe,felisa,felisha,felix,felton,fenix,fenton,ferdinand,fergus,fermin,fern,fernanda,fernando," +
"ferrell,ferris,ffion,fidel,fidencio,filiberto,filip,filomena,finlay,finley,finn,finneas,finnegan," +
"finnian,finnick,finnigan,finnley,fiona,fionn,fischer,fisher,fitzgerald,flavio,fletcher,flint,flor," +
"flora,florence,florencio,florentino,florian,florine,flossie,floyd,flynn,fonda,ford,forest,forrest," +
"foster,fox,foy,fran,francene,frances,francesca,francesco,franchesca,francheska,francie,francine,francis," +
"francisca,francisco,franco,francois,frank,frankie,franklin,franklyn,franky,fransisco,frantz,franz," +
"frazier,fred,freda,freddie,freddrick,freddy,frederic,frederica,frederick,frederico,fredia,fredric," +
"fredrick,fredy,freeman,freida,freya,freyja,frida,frieda,fritz,fulton,furman,fynn,gabe,gabino,gabrial," +
"gabriel,gabriela,gabriele,gabriella,gabrielle,gadiel,gael,gaetano,gage,gaia,gaige,gail,gaines,gala," +
"gale,galen,galilea,gamaliel,gannon,gardner,garen,garet,gareth,garett,garey,garfield,garin,garland," +
"garner,garnet,garnett,garold,garon,garren,garret,garrett,garrick,garrison,garry,garth,garvin,gary," +
"gaspar,gaston,gatlin,gauge,gavan,gaven,gavin,gavino,gavriel,gavyn,gay,gaye,gayla,gayle,gaylen,gaylene," +
"gaylon,gaylord,gaynell,gearld,gearldine,geary,gema,gemma,gena,genaro,gene,general,genesis,geneva," +
"genevieve,genie,genna,gennaro,geno,genoveva,gentry,geoff,geoffery,geoffrey,george,georgeann,georgene," +
"georgetta,georgette,georgia,georgiana,georgiann,georgianna,georgie,georgina,georgine,georgios,geovani," +
"geovanni,geovanny,geovany,gerald,geraldine,geraldo,geralyn,gerard,gerardo,geremy,gerhard,geri,germaine," +
"german,gerold,gerome,geronimo,gerri,gerrit,gerry,gerson,gertie,gertrude,gethin,gia,giacomo,giada," +
"gian,giana,giancarlo,gianfranco,gianluca,gianna,gianni,giannis,giavanna,gibran,gibson,gideon,gigi," +
"gil,gilbert,gilberto,gilda,gildardo,giles,gill,gillian,gina,ginger,ginny,gino,gio,gionni,giorgio," +
"giovani,giovanna,giovanni,giovanny,giovany,giovonni,girard,gisel,gisela,gisele,gisell,giselle,gissel," +
"gisselle,gitty,giulia,giuliana,giuliano,giuseppe,gizelle,gladis,gladys,glen,glenda,glendon,glenn," +
"glenna,glenwood,glinda,gloria,glory,glynda,glynis,glynn,godfrey,golda,golden,goldie,gonzalo,gorden," +
"gordon,gorge,grace,gracelyn,gracelynn,gracen,gracey,gracie,graciela,gracyn,grady,graeme,graham,graig," +
"granger,grant,granville,gray,grayce,grayden,graydon,graysen,grayson,grecia,greer,greg,gregg,greggory," +
"gregor,gregorio,gregory,greta,gretchen,gretta,grey,greysen,greyson,griffen,griffin,griffith,grisel," +
"griselda,grover,gruffudd,gryffin,guadalupe,guido,guillermina,guillermo,guinevere,gunnar,gunner,gunther," +
"gus,gussie,gustav,gustave,gustavo,guy,gwen,gwenda,gwendolyn,gwenyth,gwyn,gwyneth,habib,hadassah,haddie," +
"haden,hadi,hadlee,hadleigh,hadley,hafsa,hagan,hagen,haiden,haider,haidyn,hailee,haileigh,hailey,hailie," +
"haily,haisley,hakeem,hakim,hal,hala,halee,haleigh,halen,haley,hali,halie,halima,halle,halley,hallie," +
"halo,hamid,hamilton,hamish,hampton,hamza,hamzah,hana,hanah,hanan,hank,hanna,hannah,hans,hansel,hanson," +
"hardy,haris,harlan,harland,harlee,harleigh,harlem,harlen,harley,harlie,harlin,harlon,harlow,harlyn," +
"harmon,harmoni,harmonie,harmony,harold,haroon,harper,harrell,harriet,harriett,harriette,harris,harrison," +
"harry,hart,hartley,harun,harvey,hasan,hasani,hashim,haskell,hassan,hattie,haven,hawa,hawk,haydee," +
"hayden,haydn,haydon,hayes,haylee,hayleigh,hayley,hayli,haylie,hayward,haywood,haze,hazel,hazen,haziel," +
"heath,heather,heaven,heavenly,heber,hector,hedy,heide,heidi,heidy,helen,helena,helene,hellen,henderson," +
"hendrick,hendrik,hendrix,henley,henri,henrietta,henrik,henry,hensley,herb,herbert,herbie,hercules," +
"heriberto,herlinda,herman,hermelinda,herminia,herminio,hermione,hermon,hernan,herschel,hershel,hershell," +
"hershy,hester,heston,heyward,hezekiah,hiba,hilario,hilary,hilda,hillard,hillary,hillel,hilton,hindy," +
"hipolito,hiram,hobart,hobert,hogan,holden,holland,holley,holli,hollie,hollis,holly,hollyn,holt,holton," +
"homer,homero,honesty,honey,honor,hope,horace,horacio,horatio,hortencia,hosanna,hosea,houston,howard," +
"howell,hoyt,hubert,huck,huda,hudson,huey,hugh,hugo,humberto,humza,hung,hunter,huntley,hurley,hussain," +
"hussein,huston,huxley,huxton,huy,hyrum,iain,ian,ibn,ibraheem,ibrahim,ibrahima,ida,idalia,idella,idris," +
"iesha,ieshia,ignacio,ignatius,ikaika,ike,iker,ila,ilan,ilana,ileana,ilene,iliana,ilias,illiana,ilona," +
"ilse,ilya,ilyas,ima,iman,imani,imanol,imari,imelda,immanuel,imogen,imogene,imran,ina,inaaya,inara," +
"inaya,india,indiana,indie,indigo,indira,indy,indya,ines,inez,infant,inga,ingrid,ioannis,iola,iona," +
"ione,iqra,ira,iran,ireland,irelynn,irene,irie,irina,iris,irma,irvin,irving,irwin,isa,isaac,isaak," +
"isabel,isabela,isabell,isabella,isabelle,isac,isacc,isadora,isadore,isael,isai,isaiah,isaias,isaih," +
"isak,isamar,isela,isha,ishaan,ishan,ishmael,isiah,isidoro,isidro,isis,isla,ismael,ismail,isobel,isra," +
"israel,isreal,issa,issabella,issac,issiah,italia,italy,itzayana,itzel,iva,ivaan,ivan,ivana,ivanna," +
"ivar,ivelisse,iver,iverson,ivette,ivey,ivie,ivonne,ivory,ivy,iwan,iyana,iyanna,iyla,iyonna,izaac," +
"izaak,izabel,izabela,izabella,izabelle,izael,izaiah,izak,izan,izaya,izayah,iziah,izrael,izzabella," +
"jabari,jabez,jabriel,jabril,jacalyn,jacari,jace,jacee,jacelyn,jacen,jaceon,jacey,jaci,jacie,jaciel," +
"jacinda,jacinta,jacinto,jack,jackeline,jackelyn,jacki,jackie,jacklyn,jacklynn,jackson,jacky,jaclyn," +
"jaclynn,jacob,jacobe,jacobi,jacobo,jacoby,jacolby,jacorey,jacori,jacory,jacqualine,jacque,jacquelin," +
"jacqueline,jacquelyn,jacquelyne,jacquelynn,jacques,jacquez,jacquline,jacqulyn,jacy,jad,jada,jadah," +
"jadan,jadarius,jade,jadelyn,jaden,jadiel,jadin,jadon,jadyn,jae,jaeda,jaeden,jaedon,jaedyn,jael,jaela," +
"jaelen,jaelin,jaelyn,jaelynn,jafet,jagger,jahari,jahaziel,jaheem,jaheim,jahiem,jahir,jahleel,jahlil," +
"jahmal,jahmari,jahmir,jahsiah,jahzara,jahziel,jai,jaida,jaidan,jaide,jaiden,jaidon,jaidyn,jaila,jailen," +
"jailene,jailyn,jailynn,jaime,jaimee,jaimie,jaina,jair,jaire,jairo,jairus,jaison,jajuan,jakai,jakari," +
"jakayla,jake,jakeb,jakeem,jakhari,jakhi,jakob,jakobe,jakobi,jakoby,jakub,jala,jalaya,jalayah,jaleah," +
"jaleel,jaleesa,jalen,jalia,jalil,jalin,jalisa,jalissa,jaliyah,jalon,jalyn,jalynn,jalyssa,jamaal,jamaine," +
"jamal,jamall,jamar,jamarcus,jamari,jamarian,jamario,jamarion,jamarius,jamarr,jamauri,jamaya,jame," +
"jamee,jameel,jameer,jameka,jamel,jamell,jamere,james,jamesha,jameson,jamey,jami,jamia,jamiah,jamichael," +
"jamie,jamier,jamieson,jamil,jamila,jamilah,jamin,jamir,jamison,jamiya,jamiyah,jammie,jamon,jamya," +
"jan,jana,janae,janai,janay,janaya,jancarlos,jane,janea,janee,janeen,janel,janell,janella,janelle," +
"janelly,janely,janene,janessa,janet,janeth,janett,janetta,janette,janey,jani,jania,janiah,janice," +
"janie,janiece,janina,janine,janis,janise,janita,janiya,janiyah,jann,janna,jannah,jannet,jannette," +
"jannie,jansen,janson,january,janya,janyce,janyla,japheth,jaquan,jaquelin,jaqueline,jaquelyn,jaquez," +
"jarad,jared,jarek,jarel,jarell,jaren,jaret,jareth,jarett,jarid,jariel,jarin,jarius,jarod,jarom,jaron," +
"jarrad,jarred,jarrel,jarrell,jarren,jarret,jarrett,jarrid,jarrod,jarron,jarvis,jasai,jase,jasean," +
"jasen,jashaun,jashawn,jashon,jashua,jasiah,jasiel,jasir,jasleen,jaslene,jaslyn,jaslynn,jasmin,jasmine," +
"jasmyn,jasmyne,jason,jasper,jasson,jathan,jaunita,javan,javari,javaris,javaughn,javen,javeon,javian," +
"javien,javier,javin,javion,javon,javontae,javonte,jawad,jawan,jax,jaxen,jaxin,jaxon,jaxsen,jaxson," +
"jaxsyn,jaxton,jaxtyn,jaxx,jaxxon,jaxyn,jay,jaya,jayce,jaycee,jaycen,jayceon,jayci,jaycie,jaycob,jayda," +
"jaydan,jayde,jayden,jaydin,jaydon,jaydyn,jaye,jaykob,jayla,jaylah,jaylan,jaylani,jaylee,jayleen,jaylen," +
"jaylene,jaylin,jaylon,jaylyn,jaylynn,jayme,jaymee,jaymes,jaymie,jayna,jayne,jayon,jayquan,jayse,jaysen," +
"jayshawn,jayson,jaythan,jayton,jayven,jayveon,jayvian,jayvin,jayvion,jayvon,jazelle,jaziah,jaziel," +
"jazlyn,jazlynn,jazmin,jazmine,jazmyn,jazmyne,jazzlyn,jazzlynn,jazzmin,jazzmine,jc,jd,jean,jeana,jeancarlo," +
"jeancarlos,jeane,jeanelle,jeanene,jeanetta,jeanette,jeanie,jeanine,jeanluc,jeanmarie,jeanna,jeanne," +
"jeannette,jeannie,jeannine,jeanpaul,jeanpierre,jeb,jed,jedediah,jedidiah,jeff,jefferey,jefferson," +
"jeffery,jeffory,jeffrey,jeffrie,jeffry,jehu,jelani,jelena,jemma,jena,jenae,jencarlos,jenee,jenell," +
"jenelle,jenesis,jenessa,jenette,jenevieve,jeni,jenica,jenice,jenifer,jeniffer,jenine,jenise,jenna," +
"jennah,jennette,jenni,jennica,jennie,jennifer,jenniffer,jennings,jenny,jennyfer,jens,jensen,jenson," +
"jerad,jerald,jeraldine,jeramiah,jeramie,jeramy,jerard,jerardo,jere,jered,jerel,jerell,jereme,jeremey," +
"jeremi,jeremiah,jeremias,jeremie,jeremih,jeremy,jeremyah,jeri,jeriah,jerica,jericho,jeriel,jerilyn," +
"jerimiah,jermain,jermaine,jermel,jermey,jermiah,jerod,jerold,jerome,jeromy,jeron,jerone,jeronimo," +
"jerrad,jerred,jerrel,jerrell,jerrett,jerri,jerrica,jerrick,jerrid,jerrie,jerrod,jerrold,jerron,jerry," +
"jersey,jerson,jesenia,jeshua,jesiah,jesica,jess,jessa,jessalyn,jesse,jessee,jessenia,jessi,jessiah," +
"jessica,jessie,jessika,jesslyn,jessy,jestin,jesus,jet,jethro,jett,jetta,jettson,jevin,jevon,jewel," +
"jewell,jhene,jhett,jhon,jhonatan,jhonathan,jhonny,jia,jianna,jibreel,jibril,jihad,jill,jillian,jim," +
"jimena,jimi,jimmie,jimmy,jin,jina,jionni,jiovanni,jiraiya,jireh,jiselle,jiya,jo,joab,joachim,joah," +
"joan,joana,joanie,joann,joanna,joanne,joao,joaquin,job,jobe,joby,jocelin,jocelyn,jocelyne,jocelynn," +
"jock,jodee,jodi,jodie,jody,joe,joel,joell,joella,joelle,joellen,joely,joeseph,joesph,joetta,joette," +
"joey,johan,johana,johann,johanna,johannah,johannes,johathan,john,johna,johnathan,johnathen,johnathon," +
"johndavid,johnell,johnetta,johnette,johnie,johnmichael,johnna,johnnie,johnny,johnpaul,johnson,johny," +
"joi,joie,jolee,joleen,jolene,jolie,joline,jolyn,jolynn,jomar,jon,jona,jonah,jonas,jonatan,jonathan," +
"jonathen,jonathon,jonell,jonelle,jones,joni,jonmichael,jonna,jonnathan,jonnie,jonny,jonpaul,jonte," +
"jonthan,jordan,jordana,jorden,jordi,jordin,jordon,jordy,jordyn,jordynn,jorel,jorge,jori,jorja,jorje," +
"jory,josalyn,joscelyn,jose,joseangel,josef,josefa,josefina,joselin,joseline,joseluis,joselyn,josemanuel," +
"joseph,josephina,josephine,josette,josey,josh,joshua,joshuah,joshue,josiah,josias,josie,joslyn,joslynn," +
"jospeh,josselyn,josslyn,josue,jourdan,journee,journei,journey,journi,journie,jovan,jovana,jovani," +
"jovanna,jovanni,jovanny,jovany,jovi,jovie,jovita,jovon,joy,joya,joyce,joycelyn,joye,jozef,joziah," +
"jr,jream,jrue,juan,juana,juancarlos,juanita,juanito,juanjose,juanpablo,juaquin,jubilee,judah,judd," +
"jude,judge,judi,judie,judith,judson,judy,juelz,julee,julene,jules,juli,julia,julian,juliana,juliane," +
"juliann,julianna,julianne,juliano,julie,julieann,julieanne,julien,julienne,juliet,julieta,julietta," +
"juliette,julio,julious,julisa,julissa,julius,jullian,jun,june,junior,juniper,junius,jurnee,justen," +
"justice,justin,justina,justine,justino,justis,justo,juston,justus,justyce,justyn,juvenal,juventino," +
"juwan,kabir,kace,kacee,kacen,kacey,kaci,kacie,kacper,kacy,kadarius,kade,kadeem,kaden,kadence,kadie," +
"kadin,kady,kadyn,kaeden,kaedyn,kael,kaela,kaelan,kaeli,kaelin,kaelyn,kaelynn,kaeson,kage,kahlani," +
"kahlil,kai,kaia,kaidan,kaiden,kaidence,kaidyn,kaila,kailah,kailani,kailee,kaileigh,kailen,kailey," +
"kaili,kaily,kailyn,kailynn,kaimana,kain,kaine,kainen,kainoa,kaira,kairi,kairo,kaisen,kaiser,kaisley," +
"kaison,kaitlin,kaitlyn,kaitlynn,kaito,kaius,kaiya,kaizen,kaizer,kal,kala,kalan,kalani,kale,kalea," +
"kaleah,kaleb,kalee,kaleena,kalei,kaleigh,kalel,kalem,kalen,kalena,kaleo,kaley,kali,kalia,kaliah,kalib," +
"kalie,kalil,kalin,kalina,kalista,kaliyah,kallen,kalli,kallie,kalman,kalob,kalon,kalvin,kalyn,kalynn," +
"kam,kamal,kamar,kamara,kamari,kamaria,kamarion,kamau,kamaya,kambree,kambria,kamden,kamdyn,kameron," +
"kameryn,kami,kamia,kamiah,kamil,kamila,kamilah,kamilla,kamille,kamiya,kamiyah,kamora,kamran,kamren," +
"kamrin,kamron,kamryn,kamya,kanaan,kanan,kandace,kandi,kandice,kandis,kandy,kane,kanesha,kanisha,kaniya," +
"kaniyah,kannon,kanon,kanye,kanyon,kara,karah,karalyn,karam,karan,kareem,karely,karen,karena,karey," +
"kari,karie,karim,karime,karin,karina,karis,karisa,karisma,karissa,karl,karla,karlee,karleen,karleigh," +
"karlene,karley,karli,karlie,karlo,karlos,karlton,karly,karlyn,karma,karmelo,karmen,karmyn,karol,karolina," +
"karoline,karolyn,karon,karren,karri,karrie,karsen,karson,karsten,karsyn,karter,karthik,kartier,kary," +
"karyl,karyme,karyn,kasandra,kase,kasen,kasey,kash,kashawn,kashif,kashmir,kashton,kasi,kasia,kasie," +
"kason,kasper,kassandra,kassi,kassidy,kassie,kassius,kasyn,kataleya,katalina,katana,katarina,kate," +
"katelin,katelyn,katelynn,kateri,katerina,katey,kathaleen,katharina,katharine,katherin,katherine,kathern," +
"katheryn,katheryne,kathey,kathi,kathie,kathleen,kathlene,kathlyn,kathrine,kathryn,kathryne,kathy," +
"kathyrn,kati,katia,katie,katilyn,katina,katlin,katlyn,katlynn,katrice,katrina,kattie,katy,katya,kaven," +
"kavin,kavion,kavon,kavya,kawika,kay,kaya,kayce,kaycee,kaycen,kayci,kaycie,kaydance,kaydee,kayden," +
"kaydence,kaydin,kaydon,kaye,kayla,kaylah,kaylan,kaylani,kayle,kaylea,kayleb,kaylee,kayleen,kaylei," +
"kayleigh,kaylen,kaylene,kayley,kayli,kaylie,kaylin,kaylon,kaylyn,kaylynn,kayne,kaysen,kayson,kaytlin," +
"kaytlyn,kayvon,kc,keagan,keagen,keaira,kean,keana,keandre,keane,keanna,keanu,keara,keasia,keaton," +
"kecia,kedric,kedrick,keegan,keelan,keeley,keely,keena,keenan,keenen,keesha,keeton,kegan,kehlani,keifer," +
"keigan,keila,keilan,keilani,keily,keion,keir,keira,keiran,keiry,keisha,keith,kejuan,kekoa,kelan,kelby," +
"kelcey,kelci,kelcie,keli,kelis,kellan,kelle,kellee,kellen,keller,kelley,kelli,kellie,kellin,kelly," +
"kellyann,kellye,kellyn,kelsea,kelsee,kelsey,kelsi,kelsie,kelson,kelsy,kelton,kelvin,kemari,kemarion," +
"kemp,kemper,ken,kena,kenadee,kenadie,kenai,kenan,kenda,kendal,kendale,kendall,kendarius,kendell,kendon," +
"kendra,kendric,kendrick,kendrix,kendyl,keneth,kenia,kenisha,kenith,kenji,kenlee,kenleigh,kenley,kenna," +
"kennadi,kennady,kennan,kennard,kennedi,kennedy,kenneth,kenney,kennie,kennith,kennon,kennth,kenny," +
"kenric,kenrick,kensington,kensley,kent,kenton,kentrell,kenya,kenyan,kenyatta,kenyetta,kenyon,kenzi," +
"kenzie,kenzley,kenzo,keon,keona,keondre,keoni,keonna,keontae,keonte,keosha,kera,keren,keri,kermit," +
"keron,kerri,kerrie,kerrigan,kerry,kerstin,kervin,kerwin,kesean,kesha,keshaun,keshav,keshawn,keshia," +
"keshon,keturah,kevan,keven,kevin,kevion,kevon,kevyn,keya,keyan,keyana,keyanna,keyara,keyla,keylan," +
"keyon,keyona,keyonna,keysha,keyshawn,kezia,keziah,khadija,khadijah,khai,khalani,khaleb,khaled,khaleel," +
"khaleesi,khalia,khalid,khalif,khalil,khalilah,khamari,khang,khari,khary,khaza,khiry,khloe,khristian," +
"khristopher,khyree,kia,kiaan,kiah,kian,kiana,kianna,kiara,kiarra,kiefer,kiel,kiera,kieran,kiernan," +
"kierra,kiersten,kierstin,kierstyn,kiesha,kieth,kile,kilee,kiley,kilian,killian,kim,kimani,kimball," +
"kimber,kimberely,kimberlee,kimberley,kimberli,kimberlie,kimberly,kimberlyn,kimi,kimora,kindra,king," +
"kingsley,kingston,kinlee,kinleigh,kinley,kinsey,kinslee,kinsleigh,kinsley,kinzie,kinzley,kion,kiona," +
"kip,kipp,kipton,kira,kiran,kirby,kirk,kirkland,kirra,kirsten,kirstie,kirstin,kirstyn,kirt,kisha,kishan," +
"kit,kitana,kitty,kiya,kiyah,kiyan,kiyomi,kizzy,klaire,klara,klarissa,klaus,klay,klayton,kloe,kloey," +
"knowledge,knox,koa,koah,kobe,kobi,kobie,koby,koda,kodi,kodie,kody,koen,kofi,kohen,kohl,kolbe,kolby," +
"kole,kolin,kollin,kolson,kolt,kolten,kolter,kolton,koltyn,kong,konner,konnor,konrad,konstantinos," +
"kooper,kora,korben,korbin,korbyn,kordell,korey,kori,korie,korina,korra,kortney,kory,kota,kourtney," +
"koy,kraig,kreed,kreg,krew,kris,krish,krisha,krishiv,krishna,krissy,krista,kristal,kristan,kristel," +
"kristen,kristi,kristian,kristiana,kristie,kristin,kristina,kristine,kristofer,kristoffer,kristopher," +
"kristy,kristyn,kross,krue,kruz,krysta,krystal,krysten,krystian,krystin,krystina,krystle,krystyna," +
"kunal,kurt,kurtis,kush,kwame,ky,kya,kyah,kyaire,kyan,kyana,kyanna,kyara,kyden,kye,kyla,kylah,kylan," +
"kylar,kyle,kylee,kyleigh,kylen,kylene,kyler,kyley,kyli,kylian,kylie,kylin,kylo,kylon,kymani,kymberly," +
"kyndal,kyndall,kyndra,kyng,kyngston,kynlee,kynleigh,kynslee,kyra,kyrah,kyran,kyree,kyren,kyrie,kyrin," +
"kyro,kyron,kyrsten,kysen,kyson,kyzer,lacee,lacey,lachelle,lachlan,laci,lacie,lacy,ladarius,ladarrius," +
"ladd,ladell,ladon,ladonna,lael,laela,lafayette,laiken,laikyn,laila,lailah,lailani,laina,laine,lainey," +
"lainie,laird,laisha,laith,lajuan,lajuana,lake,lakeisha,lakelyn,lakelynn,laken,lakendra,lakenya,lakesha," +
"lakeshia,lakia,lakiesha,lakin,lakisha,lakita,lakota,lakyn,lamar,lamarcus,lamarion,lamarr,lambert," +
"lamon,lamonica,lamont,lamonte,lamya,lana,lanae,lance,landan,landen,lander,landin,landis,landon,landry," +
"landyn,lane,lanell,lanette,laney,langdon,langston,lani,lanie,lanita,laniya,laniyah,lanna,lannie,lanny," +
"lanora,laquan,laquisha,laquita,lara,larae,laraine,laramie,larenzo,larhonda,larisa,larissa,lark,larkin," +
"laron,laronda,laroy,larry,lars,larson,larue,lary,lashae,lashanda,lashawn,lashawna,lashawnda,lashay," +
"lashonda,lashunda,lasonya,laszlo,latanya,latarsha,latasha,latashia,latavia,latesha,lathan,latia,laticia," +
"latina,latisha,latonia,latonya,latoria,latosha,latoya,latrell,latrice,latricia,latrina,latrisha,launa," +
"laura,lauralee,laurance,laure,laureen,laurel,lauren,laurence,laurene,laurent,lauretta,laurette,lauri," +
"laurie,laurin,lauro,lauryn,lavada,lavar,lavell,lavelle,lavender,lavern,laverne,lavina,lavinia,lavon," +
"lavonda,lavonna,lavonne,lavonte,lawana,lawanda,lawanna,lawerence,lawrance,lawrence,lawson,lawton," +
"laya,layan,layden,layla,laylah,laylani,layna,layne,laynee,laynie,layton,lazaro,lazarus,lea,leah,leamon," +
"leana,leander,leandra,leandre,leandro,leann,leanna,leanne,leatha,leatrice,lebron,leda,ledger,lee," +
"leeann,leeanna,leeanne,leela,leeland,leen,leena,leeroy,leesa,legacy,legend,leia,leif,leigh,leigha," +
"leighann,leighton,leila,leilah,leilani,leilany,leisa,leisha,lela,leland,lelia,lemar,lemuel,len,lena," +
"lenard,leni,lenin,lenna,lennard,lennie,lennon,lennox,lenny,lenora,lenore,lenox,lenwood,leo,leobardo," +
"leola,leon,leona,leonard,leonardo,leonel,leonidas,leonor,leonora,leopold,leopoldo,leora,leota,leron," +
"leroy,les,lesa,lesia,leslee,lesley,lesli,leslie,lesly,leslye,lessie,lester,leta,letha,leticia,letisha," +
"letitia,lettie,letty,lev,levar,levern,levi,levin,leviticus,levon,levy,lew,lewis,lex,lexi,lexie,lexington," +
"lexis,lexus,lexy,leya,leyla,leylani,leyna,leyton,lezlie,lia,liah,liam,lian,liana,liane,lianna,lianne," +
"libby,liberty,librado,lida,lidia,liesl,lila,lilah,lili,lilia,lilian,liliana,lilianna,lilibeth,lilith," +
"lilla,lilli,lillia,lillian,lilliana,lillianna,lillie,lillith,lilly,lillyan,lillyana,lillyann,lillyanna," +
"lily,lilyan,lilyana,lilyann,lilyanna,lilyanne,lina,lincoln,linda,lindell,linden,lindon,lindsay,lindsey," +
"lindsy,lindy,linette,link,linkin,linley,linn,linnea,linnie,lino,linsey,linton,linus,linwood,lionel," +
"lionell,lipa,lisa,lisamarie,lisandra,lisandro,lisbeth,lise,lisette,lisha,lissa,lissette,lita,little," +
"litzy,liv,livia,liya,liyah,liz,liza,lizabeth,lizandro,lizbeth,lizet,lizeth,lizette,lizzette,lizzie," +
"llewellyn,lloyd,lluvia,lochlan,locke,logan,logen,lois,loki,lola,lolita,lon,lona,londa,london,londyn," +
"londynn,long,loni,lonna,lonnell,lonnie,lonny,lonzo,lora,loraine,loralee,loralei,loran,lorcan,loreal," +
"loree,loreen,lorelai,lorelei,loren,lorena,lorene,lorenz,lorenza,lorenzo,loretta,lori,loriann,lorianne," +
"lorie,lorin,lorinda,lorine,lorna,lorne,lorraine,lorretta,lorri,lorrie,lory,loryn,lottie,lotus,lou," +
"louann,louanne,louella,louie,louis,louisa,louise,lourdes,louvenia,love,lovell,lovely,lovie,lowell," +
"loy,loyal,loyalty,loyce,loyd,lu,luan,luana,luann,luanna,luanne,luc,luca,lucas,lucca,lucero,luci,lucia," +
"lucian,luciana,lucianna,luciano,lucie,lucien,lucila,lucile,lucille,lucinda,lucio,lucious,lucius,lucky," +
"lucretia,lucus,lucy,ludwig,lue,luella,luigi,luis,luisa,luisangel,luiz,luka,lukas,luke,lukus,lula," +
"lulu,luna,lupe,lupita,luqman,lura,luther,lux,luz,lyam,lyanna,lydell,lydia,lyla,lylah,lyle,lyman,lyn," +
"lynda,lyndell,lynden,lyndi,lyndon,lyndsay,lyndsey,lynell,lynelle,lynette,lynlee,lynn,lynna,lynne," +
"lynnea,lynnette,lynsey,lynwood,lyon,lyra,lyric,mabel,mable,mac,macario,macarthur,macayla,mace,macee," +
"macen,maceo,macey,machelle,maci,macie,mack,mackenna,mackenzi,mackenzie,macklin,macon,macy,madaline," +
"madalyn,madalynn,madden,maddex,maddie,maddison,maddix,maddox,maddux,madelaine,madeleine,madelene," +
"madelin,madeline,madelyn,madelyne,madelynn,madelynne,madge,madilyn,madilynn,madisen,madison,madisson," +
"madisyn,madonna,madysen,madyson,mae,maegan,mael,maelyn,maelynn,maeve,magali,magaly,magan,magda,magdalena," +
"magdalene,magen,maggie,magnolia,magnus,maha,mahala,mahalia,mahdi,maher,mahir,mahki,mahlon,mahmoud," +
"mahogany,mai,maia,maida,maile,maira,maisha,maisie,maison,maisy,maisyn,maite,maiya,maizie,maja,majesty," +
"major,makaela,makai,makaila,makaio,makala,makari,makayla,makaylah,makeda,makena,makenna,makenzi,makenzie," +
"makhai,makhi,makiah,makinley,makiya,makiyah,makoa,maksim,makyla,malachai,malachi,malaika,malak,malakai," +
"malakhi,malaki,malani,malaya,malayah,malaysia,malcolm,malcom,male,malea,maleah,maleek,malek,malena," +
"malia,maliah,maliek,malik,malika,malikai,maliki,malina,malinda,malique,malisa,malissa,maliya,maliyah," +
"malka,malky,mallorie,mallory,malorie,malvin,mamadou,mamie,manda,mandi,mandie,mandy,manfred,manley," +
"manning,manny,manolo,manuel,manuela,maple,mara,marah,maranda,marbella,marc,marcanthony,marcel,marcela," +
"marcelina,marceline,marcelino,marcell,marcella,marcelle,marcello,marcellous,marcellus,marcelo,marchelle," +
"marci,marcia,marcial,marciano,marcie,marco,marcoantonio,marcos,marcus,marcy,marek,marely,maren,margaret," +
"margarett,margarette,margarita,margarito,margaux,marge,margery,margie,margo,margot,margret,marguerite," +
"mari,maria,mariaelena,mariah,mariajose,mariam,mariama,marian,mariana,mariann,marianna,marianne,mariano," +
"maribel,maribeth,maricela,maricella,maricruz,marie,mariel,mariela,mariella,marielle,marietta,marigold," +
"marika,marilee,marilou,marilu,marilyn,marilynn,marin,marina,marino,mario,marion,maris,marisa,marisela," +
"marisol,marissa,marita,maritza,marius,marivel,mariya,mariyah,marjorie,marjory,mark,markanthony,markayla," +
"markeith,markel,markell,markese,markia,markis,markita,marko,markos,markus,marla,marlan,marlana,marlee," +
"marleen,marleigh,marlen,marlena,marlene,marley,marli,marlie,marlin,marlo,marlon,marlow,marlowe,marly," +
"marlyn,marlys,marna,marni,marnie,marquan,marque,marquel,marquell,marques,marquese,marquetta,marquette," +
"marquez,marquis,marquise,marquita,marqus,mars,marsha,marshal,marshall,marshaun,marshawn,marta,martavious," +
"martel,martell,martez,martha,marti,martin,martina,martine,martinez,marty,marva,marvel,marvell,marvin," +
"marvis,marwa,marwan,mary,marya,maryah,maryalice,maryam,maryann,maryanna,maryanne,marybeth,maryelizabeth," +
"maryellen,marygrace,maryjane,maryjo,marykate,marylee,marylin,marylou,marylyn,marylynn,maryn,maryrose," +
"maryssa,masen,masiah,mason,massiah,massimo,masyn,mateo,mateus,mateusz,matheo,matheus,mathew,mathias," +
"mathieu,mathis,matias,matilda,matilde,matt,mattea,matteo,mattew,matthew,matthews,matthias,matthieu," +
"mattias,mattie,mattison,maude,maudie,maura,maureen,maurice,mauricio,maurine,mauro,maury,maverick," +
"maverik,mavis,mavrick,max,maxie,maxim,maxime,maximilian,maximiliano,maximillian,maximino,maximo,maximus," +
"maxine,maxon,maxson,maxton,maxwell,maxx,may,maya,mayah,maycee,mayer,maylee,maylin,maynard,maynor," +
"mayra,mayson,mayte,mazen,mazi,mazie,mcarthur,mccoy,mckay,mckayla,mckenna,mckenzi,mckenzie,mckinley," +
"mea,meadow,meagan,meaghan,meah,mecca,mechelle,medina,meera,meg,megan,meggan,meghan,meghann,mehdi," +
"mehki,mei,meilani,meir,mekayla,mekhi,mel,melaine,melani,melania,melanie,melannie,melany,melba,melia," +
"melina,melinda,melisa,melissa,melissia,melita,mellisa,mellissa,melodee,melodi,melodie,melody,melonie," +
"melony,melton,melva,melvin,melvina,melvyn,melynda,melyssa,memphis,menachem,mendel,mendy,menno,meranda," +
"mercedes,mercedez,mercer,mercy,meredith,meri,merideth,meridith,merilyn,merissa,merl,merle,merlene," +
"merlin,merlyn,merri,merrick,merrie,merrilee,merrill,merritt,merry,merton,mervin,meryl,messiah,meta," +
"meyer,mia,miabella,miah,mica,micaela,micah,micahel,micaiah,micayla,micha,michael,michaela,michaelangelo," +
"michaele,michaella,michal,michale,micheal,michel,michela,michelangelo,michele,michell,michelle,michial," +
"michiel,mick,mickael,mickayla,mickeal,mickel,mickey,micki,mickie,micky,miesha,migdalia,migel,miguel," +
"miguelangel,mihir,mika,mikael,mikaela,mikah,mikail,mikaila,mikal,mikala,mikayla,mike,mikeal,mikel," +
"mikell,mikey,mikhael,mikhail,miki,mikki,miko,mila,milagro,milagros,milah,milan,milana,milani,milania," +
"mildred,mileena,milena,miles,miley,milford,milissa,milla,millard,miller,millicent,millie,milly,milo," +
"milton,mimi,mina,mindi,mindy,minerva,minh,minnie,miquel,mira,miracle,miranda,mirella,mireya,miriah," +
"miriam,mirian,mirna,misael,mischa,misha,missy,misti,mistie,misty,mitch,mitchel,mitchell,mitzi,miya," +
"miyah,modesto,mohamad,mohamed,mohammad,mohammed,moira,moises,moishe,molli,mollie,molly,mona,monae," +
"monet,monica,monika,monique,monroe,monserrat,montana,montavious,monte,montel,montez,montgomery,montie," +
"montreal,montrel,montrell,montserrat,monty,morag,mordecai,mordechai,morgan,morgen,moriah,morris,morrison," +
"morton,mose,moses,moshe,moussa,muhammad,muhammed,murad,muriel,murphy,murray,murry,musa,mustafa,mya," +
"myah,myasia,mychael,mychal,myesha,myia,myka,mykah,mykal,mykayla,mykel,myla,mylah,mylan,mylee,myles," +
"mylie,mylo,myra,myranda,myriah,myriam,myrna,myron,myrtis,myrtle,nabeel,nabil,nada,nader,nadia,nadine," +
"nadir,nadya,naeem,nael,naftali,nahla,nahom,nahomi,nahum,naia,naila,nailah,naim,naima,naimah,naisha," +
"naiya,najah,najee,nakayla,nakia,nakisha,nakita,nakiya,nakoa,nala,nalani,nallely,nam,nan,nana,nanci," +
"nancie,nancy,nanette,nannette,nannie,naomi,naomie,naomy,napoleon,naquan,narciso,nariah,nariyah,naseem," +
"nash,nashawn,nasir,nasser,nassir,natalee,natali,natalia,natalie,nataly,natalya,natan,natanael,natasha," +
"natashia,nate,nathalia,nathalie,nathaly,nathan,nathanael,nathaneal,nathanial,nathaniel,nathen,nathon," +
"natisha,natividad,natosha,nautica,navaeh,naveah,naveen,navy,navya,naya,nayeli,nayely,nayla,nazareth," +
"nazario,nazir,neal,nechama,ned,neda,nedra,neel,neely,neena,neftali,neha,nehemiah,nehemias,neida,neil," +
"neill,neko,nelda,nell,nella,nellie,nelly,nels,nelson,nena,neo,nereida,neriah,nerissa,nery,nestor," +
"nettie,neva,nevada,nevaeh,nevan,neveah,neville,nevin,newell,newton,neymar,nia,niah,niall,niam,niamh," +
"nicco,niccolo,nichelle,nichol,nicholai,nicholas,nicholaus,nichole,nicholle,nick,nickey,nicki,nickie," +
"nicklas,nicklaus,nickolas,nickolaus,nickole,nicky,nico,nicodemus,nicol,nicola,nicolai,nicolas,nicolaus," +
"nicole,nicolette,nicolle,nicolo,nidia,niel,niels,niesha,nigel,nika,nikhil,niki,nikia,nikita,nikki," +
"nikko,niklas,niklaus,niko,nikola,nikolai,nikolaos,nikolas,nikolaus,nikole,nila,nilda,nile,niles,nils," +
"nilsa,nima,nina,ninfa,nino,nisa,nisha,nita,nixon,niya,niyah,noa,noah,noam,noble,noe,noel,noelani," +
"noelia,noella,noelle,noemi,noemy,nohemi,nola,nolan,noland,nolen,nona,noor,nora,norah,norbert,norberto," +
"noreen,norene,nori,norine,norma,norman,normand,norris,norwood,nour,nova,novah,novalee,novella,nuala," +
"nubia,nya,nyah,nyasia,nydia,nyla,nylah,nyle,nyomi,nyra,nyree,nyssa,oakland,oaklee,oakleigh,oakley," +
"oaklyn,oaklynn,obadiah,obed,obie,ocean,ocie,octavia,octavian,octavio,octavious,octavius,odalis,odalys," +
"odelia,odell,oden,odessa,odette,odie,odin,odis,ofelia,oisin,ola,olaf,olan,ole,olen,olga,olin,olive," +
"oliver,olivia,olivier,ollie,olympia,olyvia,om,oma,omar,omari,omarion,omer,ona,oneal,oneil,onyx,oona," +
"opal,ophelia,ora,oral,oralia,oran,oren,ori,oriana,orin,orion,orla,orlando,orlin,orrin,orson,orval," +
"orville,oryan,osama,osbaldo,oscar,oshea,osiel,osiris,oskar,osman,osmar,osvaldo,oswald,oswaldo,otha," +
"otis,otoniel,ottis,otto,ouida,ovidio,owen,ozell,ozias,oziel,ozzie,ozzy,pablo,paden,padraic,padraig," +
"page,paige,paislee,paisleigh,paisley,paityn,palmer,paloma,pam,pamala,pamela,pamelia,pamella,panagiotis," +
"pandora,pansy,paola,paolo,paris,park,parker,parks,parnell,parris,parrish,parth,pascal,pascual,pasquale," +
"passion,pat,patience,patric,patrica,patrice,patricia,patricio,patrick,patrina,patryk,patsy,patti," +
"pattie,patton,patty,paul,paula,pauletta,paulette,paulina,pauline,paulino,paulo,pavel,pax,paxton,payden," +
"payne,payson,payten,payton,pearce,pearl,pearlie,pearline,pearson,pedro,peggie,peggy,peighton,penelope," +
"penn,penney,penni,pennie,penny,pepper,percival,percy,peri,perla,pernell,perri,perrin,perry,persephone," +
"perseus,pete,peter,petra,petrina,peyton,phaedra,pharaoh,phebe,phil,philip,philipp,philippa,philippe," +
"phillip,phillips,phillis,philomena,phineas,phoebe,phoenix,phong,phylicia,phylis,phyliss,phyllis,pia," +
"pierce,pierre,pierson,pieter,pietro,pilar,pinchas,piper,pippa,polly,pooja,poppy,porfirio,porsche," +
"porsha,porter,portia,powell,pranav,precious,prentice,prentis,prentiss,prescott,preslee,presleigh," +
"presley,preslie,preston,price,pricilla,prince,princess,princeton,priscila,priscilla,prisha,priya," +
"priyanka,promise,prudence,pryce,pyper,qasim,qiana,quade,quadir,quan,queen,queenie,quentin,quenton," +
"quest,quiana,quin,quincey,quincy,quinlan,quinn,quinten,quintin,quinton,quran,race,rachael,racheal," +
"rachel,rachele,rachell,rachelle,racquel,radley,rae,raeann,raeanna,raeanne,raechel,raegan,raekwon," +
"raelee,raeleigh,raelene,raelyn,raelynn,raena,rafael,rafaela,rafe,rafeal,raffaele,ragan,raghav,raheem," +
"rahim,rahman,rahsaan,rahul,raiden,rain,raina,raine,rainer,rainey,raizel,raizy,raj,rajan,rakeem,rakim," +
"raleigh,ralph,ram,ramel,rami,ramir,ramiro,ramon,ramona,ramond,ramone,ramses,ramsey,ramy,rana,ranae," +
"rance,rand,randa,randal,randall,randee,randel,randell,randi,randle,randolf,randolph,randon,randy," +
"ranger,rani,rania,raniyah,ransom,raoul,raphael,rapheal,raquan,raquel,rashaad,rashaan,rashad,rashan," +
"rashard,rashaud,rashaun,rashawn,rasheed,rasheeda,rasheem,rasheen,rashid,rashida,rashod,rashon,raudel," +
"raul,raven,ravi,ravon,ravyn,ray,raya,rayaan,rayan,rayann,rayanna,rayburn,rayce,rayden,raye,rayfield," +
"rayford,raylan,raylee,rayleigh,raylen,raylene,raylon,raylynn,raymon,raymond,raymundo,rayna,raynaldo," +
"raynard,rayne,rayquan,rayshaun,rayshawn,rayven,rayvon,rayyan,raziel,reagan,reanna,reba,rebbecca,rebeca," +
"rebecca,rebecka,rebeka,rebekah,rebekka,rebel,reco,reece,reed,reef,reem,reema,reena,rees,reese,refugio," +
"regan,regena,regenia,reggie,regina,reginal,reginald,regis,rehan,reid,reign,reilly,reina,reinaldo," +
"remi,remington,remy,ren,rena,renae,renaldo,renard,renata,renato,renay,rene,renea,renee,renesmee,renita," +
"reno,renzo,reta,retha,reuben,reuven,reva,revan,rex,rexford,rey,reya,reyansh,reyes,reymundo,reyna," +
"reynaldo,reynold,reynolds,reza,rhea,rheanna,rhett,rhianna,rhiannon,rhoda,rhodes,rhonda,rhyan,rhyder," +
"rhylee,rhys,ria,riaan,rian,riana,rianna,ric,ricardo,riccardo,ricco,rich,richard,richardo,richelle," +
"richie,richmond,rick,rickey,ricki,rickie,ricky,rico,rider,ridge,ridley,riggs,rigo,rigoberto,rihanna," +
"riker,rikki,rilee,rileigh,riley,rilynn,rima,rina,rio,rion,riot,ripley,risa,rishaan,rishabh,rishi," +
"rita,ritchie,rito,river,rivers,rivka,rivky,riya,riyan,roan,rob,robb,robbie,robbin,robby,robert,roberta," +
"roberto,robie,robin,robinson,roby,robyn,rocco,rochel,rochell,rochelle,rocio,rock,rockey,rockie,rockwell," +
"rocky,rod,roddy,roderic,roderick,rodger,rodney,rodolfo,rodrick,rodrigo,rodriguez,rodriquez,roel,roen," +
"rogan,rogelio,roger,rogers,rohan,rohit,roisin,rojelio,roland,rolanda,rolando,rolf,rolland,rollie," +
"rollin,roma,roman,romario,rome,romel,romell,romello,romelo,romeo,romero,romie,romina,rommel,romona," +
"romy,ron,rona,ronak,ronal,ronald,ronaldo,ronan,ronda,rondal,rondell,ronell,ronen,roni,ronin,ronna," +
"ronnell,ronney,ronni,ronnie,ronny,rony,roosevelt,roque,rori,rory,rosa,rosalba,rosalee,rosalia,rosalie," +
"rosalina,rosalind,rosalinda,rosaline,rosalio,rosalva,rosalyn,rosalynn,rosamaria,rosana,rosann,rosanna," +
"rosanne,rosario,rosaura,roscoe,rose,roseann,roseanna,roseanne,rosella,roselyn,roselynn,rosemarie," +
"rosemary,rosendo,rosetta,rosevelt,roshan,roshawn,rosie,rosina,rosio,rosita,roslyn,ross,rosy,rowan," +
"rowdy,rowen,rowena,rowland,rowyn,roxana,roxane,roxann,roxanna,roxanne,roxie,roxy,roy,royal,royalty," +
"royce,ruairi,ruben,rubi,rubie,rubin,ruby,rubye,rudolf,rudolfo,rudolph,rudra,rudy,rueben,ruel,rufino," +
"rufus,ruger,rupert,rush,russ,russel,russell,rustin,ruston,rusty,ruth,ruthann,ruthanne,ruthie,rya," +
"ryan,ryann,ryanne,ryatt,ryden,ryder,rye,ryen,ryker,rylan,ryland,rylee,ryleigh,rylen,ryley,rylie,rylin," +
"rylynn,ryne,ryon,ryu,saad,saanvi,sabastian,sabian,sabina,sabine,sabino,sable,sabra,sabrena,sabrina," +
"sacha,sachin,sade,sadie,saeed,safa,safiya,sagar,sage,sahana,sahar,sahara,sahasra,sahil,sai,said,saif," +
"saige,sailor,saint,saira,sakura,sal,salah,saleem,saleh,salem,salena,salim,salina,sallie,sally,salma," +
"salman,salome,salomon,salvador,salvatore,sam,sama,samanta,samantha,samar,samara,samarah,samaria,samarth," +
"samatha,samaya,sameer,samer,sami,samia,samir,samira,samirah,samiya,samiyah,sammantha,sammi,sammie," +
"sammuel,sammy,samone,sampson,samson,samual,samuel,samya,san,sana,sanaa,sanai,sanaya,sanchez,sandee," +
"sander,sanders,sandi,sandie,sandra,sandro,sandy,sanford,sania,saniya,saniyah,sanjana,sanjay,sanjuana," +
"sanjuanita,santa,santana,santiago,santina,santino,santo,santonio,santos,sanya,saoirse,saphira,sapphire," +
"sara,sarah,sarahi,sarai,saray,saraya,sarena,sari,sariah,sarina,sarita,sariya,sariyah,sasha,saul,saundra," +
"savana,savanah,savanna,savannah,saverio,savion,savon,sawyer,saxon,saylor,scarlet,scarlett,scarlette," +
"schuyler,scot,scott,scottie,scotty,scout,seamus,sean,seana,seanna,sebastian,sebastien,sebrina,sedona," +
"sedric,sedrick,seferino,sekani,sekou,selah,selena,selene,selim,selina,selma,selvin,selwyn,semaj,sena," +
"seneca,september,sequoia,sera,serafin,serafina,seraphina,seren,serena,serene,serenity,serge,sergio," +
"serina,serjio,servando,seth,seven,severo,sevyn,seymour,shaan,shad,shade,shae,shaelyn,shaelynn,shaheed," +
"shai,shaila,shain,shaina,shaindy,shaine,shakayla,shakia,shakir,shakira,shakur,shala,shalanda,shalom," +
"shalonda,shalyn,shamar,shamara,shameka,shamel,shamika,shamir,shamus,shamya,shan,shana,shanae,shanaya," +
"shanda,shandi,shandra,shane,shaneka,shanel,shanell,shanelle,shanequa,shani,shania,shaniah,shanice," +
"shaniece,shanika,shaniqua,shanique,shanita,shaniya,shaniyah,shanna,shannan,shannen,shannon,shanon," +
"shanta,shantal,shante,shantel,shantell,shantelle,shanti,shanya,shaquan,shaquana,shaquille,shaquita," +
"shara,sharee,shareef,sharen,shari,sharie,sharif,sharilyn,sharita,sharla,sharleen,sharlene,sharmaine," +
"sharod,sharon,sharonda,sharron,sharyl,sharyn,shasta,shaun,shauna,shaunda,shaunna,shaunte,shaurya," +
"shavon,shavonne,shaw,shawana,shawanda,shawn,shawna,shawnda,shawnee,shawnna,shawnta,shay,shaya,shayan," +
"shayden,shaye,shayla,shaylee,shaylin,shaylyn,shaylynn,shayna,shayne,shea,shedrick,sheena,sheila,sheilah," +
"shekinah,shelba,shelbi,shelbie,shelby,sheldon,shelia,shelley,shelli,shellie,shelly,shelton,shemar," +
"shena,shenika,shepard,shepherd,sheree,sheri,sheridan,sherie,sherika,sherilyn,sherita,sherlyn,sherman," +
"sheron,sherrell,sherri,sherrie,sherril,sherrill,sherrod,sherron,sherry,sherryl,sherwin,sherwood,sheryl," +
"sheyla,shia,shiann,shianne,shiela,shifra,shilo,shiloh,shimon,shira,shirlee,shirleen,shirlene,shirley," +
"shiv,shivam,shivani,shivansh,shlok,shlomo,shmuel,sholom,shomari,shon,shona,shonda,shonna,shonta,shoshana," +
"shreya,shreyas,shriya,shulem,shyann,shyanna,shyanne,shyheim,shyla,shylah,sia,sian,sianna,siara,sid," +
"siddharth,sidney,sidra,siena,sienna,siera,sierra,sigmund,signe,sigrid,silas,silvana,silvano,silver," +
"silverio,silvestre,silvia,silvio,sima,simcha,simeon,simon,simona,simone,simran,sinai,sincere,sinclair," +
"sindy,sinead,siobhan,sione,sir,sire,sirena,siri,sixto,siya,skip,sky,skye,skyla,skylah,skylar,skylee," +
"skyler,skylor,skylynn,skyy,slade,slater,sloan,sloane,smith,socorro,sofia,sofie,soham,sol,solana,soledad," +
"soleil,soloman,solomon,somer,sommer,sondra,sonia,sonja,sonny,sonya,sophia,sophie,sora,soraya,soren," +
"sparkle,spence,spencer,spenser,spring,stacee,stacey,staci,stacia,stacie,stacy,stafford,stan,stanford," +
"stanley,stanton,star,starla,starr,stavros,steele,stefan,stefani,stefania,stefanie,stefano,stefany," +
"steffan,steffanie,steffany,steffen,stefon,stella,stellan,stephaine,stephan,stephani,stephania,stephanie," +
"stephany,stephen,stephenie,stephine,stephon,sterling,stetson,stevan,steve,steven,stevens,stevenson," +
"stevi,stevie,stewart,stockton,stone,stoney,storm,stormi,stormie,stormy,story,stratton,struan,stryker," +
"stuart,sue,sueann,suellen,sulaiman,suleiman,sulema,sullivan,sultan,sumaya,summer,summit,sumner,sunday," +
"sunil,sunni,sunnie,sunny,sunshine,suraj,suri,surya,susan,susana,susann,susanna,susannah,susanne,susie," +
"sutton,suzan,suzann,suzanna,suzannah,suzanne,suzette,suzie,suzy,sven,sy,sybil,syble,sydnee,sydney," +
"sydni,sydnie,syed,syeda,sylas,sylis,sylus,sylvan,sylvester,sylvia,sylvie,symone,symphony,syncere," +
"synthia,syreeta,syrus,tab,tabatha,tabetha,tabitha,tad,tadd,tadeo,tadhg,taelor,taelyn,taelynn,tafari," +
"taft,taha,tahir,tahj,tahlia,tai,taina,taisha,tait,taj,taja,takia,takisha,takiyah,takoda,tal,tala," +
"talan,taleah,talen,talha,talia,taliah,talisa,talisha,talitha,taliyah,tallon,tallulah,talmadge,talmage," +
"talon,talya,tam,tamala,tamar,tamara,tamatha,tambra,tameka,tamekia,tamela,tamera,tamesha,tami,tamia," +
"tamica,tamie,tamika,tamiko,tamir,tamira,tamisha,tamiya,tammara,tammi,tammie,tammy,tamra,tamya,tamyra," +
"tana,tanaya,taneisha,tanesha,tangela,tania,tanika,tanisha,taniya,taniyah,tanja,tanna,tanner,tanvi," +
"tanya,taquan,tara,tarah,taraji,taran,tarek,tari,tarik,tariq,taron,tarra,tarsha,taryn,tasha,tashawn," +
"tashia,tashina,tasia,tasneem,tate,tatiana,tatianna,tatiyana,tatum,tatyana,tatyanna,taurean,taurus," +
"tavares,tavaris,tavarus,taven,tavia,tavian,tavin,tavion,tavis,tavon,tawana,tawanda,tawanna,tawni," +
"tawny,tawnya,taya,tayden,tayla,taylar,taylee,taylen,tayler,taylin,taylon,taylor,tayshaun,tayshawn," +
"tayson,tayton,taytum,tayvion,tayvon,tea,teagan,teague,teal,teanna,ted,tedd,teddi,teddie,teddy,teegan," +
"teena,tegan,tehya,tejas,telly,temperance,tena,tenisha,tenley,tennille,tennyson,tenzin,teo,teodoro," +
"teon,tequila,tera,terance,terell,terence,teresa,terese,teresita,teressa,teri,teron,terra,terran,terrance," +
"terrel,terrell,terrence,terri,terrie,terrill,terrion,terron,terry,tesha,tesla,tess,tessa,tessie,tevin," +
"tevon,tex,thad,thaddaeus,thaddeus,thai,thais,thalia,thane,thanh,thatcher,thayer,thayne,thea,theadore," +
"theda,thelma,theo,theodis,theodor,theodora,theodore,theophilus,theresa,therese,therman,theron,thiago," +
"thien,thomas,thomasina,thomasine,thompson,thor,thorin,thornton,thurman,thurston,tia,tiago,tiana,tianna," +
"tiara,tiarra,tiberius,tiera,tiernan,tierney,tierra,tiesha,tiffaney,tiffani,tiffanie,tiffany,tiffiny," +
"tiger,tilden,tillie,tillman,tilly,tim,timmie,timmothy,timmy,timoteo,timothy,timur,tina,tinley,tino," +
"tinsley,tionna,tirzah,tisha,titan,tito,titus,tj,tobey,tobi,tobias,tobin,toby,tod,todd,tom,tomas,tomeka," +
"tomi,tomika,tommi,tommie,tommy,tonda,toney,toni,tonia,tonie,tonisha,tonja,tony,tonya,toren,torey," +
"tori,torian,toriano,torie,torin,torrance,torrence,torrey,torri,torrie,torrin,torry,tory,tosha,tou," +
"tova,towanda,townes,toya,trace,tracee,tracey,traci,tracie,tracy,trae,tramaine,trapper,traveon,travion," +
"travis,travon,tray,trayvon,tre,treasa,treasure,tremain,tremaine,tremayne,trena,trent,trenten,trentin," +
"trenton,tresa,treshawn,tressa,tressie,treston,treva,trevan,treven,treveon,trever,trevin,trevion,trevis," +
"trevon,trevor,trey,treyson,treyton,treyvon,tricia,trina,trinidad,triniti,trinity,tripp,trish,trisha," +
"trista,tristan,tristen,tristian,tristin,triston,tristyn,triton,troy,tru,trudi,trudie,trudy,true,truett," +
"truitt,truman,truth,trystan,trysten,tryston,tuan,tucker,tuesday,turner,twana,twila,twyla,ty,tyana," +
"tyanna,tyasia,tyce,tye,tyesha,tyisha,tyjuan,tyla,tylan,tylar,tylen,tyler,tylin,tylon,tylor,tymir," +
"tynisha,tyquan,tyra,tyran,tyre,tyree,tyreek,tyreese,tyrek,tyreke,tyrel,tyrell,tyren,tyrese,tyrice," +
"tyrik,tyrin,tyriq,tyrique,tyrome,tyron,tyrone,tyronne,tyrus,tysean,tysen,tyshaun,tyshawn,tyshon,tyson," +
"tytan,tytus,tyus,tywan,tzvi,ubaldo,ulices,ulises,ulisses,ulyses,ulysses,uma,umar,una,unique,unknown," +
"urban,uri,uriah,uriel,urijah,ursula,usher,usman,uziel,uzziah,vada,val,valarie,valen,valencia,valente," +
"valentin,valentina,valentine,valentino,valeri,valeria,valerie,valery,valor,valorie,van,vance,vander," +
"vanesa,vanessa,vania,vanita,vanity,vann,vanna,vannessa,varun,vasilios,vaughan,vaughn,vayda,ved,veda," +
"vedant,veer,velda,velia,velma,velvet,venessa,venice,venita,ventura,venus,vera,verda,verdell,verenice," +
"verity,verl,verla,verlin,verlon,vern,verna,vernal,vernard,verne,vernell,vernetta,vernice,vernie,vernita," +
"vernon,verona,veronica,veronika,vesta,vester,viaan,vianca,vianey,vianna,vianney,vic,vicente,vickey," +
"vicki,vickie,vicky,victor,victoria,victoriano,vida,vidal,vienna,viet,viggo,vihaan,vijay,viki,vikki," +
"vikram,viktor,viktoria,vilma,vina,vinay,vince,vincent,vincente,vincenzo,vinh,vinny,vinson,viola,violet," +
"violeta,violetta,violette,viraj,virgie,virgil,virgilio,virginia,viridiana,vishal,vishnu,vita,vito," +
"vittorio,vivaan,vivek,vivian,viviana,vivianna,vivianne,vivien,vivienne,vladimir,von,vonda,vonnie," +
"wade,walden,waldo,waleed,wali,walid,walker,wallace,wally,walt,walter,walton,wanda,ward,wardell,warner," +
"warren,washington,watson,waverly,wayde,waylan,wayland,waylen,waylon,wayman,waymon,waymond,wayne,webb," +
"webster,wednesday,weldon,wellington,wells,welton,wendall,wendel,wendell,wendi,wendie,wendy,werner," +
"wes,weslee,wesley,wesly,wesson,west,westen,westin,westley,weston,westyn,wheeler,whit,whitley,whitney," +
"whittney,wil,wilber,wilbert,wilbur,wilburn,wilda,wilder,wiley,wilford,wilfred,wilfredo,wilhelm,wilhelmina," +
"wiliam,will,willa,willaim,willam,willard,willem,willette,william,williams,willian,willie,willis,willow," +
"willy,wilma,wilmer,wilson,wilton,windell,windy,winfield,winford,winfred,winifred,winnie,winona,winslow," +
"winston,winter,winton,wisdom,witten,wolf,wolfgang,wonda,woodie,woodrow,woody,worth,wren,wrenlee,wrenley," +
"wyatt,wylder,wylie,wyman,wynn,wynona,wynter,xaiden,xaiver,xander,xavi,xavian,xavien,xavier,xavion," +
"xavior,xayden,xena,xenia,ximena,xiomara,xion,xitlali,xitlaly,xochitl,xyla,xzavier,xzavion,yaakov," +
"yadiel,yadira,yael,yahaira,yahir,yahya,yair,yajaira,yakov,yale,yamil,yamilet,yamileth,yan,yana,yancey," +
"yancy,yandel,yaneli,yanely,yanet,yanira,yannick,yara,yareli,yarely,yaretzi,yaretzy,yariel,yaritza," +
"yaseen,yash,yasin,yasir,yasmeen,yasmin,yasmine,yasser,yassin,yazan,yazmin,yazmine,yechiel,yehoshua," +
"yehuda,yehudis,yerik,yesenia,yeshua,yesica,yessenia,yessica,yisrael,yisroel,yitty,yitzchak,yitzchok," +
"yocheved,yoel,yohan,yolanda,yolonda,yonatan,yonathan,yosef,yoselin,yoselyn,yoseph,young,yousef,yousif," +
"youssef,yousuf,yovani,ysabella,ysidro,yuliana,yulisa,yulissa,yuna,yunus,yurem,yuri,yuridia,yusef," +
"yusra,yusuf,yuvaan,yuvan,yuvraj,yves,yvette,yvonne,zabdiel,zac,zacarias,zacary,zacchaeus,zach,zacharia," +
"zachariah,zacharias,zacharie,zachary,zachery,zachry,zack,zackariah,zackary,zackery,zada,zade,zaden," +
"zadie,zahara,zahid,zahir,zahra,zaid,zaida,zaiden,zaidyn,zain,zaina,zainab,zaine,zaira,zaire,zak,zakai," +
"zakari,zakaria,zakariya,zakary,zakery,zaki,zakia,zakiya,zakiyah,zakkary,zamari,zamarion,zamir,zana," +
"zander,zandra,zane,zaniah,zaniya,zaniyah,zara,zarah,zarek,zaria,zariah,zariya,zariyah,zavian,zavien," +
"zavier,zavion,zaya,zayan,zayd,zayda,zayden,zayla,zaylee,zaylen,zayn,zayna,zaynab,zayne,zayra,zayvion," +
"zeb,zebadiah,zebedee,zebulon,zechariah,zeke,zelda,zella,zelma,zen,zena,zenaida,zendaya,zeno,zenobia," +
"zenon,zephaniah,zephyr,zeppelin,zeth,zeus,zev,zhane,zhuri,zia,ziad,ziggy,zina,zinnia,zion,zipporah," +
"ziva,ziya,ziyad,zoe,zoee,zoey,zofia,zoie,zoila,zola,zona,zora,zoraida,zoya,zulema,zulma,zuri,zuriel," +
"zyair,zyaire,zyan,zyion,zyla,zyler,zymir,zyon";
let known: Set<string> | null = null;
/** Name-key normalization: diacritics folded, lowercased, non-alphanumerics dropped. */
function nameKey(value: string): string {
return value
.normalize("NFD")
.replace(/[\u0300-\u036f]/g, "")
.toLowerCase()
.replace(/[^a-z0-9]/g, "");
}
/** Whether a single word is in the known-first-names dataset. Lazy-parses the blob on first call. */
export function isKnownFirstName(word: string): boolean {
if (!known) known = new Set(RAW.split(","));
const key = nameKey(word);
return key.length >= 2 && known.has(key);
}
/** How many names the dataset holds (for diagnostics/UI). */
export function knownFirstNameCount(): number {
if (!known) known = new Set(RAW.split(","));
return known.size;
}
+153
View File
@@ -0,0 +1,153 @@
/**
* Introduction-based speaker naming: when a caption line
* contains a spoken introduction, the auto-numbered
* "Speaker N" profile it belongs to can be renamed without the user typing
* anything. Two shapes are recognized:
*
* - Self-introduction ("I'm Alice", "my name is Alice") — names the speaker
* of the line itself.
* - Third-party introduction ("this is Bob", "meet Bob") — pends the name
* and applies it to the next DIFFERENT still-generic speaker heard.
*
* Names inferred from speech are suggestions applied only to still-generic
* profiles; a name the user set (or a prior inference) is never overwritten.
* Pure module: no platform imports.
*/
import { isKnownFirstName } from "./name-data";
export type NameInference = { name: string; kind: "self" | "third-party" };
// Words that commonly follow "I'm ..." / "this is ..." without being names.
// Lowercase; candidates are checked case-insensitively against this list (ASR
// capitalization is unreliable, so "I'm Hungry" must fail like "I'm hungry").
// The list is deliberately broad — a rejected real introduction costs one
// manual rename, while a false positive mislabels a person in every caption.
const NOT_NAMES = new Set([
// Function words, intensifiers, hedges.
..."not no yes so just really very too quite pretty almost about kind sort still always never now then here there back home away the a an in on at all both only even also again once maybe probably definitely honestly actually literally basically totally"
.split(" "),
// States and feelings ("I'm hungry", "I'm exhausted").
..."sure sorry afraid good fine okay ok great well better worse bad happy sad glad mad angry upset annoyed frustrated tired exhausted sleepy awake hungry thirsty starving full sick ill healthy cold hot warm freezing boiling excited nervous anxious worried scared terrified confused surprised shocked impressed disappointed proud grateful thankful jealous embarrassed ashamed bored curious serious certain positive confident comfortable uncomfortable ready busy free late early lost stuck broke rich famous lucky unlucky alone single married engaged divorced retired unemployed pregnant alive dead"
.split(" "),
// Progressive verbs ("I'm wanting", "I'm heading out").
..."gonna going wanting hoping waiting wondering thinking trying getting feeling speaking calling recording sending listening watching looking asking telling saying talking hearing working walking running driving flying riding leaving arriving staying coming moving heading starting stopping finishing planning meeting eating drinking cooking cleaning shopping packing visiting traveling studying learning teaching reading writing playing singing dancing sleeping dreaming waking standing sitting laughing crying kidding joking guessing counting checking testing building making taking giving putting buying selling paying saving spending losing winning helping"
.split(" "),
// Descriptors that read as predicates, not names.
..."new old young tall short big small huge tiny first last next early done finished set open closed right wrong left in out off on up down over under behind ahead around through outside inside upstairs downstairs downtown"
.split(" "),
// Exclamations and judgments ("this is Ridiculous", "this is Awesome").
..."awesome amazing ridiculous terrible horrible incredible impossible important interesting boring crazy insane weird strange funny hilarious perfect beautiful gorgeous wonderful fantastic excellent brilliant stupid dumb silly annoying confusing exciting embarrassing frustrating disappointing surprising shocking unbelievable outrageous obvious delicious gross disgusting nasty cool nice sweet cute lovely fair unfair true false real fake normal typical classic official final original actual exact simple easy hard difficult complicated expensive cheap heavy light loud quiet fast slow safe dangerous risky enough everything nothing something anything everyone nobody someone anyone mine yours hers theirs ours it that this what how why where who when"
.split(" "),
]);
// Suffixes that mark ordinary adjectives, not given names ("Ridiculous",
// "Wonderful", "Believable"). Kept narrow: common name endings like "-ly"
// (Emily, Kelly) and "-ing" (Ming, Qing) are deliberately NOT here — those
// rely on the word list and the LLM tier instead.
const NON_NAME_SUFFIXES = ["ous", "ful", "less", "able", "ible"];
// Trigger phrases match either sentence case; the captured NAME must be
// capitalized (ASR renders proper nouns capitalized, and this rejects
// ordinary words after "I'm ...").
const NAME = "([A-Z][a-zA-Z'-]+(?: [A-Z][a-zA-Z'-]+)?)";
const SELF_PATTERNS = [
new RegExp(`\\b[Mm]y name is ${NAME}`),
new RegExp(`\\b[Ii](?:'| a)m ${NAME}`),
new RegExp(`\\b[Cc]all me ${NAME}`),
new RegExp(`\\b[Tt]his is ${NAME} speaking\\b`),
];
const THIRD_PARTY_PATTERNS = [
new RegExp(`\\b[Tt]his is ${NAME}`),
new RegExp(`\\b(?:[Mm]eet|[Ss]ay hi to|[Ss]ay hello to) ${NAME}`),
new RegExp(`\\b[Hh]is name is ${NAME}`),
new RegExp(`\\b[Hh]er name is ${NAME}`),
new RegExp(`\\b[Tt]heir name is ${NAME}`),
];
function plausibleName(candidate: string): string | null {
const words = candidate.trim().split(/\s+/);
if (words.length === 0 || words.length > 2) return null;
for (const word of words) {
if (word.length < 2 || word.length > 20) return null;
const lower = word.toLowerCase();
// NOT_NAMES wins even over the known-names dataset: words like "Rich"
// and "Young" ARE real given names, but "I'm rich" is far more often a
// predicate, and a false positive mislabels a person in every caption.
if (NOT_NAMES.has(lower)) return null;
// The suffix rule, by contrast, defers to the dataset — it exists to
// catch adjectives ("Ridiculous"), and it wrongly rejects real names
// like Precious, Demetrious, and Octavious without this carve-out.
if (
!isKnownFirstName(word) &&
NON_NAME_SUFFIXES.some((suffix) => lower.length > suffix.length + 2 && lower.endsWith(suffix))
) {
return null;
}
if (!/^[A-Z]/.test(word)) return null;
}
return words.join(" ");
}
/**
* Whether an inferred name's given name (its first word — a second word is
* a surname the first-name dataset can't know) appears in the known-names
* dataset. Positive signal only: known names can skip the slower LLM
* verification, but absence never rejects — real names the dataset misses
* (non-Anglophone names especially) still go through the normal path.
*/
export function isKnownName(candidate: string): boolean {
const first = candidate.trim().split(/\s+/)[0];
return first ? isKnownFirstName(first) : false;
}
/**
* Detect a spoken introduction in one caption line. Self-introductions win
* over third-party shapes ("this is Alice speaking" is a self-intro even
* though "this is Alice" also matches the third-party pattern).
*/
export function inferIntroducedName(text: string): NameInference | null {
if (!text) return null;
for (const pattern of SELF_PATTERNS) {
const match = pattern.exec(text);
if (match) {
const name = plausibleName(match[1]!);
if (name) return { name, kind: "self" };
}
}
for (const pattern of THIRD_PARTY_PATTERNS) {
const match = pattern.exec(text);
if (match) {
const name = plausibleName(match[1]!);
if (name) return { name, kind: "third-party" };
}
}
return null;
}
/** True for the auto-assigned "Speaker N" names (safe to overwrite). */
export function isGenericSpeakerName(name: string): boolean {
return /^Speaker \d+$/.test(name.trim());
}
export type PendingIntroduction = { name: string; bySpeakerId: number; atMs: number };
/** How long a third-party introduction waits for its subject to speak. */
export const PENDING_INTRODUCTION_TTL_MS = 2 * 60 * 1000;
/**
* Whether a pending third-party introduction applies to a newly heard
* speaker: someone OTHER than the introducer, still generically named,
* speaking within the window.
*/
export function pendingApplies(
pending: PendingIntroduction,
speakerId: number,
speakerName: string,
nowMs: number,
): boolean {
if (nowMs - pending.atMs > PENDING_INTRODUCTION_TTL_MS) return false;
if (speakerId === pending.bySpeakerId) return false;
return isGenericSpeakerName(speakerName);
}
+79
View File
@@ -0,0 +1,79 @@
import { isLocalModelReady, streamLocalQwen } from "../../native/llama";
import type { NameInference } from "./name-guess";
/**
* Second-tier verification of heuristic name detections using the on-phone
* LLM (the assistant's Qwen model, when downloaded). The regex tier is
* deliberately permissive about unusual real names; the model is asked the
* one question the regex can't answer — "is this actually a person's name
* being introduced here?" — before a speaker profile gets renamed.
*
* Verdicts: true (confirmed), false (rejected), null (model unavailable,
* busy, timed out, or gave a non-answer). Callers treat null as "trust the
* heuristic": renames are retroactively correctable, so a missing model
* must not disable introduction naming entirely.
*/
const VERDICT_TIMEOUT_MS = 25_000;
// One verification at a time: the runner is shared with the assistant, and
// caption lines can arrive faster than CPU inference finishes.
let inFlight = false;
export function verifyIntroducedName(
inference: NameInference,
sentence: string,
): Promise<boolean | null> {
if (!global.isAndroid || !isLocalModelReady() || inFlight) {
return Promise.resolve(null);
}
inFlight = true;
return new Promise((resolve) => {
let settled = false;
const finish = (verdict: boolean | null) => {
if (settled) return;
settled = true;
inFlight = false;
resolve(verdict);
};
const timer = setTimeout(() => finish(null), VERDICT_TIMEOUT_MS);
try {
streamLocalQwen({
apiKey: "",
model: "local",
system:
"You verify speaker introductions for a live-captioning app. " +
"Given a transcript line and a candidate name, decide whether the candidate " +
"is genuinely a person's name being introduced (their own or someone else's), " +
"rather than an ordinary word, feeling, or phrase. " +
'Answer with exactly one word: "YES" or "NO".',
messages: [
{
role: "user",
content:
`Transcript line: "${sentence.trim()}"\n` +
`Candidate name: "${inference.name}" ` +
`(detected as a ${inference.kind === "self" ? "self-introduction" : "third-party introduction"}).\n` +
`Is "${inference.name}" a person's name being introduced in this line?`,
},
],
maxTokens: 8,
onDone: (result) => {
clearTimeout(timer);
const text = result.text.trim().toUpperCase();
if (/\bYES\b/.test(text)) finish(true);
else if (/\bNO\b/.test(text)) finish(false);
else finish(null);
},
onError: () => {
clearTimeout(timer);
finish(null);
},
});
} catch (error) {
clearTimeout(timer);
console.warn(`name verification failed: ${error}`);
finish(null);
}
});
}
+137
View File
@@ -0,0 +1,137 @@
// Speaker-dot tracking for the Sonic Radar. Dots live in the world frame
// (compass-anchored) so they stay put while the wearer's head turns; the
// people they mark can wander, so each confirmed utterance re-fixes its
// speaker's dot, and while a voice is actively being heard the nearest dot
// glides with the live direction-of-arrival. Pure TypeScript; the session
// engine owns the wall clock and passes `nowMs` in.
export type SpeakerDot = {
speakerId: number;
name: string;
color: string;
worldAngleDeg: number;
/** Wall time this speaker was last heard (confirmed or live). */
lastSpokenMs: number;
/** True while this speaker's voice is currently being heard. */
speaking: boolean;
};
/** How long a silent speaker stays on the radar (fading all the while). */
export const SPEAKER_DOT_TTL_MS = 90_000;
/** A confirmed utterance within this arc of a dot refines it; beyond, they moved. */
const SNAP_DEG = 45;
/** Live DOA within this arc of a dot is attributed to that speaker. */
const MATCH_DEG = 30;
/** Smoothing for utterance-confirmed position updates. */
const MOVE_SMOOTHING = 0.5;
/** Smoothing for packet-rate live tracking while they talk (and walk). */
const LIVE_SMOOTHING = 0.25;
const IDLE_BRIGHTNESS_MAX = 220;
const IDLE_BRIGHTNESS_MIN = 80;
/** Wrap to (-180, 180]. */
export function normalizeDeg(deg: number): number {
let value = deg % 360;
if (value > 180) value -= 360;
if (value <= -180) value += 360;
return value;
}
/** Angle EMA that follows the shorter way around the circle. */
export function smoothAngleDeg(previous: number | null, next: number, alpha: number): number {
if (previous === null) return normalizeDeg(next);
const delta = normalizeDeg(next - previous);
return normalizeDeg(previous + delta * alpha);
}
export type SpeakerIdentity = { speakerId: number; name: string; color: string };
/**
* A captioned utterance was attributed to a speaker: fix their dot at the
* utterance's bearing. Small changes smooth (jittery DOA); large ones snap
* (the person actually moved). Returns the updated dot list.
*/
export function placeDotForUtterance(
dots: SpeakerDot[],
who: SpeakerIdentity,
worldAngleDeg: number,
nowMs: number,
): SpeakerDot[] {
const existing = dots.find((dot) => dot.speakerId === who.speakerId);
if (!existing) {
return [
...dots,
{
...who,
worldAngleDeg: normalizeDeg(worldAngleDeg),
lastSpokenMs: nowMs,
speaking: false,
},
];
}
const delta = normalizeDeg(worldAngleDeg - existing.worldAngleDeg);
existing.worldAngleDeg =
Math.abs(delta) > SNAP_DEG
? normalizeDeg(worldAngleDeg)
: smoothAngleDeg(existing.worldAngleDeg, worldAngleDeg, MOVE_SMOOTHING);
existing.name = who.name;
existing.color = who.color;
existing.lastSpokenMs = nowMs;
existing.speaking = false;
return dots;
}
/**
* Speech is being heard right now from `worldAngleDeg`: mark the nearest dot
* within MATCH_DEG as actively speaking and glide it toward the live bearing,
* so a talker walking around drags their dot with them. Everyone else stops
* "speaking". Returns whether a dot matched.
*/
export function trackSpeakingDot(dots: SpeakerDot[], worldAngleDeg: number, nowMs: number): boolean {
let nearest: SpeakerDot | null = null;
let nearestDelta = Infinity;
for (const dot of dots) {
const delta = Math.abs(normalizeDeg(worldAngleDeg - dot.worldAngleDeg));
if (delta < nearestDelta) {
nearestDelta = delta;
nearest = dot;
}
}
for (const dot of dots) dot.speaking = false;
if (!nearest || nearestDelta > MATCH_DEG) return false;
nearest.speaking = true;
nearest.lastSpokenMs = nowMs;
nearest.worldAngleDeg = smoothAngleDeg(nearest.worldAngleDeg, worldAngleDeg, LIVE_SMOOTHING);
return true;
}
/** No voice is being heard: nobody is actively speaking. */
export function clearSpeaking(dots: SpeakerDot[]): void {
for (const dot of dots) dot.speaking = false;
}
/** Drop dots whose speakers have been silent past the TTL. */
export function pruneDots(
dots: SpeakerDot[],
nowMs: number,
ttlMs: number = SPEAKER_DOT_TTL_MS,
): SpeakerDot[] {
return dots.filter((dot) => nowMs - dot.lastSpokenMs < ttlMs);
}
/**
* Dot brightness: full while actively speaking, then fading with silence age
* from IDLE_BRIGHTNESS_MAX down to IDLE_BRIGHTNESS_MIN at the TTL.
*/
export function dotBrightness(
dot: SpeakerDot,
nowMs: number,
ttlMs: number = SPEAKER_DOT_TTL_MS,
): number {
if (dot.speaking) return 255;
const age = Math.max(0, nowMs - dot.lastSpokenMs);
const fraction = Math.min(1, age / ttlMs);
return Math.round(IDLE_BRIGHTNESS_MAX - (IDLE_BRIGHTNESS_MAX - IDLE_BRIGHTNESS_MIN) * fraction);
}
+223
View File
@@ -0,0 +1,223 @@
import { GrayImage } from "../../graphics/image";
import { getDefaultSmallFont } from "../../graphics/ui-fonts";
import { GESTURE_CLICK, GESTURE_DOUBLE_CLICK, GESTURE_SCROLL } from "../../ui/gestures";
import { Layer, type DashboardInputEvent, type LayerContext } from "../../ui/layers";
import { micSession, type MicSessionState } from "./mic-session";
import { dotBrightness } from "./radar-dots";
/**
* The Sonic Radar: a top-down view around the wearer's head. The shaded
* wedge is the listening beam (scroll rotates it, click locks it onto the
* detected talker); the bright tick is the live direction-of-arrival from
* the glasses DSP; speaker dots mark who was last heard where, labeled with
* the speaker id or their name once tagged. With a compass heading the whole
* scene is world-anchored (an N tick marks north and dots stay put as the
* head turns); dots glow full-bright while their speaker is talking and fade
* with the time since they last spoke.
*/
export class RadarLayer implements Layer {
private state: MicSessionState = micSession.getState();
private unsubscribe: (() => void) | null = null;
start(requestRender: () => void): void {
this.unsubscribe = micSession.onState((state) => {
this.state = state;
requestRender();
});
}
paint(ctx: LayerContext): GrayImage {
const font = getDefaultSmallFont();
const { width, height } = ctx.stack.getBaseSize();
const image = new GrayImage(width, height, 0);
const state = this.state;
const centerX = (width / 2) | 0;
const centerY = ((height - 24) / 2 + 6) | 0;
const radius = Math.min(centerX - 90, ((height - 40) / 2) | 0);
image.drawText(font, 12, 6, "Sonic Radar", 220);
const modeText = state.mode === "extended" ? "4-mic array" : "firmware DoA";
image.drawText(font, width - font.measureText(modeText) - 12, 6, modeText, 110);
// Beam wedge (device frame; the head is the reference for display).
const beamDeviceDeg = this.deviceBeamDeg(state);
const halfWidth = state.beamWidthDeg / 2;
if (state.beamFilterOn || state.beamLocked) {
for (let offset = -halfWidth; offset <= halfWidth; offset += 1.5) {
const angle = ((beamDeviceDeg + offset - 90) * Math.PI) / 180;
image.drawLine(
centerX,
centerY,
centerX + Math.round(Math.cos(angle) * radius),
centerY + Math.round(Math.sin(angle) * radius),
26,
);
}
}
// Beam edges stay visible even when the fill is off.
for (const edge of [-halfWidth, halfWidth]) {
const angle = ((beamDeviceDeg + edge - 90) * Math.PI) / 180;
image.drawLine(
centerX,
centerY,
centerX + Math.round(Math.cos(angle) * radius),
centerY + Math.round(Math.sin(angle) * radius),
70,
);
}
// Radar rings.
drawCircle(image, centerX, centerY, radius, 60);
drawCircle(image, centerX, centerY, (radius / 2) | 0, 30);
image.drawText(font, centerX - (font.measureText("front") / 2) | 0, centerY - radius - 14, "front", 90);
// Compass north tick: anchors the world frame visually as the head turns.
if (state.headingDeg !== null) {
const northAngle = ((this.worldToDeviceDeg(0, state) - 90) * Math.PI) / 180;
const cos = Math.cos(northAngle);
const sin = Math.sin(northAngle);
image.drawLine(
centerX + Math.round(cos * (radius - 6)),
centerY + Math.round(sin * (radius - 6)),
centerX + Math.round(cos * (radius + 2)),
centerY + Math.round(sin * (radius + 2)),
200,
);
image.drawText(
font,
centerX + Math.round(cos * (radius + 10)) - ((font.measureText("N") / 2) | 0),
centerY + Math.round(sin * (radius + 10)) - ((font.lineHeight / 2) | 0),
"N",
200,
);
}
// Head marker.
image.fillRoundedRect(centerX - 4, centerY - 5, 8, 10, 160, 3);
// Live direction-of-arrival tick.
if (state.doaDeviceDeg !== null && state.ssr > 0) {
const angle = ((state.doaDeviceDeg - 90) * Math.PI) / 180;
const tipX = centerX + Math.cos(angle) * radius;
const tipY = centerY + Math.sin(angle) * radius;
image.drawLine(
centerX + Math.round(Math.cos(angle) * (radius * 0.55)),
centerY + Math.round(Math.sin(angle) * (radius * 0.55)),
Math.round(tipX),
Math.round(tipY),
255,
);
}
// Speaker dots with id/name labels: full-bright (and ringed) while that
// person is actively speaking, fading with silence age otherwise.
const now = Date.now();
for (const dot of state.speakerDots) {
const deviceDeg = this.worldToDeviceDeg(dot.worldAngleDeg, state);
const angle = ((deviceDeg - 90) * Math.PI) / 180;
const dotX = centerX + Math.round(Math.cos(angle) * radius * 0.8);
const dotY = centerY + Math.round(Math.sin(angle) * radius * 0.8);
const value = dotBrightness(dot, now);
if (dot.speaking) {
image.fillRoundedRect(dotX - 4, dotY - 4, 9, 9, value, 4);
drawCircle(image, dotX, dotY, 7, 140);
} else {
image.fillRoundedRect(dotX - 3, dotY - 3, 7, 7, value, 3);
}
const label = dot.name;
const labelValue = Math.max(90, value - 50);
const labelX = dotX + 8 + font.measureText(label) > width ? dotX - font.measureText(label) - 8 : dotX + 8;
image.drawText(font, labelX, dotY - 6, label, labelValue);
}
// Side panel: beam + level readouts.
const panelX = width - 116;
let panelY = 26;
image.drawText(
font,
panelX,
panelY,
state.headingDeg !== null ? `Heading ${Math.round(state.headingDeg)}°` : "No compass",
state.headingDeg !== null ? 150 : 90,
);
panelY += 16;
image.drawText(font, panelX, panelY, `Beam ${Math.round(state.beamWorldDeg)}°`, 170);
panelY += 16;
image.drawText(font, panelX, panelY, `Width ${Math.round(state.beamWidthDeg)}°`, 130);
panelY += 16;
image.drawText(font, panelX, panelY, state.beamLocked ? "Locked on talker" : "Manual aim", 130);
panelY += 16;
if (state.doaDeviceDeg !== null) {
image.drawText(font, panelX, panelY, `Heard ${Math.round(state.doaDeviceDeg)}°`, 200);
panelY += 16;
}
image.drawText(font, panelX, panelY, state.beamFilterOn ? "Filter: beam only" : "Filter: off", 130);
const footerY = height - font.lineHeight - 4;
image.drawText(
font,
12,
footerY,
`${GESTURE_SCROLL} aim ${GESTURE_CLICK} lock ${GESTURE_DOUBLE_CLICK} back`,
110,
);
return image;
}
private deviceBeamDeg(state: MicSessionState): number {
if (state.headingDeg === null) return state.beamWorldDeg;
return normalize(state.beamWorldDeg - state.headingDeg);
}
private worldToDeviceDeg(worldDeg: number, state: MicSessionState): number {
if (state.headingDeg === null) return normalize(worldDeg);
return normalize(worldDeg - state.headingDeg);
}
handleInput(event: DashboardInputEvent, ctx: LayerContext): void {
switch (event.type) {
case "scroll-up":
micSession.setBeamWorldDeg(this.state.beamWorldDeg - 15);
return;
case "scroll-down":
micSession.setBeamWorldDeg(this.state.beamWorldDeg + 15);
return;
case "click":
micSession.toggleBeamLock();
return;
case "long-press":
micSession.adjustBeamWidth(30 * (this.state.beamWidthDeg >= 180 ? -5 : 1));
return;
case "double-click":
ctx.stack.pop();
return;
default:
return;
}
}
onRemoved(): void {
this.unsubscribe?.();
this.unsubscribe = null;
}
}
function normalize(deg: number): number {
let value = deg % 360;
if (value > 180) value -= 360;
if (value < -180) value += 360;
return value;
}
function drawCircle(image: GrayImage, centerX: number, centerY: number, radius: number, value: number): void {
const steps = Math.max(48, radius * 4);
for (let step = 0; step < steps; step++) {
const angle = (step / steps) * 2 * Math.PI;
image.setPixel(
centerX + Math.round(Math.cos(angle) * radius),
centerY + Math.round(Math.sin(angle) * radius),
value,
);
}
}
+199
View File
@@ -0,0 +1,199 @@
import { Utils } from "@nativescript/core";
import { toUint8Array } from "../../util/array-util";
import { micModelPath } from "./mic-models";
import { SPEAKER_KNOWN_THRESHOLD, encodeEmbedding, speakerRegistry } from "./speakers";
declare const com: any;
declare const android: any;
/**
* Re-diarize a saved conversation: run offline speaker diarization (pyannote
* segmentation + speaker embeddings + clustering) over the session's
* recording, then reconcile the resulting speaker turns against the stored
* transcript segments — matching each cluster back to an enrolled speaker by
* voice-print, or minting a new speaker when no one matches.
*/
export type RediarizeResult = {
turns: number;
clusters: number;
reassignedSegments: number;
newSpeakers: number;
};
export type RediarizeCallbacks = {
onProgress: (fraction: number) => void;
onDone: (result: RediarizeResult) => void;
onError: (message: string) => void;
};
type Turn = { startMs: number; endMs: number; cluster: number };
function store(): any {
const context = Utils.android.getApplicationContext();
return com.faceclaw.app.FaceclawConversationStore.getInstance(context);
}
export function rediarizeSession(
sessionId: number,
options: { numSpeakers?: number; threshold?: number },
callbacks: RediarizeCallbacks,
): void {
const audioPath = String(store().getSessionAudioPath(sessionId));
if (!audioPath) {
callbacks.onError("This conversation has no saved recording to re-analyze.");
return;
}
const segmentationModel = micModelPath("diarization-segmentation");
const embeddingModel = micModelPath("speaker-embedding");
if (!segmentationModel || !embeddingModel) {
callbacks.onError("Download the re-diarization and speaker voice models first (Microphones > Voice & speakers).");
return;
}
const listener = new com.faceclaw.app.FaceclawDiarizer.Listener({
onProgress: (progress: number) => callbacks.onProgress(Number(progress)),
onDone: (turnsJson: string) => {
try {
const turns = JSON.parse(String(turnsJson)) as Turn[];
callbacks.onDone(applyTurns(sessionId, turns));
} catch (error) {
callbacks.onError(`Applying diarization failed: ${String(error)}`);
}
},
onError: (message: string) => callbacks.onError(String(message)),
});
const diarizer = new com.faceclaw.app.FaceclawDiarizer(
segmentationModel,
embeddingModel,
audioPath,
options.numSpeakers ?? -1,
options.threshold ?? 0.5,
listener,
);
diarizer.start();
}
type StoredSegment = {
id: number;
speakerId: number | null;
startedAt: number;
endedAt: number;
audioOffsetMs: number | null;
};
function applyTurns(sessionId: number, turns: Turn[]): RediarizeResult {
const segments = (JSON.parse(String(store().querySegments(sessionId))) as Array<Record<string, unknown>>).map(
(row): StoredSegment => ({
id: Number(row.id),
speakerId: row.speakerId === null ? null : Number(row.speakerId),
startedAt: Number(row.startedAt),
endedAt: Number(row.endedAt),
audioOffsetMs: row.audioOffsetMs === null ? null : Number(row.audioOffsetMs),
}),
);
const embeddings = new Map<number, Float32Array>();
for (const row of JSON.parse(String(store().querySegmentEmbeddings(sessionId))) as Array<
Record<string, unknown>
>) {
const decoded = decodeBase64Floats(String(row.embeddingBase64 ?? ""));
if (decoded) embeddings.set(Number(row.id), decoded);
}
// Assign each transcript segment to the diarization cluster it overlaps most.
const segmentClusters = new Map<number, number>();
for (const segment of segments) {
if (segment.audioOffsetMs === null) continue;
const startMs = segment.audioOffsetMs;
const endMs = startMs + (segment.endedAt - segment.startedAt);
let bestCluster = -1;
let bestOverlap = 0;
for (const turn of turns) {
const overlap = Math.min(endMs, turn.endMs) - Math.max(startMs, turn.startMs);
if (overlap > bestOverlap) {
bestOverlap = overlap;
bestCluster = turn.cluster;
}
}
if (bestCluster >= 0) segmentClusters.set(segment.id, bestCluster);
}
// Centroid per cluster from the stored per-segment voice-prints.
const clusterEmbeddings = new Map<number, Float32Array[]>();
for (const [segmentId, cluster] of segmentClusters) {
const embedding = embeddings.get(segmentId);
if (!embedding) continue;
const list = clusterEmbeddings.get(cluster) ?? [];
list.push(embedding);
clusterEmbeddings.set(cluster, list);
}
speakerRegistry.reload();
const clusterSpeaker = new Map<number, number>();
let newSpeakers = 0;
for (const [cluster, prints] of clusterEmbeddings) {
const centroid = meanEmbedding(prints);
if (!centroid) continue;
const best = speakerRegistry.bestMatch(centroid);
if (best && best.similarity >= SPEAKER_KNOWN_THRESHOLD) {
clusterSpeaker.set(cluster, best.profile.id);
} else {
const id = Number(store().createSpeaker(nextAutoName(), "#90A4AE", false, encodeEmbedding(centroid)));
speakerRegistry.reload();
clusterSpeaker.set(cluster, id);
newSpeakers += 1;
}
}
let reassigned = 0;
for (const segment of segments) {
const cluster = segmentClusters.get(segment.id);
if (cluster === undefined) continue;
const speakerId = clusterSpeaker.get(cluster);
if (speakerId === undefined || speakerId === segment.speakerId) continue;
store().reassignSegmentSpeaker(segment.id, speakerId);
reassigned += 1;
}
speakerRegistry.reload();
return {
turns: turns.length,
clusters: clusterEmbeddings.size,
reassignedSegments: reassigned,
newSpeakers,
};
}
function nextAutoName(): string {
const taken = new Set(speakerRegistry.all().map((profile) => profile.name));
for (let index = 1; ; index++) {
const candidate = `Speaker ${index}`;
if (!taken.has(candidate)) return candidate;
}
}
function meanEmbedding(prints: Float32Array[]): Float32Array | null {
if (prints.length === 0) return null;
const mean = new Float32Array(prints[0]!.length);
for (const print of prints) {
if (print.length !== mean.length) continue;
for (let i = 0; i < mean.length; i++) mean[i] += print[i]!;
}
let norm = 0;
for (let i = 0; i < mean.length; i++) norm += mean[i]! * mean[i]!;
norm = Math.sqrt(norm);
if (norm > 0) {
for (let i = 0; i < mean.length; i++) mean[i] /= norm;
}
return mean;
}
function decodeBase64Floats(base64: string): Float32Array | null {
if (!base64) return null;
try {
const bytes = toUint8Array(android.util.Base64.decode(base64, android.util.Base64.NO_WRAP));
if (bytes.length < 4 || bytes.length % 4 !== 0) return null;
return new Float32Array(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.length));
} catch {
return null;
}
}
+403
View File
@@ -0,0 +1,403 @@
// Deterministic sentiment analysis: a keyword emotion classifier (with
// negation scoping and confidence calibration) plus hand-lexicon polarity
// scoring. No platform NLP dependency — the deterministic tiers carry the
// whole signal.
export type EmotionLabel =
| "happy"
| "sad"
| "angry"
| "frustrated"
| "excited"
| "anxious"
| "surprised"
| "confident"
| "confused"
| "disgusted"
| "embarrassed"
| "relieved"
| "bored"
| "calm"
| "neutral";
export type SentimentBucket = "veryPositive" | "positive" | "neutral" | "negative" | "veryNegative";
export type EmotionDetection = {
emotion: EmotionLabel;
confidence: number;
source: "keyword" | "lexical" | "none";
};
// Declaration order matters twice: EMOTION_ORDER breaks ranking ties, and
// EMOTION_PATTERNS is evaluated in table order.
const EMOTION_ORDER: EmotionLabel[] = [
"happy", "sad", "angry", "frustrated", "excited", "anxious", "surprised",
"confident", "confused", "disgusted", "embarrassed", "relieved", "bored",
"calm", "neutral",
];
// Terms users commonly use when searching for each emotion. The classifier
// matches these too, so storage and retrieval speak the same vocabulary.
const SEARCH_ALIASES: Record<EmotionLabel, string[]> = {
happy: ["happy", "happiness", "glad", "pleased", "joy", "joyful", "cheerful", "delighted"],
sad: ["sad", "sadness", "unhappy", "heartbroken", "depressed", "grief", "somber", "upset"],
angry: ["angry", "anger", "mad", "furious", "livid", "irate", "outraged", "rage", "hostile"],
frustrated: ["frustrated", "frustration", "annoyed", "annoying", "irritated", "irritating", "fed up"],
excited: ["excited", "excitement", "enthusiastic", "thrilled", "pumped", "stoked"],
anxious: ["anxious", "anxiety", "worried", "worry", "nervous", "afraid", "scared", "stressed", "panic"],
surprised: ["surprised", "surprise", "shocked", "unexpected", "astonished", "amazed"],
confident: ["confident", "confidence", "certain", "assured", "sure", "determined"],
confused: ["confused", "confusion", "unclear", "uncertain", "puzzled", "lost"],
disgusted: ["disgusted", "disgust", "repulsed", "revolted", "sickened", "revolting"],
embarrassed: ["embarrassed", "embarrassment", "ashamed", "humiliated", "mortified", "self-conscious", "awkward"],
relieved: ["relieved", "relief", "reassured", "thank goodness", "weight off my shoulders"],
bored: ["bored", "boredom", "boring", "uninterested", "tedious", "zoned out"],
calm: ["calm", "calmness", "relaxed", "peaceful", "at ease", "settled"],
neutral: ["neutral"],
};
// High-precision subset suitable for silently turning natural language into
// an exact filter. Ambiguous terms such as "sure", "lost", "miss", and "mad"
// remain indexed search aliases but never hijack ordinary searches.
const INFERRED_FILTER_ALIASES: Record<EmotionLabel, string[]> = {
happy: ["happy", "happiness", "glad", "joy", "joyful", "cheerful", "delighted"],
sad: ["sad", "sadness", "unhappy", "heartbroken", "depressed", "grief", "somber"],
angry: ["angry", "anger", "furious", "livid", "irate", "outraged", "rage", "hostile"],
frustrated: ["frustrated", "frustration", "annoyed", "irritated", "fed up"],
excited: ["excited", "excitement", "enthusiastic", "thrilled", "pumped", "stoked"],
anxious: ["anxious", "anxiety", "worried", "nervous", "afraid", "scared", "panic"],
surprised: ["surprised", "surprise", "shocked", "astonished"],
confident: ["confident", "confidence", "assured"],
confused: ["confused", "confusion", "puzzled"],
disgusted: ["disgusted", "disgust", "repulsed", "revolted", "sickened"],
embarrassed: ["embarrassed", "embarrassment", "ashamed", "humiliated", "mortified"],
relieved: ["relieved", "relief", "reassured"],
bored: ["bored", "boredom", "uninterested"],
calm: ["calm", "calmness", "relaxed"],
neutral: [],
};
const EMOTION_PATTERNS: Array<[EmotionLabel, string[]]> = [
["happy", ["happy", "happier", "glad", "pleased", "wonderful", "great", "awesome", "fantastic", "love", "enjoy", "thankful", "grateful", "delighted", "joyful", "cheerful"]],
["excited", ["excited", "enthusiastic", "amazing", "incredible", "can't wait", "thrilled", "pumped", "stoked", "wow", "unbelievable", "blown away"]],
["sad", ["sad", "unhappy", "unfortunately", "miss", "sorry", "regret", "disappointing", "heartbreaking", "crying", "depressed", "grief", "mourn"]],
["angry", ["angry", "mad", "furious", "livid", "irate", "outraged", "rage", "hostile", "unacceptable", "ridiculous", "hate", "damn", "pissed", "how dare you", "enough is enough", "what the hell", "this is bullshit", "you never listen", "i have had enough", "stop it right now"]],
["frustrated", ["frustrated", "annoyed", "annoying", "irritated", "irritating", "stuck", "struggling", "can't figure", "doesn't work", "broken", "keeps failing", "fed up", "tired of", "sick of", "waste of time", "again and again", "why does this keep"]],
["anxious", ["worried", "anxious", "nervous", "concerned", "afraid", "scared", "uneasy", "stressed", "stress", "panic", "overwhelmed", "overwhelm", "dread"]],
["surprised", ["surprised", "astonished", "unexpected", "didn't expect", "shocking", "no way", "whoa"]],
["confident", ["confident", "certain", "sure", "guaranteed", "no doubt", "convinced"]],
["confused", ["confused", "don't understand", "unclear", "what do you mean", "lost", "lost me", "makes no sense", "wait what", "i'm not sure", "puzzled"]],
["disgusted", ["disgusted", "repulsed", "revolted", "sickened", "that's disgusting", "that is disgusting", "makes me sick", "turns my stomach"]],
["embarrassed", ["embarrassed", "ashamed", "humiliated", "mortified", "self-conscious", "i could die of embarrassment"]],
["relieved", ["relieved", "what a relief", "thank goodness", "thank god", "weight off my shoulders", "can breathe again"]],
["bored", ["bored", "uninterested", "zoned out", "lost interest", "couldn't care less"]],
["calm", ["calm", "relaxed", "peaceful", "at ease", "settled", "untroubled"]],
];
const EMOTION_SEARCH_PATTERNS: Array<[EmotionLabel, string[]]> = EMOTION_PATTERNS.map(
([emotion, patterns]) => [emotion, dedupe(patterns.concat(SEARCH_ALIASES[emotion]))],
);
function dedupe(values: string[]): string[] {
return Array.from(new Set(values));
}
// These lexicons carry the whole polarity signal, so both sets are extended
// (see below).
const POSITIVE_LEXICON = new Set<string>([
"amazing", "awesome", "best", "excellent", "fantastic", "glad", "great", "happy",
"love", "outstanding", "perfect", "pleased", "positive", "relieved", "thankful", "wonderful",
// Extension: common polarity words added so the lexicons carry the whole
// polarity signal on their own.
"beautiful", "better", "brilliant", "delighted", "enjoy", "enjoyed", "excited",
"fun", "good", "grateful", "helpful", "hopeful", "impressive", "joy", "lovely",
"nice", "proud", "success", "successful", "thrilled",
]);
const NEGATIVE_LEXICON = new Set<string>([
"angry", "ashamed", "awful", "bad", "bored", "disappointed", "disappointing",
"disgusted", "embarrassed", "frustrated", "hate", "horrible", "negative", "sad",
"terrible", "unacceptable", "unhappy", "upset", "worried", "worse",
// Extension: see the note on POSITIVE_LEXICON.
"annoyed", "annoying", "anxious", "broken", "crying", "depressed", "dreadful",
"failed", "failing", "furious", "hurt", "miserable", "nasty", "painful", "poor",
"scared", "stressed", "useless", "worst", "wrong",
]);
const NEGATION_TOKENS = new Set<string>([
"not", "never", "no", "neither", "nor", "hardly", "without", "cannot", "cant",
]);
// Contrastive conjunctions end a negation scope: "not happy, but angry"
// expresses anger. Coordinating "and" is intentionally excluded because
// "not angry and frustrated" often negates both states.
const NEGATION_SCOPE_BOUNDARY_TOKENS = new Set<string>([
"but", "however", "though", "yet",
]);
function emotionTokens(text: string): string[] {
// Preserve the semantic negation before punctuation/apostrophes are stripped.
const normalized = text
.toLowerCase()
.replace(/’/g, "'")
.replace(/can't/g, "cannot")
.replace(/i'm/g, "i am")
.replace(/n't/g, " not");
return normalized.split(/[^\p{L}\p{N}]+/u).filter((token) => token.length > 0);
}
function emotionCueIsNegated(start: number, tokens: string[]): boolean {
if (start <= 0) return false;
const windowStart = Math.max(0, start - 3);
for (let i = start - 1; i >= windowStart; i--) {
if (NEGATION_SCOPE_BOUNDARY_TOKENS.has(tokens[i])) {
// Only a negation between the boundary and the cue still applies.
for (let j = i + 1; j < start; j++) {
if (NEGATION_TOKENS.has(tokens[j])) return true;
}
return false;
}
}
for (let i = windowStart; i < start; i++) {
if (NEGATION_TOKENS.has(tokens[i])) return true;
}
return false;
}
function matchesAt(patternTokens: string[], start: number, tokens: string[]): boolean {
for (let i = 0; i < patternTokens.length; i++) {
if (tokens[start + i] !== patternTokens[i]) return false;
}
return true;
}
// Match whole words/phrases, not substrings ("mad" must not match "made"),
// and ignore explicitly negated cues ("I am not angry").
function nonNegatedMatchCount(pattern: string, tokens: string[]): number {
const patternTokens = emotionTokens(pattern);
if (patternTokens.length === 0 || patternTokens.length > tokens.length) return 0;
let count = 0;
for (let start = 0; start <= tokens.length - patternTokens.length; start++) {
if (!matchesAt(patternTokens, start, tokens)) continue;
if (emotionCueIsNegated(start, tokens)) continue;
count++;
}
return count;
}
function containsNonNegatedPattern(pattern: string, tokens: string[]): boolean {
const patternTokens = emotionTokens(pattern);
if (patternTokens.length === 0 || patternTokens.length > tokens.length) return false;
for (let start = 0; start <= tokens.length - patternTokens.length; start++) {
if (!matchesAt(patternTokens, start, tokens)) continue;
if (emotionCueIsNegated(start, tokens)) continue;
return true;
}
return false;
}
function detectEmotionWithScore(text: string, sentimentScore: number): EmotionDetection {
const tokens = emotionTokens(text);
// Stable ordering makes runner-up selection reproducible, while equal
// evidence is handled as ambiguity below rather than guessed.
const ranked: Array<[EmotionLabel, number]> = [];
for (const [emotion, patterns] of EMOTION_SEARCH_PATTERNS) {
let score = 0;
for (const pattern of patterns) {
score += nonNegatedMatchCount(pattern, tokens);
}
if (score > 0) ranked.push([emotion, score]);
}
ranked.sort((a, b) => {
if (a[1] !== b[1]) return b[1] - a[1];
return EMOTION_ORDER.indexOf(a[0]) - EMOTION_ORDER.indexOf(b[0]);
});
if (ranked.length > 0) {
const [bestEmotion, bestScore] = ranked[0];
const runnerUpScore = ranked.length > 1 ? ranked[1][1] : 0;
if (bestScore - runnerUpScore === 0) {
// Equally strong cues for different emotions are genuinely ambiguous;
// picking one would make mixed statements depend on declaration order.
return { emotion: "neutral", confidence: 0.40, source: "none" };
}
const confidence =
bestScore >= 2
? Math.min(0.98, 0.88 + (bestScore - 2) * 0.03)
: // A single cue can be quoted, topical, idiomatic, or sarcastic.
0.70;
return { emotion: bestEmotion, confidence, source: "keyword" };
}
// Polarity is not an emotion taxonomy: a negative score cannot distinguish
// anger, sadness, fear, or frustration. Keep the categorical label neutral
// and expose the independent score for search.
if (Math.abs(sentimentScore) < 0.10) {
return { emotion: "neutral", confidence: 0.76, source: "none" };
}
return { emotion: "neutral", confidence: 0.46, source: "lexical" };
}
export function detectEmotion(text: string): EmotionDetection {
return detectEmotionWithScore(text, scoreSentiment(text));
}
// Score a single text string in [-1, 1]. Sentences are scored independently
// and averaged; the lexicon delta per sentence is normalized by sentence
// length.
export function scoreSentiment(text: string): number {
const sentences = text
.split(/[.!?]+/)
.map((sentence) => sentence.trim())
.filter((sentence) => sentence.length > 0);
if (sentences.length === 0) return 0;
const scores: number[] = [];
for (const sentence of sentences) {
const tokens = emotionTokens(sentence);
if (tokens.length === 0) continue;
let delta = 0;
for (let i = 0; i < tokens.length; i++) {
let polarity = 0;
if (POSITIVE_LEXICON.has(tokens[i])) polarity = 1;
else if (NEGATIVE_LEXICON.has(tokens[i])) polarity = -1;
if (polarity === 0) continue;
if (emotionCueIsNegated(i, tokens)) polarity = -polarity;
delta += polarity;
}
if (delta === 0) {
scores.push(0);
continue;
}
const normalized = delta / Math.max(Math.floor(tokens.length / 3), 1);
scores.push(Math.max(-1, Math.min(1, normalized)));
}
if (scores.length === 0) return 0;
const average = scores.reduce((total, score) => total + score, 0) / scores.length;
return Math.max(-1, Math.min(1, average));
}
export function sentimentBucket(score: number): SentimentBucket {
if (score > 0.3) return "veryPositive";
if (score > 0.1) return "positive";
if (score < -0.3) return "veryNegative";
if (score < -0.1) return "negative";
return "neutral";
}
export type AnalyzedLine = {
score: number;
emotion: EmotionLabel;
emotionConfidence: number;
};
export function analyzeLine(text: string): AnalyzedLine {
const score = scoreSentiment(text);
const detection = detectEmotionWithScore(text, score);
return { score, emotion: detection.emotion, emotionConfidence: detection.confidence };
}
export type SentimentPoint = {
index: number;
score: number;
emotion: EmotionLabel;
};
export type SentimentSummary = {
averageScore: number;
bucket: SentimentBucket;
bucketCounts: Record<SentimentBucket, number>;
emotionDistribution: Partial<Record<EmotionLabel, number>>;
trend: SentimentPoint[];
};
const MAX_TREND_POINTS = 60;
export function summarize(lines: AnalyzedLine[]): SentimentSummary {
const bucketCounts: Record<SentimentBucket, number> = {
veryPositive: 0,
positive: 0,
neutral: 0,
negative: 0,
veryNegative: 0,
};
const emotionDistribution: Partial<Record<EmotionLabel, number>> = {};
if (lines.length === 0) {
return { averageScore: 0, bucket: "neutral", bucketCounts, emotionDistribution, trend: [] };
}
let total = 0;
for (const line of lines) {
total += line.score;
bucketCounts[sentimentBucket(line.score)]++;
emotionDistribution[line.emotion] = (emotionDistribution[line.emotion] ?? 0) + 1;
}
const averageScore = total / lines.length;
// Downsample by averaging within evenly-spaced chunks, keeping the most
// extreme emotion per chunk so spikes stay visible on the chart. The chunk
// width rounds up so the trend never exceeds MAX_TREND_POINTS.
const trend: SentimentPoint[] = [];
const step = Math.max(1, Math.ceil(lines.length / MAX_TREND_POINTS));
for (let i = 0; i < lines.length; i += step) {
const chunk = lines.slice(i, i + step);
const chunkTotal = chunk.reduce((sum, line) => sum + line.score, 0);
let extreme = chunk[0];
for (const line of chunk) {
if (Math.abs(line.score) > Math.abs(extreme.score)) extreme = line;
}
trend.push({ index: i, score: chunkTotal / chunk.length, emotion: extreme.emotion });
}
return {
averageScore,
bucket: sentimentBucket(averageScore),
bucketCounts,
emotionDistribution,
trend,
};
}
// Human-readable metadata for the transcript search index. Keeping the alias
// mapping beside the classifier prevents an analysis label and its retrieval
// aliases from drifting apart.
export function searchableMetadata(emotion: EmotionLabel, score: number): string {
const emotionTerms = [emotion as string].concat(SEARCH_ALIASES[emotion]);
let sentimentTerms: string[];
switch (sentimentBucket(score)) {
case "veryPositive":
sentimentTerms = ["very positive", "positive sentiment"];
break;
case "positive":
sentimentTerms = ["positive", "positive sentiment"];
break;
case "neutral":
sentimentTerms = ["neutral", "neutral sentiment"];
break;
case "negative":
sentimentTerms = ["negative", "negative sentiment"];
break;
case "veryNegative":
sentimentTerms = ["very negative", "negative sentiment"];
break;
}
return emotionTerms.concat(sentimentTerms).join(" ");
}
// Infer an exact emotion filter from ordinary search language. Returns null
// for no emotion or multiple distinct emotions so compound requests can fall
// back to normal ranked retrieval.
export function inferredEmotionFilter(query: string): EmotionLabel | null {
const tokens = emotionTokens(query);
const matches: EmotionLabel[] = [];
for (const emotion of EMOTION_ORDER) {
if (emotion === "neutral") continue;
const patterns = dedupe([emotion as string].concat(INFERRED_FILTER_ALIASES[emotion]));
if (patterns.some((pattern) => containsNonNegatedPattern(pattern, tokens))) {
matches.push(emotion);
}
}
return matches.length === 1 ? matches[0] : null;
}
+183
View File
@@ -0,0 +1,183 @@
import { Utils } from "@nativescript/core";
import { isLocalModelReady, streamLocalQwen } from "../../native/llama";
import { speakerRegistry } from "./speakers";
declare const com: any;
/**
* Per-speaker conversation insights, generated with the on-phone LLM when a
* caption session ends: a short recap of the conversation, the action items
* it produced, and a consolidated list of inferred facts about the person
* (fed by the transcript, the contact's tag/notes, and previously inferred
* facts). Stored on the speaker row in the conversation store, where the
* encounter popup and the People view read them back.
*
* Best-effort by design: no model, a busy runner, or an unparseable reply
* simply leaves the speaker's existing insights in place. Everything runs
* sequentially — the runner is shared with the assistant and caption name
* verification.
*/
/** Speakers with fewer transcript lines than this in the session are skipped. */
const MIN_SPEAKER_LINES = 2;
/** Transcript excerpt budget; Qwen runs with a 4096-token context. */
const MAX_TRANSCRIPT_CHARS = 4500;
const MAX_FACTS = 8;
const MAX_ACTION_ITEMS = 6;
const GENERATION_TIMEOUT_MS = 90_000;
type SegmentLine = { speakerId: number | null; text: string };
function store(): any {
const context = Utils.android.getApplicationContext();
return com.faceclaw.app.FaceclawConversationStore.getInstance(context);
}
/** One generation at a time across sessions; a second session-end call queues behind the first. */
let chain: Promise<void> = Promise.resolve();
/**
* Generate and store insights for every non-wearer speaker heard in the
* session. Fire-and-forget: call after the session row is finished; errors
* only log.
*/
export function generateSessionInsights(sessionId: number): void {
if (!global.isAndroid || sessionId < 0 || !isLocalModelReady()) return;
chain = chain.then(() => generateForSession(sessionId)).catch((error) => {
console.warn(`speaker insights generation failed: ${error}`);
});
}
async function generateForSession(sessionId: number): Promise<void> {
const segments = (JSON.parse(String(store().querySegments(sessionId))) as Array<Record<string, unknown>>)
.map((row): SegmentLine => ({
speakerId: row.speakerId === null ? null : Number(row.speakerId),
text: String(row.text ?? "").trim(),
}))
.filter((line) => line.text);
if (!segments.length) return;
speakerRegistry.reload();
const lineCounts = new Map<number, number>();
for (const line of segments) {
if (line.speakerId !== null) {
lineCounts.set(line.speakerId, (lineCounts.get(line.speakerId) ?? 0) + 1);
}
}
const transcript = buildTranscript(segments);
for (const [speakerId, lines] of lineCounts) {
if (lines < MIN_SPEAKER_LINES) continue;
const profile = speakerRegistry.byId(speakerId);
if (!profile || profile.isWearer) continue;
try {
const insights = await generateForSpeaker(profile.name, profile.tag, profile.facts, transcript);
if (insights) {
speakerRegistry.setInsights(
speakerId,
insights.recap,
insights.actionItems.slice(0, MAX_ACTION_ITEMS),
insights.facts.slice(0, MAX_FACTS),
sessionId,
);
}
} catch (error) {
console.warn(`speaker insights failed for ${profile.name}: ${error}`);
}
}
}
function buildTranscript(segments: SegmentLine[]): string {
const names = new Map<number, string>();
for (const profile of speakerRegistry.all()) {
names.set(profile.id, profile.isWearer ? `${profile.name} (the wearer)` : profile.name);
}
const lines = segments.map((line) => {
const who = line.speakerId !== null ? (names.get(line.speakerId) ?? "Speaker") : "Speaker";
return `${who}: ${line.text}`;
});
let text = lines.join("\n");
if (text.length > MAX_TRANSCRIPT_CHARS) {
// Keep the end of the conversation: goodbyes and plans (the action items)
// cluster there, and the recap should reflect where things landed.
text = "..." + text.slice(text.length - MAX_TRANSCRIPT_CHARS);
}
return text;
}
type SpeakerInsights = { recap: string; actionItems: string[]; facts: string[] };
function generateForSpeaker(
name: string,
notes: string,
existingFacts: string[],
transcript: string,
): Promise<SpeakerInsights | null> {
return new Promise((resolve) => {
let settled = false;
const finish = (value: SpeakerInsights | null) => {
if (!settled) {
settled = true;
resolve(value);
}
};
const timer = setTimeout(() => finish(null), GENERATION_TIMEOUT_MS);
try {
streamLocalQwen({
apiKey: "",
model: "local",
system:
"You maintain a contact's conversation memory for a live-captioning app. " +
"From the transcript, produce for the named person: a recap of this conversation " +
"(1-2 sentences), the concrete action items agreed or requested in it (things to do, " +
"send, or follow up on — empty if none), and an updated list of short facts about the " +
"person (job, family, interests, plans, preferences). Merge the previously known facts " +
"with anything new from the transcript; drop duplicates and anything now outdated. " +
"Never invent details that are not supported by the notes, known facts, or transcript. " +
'Reply with ONLY a JSON object: {"recap": "...", "actionItems": ["..."], "facts": ["..."]}.',
messages: [
{
role: "user",
content:
`Person: ${name}\n` +
(notes ? `Contact notes: ${notes}\n` : "") +
`Previously known facts: ${existingFacts.length ? JSON.stringify(existingFacts) : "(none)"}\n\n` +
`# Transcript\n${transcript}`,
},
],
maxTokens: 350,
onDone: (result) => {
clearTimeout(timer);
finish(parseInsights(result.text));
},
onError: (message) => {
clearTimeout(timer);
console.warn(`speaker insights model error: ${message}`);
finish(null);
},
});
} catch (error) {
clearTimeout(timer);
console.warn(`speaker insights request failed: ${error}`);
finish(null);
}
});
}
/** Parse the model's reply leniently: the first {...} block wins. */
export function parseInsights(reply: string): SpeakerInsights | null {
const start = reply.indexOf("{");
const end = reply.lastIndexOf("}");
if (start < 0 || end <= start) return null;
try {
const parsed = JSON.parse(reply.slice(start, end + 1)) as Record<string, unknown>;
const recap = String(parsed.recap ?? "").trim();
if (!recap) return null;
const list = (value: unknown): string[] =>
Array.isArray(value) ? value.map((item) => String(item).trim()).filter(Boolean) : [];
return { recap, actionItems: list(parsed.actionItems), facts: list(parsed.facts) };
} catch {
return null;
}
}
+311
View File
@@ -0,0 +1,311 @@
import { Utils } from "@nativescript/core";
import { encodeBase64 } from "../../native/cloud-stt";
import { toUint8Array } from "../../util/array-util";
import { micModelPath } from "./mic-models";
import { wearerCommandsOnlySetting } from "./mic-settings";
declare const com: any;
declare const android: any;
/**
* Speaker voice-print registry over FaceclawConversationStore. Matching is
* cosine similarity on L2-normalized embeddings: >= 0.80 auto-assign ("known"), 0.50-0.80 "uncertain" (assigned
* but flagged for review), below that a new speaker is enrolled. Centroids
* update as a capped running mean so one long session cannot drown an
* enrolled voice.
*/
export const SPEAKER_KNOWN_THRESHOLD = 0.8;
export const SPEAKER_UNCERTAIN_THRESHOLD = 0.5;
/** Cap on the running-mean weight of an existing centroid. */
export const CENTROID_UPDATE_CAP = 24;
const SPEAKER_COLORS = [
"#4FC3F7",
"#FFB74D",
"#81C784",
"#E57373",
"#BA68C8",
"#FFD54F",
"#4DB6AC",
"#F06292",
"#A1887F",
"#90A4AE",
];
export type SpeakerProfile = {
id: number;
name: string;
color: string;
isWearer: boolean;
embedding: Float32Array | null;
embeddingCount: number;
lastHeardAt: number;
tag: string;
segmentCount: number;
/** LLM recap of this speaker's most recent conversation ("" until one is generated). */
lastRecap: string;
/** Open action items from that conversation. */
actionItems: string[];
/** Accumulated inferred facts about this person. */
facts: string[];
insightsUpdatedAt: number;
insightsSessionId: number;
};
export type SpeakerMatch = {
profile: SpeakerProfile;
similarity: number;
classification: "known" | "uncertain" | "new";
/**
* The profile's last_heard_at BEFORE this utterance updated it — i.e. when
* this person's voice was previously heard. 0 for a newly enrolled speaker.
*/
previousLastHeardAt: number;
};
function store(): any {
const context = Utils.android.getApplicationContext();
return com.faceclaw.app.FaceclawConversationStore.getInstance(context);
}
/** Parse a stored JSON string array leniently; anything malformed reads as empty. */
function parseStringArray(json: unknown): string[] {
try {
const parsed = JSON.parse(String(json || "[]"));
return Array.isArray(parsed) ? parsed.map((item) => String(item)).filter(Boolean) : [];
} catch {
return [];
}
}
function decodeEmbedding(base64: string): Float32Array | null {
if (!base64) return null;
try {
const bytes = toUint8Array(android.util.Base64.decode(base64, android.util.Base64.NO_WRAP));
if (bytes.length < 4 || bytes.length % 4 !== 0) return null;
return new Float32Array(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.length));
} catch {
return null;
}
}
export function encodeEmbedding(embedding: Float32Array): string {
return encodeBase64(new Uint8Array(embedding.buffer, embedding.byteOffset, embedding.byteLength));
}
export function cosineSimilarity(a: Float32Array, b: Float32Array): number {
if (a.length !== b.length || a.length === 0) return 0;
let dot = 0;
for (let i = 0; i < a.length; i++) dot += a[i]! * b[i]!;
// Embeddings are L2-normalized at the source, so the dot product is the
// cosine; renormalizing here would only amplify float noise.
return dot;
}
export class SpeakerRegistry {
private profiles: SpeakerProfile[] = [];
private loaded = false;
private readonly changeListeners = new Set<() => void>();
onChanged(listener: () => void): () => void {
this.changeListeners.add(listener);
return () => this.changeListeners.delete(listener);
}
private notifyChanged(): void {
this.changeListeners.forEach((listener) => listener());
}
reload(): void {
try {
const rows = JSON.parse(String(store().querySpeakers())) as Array<Record<string, unknown>>;
this.profiles = rows.map((row) => ({
id: Number(row.id),
name: String(row.name ?? ""),
color: String(row.color ?? SPEAKER_COLORS[0]),
isWearer: Boolean(row.isWearer),
embedding: decodeEmbedding(String(row.embeddingBase64 ?? "")),
embeddingCount: Number(row.embeddingCount ?? 0),
lastHeardAt: Number(row.lastHeardAt ?? 0),
tag: String(row.tag ?? ""),
segmentCount: Number(row.segmentCount ?? 0),
lastRecap: String(row.lastRecap ?? ""),
actionItems: parseStringArray(row.actionItemsJson),
facts: parseStringArray(row.factsJson),
insightsUpdatedAt: Number(row.insightsUpdatedAt ?? 0),
insightsSessionId: Number(row.insightsSessionId ?? 0),
}));
this.loaded = true;
} catch (error) {
console.error(`speaker reload failed: ${String(error)}`);
this.profiles = [];
}
}
all(): SpeakerProfile[] {
if (!this.loaded) this.reload();
return this.profiles;
}
byId(id: number): SpeakerProfile | null {
return this.all().find((profile) => profile.id === id) ?? null;
}
wearer(): SpeakerProfile | null {
return this.all().find((profile) => profile.isWearer) ?? null;
}
/** Best cosine match against every enrolled profile, or null when none have prints. */
bestMatch(embedding: Float32Array): { profile: SpeakerProfile; similarity: number } | null {
let best: { profile: SpeakerProfile; similarity: number } | null = null;
for (const profile of this.all()) {
if (!profile.embedding || profile.embedding.length !== embedding.length) continue;
const similarity = cosineSimilarity(embedding, profile.embedding);
if (!best || similarity > best.similarity) {
best = { profile, similarity };
}
}
return best;
}
/**
* Match an utterance's voice-print to a profile, enrolling a new
* "Speaker N" when nothing crosses the uncertain threshold. Known and
* uncertain matches also fold the print into the centroid.
*/
assign(embedding: Float32Array): SpeakerMatch {
const best = this.bestMatch(embedding);
if (best && best.similarity >= SPEAKER_UNCERTAIN_THRESHOLD) {
const previousLastHeardAt = best.profile.lastHeardAt;
store().updateSpeakerEmbedding(best.profile.id, encodeEmbedding(embedding), CENTROID_UPDATE_CAP);
this.reload();
const profile = this.byId(best.profile.id) ?? best.profile;
return {
profile,
similarity: best.similarity,
classification: best.similarity >= SPEAKER_KNOWN_THRESHOLD ? "known" : "uncertain",
previousLastHeardAt,
};
}
const name = this.nextAutoName();
const color = SPEAKER_COLORS[this.all().length % SPEAKER_COLORS.length]!;
const id = Number(store().createSpeaker(name, color, false, encodeEmbedding(embedding)));
this.reload();
this.notifyChanged();
const profile = this.byId(id)!;
return { profile, similarity: best?.similarity ?? 0, classification: "new", previousLastHeardAt: 0 };
}
private nextAutoName(): string {
const taken = new Set(this.all().map((profile) => profile.name));
for (let index = 1; ; index++) {
const candidate = `Speaker ${index}`;
if (!taken.has(candidate)) return candidate;
}
}
/** Enroll (or refresh) the wearer's own voice from a training utterance. */
enrollWearer(embedding: Float32Array): SpeakerProfile {
const existing = this.wearer();
if (existing) {
store().updateSpeakerEmbedding(existing.id, encodeEmbedding(embedding), CENTROID_UPDATE_CAP);
this.reload();
this.notifyChanged();
return this.byId(existing.id)!;
}
const id = Number(store().createSpeaker("Me", "#64B5F6", true, encodeEmbedding(embedding)));
this.reload();
this.notifyChanged();
return this.byId(id)!;
}
/** Is this utterance the wearer's own voice? Used to gate command recognition. */
isWearerVoice(embedding: Float32Array): boolean {
const wearer = this.wearer();
if (!wearer?.embedding || wearer.embedding.length !== embedding.length) return false;
return cosineSimilarity(embedding, wearer.embedding) >= SPEAKER_KNOWN_THRESHOLD;
}
rename(id: number, name: string): void {
store().renameSpeaker(id, name);
this.reload();
this.notifyChanged();
}
setColor(id: number, color: string): void {
store().setSpeakerColor(id, color);
this.reload();
this.notifyChanged();
}
setTag(id: number, tag: string): void {
store().setSpeakerTag(id, tag);
this.reload();
this.notifyChanged();
}
/** Store LLM-derived insights: recap + action items of `sessionId`, merged fact list. */
setInsights(id: number, recap: string, actionItems: string[], facts: string[], sessionId: number): void {
store().setSpeakerInsights(id, recap, JSON.stringify(actionItems), JSON.stringify(facts), sessionId);
this.reload();
this.notifyChanged();
}
setWearer(id: number, isWearer: boolean): void {
store().setSpeakerWearer(id, isWearer);
this.reload();
this.notifyChanged();
}
merge(fromId: number, intoId: number): void {
store().mergeSpeakers(fromId, intoId);
this.reload();
this.notifyChanged();
}
/**
* Split support: give one session's segments of a speaker their own new
* profile (e.g. when two people were fused into one). Returns the new id.
*/
splitFromSession(sessionId: number, speakerId: number): number {
const source = this.byId(speakerId);
const name = this.nextAutoName();
const color = SPEAKER_COLORS[this.all().length % SPEAKER_COLORS.length]!;
const newId = Number(store().createSpeaker(name, color, false, ""));
store().reassignSessionSpeaker(sessionId, speakerId, newId);
if (source) {
this.reload();
}
this.notifyChanged();
return newId;
}
remove(id: number): void {
store().deleteSpeaker(id);
this.reload();
this.notifyChanged();
}
}
export const speakerRegistry = new SpeakerRegistry();
/**
* The speaker-verification config for "my voice only" command gating, or
* null when the setting is off, no wearer voice is enrolled, or the speaker
* model isn't downloaded. Consumed by the voice-capture path so assistant /
* dictation commands from other speakers are discarded.
*/
export function wearerVerificationOptions(): {
speakerModelPath: string;
wearerEmbedding: Float32Array;
threshold: number;
} | null {
if (!wearerCommandsOnlySetting.get()) return null;
const wearer = speakerRegistry.wearer();
if (!wearer?.embedding) return null;
const speakerModelPath = micModelPath("speaker-embedding");
if (!speakerModelPath) return null;
return { speakerModelPath, wearerEmbedding: wearer.embedding, threshold: SPEAKER_KNOWN_THRESHOLD };
}
+124
View File
@@ -0,0 +1,124 @@
declare const com: any;
declare const java: any;
/**
* On-device language identification and translation for captions, over ML
* Kit (bundled language-id, per-pair translation models downloaded on
* demand). Foreign-language captions show the original line with the
* translation to the phone's default language beneath it.
*/
let languageIdentifier: any | null = null;
// Translators are expensive to build (model download on first use); cache by
// "src>dst" and keep the proxies referenced so they aren't GC'd mid-flight.
const translators = new Map<string, any>();
const downloadedPairs = new Set<string>();
/** The phone's default language as a two-letter code (the translation target). */
export function deviceLanguage(): string {
if (!global.isAndroid) return "en";
try {
return String(java.util.Locale.getDefault().getLanguage() || "en");
} catch {
return "en";
}
}
function successListener(resolve: (value: any) => void): any {
return new com.google.android.gms.tasks.OnSuccessListener({
onSuccess: (result: any) => resolve(result),
});
}
function failureListener(reject: (reason: Error) => void): any {
return new com.google.android.gms.tasks.OnFailureListener({
onFailure: (error: any) => reject(new Error(String(error?.getMessage?.() ?? error))),
});
}
/**
* Identify the language of a caption line. Resolves to a BCP-47 code, or
* "und" when ML Kit isn't confident. Short lines are noisy; callers should
* apply hysteresis across consecutive finals before switching languages.
*/
export function identifyLanguage(text: string): Promise<string> {
if (!global.isAndroid || !text.trim()) return Promise.resolve("und");
return new Promise((resolve) => {
try {
if (!languageIdentifier) {
languageIdentifier = com.google.mlkit.nl.languageid.LanguageIdentification.getClient();
}
languageIdentifier
.identifyLanguage(text)
.addOnSuccessListener(successListener((code: any) => resolve(String(code))))
.addOnFailureListener(failureListener(() => resolve("und")));
} catch (error) {
console.warn(`language id failed: ${error}`);
resolve("und");
}
});
}
function translatorFor(sourceLang: string, targetLang: string): any | null {
const key = `${sourceLang}>${targetLang}`;
const cached = translators.get(key);
if (cached) return cached;
try {
const TranslateLanguage = com.google.mlkit.nl.translate.TranslateLanguage;
const source = TranslateLanguage.fromLanguageTag(sourceLang);
const target = TranslateLanguage.fromLanguageTag(targetLang);
if (source == null || target == null) return null;
const options = new com.google.mlkit.nl.translate.TranslatorOptions.Builder()
.setSourceLanguage(source)
.setTargetLanguage(target)
.build();
const translator = com.google.mlkit.nl.translate.Translation.getClient(options);
translators.set(key, translator);
return translator;
} catch (error) {
console.warn(`translator setup failed (${key}): ${error}`);
return null;
}
}
/**
* Translate one caption line. Resolves to the translated text, or "" when the
* pair is unsupported or the model download hasn't finished (translation of
* later lines picks up once it has; downloads are WiFi-unrestricted since
* caption sessions are live).
*/
export function translateText(text: string, sourceLang: string, targetLang: string): Promise<string> {
if (!global.isAndroid || !text.trim() || sourceLang === targetLang) {
return Promise.resolve("");
}
const translator = translatorFor(sourceLang, targetLang);
if (!translator) return Promise.resolve("");
const key = `${sourceLang}>${targetLang}`;
return new Promise((resolve) => {
const runTranslate = () => {
translator
.translate(text)
.addOnSuccessListener(successListener((result: any) => resolve(String(result))))
.addOnFailureListener(failureListener(() => resolve("")));
};
if (downloadedPairs.has(key)) {
runTranslate();
return;
}
try {
const conditions = new com.google.mlkit.common.model.DownloadConditions.Builder().build();
translator
.downloadModelIfNeeded(conditions)
.addOnSuccessListener(
successListener(() => {
downloadedPairs.add(key);
runTranslate();
}),
)
.addOnFailureListener(failureListener(() => resolve("")));
} catch (error) {
console.warn(`translation model download failed (${key}): ${error}`);
resolve("");
}
});
}