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: infer splits for metadata-free cached datasets (#8144)
Ricardo-M-Leda3b2693828
diff --git a/studio/backend/hub/services/datasets/local_options.py b/studio/backend/hub/services/datasets/local_options.pyindex 7c2d5273a77..21746f3ee99 100644--- a/studio/backend/hub/services/datasets/local_options.py+++ b/studio/backend/hub/services/datasets/local_options.py@@ -6,7 +6,7 @@ from __future__ import annotationsimport jsonimport osimport re-from pathlib import Path+from pathlib import Path, PurePosixPathfrom typing import Any, Iterable, Optionalfrom hub.schemas.datasets import (@@ -15,6 +15,7 @@ from hub.schemas.datasets import (LocalDatasetOptionsResponse,)from hub.utils.dataset_cache import (+ TRAINING_DATA_EXTS,dataset_cache_path_from_cache_path,dataset_snapshot_from_cache_path,latest_cached_dataset_path,@@ -217,7 +218,12 @@ def _snapshot_metadata_file(snapshot: Path, name: str) -> Optional[Path]:return path if 0 < size <= _MAX_METADATA_BYTES else None-def _read_card_metadata(path: Path) -> Optional[dict[str, Any]]:+# _read_card_metadata returns this when a card has front matter datasets cannot parse.+# DatasetCard.load raises on it, so nothing in the snapshot is loadable.+_UNPARSABLE_METADATA = object()+++def _read_card_metadata(path: Path) -> Any:try:lines = path.read_text(encoding = "utf-8").splitlines()if not lines or lines[0].strip() != "---":@@ -228,31 +234,481 @@ def _read_card_metadata(path: Path) -> Optional[dict[str, Any]]:try:payload = safe_load("\n".join(lines[1:end]))except YAMLError:+ return _UNPARSABLE_METADATA+ if payload is None:+ # Empty, comment-only or null front matter, which RepoCard reads as an empty+ # card rather than refusing.+ return {}+ except StopIteration:+ # Front matter that never closes is not front matter at all.+ return None+ except UnicodeError:+ # DatasetCard.load reads the card as utf-8 and raises, so nothing here loads.+ return _UNPARSABLE_METADATA+ except (ImportError, OSError, ValueError):+ return None+ return payload if isinstance(payload, dict) else _UNPARSABLE_METADATA+++# --- Split inference for cached datasets whose card declares nothing ------------------+#+# datasets resolves a metadata-free directory with get_data_patterns: it tries sharded+# data/{split}-NNNNN-of-NNNNN files, then directory-name keywords, then filename keywords,+# and falls back to one train split holding everything. The first stage that names any+# split wins, and one builder is chosen for all of them. This mirrors that without+# importing datasets, which dataset_cache.py forbids on cache paths.+#+# The contract is that an offered split has to be trainable: anything looser is offered and+# then 422s, anything tighter hides a usable option. Deliberately tighter in two places,+# both to keep training inside the cache: a file whose symlink leaves the repository is+# refused, and only the extensions Studio can train on are offered.++# Only names are read during the scan, so this can sit well above any real snapshot. Past+# it the result would depend on traversal order, so nothing is offered.+_MAX_SNAPSHOT_DATA_FILES = 200_000+# datasets drops these by basename before it infers anything, so a metadata-only cache is+# empty rather than a bogus train split.+_IGNORED_DATA_FILENAMES = frozenset(+ {+ "README.md",+ "config.json",+ "dataset_info.json",+ "dataset_infos.json",+ "dataset_dict.json",+ "dummy_data.zip",+ }+)+# What fsspec can decompress in a Studio install, as suffixes that sit after the real one.+_COMPRESSION_EXTENSIONS = frozenset({".gz", ".gzip", ".bz2", ".xz", ".zip"})+# Named by datasets but needing codecs a Studio install does not ship, so they raise+# "Compression type not supported" and offering them would put a dead split in the picker.+# .lzma is the legacy alone-format: datasets registers .xz for its filter, not this.+_UNREADABLE_COMPRESSION = frozenset({".zst", ".zstd", ".lz4", ".lzma"})+# datasets picks one builder for the whole dataset, from the extensions it finds. Splits+# that disagree make it raise, so a snapshot mixing formats is not offerable at all.+_MODULE_EXTENSIONS = {+ "arrow": ".arrow",+ "csv": ".csv",+ # datasets compares the whole builder result, and tsv carries sep="\t", so it is not csv.+ "csv+tab": ".tsv",+ "json": ".json .jsonl .ndjson",+ "parquet": ".parquet .geoparquet .gpq",+ "text": ".txt",+ "webdataset": ".tar",+ "xml": ".xml",+ "hdf5": ".h5 .hdf5",+}+# The folder builders. datasets registers only these in both letter cases, so only their+# extensions match case-insensitively; everything else is matched by a case-sensitive glob.+_FOLDER_EXTENSIONS = frozenset(+ # imagefolder+ ".apng .blp .bmp .bufr .bw .cur .dcx .dds .dib .emf .eps .fit .fits .flc .fli .ftc .ftu "+ ".gbr .gif .grib .icb .icns .ico .iim .im .j2c .j2k .jfif .jp2 .jpc .jpe .jpeg .jpf "+ ".jpg .jpx .msp .pbm .pcd .pcx .pgm .png .pnm .ppm .ps .psd .pxr .ras .rgb .rgba .sgi "+ ".tga .tif .tiff .vda .vst .webp .wmf .xbm .xpm "+ # audiofolder+ ".3g2 .3gp .aiff .asf .au .avr .caf .f4v .flac .flv .htk .ircam .m4v .mat4 .mat5 .mp3 "+ ".mpc2k .mpg .mxf .nist .nut .ogg .ogm .opus .paf .pvf .raw .rf64 .sd2 .sds .svx .voc "+ ".w64 .wav .wavex .webm .wma .wmv .wve .xi "+ # videofolder and pdffolder+ ".avi .mkv .mov .mp4 .mpeg .pdf".split()+)+_EXTENSION_MODULES = {+ extension: module for module, names in _MODULE_EXTENSIONS.items() for extension in names.split()+}+# datasets infers a split's module from its first 200 files, in resolved (sorted) order.+_MAX_MODULE_INFERENCE_FILES = 200+# datasets' tie-break once the counts are level, then the extension string itself.+# TRAINING_DATA_EXTS only ever resolves to these, so any other builder means the+# snapshot holds nothing trainable and no file needs opening to find that out.+_TRAINABLE_MODULES = frozenset({"csv", "json", "parquet"})+_ROW_PROBE_BYTES = 8192+_EXTENSION_PRIORITY = (".parquet", ".jsonl", ".json", ".csv")+# Folder-builder metadata loses every tie-break, so it never decides a split's builder.+_METADATA_FILENAMES = frozenset({"metadata.csv", "metadata.jsonl", "metadata.parquet"})+# datasets' split keywords, in the order it resolves them.+_SPLIT_KEYWORDS = {+ "train": ("train", "training"),+ "validation": ("validation", "valid", "dev", "val"),+ "test": ("test", "testing", "eval", "evaluation"),+}+# Its keyword globs as regexes: "sep" is NON_WORDS_CHARS and * never crosses a directory.+_SEP = "[-._ 0-9]"+_FILENAME_KEYWORD_PATTERNS = (+ r"(?:.*/)?{keyword}%s[^/]*" % _SEP,+ r"(?:.*/)?[^/]*%s{keyword}%s[^/]*" % (_SEP, _SEP),+)+_DIR_NAME_KEYWORD_PATTERNS = (+ r"(?:.*/)?{keyword}/.*",+ r"(?:.*/)?{keyword}%s[^/]*/.*" % _SEP,+ r"(?:.*/)?[^/]*%s{keyword}/.*" % _SEP,+ r"(?:.*/)?[^/]*%s{keyword}%s[^/]*/.*" % (_SEP, _SEP),+)+# data/{split}-NNNNN-of-NNNNN*.*, where a * matches nothing as happily as something.+_SHARDED_DATA_RE = re.compile(r"^data/(?P<split>[^/]*)-[0-9]{5}-of-[0-9]{5}[^/]*\.[^/]*$")+# datasets' own split grammar, which is stricter than the one the picker accepts. A shard+# named outside it makes the whole snapshot unloadable rather than falling through.+_SHARD_SPLIT_RE = re.compile(r"^\w+(\.\w+)*$")+++def _keyword_patterns(bases: tuple[str, ...]) -> dict[str, list["re.Pattern[str]"]]:+ return {+ split: [+ re.compile(base.format(keyword = re.escape(keyword)) + r"\Z")+ for keyword in keywords+ for base in bases+ ]+ for split, keywords in _SPLIT_KEYWORDS.items()+ }+++_DIR_NAME_SPLITS = _keyword_patterns(_DIR_NAME_KEYWORD_PATTERNS)+_FILENAME_SPLITS = _keyword_patterns(_FILENAME_KEYWORD_PATTERNS)+++def _data_suffix(name: str) -> Optional[str]:+ """The suffix that decides this file's builder, or None when it has none.++ datasets reads the whole suffix chain, so records.parquet.backup is still parquet, and+ a trailing compression suffix is stripped before the rest is considered.+ """+ suffixes = PurePosixPath(name).suffixes+ if suffixes and suffixes[-1].lower() in _COMPRESSION_EXTENSIONS | _UNREADABLE_COMPRESSION:+ suffixes = suffixes[:-1]+ for suffix in reversed(suffixes):+ if suffix in _EXTENSION_MODULES or suffix.lower() in _FOLDER_EXTENSIONS:+ return suffix+ return suffixes[-1] if suffixes else None+++def _file_module(name: str) -> Optional[str]:+ """The builder datasets would pick for this filename.++ Its globs are case-sensitive, so TRAIN.JSONL is a file it never resolves. The folder+ builders are the exception: those are registered in both cases.+ """+ suffix = _data_suffix(name)+ if suffix is None:+ return None+ if suffix.lower() in _FOLDER_EXTENSIONS:+ return "folder"+ return _EXTENSION_MODULES.get(suffix)+++def _trainable_name(name: str) -> bool:+ """Whether Studio can train on this file. Narrower than what datasets would read."""+ suffix = _data_suffix(name)+ return suffix is not None and suffix in TRAINING_DATA_EXTS+++def _snapshot_data_files(snapshot: Path) -> Optional[list[PurePosixPath]]:+ """Every file datasets would consider, relative to the snapshot and sorted the way+ fsspec returns them, or None when the snapshot is too large to compare with."""+ found: list[PurePosixPath] = []+ try:+ root = snapshot.resolve(strict = True)+ except (OSError, RuntimeError, ValueError):+ return found+ for directory, dirnames, filenames in os.walk(root):+ base = Path(directory)+ try:+ relative = base.relative_to(root)+ except ValueError:+ dirnames[:] = []+ continue+ # datasets hides dot and __ directories from its own patterns.+ dirnames[:] = [name for name in dirnames if not name.startswith((".", "__"))]+ for filename in filenames:+ if filename in _IGNORED_DATA_FILENAMES or filename.startswith("."):+ continue+ # resolve_pattern keeps a link only when its target is a file, so a dangling+ # one is not a file datasets sees, let alone one that condemns its split.+ if not (base / filename).is_file():+ continue+ # Files with no builder of their own are kept: they cannot win the vote, but a+ # split holding nothing else is one datasets refuses to build.+ if len(found) >= _MAX_SNAPSHOT_DATA_FILES:+ # Past the cap this is a traversal-order prefix, which cannot be compared+ # with what the loader would resolve.+ return None+ found.append(PurePosixPath((relative / filename).as_posix()))+ found.sort(key = lambda path: path.as_posix())+ return found+++def _sharded_splits(files: list[PurePosixPath]) -> Optional[dict[str, list[PurePosixPath]]]:+ """The sharded stage, or None when a shard name is one datasets refuses outright."""+ grouped: dict[str, list[PurePosixPath]] = {}+ for path in files:+ matched = _SHARDED_DATA_RE.match(path.as_posix())+ if matched is None:+ continue+ split = matched.group("split")+ if _SHARD_SPLIT_RE.fullmatch(split) is None:+ # datasets raises on the name rather than moving on to the next stage.return None- except (ImportError, OSError, UnicodeError, ValueError, StopIteration):+ grouped.setdefault(split, []).append(path)+ return grouped+++def _keyword_splits(+ files: list[PurePosixPath], patterns: dict[str, list["re.Pattern[str]"]]+) -> dict[str, list[PurePosixPath]]:+ grouped: dict[str, list[PurePosixPath]] = {}+ for split, expressions in patterns.items():+ matched = [+ path+ for path in files+ if any(expression.match(path.as_posix()) for expression in expressions)+ ]+ if matched:+ grouped[split] = matched+ return grouped+++def _grouped_splits(files: list[PurePosixPath]) -> Optional[dict[str, list[PurePosixPath]]]:+ """The splits datasets would resolve, by the first stage that names any."""+ grouped = _sharded_splits(files)+ if grouped is None:return None- return payload if isinstance(payload, dict) else None+ for stage in (_DIR_NAME_SPLITS, _FILENAME_SPLITS):+ if grouped:+ break+ grouped = _keyword_splits(files, stage)+ return grouped or {"train": files}+++def _one_module(grouped: dict[str, list[PurePosixPath]]) -> Optional[str]:+ """The single builder every split agrees on, or None when datasets would refuse them.++ It counts a split's files by extension and takes the winner, so a split with no clear+ winner, or two splits wanting different builders, is a dataset it cannot build.+ """+ modules = set()+ for entries in grouped.values():+ counts: dict[tuple[str, str], int] = {}+ for path in entries[:_MAX_MODULE_INFERENCE_FILES]:+ suffix = _data_suffix(path.name)+ module = _file_module(path.name)+ # Folder metadata is counted last whatever it is, so it never wins on its own.+ if module is not None and path.name not in _METADATA_FILENAMES:+ counts[(module, suffix or "")] = counts.get((module, suffix or ""), 0) + 1+ if not counts:+ return None+ best = max(+ counts,+ key = lambda key: (+ counts[key],+ -_EXTENSION_PRIORITY.index(key[1]) if key[1] in _EXTENSION_PRIORITY else -99,+ key[1],+ ),+ )+ modules.add(best[0])+ return modules.pop() if len(modules) == 1 else None+++def _blocked_by_compression(name: str, module: str) -> bool:+ """Whether datasets keeps this file for the chosen builder but cannot decompress it.+ Its extension filter reads the whole basename, so train.jsonl.zst still looks like+ json to it, and the build then dies on the missing codec."""+ stem, _, suffix = name.rpartition(".")+ if not stem or f".{suffix}".lower() not in _UNREADABLE_COMPRESSION:+ return False+ return _file_module(stem) == module+++def _offerable(entries: list[PurePosixPath], snapshot: Path, module: str) -> Optional[bool]:+ """True when the split holds data Studio can train on, False when it holds none, None+ when the config is unusable. datasets reads every file in the split, so one file that+ escapes the cache, or one the builder chokes on, condemns the config rather than+ the single file."""+ trainable = False+ empty = False+ for path in entries:+ resolved = resolved_dataset_snapshot_file(snapshot, path.as_posix())+ if resolved is None or _blocked_by_compression(path.name, module):+ return None+ # Once a builder is chosen, datasets reads only what that builder claims, so a+ # training file left behind by a folder builder is not data this split offers.+ if _file_module(path.name) != module or not _trainable_name(path.name):+ continue+ if _empty_payload(resolved):+ empty = True+ continue+ if _rowless(resolved, path.name, module):+ continue+ trainable = True+ # Every builder but json fails outright on a file with no rows, and datasets prepares+ # every split before handing one back, so such a file condemns its siblings too.+ if empty and module != "json":+ return None+ return trainable+++def _rowless(path: Path, name: str, module: str) -> bool:+ """Whether the builder would read this file and find no row in it, as it does for a+ csv holding only its header. That split is dropped, but unlike a file it cannot read+ at all, datasets still builds the rest of the dataset around it."""+ suffixes = PurePosixPath(name).suffixes+ if module not in {"csv", "json"} or (+ suffixes and suffixes[-1].lower() in _COMPRESSION_EXTENSIONS | _UNREADABLE_COMPRESSION+ ):+ # Compressed bytes say nothing about the rows inside without decompressing them.+ return False+ try:+ with path.open("rb") as handle:+ head = handle.read(_ROW_PROBE_BYTES)+ except OSError:+ return True+ if module == "json":+ # A canonical empty container parses fine and yields no row.+ return head.strip() in (b"", b"[]", b"{}")+ # A header with no row under it. Anything longer than the probe has one.+ return len(head) < _ROW_PROBE_BYTES and len([x for x in head.splitlines() if x.strip()]) < 2+++def _empty_payload(path: Path) -> bool:+ """Whether the builder would read no bytes out of this file."""+ try:+ return path.stat().st_size == 0+ except OSError:+ return True+++def _inferred_snapshot_options(snapshot: Path) -> set[tuple[str, str]]:+ """What the picker can offer for a snapshot whose metadata named nothing."""+ files = _snapshot_data_files(snapshot)+ if not files:+ return set()+ grouped = _grouped_splits(files)+ module = _one_module(grouped) if grouped is not None else None+ if grouped is None or module is None or module not in _TRAINABLE_MODULES:+ return set()+ offerable = {split: _offerable(entries, snapshot, module) for split, entries in grouped.items()}+ if any(state is None for state in offerable.values()):+ return set()+ return {+ ("default", name)+ for split, state in offerable.items()+ if state and (name := _valid_option(split, _SPLIT_RE, reject_dotdot = True)) is not None+ }+++def _metadata_present(snapshot: Path, name: str) -> bool:+ """Whether the snapshot holds this metadata file at all, readable or not."""+ try:+ return (snapshot / name).is_file()+ except OSError:+ return False+++def _nonempty(snapshot: Path, name: str) -> bool:+ """Whether the file holds any bytes. One that holds none declares nothing."""+ try:+ return (snapshot / name).stat().st_size > 0+ except OSError:+ return True+++def _unreadable_metadata(snapshot: Path, name: str) -> bool:+ """Whether the file is there but _snapshot_metadata_file refused it, for being too big+ or for pointing out of the cache. The loader still reads it, so we cannot ignore it.+ An empty file is refused too, but it declares nothing and so blocks nothing."""+ return (+ _metadata_present(snapshot, name)+ and _snapshot_metadata_file(snapshot, name) is None+ and _nonempty(snapshot, name)+ )+++def _declares_configs(snapshot: Path, name: str) -> bool:+ """Whether this standalone yaml file names configs the loader would build. Unreadable+ counts as declaring, since datasets reads it as a card and we cannot see what it says."""+ if not _metadata_present(snapshot, name):+ return False+ path = _snapshot_metadata_file(snapshot, name)+ if path is None:+ return _nonempty(snapshot, name)+ try:+ from yaml import YAMLError, safe_load+ try:+ payload = safe_load(path.read_text(encoding = "utf-8"))+ except YAMLError:+ return True+ except (ImportError, OSError, UnicodeError, ValueError):+ return True+ if not isinstance(payload, dict):+ # DatasetCardData updates a dict from it, which raises on anything else.+ return bool(payload)+ # Only configs count: 4.3.0 builds no config from dataset_info declared here, so a+ # feature schema in this file leaves the loader inferring the files by pattern.+ return bool(payload.get("configs"))+++def _declares_splits(payload: Any) -> bool:+ """Whether dataset_info states its splits. An empty statement is still authoritative:+ datasets exposes no config at all rather than falling back to the files."""+ entries = payload if isinstance(payload, list) else [payload]+ return any(isinstance(item, dict) and "splits" in item for item in entries)+++def _malformed_info(payload: Any) -> bool:+ """A dataset_info list holding anything but mappings, which datasets calls .get on."""+ return isinstance(payload, list) and any(not isinstance(item, dict) for item in payload)def _snapshot_options(snapshot: Path) -> set[tuple[str, str]]:options: set[tuple[str, str]] = set()+ # Metadata we cannot read still names the loader's configs, so inference must not+ # step in beside it: a card too large or too unsafe to open, or the standalone yaml+ # file, which datasets reads as a card and we do not.+ declared = _unreadable_metadata(snapshot, "README.md") or _declares_configs(+ snapshot, ".huggingface.yaml"+ )readme = _snapshot_metadata_file(snapshot, "README.md")if readme is not None:card_data = _read_card_metadata(readme)+ if card_data is _UNPARSABLE_METADATA:+ # datasets raises out of DatasetCard.load, so no option here would ever start.+ return optionsif isinstance(card_data, dict):+ # datasets merges the standalone YAML into the card, so a README that+ # declares nothing does not undo a declaration made there.+ declared = declared or bool(card_data.get("configs"))_add_config_options(options, card_data.get("configs"))- _add_dataset_info_options(options, card_data.get("dataset_info"))+ named = len(options)+ info = card_data.get("dataset_info")+ _add_dataset_info_options(options, info)+ # dataset_info carrying only a feature schema names no config, so datasets+ # still resolves the files by pattern and inference has to run.+ declared = (+ declared or len(options) > named or _malformed_info(info) or _declares_splits(info)+ )for filename in ("dataset_infos.json", "dataset_info.json"):metadata = _snapshot_metadata_file(snapshot, filename)if metadata is None:+ # datasets json.loads dataset_infos.json unconditionally, so one it cannot+ # read raises before any split exists, inferred or not.+ declared = declared or (+ filename == "dataset_infos.json" and _metadata_present(snapshot, filename)+ )continuepayload = _safe_json_file(metadata, snapshot, allow_snapshot_symlink = True)if filename == "dataset_infos.json":+ # datasets json.loads this one while resolving configs, so a file it cannot+ # parse raises before any split exists, inferred or not.+ declared = declared or payload is None_add_dataset_info_options(options, payload)else:_add_info_options(options, payload)++ if not options and not declared:+ # Nothing was declared, which is the case #8140 reports: the loader still resolves+ # the files by pattern, so the picker infers the same splits it would. A card that+ # did declare something names its own configs, which inference cannot reproduce.+ options.update(_inferred_snapshot_options(snapshot))return optionsdiff --git a/studio/backend/hub/tests/test_dataset_local_options.py b/studio/backend/hub/tests/test_dataset_local_options.pyindex 690c988f41a..a7549c3da41 100644--- a/studio/backend/hub/tests/test_dataset_local_options.py+++ b/studio/backend/hub/tests/test_dataset_local_options.py@@ -5,6 +5,8 @@ from __future__ import annotationsimport json+import pytest+from hub.schemas.datasets import LocalDatasetOptionsRequestfrom hub.services.datasets import local_optionsfrom hub.utils import dataset_cache@@ -195,3 +197,583 @@ def test_local_options_rejects_an_arbitrary_supplied_path(tmp_path):assert response.cache_available is Falseassert response.splits == []+++def _snapshot(tmp_path):+ snapshot = tmp_path / "datasets--org--data" / "snapshots" / "commit"+ snapshot.mkdir(parents = True)+ return snapshot+++def _rows(snapshot, *names: str) -> None:+ for name in names:+ path = snapshot / name+ path.parent.mkdir(parents = True, exist_ok = True)+ path.write_text('{"text":"row"}\n', encoding = "utf-8")+++def _card(snapshot, body: str) -> None:+ snapshot.mkdir(parents = True, exist_ok = True)+ (snapshot / "README.md").write_text(f"---\n{body}---\nCard.\n", encoding = "utf-8")+++def test_snapshot_options_infer_the_splits_of_a_metadata_free_cache(tmp_path):+ snapshot = _snapshot(tmp_path)+ _rows(snapshot, "train.jsonl", "test.jsonl", "val.jsonl")++ # The shape reported in #8140: no card, three keyword-named files.+ assert local_options._snapshot_options(snapshot) == {+ ("default", "train"),+ ("default", "test"),+ ("default", "validation"),+ }+++def test_snapshot_options_infer_one_train_split_from_unlabelled_files(tmp_path):+ snapshot = _snapshot(tmp_path)+ _rows(snapshot, "records.jsonl")++ assert local_options._snapshot_options(snapshot) == {("default", "train")}+++def test_snapshot_options_infer_splits_from_directory_names(tmp_path):+ snapshot = _snapshot(tmp_path)+ _rows(snapshot, "train/a.parquet", "test/b.parquet")++ assert local_options._snapshot_options(snapshot) == {("default", "train"), ("default", "test")}+++def test_snapshot_options_infer_splits_from_sharded_names(tmp_path):+ snapshot = _snapshot(tmp_path)+ _rows(snapshot, "data/train-00000-of-00001.parquet", "data/test-00000-of-00001.parquet")++ assert local_options._snapshot_options(snapshot) == {("default", "train"), ("default", "test")}+++def test_snapshot_options_reject_a_shard_name_the_loader_refuses(tmp_path):+ snapshot = _snapshot(tmp_path)+ _rows(snapshot, "data/train-clean-00000-of-00001.parquet")++ # datasets raises on the name rather than falling through to the keyword stages.+ assert local_options._snapshot_options(snapshot) == set()+++def test_snapshot_options_offer_nothing_when_the_splits_disagree_on_a_format(tmp_path):+ snapshot = _snapshot(tmp_path)+ _rows(snapshot, "train.jsonl")+ (snapshot / "test.csv").write_text("text\nrow\n", encoding = "utf-8")++ # One builder serves the whole dataset, so datasets cannot load this at all.+ assert local_options._snapshot_options(snapshot) == set()+++def test_snapshot_options_treat_tsv_as_its_own_builder(tmp_path):+ snapshot = _snapshot(tmp_path)+ (snapshot / "train.csv").write_text("text\nrow\n", encoding = "utf-8")+ (snapshot / "test.tsv").write_text("text\trow\n", encoding = "utf-8")++ # tsv carries a tab separator, so datasets sees two different builders.+ assert local_options._snapshot_options(snapshot) == set()+++def test_snapshot_options_ignore_the_metadata_filenames_the_loader_drops(tmp_path):+ snapshot = _snapshot(tmp_path)+ (snapshot / "dataset_infos.json").write_text("{}", encoding = "utf-8")++ # FILES_TO_IGNORE drops these by basename, so the cache holds no data at all.+ assert local_options._snapshot_options(snapshot) == set()+++def test_snapshot_options_ignore_a_metadata_file_when_it_steers_a_split(tmp_path):+ snapshot = _snapshot(tmp_path)+ _rows(snapshot, "records.jsonl")+ (snapshot / "test").mkdir()+ (snapshot / "test" / "dataset_info.json").write_text("{}", encoding = "utf-8")++ assert local_options._snapshot_options(snapshot) == {("default", "train")}+++def test_snapshot_options_match_extensions_case_sensitively(tmp_path):+ snapshot = _snapshot(tmp_path)+ _rows(snapshot, "TRAIN.JSONL")++ # A POSIX glob never matches .JSONL, so datasets finds no data files here.+ assert local_options._snapshot_options(snapshot) == set()+++def test_snapshot_options_let_a_media_file_poison_a_split(tmp_path):+ snapshot = _snapshot(tmp_path)+ _rows(snapshot, "train.jsonl")+ (snapshot / "test.JPG").write_bytes(b"image")++ # The folder builders are registered in both cases, so this is a second builder.+ assert local_options._snapshot_options(snapshot) == set()+++def test_snapshot_options_reject_a_split_with_no_builder_of_its_own(tmp_path):+ snapshot = _snapshot(tmp_path)+ _rows(snapshot, "train.jsonl")+ (snapshot / "test").mkdir()+ (snapshot / "test" / "notes.bin").write_bytes(b"data")++ assert local_options._snapshot_options(snapshot) == set()+++def test_snapshot_options_read_through_a_compression_suffix(tmp_path):+ snapshot = _snapshot(tmp_path)+ (snapshot / "records.jsonl.gz").write_bytes(b"gzipped")++ assert local_options._snapshot_options(snapshot) == {("default", "train")}+++def test_snapshot_options_skip_a_codec_the_install_cannot_read(tmp_path):+ snapshot = _snapshot(tmp_path)+ (snapshot / "records.jsonl.zstd").write_bytes(b"zstd")++ assert local_options._snapshot_options(snapshot) == set()+++def test_snapshot_options_keep_a_readable_suffix_after_an_unknown_one(tmp_path):+ snapshot = _snapshot(tmp_path)+ (snapshot / "records.parquet.backup").write_bytes(b"parquet")++ assert local_options._snapshot_options(snapshot) == {("default", "train")}+++def test_snapshot_options_rank_folder_metadata_last(tmp_path):+ snapshot = _snapshot(tmp_path)+ for name in ("train/data.csv", "test/data.csv"):+ path = snapshot / name+ path.parent.mkdir(parents = True, exist_ok = True)+ path.write_text("text\nrow\n", encoding = "utf-8")+ (snapshot / "train" / "metadata.parquet").write_bytes(b"parquet")++ assert local_options._snapshot_options(snapshot) == {("default", "train"), ("default", "test")}+++def test_snapshot_options_skip_hidden_and_dunder_directories(tmp_path):+ snapshot = _snapshot(tmp_path)+ _rows(snapshot, "records.jsonl", ".git/val.jsonl", "__pycache__/val.jsonl")++ assert local_options._snapshot_options(snapshot) == {("default", "train")}+++def test_snapshot_options_refuse_a_file_symlinked_out_of_the_cache(tmp_path):+ outside = tmp_path / "outside"+ outside.mkdir()+ (outside / "test.jsonl").write_text('{"text":"row"}\n', encoding = "utf-8")+ snapshot = _snapshot(tmp_path)+ _rows(snapshot, "train.jsonl")+ (snapshot / "test.jsonl").symlink_to(outside / "test.jsonl")++ # datasets reads every file in the config, so one escape condemns all of it.+ assert local_options._snapshot_options(snapshot) == set()+++def test_snapshot_options_read_a_blob_symlink_the_cache_owns(tmp_path):+ repo = tmp_path / "datasets--org--data"+ blobs = repo / "blobs"+ blobs.mkdir(parents = True)+ (blobs / "abc123").write_text('{"text":"row"}\n', encoding = "utf-8")+ snapshot = repo / "snapshots" / "commit"+ snapshot.mkdir(parents = True)+ (snapshot / "records.jsonl").symlink_to(blobs / "abc123")++ # The normal cache layout: every file is a link into blobs.+ assert local_options._snapshot_options(snapshot) == {("default", "train")}+++def test_snapshot_options_leave_a_declared_card_to_its_own_configs(tmp_path):+ snapshot = _snapshot(tmp_path)+ _card(snapshot, "configs:\n- config_name: foo\n data_dir: foo\n")+ _rows(snapshot, "foo/records.jsonl", "test.jsonl")++ # The card names the loader's configs, and inference cannot reproduce them, so the+ # picker does not invent a default one beside them.+ assert local_options._snapshot_options(snapshot) == set()+++def test_snapshot_options_leave_a_standalone_yaml_card_alone(tmp_path):+ snapshot = _snapshot(tmp_path)+ (snapshot / ".huggingface.yaml").write_text("configs:\n- config_name: foo\n", encoding = "utf-8")+ _rows(snapshot, "records.jsonl")++ assert local_options._snapshot_options(snapshot) == set()+++def test_snapshot_options_offer_nothing_for_a_card_the_loader_cannot_parse(tmp_path):+ snapshot = _snapshot(tmp_path)+ (snapshot / "README.md").write_text("---\nconfigs: [\n---\n", encoding = "utf-8")+ _rows(snapshot, "train.jsonl")++ # DatasetCard.load raises on it, so nothing in the snapshot is loadable.+ assert local_options._snapshot_options(snapshot) == set()+++def test_snapshot_options_still_infer_beside_a_plain_readme(tmp_path):+ snapshot = _snapshot(tmp_path)+ (snapshot / "README.md").write_text("# Just prose\n", encoding = "utf-8")+ _rows(snapshot, "records.jsonl")++ assert local_options._snapshot_options(snapshot) == {("default", "train")}+++def test_snapshot_options_stay_empty_for_a_readme_only_cache(tmp_path):+ snapshot = _snapshot(tmp_path)+ (snapshot / "README.md").write_text("# Alpaca\n", encoding = "utf-8")++ # The first #8140 negative: nothing to train on, so nothing is offered.+ assert local_options._snapshot_options(snapshot) == set()+++def test_snapshot_options_stay_empty_for_a_licence_only_subdirectory(tmp_path):+ snapshot = _snapshot(tmp_path)+ (snapshot / "legal").mkdir()+ (snapshot / "legal" / "LICENSE").write_text("MIT\n", encoding = "utf-8")++ # The second #8140 negative.+ assert local_options._snapshot_options(snapshot) == set()+++def test_snapshot_options_skip_a_split_name_the_picker_cannot_start(tmp_path):+ snapshot = _snapshot(tmp_path)+ _rows(snapshot, f"data/{'x' * 200}-00000-of-00001.jsonl")++ assert local_options._snapshot_options(snapshot) == set()+++def test_snapshot_options_give_up_on_a_snapshot_too_large_to_compare(tmp_path, monkeypatch):+ monkeypatch.setattr(local_options, "_MAX_SNAPSHOT_DATA_FILES", 1)+ snapshot = _snapshot(tmp_path)+ _rows(snapshot, "train.jsonl", "test.jsonl")++ # Past the cap the scan is a traversal-order prefix, which proves nothing.+ assert local_options._snapshot_options(snapshot) == set()+++def test_snapshot_options_vote_on_the_files_the_loader_samples(tmp_path):+ snapshot = _snapshot(tmp_path)+ for index in range(200):+ _rows(snapshot, f"train/{index:04d}.jsonl")+ for index in range(300):+ (snapshot / "train" / f"z{index:04d}.csv").write_text("text\nrow\n", encoding = "utf-8")+ (snapshot / "test").mkdir()+ (snapshot / "test" / "a.csv").write_text("text\nrow\n", encoding = "utf-8")++ # datasets samples a split's first 200 files, so train is json and disagrees with test.+ assert local_options._snapshot_options(snapshot) == set()+++def test_snapshot_options_ignore_a_training_file_a_folder_builder_drops(tmp_path):+ snapshot = _snapshot(tmp_path)+ (snapshot / "train").mkdir()+ for name in ("a.JPG", "b.JPG"):+ (snapshot / "train" / name).write_bytes(b"image")+ _rows(snapshot, "train/c.jsonl")++ # The folder builder wins the vote and then reads only the images.+ assert local_options._snapshot_options(snapshot) == set()+++def test_snapshot_options_count_the_full_folder_extension_set(tmp_path):+ snapshot = _snapshot(tmp_path)+ _rows(snapshot, "train/a.jsonl", "test/b.jsonl")+ for name in ("c.blp", "d.blp"):+ (snapshot / "test" / name).write_bytes(b"image")++ # .blp is an imagefolder extension, so test is a different builder from train.+ assert local_options._snapshot_options(snapshot) == set()+++ "front", ["---\n---\n", "---\nnull\n---\n", "---\n# only a comment\n---\n"]+)+def test_snapshot_options_read_empty_front_matter_as_an_empty_card(tmp_path, front):+ snapshot = _snapshot(tmp_path)+ (snapshot / "README.md").write_text(front + "Prose.\n", encoding = "utf-8")+ _rows(snapshot, "records.jsonl")++ # RepoCard treats these as an empty card and carries on with file inference.+ assert local_options._snapshot_options(snapshot) == {("default", "train")}+++def test_snapshot_options_reject_a_split_whose_only_file_is_empty(tmp_path):+ snapshot = _snapshot(tmp_path)+ (snapshot / "train.jsonl").write_text("", encoding = "utf-8")++ assert local_options._snapshot_options(snapshot) == set()+++def test_snapshot_options_keep_a_json_split_holding_one_empty_file(tmp_path):+ snapshot = _snapshot(tmp_path)+ (snapshot / "train.jsonl").write_text("", encoding = "utf-8")+ _rows(snapshot, "train2.jsonl")++ # The json builder skips an empty file as long as another still holds rows.+ assert local_options._snapshot_options(snapshot) == {("default", "train")}+++def test_snapshot_options_reject_a_csv_split_holding_one_empty_file(tmp_path):+ snapshot = _snapshot(tmp_path)+ (snapshot / "train.csv").write_text("", encoding = "utf-8")+ (snapshot / "train2.csv").write_text("text\nrow\n", encoding = "utf-8")++ assert local_options._snapshot_options(snapshot) == set()+++def test_snapshot_options_stand_down_beside_a_card_too_large_to_read(tmp_path):+ snapshot = _snapshot(tmp_path)+ (snapshot / "README.md").write_text(+ "---\nconfigs:\n- config_name: foo\n---\n" + "x" * 3_000_000, encoding = "utf-8"+ )+ _rows(snapshot, "records.jsonl")++ # The loader reads the card and names foo, so inventing a default beside it is wrong.+ assert local_options._snapshot_options(snapshot) == set()+++def test_snapshot_options_stand_down_beside_a_card_outside_the_cache(tmp_path):+ outside = tmp_path / "outside"+ outside.mkdir()+ (outside / "README.md").write_text("---\nconfigs:\n- config_name: foo\n---\n", encoding = "utf-8")+ snapshot = _snapshot(tmp_path)+ (snapshot / "README.md").symlink_to(outside / "README.md")+ _rows(snapshot, "records.jsonl")++ assert local_options._snapshot_options(snapshot) == set()+++def test_snapshot_options_reject_every_split_when_a_sibling_is_empty(tmp_path):+ snapshot = _snapshot(tmp_path)+ (snapshot / "train.csv").write_text("text\nrow\n", encoding = "utf-8")+ (snapshot / "test.csv").write_text("", encoding = "utf-8")++ # datasets prepares both splits, so the empty test file fails train as well.+ assert local_options._snapshot_options(snapshot) == set()+++def test_snapshot_options_keep_a_json_split_beside_an_empty_sibling(tmp_path):+ snapshot = _snapshot(tmp_path)+ _rows(snapshot, "train.jsonl")+ (snapshot / "test.jsonl").write_text("", encoding = "utf-8")++ # The json builder skips a file with no rows rather than failing the build.+ assert local_options._snapshot_options(snapshot) == {("default", "train")}+++def test_snapshot_options_stand_down_when_standalone_yaml_declares_a_config(tmp_path):+ snapshot = _snapshot(tmp_path)+ (snapshot / ".huggingface.yaml").write_text(+ "configs:\n- config_name: foo\n data_files: train.jsonl\n", encoding = "utf-8"+ )+ (snapshot / "README.md").write_text("---\nlicense: mit\n---\n", encoding = "utf-8")+ _rows(snapshot, "train.jsonl")++ # A README declaring nothing must not undo the standalone YAML's declaration.+ assert local_options._snapshot_options(snapshot) == set()+++def test_snapshot_options_infer_beside_a_standalone_yaml_declaring_nothing(tmp_path):+ snapshot = _snapshot(tmp_path)+ (snapshot / ".huggingface.yaml").write_text("viewer: false\n", encoding = "utf-8")+ _rows(snapshot, "train.jsonl")++ # The loader finds no config there either, so it resolves the files by pattern.+ assert local_options._snapshot_options(snapshot) == {("default", "train")}+++def test_snapshot_options_stand_down_beside_an_unreadable_standalone_yaml(tmp_path):+ snapshot = _snapshot(tmp_path)+ (snapshot / ".huggingface.yaml").write_text("configs: [\n", encoding = "utf-8")+ _rows(snapshot, "train.jsonl")++ assert local_options._snapshot_options(snapshot) == set()+++def test_snapshot_options_infer_beside_dataset_info_naming_no_split(tmp_path):+ snapshot = _snapshot(tmp_path)+ _card(snapshot, "dataset_info:\n features:\n - name: text\n dtype: string\n")+ _rows(snapshot, "train.jsonl")++ # A feature schema alone names no config, so the loader still infers by pattern.+ assert local_options._snapshot_options(snapshot) == {("default", "train")}+++def test_snapshot_options_reject_a_split_holding_an_undecompressible_file(tmp_path):+ snapshot = _snapshot(tmp_path)+ _rows(snapshot, "train.jsonl")+ (snapshot / "train2.jsonl.zst").write_bytes(b"\x28\xb5\x2f\xfd\x00\x00")++ # datasets keeps the .zst for the json builder and dies on the missing codec.+ assert local_options._snapshot_options(snapshot) == set()+++def test_snapshot_options_infer_beside_standalone_yaml_dataset_info(tmp_path):+ snapshot = _snapshot(tmp_path)+ (snapshot / ".huggingface.yaml").write_text(+ "dataset_info:\n features:\n - name: text\n dtype: string\n", encoding = "utf-8"+ )+ _rows(snapshot, "train.jsonl")++ # 4.3.0 builds no config from dataset_info declared there, so it infers the files.+ assert local_options._snapshot_options(snapshot) == {("default", "train")}+++def test_snapshot_options_stand_down_beside_unparsable_legacy_metadata(tmp_path):+ snapshot = _snapshot(tmp_path)+ (snapshot / "dataset_infos.json").write_text("{not json", encoding = "utf-8")+ _rows(snapshot, "train.jsonl")++ # datasets json.loads it while resolving configs and raises before any split exists.+ assert local_options._snapshot_options(snapshot) == set()+++def test_snapshot_options_infer_beside_an_empty_readme(tmp_path):+ snapshot = _snapshot(tmp_path)+ (snapshot / "README.md").write_text("", encoding = "utf-8")+ _rows(snapshot, "train.jsonl")++ # A card with no bytes declares nothing, so it blocks nothing.+ assert local_options._snapshot_options(snapshot) == {("default", "train")}+++def test_snapshot_options_count_bw_images_as_a_folder_builder(tmp_path):+ snapshot = _snapshot(tmp_path)+ (snapshot / "a.bw").write_bytes(b"\x89PNG\r\n\x1a\n")+ (snapshot / "b.bw").write_bytes(b"\x89PNG\r\n\x1a\n")+ _rows(snapshot, "notes.jsonl")++ # imagefolder wins the vote and drops the jsonl, so there is nothing to train on.+ assert local_options._snapshot_options(snapshot) == set()+++def test_snapshot_options_stand_down_beside_a_non_mapping_standalone_yaml(tmp_path):+ snapshot = _snapshot(tmp_path)+ (snapshot / ".huggingface.yaml").write_text("hello\n", encoding = "utf-8")+ _rows(snapshot, "train.jsonl")++ # DatasetCardData updates a dict from it and raises on a scalar.+ assert local_options._snapshot_options(snapshot) == set()+++def test_snapshot_options_infer_beside_an_empty_standalone_yaml(tmp_path):+ snapshot = _snapshot(tmp_path)+ (snapshot / ".huggingface.yaml").write_text("", encoding = "utf-8")+ _rows(snapshot, "train.jsonl")++ assert local_options._snapshot_options(snapshot) == {("default", "train")}+++def test_snapshot_options_reject_a_split_whose_module_needs_a_missing_codec(tmp_path):+ snapshot = _snapshot(tmp_path)+ (snapshot / "train.csv").write_text("text\nrow\n", encoding = "utf-8")+ (snapshot / "train2.jsonl.zst").write_bytes(b"\x28\xb5\x2f\xfd\x00\x00")++ # The inner .jsonl still votes, so datasets picks json and dies on the .zst.+ assert local_options._snapshot_options(snapshot) == set()+++def test_snapshot_options_stand_down_beside_an_empty_legacy_metadata_file(tmp_path):+ snapshot = _snapshot(tmp_path)+ (snapshot / "dataset_infos.json").write_text("", encoding = "utf-8")+ _rows(snapshot, "train.jsonl")++ assert local_options._snapshot_options(snapshot) == set()+++def test_snapshot_options_stand_down_beside_a_card_that_cannot_be_decoded(tmp_path):+ snapshot = _snapshot(tmp_path)+ (snapshot / "README.md").write_bytes(b"\xff\xfe---\nconfigs: x\n---\n")+ _rows(snapshot, "train.jsonl")++ # DatasetCard.load reads the card as utf-8 and raises before any data file.+ assert local_options._snapshot_options(snapshot) == set()+++def test_snapshot_options_stand_down_beside_a_malformed_dataset_info_list(tmp_path):+ snapshot = _snapshot(tmp_path)+ _card(snapshot, "dataset_info: [foo]\n")+ _rows(snapshot, "train.jsonl")++ # datasets calls .get on each entry, so a list of scalars raises.+ assert local_options._snapshot_options(snapshot) == set()+++def test_snapshot_options_ignore_a_dangling_link_beside_a_good_file(tmp_path):+ snapshot = _snapshot(tmp_path)+ _rows(snapshot, "train.jsonl")+ (snapshot / "train-missing.jsonl").symlink_to("../../blobs/gone")++ # resolve_pattern keeps a link only when its target is a file, so the loader+ # never sees this one and the surviving split still loads.+ assert local_options._snapshot_options(snapshot) == {("default", "train")}+++def test_snapshot_options_drop_a_header_only_csv_split(tmp_path):+ snapshot = _snapshot(tmp_path)+ (snapshot / "train.csv").write_text("text\nrow\n", encoding = "utf-8")+ (snapshot / "test.csv").write_text("text\n", encoding = "utf-8")++ # The header alone yields no row, and datasets still builds train around it.+ assert local_options._snapshot_options(snapshot) == {("default", "train")}+++def test_snapshot_options_offer_nothing_when_every_csv_is_header_only(tmp_path):+ snapshot = _snapshot(tmp_path)+ (snapshot / "train.csv").write_text("text\n", encoding = "utf-8")++ assert local_options._snapshot_options(snapshot) == set()+++def test_snapshot_options_stand_down_beside_an_empty_split_declaration(tmp_path):+ snapshot = _snapshot(tmp_path)+ _card(snapshot, "dataset_info:\n splits: {}\n")+ _rows(snapshot, "train.jsonl")++ # datasets treats the empty declaration as authoritative and exposes no config.+ assert local_options._snapshot_options(snapshot) == set()+++def test_snapshot_options_skip_file_checks_for_an_untrainable_builder(tmp_path, monkeypatch):+ snapshot = _snapshot(tmp_path)+ for index in range(8):+ (snapshot / f"img{index}.png").write_bytes(b"\x89PNG\r\n\x1a\n")++ def _fail(*args, **kwargs):+ raise AssertionError("resolved every file for a builder that trains nothing")++ monkeypatch.setattr(local_options, "_offerable", _fail)++ # imagefolder wins, so no file can be offered and none needs opening to say so.+ assert local_options._inferred_snapshot_options(snapshot) == set()+++def test_snapshot_options_keep_a_compressed_csv_split(tmp_path):+ import gzip++ snapshot = _snapshot(tmp_path)+ (snapshot / "train.csv.gz").write_bytes(gzip.compress(b"text\nrow\n"))++ # Compressed bytes say nothing about the rows inside, so the split still stands.+ assert local_options._snapshot_options(snapshot) == {("default", "train")}+++def test_snapshot_options_drop_a_split_holding_an_empty_json_container(tmp_path):+ snapshot = _snapshot(tmp_path)+ _rows(snapshot, "train.jsonl")+ (snapshot / "test.json").write_text("[]", encoding = "utf-8")++ # `[]` parses fine and yields no row, so datasets builds train around it.+ assert local_options._snapshot_options(snapshot) == {("default", "train")}+++def test_snapshot_options_reject_a_legacy_lzma_stream(tmp_path):+ import lzma++ snapshot = _snapshot(tmp_path)+ (snapshot / "train.jsonl.lzma").write_bytes(+ lzma.compress(b'{"text":"row"}\n', format = lzma.FORMAT_ALONE)+ )++ # datasets registers .xz for its filter, not the alone-format .lzma.+ assert local_options._snapshot_options(snapshot) == set()