1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace LeKoala\Multilingual; |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* A simple helper to help translating strings |
7
|
|
|
* @link https://github.com/UKPLab/EasyNMT/tree/main/docker |
8
|
|
|
*/ |
9
|
|
|
class EasyNmtHelper |
10
|
|
|
{ |
11
|
|
|
public static $baseUrl = 'http://localhost:24080/translate'; |
12
|
|
|
public static $defaultLanguage = 'en'; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* Translate from provider |
16
|
|
|
* |
17
|
|
|
* @param string $sourceText |
18
|
|
|
* @param string $targetLang |
19
|
|
|
* @param string $sourceLang |
20
|
|
|
* @return string |
21
|
|
|
*/ |
22
|
|
|
public static function translate($sourceText, $targetLang = null, $sourceLang = null) |
|
|
|
|
23
|
|
|
{ |
24
|
|
|
$src_lang = self::$defaultLanguage; |
25
|
|
|
if ($targetLang == $src_lang) { |
26
|
|
|
return $sourceText; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
$orgText = $sourceText; |
30
|
|
|
$containsVar = str_contains($sourceText, '{'); |
31
|
|
|
|
32
|
|
|
$extractedVars = []; |
33
|
|
|
if ($containsVar) { |
34
|
|
|
$matches = []; |
35
|
|
|
preg_match_all('/(\{[\w_]*?\})/', $sourceText, $matches); |
36
|
|
|
$extractedVars = $matches[0] ?? []; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
// use en as intermediate language |
40
|
|
|
if ($targetLang != 'en') { |
41
|
|
|
$params2 = [ |
42
|
|
|
'target_lang' => 'en', |
43
|
|
|
'text' => $sourceText |
44
|
|
|
]; |
45
|
|
|
$url = self::$baseUrl . '?' . http_build_query($params2); |
46
|
|
|
$result = @file_get_contents($url); |
47
|
|
|
if ($result) { |
48
|
|
|
$jsonData = json_decode($result, 1); |
49
|
|
|
if ($jsonData) { |
50
|
|
|
$sourceText = $jsonData['translated'][0] ?? $sourceText; |
51
|
|
|
} |
52
|
|
|
} |
53
|
|
|
$src_lang = 'en'; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
$params = [ |
57
|
|
|
'target_lang' => $targetLang, |
58
|
|
|
'text' => $sourceText, |
59
|
|
|
'source_lang' => $src_lang, |
60
|
|
|
]; |
61
|
|
|
|
62
|
|
|
$url = 'http://localhost:24080/translate?' . http_build_query($params); |
63
|
|
|
$result = @file_get_contents($url); |
64
|
|
|
if ($result) { |
65
|
|
|
$jsonData = json_decode($result, 1); |
66
|
|
|
if ($jsonData) { |
67
|
|
|
$sourceText = $jsonData['translated'][0] ?? $sourceText; |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
// It has replaced all the {}, not good! |
72
|
|
|
if ($containsVar && !str_contains($sourceText, '{')) { |
73
|
|
|
return $orgText; |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
// Make sure we keep placeholders |
77
|
|
|
if ($containsVar) { |
78
|
|
|
preg_match_all('/(\{[\w_]*?\})/', $sourceText, $matches); |
79
|
|
|
$newVars = $matches[0] ?? []; |
80
|
|
|
foreach ($newVars as $idx => $v) { |
81
|
|
|
$sourceText = str_replace($v, $extractedVars[$idx], $sourceText); |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
|
85
|
|
|
return $sourceText; |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
|
This check looks for parameters that have been defined for a function or method, but which are not used in the method body.