Translate.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. namespace crmeb\utils;
  3. use crmeb\exceptions\ApiException;
  4. use Volc\Base\V4Curl;
  5. /**
  6. * 机器翻译
  7. */
  8. class Translate extends V4Curl
  9. {
  10. protected $apiList = [
  11. "LangDetect" => [
  12. "url" => "/",
  13. "method" => "post",
  14. "config" => [
  15. "query" => [
  16. "Action" => "LangDetect",
  17. "Version" => "2020-06-01",
  18. ],
  19. ],
  20. ],
  21. "TranslateText" => [
  22. "url" => "/",
  23. "method" => "post",
  24. "config" => [
  25. "query" => [
  26. "Action" => "TranslateText",
  27. "Version" => "2020-06-01",
  28. ],
  29. ],
  30. ],
  31. ];
  32. protected function getConfig(string $region)
  33. {
  34. return [
  35. "host" => "https://open.volcengineapi.com",
  36. "config" => [
  37. "timeout" => 5.0,
  38. "headers" => [
  39. "Accept" => "application/json"
  40. ],
  41. "v4_credentials" => [
  42. "region" => "cn-north-1",
  43. "service" => "translate",
  44. ],
  45. ],
  46. ];
  47. }
  48. public function langDetect(array $textList): array
  49. {
  50. $req = array('TextList' => $textList);
  51. try {
  52. $resp = $this->request('LangDetect', ['json' => $req]);
  53. } catch (\Throwable $e) {
  54. throw $e;
  55. }
  56. if ($resp->getStatusCode() != 200) {
  57. throw new ApiException("failed to detect language: status_code=%d, resp=%s", $resp->getStatusCode(), $resp->getBody());
  58. }
  59. return json_decode($resp->getBody()->getContents(), true)["DetectedLanguageList"];
  60. }
  61. public function translateText(string $sourceLanguage, string $targetLanguage, array $textList): array
  62. {
  63. $req = array('SourceLanguage' => $sourceLanguage, 'TargetLanguage' => $targetLanguage, 'TextList' => $textList);
  64. try {
  65. $resp = $this->request('TranslateText', ['json' => $req]);
  66. } catch (\Throwable $e) {
  67. throw $e;
  68. }
  69. if ($resp->getStatusCode() != 200) {
  70. throw new ApiException("failed to translate: status_code=%d, resp=%s", $resp->getStatusCode(), $resp->getBody());
  71. }
  72. $result = json_decode($resp->getBody()->getContents(), true);
  73. if (isset($result["TranslationList"])) {
  74. return $result["TranslationList"];
  75. } else {
  76. throw new ApiException("failed to translate: " . $result["ResponseMetadata"]['Error']['Message']);
  77. }
  78. }
  79. }