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
|
|
|
// use en as intermediate language |
33
|
|
|
if ($targetLang != 'en') { |
34
|
|
|
$params2 = [ |
35
|
|
|
'target_lang' => 'en', |
36
|
|
|
'text' => $sourceText |
37
|
|
|
]; |
38
|
|
|
$url = self::$baseUrl . '?' . http_build_query($params2); |
39
|
|
|
$result = @file_get_contents($url); |
40
|
|
|
if ($result) { |
41
|
|
|
$jsonData = json_decode($result, 1); |
42
|
|
|
if ($jsonData) { |
43
|
|
|
$sourceText = $jsonData['translated'][0] ?? $sourceText; |
44
|
|
|
} |
45
|
|
|
} |
46
|
|
|
$src_lang = 'en'; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
$params = [ |
50
|
|
|
'target_lang' => $targetLang, |
51
|
|
|
'text' => $sourceText, |
52
|
|
|
'source_lang' => $src_lang, |
53
|
|
|
]; |
54
|
|
|
|
55
|
|
|
$url = 'http://localhost:24080/translate?' . http_build_query($params); |
56
|
|
|
$result = @file_get_contents($url); |
57
|
|
|
if ($result) { |
58
|
|
|
$jsonData = json_decode($result, 1); |
59
|
|
|
if ($jsonData) { |
60
|
|
|
$sourceText = $jsonData['translated'][0] ?? $sourceText; |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
if ($containsVar && !str_contains($sourceText, '{')) { |
65
|
|
|
return $orgText; |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
return $sourceText; |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|
This check looks for parameters that have been defined for a function or method, but which are not used in the method body.