Merge branch 'dev' of bitbucket.org:jubilian/nhance into dev

This commit is contained in:
VENKATESHWARAN 2025-10-30 17:02:17 +05:30
commit 8a136faf70
3 changed files with 82 additions and 36 deletions

View File

@ -210,13 +210,13 @@ class Home extends PublicController
public function checkPolicyDoc()
{
// $this->convertToPdf();die();
try
{ // $this->convertToPdf();die();
// Replace with your actual Gemini API key
$apiKey = 'AIzaSyBbx-uotRBqkYhqLpmD60420E_a0G0duP8';
$apiKey = getenv('GEMINI_API_KEY');
// The model to use and the API endpoint
$model = "gemini-pro";
$model = "gemini-2.5-flash";
$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}";
@ -233,7 +233,7 @@ class Home extends PublicController
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mimeType = finfo_file($finfo, $filePath);
finfo_close($finfo);
// print_r($mimeType);die();
print_r($mimeType);die();
// Define supported inline MIME types
$supportedInlineMimeTypes = ['application/pdf','text/csv'];
@ -242,8 +242,8 @@ class Home extends PublicController
$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.";
$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\":\"\",\"engine_no\":\"\",\"chassis_no\":\"\",\"make\":\"\",\"model\":\"\",\"year\":\"\",\"cubic_capacity\":\"\",\"vehicle_type\":\"\"},\"rto\":\"\",\"premium\":{\"tp\":0,\"od\":0,\"pa_od\":0,\"taxes\":{},\"total\":0,\"in_words\":\"\"},\"endorsements\":[{\"code\":\"\",\"desc\":\"\"}]}"';
$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;
@ -253,7 +253,7 @@ class Home extends PublicController
];
// Conditionally handle the file upload based on MIME type
if (in_array($mimeType, $supportedInlineMimeTypes)) {
echo "Detected supported format inline MIME type ({$mimeType})";
// echo "Detected supported format inline MIME type ({$mimeType})";
// Handle PDF as inline data
$fileContent = file_get_contents($filePath);
$base64Content = base64_encode($fileContent);
@ -272,10 +272,10 @@ class Home extends PublicController
];
} else {
// Handle Excel/CSV using the Files API
echo "Detected unsupported inline MIME type ({$mimeType}). Uploading via Files API...\n";
// echo "Detected unsupported inline MIME type ({$mimeType}). Uploading via Files API...\n";
$fileInfo = $this->uploadFileToGemini($filePath, $apiKey); // Pass apiKey
print_r($fileInfo);
// print_r($fileInfo);
// The file part, using the URI from the Files API upload
$file_part = [
"fileData" => [
@ -321,24 +321,70 @@ class Home extends PublicController
// Check for cURL errors
if (curl_errno($ch)) {
echo 'cURL Error: ' . curl_error($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);
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;
$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
}
}

View File

@ -2236,12 +2236,12 @@ class PolicyTransactionModel extends Model
$startDate = date('Y-m-d', strtotime($start_date));
$endDate = date('Y-m-d', strtotime($end_date));
$builder->join('co_share_stmt_details', 'pt_co_share_details.id = co_share_stmt_details.co_share_id', 'left')
->join('insurer_statements', 'co_share_stmt_details.statement_id = insurer_statements.id', 'left')
$builder->join('co_share_stmt_details cssdfilter', 'pt_co_share_details.id = cssdfilter.co_share_id', 'left')
->join('insurer_statements', 'cssdfilter.statement_id = insurer_statements.id', 'left')
->where('insurer_statements.is_active', 1)
->where('insurer_statements.month >=', $startDate)
->where('insurer_statements.month <=', $endDate)
->groupBy('co_share_stmt_details.co_share_id');
->groupBy('cssdfilter.co_share_id');
}
// ==============================

View File

@ -62,7 +62,7 @@
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.5.3/dist/umd/popper.min.js"></script>
<link rel="manifest" href="../manifest.json">
<!-- <link rel="manifest" href="../manifest.json"> -->
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;700&display=swap" rel="stylesheet">
@ -71,15 +71,15 @@
<script>
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('../service-worker.js').then(function(registration) {
// console.log('Service Worker registration successful with scope:', registration.scope);
}, function(err) {
// console.log('Service Worker registration failed:', err);
});
});
}
// if ('serviceWorker' in navigator) {
// window.addEventListener('load', function() {
// navigator.serviceWorker.register('../service-worker.js').then(function(registration) {
// // console.log('Service Worker registration successful with scope:', registration.scope);
// }, function(err) {
// // console.log('Service Worker registration failed:', err);
// });
// });
// }
</script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.css" />
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick-theme.min.css" />