527 lines
22 KiB
PHP
Executable File
527 lines
22 KiB
PHP
Executable File
<?php
|
|
|
|
namespace App\Controllers;
|
|
|
|
|
|
use GeminiAPI\Client;
|
|
use GeminiAPI\Resources\ModelName;
|
|
use GeminiAPI\Resources\Parts\TextPart;
|
|
|
|
use Mpdf\Mpdf;
|
|
use PhpOffice\PhpSpreadsheet\IOFactory;
|
|
use PhpOffice\PhpSpreadsheet\Shared\Date;
|
|
|
|
|
|
class Home extends PublicController
|
|
{
|
|
public function index(): string
|
|
{
|
|
return view('mail_welcome');
|
|
}
|
|
|
|
public function test()
|
|
{
|
|
echo base_url();
|
|
//echo ($_SERVER['SERVER_PORT'] == 443 ? 'https' : 'http') . "://{$_SERVER['SERVER_NAME']}".str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);
|
|
return view('welcome_message');
|
|
return view('test');
|
|
}
|
|
|
|
public function testService()
|
|
{
|
|
return 'from test service';
|
|
}
|
|
|
|
public function addTwoNumbers($payload)
|
|
{
|
|
//echo $payload['a'] + $payload['b'];
|
|
return $payload['a'] + $payload['b'];
|
|
}
|
|
|
|
public function check_Gemini()
|
|
{
|
|
try {
|
|
$apiKey = 'AIzaSyBbx-uotRBqkYhqLpmD60420E_a0G0duP8';
|
|
// Initialize the Gemini client
|
|
$client = new Client($apiKey);
|
|
|
|
// Send a prompt to the Gemini Pro model
|
|
$response = $client->generativeModel(ModelName::GEMINI_PRO)->generateContent(
|
|
new TextPart('Write a short, creative story about a knight and a dragon.')
|
|
);
|
|
|
|
// Display the generated text
|
|
$data['gemini_response'] = $response->text();
|
|
} catch (\Exception $e) {
|
|
// Handle any errors that occur during the API call
|
|
$data['gemini_response'] = 'An error occurred: ' . $e->getMessage();
|
|
}
|
|
|
|
//print_rr($data);
|
|
}
|
|
|
|
|
|
//for insurer statement upload
|
|
public function check_gemini_2()
|
|
{
|
|
|
|
// $this->convertToPdf();die();
|
|
// Replace with your actual Gemini API key
|
|
$apiKey = 'AIzaSyBbx-uotRBqkYhqLpmD60420E_a0G0duP8';
|
|
|
|
// The model to use and the API endpoint
|
|
$model = "gemini-pro";
|
|
$model = "gemini-2.5-flash";
|
|
// $model = "gemini-1.5-pro";
|
|
// $model = "gemini-1.5-pro";
|
|
$url = "https://generativelanguage.googleapis.com/v1beta/models/{$model}:generateContent?key={$apiKey}";
|
|
|
|
$filePath = 'C:\Users\Venba\Downloads\NIA MDU May-2025 (2).pdf';
|
|
$filePath = 'C:/Users/Venba/Desktop/ins stmts/NIC MDU June-2025 (1).pdf';
|
|
$filePath = 'C:/Users/Venba/Desktop/ins stmts/UIIC GR June-2025.pdf';
|
|
$filePath = 'C:/Users/Venba/Desktop/ins stmts/UIIC VLR June-2025 (2).xlsx';
|
|
$filePath = 'C:/Users/Venba/Desktop/ins stmts/pdf/1.pdf';
|
|
$filePath = 'C:/Users/Venba/Desktop/ins stmts/output.csv';
|
|
// $filePath = 'C:\Users\Venba\Downloads\Raheja June-2025.csv';
|
|
// $filePath = 'C:/Users/Venba/Downloads/Raheja June-2025.pdf';
|
|
// $filePath = 'C:/Users/Venba/Desktop/ins stmts/ICICI Pru June-2025 (1).xlsx';
|
|
// $filePath = 'C:/Users/Venba/Desktop/ins stmts/Digit Life June-2025.xlsx';
|
|
|
|
// Check if the file exists
|
|
if (!file_exists($filePath)) {
|
|
die("Error: File not found at {$filePath}");
|
|
}
|
|
|
|
// Get the file's MIME type using the finfo extension
|
|
$finfo = finfo_open(FILEINFO_MIME_TYPE);
|
|
$mimeType = finfo_file($finfo, $filePath);
|
|
finfo_close($finfo);
|
|
// print_r($mimeType);die();
|
|
// Define supported inline MIME types
|
|
$supportedInlineMimeTypes = ['application/pdf','text/csv'];
|
|
|
|
// Read the file content and encode it to Base64
|
|
$fileContent = file_get_contents($filePath);
|
|
$base64Content = base64_encode($fileContent);
|
|
// The prompt you want to send to the model
|
|
$prompt = "give me a json with emp data like name,age,dob,mobile and email. only json not any explanations";
|
|
$prompt = "Read the following insurer monthly statement file and convert into JSON format as sample specified.attach statement items in 'items' key and if any other data available put it in 'meta'. Give me only JSON,not any explanations. If you find the same details like insured name, policy number,endorsement no,policy start date,policy end date group it as single policy and identify base premium, third party premium and terrorism premium.All brokerage amount may in the same name as brokerage or commission, so pick accordingly";
|
|
$prompt .= "{\'items\': [{\'sno\': 1, \'policy_no\': \'\', \'insured_name\': \'\', \'endorsement_no\': \'\', \'policy_start_date\': \'\', \'policy_end_date\': \'\', \'actual_base_premium_amount\': \'\', \'actual_third_party_premium_amount\': \'\', \'actual_terrorism_premium_amount\': \'\', \'actual_base_premium_percentage\': \'\', \'actual_third_party_premium_percentage\': \'\', \'actual_terrorism_premium_percentage\': \'\', \'actual_bp_brokerage_amount\': \'\', \'actual_tp_brokerage_amount\': \'\', \'actual_tep_brokerage_amount\': \'\', \'reward_amount\': \'\'}]}";
|
|
|
|
$payloadPart = null;
|
|
|
|
// The text part of the prompt
|
|
$text_part = [
|
|
"text" => $prompt
|
|
];
|
|
// Conditionally handle the file upload based on MIME type
|
|
if (in_array($mimeType, $supportedInlineMimeTypes)) {
|
|
echo "Detected supported format inline MIME type ({$mimeType})";
|
|
// Handle PDF as inline data
|
|
$fileContent = file_get_contents($filePath);
|
|
$base64Content = base64_encode($fileContent);
|
|
$payloadPart = [
|
|
"inlineData" => [
|
|
"mimeType" => $mimeType,
|
|
"data" => $base64Content
|
|
]
|
|
];
|
|
|
|
$content_parts = [
|
|
"parts" => [
|
|
$text_part,
|
|
$payloadPart
|
|
]
|
|
];
|
|
} else {
|
|
// Handle Excel/CSV using the Files API
|
|
echo "Detected unsupported inline MIME type ({$mimeType}). Uploading via Files API...\n";
|
|
$fileInfo = $this->uploadFileToGemini($filePath, $apiKey); // Pass apiKey
|
|
|
|
print_r($fileInfo);
|
|
// The file part, using the URI from the Files API upload
|
|
$file_part = [
|
|
"fileData" => [
|
|
"fileUri" => $fileInfo['uri'],
|
|
"mimeType" => $fileInfo['mimeType']
|
|
]
|
|
];
|
|
|
|
// The full content array, containing both parts
|
|
$content_parts = [
|
|
"parts" => [
|
|
$text_part,
|
|
$file_part
|
|
]
|
|
];
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// The final JSON payload
|
|
$data = [
|
|
"contents" => [
|
|
$content_parts
|
|
]
|
|
];
|
|
|
|
// Encode the data to a JSON string
|
|
$json_data = json_encode($data);
|
|
|
|
// Initialize cURL
|
|
$ch = curl_init($url);
|
|
|
|
// Set cURL options
|
|
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); // Set the Content-Type header
|
|
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data); // Set the JSON payload
|
|
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the response as a string
|
|
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Optional: to bypass SSL verification if needed (not recommended for production)
|
|
|
|
// Execute the cURL request and get the response
|
|
$response = curl_exec($ch);
|
|
|
|
// Check for cURL errors
|
|
if (curl_errno($ch)) {
|
|
echo 'cURL Error: ' . curl_error($ch);
|
|
}
|
|
|
|
// Close the cURL handle
|
|
curl_close($ch);
|
|
|
|
// Decode the JSON response
|
|
$responseData = json_decode($response, true);
|
|
echo '<pre>';
|
|
print_r($responseData);
|
|
echo '<pre>';
|
|
// Check if the response contains generated text
|
|
if (isset($responseData['candidates'][0]['content']['parts'][0]['text'])) {
|
|
$generatedText = $responseData['candidates'][0]['content']['parts'][0]['text'];
|
|
echo "Generated Text: " . $generatedText;
|
|
} else {
|
|
echo "Error or no text generated. Response: " . $response;
|
|
}
|
|
|
|
}
|
|
|
|
|
|
//for insurer policy doc upload
|
|
public function checkPolicyDoc()
|
|
{
|
|
|
|
try
|
|
{ // $this->convertToPdf();die();
|
|
// Replace with your actual Gemini API key
|
|
$apiKey = getenv('GEMINI_API_KEY');
|
|
// The model to use and the API endpoint
|
|
$model = "gemini-pro";
|
|
$model = getenv('GEMINI_MODEL');
|
|
// $model = "gemini-1.5-pro";
|
|
// $model = "gemini-1.5-pro";
|
|
$url = "https://generativelanguage.googleapis.com/v1beta/models/{$model}:generateContent?key={$apiKey}";
|
|
|
|
$filePath = 'C:\Users\Venba\AppData\Local\Programs\Python\pyenv\pdfreader\bike-0904023124P114268957.pdf';
|
|
$filePath = 'C:\Users\Venba\AppData\Local\Programs\Python\pyenv\pdfreader\car-insurance-0904023124P114213011.pdf';
|
|
|
|
// Check if the file exists
|
|
if (!file_exists($filePath)) {
|
|
die("Error: File not found at {$filePath}");
|
|
}
|
|
|
|
// Get the file's MIME type using the finfo extension
|
|
$finfo = finfo_open(FILEINFO_MIME_TYPE);
|
|
$mimeType = finfo_file($finfo, $filePath);
|
|
finfo_close($finfo);
|
|
print_r($mimeType);die();
|
|
// Define supported inline MIME types
|
|
$supportedInlineMimeTypes = ['application/pdf','text/csv'];
|
|
|
|
// Read the file content and encode it to Base64
|
|
$fileContent = file_get_contents($filePath);
|
|
$base64Content = base64_encode($fileContent);
|
|
// The prompt you want to send to the model
|
|
// $prompt = "give me a json with emp data like name,age,dob,mobile and email. only json not any explanations";
|
|
$prompt = "Read the following motor policy pdf document and convert into JSON format as sample specified. Give me only JSON,not any explanations.while pick up premium break up give own damage, third party ,personal accident and taxes as mentioned in JSON format.Notes:vehicle_type should be like Two Wheeler,Four Feeler,Good Vehicle,Bus, Tractor,Commercial Vehicle.rto_state_code is first two char of reg_no and rto_city_code 3rd & 4th char of reg_no and it should be two digit numeric code. Any date should be in mysql date format";
|
|
$prompt .= '"{\"policy\":{\"policy_number\":\"\",\"issue_date\":\"\",\"period\":{\"start\":\"\",\"end\":\"\"},\"insurer\":\"\",\"previous_policy_number\":\"\"},\"insured\":{\"name\":\"\",\"father_name\":\"\",\"address\":[\"\"],\"mobile\":\"\",\"id_proofs\":{\"aadhaar\":\"\",\"pan\":\"\"}},\"vehicle\":{\"reg_no\":\"\",\"rto_state_code\":\"\",\"rto_city_code\":\"\",\"weight\":\"\",\"fuel_type\":\"\",\"date_of_registration\":\"\",\"year_of_manufacture\":\"\",\"engine_no\":\"\",\"chassis_no\":\"\",\"make\":\"\",\"model\":\"\",\"year\":\"\",\"cubic_capacity\":\"\",\"vehicle_type\":\"\"},\"rto\":\"\",\"premium\":{\"tp\":0,\"od\":0,\"pa\":0,\"taxes\":{},\"total\":0,\"in_words\":\"\"},\"endorsements\":[{\"code\":\"\",\"desc\":\"\"}]}"';
|
|
|
|
$payloadPart = null;
|
|
|
|
// The text part of the prompt
|
|
$text_part = [
|
|
"text" => $prompt
|
|
];
|
|
// Conditionally handle the file upload based on MIME type
|
|
if (in_array($mimeType, $supportedInlineMimeTypes)) {
|
|
// echo "Detected supported format inline MIME type ({$mimeType})";
|
|
// Handle PDF as inline data
|
|
$fileContent = file_get_contents($filePath);
|
|
$base64Content = base64_encode($fileContent);
|
|
$payloadPart = [
|
|
"inlineData" => [
|
|
"mimeType" => $mimeType,
|
|
"data" => $base64Content
|
|
]
|
|
];
|
|
|
|
$content_parts = [
|
|
"parts" => [
|
|
$text_part,
|
|
$payloadPart
|
|
]
|
|
];
|
|
} else {
|
|
// Handle Excel/CSV using the Files API
|
|
// echo "Detected unsupported inline MIME type ({$mimeType}). Uploading via Files API...\n";
|
|
$fileInfo = $this->uploadFileToGemini($filePath, $apiKey); // Pass apiKey
|
|
|
|
// print_r($fileInfo);
|
|
// The file part, using the URI from the Files API upload
|
|
$file_part = [
|
|
"fileData" => [
|
|
"fileUri" => $fileInfo['uri'],
|
|
"mimeType" => $fileInfo['mimeType']
|
|
]
|
|
];
|
|
|
|
// The full content array, containing both parts
|
|
$content_parts = [
|
|
"parts" => [
|
|
$text_part,
|
|
$file_part
|
|
]
|
|
];
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// The final JSON payload
|
|
$data = [
|
|
"contents" => [
|
|
$content_parts
|
|
]
|
|
];
|
|
|
|
// Encode the data to a JSON string
|
|
$json_data = json_encode($data);
|
|
|
|
// Initialize cURL
|
|
$ch = curl_init($url);
|
|
|
|
// Set cURL options
|
|
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); // Set the Content-Type header
|
|
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data); // Set the JSON payload
|
|
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the response as a string
|
|
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Optional: to bypass SSL verification if needed (not recommended for production)
|
|
|
|
// Execute the cURL request and get the response
|
|
$response = curl_exec($ch);
|
|
|
|
// Check for cURL errors
|
|
if (curl_errno($ch)) {
|
|
$curl_error = curl_error($ch);
|
|
throw new Exception("cURL Error: " . $curl_error);
|
|
}
|
|
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
|
|
|
// Close the cURL handle
|
|
curl_close($ch);
|
|
$ch = null; // Mark handle as closed
|
|
// Check for non-successful HTTP status codes
|
|
if ($http_code < 200 || $http_code >= 300) {
|
|
throw new Exception("API returned non-successful HTTP status code: $http_code. Response: " . substr($response, 0, 200) . '...');
|
|
}
|
|
|
|
// Decode the JSON response
|
|
$responseData = json_decode($response, true, 512, JSON_THROW_ON_ERROR);
|
|
$text_path = $responseData['candidates'][0]['content']['parts'][0]['text'] ?? null;
|
|
|
|
if ($text_path) {
|
|
$generatedText = $text_path;
|
|
log_message('info', "Successfully received generated text.");
|
|
|
|
// 9. Attempt to extract and decode the exact JSON from the generated text
|
|
$json_string = '';
|
|
|
|
// Preferred: Regex to find content inside a JSON markdown block: ```json\n(.*?)\n```
|
|
$extracted_json_match = [];
|
|
if (preg_match('/```json\s*(.*?)\s*```/s', $generatedText, $extracted_json_match)) {
|
|
$json_string = trim($extracted_json_match[1]);
|
|
} else {
|
|
// Fallback: Find the first '{' and the last '}'
|
|
$start = strpos($generatedText, '{');
|
|
$end = strrpos($generatedText, '}');
|
|
if ($start !== false && $end !== false && $end > $start) {
|
|
$json_string = substr($generatedText, $start, $end - $start + 1);
|
|
}
|
|
}
|
|
|
|
if (empty($json_string)) {
|
|
throw new Exception("Could not extract a valid JSON string from the generated text.");
|
|
}
|
|
|
|
// Decode the extracted JSON string
|
|
$final_data = json_decode($json_string, true, 512, JSON_THROW_ON_ERROR);
|
|
|
|
log_message('info', "Extracted and decoded final JSON data successfully.");
|
|
echo '<pre>';
|
|
print_r($final_data);
|
|
// return $final_data;
|
|
|
|
} else {
|
|
// No generated text found, possibly a model safety block or API structure change
|
|
throw new Exception("Response structure invalid or no generated text candidate found.");
|
|
}
|
|
|
|
} catch (Exception $e) {
|
|
// Log the error
|
|
log_message('ERROR', "$request_id: Fatal Error: " . $e->getMessage());
|
|
|
|
// Ensure cURL handle is closed if an exception occurred after initialization but before closing
|
|
if ($ch !== null) {
|
|
curl_close($ch);
|
|
}
|
|
return null; // Return null on failure
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Function to upload a file to the Gemini Files API
|
|
function uploadFileToGemini($filePath, $apiKey)
|
|
{
|
|
// Define the URL for the Files API upload
|
|
$uploadUrl = "https://generativelanguage.googleapis.com/upload/v1beta/files?key={$apiKey}";
|
|
|
|
// Get file info
|
|
$finfo = finfo_open(FILEINFO_MIME_TYPE);
|
|
$fileMimeType = finfo_file($finfo, $filePath);
|
|
finfo_close($finfo);
|
|
|
|
$displayName = basename($filePath);
|
|
|
|
// Build the request body for the Files API
|
|
$fileUploadData = [
|
|
'file' => [
|
|
'display_name' => $displayName,
|
|
],
|
|
];
|
|
$jsonUploadData = json_encode($fileUploadData);
|
|
|
|
// Initialize cURL for the upload
|
|
$ch_upload = curl_init();
|
|
curl_setopt($ch_upload, CURLOPT_URL, $uploadUrl);
|
|
curl_setopt($ch_upload, CURLOPT_RETURNTRANSFER, true);
|
|
curl_setopt($ch_upload, CURLOPT_POST, true);
|
|
|
|
// Use CURLFile for multipart/form-data upload
|
|
$payload = [
|
|
'metadata' => $jsonUploadData,
|
|
'file' => new \CURLFile($filePath, $fileMimeType, $displayName),
|
|
];
|
|
|
|
curl_setopt($ch_upload, CURLOPT_POSTFIELDS, $payload);
|
|
curl_setopt($ch_upload, CURLOPT_HTTPHEADER, [
|
|
'X-Goog-Upload-Protocol: multipart',
|
|
]);
|
|
curl_setopt($ch_upload, CURLOPT_SSL_VERIFYPEER, false); // Optional: not for production
|
|
|
|
// Execute the upload request
|
|
$uploadResponse = curl_exec($ch_upload);
|
|
|
|
if (curl_errno($ch_upload)) {
|
|
die('cURL Error (Files API): ' . curl_error($ch_upload));
|
|
}
|
|
|
|
curl_close($ch_upload);
|
|
|
|
$uploadResponseData = json_decode($uploadResponse, true);
|
|
|
|
// Check for a successful upload and return the file URI
|
|
if (!isset($uploadResponseData['file']['uri'])) {
|
|
die("Error uploading file. Response: " . $uploadResponse);
|
|
}
|
|
|
|
return [
|
|
'uri' => $uploadResponseData['file']['uri'],
|
|
'mimeType' => $fileMimeType
|
|
];
|
|
}
|
|
|
|
|
|
public function convertToPdf($inputFile = null)
|
|
{
|
|
// 1. Load your Excel file
|
|
$inputFile = 'C:/Users/Venba/Desktop/ins stmts/Raheja June-2025.xlsx';
|
|
$inputFile = 'C:/Users/Venba/Desktop/ins stmts/ICICI Lom June-2025.xlsx';
|
|
// $inputFile = 'C:/Users/Venba/Desktop/ins stmts/pdf/sample.pdf';
|
|
$spreadsheet = IOFactory::load($inputFile);
|
|
|
|
// 2. Initialize mPDF with proper configuration
|
|
$mpdf = new Mpdf([
|
|
'mode' => 'utf-8',
|
|
'format' => 'A4',
|
|
'margin_header' => 5,
|
|
'margin_footer' => 5,
|
|
'orientation' => 'L',
|
|
'default_font_size' => 18,
|
|
// 'default_font' => 'Arial'
|
|
]);
|
|
|
|
// 3. Process each worksheet
|
|
foreach ($spreadsheet->getWorksheetIterator() as $worksheet) {
|
|
// Get HTML representation of the sheet
|
|
$html = $this->worksheetToHtml($worksheet);
|
|
// print_r($html);
|
|
// Add to PDF
|
|
$mpdf->AddPage();
|
|
$mpdf->WriteHTML($html);
|
|
}
|
|
$pdfPath = 'C:/Users/Venba/Desktop/ins stmts/pdf/1.pdf';
|
|
// $pdfPath = WRITEPATH.'tmp';
|
|
$mpdf->Output($pdfPath, \Mpdf\Output\Destination::FILE); // Save file on server
|
|
// 4. Output
|
|
// $mpdf->Output('financial_report.pdf', 'D');
|
|
}
|
|
|
|
|
|
|
|
|
|
protected function worksheetToHtml($worksheet)
|
|
{
|
|
// Customize this based on your needs
|
|
$html = '<h2>' . htmlspecialchars($worksheet->getTitle()) . '</h2>';
|
|
$html .= '<table data-custom-table-css="table" border="1" cellpadding="5">';
|
|
|
|
foreach ($worksheet->getRowIterator() as $row) {
|
|
$html .= '<tr>';
|
|
$cellIterator = $row->getCellIterator();
|
|
$cellIterator->setIterateOnlyExistingCells(true);
|
|
|
|
foreach ($cellIterator as $cell) {
|
|
$value = $cell->getValue();
|
|
|
|
// ✅ Detect and format Excel date cells
|
|
if (Date::isDateTime($cell)) {
|
|
$formattedValue = Date::excelToDateTimeObject($value)->format('Y-m-d');
|
|
} else {
|
|
$formattedValue = $cell->getCalculatedValue();
|
|
}
|
|
|
|
$html .= '<td>' . htmlspecialchars($formattedValue) . '</td>';
|
|
}
|
|
|
|
$html .= '</tr>';
|
|
}
|
|
|
|
$html .= '</table>';
|
|
return $html;
|
|
}
|
|
|
|
|
|
|
|
}
|