Spaces:
Running
Running
Deploy d16ef9a từ GitHub Actions
Browse filesFiles changed (11)
- passport-check/.gitignore+3
- passport-check/apps/server/src/gemini.ts+2-2
- passport-check/apps/server/src/jobs.ts+6-5
- passport-check/packages/core/src/reconcile.ts+77-5
- passport-check/packages/core/src/visa.ts+6-2
- passport-check/packages/core/test/china.test.ts+34
- passport-check/packages/core/test/llm-wins.test.tsAdded+88
- passport-check/packages/core/test/visa.test.ts+8
- passport-check/scripts/_retest-fetch.tsAdded+29
- passport-check/scripts/_retest-gemini.tsAdded+20
- passport-check/scripts/_retest-run.tsAdded+60
39 unmodified lines40414239 unmodified lines.vscode/*.pem*.key39 unmodified lines40414243444539 unmodified lines.vscode/*.pem*.key# ảnh hộ chiếu thật dùng để rà lỗi pipeline — KHÔNG commitpassport-wrong-images/
34 unmodified lines353637383940411 unmodified line4344454647484934 unmodified linessurname: str('Họ, theo chữ Latin như in trên trang'),givenNames: str('Tên, theo chữ Latin như in trên trang'),fullNameNative: str('Họ tên đầy đủ như in trên vùng chữ, GIỮ NGUYÊN dấu / chữ gốc (VD: NGUYỄN VĂN AN). Rỗng nếu không có.'),documentNumber: str('Số hộ chiếu in trên vùng chữ'),nationality: str('Quốc tịch, mã 3 chữ cái nếu có, nếu không thì như in'),birthDate: str('Ngày sinh dạng YYYY-MM-DD'),sex: str('M, F hoặc X'),1 unmodified lineplaceOfIssue: str('Nơi cấp như in trên trang (nếu có). Nếu in song ngữ thì chỉ lấy phần Latin'),issueDate: str('Ngày cấp dạng YYYY-MM-DD'),expiryDate: 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'),34 unmodified lines353637383940411 unmodified line4344454647484934 unmodified linessurname: str('Họ, theo chữ Latin như in trên trang'),givenNames: str('Tên, theo chữ Latin như in trên trang'),fullNameNative: str('Họ tên đầy đủ như in trên vùng chữ, GIỮ NGUYÊN dấu / chữ gốc (VD: NGUYỄN VĂN AN). Rỗng nếu không có.'),documentNumber: str('Số hộ chiếu in ở ô Passport No. trên vùng chữ của trang, đọc trực tiếp từ ô đó, KHÔNG chép từ dòng MRZ và KHÔNG kèm check digit (số trên trang thường 9 ký tự, VD H24056338; MRZ có thêm 1 chữ số kiểm tra ở cuối, VD H240563388 -> không lấy chữ số đó)'),nationality: str('Quốc tịch, mã 3 chữ cái nếu có, nếu không thì như in'),birthDate: str('Ngày sinh dạng YYYY-MM-DD'),sex: str('M, F hoặc X'),1 unmodified lineplaceOfIssue: str('Nơi cấp như in trên trang (nếu có). Nếu in song ngữ thì chỉ lấy phần Latin'),issueDate: str('Ngày cấp dạng YYYY-MM-DD'),expiryDate: str('Ngày hết hạn dạng YYYY-MM-DD'),authority: str('Cơ quan cấp như in trên trang (giữ đủ tên, VD IMMIGRATION DEPARTMENT, HONG KONG SPECIAL ADMINISTRATIVE REGION với hộ chiếu Hồng Kông)'),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'),
344 unmodified lines34534634734834935035135235335435535635735815 unmodified lines374375376377378379380381382383384344 unmodified linesreturn buf;}const LEVEL = { HIGH: 2, MEDIUM: 1, LOW: 0 } as const;function 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;}async function runOcr() {15 unmodified lineslet result: ExtractionResult;let rotation = it.rotation ?? 0;const img = await loadImage(buf);// lượt nhanh trước; chưa chắc chắn mới chạy lượt kỹ (nhiều biến thể ảnh hơn)const fast = await runPipeline(img, sharpOps, tessEngine, { thorough: false, maxAttempts: OCR_BUDGET.fast, onStep: step });result = reconcile({ mrz: fast.mrz, viz: fast.viz, sources: ['local'] });rotation = fast.rotation;if (result.confidence !== 'HIGH' || force === 'ocr' || force === 'full') {step('OCR kỹ');const deep = await runPipeline(img, sharpOps, tessEngine, { thorough: true, maxAttempts: OCR_BUDGET.deep, onStep: (s) => step(`OCR kỹ · ${s}`) });result = mergeResults(result, { mrz: deep.mrz, viz: deep.viz, source: 'server-ocr' });344 unmodified lines34534634734834935035135235335435535635735835915 unmodified lines375376377378379380381382383384385344 unmodified linesreturn buf;}function wantLlm(r: ExtractionResult, policy: BatchSettings['llm']): boolean {if (!llmAvailable() || policy === 'off') return false;if (policy === 'all') return true;// lượt nhanh chưa đạt HIGH -> hỏi Gemini luôn (không chạy lượt OCR kỹ tốn CPU)if (r.confidence !== 'HIGH') 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;// tới đây confidence = HIGH: chính sách 'low' không hỏi thêm, các chính sách còn lại chỉ hỏi khi cần kiểm trareturn policy !== 'low' && r.needsReview;}async function runOcr() {15 unmodified lineslet result: ExtractionResult;let rotation = it.rotation ?? 0;const img = await loadImage(buf);// chỉ chạy lượt nhanh; chưa HIGH thì chuyển Gemini (wantLlm). Lượt kỹ chỉ chạy khi admin ép OCR lại (force ocr/full)const fast = await runPipeline(img, sharpOps, tessEngine, { thorough: false, maxAttempts: OCR_BUDGET.fast, onStep: step });result = reconcile({ mrz: fast.mrz, viz: fast.viz, sources: ['local'] });rotation = fast.rotation;if (force === 'ocr' || force === 'full') {step('OCR kỹ');const deep = await runPipeline(img, sharpOps, tessEngine, { thorough: true, maxAttempts: OCR_BUDGET.deep, onStep: (s) => step(`OCR kỹ · ${s}`) });result = mergeResults(result, { mrz: deep.mrz, viz: deep.viz, source: 'server-ocr' });
42 unmodified lines4344454647484950515267 unmodified lines12012112212312412512 unmodified lines13813914014114214314468 unmodified lines2132142152162172183 unmodified lines22222322422522622722822923042 unmodified linessources: Source[];}export function reconcile({ mrz, viz, llm, sources }: Inputs): ExtractionResult {const warnings: string[] = [];const mismatches: string[] = [];const llmMrz = llm?.mrzLines?.length ? parseMrz(llm.mrzLines) : null;// Chọn MRZ tốt nhất giữa local và LLMlet best = mrz;67 unmodified linesfill('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(' ');12 unmodified lines// chỉ khi ngày sinh + ngày hết hạn MRZ đã qua checksumconst datesOk = !!best && ['birthDate', 'expiryDate'].every((f) => best!.checks.find((c) => c.field === f)?.valid);if (r.issuingState === 'CHN' && datesOk) chinaRules(r, warnings);// Đối chiếu chéo VIZ/LLM với MRZif (best && best.score >= 0.5) {68 unmodified lines};}/*** Hộ chiếu phổ thông Trung Quốc có quy tắc cố định (luật Hộ chiếu TQ, đúng với mọi mẫu đã kiểm):* - hạn 10 năm (5 năm nếu dưới 16 tuổi lúc cấp), ngày hết hạn = ngày cấp + N năm − 1 ngày3 unmodified lines*/function chinaRules(r: PassportRecord, warnings: string[]) {if (!r.expiryDate || !r.birthDate) return;const shift = (iso: string, years: number, days: number) => {const d = new Date(Date.UTC(Number(iso.slice(0, 4)) + years, Number(iso.slice(5, 7)) - 1, Number(iso.slice(8, 10)) + days));return d.toISOString().slice(0, 10);};const issue5 = shift(r.expiryDate, -5, 1);const child = Date.parse(issue5) - Date.parse(r.birthDate) < 16 * 365.2425 * 86400000;42 unmodified lines434445464748495051525367 unmodified lines12112212312412512612712812913013112 unmodified lines14414514614714814915015168 unmodified lines2202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882893 unmodified lines29329429529629729829930030130242 unmodified linessources: Source[];}export function reconcile({ mrz, viz, llm: llmRaw, sources }: Inputs): ExtractionResult {const warnings: string[] = [];const mismatches: string[] = [];const llmMrz = llmRaw?.mrzLines?.length ? parseMrz(llmRaw.mrzLines) : null;const llm = stripDocNoCheckDigit(llmRaw, llmMrz, mrz);// Chọn MRZ tốt nhất giữa local và LLMlet best = mrz;67 unmodified linesfill('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)`);// Họ, tên, số HC: Gemini đọc trang in chính xác hơn OCR MRZ cục bộ (tên không có checksum, MRZ hay lẫn rác "LLL…")if (best && llm && llm.isPassport !== false) {const over = llmWinsIdentity(r, llm, best);if (over.length) warnings.push(`Đã lấy từ Gemini thay cho MRZ cục bộ: ${over.join(', ')}`);}}r.fullName = src.fullName?.trim() || [r.surname, r.givenNames].filter(Boolean).join(' ');12 unmodified lines// chỉ khi ngày sinh + ngày hết hạn MRZ đã qua checksumconst datesOk = !!best && ['birthDate', 'expiryDate'].every((f) => best!.checks.find((c) => c.field === f)?.valid);// hộ chiếu Hồng Kông (HKSAR) cũng mang mã nước cấp CHN nhưng hạn đúng 10 năm (không trừ 1 ngày) -> không áp quy tắc TQ đại lụcif (r.issuingState === 'CHN' && datesOk && !isHongKong(r, src)) chinaRules(r, warnings);// Đối chiếu chéo VIZ/LLM với MRZif (best && best.score >= 0.5) {68 unmodified lines};}/*** Hộ chiếu Hồng Kông (HKSAR): nhận ra qua cơ quan cấp / nơi cấp in trên trang (Immigration Department, Hong Kong SAR, 香港)* hoặc số hộ chiếu dạng H/K + 8 chữ số (hộ chiếu TQ đại lục bắt đầu bằng E/G/P...).*/export function isHongKong(r: Pick<PassportRecord, 'documentNumber' | 'issuingState'>, src: VizFields): boolean {const text = `${src.authority ?? ''} ${src.placeOfIssue ?? ''}`;return /HONG\s*KONG|香港/i.test(text) || (r.issuingState === 'CHN' && /^[HK]\d{8}$/.test(r.documentNumber));}/** Hai số HC chỉ khác nhau ở các ký tự dễ nhầm Q/O/D với số 0 */function onlyZeroLookalikes(a: string, b: string): boolean {if (a.length !== b.length || a === b) return false;const f = (c: string) => (c === 'Q' || c === 'O' || c === 'D' ? '0' : c);return [...a].every((c, i) => c === b[i] || (f(c) === f(b[i]) && (c === '0' || b[i] === '0' || f(c) === '0')));}/*** Cho Gemini thắng ở họ / tên / số hộ chiếu (đã đo: 94,5% -> 98,8% trên 491 ảnh).* Ngày tháng, giới tính, quốc tịch vẫn theo MRZ có checksum (Gemini hay đọc sai năm).* Ngoại lệ: số HC chỉ khác ở ký tự Q/O/D~0 mà check digit số HC của MRZ đúng thì giữ MRZ* (Gemini hay đọc chữ Q thành số 0: EQ8836235 -> E08836235).* Trả về nhãn các trường đã bị Gemini ghi đè giá trị MRZ.*/function llmWinsIdentity(r: PassportRecord, llm: LlmOutput, best: MrzResult): string[] {const changed: string[] = [];const surname = (llm.surname ?? '').trim().toUpperCase();const given = (llm.givenNames ?? '').trim().toUpperCase();const docNo = normDocNo(llm.documentNumber);const keyOf = (x: string) => x.replace(/[^A-Z]/g, '');if (surname && given) {// họ + tên phải đi cùng nhau từ Gemini để không ghép chéo với MRZif (keyOf(surname) !== keyOf(r.surname)) { r.surname = surname; changed.push('họ'); }if (keyOf(given) !== keyOf(r.givenNames)) { r.givenNames = given; changed.push('tên'); }} else if (surname && !r.surname) {r.surname = surname; changed.push('họ');}if (docNo && docNo !== r.documentNumber) {const docChecked = best.checks.find((c) => c.field === 'documentNumber')?.valid;if (!(docChecked && onlyZeroLookalikes(docNo, r.documentNumber))) {r.documentNumber = docNo; changed.push('số HC');}}return changed;}/*** Gemini hay chép số hộ chiếu từ dòng MRZ, kèm luôn check digit (H240563388 thay vì H24056338 in trên trang).* Số trên trang là 9 ký tự không có check digit -> bỏ chữ số thừa nếu nó đúng bằng "số + check digit" trong MRZ.*/function stripDocNoCheckDigit(llm: LlmOutput | null | undefined, llmMrz: MrzResult | null, mrz: MrzResult | null): LlmOutput | null | undefined {if (!llm?.documentNumber) return llm;const d = normDocNo(llm.documentNumber);for (const m of [llmMrz, mrz]) {if (!m || (m.format !== 'TD3' && m.format !== 'TD2')) continue;const l2 = m.lines[1] ?? '';const cd = l2[9];if (!cd || cd === '<') continue;for (const field of [l2.slice(0, 9).replace(/</g, ''), m.documentNumber]) {if (field && d === normDocNo(field + cd)) return { ...llm, documentNumber: field };}}return llm;}/*** Hộ chiếu phổ thông Trung Quốc có quy tắc cố định (luật Hộ chiếu TQ, đúng với mọi mẫu đã kiểm):* - hạn 10 năm (5 năm nếu dưới 16 tuổi lúc cấp), ngày hết hạn = ngày cấp + N năm − 1 ngày3 unmodified lines*/function chinaRules(r: PassportRecord, warnings: string[]) {if (!r.expiryDate || !r.birthDate) return;// cộng ngày TRƯỚC rồi mới trừ năm: hết hạn 28/02/2034 -> 01/03/2034 -> 01/03/2024 (trừ năm trước sẽ ra 29/02/2024 sai)const shift = (iso: string, years: number, days: number) => {const d = new Date(Date.UTC(Number(iso.slice(0, 4)), Number(iso.slice(5, 7)) - 1, Number(iso.slice(8, 10)) + days));return new Date(Date.UTC(d.getUTCFullYear() + years, d.getUTCMonth(), d.getUTCDate())).toISOString().slice(0, 10);};const issue5 = shift(r.expiryDate, -5, 1);const child = Date.parse(issue5) - Date.parse(r.birthDate) < 16 * 365.2425 * 86400000;
181 unmodified lines182183184185186187188189190181 unmodified linesexport interface ExportEntry { item: StoredItem; rec: PassportRecord; trip: TripInfo }/** Hộ chiếu Trung Quốc (theo nước cấp, không có thì theo quốc tịch) */function isChinese(rec: Pick<PassportRecord, 'issuingState' | 'nationality'>): boolean {return (rec.issuingState || rec.nationality || '').toUpperCase() === 'CHN';}/**181 unmodified lines182183184185186187188189190191192193194181 unmodified linesexport interface ExportEntry { item: StoredItem; rec: PassportRecord; trip: TripInfo }/*** Hộ chiếu Trung Quốc: nước cấp HOẶC quốc tịch là CHN. Không chỉ dựa vào nước cấp vì* OCR có thể đọc lệch một trường (vd quốc tịch CHN nhưng nước cấp ra mã lạ) làm khách* bị xếp nhầm lên nhóm đầu.*/function isChinese(rec: Pick<PassportRecord, 'issuingState' | 'nationality'>): boolean {return [rec.issuingState, rec.nationality].some((c) => (c ?? '').toUpperCase() === 'CHN');}/**
238 unmodified lines239240241238 unmodified linesexpect(reconcile({ mrz: r, viz: {}, sources: ['local'] }).confidence).not.toBe('HIGH');});});238 unmodified lines239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275238 unmodified linesexpect(reconcile({ mrz: r, viz: {}, sources: ['local'] }).confidence).not.toBe('HIGH');});});describe('hộ chiếu Hồng Kông (mã nước cấp CHN nhưng không theo quy tắc TQ đại lục)', () => {const doc = 'H24056338', birth = '580215', exp = '350818', opt = 'C4962808<<<<<<';const head = `${doc}${checkDigit(doc)}CHN${birth}${checkDigit(birth)}M${exp}${checkDigit(exp)}${opt}${checkDigit(opt)}`;const comp = checkDigit(head.slice(0, 10) + head.slice(13, 20) + head.slice(21, 43));const HK = ['P<CHNLAW<<SUN<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<', head + comp];const hk = () => parseMrz(HK)!;it('không suy ngày cấp theo quy tắc TQ (hạn đúng 10 năm, không trừ 1 ngày)', () => {expect(hk().valid).toBe(true);const r = reconcile({ mrz: hk(), viz: { issueDate: '2025-08-18', authority: 'IMMIGRATION DEPARTMENT, HONG KONG SPECIAL ADMINISTRATIVE REGION' }, sources: ['local'] }).record;expect(r.issueDate).toBe('2025-08-18');expect(r.authority).toContain('HONG KONG');});it('nhận ra qua số hộ chiếu H/K + 8 chữ số khi chưa đọc được cơ quan cấp', () => {const r = reconcile({ mrz: hk(), viz: { issueDate: '2025-08-18' }, sources: ['local'] }).record;expect(r.issueDate).toBe('2025-08-18');expect(r.authority).toBe('');});it('hộ chiếu TQ đại lục vẫn áp quy tắc cũ', () => {expect(reconcile({ mrz: parseMrz(NEW), viz: { issueDate: '2026-10-08' }, sources: ['local'] }).record.issueDate).toBe('2026-10-10');});it('bỏ check digit Gemini chép thừa vào số hộ chiếu (H240563388 -> H24056338)', () => {const res = reconcile({ mrz: hk(), viz: {}, llm: { documentNumber: 'H240563388', mrzLines: HK, issueDate: '2025-08-18', isPassport: true }, sources: ['local', 'llm'] });expect(res.record.documentNumber).toBe('H24056338');expect(res.llm?.documentNumber).toBe('H24056338');expect(res.warnings.some((w) => w.includes('Số HC'))).toBe(false);});it('số hộ chiếu Gemini đọc từ trang khác số MRZ -> Gemini thắng và có cảnh báo', () => {const res = reconcile({ mrz: hk(), viz: {}, llm: { documentNumber: 'H24056999', mrzLines: HK, isPassport: true }, sources: ['local', 'llm'] });expect(res.record.documentNumber).toBe('H24056999');expect(res.warnings.some((w) => w.includes('Gemini thay cho MRZ') && w.includes('số HC'))).toBe(true);});});
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788import { describe, expect, it } from 'vitest';import { checkDigit, parseMrz } from '../src/mrz.ts';import { reconcile } from '../src/reconcile.ts';
/** Dựng MRZ TD3 hợp lệ checksum, họ/tên và số HC tuỳ ý */function td3(doc: string, name = 'HUANG<<JIANYE') { const birth = '741102', exp = '361009', opt = 'LLMGLNKINCLFA9'; const l1 = `PPCHN${name}`.padEnd(44, '<'); const head = `${doc}${checkDigit(doc)}CHN${birth}${checkDigit(birth)}M${exp}${checkDigit(exp)}${opt}${checkDigit(opt)}`; const comp = checkDigit(head.slice(0, 10) + head.slice(13, 20) + head.slice(21, 43)); return [l1, head + comp];}
const run = (lines: string[], llm: Record<string, unknown>) => reconcile({ mrz: parseMrz(lines), viz: {}, llm: { isPassport: true, ...llm }, sources: ['local', 'llm'] });
describe('Gemini thắng họ / tên / số hộ chiếu', () => { const lines = td3('ES6937641');
it('tên MRZ đọc sai nhưng checksum vẫn đúng -> lấy tên Gemini', () => { const bad = td3('ES6937641', 'HUANG<<JIANYF'); expect(parseMrz(bad)!.valid).toBe(true); const res = run(bad, { surname: 'HUANG', givenNames: 'JIANYE' }); expect(res.record.givenNames).toBe('JIANYE'); expect(res.record.surname).toBe('HUANG'); expect(res.warnings.some((w) => w.includes('Gemini thay cho MRZ') && w.includes('tên'))).toBe(true); });
it('họ/tên khớp MRZ thì không báo ghi đè', () => { const res = run(lines, { surname: 'Huang', givenNames: 'Jianye', documentNumber: 'ES6937641' }); expect(res.record.surname).toBe('HUANG'); expect(res.warnings.some((w) => w.includes('Gemini thay cho MRZ'))).toBe(false); });
it('số HC MRZ đọc sai ký tự (checksum trùng) -> lấy số Gemini đọc từ trang', () => { const bad = td3('E86937641'); const res = run(bad, { surname: 'HUANG', givenNames: 'JIANYE', documentNumber: 'ES6937641' }); expect(res.record.documentNumber).toBe('ES6937641'); });
it('Gemini đọc chữ Q thành số 0 và check digit MRZ đúng -> giữ số MRZ', () => { const q = td3('EQ8836235'); const res = run(q, { surname: 'HUANG', givenNames: 'JIANYE', documentNumber: 'E08836235' }); expect(res.record.documentNumber).toBe('EQ8836235'); });
it('Gemini chép cả check digit vào số HC -> vẫn được bỏ rồi so với MRZ', () => { const res = run(lines, { surname: 'HUANG', givenNames: 'JIANYE', documentNumber: 'ES69376412' }); expect(res.record.documentNumber).toBe('ES6937641'); });
it('ngày tháng, giới tính, quốc tịch vẫn theo MRZ dù Gemini đọc khác', () => { const res = run(lines, { surname: 'HUANG', givenNames: 'JIANYE', birthDate: '1974-11-03', expiryDate: '2026-10-09', sex: 'F', nationality: 'CHINESE' }); expect([res.record.birthDate, res.record.expiryDate, res.record.sex, res.record.nationality]).toEqual(['1974-11-02', '2036-10-09', 'M', 'CHN']); });
it('Gemini chỉ trả họ mà thiếu tên -> không ghép chéo, giữ họ/tên của MRZ', () => { const res = run(lines, { surname: 'WANG', givenNames: '' }); expect([res.record.surname, res.record.givenNames]).toEqual(['HUANG', 'JIANYE']); });
it('Gemini báo không phải hộ chiếu -> không ghi đè', () => { const res = run(lines, { isPassport: false, surname: 'WANG', givenNames: 'XX', documentNumber: 'E11111111' }); expect(res.record.surname).toBe('HUANG'); expect(res.record.documentNumber).toBe('ES6937641'); });});
describe('chinaRules: ngày cấp quanh năm nhuận', () => { // hộ chiếu cấp 01/03/2024 hết hạn 28/02/2034 (2034 không nhuận): phải ra 2024-03-01, không phải 2024-02-29 const mk = (birth: string, exp: string) => { const doc = 'EL9566146'; const head = `${doc}${checkDigit(doc)}CHN${birth}${checkDigit(birth)}F${exp}${checkDigit(exp)}${'NFNEMOLAMDPEA9'}${checkDigit('NFNEMOLAMDPEA9')}`; const comp = checkDigit(head.slice(0, 10) + head.slice(13, 20) + head.slice(21, 43)); return parseMrz(['POCHNZHAO<<WEIMIN'.padEnd(44, '<'), head + comp]); }; it('hết hạn 28/02/2034 -> ngày cấp 01/03/2024', () => { const r = reconcile({ mrz: mk('730814', '340228'), viz: { issueDate: '2024-03-01' }, sources: ['local'] }); expect(r.record.issueDate).toBe('2024-03-01'); expect(r.warnings.some((w) => w.includes('quy tắc hộ chiếu TQ'))).toBe(false); }); it('hết hạn 29/02/2036 (nhuận) -> ngày cấp 01/03/2026', () => { expect(reconcile({ mrz: mk('730814', '360229'), viz: {}, sources: ['local'] }).record.issueDate).toBe('2026-03-01'); }); it('ngày thường vẫn hết hạn + 1 ngày - 10 năm', () => { expect(reconcile({ mrz: mk('730814', '361101'), viz: {}, sources: ['local'] }).record.issueDate).toBe('2026-11-02'); });});40 unmodified lines41424344454640 unmodified linesconst s = sortMaleFirst([{ rec: { sex: 'F' }, n: 1 }, { rec: { sex: 'M' }, n: 2 }, { rec: { sex: 'F' }, n: 3 }, { rec: { sex: 'M' }, n: 4 }]);expect(s.map((x) => x.n)).toEqual([2, 4, 1, 3]);});});describe('xuất file theo mẫu', () => {40 unmodified lines414243444546474849505152535440 unmodified linesconst s = sortMaleFirst([{ rec: { sex: 'F' }, n: 1 }, { rec: { sex: 'M' }, n: 2 }, { rec: { sex: 'F' }, n: 3 }, { rec: { sex: 'M' }, n: 4 }]);expect(s.map((x) => x.n)).toEqual([2, 4, 1, 3]);});it('quốc tịch CHN nhưng nước cấp OCR lệch vẫn tính là khách Trung Quốc', () => {const s = sortMaleFirst([{ rec: { sex: 'F', issuingState: 'CHM', nationality: 'CHN' }, n: 1 },{ rec: { sex: 'M', issuingState: 'CHN', nationality: 'CHN' }, n: 2 },{ rec: { sex: 'F', issuingState: 'CHN', nationality: 'CHN' }, n: 3 },]);expect(s.map((x) => x.n)).toEqual([2, 1, 3]);});});describe('xuất file theo mẫu', () => {
1234567891011121314151617181920212223242526272829// Chỉ đọc Firestore + tải ảnh từ Telegram vào thư mục OUT. Không ghi gì lên Firestore/Telegram.import fs from 'node:fs';import path from 'node:path';import { db } from '../apps/server/src/firebase.ts';import { downloadFile } from '../apps/server/src/telegram.ts';
const OUT = process.argv[2];const bs = await db().collection('batches').get();const its = await db().collection('batches').get().then(() => db().collectionGroup('items').get());const manifest: any[] = [];const batchName = new Map(bs.docs.map((d) => [d.id, (d.data() as any).name]));console.log(`${bs.size} lô, ${its.size} item`);const list = its.docs.map((d) => d.data() as any);const seen = new Set<string>();let n = 0;for (const it of list) { if (!it.telegram || seen.has(it.sha256)) { manifest.push({ id: it.id, batchId: it.batchId, skipped: it.telegram ? 'dup' : 'no-telegram' }); continue; } seen.add(it.sha256); const file = `${it.batchId}__${it.id}${path.extname(it.name || '') || '.jpg'}`; const dst = path.join(OUT, file); try { if (!fs.existsSync(dst)) fs.writeFileSync(dst, await downloadFile(it.telegram.fileId)); manifest.push({ id: it.id, batchId: it.batchId, batchName: batchName.get(it.batchId), name: it.name, file, status: it.status, confidence: it.confidence, stored: it.result?.record ?? null }); } catch (e) { manifest.push({ id: it.id, batchId: it.batchId, file, error: (e as Error).message }); } if (++n % 20 === 0) console.log(n);}fs.writeFileSync(path.join(OUT, '..', 'manifest.json'), JSON.stringify(manifest, null, 1));console.log('xong', n, 'ảnh');process.exit(0);1234567891011121314151617181920// Gọi Gemini cho mọi ảnh, lưu đầu ra thô (JSONL, chạy tiếp được).import fs from 'node:fs';import path from 'node:path';import { geminiExtract } from '../apps/server/src/gemini.ts';const [DIR, OUT] = [process.argv[2], process.argv[3]];const done = new Set(fs.existsSync(OUT) ? fs.readFileSync(OUT, 'utf8').split('\n').filter(Boolean).map((l) => JSON.parse(l).file) : []);const files = fs.readdirSync(DIR).filter((f) => /\.(jpe?g|png)$/i.test(f) && !done.has(f)).sort();let i = 0, n = 0;await Promise.all(Array.from({ length: 4 }, async () => { while (i < files.length) { const file = files[i++]; try { const { llm } = await geminiExtract(fs.readFileSync(path.join(DIR, file)), file.endsWith('.png') ? 'image/png' : 'image/jpeg'); fs.appendFileSync(OUT, JSON.stringify({ file, llm }) + '\n'); } catch (e) { fs.appendFileSync(OUT, JSON.stringify({ file, error: (e as Error).message }) + '\n'); } if (++n % 50 === 0) console.log(n, files.length); }}));console.log('XONG', n);process.exit(0);123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960// OCR (nhanh -> kỹ nếu chưa HIGH) + Gemini cho mọi ảnh, giống jobs.ts. Ghi mỗi ảnh 1 dòng JSONL (chạy tiếp được).import fs from 'node:fs';import path from 'node:path';import { mergeResults, reconcile, runPipeline } from '../packages/core/src/index.ts';import { loadImage, sharpOps, tessEngine, shutdownOcr } from '../apps/server/src/ocr.ts';import { geminiExtract } from '../apps/server/src/gemini.ts';import { OCR_BUDGET } from '../apps/server/src/jobs.ts';
const [DIR, OUT] = [process.argv[2], process.argv[3]];const done = new Set(fs.existsSync(OUT) ? fs.readFileSync(OUT, 'utf8').split('\n').filter(Boolean).map((l) => JSON.parse(l).file) : []);const files = fs.readdirSync(DIR).filter((f) => /\.(jpe?g|png)$/i.test(f) && !done.has(f)).sort();const write = (o: unknown) => fs.appendFileSync(OUT, JSON.stringify(o) + '\n');const pending: Promise<void>[] = [];let llmRun = 0; const llmWait: (() => void)[] = [];const RPM = Number(process.env.GEMINI_RPM ?? 10);let nextCall = 0;// giới hạn số lần gọi Gemini / phút: các lần gọi cách nhau tối thiểu 60000/RPM msconst slot = async () => { if (llmRun >= 4) await new Promise<void>((r) => llmWait.push(r)); llmRun++; const at = Math.max(Date.now(), nextCall); nextCall = at + 60000 / RPM; if (at > Date.now()) await new Promise((r) => setTimeout(r, at - Date.now()));};const free = () => { llmRun--; llmWait.shift()?.(); };const t00 = Date.now(); let n = 0;for (const file of files) { const t0 = Date.now(); let result: any, err = ''; let buf: Buffer; try { buf = fs.readFileSync(path.join(DIR, file)); const img = await loadImage(buf); const fast = await runPipeline(img, sharpOps, tessEngine, { thorough: false, maxAttempts: OCR_BUDGET.fast }); result = reconcile({ mrz: fast.mrz, viz: fast.viz, sources: ['local'] }); if (result.confidence !== 'HIGH') { const deep = await runPipeline(img, sharpOps, tessEngine, { thorough: true, maxAttempts: OCR_BUDGET.deep }); result = mergeResults(result, { mrz: deep.mrz, viz: deep.viz, source: 'server-ocr' }); } } catch (e) { err = (e as Error).message; } const ocrMs = Date.now() - t0; const ocrOnly = result?.record; const ocrConf = result?.confidence; pending.push((async () => { await slot(); const t1 = Date.now(); try { if (!result) throw new Error('OCR lỗi: ' + err); const { llm, usage } = await geminiExtract(buf!, file.endsWith('.png') ? 'image/png' : 'image/jpeg'); const m = mergeResults(result, { llm, source: 'llm' }); write({ file, ocrMs, llmMs: Date.now() - t1, rawMrz: result.mrz, rawViz: result.viz, rawLlm: llm, ocrConf, ocrOnly, final: m.record, confidence: m.confidence, checksumOk: m.checksumOk, needsReview: m.needsReview, warnings: m.warnings, usage }); } catch (e) { write({ file, ocrMs, ocrConf, ocrOnly, final: result?.record ?? null, confidence: result?.confidence, error: (e as Error).message }); } finally { free(); } })()); if (++n % 10 === 0) console.log(n, files.length, ((Date.now() - t00) / 1000).toFixed(0) + 's');}await Promise.all(pending);console.log('XONG', n, ((Date.now() - t00) / 1000).toFixed(0) + 's');await shutdownOcr();process.exit(0);passport-check/.gitignore+3
passport-check/apps/server/src/gemini.ts+2-2
passport-check/apps/server/src/jobs.ts+6-5
passport-check/packages/core/src/reconcile.ts+77-5
passport-check/packages/core/src/visa.ts+6-2
passport-check/packages/core/test/china.test.ts+34
passport-check/packages/core/test/llm-wins.test.tsAdded+88
passport-check/packages/core/test/visa.test.ts+8
passport-check/scripts/_retest-fetch.tsAdded+29
passport-check/scripts/_retest-gemini.tsAdded+20
passport-check/scripts/_retest-run.tsAdded+60