258 lines
8.8 KiB
PHP
258 lines
8.8 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),
|
||
'zip' => $this->recognizeZip($path, $tempDir),
|
||
default => [
|
||
'invoices' => [],
|
||
'errors' => ['暂不支持识别 .' . ($extension ?: '未知') . ' 附件'],
|
||
'provider' => '',
|
||
],
|
||
};
|
||
} finally {
|
||
$this->removeDirectory($tempDir);
|
||
}
|
||
}
|
||
|
||
/** @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->vision->configured()) {
|
||
return [
|
||
'invoices' => [],
|
||
'errors' => ['PDF 未提取到结构化发票,且未配置 OCR API。'],
|
||
'provider' => 'pdf_text',
|
||
];
|
||
}
|
||
|
||
$invoices = [];
|
||
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 {
|
||
$invoice = $this->vision->recognize(
|
||
(string) file_get_contents($imagePath),
|
||
'image/png',
|
||
);
|
||
if ($invoice !== null) {
|
||
$invoices[] = $invoice;
|
||
}
|
||
} catch (Throwable $exception) {
|
||
$errors[] = 'PDF 第 ' . $page . ' 页:' . $exception->getMessage();
|
||
}
|
||
}
|
||
|
||
return ['invoices' => $invoices, 'errors' => $errors, 'provider' => 'vision'];
|
||
}
|
||
|
||
/** @return array{invoices:list<array<string,mixed>>,errors:list<string>,provider:string} */
|
||
private function recognizeImage(string $path): array
|
||
{
|
||
if (! $this->vision->configured()) {
|
||
return [
|
||
'invoices' => [],
|
||
'errors' => ['图片发票需要配置 OCR API。'],
|
||
'provider' => 'vision',
|
||
];
|
||
}
|
||
|
||
$mime = mime_content_type($path) ?: 'image/jpeg';
|
||
$bytes = (string) file_get_contents($path);
|
||
$invoice = $this->vision->recognize($bytes, $mime);
|
||
|
||
return [
|
||
'invoices' => $invoice === null ? [] : [$invoice],
|
||
'errors' => [],
|
||
'provider' => 'vision',
|
||
];
|
||
}
|
||
|
||
/** @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);
|
||
}
|
||
}
|