CaiWuXiTong/modules/EcommerceFinance/Services/DingInvoiceVisionClient.php

170 lines
6.0 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace Modules\EcommerceFinance\Services;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Http;
use RuntimeException;
class DingInvoiceVisionClient
{
private const PROMPT = <<<'PROMPT'
你是财务发票识别器。只识别图片中的发票,合同、付款截图、银行回单、审批截图都必须返回 is_invoice=false。
返回严格 JSON,不要 Markdown,不要解释,字段固定如下:
{
"is_invoice": true,
"invoice_type": "无票|电子发票(普通发票)|电子发票(增值税专用发票)|电子发票(铁路电子客票)|其他",
"seller_name": "",
"seller_tax_no": "",
"buyer_name": "",
"buyer_tax_no": "",
"invoice_total": 0.00,
"invoice_number": "",
"invoice_date": "YYYY-MM-DD",
"item_name": "",
"amount_without_tax": null,
"tax_rate": "",
"tax_amount": null
}
金额只返回数字。无法确认的文本字段返回空字符串,无法确认的数字字段返回 null。多行项目名用换行分隔。
PROMPT;
public function configured(): bool
{
return trim((string) config('ding_invoice_data.ocr.api_key', '')) !== '';
}
/** @return array<string,mixed>|null */
public function recognize(string $bytes, string $mimeType): ?array
{
$apiKey = trim((string) config('ding_invoice_data.ocr.api_key', ''));
if ($apiKey === '') {
throw new RuntimeException(
'发票 OCR 未配置。请在服务器设置 DING_INVOICE_OCR_API_KEY 后重试。',
);
}
if ($bytes === '') {
return null;
}
$mimeType = str_starts_with($mimeType, 'image/') ? $mimeType : 'image/jpeg';
$payload = [
'model' => (string) config('ding_invoice_data.ocr.model', 'deepseek-chat'),
'temperature' => 0,
'messages' => [[
'role' => 'user',
'content' => [
['type' => 'text', 'text' => self::PROMPT],
[
'type' => 'image_url',
'image_url' => [
'url' => 'data:' . $mimeType . ';base64,' . base64_encode($bytes),
],
],
],
]],
];
try {
$response = Http::withToken($apiKey)
->acceptJson()
->timeout(max(15, (int) config('ding_invoice_data.ocr.timeout_seconds', 90)))
->post((string) config('ding_invoice_data.ocr.base_url'), $payload);
} catch (ConnectionException|RequestException $exception) {
throw new RuntimeException('发票 OCR 请求失败:' . $exception->getMessage(), 0, $exception);
}
if (! $response->successful()) {
throw new RuntimeException('发票 OCR 返回 HTTP ' . $response->status() . '。');
}
$content = (string) $response->json('choices.0.message.content', '');
$decoded = $this->decodeJson($content);
if ($decoded === null || ($decoded['is_invoice'] ?? false) !== true) {
return null;
}
$invoiceTotal = $this->number($decoded['invoice_total'] ?? null);
$invoiceNumber = preg_replace(
'/[^0-9A-Za-z]/',
'',
trim((string) ($decoded['invoice_number'] ?? '')),
) ?? '';
if ($invoiceTotal <= 0 && $invoiceNumber === '') {
return null;
}
return [
'is_invoice' => true,
'invoice_type' => trim((string) ($decoded['invoice_type'] ?? '')) ?: '其他',
'seller_name' => trim((string) ($decoded['seller_name'] ?? '')),
'seller_tax_no' => trim((string) ($decoded['seller_tax_no'] ?? '')),
'buyer_name' => trim((string) ($decoded['buyer_name'] ?? '')),
'buyer_tax_no' => trim((string) ($decoded['buyer_tax_no'] ?? '')),
'invoice_total' => $invoiceTotal,
'invoice_number' => $invoiceNumber,
'invoice_date' => $this->date($decoded['invoice_date'] ?? null),
'item_name' => trim((string) ($decoded['item_name'] ?? '')),
'amount_without_tax' => $this->numberOrNull($decoded['amount_without_tax'] ?? null),
'tax_rate' => trim((string) ($decoded['tax_rate'] ?? '')),
'tax_amount' => $this->numberOrNull($decoded['tax_amount'] ?? null),
'ocr_text' => $content,
];
}
/** @return array<string,mixed>|null */
private function decodeJson(string $content): ?array
{
$content = trim($content);
$content = preg_replace('/^```(?:json)?\s*/i', '', $content) ?? $content;
$content = preg_replace('/\s*```$/', '', $content) ?? $content;
$decoded = json_decode($content, true);
if (is_array($decoded)) {
return $decoded;
}
$start = strpos($content, '{');
$end = strrpos($content, '}');
if ($start !== false && $end !== false && $end > $start) {
$decoded = json_decode(substr($content, $start, $end - $start + 1), true);
}
return is_array($decoded) ? $decoded : null;
}
private function number(mixed $value): float
{
return $this->numberOrNull($value) ?? 0.0;
}
private function numberOrNull(mixed $value): ?float
{
if ($value === null || trim((string) $value) === '') {
return null;
}
$normalized = str_replace([',', ',', '¥', '¥', ' '], '', (string) $value);
if (! is_numeric($normalized)) {
return null;
}
return round((float) $normalized, 2);
}
private function date(mixed $value): ?string
{
$value = trim((string) ($value ?? ''));
if (preg_match('/^\d{4}-\d{1,2}-\d{1,2}$/', $value) !== 1) {
return null;
}
[$year, $month, $day] = array_map('intval', explode('-', $value));
return checkdate($month, $day, $year)
? sprintf('%04d-%02d-%02d', $year, $month, $day)
: null;
}
}