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/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..2ea6c364 --- /dev/null +++ b/lib/BackgroundJobs/DownloadModelsJob.php @@ -0,0 +1,41 @@ +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/Command/Classify.php b/lib/Command/Classify.php index d48eeaf4..58b3b4ac 100644 --- a/lib/Command/Classify.php +++ b/lib/Command/Classify.php @@ -12,8 +12,8 @@ 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; @@ -42,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; @@ -85,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']); @@ -100,50 +99,19 @@ 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++; - $lastFileId = $file['fileid']; - $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 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; - } - } - 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; - } - } + $files = iterator_to_array( + $this->storageService->getFilesInMount($mount['storage_id'], $mount['override_root'], $models, $lastFileId), + false + ); + $i = count($files); + // 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); + $processedFileIds = $input->getOption('retry') && count($fileIds) > 0 + ? array_fill_keys($this->tagManager->getProcessedFileIds($fileIds), true) + : []; + $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) { 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/Controller/AdminController.php b/lib/Controller/AdminController.php index 0aee1ac1..5cf2ff01 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; @@ -25,7 +26,10 @@ 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\BackgroundJob\JobRun; use OCP\DB\Exception; use OCP\Exceptions\AppConfigTypeConflictException; use OCP\IBinaryFinder; @@ -41,8 +45,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; @@ -53,6 +59,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 { @@ -70,6 +78,48 @@ 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]); + } + // 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->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; + /** @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; + } + } + return false; + } + public function resetFaces(): JSONResponse { try { $this->clusterMapper->deleteAll(); diff --git a/lib/Migration/InstallDeps.php b/lib/Migration/InstallDeps.php index 4f074c23..9efad2ac 100644 --- a/lib/Migration/InstallDeps.php +++ b/lib/Migration/InstallDeps.php @@ -91,9 +91,27 @@ 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 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->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->runInstallStep($output, 'TensorFlow.js GPU binaries', fn () => $this->runTfjsGpuInstall($binaryPath)); + } + + if ($this->isFfmpegInstalled()) { + $output->info('ffmpeg binary is already installed, skipping download.'); + } else { + $this->runInstallStep($output, 'ffmpeg binary', fn () => $this->runFfmpegInstall($binaryPath)); + } + $this->setNodeModulesPermissions(); $this->setNiceBinaryPath(); $this->setFfmpegBinaryPath(); @@ -103,6 +121,32 @@ 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); + } + + /** + * 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/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/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..a6da417f 100644 --- a/lib/Service/TagManager.php +++ b/lib/Service/TagManager.php @@ -95,6 +95,32 @@ 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(); + // 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) { + if (in_array($processedTagId, $tagIds, true)) { + $processedFileIds[] = (string)$fileId; + } + } + return $processedFileIds; + } + /** * @return list */ 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')) 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/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(); 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'])); + } +}