|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +/** |
| 6 | + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors |
| 7 | + * SPDX-License-Identifier: AGPL-3.0-or-later |
| 8 | + */ |
| 9 | + |
| 10 | +namespace OCA\OpenAi\TaskProcessing; |
| 11 | + |
| 12 | +use Exception; |
| 13 | +use OCA\OpenAi\AppInfo\Application; |
| 14 | +use OCA\OpenAi\Service\OpenAiAPIService; |
| 15 | +use OCA\OpenAi\Service\OpenAiSettingsService; |
| 16 | +use OCA\OpenAi\Service\TranslationService; |
| 17 | +use OCA\OpenAi\Service\WatermarkingService; |
| 18 | +use OCP\Files\File; |
| 19 | +use OCP\IAppConfig; |
| 20 | +use OCP\IL10N; |
| 21 | +use OCP\IUserManager; |
| 22 | +use OCP\L10N\IFactory; |
| 23 | +use OCP\TaskProcessing\Exception\ProcessingException; |
| 24 | +use OCP\TaskProcessing\ISynchronousWatermarkingProvider; |
| 25 | +use OCP\TaskProcessing\ShapeEnumValue; |
| 26 | +use Psr\Log\LoggerInterface; |
| 27 | + |
| 28 | +class AudioToAudioTranslateProvider implements ISynchronousWatermarkingProvider { |
| 29 | + |
| 30 | + public function __construct( |
| 31 | + private OpenAiAPIService $openAiAPIService, |
| 32 | + private TranslationService $translationService, |
| 33 | + private OpenAiSettingsService $openAiSettingsService, |
| 34 | + private WatermarkingService $watermarkingService, |
| 35 | + private LoggerInterface $logger, |
| 36 | + private IFactory $l10nFactory, |
| 37 | + private IL10N $l, |
| 38 | + private IAppConfig $appConfig, |
| 39 | + private IUserManager $userManager, |
| 40 | + ) { |
| 41 | + } |
| 42 | + |
| 43 | + public function getId(): string { |
| 44 | + return Application::APP_ID . '-audio2audio:translate'; |
| 45 | + } |
| 46 | + |
| 47 | + public function getName(): string { |
| 48 | + return $this->openAiAPIService->getServiceName(Application::SERVICE_TYPE_STT); |
| 49 | + } |
| 50 | + |
| 51 | + public function getTaskTypeId(): string { |
| 52 | + return AudioToAudioTranslateTaskType::ID; |
| 53 | + } |
| 54 | + |
| 55 | + public function getExpectedRuntime(): int { |
| 56 | + return 60; |
| 57 | + } |
| 58 | + |
| 59 | + public function getInputShapeEnumValues(): array { |
| 60 | + $coreL = $this->l10nFactory->getLanguages(); |
| 61 | + $languages = array_merge($coreL['commonLanguages'], $coreL['otherLanguages']); |
| 62 | + $languageEnumValues = array_map(static function (array $language) { |
| 63 | + return new ShapeEnumValue($language['name'], $language['code']); |
| 64 | + }, $languages); |
| 65 | + $detectLanguageEnumValue = new ShapeEnumValue($this->l->t('Detect language'), 'detect_language'); |
| 66 | + return [ |
| 67 | + 'origin_language' => array_merge([$detectLanguageEnumValue], $languageEnumValues), |
| 68 | + 'target_language' => $languageEnumValues, |
| 69 | + ]; |
| 70 | + } |
| 71 | + |
| 72 | + public function getInputShapeDefaults(): array { |
| 73 | + return [ |
| 74 | + 'origin_language' => 'detect_language', |
| 75 | + ]; |
| 76 | + } |
| 77 | + |
| 78 | + |
| 79 | + public function getOptionalInputShape(): array { |
| 80 | + return []; |
| 81 | + } |
| 82 | + |
| 83 | + public function getOptionalInputShapeEnumValues(): array { |
| 84 | + return []; |
| 85 | + } |
| 86 | + |
| 87 | + public function getOptionalInputShapeDefaults(): array { |
| 88 | + return []; |
| 89 | + } |
| 90 | + |
| 91 | + public function getOutputShapeEnumValues(): array { |
| 92 | + return []; |
| 93 | + } |
| 94 | + |
| 95 | + public function getOptionalOutputShape(): array { |
| 96 | + return []; |
| 97 | + } |
| 98 | + |
| 99 | + public function getOptionalOutputShapeEnumValues(): array { |
| 100 | + return []; |
| 101 | + } |
| 102 | + |
| 103 | + public function process(?string $userId, array $input, callable $reportProgress, bool $includeWatermark = true): array { |
| 104 | + if (!isset($input['input']) || !$input['input'] instanceof File || !$input['input']->isReadable()) { |
| 105 | + throw new ProcessingException('Invalid input file'); |
| 106 | + } |
| 107 | + $inputFile = $input['input']; |
| 108 | + |
| 109 | + if (!isset($input['origin_language']) || !is_string($input['origin_language'])) { |
| 110 | + throw new ProcessingException('Invalid origin_language input'); |
| 111 | + } |
| 112 | + if (!isset($input['target_language']) || !is_string($input['target_language'])) { |
| 113 | + throw new ProcessingException('Invalid target_language input'); |
| 114 | + } |
| 115 | + |
| 116 | + // STT |
| 117 | + $sttModel = $this->appConfig->getValueString(Application::APP_ID, 'default_stt_model_id', Application::DEFAULT_MODEL_ID, lazy: true) ?: Application::DEFAULT_MODEL_ID; |
| 118 | + try { |
| 119 | + $transcription = $this->openAiAPIService->transcribeFile($userId, $inputFile, false, $sttModel, $input['origin_language']); |
| 120 | + } catch (Exception $e) { |
| 121 | + $this->logger->warning('Transcription failed with: ' . $e->getMessage(), ['exception' => $e]); |
| 122 | + throw new ProcessingException( |
| 123 | + 'Transcription failed with: ' . $e->getMessage(), |
| 124 | + $e->getCode(), |
| 125 | + $e, |
| 126 | + ); |
| 127 | + } |
| 128 | + |
| 129 | + $reportProgress(0.3); |
| 130 | + |
| 131 | + // translate |
| 132 | + $completionModel = $this->openAiAPIService->isUsingOpenAi() |
| 133 | + ? ($this->appConfig->getValueString(Application::APP_ID, 'default_completion_model_id', Application::DEFAULT_MODEL_ID, lazy: true) ?: Application::DEFAULT_MODEL_ID) |
| 134 | + : $this->appConfig->getValueString(Application::APP_ID, 'default_completion_model_id', lazy: true); |
| 135 | + $maxTokens = $this->openAiSettingsService->getMaxTokens(); |
| 136 | + |
| 137 | + try { |
| 138 | + $translatedText = $this->translationService->translate( |
| 139 | + $transcription, $input['origin_language'], $input['target_language'], $completionModel, $maxTokens, $userId, |
| 140 | + ); |
| 141 | + |
| 142 | + if (empty($translatedText)) { |
| 143 | + throw new ProcessingException("Empty translation result from {$input['origin_language']} to {$input['target_language']}"); |
| 144 | + } |
| 145 | + } catch (Exception $e) { |
| 146 | + throw new ProcessingException( |
| 147 | + "Failed to translate from {$input['origin_language']} to {$input['target_language']}: {$e->getMessage()}", |
| 148 | + $e->getCode(), |
| 149 | + $e, |
| 150 | + ); |
| 151 | + } |
| 152 | + |
| 153 | + $reportProgress(0.6); |
| 154 | + |
| 155 | + // TTS |
| 156 | + $ttsPrompt = $translatedText; |
| 157 | + if ($includeWatermark) { |
| 158 | + if ($userId !== null) { |
| 159 | + $user = $this->userManager->getExistingUser($userId); |
| 160 | + $lang = $this->l10nFactory->getUserLanguage($user); |
| 161 | + $l = $this->l10nFactory->get(Application::APP_ID, $lang); |
| 162 | + $ttsPrompt .= "\n\n" . $l->t('This was generated using Artificial Intelligence.'); |
| 163 | + } else { |
| 164 | + $ttsPrompt .= "\n\n" . $this->l->t('This was generated using Artificial Intelligence.'); |
| 165 | + } |
| 166 | + } |
| 167 | + $ttsModel = $this->appConfig->getValueString(Application::APP_ID, 'default_speech_model_id', Application::DEFAULT_SPEECH_MODEL_ID, lazy: true) ?: Application::DEFAULT_SPEECH_MODEL_ID; |
| 168 | + $voice = $this->appConfig->getValueString(Application::APP_ID, 'default_speech_voice', Application::DEFAULT_SPEECH_VOICE, lazy: true) ?: Application::DEFAULT_SPEECH_VOICE; |
| 169 | + $speed = 1; |
| 170 | + try { |
| 171 | + $apiResponse = $this->openAiAPIService->requestSpeechCreation($userId, $ttsPrompt, $ttsModel, $voice, $speed); |
| 172 | + |
| 173 | + if (!isset($apiResponse['body'])) { |
| 174 | + $this->logger->warning('Text to speech generation failed: no speech returned'); |
| 175 | + throw new ProcessingException('Text to speech generation failed: no speech returned'); |
| 176 | + } |
| 177 | + $translatedAudio = $includeWatermark ? $this->watermarkingService->markAudio($apiResponse['body']) : $apiResponse['body']; |
| 178 | + } catch (\Exception $e) { |
| 179 | + $this->logger->warning('Text to speech generation failed with: ' . $e->getMessage(), ['exception' => $e]); |
| 180 | + throw new ProcessingException( |
| 181 | + 'Text to speech generation failed with: ' . $e->getMessage(), |
| 182 | + $e->getCode(), |
| 183 | + $e, |
| 184 | + ); |
| 185 | + } |
| 186 | + |
| 187 | + $reportProgress(1.0); |
| 188 | + |
| 189 | + // Translation |
| 190 | + return [ |
| 191 | + 'audio_output' => $translatedAudio, |
| 192 | + 'text_output' => $translatedText, |
| 193 | + ]; |
| 194 | + } |
| 195 | +} |
0 commit comments