From 9d9fa08f18487f15b801f12ba6df3097fd36c512 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benedikt=20Sch=C3=A4chner?= Date: Tue, 24 Nov 2026 19:44:31 +0000 Subject: [PATCH 1/6] fix(Classify): skip already processed files with --retry MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The retry check looked up the tags of the last file id under an integer key, while getTagsForFiles returns them keyed by string, so the lookup never matched and already processed files were classified again. Check the tags of a whole page in one query and compare tag ids instead, and skip such files before they are added to any classifier queue. Fixes #1471 🤖 Generated with Codebuff Co-Authored-By: Codebuff Signed-off-by: Benedikt Schächner --- lib/Command/Classify.php | 39 ++++++++++++++++++++++++++++----------- 1 file changed, 28 insertions(+), 11 deletions(-) diff --git a/lib/Command/Classify.php b/lib/Command/Classify.php index d48eeaf4..f7f1150d 100644 --- a/lib/Command/Classify.php +++ b/lib/Command/Classify.php @@ -20,6 +20,7 @@ use OCA\Recognize\Service\TagManager; use OCP\Files\Config\ICachedMountInfo; use OCP\Files\Config\IUserMountCache; +use OCP\SystemTag\ISystemTag; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Exception\ExceptionInterface; use Symfony\Component\Console\Input\ArrayInput; @@ -100,16 +101,28 @@ protected function execute(InputInterface $input, OutputInterface $output): int $lastFileId = 0; do { - $i = 0; $queues = [ ImagenetClassifier::MODEL_NAME => [], ClusteringFaceClassifier::MODEL_NAME => [], MovinetClassifier::MODEL_NAME => [], MusicnnClassifier::MODEL_NAME => [], ]; - foreach ($this->storageService->getFilesInMount($mount['storage_id'], $mount['override_root'], $models, $lastFileId) as $file) { - $i++; + $files = iterator_to_array( + $this->storageService->getFilesInMount($mount['storage_id'], $mount['override_root'], $models, $lastFileId), + false + ); + $i = count($files); + // Fetch the tags of the whole page at once instead of issuing one query per file + $fileIds = array_map(static fn (array $file): string => (string)$file['fileid'], $files); + $tagsByFile = $input->getOption('retry') && count($fileIds) > 0 + ? $this->tagManager->getTagsForFiles($fileIds) + : []; + foreach ($files as $file) { $lastFileId = $file['fileid']; + // If the retry flag is set, skip files that already carry the processed tag, for all classifiers + if ($input->getOption('retry') && $this->hasProcessedTag($tagsByFile[(string)$file['fileid']] ?? [], $processedTag)) { + continue; + } $queueFile = new QueueFile(); $queueFile->setStorageId($mount['storage_id']); $queueFile->setRootId($mount['root_id']); @@ -121,14 +134,6 @@ protected function execute(InputInterface $input, OutputInterface $output): int $queues[ClusteringFaceClassifier::MODEL_NAME][] = $queueFile; } } - // if retry flag is set, skip other classifiers for tagged files - if ($input->getOption('retry')) { - $fileTags = $this->tagManager->getTagsForFiles([(string)$lastFileId]); - // check if processed tag is already in the tags - if (in_array($processedTag, $fileTags[$lastFileId])) { - continue; - } - } if ($file['image']) { if (in_array(ImagenetClassifier::MODEL_NAME, $models)) { $queues[ImagenetClassifier::MODEL_NAME][] = $queueFile; @@ -166,4 +171,16 @@ protected function execute(InputInterface $input, OutputInterface $output): int } return 0; } + + /** + * @param array $tags + */ + private function hasProcessedTag(array $tags, ISystemTag $processedTag): bool { + foreach ($tags as $tag) { + if ($tag->getId() === $processedTag->getId()) { + return true; + } + } + return false; + } } From d3f110568f2998d2bf304c0a0af65071d6481a5e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benedikt=20Sch=C3=A4chner?= Date: Tue, 24 Nov 2026 19:44:31 +0000 Subject: [PATCH 2/6] fix(InstallDeps): do not re-download installed TF.js and ffmpeg binaries MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The repair step runs on every maintenance:repair and re-downloaded ~150 MB of TensorFlow.js binaries each time although they were already present. Only run the install scripts when the native bindings or the ffmpeg binary are actually missing. Fixes #1478 🤖 Generated with Codebuff Co-Authored-By: Codebuff Signed-off-by: Benedikt Schächner --- lib/Migration/InstallDeps.php | 37 ++++++++++++++++++++++++++++++++--- 1 file changed, 34 insertions(+), 3 deletions(-) diff --git a/lib/Migration/InstallDeps.php b/lib/Migration/InstallDeps.php index 4f074c23..833e351d 100644 --- a/lib/Migration/InstallDeps.php +++ b/lib/Migration/InstallDeps.php @@ -91,9 +91,26 @@ public function run(IOutput $output): void { $binaryPath = $this->config->getAppValueString('node_binary', '', lazy: true); - $this->runTfjsInstall($binaryPath); - $this->runFfmpegInstall($binaryPath); - $this->runTfjsGpuInstall($binaryPath); + // Repair steps run on every `occ maintenance:repair` and app update. Skip the downloads + // when the native bindings are already in place instead of fetching ~150 MB each time. + if ($this->hasNativeBinding($this->tfjsPath, 'tfjs_binding.node')) { + $output->info('TensorFlow.js CPU binaries are already installed, skipping download.'); + } else { + $this->runTfjsInstall($binaryPath); + } + + if ($this->hasNativeBinding($this->tfjsGPUPath, 'tfjs_binding.node')) { + $output->info('TensorFlow.js GPU binaries are already installed, skipping download.'); + } else { + $this->runTfjsGpuInstall($binaryPath); + } + + if ($this->isFfmpegInstalled()) { + $output->info('ffmpeg binary is already installed, skipping download.'); + } else { + $this->runFfmpegInstall($binaryPath); + } + $this->setNodeModulesPermissions(); $this->setNiceBinaryPath(); $this->setFfmpegBinaryPath(); @@ -103,6 +120,20 @@ public function run(IOutput $output): void { } } + /** + * Check whether the native TensorFlow.js bindings of a module are already installed. + * The bindings live in node_modules/@tensorflow/tfjs-node{,-gpu}/lib//tfjs_binding.node. + */ + private function hasNativeBinding(string $moduleDir, string $bindingName): bool { + $bindings = glob($moduleDir . 'lib/*/' . $bindingName); + return $bindings !== false && count($bindings) > 0; + } + + private function isFfmpegInstalled(): bool { + $ffmpeg = $this->ffmpegDir . 'ffmpeg'; + return is_file($ffmpeg) && is_executable($ffmpeg); + } + protected function setNiceBinaryPath() : void { /* use nice binary from settings if available */ if ($this->config->getAppValueString('nice_binary', '', lazy: true) !== '') { From 9a9ccd03cf8bea1cd9040a6eab43818d2f910fce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benedikt=20Sch=C3=A4chner?= Date: Tue, 24 Nov 2026 19:44:31 +0000 Subject: [PATCH 3/6] feat(Command): add recognize:remove-duplicate-faces with --dry-run MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Expose the duplicate face detection repair step as an occ command, with a dry-run mode that only reports how many detections would be removed. The repair step now returns the number of removed duplicates so the command and the repair step share one implementation. Refs #1604 🤖 Generated with Codebuff Co-Authored-By: Codebuff Signed-off-by: Benedikt Schächner --- appinfo/info.xml | 1 + lib/Command/RemoveDuplicateFaces.php | 55 +++++++++++++++++++ .../RemoveDuplicateFaceDetections.php | 46 ++++++++++------ tests/RemoveDuplicateFaceDetectionsTest.php | 15 +++++ 4 files changed, 101 insertions(+), 16 deletions(-) create mode 100644 lib/Command/RemoveDuplicateFaces.php diff --git a/appinfo/info.xml b/appinfo/info.xml index d415d4c0..31c5a210 100644 --- a/appinfo/info.xml +++ b/appinfo/info.xml @@ -117,6 +117,7 @@ The app does not send any sensitive data to cloud providers or similar services. OCA\Recognize\Command\ClearBackgroundJobs OCA\Recognize\Command\RemoveLegacyTags OCA\Recognize\Command\CleanupTags + OCA\Recognize\Command\RemoveDuplicateFaces OCA\Recognize\Command\Recrawl OCA\Recognize\Command\DownloadModels OCA\Recognize\Command\Classify diff --git a/lib/Command/RemoveDuplicateFaces.php b/lib/Command/RemoveDuplicateFaces.php new file mode 100644 index 00000000..a029615e --- /dev/null +++ b/lib/Command/RemoveDuplicateFaces.php @@ -0,0 +1,55 @@ +setName('recognize:remove-duplicate-faces') + ->setDescription('Remove face detections that describe the same face of the same user in the same file more than once') + ->addOption('dry-run', null, InputOption::VALUE_NONE, 'Only report the number of duplicate detections instead of removing them'); + } + + protected function execute(InputInterface $input, OutputInterface $output): int { + $dryRun = (bool) $input->getOption('dry-run'); + + try { + $count = $this->repairStep->removeDuplicates($dryRun); + } catch (\Throwable $e) { + $output->writeln('Failed to remove duplicate face detections'); + $output->writeln($e->getMessage()); + return 1; + } + + if ($count === 0) { + $output->writeln('No duplicate face detections found.'); + } elseif ($dryRun) { + $output->writeln('Would remove ' . $count . ' duplicate face detections. Run without --dry-run to remove them.'); + } else { + $output->writeln('Removed ' . $count . ' duplicate face detections.'); + } + + return 0; + } +} diff --git a/lib/Migration/RemoveDuplicateFaceDetections.php b/lib/Migration/RemoveDuplicateFaceDetections.php index fedd1c83..68b51fad 100644 --- a/lib/Migration/RemoveDuplicateFaceDetections.php +++ b/lib/Migration/RemoveDuplicateFaceDetections.php @@ -70,31 +70,45 @@ public function getName(): string { public function run(IOutput $output): void { try { - $removed = 0; - $lastFileId = -1; - while (true) { - $upperFileId = $this->findBatchUpperBound($lastFileId); - $idsToDelete = $this->findDuplicateIds($lastFileId, $upperFileId); + $removed = $this->removeDuplicates(); + if ($removed > 0) { + $output->info('Removed ' . $removed . ' duplicate face detections'); + $this->logger->info('Removed ' . $removed . ' duplicate face detections'); + } + } catch (\Throwable $e) { + $output->warning('Failed to automatically remove duplicate face detections for recognize.'); + throw new \Exception('Failed to automatically remove duplicate face detections', previous: $e); + } + } + + /** + * Removes face detections that duplicate another detection of the same face in the same file. + * + * @param bool $dryRun Only count the duplicate detections without deleting them + * @return int The number of duplicate detections that were removed (or, in dry-run mode, would be removed) + * @throws \Throwable + */ + public function removeDuplicates(bool $dryRun = false): int { + $removed = 0; + $lastFileId = -1; + while (true) { + $upperFileId = $this->findBatchUpperBound($lastFileId); + $idsToDelete = $this->findDuplicateIds($lastFileId, $upperFileId); + if (!$dryRun) { foreach (array_chunk($idsToDelete, self::DELETE_CHUNK_SIZE) as $chunk) { $deleteQuery = $this->db->getQueryBuilder(); $deleteQuery->delete('recognize_face_detections') ->where($deleteQuery->expr()->in('id', $deleteQuery->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY))); $deleteQuery->executeStatement(); } - $removed += count($idsToDelete); - if ($upperFileId === null) { - break; - } - $lastFileId = $upperFileId; } - if ($removed > 0) { - $output->info('Removed ' . $removed . ' duplicate face detections'); - $this->logger->info('Removed ' . $removed . ' duplicate face detections'); + $removed += count($idsToDelete); + if ($upperFileId === null) { + break; } - } catch (\Throwable $e) { - $output->warning('Failed to automatically remove duplicate face detections for recognize.'); - throw new \Exception('Failed to automatically remove duplicate face detections', previous: $e); + $lastFileId = $upperFileId; } + return $removed; } /** diff --git a/tests/RemoveDuplicateFaceDetectionsTest.php b/tests/RemoveDuplicateFaceDetectionsTest.php index 5350379c..662e9edf 100644 --- a/tests/RemoveDuplicateFaceDetectionsTest.php +++ b/tests/RemoveDuplicateFaceDetectionsTest.php @@ -75,6 +75,21 @@ public function testRepairStep() : void { $this->assertEquals(10 * 10 * 11 - 10 * 10 * 9, (int)$count); // 200 } + public function testDryRunReportsDuplicatesWithoutRemovingThem() : void { + $repairStep = Server::get(RemoveDuplicateFaceDetections::class); + + $qb = $this->db->getQueryBuilder(); + $countBefore = (int)$qb->select($qb->func()->count('*'))->from('recognize_face_detections')->executeQuery()->fetchOne(); + $this->assertEquals(10 * 10 * 11, $countBefore); + + $duplicates = $repairStep->removeDuplicates(true); + + $this->assertEquals(10 * 10 * 9, $duplicates); + $qb = $this->db->getQueryBuilder(); + $countAfter = (int)$qb->select($qb->func()->count('*'))->from('recognize_face_detections')->executeQuery()->fetchOne(); + $this->assertEquals($countBefore, $countAfter, 'A dry run must not delete any detections'); + } + public function testRepairStepRemovesNearDuplicates() : void { $qb = $this->db->getQueryBuilder(); $qb->delete('recognize_face_detections')->executeStatement(); From 6c016ddcc3d9714765f445c2ec0834a719f1f022 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benedikt=20Sch=C3=A4chner?= Date: Tue, 24 Nov 2026 19:44:31 +0000 Subject: [PATCH 4/6] feat(Admin): download models from the admin settings MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add a button to the admin settings that queues a background job downloading the machine learning models, so installations without shell access can download them. The page polls the job status and updates automatically. Fixes #1529 🤖 Generated with Codebuff Co-Authored-By: Codebuff Signed-off-by: Benedikt Schächner --- appinfo/routes.php | 2 + lib/BackgroundJobs/DownloadModelsJob.php | 38 +++++++++++++++ lib/Controller/AdminController.php | 20 ++++++++ src/components/ViewAdmin.vue | 60 ++++++++++++++++++++++++ 4 files changed, 120 insertions(+) create mode 100644 lib/BackgroundJobs/DownloadModelsJob.php diff --git a/appinfo/routes.php b/appinfo/routes.php index 7e098302..9d016ee2 100644 --- a/appinfo/routes.php +++ b/appinfo/routes.php @@ -24,6 +24,8 @@ ['name' => 'admin#reset', 'url' => '/admin/reset', 'verb' => 'GET'], ['name' => 'admin#clearAllJobs', 'url' => '/admin/clearJobs', 'verb' => 'GET'], ['name' => 'admin#recrawl', 'url' => '/admin/recrawl', 'verb' => 'GET'], + ['name' => 'admin#downloadModels', 'url' => '/admin/downloadModels', 'verb' => 'GET'], + ['name' => 'admin#modelsStatus', 'url' => '/admin/modelsStatus', 'verb' => 'GET'], ['name' => 'admin#reset_faces', 'url' => '/admin/resetFaces', 'verb' => 'GET'], ['name' => 'admin#count', 'url' => '/admin/count', 'verb' => 'GET'], ['name' => 'admin#countQueued', 'url' => '/admin/countQueued', 'verb' => 'GET'], diff --git a/lib/BackgroundJobs/DownloadModelsJob.php b/lib/BackgroundJobs/DownloadModelsJob.php new file mode 100644 index 00000000..69319cf5 --- /dev/null +++ b/lib/BackgroundJobs/DownloadModelsJob.php @@ -0,0 +1,38 @@ +downloader->download(); + } catch (\Throwable $e) { + // Keep the job from failing cron; the admin settings show that the models are still missing + $this->logger->error('Failed to download the machine learning models', ['exception' => $e]); + } + } +} diff --git a/lib/Controller/AdminController.php b/lib/Controller/AdminController.php index 0aee1ac1..2d6c4add 100644 --- a/lib/Controller/AdminController.php +++ b/lib/Controller/AdminController.php @@ -15,6 +15,7 @@ use OCA\Recognize\BackgroundJobs\ClassifyMovinetJob; use OCA\Recognize\BackgroundJobs\ClassifyMusicnnJob; use OCA\Recognize\BackgroundJobs\ClusterFacesJob; +use OCA\Recognize\BackgroundJobs\DownloadModelsJob; use OCA\Recognize\Db\FaceClusterMapper; use OCA\Recognize\Db\FaceDetectionMapper; use OCA\Recognize\Service\QueueService; @@ -70,6 +71,25 @@ public function recrawl(): JSONResponse { return new JSONResponse([]); } + /** + * Queue the download of the machine learning models. The download runs in a background job + * because it can take a long time and is too large for a single HTTP request. + */ + public function downloadModels(): JSONResponse { + if (file_exists(__DIR__ . '/../../models')) { + return new JSONResponse(['downloaded' => true, 'scheduled' => false]); + } + $this->jobList->add(DownloadModelsJob::class); + return new JSONResponse(['downloaded' => false, 'scheduled' => true]); + } + + public function modelsStatus(): JSONResponse { + return new JSONResponse([ + 'downloaded' => file_exists(__DIR__ . '/../../models'), + 'scheduled' => $this->jobList->has(DownloadModelsJob::class, null), + ]); + } + public function resetFaces(): JSONResponse { try { $this->clusterMapper->deleteAll(); diff --git a/src/components/ViewAdmin.vue b/src/components/ViewAdmin.vue index e2b27e61..b3085101 100644 --- a/src/components/ViewAdmin.vue +++ b/src/components/ViewAdmin.vue @@ -14,6 +14,18 @@ {{ t('recognize', 'The machine learning models still need to be downloaded.') }} + + {{ t('recognize', 'The systemtags app is enabled.') }} @@ -477,6 +489,9 @@

{{ t('recognize', 'You can delete all tags that no longer have any files associated with them with the following command:') }}

occ recognize:cleanup-tags

 

+

{{ t('recognize', 'To find and remove face detections that describe the same face of the same user in the same file more than once, run the following. Add --dry-run to only count them without changing anything.') }}

+
occ recognize:remove-duplicate-faces --dry-run
+

 

{{ t('recognize', 'To remove tags that were created by Recognize version 2 from all files run the following on the terminal:') }}

occ recognize:remove-legacy-tags
@@ -531,6 +546,8 @@ export default { ffmpeg: undefined, cron: undefined, modelsDownloaded: null, + modelsDownloadScheduled: false, + modelsPoll: null, imagenetJobs: null, facesJobs: null, landmarksJobs: null, @@ -589,6 +606,7 @@ export default { }, async created() { this.modelsDownloaded = loadState('recognize', 'modelsDownloaded') + this.getModelsStatus() this.tagsEnabled = loadState('recognize', 'tagsEnabled') this.recognizeBackendInstalled = loadState('recognize', 'recognizeBackendInstalled', false) this.faceEmbeddingDimensions = loadState('recognize', 'faceEmbeddingDimensions', null) @@ -654,7 +672,49 @@ export default { } }, + beforeUnmount() { + if (this.modelsPoll) { + clearInterval(this.modelsPoll) + } + }, + methods: { + async onDownloadModels() { + this.loading = true + try { + await axios.get(generateUrl('/apps/recognize/admin/downloadModels')) + this.modelsDownloadScheduled = true + this.startModelsPolling() + } catch (e) { + this.error = this.t('recognize', 'Failed to schedule the model download') + } finally { + this.loading = false + } + }, + async getModelsStatus() { + try { + const resp = await axios.get(generateUrl('/apps/recognize/admin/modelsStatus')) + this.modelsDownloaded = resp.data.downloaded + this.modelsDownloadScheduled = resp.data.scheduled + if (!this.modelsDownloaded && this.modelsDownloadScheduled) { + this.startModelsPolling() + } + } catch (e) { + console.error(e) + } + }, + startModelsPolling() { + if (this.modelsPoll) { + return + } + this.modelsPoll = setInterval(async () => { + await this.getModelsStatus() + if (this.modelsDownloaded || !this.modelsDownloadScheduled) { + clearInterval(this.modelsPoll) + this.modelsPoll = null + } + }, 10 * 1000) + }, async onReset() { this.loading = true await axios.get(generateUrl('/apps/recognize/admin/reset')) From a1c9c0813b2acfa0832c120559b7efb6e0959f97 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benedikt=20Sch=C3=A4chner?= Date: Sat, 28 Nov 2026 12:33:01 +0000 Subject: [PATCH 5/6] fix: address review feedback on classify retry, install isolation and model downloads - recognize:classify --retry now resolves the processed tag state of a whole page in a single query (TagManager::getProcessedFileIds) instead of loading full tag objects per file, and only skips the tag-based classifiers. The face classifier keeps its independent retry behaviour because it does not tag files and tracks progress in the face detection table. - Queue distribution moved into ClassificationQueueBuilder so the per-classifier retry semantics are covered by unit tests. - InstallDeps runs each download step isolated, so a failing tfjs-node-gpu install can no longer prevent the ffmpeg install. - The admin model download now also detects a currently running DownloadModelsJob via OCP\BackgroundJob\IJobRuns, because queued jobs leave the jobs table once they start. Stale running entries older than 24h are ignored so a crashed download cannot block the button forever. - Add regression tests for all of the above. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- lib/BackgroundJobs/DownloadModelsJob.php | 3 + lib/Command/Classify.php | 65 +---- lib/Controller/AdminController.php | 33 ++- lib/Migration/InstallDeps.php | 21 +- lib/Service/ClassificationQueueBuilder.php | 63 +++++ lib/Service/TagManager.php | 24 ++ tests/Controller/AdminControllerTest.php | 178 +++++++++++++ tests/InstallDepsTest.php | 235 ++++++++++++++++++ .../ClassificationQueueBuilderTest.php | 118 +++++++++ tests/Service/TagManagerTest.php | 76 ++++++ 10 files changed, 752 insertions(+), 64 deletions(-) create mode 100644 lib/Service/ClassificationQueueBuilder.php create mode 100644 tests/Controller/AdminControllerTest.php create mode 100644 tests/InstallDepsTest.php create mode 100644 tests/Service/ClassificationQueueBuilderTest.php create mode 100644 tests/Service/TagManagerTest.php diff --git a/lib/BackgroundJobs/DownloadModelsJob.php b/lib/BackgroundJobs/DownloadModelsJob.php index 69319cf5..2ea6c364 100644 --- a/lib/BackgroundJobs/DownloadModelsJob.php +++ b/lib/BackgroundJobs/DownloadModelsJob.php @@ -27,6 +27,9 @@ public function __construct( parent::__construct($time); } + /** + * @param mixed $argument unused, the job takes no arguments + */ protected function run($argument): void { try { $this->downloader->download(); diff --git a/lib/Command/Classify.php b/lib/Command/Classify.php index f7f1150d..58b3b4ac 100644 --- a/lib/Command/Classify.php +++ b/lib/Command/Classify.php @@ -12,15 +12,14 @@ use OCA\Recognize\Classifiers\Images\ClusteringFaceClassifier; use OCA\Recognize\Classifiers\Images\ImagenetClassifier; use OCA\Recognize\Classifiers\Video\MovinetClassifier; -use OCA\Recognize\Db\QueueFile; use OCA\Recognize\Exception\Exception; +use OCA\Recognize\Service\ClassificationQueueBuilder; use OCA\Recognize\Service\Logger; use OCA\Recognize\Service\SettingsService; use OCA\Recognize\Service\StorageService; use OCA\Recognize\Service\TagManager; use OCP\Files\Config\ICachedMountInfo; use OCP\Files\Config\IUserMountCache; -use OCP\SystemTag\ISystemTag; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Exception\ExceptionInterface; use Symfony\Component\Console\Input\ArrayInput; @@ -43,6 +42,7 @@ public function __construct( private IUserMountCache $userMountCache, private SettingsService $settings, private ClearBackgroundJobs $clearBackgroundJobs, + private ClassificationQueueBuilder $queueBuilder, ) { parent::__construct(); $this->classifiers[ImagenetClassifier::MODEL_NAME] = $imagenet; @@ -86,8 +86,6 @@ protected function execute(InputInterface $input, OutputInterface $output): int MusicnnClassifier::MODEL_NAME, ], fn ($modelName) => $this->settings->getSetting($modelName . '.enabled') === 'true')); - $processedTag = $this->tagManager->getProcessedTag(); - foreach ($this->storageService->getMounts() as $mount) { $this->logger->info('Processing storage ' . $mount['storage_id'] . ' with root ID ' . $mount['override_root']); @@ -101,54 +99,19 @@ protected function execute(InputInterface $input, OutputInterface $output): int $lastFileId = 0; do { - $queues = [ - ImagenetClassifier::MODEL_NAME => [], - ClusteringFaceClassifier::MODEL_NAME => [], - MovinetClassifier::MODEL_NAME => [], - MusicnnClassifier::MODEL_NAME => [], - ]; $files = iterator_to_array( $this->storageService->getFilesInMount($mount['storage_id'], $mount['override_root'], $models, $lastFileId), false ); $i = count($files); - // Fetch the tags of the whole page at once instead of issuing one query per file + // Fetch the processed tag state of the whole page with a single query $fileIds = array_map(static fn (array $file): string => (string)$file['fileid'], $files); - $tagsByFile = $input->getOption('retry') && count($fileIds) > 0 - ? $this->tagManager->getTagsForFiles($fileIds) + $processedFileIds = $input->getOption('retry') && count($fileIds) > 0 + ? array_fill_keys($this->tagManager->getProcessedFileIds($fileIds), true) : []; - foreach ($files as $file) { - $lastFileId = $file['fileid']; - // If the retry flag is set, skip files that already carry the processed tag, for all classifiers - if ($input->getOption('retry') && $this->hasProcessedTag($tagsByFile[(string)$file['fileid']] ?? [], $processedTag)) { - continue; - } - $queueFile = new QueueFile(); - $queueFile->setStorageId($mount['storage_id']); - $queueFile->setRootId($mount['root_id']); - $queueFile->setFileId($file['fileid']); - $queueFile->setUpdate(false); - - if ($file['image']) { - if (in_array(ClusteringFaceClassifier::MODEL_NAME, $models)) { - $queues[ClusteringFaceClassifier::MODEL_NAME][] = $queueFile; - } - } - if ($file['image']) { - if (in_array(ImagenetClassifier::MODEL_NAME, $models)) { - $queues[ImagenetClassifier::MODEL_NAME][] = $queueFile; - } - } - if ($file['video']) { - if (in_array(MovinetClassifier::MODEL_NAME, $models)) { - $queues[MovinetClassifier::MODEL_NAME][] = $queueFile; - } - } - if ($file['audio']) { - if (in_array(MusicnnClassifier::MODEL_NAME, $models)) { - $queues[MusicnnClassifier::MODEL_NAME][] = $queueFile; - } - } + $queues = $this->queueBuilder->build($files, $processedFileIds, $models, $mount['storage_id'], $mount['root_id']); + if ($i > 0) { + $lastFileId = $files[$i - 1]['fileid']; } foreach ($this->classifiers as $modelName => $classifier) { @@ -171,16 +134,4 @@ protected function execute(InputInterface $input, OutputInterface $output): int } return 0; } - - /** - * @param array $tags - */ - private function hasProcessedTag(array $tags, ISystemTag $processedTag): bool { - foreach ($tags as $tag) { - if ($tag->getId() === $processedTag->getId()) { - return true; - } - } - return false; - } } diff --git a/lib/Controller/AdminController.php b/lib/Controller/AdminController.php index 2d6c4add..4a8d315d 100644 --- a/lib/Controller/AdminController.php +++ b/lib/Controller/AdminController.php @@ -26,7 +26,9 @@ use OCP\AppFramework\Http\JSONResponse; use OCP\AppFramework\QueryException; use OCP\AppFramework\Services\IAppConfig; +use OCP\AppFramework\Utility\ITimeFactory; use OCP\BackgroundJob\IJobList; +use OCP\BackgroundJob\IJobRuns; use OCP\DB\Exception; use OCP\Exceptions\AppConfigTypeConflictException; use OCP\IBinaryFinder; @@ -42,8 +44,10 @@ final class AdminController extends Controller { private IAppConfig $config; private FaceDetectionMapper $faceDetections; private IBinaryFinder $binaryFinder; + private IJobRuns $jobRuns; + private ITimeFactory $timeFactory; - public function __construct(string $appName, IRequest $request, TagManager $tagManager, IJobList $jobList, SettingsService $settingsService, QueueService $queue, FaceClusterMapper $clusterMapper, FaceDetectionMapper $detectionMapper, IAppConfig $config, FaceDetectionMapper $faceDetections, IBinaryFinder $binaryFinder) { + public function __construct(string $appName, IRequest $request, TagManager $tagManager, IJobList $jobList, SettingsService $settingsService, QueueService $queue, FaceClusterMapper $clusterMapper, FaceDetectionMapper $detectionMapper, IAppConfig $config, FaceDetectionMapper $faceDetections, IBinaryFinder $binaryFinder, IJobRuns $jobRuns, ITimeFactory $timeFactory) { parent::__construct($appName, $request); $this->tagManager = $tagManager; $this->jobList = $jobList; @@ -54,6 +58,8 @@ public function __construct(string $appName, IRequest $request, TagManager $tagM $this->config = $config; $this->faceDetections = $faceDetections; $this->binaryFinder = $binaryFinder; + $this->jobRuns = $jobRuns; + $this->timeFactory = $timeFactory; } public function reset(): JSONResponse { @@ -79,17 +85,38 @@ public function downloadModels(): JSONResponse { if (file_exists(__DIR__ . '/../../models')) { return new JSONResponse(['downloaded' => true, 'scheduled' => false]); } - $this->jobList->add(DownloadModelsJob::class); + // Queued jobs leave the jobs table as soon as they start, so a running + // download has to be detected through the job runs as well. + if (!$this->isModelDownloadActive()) { + $this->jobList->add(DownloadModelsJob::class); + } return new JSONResponse(['downloaded' => false, 'scheduled' => true]); } public function modelsStatus(): JSONResponse { return new JSONResponse([ 'downloaded' => file_exists(__DIR__ . '/../../models'), - 'scheduled' => $this->jobList->has(DownloadModelsJob::class, null), + 'scheduled' => $this->isModelDownloadActive(), ]); } + private function isModelDownloadActive(): bool { + if ($this->jobList->has(DownloadModelsJob::class, null)) { + return true; + } + // A crashed PHP process can leave a stale "running" entry behind, so only + // count runs that started recently; the download itself is bounded by the + // job runner and a day is far beyond any realistic download time. + $maxAge = 24 * 3600; + foreach ($this->jobRuns->runningJobs() as $jobRun) { + if ($jobRun->className === DownloadModelsJob::class + && $jobRun->startedAt->getTimestamp() > $this->timeFactory->getTime() - $maxAge) { + return true; + } + } + return false; + } + public function resetFaces(): JSONResponse { try { $this->clusterMapper->deleteAll(); diff --git a/lib/Migration/InstallDeps.php b/lib/Migration/InstallDeps.php index 833e351d..9efad2ac 100644 --- a/lib/Migration/InstallDeps.php +++ b/lib/Migration/InstallDeps.php @@ -92,23 +92,24 @@ public function run(IOutput $output): void { $binaryPath = $this->config->getAppValueString('node_binary', '', lazy: true); // Repair steps run on every `occ maintenance:repair` and app update. Skip the downloads - // when the native bindings are already in place instead of fetching ~150 MB each time. + // when the binaries are already in place instead of fetching ~150 MB each time, and + // isolate every step so that one failure cannot prevent the remaining ones. if ($this->hasNativeBinding($this->tfjsPath, 'tfjs_binding.node')) { $output->info('TensorFlow.js CPU binaries are already installed, skipping download.'); } else { - $this->runTfjsInstall($binaryPath); + $this->runInstallStep($output, 'TensorFlow.js CPU binaries', fn () => $this->runTfjsInstall($binaryPath)); } if ($this->hasNativeBinding($this->tfjsGPUPath, 'tfjs_binding.node')) { $output->info('TensorFlow.js GPU binaries are already installed, skipping download.'); } else { - $this->runTfjsGpuInstall($binaryPath); + $this->runInstallStep($output, 'TensorFlow.js GPU binaries', fn () => $this->runTfjsGpuInstall($binaryPath)); } if ($this->isFfmpegInstalled()) { $output->info('ffmpeg binary is already installed, skipping download.'); } else { - $this->runFfmpegInstall($binaryPath); + $this->runInstallStep($output, 'ffmpeg binary', fn () => $this->runFfmpegInstall($binaryPath)); } $this->setNodeModulesPermissions(); @@ -134,6 +135,18 @@ private function isFfmpegInstalled(): bool { return is_file($ffmpeg) && is_executable($ffmpeg); } + /** + * Run a single install step. A failure is reported but must not abort the + * remaining steps, e.g. a missing GPU must not prevent the ffmpeg install. + */ + private function runInstallStep(IOutput $output, string $description, callable $step): void { + try { + $step(); + } catch (\Throwable $e) { + $output->warning('Failed to install ' . $description . ': ' . $e->getMessage()); + } + } + protected function setNiceBinaryPath() : void { /* use nice binary from settings if available */ if ($this->config->getAppValueString('nice_binary', '', lazy: true) !== '') { diff --git a/lib/Service/ClassificationQueueBuilder.php b/lib/Service/ClassificationQueueBuilder.php new file mode 100644 index 00000000..19e149aa --- /dev/null +++ b/lib/Service/ClassificationQueueBuilder.php @@ -0,0 +1,63 @@ + $files + * @param array $processedFileIds lookup of file ids that already carry the processed tag + * @param list $models enabled model names + * @return array> + */ + public function build(array $files, array $processedFileIds, array $models, int $storageId, int $rootId): array { + $queues = [ + ImagenetClassifier::MODEL_NAME => [], + ClusteringFaceClassifier::MODEL_NAME => [], + MovinetClassifier::MODEL_NAME => [], + MusicnnClassifier::MODEL_NAME => [], + ]; + foreach ($files as $file) { + $queueFile = new QueueFile(); + $queueFile->setStorageId($storageId); + $queueFile->setRootId($rootId); + $queueFile->setFileId($file['fileid']); + $queueFile->setUpdate(false); + + if ($file['image'] && in_array(ClusteringFaceClassifier::MODEL_NAME, $models, true)) { + $queues[ClusteringFaceClassifier::MODEL_NAME][] = $queueFile; + } + if (isset($processedFileIds[(string)$file['fileid']])) { + continue; + } + if ($file['image'] && in_array(ImagenetClassifier::MODEL_NAME, $models, true)) { + $queues[ImagenetClassifier::MODEL_NAME][] = $queueFile; + } + if ($file['video'] && in_array(MovinetClassifier::MODEL_NAME, $models, true)) { + $queues[MovinetClassifier::MODEL_NAME][] = $queueFile; + } + if ($file['audio'] && in_array(MusicnnClassifier::MODEL_NAME, $models, true)) { + $queues[MusicnnClassifier::MODEL_NAME][] = $queueFile; + } + } + return $queues; + } +} diff --git a/lib/Service/TagManager.php b/lib/Service/TagManager.php index 9dd61059..d41bfb11 100644 --- a/lib/Service/TagManager.php +++ b/lib/Service/TagManager.php @@ -95,6 +95,30 @@ public function getTagsForFiles(array $fileIds): array { }, $tagsByFile); } + /** + * Returns the ids of the given files that already carry the processed tag. + * Unlike getTagsForFiles() this only resolves tag ids, so the whole batch + * is fetched with a single query instead of one query per file. + * + * @param list $fileIds + * @return list + */ + public function getProcessedFileIds(array $fileIds): array { + if ($fileIds === []) { + return []; + } + $processedTagId = $this->getProcessedTag()->getId(); + /** @var array $tagsByFile */ + $tagsByFile = $this->objectMapper->getTagIdsForObjects($fileIds, 'files'); + $processedFileIds = []; + foreach ($tagsByFile as $fileId => $tagIds) { + if (in_array($processedTagId, $tagIds, true)) { + $processedFileIds[] = (string)$fileId; + } + } + return $processedFileIds; + } + /** * @return list */ diff --git a/tests/Controller/AdminControllerTest.php b/tests/Controller/AdminControllerTest.php new file mode 100644 index 00000000..8479c782 --- /dev/null +++ b/tests/Controller/AdminControllerTest.php @@ -0,0 +1,178 @@ +markTestSkipped('The models directory exists in this checkout'); + } + + $eventDispatcher = $this->createMock(IEventDispatcher::class); + $jobList = $this->createMock(IJobList::class); + $appConfig = $this->createMock(IAppConfig::class); + $db = $this->createMock(IDBConnection::class); + $systemConfig = $this->createMock(IConfig::class); + + $this->jobList = $jobList; + $this->jobRuns = $this->createMock(IJobRuns::class); + $this->timeFactory = $this->createMock(ITimeFactory::class); + + $settingsService = new SettingsService($appConfig, $jobList, $eventDispatcher, $db); + $queueService = new QueueService(new QueueMapper($db), $jobList, $appConfig, $eventDispatcher); + $clusterMapper = new FaceClusterMapper($db, $eventDispatcher); + $detectionMapper = new FaceDetectionMapper($db, $systemConfig, $settingsService, $eventDispatcher); + $tagManager = new TagManager( + $this->createMock(ISystemTagManager::class), + $this->createMock(ISystemTagObjectMapper::class), + $eventDispatcher, + ); + + $this->controller = new AdminController( + 'recognize', + $this->createMock(IRequest::class), + $tagManager, + $jobList, + $settingsService, + $queueService, + $clusterMapper, + $detectionMapper, + $appConfig, + $detectionMapper, + $this->createMock(IBinaryFinder::class), + $this->jobRuns, + $this->timeFactory, + ); + } + + /** + * @param list $runningJobs + */ + private function mockRunningJobs(array $runningJobs): void { + $this->jobRuns->method('runningJobs')->willReturnCallback( + static function () use ($runningJobs): \Generator { + yield from $runningJobs; + }, + ); + } + + private function runningJob(string $className, int $ageInSeconds = 60): JobRun { + return new JobRun( + '123456789', + $className, + 1, + 1234, + new \DateTimeImmutable('-' . $ageInSeconds . ' seconds'), + JobStatus::RUNNING, + ); + } + + public function testModelsStatusReportsQueuedJob(): void { + $this->jobList->method('has')->with(DownloadModelsJob::class, null)->willReturn(true); + $this->mockRunningJobs([]); + + $response = $this->controller->modelsStatus(); + + $this->assertSame(['downloaded' => false, 'scheduled' => true], $response->getData()); + } + + public function testModelsStatusReportsRunningJob(): void { + $this->jobList->method('has')->willReturn(false); + $this->mockRunningJobs([$this->runningJob(DownloadModelsJob::class)]); + $this->timeFactory->method('getTime')->willReturn(\time()); + + $response = $this->controller->modelsStatus(); + + $this->assertSame(['downloaded' => false, 'scheduled' => true], $response->getData()); + } + + public function testModelsStatusIgnoresStaleRunningJob(): void { + $this->jobList->method('has')->willReturn(false); + // A crashed PHP process can leave a stale "running" entry behind + $this->mockRunningJobs([$this->runningJob(DownloadModelsJob::class, 25 * 3600)]); + $this->timeFactory->method('getTime')->willReturn(\time()); + + $response = $this->controller->modelsStatus(); + + $this->assertSame(['downloaded' => false, 'scheduled' => false], $response->getData()); + } + + public function testModelsStatusIgnoresOtherRunningJobs(): void { + $this->jobList->method('has')->willReturn(false); + $this->mockRunningJobs([$this->runningJob(\stdClass::class)]); + $this->timeFactory->method('getTime')->willReturn(\time()); + + $response = $this->controller->modelsStatus(); + + $this->assertSame(['downloaded' => false, 'scheduled' => false], $response->getData()); + } + + public function testDownloadModelsDoesNotQueueSecondJobWhileQueued(): void { + $this->jobList->method('has')->willReturn(true); + $this->mockRunningJobs([]); + $this->jobList->expects($this->never())->method('add'); + + $response = $this->controller->downloadModels(); + + $this->assertSame(['downloaded' => false, 'scheduled' => true], $response->getData()); + } + + public function testDownloadModelsDoesNotQueueSecondJobWhileRunning(): void { + $this->jobList->method('has')->willReturn(false); + $this->mockRunningJobs([$this->runningJob(DownloadModelsJob::class)]); + $this->timeFactory->method('getTime')->willReturn(\time()); + $this->jobList->expects($this->never())->method('add'); + + $response = $this->controller->downloadModels(); + + $this->assertSame(['downloaded' => false, 'scheduled' => true], $response->getData()); + } + + public function testDownloadModelsQueuesJobWhenIdle(): void { + $this->jobList->method('has')->willReturn(false); + $this->mockRunningJobs([]); + $this->jobList->expects($this->once())->method('add')->with(DownloadModelsJob::class); + + $response = $this->controller->downloadModels(); + + $this->assertSame(['downloaded' => false, 'scheduled' => true], $response->getData()); + } +} diff --git a/tests/InstallDepsTest.php b/tests/InstallDepsTest.php new file mode 100644 index 00000000..929e537f --- /dev/null +++ b/tests/InstallDepsTest.php @@ -0,0 +1,235 @@ +appRoot = \dirname(__DIR__); + $this->logFile = \tempnam(\sys_get_temp_dir(), 'recognize-installdeps-'); + $this->fakeNode = \tempnam(\sys_get_temp_dir(), 'recognize-fakenode-'); + $script = <<<'SCRIPT' +#!/bin/sh +if [ "$1" = "--version" ]; then + echo "fake-node 1.0.0" + exit 0 +fi +echo "$PWD :: $*" >> "LOGFILE_PATH" +case "$*" in + *tfjs-node-gpu*) + if [ "$RECOGNIZE_TEST_GPU_FAIL" = "1" ]; then + exit 1 + fi + ;; + *tfjs-node/scripts/install.js*) + if [ "$RECOGNIZE_TEST_CPU_FAIL" = "1" ]; then + exit 1 + fi + ;; +esac +exit 0 +SCRIPT; + \file_put_contents($this->fakeNode, \str_replace('LOGFILE_PATH', $this->logFile, $script)); + \chmod($this->fakeNode, 0755); + + $this->appConfig = $this->createMock(IAppConfig::class); + $this->appConfig->method('getAppValueString')->willReturnCallback( + fn (string $key): string => $key === 'node_binary' ? $this->fakeNode : '', + ); + $this->output = $this->createMock(IOutput::class); + } + + protected function tearDown(): void { + \unlink($this->logFile); + \unlink($this->fakeNode); + parent::tearDown(); + } + + private function createRepairStep(): InstallDeps { + $systemConfig = $this->createMock(IConfig::class); + $systemConfig->method('getSystemValueString')->willReturn(''); + $binaryFinder = $this->createMock(IBinaryFinder::class); + $binaryFinder->method('findBinaryPath')->willReturn(false); + + return new InstallDeps( + $this->appConfig, + $systemConfig, + $this->createMock(IClientService::class), + $this->createMock(LoggerInterface::class), + $binaryFinder, + ); + } + + /** + * @return list the install scripts that were executed, one per line + */ + private function executedInstallScripts(): array { + if (!\is_file($this->logFile)) { + return []; + } + $lines = \file($this->logFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); + return \array_values(\array_filter($lines, static fn (string $line): bool => \str_contains($line, 'install.js'))); + } + + private function createBinding(string $moduleDir): void { + $dir = $this->appRoot . '/node_modules/' . $moduleDir . '/lib/9.9.9'; + \mkdir($dir, 0755, true); + \file_put_contents($dir . '/tfjs_binding.node', ''); + } + + private function createFfmpegBinary(): void { + $ffmpeg = $this->appRoot . '/node_modules/ffmpeg-static/ffmpeg'; + \file_put_contents($ffmpeg, "#!/bin/sh\nexit 0\n"); + \chmod($ffmpeg, 0755); + } + + /** + * Remove a fixture file and any directories the test created for it. + */ + private function removeFixture(string $path): void { + if (\is_file($path)) { + \unlink($path); + } + $dir = \dirname($path); + while ($dir !== $this->appRoot . '/node_modules' && \is_dir($dir) && \count(\scandir($dir)) === 2) { + if (!\rmdir($dir)) { + break; + } + $dir = \dirname($dir); + } + } + + private function assertAllArtifactsMissing(): void { + if ($this->nativeBindingExists('@tensorflow/tfjs-node') + || $this->nativeBindingExists('@tensorflow/tfjs-node-gpu') + || $this->ffmpegExists()) { + $this->markTestSkipped('Binaries are already installed in this environment'); + } + } + + public function testAllInstallersRunWhenArtifactsAreMissing(): void { + $this->assertAllArtifactsMissing(); + + $this->createRepairStep()->run($this->output); + + $scripts = $this->executedInstallScripts(); + $this->assertCount(3, $scripts); + $this->assertStringContainsString('tfjs-node/scripts/install.js', $scripts[0]); + $this->assertStringContainsString('tfjs-node-gpu/scripts/install.js', $scripts[1]); + $this->assertStringContainsString('ffmpeg-static/install.js', $scripts[2]); + } + + public function testGpuFailureDoesNotPreventFfmpegInstall(): void { + $this->assertAllArtifactsMissing(); + \putenv('RECOGNIZE_TEST_GPU_FAIL=1'); + + try { + $this->createRepairStep()->run($this->output); + } finally { + \putenv('RECOGNIZE_TEST_GPU_FAIL'); + } + + $scripts = $this->executedInstallScripts(); + $this->assertCount(3, $scripts, 'A failing GPU install must not prevent the ffmpeg install'); + $this->assertStringContainsString('tfjs-node-gpu/scripts/install.js', $scripts[1]); + $this->assertStringContainsString('ffmpeg-static/install.js', $scripts[2]); + } + + public function testCpuFailureDoesNotPreventOtherInstalls(): void { + $this->assertAllArtifactsMissing(); + \putenv('RECOGNIZE_TEST_CPU_FAIL=1'); + + try { + $this->createRepairStep()->run($this->output); + } finally { + \putenv('RECOGNIZE_TEST_CPU_FAIL'); + } + + $scripts = $this->executedInstallScripts(); + $this->assertCount(3, $scripts, 'A failing CPU install must not prevent the GPU and ffmpeg installs'); + $this->assertStringContainsString('tfjs-node-gpu/scripts/install.js', $scripts[1]); + $this->assertStringContainsString('ffmpeg-static/install.js', $scripts[2]); + } + + public function testInstalledArtifactsAreNotDownloadedAgain(): void { + $fixtures = [ + $this->appRoot . '/node_modules/@tensorflow/tfjs-node/lib/9.9.9/tfjs_binding.node', + $this->appRoot . '/node_modules/@tensorflow/tfjs-node-gpu/lib/9.9.9/tfjs_binding.node', + $this->appRoot . '/node_modules/ffmpeg-static/ffmpeg', + ]; + try { + $this->createBinding('@tensorflow/tfjs-node'); + $this->createBinding('@tensorflow/tfjs-node-gpu'); + $this->createFfmpegBinary(); + + $this->createRepairStep()->run($this->output); + + $this->assertSame([], $this->executedInstallScripts(), 'Installed artifacts must not be downloaded again'); + } finally { + foreach ($fixtures as $fixture) { + $this->removeFixture($fixture); + } + } + } + + public function testOnlyMissingGpuBindingIsDownloaded(): void { + if ($this->nativeBindingExists('@tensorflow/tfjs-node-gpu')) { + $this->markTestSkipped('GPU binaries are already installed in this environment'); + } + $fixtures = [ + $this->appRoot . '/node_modules/@tensorflow/tfjs-node/lib/9.9.9/tfjs_binding.node', + $this->appRoot . '/node_modules/ffmpeg-static/ffmpeg', + ]; + try { + $this->createBinding('@tensorflow/tfjs-node'); + $this->createFfmpegBinary(); + + $this->createRepairStep()->run($this->output); + + $scripts = $this->executedInstallScripts(); + $this->assertCount(1, $scripts); + $this->assertStringContainsString('tfjs-node-gpu/scripts/install.js', $scripts[0]); + } finally { + foreach ($fixtures as $fixture) { + $this->removeFixture($fixture); + } + } + } + + private function nativeBindingExists(string $moduleDir): bool { + $bindings = \glob($this->appRoot . '/node_modules/' . $moduleDir . '/lib/*/tfjs_binding.node'); + return $bindings !== false && \count($bindings) > 0; + } + + private function ffmpegExists(): bool { + $ffmpeg = $this->appRoot . '/node_modules/ffmpeg-static/ffmpeg'; + return \is_file($ffmpeg) && \is_executable($ffmpeg); + } +} diff --git a/tests/Service/ClassificationQueueBuilderTest.php b/tests/Service/ClassificationQueueBuilderTest.php new file mode 100644 index 00000000..de1a5d46 --- /dev/null +++ b/tests/Service/ClassificationQueueBuilderTest.php @@ -0,0 +1,118 @@ +builder = new ClassificationQueueBuilder(); + } + + /** + * @param list $files + * @param array $processedFileIds + * @param list $models + * @return array> + */ + private function queuedFileIds(array $files, array $processedFileIds = [], array $models = [ + ClusteringFaceClassifier::MODEL_NAME, + ImagenetClassifier::MODEL_NAME, + MovinetClassifier::MODEL_NAME, + MusicnnClassifier::MODEL_NAME, + ]): array { + $queues = $this->builder->build($files, $processedFileIds, $models, self::STORAGE_ID, self::ROOT_ID); + return array_map(static function (array $queue): array { + return array_map(static fn (QueueFile $queueFile): int => $queueFile->getFileId(), $queue); + }, $queues); + } + + public function testEveryFileTypeReachesItsClassifier(): void { + $files = [ + ['fileid' => 1, 'image' => true, 'video' => false, 'audio' => false], + ['fileid' => 2, 'image' => false, 'video' => true, 'audio' => false], + ['fileid' => 3, 'image' => false, 'video' => false, 'audio' => true], + ]; + + $queues = $this->queuedFileIds($files); + + $this->assertSame([1], $queues[ClusteringFaceClassifier::MODEL_NAME]); + $this->assertSame([1], $queues[ImagenetClassifier::MODEL_NAME]); + $this->assertSame([2], $queues[MovinetClassifier::MODEL_NAME]); + $this->assertSame([3], $queues[MusicnnClassifier::MODEL_NAME]); + } + + public function testDisabledModelsGetNoFiles(): void { + $files = [ + ['fileid' => 1, 'image' => true, 'video' => true, 'audio' => true], + ]; + + $queues = $this->queuedFileIds($files, [], [ImagenetClassifier::MODEL_NAME]); + + $this->assertSame([], $queues[ClusteringFaceClassifier::MODEL_NAME]); + $this->assertSame([1], $queues[ImagenetClassifier::MODEL_NAME]); + $this->assertSame([], $queues[MovinetClassifier::MODEL_NAME]); + $this->assertSame([], $queues[MusicnnClassifier::MODEL_NAME]); + } + + public function testProcessedFilesAreOnlySkippedForTagBasedClassifiers(): void { + $files = [ + ['fileid' => 1, 'image' => true, 'video' => false, 'audio' => false], + ['fileid' => 2, 'image' => true, 'video' => false, 'audio' => false], + ]; + + // File 2 already carries the processed tag + $queues = $this->queuedFileIds($files, [2 => true]); + + // The face classifier does not tag files and has its own retry tracking, + // so it still receives both files. + $this->assertSame([1, 2], $queues[ClusteringFaceClassifier::MODEL_NAME]); + // Tag-based classifiers only see the untagged file. + $this->assertSame([1], $queues[ImagenetClassifier::MODEL_NAME]); + } + + public function testProcessedLookupMatchesStringAndIntKeys(): void { + $files = [ + ['fileid' => 123, 'image' => true, 'video' => false, 'audio' => false], + ]; + + // array_fill_keys() on numeric strings produces int keys, like the command does + $processedFileIds = array_fill_keys(['123'], true); + $queues = $this->queuedFileIds($files, $processedFileIds); + + $this->assertSame([123], $queues[ClusteringFaceClassifier::MODEL_NAME]); + $this->assertSame([], $queues[ImagenetClassifier::MODEL_NAME]); + } + + public function testQueueFilesCarryStorageInformation(): void { + $files = [ + ['fileid' => 7, 'image' => true, 'video' => false, 'audio' => false], + ]; + + $queues = $this->builder->build($files, [], [ImagenetClassifier::MODEL_NAME], self::STORAGE_ID, self::ROOT_ID); + $queueFile = $queues[ImagenetClassifier::MODEL_NAME][0]; + + $this->assertSame(7, $queueFile->getFileId()); + $this->assertSame(self::STORAGE_ID, $queueFile->getStorageId()); + $this->assertSame(self::ROOT_ID, $queueFile->getRootId()); + $this->assertFalse($queueFile->getUpdate()); + } +} diff --git a/tests/Service/TagManagerTest.php b/tests/Service/TagManagerTest.php new file mode 100644 index 00000000..c3fce3d6 --- /dev/null +++ b/tests/Service/TagManagerTest.php @@ -0,0 +1,76 @@ +systemTagManager = $this->createMock(ISystemTagManager::class); + $this->objectMapper = $this->createMock(ISystemTagObjectMapper::class); + $this->tagManager = new TagManager( + $this->systemTagManager, + $this->objectMapper, + $this->createMock(IEventDispatcher::class), + ); + + $processedTag = $this->createMock(ISystemTag::class); + $processedTag->method('getId')->willReturn('1'); + $this->systemTagManager->method('getTag') + ->willReturnCallback(function (string $name) use ($processedTag): ISystemTag { + if ($name === TagManager::RECOGNIZED_TAG) { + return $processedTag; + } + throw new TagNotFoundException(); + }); + } + + public function testGetProcessedFileIdsReturnsOnlyTaggedFiles(): void { + $this->objectMapper->expects($this->once()) + ->method('getTagIdsForObjects') + ->with(['10', '11', '12'], 'files') + ->willReturn([ + '10' => ['2', '3'], + '11' => ['1'], + '12' => [], + ]); + // Resolving full tag objects per file would reintroduce the N+1 pattern + $this->systemTagManager->expects($this->never())->method('getTagsByIds'); + + $this->assertSame(['11'], $this->tagManager->getProcessedFileIds(['10', '11', '12'])); + } + + public function testGetProcessedFileIdsWithEmptyInputDoesNotQuery(): void { + $this->objectMapper->expects($this->never())->method('getTagIdsForObjects'); + $this->systemTagManager->expects($this->never())->method('getTag'); + + $this->assertSame([], $this->tagManager->getProcessedFileIds([])); + } + + public function testGetProcessedFileIdsWithoutMatches(): void { + $this->objectMapper->method('getTagIdsForObjects')->willReturn([ + '10' => ['2'], + '11' => ['3', '4'], + ]); + + $this->assertSame([], $this->tagManager->getProcessedFileIds(['10', '11'])); + } +} From c1a73c872f23a0217907e68533c64e2de08902cd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benedikt=20Sch=C3=A4chner?= Date: Sat, 28 Nov 2026 12:36:39 +0000 Subject: [PATCH 6/6] fix: satisfy psalm on JobRun iteration and tag map keys Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- lib/Controller/AdminController.php | 5 ++++- lib/Service/TagManager.php | 4 +++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/lib/Controller/AdminController.php b/lib/Controller/AdminController.php index 4a8d315d..5cf2ff01 100644 --- a/lib/Controller/AdminController.php +++ b/lib/Controller/AdminController.php @@ -29,6 +29,7 @@ use OCP\AppFramework\Utility\ITimeFactory; use OCP\BackgroundJob\IJobList; use OCP\BackgroundJob\IJobRuns; +use OCP\BackgroundJob\JobRun; use OCP\DB\Exception; use OCP\Exceptions\AppConfigTypeConflictException; use OCP\IBinaryFinder; @@ -108,7 +109,9 @@ private function isModelDownloadActive(): bool { // count runs that started recently; the download itself is bounded by the // job runner and a day is far beyond any realistic download time. $maxAge = 24 * 3600; - foreach ($this->jobRuns->runningJobs() as $jobRun) { + /** @var \Generator $runningJobs */ + $runningJobs = $this->jobRuns->runningJobs(); + foreach ($runningJobs as $jobRun) { if ($jobRun->className === DownloadModelsJob::class && $jobRun->startedAt->getTimestamp() > $this->timeFactory->getTime() - $maxAge) { return true; diff --git a/lib/Service/TagManager.php b/lib/Service/TagManager.php index d41bfb11..a6da417f 100644 --- a/lib/Service/TagManager.php +++ b/lib/Service/TagManager.php @@ -108,7 +108,9 @@ public function getProcessedFileIds(array $fileIds): array { return []; } $processedTagId = $this->getProcessedTag()->getId(); - /** @var array $tagsByFile */ + // Numeric string keys are cast to int by PHP, so the key type is array-key + // even though the mapper documents string keys. + /** @var array> $tagsByFile */ $tagsByFile = $this->objectMapper->getTagIdsForObjects($fileIds, 'files'); $processedFileIds = []; foreach ($tagsByFile as $fileId => $tagIds) {