568 lines
19 KiB
PHP
568 lines
19 KiB
PHP
<?php
|
||
|
||
namespace Modules\EcommerceFinance\Services;
|
||
|
||
use RuntimeException;
|
||
use Symfony\Component\Process\Process;
|
||
use Throwable;
|
||
use ZipArchive;
|
||
|
||
class DingInvoiceFileRecognizer
|
||
{
|
||
public function __construct(
|
||
private readonly DingInvoiceTextParser $textParser,
|
||
private readonly DingInvoiceVisionClient $vision,
|
||
) {}
|
||
|
||
/**
|
||
* @return array{invoices:list<array<string,mixed>>,errors:list<string>,provider:string}
|
||
*/
|
||
public function recognize(string $path, string $fileName = ''): array
|
||
{
|
||
if (! is_file($path)) {
|
||
return ['invoices' => [], 'errors' => ['文件不存在'], 'provider' => ''];
|
||
}
|
||
|
||
$extension = strtolower(pathinfo($fileName !== '' ? $fileName : $path, PATHINFO_EXTENSION));
|
||
$tempDir = storage_path('app/temp/invoice-ocr/' . bin2hex(random_bytes(8)));
|
||
if (! is_dir($tempDir) && ! mkdir($tempDir, 0755, true) && ! is_dir($tempDir)) {
|
||
throw new RuntimeException('无法创建发票临时目录。');
|
||
}
|
||
|
||
try {
|
||
return match ($extension) {
|
||
'pdf' => $this->recognizePdf($path, $tempDir),
|
||
'jpg', 'jpeg', 'png', 'webp', 'bmp' => $this->recognizeImage($path),
|
||
'xlsx' => $this->recognizeXlsx($path, $tempDir),
|
||
'xls' => $this->recognizeLegacyXls($path, $tempDir),
|
||
'zip' => $this->recognizeZip($path, $tempDir),
|
||
'rar', '7z' => $this->recognizeArchive($path, $tempDir, $extension),
|
||
default => [
|
||
'invoices' => [],
|
||
'errors' => ['暂不支持识别 .' . ($extension ?: '未知') . ' 附件'],
|
||
'provider' => '',
|
||
],
|
||
};
|
||
} finally {
|
||
$this->removeDirectory($tempDir);
|
||
}
|
||
}
|
||
|
||
public function ocrConfigured(): bool
|
||
{
|
||
return $this->vision->configured()
|
||
|| is_executable((string) config(
|
||
'ding_invoice_data.tesseract_binary',
|
||
'/usr/bin/tesseract',
|
||
));
|
||
}
|
||
|
||
/** @return array{invoices:list<array<string,mixed>>,errors:list<string>,provider:string} */
|
||
private function recognizePdf(string $path, string $tempDir): array
|
||
{
|
||
$errors = [];
|
||
$text = $this->pdfText($path);
|
||
if ($text !== '') {
|
||
$parsed = $this->textParser->parse($text);
|
||
if ($parsed !== null) {
|
||
return ['invoices' => [$parsed], 'errors' => [], 'provider' => 'pdf_text'];
|
||
}
|
||
}
|
||
|
||
if (! $this->ocrConfigured()) {
|
||
return [
|
||
'invoices' => [],
|
||
'errors' => ['PDF 未提取到结构化发票,且未配置 OCR。'],
|
||
'provider' => 'pdf_text',
|
||
];
|
||
}
|
||
|
||
$invoices = [];
|
||
$errors = [];
|
||
$providers = [];
|
||
for ($page = 1; $page <= max(1, (int) config('ding_invoice_data.max_pdf_pages', 5)); $page++) {
|
||
$prefix = $tempDir . '/page-' . $page;
|
||
if (! $this->renderPdfPage($path, $prefix, $page)) {
|
||
break;
|
||
}
|
||
$imagePath = $prefix . '.png';
|
||
try {
|
||
$result = $this->recognizeImage($imagePath);
|
||
array_push($invoices, ...$result['invoices']);
|
||
array_push($errors, ...array_map(
|
||
static fn (string $error): string => 'PDF 第 ' . $page . ' 页:' . $error,
|
||
$result['errors'],
|
||
));
|
||
if ($result['provider'] !== '') {
|
||
$providers[] = $result['provider'];
|
||
}
|
||
} catch (Throwable $exception) {
|
||
$errors[] = 'PDF 第 ' . $page . ' 页:' . $exception->getMessage();
|
||
}
|
||
}
|
||
|
||
return [
|
||
'invoices' => $invoices,
|
||
'errors' => $errors,
|
||
'provider' => implode('+', array_values(array_unique($providers))),
|
||
];
|
||
}
|
||
|
||
/** @return array{invoices:list<array<string,mixed>>,errors:list<string>,provider:string} */
|
||
private function recognizeImage(string $path): array
|
||
{
|
||
$errors = [];
|
||
$localOcrAvailable = is_executable((string) config(
|
||
'ding_invoice_data.tesseract_binary',
|
||
'/usr/bin/tesseract',
|
||
));
|
||
$ocrAttempted = $this->vision->configured() || $localOcrAvailable;
|
||
if ($this->vision->configured()) {
|
||
try {
|
||
$mime = mime_content_type($path) ?: 'image/jpeg';
|
||
$invoice = $this->vision->recognize(
|
||
(string) file_get_contents($path),
|
||
$mime,
|
||
);
|
||
if ($invoice !== null) {
|
||
return [
|
||
'invoices' => [$invoice],
|
||
'errors' => [],
|
||
'provider' => 'vision',
|
||
];
|
||
}
|
||
} catch (Throwable $exception) {
|
||
$errors[] = '图片 OCR API:' . $exception->getMessage();
|
||
}
|
||
}
|
||
|
||
try {
|
||
$invoice = $this->recognizeLocalImage($path);
|
||
if ($invoice !== null) {
|
||
return [
|
||
'invoices' => [$invoice],
|
||
'errors' => $errors,
|
||
'provider' => 'local_ocr',
|
||
];
|
||
}
|
||
} catch (Throwable $exception) {
|
||
$errors[] = '本地 OCR:' . $exception->getMessage();
|
||
}
|
||
|
||
return [
|
||
'invoices' => [],
|
||
'errors' => $ocrAttempted
|
||
? $errors
|
||
: ['图片发票需要配置 OCR API 或本地 Tesseract。'],
|
||
'provider' => '',
|
||
];
|
||
}
|
||
|
||
/** @return array<string,mixed>|null */
|
||
private function recognizeLocalImage(string $path): ?array
|
||
{
|
||
$binary = (string) config(
|
||
'ding_invoice_data.tesseract_binary',
|
||
'/usr/bin/tesseract',
|
||
);
|
||
if (! is_executable($binary)) {
|
||
return null;
|
||
}
|
||
|
||
$best = null;
|
||
$bestScore = -1;
|
||
foreach ([0, 90, 180, 270] as $degrees) {
|
||
$imagePath = $degrees === 0
|
||
? $path
|
||
: $this->rotateImage($path, $degrees);
|
||
if ($imagePath === null) {
|
||
continue;
|
||
}
|
||
try {
|
||
$text = $this->tesseractText($binary, $imagePath);
|
||
$invoice = $this->textParser->parse($text);
|
||
if ($invoice === null) {
|
||
continue;
|
||
}
|
||
$score = ($invoice['invoice_number'] !== '' ? 30 : 0)
|
||
+ ((float) $invoice['invoice_total'] > 0 ? 30 : 0)
|
||
+ ($invoice['invoice_date'] !== null ? 10 : 0)
|
||
+ ($invoice['seller_name'] !== '' ? 5 : 0)
|
||
+ min(20, substr_count((string) $invoice['item_name'], "\n") * 2);
|
||
if ($score > $bestScore) {
|
||
$best = $invoice;
|
||
$bestScore = $score;
|
||
}
|
||
} finally {
|
||
if ($degrees !== 0 && is_file($imagePath)) {
|
||
@unlink($imagePath);
|
||
}
|
||
}
|
||
if (($best['invoice_number'] ?? '') !== ''
|
||
&& (float) ($best['invoice_total'] ?? 0) > 0) {
|
||
break;
|
||
}
|
||
}
|
||
|
||
return $best;
|
||
}
|
||
|
||
private function tesseractText(string $binary, string $path): string
|
||
{
|
||
$languages = trim((string) config(
|
||
'ding_invoice_data.tesseract_languages',
|
||
'chi_sim+eng',
|
||
)) ?: 'chi_sim+eng';
|
||
$process = new Process([
|
||
$binary,
|
||
$path,
|
||
'stdout',
|
||
'-l',
|
||
$languages,
|
||
'--psm',
|
||
'3',
|
||
]);
|
||
$process->setTimeout(90);
|
||
$process->run();
|
||
if (! $process->isSuccessful()) {
|
||
throw new RuntimeException(
|
||
trim($process->getErrorOutput()) ?: 'Tesseract OCR 执行失败。',
|
||
);
|
||
}
|
||
|
||
return $process->getOutput();
|
||
}
|
||
|
||
private function rotateImage(string $path, int $degrees): ?string
|
||
{
|
||
$bytes = @file_get_contents($path);
|
||
if ($bytes === false || $bytes === '') {
|
||
return null;
|
||
}
|
||
$image = @imagecreatefromstring($bytes);
|
||
if ($image === false) {
|
||
return null;
|
||
}
|
||
$background = imagecolorallocate($image, 255, 255, 255);
|
||
$rotated = imagerotate($image, -$degrees, $background);
|
||
imagedestroy($image);
|
||
if ($rotated === false) {
|
||
return null;
|
||
}
|
||
$target = $path . '.rot' . $degrees . '.png';
|
||
$saved = imagepng($rotated, $target);
|
||
imagedestroy($rotated);
|
||
|
||
return $saved ? $target : null;
|
||
}
|
||
|
||
/** @return array{invoices:list<array<string,mixed>>,errors:list<string>,provider:string} */
|
||
private function recognizeLegacyXls(string $path, string $tempDir): array
|
||
{
|
||
$binary = (string) config(
|
||
'ding_invoice_data.libreoffice_binary',
|
||
'/usr/bin/libreoffice',
|
||
);
|
||
if (! is_executable($binary)) {
|
||
return [
|
||
'invoices' => [],
|
||
'errors' => ['XLS 附件需要服务器安装 LibreOffice 后转换识别。'],
|
||
'provider' => '',
|
||
];
|
||
}
|
||
$outputDir = $tempDir . '/xls-pdf';
|
||
if (! is_dir($outputDir) && ! mkdir($outputDir, 0755, true) && ! is_dir($outputDir)) {
|
||
throw new RuntimeException('无法创建 XLS 转换临时目录。');
|
||
}
|
||
$process = new Process([
|
||
$binary,
|
||
'--headless',
|
||
'--convert-to',
|
||
'pdf',
|
||
'--outdir',
|
||
$outputDir,
|
||
$path,
|
||
]);
|
||
$process->setTimeout(180);
|
||
$process->run();
|
||
$pdf = $outputDir . '/' . pathinfo($path, PATHINFO_FILENAME) . '.pdf';
|
||
if (! $process->isSuccessful() || ! is_file($pdf)) {
|
||
return [
|
||
'invoices' => [],
|
||
'errors' => [
|
||
trim($process->getErrorOutput())
|
||
?: 'XLS 转换为 PDF 失败。',
|
||
],
|
||
'provider' => 'libreoffice',
|
||
];
|
||
}
|
||
|
||
$result = $this->recognizePdf($pdf, $outputDir);
|
||
$result['provider'] = $this->joinProviders([
|
||
'libreoffice',
|
||
$result['provider'],
|
||
]);
|
||
|
||
return $result;
|
||
}
|
||
|
||
/** @return array{invoices:list<array<string,mixed>>,errors:list<string>,provider:string} */
|
||
private function recognizeArchive(
|
||
string $path,
|
||
string $tempDir,
|
||
string $extension,
|
||
): array {
|
||
$sevenZip = (string) config(
|
||
'ding_invoice_data.seven_zip_binary',
|
||
'/usr/bin/7z',
|
||
);
|
||
$unar = (string) config(
|
||
'ding_invoice_data.unar_binary',
|
||
'/usr/bin/unar',
|
||
);
|
||
$useUnar = $extension === 'rar' && is_executable($unar);
|
||
$binary = $useUnar ? $unar : $sevenZip;
|
||
if (! is_executable($binary)) {
|
||
return [
|
||
'invoices' => [],
|
||
'errors' => ['压缩附件需要服务器安装对应的解压工具。'],
|
||
'provider' => $extension,
|
||
];
|
||
}
|
||
$outputDir = $tempDir . '/archive-' . bin2hex(random_bytes(4));
|
||
if (! mkdir($outputDir, 0755, true) && ! is_dir($outputDir)) {
|
||
throw new RuntimeException('无法创建压缩附件临时目录。');
|
||
}
|
||
$process = new Process($useUnar
|
||
? [$binary, '-q', '-f', '-o', $outputDir, $path]
|
||
: [$binary, 'x', '-y', '-bd', '-o' . $outputDir, $path]);
|
||
$process->setTimeout(120);
|
||
$process->run();
|
||
$extractedFiles = 0;
|
||
if (is_dir($outputDir)) {
|
||
$iterator = new \RecursiveIteratorIterator(
|
||
new \RecursiveDirectoryIterator($outputDir, \FilesystemIterator::SKIP_DOTS),
|
||
);
|
||
foreach ($iterator as $item) {
|
||
if ($item->isFile()) {
|
||
$extractedFiles++;
|
||
}
|
||
}
|
||
}
|
||
if ($extractedFiles === 0) {
|
||
return [
|
||
'invoices' => [],
|
||
'errors' => [
|
||
trim($process->getErrorOutput()) ?: '压缩附件解压失败。',
|
||
],
|
||
'provider' => $extension,
|
||
];
|
||
}
|
||
|
||
$invoices = [];
|
||
$errors = [];
|
||
if (! $process->isSuccessful()) {
|
||
$errors[] = trim($process->getErrorOutput())
|
||
?: '压缩附件部分文件解压失败。';
|
||
}
|
||
$providers = [$extension];
|
||
$files = 0;
|
||
$iterator = new \RecursiveIteratorIterator(
|
||
new \RecursiveDirectoryIterator($outputDir, \FilesystemIterator::SKIP_DOTS),
|
||
);
|
||
foreach ($iterator as $item) {
|
||
if (! $item->isFile()) {
|
||
continue;
|
||
}
|
||
$files++;
|
||
if ($files > max(1, (int) config('ding_invoice_data.max_archive_files', 100))) {
|
||
$errors[] = '压缩附件文件数量超过限制。';
|
||
break;
|
||
}
|
||
$extension = strtolower($item->getExtension());
|
||
if (! in_array($extension, [
|
||
'pdf',
|
||
'png',
|
||
'jpg',
|
||
'jpeg',
|
||
'webp',
|
||
'bmp',
|
||
'xlsx',
|
||
'xls',
|
||
], true)) {
|
||
continue;
|
||
}
|
||
try {
|
||
$result = $this->recognize($item->getPathname(), $item->getFilename());
|
||
array_push($invoices, ...$result['invoices']);
|
||
array_push($errors, ...array_map(
|
||
static fn (string $error): string =>
|
||
$item->getFilename() . ':' . $error,
|
||
$result['errors'],
|
||
));
|
||
$providers[] = $result['provider'];
|
||
} catch (Throwable $exception) {
|
||
$errors[] = $item->getFilename() . ':' . $exception->getMessage();
|
||
}
|
||
}
|
||
|
||
return [
|
||
'invoices' => $invoices,
|
||
'errors' => $errors,
|
||
'provider' => $this->joinProviders($providers),
|
||
];
|
||
}
|
||
|
||
/** @param list<string> $providers */
|
||
private function joinProviders(array $providers): string
|
||
{
|
||
return implode('+', array_values(array_unique(array_filter(
|
||
array_map('trim', $providers),
|
||
))));
|
||
}
|
||
|
||
/** @return array{invoices:list<array<string,mixed>>,errors:list<string>,provider:string} */
|
||
private function recognizeXlsx(string $path, string $tempDir): array
|
||
{
|
||
$zip = new ZipArchive();
|
||
if ($zip->open($path) !== true) {
|
||
return ['invoices' => [], 'errors' => ['无法打开 Excel 附件'], 'provider' => ''];
|
||
}
|
||
|
||
$invoices = [];
|
||
$errors = [];
|
||
try {
|
||
for ($index = 0; $index < $zip->numFiles; $index++) {
|
||
$name = (string) $zip->getNameIndex($index);
|
||
if (! str_starts_with($name, 'xl/media/')) {
|
||
continue;
|
||
}
|
||
$extension = strtolower(pathinfo($name, PATHINFO_EXTENSION));
|
||
if (! in_array($extension, ['png', 'jpg', 'jpeg', 'webp', 'bmp'], true)) {
|
||
continue;
|
||
}
|
||
$target = $tempDir . '/' . basename($name);
|
||
$stream = $zip->getStream($name);
|
||
if ($stream === false) {
|
||
continue;
|
||
}
|
||
file_put_contents($target, stream_get_contents($stream));
|
||
fclose($stream);
|
||
|
||
try {
|
||
$result = $this->recognizeImage($target);
|
||
array_push($invoices, ...$result['invoices']);
|
||
array_push($errors, ...$result['errors']);
|
||
} catch (Throwable $exception) {
|
||
$errors[] = $name . ':' . $exception->getMessage();
|
||
}
|
||
}
|
||
} finally {
|
||
$zip->close();
|
||
}
|
||
|
||
return [
|
||
'invoices' => $invoices,
|
||
'errors' => $errors,
|
||
'provider' => 'xlsx_media',
|
||
];
|
||
}
|
||
|
||
/** @return array{invoices:list<array<string,mixed>>,errors:list<string>,provider:string} */
|
||
private function recognizeZip(string $path, string $tempDir): array
|
||
{
|
||
$zip = new ZipArchive();
|
||
if ($zip->open($path) !== true) {
|
||
return ['invoices' => [], 'errors' => ['无法打开 ZIP 附件'], 'provider' => ''];
|
||
}
|
||
|
||
$invoices = [];
|
||
$errors = [];
|
||
try {
|
||
for ($index = 0; $index < $zip->numFiles; $index++) {
|
||
$name = (string) $zip->getNameIndex($index);
|
||
$extension = strtolower(pathinfo($name, PATHINFO_EXTENSION));
|
||
if (! in_array($extension, ['pdf', 'png', 'jpg', 'jpeg', 'webp', 'bmp'], true)) {
|
||
continue;
|
||
}
|
||
$target = $tempDir . '/' . $index . '-' . basename($name);
|
||
$stream = $zip->getStream($name);
|
||
if ($stream === false) {
|
||
continue;
|
||
}
|
||
file_put_contents($target, stream_get_contents($stream));
|
||
fclose($stream);
|
||
|
||
try {
|
||
$result = $this->recognize($target, $name);
|
||
array_push($invoices, ...$result['invoices']);
|
||
array_push($errors, ...$result['errors']);
|
||
} catch (Throwable $exception) {
|
||
$errors[] = $name . ':' . $exception->getMessage();
|
||
}
|
||
}
|
||
} finally {
|
||
$zip->close();
|
||
}
|
||
|
||
return ['invoices' => $invoices, 'errors' => $errors, 'provider' => 'zip'];
|
||
}
|
||
|
||
private function pdfText(string $path): string
|
||
{
|
||
$binary = (string) config('ding_invoice_data.pdftotext_binary', '/usr/bin/pdftotext');
|
||
if (! is_executable($binary)) {
|
||
return '';
|
||
}
|
||
$process = new Process([$binary, '-layout', $path, '-']);
|
||
$process->setTimeout(45);
|
||
$process->run();
|
||
|
||
return $process->isSuccessful() ? $process->getOutput() : '';
|
||
}
|
||
|
||
private function renderPdfPage(string $path, string $prefix, int $page): bool
|
||
{
|
||
$binary = (string) config('ding_invoice_data.pdftoppm_binary', '/usr/bin/pdftoppm');
|
||
if (! is_executable($binary)) {
|
||
return false;
|
||
}
|
||
$process = new Process([
|
||
$binary,
|
||
'-png',
|
||
'-r',
|
||
'150',
|
||
'-f',
|
||
(string) $page,
|
||
'-l',
|
||
(string) $page,
|
||
'-singlefile',
|
||
$path,
|
||
$prefix,
|
||
]);
|
||
$process->setTimeout(60);
|
||
$process->run();
|
||
|
||
return $process->isSuccessful() && is_file($prefix . '.png');
|
||
}
|
||
|
||
private function removeDirectory(string $directory): void
|
||
{
|
||
if (! is_dir($directory)) {
|
||
return;
|
||
}
|
||
$iterator = new \RecursiveIteratorIterator(
|
||
new \RecursiveDirectoryIterator($directory, \FilesystemIterator::SKIP_DOTS),
|
||
\RecursiveIteratorIterator::CHILD_FIRST,
|
||
);
|
||
foreach ($iterator as $item) {
|
||
if ($item->isDir()) {
|
||
@rmdir($item->getPathname());
|
||
} else {
|
||
@unlink($item->getPathname());
|
||
}
|
||
}
|
||
@rmdir($directory);
|
||
}
|
||
}
|