Spaces:
Running
Running
Deploy 5e985bf từ GitHub Actions
Browse filesFiles changed (7)
- passport-check/apps/server/src/bench.tsAdded+261
- passport-check/apps/server/src/index.ts+6
- passport-check/apps/server/src/jobs.ts+11-2
- passport-check/apps/server/src/ocr.ts+43-28
- passport-check/apps/web/src/components/BenchPanel.tsxAdded+175
- passport-check/apps/web/src/components/TestTools.tsx+3
- passport-check/apps/web/src/lib/api.ts+24
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261/** * Benchmark OCR cho admin (trang Kiểm tra): chạy cùng 1 mẫu ảnh ngẫu nhiên trong hệ thống ở nhiều mức song song * (1, 2, 3, 4 ảnh cùng lúc), đo thời gian / ảnh, thông lượng, CPU, RAM để chọn OCR_CONCURRENCY / OCR_WORKERS. * * - Chỉ đo phần OCR (CPU). Gemini là chờ mạng, chạy ở hàng đợi riêng nên không đưa vào phép đo. * - Ảnh gốc được tải + giải mã trước khi đo (không tính thời gian tải từ Telegram). * - Mỗi mức dùng pool tesseract riêng đúng bằng số ảnh song song, tạo sẵn worker trước khi bấm giờ. * - Trong lúc đo, hàng đợi OCR thật bị tạm dừng (ảnh mới vẫn nhận, xử lý tiếp khi đo xong). Không ghi gì vào Firestore. */import fs from 'node:fs';import os from 'node:os';import { reconcile, mergeResults, runPipeline } from '@pc/core';import { allItems, batchById, loadOriginal, ocrBusy, queueConfig, setOcrPaused } from './jobs.ts';import { createTessEngine, loadImage, ocrWorkers, sharpOps, type Img } from './ocr.ts';
export interface BenchImage { batchId: string; itemId: string; name: string; batchName: string }export interface BenchRun { itemId: string; ms: number; deep: boolean; confidence?: string; error?: string }export interface BenchLevel { concurrency: number; wallMs: number; /** ảnh / phút */ throughput: number; avgMs: number; p50Ms: number; maxMs: number; /** % CPU của cả process (100% = 1 core bận kín) */ cpuPct: number; peakRssMb: number; deepCount: number; errors: number; runs: BenchRun[];}export interface BenchEnv { cpus: number; /** số core thực được cấp theo cgroup (container), null = không giới hạn / không đọc được */ cgroupCpus: number | null; totalMemMb: number; cgroupMemMb: number | null; loadAvg: number[]; node: string; ocrConcurrency: number; ocrWorkers: number; llmConcurrency: number;}export interface BenchState { status: 'idle' | 'preparing' | 'running' | 'done' | 'cancelled' | 'error'; params?: { levels: number[]; images: number; deep: boolean }; startedAt?: number; finishedAt?: number; env: BenchEnv; sample: BenchImage[]; levels: BenchLevel[]; current?: { concurrency: number; done: number; total: number; step: string }; error?: string; /** thời gian xử lý thực tế (OCR + Gemini, tính từ lúc bắt đầu OCR) của các ảnh gần đây, để so sánh */ history: { count: number; avgMs: number; p50Ms: number; withLlm: number } | null; recommendation?: { concurrency: number; reason: string; env: string[] };}
let state: BenchState = { status: 'idle', env: readEnv(), sample: [], levels: [], history: null };let cancel = false;
function readNum(file: string): string | null { try { return fs.readFileSync(file, 'utf8').trim(); } catch { return null; }}
function cgroupCpus(): number | null { const v2 = readNum('/sys/fs/cgroup/cpu.max'); if (v2) { const [q, p] = v2.split(/\s+/); return q === 'max' ? null : Math.round((Number(q) / Number(p)) * 100) / 100; } const q = Number(readNum('/sys/fs/cgroup/cpu/cpu.cfs_quota_us')); const p = Number(readNum('/sys/fs/cgroup/cpu/cpu.cfs_period_us')); return q > 0 && p > 0 ? Math.round((q / p) * 100) / 100 : null;}
function cgroupMemMb(): number | null { const v = readNum('/sys/fs/cgroup/memory.max') ?? readNum('/sys/fs/cgroup/memory/memory.limit_in_bytes'); const n = Number(v); // v1 trả số cực lớn khi không giới hạn return v && v !== 'max' && n > 0 && n < 2 ** 50 ? Math.round(n / 2 ** 20) : null;}
function readEnv(): BenchEnv { const q = queueConfig(); return { cpus: os.cpus().length, cgroupCpus: cgroupCpus(), totalMemMb: Math.round(os.totalmem() / 2 ** 20), cgroupMemMb: cgroupMemMb(), loadAvg: os.loadavg().map((x) => Math.round(x * 100) / 100), node: process.version, ocrConcurrency: q.ocrConcurrency, ocrWorkers: ocrWorkers(), llmConcurrency: q.llmConcurrency, };}
const median = (xs: number[]) => { if (!xs.length) return 0; const s = [...xs].sort((a, b) => a - b); const m = s.length >> 1; return s.length % 2 ? s[m] : Math.round((s[m - 1] + s[m]) / 2);};const avg = (xs: number[]) => (xs.length ? Math.round(xs.reduce((a, b) => a + b, 0) / xs.length) : 0);
function historyStats(): BenchState['history'] { const done = allItems() .filter((i) => i.status === 'done' && typeof i.ms === 'number' && i.ms > 0) .sort((a, b) => (b.updatedAt ?? 0) - (a.updatedAt ?? 0)) .slice(0, 100); if (!done.length) return null; const ms = done.map((i) => i.ms!); return { count: done.length, avgMs: avg(ms), p50Ms: median(ms), withLlm: done.filter((i) => i.result?.sources?.includes('llm')).length };}
export function benchState(): BenchState { if (state.status !== 'running' && state.status !== 'preparing') state = { ...state, env: readEnv(), history: historyStats() }; return state;}
export function cancelBench() { if (state.status === 'running' || state.status === 'preparing') cancel = true; return state;}
/** Chọn ngẫu nhiên `n` ảnh đã xử lý xong và còn ảnh gốc trên Storage */function pickSample(n: number): BenchImage[] { const pool = allItems().filter((i) => i.status === 'done' && i.telegram); for (let i = pool.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [pool[i], pool[j]] = [pool[j], pool[i]]; } return pool.slice(0, n).map((i) => ({ batchId: i.batchId, itemId: i.id, name: i.name, batchName: batchById(i.batchId)?.name ?? i.batchId }));}
const bad = (status: number, message: string) => Object.assign(new Error(message), { status });
export function startBench(input: { levels?: unknown; images?: unknown; deep?: unknown }): BenchState { if (state.status === 'running' || state.status === 'preparing') throw bad(409, 'Benchmark đang chạy'); const busy = ocrBusy(); if (busy.running || busy.waiting) { throw bad(409, `Hàng đợi OCR đang bận (${busy.running} ảnh đang xử lý, ${busy.waiting} ảnh chờ) — đợi xử lý xong rồi chạy để số đo chính xác`); } const levels = [...new Set((Array.isArray(input.levels) ? input.levels : [1, 2, 3, 4]).map(Number))] .filter((n) => Number.isInteger(n) && n >= 1 && n <= 8) .sort((a, b) => a - b); if (!levels.length) throw bad(400, 'Chọn ít nhất 1 mức song song (1–8)'); const images = Math.min(24, Math.max(1, Math.floor(Number(input.images ?? 8)) || 8)); const deep = input.deep !== false; const sample = pickSample(images); if (!sample.length) throw bad(400, 'Chưa có ảnh nào đã xử lý xong trong hệ thống để làm mẫu');
cancel = false; state = { status: 'preparing', params: { levels, images: sample.length, deep }, startedAt: Date.now(), env: readEnv(), sample, levels: [], history: historyStats(), }; setOcrPaused(true); void run(levels, sample, deep).finally(() => setOcrPaused(false)); return state;}
async function run(levels: number[], sample: BenchImage[], deep: boolean) { try { // tải + giải mã ảnh trước, không tính vào phép đo const imgs: { meta: BenchImage; img: Img }[] = []; for (let i = 0; i < sample.length; i++) { if (cancel) return finish('cancelled'); state = { ...state, current: { concurrency: 0, done: i, total: sample.length, step: `Tải ảnh mẫu ${i + 1}/${sample.length}` } }; const it = allItems().find((x) => x.id === sample[i].itemId); if (!it) continue; imgs.push({ meta: sample[i], img: await loadImage(await loadOriginal(it)) }); } state = { ...state, status: 'running' };
for (const c of levels) { if (cancel) return finish('cancelled'); const level = await runLevel(c, imgs, deep); state = { ...state, levels: [...state.levels, level] }; } finish(cancel ? 'cancelled' : 'done'); } catch (e) { console.error('bench error', e); finish('error', (e as Error).message); }}
function finish(status: BenchState['status'], error?: string) { state = { ...state, status, error, current: undefined, finishedAt: Date.now(), env: readEnv(), recommendation: recommend(state.levels) };}
async function runLevel(c: number, imgs: { meta: BenchImage; img: Img }[], deep: boolean): Promise<BenchLevel> { const step = (s: string, done: number) => (state = { ...state, current: { concurrency: c, done, total: imgs.length, step: s } }); step(`Mức ${c}: tạo ${c} worker`, 0); const tess = createTessEngine(c); try { await tess.warmup(); const runs: BenchRun[] = []; let peakRss = process.memoryUsage().rss; const sampler = setInterval(() => { peakRss = Math.max(peakRss, process.memoryUsage().rss); }, 250); const cpu0 = process.cpuUsage(); const t0 = Date.now(); let next = 0; const worker = async () => { while (!cancel && next < imgs.length) { const { meta, img } = imgs[next++]; const t = Date.now(); try { const fast = await runPipeline(img, sharpOps, tess.engine, { thorough: false }); let result = reconcile({ mrz: fast.mrz, viz: fast.viz, sources: ['local'] }); let usedDeep = false; if (deep && result.confidence !== 'HIGH') { usedDeep = true; const d = await runPipeline(img, sharpOps, tess.engine, { thorough: true }); result = mergeResults(result, { mrz: d.mrz, viz: d.viz, source: 'server-ocr' }); } runs.push({ itemId: meta.itemId, ms: Date.now() - t, deep: usedDeep, confidence: result.confidence }); } catch (e) { runs.push({ itemId: meta.itemId, ms: Date.now() - t, deep: false, error: (e as Error).message }); } step(`Mức ${c} ảnh song song`, runs.length); } }; step(`Mức ${c} ảnh song song`, 0); await Promise.all(Array.from({ length: Math.min(c, imgs.length) }, worker)); const wallMs = Date.now() - t0; clearInterval(sampler); const cpu = process.cpuUsage(cpu0); const ok = runs.filter((r) => !r.error).map((r) => r.ms); return { concurrency: c, wallMs, throughput: Math.round((runs.length / (wallMs / 60000)) * 100) / 100, avgMs: avg(ok), p50Ms: median(ok), maxMs: ok.length ? Math.max(...ok) : 0, cpuPct: Math.round(((cpu.user + cpu.system) / 1000 / wallMs) * 100), peakRssMb: Math.round(peakRss / 2 ** 20), deepCount: runs.filter((r) => r.deep).length, errors: runs.filter((r) => r.error).length, runs, }; } finally { await tess.shutdown(); }}
/** Mức nhỏ nhất đạt ≥ 95% thông lượng cao nhất (thêm song song mà không nhanh hơn thì chỉ làm từng ảnh chậm đi) */function recommend(levels: BenchLevel[]): BenchState['recommendation'] { const full = levels.filter((l) => l.runs.length && !l.errors); if (!full.length) return undefined; const best = Math.max(...full.map((l) => l.throughput)); const pick = full.find((l) => l.throughput >= best * 0.95)!; const top = full.find((l) => l.throughput === best)!; const reason = pick === top ? `Mức ${pick.concurrency} cho thông lượng cao nhất (${pick.throughput} ảnh/phút, ${(pick.p50Ms / 1000).toFixed(1)}s/ảnh).` : `Mức ${top.concurrency} nhanh nhất (${top.throughput} ảnh/phút) nhưng mức ${pick.concurrency} đã đạt ${pick.throughput} ảnh/phút (≥95%) với thời gian mỗi ảnh ngắn hơn (${(pick.p50Ms / 1000).toFixed(1)}s so với ${(top.p50Ms / 1000).toFixed(1)}s).`; return { concurrency: pick.concurrency, reason, env: [`OCR_CONCURRENCY=${pick.concurrency}`, `OCR_WORKERS=${pick.concurrency}`] };}16 unmodified lines171819202122187 unmodified lines21021121221321421516 unmodified linesimport busboy from 'busboy';import { batchTokens, currentRule, fixedTokens, formulaInfo, itemTokens, usageReport, actualReport } from './tokens.ts';import { receiveUpload } from './upload.ts';import {allItems, batchById, cacheReady, createBatch, deleteItem, getBatch, getItem, ingest, listBatches, listItems, liveStatus, loadOriginal, recover,knownHashes, rerun, rerunMany, saveEdit, updateBatchInfo,187 unmodified lines}}));/** Test đăng nhập Google: xác minh ID token, báo từng vấn đề; không tạo phiên */api.post('/test/google', requireAdmin, json, h(async (req, res) => {res.json(await diagnoseGoogle(req.body?.idToken));16 unmodified lines17181920212223187 unmodified lines21121221321421521621721821922022116 unmodified linesimport busboy from 'busboy';import { batchTokens, currentRule, fixedTokens, formulaInfo, itemTokens, usageReport, actualReport } from './tokens.ts';import { receiveUpload } from './upload.ts';import { benchState, cancelBench, startBench } from './bench.ts';import {allItems, batchById, cacheReady, createBatch, deleteItem, getBatch, getItem, ingest, listBatches, listItems, liveStatus, loadOriginal, recover,knownHashes, rerun, rerunMany, saveEdit, updateBatchInfo,187 unmodified lines}}));/** Benchmark OCR: chạy mẫu ảnh ngẫu nhiên ở các mức song song 1..4 để chọn OCR_CONCURRENCY (chạy nền, client poll GET) */api.get('/test/bench', requireAdmin, (_req, res) => void res.json(benchState()));api.post('/test/bench', requireAdmin, json, h(async (req, res) => res.json(startBench(req.body ?? {}))));api.delete('/test/bench', requireAdmin, (_req, res) => void res.json(cancelBench()));/** Test đăng nhập Google: xác minh ID token, báo từng vấn đề; không tạo phiên */api.post('/test/google', requireAdmin, json, h(async (req, res) => {res.json(await diagnoseGoogle(req.body?.idToken));
276 unmodified lines27727827928028128228328428528654 unmodified lines341342343344345346347276 unmodified lineslet tgRunning = false;let ocrRunning = 0;let llmRunning = 0;function kick() {if (!tgRunning && tgQueue.length) void runTelegram();while (ocrRunning < OCR_CONCURRENCY && ocrQueue.length) void runOcr();while (llmRunning < LLM_CONCURRENCY && llmQueue.length) void runLlm();}54 unmodified linesasync function runOcr() {ocrRunning++;try {while (ocrQueue.length) {const task = ocrQueue.shift()!;const { batchId, itemId, force } = task;const step = (s: string) => live.set(itemId, { batchId, step: s });276 unmodified lines27727827928028128228328428528628728828929029129229329429554 unmodified lines350351352353354355356276 unmodified lineslet tgRunning = false;let ocrRunning = 0;let llmRunning = 0;/** benchmark đang chạy: giữ ảnh mới trong hàng đợi OCR để không làm sai phép đo */let ocrPaused = false;export const queueConfig = () => ({ ocrConcurrency: OCR_CONCURRENCY, llmConcurrency: LLM_CONCURRENCY });export const ocrBusy = () => ({ running: ocrRunning, waiting: ocrQueue.length, llmRunning, llmWaiting: llmQueue.length });export function setOcrPaused(v: boolean) {ocrPaused = v;if (!v) kick();}function kick() {if (!tgRunning && tgQueue.length) void runTelegram();while (!ocrPaused && ocrRunning < OCR_CONCURRENCY && ocrQueue.length) void runOcr();while (llmRunning < LLM_CONCURRENCY && llmQueue.length) void runLlm();}54 unmodified linesasync function runOcr() {ocrRunning++;try {while (!ocrPaused && ocrQueue.length) {const task = ocrQueue.shift()!;const { batchId, itemId, force } = task;const step = (s: string) => live.set(itemId, { batchId, step: s });
49 unmodified lines50515253545556575859606162636465666768697071727374757677787980818283848586878849 unmodified linesconst TESSDATA = process.env.TESSDATA_DIR ?? new URL('../../../tessdata', import.meta.url).pathname;const POOL_SIZE = Number(process.env.OCR_WORKERS ?? Math.max(1, Math.min(2, os.cpus().length)));const pool = createWorkerPool<Worker>({size: POOL_SIZE,maxNative: 3,create: (lang) => createWorker(lang, 1, { langPath: TESSDATA, gzip: true, cacheMethod: 'none' }),terminate: (w) => w.terminate(),});const THRESH = { otsu: '0', adaptive: '1', sauvola: '2' } as const;export const tessEngine: OcrEngine<Img> = {async recognize(img, opts: OcrOptions) {const w = await pool.acquire(opts.lang);try {await w.setParameters({tessedit_pageseg_mode: opts.psm as never,tessedit_char_whitelist: opts.whitelist ?? '',user_defined_dpi: '300',thresholding_method: THRESH[opts.threshold ?? 'otsu'] as never,});const { data } = await w.recognize(img.data, {}, { text: true, blocks: true });const lines: OcrLine[] = [];for (const b of data.blocks ?? []) for (const p of b.paragraphs) for (const l of p.lines) {const b = l.baseline;const angle = b && b.x1 !== b.x0 ? (Math.atan2(b.y1 - b.y0, b.x1 - b.x0) * 180) / Math.PI : undefined;lines.push({ text: l.text.trim(), bbox: l.bbox, confidence: l.confidence, angle });}return { text: data.text, lines, confidence: data.confidence };} finally {pool.release(opts.lang, w);}},};export async function shutdownOcr() {await pool.shutdown();}49 unmodified lines505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210349 unmodified linesconst TESSDATA = process.env.TESSDATA_DIR ?? new URL('../../../tessdata', import.meta.url).pathname;const POOL_SIZE = Number(process.env.OCR_WORKERS ?? Math.max(1, Math.min(2, os.cpus().length)));export const ocrWorkers = () => POOL_SIZE;const THRESH = { otsu: '0', adaptive: '1', sauvola: '2' } as const;/** Engine tesseract với pool riêng `size` worker / ngôn ngữ chính (benchmark dùng pool riêng để không đụng hàng đợi thật) */export function createTessEngine(size: number) {const pool = createWorkerPool<Worker>({size,maxNative: 3,create: (lang) => createWorker(lang, 1, { langPath: TESSDATA, gzip: true, cacheMethod: 'none' }),terminate: (w) => w.terminate(),});const engine: OcrEngine<Img> = {async recognize(img, opts: OcrOptions) {const w = await pool.acquire(opts.lang);try {await w.setParameters({tessedit_pageseg_mode: opts.psm as never,tessedit_char_whitelist: opts.whitelist ?? '',user_defined_dpi: '300',thresholding_method: THRESH[opts.threshold ?? 'otsu'] as never,});const { data } = await w.recognize(img.data, {}, { text: true, blocks: true });const lines: OcrLine[] = [];for (const b of data.blocks ?? []) for (const p of b.paragraphs) for (const l of p.lines) {const b = l.baseline;const angle = b && b.x1 !== b.x0 ? (Math.atan2(b.y1 - b.y0, b.x1 - b.x0) * 180) / Math.PI : undefined;lines.push({ text: l.text.trim(), bbox: l.bbox, confidence: l.confidence, angle });}return { text: data.text, lines, confidence: data.confidence };} finally {pool.release(opts.lang, w);}},};/** tạo sẵn `size` worker cho mỗi ngôn ngữ chính (không tính thời gian tải model vào phép đo) */const warmup = async (langs = ['mrz', 'eng']) => {for (const lang of langs) {const ws = await Promise.all(Array.from({ length: size }, () => pool.acquire(lang)));for (const w of ws) pool.release(lang, w);}};return { engine, warmup, shutdown: () => pool.shutdown() };}const main = createTessEngine(POOL_SIZE);export const tessEngine = main.engine;export async function shutdownOcr() {await main.shutdown();}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175'use client';import Link from 'next/link';import { useEffect, useState } from 'react';import { ApiError, benchCancel, benchGet, benchStart, type BenchState } from '../lib/api';
const sec = (ms: number) => `${(ms / 1000).toFixed(1)}s`;const LEVELS = [1, 2, 3, 4];
/** Admin: đo OCR ở các mức 1..4 ảnh song song trên ảnh ngẫu nhiên trong hệ thống để chọn cấu hình tối ưu */export function BenchPanel() { const [s, setS] = useState<BenchState | null>(null); const [levels, setLevels] = useState<number[]>(LEVELS); const [images, setImages] = useState(8); const [deep, setDeep] = useState(true); const [error, setError] = useState(''); const [busy, setBusy] = useState(false); const active = s?.status === 'running' || s?.status === 'preparing';
const act = async (fn: () => Promise<BenchState>) => { setBusy(true); setError(''); try { setS(await fn()); } catch (e) { setError(e instanceof ApiError ? e.message : e instanceof TypeError ? 'Mất kết nối tới server' : String((e as Error)?.message ?? e)); } finally { setBusy(false); } };
useEffect(() => { void act(benchGet); }, []); // đang chạy -> poll trạng thái useEffect(() => { if (!active) return; const t = setInterval(() => benchGet().then(setS).catch(() => undefined), 2000); return () => clearInterval(t); }, [active]);
const env = s?.env; const realCpus = env?.cgroupCpus ?? env?.cpus; const best = s?.recommendation?.concurrency;
return ( <section className="panel pad stack-gap"> <h3>Benchmark OCR</h3> <p className="muted small"> Chọn ngẫu nhiên ảnh đã xử lý trong hệ thống, chạy OCR lần lượt ở từng mức song song (1, 2, 3, 4 ảnh cùng lúc) để tìm số ảnh song song tối ưu cho server. Chỉ đo phần OCR (CPU), không gọi Gemini, không ghi dữ liệu. Trong lúc đo, ảnh mới upload sẽ chờ và được xử lý tiếp khi đo xong. </p>
{env && ( <p className="small mono"> CPU: {env.cpus} core{env.cgroupCpus != null && <> (container được cấp {env.cgroupCpus})</>} · RAM: {env.cgroupMemMb ?? env.totalMemMb} MB · load {env.loadAvg.join(' / ')} · hiện tại OCR_CONCURRENCY={env.ocrConcurrency}, OCR_WORKERS={env.ocrWorkers}, LLM_CONCURRENCY={env.llmConcurrency} </p> )} {s?.history && ( <p className="small muted"> Thực tế {s.history.count} ảnh gần nhất (OCR + Gemini): trung bình {sec(s.history.avgMs)}, trung vị {sec(s.history.p50Ms)} / ảnh; {s.history.withLlm} ảnh có gọi Gemini. </p> )}
<div className="row" style={{ flexWrap: 'wrap', gap: 16, alignItems: 'center' }}> <span>Mức song song:</span> {LEVELS.map((n) => ( <label key={n} className="row" style={{ gap: 4 }}> <input type="checkbox" disabled={active} checked={levels.includes(n)} onChange={(e) => setLevels((l) => (e.target.checked ? [...l, n] : l.filter((x) => x !== n)).sort())} /> {n} ảnh </label> ))} <label className="row" style={{ gap: 4 }}> Số ảnh mẫu <input type="number" min={1} max={24} value={images} disabled={active} style={{ width: 70 }} onChange={(e) => setImages(Math.max(1, Math.min(24, Number(e.target.value) || 1)))} /> </label> <label className="row" style={{ gap: 4 }} title="Giống hàng đợi thật: lượt nhanh chưa chắc chắn thì chạy thêm lượt OCR kỹ"> <input type="checkbox" checked={deep} disabled={active} onChange={(e) => setDeep(e.target.checked)} /> Kèm OCR kỹ như thật </label> </div> <p className="muted small"> Mỗi mức chạy cùng {images} ảnh mẫu. Ước tính tổng thời gian ≈ {levels.length ? `${Math.ceil((images * 60 * levels.reduce((a, n) => a + 1 / Math.min(n, realCpus ?? 1), 0)) / 60)} phút` : '—'} {' '}(giả định ~60s/ảnh). Nên dùng số ảnh chia hết cho các mức, ví dụ 8 hoặc 12. </p>
<div className="row"> {active ? ( <button className="btn ghost" disabled={busy} onClick={() => act(benchCancel)}>Dừng</button> ) : ( <button className="btn" disabled={busy || !levels.length} onClick={() => act(() => benchStart({ levels, images, deep }))}> {busy ? 'Đang bắt đầu…' : 'Chạy benchmark'} </button> )} </div> {error && <p className="err-text small" role="alert">✗ {error}</p>}
{s?.current && ( <p className="small"> ⏳ {s.current.step} — {s.current.done}/{s.current.total} {s.startedAt && <span className="muted"> · đã chạy {Math.round((Date.now() - s.startedAt) / 1000)}s</span>} </p> )} {s?.status === 'error' && <p className="err-text small">✗ Benchmark lỗi: {s.error}</p>} {s?.status === 'cancelled' && <p className="muted small">Đã dừng — kết quả bên dưới chỉ gồm các mức đã chạy.</p>}
{!!s?.levels.length && ( <div className="table-wrap"> <table className="cost-table"> <thead> <tr> <th className="num">Song song</th><th className="num">Tổng thời gian</th><th className="num">Ảnh/phút</th> <th className="num">TB / ảnh</th><th className="num">Trung vị</th><th className="num">Chậm nhất</th> <th className="num">CPU</th><th className="num">RAM đỉnh</th><th className="num">OCR kỹ</th><th className="num">Lỗi</th> </tr> </thead> <tbody> {s.levels.map((l) => ( <tr key={l.concurrency} style={l.concurrency === best ? { fontWeight: 600 } : undefined}> <td className="num">{l.concurrency}{l.concurrency === best && ' ★'}</td> <td className="num">{sec(l.wallMs)}</td> <td className="num">{l.throughput}</td> <td className="num">{sec(l.avgMs)}</td> <td className="num">{sec(l.p50Ms)}</td> <td className="num">{sec(l.maxMs)}</td> <td className="num" title="100% = 1 core bận kín">{l.cpuPct}%</td> <td className="num">{l.peakRssMb} MB</td> <td className="num">{l.deepCount}/{l.runs.length}</td> <td className="num">{l.errors || ''}</td> </tr> ))} </tbody> </table> </div> )}
{s?.recommendation && !active && ( <div className="small stack-gap"> <p className="ok-text">★ Gợi ý: {s.recommendation.reason}</p> <p>Đặt biến môi trường của Space: <span className="mono">{s.recommendation.env.join(' ')}</span></p> {realCpus != null && s.recommendation.concurrency > Math.ceil(realCpus) && ( <p className="err-text">⚠ Mức gợi ý lớn hơn số core được cấp ({realCpus}) — kết quả có thể dao động, nên chạy lại để xác nhận.</p> )} </div> )}
{!!s?.levels.length && ( <details className="small"> <summary>Chi tiết từng ảnh</summary> <div className="table-wrap"> <table className="cost-table"> <thead><tr><th>Ảnh</th>{s.levels.map((l) => <th key={l.concurrency} className="num">Mức {l.concurrency}</th>)}</tr></thead> <tbody> {s.sample.map((x) => ( <tr key={x.itemId}> <td className="name"><Link href={`/b/${x.batchId}/i/${x.itemId}`}>{x.name}</Link> <span className="muted">· {x.batchName}</span></td> {s.levels.map((l) => { const r = l.runs.find((r) => r.itemId === x.itemId); return ( <td key={l.concurrency} className="num" title={r?.error ?? r?.confidence}> {r ? (r.error ? '✗' : `${sec(r.ms)}${r.deep ? ' (kỹ)' : ''}`) : '—'} </td> ); })} </tr> ))} </tbody> </table> </div> <p className="muted">(kỹ) = lượt nhanh chưa chắc chắn nên chạy thêm lượt OCR kỹ.</p> </details> )} </section> );}1 unmodified line23456730 unmodified lines3839404142431 unmodified lineimport { useState } from 'react';import { ApiError, googleDiagnose, telegramDiagnose, telegramTest, type GoogleDiagnose, type TelegramDiagnose } from '../lib/api';import { authMessage, googleIdToken } from '../lib/firebase';type Out<T> = { data?: T; error?: string; code?: string };30 unmodified linesreturn (<div className="stack-gap"><section className="panel pad stack-gap"><h3>Telegram</h3><p className="muted small">Kiểm tra bot token / chat id / quyền của bot, rồi gửi thử tin nhắn hoặc ảnh lên chat đã cấu hình.</p>1 unmodified line234567830 unmodified lines39404142434445461 unmodified lineimport { useState } from 'react';import { ApiError, googleDiagnose, telegramDiagnose, telegramTest, type GoogleDiagnose, type TelegramDiagnose } from '../lib/api';import { authMessage, googleIdToken } from '../lib/firebase';import { BenchPanel } from './BenchPanel';type Out<T> = { data?: T; error?: string; code?: string };30 unmodified linesreturn (<div className="stack-gap"><BenchPanel /><section className="panel pad stack-gap"><h3>Telegram</h3><p className="muted small">Kiểm tra bot token / chat id / quyền của bot, rồi gửi thử tin nhắn hoặc ảnh lên chat đã cấu hình.</p>
185 unmodified lines186187188185 unmodified linesreturn call<{ ok: true; kind: 'message' | 'photo'; messageId: number }>('/api/test/telegram', { method: 'POST', body: form });}export const googleDiagnose = (idToken: string) => call<GoogleDiagnose>('/api/test/google', jsonBody('POST', { idToken }));185 unmodified lines186187188189190191192193194195196197198199200201202203204205206207208209210211212185 unmodified linesreturn call<{ ok: true; kind: 'message' | 'photo'; messageId: number }>('/api/test/telegram', { method: 'POST', body: form });}export const googleDiagnose = (idToken: string) => call<GoogleDiagnose>('/api/test/google', jsonBody('POST', { idToken }));export interface BenchLevel {concurrency: number; wallMs: number; throughput: number; avgMs: number; p50Ms: number; maxMs: number;cpuPct: number; peakRssMb: number; deepCount: number; errors: number;runs: { itemId: string; ms: number; deep: boolean; confidence?: string; error?: string }[];}export interface BenchState {status: 'idle' | 'preparing' | 'running' | 'done' | 'cancelled' | 'error';params?: { levels: number[]; images: number; deep: boolean };startedAt?: number; finishedAt?: number;env: {cpus: number; cgroupCpus: number | null; totalMemMb: number; cgroupMemMb: number | null; loadAvg: number[]; node: string;ocrConcurrency: number; ocrWorkers: number; llmConcurrency: number;};sample: { batchId: string; itemId: string; name: string; batchName: string }[];levels: BenchLevel[];current?: { concurrency: number; done: number; total: number; step: string };error?: string;history: { count: number; avgMs: number; p50Ms: number; withLlm: number } | null;recommendation?: { concurrency: number; reason: string; env: string[] };}export const benchGet = () => call<BenchState>('/api/test/bench');export const benchStart = (p: { levels: number[]; images: number; deep: boolean }) => call<BenchState>('/api/test/bench', jsonBody('POST', p));export const benchCancel = () => call<BenchState>('/api/test/bench', { method: 'DELETE' });
passport-check/apps/server/src/bench.tsAdded+261
passport-check/apps/server/src/index.ts+6
passport-check/apps/server/src/jobs.ts+11-2
passport-check/apps/server/src/ocr.ts+43-28
passport-check/apps/web/src/components/BenchPanel.tsxAdded+175
passport-check/apps/web/src/components/TestTools.tsx+3
passport-check/apps/web/src/lib/api.ts+24