Files
photoreport/apps/api/src/faces/process.ts
T
spark ac88d2445d
ci / rust (pull_request) Successful in 12m25s
ci / typescript (pull_request) Failing after 14m4s
Recognize a player from the club they were at that season.
The same person keeps one record when they change club, and the shirt number stays the one worn that season. Liga squads are read for every season still published, and face processes grow until the CPU is about 99% full.
2026-10-21 20:37:41 +01:00

168 lines
4.7 KiB
TypeScript

import { cpus } from "node:os";
import { LeastBusy, LineProcess } from "../lib/line-process.js";
/** Stop adding face processes once the machine is this full. One percent stays free for the rest of the system. */
const CPU_TARGET = 0.99;
interface CpuTimes {
idle: number;
total: number;
}
function cpuTimes(): CpuTimes {
let idle = 0;
let total = 0;
for (const cpu of cpus()) {
const t = cpu.times;
idle += t.idle;
total += t.user + t.nice + t.sys + t.idle + t.irq;
}
return { idle, total };
}
export interface DetectedFace {
x0: number;
y0: number;
x1: number;
y1: number;
score: number;
/** Variance of the Laplacian of the aligned face; absent from older workers. */
sharpness?: number | null;
landmarks: [number, number][];
embedding: number[] | null;
}
export interface FaceAnalysis {
width: number;
height: number;
faces: DetectedFace[];
}
export interface FaceEngine {
readonly model: string;
analyse(path: string): Promise<FaceAnalysis>;
close(): Promise<void>;
}
export const MODEL_IDS = { auraface: "auraface-v1", sface: "sface-2021dec" } as const;
export type EmbedderName = keyof typeof MODEL_IDS;
/**
* The Rust face worker (`workers/faces`), kept running: one photo at a time over stdin/stdout. Restarts after a
* crash; a request that hangs is failed after `timeoutMs`.
*/
export class FaceProcess implements FaceEngine {
readonly model: string;
private readonly proc: LineProcess;
constructor(opts: { bin: string; modelsDir: string; embedder: EmbedderName; minScore?: number; timeoutMs?: number }) {
this.model = MODEL_IDS[opts.embedder];
this.proc = new LineProcess({
name: "face worker",
bin: opts.bin,
args: ["--models", opts.modelsDir, "--embedder", opts.embedder, "--min-score", String(opts.minScore ?? 0.6)],
timeoutMs: opts.timeoutMs ?? 120_000,
});
}
async analyse(path: string): Promise<FaceAnalysis> {
const msg = (await this.proc.request({ path })) as Partial<FaceAnalysis>;
return { width: msg.width ?? 0, height: msg.height ?? 0, faces: msg.faces ?? [] };
}
close(): Promise<void> {
return this.proc.close();
}
}
/** Several face processes behind one engine; each request goes to the least busy one. */
export class FacePool implements FaceEngine {
readonly model: string;
private readonly pool: LeastBusy<FaceEngine>;
constructor(private readonly engines: FaceEngine[]) {
this.pool = new LeastBusy(engines);
this.model = engines[0]!.model;
}
analyse(path: string): Promise<FaceAnalysis> {
return this.pool.use((e) => e.analyse(path));
}
async close(): Promise<void> {
await Promise.all(this.engines.map((e) => e.close()));
}
}
/**
* Face processes that start a few at a time and keep being added while the CPU is under {@link CPU_TARGET}.
* Each process is one core. `cap` is the most this machine should run.
*/
export class GrowingFacePool implements FaceEngine {
readonly model: string;
private readonly engines: FaceEngine[] = [];
private readonly busy: number[] = [];
private last: CpuTimes = cpuTimes();
private lastGrow = 0;
constructor(
private readonly make: () => FaceEngine,
private readonly cap: number,
) {
const first = make();
this.model = first.model;
this.engines.push(first);
this.busy.push(0);
this.add(Math.min(3, Math.max(0, cap - 1)));
}
get size(): number {
return this.engines.length;
}
private add(count: number): void {
const room = Math.max(0, this.cap - this.engines.length);
const n = Math.min(count, room);
for (let i = 0; i < n; i++) {
this.engines.push(this.make());
this.busy.push(0);
}
}
/** Add more processes when every current one is busy and the CPU is not full yet. */
private grow(): void {
if (this.engines.length >= this.cap) return;
const now = Date.now();
if (now - this.lastGrow < 1500) return;
const allBusy = this.busy.every((n) => n > 0);
if (!allBusy && this.engines.length >= 4) return;
const sample = cpuTimes();
const idle = sample.idle - this.last.idle;
const total = sample.total - this.last.total;
this.last = sample;
const used = total > 0 ? 1 - idle / total : 0;
if (used >= CPU_TARGET) return;
const step = Math.max(2, Math.floor(this.engines.length / 2));
this.add(step);
this.lastGrow = now;
}
async analyse(path: string): Promise<FaceAnalysis> {
this.grow();
let index = 0;
for (let i = 1; i < this.busy.length; i++) {
if (this.busy[i]! < this.busy[index]!) index = i;
}
this.busy[index]!++;
try {
return await this.engines[index]!.analyse(path);
} finally {
this.busy[index]!--;
}
}
async close(): Promise<void> {
await Promise.all(this.engines.map((e) => e.close()));
}
}