Manager.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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 ?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. * @inerhitDocs
  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. $this->providers[$class] = $this->serverContainer->get($class);
  77. } catch (Throwable $e) {
  78. $this->logger->error('Failed to load Text to image provider ' . $class, [
  79. 'exception' => $e,
  80. ]);
  81. }
  82. }
  83. return $this->providers;
  84. }
  85. /**
  86. * @inheritDoc
  87. */
  88. public function hasProviders(): bool {
  89. $context = $this->coordinator->getRegistrationContext();
  90. if ($context === null) {
  91. return false;
  92. }
  93. return count($context->getTextToImageProviders()) > 0;
  94. }
  95. /**
  96. * @inheritDoc
  97. */
  98. public function runTask(Task $task): void {
  99. $this->logger->debug('Running TextToImage Task');
  100. if (!$this->hasProviders()) {
  101. throw new PreConditionNotMetException('No text to image provider is installed that can handle this task');
  102. }
  103. $providers = $this->getPreferredProviders();
  104. foreach ($providers as $provider) {
  105. $this->logger->debug('Trying to run Text2Image provider '.$provider::class);
  106. try {
  107. $task->setStatus(Task::STATUS_RUNNING);
  108. $completionExpectedAt = new \DateTime('now');
  109. $completionExpectedAt->add(new \DateInterval('PT'.$provider->getExpectedRuntime().'S'));
  110. $task->setCompletionExpectedAt($completionExpectedAt);
  111. if ($task->getId() === null) {
  112. $this->logger->debug('Inserting Text2Image task into DB');
  113. $taskEntity = $this->taskMapper->insert(DbTask::fromPublicTask($task));
  114. $task->setId($taskEntity->getId());
  115. } else {
  116. $this->logger->debug('Updating Text2Image task in DB');
  117. $this->taskMapper->update(DbTask::fromPublicTask($task));
  118. }
  119. try {
  120. $folder = $this->appData->getFolder('text2image');
  121. } catch(NotFoundException) {
  122. $this->logger->debug('Creating folder in appdata for Text2Image results');
  123. $folder = $this->appData->newFolder('text2image');
  124. }
  125. try {
  126. $folder = $folder->getFolder((string) $task->getId());
  127. } catch(NotFoundException) {
  128. $this->logger->debug('Creating new folder in appdata Text2Image results folder');
  129. $folder = $folder->newFolder((string) $task->getId());
  130. }
  131. $this->logger->debug('Creating result files for Text2Image task');
  132. $resources = [];
  133. $files = [];
  134. for ($i = 0; $i < $task->getNumberOfImages(); $i++) {
  135. $file = $folder->newFile((string) $i);
  136. $files[] = $file;
  137. $resource = $file->write();
  138. if ($resource !== false && $resource !== true && is_resource($resource)) {
  139. $resources[] = $resource;
  140. } else {
  141. throw new RuntimeException('Text2Image generation using provider "' . $provider->getName() . '" failed: Couldn\'t open file to write.');
  142. }
  143. }
  144. $this->logger->debug('Calling Text2Image provider\'s generate method');
  145. $provider->generate($task->getInput(), $resources);
  146. for ($i = 0; $i < $task->getNumberOfImages(); $i++) {
  147. if (is_resource($resources[$i])) {
  148. // If $resource hasn't been closed yet, we'll do that here
  149. fclose($resources[$i]);
  150. }
  151. }
  152. $task->setStatus(Task::STATUS_SUCCESSFUL);
  153. $this->logger->debug('Updating Text2Image task in DB');
  154. $this->taskMapper->update(DbTask::fromPublicTask($task));
  155. return;
  156. } catch (\RuntimeException|\Throwable $e) {
  157. for ($i = 0; $i < $task->getNumberOfImages(); $i++) {
  158. if (isset($files, $files[$i])) {
  159. try {
  160. $files[$i]->delete();
  161. } catch(NotPermittedException $e) {
  162. $this->logger->warning('Failed to clean up Text2Image result file after error', ['exception' => $e]);
  163. }
  164. }
  165. }
  166. $this->logger->info('Text2Image generation using provider "' . $provider->getName() . '" failed', ['exception' => $e]);
  167. $task->setStatus(Task::STATUS_FAILED);
  168. try {
  169. $this->taskMapper->update(DbTask::fromPublicTask($task));
  170. } catch (Exception $e) {
  171. $this->logger->warning('Failed to update database after Text2Image error', ['exception' => $e]);
  172. }
  173. throw new TaskFailureException('Text2Image generation using provider "' . $provider->getName() . '" failed: ' . $e->getMessage(), 0, $e);
  174. }
  175. }
  176. $task->setStatus(Task::STATUS_FAILED);
  177. try {
  178. $this->taskMapper->update(DbTask::fromPublicTask($task));
  179. } catch (Exception $e) {
  180. $this->logger->warning('Failed to update database after Text2Image error', ['exception' => $e]);
  181. }
  182. throw new TaskFailureException('Could not run task');
  183. }
  184. /**
  185. * @inheritDoc
  186. */
  187. public function scheduleTask(Task $task): void {
  188. if (!$this->hasProviders()) {
  189. throw new PreConditionNotMetException('No text to image provider is installed that can handle this task');
  190. }
  191. $this->logger->debug('Scheduling Text2Image Task');
  192. $task->setStatus(Task::STATUS_SCHEDULED);
  193. $completionExpectedAt = new \DateTime('now');
  194. $completionExpectedAt->add(new \DateInterval('PT'.$this->getPreferredProviders()[0]->getExpectedRuntime().'S'));
  195. $task->setCompletionExpectedAt($completionExpectedAt);
  196. $taskEntity = DbTask::fromPublicTask($task);
  197. $this->taskMapper->insert($taskEntity);
  198. $task->setId($taskEntity->getId());
  199. $this->jobList->add(TaskBackgroundJob::class, [
  200. 'taskId' => $task->getId()
  201. ]);
  202. }
  203. /**
  204. * @inheritDoc
  205. */
  206. public function runOrScheduleTask(Task $task) : void {
  207. if (!$this->hasProviders()) {
  208. throw new PreConditionNotMetException('No text to image provider is installed that can handle this task');
  209. }
  210. $providers = $this->getPreferredProviders();
  211. $maxExecutionTime = (int) ini_get('max_execution_time');
  212. // Offload the task to a background job if the expected runtime of the likely provider is longer than 80% of our max execution time
  213. if ($providers[0]->getExpectedRuntime() > $maxExecutionTime * 0.8) {
  214. $this->scheduleTask($task);
  215. return;
  216. }
  217. $this->runTask($task);
  218. }
  219. /**
  220. * @inheritDoc
  221. */
  222. public function deleteTask(Task $task): void {
  223. $taskEntity = DbTask::fromPublicTask($task);
  224. $this->taskMapper->delete($taskEntity);
  225. $this->jobList->remove(TaskBackgroundJob::class, [
  226. 'taskId' => $task->getId()
  227. ]);
  228. }
  229. /**
  230. * Get a task from its id
  231. *
  232. * @param int $id The id of the task
  233. * @return Task
  234. * @throws RuntimeException If the query failed
  235. * @throws TaskNotFoundException If the task could not be found
  236. */
  237. public function getTask(int $id): Task {
  238. try {
  239. $taskEntity = $this->taskMapper->find($id);
  240. return $taskEntity->toPublicTask();
  241. } catch (DoesNotExistException $e) {
  242. throw new TaskNotFoundException('Could not find task with the provided id');
  243. } catch (MultipleObjectsReturnedException $e) {
  244. throw new RuntimeException('Could not uniquely identify task with given id', 0, $e);
  245. } catch (Exception $e) {
  246. throw new RuntimeException('Failure while trying to find task by id: ' . $e->getMessage(), 0, $e);
  247. }
  248. }
  249. /**
  250. * Get a task from its user id and task id
  251. * If userId is null, this can only get a task that was scheduled anonymously
  252. *
  253. * @param int $id The id of the task
  254. * @param string|null $userId The user id that scheduled the task
  255. * @return Task
  256. * @throws RuntimeException If the query failed
  257. * @throws TaskNotFoundException If the task could not be found
  258. */
  259. public function getUserTask(int $id, ?string $userId): Task {
  260. try {
  261. $taskEntity = $this->taskMapper->findByIdAndUser($id, $userId);
  262. return $taskEntity->toPublicTask();
  263. } catch (DoesNotExistException $e) {
  264. throw new TaskNotFoundException('Could not find task with the provided id and user id');
  265. } catch (MultipleObjectsReturnedException $e) {
  266. throw new RuntimeException('Could not uniquely identify task with given id and user id', 0, $e);
  267. } catch (Exception $e) {
  268. throw new RuntimeException('Failure while trying to find task by id and user id: ' . $e->getMessage(), 0, $e);
  269. }
  270. }
  271. /**
  272. * Get a list of tasks scheduled by a specific user for a specific app
  273. * and optionally with a specific identifier.
  274. * This cannot be used to get anonymously scheduled tasks
  275. *
  276. * @param string $userId
  277. * @param string $appId
  278. * @param string|null $identifier
  279. * @return Task[]
  280. * @throws RuntimeException
  281. */
  282. public function getUserTasksByApp(?string $userId, string $appId, ?string $identifier = null): array {
  283. try {
  284. $taskEntities = $this->taskMapper->findUserTasksByApp($userId, $appId, $identifier);
  285. return array_map(static function (DbTask $taskEntity) {
  286. return $taskEntity->toPublicTask();
  287. }, $taskEntities);
  288. } catch (Exception $e) {
  289. throw new RuntimeException('Failure while trying to find tasks by appId and identifier: ' . $e->getMessage(), 0, $e);
  290. }
  291. }
  292. /**
  293. * @return IProvider[]
  294. */
  295. private function getPreferredProviders() {
  296. $providers = $this->getProviders();
  297. $json = $this->config->getAppValue('core', 'ai.text2image_provider', '');
  298. if ($json !== '') {
  299. try {
  300. $id = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
  301. $provider = current(array_filter($providers, fn ($provider) => $provider->getId() === $id));
  302. if ($provider !== false && $provider !== null) {
  303. $providers = [$provider];
  304. }
  305. } catch (\JsonException $e) {
  306. $this->logger->warning('Failed to decode Text2Image setting `ai.text2image_provider`', ['exception' => $e]);
  307. }
  308. }
  309. return $providers;
  310. }
  311. }