Spaces:
Running
Running
Deploy cf7b4ca từ GitHub Actions
Browse filesFiles changed (12)
- passport-check/README.md+1-1
- passport-check/apps/server/src/gemini.ts+2-1
- passport-check/apps/server/src/index.ts+8-4
- passport-check/apps/server/src/jobs.ts+38-8
- passport-check/apps/server/src/tokens.ts+53-25
- passport-check/apps/web/src/components/GeminiActual.tsx+22-1
- passport-check/apps/web/src/components/TokenDialog.tsx+21-5
- passport-check/apps/web/src/lib/api.ts+4-1
- passport-check/packages/core/src/mrz.ts+8
- passport-check/packages/core/src/reconcile.ts+34-11
- passport-check/packages/core/src/schema.ts+15-2
- passport-check/packages/core/src/tokens.ts+4
46 unmodified lines4748495051525346 unmodified lines- Parse MRZ (TD3/TD2/TD1/visa), kiểm 5 check digit, sửa lỗi OCR theo loại ô (O/0, I/1…).- Đối chiếu tên với chữ in trên trang, kiểm logic ngày.- Chấm độ tin cậy `Cao` / `Trung bình` / `Thấp`.6. **Gemini (tuỳ chọn)**: chọn cho từng lô khi nào hỏi Gemini (không bao giờ / ảnh độ tin cậy thấp / mọi ảnh chưa chắc chắn / tất cả). Kết quả Gemini cũng bị kiểm checksum lại. Gemini chạy ở hàng đợi riêng (`LLM_CONCURRENCY`, mặc định 2), nên trong lúc chờ Gemini server vẫn OCR ảnh khác.7. **Kết quả lưu Firestore**: xem, sửa tay, duyệt, xuất **Excel** / **CSV**. File Excel có cột link xem ảnh.8. **Link xem lại ảnh**: `/b/<lô>/i/<ảnh>`. Người mở phải đăng nhập; server tải ảnh từ Telegram rồi trả về, bot token không bao giờ tới trình duyệt.46 unmodified lines4748495051525346 unmodified lines- Parse MRZ (TD3/TD2/TD1/visa), kiểm 5 check digit, sửa lỗi OCR theo loại ô (O/0, I/1…).- Đối chiếu tên với chữ in trên trang, kiểm logic ngày.- Chấm độ tin cậy `Cao` / `Trung bình` / `Thấp`.6. **Gemini (tuỳ chọn)**: chọn cho từng lô khi nào hỏi Gemini (không bao giờ / ảnh độ tin cậy thấp / mọi ảnh chưa chắc chắn / tất cả). Kết quả Gemini cũng bị kiểm checksum lại. Gemini chạy ở hàng đợi riêng (`LLM_CONCURRENCY`, mặc định 4), nên trong lúc chờ Gemini server vẫn OCR ảnh khác.7. **Kết quả lưu Firestore**: xem, sửa tay, duyệt, xuất **Excel** / **CSV**. File Excel có cột link xem ảnh.8. **Link xem lại ảnh**: `/b/<lô>/i/<ảnh>`. Người mở phải đăng nhập; server tải ảnh từ Telegram rồi trả về, bot token không bao giờ tới trình duyệt.
44 unmodified lines45464748495051525344 unmodified linesexpiryDate: str('Ngày hết hạn dạng YYYY-MM-DD'),authority: str('Cơ quan cấp như in trên trang'),personalNumber: str('Số cá nhân / số định danh nếu có'),notes: str('Ghi chú ngắn nếu ảnh mờ, bị che, hoặc trường nào không chắc chắn'),},required: ['isPassport', 'mrzLines'],};const PROMPT = `Bạn là hệ thống trích xuất dữ liệu hộ chiếu. Đọc ảnh và trả JSON theo schema.44 unmodified lines4546474849505152535444 unmodified linesexpiryDate: str('Ngày hết hạn dạng YYYY-MM-DD'),authority: str('Cơ quan cấp như in trên trang'),personalNumber: str('Số cá nhân / số định danh nếu có'),confidence: { type: 'string', enum: ['HIGH', 'MEDIUM', 'LOW'], description: 'Mức chắc chắn của toàn bộ kết quả đọc: HIGH nếu ảnh rõ và mọi trường quan trọng (MRZ, số HC, ngày) đọc chắc chắn; MEDIUM nếu có trường hơi mờ/không chắc; LOW nếu ảnh mờ, bị che hoặc phải đoán.' },notes: str('Ghi chú ngắn nếu ảnh mờ, bị che, hoặc trường nào không chắc chắn'),},required: ['isPassport', 'mrzLines', 'confidence'],};const PROMPT = `Bạn là hệ thống trích xuất dữ liệu hộ chiếu. Đọc ảnh và trả JSON theo schema.
288 unmodified lines28929029129229329429529645 unmodified lines34234334434534634734814 unmodified lines363364365366367368369288 unmodified lines/** User thường không được thấy llmUsage (token thực tế, hệ số, model) */function forUser<T extends { result?: any }>(it: T, admin: boolean): T {if (admin || !it.result?.llmUsage) return it;const { llmUsage: _u, ...result } = it.result;return { ...it, result };}45 unmodified linesapi.get('/tokens/usage', requireCostAccess, h(async (req, res) => res.json(await usageReport(allItems(), batchById, req.user!.role === 'admin'))));// Token Gemini thực tế (in / out / thinking) theo model + chi phí — chỉ adminapi.get('/tokens/actual', requireAdmin, h(async (_req, res) => res.json(actualReport(allItems()))));// Đơn giá & cách tính dùng chung: ai xem được trang chi phí thì đọc, chỉ admin sửa (body null = về mặc định)api.get('/cost-settings', requireCostAccess, h(async (_req, res) => res.json({ settings: await getCostSettings() })));14 unmodified linesres.json({batchId: bid, batchName: batch.name, simple: true,total: { images: rep.total.all.images, tokens: rep.total.all.totalTokens, cost: cost(rep.total.all.inputTokens, rep.total.all.outputTokens) },items: rep.items.map((x) => ({ id: x.id, name: x.name, tokens: x.total, cost: cost(x.input.total, x.output.tokens) })),});}));288 unmodified lines28929029129229329429529645 unmodified lines34234334434534634734814 unmodified lines363364365366367368369370371372373288 unmodified lines/** User thường không được thấy llmUsage (token thực tế, hệ số, model) */function forUser<T extends { result?: any }>(it: T, admin: boolean): T {if (admin || !(it.result?.llmUsage || it.result?.llmCalls)) return it;const { llmUsage: _u, llmCalls: _c, ...result } = it.result;return { ...it, result };}45 unmodified linesapi.get('/tokens/usage', requireCostAccess, h(async (req, res) => res.json(await usageReport(allItems(), batchById, req.user!.role === 'admin'))));// Token Gemini thực tế (in / out / thinking) theo model + chi phí — chỉ adminapi.get('/tokens/actual', requireAdmin, h(async (_req, res) => res.json(actualReport(allItems(), (id) => batchById(id)?.name ?? id))));// Đơn giá & cách tính dùng chung: ai xem được trang chi phí thì đọc, chỉ admin sửa (body null = về mặc định)api.get('/cost-settings', requireCostAccess, h(async (_req, res) => res.json({ settings: await getCostSettings() })));14 unmodified linesres.json({batchId: bid, batchName: batch.name, simple: true,total: { images: rep.total.all.images, tokens: rep.total.all.totalTokens, cost: cost(rep.total.all.inputTokens, rep.total.all.outputTokens) },items: rep.items.map((x) => ({id: x.id, name: x.name, tokens: x.total, cost: cost(x.input.total, x.output.tokens),// từng lần đọc (đã nhân hệ số) để đối chiếu tiền khi một ảnh đọc lại nhiều lần...(x.billed ? { reads: x.billed.calls.map((c) => ({ n: c.n, at: c.at, tokens: c.input + c.output, cost: cost(c.input, c.output) })), base: { tokens: x.billed.base.input + x.billed.base.output, cost: cost(x.billed.base.input, x.billed.base.output) } } : {}),})),});}));
18 unmodified lines19202122232425261 unmodified line282930313233343536295 unmodified lines33233333433533633727 unmodified lines36536636736836937037115 unmodified lines38738838939039139239339439539639710 unmodified lines40840941041141241341466 unmodified lines48148248348448548648748818 unmodified linesimport crypto from 'node:crypto';import { FieldValue } from 'firebase-admin/firestore';import {EMPTY_COUNTS, itemCounts, mergeResults, reconcile, runPipeline,type Batch, type BatchSettings, type ExtractionResult, type StoredItem, type TripInfo,} from '@pc/core';import { db } from './firebase.ts';import { sendDocument, downloadFile, deleteMessage, type TelegramRef } from './telegram.ts';1 unmodified lineimport { loadImage, sharpOps, tessEngine } from './ocr.ts';import { geminiExtract, llmAvailable } from './gemini.ts';const OCR_CONCURRENCY = Number(process.env.OCR_CONCURRENCY ?? 1);/** số lời gọi Gemini chạy cùng lúc (chủ yếu là chờ mạng, không tốn CPU) */const LLM_CONCURRENCY = Number(process.env.LLM_CONCURRENCY ?? 2);const batches = () => db().collection('batches');const items = (batchId: string) => batches().doc(batchId).collection('items');295 unmodified linesfunction wantLlm(r: ExtractionResult, policy: BatchSettings['llm']): boolean {if (!llmAvailable() || policy === 'off') return false;if (policy === 'all') return true;if (policy === 'low') return LEVEL[r.confidence] === 0;return LEVEL[r.confidence] < 2 || r.needsReview;}27 unmodified linesresult = mergeResults(result, { mrz: deep.mrz, viz: deep.viz, source: 'server-ocr' });if (deep.mrz && deep.mrz === result.mrz) rotation = deep.rotation;}if (force === 'llm' || (force === 'full' && llmAvailable()) || (!force && wantLlm(result, policy))) {// chuyển sang hàng đợi Gemini; worker OCR làm tiếp ảnh khácllmQueue.push({ batchId, itemId, result, rotation, t0 });handedOff = true;15 unmodified lines}async function saveResult(batchId: string, itemId: string, result: ExtractionResult, rotation: number, t0: number) {await updateItem(batchId, itemId, {status: 'done', error: '', result, confidence: result.confidence,needsReview: result.needsReview, rotation, ms: Date.now() - t0, edited: false,});fs.rmSync(inboxPath(itemId), { force: true });}async function runLlm() {10 unmodified linesconst buf = await loadOriginal(it);try {const { llm, usage } = await geminiExtract(buf, it.mime);result = { ...mergeResults(result, { llm, source: 'llm' }), llmUsage: usage };} catch (e: any) {result = { ...result, warnings: [...result.warnings, `Gemini lỗi: ${e?.status === 429 ? 'hết quota' : e?.message ?? e}`] };}66 unmodified linesconst patch: Partial<StoredItem> = {};if (edit.result) {// llmUsage do server ghi, không nhận từ client (client thường không thấy trường này)const { llmUsage: _drop, ...clean } = edit.result;const result: ExtractionResult = it.result?.llmUsage ? { ...clean, llmUsage: it.result.llmUsage } : clean;Object.assign(patch, { status: 'done', result, confidence: edit.result.confidence, needsReview: edit.result.needsReview, edited: true, reviewedBy: email });}// ghi đè thông tin chuyến đi riêng của khách; giá trị rỗng = dùng lại thông tin đoàn18 unmodified lines19202122232425261 unmodified line282930313233343536295 unmodified lines33233333433533633733833927 unmodified lines36736836937037137237315 unmodified lines38939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242310 unmodified lines43443543643743843944066 unmodified lines50750850951051151251351451551651751818 unmodified linesimport crypto from 'node:crypto';import { FieldValue } from 'firebase-admin/firestore';import {EMPTY_COUNTS, isWellFormedMrz, itemCounts, llmCallsOf, mergeResults, reconcile, runPipeline,type Batch, type BatchSettings, type ExtractionResult, type LlmCall, type StoredItem, type TripInfo,} from '@pc/core';import { db } from './firebase.ts';import { sendDocument, downloadFile, deleteMessage, type TelegramRef } from './telegram.ts';1 unmodified lineimport { loadImage, sharpOps, tessEngine } from './ocr.ts';import { geminiExtract, llmAvailable } from './gemini.ts';const OCR_CONCURRENCY = Number(process.env.OCR_CONCURRENCY ?? 2);/** số lời gọi Gemini chạy cùng lúc (chủ yếu là chờ mạng, không tốn CPU) */const LLM_CONCURRENCY = Number(process.env.LLM_CONCURRENCY ?? 4);const batches = () => db().collection('batches');const items = (batchId: string) => batches().doc(batchId).collection('items');295 unmodified linesfunction wantLlm(r: ExtractionResult, policy: BatchSettings['llm']): boolean {if (!llmAvailable() || policy === 'off') return false;if (policy === 'all') return true;// OCR không đọc được đủ 2 dòng MRZ đúng cấu trúc (hộ chiếu TD3 44 ký tự, checksum khớp) -> luôn hỏi Geminiif (!isWellFormedMrz(r.mrz)) return true;if (policy === 'low') return LEVEL[r.confidence] === 0;return LEVEL[r.confidence] < 2 || r.needsReview;}27 unmodified linesresult = mergeResults(result, { mrz: deep.mrz, viz: deep.viz, source: 'server-ocr' });if (deep.mrz && deep.mrz === result.mrz) rotation = deep.rotation;}if (force === 'llm' || (force === 'full' && llmAvailable()) || wantLlm(result, policy)) {// chuyển sang hàng đợi Gemini; worker OCR làm tiếp ảnh khácllmQueue.push({ batchId, itemId, result, rotation, t0 });handedOff = true;15 unmodified lines}async function saveResult(batchId: string, itemId: string, result: ExtractionResult, rotation: number, t0: number) {// Đọc lại nhiều lần: cộng dồn lịch sử các lần gọi Gemini (kể cả khi lần này OCR lại từ đầu và dựng kết quả mới)const prev = llmCallsOf(itemCache.get(itemId)?.result);const key = (c: LlmCall) => `${c.at ?? ''}|${c.promptTokens}|${c.outputTokens}|${c.thinkingTokens ?? 0}`;const seen = new Set(prev.map(key));const calls = [...prev, ...llmCallsOf(result).filter((c) => !seen.has(key(c)))];if (calls.length) result = { ...result, llmCalls: calls, llmUsage: calls[calls.length - 1] };await updateItem(batchId, itemId, {status: 'done', error: '', result, confidence: result.confidence,needsReview: result.needsReview, rotation, ms: Date.now() - t0, edited: false,});fs.rmSync(inboxPath(itemId), { force: true });await syncDuplicates(batchId, itemId, result, rotation);}/*** Ảnh trùng (cùng sha256) ở lô khác được sao chép kết quả lúc upload, nên đọc lại ở một lô sẽ làm các bản sao bị cũ.* Đọc lại xong thì đồng bộ kết quả mới sang các bản sao đã xử lý xong, trừ bản người dùng đã sửa tay.*/async function syncDuplicates(batchId: string, itemId: string, result: ExtractionResult, rotation: number) {const src = itemCache.get(itemId);if (!src) return;const { llmUsage: _u, llmCalls: _c, ...copy } = result; // bản sao không gọi Gemini -> không tính token lần nữafor (const o of [...itemCache.values()]) {if (o.id === itemId || o.sha256 !== src.sha256 || o.status !== 'done' || o.edited || live.has(o.id)) continue;if (o.batchId === batchId) continue; // cùng lô không thể trùng (đã chặn lúc upload)await updateItem(o.batchId, o.id, {result: copy, confidence: copy.confidence, needsReview: copy.needsReview, rotation,}).catch((e) => console.error('sync duplicate', (e as Error).message));}}async function runLlm() {10 unmodified linesconst buf = await loadOriginal(it);try {const { llm, usage } = await geminiExtract(buf, it.mime);result = { ...mergeResults(result, { llm, source: 'llm' }), llmUsage: usage, llmCalls: [...llmCallsOf(result), { ...usage, at: Date.now() }] };} catch (e: any) {result = { ...result, warnings: [...result.warnings, `Gemini lỗi: ${e?.status === 429 ? 'hết quota' : e?.message ?? e}`] };}66 unmodified linesconst patch: Partial<StoredItem> = {};if (edit.result) {// llmUsage do server ghi, không nhận từ client (client thường không thấy trường này)const { llmUsage: _drop, llmCalls: _dropCalls, ...clean } = edit.result;const result: ExtractionResult = {...clean,...(it.result?.llmUsage ? { llmUsage: it.result.llmUsage } : {}),...(it.result?.llmCalls ? { llmCalls: it.result.llmCalls } : {}),};Object.assign(patch, { status: 'done', result, confidence: edit.result.confidence, needsReview: edit.result.needsReview, edited: true, reviewedBy: email });}// ghi đè thông tin chuyến đi riêng của khách; giá trị rỗng = dùng lại thông tin đoàn
9 unmodified lines1011121314151674 unmodified lines919293949596979899100101102103104105106107108109110111112113114115116125 unmodified lines2422432442452462472482492502512522532542552562572582592602612622632642652663 unmodified lines2702712722732742759 unmodified lines*/import { LocalTokenizer } from '@google/genai/tokenizer';import {addTokenSum, base64Size, emptyTokenSum, GEMINI_TOKEN_DOCS, imageTokenRule, imageTokens, vnDay, type Batch, type ImageTokenRule, type ItemTokens,type LlmOutput, type StoredItem, type TokenFormula, type TokenPrices, type TokenSum, type TokenUsageReport, type UsageBatch, type UsageDay,} from '@pc/core';import { llmModel, promptText, SCHEMA } from './gemini.ts';74 unmodified lines// Ảnh đã gọi Gemini:// - user thường: ước lượng + thực tế × hệ số chốt lúc gọi// - admin: đúng số Gemini báo (input / output / thinking); ảnh chưa gọi Gemini = 0const usage = it.result?.sources.includes('llm') ? it.result.llmUsage : undefined;const wt = usage?.weight ?? LEGACY_WEIGHT;let input: number;let outTokens: number;if (admin) {input = usage?.promptTokens ?? 0;outTokens = (usage?.outputTokens ?? 0) + (usage?.thinkingTokens ?? 0); // thinking tính giá như output} else {input = img.tokens + fixed.prompt + fixed.schema + (usage ? usage.promptTokens * wt : 0);outTokens = o.tokens + (usage ? (usage.outputTokens + (usage.thinkingTokens ?? 0)) * wt : 0);}return {id: it.id,name: it.name,status: it.status,sentToLlm: !!it.result?.sources.includes('llm'),image: { bytes: it.size, base64Bytes: base64Size(it.size), width: w, height: h, megapixels: +((w * h) / 1e6).toFixed(2), mime: it.mime },input: { image: img, prompt: fixed.prompt, schema: fixed.schema, total: input },output: { source: out.source, jsonChars: text.length, jsonBytes: Buffer.byteLength(text, 'utf8'), tokens: outTokens, ...(withJson ? { json: out.json } : {}) },...(usage ? { actual: { input: usage.promptTokens, output: usage.outputTokens, thinking: usage.thinkingTokens ?? 0 } } : {}),total: input + outTokens,exact: fixed.exact && o.exact,};125 unmodified linesexport interface ActualRow { model: string; label: string; priced: boolean; calls: number; input: number; output: number; thinking: number; total: number; cost: number }/** Tổng token Gemini báo về, tách input / output / thinking, theo model (toàn bộ và theo ngày); chi phí tính theo bảng giá của từng model */export function actualReport(items: StoredItem[]) {const fallback = tokenPrices();const byModel = new Map<string, ActualRow>();const byDay = new Map<string, { date: string; calls: number; input: number; output: number; thinking: number; cost: number }>();for (const it of items) {const u = it.result?.sources.includes('llm') ? it.result.llmUsage : undefined;if (!u) continue;const model = u.model ?? llmModel(); // ảnh cũ chưa lưu model: giả định model hiện tạiconst at = it.updatedAt ?? it.createdAt;const p = priceFor(model, at, fallback);const th = u.thinkingTokens ?? 0;const cost = (u.promptTokens * p.input + (u.outputTokens + th) * p.output) / 1e6;const m = byModel.get(model) ?? { model, label: p.label, priced: p.known, calls: 0, input: 0, output: 0, thinking: 0, total: 0, cost: 0 };m.calls++; m.input += u.promptTokens; m.output += u.outputTokens; m.thinking += th; m.total += u.promptTokens + u.outputTokens + th; m.cost += cost;byModel.set(model, m);const date = vnDay(at);const d = byDay.get(date) ?? { date, calls: 0, input: 0, output: 0, thinking: 0, cost: 0 };d.calls++; d.input += u.promptTokens; d.output += u.outputTokens; d.thinking += th; d.cost += cost;byDay.set(date, d);}const models = [...byModel.values()].sort((a, b) => b.cost - a.cost);const sum = models.reduce((s, m) => ({ calls: s.calls + m.calls, input: s.input + m.input, output: s.output + m.output, thinking: s.thinking + m.thinking, total: s.total + m.total, cost: s.cost + m.cost }),3 unmodified linestotal: sum,models,days: [...byDay.values()].sort((a, b) => b.date.localeCompare(a.date)),note: 'Số liệu lấy từ usageMetadata Gemini trả về ở mỗi lần gọi (chỉ các ảnh gọi Gemini sau khi có tính năng này). Thinking tính giá như output. Giá theo bảng của Google (Standard, trả phí); model ngoài bảng dùng giá mặc định.',};}9 unmodified lines1011121314151674 unmodified lines919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134125 unmodified lines2602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902913 unmodified lines2952962972982993003013023039 unmodified lines*/import { LocalTokenizer } from '@google/genai/tokenizer';import {addTokenSum, base64Size, llmCallsOf, emptyTokenSum, GEMINI_TOKEN_DOCS, imageTokenRule, imageTokens, vnDay, type Batch, type ImageTokenRule, type ItemTokens,type LlmOutput, type StoredItem, type TokenFormula, type TokenPrices, type TokenSum, type TokenUsageReport, type UsageBatch, type UsageDay,} from '@pc/core';import { llmModel, promptText, SCHEMA } from './gemini.ts';74 unmodified lines// Ảnh đã gọi Gemini:// - user thường: ước lượng + thực tế × hệ số chốt lúc gọi// - admin: đúng số Gemini báo (input / output / thinking); ảnh chưa gọi Gemini = 0const calls = llmCallsOf(it.result);let input: number;let outTokens: number;if (admin) {// đúng số Gemini báo, cộng dồn mọi lần đọc lại; thinking tính giá như outputinput = calls.reduce((s, c) => s + c.promptTokens, 0);outTokens = calls.reduce((s, c) => s + c.outputTokens + (c.thinkingTokens ?? 0), 0);} else {// user thường: ước lượng một lần + thực tế × hệ số chốt lúc gọi, mỗi lần đọc lại cộng thêminput = img.tokens + fixed.prompt + fixed.schema + calls.reduce((s, c) => s + c.promptTokens * (c.weight ?? LEGACY_WEIGHT), 0);outTokens = o.tokens + calls.reduce((s, c) => s + (c.outputTokens + (c.thinkingTokens ?? 0)) * (c.weight ?? LEGACY_WEIGHT), 0);}return {id: it.id,name: it.name,status: it.status,sentToLlm: calls.length > 0 || !!it.result?.sources.includes('llm'),image: { bytes: it.size, base64Bytes: base64Size(it.size), width: w, height: h, megapixels: +((w * h) / 1e6).toFixed(2), mime: it.mime },input: { image: img, prompt: fixed.prompt, schema: fixed.schema, total: input },output: { source: out.source, jsonChars: text.length, jsonBytes: Buffer.byteLength(text, 'utf8'), tokens: outTokens, ...(withJson ? { json: out.json } : {}) },...(admin && calls.length ? {actual: {input: calls.reduce((s, c) => s + c.promptTokens, 0),output: calls.reduce((s, c) => s + c.outputTokens, 0),thinking: calls.reduce((s, c) => s + (c.thinkingTokens ?? 0), 0),},// calls chỉ kèm cho admin (user thường không được thấy token thực tế)...(admin ? { calls: calls.map((c, i) => ({ n: i + 1, at: c.at, model: c.model, input: c.promptTokens, output: c.outputTokens, thinking: c.thinkingTokens ?? 0 })) } : {}),} : {}),...(!admin && calls.length ? {billed: {base: { input: img.tokens + fixed.prompt + fixed.schema, output: o.tokens },calls: calls.map((c, i) => {const w = c.weight ?? LEGACY_WEIGHT;return { n: i + 1, at: c.at, input: c.promptTokens * w, output: (c.outputTokens + (c.thinkingTokens ?? 0)) * w };}),},} : {}),total: input + outTokens,exact: fixed.exact && o.exact,};125 unmodified linesexport interface ActualRow { model: string; label: string; priced: boolean; calls: number; input: number; output: number; thinking: number; total: number; cost: number }/** Tổng token Gemini báo về, tách input / output / thinking, theo model (toàn bộ và theo ngày); chi phí tính theo bảng giá của từng model */export interface ActualCall { itemId: string; batchId: string; name: string; n: number; of: number; at: number; model: string; input: number; output: number; thinking: number; cost: number }export function actualReport(items: StoredItem[], batchName: (id: string) => string = (id) => id) {const fallback = tokenPrices();const byModel = new Map<string, ActualRow>();const byDay = new Map<string, { date: string; calls: number; input: number; output: number; thinking: number; cost: number }>();const list: ActualCall[] = [];let rereads = 0;for (const it of items) {const calls = llmCallsOf(it.result);if (calls.length > 1) rereads += calls.length - 1;calls.forEach((u, i) => {const model = u.model ?? llmModel(); // ảnh cũ chưa lưu model: giả định model hiện tạiconst at = u.at ?? it.updatedAt ?? it.createdAt; // dữ liệu cũ chưa có giờ gọi: lấy giờ cập nhật ảnhconst p = priceFor(model, at, fallback);const th = u.thinkingTokens ?? 0;const cost = (u.promptTokens * p.input + (u.outputTokens + th) * p.output) / 1e6;const m = byModel.get(model) ?? { model, label: p.label, priced: p.known, calls: 0, input: 0, output: 0, thinking: 0, total: 0, cost: 0 };m.calls++; m.input += u.promptTokens; m.output += u.outputTokens; m.thinking += th; m.total += u.promptTokens + u.outputTokens + th; m.cost += cost;byModel.set(model, m);const date = vnDay(at);const d = byDay.get(date) ?? { date, calls: 0, input: 0, output: 0, thinking: 0, cost: 0 };d.calls++; d.input += u.promptTokens; d.output += u.outputTokens; d.thinking += th; d.cost += cost;byDay.set(date, d);list.push({ itemId: it.id, batchId: it.batchId, name: it.name, n: i + 1, of: calls.length, at, model, input: u.promptTokens, output: u.outputTokens, thinking: th, cost });});}const models = [...byModel.values()].sort((a, b) => b.cost - a.cost);const sum = models.reduce((s, m) => ({ calls: s.calls + m.calls, input: s.input + m.input, output: s.output + m.output, thinking: s.thinking + m.thinking, total: s.total + m.total, cost: s.cost + m.cost }),3 unmodified linestotal: sum,models,days: [...byDay.values()].sort((a, b) => b.date.localeCompare(a.date)),rereads,/** từng lần gọi, mới nhất trước (tối đa 500) */calls: list.sort((a, b) => b.at - a.at).slice(0, 500).map((c) => ({ ...c, batch: batchName(c.batchId) })),note: 'Số liệu lấy từ usageMetadata Gemini trả về ở mỗi lần gọi; đọc lại một ảnh nhiều lần thì mỗi lần là một dòng và chi phí cộng dồn (chỉ các ảnh gọi Gemini sau khi có tính năng này). Thinking tính giá như output. Giá theo bảng của Google (Standard, trả phí); model ngoài bảng dùng giá mặc định.',};}
3 unmodified lines45678915 unmodified lines2526272829303142 unmodified lines7475767778793 unmodified linesconst num = (n: number) => Math.round(n).toLocaleString('vi-VN');const usd = (n: number) => `$${n.toLocaleString('en-US', { minimumFractionDigits: n > 0 && n < 1 ? 4 : 2, maximumFractionDigits: n > 0 && n < 1 ? 4 : 2 })}`;const vnd = (n: number) => `${Math.round(n).toLocaleString('vi-VN')} ₫`;/** Admin: tổng token Gemini thực tế (input / output / thinking) và chi phí ước tính theo giá từng model */15 unmodified lines<section className="panel pad-panel"><div className="tk-cards"><div className="tk-card"><div className="tk-card-title">{num(t.calls)} lần gọi</div><div className="tk-big">{num(t.total)} <span className="muted small">token</span></div><div className="tk-split small"><span>Input <strong>{num(t.input)}</strong></span>42 unmodified lines</table></div></section></div>);}3 unmodified lines4567891015 unmodified lines2627282930313242 unmodified lines757677787980818283848586878889909192939495969798991003 unmodified linesconst num = (n: number) => Math.round(n).toLocaleString('vi-VN');const usd = (n: number) => `$${n.toLocaleString('en-US', { minimumFractionDigits: n > 0 && n < 1 ? 4 : 2, maximumFractionDigits: n > 0 && n < 1 ? 4 : 2 })}`;const when = (ms: number) => new Date(ms).toLocaleString('vi-VN', { timeZone: 'Asia/Ho_Chi_Minh', hour12: false, day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit' });const vnd = (n: number) => `${Math.round(n).toLocaleString('vi-VN')} ₫`;/** Admin: tổng token Gemini thực tế (input / output / thinking) và chi phí ước tính theo giá từng model */15 unmodified lines<section className="panel pad-panel"><div className="tk-cards"><div className="tk-card"><div className="tk-card-title">{num(t.calls)} lần gọi{r.rereads > 0 && <span className="muted small"> (gồm {num(r.rereads)} lần đọc lại, mỗi lần tính tiền riêng)</span>}</div><div className="tk-big">{num(t.total)} <span className="muted small">token</span></div><div className="tk-split small"><span>Input <strong>{num(t.input)}</strong></span>42 unmodified lines</table></div></section><section className="panel pad-panel"><h3>Theo từng lần gọi</h3><p className="muted small">Mới nhất trước{r.calls.length >= 500 ? ' (500 lần gần nhất)' : ''}. Ảnh đọc lại nhiều lần có nhiều dòng, "Lần" là thứ tự đọc của ảnh đó.</p><div className="table-wrap"><table className="cost-table"><thead><tr><th>Giờ đọc</th><th>Lô</th><th>Ảnh</th><th className="num">Lần</th><th className="num">Input</th><th className="num">Output</th><th className="num">Thinking</th><th className="num">USD</th><th className="num">VND</th></tr></thead><tbody>{r.calls.map((c, i) => (<tr key={`${c.itemId}-${c.n}-${i}`}><td title={c.model}>{when(c.at)}</td><td>{c.batch}</td><td>{c.name}</td><td className="num">{c.n}/{c.of}{c.n > 1 && <span className="badge medium" title="Đọc lại"> lại</span>}</td><td className="num">{num(c.input)}</td><td className="num">{num(c.output)}</td><td className="num">{num(c.thinking)}</td><td className="num"><strong>{usd(c.cost)}</strong></td><td className="num">{vnd(c.cost * rate)}</td></tr>))}{!r.calls.length && <tr><td colSpan={9} className="empty">Chưa có dữ liệu</td></tr>}</tbody></table></div></section></div>);}
66 unmodified lines67686970717273747576777863 unmodified lines14214314414514614714866 unmodified lines<p className="small">{SRC[x.output.source]} · {num(x.output.jsonChars)} ký tự · {size(x.output.jsonBytes)}</p>{x.actual && (<><h4>Gemini báo thực tế</h4><table className="tk-mini"><tbody><tr><td>Input</td><td className="num">{num(x.actual.input)}</td></tr><tr><td>Output</td><td className="num">{num(x.actual.output)}</td></tr><tr><td>Thinking</td><td className="num">{num(x.actual.thinking)}</td></tr></tbody></table></>63 unmodified lines<table><thead><tr><th>Ảnh</th><th className="num">Token</th><th className="num">Chi phí</th></tr></thead><tbody>{simple.items.map((x) => <tr key={x.id}><td className="file" title={x.name}>{x.name}</td><td className="num">{num(x.tokens)}</td><td className="num">{usd(x.cost)}</td></tr>)}{!simple.items.length && <tr><td colSpan={3} className="empty">Không có ảnh nào</td></tr>}</tbody></table>66 unmodified lines67686970717273747576777879808182838463 unmodified lines14814915015115215315415515615715815916016116216316466 unmodified lines<p className="small">{SRC[x.output.source]} · {num(x.output.jsonChars)} ký tự · {size(x.output.jsonBytes)}</p>{x.actual && (<><h4>Gemini báo thực tế{x.calls && x.calls.length > 1 ? ` · ${x.calls.length} lần đọc (cộng dồn)` : ''}</h4><table className="tk-mini"><thead>{x.calls && <tr><th>Lần</th><th>Giờ đọc</th><th className="num">In</th><th className="num">Out</th><th className="num">Think</th></tr>}</thead><tbody>{x.calls?.map((c) => (<tr key={c.n}><td>{c.n}</td><td title={c.model}>{c.at ? new Date(c.at).toLocaleString('vi-VN', { timeZone: 'Asia/Ho_Chi_Minh', hour12: false }) : 'không rõ'}</td><td className="num">{num(c.input)}</td><td className="num">{num(c.output)}</td><td className="num">{num(c.thinking)}</td></tr>))}<tr><td colSpan={x.calls ? 2 : 1}><strong>Tổng</strong></td><td className="num">{num(x.actual.input)}</td><td className="num">{num(x.actual.output)}</td><td className="num">{num(x.actual.thinking)}</td></tr></tbody></table></>63 unmodified lines<table><thead><tr><th>Ảnh</th><th className="num">Token</th><th className="num">Chi phí</th></tr></thead><tbody>{simple.items.map((x) => (<Fragment key={x.id}><tr><td className="file" title={x.name}>{x.name}{x.reads && x.reads.length > 1 && <span className="badge medium" title="Đã đọc lại, mỗi lần tính tiền riêng"> {x.reads.length} lần đọc</span>}</td><td className="num">{num(x.tokens)}</td><td className="num">{usd(x.cost)}</td></tr>{x.reads && x.reads.length > 1 && (<>{x.base && <tr className="muted small"><td> Cơ sở</td><td className="num">{num(x.base.tokens)}</td><td className="num">{usd(x.base.cost)}</td></tr>}{x.reads.map((c) => <tr key={c.n} className="muted small"><td> Lần {c.n} · {c.at ? new Date(c.at).toLocaleString('vi-VN', { timeZone: 'Asia/Ho_Chi_Minh', hour12: false }) : 'không rõ giờ'}</td><td className="num">{num(c.tokens)}</td><td className="num">{usd(c.cost)}</td></tr>)}</>)}</Fragment>))}{!simple.items.length && <tr><td colSpan={3} className="empty">Không có ảnh nào</td></tr>}</tbody></table>
70 unmodified lines7172737475767778798081828370 unmodified lines/** Ước lượng token Gemini (server tự tính theo kích thước ảnh, không gọi Gemini) */export const batchTokens = (bid: string) => call<BatchTokenReport | SimpleTokenReport>(`/api/batches/${bid}/tokens`);/** User thường: chỉ tổng token + giá */export interface SimpleTokenReport { simple: true; batchId: string; batchName: string; total: { images: number; tokens: number; cost: number }; items: { id: string; name: string; tokens: number; cost: number }[] }export interface ActualRow { model: string; label: string; priced: boolean; calls: number; input: number; output: number; thinking: number; total: number; cost: number }export interface ActualReport {current: string; note: string;total: { calls: number; input: number; output: number; thinking: number; total: number; cost: number };models: ActualRow[];days: { date: string; calls: number; input: number; output: number; thinking: number; cost: number }[];}export const tokenActual = () => call<ActualReport>('/api/tokens/actual');export const tokenUsage = () => call<TokenUsageReport>('/api/tokens/usage');70 unmodified lines7172737475767778798081828384858670 unmodified lines/** Ước lượng token Gemini (server tự tính theo kích thước ảnh, không gọi Gemini) */export const batchTokens = (bid: string) => call<BatchTokenReport | SimpleTokenReport>(`/api/batches/${bid}/tokens`);/** User thường: chỉ tổng token + giá */export interface SimpleTokenReport { simple: true; batchId: string; batchName: string; total: { images: number; tokens: number; cost: number }; items: { id: string; name: string; tokens: number; cost: number; base?: { tokens: number; cost: number }; reads?: { n: number; at?: number; tokens: number; cost: number }[] }[] }export interface ActualRow { model: string; label: string; priced: boolean; calls: number; input: number; output: number; thinking: number; total: number; cost: number }export interface ActualReport {current: string; note: string;total: { calls: number; input: number; output: number; thinking: number; total: number; cost: number };models: ActualRow[];days: { date: string; calls: number; input: number; output: number; thinking: number; cost: number }[];/** số lần đọc lại (lần gọi thứ 2 trở đi của cùng một ảnh), đã nằm trong total */rereads: number;calls: { itemId: string; batchId: string; batch: string; name: string; n: number; of: number; at: number; model: string; input: number; output: number; thinking: number; cost: number }[];}export const tokenActual = () => call<ActualReport>('/api/tokens/actual');export const tokenUsage = () => call<TokenUsageReport>('/api/tokens/usage');
788 unmodified lines789790791788 unmodified linesexport function mrzRank(r: MrzResult | null): number {return r ? rank(r) : -Infinity;}788 unmodified lines789790791792793794795796797798799788 unmodified linesexport function mrzRank(r: MrzResult | null): number {return r ? rank(r) : -Infinity;}/*** MRZ hộ chiếu "đúng cấu trúc": TD3, đúng 2 dòng × 44 ký tự, không phải căn chỉnh lại độ dài và mọi check digit khớp.* Không đạt -> OCR chưa đủ tin cậy, nên hỏi Gemini.*/export function isWellFormedMrz(r: MrzResult | null | undefined): boolean {return !!r && r.format === 'TD3' && r.lines.length === 2 && r.lines.every((l) => l.length === 44) && !r.lengthAdjusted && r.valid;}
12 unmodified lines13141516171870 unmodified lines899091929394959697989910010110210310410510610767 unmodified lines17517617717817918012 unmodified linesdocumentCode?: string;fullNameNative?: string;isPassport?: boolean;notes?: string;}70 unmodified linesif (llm?.fullNameNative) src.fullName = llm.fullNameNative;// Nếu không có MRZ hợp lệ, dùng trực tiếp các trường LLM/VIZ (không xác minh được)if (!best || best.score < 0.5) {const fb = src;r.surname ||= (fb.surname ?? '').toUpperCase();r.givenNames ||= (fb.givenNames ?? '').toUpperCase();r.documentNumber ||= normDocNo(fb.documentNumber);r.nationality ||= normalizeCountryCode(fb.nationality ?? '').code;r.issuingState ||= normalizeCountryCode(llm?.issuingState ?? '').code;r.documentCode ||= llm?.documentCode ?? '';r.birthDate ||= normDate(fb.birthDate);r.expiryDate ||= normDate(fb.expiryDate);r.sex ||= (fb.sex ?? '').toUpperCase().slice(0, 1);r.personalNumber ||= fb.personalNumber ?? '';if (r.documentNumber) warnings.push('Các trường MRZ chưa được xác minh bằng checksum');}r.fullName = src.fullName?.trim() || [r.surname, r.givenNames].filter(Boolean).join(' ');67 unmodified linesif (checksumOk && countriesOk && mismatches.length === 0 && !unverifiedName && !riskyUnconfirmed && !ambiguous) confidence = 'HIGH';else if (best && (checksumOk || best.score >= 0.75)) confidence = 'MEDIUM';else confidence = 'LOW';return {record: r,12 unmodified lines131415161718192070 unmodified lines91929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412567 unmodified lines19319419519619719819920020120220312 unmodified linesdocumentCode?: string;fullNameNative?: string;isPassport?: boolean;/** Gemini tự đánh giá mức chắc chắn của lần đọc */confidence?: Confidence;notes?: string;}70 unmodified linesif (llm?.fullNameNative) src.fullName = llm.fullNameNative;// Nếu không có MRZ hợp lệ, dùng trực tiếp các trường LLM/VIZ (không xác minh được)if (!best || (!best.valid && best.score < 0.75)) {// MRZ sai checksum và <75% check digit đúng (OCR đọc rác, có thể trùng hợp 1-2 check) không đáng tin: ưu tiên LLM/VIZ, MRZ rác chỉ làm giá trị dự phòngconst fb = src;r.surname = (fb.surname ?? '').toUpperCase() || r.surname;r.givenNames = (fb.givenNames ?? '').toUpperCase() || r.givenNames;r.documentNumber = normDocNo(fb.documentNumber) || r.documentNumber;r.nationality = normalizeCountryCode(fb.nationality ?? '').code || r.nationality;r.issuingState = normalizeCountryCode(llm?.issuingState ?? '').code || r.issuingState;r.documentCode = llm?.documentCode || r.documentCode;r.birthDate = normDate(fb.birthDate) || r.birthDate;r.expiryDate = normDate(fb.expiryDate) || r.expiryDate;r.sex = (fb.sex ?? '').toUpperCase().slice(0, 1) || r.sex;r.personalNumber = fb.personalNumber || r.personalNumber;if (r.documentNumber) warnings.push('Các trường MRZ chưa được xác minh bằng checksum');} else {// MRZ đủ tin nhưng có trường rỗng (vd ngày MRZ không parse được): bù từ LLM/VIZ thay vì để trốngconst filled: string[] = [];const fill = <K extends 'surname' | 'givenNames' | 'documentNumber' | 'nationality' | 'issuingState' | 'birthDate' | 'expiryDate' | 'sex'>(k: K, v: string, label: string) => {if (!r[k] && v) { r[k] = v as PassportRecord[K]; filled.push(label); }};fill('surname', (src.surname ?? '').toUpperCase(), 'họ');fill('givenNames', (src.givenNames ?? '').toUpperCase(), 'tên');fill('documentNumber', normDocNo(src.documentNumber), 'số HC');fill('nationality', normalizeCountryCode(src.nationality ?? '').code, 'quốc tịch');fill('issuingState', normalizeCountryCode(llm?.issuingState ?? '').code, 'nước cấp');fill('birthDate', normDate(src.birthDate), 'ngày sinh');fill('expiryDate', normDate(src.expiryDate), 'ngày hết hạn');fill('sex', (src.sex ?? '').toUpperCase().slice(0, 1), 'giới tính');if (filled.length) warnings.push(`MRZ thiếu ${filled.join(', ')}, đã lấy từ vùng chữ/LLM (chưa xác minh)`);}r.fullName = src.fullName?.trim() || [r.surname, r.givenNames].filter(Boolean).join(' ');67 unmodified linesif (checksumOk && countriesOk && mismatches.length === 0 && !unverifiedName && !riskyUnconfirmed && !ambiguous) confidence = 'HIGH';else if (best && (checksumOk || best.score >= 0.75)) confidence = 'MEDIUM';else confidence = 'LOW';// Đã dùng Gemini: lấy độ tin cậy do Gemini đánh giá (nếu có); mismatch logic vẫn chặn không cho HIGHconst llmConf = llm?.confidence;if (llmConf === 'HIGH' || llmConf === 'MEDIUM' || llmConf === 'LOW') {confidence = llmConf === 'HIGH' && mismatches.length > 0 ? 'MEDIUM' : llmConf;}return {record: r,
42 unmodified lines4344454647486 unmodified lines555657585960616242 unmodified linesmrz: string;}export interface ExtractionResult {record: PassportRecord;confidence: Confidence;6 unmodified linesmrz: MrzResult | null;viz: VizFields;/** Token thực tế Gemini báo về (usageMetadata) ở lần gọi gần nhất */llmUsage?: { promptTokens: number; outputTokens: number; thinkingTokens?: number; /** hệ số nhân tại thời điểm gọi (chốt cứng, đổi cấu hình không ảnh hưởng ảnh cũ) */ weight?: number; /** model đã gọi (để tính giá theo model) */ model?: string };llm?: (VizFields & { mrzLines?: string[]; notes?: string; fullNameNative?: string }) | null;}export const RECORD_FIELDS: { key: keyof PassportRecord; label: string }[] = [42 unmodified lines43444546474849505152535455565758596 unmodified lines6667686970717273747542 unmodified linesmrz: string;}export interface LlmUsage { promptTokens: number; outputTokens: number; thinkingTokens?: number; /** hệ số nhân tại thời điểm gọi (chốt cứng, đổi cấu hình không ảnh hưởng ảnh cũ) */ weight?: number; /** model đã gọi (để tính giá theo model) */ model?: string }/** Một lần gọi Gemini; at = epoch ms lúc gọi xong (dữ liệu cũ trước khi có lịch sử thì không có) */export interface LlmCall extends LlmUsage { at?: number }/** Danh sách các lần gọi Gemini của một kết quả; dữ liệu cũ chỉ có llmUsage thì coi là 1 lần (không rõ giờ) */export function llmCallsOf(r: { llmCalls?: LlmCall[]; llmUsage?: LlmUsage; sources?: string[] } | null | undefined): LlmCall[] {if (!r) return [];if (r.llmCalls?.length) return r.llmCalls;return r.llmUsage && r.sources?.includes('llm') ? [r.llmUsage] : [];}export interface ExtractionResult {record: PassportRecord;confidence: Confidence;6 unmodified linesmrz: MrzResult | null;viz: VizFields;/** Token thực tế Gemini báo về (usageMetadata) ở lần gọi gần nhất */llmUsage?: LlmUsage;/** Lịch sử MỌI lần gọi Gemini của ảnh này (đọc lại nhiều lần thì cộng dồn, mỗi lần một dòng kèm giờ) */llmCalls?: LlmCall[];llm?: (VizFields & { mrzLines?: string[]; notes?: string; confidence?: Confidence; fullNameNative?: string }) | null;}export const RECORD_FIELDS: { key: keyof PassportRecord; label: string }[] = [
98 unmodified lines9910010110210310498 unmodified linesoutput: { source: TokenOutputSource; jsonChars: number; jsonBytes: number; tokens: number; json?: unknown };/** Token thực tế Gemini báo về (chưa nhân), chỉ có khi ảnh đã gọi Gemini; thinking tách riêng */actual?: { input: number; output: number; thinking: number };total: number;exact: boolean;}98 unmodified lines9910010110210310410510610710898 unmodified linesoutput: { source: TokenOutputSource; jsonChars: number; jsonBytes: number; tokens: number; json?: unknown };/** Token thực tế Gemini báo về (chưa nhân), chỉ có khi ảnh đã gọi Gemini; thinking tách riêng */actual?: { input: number; output: number; thinking: number };/** Từng lần gọi Gemini (đọc lại nhiều lần thì nhiều dòng, mới nhất cuối); chỉ admin thấy *//** Bản dành cho user thường: token đã nhân hệ số, không lộ số thực tế. base = ước lượng một lần; calls = phụ thêm của từng lần đọc */billed?: { base: { input: number; output: number }; calls: { n: number; at?: number; input: number; output: number }[] };calls?: { n: number; at?: number; model?: string; input: number; output: number; thinking: number }[];total: number;exact: boolean;}
passport-check/README.md+1-1
passport-check/apps/server/src/gemini.ts+2-1
passport-check/apps/server/src/index.ts+8-4
passport-check/apps/server/src/jobs.ts+38-8
passport-check/apps/server/src/tokens.ts+53-25
passport-check/apps/web/src/components/GeminiActual.tsx+22-1
passport-check/apps/web/src/components/TokenDialog.tsx+21-5
passport-check/apps/web/src/lib/api.ts+4-1
passport-check/packages/core/src/mrz.ts+8
passport-check/packages/core/src/reconcile.ts+34-11
passport-check/packages/core/src/schema.ts+15-2
passport-check/packages/core/src/tokens.ts+4