Case 1. Automatic contract parsing (Legal / CRM)

In this case we extract key entities from a legal contract: parties, dates, locations, and monetary values. Choose one of two implementation variants below.

Token-classification pipeline for legal contract parsing

Install package: composer require codewithkyrian/transformers. This variant uses Xenova/bert-base-NER via TransformersPHP and runs NER over contract text.

 
<?php

use Codewithkyrian\Transformers\Transformers;

use function 
Codewithkyrian\Transformers\Pipelines\pipeline;

$text = <<<'TEXT'
This Agreement is made on March 12, 2025 between Apple Inc. and John Smith.
Apple Inc. agrees to provide software development services to the client.
The total amount of the agreement is $3,000,000.
The services will be delivered in London, United Kingdom.
The contract duration starts on March 12, 2025 and expires on March 12, 2027.

The agreement was approved by Michael Brown,
Legal Director of Apple Inc.
TEXT;

$entities = [];
$nerError null;

try {
    if (!
class_exists(Transformers::class) || !function_exists('Codewithkyrian\\Transformers\\Pipelines\\pipeline')) {
        throw new 
RuntimeException('TransformersPHP is not available. Run composer install.');
    }

    
$pipeline pipeline(task'token-classification'modelName'Xenova/bert-base-NER');
    
$entities $pipeline($text);
} catch (
Throwable $e) {
    
$nerError $e->getMessage();
}

Entity extraction with Mitie\NER and local model

Install package: composer require ankane/mitie-php. This variant runs local NER with MITIE and extracts contract entities from a longer legal text.

 
<?php

use Mitie\NER;

$text = <<<'TEXT'
This Agreement is made on March 12, 2025 between Apple Inc. and John Smith.
Apple Inc. agrees to provide software development services to the client.
The total amount of the agreement is $3,000,000.
The services will be delivered in London, United Kingdom.
The contract duration starts on March 12, 2025 and expires on March 12, 2027.

The agreement was approved by Michael Brown,
Legal Director of Apple Inc.
TEXT;

$modelPath '.mitie/ner_model.dat';
$entities = [];
$nerError null;

try {
    if (!
class_exists(NER::class)) {
        throw new 
RuntimeException('Class Mitie\\NER is not available. Run composer install.');
    }

    if (!
extension_loaded('ffi')) {
        throw new 
RuntimeException('PHP extension ffi is disabled.');
    }

    if (!
is_file($modelPath)) {
        throw new 
RuntimeException('MITIE model file not found: ' $modelPath);
    }

    
$ner = new NER($modelPath);
    
$entities $ner->entities($text);
} catch (
Throwable $e) {
    
$nerError $e->getMessage();
}