-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathTextCategorizer.php
60 lines (50 loc) · 1.61 KB
/
TextCategorizer.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<?php
namespace Mitie;
class TextCategorizer
{
private $ffi;
private $pointer;
public function __construct($path = null, $pointer = null)
{
$this->ffi = FFI::instance();
if (!is_null($path)) {
if (!file_exists($path)) {
throw new \InvalidArgumentException('File does not exist');
}
$this->pointer = $this->ffi->mitie_load_text_categorizer($path);
} elseif (!is_null($pointer)) {
$this->pointer = $pointer;
} else {
throw new \InvalidArgumentException('Must pass either a path or a pointer');
}
}
public function __destruct()
{
$this->ffi->mitie_free($this->pointer);
}
public function categorize($text)
{
try {
// TODO support tokens
$tokensPtr = $this->ffi->mitie_tokenize($text);
$textTag = $this->ffi->new('char*');
$textScore = $this->ffi->new('double');
if ($this->ffi->mitie_categorize_text($this->pointer, $tokensPtr, \FFI::addr($textTag), \FFI::addr($textScore)) != 0) {
throw new Exception('Unable to categorize');
}
return [
'tag' => \FFI::string($textTag),
'score' => $textScore->cdata
];
} finally {
FFI::mitie_free($tokensPtr);
FFI::mitie_free($textTag);
}
}
public function saveToDisk($filename)
{
if ($this->ffi->mitie_save_text_categorizer($filename, $this->pointer) != 0) {
throw new Exception('Unable to save model');
}
}
}