TranslationManager.php 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OC\Translation;
  8. use InvalidArgumentException;
  9. use OC\AppFramework\Bootstrap\Coordinator;
  10. use OCP\IConfig;
  11. use OCP\IServerContainer;
  12. use OCP\IUserSession;
  13. use OCP\PreConditionNotMetException;
  14. use OCP\Translation\CouldNotTranslateException;
  15. use OCP\Translation\IDetectLanguageProvider;
  16. use OCP\Translation\ITranslationManager;
  17. use OCP\Translation\ITranslationProvider;
  18. use OCP\Translation\ITranslationProviderWithId;
  19. use OCP\Translation\ITranslationProviderWithUserId;
  20. use Psr\Container\ContainerExceptionInterface;
  21. use Psr\Container\NotFoundExceptionInterface;
  22. use Psr\Log\LoggerInterface;
  23. use RuntimeException;
  24. use Throwable;
  25. class TranslationManager implements ITranslationManager {
  26. /** @var ?ITranslationProvider[] */
  27. private ?array $providers = null;
  28. public function __construct(
  29. private IServerContainer $serverContainer,
  30. private Coordinator $coordinator,
  31. private LoggerInterface $logger,
  32. private IConfig $config,
  33. private IUserSession $userSession,
  34. ) {
  35. }
  36. public function getLanguages(): array {
  37. $languages = [];
  38. foreach ($this->getProviders() as $provider) {
  39. $languages = array_merge($languages, $provider->getAvailableLanguages());
  40. }
  41. return $languages;
  42. }
  43. public function translate(string $text, ?string &$fromLanguage, string $toLanguage): string {
  44. if (!$this->hasProviders()) {
  45. throw new PreConditionNotMetException('No translation providers available');
  46. }
  47. $providers = $this->getProviders();
  48. $json = $this->config->getAppValue('core', 'ai.translation_provider_preferences', '');
  49. if ($json !== '') {
  50. $precedence = json_decode($json, true);
  51. $newProviders = [];
  52. foreach ($precedence as $className) {
  53. $provider = current(array_filter($providers, function ($provider) use ($className) {
  54. return $provider instanceof ITranslationProviderWithId ? $provider->getId() === $className : $provider::class === $className;
  55. }));
  56. if ($provider !== false) {
  57. $newProviders[] = $provider;
  58. }
  59. }
  60. // Add all providers that haven't been added so far
  61. $newProviders += array_udiff($providers, $newProviders, function ($a, $b) {
  62. return ($a instanceof ITranslationProviderWithId ? $a->getId() : $a::class) <=> ($b instanceof ITranslationProviderWithId ? $b->getId() : $b::class);
  63. });
  64. $providers = $newProviders;
  65. }
  66. if ($fromLanguage === null) {
  67. foreach ($providers as $provider) {
  68. if ($provider instanceof IDetectLanguageProvider) {
  69. if ($provider instanceof ITranslationProviderWithUserId) {
  70. $provider->setUserId($this->userSession->getUser()?->getUID());
  71. }
  72. $fromLanguage = $provider->detectLanguage($text);
  73. }
  74. if ($fromLanguage !== null) {
  75. break;
  76. }
  77. }
  78. if ($fromLanguage === null) {
  79. throw new InvalidArgumentException('Could not detect language');
  80. }
  81. }
  82. if ($fromLanguage === $toLanguage) {
  83. return $text;
  84. }
  85. foreach ($providers as $provider) {
  86. try {
  87. if ($provider instanceof ITranslationProviderWithUserId) {
  88. $provider->setUserId($this->userSession->getUser()?->getUID());
  89. }
  90. return $provider->translate($fromLanguage, $toLanguage, $text);
  91. } catch (RuntimeException $e) {
  92. $this->logger->warning("Failed to translate from {$fromLanguage} to {$toLanguage} using provider {$provider->getName()}", ['exception' => $e]);
  93. }
  94. }
  95. throw new CouldNotTranslateException($fromLanguage);
  96. }
  97. public function getProviders(): array {
  98. $context = $this->coordinator->getRegistrationContext();
  99. if ($this->providers !== null) {
  100. return $this->providers;
  101. }
  102. $this->providers = [];
  103. foreach ($context->getTranslationProviders() as $providerRegistration) {
  104. $class = $providerRegistration->getService();
  105. try {
  106. $this->providers[$class] = $this->serverContainer->get($class);
  107. } catch (NotFoundExceptionInterface|ContainerExceptionInterface|Throwable $e) {
  108. $this->logger->error('Failed to load translation provider ' . $class, [
  109. 'exception' => $e
  110. ]);
  111. }
  112. }
  113. return $this->providers;
  114. }
  115. public function hasProviders(): bool {
  116. $context = $this->coordinator->getRegistrationContext();
  117. return !empty($context->getTranslationProviders());
  118. }
  119. public function canDetectLanguage(): bool {
  120. foreach ($this->getProviders() as $provider) {
  121. if ($provider instanceof IDetectLanguageProvider) {
  122. return true;
  123. }
  124. }
  125. return false;
  126. }
  127. }