univ-pau-ics/build/service/Tesseract.php

86 lines
2.2 KiB
PHP
Executable File

<?php
namespace service;
class Tesseract{
/* [1] Attributes
=========================================================*/
private $fname = null;
/* (1) Constructs and initialise a readed file
*
* @fname<String> Path of the image
*
* @return instance<Tesseract> New Tesseract
*
---------------------------------------------------------*/
public function __construct($fname=null){
/* [1] Check argument
=========================================================*/ {
/* (1) Check type */
if( !is_string($fname) )
throw new \Exception("Tesseract.__construct(<String>) expected but Tesseract.__construct(<".gettype($fname).">) received");
/* (2) Check file validity */
if( !file_exists($fname) )
throw new \Exception("Tesseract.__construct(<PATH>) but <PATH> is not valid");
}
/* [2] Store as attribute
=========================================================*/
$this->fname = $fname;
}
/* (2) Read the image file
*
* @return read<String> The read content
*
---------------------------------------------------------*/
public function read(){
/* [1] Record the text from the image
=========================================================*/
/* (1) Process tesseract */
$read = shell_exec("tesseract ".$this->fname." stdout -l fra --user-words ".__ROOT__."/config/edt.user-words -c language_model_penalty_non_freq_dict_word=0.1 -c language_model_penalty_non_dict_word=.15 -c tessedit_char_whitelist=abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 2>/dev/null");
/* (2) If empty */
if( is_null($read) )
throw new \Exception("Nothing read");
/* (3) Split by lines */
$by_line = explode("\n", $read);
/* (4) Get first line (title) */
$title = $by_line[0];
/* (5) Get last non-empty line */
for( $i = count($by_line)-1 ; $i > 0 ; $i-- ){
// {1} Check not empty //
if( empty($by_line[$i]) )
continue;
// {2} Matches //
if( preg_match('@^amphi@i', $by_line[$i]) || // 'amphi A', 'amphi 600 droit'
preg_match('@^S\d+@i', $by_line[$i]) // 'S10', 'S22'
)
return [ $title, $by_line[$i] ];
}
return [ $title, 'unknown' ];
}
}