Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: let a dataset of clips be selected for training (#8287)
Daniel Hand6956c383e56
diff --git a/studio/backend/core/training/diffusion_clip_formats.py b/studio/backend/core/training/diffusion_clip_formats.pynew file mode 100644index 00000000000..695000c990e--- /dev/null+++ b/studio/backend/core/training/diffusion_clip_formats.py@@ -0,0 +1,24 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The one list of video container extensions a training dataset may hold.++Studio's diffusion dataset layer grew up image-only, so the routes carry their own+``_DIFFUSION_DATASET_IMAGE_EXTS``. Clips need the same treatment, but a clip dataset is read+by the trainer and written by the upload endpoint, and those live on opposite sides of the+backend. Putting the set in either one makes the other import it across a layer it has no+business importing (the routes would pull a trainer module; the trainer would pull FastAPI).+So it lives here, in a module with no imports at all, and both sides read it from here.++Keeping it in one place is not cosmetic. Discovery, the upload allowlist and the duplicate-stem+check all have to agree on what a clip is: a container the upload accepts but discovery does+not count is a dataset that uploads fine and then trains on nothing.+"""++from __future__ import annotations++# Containers the video decode path (PyAV) opens. Lowercase, with the leading dot, so a+# ``Path.suffix.lower()`` can be tested against the set directly.+CLIP_EXTS = frozenset({".mp4", ".mov", ".mkv", ".webm", ".m4v", ".avi"})++__all__ = ["CLIP_EXTS"]diff --git a/studio/backend/models/training.py b/studio/backend/models/training.pyindex c8fde04d396..3773ae709b6 100644--- a/studio/backend/models/training.py+++ b/studio/backend/models/training.py@@ -1074,11 +1074,14 @@ class DiffusionTrainingRunsResponse(BaseModel):class DiffusionDatasetSummary(BaseModel):- """One image-dataset folder under the Studio datasets root."""+ """One dataset folder under the Studio datasets root: images, clips, or both."""name: strpath: strimage_count: int+ # Clips, for the families that train from video. Defaults to 0 so an older backend's+ # payload (and every image-only caller) stays valid.+ clip_count: int = 0caption_count: int@@ -1116,12 +1119,15 @@ class DiffusionTrainingInfoResponse(BaseModel):class DiffusionDatasetUploadResponse(BaseModel):- """Result of uploading images/captions into a named dataset folder. Counts are+ """Result of uploading images/clips/captions into a named dataset folder. Counts arefor the whole folder after the upload, so repeat uploads show the running total."""name: strpath: strimage_count: int+ # Clips, for the families that train from video. Defaults to 0 so an older backend's+ # payload (and every image-only caller) stays valid.+ clip_count: int = 0caption_count: intuploaded: int@@ -1135,13 +1141,17 @@ class DiffusionDatasetImageRecord(BaseModel):filename: strcaption: Optional[str] = Nonecaption_source: Literal["sidecar", "metadata", "none"] = "none"+ # Which kind of item this is. Clips are listed so a caller can see everything the folder+ # holds under a stem, but they carry no pixel dimensions and the labeling grid skips them.+ # Defaults to "image" so an older backend's payload still validates.+ kind: Literal["image", "clip"] = "image"width: intheight: intsize_bytes: intclass DiffusionDatasetImagesResponse(BaseModel):- """Every image in a dataset folder (including uncaptioned ones), for the labeling grid."""+ """Every item in a dataset folder (including uncaptioned ones), for the labeling grid."""name: strpath: str@@ -1189,6 +1199,9 @@ class DiffusionDatasetImportResponse(BaseModel):name: strpath: strimage_count: int+ # Clips, for the families that train from video. Defaults to 0 so an older backend's+ # payload (and every image-only caller) stays valid.+ clip_count: int = 0caption_count: intimported: intlicense: strdiff --git a/studio/backend/routes/training.py b/studio/backend/routes/training.pyindex 3e3448038dc..b0eaef87bb4 100644--- a/studio/backend/routes/training.py+++ b/studio/backend/routes/training.py@@ -37,6 +37,7 @@ if str(backend_path) not in sys.path:try:from core.training import get_training_backend+ from core.training.diffusion_clip_formats import CLIP_EXTS as _CLIP_EXTSfrom core.training.training import (TrainingStartCancellationCapacityError,TrainingStatusIdentitySnapshot,@@ -57,6 +58,7 @@ except ImportError:if str(parent_backend) not in sys.path:sys.path.insert(0, str(parent_backend))from core.training import get_training_backend+ from core.training.diffusion_clip_formats import CLIP_EXTS as _CLIP_EXTSfrom core.training.training import (TrainingStartCancellationCapacityError,TrainingStatusIdentitySnapshot,@@ -2851,6 +2853,15 @@ async def start_diffusion_training(try:service.reserve()reserved = True+ # Fail closed on clips BEFORE that discovery, which cannot see them: clip-only it+ # reports the folder as uncaptioned, and mixed it succeeds on the images and trains on+ # that subset without saying so.+ # In a worker thread like the discovery below it, and for the same reason: the scan stats+ # every file and reads the caption sidecars, which on a large or network-mounted dataset+ # would hold the event loop and stall status/stop alongside it.+ clip_refusal = await asyncio.to_thread(_clip_dataset_refusal, config["data_dir"])+ if clip_refusal is not None:+ raise HTTPException(status_code = 400, detail = clip_refusal)# Preflight the dataset: a missing/empty/uncaptionable data_dir otherwise fails inside the trainer AFTER eviction. Same discovery the trainer runs, so the two cannot disagree.try:pairs = await asyncio.to_thread(@@ -2972,18 +2983,34 @@ async def get_diffusion_training_run(raise HTTPException(status_code = 404, detail = "No such training run.")-# Extensions accepted into an image-training dataset folder: images the trainer reads, plus its caption sources (per-image sidecars and metadata/captions jsonl).+# Extensions accepted into a diffusion-training dataset folder: the media the trainer reads, plus its caption sources (per-item sidecars and metadata/captions jsonl)._DIFFUSION_DATASET_IMAGE_EXTS = {".png", ".jpg", ".jpeg", ".webp", ".bmp"}+# Video containers, for the families that train from clips rather than stills. Read from the one+# shared definition so the trainer's discovery and this endpoint cannot drift apart.+_DIFFUSION_DATASET_CLIP_EXTS = set(_CLIP_EXTS)+# The trainable unit of a dataset, whichever kind it is. Every rule that is about "an item and its+# caption" -- the upload allowlist, the shared-sidecar check, the delete -- keys off this set, and+# only the rules that are genuinely about pixels (the decompression-bomb check, the labeling grid's+# thumbnails) stay on _DIFFUSION_DATASET_IMAGE_EXTS.+#+# The two halves are DISJOINT and the caption rules over them are IDENTICAL (a <stem>.txt /+# <stem>.caption sidecar wins, then a metadata.jsonl / captions.jsonl row, then the trigger+# prompt), which is what makes clip support purely additive: no path an image dataset can take+# through this file changes. test_diffusion_dataset_clips.py asserts both of those properties.+_DIFFUSION_DATASET_MEDIA_EXTS = _DIFFUSION_DATASET_IMAGE_EXTS | _DIFFUSION_DATASET_CLIP_EXTS_DIFFUSION_DATASET_TEXT_EXTS = {".txt", ".caption", ".jsonl"}def _resolve_dataset_caption(folder: Path, image_path: Path, meta_captions: dict[str, str]) -> Optional[str]:- """Resolve an image's caption using the same sidecar > metadata precedence the trainer- applies in ``discover_image_caption_pairs``. A per-image .txt/.caption sidecar wins and+ """Resolve an item's caption using the same sidecar > metadata precedence the trainer+ applies in ``discover_image_caption_pairs``. A per-item .txt/.caption sidecar wins andis stripped, so an empty (tombstone) sidecar shadows metadata and yields "" -- the- trainer then skips that image (``if caption:``), so it must not count as captioned."""+ trainer then skips that item (``if caption:``), so it must not count as captioned.++ Clips resolve through this same function unchanged: the clip discovery the video trainers+ use applies the identical precedence, only over a different extension set."""caption: Optional[str] = Nonesidecar_present = Falsefor ext in (".txt", ".caption"):@@ -3035,6 +3062,7 @@ def _import_response(name = folder.name,path = str(folder),image_count = summary.image_count,+ clip_count = summary.clip_count,caption_count = summary.caption_count,imported = imported,license = entry["license"],@@ -3043,17 +3071,56 @@ def _import_response(def _diffusion_dataset_summary(folder: Path) -> DiffusionDatasetSummary:- # Count an image as captioned only when it resolves to a NON-EMPTY caption via the trainer's sidecar-over-metadata precedence: an empty tombstone makes the trainer skip the image.+ # Count an item as captioned only when it resolves to a NON-EMPTY caption via the trainer's sidecar-over-metadata precedence: an empty tombstone makes the trainer skip the item.+ # Images and clips are counted separately (the UI names them differently and only one family+ # kind can read each), but captions are one folder total: the resolution rule is the same.meta_captions = _load_metadata_captions(folder)- images = captions = 0+ images = clips = captions = 0for f in folder.iterdir():- if not f.is_file() or f.suffix.lower() not in _DIFFUSION_DATASET_IMAGE_EXTS:+ if not f.is_file():+ continue+ ext = f.suffix.lower()+ if ext in _DIFFUSION_DATASET_IMAGE_EXTS:+ images += 1+ elif ext in _DIFFUSION_DATASET_CLIP_EXTS:+ clips += 1+ else:continue- images += 1if _resolve_dataset_caption(folder, f, meta_captions):captions += 1return DiffusionDatasetSummary(- name = folder.name, path = str(folder), image_count = images, caption_count = captions+ name = folder.name,+ path = str(folder),+ image_count = images,+ clip_count = clips,+ caption_count = captions,+ )+++def _clip_dataset_refusal(data_dir: str) -> Optional[str]:+ """Why a folder holding clips cannot be trained on yet, or None when it can.++ No trainer reads clips, and ``discover_image_caption_pairs`` scans stills only, so+ without this a clip folder fails two different ways and neither says so. Clip-only, it+ raises "No captioned images found. Provide ... per-image .txt captions", which is wrong+ twice over on a folder where every clip has one. MIXED, it succeeds on the images and+ the run trains on that subset in silence, while the picker counted the clips as+ trainable items. So the rule is the folder, not the outcome: any clip present, refuse.++ The dataset layer still lists these folders, because uploading and captioning a clip set+ is what lets one exist before the trainer does. Once discovery reads clips this check+ goes with it."""+ try:+ summary = _diffusion_dataset_summary(Path(data_dir).expanduser())+ except OSError:+ return None+ if summary.clip_count <= 0:+ return None+ clips = f"{summary.clip_count} video clip" + ("" if summary.clip_count == 1 else "s")+ return (+ f"'{Path(data_dir).expanduser().name}' holds {clips}. Training from clips is not "+ "supported yet, and a run started here would train on the still images alone. "+ "Choose a dataset of images, or take the clips out of this folder.")@@ -3062,7 +3129,8 @@ async def diffusion_training_info(current_subject: str = Depends(get_current_sub"""Describe where diffusion training reads/writes, and list usable dataset folders.A dataset folder is any direct child of the datasets root that contains at least one- image. The UI uses this to offer a picker instead of a blind free-text path."""+ trainable item: an image, or a clip for the families that train from video. The UI uses+ this to offer a picker instead of a blind free-text path."""from utils.paths import datasets_root, outputs_rootdef scan() -> DiffusionTrainingInfoResponse:@@ -3083,7 +3151,8 @@ async def diffusion_training_info(current_subject: str = Depends(get_current_subsummary = _diffusion_dataset_summary(child)except OSError:continue- if summary.image_count > 0:+ # A clip-only folder is a real dataset for the video families, so admit on either count.+ if summary.image_count > 0 or summary.clip_count > 0:found.append(summary)from core.training.diffusion_train_common import family_train_infos@@ -3210,8 +3279,8 @@ async def upload_diffusion_dataset(limit_bytes = get_upload_limit_bytes()total_bytes = 0uploaded = 0- allowed = _DIFFUSION_DATASET_IMAGE_EXTS | _DIFFUSION_DATASET_TEXT_EXTS- # Validate every filename up front so a valid image ahead of a bad one is not left on disk when the 400 fires; the upload is all-or-nothing.+ allowed = _DIFFUSION_DATASET_MEDIA_EXTS | _DIFFUSION_DATASET_TEXT_EXTS+ # Validate every filename up front so a valid file ahead of a bad one is not left on disk when the 400 fires; the upload is all-or-nothing.names: list[str] = []for f in files:# Normalise to a safe basename. Path.name does not split on a backslash on POSIX, so fold@@ -3236,9 +3305,11 @@ async def upload_diffusion_dataset("uploading."),)- # Reject a second IMAGE sharing this stem but differing by extension (sample.png vs .jpg):- # both resolve to the same <stem>.txt sidecar. Caption files are exempt.- if ext in _DIFFUSION_DATASET_IMAGE_EXTS:+ # Reject a second ITEM sharing this stem but differing by extension (sample.png vs .jpg,+ # or sample.png vs sample.mp4): both resolve to the same <stem>.txt sidecar. Caption+ # files are exempt. Images and clips are compared together, not per kind, because the+ # sidecar they would collide on is keyed on the stem alone and knows nothing of kind.+ if ext in _DIFFUSION_DATASET_MEDIA_EXTS:stem = Path(filename).stem# Compare stems case-insensitively: on case-insensitive filesystems two stems differing only# by case resolve to the SAME sidecar. cat.PNG vs cat.png is not exempt.@@ -3248,7 +3319,7 @@ async def upload_diffusion_dataset(other = Path(other_name)if (other_name == filename- or other.suffix.lower() not in _DIFFUSION_DATASET_IMAGE_EXTS+ or other.suffix.lower() not in _DIFFUSION_DATASET_MEDIA_EXTSor other.stem.casefold() != stem_cf):return False@@ -3262,11 +3333,12 @@ async def upload_diffusion_dataset(if clash is None:clash = next((n for n in names if _shares_sidecar(n)), None)if clash is not None:+ kind = "clip" if ext in _DIFFUSION_DATASET_CLIP_EXTS else "image"raise HTTPException(status_code = 400,detail = (- f"Duplicate image name '{stem}'. '{clash}' is already in this "- f"dataset; two images sharing a name would share one '{stem}.txt' "+ f"Duplicate {kind} name '{stem}'. '{clash}' is already in this "+ f"dataset; two files sharing a name would share one '{stem}.txt' "f"caption. Rename one before uploading."),)@@ -3305,11 +3377,13 @@ async def upload_diffusion_dataset(detail = ("Dataset upload too large. "f"Maximum is {get_upload_limit_label()} per upload; "- "add the remaining images in another batch."+ "add the remaining files in another batch."),)out.write(chunk)# Reject a decompression bomb before commit: a small PNG can pass the byte limit yet decode to huge pixels and OOM the trainer's latent cache.+ # Images only. A clip's frames are bounded by the canvas the video trainer resizes+ # to, not by the container, so there is no equivalent still to decode here.if Path(filename).suffix.lower() in _DIFFUSION_DATASET_IMAGE_EXTS:_validate_uploaded_training_image(tmp, filename)uploaded += 1@@ -3364,6 +3438,7 @@ async def upload_diffusion_dataset(name = cleaned,path = str(folder),image_count = summary.image_count,+ clip_count = summary.clip_count,caption_count = summary.caption_count,uploaded = uploaded,)@@ -3528,17 +3603,20 @@ def _image_record(size_bytes = image_path.stat().st_sizeexcept OSError:size_bytes = 0+ is_clip = image_path.suffix.lower() in _DIFFUSION_DATASET_CLIP_EXTSwidth = height = 0- try:- from PIL import Image- with Image.open(image_path) as im:- width, height = im.size- except Exception: # noqa: BLE001 -- an unreadable image still lists (0x0) rather than 500- pass+ if not is_clip:+ try:+ from PIL import Image+ with Image.open(image_path) as im:+ width, height = im.size+ except Exception: # noqa: BLE001 -- an unreadable image still lists (0x0) rather than 500+ passreturn DiffusionDatasetImageRecord(filename = image_path.name,caption = caption,caption_source = source, # type: ignore[arg-type]+ kind = "clip" if is_clip else "image",width = width,height = height,size_bytes = size_bytes,@@ -3549,15 +3627,19 @@ def _image_record(async def list_diffusion_dataset_images(name: str, current_subject: str = Depends(get_current_subject)):- """List every image in a dataset folder with its resolved caption (including- uncaptioned images), for the labeling grid."""+ """List every item in a dataset folder with its resolved caption (including+ uncaptioned ones), for the labeling grid.++ Clips are listed with ``kind: "clip"`` and 0x0 dimensions. The grid renders images only,+ but the upload's pre-flight needs every name that holds a ``<stem>.txt`` sidecar open, and+ a clip does that just as an image does."""folder = _resolve_dataset_folder(name)def scan() -> DiffusionDatasetImagesResponse:meta = _load_metadata_captions(folder)records: list[DiffusionDatasetImageRecord] = []for p in sorted(folder.iterdir()):- if p.is_file() and p.suffix.lower() in _DIFFUSION_DATASET_IMAGE_EXTS:+ if p.is_file() and p.suffix.lower() in _DIFFUSION_DATASET_MEDIA_EXTS:records.append(_image_record(folder, p, meta))return DiffusionDatasetImagesResponse(name = folder.name, path = str(folder), images = records)@@ -3676,11 +3758,28 @@ async def delete_diffusion_dataset_image(image_path.unlink(missing_ok = True)# Sidecars are keyed on the STEM, so cat.jpg and cat.png share cat.txt: deleting it with one# would strip the survivor's caption. New collisions are refused at upload; legacy ones exist.+ # Fold stems only where the filesystem folds them, off the same probe the upload's case+ # checks use. Where it folds, CAT.mp4 reads the very file cat.png calls cat.txt, so an+ # exact compare would not see the survivor and would unlink its caption. Where it does+ # not, those are two separate sidecars, and folding would strand cat.txt for whatever+ # later takes the cat stem to inherit.+ folds_case = _dataset_folder_is_case_insensitive(folder)++ def same_stem(p: Path) -> bool:+ return (+ p.stem.casefold() == image_path.stem.casefold()+ if folds_case+ else p.stem == image_path.stem+ )+stem_still_used = any(p.is_file()and p != image_path- and p.stem == image_path.stem- and p.suffix.lower() in _DIFFUSION_DATASET_IMAGE_EXTS+ and same_stem(p)+ # Clips share the stem-keyed sidecar with images, so a cat.mp4 beside cat.png holds+ # cat.txt open just as a second image would. Checking images alone would strip the+ # clip's caption when the image is deleted.+ and p.suffix.lower() in _DIFFUSION_DATASET_MEDIA_EXTSfor p in folder.iterdir())if not stem_still_used:@@ -3957,7 +4056,10 @@ async def import_diffusion_dataset_example(def do_import() -> DiffusionDatasetImportResponse:folder.mkdir(parents = True, exist_ok = True)- if _diffusion_dataset_summary(folder).image_count > 0:+ # Any trainable item already in the folder makes this a no-op: dropping example images+ # into a folder the user filled with clips would silently mix two dataset kinds.+ summary = _diffusion_dataset_summary(folder)+ if summary.image_count > 0 or summary.clip_count > 0:return _import_response(entry, folder, imported = 0)# One import at a time per dataset folder: the training interlock COUNTS mutations rather than excluding them, so two# imports into the same empty name both passed the emptiness check and merged. Refusing the second is honest.@@ -3983,7 +4085,7 @@ async def import_diffusion_dataset_example(imported = 0# Re-read under the lock: a winner may have promoted its staging dir while this request was checking, so returning the folder as-is matches the idempotent path.existing = _diffusion_dataset_summary(folder)- if existing.image_count == 0:+ if existing.image_count == 0 and existing.clip_count == 0:cap = int(entry["image_cap"])# Materialize into a private staging dir and promote only after the whole import succeeds, so a partial materialize# leaves only that dir. Staged as a hidden same-filesystem sibling so promotion is an atomic rename.diff --git a/studio/backend/tests/test_diffusion_dataset_clips.py b/studio/backend/tests/test_diffusion_dataset_clips.pynew file mode 100644index 00000000000..1daafa40fd6--- /dev/null+++ b/studio/backend/tests/test_diffusion_dataset_clips.py@@ -0,0 +1,441 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Clip datasets in the diffusion dataset routes.++The families that train from video read a folder of clips and the caption beside each one.+Before this, the routes only knew about images, so such a folder summarised as empty and+``/diffusion/info`` never listed it: the video trainer was unreachable from the UI.++The claim these tests exist to hold is that admitting clips is PURELY ADDITIVE. That rests on+two properties, both asserted below rather than asserted in prose:++* the image and clip extension sets are DISJOINT, so no file changes which branch it takes;+* the caption rules over them are IDENTICAL, so a clip resolves its caption through the very+ same function, with the same sidecar-over-metadata precedence and the same empty-sidecar+ tombstone, as an image does.++Everything else here is the behaviour those two properties buy: a clip folder is listed, a+clip uploads with its sidecar, and the stem-keyed sidecar is shared between kinds exactly as+it is shared between two images.+"""++from __future__ import annotations++import io+import json++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient+from PIL import Image++from auth.authentication import get_current_subject+from core.training.diffusion_clip_formats import CLIP_EXTS+from routes.training import (+ _DIFFUSION_DATASET_CLIP_EXTS,+ _DIFFUSION_DATASET_IMAGE_EXTS,+ _DIFFUSION_DATASET_MEDIA_EXTS,+ _diffusion_dataset_summary,+ _resolve_dataset_caption,+)+from routes.training import router as training_router+++def _write_png(+ path,+ color = (200, 100, 50),+ size = (8, 8),+) -> None:+ Image.new("RGB", size, color).save(path, format = "PNG")+++def _png_bytes(color = (200, 100, 50), size = (8, 8)) -> bytes:+ buf = io.BytesIO()+ Image.new("RGB", size, color).save(buf, format = "PNG")+ return buf.getvalue()+++# An mp4 is never decoded by these routes, only counted and moved, so a recognisable ftyp box+# is enough to stand in for one. Nothing here opens it.+_MP4_BYTES = b"\x00\x00\x00\x18ftypmp42" + b"\x00" * 64+++def client():+ app = FastAPI()+ app.include_router(training_router, prefix = "/api/train")+ app.dependency_overrides[get_current_subject] = lambda: "test-user"+ return TestClient(app)+++def ds_root(monkeypatch, tmp_path):+ import utils.paths as up++ root = tmp_path / "assets" / "datasets"+ root.mkdir(parents = True)+ monkeypatch.setattr(up, "datasets_root", lambda: root)+ return root+++# ── the additive claim ───────────────────────────────────────────────────────+def test_image_and_clip_extension_sets_are_disjoint():+ """The whole design rests on this. Every site that widened from images to media assumes an+ extension belongs to exactly ONE kind: the summary picks its counter with an if/elif, so an+ overlapping extension would count as an image and never as a clip, and the two counts would+ stop summing to the number of trainable files in the folder."""+ assert _DIFFUSION_DATASET_IMAGE_EXTS & _DIFFUSION_DATASET_CLIP_EXTS == set()+ assert _DIFFUSION_DATASET_MEDIA_EXTS == (+ _DIFFUSION_DATASET_IMAGE_EXTS | _DIFFUSION_DATASET_CLIP_EXTS+ )+ assert len(_DIFFUSION_DATASET_MEDIA_EXTS) == len(_DIFFUSION_DATASET_IMAGE_EXTS) + len(+ _DIFFUSION_DATASET_CLIP_EXTS+ )+ # Every extension is lowercase and dotted, since every test site compares Path.suffix.lower().+ for ext in _DIFFUSION_DATASET_MEDIA_EXTS:+ assert ext == ext.lower() and ext.startswith(".") and len(ext) > 1+++def test_routes_read_the_shared_clip_definition():+ """The routes must not carry their own copy: a container the upload accepts but the+ trainer's discovery does not read is a dataset that uploads fine and trains on nothing."""+ assert _DIFFUSION_DATASET_CLIP_EXTS == set(CLIP_EXTS)+++def test_trainer_clip_discovery_uses_the_same_set_when_it_is_present():+ """A divergence tripwire for the video trainers.++ The clip trainer lands separately from this. Once it is in the tree its own extension set+ has to be the shared one, or the two halves can drift: a clip the upload accepts and the+ summary counts but the trainer skips is a run that starts and trains on nothing. Skipped+ while the module is absent, enforced the moment it appears."""+ clips = pytest.importorskip("core.training.diffusion_h3_clips")+ assert set(clips._VIDEO_EXTS) == set(CLIP_EXTS)+++def test_clip_captions_resolve_through_the_same_rules_as_images(tmp_path):+ """Identical caption rules, asserted by running BOTH kinds through the one resolver over the+ same four cases. If any row ever differs, clip support has stopped being additive."""+ folder = tmp_path / "mixed"+ folder.mkdir()+ meta = {+ "sidecar.png": "from metadata",+ "sidecar.mp4": "from metadata",+ "meta.png": "from metadata",+ "meta.mp4": "from metadata",+ "tombstone.png": "from metadata",+ "tombstone.mp4": "from metadata",+ }+ for stem in ("sidecar", "meta", "tombstone", "bare"):+ _write_png(folder / f"{stem}.png")+ (folder / f"{stem}.mp4").write_bytes(_MP4_BYTES)+ # A sidecar wins over the metadata row; an EMPTY sidecar is a tombstone that shadows it.+ (folder / "sidecar.txt").write_text("edited sidecar", encoding = "utf-8")+ (folder / "tombstone.txt").write_text(" ", encoding = "utf-8")++ # sidecar.txt is shared by sidecar.png and sidecar.mp4 here on purpose: that sharing is the+ # point, and it is what the upload's stem check refuses to let a user create by accident.+ for stem, expected in (+ ("sidecar", "edited sidecar"),+ ("meta", "from metadata"),+ ("tombstone", ""),+ ("bare", None),+ ):+ image = _resolve_dataset_caption(folder, folder / f"{stem}.png", meta)+ clip = _resolve_dataset_caption(folder, folder / f"{stem}.mp4", meta)+ assert image == expected, stem+ assert clip == expected, stem+ assert image == clip, stem+++def test_an_image_only_dataset_summarises_exactly_as_before(tmp_path):+ """The regression guard on the additive claim: nothing about an image dataset moves."""+ folder = tmp_path / "styleset"+ folder.mkdir()+ _write_png(folder / "a.png")+ _write_png(folder / "b.jpg")+ _write_png(folder / "c.webp")+ (folder / "a.txt").write_text("a cat", encoding = "utf-8")+ (folder / "metadata.jsonl").write_text(+ json.dumps({"file_name": "b.jpg", "text": "a dog"}) + "\n", encoding = "utf-8"+ )+ (folder / "notes.pdf").write_bytes(b"not a dataset file")++ summary = _diffusion_dataset_summary(folder)+ assert summary.image_count == 3+ assert summary.clip_count == 0+ assert summary.caption_count == 2+++# ── summary + listing ────────────────────────────────────────────────────────+def test_summary_counts_clips_and_their_captions(tmp_path):+ folder = tmp_path / "clipset"+ folder.mkdir()+ for name in ("one.mp4", "two.MOV", "three.webm"):+ (folder / name).write_bytes(_MP4_BYTES)+ (folder / "one.txt").write_text("a waterfall", encoding = "utf-8")+ (folder / "captions.jsonl").write_text(+ json.dumps({"file_name": "two.MOV", "text": "a train"}) + "\n", encoding = "utf-8"+ )++ summary = _diffusion_dataset_summary(folder)+ assert summary.image_count == 0+ assert summary.clip_count == 3+ # Captions are one folder total over both kinds; three.webm has none from any source.+ assert summary.caption_count == 2+++def test_summary_counts_a_mixed_folder_by_kind(tmp_path):+ folder = tmp_path / "both"+ folder.mkdir()+ _write_png(folder / "still.png")+ (folder / "moving.mp4").write_bytes(_MP4_BYTES)++ summary = _diffusion_dataset_summary(folder)+ assert (summary.image_count, summary.clip_count) == (1, 1)+++def test_info_lists_a_clip_only_dataset(client, ds_root):+ """The bug this change exists to fix: a folder of clips was never offered in the picker,+ so the video trainer could not be pointed at anything."""+ folder = ds_root / "clipset"+ folder.mkdir()+ (folder / "one.mp4").write_bytes(_MP4_BYTES)+ (folder / "one.txt").write_text("a waterfall", encoding = "utf-8")++ r = client.get("/api/train/diffusion/info")+ assert r.status_code == 200, r.text+ datasets = {d["name"]: d for d in r.json()["datasets"]}+ assert "clipset" in datasets+ assert datasets["clipset"]["clip_count"] == 1+ assert datasets["clipset"]["image_count"] == 0+ assert datasets["clipset"]["caption_count"] == 1+++def test_info_still_skips_a_folder_holding_neither(client, ds_root):+ """Admission widened to "an image OR a clip", not to "any folder"."""+ folder = ds_root / "captions-only"+ folder.mkdir()+ (folder / "metadata.jsonl").write_text(+ json.dumps({"file_name": "gone.png", "text": "x"}) + "\n", encoding = "utf-8"+ )+ (folder / "readme.txt").write_text("nothing to train on", encoding = "utf-8")++ r = client.get("/api/train/diffusion/info")+ assert r.status_code == 200, r.text+ assert [d["name"] for d in r.json()["datasets"]] == []+++def test_list_images_marks_clips_and_leaves_images_unchanged(client, ds_root):+ """Clips list so a caller can see every name holding a stem-keyed sidecar open, but they+ carry no pixel dimensions and the grid filters them out on ``kind``."""+ folder = ds_root / "both"+ folder.mkdir()+ _write_png(folder / "still.png", size = (12, 9))+ (folder / "moving.mp4").write_bytes(_MP4_BYTES)+ (folder / "moving.txt").write_text("a train", encoding = "utf-8")++ r = client.get("/api/train/diffusion/dataset/both/images")+ assert r.status_code == 200, r.text+ recs = {rec["filename"]: rec for rec in r.json()["images"]}+ assert recs["still.png"]["kind"] == "image"+ assert (recs["still.png"]["width"], recs["still.png"]["height"]) == (12, 9)+ assert recs["moving.mp4"]["kind"] == "clip"+ assert (recs["moving.mp4"]["width"], recs["moving.mp4"]["height"]) == (0, 0)+ assert recs["moving.mp4"]["caption"] == "a train"+ assert recs["moving.mp4"]["caption_source"] == "sidecar"+++# ── upload ───────────────────────────────────────────────────────────────────+def test_upload_accepts_a_clip_and_its_sidecar_as_a_pair(client, ds_root):+ r = client.post(+ "/api/train/diffusion/dataset",+ data = {"name": "clipset"},+ files = [+ ("files", ("one.mp4", _MP4_BYTES, "video/mp4")),+ ("files", ("one.txt", b"a waterfall", "text/plain")),+ ("files", ("two.webm", _MP4_BYTES, "video/webm")),+ ],+ )+ assert r.status_code == 200, r.text+ body = r.json()+ assert body["uploaded"] == 3+ assert body["clip_count"] == 2+ assert body["image_count"] == 0+ assert body["caption_count"] == 1+ folder = ds_root / "clipset"+ assert (folder / "one.mp4").read_bytes() == _MP4_BYTES+ assert (folder / "one.txt").read_text(encoding = "utf-8") == "a waterfall"+++def test_upload_still_refuses_an_extension_of_neither_kind(client, ds_root):+ r = client.post(+ "/api/train/diffusion/dataset",+ data = {"name": "clipset"},+ files = [("files", ("notes.pdf", b"%PDF-1.4", "application/pdf"))],+ )+ assert r.status_code == 400, r.text+ # All-or-nothing: the refused batch leaves nothing behind.+ assert not (ds_root / "clipset" / "notes.pdf").exists()+++def test_upload_refuses_an_image_and_a_clip_sharing_a_stem(client, ds_root):+ """cat.png and cat.mp4 both resolve to cat.txt, exactly as two images do, so the same+ refusal has to cover the cross-kind pair."""+ r = client.post(+ "/api/train/diffusion/dataset",+ data = {"name": "mixed"},+ files = [+ ("files", ("cat.png", _png_bytes(), "image/png")),+ ("files", ("cat.mp4", _MP4_BYTES, "video/mp4")),+ ],+ )+ assert r.status_code == 400, r.text+ # The wording names the kind of the file being refused, so the existing image-vs-image+ # message is unchanged and the cross-kind one still reads truthfully.+ assert "Duplicate clip name 'cat'" in r.json()["detail"]+ assert "cat.png" in r.json()["detail"]+ assert list((ds_root / "mixed").iterdir()) == []+++def test_upload_refuses_a_clip_whose_stem_is_already_in_the_folder(client, ds_root):+ folder = ds_root / "mixed"+ folder.mkdir()+ _write_png(folder / "cat.png")++ r = client.post(+ "/api/train/diffusion/dataset",+ data = {"name": "mixed"},+ files = [("files", ("cat.mp4", _MP4_BYTES, "video/mp4"))],+ )+ assert r.status_code == 400, r.text+ assert not (folder / "cat.mp4").exists()+++def test_upload_does_not_decode_a_clip_as_an_image(client, ds_root):+ """The decompression-bomb check is about pixels and stays on images. A clip whose bytes+ Pillow cannot open must not be turned into a 400 by it."""+ r = client.post(+ "/api/train/diffusion/dataset",+ data = {"name": "clipset"},+ files = [("files", ("one.mkv", b"\x1a\x45\xdf\xa3" + b"\x00" * 32, "video/x-matroska"))],+ )+ assert r.status_code == 200, r.text+ assert r.json()["clip_count"] == 1+++# ── delete ───────────────────────────────────────────────────────────────────+def test_deleting_an_image_keeps_a_clip_of_the_same_stem_captioned(client, ds_root):+ """Legacy folders can hold cat.png beside cat.mp4 (the upload refuses new ones). Deleting+ the image must not strip the sidecar the surviving clip still reads."""+ folder = ds_root / "legacy"+ folder.mkdir()+ _write_png(folder / "cat.png")+ (folder / "cat.mp4").write_bytes(_MP4_BYTES)+ (folder / "cat.txt").write_text("a cat", encoding = "utf-8")++ r = client.delete("/api/train/diffusion/dataset/legacy/image/cat.png")+ assert r.status_code == 200, r.text+ assert not (folder / "cat.png").exists()+ assert (folder / "cat.txt").read_text(encoding = "utf-8") == "a cat"+ assert _diffusion_dataset_summary(folder).caption_count == 1+++# ── the start refusal ────────────────────────────────────────────────────────+def test_start_refuses_a_clip_only_folder_by_naming_the_clips(tmp_path):+ """A clip folder is listed now, so a user can pick it and press Start. Discovery reads+ stills, so the raw refusal is "No captioned images found ... provide per-image .txt+ captions" -- wrong twice over on a folder where every clip has one."""+ from core.training.diffusion_train_common import discover_image_caption_pairs+ from routes.training import _clip_dataset_refusal++ folder = tmp_path / "clip-style"+ folder.mkdir()+ for stem in ("a", "b"):+ (folder / f"{stem}.mp4").write_bytes(_MP4_BYTES)+ (folder / f"{stem}.txt").write_text(f"clip {stem}", encoding = "utf-8")++ # The folder IS captioned, by the summary the picker is built from.+ assert _diffusion_dataset_summary(folder).caption_count == 2+ with pytest.raises(ValueError, match = "No captioned images found"):+ discover_image_caption_pairs(folder)++ detail = _clip_dataset_refusal(str(folder))+ assert detail is not None+ assert "2 video clips" in detail+ assert "not supported yet" in detail+ assert ".txt" not in detail+++def test_start_refuses_a_mixed_folder_rather_than_training_the_images_alone(tmp_path):+ """The sharper case: discovery SUCCEEDS on the images, so nothing raises and the run+ trains on the still subset while the picker counted the clips as trainable items."""+ from core.training.diffusion_train_common import discover_image_caption_pairs+ from routes.training import _clip_dataset_refusal++ folder = tmp_path / "mixed"+ folder.mkdir()+ _write_png(folder / "still.png")+ (folder / "still.txt").write_text("a still", encoding = "utf-8")+ (folder / "clip.mp4").write_bytes(_MP4_BYTES)+ (folder / "clip.txt").write_text("a clip", encoding = "utf-8")++ # Two captioned items by the summary, one trainable pair by discovery.+ assert _diffusion_dataset_summary(folder).caption_count == 2+ assert len(discover_image_caption_pairs(folder)) == 1++ detail = _clip_dataset_refusal(str(folder))+ assert detail is not None+ assert "1 video clip" in detail and "1 video clips" not in detail+++def test_start_leaves_an_image_only_folder_alone(tmp_path):+ """No clips, no refusal: the ordinary uncaptioned-folder error still speaks for itself."""+ from routes.training import _clip_dataset_refusal++ folder = tmp_path / "photo-style"+ folder.mkdir()+ _write_png(folder / "one.png")++ assert _clip_dataset_refusal(str(folder)) is None+ assert _clip_dataset_refusal(str(tmp_path / "does-not-exist")) is None+++def test_deleting_an_image_keeps_a_case_folded_clips_caption(client, ds_root, monkeypatch):+ """Where the filesystem folds case, CAT.mp4's sidecar IS cat.txt, so an exact stem compare+ would delete the caption the clip still reads. The upload refuses to create such a pair,+ but an externally populated folder can hold one."""+ import routes.training as tr++ monkeypatch.setattr(tr, "_dataset_folder_is_case_insensitive", lambda folder: True)+ folder = ds_root / "legacy-case"+ folder.mkdir()+ _write_png(folder / "cat.png")+ (folder / "CAT.mp4").write_bytes(_MP4_BYTES)+ (folder / "cat.txt").write_text("a cat", encoding = "utf-8")++ r = client.delete("/api/train/diffusion/dataset/legacy-case/image/cat.png")+ assert r.status_code == 200, r.text+ assert not (folder / "cat.png").exists()+ assert (folder / "cat.txt").read_text(encoding = "utf-8") == "a cat"+++def test_deleting_an_image_still_drops_its_sidecar_where_case_is_kept(client, ds_root, monkeypatch):+ """The other half of the same probe. Here CAT.mp4 reads CAT.txt, a different file, so+ cat.txt belongs to the image alone and must go with it: left behind, the next cat.png+ uploaded into this folder would silently inherit a caption written for something else."""+ import routes.training as tr++ monkeypatch.setattr(tr, "_dataset_folder_is_case_insensitive", lambda folder: False)+ folder = ds_root / "sensitive-case"+ folder.mkdir()+ _write_png(folder / "cat.png")+ (folder / "CAT.mp4").write_bytes(_MP4_BYTES)+ (folder / "cat.txt").write_text("a cat", encoding = "utf-8")+ (folder / "CAT.txt").write_text("a CAT", encoding = "utf-8")++ r = client.delete("/api/train/diffusion/dataset/sensitive-case/image/cat.png")+ assert r.status_code == 200, r.text+ assert not (folder / "cat.txt").exists()+ assert (folder / "CAT.txt").read_text(encoding = "utf-8") == "a CAT"diff --git a/studio/backend/tests/test_diffusion_training.py b/studio/backend/tests/test_diffusion_training.pyindex b93078b279e..61057ad39dd 100644--- a/studio/backend/tests/test_diffusion_training.py+++ b/studio/backend/tests/test_diffusion_training.py@@ -801,6 +801,39 @@ def test_route_start_resolves_bare_name_under_image_dataset_root(client, monkeypassert client._fake.started_with["data_dir"] == str(img_ds)+def test_route_start_refuses_a_dataset_holding_clips(client, monkeypatch, tmp_path):+ """No trainer reads clips. This fixture stubs discovery to SUCCEED, which is exactly the+ mixed-folder case: without the route's own check the run starts and trains on the still+ images alone while the picker counted the clips as trainable items."""+ import utils.paths as up++ ds_root = tmp_path / "assets" / "datasets"+ folder = ds_root / "mixed-set"+ folder.mkdir(parents = True)+ (folder / "a.png").write_bytes(b"x")+ (folder / "b.mp4").write_bytes(b"x")+ monkeypatch.setattr(up, "datasets_root", lambda: ds_root)++ r = client.post("/api/train/diffusion/start", json = {**_BODY, "data_dir": "mixed-set"})+ assert r.status_code == 400, r.text+ assert "1 video clip" in r.json()["detail"]+ assert client._fake.started_with is None+++def test_route_start_still_accepts_an_image_only_dataset(client, monkeypatch, tmp_path):+ """The twin of the above: the clip check must not stand in the way of a normal folder."""+ import utils.paths as up++ ds_root = tmp_path / "assets" / "datasets"+ folder = ds_root / "photo-set"+ folder.mkdir(parents = True)+ (folder / "a.png").write_bytes(b"x")+ monkeypatch.setattr(up, "datasets_root", lambda: ds_root)++ r = client.post("/api/train/diffusion/start", json = {**_BODY, "data_dir": "photo-set"})+ assert r.status_code == 200, r.text++def test_route_start_blocked_by_active_llm_training(client, monkeypatch):import routes.training as trdiff --git a/studio/frontend/src/features/images/api.ts b/studio/frontend/src/features/images/api.tsindex aa3ff152e03..0a4567f43ef 100644--- a/studio/frontend/src/features/images/api.ts+++ b/studio/frontend/src/features/images/api.ts@@ -597,14 +597,24 @@ export async function getDiffusionTrainingStatus(): Promise<DiffusionTrainingStareturn parseJson(await authFetch("/api/train/diffusion/status"));}-// One image-dataset folder under the Studio datasets root (GET /api/train/diffusion/info).+// One dataset folder under the Studio datasets root (GET /api/train/diffusion/info): images,+// clips, or both. `clip_count` is absent on older backends, hence optional.export interface DiffusionDatasetSummary {name: string;path: string;image_count: number;+ clip_count?: number;caption_count: number;}+/** trainable items in a dataset folder, of whichever kind. */+export function datasetItemCount(d: {+ image_count: number;+ clip_count?: number;+}): number {+ return d.image_count + (d.clip_count ?? 0);+}+// Per-family training defaults (from GET /api/train/diffusion/info). Absent on older backends; the Train tab then falls back to a hardcoded list.export interface DiffusionTrainableFamily {name: string;@@ -665,16 +675,25 @@ export async function uploadDiffusionDataset();}-// One image in a training dataset folder, with its resolved caption. `caption_source` records where it came from, so the labeling grid can highlight uncaptioned images.+// One item in a training dataset folder, with its resolved caption. `caption_source` records where it came from, so the labeling grid can highlight uncaptioned items.+// `kind` is absent on older backends, which listed images only; treat a missing value as "image".export interface DiffusionDatasetImageRecord {filename: string;caption: string | null;caption_source: "sidecar" | "metadata" | "none";+ kind?: "image" | "clip";width: number;height: number;size_bytes: number;}+/** the records the labeling grid can render: clips have no thumbnail endpoint. */+export function imageRecordsOnly(+ records: DiffusionDatasetImageRecord[],+): DiffusionDatasetImageRecord[] {+ return records.filter((r) => (r.kind ?? "image") === "image");+}+export interface DiffusionDatasetImages {name: string;path: string;@@ -752,6 +771,7 @@ export interface DiffusionDatasetImportResult {name: string;path: string;image_count: number;+ clip_count?: number;caption_count: number;imported: number;license: string;diff --git a/studio/frontend/src/features/images/train/dataset-files.ts b/studio/frontend/src/features/images/train/dataset-files.tsindex a17296364c4..ac931c4727d 100644--- a/studio/frontend/src/features/images/train/dataset-files.ts+++ b/studio/frontend/src/features/images/train/dataset-files.ts@@ -1,12 +1,17 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-// mirrors _DIFFUSION_DATASET_IMAGE_EXTS and _DIFFUSION_DATASET_TEXT_EXTS in backend/routes/training.py.+// mirrors _DIFFUSION_DATASET_IMAGE_EXTS, _DIFFUSION_DATASET_CLIP_EXTS and+// _DIFFUSION_DATASET_TEXT_EXTS in backend/routes/training.py.export const DATASET_IMAGE_EXTS = [".png", ".jpg", ".jpeg", ".webp", ".bmp"];+// video containers, for the families that train from clips rather than stills.+export const DATASET_CLIP_EXTS = [".mp4", ".mov", ".mkv", ".webm", ".m4v", ".avi"];+// the trainable unit, whichever kind: everything that pairs with a <stem>.txt caption.+export const DATASET_MEDIA_EXTS = [...DATASET_IMAGE_EXTS, ...DATASET_CLIP_EXTS];export const DATASET_TEXT_EXTS = [".txt", ".caption", ".jsonl"];-export const DATASET_FILE_ACCEPT = [...DATASET_IMAGE_EXTS, ...DATASET_TEXT_EXTS].join(",");+export const DATASET_FILE_ACCEPT = [...DATASET_MEDIA_EXTS, ...DATASET_TEXT_EXTS].join(",");-const ACCEPTED = new Set([...DATASET_IMAGE_EXTS, ...DATASET_TEXT_EXTS]);+const ACCEPTED = new Set([...DATASET_MEDIA_EXTS, ...DATASET_TEXT_EXTS]);// a caption jsonl runs to kilobytes, so scan a prefix rather than decoding the whole upload.const METADATA_SCAN_BYTES = 1024 * 1024;@@ -129,11 +134,12 @@ function inHiddenPath(file: File): boolean {return relative ? relative.split("/").slice(1).some(isHidden) : false;}-/** whether two image names resolve to one `<stem>.txt` sidecar, as `_shares_sidecar` does:- * the stems clash on an exact match, so only an extension-case pair of one spelling is exempt. */+/** whether two item names resolve to one `<stem>.txt` sidecar, as `_shares_sidecar` does:+ * the stems clash on an exact match, so only an extension-case pair of one spelling is exempt.+ * images and clips are compared together, since the sidecar is keyed on the stem alone. */function sharesSidecar(other: string, name: string): boolean {const otherExt = extensionOf(other);- if (other === name || !DATASET_IMAGE_EXTS.includes(otherExt)) return false;+ if (other === name || !DATASET_MEDIA_EXTS.includes(otherExt)) return false;const otherStem = other.slice(0, other.length - otherExt.length);const stem = name.slice(0, name.length - extensionOf(name).length);if (otherStem.toLowerCase() !== stem.toLowerCase()) return false;@@ -151,6 +157,7 @@ export interface DatasetFileSelection {/** the files to upload, in picked order. */files: File[];imageCount: number;+ clipCount: number;captionCount: number;/** files left out because the endpoint does not accept their extension. */skipped: number;@@ -162,8 +169,9 @@ export function selectDatasetFiles(input: File[]): DatasetFileSelection {const files: File[] = [];const collisions: DatasetCollision[] = [];const seen = new Map<string, string>();- const imageStems = new Map<string, Array<{ name: string; path: string }>>();+ const mediaStems = new Map<string, Array<{ name: string; path: string }>>();let imageCount = 0;+ let clipCount = 0;let captionCount = 0;let skipped = 0;@@ -185,35 +193,37 @@ export function selectDatasetFiles(input: File[]): DatasetFileSelection {continue;}const isImage = DATASET_IMAGE_EXTS.includes(ext);- // two images sharing a stem resolve to one <stem>.txt caption, which the backend refuses.+ const isClip = DATASET_CLIP_EXTS.includes(ext);+ // two items sharing a stem resolve to one <stem>.txt caption, which the backend refuses.// every accepted variant is kept and compared, since the exemption is not transitive.- if (isImage) {+ if (isImage || isClip) {const key = dest.slice(0, dest.length - ext.length).toLowerCase();- const variants = imageStems.get(key) ?? [];+ const variants = mediaStems.get(key) ?? [];const clash = variants.find((v) => sharesSidecar(v.name, dest));if (clash !== undefined) {collisions.push({ kind: "stem", first: clash.path, second: path });continue;}variants.push({ name: dest, path });- imageStems.set(key, variants);+ mediaStems.set(key, variants);}seen.set(dest, path);files.push(file);if (isImage) imageCount += 1;+ else if (isClip) clipCount += 1;else captionCount += 1;}- return { files, imageCount, captionCount, skipped, collisions };+ return { files, imageCount, clipCount, captionCount, skipped, collisions };}-/** the first selected image the dataset folder already holds under a sidecar-sharing name, or+/** the first selected item the dataset folder already holds under a sidecar-sharing name, or* null. the backend compares each upload against the folder, so on a chunked top-up that 400- * lands with the slices before it already written. `existing` is the folder's image names. */+ * lands with the slices before it already written. `existing` is the folder's item names. */export function existingStemClash(files: File[], existing: string[]): DatasetCollision | null {for (const file of files) {const dest = destinationName(file);- if (!DATASET_IMAGE_EXTS.includes(extensionOf(dest))) continue;+ if (!DATASET_MEDIA_EXTS.includes(extensionOf(dest))) continue;const clash = existing.find((name) => sharesSidecar(name, dest));if (clash !== undefined) return { kind: "stem", first: clash, second: displayPath(file) };}diff --git a/studio/frontend/src/features/images/train/dataset-labeling-grid.tsx b/studio/frontend/src/features/images/train/dataset-labeling-grid.tsxindex 38c2998d55f..c527f42bad5 100644--- a/studio/frontend/src/features/images/train/dataset-labeling-grid.tsx+++ b/studio/frontend/src/features/images/train/dataset-labeling-grid.tsx@@ -30,6 +30,7 @@ import {deleteDiffusionDatasetImage,diffusionDatasetImageUrl,fetchGalleryObjectUrl,+ imageRecordsOnly,listDiffusionDatasetImages,setDiffusionDatasetCaption,} from "../api";@@ -194,7 +195,8 @@ export function DatasetLabelingGrid({setPage(0); // a new dataset (or refresh) always starts at the first batchlistDiffusionDatasetImages(dataset).then((r) => {- if (!cancelled) setRecords(r.images);+ // clips list alongside images but have no thumbnail endpoint; the grid is image-only.+ if (!cancelled) setRecords(imageRecordsOnly(r.images));}).catch((e) => {if (!cancelled) setError(e instanceof Error ? e.message : "Failed to list images");diff --git a/studio/frontend/src/features/images/train/dataset-showcase.tsx b/studio/frontend/src/features/images/train/dataset-showcase.tsxindex a20cd97d5bd..60026c588b2 100644--- a/studio/frontend/src/features/images/train/dataset-showcase.tsx+++ b/studio/frontend/src/features/images/train/dataset-showcase.tsx@@ -18,6 +18,7 @@ import {deleteDiffusionDatasetImage,diffusionDatasetImageUrl,fetchGalleryObjectUrl,+ imageRecordsOnly,listDiffusionDatasetImages,} from "../api";@@ -144,7 +145,8 @@ export function DatasetShowcase({.then((r) => {if (cancelled) return;// Sample up to MAX_TILES evenly across the folder so the strip represents the whole set, not just the first few files.- const all = r.images.map((im) => im.filename);+ // clips have no thumbnail endpoint, so the strip shows images only.+ const all = imageRecordsOnly(r.images).map((im) => im.filename);if (all.length <= MAX_TILES) {setNames(all);return;diff --git a/studio/frontend/src/features/images/train/diffusion-train-panel.tsx b/studio/frontend/src/features/images/train/diffusion-train-panel.tsxindex 4632a803d22..d6d4534008b 100644--- a/studio/frontend/src/features/images/train/diffusion-train-panel.tsx+++ b/studio/frontend/src/features/images/train/diffusion-train-panel.tsx@@ -67,6 +67,7 @@ import {type DiffusionTrainingRunDetail,type DiffusionTrainingRunSummary,type DiffusionTrainingStatus,+ datasetItemCount,getDiffusionTrainingInfo,getDiffusionTrainingRun,getDiffusionTrainingStatus,@@ -79,6 +80,7 @@ import {} from "../api";import { DatasetLabelingGrid, LabelingGridToggle } from "./dataset-labeling-grid";import {+ DATASET_CLIP_EXTS,DATASET_FILE_ACCEPT,DATASET_IMAGE_EXTS,chunkDatasetUpload,@@ -172,6 +174,15 @@ function repoIsPrequantized(baseModel: string): boolean {}// Dataset-select option value prefix for a not-yet-imported example; picking it imports.const EXAMPLE_PREFIX = "example:";++/** "12 images", "12 clips", or "12 items" for a mixed folder. The picker has one line per+ * dataset, and a clip folder reading "0 images" is exactly the bug this labels away. */+function datasetItemLabel(d: { image_count: number; clip_count?: number }): string {+ const clips = d.clip_count ?? 0;+ const total = d.image_count + clips;+ const noun = clips === 0 ? "image" : d.image_count === 0 ? "clip" : "item";+ return `${total} ${noun}${total === 1 ? "" : "s"}`;+}// min-w-0 + a truncating value: a long option would otherwise set the grid column min width and push into its neighbour.const selectClass ="h-8 w-full min-w-0 text-xs *:data-[slot=select-value]:min-w-0 *:data-[slot=select-value]:truncate";@@ -687,11 +698,14 @@ export function DiffusionTrainPanel({dataset !== UPLOAD_DATASET ? info?.datasets.find((d) => d.name === dataset) : undefined;// A deleted dataset leaves a name that no longer resolves; fall back to the upload form.const uploadMode = dataset === UPLOAD_DATASET || (info !== null && !selectedDataset);- // A dataset where every image already ships a caption needs no trigger prompt; hide the field and explain why.+ // Trainable items in the picked dataset, images and clips alike. caption_count is the folder+ // total over both kinds, so every ratio below has to be against this and not image_count.+ const selectedItemCount = selectedDataset ? datasetItemCount(selectedDataset) : 0;+ // A dataset where every item already ships a caption needs no trigger prompt; hide the field and explain why.const fullyCaptioned = Boolean(selectedDataset &&- selectedDataset.image_count > 0 &&- selectedDataset.caption_count >= selectedDataset.image_count,+ selectedItemCount > 0 &&+ selectedDataset.caption_count >= selectedItemCount,);// Map the backend's paired history arrays into the chart component's {step,value} series.@@ -764,7 +778,7 @@ export function DiffusionTrainPanel({toast.error("Give the dataset a folder name, e.g. my-style-photos.");return;}- const { files, imageCount, skipped, collisions } = selectDatasetFiles(picked);+ const { files, imageCount, clipCount, skipped, collisions } = selectDatasetFiles(picked);if (collisions.length > 0) {const { kind, first, second } = collisions[0];const more =@@ -782,15 +796,16 @@ export function DiffusionTrainPanel({}if (files.length === 0) {toast.error(- `Nothing to upload. Pick images (${DATASET_IMAGE_EXTS.join(", ")}) and, ` ++ `Nothing to upload. Pick images (${DATASET_IMAGE_EXTS.join(", ")}) or ` ++ `clips (${DATASET_CLIP_EXTS.join(", ")}) and, ` +"optionally, a caption file beside each one.",);return;}- // /diffusion/info only lists folders holding an image, so say why the set will not- // appear yet rather than refusing a captions-first upload.+ // /diffusion/info only lists folders holding a trainable item, so say why the set will+ // not appear yet rather than refusing a captions-first upload.const newCaptionsOnly =- imageCount === 0 && !(info?.datasets ?? []).some((d) => d.name === name);+ imageCount === 0 && clipCount === 0 && !(info?.datasets ?? []).some((d) => d.name === name);if (uploadInFlight.current) {toast.error("An upload is already running. Wait for it to finish, then try again.");return;@@ -888,26 +903,26 @@ export function DiffusionTrainPanel({} else {toast.success(`Uploaded ${sent} file${sent === 1 ? "" : "s"} - ` +- `"${res.name}" now has ${res.image_count} images, ` ++ `"${res.name}" now has ${datasetItemLabel(res)}, ` +`${res.caption_count} captioned`,);}if (skipped > 0) {toast.info(`Skipped ${skipped} file${skipped === 1 ? "" : "s"} that ` +- `${skipped === 1 ? "was" : "were"} neither an image nor a caption.`,+ `${skipped === 1 ? "was" : "were"} neither an image, a clip, nor a caption.`,);}if (newCaptionsOnly) {toast.info(- `"${res.name}" holds captions but no images yet, so it stays out of the dataset ` +- "picker until you add some.",+ `"${res.name}" holds captions but no images or clips yet, so it stays out of the ` ++ "dataset picker until you add some.",);}if (misKeyed) {toast.info(`${misKeyed} keys its captions on subfolder paths, and a dataset folder is flat, ` +- "so those rows will not match. A .txt beside each image always will.",+ "so those rows will not match. A .txt beside each file always will.",);}await refreshInfo();@@ -984,16 +999,16 @@ export function DiffusionTrainPanel({// Require a trigger prompt whenever ANY image lacks a caption: without an instance_prompt the backend silently skips every uncaptioned image.if (selectedDataset &&- selectedDataset.caption_count < selectedDataset.image_count &&+ selectedDataset.caption_count < selectedItemCount &&!instancePrompt.trim()) {toast.error(selectedDataset.caption_count === 0- ? "These images have no captions - add a trigger prompt so the trainer knows " +- "what to learn (it becomes the caption for every image)."- : `Only ${selectedDataset.caption_count} of ${selectedDataset.image_count} images ` ++ ? "This dataset has no captions - add a trigger prompt so the trainer knows " ++ "what to learn (it becomes the caption for every item)."+ : `Only ${selectedDataset.caption_count} of ${selectedItemCount} items ` +"have captions - the rest would be silently skipped. Add a trigger prompt " +- "(it becomes their caption) or caption every image.",+ "(it becomes their caption) or caption every one.",);return;}@@ -1056,6 +1071,7 @@ export function DiffusionTrainPanel({family,dataset,selectedDataset,+ selectedItemCount,outputDir,instancePrompt,resolution,@@ -1552,10 +1568,10 @@ export function DiffusionTrainPanel({<SelectValue /></SelectTrigger><SelectContent>- {/* Name plus image count only; captions and license show elsewhere. */}+ {/* Name plus item count only; captions and license show elsewhere. */}{(info?.datasets ?? []).map((d) => (<SelectItem key={d.name} value={d.name}>- {d.name} - {d.image_count} image{d.image_count === 1 ? "" : "s"}+ {d.name} - {datasetItemLabel(d)}</SelectItem>))}{pendingExamples.length > 0 && (@@ -1681,8 +1697,8 @@ export function DiffusionTrainPanel({</div><p className="text-ui-11 leading-snug text-muted-foreground">{isTauri ? "Pick files or a folder." : "Pick files or a folder, or drop them here."}{" "}- A caption file beside an image (cat.png and cat.txt) is read as that image's- caption.+ Images, or clips for the video families. A caption file beside one (cat.png and+ cat.txt, or cat.mp4 and cat.txt) is read as that item's caption.</p></div>) : (@@ -1697,21 +1713,29 @@ export function DiffusionTrainPanel({onChanged={() => void refreshInfo()}/>)}- <LabelingGridToggle- count={selectedDataset.image_count}- open={gridOpen}- onToggle={() => setGridOpen((o) => !o)}- />- {gridOpen && (- <DatasetLabelingGrid- dataset={dataset}- refreshKey={gridRefresh}- onCountsChanged={() => void refreshInfo()}- />+ {/* The grid renders thumbnails, so it is offered only where there are images.+ One guard over the toggle AND the grid: gating only the toggle would leave+ an open grid with nothing to close it once a mixed folder's last image is+ deleted, since the clips keep the folder listed. */}+ {selectedDataset.image_count > 0 && (+ <>+ <LabelingGridToggle+ count={selectedDataset.image_count}+ open={gridOpen}+ onToggle={() => setGridOpen((o) => !o)}+ />+ {gridOpen && (+ <DatasetLabelingGrid+ dataset={dataset}+ refreshKey={gridRefresh}+ onCountsChanged={() => void refreshInfo()}+ />+ )}+ </>)}{selectedDataset.caption_count === 0 && !gridOpen && (<p className="text-ui-11 leading-snug text-muted-foreground">- No captions yet, so the trigger prompt describes every image.+ No captions yet, so the trigger prompt describes every item.</p>)}</>@@ -1730,7 +1754,7 @@ export function DiffusionTrainPanel({{/* Trigger + adapter name (trigger first: it describes the dataset, the name just labels the output) */}{fullyCaptioned ? (<p className="text-ui-11 leading-snug text-muted-foreground">- All {selectedDataset?.image_count} images have captions, so no trigger prompt+ Every item in {selectedDataset?.name} has a caption, so no trigger promptis needed.</p>) : (diff --git a/studio/frontend/tests/dataset-file-selection.test.ts b/studio/frontend/tests/dataset-file-selection.test.tsindex e75a3d75197..002c1987299 100644--- a/studio/frontend/tests/dataset-file-selection.test.ts+++ b/studio/frontend/tests/dataset-file-selection.test.ts@@ -6,7 +6,9 @@ import { readFile } from "node:fs/promises";import test from "node:test";import {+ DATASET_CLIP_EXTS,DATASET_IMAGE_EXTS,+ DATASET_MEDIA_EXTS,DATASET_TEXT_EXTS,chunkDatasetUpload,existingStemClash,@@ -48,6 +50,26 @@ test("accepts exactly the extensions the backend accepts", async () => {// still reads, so a backend that widens either list must widen the picker with it.assert.deepEqual([...DATASET_IMAGE_EXTS].sort(), literals("_DIFFUSION_DATASET_IMAGE_EXTS"));assert.deepEqual([...DATASET_TEXT_EXTS].sort(), literals("_DIFFUSION_DATASET_TEXT_EXTS"));++ // clips are defined once, in core/training/diffusion_clip_formats.py, and read from there by+ // both the routes and the trainer's clip discovery. The picker has to mirror that same list.+ const clipSource = await readFile(+ new URL("../../backend/core/training/diffusion_clip_formats.py", import.meta.url),+ "utf8",+ );+ const clipMatch = /CLIP_EXTS\s*=\s*frozenset\(\{([^}]+)\}\)/.exec(clipSource);+ assert.ok(clipMatch, "CLIP_EXTS not found in diffusion_clip_formats.py");+ assert.deepEqual(+ [...DATASET_CLIP_EXTS].sort(),+ [...clipMatch[1].matchAll(/"([^"]+)"/g)].map((m) => m[1]).sort(),+ );++ // the two halves must stay DISJOINT: every rule that widened to media relies on an extension+ // belonging to exactly one kind, so a container that is also an image extension would make+ // the same file count twice and pick an arbitrary branch in the summary.+ const overlap = DATASET_IMAGE_EXTS.filter((e) => DATASET_CLIP_EXTS.includes(e));+ assert.deepEqual(overlap, []);+ assert.equal(DATASET_MEDIA_EXTS.length, DATASET_IMAGE_EXTS.length + DATASET_CLIP_EXTS.length);});test("keeps images alongside the caption files paired to them", () => {@@ -70,12 +92,41 @@ test("drops files the upload endpoint would reject, and counts them", () => {const result = selectDatasetFiles([picked("cat.png"),picked("notes.pdf"),- picked("clip.mp4"),picked("README"),]);assert.deepEqual(result.files.map((f) => f.name), ["cat.png"]);- assert.equal(result.skipped, 3);+ assert.equal(result.skipped, 2);+});++test("keeps clips alongside the caption files paired to them", () => {+ const result = selectDatasetFiles([+ picked("clip.mp4"),+ picked("clip.txt"),+ picked("second.MOV"),+ picked("metadata.jsonl"),+ ]);++ assert.equal(result.files.length, 4);+ assert.equal(result.clipCount, 2);+ assert.equal(result.imageCount, 0);+ assert.equal(result.captionCount, 2);+ assert.equal(result.skipped, 0);+ assert.deepEqual(result.collisions, []);+});++test("reports an image and a clip sharing a stem, which would share one caption sidecar", () => {+ // the sidecar is keyed on the stem alone, so cat.png and cat.mp4 collide exactly as two+ // images would; training.py refuses the batch, and catching it here says so before the upload.+ const result = selectDatasetFiles([picked("cat.png"), picked("cat.mp4"), picked("cat.txt")]);++ assert.deepEqual(result.files.map((f) => f.name), ["cat.png", "cat.txt"]);+ assert.deepEqual(result.collisions, [{ kind: "stem", first: "cat.png", second: "cat.mp4" }]);+});++test("a clip already in the folder holds its sidecar against a new image of that stem", () => {+ const clash = existingStemClash([picked("cat.png")], ["cat.mp4"]);+ assert.deepEqual(clash, { kind: "stem", first: "cat.mp4", second: "cat.png" });});test("reports basenames a folder pick would flatten together", () => {@@ -422,3 +473,34 @@ test("uses the flat list when the entries API is unavailable", async () => {assert.deepEqual(out.map((f) => f.name), ["a.png", "b.png"]);});++test("the labeling grid is gated on images, not just its toggle", async () => {+ // A mixed folder keeps its listing on clip_count alone, so deleting the last image leaves the+ // grid with no toggle to close it unless the grid itself sits inside the same guard.+ const source = await readFile(+ new URL("../src/features/images/train/diffusion-train-panel.tsx", import.meta.url),+ "utf8",+ );+ const guard = "{selectedDataset.image_count > 0 && (";+ const toggle = source.indexOf("<LabelingGridToggle");+ const grid = source.indexOf("<DatasetLabelingGrid");+ assert.ok(toggle > 0 && grid > 0);+ // The guard opening the block the toggle sits in.+ const start = source.lastIndexOf(guard, toggle);+ assert.ok(start > 0, "the toggle is not inside an image_count guard");+ // Walk to that block's matching close brace.+ let depth = 0;+ let end = -1;+ for (let i = start; i < source.length; i += 1) {+ if (source[i] === "{") depth += 1;+ else if (source[i] === "}") {+ depth -= 1;+ if (depth === 0) {+ end = i;+ break;+ }+ }+ }+ assert.ok(end > start, "unbalanced braces around the labeling grid guard");+ assert.ok(grid > start && grid < end, "the grid renders outside the image_count guard");+});