From e55aa6fc4015f29afe33262971d4e1df0b747074 Mon Sep 17 00:00:00 2001 From: Hergen Dillema Date: Mon, 12 Apr 2021 17:43:29 +0200 Subject: [PATCH 01/26] Finding and parsing MRZ v2 - Reworked MRZ finding algorithm - Rewrite of codebase --- src/IdentityDocument.php | 103 +++++++++++++ src/IdentityDocuments.php | 313 -------------------------------------- src/IdentityImage.php | 50 ++++++ src/MRZ.php | 183 ++++++++++++++++++++++ src/MrzSearcher.php | 143 +++++++++++++++++ 5 files changed, 479 insertions(+), 313 deletions(-) create mode 100644 src/IdentityDocument.php delete mode 100644 src/IdentityDocuments.php create mode 100644 src/IdentityImage.php create mode 100644 src/MRZ.php create mode 100644 src/MrzSearcher.php diff --git a/src/IdentityDocument.php b/src/IdentityDocument.php new file mode 100644 index 0000000..26d0a2a --- /dev/null +++ b/src/IdentityDocument.php @@ -0,0 +1,103 @@ +addFrontImage($frontImage); + } + if($backImage){ + $this->addBackImage($backImage); + } + + $this->mrzSearcher = new MrzSearcher(); + } + + public function addFrontImage($image): void + { + $image = $this->createImage($image); + $this->frontImage = new IdentityImage($image); + $this->images[] = &$this->frontImage; + } + + public function addBackImage($image): void + { + $image = $this->createImage($image); + $this->backImage = new IdentityImage($image); + $this->images[] = &$this->backImage; + } + + private function createImage($file): ?Image + { + if(!is_file($file)){ + return null; + } + file_get_contents($file->getRealPath()); + return Img::make($file); + } + + private function mergeBackAndFrontImages(){ + if(!$this->frontImage || !$this->backImage){ + return false; + } + if(!$this->mergedImage = $this->frontImage->merge($this->backImage)){ + return false; + } + $this->images = [&$this->mergedImage]; + return true; + } + + private function mrz(): string + { + $this->mrz = ""; + foreach($this->images as $image){ + $image->ocr(); + if($mrz = $this->mrzSearcher->search($image->text)){ + $this->mrz = $mrz??""; + break; + } + } + + return $this->mrz; + } + + public function getMrz(): string + { + if(!isset($this->mrz)){ + $this->mrz(); + } + return $this->mrz; + } + + public function getParsedMrz(): array + { + if(!isset($this->parsedMrz) && $this->mrz){ + $this->parseMrz(); + } + return $this->parsedMrz??[]; + } + + public function setMrz($mrz): IdentityDocument + { + $this->mrz = $mrz; + return $this; + } + + private function parseMrz(): void + { + $this->parsedMrz = $this->mrzSearcher->parse($this->getMrz()); + } +} diff --git a/src/IdentityDocuments.php b/src/IdentityDocuments.php deleted file mode 100644 index 2a75a1e..0000000 --- a/src/IdentityDocuments.php +++ /dev/null @@ -1,313 +0,0 @@ -all(), [ - 'front_img' => 'mimes:jpeg,png,jpg|max:5120', - 'back_img' => 'mimes:jpeg,png,jpg|max:5120', - ]); - if ($validator->fails()) { - return json_encode([ - 'error' => $validator->errors()->first(), - 'success' => false, - ]); - } - - $front_img = $request->front_img; - $back_img = $request->back_img; - - $imageAnnotator = new ImageAnnotatorClient( - ['credentials' => config('google_key')] - ); - - $images = (object) [ - 'front_img' => ($front_img) ? file_get_contents($front_img->getRealPath()) : null, - 'back_img' => ($back_img) ? file_get_contents($back_img->getRealPath()) : null, - ]; - - if ($images->front_img && $images->back_img) { - $base_img = Image::make($images->front_img); - $full_img = $base_img->filter(new MergeFilter(Image::make($images->back_img))); - } elseif ($images->front_img) { - $full_img = Image::make($images->front_img); - } elseif ($images->back_img) { - $full_img = Image::make($images->back_img); - } else { - return json_encode([ - 'error' => 'Missing images', - 'success' => false, - ]); - } - - $response = $imageAnnotator->textDetection((string) $full_img->encode()); - $response_text = $response->getTextAnnotations(); - $full_text = $response_text[0]->getDescription(); - - // Split string on newlines into array - $lines = preg_split('/\r\n|\r|\n/', $full_text); - - foreach ($lines as $key => $line) { - $lines[$key] = preg_replace('/\s+/', '', $line); - } - // Get MRZ lines from text - $document = self::getMRZ($lines); - - // Parse lines to known values - $document = self::parseMRZ($document); - - $all = []; - if ($response_text) { - foreach ($response_text as $text) { - array_push($all, [ - 'original' => $text->getDescription(), - 'converted' => IdStr::convert($text->getDescription()), - ]); - } - } - - $document->raw = $all; - - // Validate values with MRZ checkdigits - if ($e = self::validateMRZ($document)) { - try { - $document = self::stripFiller($document); - } catch (\Exception $exception) { - $e .= ' and stripFiller failed.'; - } - - $document->error = $e; - $document->success = false; - - if (! config('identitydocuments.return_all')) { - unset($document->raw); - } - - return json_encode($document); - } - - $document = self::stripFiller($document); - - $document = IdParseRaw::parse($document); - - if (! config('identitydocuments.return_all')) { - unset($document->raw); - } - - return json_encode($document); - } - - private static function getMRZ(array $lines): object - { - $document = (object) [ - 'type' => null, - 'MRZ' => [], - 'parsed' => (object) [], - ]; - foreach ($lines as $key => $line) { - if (strlen($line) === 30 && ($line[0] === 'I' || $line[0] === 'A' || $line[0] === 'C') && strlen($lines[$key + 1]) === 30 && strlen($lines[$key + 2]) === 30) { - $document->type = 'TD1'; - $document->MRZ[0] = $line; - $document->MRZ[1] = $lines[$key + 1]; - $document->MRZ[2] = $lines[$key + 2]; - break; - } elseif (strlen($line) === 44 && ($line[0] === 'P') && strlen($lines[$key + 1]) === 44) { - $document->type = 'TD3'; - $document->MRZ[0] = $line; - $document->MRZ[1] = $lines[$key + 1]; - break; - } elseif (strlen($line) === 36 && ($line[0] === 'V') && strlen($lines[$key + 1]) === 36) { - $document->type = 'VISA'; - $document->MRZ[0] = $line; - $document->MRZ[1] = $lines[$key + 1]; - break; - } - } - - return $document; - } - - private static function parseMRZ(object $document): object - { - if ($document->type === 'TD1') { - // Row 1 - $document->parsed = IdStr::substrs( - $document->MRZ[0], - [ - [0, 1, 'document'], - [1, 1, 'type'], - [2, 3, 'country'], - [5, 9, 'document_number'], - [14, 1, 'check_document_number'], - [15, 15, 'personal_number'], - ] - ); - - // Row 2 - $document->parsed = array_merge($document->parsed, IdStr::substrs( - $document->MRZ[1], - [ - [0, 6, 'date_of_birth'], - [6, 1, 'check_date_of_birth'], - [7, 1, 'sex'], - [8, 6, 'expiration'], - [14, 1, 'check_expiration'], - [15, 3, 'nationality'], - [18, 11, 'optional'], - [29, 1, 'check_general'], - ] - )); - - // Row 3 - $document->parsed = array_merge($document->parsed, IdStr::substrs( - $document->MRZ[2], - [ - [0, 30, 'names'], - ] - )); - - $document->parsed['general'] = IdStr::substrs( - $document->MRZ[0], - [ - [5, 25], - ] - ); - - $document->parsed['general'] = array_merge($document->parsed['general'], IdStr::substrs( - $document->MRZ[1], - [ - [0, 7], - [8, 7], - [18, 11], - ] - )); - $document->success = true; - $document->error = null; - } elseif ($document->type === 'TD3') { - // Row 1 - $document->parsed = IdStr::substrs( - $document->MRZ[0], - [ - [0, 1, 'document'], - [1, 1, 'type'], - [2, 3, 'country'], - [5, 39, 'names'], - ] - ); - - // Row 2 - $document->parsed = array_merge($document->parsed, IdStr::substrs( - $document->MRZ[1], - [ - [0, 9, 'document_number'], - [9, 1, 'check_document_number'], - [10, 3, 'nationality'], - [13, 6, 'date_of_birth'], - [19, 1, 'check_date_of_birth'], - [20, 1, 'sex'], - [21, 6, 'expiration'], - [27, 1, 'check_expiration'], - [28, 14, 'personal_number'], - [42, 1, 'check_personal_number'], - [43, 1, 'check_general'], - ] - )); - - $document->parsed['general'] = IdStr::substrs( - $document->MRZ[1], - [ - [0, 10], - [13, 7], - [21, 22], - ] - ); - $document->success = true; - $document->error = null; - } - $document->parsed = (object) $document->parsed; - if (isset($document->parsed->general)) { - $document->parsed->general = implode('', $document->parsed->general); - } - - if ($document->type && (in_array($document->parsed->country, config('identitydocuments.countries_convert_o_to_zero')) || config('identitydocuments.countries_convert_o_to_zero'))) { - $re = '/o|O/m'; - $subst = '0'; - $document->parsed->document_number = preg_replace($re, $subst, $document->parsed->document_number); - } - - return $document; - } - - private static function validateMRZ($document): ?string - { - if ($document->type === null) { - return 'Document not recognized'; - } - - $checks = (object) [ - 'document_number' => (object) [ - 'error_msg' => 'Document number check failed', - 'document_type' => ['TD1', 'TD3'], - ], - 'date_of_birth' => (object) [ - 'error_msg' => 'Date of birth check failed', - 'document_type' => ['TD1', 'TD3'], - ], - 'expiration' => (object) [ - 'error_msg' => 'Expiration date check failed', - 'document_type' => ['TD1', 'TD3'], - ], - 'personal_number' => (object) [ - 'error_msg' => 'Personal number check failed', - 'document_type' => ['TD3'], - ], - 'general' => (object) [ - 'error_msg' => 'General check failed', - 'document_type' => ['TD1, TD3'], - ], - ]; - - foreach ($checks as $key => $check) { - if (in_array($document->type, $check->document_type)) { - $check->value = $document->parsed->$key ?? null; - $check_key = $key ? 'check_'.$key : null; - $check->check_value = $document->parsed->$check_key ?? null; - if (! IdCheck::checkDigit( - $check->value, - $check->check_value - )) { - return $check->error_msg; - } - } - } - - return null; - } - - private static function stripFiller( - object $document - ): object { - $names = explode('<<', $document->parsed->names, 2); - $document->parsed->surname = trim(str_replace('<', ' ', $names[0])); - $document->parsed->given_names = trim(str_replace('<', ' ', $names[1])); - unset($document->parsed->names); - foreach ($document->parsed as $key => $value) { - $document->parsed->$key = trim(str_replace('<', ' ', $value)); - } - - return $document; - } -} diff --git a/src/IdentityImage.php b/src/IdentityImage.php new file mode 100644 index 0000000..b67dfc3 --- /dev/null +++ b/src/IdentityImage.php @@ -0,0 +1,50 @@ +setImage($image); + $this->annotator = new ImageAnnotatorClient( + ['credentials' => config('google_key')] + ); + } + + public function setImage(Image $image){ + $this->image = $image; + } + + public function resize(){ + + } + + public function rotate(){ + + } + + public function merge(IdentityImage $image): IdentityImage + { + return $image; + } + + public function ocr(): string + { + $response = $this->annotator->textDetection((string) $this->image->encode()); + $text = $response->getTextAnnotations(); + $this->text = $text[0]->getDescription(); + return $this->text; + } +} diff --git a/src/MRZ.php b/src/MRZ.php new file mode 100644 index 0000000..8d15636 --- /dev/null +++ b/src/MRZ.php @@ -0,0 +1,183 @@ +loadConfig(); + } + + private function loadConfig(){ + $this->TD3 = [ + "checks" => [ + 53 => [[44, 9]], + 63 => [[57, 6]], + 71 => [[65, 6]], + 86 => [[72, 14]], + 87 => [[44, 10], [57, 7], [65, 22]] + ], + "length" => 88 + ]; + + $this->TD2 = [ + "checks" => [ + 45 => [[36, 9]], + 55 => [[49, 6]], + 64 => [[58, 6]], + 71 => [[44, 10], [49, 7], [58, 12]], + ], + "length" => 72 + ]; + + $this->TD1 = [ + "checks" => [ + 14 => [[5, 9]], + 36 => [[30, 6]], + 44 => [[38, 6]], + 59 => [[5, 25], [30, 7], [38, 7], [48, 10]] + ], + "length" => 90 + ]; + + $this->MRVA = [ + "checks" => [ + 53 => [[44, 9]], + 63 => [[57, 6]], + 71 => [[65, 6]], + 86 => [[72, 14]], + 87 => [[44, 10], [57, 7], [65, 22]] + ], + "length" => 88 + ]; + + $this->MRVB = [ + "checks" => [ + 53 => [[44, 9]], + 63 => [[57, 6]], + 71 => [[65, 6]], + 86 => [[72, 14]], + 87 => [[44, 10], [57, 7], [65, 22]] + ], + "length" => 88 + ]; + + $this->keys = [ + 'P' => ["TD3" => &$this->TD3["checks"]], + 'I' => ["TD1" => &$this->TD1["checks"], "TD2" => &$this->TD2["checks"]], + 'A' => ["TD1" => &$this->TD1["checks"], "TD2" => &$this->TD2["checks"]], + 'C' => ["TD1" => &$this->TD1["checks"], "TD2" => &$this->TD2["checks"]], + 'V' => ["MRVA" => &$this->MRVA["checks"], "MRVB" => &$this->MRVB["checks"]], + ]; + + // values to be found in MRZ by format, [position in string, sub string length] + $this->values = [ + 'document_key' => + [ + "TD1" => [0,1], + "TD2" => [0,1], + "TD3" => [0,1], + "MRVA" => [0,1], + "MRVB" => [0,1], + ], + 'document_type' => + [ + "TD1" => [1,1], + "TD2" => [1,1], + "TD3" => [1,1], + "MRVA" => [1,1], + "MRVB" => [1,1], + ], + 'issuing_country' => + [ + "TD1" => [2,3], + "TD2" => [2,3], + "TD3" => [2,3], + "MRVA" => [2,3], + "MRVB" => [2,3], + ], + 'full_name' => + [ + "TD1" => [60,30], + "TD2" => [5,31], + "TD3" => [5,39], + "MRVA" => [5,39], + "MRVB" => [5,31], + ], + 'document_number' => + [ + "TD1" => [5,9], + "TD2" => [36,9], + "TD3" => [44,9], + "MRVA" => [44,9], + "MRVB" => [36,9], + ], + 'nationality' => + [ + "TD1" => [45,3], + "TD2" => [46,3], + "TD3" => [54,3], + "MRVA" => [54,3], + "MRVB" => [46,3], + ], + 'date_of_birth' => + [ + "TD1" => [30,6], + "TD2" => [49,6], + "TD3" => [57,6], + "MRVA" => [57,6], + "MRVB" => [49,6], + ], + 'sex' => + [ + "TD1" => [37,1], + "TD2" => [56,1], + "TD3" => [64,1], + "MRVA" => [64,1], + "MRVB" => [56,1], + ], + 'expiration_date' => + [ + "TD1" => [38,6], + "TD2" => [57,6], + "TD3" => [65,6], + "MRVA" => [65,6], + "MRVB" => [57,6], + ], + 'personal_number' => + [ + "TD1" => [], + "TD2" => [], + "TD3" => [72,14], + "MRVA" => [], + "MRVB" => [], + ], + 'optional_data_row_1' => + [ + "TD1" => [15,15], + "TD2" => [], + "TD3" => [], + "MRVA" => [], + "MRVB" => [], + ], + 'optional_data_row_2' => + [ + "TD1" => [48,11], + "TD2" => [64,7], + "TD3" => [], + "MRVA" => [72,16], + "MRVB" => [64,8], + ], + ]; + } +} diff --git a/src/MrzSearcher.php b/src/MrzSearcher.php new file mode 100644 index 0000000..bd2b8d3 --- /dev/null +++ b/src/MrzSearcher.php @@ -0,0 +1,143 @@ +stripString($string); + $keysPositions = $this->findKeysInCharacters($this->keys, $characters); + $startPosition = $this->findMrzStartPosition($keysPositions, $characters); + + if($startPosition === null){ + dd("Not found"); + } + + $mrz = $this->getMrz($strippedString, $startPosition); + + return $mrz; + } + + private function getMrz($strippedString, $startPosition){ + return substr($strippedString, $startPosition, $this->{$this->type}["length"]); + } + + public function parse($mrz){ + $parsed = []; + foreach($this->values as $name=>$value){ + if($value[$this->type]){ + $parsed[$name] = substr($mrz, ...$value[$this->type]); + } else { + $parsed[$name] = null; + } + + } + return $parsed; + } + + private function findKeysInCharacters(array $keys, array $characters, $positions = []): array + { + foreach ($keys as $key => $value) { + $positions[$key] = array_keys($characters, $key, true); + } + return $positions; + } + + private function canBeCheckDigit(array $characters, int $checkDigitPosition): bool + { + if(!isset($characters[$checkDigitPosition])){ + return false; + } + if(!is_numeric($characters[$checkDigitPosition])){ + return $characters[$checkDigitPosition] === "O"; + } + + return true; + } + + private function buildCheckString(array $checkOver, int $position, array $characters, bool $convert = false): string + { + $checkStringArray = []; + foreach($checkOver as $check){ + $start = $position + $check[0]; + $end = $start + $check[1] - 1; + $checkStringArray = array_merge($checkStringArray, range($start, $end)); + } + $checkString = ""; + foreach($checkStringArray as $character){ + $checkString .= ($characters[$character] === "O" && $convert)?"0":$characters[$character]; + } + return $checkString; + } + + private function checkPositionInFormat(int $position, array $characters, array $checkDigits){ + + foreach($checkDigits as $checkDigitIndex => $checkOver){ + $checkDigitPosition = $position + $checkDigitIndex; + + if(!$this->canBeCheckDigit($characters, $checkDigitPosition)){ + return false; + } + + $checkDigit = ($characters[$checkDigitPosition] === "O")?"0":$characters[$checkDigitPosition]; + + $checkString = $this->buildCheckString($checkOver, $position, $characters); + + if(!IdCheck::checkDigit($checkString, $checkDigit)){ + + $checkString = $this->buildCheckString($checkOver, $position, $characters, true); + if(!IdCheck::checkDigit($checkString, $checkDigit)){ + + return false; + } + } + } + + return true; + } + + private function testPositions(array $template, array $positions, $characters): ?int + { + foreach($positions as $position){ + if($this->checkPositionInFormat($position, $characters, $template)){ + return $position; + } + } + return null; + } + + private function testKeyTemplates(string $key, array $positions, array $characters): ?int + { + foreach($this->keys[$key] as $name => $template){ + $position = $this->testPositions($template, $positions, $characters); + if($position !== null) { + $this->type = $name; + return $position; + } + } + return null; + } + + private function findMrzStartPosition(array $mrzKeys, array $characters): ?int + { + foreach($mrzKeys as $key => $positions){ + $position = $this->testKeyTemplates($key, $positions, $characters); + if($position){ + return $position; + } + } + return null; + } + + + private function stripString(string $string): array + { + $strippedString = preg_replace('/\r\n|\r|\n/', '', $string); + $strippedString = preg_replace('/\s+/', '', $strippedString); + $strippedString = (is_string($strippedString))?$strippedString:$string; + $characters = str_split($strippedString); + return [$strippedString, $characters]; + } +} From 8ab58ca703784e265354908c9353acfd3724acb6 Mon Sep 17 00:00:00 2001 From: HergenD Date: Mon, 12 Apr 2021 15:45:29 +0000 Subject: [PATCH 02/26] Apply fixes from StyleCI --- src/IdentityDocument.php | 37 ++++--- src/IdentityImage.php | 18 ++-- src/MRZ.php | 203 ++++++++++++++++++--------------------- src/MrzSearcher.php | 71 ++++++++------ 4 files changed, 166 insertions(+), 163 deletions(-) diff --git a/src/IdentityDocument.php b/src/IdentityDocument.php index 26d0a2a..79ef017 100644 --- a/src/IdentityDocument.php +++ b/src/IdentityDocument.php @@ -2,8 +2,8 @@ namespace werk365\IdentityDocuments; -use Intervention\Image\Image; use Intervention\Image\Facades\Image as Img; +use Intervention\Image\Image; class IdentityDocument { @@ -15,11 +15,12 @@ class IdentityDocument private array $images; private MrzSearcher $mrzSearcher; - public function __construct($frontImage = null, $backImage = null){ - if($frontImage){ + public function __construct($frontImage = null, $backImage = null) + { + if ($frontImage) { $this->addFrontImage($frontImage); } - if($backImage){ + if ($backImage) { $this->addBackImage($backImage); } @@ -42,31 +43,34 @@ public function addBackImage($image): void private function createImage($file): ?Image { - if(!is_file($file)){ + if (! is_file($file)) { return null; } file_get_contents($file->getRealPath()); + return Img::make($file); } - private function mergeBackAndFrontImages(){ - if(!$this->frontImage || !$this->backImage){ + private function mergeBackAndFrontImages() + { + if (! $this->frontImage || ! $this->backImage) { return false; } - if(!$this->mergedImage = $this->frontImage->merge($this->backImage)){ + if (! $this->mergedImage = $this->frontImage->merge($this->backImage)) { return false; } $this->images = [&$this->mergedImage]; + return true; } private function mrz(): string { - $this->mrz = ""; - foreach($this->images as $image){ + $this->mrz = ''; + foreach ($this->images as $image) { $image->ocr(); - if($mrz = $this->mrzSearcher->search($image->text)){ - $this->mrz = $mrz??""; + if ($mrz = $this->mrzSearcher->search($image->text)) { + $this->mrz = $mrz ?? ''; break; } } @@ -76,23 +80,26 @@ private function mrz(): string public function getMrz(): string { - if(!isset($this->mrz)){ + if (! isset($this->mrz)) { $this->mrz(); } + return $this->mrz; } public function getParsedMrz(): array { - if(!isset($this->parsedMrz) && $this->mrz){ + if (! isset($this->parsedMrz) && $this->mrz) { $this->parseMrz(); } - return $this->parsedMrz??[]; + + return $this->parsedMrz ?? []; } public function setMrz($mrz): IdentityDocument { $this->mrz = $mrz; + return $this; } diff --git a/src/IdentityImage.php b/src/IdentityImage.php index b67dfc3..173374d 100644 --- a/src/IdentityImage.php +++ b/src/IdentityImage.php @@ -1,10 +1,8 @@ setImage($image); $this->annotator = new ImageAnnotatorClient( ['credentials' => config('google_key')] ); } - public function setImage(Image $image){ + public function setImage(Image $image) + { $this->image = $image; } - public function resize(){ - + public function resize() + { } - public function rotate(){ - + public function rotate() + { } public function merge(IdentityImage $image): IdentityImage @@ -45,6 +44,7 @@ public function ocr(): string $response = $this->annotator->textDetection((string) $this->image->encode()); $text = $response->getTextAnnotations(); $this->text = $text[0]->getDescription(); + return $this->text; } } diff --git a/src/MRZ.php b/src/MRZ.php index 8d15636..f1283e2 100644 --- a/src/MRZ.php +++ b/src/MRZ.php @@ -1,6 +1,5 @@ loadConfig(); } - private function loadConfig(){ + private function loadConfig() + { $this->TD3 = [ - "checks" => [ + 'checks' => [ 53 => [[44, 9]], 63 => [[57, 6]], 71 => [[65, 6]], 86 => [[72, 14]], - 87 => [[44, 10], [57, 7], [65, 22]] + 87 => [[44, 10], [57, 7], [65, 22]], ], - "length" => 88 + 'length' => 88, ]; $this->TD2 = [ - "checks" => [ + 'checks' => [ 45 => [[36, 9]], 55 => [[49, 6]], 64 => [[58, 6]], 71 => [[44, 10], [49, 7], [58, 12]], ], - "length" => 72 + 'length' => 72, ]; $this->TD1 = [ - "checks" => [ + 'checks' => [ 14 => [[5, 9]], 36 => [[30, 6]], 44 => [[38, 6]], - 59 => [[5, 25], [30, 7], [38, 7], [48, 10]] + 59 => [[5, 25], [30, 7], [38, 7], [48, 10]], ], - "length" => 90 + 'length' => 90, ]; $this->MRVA = [ - "checks" => [ + 'checks' => [ 53 => [[44, 9]], 63 => [[57, 6]], 71 => [[65, 6]], 86 => [[72, 14]], - 87 => [[44, 10], [57, 7], [65, 22]] + 87 => [[44, 10], [57, 7], [65, 22]], ], - "length" => 88 + 'length' => 88, ]; $this->MRVB = [ - "checks" => [ + 'checks' => [ 53 => [[44, 9]], 63 => [[57, 6]], 71 => [[65, 6]], 86 => [[72, 14]], - 87 => [[44, 10], [57, 7], [65, 22]] + 87 => [[44, 10], [57, 7], [65, 22]], ], - "length" => 88 + 'length' => 88, ]; $this->keys = [ - 'P' => ["TD3" => &$this->TD3["checks"]], - 'I' => ["TD1" => &$this->TD1["checks"], "TD2" => &$this->TD2["checks"]], - 'A' => ["TD1" => &$this->TD1["checks"], "TD2" => &$this->TD2["checks"]], - 'C' => ["TD1" => &$this->TD1["checks"], "TD2" => &$this->TD2["checks"]], - 'V' => ["MRVA" => &$this->MRVA["checks"], "MRVB" => &$this->MRVB["checks"]], + 'P' => ['TD3' => &$this->TD3['checks']], + 'I' => ['TD1' => &$this->TD1['checks'], 'TD2' => &$this->TD2['checks']], + 'A' => ['TD1' => &$this->TD1['checks'], 'TD2' => &$this->TD2['checks']], + 'C' => ['TD1' => &$this->TD1['checks'], 'TD2' => &$this->TD2['checks']], + 'V' => ['MRVA' => &$this->MRVA['checks'], 'MRVB' => &$this->MRVB['checks']], ]; // values to be found in MRZ by format, [position in string, sub string length] $this->values = [ - 'document_key' => - [ - "TD1" => [0,1], - "TD2" => [0,1], - "TD3" => [0,1], - "MRVA" => [0,1], - "MRVB" => [0,1], + 'document_key' => [ + 'TD1' => [0, 1], + 'TD2' => [0, 1], + 'TD3' => [0, 1], + 'MRVA' => [0, 1], + 'MRVB' => [0, 1], ], - 'document_type' => - [ - "TD1" => [1,1], - "TD2" => [1,1], - "TD3" => [1,1], - "MRVA" => [1,1], - "MRVB" => [1,1], + 'document_type' => [ + 'TD1' => [1, 1], + 'TD2' => [1, 1], + 'TD3' => [1, 1], + 'MRVA' => [1, 1], + 'MRVB' => [1, 1], ], - 'issuing_country' => - [ - "TD1" => [2,3], - "TD2" => [2,3], - "TD3" => [2,3], - "MRVA" => [2,3], - "MRVB" => [2,3], + 'issuing_country' => [ + 'TD1' => [2, 3], + 'TD2' => [2, 3], + 'TD3' => [2, 3], + 'MRVA' => [2, 3], + 'MRVB' => [2, 3], ], - 'full_name' => - [ - "TD1" => [60,30], - "TD2" => [5,31], - "TD3" => [5,39], - "MRVA" => [5,39], - "MRVB" => [5,31], + 'full_name' => [ + 'TD1' => [60, 30], + 'TD2' => [5, 31], + 'TD3' => [5, 39], + 'MRVA' => [5, 39], + 'MRVB' => [5, 31], ], - 'document_number' => - [ - "TD1" => [5,9], - "TD2" => [36,9], - "TD3" => [44,9], - "MRVA" => [44,9], - "MRVB" => [36,9], + 'document_number' => [ + 'TD1' => [5, 9], + 'TD2' => [36, 9], + 'TD3' => [44, 9], + 'MRVA' => [44, 9], + 'MRVB' => [36, 9], ], - 'nationality' => - [ - "TD1" => [45,3], - "TD2" => [46,3], - "TD3" => [54,3], - "MRVA" => [54,3], - "MRVB" => [46,3], + 'nationality' => [ + 'TD1' => [45, 3], + 'TD2' => [46, 3], + 'TD3' => [54, 3], + 'MRVA' => [54, 3], + 'MRVB' => [46, 3], ], - 'date_of_birth' => - [ - "TD1" => [30,6], - "TD2" => [49,6], - "TD3" => [57,6], - "MRVA" => [57,6], - "MRVB" => [49,6], + 'date_of_birth' => [ + 'TD1' => [30, 6], + 'TD2' => [49, 6], + 'TD3' => [57, 6], + 'MRVA' => [57, 6], + 'MRVB' => [49, 6], ], - 'sex' => - [ - "TD1" => [37,1], - "TD2" => [56,1], - "TD3" => [64,1], - "MRVA" => [64,1], - "MRVB" => [56,1], + 'sex' => [ + 'TD1' => [37, 1], + 'TD2' => [56, 1], + 'TD3' => [64, 1], + 'MRVA' => [64, 1], + 'MRVB' => [56, 1], ], - 'expiration_date' => - [ - "TD1" => [38,6], - "TD2" => [57,6], - "TD3" => [65,6], - "MRVA" => [65,6], - "MRVB" => [57,6], + 'expiration_date' => [ + 'TD1' => [38, 6], + 'TD2' => [57, 6], + 'TD3' => [65, 6], + 'MRVA' => [65, 6], + 'MRVB' => [57, 6], ], - 'personal_number' => - [ - "TD1" => [], - "TD2" => [], - "TD3" => [72,14], - "MRVA" => [], - "MRVB" => [], + 'personal_number' => [ + 'TD1' => [], + 'TD2' => [], + 'TD3' => [72, 14], + 'MRVA' => [], + 'MRVB' => [], ], - 'optional_data_row_1' => - [ - "TD1" => [15,15], - "TD2" => [], - "TD3" => [], - "MRVA" => [], - "MRVB" => [], + 'optional_data_row_1' => [ + 'TD1' => [15, 15], + 'TD2' => [], + 'TD3' => [], + 'MRVA' => [], + 'MRVB' => [], ], - 'optional_data_row_2' => - [ - "TD1" => [48,11], - "TD2" => [64,7], - "TD3" => [], - "MRVA" => [72,16], - "MRVB" => [64,8], + 'optional_data_row_2' => [ + 'TD1' => [48, 11], + 'TD2' => [64, 7], + 'TD3' => [], + 'MRVA' => [72, 16], + 'MRVB' => [64, 8], ], ]; } diff --git a/src/MrzSearcher.php b/src/MrzSearcher.php index bd2b8d3..498141f 100644 --- a/src/MrzSearcher.php +++ b/src/MrzSearcher.php @@ -1,6 +1,7 @@ findKeysInCharacters($this->keys, $characters); $startPosition = $this->findMrzStartPosition($keysPositions, $characters); - if($startPosition === null){ - dd("Not found"); + if ($startPosition === null) { + dd('Not found'); } $mrz = $this->getMrz($strippedString, $startPosition); @@ -20,20 +21,22 @@ public function search(string $string): ?string return $mrz; } - private function getMrz($strippedString, $startPosition){ - return substr($strippedString, $startPosition, $this->{$this->type}["length"]); + private function getMrz($strippedString, $startPosition) + { + return substr($strippedString, $startPosition, $this->{$this->type}['length']); } - public function parse($mrz){ + public function parse($mrz) + { $parsed = []; - foreach($this->values as $name=>$value){ - if($value[$this->type]){ + foreach ($this->values as $name=>$value) { + if ($value[$this->type]) { $parsed[$name] = substr($mrz, ...$value[$this->type]); } else { $parsed[$name] = null; } - } + return $parsed; } @@ -42,16 +45,17 @@ private function findKeysInCharacters(array $keys, array $characters, $positions foreach ($keys as $key => $value) { $positions[$key] = array_keys($characters, $key, true); } + return $positions; } private function canBeCheckDigit(array $characters, int $checkDigitPosition): bool { - if(!isset($characters[$checkDigitPosition])){ + if (! isset($characters[$checkDigitPosition])) { return false; } - if(!is_numeric($characters[$checkDigitPosition])){ - return $characters[$checkDigitPosition] === "O"; + if (! is_numeric($characters[$checkDigitPosition])) { + return $characters[$checkDigitPosition] === 'O'; } return true; @@ -60,36 +64,35 @@ private function canBeCheckDigit(array $characters, int $checkDigitPosition): bo private function buildCheckString(array $checkOver, int $position, array $characters, bool $convert = false): string { $checkStringArray = []; - foreach($checkOver as $check){ + foreach ($checkOver as $check) { $start = $position + $check[0]; $end = $start + $check[1] - 1; $checkStringArray = array_merge($checkStringArray, range($start, $end)); } - $checkString = ""; - foreach($checkStringArray as $character){ - $checkString .= ($characters[$character] === "O" && $convert)?"0":$characters[$character]; + $checkString = ''; + foreach ($checkStringArray as $character) { + $checkString .= ($characters[$character] === 'O' && $convert) ? '0' : $characters[$character]; } + return $checkString; } - private function checkPositionInFormat(int $position, array $characters, array $checkDigits){ - - foreach($checkDigits as $checkDigitIndex => $checkOver){ + private function checkPositionInFormat(int $position, array $characters, array $checkDigits) + { + foreach ($checkDigits as $checkDigitIndex => $checkOver) { $checkDigitPosition = $position + $checkDigitIndex; - if(!$this->canBeCheckDigit($characters, $checkDigitPosition)){ + if (! $this->canBeCheckDigit($characters, $checkDigitPosition)) { return false; } - $checkDigit = ($characters[$checkDigitPosition] === "O")?"0":$characters[$checkDigitPosition]; + $checkDigit = ($characters[$checkDigitPosition] === 'O') ? '0' : $characters[$checkDigitPosition]; $checkString = $this->buildCheckString($checkOver, $position, $characters); - if(!IdCheck::checkDigit($checkString, $checkDigit)){ - + if (! IdCheck::checkDigit($checkString, $checkDigit)) { $checkString = $this->buildCheckString($checkOver, $position, $characters, true); - if(!IdCheck::checkDigit($checkString, $checkDigit)){ - + if (! IdCheck::checkDigit($checkString, $checkDigit)) { return false; } } @@ -100,44 +103,48 @@ private function checkPositionInFormat(int $position, array $characters, array $ private function testPositions(array $template, array $positions, $characters): ?int { - foreach($positions as $position){ - if($this->checkPositionInFormat($position, $characters, $template)){ + foreach ($positions as $position) { + if ($this->checkPositionInFormat($position, $characters, $template)) { return $position; } } + return null; } private function testKeyTemplates(string $key, array $positions, array $characters): ?int { - foreach($this->keys[$key] as $name => $template){ + foreach ($this->keys[$key] as $name => $template) { $position = $this->testPositions($template, $positions, $characters); - if($position !== null) { + if ($position !== null) { $this->type = $name; + return $position; } } + return null; } private function findMrzStartPosition(array $mrzKeys, array $characters): ?int { - foreach($mrzKeys as $key => $positions){ + foreach ($mrzKeys as $key => $positions) { $position = $this->testKeyTemplates($key, $positions, $characters); - if($position){ + if ($position) { return $position; } } + return null; } - private function stripString(string $string): array { $strippedString = preg_replace('/\r\n|\r|\n/', '', $string); $strippedString = preg_replace('/\s+/', '', $strippedString); - $strippedString = (is_string($strippedString))?$strippedString:$string; + $strippedString = (is_string($strippedString)) ? $strippedString : $string; $characters = str_split($strippedString); + return [$strippedString, $characters]; } } From b4a23849c48532c77b62e2899dafccdd207e07da Mon Sep 17 00:00:00 2001 From: Hergen Dillema Date: Wed, 21 Apr 2021 14:48:14 +0200 Subject: [PATCH 03/26] Update for 2.0.0 beta - Country code resolver - Set up base for interchangable OCR provider (interface + response) - Added Face Detection support to extract passport photo - Set up base for interchangable Face Detection provider (interface + response) - Restructured MRZ seacher and parser - Added Viz Parser for fuzzy searching names in viz based on names found in mrz - Clean up --- composer.json | 7 +- config/countries.php | 274 +++++++++++++++++++++++ config/mrz_templates.php | 20 ++ src/Helpers/IdParseRaw.php | 158 ------------- src/Helpers/IdStr.php | 31 --- src/IdentityDocument.php | 90 +++++++- src/IdentityDocumentsServiceProvider.php | 2 +- src/IdentityImage.php | 49 ++-- src/Interfaces/FaceDetection.php | 10 + src/Interfaces/OCR.php | 10 + src/{MRZ.php => Mrz/Mrz.php} | 6 +- src/Mrz/MrzParser.php | 41 ++++ src/{ => Mrz}/MrzSearcher.php | 20 +- src/Responses/OcrResponse.php | 12 + src/Services/Google.php | 71 ++++++ src/Viz/Viz.php | 8 + src/Viz/VizParser.php | 66 ++++++ 17 files changed, 640 insertions(+), 235 deletions(-) create mode 100644 config/countries.php create mode 100644 config/mrz_templates.php delete mode 100644 src/Helpers/IdParseRaw.php delete mode 100644 src/Helpers/IdStr.php create mode 100644 src/Interfaces/FaceDetection.php create mode 100644 src/Interfaces/OCR.php rename src/{MRZ.php => Mrz/Mrz.php} (97%) create mode 100644 src/Mrz/MrzParser.php rename src/{ => Mrz}/MrzSearcher.php (90%) create mode 100644 src/Responses/OcrResponse.php create mode 100644 src/Services/Google.php create mode 100644 src/Viz/Viz.php create mode 100644 src/Viz/VizParser.php diff --git a/composer.json b/composer.json index 0520986..2d0019b 100644 --- a/composer.json +++ b/composer.json @@ -2,7 +2,7 @@ "name": "werk365/identitydocuments", "description": "Package to parse identity documents like passports", "license": "MIT", - "version": "1.4.0", + "version": "2.0.0-beta", "authors": [ { "name": "Hergen Dillema", @@ -13,9 +13,10 @@ "homepage": "https://github.com/werk365/identitydocuments", "keywords": ["Laravel", "IdentityDocuments"], "require": { - "google/cloud-vision": "^1.1", + "google/cloud-vision": "^1.3", "intervention/image": "^2.5", - "illuminate/support": "~5|~6|~7|~8" + "illuminate/support": "~5|~6|~7|~8", + "ext-gd": "*" }, "require-dev": { "phpunit/phpunit": "^8.0", diff --git a/config/countries.php b/config/countries.php new file mode 100644 index 0000000..def3735 --- /dev/null +++ b/config/countries.php @@ -0,0 +1,274 @@ +'Aruba', + 'AFG'=>'Afghanistan', + 'AGO'=>'Angola', + 'AIA'=>'Anguilla', + 'ALA'=>'Åland Islands', + 'ALB'=>'Albania', + 'AND'=>'Andorra', + 'ARE'=>'United Arab Emirates', + 'ARG'=>'Argentina', + 'ARM'=>'Armenia', + 'ASM'=>'American Samoa', + 'ATA'=>'Antarctica', + 'ATF'=>'French Southern Territories', + 'ATG'=>'Antigua and Barbuda', + 'AUS'=>'Australia', + 'AUT'=>'Austria', + 'AZE'=>'Azerbaijan', + 'BDI'=>'Burundi', + 'BEL'=>'Belgium', + 'BEN'=>'Benin', + 'BES'=>'Bonaire, Sint Eustatius and Saba', + 'BFA'=>'Burkina Faso', + 'BGD'=>'Bangladesh', + 'BGR'=>'Bulgaria', + 'BHR'=>'Bahrain', + 'BHS'=>'Bahamas', + 'BIH'=>'Bosnia and Herzegovina', + 'BLM'=>'Saint Barthélemy', + 'BLR'=>'Belarus', + 'BLZ'=>'Belize', + 'BMU'=>'Bermuda', + 'BOL'=>'Bolivia, Plurinational State of', + 'BRA'=>'Brazil', + 'BRB'=>'Barbados', + 'BRN'=>'Brunei Darussalam', + 'BTN'=>'Bhutan', + 'BVT'=>'Bouvet Island', + 'BWA'=>'Botswana', + 'CAF'=>'Central African Republic', + 'CAN'=>'Canada', + 'CCK'=>'Cocos (Keeling) Islands', + 'CHE'=>'Switzerland', + 'CHL'=>'Chile', + 'CHN'=>'China', + 'CIV'=>'Côte d\'Ivoire', + 'CMR'=>'Cameroon', + 'COD'=>'Congo, the Democratic Republic of the', + 'COG'=>'Congo', + 'COK'=>'Cook Islands', + 'COL'=>'Colombia', + 'COM'=>'Comoros', + 'CPV'=>'Cape Verde', + 'CRI'=>'Costa Rica', + 'CUB'=>'Cuba', + 'CUW'=>'Curaçao', + 'CXR'=>'Christmas Island', + 'CYM'=>'Cayman Islands', + 'CYP'=>'Cyprus', + 'CZE'=>'Czech Republic', + 'DEU'=>'Germany', + 'DJI'=>'Djibouti', + 'DMA'=>'Dominica', + 'DNK'=>'Denmark', + 'DOM'=>'Dominican Republic', + 'DZA'=>'Algeria', + 'ECU'=>'Ecuador', + 'EGY'=>'Egypt', + 'ERI'=>'Eritrea', + 'ESH'=>'Western Sahara', + 'ESP'=>'Spain', + 'EST'=>'Estonia', + 'ETH'=>'Ethiopia', + 'FIN'=>'Finland', + 'FJI'=>'Fiji', + 'FLK'=>'Falkland Islands (Malvinas)', + 'FRA'=>'France', + 'FRO'=>'Faroe Islands', + 'FSM'=>'Micronesia, Federated States of', + 'GAB'=>'Gabon', + 'GBR'=>'United Kingdom', + 'GEO'=>'Georgia', + 'GGY'=>'Guernsey', + 'GHA'=>'Ghana', + 'GIB'=>'Gibraltar', + 'GIN'=>'Guinea', + 'GLP'=>'Guadeloupe', + 'GMB'=>'Gambia', + 'GNB'=>'Guinea-Bissau', + 'GNQ'=>'Equatorial Guinea', + 'GRC'=>'Greece', + 'GRD'=>'Grenada', + 'GRL'=>'Greenland', + 'GTM'=>'Guatemala', + 'GUF'=>'French Guiana', + 'GUM'=>'Guam', + 'GUY'=>'Guyana', + 'HKG'=>'Hong Kong', + 'HMD'=>'Heard Island and McDonald Islands', + 'HND'=>'Honduras', + 'HRV'=>'Croatia', + 'HTI'=>'Haiti', + 'HUN'=>'Hungary', + 'IDN'=>'Indonesia', + 'IMN'=>'Isle of Man', + 'IND'=>'India', + 'IOT'=>'British Indian Ocean Territory', + 'IRL'=>'Ireland', + 'IRN'=>'Iran, Islamic Republic of', + 'IRQ'=>'Iraq', + 'ISL'=>'Iceland', + 'ISR'=>'Israel', + 'ITA'=>'Italy', + 'JAM'=>'Jamaica', + 'JEY'=>'Jersey', + 'JOR'=>'Jordan', + 'JPN'=>'Japan', + 'KAZ'=>'Kazakhstan', + 'KEN'=>'Kenya', + 'KGZ'=>'Kyrgyzstan', + 'KHM'=>'Cambodia', + 'KIR'=>'Kiribati', + 'KNA'=>'Saint Kitts and Nevis', + 'KOR'=>'Korea, Republic of', + 'KWT'=>'Kuwait', + 'LAO'=>'Lao People\'s Democratic Republic', + 'LBN'=>'Lebanon', + 'LBR'=>'Liberia', + 'LBY'=>'Libya', + 'LCA'=>'Saint Lucia', + 'LIE'=>'Liechtenstein', + 'LKA'=>'Sri Lanka', + 'LSO'=>'Lesotho', + 'LTU'=>'Lithuania', + 'LUX'=>'Luxembourg', + 'LVA'=>'Latvia', + 'MAC'=>'Macao', + 'MAF'=>'Saint Martin (French part)', + 'MAR'=>'Morocco', + 'MCO'=>'Monaco', + 'MDA'=>'Moldova, Republic of', + 'MDG'=>'Madagascar', + 'MDV'=>'Maldives', + 'MEX'=>'Mexico', + 'MHL'=>'Marshall Islands', + 'MKD'=>'Macedonia, the former Yugoslav Republic of', + 'MLI'=>'Mali', + 'MLT'=>'Malta', + 'MMR'=>'Myanmar', + 'MNE'=>'Montenegro', + 'MNG'=>'Mongolia', + 'MNP'=>'Northern Mariana Islands', + 'MOZ'=>'Mozambique', + 'MRT'=>'Mauritania', + 'MSR'=>'Montserrat', + 'MTQ'=>'Martinique', + 'MUS'=>'Mauritius', + 'MWI'=>'Malawi', + 'MYS'=>'Malaysia', + 'MYT'=>'Mayotte', + 'NAM'=>'Namibia', + 'NCL'=>'New Caledonia', + 'NER'=>'Niger', + 'NFK'=>'Norfolk Island', + 'NGA'=>'Nigeria', + 'NIC'=>'Nicaragua', + 'NIU'=>'Niue', + 'NLD'=>'Netherlands', + 'NOR'=>'Norway', + 'NPL'=>'Nepal', + 'NRU'=>'Nauru', + 'NZL'=>'New Zealand', + 'OMN'=>'Oman', + 'PAK'=>'Pakistan', + 'PAN'=>'Panama', + 'PCN'=>'Pitcairn', + 'PER'=>'Peru', + 'PHL'=>'Philippines', + 'PLW'=>'Palau', + 'PNG'=>'Papua New Guinea', + 'POL'=>'Poland', + 'PRI'=>'Puerto Rico', + 'PRK'=>'Korea, Democratic People\'s Republic of', + 'PRT'=>'Portugal', + 'PRY'=>'Paraguay', + 'PSE'=>'Palestinian Territory, Occupied', + 'PYF'=>'French Polynesia', + 'QAT'=>'Qatar', + 'REU'=>'Réunion', + 'ROU'=>'Romania', + 'RUS'=>'Russian Federation', + 'RWA'=>'Rwanda', + 'SAU'=>'Saudi Arabia', + 'SDN'=>'Sudan', + 'SEN'=>'Senegal', + 'SGP'=>'Singapore', + 'SGS'=>'South Georgia and the South Sandwich Islands', + 'SHN'=>'Saint Helena, Ascension and Tristan da Cunha', + 'SJM'=>'Svalbard and Jan Mayen', + 'SLB'=>'Solomon Islands', + 'SLE'=>'Sierra Leone', + 'SLV'=>'El Salvador', + 'SMR'=>'San Marino', + 'SOM'=>'Somalia', + 'SPM'=>'Saint Pierre and Miquelon', + 'SRB'=>'Serbia', + 'SSD'=>'South Sudan', + 'STP'=>'Sao Tome and Principe', + 'SUR'=>'Suriname', + 'SVK'=>'Slovakia', + 'SVN'=>'Slovenia', + 'SWE'=>'Sweden', + 'SWZ'=>'Swaziland', + 'SXM'=>'Sint Maarten (Dutch part)', + 'SYC'=>'Seychelles', + 'SYR'=>'Syrian Arab Republic', + 'TCA'=>'Turks and Caicos Islands', + 'TCD'=>'Chad', + 'TGO'=>'Togo', + 'THA'=>'Thailand', + 'TJK'=>'Tajikistan', + 'TKL'=>'Tokelau', + 'TKM'=>'Turkmenistan', + 'TLS'=>'Timor-Leste', + 'TON'=>'Tonga', + 'TTO'=>'Trinidad and Tobago', + 'TUN'=>'Tunisia', + 'TUR'=>'Turkey', + 'TUV'=>'Tuvalu', + 'TWN'=>'Taiwan, Province of China', + 'TZA'=>'Tanzania, United Republic of', + 'UGA'=>'Uganda', + 'UKR'=>'Ukraine', + 'UMI'=>'United States Minor Outlying Islands', + 'URY'=>'Uruguay', + 'USA'=>'United States', + 'UZB'=>'Uzbekistan', + 'VAT'=>'Holy See (Vatican City State)', + 'VCT'=>'Saint Vincent and the Grenadines', + 'VEN'=>'Venezuela, Bolivarian Republic of', + 'VGB'=>'Virgin Islands, British', + 'VIR'=>'Virgin Islands, U.S.', + 'VNM'=>'Viet Nam', + 'VUT'=>'Vanuatu', + 'WLF'=>'Wallis and Futuna', + 'WSM'=>'Samoa', + 'YEM'=>'Yemen', + 'ZAF'=>'South Africa', + 'ZMB'=>'Zambia', + 'ZWE'=>'Zimbabwe', + "D" => "Germany", + "EUE" => "European Union", + "GBD" => "British Overseas Territories Citizen", + "GBN" => "British National (Overseas)", + "GBO" => "British Overseas Citizen", + "GBP" => "British Protected Person", + "GBS" => "British Subject", + "UNA" => "specialized agency of the United Nations", + "UNK" => "Resident of Kosovo", + "UNO" => "United Nations organization", + "XBA" => "African Development Bank", + "XIM" => "African Export–Import Bank", + "XCC" => "Caribbean Community or one of its emissaries", + "XCO" => "Common Market for Eastern and Southern Africa", + "XEC" => "Economic Community of West African States", + "XPO" => "International Criminal Police Organization", + "XOM" => "Sovereign Military Order of Malta", + "XXA" => "Stateless person", + "XXB" => "Refugee", + "XXC" => "Refugee", + "XXX" => "Unspecified nationality" +]; diff --git a/config/mrz_templates.php b/config/mrz_templates.php new file mode 100644 index 0000000..9d487a6 --- /dev/null +++ b/config/mrz_templates.php @@ -0,0 +1,20 @@ + [ + "keys" => ["P"], + "check_digits" => [ + 53 => [[44, 9]], + 63 => [[57, 6]], + 71 => [[65, 6]], + 86 => [[72, 14]], + 87 => [[44, 10], [57, 7], [65, 22]] + ] + ], + "TD1" => [ + + ], + "VISA" => [ + + ], +]; diff --git a/src/Helpers/IdParseRaw.php b/src/Helpers/IdParseRaw.php deleted file mode 100644 index acb7439..0000000 --- a/src/Helpers/IdParseRaw.php +++ /dev/null @@ -1,158 +0,0 @@ -matched = (object) []; - $MRZ_string = implode('', $document->MRZ); - foreach ($document->raw as $raw) { - if ($raw['converted'] != '' && ! Str::contains($MRZ_string, $raw['original'])) { - // Parsed variables to match: - // document_number - if ($document->parsed->document_number === $raw['converted']) { - $document->matched->document_number = [ - 'value' => $raw['original'], - 'confidence' => 1, - ]; - } - // personal_number - if ($document->parsed->personal_number === $raw['converted']) { - $document->matched->personal_number = [ - 'value' => $raw['original'], - 'confidence' => 1, - ]; - } - // date_of_birth - $dob = $document->parsed->date_of_birth; - $dob_YY = substr($dob, 0, 2); - $dob_MM = substr($dob, 2, 2); - $dateObj = DateTime::createFromFormat('!m', $dob_MM); - $dob_Month = strtoupper($dateObj->format('M')); - $dob_DD = substr($dob, 4, 2); - if ( - Str::is("$dob_DD*$dob_MM*$dob_YY", $raw['converted']) || - Str::is("*$dob_YY*$dob_MM*$dob_DD", $raw['converted']) || - Str::is("$dob_MM*$dob_DD*$dob_YY", $raw['converted']) || - Str::is("$dob_DD*$dob_Month*$dob_YY", $raw['converted']) || - Str::is("*$dob_YY*$dob_Month*$dob_DD", $raw['converted']) || - Str::is("$dob_Month*$dob_DD*$dob_YY", $raw['converted']) - ) { - $document->matched->date_of_birth = [ - 'value' => $raw['original'], - 'confidence' => 1, - ]; - } - // sex - if ($document->parsed->sex === $raw['converted'] || Str::is($document->parsed->sex.$document->parsed->sex, $raw['converted'])) { - $document->matched->sex = [ - 'value' => $raw['original'], - 'confidence' => 1, - ]; - } - // expiration - $exp = $document->parsed->expiration; - $exp_YY = substr($exp, 0, 2); - $exp_MM = substr($exp, 2, 2); - $dateObj = DateTime::createFromFormat('!m', $exp_MM); - $exp_Month = strtoupper($dateObj->format('M')); - $exp_DD = substr($exp, 4, 2); - if ( - Str::is("$exp_DD*$exp_MM*$exp_YY", $raw['converted']) || - Str::is("*$exp_YY*$exp_MM*$exp_DD", $raw['converted']) || - Str::is("$exp_MM*$exp_DD*$exp_YY", $raw['converted']) || - Str::is("$exp_DD*$exp_Month*$exp_YY", $raw['converted']) || - Str::is("*$exp_YY*$exp_Month*$exp_DD", $raw['converted']) || - Str::is("$exp_Month*$exp_DD*$exp_YY", $raw['converted']) - ) { - $document->matched->expiration = [ - 'value' => $raw['original'], - 'confidence' => 1, - ]; - } - // nationality - if ($document->parsed->nationality === $raw['converted']) { - $document->matched->nationality = [ - 'value' => $raw['original'], - 'confidence' => 1, - ]; - } - // surname - $surname = $document->parsed->surname; - $surname_characters = str_split($surname); - $surname_search = implode('*', $surname_characters).'*'; - - if ($surname === $raw['converted']) { - $document->matched->surname = [ - 'value' => $raw['original'], - 'confidence' => 1, - ]; - } elseif (Str::startsWith($raw['converted'], $surname)) { - if (! isset($document->matched->surname) || strlen($document->matched->surname['value']) > strlen($raw['original'])) { - $document->matched->surname = [ - 'value' => $raw['original'], - 'confidence' => 0.9, - ]; - } - } elseif (Str::is($surname_search, $raw['converted'])) { - if (! isset($document->matched->surname) || strlen($document->matched->surname['value']) > strlen($raw['original'])) { - $document->matched->surname = [ - 'value' => $raw['original'], - 'confidence' => 0.75, - ]; - } - } - // given_names - $given_names = $document->parsed->given_names; - $given_names_split = explode(' ', $given_names); - $given_names_search = []; - foreach ($given_names_split as $key=>$given_name) { - $given_names_characters = str_split($given_name); - $given_names_search[$key] = '*'.implode('*', $given_names_characters).'*'; - } - - if (! isset($document->matched->given_names)) { - $document->matched->given_names = []; - } - foreach ($given_names_split as $key=>$given_name) { - if ($given_name === $raw['converted']) { - $document->matched->given_names[$key] = [ - 'value' => $raw['original'], - 'confidence' => 1, - ]; - } elseif (Str::startsWith($raw['converted'], $given_name)) { - if (! isset($document->matched->given_names[$key]['value']) || strlen($document->matched->given_names[$key]['value']) > strlen($raw['original'])) { - $document->matched->given_names[$key] = [ - 'value' => $raw['original'], - 'confidence' => 0.9, - ]; - } - } elseif (Str::is($given_names_search[$key], $raw['converted'])) { - if (! isset($document->matched->given_names[$key]['value']) || strlen($document->matched->given_names[$key]['value']) > strlen($raw['original'])) { - $document->matched->given_names[$key] = [ - 'value' => $raw['original'], - 'confidence' => 0.75, - ]; - } - } else { - $chars_raw = str_split($raw['converted']); - $chars_search = implode('*', $chars_raw); - if (Str::is($chars_search, $given_name) && (! isset($document->matched->given_names[$key]['value']) || strlen($document->matched->given_names[$key]['value']) > strlen($raw['original']))) { - $document->matched->given_names[$key] = [ - 'value' => $raw['original'], - 'confidence' => 0.75, - ]; - } - } - } - } - } - - return $document; - } -} diff --git a/src/Helpers/IdStr.php b/src/Helpers/IdStr.php deleted file mode 100644 index 4fe53d7..0000000 --- a/src/Helpers/IdStr.php +++ /dev/null @@ -1,31 +0,0 @@ -addBackImage($backImage); } - $this->mrzSearcher = new MrzSearcher(); + $this->searcher = new MrzSearcher(); + $this->parser = new MrzParser(); + $this->resolver = new VizParser(); } - public function addFrontImage($image): void + public static function all($frontImage = null, $backImage = null){ + $id = new IdentityDocument($frontImage, $backImage); + $mrz = $id->getMrz(); + $parsed = $id->getParsedMrz(); + $face = $id->getFace(); + $faceB64 = "data:image/jpg;base64," . + base64_encode( + $face + ->resize(null, 200, function ($constraint) { + $constraint->aspectRatio(); + }) + ->encode() + ->encoded + ); + $viz = $id->getViz(); + + return [ + "mrz" => $mrz, + "parsed" => $parsed, + "viz" => $viz, + "face" => $faceB64, + ]; + } + + public function addFrontImage($image): IdentityDocument { $image = $this->createImage($image); $this->frontImage = new IdentityImage($image); $this->images[] = &$this->frontImage; + return $this; } - public function addBackImage($image): void + public function addBackImage($image): IdentityDocument { $image = $this->createImage($image); $this->backImage = new IdentityImage($image); $this->images[] = &$this->backImage; + return $this; } private function createImage($file): ?Image @@ -68,8 +103,8 @@ private function mrz(): string { $this->mrz = ''; foreach ($this->images as $image) { - $image->ocr(); - if ($mrz = $this->mrzSearcher->search($image->text)) { + $this->text .= $image->ocr(); + if ($mrz = $this->searcher->search($image->text)) { $this->mrz = $mrz ?? ''; break; } @@ -78,6 +113,23 @@ private function mrz(): string return $this->mrz; } + public function viz(){ + if(!$this->text){ + return null; + } + + return $this->viz = $this->resolver->match($this->parsedMrz, $this->mrz, $this->text); + } + + public function getViz(): array + { + if (! isset($this->viz)) { + $this->viz(); + } + + return $this->viz; + } + public function getMrz(): string { if (! isset($this->mrz)) { @@ -87,9 +139,31 @@ public function getMrz(): string return $this->mrz; } + public function getFace(): ?Image + { + if (! isset($this->face) || !$this->face) { + $this->face(); + } + + return $this->face; + } + + private function face(): string + { + $this->face = null; + foreach ($this->images as $image) { + if ($face = $image->face()) { + $this->face = $face ?? null; + break; + } + } + + return $this->face; + } + public function getParsedMrz(): array { - if (! isset($this->parsedMrz) && $this->mrz) { + if (! isset($this->parsedMrz) || !$this->mrz) { $this->parseMrz(); } @@ -105,6 +179,6 @@ public function setMrz($mrz): IdentityDocument private function parseMrz(): void { - $this->parsedMrz = $this->mrzSearcher->parse($this->getMrz()); + $this->parsedMrz = $this->parser->parse($this->getMrz(), $this->searcher->type); } } diff --git a/src/IdentityDocumentsServiceProvider.php b/src/IdentityDocumentsServiceProvider.php index f57044a..c2e2d3c 100644 --- a/src/IdentityDocumentsServiceProvider.php +++ b/src/IdentityDocumentsServiceProvider.php @@ -32,7 +32,7 @@ public function boot() public function register() { $this->mergeConfigFrom(__DIR__.'/../config/identitydocuments.php', 'identitydocuments'); - + $this->mergeConfigFrom(__DIR__.'/../config/countries.php', 'id_countries'); $this->commands($this->commands); } } diff --git a/src/IdentityImage.php b/src/IdentityImage.php index 173374d..4ac67a9 100644 --- a/src/IdentityImage.php +++ b/src/IdentityImage.php @@ -5,46 +5,65 @@ use Exception; use Google\Cloud\Vision\V1\ImageAnnotatorClient; use Intervention\Image\Image; +use ReflectionClass; +use werk365\IdentityDocuments\Filters\MergeFilter; +use werk365\IdentityDocuments\Interfaces\OCR; +use werk365\IdentityDocuments\Interfaces\FaceDetection; +use werk365\IdentityDocuments\Services\Google; class IdentityImage { public Image $image; public Exception $error; public string $text; - private ImageAnnotatorClient $annotator; + public Image $face; + private string $ocrService; + private string $faceDetectionService; public function __construct(Image $image) { + $this->setOcrService(Google::class); + $this->setFaceDetectionService(Google::class); $this->setImage($image); - $this->annotator = new ImageAnnotatorClient( - ['credentials' => config('google_key')] - ); } - public function setImage(Image $image) - { - $this->image = $image; + public function setOcrService(string $service){ + $class = new ReflectionClass($service); + if (!$class->implementsInterface(OCR::class)) + { + dd("not ocr"); + } + $this->ocrService = $service; } - public function resize() - { + public function setFaceDetectionService(string $service){ + $class = new ReflectionClass($service); + if (!$class->implementsInterface(FaceDetection::class)) + { + dd("not fd"); + } + $this->faceDetectionService = $service; } - public function rotate() + public function setImage(Image $image) { + $this->image = $image; } public function merge(IdentityImage $image): IdentityImage { - return $image; + return new IdentityImage($this->image->filter(new MergeFilter($image->image))); } public function ocr(): string { - $response = $this->annotator->textDetection((string) $this->image->encode()); - $text = $response->getTextAnnotations(); - $this->text = $text[0]->getDescription(); + $service = new $this->ocrService(); + return $this->text = $service->ocr($this->image)->text; + } - return $this->text; + public function face(): ?Image + { + $service = new $this->faceDetectionService(); + return $this->face = $service->detect($this); } } diff --git a/src/Interfaces/FaceDetection.php b/src/Interfaces/FaceDetection.php new file mode 100644 index 0000000..f5ac7e9 --- /dev/null +++ b/src/Interfaces/FaceDetection.php @@ -0,0 +1,10 @@ +countries = config('id_countries'); $this->loadConfig(); } diff --git a/src/Mrz/MrzParser.php b/src/Mrz/MrzParser.php new file mode 100644 index 0000000..9519a9b --- /dev/null +++ b/src/Mrz/MrzParser.php @@ -0,0 +1,41 @@ +values as $name=>$value) { + if ($value[$type]) { + $parsed[$name] = substr($mrz, ...$value[$type]); + } else { + $parsed[$name] = null; + } + } + + [$parsed["last_name"], $parsed["first_name"]] = $this->getFirstLastName($parsed["full_name"]); + + $parsed["issuing_country_name"] = $this->getFullCountryName($parsed["issuing_country"]); + $parsed["nationality_name"] = $this->getFullCountryName($parsed["issuing_country"]); + + return $parsed; + } + + private function getFirstLastName(string $fullName): array + { + [$lastName, $firstName] = explode("<<", $fullName); + return [$lastName, explode("<", $firstName)]; + } + + private function getFullCountryName($countryCode){ + return $this->countries[$countryCode] ?? null; + } +} diff --git a/src/MrzSearcher.php b/src/Mrz/MrzSearcher.php similarity index 90% rename from src/MrzSearcher.php rename to src/Mrz/MrzSearcher.php index 498141f..b0e6548 100644 --- a/src/MrzSearcher.php +++ b/src/Mrz/MrzSearcher.php @@ -1,10 +1,10 @@ findMrzStartPosition($keysPositions, $characters); if ($startPosition === null) { - dd('Not found'); + return null; } $mrz = $this->getMrz($strippedString, $startPosition); @@ -26,20 +26,6 @@ private function getMrz($strippedString, $startPosition) return substr($strippedString, $startPosition, $this->{$this->type}['length']); } - public function parse($mrz) - { - $parsed = []; - foreach ($this->values as $name=>$value) { - if ($value[$this->type]) { - $parsed[$name] = substr($mrz, ...$value[$this->type]); - } else { - $parsed[$name] = null; - } - } - - return $parsed; - } - private function findKeysInCharacters(array $keys, array $characters, $positions = []): array { foreach ($keys as $key => $value) { diff --git a/src/Responses/OcrResponse.php b/src/Responses/OcrResponse.php new file mode 100644 index 0000000..65131cc --- /dev/null +++ b/src/Responses/OcrResponse.php @@ -0,0 +1,12 @@ +text = $input; + } +} diff --git a/src/Services/Google.php b/src/Services/Google.php new file mode 100644 index 0000000..15d0ef8 --- /dev/null +++ b/src/Services/Google.php @@ -0,0 +1,71 @@ +credentials = config('google_key'); + $this->annotator = new ImageAnnotatorClient( + ['credentials' => $this->credentials] + ); + } + + public function ocr(Image $image):OcrResponse + { + $response = $this->annotator->textDetection((string) $image->encode()); + $text = $response->getTextAnnotations(); + return new OcrResponse($text[0]->getDescription()); + } + + public function detect(IdentityImage $image): ?Image + { + $response = $this->annotator->faceDetection((string) $image->image->encode()); + $largest = 0; + $largestFace = null; + foreach( $response->getFaceAnnotations() as $key => $face){ + $dimensions = $this->getFaceDimensions($face); + if($dimensions['width'] + $dimensions['height'] > $largest){ + $largest = $dimensions['width'] + $dimensions['height']; + $largestFace = $dimensions; + } + } + if(!$largestFace){ + return null; + } + $face = $image->image; + $face->resizeCanvas($largestFace['centerX']*2, $largestFace['centerY']*2, 'top-left'); + $face->rotate($largestFace['roll']); + $face->resizeCanvas($largestFace['width'], $largestFace['height'], 'center'); + return $face; + } + + private function getFaceDimensions($face){ + $rectangle = []; + $roll = $face->getRollAngle(); + + foreach($face->getBoundingPoly()->getVertices() as $key => $vertex){ + $rectangle[$key] = []; + $rectangle[$key]['x'] = $vertex->getX(); + $rectangle[$key]['y'] = $vertex->getY(); + } + + $rectangle['width'] = $rectangle[1]['x'] - $rectangle[0]['x']; + $rectangle['height'] = $rectangle[3]['y'] - $rectangle[0]['y']; + $rectangle['centerX'] = $rectangle[0]['x'] + $rectangle['width']/2; + $rectangle['centerY'] = $rectangle[0]['y'] + $rectangle['height']/2; + $rectangle['roll'] = $roll; + + return $rectangle; + } +} diff --git a/src/Viz/Viz.php b/src/Viz/Viz.php new file mode 100644 index 0000000..069b75d --- /dev/null +++ b/src/Viz/Viz.php @@ -0,0 +1,8 @@ + $character){ + $mrzCharacters[$key] = $character . $ignore; + } + $mrzRegex = implode($mrzCharacters); + $text = preg_replace("/$mrzRegex/", '', $text); + $text = preg_replace("/\n/", ' ', $text); + + $words = explode(' ', $text); + $this->viz['first_name'] = []; + foreach($words as $word){ + if($this->compare($parsed['last_name'], $word)){ + $this->viz['last_name'] = $word; + } + foreach($parsed['first_name'] as $key => $first_name){ + if($this->compare($parsed['first_name'][$key], $word)){ + $this->viz['first_name'][$key] = $word; + } + } + } + return $this->viz; + } + + private function compare($mrz, $viz){ + $viz = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $viz); + $viz = preg_replace('/([ ]|[-])/', '<', $viz); + $viz = preg_replace("/\p{P}/u", '', $viz); + if($this->fuzzy_match($mrz, $viz, 0)['match']){ + return true; + } + return false; + } + + private function fuzzy_match($query,$target,$distance) { + ## set max substitution steps if set to 0 + if ($distance == 0) { + $length = strlen($query); + if ($length > 10) { + $distance = 4; + } + elseif ($length > 6) { + $distance = 3; + } + else { + $distance = 2; + } + } + $lev = levenshtein(strtolower($query), strtolower($target)); + if ($lev <= $distance) { + return array('match' => 1, 'distance' => $lev, 'max_distance' => $distance); + } + else { + return array('match' => 0, 'distance' => $lev, 'max_distance' => $distance); + } + } +} From df0f1c9c3556dc0e9d2deb36c9809530c0500b47 Mon Sep 17 00:00:00 2001 From: HergenD Date: Wed, 21 Apr 2021 12:49:50 +0000 Subject: [PATCH 04/26] Apply fixes from StyleCI --- config/countries.php | 42 ++++----- config/mrz_templates.php | 14 +-- src/IdentityDocument.php | 24 +++--- src/IdentityImage.php | 21 ++--- src/Interfaces/FaceDetection.php | 1 + src/Interfaces/OCR.php | 1 + src/Mrz/Mrz.php | 144 +++++++++++++++---------------- src/Mrz/MrzParser.php | 17 ++-- src/Responses/OcrResponse.php | 3 +- src/Services/Google.php | 28 +++--- src/Viz/Viz.php | 1 - src/Viz/VizParser.php | 40 +++++---- 12 files changed, 175 insertions(+), 161 deletions(-) diff --git a/config/countries.php b/config/countries.php index def3735..d58f5eb 100644 --- a/config/countries.php +++ b/config/countries.php @@ -250,25 +250,25 @@ 'ZAF'=>'South Africa', 'ZMB'=>'Zambia', 'ZWE'=>'Zimbabwe', - "D" => "Germany", - "EUE" => "European Union", - "GBD" => "British Overseas Territories Citizen", - "GBN" => "British National (Overseas)", - "GBO" => "British Overseas Citizen", - "GBP" => "British Protected Person", - "GBS" => "British Subject", - "UNA" => "specialized agency of the United Nations", - "UNK" => "Resident of Kosovo", - "UNO" => "United Nations organization", - "XBA" => "African Development Bank", - "XIM" => "African Export–Import Bank", - "XCC" => "Caribbean Community or one of its emissaries", - "XCO" => "Common Market for Eastern and Southern Africa", - "XEC" => "Economic Community of West African States", - "XPO" => "International Criminal Police Organization", - "XOM" => "Sovereign Military Order of Malta", - "XXA" => "Stateless person", - "XXB" => "Refugee", - "XXC" => "Refugee", - "XXX" => "Unspecified nationality" + 'D' => 'Germany', + 'EUE' => 'European Union', + 'GBD' => 'British Overseas Territories Citizen', + 'GBN' => 'British National (Overseas)', + 'GBO' => 'British Overseas Citizen', + 'GBP' => 'British Protected Person', + 'GBS' => 'British Subject', + 'UNA' => 'specialized agency of the United Nations', + 'UNK' => 'Resident of Kosovo', + 'UNO' => 'United Nations organization', + 'XBA' => 'African Development Bank', + 'XIM' => 'African Export–Import Bank', + 'XCC' => 'Caribbean Community or one of its emissaries', + 'XCO' => 'Common Market for Eastern and Southern Africa', + 'XEC' => 'Economic Community of West African States', + 'XPO' => 'International Criminal Police Organization', + 'XOM' => 'Sovereign Military Order of Malta', + 'XXA' => 'Stateless person', + 'XXB' => 'Refugee', + 'XXC' => 'Refugee', + 'XXX' => 'Unspecified nationality', ]; diff --git a/config/mrz_templates.php b/config/mrz_templates.php index 9d487a6..39c7ded 100644 --- a/config/mrz_templates.php +++ b/config/mrz_templates.php @@ -1,20 +1,20 @@ [ - "keys" => ["P"], - "check_digits" => [ + 'TD3' => [ + 'keys' => ['P'], + 'check_digits' => [ 53 => [[44, 9]], 63 => [[57, 6]], 71 => [[65, 6]], 86 => [[72, 14]], - 87 => [[44, 10], [57, 7], [65, 22]] - ] + 87 => [[44, 10], [57, 7], [65, 22]], + ], ], - "TD1" => [ + 'TD1' => [ ], - "VISA" => [ + 'VISA' => [ ], ]; diff --git a/src/IdentityDocument.php b/src/IdentityDocument.php index c9b9fe3..2b8a7f6 100644 --- a/src/IdentityDocument.php +++ b/src/IdentityDocument.php @@ -36,12 +36,13 @@ public function __construct($frontImage = null, $backImage = null) $this->resolver = new VizParser(); } - public static function all($frontImage = null, $backImage = null){ + public static function all($frontImage = null, $backImage = null) + { $id = new IdentityDocument($frontImage, $backImage); $mrz = $id->getMrz(); $parsed = $id->getParsedMrz(); $face = $id->getFace(); - $faceB64 = "data:image/jpg;base64," . + $faceB64 = 'data:image/jpg;base64,'. base64_encode( $face ->resize(null, 200, function ($constraint) { @@ -53,10 +54,10 @@ public static function all($frontImage = null, $backImage = null){ $viz = $id->getViz(); return [ - "mrz" => $mrz, - "parsed" => $parsed, - "viz" => $viz, - "face" => $faceB64, + 'mrz' => $mrz, + 'parsed' => $parsed, + 'viz' => $viz, + 'face' => $faceB64, ]; } @@ -65,6 +66,7 @@ public function addFrontImage($image): IdentityDocument $image = $this->createImage($image); $this->frontImage = new IdentityImage($image); $this->images[] = &$this->frontImage; + return $this; } @@ -73,6 +75,7 @@ public function addBackImage($image): IdentityDocument $image = $this->createImage($image); $this->backImage = new IdentityImage($image); $this->images[] = &$this->backImage; + return $this; } @@ -113,8 +116,9 @@ private function mrz(): string return $this->mrz; } - public function viz(){ - if(!$this->text){ + public function viz() + { + if (! $this->text) { return null; } @@ -141,7 +145,7 @@ public function getMrz(): string public function getFace(): ?Image { - if (! isset($this->face) || !$this->face) { + if (! isset($this->face) || ! $this->face) { $this->face(); } @@ -163,7 +167,7 @@ private function face(): string public function getParsedMrz(): array { - if (! isset($this->parsedMrz) || !$this->mrz) { + if (! isset($this->parsedMrz) || ! $this->mrz) { $this->parseMrz(); } diff --git a/src/IdentityImage.php b/src/IdentityImage.php index 4ac67a9..cbb9fc0 100644 --- a/src/IdentityImage.php +++ b/src/IdentityImage.php @@ -3,12 +3,11 @@ namespace werk365\IdentityDocuments; use Exception; -use Google\Cloud\Vision\V1\ImageAnnotatorClient; use Intervention\Image\Image; use ReflectionClass; use werk365\IdentityDocuments\Filters\MergeFilter; -use werk365\IdentityDocuments\Interfaces\OCR; use werk365\IdentityDocuments\Interfaces\FaceDetection; +use werk365\IdentityDocuments\Interfaces\OCR; use werk365\IdentityDocuments\Services\Google; class IdentityImage @@ -27,20 +26,20 @@ public function __construct(Image $image) $this->setImage($image); } - public function setOcrService(string $service){ + public function setOcrService(string $service) + { $class = new ReflectionClass($service); - if (!$class->implementsInterface(OCR::class)) - { - dd("not ocr"); + if (! $class->implementsInterface(OCR::class)) { + dd('not ocr'); } $this->ocrService = $service; } - public function setFaceDetectionService(string $service){ + public function setFaceDetectionService(string $service) + { $class = new ReflectionClass($service); - if (!$class->implementsInterface(FaceDetection::class)) - { - dd("not fd"); + if (! $class->implementsInterface(FaceDetection::class)) { + dd('not fd'); } $this->faceDetectionService = $service; } @@ -58,12 +57,14 @@ public function merge(IdentityImage $image): IdentityImage public function ocr(): string { $service = new $this->ocrService(); + return $this->text = $service->ocr($this->image)->text; } public function face(): ?Image { $service = new $this->faceDetectionService(); + return $this->face = $service->detect($this); } } diff --git a/src/Interfaces/FaceDetection.php b/src/Interfaces/FaceDetection.php index f5ac7e9..6a7b251 100644 --- a/src/Interfaces/FaceDetection.php +++ b/src/Interfaces/FaceDetection.php @@ -1,4 +1,5 @@ values = [ 'document_key' => [ - 'TD1' => [0, 1], - 'TD2' => [0, 1], - 'TD3' => [0, 1], - 'MRVA' => [0, 1], - 'MRVB' => [0, 1], - ], + 'TD1' => [0, 1], + 'TD2' => [0, 1], + 'TD3' => [0, 1], + 'MRVA' => [0, 1], + 'MRVB' => [0, 1], + ], 'document_type' => [ - 'TD1' => [1, 1], - 'TD2' => [1, 1], - 'TD3' => [1, 1], - 'MRVA' => [1, 1], - 'MRVB' => [1, 1], - ], + 'TD1' => [1, 1], + 'TD2' => [1, 1], + 'TD3' => [1, 1], + 'MRVA' => [1, 1], + 'MRVB' => [1, 1], + ], 'issuing_country' => [ - 'TD1' => [2, 3], - 'TD2' => [2, 3], - 'TD3' => [2, 3], - 'MRVA' => [2, 3], - 'MRVB' => [2, 3], - ], + 'TD1' => [2, 3], + 'TD2' => [2, 3], + 'TD3' => [2, 3], + 'MRVA' => [2, 3], + 'MRVB' => [2, 3], + ], 'full_name' => [ - 'TD1' => [60, 30], - 'TD2' => [5, 31], - 'TD3' => [5, 39], - 'MRVA' => [5, 39], - 'MRVB' => [5, 31], - ], + 'TD1' => [60, 30], + 'TD2' => [5, 31], + 'TD3' => [5, 39], + 'MRVA' => [5, 39], + 'MRVB' => [5, 31], + ], 'document_number' => [ - 'TD1' => [5, 9], - 'TD2' => [36, 9], - 'TD3' => [44, 9], - 'MRVA' => [44, 9], - 'MRVB' => [36, 9], - ], + 'TD1' => [5, 9], + 'TD2' => [36, 9], + 'TD3' => [44, 9], + 'MRVA' => [44, 9], + 'MRVB' => [36, 9], + ], 'nationality' => [ - 'TD1' => [45, 3], - 'TD2' => [46, 3], - 'TD3' => [54, 3], - 'MRVA' => [54, 3], - 'MRVB' => [46, 3], - ], + 'TD1' => [45, 3], + 'TD2' => [46, 3], + 'TD3' => [54, 3], + 'MRVA' => [54, 3], + 'MRVB' => [46, 3], + ], 'date_of_birth' => [ - 'TD1' => [30, 6], - 'TD2' => [49, 6], - 'TD3' => [57, 6], - 'MRVA' => [57, 6], - 'MRVB' => [49, 6], - ], + 'TD1' => [30, 6], + 'TD2' => [49, 6], + 'TD3' => [57, 6], + 'MRVA' => [57, 6], + 'MRVB' => [49, 6], + ], 'sex' => [ - 'TD1' => [37, 1], - 'TD2' => [56, 1], - 'TD3' => [64, 1], - 'MRVA' => [64, 1], - 'MRVB' => [56, 1], - ], + 'TD1' => [37, 1], + 'TD2' => [56, 1], + 'TD3' => [64, 1], + 'MRVA' => [64, 1], + 'MRVB' => [56, 1], + ], 'expiration_date' => [ - 'TD1' => [38, 6], - 'TD2' => [57, 6], - 'TD3' => [65, 6], - 'MRVA' => [65, 6], - 'MRVB' => [57, 6], - ], + 'TD1' => [38, 6], + 'TD2' => [57, 6], + 'TD3' => [65, 6], + 'MRVA' => [65, 6], + 'MRVB' => [57, 6], + ], 'personal_number' => [ - 'TD1' => [], - 'TD2' => [], - 'TD3' => [72, 14], - 'MRVA' => [], - 'MRVB' => [], - ], + 'TD1' => [], + 'TD2' => [], + 'TD3' => [72, 14], + 'MRVA' => [], + 'MRVB' => [], + ], 'optional_data_row_1' => [ - 'TD1' => [15, 15], - 'TD2' => [], - 'TD3' => [], - 'MRVA' => [], - 'MRVB' => [], - ], + 'TD1' => [15, 15], + 'TD2' => [], + 'TD3' => [], + 'MRVA' => [], + 'MRVB' => [], + ], 'optional_data_row_2' => [ - 'TD1' => [48, 11], - 'TD2' => [64, 7], - 'TD3' => [], - 'MRVA' => [72, 16], - 'MRVB' => [64, 8], - ], + 'TD1' => [48, 11], + 'TD2' => [64, 7], + 'TD3' => [], + 'MRVA' => [72, 16], + 'MRVB' => [64, 8], + ], ]; } } diff --git a/src/Mrz/MrzParser.php b/src/Mrz/MrzParser.php index 9519a9b..987414f 100644 --- a/src/Mrz/MrzParser.php +++ b/src/Mrz/MrzParser.php @@ -6,10 +6,9 @@ class MrzParser extends Mrz { public function parse($mrz, $type) { - $parsed = []; - if(!isset($type) || !$type){ + if (! isset($type) || ! $type) { return $parsed; } @@ -21,21 +20,23 @@ public function parse($mrz, $type) } } - [$parsed["last_name"], $parsed["first_name"]] = $this->getFirstLastName($parsed["full_name"]); + [$parsed['last_name'], $parsed['first_name']] = $this->getFirstLastName($parsed['full_name']); - $parsed["issuing_country_name"] = $this->getFullCountryName($parsed["issuing_country"]); - $parsed["nationality_name"] = $this->getFullCountryName($parsed["issuing_country"]); + $parsed['issuing_country_name'] = $this->getFullCountryName($parsed['issuing_country']); + $parsed['nationality_name'] = $this->getFullCountryName($parsed['issuing_country']); return $parsed; } private function getFirstLastName(string $fullName): array { - [$lastName, $firstName] = explode("<<", $fullName); - return [$lastName, explode("<", $firstName)]; + [$lastName, $firstName] = explode('<<', $fullName); + + return [$lastName, explode('<', $firstName)]; } - private function getFullCountryName($countryCode){ + private function getFullCountryName($countryCode) + { return $this->countries[$countryCode] ?? null; } } diff --git a/src/Responses/OcrResponse.php b/src/Responses/OcrResponse.php index 65131cc..6116c1b 100644 --- a/src/Responses/OcrResponse.php +++ b/src/Responses/OcrResponse.php @@ -6,7 +6,8 @@ class OcrResponse { public string $text; - public function __construct(string $input){ + public function __construct(string $input) + { $this->text = $input; } } diff --git a/src/Services/Google.php b/src/Services/Google.php index 15d0ef8..4831be4 100644 --- a/src/Services/Google.php +++ b/src/Services/Google.php @@ -1,30 +1,32 @@ credentials = config('google_key'); $this->annotator = new ImageAnnotatorClient( ['credentials' => $this->credentials] ); } - public function ocr(Image $image):OcrResponse + public function ocr(Image $image): OcrResponse { $response = $this->annotator->textDetection((string) $image->encode()); $text = $response->getTextAnnotations(); + return new OcrResponse($text[0]->getDescription()); } @@ -33,28 +35,30 @@ public function detect(IdentityImage $image): ?Image $response = $this->annotator->faceDetection((string) $image->image->encode()); $largest = 0; $largestFace = null; - foreach( $response->getFaceAnnotations() as $key => $face){ + foreach ($response->getFaceAnnotations() as $key => $face) { $dimensions = $this->getFaceDimensions($face); - if($dimensions['width'] + $dimensions['height'] > $largest){ + if ($dimensions['width'] + $dimensions['height'] > $largest) { $largest = $dimensions['width'] + $dimensions['height']; $largestFace = $dimensions; } } - if(!$largestFace){ + if (! $largestFace) { return null; } $face = $image->image; - $face->resizeCanvas($largestFace['centerX']*2, $largestFace['centerY']*2, 'top-left'); + $face->resizeCanvas($largestFace['centerX'] * 2, $largestFace['centerY'] * 2, 'top-left'); $face->rotate($largestFace['roll']); $face->resizeCanvas($largestFace['width'], $largestFace['height'], 'center'); + return $face; } - private function getFaceDimensions($face){ + private function getFaceDimensions($face) + { $rectangle = []; $roll = $face->getRollAngle(); - foreach($face->getBoundingPoly()->getVertices() as $key => $vertex){ + foreach ($face->getBoundingPoly()->getVertices() as $key => $vertex) { $rectangle[$key] = []; $rectangle[$key]['x'] = $vertex->getX(); $rectangle[$key]['y'] = $vertex->getY(); @@ -62,8 +66,8 @@ private function getFaceDimensions($face){ $rectangle['width'] = $rectangle[1]['x'] - $rectangle[0]['x']; $rectangle['height'] = $rectangle[3]['y'] - $rectangle[0]['y']; - $rectangle['centerX'] = $rectangle[0]['x'] + $rectangle['width']/2; - $rectangle['centerY'] = $rectangle[0]['y'] + $rectangle['height']/2; + $rectangle['centerX'] = $rectangle[0]['x'] + $rectangle['width'] / 2; + $rectangle['centerY'] = $rectangle[0]['y'] + $rectangle['height'] / 2; $rectangle['roll'] = $roll; return $rectangle; diff --git a/src/Viz/Viz.php b/src/Viz/Viz.php index 069b75d..498c97d 100644 --- a/src/Viz/Viz.php +++ b/src/Viz/Viz.php @@ -4,5 +4,4 @@ class Viz { - } diff --git a/src/Viz/VizParser.php b/src/Viz/VizParser.php index 20629dc..307e423 100644 --- a/src/Viz/VizParser.php +++ b/src/Viz/VizParser.php @@ -6,11 +6,12 @@ class VizParser extends Viz { private array $viz = []; - public function match($parsed, $mrz, $text){ + public function match($parsed, $mrz, $text) + { $ignore = "\n*\s*"; $mrzCharacters = str_split($mrz); - foreach($mrzCharacters as $key => $character){ - $mrzCharacters[$key] = $character . $ignore; + foreach ($mrzCharacters as $key => $character) { + $mrzCharacters[$key] = $character.$ignore; } $mrzRegex = implode($mrzCharacters); $text = preg_replace("/$mrzRegex/", '', $text); @@ -18,49 +19,50 @@ public function match($parsed, $mrz, $text){ $words = explode(' ', $text); $this->viz['first_name'] = []; - foreach($words as $word){ - if($this->compare($parsed['last_name'], $word)){ + foreach ($words as $word) { + if ($this->compare($parsed['last_name'], $word)) { $this->viz['last_name'] = $word; } - foreach($parsed['first_name'] as $key => $first_name){ - if($this->compare($parsed['first_name'][$key], $word)){ + foreach ($parsed['first_name'] as $key => $first_name) { + if ($this->compare($parsed['first_name'][$key], $word)) { $this->viz['first_name'][$key] = $word; } } } + return $this->viz; } - private function compare($mrz, $viz){ + private function compare($mrz, $viz) + { $viz = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $viz); $viz = preg_replace('/([ ]|[-])/', '<', $viz); $viz = preg_replace("/\p{P}/u", '', $viz); - if($this->fuzzy_match($mrz, $viz, 0)['match']){ + if ($this->fuzzy_match($mrz, $viz, 0)['match']) { return true; } + return false; } - private function fuzzy_match($query,$target,$distance) { - ## set max substitution steps if set to 0 + private function fuzzy_match($query, $target, $distance) + { + //# set max substitution steps if set to 0 if ($distance == 0) { $length = strlen($query); if ($length > 10) { $distance = 4; - } - elseif ($length > 6) { + } elseif ($length > 6) { $distance = 3; - } - else { + } else { $distance = 2; } } $lev = levenshtein(strtolower($query), strtolower($target)); if ($lev <= $distance) { - return array('match' => 1, 'distance' => $lev, 'max_distance' => $distance); - } - else { - return array('match' => 0, 'distance' => $lev, 'max_distance' => $distance); + return ['match' => 1, 'distance' => $lev, 'max_distance' => $distance]; + } else { + return ['match' => 0, 'distance' => $lev, 'max_distance' => $distance]; } } } From 7c5878c857cb7d0102d01817af6a80b00830d738 Mon Sep 17 00:00:00 2001 From: Hergen Dillema Date: Thu, 22 Apr 2021 12:23:28 +0200 Subject: [PATCH 05/26] SOme tests added --- src/IdentityDocumentsServiceProvider.php | 2 +- tests/Feature/MrzParserTest.php | 50 +++++++++++++++++++++ tests/Feature/MrzSearcherTest.php | 35 +++++++++++++++ tests/Feature/VizParserTest.php | 56 ++++++++++++++++++++++++ 4 files changed, 142 insertions(+), 1 deletion(-) create mode 100644 tests/Feature/MrzParserTest.php create mode 100644 tests/Feature/MrzSearcherTest.php create mode 100644 tests/Feature/VizParserTest.php diff --git a/src/IdentityDocumentsServiceProvider.php b/src/IdentityDocumentsServiceProvider.php index c2e2d3c..a020373 100644 --- a/src/IdentityDocumentsServiceProvider.php +++ b/src/IdentityDocumentsServiceProvider.php @@ -1,6 +1,6 @@ 'P', + 'document_type' => '<', + 'issuing_country' => 'NLD', + 'full_name' => 'DE 'SPECI2014', + 'nationality' => 'NLD', + 'date_of_birth' => '650310', + 'sex' => 'F', + 'expiration_date' => '240115', + 'personal_number' => '999999990<<<<<', + 'optional_data_row_1' => NULL, + 'optional_data_row_2' => NULL, + 'last_name' => 'DE + [ + 0 => 'WILLEKE', + 1 => 'LISELOTTE', + ], + 'issuing_country_name' => 'Netherlands', + 'nationality_name' => 'Netherlands', + ]; + + public function setUp(): void + { + parent::setUp(); + } + + + + /** @test */ + public function correctly_parse_mrz() + { + $parser = new MrzParser(); + $this->assertEquals($this->expected, $parser->parse($this->mrz, 'TD3')); + } +} diff --git a/tests/Feature/MrzSearcherTest.php b/tests/Feature/MrzSearcherTest.php new file mode 100644 index 0000000..65ee533 --- /dev/null +++ b/tests/Feature/MrzSearcherTest.php @@ -0,0 +1,35 @@ +assertEquals($this->mrz, $searcher->search($this->full_text)); + } + + /** @test */ + public function malformed_mrz_is_not_found_in_text() + { + $searcher = new MrzSearcher(); + $this->assertEquals(null, $searcher->search($this->malformed_text)); + } +} diff --git a/tests/Feature/VizParserTest.php b/tests/Feature/VizParserTest.php new file mode 100644 index 0000000..83b7e02 --- /dev/null +++ b/tests/Feature/VizParserTest.php @@ -0,0 +1,56 @@ + 'P', + 'document_type' => '<', + 'issuing_country' => 'NLD', + 'full_name' => 'DE 'SPECI2014', + 'nationality' => 'NLD', + 'date_of_birth' => '650310', + 'sex' => 'F', + 'expiration_date' => '240115', + 'personal_number' => '999999990<<<<<', + 'optional_data_row_1' => NULL, + 'optional_data_row_2' => NULL, + 'last_name' => 'DE + [ + 0 => 'WILLEKE', + 1 => 'LISELOTTE', + ], + 'issuing_country_name' => 'Netherlands', + 'nationality_name' => 'Netherlands', + ]; + private array $expected = [ + "first_name" => [ + "Willeke", + "Liselotte" + ], + "last_name" => "Bruijn" + ]; + + public function setUp(): void + { + parent::setUp(); + } + + + /** @test */ + public function viz_is_parsed_correctly() + { + $parser = new VizParser(); + $this->assertEquals($this->expected, $parser->match($this->parsed, $this->mrz, $this->full_text)); + } +} From 127cf220dc587779f75eb50f380e7c07745701e7 Mon Sep 17 00:00:00 2001 From: HergenD Date: Thu, 22 Apr 2021 10:24:28 +0000 Subject: [PATCH 06/26] Apply fixes from StyleCI --- tests/Feature/MrzParserTest.php | 48 ++++++++++++++----------------- tests/Feature/MrzSearcherTest.php | 9 ++---- tests/Feature/VizParserTest.php | 22 ++++++-------- 3 files changed, 33 insertions(+), 46 deletions(-) diff --git a/tests/Feature/MrzParserTest.php b/tests/Feature/MrzParserTest.php index aa5fefe..6c42692 100644 --- a/tests/Feature/MrzParserTest.php +++ b/tests/Feature/MrzParserTest.php @@ -2,45 +2,39 @@ namespace Werk365\IdentityDocuments\Tests\Feature; -use Illuminate\Support\Facades\Config; use Tests\TestCase; use werk365\IdentityDocuments\Mrz\MrzParser; -use werk365\IdentityDocuments\Mrz\MrzSearcher; - class MrzParserTest extends TestCase { - private string $mrz = "P 'P', - 'document_type' => '<', - 'issuing_country' => 'NLD', - 'full_name' => 'DE 'SPECI2014', - 'nationality' => 'NLD', - 'date_of_birth' => '650310', - 'sex' => 'F', - 'expiration_date' => '240115', - 'personal_number' => '999999990<<<<<', - 'optional_data_row_1' => NULL, - 'optional_data_row_2' => NULL, - 'last_name' => 'DE - [ - 0 => 'WILLEKE', - 1 => 'LISELOTTE', - ], - 'issuing_country_name' => 'Netherlands', - 'nationality_name' => 'Netherlands', - ]; + 'document_key' => 'P', + 'document_type' => '<', + 'issuing_country' => 'NLD', + 'full_name' => 'DE 'SPECI2014', + 'nationality' => 'NLD', + 'date_of_birth' => '650310', + 'sex' => 'F', + 'expiration_date' => '240115', + 'personal_number' => '999999990<<<<<', + 'optional_data_row_1' => null, + 'optional_data_row_2' => null, + 'last_name' => 'DE [ + 0 => 'WILLEKE', + 1 => 'LISELOTTE', + ], + 'issuing_country_name' => 'Netherlands', + 'nationality_name' => 'Netherlands', + ]; public function setUp(): void { parent::setUp(); } - - /** @test */ public function correctly_parse_mrz() { diff --git a/tests/Feature/MrzSearcherTest.php b/tests/Feature/MrzSearcherTest.php index 65ee533..291e0cf 100644 --- a/tests/Feature/MrzSearcherTest.php +++ b/tests/Feature/MrzSearcherTest.php @@ -5,20 +5,17 @@ use Tests\TestCase; use werk365\IdentityDocuments\Mrz\MrzSearcher; - class MrzSearcherTest extends TestCase { - private string $mrz = "P 'P', 'document_type' => '<', @@ -22,11 +20,10 @@ class VizParserTest extends TestCase 'sex' => 'F', 'expiration_date' => '240115', 'personal_number' => '999999990<<<<<', - 'optional_data_row_1' => NULL, - 'optional_data_row_2' => NULL, + 'optional_data_row_1' => null, + 'optional_data_row_2' => null, 'last_name' => 'DE - [ + 'first_name' => [ 0 => 'WILLEKE', 1 => 'LISELOTTE', ], @@ -34,11 +31,11 @@ class VizParserTest extends TestCase 'nationality_name' => 'Netherlands', ]; private array $expected = [ - "first_name" => [ - "Willeke", - "Liselotte" + 'first_name' => [ + 'Willeke', + 'Liselotte', ], - "last_name" => "Bruijn" + 'last_name' => 'Bruijn', ]; public function setUp(): void @@ -46,7 +43,6 @@ public function setUp(): void parent::setUp(); } - /** @test */ public function viz_is_parsed_correctly() { From 9a719bed9f9d7ea951a898ba18ec544463f029b3 Mon Sep 17 00:00:00 2001 From: Hergen Dillema Date: Thu, 22 Apr 2021 15:56:38 +0200 Subject: [PATCH 07/26] Few updates in parsing - Able to detect last names that have spaces in them - Strip filler characters from country code before resolving - Add confidence score to viz fuzzy search results --- src/Mrz/MrzParser.php | 1 + src/Viz/VizParser.php | 75 +++++++++++++++++++++++-------------------- 2 files changed, 41 insertions(+), 35 deletions(-) diff --git a/src/Mrz/MrzParser.php b/src/Mrz/MrzParser.php index 987414f..ae5c15c 100644 --- a/src/Mrz/MrzParser.php +++ b/src/Mrz/MrzParser.php @@ -37,6 +37,7 @@ private function getFirstLastName(string $fullName): array private function getFullCountryName($countryCode) { + $countryCode = preg_replace('/countries[$countryCode] ?? null; } } diff --git a/src/Viz/VizParser.php b/src/Viz/VizParser.php index 307e423..378d365 100644 --- a/src/Viz/VizParser.php +++ b/src/Viz/VizParser.php @@ -4,7 +4,10 @@ class VizParser extends Viz { - private array $viz = []; + private array $viz = [ + 'first_name' => [], + 'last_name' => null, + ]; public function match($parsed, $mrz, $text) { @@ -16,53 +19,55 @@ public function match($parsed, $mrz, $text) $mrzRegex = implode($mrzCharacters); $text = preg_replace("/$mrzRegex/", '', $text); $text = preg_replace("/\n/", ' ', $text); - $words = explode(' ', $text); - $this->viz['first_name'] = []; - foreach ($words as $word) { - if ($this->compare($parsed['last_name'], $word)) { - $this->viz['last_name'] = $word; + $lastNameScore = 0.4; + $firstNameScore = []; + foreach ($words as $wordKey => $word) { + $lastName = $word; + if(substr_count($parsed['last_name'], "<")){ + $fillerAmount = range(0, substr_count($parsed['last_name'], "<")); + $lastName = []; + foreach($fillerAmount as $count){ + if(isset($words[$wordKey + $count])){ + array_push($lastName, $words[$wordKey + $count]); + } + } + $lastName = implode('<', $lastName); + } + if ($this->compare($parsed['last_name'], $lastName) > $lastNameScore) { + $this->viz['last_name']['value'] = preg_replace('/compare($parsed['last_name'], $lastName); + $this->viz['last_name']['confidence'] = $lastNameScore; + } foreach ($parsed['first_name'] as $key => $first_name) { - if ($this->compare($parsed['first_name'][$key], $word)) { - $this->viz['first_name'][$key] = $word; + if(!isset($firstNameScore[$key])){ + $firstNameScore[$key] = 0.4; + } + if ($this->compare($parsed['first_name'][$key], $word) > $firstNameScore[$key]) { + $firstNameScore[$key] = $this->compare($parsed['first_name'][$key], $word); + $first_name = [ + 'value' => $word, + 'confidence' => $firstNameScore[$key] + ]; + $this->viz['first_name'][$key] = $first_name; } } } - + ksort($this->viz['first_name']); + $this->viz['first_name'] = array_values($this->viz['first_name']); return $this->viz; } private function compare($mrz, $viz) { + if(strlen($viz) == 0){ + return 0; + } $viz = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $viz); $viz = preg_replace('/([ ]|[-])/', '<', $viz); $viz = preg_replace("/\p{P}/u", '', $viz); - if ($this->fuzzy_match($mrz, $viz, 0)['match']) { - return true; - } - - return false; - } - - private function fuzzy_match($query, $target, $distance) - { - //# set max substitution steps if set to 0 - if ($distance == 0) { - $length = strlen($query); - if ($length > 10) { - $distance = 4; - } elseif ($length > 6) { - $distance = 3; - } else { - $distance = 2; - } - } - $lev = levenshtein(strtolower($query), strtolower($target)); - if ($lev <= $distance) { - return ['match' => 1, 'distance' => $lev, 'max_distance' => $distance]; - } else { - return ['match' => 0, 'distance' => $lev, 'max_distance' => $distance]; - } + $distance = levenshtein(strtolower($mrz), strtolower($viz)); + return (strlen($viz)-$distance)/strlen($viz); } } From 6133d2a07198ad44fc11b6e312f12b60ceefd6d8 Mon Sep 17 00:00:00 2001 From: HergenD Date: Thu, 22 Apr 2021 13:57:59 +0000 Subject: [PATCH 08/26] Apply fixes from StyleCI --- src/Mrz/MrzParser.php | 1 + src/Viz/VizParser.php | 19 ++++++++++--------- 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/src/Mrz/MrzParser.php b/src/Mrz/MrzParser.php index ae5c15c..ecda2ff 100644 --- a/src/Mrz/MrzParser.php +++ b/src/Mrz/MrzParser.php @@ -38,6 +38,7 @@ private function getFirstLastName(string $fullName): array private function getFullCountryName($countryCode) { $countryCode = preg_replace('/countries[$countryCode] ?? null; } } diff --git a/src/Viz/VizParser.php b/src/Viz/VizParser.php index 378d365..c3a7c09 100644 --- a/src/Viz/VizParser.php +++ b/src/Viz/VizParser.php @@ -24,11 +24,11 @@ public function match($parsed, $mrz, $text) $firstNameScore = []; foreach ($words as $wordKey => $word) { $lastName = $word; - if(substr_count($parsed['last_name'], "<")){ - $fillerAmount = range(0, substr_count($parsed['last_name'], "<")); + if (substr_count($parsed['last_name'], '<')) { + $fillerAmount = range(0, substr_count($parsed['last_name'], '<')); $lastName = []; - foreach($fillerAmount as $count){ - if(isset($words[$wordKey + $count])){ + foreach ($fillerAmount as $count) { + if (isset($words[$wordKey + $count])) { array_push($lastName, $words[$wordKey + $count]); } } @@ -38,17 +38,16 @@ public function match($parsed, $mrz, $text) $this->viz['last_name']['value'] = preg_replace('/compare($parsed['last_name'], $lastName); $this->viz['last_name']['confidence'] = $lastNameScore; - } foreach ($parsed['first_name'] as $key => $first_name) { - if(!isset($firstNameScore[$key])){ + if (! isset($firstNameScore[$key])) { $firstNameScore[$key] = 0.4; } if ($this->compare($parsed['first_name'][$key], $word) > $firstNameScore[$key]) { $firstNameScore[$key] = $this->compare($parsed['first_name'][$key], $word); $first_name = [ 'value' => $word, - 'confidence' => $firstNameScore[$key] + 'confidence' => $firstNameScore[$key], ]; $this->viz['first_name'][$key] = $first_name; } @@ -56,18 +55,20 @@ public function match($parsed, $mrz, $text) } ksort($this->viz['first_name']); $this->viz['first_name'] = array_values($this->viz['first_name']); + return $this->viz; } private function compare($mrz, $viz) { - if(strlen($viz) == 0){ + if (strlen($viz) == 0) { return 0; } $viz = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $viz); $viz = preg_replace('/([ ]|[-])/', '<', $viz); $viz = preg_replace("/\p{P}/u", '', $viz); $distance = levenshtein(strtolower($mrz), strtolower($viz)); - return (strlen($viz)-$distance)/strlen($viz); + + return (strlen($viz) - $distance) / strlen($viz); } } From 29bd46c06c64953427b9e480a94c232404a52f56 Mon Sep 17 00:00:00 2001 From: Hergen Dillema Date: Thu, 22 Apr 2021 16:43:18 +0200 Subject: [PATCH 09/26] quick fix --- src/Viz/VizParser.php | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/Viz/VizParser.php b/src/Viz/VizParser.php index c3a7c09..9508676 100644 --- a/src/Viz/VizParser.php +++ b/src/Viz/VizParser.php @@ -61,12 +61,15 @@ public function match($parsed, $mrz, $text) private function compare($mrz, $viz) { - if (strlen($viz) == 0) { - return 0; - } + $viz = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $viz); $viz = preg_replace('/([ ]|[-])/', '<', $viz); $viz = preg_replace("/\p{P}/u", '', $viz); + + if (strlen($viz) == 0) { + return 0; + } + $distance = levenshtein(strtolower($mrz), strtolower($viz)); return (strlen($viz) - $distance) / strlen($viz); From aa78d4134e04f797212aaa7c1522a9f23b2118ab Mon Sep 17 00:00:00 2001 From: HergenD Date: Mon, 26 Apr 2021 08:47:41 +0000 Subject: [PATCH 10/26] Apply fixes from StyleCI --- src/Viz/VizParser.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/Viz/VizParser.php b/src/Viz/VizParser.php index 9508676..d1b90f7 100644 --- a/src/Viz/VizParser.php +++ b/src/Viz/VizParser.php @@ -61,7 +61,6 @@ public function match($parsed, $mrz, $text) private function compare($mrz, $viz) { - $viz = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $viz); $viz = preg_replace('/([ ]|[-])/', '<', $viz); $viz = preg_replace("/\p{P}/u", '', $viz); @@ -69,7 +68,7 @@ private function compare($mrz, $viz) if (strlen($viz) == 0) { return 0; } - + $distance = levenshtein(strtolower($mrz), strtolower($viz)); return (strlen($viz) - $distance) / strlen($viz); From 57f7435c9d5359d19fd7b0e6cb1dfa102fd45910 Mon Sep 17 00:00:00 2001 From: HergenD Date: Mon, 26 Apr 2021 08:48:02 +0000 Subject: [PATCH 11/26] Apply fixes from StyleCI --- tests/Feature/MrzParserTest.php | 6 +++--- tests/Feature/VizParserTest.php | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/tests/Feature/MrzParserTest.php b/tests/Feature/MrzParserTest.php index 6c42692..310a465 100644 --- a/tests/Feature/MrzParserTest.php +++ b/tests/Feature/MrzParserTest.php @@ -23,9 +23,9 @@ class MrzParserTest extends TestCase 'optional_data_row_2' => null, 'last_name' => 'DE [ - 0 => 'WILLEKE', - 1 => 'LISELOTTE', - ], + 0 => 'WILLEKE', + 1 => 'LISELOTTE', + ], 'issuing_country_name' => 'Netherlands', 'nationality_name' => 'Netherlands', ]; diff --git a/tests/Feature/VizParserTest.php b/tests/Feature/VizParserTest.php index 0ce80bb..f276257 100644 --- a/tests/Feature/VizParserTest.php +++ b/tests/Feature/VizParserTest.php @@ -24,9 +24,9 @@ class VizParserTest extends TestCase 'optional_data_row_2' => null, 'last_name' => 'DE [ - 0 => 'WILLEKE', - 1 => 'LISELOTTE', - ], + 0 => 'WILLEKE', + 1 => 'LISELOTTE', + ], 'issuing_country_name' => 'Netherlands', 'nationality_name' => 'Netherlands', ]; From ff0ebe8e7354dfb929b3933838de74066e804997 Mon Sep 17 00:00:00 2001 From: Hergen Dillema Date: Mon, 26 Apr 2021 19:17:16 +0200 Subject: [PATCH 12/26] Namespacing change, tesseract example service added --- composer.json | 6 +-- config/identitydocuments.php | 10 +++-- src/Facades/IdentityDocuments.php | 2 +- src/Filters/MergeFilter.php | 2 +- src/Helpers/IdCheck.php | 2 +- src/IdentityDocument.php | 52 ++++++++++++++++-------- src/IdentityDocumentsServiceProvider.php | 2 +- src/IdentityImage.php | 19 +++++---- src/Interfaces/FaceDetection.php | 4 +- src/Interfaces/OCR.php | 4 +- src/Mrz/Mrz.php | 2 +- src/Mrz/MrzParser.php | 2 +- src/Mrz/MrzSearcher.php | 4 +- src/Responses/OcrResponse.php | 2 +- src/Services/Google.php | 10 ++--- src/Services/Tesseract.php | 25 ++++++++++++ src/Viz/Viz.php | 2 +- src/Viz/VizParser.php | 2 +- tests/Feature/MrzParserTest.php | 2 +- tests/Feature/MrzSearcherTest.php | 2 +- tests/Feature/VizParserTest.php | 2 +- 21 files changed, 103 insertions(+), 55 deletions(-) create mode 100644 src/Services/Tesseract.php diff --git a/composer.json b/composer.json index 2d0019b..67b5551 100644 --- a/composer.json +++ b/composer.json @@ -26,18 +26,18 @@ }, "autoload": { "psr-4": { - "werk365\\IdentityDocuments\\": "src/" + "Werk365\\IdentityDocuments\\": "src/" } }, "autoload-dev": { "psr-4": { - "werk365\\IdentityDocuments\\Tests\\": "tests" + "Werk365\\IdentityDocuments\\Tests\\": "tests" } }, "extra": { "laravel": { "providers": [ - "werk365\\IdentityDocuments\\IdentityDocumentsServiceProvider" + "Werk365\\IdentityDocuments\\IdentityDocumentsServiceProvider" ], "aliases": { "IdentityDocuments": "werk365\\IdentityDocuments\\Facades\\IdentityDocuments" diff --git a/config/identitydocuments.php b/config/identitydocuments.php index 492993d..c55c64c 100644 --- a/config/identitydocuments.php +++ b/config/identitydocuments.php @@ -1,8 +1,10 @@ false, - 'countries_convert_o_to_zero' => [ - 'NLD', - ], + 'ocrService' => Google::class, + 'faceDetectionService' => Google::class, + 'mergeImages' => false, // bool ]; diff --git a/src/Facades/IdentityDocuments.php b/src/Facades/IdentityDocuments.php index 6dcb6d8..26a9622 100644 --- a/src/Facades/IdentityDocuments.php +++ b/src/Facades/IdentityDocuments.php @@ -1,6 +1,6 @@ ocrService = config('identitydocuments.ocrService')??Google::class; + $this->faceDetectionService = config('identitydocuments.faceDetectionService')??Google::class; + if ($frontImage) { $this->addFrontImage($frontImage); } @@ -39,6 +46,9 @@ public function __construct($frontImage = null, $backImage = null) public static function all($frontImage = null, $backImage = null) { $id = new IdentityDocument($frontImage, $backImage); + if(config('identitydocuments.mergeImages')){ + $id->mergeBackAndFrontImages(); + } $mrz = $id->getMrz(); $parsed = $id->getParsedMrz(); $face = $id->getFace(); @@ -54,6 +64,7 @@ public static function all($frontImage = null, $backImage = null) $viz = $id->getViz(); return [ + 'type' => $id->type, 'mrz' => $mrz, 'parsed' => $parsed, 'viz' => $viz, @@ -63,8 +74,7 @@ public static function all($frontImage = null, $backImage = null) public function addFrontImage($image): IdentityDocument { - $image = $this->createImage($image); - $this->frontImage = new IdentityImage($image); + $this->frontImage = $this->createImage($image); $this->images[] = &$this->frontImage; return $this; @@ -72,24 +82,34 @@ public function addFrontImage($image): IdentityDocument public function addBackImage($image): IdentityDocument { - $image = $this->createImage($image); - $this->backImage = new IdentityImage($image); + $this->backImage = $this->createImage($image); $this->images[] = &$this->backImage; return $this; } - private function createImage($file): ?Image + private function createImage($file): IdentityImage { - if (! is_file($file)) { - return null; - } file_get_contents($file->getRealPath()); - return Img::make($file); + return new IdentityImage(Img::make($file), $this->ocrService, $this->faceDetectionService); } - private function mergeBackAndFrontImages() + public function setOcrService(string $service) + { + foreach($this->images as $image){ + $image->setOcrService($service); + } + } + + public function setFaceDetectionService(string $service) + { + foreach($this->images as $image){ + $image->setFaceDetectionService($service); + } + } + + public function mergeBackAndFrontImages() { if (! $this->frontImage || ! $this->backImage) { return false; @@ -112,7 +132,7 @@ private function mrz(): string break; } } - + $this->type = $this->searcher->type; return $this->mrz; } @@ -183,6 +203,6 @@ public function setMrz($mrz): IdentityDocument private function parseMrz(): void { - $this->parsedMrz = $this->parser->parse($this->getMrz(), $this->searcher->type); + $this->parsedMrz = $this->parser->parse($this->getMrz(), $this->type); } } diff --git a/src/IdentityDocumentsServiceProvider.php b/src/IdentityDocumentsServiceProvider.php index a020373..6f8d4ee 100644 --- a/src/IdentityDocumentsServiceProvider.php +++ b/src/IdentityDocumentsServiceProvider.php @@ -1,6 +1,6 @@ setOcrService(Google::class); - $this->setFaceDetectionService(Google::class); + $this->setOcrService($ocrService); + $this->setFaceDetectionService($faceDetectionService); $this->setImage($image); } @@ -51,7 +52,7 @@ public function setImage(Image $image) public function merge(IdentityImage $image): IdentityImage { - return new IdentityImage($this->image->filter(new MergeFilter($image->image))); + return new IdentityImage($this->image->filter(new MergeFilter($image->image)), $this->ocrService, $this->faceDetectionService); } public function ocr(): string diff --git a/src/Interfaces/FaceDetection.php b/src/Interfaces/FaceDetection.php index 6a7b251..44935d8 100644 --- a/src/Interfaces/FaceDetection.php +++ b/src/Interfaces/FaceDetection.php @@ -1,9 +1,9 @@ save($imagePath); + return new OcrResponse((new TesseractOCR($imagePath)) + ->run()); + } +} diff --git a/src/Viz/Viz.php b/src/Viz/Viz.php index 498c97d..07360ef 100644 --- a/src/Viz/Viz.php +++ b/src/Viz/Viz.php @@ -1,6 +1,6 @@ Date: Mon, 26 Apr 2021 21:03:41 +0200 Subject: [PATCH 13/26] Added service creation command and service stubs --- src/Commands/MakeService.php | 113 +++++++++++++++++++++++ src/IdentityDocumentsServiceProvider.php | 1 + stubs/FaceDetectionServiceStub.php | 16 ++++ stubs/OcrFdServiceStub.php | 24 +++++ stubs/OcrServiceStub.php | 16 ++++ 5 files changed, 170 insertions(+) create mode 100644 src/Commands/MakeService.php create mode 100644 stubs/FaceDetectionServiceStub.php create mode 100644 stubs/OcrFdServiceStub.php create mode 100644 stubs/OcrServiceStub.php diff --git a/src/Commands/MakeService.php b/src/Commands/MakeService.php new file mode 100644 index 0000000..aa0a2e9 --- /dev/null +++ b/src/Commands/MakeService.php @@ -0,0 +1,113 @@ +stubName; + } + + public function handle() + { + $type = strtolower($this->argument('type')); + switch($type){ + case 'ocr': + $this->stubName = 'OcrServiceStub.php'; + break; + case 'facedetection': + case 'fd': + $this->stubName = 'FaceDetectionServiceStub.php'; + case 'both': + $this->stubName = 'OcrFdServiceStub.php'; + } + // First we need to ensure that the given name is not a reserved word within the PHP + // language and that the class name will actually be valid. If it is not valid we + // can error now and prevent from polluting the filesystem using invalid files. + if ($this->isReservedName($this->getNameInput())) { + $this->error('The name "'.$this->getNameInput().'" is reserved by PHP.'); + + return false; + } + + $name = $this->qualifyClass($this->getNameInput()); + + $path = $this->getPath($name); + + // Next, We will check to see if the class already exists. If it does, we don't want + // to create the class and overwrite the user's code. So, we will bail out so the + // code is untouched. Otherwise, we will continue generating this class' files. + if ((! $this->hasOption('force') || + ! $this->option('force')) && + $this->alreadyExists($this->getNameInput())) { + $this->error($this->type.' already exists!'); + + return false; + } + + // Next, we will generate the path to the location where this class' file should get + // written. Then, we will build the class and make the proper replacements on the + // stub files so that it gets the correctly formatted namespace and class name. + $this->makeDirectory($path); + + $this->files->put($path, $this->sortImports($this->buildClass($name))); + + $this->info($this->type.' created successfully.'); + } + /** + * Get the default namespace for the class. + * + * @param string $rootNamespace + * + * @return string + */ + protected function getDefaultNamespace($rootNamespace) + { + return $rootNamespace . '/Services'; + } + + /** + * Get the console command arguments. + * + * @return array + */ + protected function getArguments() + { + return [ + ['name', InputArgument::REQUIRED, 'The name of the service'], + ['type', InputArgument::REQUIRED, 'The type of the service, OCR - FaceDetection (fd) or Both'], + ]; + } +} \ No newline at end of file diff --git a/src/IdentityDocumentsServiceProvider.php b/src/IdentityDocumentsServiceProvider.php index 6f8d4ee..6607220 100644 --- a/src/IdentityDocumentsServiceProvider.php +++ b/src/IdentityDocumentsServiceProvider.php @@ -13,6 +13,7 @@ class IdentityDocumentsServiceProvider extends ServiceProvider * @var bool */ protected $commands = [ + 'Werk365\IdentityDocuments\Commands\MakeService' ]; /** diff --git a/stubs/FaceDetectionServiceStub.php b/stubs/FaceDetectionServiceStub.php new file mode 100644 index 0000000..fee2c32 --- /dev/null +++ b/stubs/FaceDetectionServiceStub.php @@ -0,0 +1,16 @@ + Date: Mon, 26 Apr 2021 19:06:01 +0000 Subject: [PATCH 14/26] Apply fixes from StyleCI --- config/identitydocuments.php | 1 - src/Commands/MakeService.php | 13 +++++++------ src/IdentityDocument.php | 11 ++++++----- src/IdentityDocumentsServiceProvider.php | 2 +- src/IdentityImage.php | 2 -- src/Services/Tesseract.php | 7 +++---- stubs/FaceDetectionServiceStub.php | 4 ++-- stubs/OcrFdServiceStub.php | 8 ++++---- stubs/OcrServiceStub.php | 6 +++--- 9 files changed, 26 insertions(+), 28 deletions(-) diff --git a/config/identitydocuments.php b/config/identitydocuments.php index c55c64c..548ae19 100644 --- a/config/identitydocuments.php +++ b/config/identitydocuments.php @@ -1,7 +1,6 @@ Google::class, diff --git a/src/Commands/MakeService.php b/src/Commands/MakeService.php index aa0a2e9..fd51d02 100644 --- a/src/Commands/MakeService.php +++ b/src/Commands/MakeService.php @@ -30,20 +30,20 @@ class MakeService extends GeneratorCommand protected $stubName; - /** + /** * Get the stub file for the generator. * * @return string */ protected function getStub() { - return __DIR__.'/../../stubs/'. $this->stubName; + return __DIR__.'/../../stubs/'.$this->stubName; } public function handle() { $type = strtolower($this->argument('type')); - switch($type){ + switch ($type) { case 'ocr': $this->stubName = 'OcrServiceStub.php'; break; @@ -86,6 +86,7 @@ public function handle() $this->info($this->type.' created successfully.'); } + /** * Get the default namespace for the class. * @@ -95,10 +96,10 @@ public function handle() */ protected function getDefaultNamespace($rootNamespace) { - return $rootNamespace . '/Services'; + return $rootNamespace.'/Services'; } - /** + /** * Get the console command arguments. * * @return array @@ -110,4 +111,4 @@ protected function getArguments() ['type', InputArgument::REQUIRED, 'The type of the service, OCR - FaceDetection (fd) or Both'], ]; } -} \ No newline at end of file +} diff --git a/src/IdentityDocument.php b/src/IdentityDocument.php index 2861075..a50edca 100644 --- a/src/IdentityDocument.php +++ b/src/IdentityDocument.php @@ -28,8 +28,8 @@ class IdentityDocument public function __construct($frontImage = null, $backImage = null) { - $this->ocrService = config('identitydocuments.ocrService')??Google::class; - $this->faceDetectionService = config('identitydocuments.faceDetectionService')??Google::class; + $this->ocrService = config('identitydocuments.ocrService') ?? Google::class; + $this->faceDetectionService = config('identitydocuments.faceDetectionService') ?? Google::class; if ($frontImage) { $this->addFrontImage($frontImage); @@ -46,7 +46,7 @@ public function __construct($frontImage = null, $backImage = null) public static function all($frontImage = null, $backImage = null) { $id = new IdentityDocument($frontImage, $backImage); - if(config('identitydocuments.mergeImages')){ + if (config('identitydocuments.mergeImages')) { $id->mergeBackAndFrontImages(); } $mrz = $id->getMrz(); @@ -97,14 +97,14 @@ private function createImage($file): IdentityImage public function setOcrService(string $service) { - foreach($this->images as $image){ + foreach ($this->images as $image) { $image->setOcrService($service); } } public function setFaceDetectionService(string $service) { - foreach($this->images as $image){ + foreach ($this->images as $image) { $image->setFaceDetectionService($service); } } @@ -133,6 +133,7 @@ private function mrz(): string } } $this->type = $this->searcher->type; + return $this->mrz; } diff --git a/src/IdentityDocumentsServiceProvider.php b/src/IdentityDocumentsServiceProvider.php index 6607220..5ff73b1 100644 --- a/src/IdentityDocumentsServiceProvider.php +++ b/src/IdentityDocumentsServiceProvider.php @@ -13,7 +13,7 @@ class IdentityDocumentsServiceProvider extends ServiceProvider * @var bool */ protected $commands = [ - 'Werk365\IdentityDocuments\Commands\MakeService' + 'Werk365\IdentityDocuments\Commands\MakeService', ]; /** diff --git a/src/IdentityImage.php b/src/IdentityImage.php index c80d309..c7058a6 100644 --- a/src/IdentityImage.php +++ b/src/IdentityImage.php @@ -8,8 +8,6 @@ use Werk365\IdentityDocuments\Filters\MergeFilter; use Werk365\IdentityDocuments\Interfaces\FaceDetection; use Werk365\IdentityDocuments\Interfaces\OCR; -use Werk365\IdentityDocuments\Services\Google; -use Werk365\IdentityDocuments\Services\Tesseract; class IdentityImage { diff --git a/src/Services/Tesseract.php b/src/Services/Tesseract.php index 444dd4d..e0bff87 100644 --- a/src/Services/Tesseract.php +++ b/src/Services/Tesseract.php @@ -2,23 +2,22 @@ namespace Werk365\IdentityDocuments\Services; -use Google\Cloud\Vision\V1\ImageAnnotatorClient; use Intervention\Image\Image; +use thiagoalessio\TesseractOCR\TesseractOCR; use Werk365\IdentityDocuments\Interfaces\OCR; use Werk365\IdentityDocuments\Responses\OcrResponse; -use thiagoalessio\TesseractOCR\TesseractOCR; class Tesseract implements OCR { - public function __construct() { } public function ocr(Image $image): OcrResponse { - $imagePath = sys_get_temp_dir().md5(microtime().random_bytes(5)).".jpg"; + $imagePath = sys_get_temp_dir().md5(microtime().random_bytes(5)).'.jpg'; $image->save($imagePath); + return new OcrResponse((new TesseractOCR($imagePath)) ->run()); } diff --git a/stubs/FaceDetectionServiceStub.php b/stubs/FaceDetectionServiceStub.php index fee2c32..a17e54a 100644 --- a/stubs/FaceDetectionServiceStub.php +++ b/stubs/FaceDetectionServiceStub.php @@ -2,9 +2,9 @@ namespace DummyNamespace; -use Werk365\IdentityDocuments\Interfaces\FaceDetection; use Intervention\Image\Image; use Werk365\IdentityDocuments\IdentityImage; +use Werk365\IdentityDocuments\Interfaces\FaceDetection; class DummyClass implements FaceDetection { @@ -13,4 +13,4 @@ public function detect(IdentityImage $image): ?Image // TODO: Add face detection and return image of face return new Image(); } -} \ No newline at end of file +} diff --git a/stubs/OcrFdServiceStub.php b/stubs/OcrFdServiceStub.php index b0c07c2..db0e81d 100644 --- a/stubs/OcrFdServiceStub.php +++ b/stubs/OcrFdServiceStub.php @@ -2,18 +2,18 @@ namespace DummyNamespace; -use Werk365\IdentityDocuments\Interfaces\OCR; use Intervention\Image\Image; +use Werk365\IdentityDocuments\IdentityImage; use Werk365\IdentityDocuments\Interfaces\FaceDetection; +use Werk365\IdentityDocuments\Interfaces\OCR; use Werk365\IdentityDocuments\Responses\OcrResponse; -use Werk365\IdentityDocuments\IdentityImage; class DummyClass implements OCR, FaceDetection { public function ocr(Image $image): OcrResponse { // TODO: Add OCR and return text - return new OcrResponse("Response text"); + return new OcrResponse('Response text'); } public function detect(IdentityImage $image): ?Image @@ -21,4 +21,4 @@ public function detect(IdentityImage $image): ?Image // TODO: Add face detection and return image of face return new Image(); } -} \ No newline at end of file +} diff --git a/stubs/OcrServiceStub.php b/stubs/OcrServiceStub.php index 71dcb4e..5bf799b 100644 --- a/stubs/OcrServiceStub.php +++ b/stubs/OcrServiceStub.php @@ -2,8 +2,8 @@ namespace DummyNamespace; -use Werk365\IdentityDocuments\Interfaces\OCR; use Intervention\Image\Image; +use Werk365\IdentityDocuments\Interfaces\OCR; use Werk365\IdentityDocuments\Responses\OcrResponse; class DummyClass implements OCR @@ -11,6 +11,6 @@ class DummyClass implements OCR public function ocr(Image $image): OcrResponse { // TODO: Add OCR and return text - return new OcrResponse("Response text"); + return new OcrResponse('Response text'); } -} \ No newline at end of file +} From 2c93964d85bba1ec1b3c63766b998b3c66d4c4dc Mon Sep 17 00:00:00 2001 From: Hergen Dillema Date: Mon, 26 Apr 2021 21:56:19 +0200 Subject: [PATCH 15/26] Support detecting lastnames that include hyphens --- src/Viz/VizParser.php | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/Viz/VizParser.php b/src/Viz/VizParser.php index fbf881f..aa78aa8 100644 --- a/src/Viz/VizParser.php +++ b/src/Viz/VizParser.php @@ -32,6 +32,11 @@ public function match($parsed, $mrz, $text) array_push($lastName, $words[$wordKey + $count]); } } + foreach($lastName as $name){ + if(substr_count($name, '-')){ + array_pop($lastName); + } + } $lastName = implode('<', $lastName); } if ($this->compare($parsed['last_name'], $lastName) > $lastNameScore) { From 151a16b9a7f0ae588e2e653da0719e51e9eb501c Mon Sep 17 00:00:00 2001 From: HergenD Date: Mon, 26 Apr 2021 19:56:46 +0000 Subject: [PATCH 16/26] Apply fixes from StyleCI --- src/Viz/VizParser.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Viz/VizParser.php b/src/Viz/VizParser.php index aa78aa8..fb62681 100644 --- a/src/Viz/VizParser.php +++ b/src/Viz/VizParser.php @@ -32,8 +32,8 @@ public function match($parsed, $mrz, $text) array_push($lastName, $words[$wordKey + $count]); } } - foreach($lastName as $name){ - if(substr_count($name, '-')){ + foreach ($lastName as $name) { + if (substr_count($name, '-')) { array_pop($lastName); } } From 8304d82e87d7b8b9440f065a2f1103b019a91971 Mon Sep 17 00:00:00 2001 From: Hergen Dillema Date: Mon, 26 Apr 2021 22:01:59 +0200 Subject: [PATCH 17/26] Updated license --- license.md | 675 ++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 670 insertions(+), 5 deletions(-) diff --git a/license.md b/license.md index 3e5e46e..2feb88b 100644 --- a/license.md +++ b/license.md @@ -1,9 +1,674 @@ -# MIT +## GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 -Copyright + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + Preamble -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + The GNU General Public License is a free, copyleft license for +software and other kinds of works. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. \ No newline at end of file From 044014a8a4e84795938279b7765343447afa87e8 Mon Sep 17 00:00:00 2001 From: Hergen Dillema Date: Mon, 26 Apr 2021 23:03:52 +0200 Subject: [PATCH 18/26] Cleanup + first draft readme --- config/mrz_templates.php | 20 ----- readme.md | 157 +++++++++++++++++++++++++++++++------ src/Services/Tesseract.php | 24 ------ 3 files changed, 133 insertions(+), 68 deletions(-) delete mode 100644 config/mrz_templates.php delete mode 100644 src/Services/Tesseract.php diff --git a/config/mrz_templates.php b/config/mrz_templates.php deleted file mode 100644 index 39c7ded..0000000 --- a/config/mrz_templates.php +++ /dev/null @@ -1,20 +0,0 @@ - [ - 'keys' => ['P'], - 'check_digits' => [ - 53 => [[44, 9]], - 63 => [[57, 6]], - 71 => [[65, 6]], - 86 => [[72, 14]], - 87 => [[44, 10], [57, 7], [65, 22]], - ], - ], - 'TD1' => [ - - ], - 'VISA' => [ - - ], -]; diff --git a/readme.md b/readme.md index f680a78..f23e20a 100644 --- a/readme.md +++ b/readme.md @@ -1,87 +1,196 @@ + # Laravel Identity Documents + + [![Latest Version on Packagist][ico-version]][link-packagist] + [![Total Downloads][ico-downloads]][link-downloads] + [![StyleCI][ico-styleci]][link-styleci] + + For general questions and suggestions join gitter: + + [![Join the chat at https://gitter.im/werk365/identitydocuments](https://badges.gitter.im/werk365/identitydocuments.svg)](https://gitter.im/werk365/identitydocuments?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) -Package to parse Machine Readable Passports and other travel documents from image in Laravel. + -MRZ is parsed and validated by check numbers and returned. +Package that allows you to handle documents like passports and other documents that contain a Machine Readable Zone (MRZ). This package allows you to process images of documents to find the MRZ, parse the MRZ, parse the Visual Inspection Zone (VIZ) and also to find and return a crop of the passport picture (using face detection). + + + ## Installation + + Via Composer + + ``` bash + $ composer require werk365/identitydocuments + ``` -Publish config + + +Publish config (optional) + ``` bash -$ php artisan vendor:publish --provider="werk365\identitydocuments\IdentityDocumentsServiceProvider" + +$ php artisan vendor:publish --provider="Werk365\IdentityDocuments\IdentityDocumentsServiceProvider" + ``` -## Usage -This package uses Google's Vision API to do OCR, this requires you to make a service account and download the JSON keyfile. In order to use it in this project, store the key found in the file as an array in config/google_key.php like this: +## Configuration + +### Services + +The first important thing to know about the package is that you can use any OCR and or Face Detection API that you want. This package is not doing any of those itself. + +#### Google Vision Service + +Included with the package is a `Google` service class that will be loaded for both OCR and Face Detection by default. If you wish to use the Google service, no further configuration is required besides providing your credentials. To do this, make a service account and download the JSON key file. Then convert the JSON to a PHP array so it can be used as a normal Laravel config file. Your config file would have to be called `google_key.php`, be placed in the config folder and look like this: + +```php +return [ +"type" => "service_account", +"project_id" => "", +"private_key_id" => "", +"private_key" => "", +"client_email" => "", +"client_id" => "", +"auth_uri" => "", +"token_uri" => "", +"auth_provider_x509_cert_url" => "", +"client_x509_cert_url" => "", +]; +``` +#### Creating Custom Services +If you want to use any other API for OCR and/or Face Detection, you can make your own service, or take a look at our list of available services not included in the main package (WIP). + +Making a service is relatively easy, if you want to make a service that does the OCR, all you have to do is create a class that implements `Werk365\IdentityDocuments\Interfaces\OCR`. Similarly, there is also a `Werk365\IdentityDocuments\Interfaces\FaceDetection` interface. To make creating custom services even easier you can use the following command: +```bash +$ php artisan id:service +``` +Where `name` is the `ClassName` of the service you wish to create, and `type` is either `OCR`, `FaceDetection` or `Both`. This will create a new (empty) service for you in your `App\Services` namespace implementing the `OCR`, `FaceDetection` or both interfaces. + +#### Using Custom Services +The usage section will go over how to use functionality provided by this package, but if you wish to use the static `IdentityDocument:all()` method, you will have to publish the package config and set the service values there. Default values are: ```php +use Werk365\IdentityDocuments\Services\Google; + return [ - "type" => "service_account", - "project_id" => "", - "private_key_id" => "", - "private_key" => "", - "client_email" => "", - "client_id" => "", - "auth_uri" => "", - "token_uri" => "", - "auth_provider_x509_cert_url" => "", - "client_x509_cert_url" => "", +'ocrService' => Google::class, +'faceDetectionService' => Google::class, ]; ``` + + +## Usage -Call the parse method from anywhere passing a POST request. The method expects 'front_img' and 'back_img' to be the images of the travel documents, although you can use only one if a single image contains all required data. +Create a new Identity Document with a maximum of 2 images (optional) in this example we'll use a POST request that includes 2 images on our example controller. ```php -use werk365\IdentityDocuments\IdentityDocuments; +use Illuminate\Http\Request; +use Werk365\IdentityDocuments\IdentityDocument; -public function annotate(Request $request){ - return IdentityDocuments::parse($request); +class ExampleController { + public function id(Request $request){ + $document = new IdentityDocument($request->front, $request->back); + } } ``` -This returns the document type, MRZ, the parsed MRZ and all raw text found on the images. +There are now a few things we can do with this newly created Identity Document. First of all finding and returning the MRZ: +```php +$mrz = $document->getMrz(); +``` + +We can then also get a parsed version of the MRZ by using +```php +$parsed = $document->getParsedMrz(); +``` + +As the MRZ only allows for A-Z and 0-9 characters, anyone with accents in their name would not get a correct first or last name from the MRZ. To (attempt to) find the correct first and last name on the VIZ part of the document, use: +```php +$viz = $document->getViz(); +``` +This will return an array containing both the found first and last names as well as a confidence score. The confidence score is a number between 0 and 1 and shows the similarity between the MRZ and VIZ version of the name. Please not that results can differ based on your system's iconv() implementation. + +To get the passport picture from the document use: +```php +$face = $document->getFace() +``` +This returns an `Intervention\Image\Image` + + ## Change log + + Please see the [changelog](changelog.md) for more information on what has changed recently. + + ## Contributing + + Please see [contributing.md](contributing.md) for details and a todolist. + + ## Security + + If you discover any security related issues, please email instead of using the issue tracker. + + ## Credits -- [Hergen Dillema][link-author] -- [All Contributors][link-contributors] + + +- [Hergen Dillema][link-author] + +- [All Contributors][link-contributors] + + ## License + + . Please see the [license file](license.md) for more information. + + [ico-version]: https://img.shields.io/packagist/v/werk365/identitydocuments.svg?style=flat-square + [ico-downloads]: https://img.shields.io/packagist/dt/werk365/identitydocuments.svg?style=flat-square + [ico-travis]: https://img.shields.io/travis/werk365/identitydocuments/master.svg?style=flat-square + [ico-styleci]: https://styleci.io/repos/281089912/shield + + [link-packagist]: https://packagist.org/packages/werk365/identitydocuments + [link-downloads]: https://packagist.org/packages/werk365/identitydocuments + [link-travis]: https://travis-ci.org/werk365/identitydocuments + [link-styleci]: https://styleci.io/repos/281089912 + [link-author]: https://github.com/HergenD -[link-contributors]: ../../contributors + +[link-contributors]: ../../contributors \ No newline at end of file diff --git a/src/Services/Tesseract.php b/src/Services/Tesseract.php deleted file mode 100644 index e0bff87..0000000 --- a/src/Services/Tesseract.php +++ /dev/null @@ -1,24 +0,0 @@ -save($imagePath); - - return new OcrResponse((new TesseractOCR($imagePath)) - ->run()); - } -} From 6436f003bc417a4c3a5ebb6d0ebcdcb2284e3228 Mon Sep 17 00:00:00 2001 From: Hergen Dillema Date: Tue, 27 Apr 2021 14:04:54 +0200 Subject: [PATCH 19/26] readme update, small fixes --- readme.md | 87 ++++++++++++++++++++++++++++++++++++++-- src/IdentityDocument.php | 4 +- 2 files changed, 87 insertions(+), 4 deletions(-) diff --git a/readme.md b/readme.md index f23e20a..9b58ee1 100644 --- a/readme.md +++ b/readme.md @@ -94,7 +94,7 @@ return [ ## Usage - +#### Basic usage Create a new Identity Document with a maximum of 2 images (optional) in this example we'll use a POST request that includes 2 images on our example controller. ```php use Illuminate\Http\Request; @@ -121,7 +121,7 @@ As the MRZ only allows for A-Z and 0-9 characters, anyone with accents in their ```php $viz = $document->getViz(); ``` -This will return an array containing both the found first and last names as well as a confidence score. The confidence score is a number between 0 and 1 and shows the similarity between the MRZ and VIZ version of the name. Please not that results can differ based on your system's iconv() implementation. +This will return an array containing both the found first and last names as well as a confidence score. The confidence score is a number between 0 and 1 and shows the similarity between the MRZ and VIZ version of the name. Please not that results can differ based on your system's `iconv()` implementation. To get the passport picture from the document use: ```php @@ -129,7 +129,88 @@ $face = $document->getFace() ``` This returns an `Intervention\Image\Image` - +#### Get all of the above + If you wish to use all of these in a simplified way, you can also use the static `all()` method, which also expects up to two images as argument. For example: + ```php +use Illuminate\Http\Request; +use Werk365\IdentityDocuments\IdentityDocument; + +class ExampleController { + public function id(Request $request){ + $response = IdentityDocuments::all($request->front, $request->back); + return response()->json($response); + } +} +``` +The `all()` method returns an array that looks like this: +```php +[ + 'type' => 'string', // TD1, TD2, TD3, MRVA, MRVB + 'mrz' => 'string', // Full MRZ + 'parsed' => [], // Array containing parsed MRZ + 'viz' => [], // Array containing parsed VIZ + 'face' => 'string', // Base64 image string +] +``` +As you can see this includes all the above mentioned methods, plus the `$document->type` variable. The detected face will be returned as a base64 image string, with an image height of 200px. + +#### Merging images +There are a couple of methods that will configure how the Identity Document is handled. First of all there's the `mergeBackAndFrontImages()` method. This method can be used to reduce the amount of OCR API calls have to be made. Images will be stacked on top of each other when this method is used. Please note that this method would have to be used __before__ the `getMrz()` method. Example: +```php +use Illuminate\Http\Request; +use Werk365\IdentityDocuments\IdentityDocument; + +class ExampleController { + public function id(Request $request){ + $document = new IdentityDocument($request->front, $request->back); + $document->mergeBackAndFrontImages(); + $mrz = $document->getMrz(); + } +} +``` +If you wish to use the static `all()` method and merge the images, publish the package's config file and enable it in there. Note that changing the option in the config will __only__ apply to the `all()` method. Default config value: +```php + 'mergeImages' => false, // bool +``` + +#### Setting an OCR service +If you have made a custom OCR service or are using one different than the default Google service, you can use the `setOcrService()` method. For example let's say we've creating a new `TesseractService` using the methods described above, we can use it for OCR like this: +```php +use Illuminate\Http\Request; +use App\Services\TesseractService; +use Werk365\IdentityDocuments\IdentityDocument; + +class ExampleController { + public function id(Request $request){ + $document = new IdentityDocument($request->front, $request->back); + $document->setOcrService(TesseractService::class); + $mrz = $document->getMrz(); + } +} +``` +If you wish to use the `all()` method, publish the package's config and set the correct service class there. + +#### Setting a Face Detection Service +This can be done in a similar way as the OCR service, using the `setFaceDetectionService()` method. For example: +```php +use Illuminate\Http\Request; +use App\Services\AmazonFdService; +use Werk365\IdentityDocuments\IdentityDocument; + +class ExampleController { + public function id(Request $request){ + $document = new IdentityDocument($request->front, $request->back); + $document->setFaceDetectionService(AmazonFdService::class); + $mrz = $document->getFace(); + } +} +``` +If you wish to use the `all()` method, publish the package's config and set the correct service class there. + +#### Other methods +`addBackImage()` sets the back image of the `IdentityDocument`. +`addFrontImage()` sets the front image of the `IdentityDocument`. +`setMrz()` sets the `IdentityDcoument` MRZ, for if you just wish to use the parsing functionality. ## Change log diff --git a/src/IdentityDocument.php b/src/IdentityDocument.php index a50edca..2c12e06 100644 --- a/src/IdentityDocument.php +++ b/src/IdentityDocument.php @@ -97,6 +97,7 @@ private function createImage($file): IdentityImage public function setOcrService(string $service) { + $this->ocrService = $service; foreach ($this->images as $image) { $image->setOcrService($service); } @@ -104,6 +105,7 @@ public function setOcrService(string $service) public function setFaceDetectionService(string $service) { + $this->faceDetectionService = $service; foreach ($this->images as $image) { $image->setFaceDetectionService($service); } @@ -137,7 +139,7 @@ private function mrz(): string return $this->mrz; } - public function viz() + private function viz() { if (! $this->text) { return null; From 34df58aa0cfce25d76f0be19629e46e0ce1e3929 Mon Sep 17 00:00:00 2001 From: HergenD <32772820+HergenD@users.noreply.github.com> Date: Tue, 27 Apr 2021 14:06:36 +0200 Subject: [PATCH 20/26] Update readme.md --- readme.md | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) diff --git a/readme.md b/readme.md index 9b58ee1..3063673 100644 --- a/readme.md +++ b/readme.md @@ -4,17 +4,12 @@ [![Latest Version on Packagist][ico-version]][link-packagist] - [![Total Downloads][ico-downloads]][link-downloads] - [![StyleCI][ico-styleci]][link-styleci] For general questions and suggestions join gitter: - - - [![Join the chat at https://gitter.im/werk365/identitydocuments](https://badges.gitter.im/werk365/identitydocuments.svg)](https://gitter.im/werk365/identitydocuments?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) @@ -94,7 +89,7 @@ return [ ## Usage -#### Basic usage +### Basic usage Create a new Identity Document with a maximum of 2 images (optional) in this example we'll use a POST request that includes 2 images on our example controller. ```php use Illuminate\Http\Request; @@ -129,7 +124,7 @@ $face = $document->getFace() ``` This returns an `Intervention\Image\Image` -#### Get all of the above +### Get all of the above If you wish to use all of these in a simplified way, you can also use the static `all()` method, which also expects up to two images as argument. For example: ```php use Illuminate\Http\Request; @@ -154,7 +149,7 @@ The `all()` method returns an array that looks like this: ``` As you can see this includes all the above mentioned methods, plus the `$document->type` variable. The detected face will be returned as a base64 image string, with an image height of 200px. -#### Merging images +### Merging images There are a couple of methods that will configure how the Identity Document is handled. First of all there's the `mergeBackAndFrontImages()` method. This method can be used to reduce the amount of OCR API calls have to be made. Images will be stacked on top of each other when this method is used. Please note that this method would have to be used __before__ the `getMrz()` method. Example: ```php use Illuminate\Http\Request; @@ -173,7 +168,7 @@ If you wish to use the static `all()` method and merge the images, publish the p 'mergeImages' => false, // bool ``` -#### Setting an OCR service +### Setting an OCR service If you have made a custom OCR service or are using one different than the default Google service, you can use the `setOcrService()` method. For example let's say we've creating a new `TesseractService` using the methods described above, we can use it for OCR like this: ```php use Illuminate\Http\Request; @@ -190,7 +185,7 @@ class ExampleController { ``` If you wish to use the `all()` method, publish the package's config and set the correct service class there. -#### Setting a Face Detection Service +### Setting a Face Detection Service This can be done in a similar way as the OCR service, using the `setFaceDetectionService()` method. For example: ```php use Illuminate\Http\Request; @@ -207,7 +202,7 @@ class ExampleController { ``` If you wish to use the `all()` method, publish the package's config and set the correct service class there. -#### Other methods +### Other methods `addBackImage()` sets the back image of the `IdentityDocument`. `addFrontImage()` sets the front image of the `IdentityDocument`. `setMrz()` sets the `IdentityDcoument` MRZ, for if you just wish to use the parsing functionality. @@ -274,4 +269,4 @@ If you discover any security related issues, please email Date: Tue, 27 Apr 2021 14:08:47 +0200 Subject: [PATCH 21/26] Update readme.md --- readme.md | 21 --------------------- 1 file changed, 21 deletions(-) diff --git a/readme.md b/readme.md index 3063673..b7bcd34 100644 --- a/readme.md +++ b/readme.md @@ -75,17 +75,6 @@ Making a service is relatively easy, if you want to make a service that does the $ php artisan id:service ``` Where `name` is the `ClassName` of the service you wish to create, and `type` is either `OCR`, `FaceDetection` or `Both`. This will create a new (empty) service for you in your `App\Services` namespace implementing the `OCR`, `FaceDetection` or both interfaces. - -#### Using Custom Services -The usage section will go over how to use functionality provided by this package, but if you wish to use the static `IdentityDocument:all()` method, you will have to publish the package config and set the service values there. Default values are: -```php -use Werk365\IdentityDocuments\Services\Google; - -return [ -'ocrService' => Google::class, -'faceDetectionService' => Google::class, -]; -``` ## Usage @@ -209,31 +198,23 @@ If you wish to use the `all()` method, publish the package's config and set the ## Change log - - Please see the [changelog](changelog.md) for more information on what has changed recently. - ## Contributing - - Please see [contributing.md](contributing.md) for details and a todolist. ## Security - - If you discover any security related issues, please email instead of using the issue tracker. ## Credits - - [Hergen Dillema][link-author] @@ -243,8 +224,6 @@ If you discover any security related issues, please email Date: Tue, 27 Apr 2021 14:10:24 +0200 Subject: [PATCH 22/26] Update contributing.md --- contributing.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/contributing.md b/contributing.md index ede9840..5dd5c7b 100644 --- a/contributing.md +++ b/contributing.md @@ -6,8 +6,7 @@ Contributions are accepted via Pull Requests on [Github](https://github.com/werk # Things you could do If you want to contribute but do not know where to start, this list provides some starting points. -- Set up TravisCI, StyleCI, ScrutinizerCI -- Write a comprehensive ReadMe +- Update this file ## Pull Requests From 9578a99fd6b60789492119997b0420881eced7e4 Mon Sep 17 00:00:00 2001 From: HergenD <32772820+HergenD@users.noreply.github.com> Date: Tue, 27 Apr 2021 20:16:44 +0200 Subject: [PATCH 23/26] Update readme.md --- readme.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/readme.md b/readme.md index b7bcd34..a1b89c3 100644 --- a/readme.md +++ b/readme.md @@ -14,7 +14,11 @@ For general questions and suggestions join gitter: -Package that allows you to handle documents like passports and other documents that contain a Machine Readable Zone (MRZ). This package allows you to process images of documents to find the MRZ, parse the MRZ, parse the Visual Inspection Zone (VIZ) and also to find and return a crop of the passport picture (using face detection). +Package that allows you to handle documents like passports and other documents that contain a Machine Readable Zone (MRZ). + +This package allows you to process images of documents to find the MRZ, parse the MRZ, parse the Visual Inspection Zone (VIZ) and also to find and return a crop of the passport picture (using face detection). + +> Version 2.x is a complete rewrite of the package with a new MRZ detection algorithm and is not compatible with version 1.x @@ -152,6 +156,8 @@ class ExampleController { } } ``` +> Please note that merging images might cause high memory usage, depending on the size of your images + If you wish to use the static `all()` method and merge the images, publish the package's config file and enable it in there. Note that changing the option in the config will __only__ apply to the `all()` method. Default config value: ```php 'mergeImages' => false, // bool From 64909d1e1074ea64b8bff09e88462c60093671ac Mon Sep 17 00:00:00 2001 From: HergenD <32772820+HergenD@users.noreply.github.com> Date: Tue, 27 Apr 2021 20:18:58 +0200 Subject: [PATCH 24/26] Update readme.md --- readme.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/readme.md b/readme.md index a1b89c3..108ac05 100644 --- a/readme.md +++ b/readme.md @@ -10,6 +10,7 @@ For general questions and suggestions join gitter: + [![Join the chat at https://gitter.im/werk365/identitydocuments](https://badges.gitter.im/werk365/identitydocuments.svg)](https://gitter.im/werk365/identitydocuments?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) @@ -18,7 +19,7 @@ Package that allows you to handle documents like passports and other documents t This package allows you to process images of documents to find the MRZ, parse the MRZ, parse the Visual Inspection Zone (VIZ) and also to find and return a crop of the passport picture (using face detection). -> Version 2.x is a complete rewrite of the package with a new MRZ detection algorithm and is not compatible with version 1.x +> ⚠️ Version 2.x is a complete rewrite of the package with a new MRZ detection algorithm and is not compatible with version 1.x @@ -156,7 +157,7 @@ class ExampleController { } } ``` -> Please note that merging images might cause high memory usage, depending on the size of your images +> ⚠️ Please note that merging images might cause high memory usage, depending on the size of your images If you wish to use the static `all()` method and merge the images, publish the package's config file and enable it in there. Note that changing the option in the config will __only__ apply to the `all()` method. Default config value: ```php From e6adcfd5f89490c0319fb8da71a322721def58c8 Mon Sep 17 00:00:00 2001 From: HergenD <32772820+HergenD@users.noreply.github.com> Date: Tue, 27 Apr 2021 20:21:52 +0200 Subject: [PATCH 25/26] Update composer.json --- composer.json | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/composer.json b/composer.json index 67b5551..70fa34c 100644 --- a/composer.json +++ b/composer.json @@ -1,8 +1,8 @@ { "name": "werk365/identitydocuments", "description": "Package to parse identity documents like passports", - "license": "MIT", - "version": "2.0.0-beta", + "license": "GPL-3.0-or-later", + "version": "2.0.0", "authors": [ { "name": "Hergen Dillema", @@ -11,12 +11,11 @@ } ], "homepage": "https://github.com/werk365/identitydocuments", - "keywords": ["Laravel", "IdentityDocuments"], + "keywords": ["Laravel", "IdentityDocuments", "MRZ", "Passport"], "require": { "google/cloud-vision": "^1.3", "intervention/image": "^2.5", - "illuminate/support": "~5|~6|~7|~8", - "ext-gd": "*" + "illuminate/support": "~5|~6|~7|~8" }, "require-dev": { "phpunit/phpunit": "^8.0", From 519f68f45204053f9915e279aa11c4d2f612da9e Mon Sep 17 00:00:00 2001 From: Hergen Dillema Date: Tue, 27 Apr 2021 20:26:40 +0200 Subject: [PATCH 26/26] Revert "Updated license" This reverts commit 8304d82e87d7b8b9440f065a2f1103b019a91971. --- license.md | 675 +---------------------------------------------------- 1 file changed, 5 insertions(+), 670 deletions(-) diff --git a/license.md b/license.md index 2feb88b..3e5e46e 100644 --- a/license.md +++ b/license.md @@ -1,674 +1,9 @@ -## GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 +# MIT - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. +Copyright - Preamble +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - The GNU General Public License is a free, copyleft license for -software and other kinds of works. +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. \ No newline at end of file +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.