Passport photo reader: a camera view with a frame, read in the browser
On the new person and new passport forms, next to Read:
- "Take a photo" opens a camera view (getUserMedia, the back camera): a
frame of the photo page's shape (125 by 88 mm), a band for the two lines,
and a hint from four checks of the band four times a second: too dark,
glare on the lines, no lines in the band, not sharp yet (variance of the
Laplacian). Once the band has looked readable for a second it takes the
photo itself; "Take the photo" and Cancel (or Escape) are there too.
The band where the frame showed it is read first; when that holds no
zone, the whole frame is searched.
- "Choose a picture" reads any image: EXIF orientation, the four quarter
turns, a tilt of 7 degrees either way; a failed read says when there is
glare in the picture.
Reading happens in the browser (static/mrz-photo.js): even light from a
local mean, the lines found with Tesseract's page layout, then the band cut
along their baselines, scaled and read as one block. Tesseract.js 7.0.0
and its core (SIMD and plain LSTM builds) with Doubango's MRZ model, all
served by the app from static/vendor/tesseract/ (README.txt: sources, npm
integrity, SHA-256, licenses Apache-2.0 and BSD-3), loaded at the first
photo. The photo never leaves the device: only the lines go into the zone's
field, and Read is pressed.
The server reads them like typed ones, through mrz::from_ocr when they are
no clean zone: the first line wherever it is, the second whose check digits
match best, a miscounted filler run cut or filled, K for < in the filler,
letters and digits where the zone has them, and look-alikes (O for 0, B for
8) swapped in the number fields only where a check digit asks for it,
preferring a digit. A photo's note asks to compare the names, which have no
check digit.
Only those two pages and the reader's files allow WebAssembly
('wasm-unsafe-eval', worker-src 'self', img-src blob:) and the camera
(Permissions-Policy camera=(self)); every other page keeps camera=().
Content types for .wasm and .gz.
Checks: fmt, clippy -D warnings, 99 unit and 50 integration tests (new:
from_ocr cases from real reads, tests/mrz_photo.rs for the markup, the two
policies, the files and a read from photo lines). In Edge (Playwright): 12
made-up phone photos and 16 specimen pages from Wikimedia Commons, every
zone that is readable read with all check digits matching (not: a hard
shadow across the lines; the specimens whose zone is blanked out), 1 to 5 s
each; the camera view with a fake camera: the glare and dark hints, and a
good picture taken by itself and the form filled in. Layout check 0
problems on both forms and a person, light and dark, desk and phone.
PLAN: task 7.3 done ahead of the client link, the decision recorded.
This commit is contained in:
1 parent
fc8c1b6a44
commit
1f54d93643
24 files changed
+2130
-52
No files matched your search
@@ -40,6 +40,8 @@ pub fn content_type(path: &str) -> &'static str {
|
||||
"ico" => "image/x-icon",
|
||||
"txt" => "text/plain; charset=utf-8",
|
||||
"woff2" => "font/woff2",
|
||||
"wasm" => "application/wasm",
|
||||
"gz" => "application/gzip",
|
||||
_ => "application/octet-stream",
|
||||
}
|
||||
}
|
||||
|
||||
+325
@@ -228,6 +228,266 @@ fn date(s: &str, past: bool, today: NaiveDate) -> Option<NaiveDate> {
|
||||
NaiveDate::from_ymd_opt(year, mm, dd)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ from a photo
|
||||
|
||||
/// Letters OCR reads where the zone has a digit, and the digit meant.
|
||||
const AS_DIGIT: &[(u8, u8)] = &[
|
||||
(b'O', b'0'),
|
||||
(b'Q', b'0'),
|
||||
(b'D', b'0'),
|
||||
(b'U', b'0'),
|
||||
(b'I', b'1'),
|
||||
(b'L', b'1'),
|
||||
(b'Z', b'2'),
|
||||
(b'A', b'4'),
|
||||
(b'S', b'5'),
|
||||
(b'G', b'6'),
|
||||
(b'T', b'7'),
|
||||
(b'B', b'8'),
|
||||
];
|
||||
|
||||
/// Characters OCR mixes up in the fields that hold letters and digits.
|
||||
const ALIKE: &[&[u8]] = &[b"0OQD", b"1I", b"2Z", b"5S", b"6G", b"8B"];
|
||||
|
||||
fn as_digit(b: u8) -> u8 {
|
||||
AS_DIGIT
|
||||
.iter()
|
||||
.find(|(l, _)| *l == b)
|
||||
.map_or(b, |(_, d)| *d)
|
||||
}
|
||||
|
||||
/// The first letter for a digit: 0 is O, 1 is I, 8 is B.
|
||||
fn as_letter(b: u8) -> u8 {
|
||||
AS_DIGIT
|
||||
.iter()
|
||||
.find(|(_, d)| *d == b)
|
||||
.map_or(b, |(l, _)| *l)
|
||||
}
|
||||
|
||||
fn alike(b: u8) -> Option<&'static [u8]> {
|
||||
ALIKE.iter().find(|g| g.contains(&b)).copied()
|
||||
}
|
||||
|
||||
fn as_str(b: &[u8]) -> &str {
|
||||
std::str::from_utf8(b).unwrap_or("")
|
||||
}
|
||||
|
||||
fn ok_bytes(field: &[u8], check: u8) -> bool {
|
||||
digit_ok(as_str(field), check)
|
||||
}
|
||||
|
||||
/// What OCR gives, upper case, only the zone's characters; `«` is `<<`.
|
||||
fn clean_line(line: &str) -> Vec<u8> {
|
||||
line.to_uppercase()
|
||||
.replace('«', "<<")
|
||||
.replace('‹', "<")
|
||||
.bytes()
|
||||
.filter(|b| b.is_ascii_uppercase() || b.is_ascii_digit() || *b == b'<')
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The first line holds the names: it starts with P (perhaps after a speck
|
||||
/// read as a letter), has filler and few digits.
|
||||
fn first_line(l: &[u8]) -> Option<Vec<u8>> {
|
||||
let digits = l.iter().filter(|b| b.is_ascii_digit()).count();
|
||||
let filler = l.iter().filter(|b| **b == b'<').count();
|
||||
if l.len() < 30 || digits >= 8 || filler < 2 {
|
||||
return None;
|
||||
}
|
||||
let l = match l {
|
||||
[b'P', ..] => l,
|
||||
[_, b'P', ..] => &l[1..],
|
||||
_ => return None,
|
||||
};
|
||||
let mut l = l.to_vec();
|
||||
l.resize(44, b'<');
|
||||
for b in &mut l[1..] {
|
||||
*b = as_letter(*b);
|
||||
}
|
||||
// a `<` among filler is often read as K, C or E
|
||||
for i in 5..44 {
|
||||
let left = i >= 7 && l[i - 2..i] == *b"<<";
|
||||
let right = i + 2 >= 44 || l[i + 1..(i + 3).min(44)].iter().all(|b| *b == b'<');
|
||||
if l[i] != b'<' && left && right && b"KCEL".contains(&l[i]) {
|
||||
l[i] = b'<';
|
||||
}
|
||||
}
|
||||
Some(l)
|
||||
}
|
||||
|
||||
/// A second line read a character too long or short, cut or filled to 44:
|
||||
/// in a run of filler first, where OCR most often miscounts, then at its
|
||||
/// ends.
|
||||
fn fitted(l: &[u8]) -> Vec<Vec<u8>> {
|
||||
let d = l.len() as i64 - 44;
|
||||
if d == 0 {
|
||||
return vec![l.to_vec()];
|
||||
}
|
||||
if d.abs() > 3 {
|
||||
return Vec::new();
|
||||
}
|
||||
let n = d.unsigned_abs() as usize;
|
||||
let mut out = Vec::new();
|
||||
let mut i = 0;
|
||||
while i < l.len() {
|
||||
if l[i] != b'<' {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
let start = i;
|
||||
while i < l.len() && l[i] == b'<' {
|
||||
i += 1;
|
||||
}
|
||||
let mut v = l.to_vec();
|
||||
if d > 0 && i - start > n {
|
||||
v.drain(start..start + n);
|
||||
} else if d < 0 {
|
||||
v.splice(start..start, std::iter::repeat_n(b'<', n));
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
out.push(v);
|
||||
}
|
||||
if d > 0 {
|
||||
out.push(l[n..].to_vec());
|
||||
out.push(l[..44].to_vec());
|
||||
} else {
|
||||
let mut v = l.to_vec();
|
||||
v.resize(44, b'<');
|
||||
out.push(v);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The readings of a field of letters and digits whose check digit
|
||||
/// matches, with the fewest characters swapped for a look-alike (at most
|
||||
/// two), each with what the swaps cost: a letter read where a digit was
|
||||
/// printed is the likelier mistake, so a swap to a digit costs 1 and one to
|
||||
/// a letter 2. The field as read when no reading matches.
|
||||
fn readings(field: &[u8], check: u8) -> Vec<(usize, Vec<u8>)> {
|
||||
if ok_bytes(field, check) {
|
||||
return vec![(0, field.to_vec())];
|
||||
}
|
||||
let spots: Vec<usize> = (0..field.len())
|
||||
.filter(|&i| alike(field[i]).is_some())
|
||||
.collect();
|
||||
let one = |f: &[u8], i: usize| -> Vec<(usize, Vec<u8>)> {
|
||||
alike(f[i])
|
||||
.unwrap_or_default()
|
||||
.iter()
|
||||
.filter(|c| **c != f[i])
|
||||
.map(|c| {
|
||||
let mut v = f.to_vec();
|
||||
v[i] = *c;
|
||||
(if c.is_ascii_digit() { 1 } else { 2 }, v)
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let mut found: Vec<(usize, Vec<u8>)> = spots
|
||||
.iter()
|
||||
.flat_map(|&i| one(field, i))
|
||||
.filter(|(_, v)| ok_bytes(v, check))
|
||||
.collect();
|
||||
if found.is_empty() {
|
||||
for (k, &i) in spots.iter().enumerate() {
|
||||
for (c1, v) in one(field, i) {
|
||||
for &j in &spots[k + 1..] {
|
||||
found.extend(
|
||||
one(&v, j)
|
||||
.into_iter()
|
||||
.filter(|(_, w)| ok_bytes(w, check))
|
||||
.map(|(c2, w)| (c1 + c2, w)),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if found.is_empty() {
|
||||
found.push((usize::MAX, field.to_vec()));
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// The second line with digits where the zone has digits and letters where
|
||||
/// it has letters, and the look-alikes in the number and the personal
|
||||
/// number that make the check digits match; with the number of checks that
|
||||
/// match and of characters swapped.
|
||||
fn second_line(l: &[u8]) -> (usize, usize, Vec<u8>) {
|
||||
let mut l = l.to_vec();
|
||||
for i in [
|
||||
9, 13, 14, 15, 16, 17, 18, 19, 21, 22, 23, 24, 25, 26, 27, 43,
|
||||
] {
|
||||
l[i] = as_digit(l[i]);
|
||||
}
|
||||
if l[42] != b'<' {
|
||||
l[42] = as_digit(l[42]);
|
||||
}
|
||||
for b in &mut l[10..13] {
|
||||
*b = as_letter(*b);
|
||||
}
|
||||
let mut best = (0, usize::MAX, l.clone());
|
||||
for (dn, number) in readings(&l[0..9], l[9]) {
|
||||
for (dp, personal) in readings(&l[28..42], l[42]) {
|
||||
let mut v = l.clone();
|
||||
v[0..9].copy_from_slice(&number);
|
||||
v[28..42].copy_from_slice(&personal);
|
||||
let checks = checks_ok(&v);
|
||||
let swapped = dn.saturating_add(dp);
|
||||
if checks > best.0 || (checks == best.0 && swapped < best.1) {
|
||||
best = (checks, swapped, v);
|
||||
}
|
||||
}
|
||||
}
|
||||
best
|
||||
}
|
||||
|
||||
/// How many of the five check digits of a second line match.
|
||||
fn checks_ok(l: &[u8]) -> usize {
|
||||
let composite = [&l[0..10], &l[13..20], &l[21..43]].concat();
|
||||
[
|
||||
ok_bytes(&l[0..9], l[9]),
|
||||
ok_bytes(&l[13..19], l[19]),
|
||||
ok_bytes(&l[21..27], l[27]),
|
||||
ok_bytes(&l[28..42], l[42]),
|
||||
ok_bytes(&composite, l[43]),
|
||||
]
|
||||
.iter()
|
||||
.filter(|ok| **ok)
|
||||
.count()
|
||||
}
|
||||
|
||||
/// The zone among lines read from a photo of the passport. OCR misreads
|
||||
/// a few characters (O for 0, one `<` too many), so this puts letters where
|
||||
/// the zone has letters and digits where it has digits, tries the readings
|
||||
/// a check digit asks for, and keeps the second line whose check digits
|
||||
/// match best (the lines may come in any order, more than once). None when
|
||||
/// no line looks like a passport's first line, or none like its second.
|
||||
pub fn from_ocr(text: &str) -> Option<String> {
|
||||
let lines: Vec<Vec<u8>> = text.lines().map(clean_line).collect();
|
||||
let first = lines.iter().find_map(|l| first_line(l))?;
|
||||
let mut best: Option<(usize, usize, Vec<u8>)> = None;
|
||||
for l in &lines {
|
||||
if l.iter().filter(|b| b.is_ascii_digit()).count() < 10 {
|
||||
continue;
|
||||
}
|
||||
for v in fitted(l) {
|
||||
let c = second_line(&v);
|
||||
if best
|
||||
.as_ref()
|
||||
.is_none_or(|b| c.0 > b.0 || (c.0 == b.0 && c.1 < b.1))
|
||||
{
|
||||
best = Some(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
let (_, _, second) = best?;
|
||||
Some(format!("{}\n{}", text_of(&first), text_of(&second)))
|
||||
}
|
||||
|
||||
fn text_of(b: &[u8]) -> String {
|
||||
String::from_utf8_lossy(b).into_owned()
|
||||
}
|
||||
|
||||
/// The fields of a zone to write, for demo data and tests.
|
||||
pub struct Compose<'a> {
|
||||
pub issuing_state: &'a str,
|
||||
@@ -334,6 +594,71 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// Each case: what OCR read in a photo, and the zone it holds.
|
||||
#[test]
|
||||
fn finds_the_zone_in_what_ocr_read() {
|
||||
let erika = "P<D<<MUSTERMANN<<ERIKA<<<<<<<<<<<<<<<<<<<<<<\nC01X00T478D<<8408129F3108011<<<<<<<<<<<<<<00";
|
||||
let gbr = "P<GBROBRIEN<SMITH<<JOHN<PAUL<<<<<<<<<<<<<<<<\n5334013720GBR5802140M2701013<<<<<<<<<<<<<<06";
|
||||
let cases: &[(&str, &str)] = &[
|
||||
// clean lines come back as they are
|
||||
(&specimen(), &specimen()),
|
||||
(erika, erika),
|
||||
// the lines in the wrong order, the second read twice, one
|
||||
// digit wrong in one reading (from a sideways photo)
|
||||
(
|
||||
"3334013720GBR5802140M2701013<<<<<<<<<<<<<<06\nP<GBROBRIEN<SMITH<<JOHN<PAUL<<<<<<<<<<<<<<<<\n5334013720GBR5802140M2701013<<<<<<<<<<<<<<06",
|
||||
gbr,
|
||||
),
|
||||
// O for 0 in the dates, a speck before the P, junk around
|
||||
(
|
||||
"REISEPASS PASSPORT\ncP<D<<MUSTERMANN<<ERIKA<<<<<<<<<<<<<<<<<<<<<<\nC01X00T478D<<84O8129F31O8011<<<<<<<<<<<<<<00\n12 08 1984",
|
||||
erika,
|
||||
),
|
||||
// a `<` too many in the filler, K for `<`, the first line short
|
||||
(
|
||||
"P<D<<MUSTERMANN<<ERIKA<<<<<<<<<<<<K<<<<<<<\nC01X00T478D<<8408129F3108011<<<<<<<<<<<<<<<00",
|
||||
erika,
|
||||
),
|
||||
// O for 0 in the passport number: its check digit decides
|
||||
(
|
||||
"P<D<<MUSTERMANN<<ERIKA<<<<<<<<<<<<<<<<<<<<<<\nC01XO0T478D<<8408129F3108011<<<<<<<<<<<<<<00",
|
||||
erika,
|
||||
),
|
||||
// spaces and « from a phone's own text reader
|
||||
(
|
||||
"P<D«MUSTERMANN«ERIKA««««««««««<<\nC01X00T478 D<<8408129F3108011<<<<<<<<<<<<<<00",
|
||||
erika,
|
||||
),
|
||||
];
|
||||
for (read, zone) in cases {
|
||||
assert_eq!(from_ocr(read).as_deref(), Some(*zone), "{read}");
|
||||
assert!(parse(zone, d(TODAY)).unwrap().all_ok());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finds_no_zone_where_there_is_none() {
|
||||
assert_eq!(from_ocr(""), None);
|
||||
assert_eq!(from_ocr("PASSPORT\nREISEPASS"), None);
|
||||
// a second line without a first (the names were covered)
|
||||
assert_eq!(
|
||||
from_ocr("C01X00T478D<<8408129F3108011<<<<<<<<<<<<<<00"),
|
||||
None
|
||||
);
|
||||
// a first line without a second
|
||||
assert_eq!(
|
||||
from_ocr("P<D<<MUSTERMANN<<ERIKA<<<<<<<<<<<<<<<<<<<<<<"),
|
||||
None
|
||||
);
|
||||
// a second line that starts with P is no first line
|
||||
assert_eq!(
|
||||
from_ocr(
|
||||
"PA12345673AUS0111090M3011179<<<<<<<<<<<<<<02\nPA12345673AUS0111090M3011179<<<<<<<<<<<<<<02"
|
||||
),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn composes_what_it_reads_and_maps_germany() {
|
||||
let text = compose(&Compose {
|
||||
|
||||
+53
-16
@@ -478,6 +478,34 @@ pub fn same_site(st: &AppState, headers: &HeaderMap) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Every page's policy: nothing but the app's own files, no inline script.
|
||||
pub const PAGE_CSP: &str = "default-src 'self'; img-src 'self' data:; style-src 'self'; \
|
||||
script-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; \
|
||||
form-action 'self'";
|
||||
|
||||
/// The policy of the pages that read a passport from a photo, and of the
|
||||
/// reader's own files: WebAssembly may run (a worker takes the policy of
|
||||
/// its script, in some browsers the page's), and a picture may be shown
|
||||
/// from a `blob:` address.
|
||||
pub const READER_CSP: &str = "default-src 'self'; img-src 'self' data: blob:; style-src 'self'; \
|
||||
script-src 'self' 'wasm-unsafe-eval'; worker-src 'self'; connect-src 'self'; \
|
||||
frame-ancestors 'none'; base-uri 'none'; form-action 'self'";
|
||||
|
||||
/// A page with the passport photo reader, or one of its files: its policy,
|
||||
/// and the camera allowed to this site for the camera view.
|
||||
pub fn with_reader(mut resp: Response) -> Response {
|
||||
let h = resp.headers_mut();
|
||||
h.insert(
|
||||
header::CONTENT_SECURITY_POLICY,
|
||||
HeaderValue::from_static(READER_CSP),
|
||||
);
|
||||
h.insert(
|
||||
HeaderName::from_static("permissions-policy"),
|
||||
HeaderValue::from_static("camera=(self), microphone=(), geolocation=()"),
|
||||
);
|
||||
resp
|
||||
}
|
||||
|
||||
async fn security_headers(req: Request, next: Next) -> Response {
|
||||
let mut resp = next.run(req).await;
|
||||
let h = resp.headers_mut();
|
||||
@@ -485,10 +513,7 @@ async fn security_headers(req: Request, next: Next) -> Response {
|
||||
if !h.contains_key(header::CONTENT_SECURITY_POLICY) {
|
||||
h.insert(
|
||||
header::CONTENT_SECURITY_POLICY,
|
||||
HeaderValue::from_static(
|
||||
"default-src 'self'; img-src 'self' data:; style-src 'self'; script-src 'self'; \
|
||||
connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'",
|
||||
),
|
||||
HeaderValue::from_static(PAGE_CSP),
|
||||
);
|
||||
}
|
||||
h.insert(
|
||||
@@ -504,10 +529,14 @@ async fn security_headers(req: Request, next: Next) -> Response {
|
||||
HeaderName::from_static("x-robots-tag"),
|
||||
HeaderValue::from_static("noindex, nofollow"),
|
||||
);
|
||||
h.insert(
|
||||
HeaderName::from_static("permissions-policy"),
|
||||
HeaderValue::from_static("camera=(), microphone=(), geolocation=()"),
|
||||
);
|
||||
// the photo reader's pages allow the camera (`with_reader`)
|
||||
let policy = HeaderName::from_static("permissions-policy");
|
||||
if !h.contains_key(&policy) {
|
||||
h.insert(
|
||||
policy,
|
||||
HeaderValue::from_static("camera=(), microphone=(), geolocation=()"),
|
||||
);
|
||||
}
|
||||
resp
|
||||
}
|
||||
|
||||
@@ -647,14 +676,22 @@ async fn version() -> Response {
|
||||
|
||||
async fn static_file(Path(path): Path<String>) -> Response {
|
||||
match embedded::static_file(&path) {
|
||||
Some(bytes) => (
|
||||
[
|
||||
(header::CONTENT_TYPE, embedded::content_type(&path)),
|
||||
(header::CACHE_CONTROL, "public, max-age=86400"),
|
||||
],
|
||||
bytes,
|
||||
)
|
||||
.into_response(),
|
||||
Some(bytes) => {
|
||||
let resp = (
|
||||
[
|
||||
(header::CONTENT_TYPE, embedded::content_type(&path)),
|
||||
(header::CACHE_CONTROL, "public, max-age=86400"),
|
||||
],
|
||||
bytes,
|
||||
)
|
||||
.into_response();
|
||||
// the photo reader's worker compiles WebAssembly
|
||||
if path.starts_with("vendor/tesseract/") {
|
||||
with_reader(resp)
|
||||
} else {
|
||||
resp
|
||||
}
|
||||
}
|
||||
None => StatusCode::NOT_FOUND.into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
+63
-27
@@ -10,7 +10,7 @@ use chrono::NaiveDate;
|
||||
use minijinja::context;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::{AppState, Res, not_found_page, page};
|
||||
use super::{AppState, Res, not_found_page, page, with_reader};
|
||||
use crate::audit::{self, Action, Entity, Entry};
|
||||
use crate::countries;
|
||||
use crate::dates::{self, Status};
|
||||
@@ -198,13 +198,27 @@ fn log<'a>(
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the zone typed into a form; a text that is no zone becomes a
|
||||
/// field error.
|
||||
fn read_zone(text: &str, today: NaiveDate, errors: &mut Errors) -> Option<Mrz> {
|
||||
/// Reads the zone typed into a form or read from a photo. When the text is
|
||||
/// no zone whose check digits all match, the zone in it as OCR read it
|
||||
/// (`mrz::from_ocr`: lines in any order, look-alike characters) replaces
|
||||
/// it, if that one matches or the text was no zone at all. A text that
|
||||
/// holds no zone becomes a field error.
|
||||
fn read_zone(text: &mut String, today: NaiveDate, errors: &mut Errors) -> Option<Mrz> {
|
||||
if text.is_empty() {
|
||||
return None;
|
||||
}
|
||||
match mrz::parse(text, today) {
|
||||
let typed = mrz::parse(text, today);
|
||||
if typed.as_ref().is_ok_and(Mrz::all_ok) {
|
||||
return typed.ok();
|
||||
}
|
||||
if let Some(found) = mrz::from_ocr(text)
|
||||
&& let Ok(m) = mrz::parse(&found, today)
|
||||
&& (m.all_ok() || typed.is_err())
|
||||
{
|
||||
*text = found;
|
||||
return Some(m);
|
||||
}
|
||||
match typed {
|
||||
Ok(m) => Some(m),
|
||||
Err(msg) => {
|
||||
err(errors, "mrz", msg);
|
||||
@@ -213,20 +227,40 @@ fn read_zone(text: &str, today: NaiveDate, errors: &mut Errors) -> Option<Mrz> {
|
||||
}
|
||||
}
|
||||
|
||||
fn zone_note(m: &Mrz, errors: &mut Errors) -> Option<String> {
|
||||
if m.all_ok() {
|
||||
Some("Filled in from the machine-readable zone; every check digit matches.".into())
|
||||
} else {
|
||||
err(
|
||||
errors,
|
||||
"mrz",
|
||||
format!(
|
||||
"Filled in, but the check digits do not match for: {}. Compare the lines with \
|
||||
the passport.",
|
||||
m.failed().join(", ")
|
||||
),
|
||||
);
|
||||
None
|
||||
/// `photo`: the lines came from the photo reader (the form's
|
||||
/// `mrz_source`), whose names have no check digit to catch a misread.
|
||||
fn zone_note(m: &Mrz, photo: bool, errors: &mut Errors) -> Option<String> {
|
||||
match (m.all_ok(), photo) {
|
||||
(true, false) => {
|
||||
Some("Filled in from the machine-readable zone; every check digit matches.".into())
|
||||
}
|
||||
(true, true) => Some(
|
||||
"Read from the photo; every check digit matches. The names have no check digit: \
|
||||
compare them with the passport."
|
||||
.into(),
|
||||
),
|
||||
(false, _) => {
|
||||
let what = if photo {
|
||||
"Read from the photo"
|
||||
} else {
|
||||
"Filled in"
|
||||
};
|
||||
err(
|
||||
errors,
|
||||
"mrz",
|
||||
format!(
|
||||
"{what}, but the check digits do not match for: {}. Compare the lines \
|
||||
with the passport and correct them{}.",
|
||||
m.failed().join(", "),
|
||||
if photo {
|
||||
", or take the photo again"
|
||||
} else {
|
||||
""
|
||||
}
|
||||
),
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -365,7 +399,7 @@ fn person_form_page(
|
||||
),
|
||||
None => ("New person".to_string(), "new", "/people".to_string()),
|
||||
};
|
||||
page(
|
||||
with_reader(page(
|
||||
st,
|
||||
user,
|
||||
"person_form.html",
|
||||
@@ -376,7 +410,7 @@ fn person_form_page(
|
||||
p, tab => "overview", f, pf, errors, mrz_note, mode, action, companies,
|
||||
..select_lists()
|
||||
},
|
||||
)
|
||||
))
|
||||
}
|
||||
|
||||
/// The companies the employer is chosen from (the active ones and the one
|
||||
@@ -415,7 +449,8 @@ pub async fn create(
|
||||
let mut pf = PersonForm::from_fields(&f);
|
||||
let mut ppf = PassportForm::from_fields(&f);
|
||||
let mut errors = Errors::new();
|
||||
let zone = read_zone(&ppf.mrz, today, &mut errors);
|
||||
let zone = read_zone(&mut ppf.mrz, today, &mut errors);
|
||||
let photo = get(&f, "mrz_source") == "photo";
|
||||
|
||||
if get(&f, "action") == "read-mrz" {
|
||||
let mut note = None;
|
||||
@@ -423,7 +458,7 @@ pub async fn create(
|
||||
Some(m) => {
|
||||
pf.take_mrz(m, true);
|
||||
ppf.take_mrz(m, true);
|
||||
note = zone_note(m, &mut errors);
|
||||
note = zone_note(m, photo, &mut errors);
|
||||
}
|
||||
None if ppf.mrz.is_empty() => {
|
||||
err(&mut errors, "mrz", "Paste the two lines first.");
|
||||
@@ -640,7 +675,7 @@ fn passport_form_page(
|
||||
),
|
||||
None => ("New passport", "new", format!("/people/{}/passports", p.id)),
|
||||
};
|
||||
page(
|
||||
with_reader(page(
|
||||
st,
|
||||
user,
|
||||
"passport_form.html",
|
||||
@@ -648,7 +683,7 @@ fn passport_form_page(
|
||||
"people",
|
||||
status,
|
||||
context! { p, tab => "overview", pf, errors, mrz_note, name_hint, mode, action, heading => title, ..select_lists() },
|
||||
)
|
||||
))
|
||||
}
|
||||
|
||||
pub async fn passport_new(
|
||||
@@ -710,14 +745,15 @@ async fn passport_save(
|
||||
let today = dates::today();
|
||||
let mut pf = PassportForm::from_fields(f);
|
||||
let mut errors = Errors::new();
|
||||
let zone = read_zone(&pf.mrz, today, &mut errors);
|
||||
let zone = read_zone(&mut pf.mrz, today, &mut errors);
|
||||
let photo = get(f, "mrz_source") == "photo";
|
||||
let mut notes = Notes::default();
|
||||
|
||||
if get(f, "action") == "read-mrz" {
|
||||
match &zone {
|
||||
Some(m) => {
|
||||
pf.take_mrz(m, true);
|
||||
notes.mrz_note = zone_note(m, &mut errors);
|
||||
notes.mrz_note = zone_note(m, photo, &mut errors);
|
||||
notes.name_hint = name_hint(m, &person);
|
||||
}
|
||||
None if pf.mrz.is_empty() => err(&mut errors, "mrz", "Paste the two lines first."),
|
||||
|
||||
Reference in new issue
Block a user