Repository navigation
fix: honour classify --retry, avoid repeated dependency downloads, add duplicate face command and UI model download - #1616
SchBenedikt wants to merge 6 commits into
Conversation
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 nextcloud#1471 🤖 Generated with Codebuff Co-Authored-By: Codebuff <noreply@codebuff.com> Signed-off-by: Benedikt Schächner <benedikt@schaechner.dev>
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 nextcloud#1478 🤖 Generated with Codebuff Co-Authored-By: Codebuff <noreply@codebuff.com> Signed-off-by: Benedikt Schächner <benedikt@schaechner.dev>
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 nextcloud#1604 🤖 Generated with Codebuff Co-Authored-By: Codebuff <noreply@codebuff.com> Signed-off-by: Benedikt Schächner <benedikt@schaechner.dev>
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 nextcloud#1529 🤖 Generated with Codebuff Co-Authored-By: Codebuff <noreply@codebuff.com> Signed-off-by: Benedikt Schächner <benedikt@schaechner.dev>
e915f19 to
6c016dd
Compare
| if (file_exists(__DIR__ . '/../../models')) { | ||
| return new JSONResponse(['downloaded' => true, 'scheduled' => false]); | ||
| } | ||
| $this->jobList->add(DownloadModelsJob::class); |
There was a problem hiding this comment.
We should first check if the job is already running, otherwise we have multiple download jobs at the same time. (Queued Jobs are removed from the jobs table upon being started.)
There was a problem hiding this comment.
Good catch — fixed in a1c9c08. QueuedJob rows leave the jobs table once they start, so isModelDownloadActive() now also consults OCP\BackgroundJob\IJobRuns::runningJobs() and refuses to enqueue a second job while one is running. modelsStatus() uses the same check so the UI keeps polling during the download. A stale 'running' entry older than 24h is ignored so a crashed download can't block the button forever. Note there is still a tiny check-then-queue race between two simultaneous clicks; the second download is idempotent, and I mentioned it in the PR notes — happy to add an in-job lock if you prefer.
| if ($this->isFfmpegInstalled()) { | ||
| $output->info('ffmpeg binary is already installed, skipping download.'); | ||
| } else { | ||
| $this->runFfmpegInstall($binaryPath); |
There was a problem hiding this comment.
Doesn't this skip installing ffmpeg when GPU install fails?
There was a problem hiding this comment.
Yes, it did — the steps ran sequentially and a GPU failure aborted the rest. Fixed in a1c9c08: each install step now goes through runInstallStep(), which catches the failure, reports it as a warning and lets the remaining steps run. Covered by tests/InstallDepsTest.php, which uses a fake node binary that fails the GPU install and asserts ffmpeg is still installed.
| 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)) { |
There was a problem hiding this comment.
I think the face classification pipeline doesn't add processed tags to files, so this will skip all tagged files from being processed by face classification.
There was a problem hiding this comment.
You're right, and this was the most important catch — the first revision skipped tagged files for all classifiers, but the face classifier never tags files and deduplicates via faceDetections instead. Fixed in a1c9c08: queue distribution moved into ClassificationQueueBuilder, which queues images for faces unconditionally and only applies the processed-tag skip to the tag-based classifiers (imagenet/movinet/musicnn). Covered by ClassificationQueueBuilderTest.
| // 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) |
There was a problem hiding this comment.
Doesn't this method still loop over the fileIds with one query per file?
There was a problem hiding this comment.
It did — getTagsForFiles() internally calls getTagIdsForObjects() plus a getTagsByIds() per file just to resolve full tag objects we never used. Fixed in a1c9c08: the new TagManager::getProcessedFileIds() only resolves tag ids, so the whole page is fetched with a single getTagIdsForObjects() query (one query per page instead of ~2 per file).
| 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])) { |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
… 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>
Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Summary
This PR bundles four independent improvements for maintenance and administration. They were chosen because each has a clear, reproducible root cause in the current code and can be reviewed in isolation:
fix(Classify): skip already processed files with --retryfix(InstallDeps): do not re-download installed TF.js and ffmpeg binariesfeat(Command): add recognize:remove-duplicate-faces with --dry-runfeat(Admin): download models from the admin settingsfix: address review feedback on classify retry, install isolation and model downloadsChanges
1.
occ recognize:classify --retryskipped nothing (#1471)On
main, the retry check fetched tags per file (getTagIdsForObjects()+getTagsByIds()— two queries per file) and the processed-tag comparison lived inside the per-file loop. The first revision of this PR moved the check in front of the queue building, which silently changed the semantics: files carrying the processed tag were skipped for every classifier, including the face classifier — which never tags files and tracks progress in the face detection table instead. That would have re-queued already-processed images for faces on every--retryrun, and the opposite direction (a file processed by faces but not by the tag-based classifiers) was never reachable.The command now:
TagManager::getProcessedFileIds()(tag ids only — the previous path also loaded full tag objects per file),ClassificationQueueBuilder, which is unit-tested,faceDetections), while imagenet/movinet/musicnn skip only files that carry the processed tag.2.
occ maintenance:repairre-downloaded ~150 MB every time (#1478)InstallDeps::run()unconditionally executed thetfjs-node,tfjs-node-gpuandffmpeg-staticinstall scripts, so every repair run downloaded the binaries again — even without--include-expensive.The install scripts now only run if the corresponding artifact is missing:
node_modules/@tensorflow/tfjs-node{,-gpu}/lib/<napi>/tfjs_binding.nodenode_modules/ffmpeg-static/ffmpegCPU and GPU are checked separately, so a missing GPU binding does not trigger a CPU re-download. Each step is additionally isolated (
runInstallStep()): a failing install is reported as a warning and the remaining steps still run, so e.g. atfjs-node-gpufailure can no longer prevent the ffmpeg install. This is covered bytests/InstallDepsTest.php, which drives the realrun()with a fakenodebinary.3. New
occ recognize:remove-duplicate-faceswith--dry-run(#1604)The duplicate face detection repair step added in #1318 was only reachable through the repair step. This exposes it to administrators:
RemoveDuplicateFaceDetectionsnow exposesremoveDuplicates(bool $dryRun): int;run()uses it, so the repair step and the command share one implementation and cannot drift apart. The command is registered inappinfo/info.xmland documented in the admin settings' "Terminal commands" section.A unit test asserts that a dry run reports the duplicates but leaves the table untouched.
4. Download the models from the admin settings (#1529)
Installations without shell access (managed hosting, Docker images without
occ) previously could not download the models. The status card now offers a Download models button:GET /apps/recognize/admin/downloadModelsqueues aDownloadModelsJob— but only if no download is already queued or running. Queued jobs leave thejobstable as soon as they start, so the check additionally consultsOCP\BackgroundJob\IJobRuns::runningJobs(); a stale "running" entry older than 24h is ignored so a crashed download cannot block the button forever.GET /apps/recognize/admin/modelsStatusreportsdownloaded/scheduledwith the same active-job detection, so the UI keeps polling while a download is in flight.QueuedJob, not in the HTTP request (the archive is ~1.4 GB)models/existsocc recognize:download-modelsnote stays visible as an alternativeVerification
Run in this environment (PHP 8.5.9, Node 24):
php -lon every changed PHP file — no syntax errorsphp-cs-fixeron all touched files — cleanClassificationQueueBuilderTest(5),TagManagerTest(3),TagManagerAuditTest(8),InstallDepsTest(5),AdminControllerTest(7, requires the NC3rdpartyautoloader for DBAL types)eslint src/components/ViewAdmin.vue— 0 errors (the 6vue/attributes-orderwarnings are pre-existing on untouched lines)appinfo/info.xmlparses withsimplexml_load_file()composer installandnpm ci --ignore-scriptssucceed, so the dependency manifests are consistentNot executable here: the full PHPUnit suite and Psalm. App tests bootstrap from
../../../tests/bootstrap.php, i.e. a full Nextcloud server checkout, which is not available on this machine; Psalm 6.5 additionally crashes on PHP 8.5 (SplObjectStorage::attach()deprecation in its own error handler). CI should be authoritative for both — note the pre-existingFsActionServiceTestfailures (Trashbin::deleteAll()signature) are unrelated to this PR.Notes for reviewers
jobList->add(); two simultaneous clicks could enqueue two jobs, but the second download is idempotent (it re-downloads into the same directory). Hardening the job itself against concurrent execution would need a lock insideDownloadModelsJob— happy to add that if you prefer.models/is committed in the repository (the release package strips it), so in a development checkout the UI already considers the models downloaded. This matches the existingAdminSettingsinitial state and is unchanged.InstallDeps), Added a Setting to set the Model Download Folder #1557 (configurable model folder), Feat/link faces to contacts #1580 (contacts integration) or feat(Classify): allow specifying user/path #905 #1225 (--user/--pathforrecognize:classify).Follow-ups this PR does not attempt
RemoveDuplicateFaceDetection#1604