TranscriptionJob.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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\SpeechToText;
  8. use OC\User\NoUserException;
  9. use OCP\AppFramework\Utility\ITimeFactory;
  10. use OCP\BackgroundJob\QueuedJob;
  11. use OCP\EventDispatcher\IEventDispatcher;
  12. use OCP\Files\File;
  13. use OCP\Files\IRootFolder;
  14. use OCP\Files\NotFoundException;
  15. use OCP\Files\NotPermittedException;
  16. use OCP\PreConditionNotMetException;
  17. use OCP\SpeechToText\Events\TranscriptionFailedEvent;
  18. use OCP\SpeechToText\Events\TranscriptionSuccessfulEvent;
  19. use OCP\SpeechToText\ISpeechToTextManager;
  20. use Psr\Log\LoggerInterface;
  21. class TranscriptionJob extends QueuedJob {
  22. public function __construct(
  23. ITimeFactory $timeFactory,
  24. private ISpeechToTextManager $speechToTextManager,
  25. private IEventDispatcher $eventDispatcher,
  26. private IRootFolder $rootFolder,
  27. private LoggerInterface $logger,
  28. ) {
  29. parent::__construct($timeFactory);
  30. $this->setAllowParallelRuns(false);
  31. }
  32. /**
  33. * @inheritDoc
  34. */
  35. protected function run($argument) {
  36. $fileId = $argument['fileId'];
  37. $owner = $argument['owner'];
  38. $userId = $argument['userId'];
  39. $appId = $argument['appId'];
  40. $file = null;
  41. try {
  42. \OC_Util::setupFS($owner);
  43. $userFolder = $this->rootFolder->getUserFolder($owner);
  44. $file = $userFolder->getFirstNodeById($fileId);
  45. if (!($file instanceof File)) {
  46. $this->logger->warning('Transcription of file ' . $fileId . ' failed. The file could not be found');
  47. $this->eventDispatcher->dispatchTyped(
  48. new TranscriptionFailedEvent(
  49. $fileId,
  50. null,
  51. 'File not found',
  52. $userId,
  53. $appId,
  54. )
  55. );
  56. return;
  57. }
  58. $result = $this->speechToTextManager->transcribeFile($file);
  59. $this->eventDispatcher->dispatchTyped(
  60. new TranscriptionSuccessfulEvent(
  61. $fileId,
  62. $file,
  63. $result,
  64. $userId,
  65. $appId,
  66. )
  67. );
  68. } catch (PreConditionNotMetException|\RuntimeException|\InvalidArgumentException|NotFoundException|NotPermittedException|NoUserException $e) {
  69. $this->logger->warning('Transcription of file ' . $fileId . ' failed', ['exception' => $e]);
  70. $this->eventDispatcher->dispatchTyped(
  71. new TranscriptionFailedEvent(
  72. $fileId,
  73. $file,
  74. $e->getMessage(),
  75. $userId,
  76. $appId,
  77. )
  78. );
  79. }
  80. }
  81. }