Files
api/services/nginx/app/classes/ocr_space.php
T
Jeppe Bundgaard abd21e0ad7 Add OCR processing integration and module scanner routes
- Implemented `get_ocr_result` method in the `ocr_space` class to interact with the OCR Space API.
- Added `process_ocr` method to `image_processor_t` for handling OCR logic.
- Updated interfaces (`ocr_space_i` and `image_processor_i`) to support OCR functionality.
- Introduced `moduleScannerRoute` with endpoints for testing and license plate recognition workflows.
- Included data validation and exception handling for OCR processing.
2025-08-06 15:19:43 +02:00

88 lines
2.2 KiB
PHP

<?php
namespace classes;
require_once WD . '/modules/ocrSpace/ocrSpace_c.php';
use Exception;
use interfaces\ocr_space_i;
use ocrSpace\ocrSpace_c;
class ocr_space implements ocr_space_i
{
/**
* The configuration of the module
* @var ocrSpace_c
*/
public ocrSpace_c $config;
/**
* API URL
* @var string
*/
private string $api_url = 'https://api.ocr.space/parse/image';
public function __construct()
{
$this->config = new ocrSpace_c();
}
/**
* @inheritDoc
*/
public function requireModuleEnabled(): void
{
if (!(bool)$this->config->enabled->getVariableValue()) {
throw new Exception('OCR Space module is not enabled.');
}
}
/**
* @inheritDoc
* @throws Exception If the module is not enabled or if there is an error in the API request
* @throws Exception If the API response cannot be parsed
*/
public function get_ocr_result(string $base64_image): array
{
$this->requireModuleEnabled();
if (empty($base64_image)) {
throw new Exception('Base64 image string cannot be empty.');
}
$formData = [
'base64Image' => $base64_image,
'isOverlayRequired' => 'true',
'scale' => 'true',
'detectOrientation' => 'true',
'language' => 'eng',
'OCREngine' => '2'
];
$options = [
'http' => [
'method' => 'POST',
'header' => [
'apikey: ' . $this->config->api_key->getVariableValue(),
'Content-Type: application/x-www-form-urlencoded'
],
'content' => http_build_query($formData)
]
];
$context = stream_context_create($options);
$result = file_get_contents($this->api_url, false, $context);
if ($result === false) {
throw new Exception('Failed to get OCR result from API.');
}
$response = json_decode($result, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new Exception('Failed to parse OCR API response.');
}
return $response;
}
}