Manager.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2023 Marcel Klehr <mklehr@gmx.net>
  5. *
  6. * @author Marcel Klehr <mklehr@gmx.net>
  7. *
  8. * @license GNU AGPL version 3 or any later version
  9. *
  10. * This program is free software: you can redistribute it and/or modify
  11. * it under the terms of the GNU Affero General Public License as
  12. * published by the Free Software Foundation, either version 3 of the
  13. * License, or (at your option) any later version.
  14. *
  15. * This program is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU Affero General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU Affero General Public License
  21. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. */
  23. namespace OC\TextToImage;
  24. use OC\AppFramework\Bootstrap\Coordinator;
  25. use OC\TextToImage\Db\Task as DbTask;
  26. use OC\TextToImage\Db\TaskMapper;
  27. use OCP\AppFramework\Db\DoesNotExistException;
  28. use OCP\AppFramework\Db\MultipleObjectsReturnedException;
  29. use OCP\BackgroundJob\IJobList;
  30. use OCP\DB\Exception;
  31. use OCP\Files\AppData\IAppDataFactory;
  32. use OCP\Files\IAppData;
  33. use OCP\Files\NotFoundException;
  34. use OCP\Files\NotPermittedException;
  35. use OCP\IConfig;
  36. use OCP\IServerContainer;
  37. use OCP\PreConditionNotMetException;
  38. use OCP\TextToImage\Exception\TaskFailureException;
  39. use OCP\TextToImage\Exception\TaskNotFoundException;
  40. use OCP\TextToImage\IManager;
  41. use OCP\TextToImage\IProvider;
  42. use OCP\TextToImage\Task;
  43. use Psr\Log\LoggerInterface;
  44. use RuntimeException;
  45. use Throwable;
  46. class Manager implements IManager {
  47. /** @var ?list<IProvider> */
  48. private ?array $providers = null;
  49. private IAppData $appData;
  50. public function __construct(
  51. private IServerContainer $serverContainer,
  52. private Coordinator $coordinator,
  53. private LoggerInterface $logger,
  54. private IJobList $jobList,
  55. private TaskMapper $taskMapper,
  56. private IConfig $config,
  57. IAppDataFactory $appDataFactory,
  58. ) {
  59. $this->appData = $appDataFactory->get('core');
  60. }
  61. /**
  62. * @inheritDoc
  63. */
  64. public function getProviders(): array {
  65. $context = $this->coordinator->getRegistrationContext();
  66. if ($context === null) {
  67. return [];
  68. }
  69. if ($this->providers !== null) {
  70. return $this->providers;
  71. }
  72. $this->providers = [];
  73. foreach ($context->getTextToImageProviders() as $providerServiceRegistration) {
  74. $class = $providerServiceRegistration->getService();
  75. try {
  76. /** @var IProvider $provider */
  77. $provider = $this->serverContainer->get($class);
  78. $this->providers[] = $provider;
  79. } catch (Throwable $e) {
  80. $this->logger->error('Failed to load Text to image provider ' . $class, [
  81. 'exception' => $e,
  82. ]);
  83. }
  84. }
  85. return $this->providers;
  86. }
  87. /**
  88. * @inheritDoc
  89. */
  90. public function hasProviders(): bool {
  91. $context = $this->coordinator->getRegistrationContext();
  92. if ($context === null) {
  93. return false;
  94. }
  95. return count($context->getTextToImageProviders()) > 0;
  96. }
  97. /**
  98. * @inheritDoc
  99. */
  100. public function runTask(Task $task): void {
  101. $this->logger->debug('Running TextToImage Task');
  102. if (!$this->hasProviders()) {
  103. throw new PreConditionNotMetException('No text to image provider is installed that can handle this task');
  104. }
  105. $providers = $this->getPreferredProviders();
  106. foreach ($providers as $provider) {
  107. $this->logger->debug('Trying to run Text2Image provider '.$provider::class);
  108. try {
  109. $task->setStatus(Task::STATUS_RUNNING);
  110. $completionExpectedAt = new \DateTime('now');
  111. $completionExpectedAt->add(new \DateInterval('PT'.$provider->getExpectedRuntime().'S'));
  112. $task->setCompletionExpectedAt($completionExpectedAt);
  113. if ($task->getId() === null) {
  114. $this->logger->debug('Inserting Text2Image task into DB');
  115. $taskEntity = $this->taskMapper->insert(DbTask::fromPublicTask($task));
  116. $task->setId($taskEntity->getId());
  117. } else {
  118. $this->logger->debug('Updating Text2Image task in DB');
  119. $this->taskMapper->update(DbTask::fromPublicTask($task));
  120. }
  121. try {
  122. $folder = $this->appData->getFolder('text2image');
  123. } catch(NotFoundException) {
  124. $this->logger->debug('Creating folder in appdata for Text2Image results');
  125. $folder = $this->appData->newFolder('text2image');
  126. }
  127. try {
  128. $folder = $folder->getFolder((string) $task->getId());
  129. } catch(NotFoundException) {
  130. $this->logger->debug('Creating new folder in appdata Text2Image results folder');
  131. $folder = $folder->newFolder((string) $task->getId());
  132. }
  133. $this->logger->debug('Creating result files for Text2Image task');
  134. $resources = [];
  135. $files = [];
  136. for ($i = 0; $i < $task->getNumberOfImages(); $i++) {
  137. $file = $folder->newFile((string) $i);
  138. $files[] = $file;
  139. $resource = $file->write();
  140. if ($resource !== false && $resource !== true && is_resource($resource)) {
  141. $resources[] = $resource;
  142. } else {
  143. throw new RuntimeException('Text2Image generation using provider "' . $provider->getName() . '" failed: Couldn\'t open file to write.');
  144. }
  145. }
  146. $this->logger->debug('Calling Text2Image provider\'s generate method');
  147. $provider->generate($task->getInput(), $resources);
  148. for ($i = 0; $i < $task->getNumberOfImages(); $i++) {
  149. if (is_resource($resources[$i])) {
  150. // If $resource hasn't been closed yet, we'll do that here
  151. fclose($resources[$i]);
  152. }
  153. }
  154. $task->setStatus(Task::STATUS_SUCCESSFUL);
  155. $this->logger->debug('Updating Text2Image task in DB');
  156. $this->taskMapper->update(DbTask::fromPublicTask($task));
  157. return;
  158. } catch (\RuntimeException|\Throwable $e) {
  159. for ($i = 0; $i < $task->getNumberOfImages(); $i++) {
  160. if (isset($files, $files[$i])) {
  161. try {
  162. $files[$i]->delete();
  163. } catch(NotPermittedException $e) {
  164. $this->logger->warning('Failed to clean up Text2Image result file after error', ['exception' => $e]);
  165. }
  166. }
  167. }
  168. $this->logger->info('Text2Image generation using provider "' . $provider->getName() . '" failed', ['exception' => $e]);
  169. $task->setStatus(Task::STATUS_FAILED);
  170. try {
  171. $this->taskMapper->update(DbTask::fromPublicTask($task));
  172. } catch (Exception $e) {
  173. $this->logger->warning('Failed to update database after Text2Image error', ['exception' => $e]);
  174. }
  175. throw new TaskFailureException('Text2Image generation using provider "' . $provider->getName() . '" failed: ' . $e->getMessage(), 0, $e);
  176. }
  177. }
  178. $task->setStatus(Task::STATUS_FAILED);
  179. try {
  180. $this->taskMapper->update(DbTask::fromPublicTask($task));
  181. } catch (Exception $e) {
  182. $this->logger->warning('Failed to update database after Text2Image error', ['exception' => $e]);
  183. }
  184. throw new TaskFailureException('Could not run task');
  185. }
  186. /**
  187. * @inheritDoc
  188. */
  189. public function scheduleTask(Task $task): void {
  190. if (!$this->hasProviders()) {
  191. throw new PreConditionNotMetException('No text to image provider is installed that can handle this task');
  192. }
  193. $this->logger->debug('Scheduling Text2Image Task');
  194. $task->setStatus(Task::STATUS_SCHEDULED);
  195. $completionExpectedAt = new \DateTime('now');
  196. $completionExpectedAt->add(new \DateInterval('PT'.$this->getPreferredProviders()[0]->getExpectedRuntime().'S'));
  197. $task->setCompletionExpectedAt($completionExpectedAt);
  198. $taskEntity = DbTask::fromPublicTask($task);
  199. $this->taskMapper->insert($taskEntity);
  200. $task->setId($taskEntity->getId());
  201. $this->jobList->add(TaskBackgroundJob::class, [
  202. 'taskId' => $task->getId()
  203. ]);
  204. }
  205. /**
  206. * @inheritDoc
  207. */
  208. public function runOrScheduleTask(Task $task) : void {
  209. if (!$this->hasProviders()) {
  210. throw new PreConditionNotMetException('No text to image provider is installed that can handle this task');
  211. }
  212. $providers = $this->getPreferredProviders();
  213. $maxExecutionTime = (int) ini_get('max_execution_time');
  214. // Offload the task to a background job if the expected runtime of the likely provider is longer than 80% of our max execution time
  215. if ($providers[0]->getExpectedRuntime() > $maxExecutionTime * 0.8) {
  216. $this->scheduleTask($task);
  217. return;
  218. }
  219. $this->runTask($task);
  220. }
  221. /**
  222. * @inheritDoc
  223. */
  224. public function deleteTask(Task $task): void {
  225. $taskEntity = DbTask::fromPublicTask($task);
  226. $this->taskMapper->delete($taskEntity);
  227. $this->jobList->remove(TaskBackgroundJob::class, [
  228. 'taskId' => $task->getId()
  229. ]);
  230. }
  231. /**
  232. * Get a task from its id
  233. *
  234. * @param int $id The id of the task
  235. * @return Task
  236. * @throws RuntimeException If the query failed
  237. * @throws TaskNotFoundException If the task could not be found
  238. */
  239. public function getTask(int $id): Task {
  240. try {
  241. $taskEntity = $this->taskMapper->find($id);
  242. return $taskEntity->toPublicTask();
  243. } catch (DoesNotExistException $e) {
  244. throw new TaskNotFoundException('Could not find task with the provided id');
  245. } catch (MultipleObjectsReturnedException $e) {
  246. throw new RuntimeException('Could not uniquely identify task with given id', 0, $e);
  247. } catch (Exception $e) {
  248. throw new RuntimeException('Failure while trying to find task by id: ' . $e->getMessage(), 0, $e);
  249. }
  250. }
  251. /**
  252. * Get a task from its user id and task id
  253. * If userId is null, this can only get a task that was scheduled anonymously
  254. *
  255. * @param int $id The id of the task
  256. * @param string|null $userId The user id that scheduled the task
  257. * @return Task
  258. * @throws RuntimeException If the query failed
  259. * @throws TaskNotFoundException If the task could not be found
  260. */
  261. public function getUserTask(int $id, ?string $userId): Task {
  262. try {
  263. $taskEntity = $this->taskMapper->findByIdAndUser($id, $userId);
  264. return $taskEntity->toPublicTask();
  265. } catch (DoesNotExistException $e) {
  266. throw new TaskNotFoundException('Could not find task with the provided id and user id');
  267. } catch (MultipleObjectsReturnedException $e) {
  268. throw new RuntimeException('Could not uniquely identify task with given id and user id', 0, $e);
  269. } catch (Exception $e) {
  270. throw new RuntimeException('Failure while trying to find task by id and user id: ' . $e->getMessage(), 0, $e);
  271. }
  272. }
  273. /**
  274. * Get a list of tasks scheduled by a specific user for a specific app
  275. * and optionally with a specific identifier.
  276. * This cannot be used to get anonymously scheduled tasks
  277. *
  278. * @param string $userId
  279. * @param string $appId
  280. * @param string|null $identifier
  281. * @return Task[]
  282. * @throws RuntimeException
  283. */
  284. public function getUserTasksByApp(?string $userId, string $appId, ?string $identifier = null): array {
  285. try {
  286. $taskEntities = $this->taskMapper->findUserTasksByApp($userId, $appId, $identifier);
  287. return array_map(static function (DbTask $taskEntity) {
  288. return $taskEntity->toPublicTask();
  289. }, $taskEntities);
  290. } catch (Exception $e) {
  291. throw new RuntimeException('Failure while trying to find tasks by appId and identifier: ' . $e->getMessage(), 0, $e);
  292. }
  293. }
  294. /**
  295. * @return list<IProvider>
  296. */
  297. private function getPreferredProviders() {
  298. $providers = $this->getProviders();
  299. $json = $this->config->getAppValue('core', 'ai.text2image_provider', '');
  300. if ($json !== '') {
  301. try {
  302. $id = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
  303. $provider = current(array_filter($providers, fn ($provider) => $provider->getId() === $id));
  304. if ($provider !== false && $provider !== null) {
  305. $providers = [$provider];
  306. }
  307. } catch (\JsonException $e) {
  308. $this->logger->warning('Failed to decode Text2Image setting `ai.text2image_provider`', ['exception' => $e]);
  309. }
  310. }
  311. return $providers;
  312. }
  313. }