|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|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; } }