Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions appinfo/info.xml
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@ The app does not send any sensitive data to cloud providers or similar services.
<command>OCA\Recognize\Command\ClearBackgroundJobs</command>
<command>OCA\Recognize\Command\RemoveLegacyTags</command>
<command>OCA\Recognize\Command\CleanupTags</command>
<command>OCA\Recognize\Command\RemoveDuplicateFaces</command>
<command>OCA\Recognize\Command\Recrawl</command>
<command>OCA\Recognize\Command\DownloadModels</command>
<command>OCA\Recognize\Command\Classify</command>
Expand Down
2 changes: 2 additions & 0 deletions appinfo/routes.php
Original file line number Diff line number Diff line change
Expand Up @@ -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'],
Expand Down
41 changes: 41 additions & 0 deletions lib/BackgroundJobs/DownloadModelsJob.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

declare(strict_types=1);

/*
* Copyright (c) 2026 The Recognize contributors.
* This file is licensed under the Affero General Public License version 3 or later. See the COPYING file.
*/

namespace OCA\Recognize\BackgroundJobs;

use OCA\Recognize\Service\DownloadModelsService;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\BackgroundJob\QueuedJob;
use Psr\Log\LoggerInterface;

/**
* Downloads the machine learning models in the background so that administrators
* can trigger the download from the admin settings without shell access.
*/
final class DownloadModelsJob extends QueuedJob {
public function __construct(
ITimeFactory $time,
private DownloadModelsService $downloader,
private LoggerInterface $logger,
) {
parent::__construct($time);
}

/**
* @param mixed $argument unused, the job takes no arguments
*/
protected function run($argument): void {
try {
$this->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]);
}
}
}
62 changes: 15 additions & 47 deletions lib/Command/Classify.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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']);

Expand All @@ -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])) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're claiming "getTagsForFiles() keys its result by the string file id, but the lookup used the int $lastFileId, so the array access was always undefined", but PHP turns numeric string keys into ints, so IMO the old lookup worked. Did you try it?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right — I verified it: PHP casts numeric string keys to int, so $tagsByFile[$lastFileId] did resolve, and the object comparison in in_array() was non-strict so it worked too. The PR description claimed otherwise and I've corrected it. What was actually wrong with the previous revision was semantic, not the lookup: it skipped tagged files for every classifier including faces (see the other thread), and it still cost ~2 queries per file. Both are fixed in a1c9c08.

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) {
Expand Down
55 changes: 55 additions & 0 deletions lib/Command/RemoveDuplicateFaces.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<?php

declare(strict_types=1);

/*
* Copyright (c) 2026 The Recognize contributors.
* This file is licensed under the Affero General Public License version 3 or later. See the COPYING file.
*/

namespace OCA\Recognize\Command;

use OCA\Recognize\Migration\RemoveDuplicateFaceDetections;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

/**
* Exposes the duplicate face detection repair step as a manually runnable command.
*/
final class RemoveDuplicateFaces extends Command {
public function __construct(
private RemoveDuplicateFaceDetections $repairStep,
) {
parent::__construct();
}

protected function configure(): void {
$this->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('<error>Failed to remove duplicate face detections</error>');
$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;
}
}
52 changes: 51 additions & 1 deletion lib/Controller/AdminController.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand All @@ -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;
Expand All @@ -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 {
Expand All @@ -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<int, JobRun> $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();
Expand Down
50 changes: 47 additions & 3 deletions lib/Migration/InstallDeps.php
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -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/<napi-version>/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) !== '') {
Expand Down
Loading
Loading