PHP code example of laravelsmartocr / laravel-smart-ocr

1. Go to this page and download the library: Download laravelsmartocr/laravel-smart-ocr library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

laravelsmartocr / laravel-smart-ocr example snippets


// Works free, offline, zero config — start in 60 seconds
$result = SmartOCR::driver('tesseract')->read('/path/to/invoice.jpg');
echo $result->text();

// Switch providers with a single .env change — zero code changes
SMART_OCR_DRIVER=google   # or aws, azure, claude, openai, mistral, pdf

final class Invoice {
    public function __construct(
        #[Field('Invoice number')] public string $number = '',
        #[Field('Grand total, number only')] public float $total = 0.0,
        #[Field('Due date, ISO format')] public ?string $dueDate = null,
    ) {}
}

$result = SmartOCR::from($file)->extract(Invoice::class);
echo $result->data->number;  // "INV-2026-001"
echo $result->data->total;   // 1250.0

$result = SmartOCR::from($file)->read();

echo $result->toMarkdown();   // tables and headings preserved

foreach ($result->chunks(maxTokens: 500) as $chunk) {
    echo $chunk->text;        // chunk text
    echo $chunk->heading;     // section heading
    echo $chunk->startPage;   // page number
}

$result = SmartOCR::from($file)->read();

// Redact emails, phone numbers, card numbers, IBAN, SSN, PAN
$clean = $result->redact(['email', 'phone', 'card', 'iban', 'ssn'])->text();

$result = SmartOCR::driver('pdf')->read($file);

$type = $result->classify();
// ['type' => 'invoice', 'confidence' => 0.92]

// Restrict to known types
$type = $result->classify(['invoice', 'receipt', 'contract']);

use LaravelSmartOCR\Facades\SmartOCR;

// 60-second quick start — free, no API key needed
$result = SmartOCR::driver('tesseract')->read('/path/to/image.jpg');
echo $result->text();

// Full result object
echo $result->confidence() ?? 'n/a'; // float|null — null when provider does not expose a real score
$result->tables();           // normalized tables
$result->fields();           // key-value form fields
$result->toArray();          // complete structured data

$result = SmartOCR::driver('tesseract')->read('path/to/image.png');
echo $result->text();

// Force offline (always uses Tesseract)
$text = SmartOCR::freeText($file);

// Image
$result = SmartOCR::driver('google')->read('invoice.jpg');

// With language hint
$result = SmartOCR::driver('google')->language('fr')->read('document.png');

// Uploaded file
$result = SmartOCR::driver('google')->read($request->file('document'));

// PDF (up to 5 pages synchronous)
$result = SmartOCR::driver('google')->read('contract.pdf');

echo $result->text();
echo $result->confidence();  // per-word average
$result->words();            // [{text, confidence, bounding_box}]
$result->pages();            // [{page, text, confidence, lines, blocks}]

// Standard read (auto sync/async)
$result = SmartOCR::driver('aws')->read('invoice.pdf');

// Read directly from S3
$result = SmartOCR::driver('aws')->readFromS3('documents/invoice.pdf');

// Tables
foreach ($result->tables() as $table) {
    $table['headers'];   // ['Item', 'Qty', 'Price']
    $table['rows'];      // [['Item' => 'Widget', 'Qty' => '2', 'Price' => '$10']]
    $table['page'];      // page number
}

// Key-value form fields
foreach ($result->fields() as $field) {
    $field['key'];        // 'Invoice Number'
    $field['value'];      // 'INV-1001'
    $field['confidence']; // 0.99
}

$result = SmartOCR::driver('azure')->read('document.jpg');

// With language hint
$result = SmartOCR::driver('azure')->language('en')->read('scan.pdf');

echo $result->text();

foreach ($result->lines() as $line) {
    $line['text'];         // 'Invoice Total: $1,200'
    $line['confidence'];   // 0.98
    $line['bounding_box']; // ['x'=>100,'y'=>200,'width'=>300,'height'=>40,'points'=>[...]]
}

$result = SmartOCR::driver('claude')->read('invoice.jpg');
echo $result->text();
echo $result->confidence(); // null — Claude does not expose a confidence score

$result = SmartOCR::driver('openai')->read('receipt.png');
echo $result->text();
echo $result->confidence(); // null — OpenAI does not expose a confidence score

$result = SmartOCR::driver('pdf')->read('digital-invoice.pdf');
echo $result->text();
echo $result->confidence(); // null — text extraction does not produce a confidence score

$result = SmartOCR::driver('google')->read($file);

// Text
$result->text();          // string — full extracted text
$result->confidence();    // float|null — normalized 0.0–1.0; null when provider does not expose a real score
$result->provider();      // string — 'google', 'aws', 'azure', etc.
$result->isSuccessful();  // bool

// Structure
$result->pages();   // array of pages with text, confidence, lines, blocks
$result->lines();   // array of lines with text, confidence, bounding_box
$result->words();   // array of words with text, confidence, bounding_box
$result->blocks();  // array of blocks (Google-style paragraph groups)
$result->tables();  // array of tables with headers and rows
$result->fields();  // array of key-value pairs (AWS Textract forms)

// Raw & meta
$result->raw();       // original provider response, unmodified
$result->metadata();  // engine, language, processing info
$result->errors();    // any non-fatal errors

// Full structured array
$result->toArray();

[
    'success'    => true,
    'provider'   => 'google',
    'text'       => 'Invoice\nINV-1001\nTotal: $1,200.00',
    'confidence' => 0.98,   // float|null — null for Tesseract, Claude, OpenAI, PDF
    'pages'      => [
        [
            'page'       => 1,
            'text'       => '...',
            'confidence' => 0.98,
            'lines'      => [...],
            'blocks'     => [...],
        ],
    ],
    'lines'      => [
        ['text' => 'Invoice', 'confidence' => 0.99, 'bounding_box' => ['x'=>100,'y'=>100,'width'=>200,'height'=>30,'points'=>[...]]],
    ],
    'words'      => [...],
    'blocks'     => [...],
    'tables'     => [...],
    'fields'     => [...],
    'metadata'   => ['engine' => 'google-vision', 'language' => 'auto'],
    'raw'        => [...],   // original API response
    'errors'     => [],
]

[
    'x'      => 100,    // left edge in pixels
    'y'      => 200,    // top edge in pixels
    'width'  => 300,    // width in pixels
    'height' => 40,     // height in pixels
    'points' => [       // four corner points
        ['x' => 100, 'y' => 200],
        ['x' => 400, 'y' => 200],
        ['x' => 400, 'y' => 240],
        ['x' => 100, 'y' => 240],
    ],
]

use LaravelSmartOCR\Extraction\Attributes\Field;
use LaravelSmartOCR\Extraction\Attributes\ListOf;

final class Invoice {
    public function __construct(
        #[Field('Invoice number')] public string $number = '',
        #[Field('Grand total, number only')] public float $total = 0.0,
        #[Field('Due date, ISO format')] public ?string $dueDate = null,
    ) {}
}

$result = SmartOCR::from($file)->extract(Invoice::class);
// $result->data is a typed Invoice object
echo $result->data->number;  // "INV-2026-001"
echo $result->data->total;   // 1250.0

// Per-field citations
$field = $result->field('total');
echo $field->confidence;     // float or null
echo $field->citation->page; // 1

$result = SmartOCR::from($file)->read();

// Render as Markdown (tables, headings preserved)
echo $result->toMarkdown();

// Split into chunks for vector stores
foreach ($result->chunks(maxTokens: 500) as $chunk) {
    echo $chunk->text;       // chunk text
    echo $chunk->heading;    // section heading
    echo $chunk->startPage;  // page number
}

// Cheapest available driver first
SmartOCR::from($file)->cheapest()->read();

// Highest quality first
SmartOCR::from($file)->best()->read();

// Escalate if confidence is low
SmartOCR::from($file)
    ->using('tesseract')
    ->escalateTo('mistral', whenConfidenceBelow: 0.80)
    ->read();

// Cache result for 30 days (keyed by file hash + driver)
SmartOCR::from($file)->cache(ttl: now()->addDays(30))->read();

$result = SmartOCR::from($file)->read();

// Redact PII from text
$clean = $result->redact(['email', 'phone', 'card'])->text();

// Classify document type
$type = $result->classify(); // ['type' => 'invoice', 'confidence' => 0.75]

$result = SmartOCR::from($file)->extract(Invoice::class);

// Fields below 0.85 confidence go to the review queue
$reviews = $result->sendToReview(threshold: 0.85, documentHash: hash_file('sha256', $file));

// Later, approve or correct
$review->approve();
$review->correct('INV-2026-001');
echo $review->final(); // corrected value

// Language hint
$result = SmartOCR::driver('google')
    ->language('fr')
    ->read($file);

// Fallback to Tesseract if cloud fails
$result = SmartOCR::driver('azure')
    ->fallback('tesseract')
    ->read($file);

// Chain with fallback
$result = SmartOCR::driver('google')
    ->language('en')
    ->fallback('tesseract')
    ->read($request->file('invoice'));

$result = SmartOCR::driver('aws')->read('invoice.pdf');

foreach ($result->tables() as $table) {
    echo "Page: " . $table['page'] . "\n";
    echo "Headers: " . implode(', ', $table['headers']) . "\n";

    foreach ($table['rows'] as $row) {
        echo $row['Item'] . ' — ' . $row['Price'] . "\n";
    }
}

[
    [
        'page'    => 1,
        'headers' => ['Item', 'Quantity', 'Price', 'Total'],
        'rows'    => [
            ['Item' => 'Widget A', 'Quantity' => '2', 'Price' => '$10.00', 'Total' => '$20.00'],
        ],
    ],
]

$result = SmartOCR::driver('aws')->read('form.pdf');

foreach ($result->fields() as $field) {
    echo $field['key'] . ': ' . $field['value'];
    echo ' (' . round($field['confidence'] * 100) . "% confidence)\n";
}
// Invoice Number: INV-1001 (99% confidence)
// Date: 2026-09-23 (98% confidence)
// Total: $1,200.00 (99% confidence)

use LaravelSmartOCR\Facades\SmartOCR;
use LaravelSmartOCR\Events\OcrCompleted;
use LaravelSmartOCR\Events\OcrFailed;

// Dispatch
SmartOCR::queue('/path/to/invoice.pdf', 'google');
SmartOCR::queue('/path/to/invoice.pdf', 'aws', ['language' => 'en']);

// Listen for results
Event::listen(OcrCompleted::class, function (OcrCompleted $event) {
    $result = $event->result;
    $driver = $event->driver;

    Log::info("OCR complete via {$driver}: " . substr($result->text(), 0, 100));
});

Event::listen(OcrFailed::class, function (OcrFailed $event) {
    Log::error("OCR failed via {$event->driver}: " . $event->exception->getMessage());
});

use LaravelSmartOCR\Exceptions\OCRException;
use LaravelSmartOCR\Exceptions\ConfigurationException;
use LaravelSmartOCR\Exceptions\AuthenticationException;
use LaravelSmartOCR\Exceptions\RateLimitException;
use LaravelSmartOCR\Exceptions\OcrTimeoutException;
use LaravelSmartOCR\Exceptions\UnsupportedDocumentException;
use LaravelSmartOCR\Exceptions\ProviderException;

try {
    $result = SmartOCR::driver('google')->read($file);
} catch (AuthenticationException $e) {
    // Invalid API key / credentials
} catch (RateLimitException $e) {
    $retryAfter = $e->retryAfter(); // seconds
    // Queue for retry
} catch (OcrTimeoutException $e) {
    // Request timed out
} catch (UnsupportedDocumentException $e) {
    // File format not supported by this provider
} catch (ConfigurationException $e) {
    // Missing 

// Apply a saved template
$result = SmartOCR::extractWithTemplate($file, $templateId);

// Auto-detect template from content
$parser = app('smart-ocr.parser');
$result = $parser->parse($file, ['detect_template' => true]);

$parser = app('smart-ocr.parser');
$result = $parser->parse($file, [
    'ai_cleanup' => true,
    'document_type' => 'invoice',
]);

// config/smart-ocr.php
'privacy' => [
    'allow_external_ai' => false, // block cloud/LLM drivers
],

use LaravelSmartOCR\Testing\SmartOCRFake;
use LaravelSmartOCR\Results\OcrResult;

$fake = SmartOCR::fake();
$fake->addResult(OcrResult::fromArray([
    'text'     => 'Invoice #1234',
    'provider' => 'google',
]));

$result = SmartOCR::driver('google')->read('/path/to/invoice.pdf');
$this->assertEquals('Invoice #1234', $result->text());

$fake->assertRead('/path/to/invoice.pdf');
bash
php artisan vendor:publish --tag=smart-ocr-config
bash
composer 
bash
php artisan vendor:publish --tag=smart-ocr-migrations
php artisan migrate
bash
php artisan smart-ocr:doctor