Files
musadaq-saas/app/Services/AiExtractionService.php

90 lines
2.7 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Services;
use Exception;
final class AiExtractionService
{
private string $apiKey;
private string $model;
public function __construct()
{
$this->apiKey = $_ENV['GEMINI_API_KEY'] ?? '';
$this->model = $_ENV['GEMINI_MODEL'] ?? 'gemini-2.0-flash';
}
public function extractInvoiceData(string $filePath, string $mimeType): array
{
if (empty($this->apiKey)) {
throw new Exception("Gemini API Key is missing. Please configure it in .env");
}
$fileContent = file_get_contents($filePath);
if ($fileContent === false) {
throw new Exception("Could not read uploaded invoice file.");
}
$base64Data = base64_encode($fileContent);
$prompt = "Please extract the following information from this invoice and return it strictly as JSON without markdown blocks or backticks:\n"
. "- invoice_number\n"
. "- invoice_date (YYYY-MM-DD)\n"
. "- total_amount\n"
. "- tax_amount\n"
. "- vendor_name\n"
. "- vendor_tax_number";
$payload = [
'contents' => [
[
'parts' => [
['text' => $prompt],
[
'inline_data' => [
'mime_type' => $mimeType,
'data' => $base64Data
]
]
]
]
],
'generationConfig' => [
'temperature' => 0.1,
'response_mime_type' => 'application/json'
]
];
$url = "https://generativelanguage.googleapis.com/v1beta/models/{$this->model}:generateContent?key={$this->apiKey}";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json'
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode !== 200) {
throw new Exception("AI Extraction failed. HTTP Code: {$httpCode}. Response: {$response}");
}
$result = json_decode($response, true);
$text = $result['candidates'][0]['content']['parts'][0]['text'] ?? '{}';
$data = json_decode($text, true);
if (!is_array($data)) {
throw new Exception("Failed to parse AI output as JSON: {$text}");
}
return $data;
}
}