Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.
Python cliconsumer-gpudpofine-tuningggufhuggingfacellmllmopslocal-ailocal-llmloralow-vrammachine-learningollamapeftpythonpytorchqlorasfttransformers
fix(data): resolve media paths the same way on every load path (#1599)
Alpamys Makazhanf98dac9d4958
diff --git a/changelog.d/0.75.1/1599.fixed.md b/changelog.d/0.75.1/1599.fixed.mdnew file mode 100644index 00000000..1a24a9a6--- /dev/null+++ b/changelog.d/0.75.1/1599.fixed.md@@ -0,0 +1 @@+- Vision and audio rows loaded through a streaming `data.interleave`, a remote URI or a Hugging Face Hub dataset (train and `validation` splits) now resolve their `image` / `audio` paths the same way as rows from a local file: against `data.image_dir` / `data.audio_dir` when set, otherwise against the directory of the local data file the row came from, skipping a row whose file lies outside that directory with the usual "rows skipped" warning. These load paths used to keep the value as written, so a relative path was opened against the working directory and `data.image_dir` / `data.audio_dir` had no effect. This is stricter for a remote URI or a Hub dataset whose rows hold file paths and that sets neither directory: there is no local directory to resolve them against, so the load now stops with a message naming the setting (`data.image_dir: .` resolves them under the working directory, skipping paths outside it). An image the Hub dataset has already decoded is passed on as before. On every load path, in `soup infer --task asr` and in `soup data inspect`, a value naming a network share, a device or an extended-length path is skipped without being looked up, and so are a `bytes` value and, on Windows, a DOS device name such as `nul`; on Linux and macOS a value beginning with `//` now counts as a network path too. The SFT vision and audio paths and the ASR / TTS audio loader read a file only when it is a regular file, so a directory, FIFO or device is reported instead of being read (#1599).diff --git a/docs/data.md b/docs/data.mdindex 23a6e281..d8b6f7f8 100644--- a/docs/data.md+++ b/docs/data.md@@ -743,6 +743,28 @@ is forwarded to `datasets.load_dataset(..., streaming=True)` and `buffer_size` sthat stream, then Soup materialises up to 1M rows — the same shape as remote (#689).An all-hub *list* with `streaming: true` is still refused (#459). `buffer_size` shuffles the train split only; a capped validation split takes the first N rows unshuffled.+**Image and audio paths** in `llava` / `sharegpt4v` / `audio` / `asr` rows resolve the same+way on every load path: a local file, a local or streaming interleave, a remote URI, a Hub+dataset (both splits) and the `data.replay` file. A relative path resolves against+`data.image_dir` / `data.audio_dir` when it is set, otherwise against the directory of the+local file the row came from, and a row whose file lies outside that directory is skipped+with a warning. A remote URI or a Hub dataset has no such directory, so when its rows hold+file paths the setting is required: once the rows are read, the load stops with a message+naming it. `data.image_dir: .` resolves them under the working directory. An image that a+Hub dataset has already decoded carries no path and is passed on as it is.++A value that names a network share, a device or an extended-length path (`\\host\share\...`,+`//host/share/...`, `\\?\...`, `\\.\...`, `\??\...`), or that holds a NUL byte, is skipped+without being looked up, and `soup data inspect` does not look it up either. That includes+a value beginning with two slashes on Linux and macOS, where `//srv/x.png` would otherwise+read as `/srv/x.png`, and, on Windows, a DOS device name such as `nul` or `com1`. Write such+rows relative to the media directory instead, even when the directory itself is on a share.++Before reading a file, the SFT vision and audio paths and the ASR / TTS audio loader check+that it is a regular file. A directory, FIFO or device gets the SFT path's "cannot open"+warning, and stops the ASR / TTS loader with an error, as a symlink does. The check is made+before the file is opened, so a file replaced in between is not caught.+**Multi-dataset interleave** (v0.42.0 schema, wired into training-time loading in #443;extended to streaming and HF-hub dataset names in #459):diff --git a/docs/training.md b/docs/training.mdindex 6caf7a09..a40f877c 100644--- a/docs/training.md+++ b/docs/training.md@@ -1033,6 +1033,11 @@ training:{"image": "chart.png", "conversations": [{"from": "human", "value": "<image>\nWhat does this show?"}, {"from": "gpt", "value": "Quarterly revenue."}]}```+A relative `image` path resolves against `data.image_dir`, or against the data file's+directory when it is unset. A Hub dataset or a remote URI has no data file directory, so set+`data.image_dir` when its rows hold image paths; see+[Data Pipeline Pro](data.md#data-pipeline-pro).+`soup data inspect` automatically shows image statistics (count, formats, missing files) for vision datasets.diff --git a/src/soup_cli/commands/data.py b/src/soup_cli/commands/data.pyindex 4925bb74..5b0969de 100644--- a/src/soup_cli/commands/data.py+++ b/src/soup_cli/commands/data.py@@ -17,7 +17,7 @@ from soup_cli.data.loader import load_raw_datafrom soup_cli.data.validator import validate_and_statsfrom soup_cli.utils.embed import DEFAULT_EMBED_MODEL, embed_textsfrom soup_cli.utils.exit_codes import EXIT_GATE_FAILED, EXIT_USAGE_ERROR, GateCommand-from soup_cli.utils.paths import is_under_cwd+from soup_cli.utils.paths import is_network_or_device_path, is_under_cwdfrom soup_cli.utils.semdedup import DedupReport, greedy_semdedupfrom soup_cli.utils.terminal import for_terminal@@ -693,10 +693,13 @@ def _show_vision_stats(data: list[dict]) -> None:existing = 0for row in data:img_path = row.get("image", "")- if not img_path:+ if not img_path or not isinstance(img_path, str):continueext = Path(img_path).suffix.lower()extensions[ext] = extensions.get(ext, 0) + 1+ # A network share or a device path is never looked up, nor counted as found.+ if is_network_or_device_path(img_path):+ continueif Path(img_path).exists():existing += 1diff --git a/src/soup_cli/commands/infer.py b/src/soup_cli/commands/infer.pyindex 1dd5578d..8ebdd314 100644--- a/src/soup_cli/commands/infer.py+++ b/src/soup_cli/commands/infer.py@@ -381,19 +381,20 @@ def _read_asr_rows(path: Path) -> list[dict]:def _resolve_asr_audio(audio: str, base_dir: Path) -> str:"""Resolve a row's audio path against ``base_dir`` with containment.- Rejects UNC / network paths and anything that resolves outside+ Rejects UNC / network / device paths (the same check the training loader+ runs) and anything that resolves outside``base_dir`` (realpath + commonpath) — the infer path is fed JSONL theoperator may not have authored (the training path already enforces thisvia ``_validate_audio_files``). Raises ``ValueError`` on rejection."""- from soup_cli.utils.paths import is_under+ from soup_cli.utils.paths import is_network_or_device_path, is_underif "\x00" in audio:raise ValueError("audio path must not contain null bytes")# UNC (\\host\share) / network (//host) paths trigger outbound SMB on# Windows — reject before any filesystem touch.- if audio.startswith(("\\\\", "//")):- raise ValueError("audio path must not be a UNC / network path")+ if is_network_or_device_path(audio):+ raise ValueError("audio path must not be a UNC / network / device path")candidate = Path(audio)if not candidate.is_absolute():candidate = base_dir / candidatediff --git a/src/soup_cli/data/loader.py b/src/soup_cli/data/loader.pyindex 24c81711..6a08df0d 100644--- a/src/soup_cli/data/loader.py+++ b/src/soup_cli/data/loader.py@@ -3,13 +3,17 @@from __future__ import annotationsimport json+import osfrom dataclasses import dataclass, replace+from functools import partial+from itertools import islicefrom pathlib import Pathfrom rich.console import Consolefrom soup_cli.config.schema import DataConfigfrom soup_cli.data.formats import (+ MAX_DETECT_ROWS,detect_format,format_to_messages_with_reason,is_audio_format,@@ -228,6 +232,7 @@ def _format_rows(*,preserve_source_columns: bool = False,source: str | None = None,+ kept_indices: list[int] | None = None,) -> list[dict]:"""Normalize rows, optionally retaining columns used by GRPO rewards.@@ -237,6 +242,10 @@ def _format_rows(references such as ``answer``, ``expected``, ``schema``, or custommetadata. The opt-in keeps the default loader contract byte-for-byteunchanged for every other task.++ ``kept_indices``, when given, receives the ``raw_data`` index of every row+ that converted, in order, so a caller can map a formatted row back to the+ raw row it came from."""formatted: list[dict] = []dropped = 0@@ -253,6 +262,8 @@ def _format_rows(if preserve_source_columns:normalized = {**raw_row, **normalized}formatted.append(normalized)+ if kept_indices is not None:+ kept_indices.append(index)global _last_loadif dropped and first_drop is not None:_report_dropped_rows(dropped, len(raw_data), fmt, first_drop, source)@@ -898,6 +909,13 @@ def _load_interleaved_streaming_datasets(``s3://bucket/key.jsonl?endpoint=http://169.254.169.254`` would reachhf_load unvalidated, and a non-allowlisted-scheme entry like``https://example.com/data.jsonl`` would reach it unvalidated too.++ Media paths (vision / audio formats) resolve per entry, as on the eager+ path: against ``data.image_dir`` / ``data.audio_dir`` when set, else the+ entry's own directory (a remote entry has none). When the entries do not+ share that directory, each stream is tagged with its entry's index before+ the streams are combined -- lazily, through ``IterableDataset.map`` -- and+ the tag is popped as the rows materialise (:func:`_streams_need_source_tags`)."""try:from datasets import concatenate_datasets, interleave_datasets@@ -920,6 +938,10 @@ def _load_interleaved_streaming_datasets(ds = ds.shuffle(buffer_size=buf)streams.append(ds)+ tag_sources = _streams_need_source_tags(streams, data_config, train_paths)+ if tag_sources:+ streams = _tag_streams(streams)+if spec.strategy == "concat":combined_stream = concatenate_datasets(streams)elif spec.strategy == "under":@@ -934,6 +956,7 @@ def _load_interleaved_streaming_datasets(raise AssertionError(f"unreachable interleave strategy {spec.strategy!r}")raw_data: list[dict] = []+ row_sources: list[int] = []for i, row in enumerate(combined_stream):if i >= MAX_REMOTE_ROWS:console.print(@@ -942,17 +965,29 @@ def _load_interleaved_streaming_datasets("for larger jobs).[/]")break- raw_data.append(dict(row))+ raw_row = dict(row)+ if tag_sources:+ row_sources.append(raw_row.pop(_SOURCE_INDEX_KEY))+ raw_data.append(raw_row)fmt = data_config.formatif fmt == "auto":fmt = detect_format(raw_data)console.print(f"[dim]Auto-detected format: {fmt}[/]")+ kept: list[int] = []formatted = _format_rows(raw_data,fmt,preserve_source_columns=preserve_source_columns,+ kept_indices=kept,+ )+ formatted = _resolve_streamed_media(+ formatted,+ [row_sources[position] for position in kept] if tag_sources else None,+ fmt,+ data_config,+ train_paths,)console.print(@@ -990,34 +1025,7 @@ def _validate_vision_images(data: list[dict], image_dir: Path) -> list[dict]:to ``PIL.Image.open``. Mirrors :func:`_validate_audio_files` (the siblingaudio path got this fix in v0.71.32; the vision path was missed)."""- from soup_cli.utils.paths import is_under-- valid = []- missing = 0- traversal = 0- for row in data:- if "image" not in row or not row["image"]:- missing += 1- continue- image_path = Path(row["image"])- if not image_path.is_absolute():- image_path = image_dir / image_path- # Path traversal protection: resolved path must stay under image_dir.- # realpath + commonpath (is_under) — Path.is_relative_to() breaks on- # Windows 8.3 short names.- if not is_under(image_path, image_dir):- traversal += 1- continue- valid.append({**row, "image": str(image_path.resolve())})-- if missing > 0:- console.print(f"[yellow]Warning: {missing} rows skipped (missing image path)[/]")- if traversal > 0:- console.print(- f"[yellow]Warning: {traversal} rows skipped "- f"(image path outside {image_dir})[/]"- )- return valid+ return _resolve_media_column(data, "image", image_dir)def _validate_audio_files(data: list[dict], audio_dir: Path) -> list[dict]:@@ -1026,34 +1034,280 @@ def _validate_audio_files(data: list[dict], audio_dir: Path) -> list[dict]:Each row must have an 'audio' key with a filename or path.Resolves relative paths against audio_dir. Rejects path traversal."""- valid = []- from soup_cli.utils.paths import is_under+ return _resolve_media_column(data, "audio", audio_dir)+++# Row key of a media format -> the setting that names its base directory.+_MEDIA_DIR_SETTINGS = {"image": "data.image_dir", "audio": "data.audio_dir"}++# Set on streamed rows by _tag_source_index and popped as the rows+# materialise: the data.train index the row was read from.+_SOURCE_INDEX_KEY = "__soup_source_index__"+++def _media_key(fmt: str) -> str | None:+ """The row key that holds a media path in ``fmt``; None for a text format."""+ if is_vision_format(fmt):+ return "image"+ if is_audio_format(fmt):+ return "audio"+ return None+++def _media_dir_for(key: str, data_config: DataConfig, data_dir: Path | None) -> Path | None:+ """``data.image_dir`` / ``data.audio_dir`` when set, else ``data_dir``."""+ configured = data_config.image_dir if key == "image" else data_config.audio_dir+ return Path(configured) if configured else data_dir+++def _entry_media_dir(key: str, data_config: DataConfig, entry: str) -> Path | None:+ """The base directory of one data.train entry's media; None for a remote+ entry when no directory is configured."""+ data_dir = None if _looks_like_remote_uri(entry) else Path(entry).parent+ return _media_dir_for(key, data_config, data_dir)+++def _media_dir_required(source: str, key: str, *, plural: bool = False) -> ValueError:+ """The error for media paths that have no local directory to resolve against."""+ setting = _MEDIA_DIR_SETTINGS[key]+ if plural:+ subject = f"{source} are not local files, so their"+ else:+ subject = f"{source} is not a local file, so its"+ return ValueError(+ f"{subject} {key!r} paths have no directory to resolve against. "+ f"Set {setting} to the local directory that holds the {key} files: "+ f"relative paths resolve under it, and rows whose {key} is outside it "+ "are skipped."+ )+++def _resolve_media_entries(+ rows: list[dict],+ key: str,+ media_dir: Path | None,+ *,+ source: str = "data.train",+ plural: bool = False,+) -> tuple[list[dict | None], int, int]:+ """Resolve each row's ``key`` media path against ``media_dir``.++ Returns one entry per row, in order -- the row with its path resolved,+ the row unchanged when its value is not a path at all (an image a Hub+ dataset has already decoded), or None for a skipped row -- plus how many+ rows were skipped for a missing path and for a path outside+ ``media_dir``. Every load path goes through here, so a row is treated+ the same way wherever it was read from.++ A relative path resolves against ``media_dir``. A network-share or+ device form (:func:`~soup_cli.utils.paths.is_network_or_device_path`), a+ value holding a NUL byte, and a ``bytes`` or path-object value count as+ outside and are refused before any filesystem call. ``media_dir`` is+ None for a remote URI or Hub dataset with no ``data.image_dir`` /+ ``data.audio_dir``: a string path there has nothing to resolve against,+ so the load stops and names the setting (``source``, ``plural``).+ """+ from soup_cli.utils.paths import is_network_or_device_path, is_under+ entries: list[dict | None] = []missing = 0- traversal = 0- for row in data:- if "audio" not in row or not row["audio"]:+ outside = 0+ for row in rows:+ value = row.get(key)+ if not value:missing += 1+ entries.append(None)+ continue+ if isinstance(value, (bytes, os.PathLike)):+ # A reader takes these as a file name too, but they are not path+ # strings: skipped like a path outside, never handed on unchecked.+ outside += 1+ entries.append(None)+ continue+ if not isinstance(value, str):+ entries.append(row)continue- audio_path = Path(row["audio"])- if not audio_path.is_absolute():- audio_path = audio_dir / audio_path- # Path traversal protection: resolved path must stay under audio_dir.- # realpath + commonpath (is_under) — Path.is_relative_to() breaks on+ if media_dir is None:+ raise _media_dir_required(source, key, plural=plural)+ if "\x00" in value or is_network_or_device_path(value):+ outside += 1+ entries.append(None)+ continue+ media_path = Path(value)+ if not media_path.is_absolute():+ media_path = media_dir / media_path+ # realpath + commonpath (is_under) -- Path.is_relative_to() breaks on# Windows 8.3 short names.- resolved = audio_path.resolve()- if not is_under(audio_path, audio_dir):- traversal += 1+ if not is_under(media_path, media_dir):+ outside += 1+ entries.append(None)continue- valid.append({**row, "audio": str(resolved)})+ entries.append({**row, key: str(media_path.resolve())})+ return entries, missing, outside++def _warn_media_skips(key: str, missing: int, outside: int, media_dir: Path | None) -> None:+ """The "rows skipped" warnings of one media pass, worded as they always were.++ ``media_dir`` is None only for rows with no local directory, where the+ one value counted as outside without a string path is a ``bytes`` or+ path object.+ """if missing > 0:- console.print(f"[yellow]Warning: {missing} rows skipped (missing audio path)[/]")- if traversal > 0:+ console.print(f"[yellow]Warning: {missing} rows skipped (missing {key} path)[/]")+ if outside > 0 and key == "image":+ if media_dir is None:+ reason = "image value is not a path string"+ else:+ reason = f"image path outside {media_dir}"+ console.print(f"[yellow]Warning: {outside} rows skipped ({reason})[/]")+ elif outside > 0:console.print(- f"[red]Warning: {traversal} rows skipped (audio path traversal blocked)[/]"+ f"[red]Warning: {outside} rows skipped (audio path traversal blocked)[/]"+ )+++def _resolve_media_column(+ rows: list[dict],+ key: str,+ media_dir: Path | None,+ *,+ source: str = "data.train",+ plural: bool = False,+) -> list[dict]:+ """:func:`_resolve_media_entries` plus its warnings; returns the rows kept."""+ entries, missing, outside = _resolve_media_entries(+ rows, key, media_dir, source=source, plural=plural+ )+ _warn_media_skips(key, missing, outside, media_dir)+ return [row for row in entries if row is not None]+++def _resolve_remote_media(+ rows: list[dict], fmt: str, data_config: DataConfig, *, source: str+) -> list[dict]:+ """Media pass for rows that did not come from a local file.++ A remote URI or a Hub dataset has no local directory to stand in for the+ data file's, so a string media path resolves only against+ ``data.image_dir`` / ``data.audio_dir``. Rows of a text format are+ returned unchanged.+ """+ key = _media_key(fmt)+ if key is None:+ return rows+ return _resolve_media_column(rows, key, _media_dir_for(key, data_config, None), source=source)+++def _streams_need_source_tags(+ streams: list, data_config: DataConfig, train_paths: list[str]+) -> bool:+ """Whether streamed rows must carry the index of the entry they came from.++ Only a media row needs it, and only when the entries do not share one base+ directory for its key: otherwise every row resolves against that base.+ ``format: auto`` is resolved after the rows materialise, from the first+ rows of the combined stream, which are among the first rows of each+ stream; the format found can only be a media format if one of those rows+ carries its key, so the streams are tagged when one does.+ """+ keys = [+ key+ for key in _MEDIA_DIR_SETTINGS+ if len({_entry_media_dir(key, data_config, entry) for entry in train_paths}) > 1+ ]+ if not keys:+ return False+ if data_config.format != "auto":+ return _media_key(data_config.format) in keys+ return any(+ key in row+ for stream in streams+ for row in islice(stream, MAX_DETECT_ROWS)+ for key in keys+ )+++def _tag_source_index(row: dict, index: int, columns: tuple[str, ...] = ()) -> dict:+ """``IterableDataset.map`` callback: the data.train index of ``row``, plus+ None for each of ``columns`` the row lacks."""+ tag: dict = {name: None for name in columns if name not in row}+ tag[_SOURCE_INDEX_KEY] = index+ return tag+++def _tag_streams(streams: list) -> list:+ """Tag every stream's rows with its data.train index.++ A stream whose features are known keeps them, plus the int64 tag, so+ ``datasets`` does not re-infer its types from the first rows. A row gets+ each column another stream declares and it lacks, as None: combining+ untagged streams fills those in the same way.+ """+ columns = tuple(+ dict.fromkeys(+ name for stream in streams if stream.features is not None for name in stream.features+ )+ )+ tagged = []+ for index, stream in enumerate(streams):+ tag = partial(_tag_source_index, index=index, columns=columns)+ if stream.features is None:+ tagged.append(stream.map(tag))+ continue+ from datasets import Features, Value++ features = Features({**stream.features, _SOURCE_INDEX_KEY: Value("int64")})+ tagged.append(stream.map(tag, features=features))+ return tagged+++def _resolve_streamed_media(+ rows: list[dict],+ row_sources: list[int] | None,+ fmt: str,+ data_config: DataConfig,+ train_paths: list[str],+) -> list[dict]:+ """Media pass of the streaming interleave path: each row against its own entry.++ ``row_sources[i]`` is the data.train index ``rows[i]`` was streamed from.+ A local entry's default directory is its file's parent, as on the eager+ path; a remote entry has none. Each entry is resolved and warned about+ on its own, like the eager path's per-file warnings, and the rows keep+ their stream order. ``row_sources`` is None when the streams were not+ tagged: every entry then has the same base for this format's key.+ """+ key = _media_key(fmt)+ if key is None:+ return rows+ if row_sources is None:+ names = ", ".join(repr(entry) for entry in train_paths)+ return _resolve_media_column(+ rows,+ key,+ _entry_media_dir(key, data_config, train_paths[0]),+ source=f"data.train entries {names}",+ plural=True,+ )+ positions: dict[int, list[int]] = {}+ for position, source_index in enumerate(row_sources):+ positions.setdefault(source_index, []).append(position)+ resolved: list[dict | None] = list(rows)+ for source_index in sorted(positions):+ entry = train_paths[source_index]+ media_dir = _entry_media_dir(key, data_config, entry)+ group = positions[source_index]+ entries, missing, outside = _resolve_media_entries(+ [rows[position] for position in group],+ key,+ media_dir,+ source=f"data.train[{source_index}] {entry!r}",)- return valid+ _warn_media_skips(key, missing, outside, media_dir)+ for position, entry_row in zip(group, entries):+ resolved[position] = entry_row+ return [row for row in resolved if row is not None]def _looks_like_remote_uri(value: str) -> bool:@@ -1087,6 +1341,10 @@ def _load_remote_dataset(Streaming knobs (``data_config.streaming`` + ``buffer_size`` + ``shards``)are honoured via :func:`datasets.load_dataset` when present; otherwisethe file is streamed as JSONL through :func:`fsspec.open`.++ Image / audio paths resolve against ``data.image_dir`` /+ ``data.audio_dir`` (:func:`_resolve_remote_media`): a remote object has+ no local directory of its own."""from soup_cli.utils.data_pipeline import (required_remote_package,@@ -1177,6 +1435,9 @@ def _load_remote_dataset(fmt,preserve_source_columns=preserve_source_columns,)+ formatted = _resolve_remote_media(+ formatted, fmt, data_config, source=f"Remote dataset {canonical!r}"+ )return _finalize(formatted,@@ -1221,6 +1482,10 @@ def _load_one_hub_dataset(path below reuses this rather than re-deriving it. _load_hf_dataset'sown single-name behaviour is left byte-identical by construction: itnow just calls this and forwards straight to _finalize, same as before.++ Image / audio paths in both splits resolve against ``data.image_dir`` /+ ``data.audio_dir`` (:func:`_resolve_remote_media`): a Hub dataset has+ no local directory of its own."""try:from datasets import load_dataset as hf_load@@ -1246,6 +1511,9 @@ def _load_one_hub_dataset(fmt,preserve_source_columns=preserve_source_columns,)+ formatted = _resolve_remote_media(+ formatted, fmt, data_config, source=f"Hub dataset {name!r}"+ )if "validation" in ds:val_data = _rows_from_hub_split(@@ -1256,6 +1524,9 @@ def _load_one_hub_dataset(fmt,preserve_source_columns=preserve_source_columns,)+ val_formatted = _resolve_remote_media(+ val_formatted, fmt, data_config, source=f"Hub dataset {name!r}"+ )return formatted, val_formattedreturn formatted, Nonediff --git a/src/soup_cli/trainer/sft.py b/src/soup_cli/trainer/sft.pyindex bd604452..a03595f2 100644--- a/src/soup_cli/trainer/sft.py+++ b/src/soup_cli/trainer/sft.py@@ -1996,6 +1996,8 @@ class SFTTrainerWrapper(StreamingSetupMixin):"""Keep messages + PIL images raw for processor-aware collation."""from datasets import Dataset+ from soup_cli.utils.paths import require_regular_file+def load_and_format_vision(example):from PIL import Image as PILImage@@ -2003,6 +2005,10 @@ class SFTTrainerWrapper(StreamingSetupMixin):image = Noneif image_path:try:+ # Open a file name only when it is a regular file: a FIFO+ # or a device would stall the reader.+ if isinstance(image_path, (str, bytes, os.PathLike)):+ require_regular_file(os.fsdecode(image_path))image = PILImage.open(image_path).convert("RGB")except (FileNotFoundError, OSError):console.print(@@ -2121,6 +2127,8 @@ class SFTTrainerWrapper(StreamingSetupMixin):"""Prepare dataset for audio fine-tuning with audio loading."""from datasets import Dataset+ from soup_cli.utils.paths import require_regular_file+try:import librosa # noqa: F401except ImportError:@@ -2137,6 +2145,9 @@ class SFTTrainerWrapper(StreamingSetupMixin):sampling_rate = 16000if audio_path:try:+ # Same rule as the vision path: only a regular file is read.+ if isinstance(audio_path, (str, bytes, os.PathLike)):+ require_regular_file(os.fsdecode(audio_path))audio_array, sampling_rate = librosa.load(audio_path, sr=16000, mono=True,)diff --git a/src/soup_cli/utils/paths.py b/src/soup_cli/utils/paths.pyindex 1a92ecbf..8ae2519c 100644--- a/src/soup_cli/utils/paths.py+++ b/src/soup_cli/utils/paths.py@@ -13,6 +13,7 @@ in a single module guarantees a single behaviour across the CLI.from __future__ import annotationsimport errno+import ntpathimport osimport statimport tempfile@@ -41,6 +42,90 @@ def is_under_cwd(path: Union[str, Path]) -> bool:return is_under(path, Path.cwd())+# DOS device names. Windows opens the device whatever the directory, extension+# or trailing spaces: "clips/nul.png" and "CON .wav" both name one.+_DOS_DEVICE_NAMES = frozenset(+ {"CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$"}+ | {+ f"{port}{digit}"+ for port in ("COM", "LPT")+ for digit in "123456789" + chr(0xB9) + chr(0xB2) + chr(0xB3)+ }+)+++def _names_dos_device(value: str) -> bool:+ """Whether any component of ``value`` is a DOS device name."""+ for part in value.replace("\\", "/").split("/"):+ stem = part.partition(".")[0].partition(":")[0].rstrip(" ")+ if stem.upper() in _DOS_DEVICE_NAMES:+ return True+ return False+++def is_network_or_device_path(+ value: str, *, dos_device_names: bool = os.name == "nt"+) -> bool:+ """Whether ``value`` names a network share or a device, not a local file.++ True for two leading separators in any mix of ``\\`` and ``/`` -- a UNC+ share (``\\\\host\\share``, ``//host/share``) and the ``\\\\?\\``+ extended-length and ``\\\\.\\`` device prefixes -- and for the ``\\??\\``+ object-manager prefix. ``pathlib`` and ``os.path.realpath`` collapse ``.``+ and ``..`` segments first, so the value is tested both as written and in+ its normalised form. With ``dos_device_names`` (the default on Windows), a+ component naming a DOS device (``NUL``, ``CON``, ``COM1``, ``LPT1``, ...)+ counts too.++ A pure string test: it never touches the filesystem, and for the same+ arguments it gives the same answer on every platform.+ """+ for text in (value, ntpath.normpath(value)):+ head = text[:4].replace("/", "\\")+ if head.startswith("\\\\") or head == "\\??\\":+ return True+ if dos_device_names and _names_dos_device(text):+ return True+ return False+++def is_device_namespace_path(value: str) -> bool:+ """Whether ``value`` starts with the ``\\\\.\\`` device or ``\\??\\``+ object-manager prefix, written with either separator, as is or once+ normalised. A pure string test.++ Narrower than :func:`is_network_or_device_path`: a UNC or extended-length+ (``\\\\?\\``) path is not matched, because ``os.path.realpath`` returns one+ for a directory on a mapped drive.+ """+ for text in (value, ntpath.normpath(value)):+ if text[:4].replace("/", "\\") in ("\\\\.\\", "\\??\\"):+ return True+ return False+++def require_regular_file(path: str) -> str:+ """Return ``path`` when it is an absolute path to a regular file.++ Raises :exc:`OSError` otherwise, without opening anything: for a NUL byte,+ a device or object-manager path (:func:`is_device_namespace_path`), a+ relative path, or anything ``os.stat`` reports as other than a regular+ file (a directory, a FIFO, a device). A missing file raises+ :exc:`FileNotFoundError` from ``os.stat``. A UNC or extended-length path+ is accepted: the loader stores one for a media directory on a mapped+ drive, and it has already skipped every row that names one itself.++ For readers that would block or never finish on a FIFO or a device. This+ is a check made before the open, not a guard of the open: a path that+ changes in between is not caught.+ """+ if "\x00" in path or is_device_namespace_path(path) or not Path(path).is_absolute():+ raise OSError(errno.EINVAL, "not an absolute local file path", path)+ if not stat.S_ISREG(os.stat(path).st_mode):+ raise OSError(errno.EINVAL, "not a regular file", path)+ return path++def enforce_under_cwd_and_no_symlink(path: str, field: str) -> str:"""Apply cwd containment + ``os.lstat + S_ISLNK`` rejection (TOCTOU defence).diff --git a/src/soup_cli/utils/tts_codec.py b/src/soup_cli/utils/tts_codec.pyindex b4b0f867..02ec8350 100644--- a/src/soup_cli/utils/tts_codec.py+++ b/src/soup_cli/utils/tts_codec.py@@ -44,6 +44,7 @@ import osimport statfrom typing import Any, Callable, Optional+from soup_cli.utils.paths import is_device_namespace_pathfrom soup_cli.utils.tts import validate_tts_family# SNAC checkpoint for the Orpheus family (24 kHz, 3 codebooks).@@ -156,19 +157,29 @@ def load_audio_mono(path: str, *, target_sr: int = SNAC_SAMPLE_RATE):Off-rate audio is resampled with basic linear interpolation — adequatefor codec encoding of speech; operators wanting studio-grade resamplingshould resample offline. Returns a 1-D ``np.float32`` array.++ Only a regular file is read: a directory, a FIFO or a device raises+ ``ValueError`` before ``soundfile`` sees it. The check is made before+ ``soundfile`` opens the path, so a path replaced in between is not caught."""if not isinstance(path, str) or not path:raise ValueError("audio path must be a non-empty string")if "\x00" in path:raise ValueError("audio path must not contain null bytes")+ if is_device_namespace_path(path):+ raise ValueError("audio path must not be a device path")if not os.path.exists(path):raise FileNotFoundError(f"audio file not found: {os.path.basename(path)!r}")# Symlink rejection — defence-in-depth; the loader already containment-# checks rows under data.audio_dir (v0.17.0 policy).- if stat.S_ISLNK(os.lstat(path).st_mode):+ mode = os.lstat(path).st_mode+ if stat.S_ISLNK(mode):raise ValueError("audio path must not be a symlink")+ # A FIFO would block soundfile, and a device would never end.+ if not stat.S_ISREG(mode):+ raise ValueError("audio path must be a regular file")# Byte-size cap before any read — defends against a runaway file.if os.path.getsize(path) > _MAX_AUDIO_BYTES:raise ValueError(diff --git a/tests/test_loader_media_paths_parity.py b/tests/test_loader_media_paths_parity.pynew file mode 100644index 00000000..b54db939--- /dev/null+++ b/tests/test_loader_media_paths_parity.py@@ -0,0 +1,1562 @@+"""Image and audio paths resolve the same way on every load path (#1599).++Only three loaders used to resolve the ``image`` / ``audio`` value of a vision+or audio row: the single local file, the eager per-file interleave and the+replay file. The streaming interleave, the remote URI loader and the Hub loader+left it as written, so a relative path was later opened against the working+directory instead of the data directory, and ``data.image_dir`` /+``data.audio_dir`` were ignored on those paths.++Every load path is driven here through the public ``load_dataset``, with+``datasets`` and ``fsspec`` replaced by in-process fakes, and must give the same+resolved paths and the same "rows skipped" warnings. One class repeats the+streaming interleave with the real ``datasets`` library on local files. A remote+URI or a Hub dataset has no data directory of its own, so a string path there+needs the setting, and the error names it. On the trainer side, only a regular+file is opened.++An autouse guard fails any test in which a network-share or device form, or a+value holding a NUL byte, reaches ``os.path.realpath``: those values must be+refused before any filesystem call. The guard also keeps the file offline+whatever the code under test does.+"""++from __future__ import annotations++import errno+import io+import json+import os+import re+import stat+import sys+import types+from pathlib import Path++import pytest+from rich.console import Console+from typer.testing import CliRunner++import soup_cli.data.loader as loader+from soup_cli.config.schema import DataConfig+from soup_cli.data.loader import load_dataset+from soup_cli.utils.paths import (+ is_device_namespace_path,+ is_network_or_device_path,+ require_regular_file,+)+from tests.conftest import strip_ansi+++def _plain(text: str) -> str:+ """ANSI-stripped, whitespace-collapsed console output, safe to substring-match."""+ return " ".join(strip_ansi(text).split())+++# Every network or device spelling carries "soup-sentinel", which the realpath+# guard below looks for.+NETWORK_FORMS = [+ r"\\soup-sentinel.invalid\share\x.bin",+ "//soup-sentinel.invalid/share/x.bin",+ r"\/soup-sentinel.invalid/share/x.bin",+ r"/\soup-sentinel.invalid\share\x.bin",+ r"\\?\UNC\soup-sentinel.invalid\share\x.bin",+ r"\\.\pipe\soup-sentinel",+ r"\??\UNC\soup-sentinel.invalid\share\x.bin",+ "/??/UNC/soup-sentinel.invalid/share/x.bin",+ # The same prefix once "." and ".." segments are collapsed, which pathlib+ # and os.path.realpath do before they look at the filesystem.+ r"\.\??\UNC\soup-sentinel.invalid\share\x.bin",+ "/./??/UNC/soup-sentinel.invalid/share/x.bin",+ r"\x\..\??\UNC\soup-sentinel.invalid\share\x.bin",+]++# The forms the trainer-side check refuses: device and object-manager paths.+# A UNC or extended-length path is not among them, because the loader's own+# resolve() returns one for a mapped drive.+DEVICE_NAMESPACE_FORMS = [+ r"\\.\pipe\soup-sentinel",+ "//./pipe/soup-sentinel",+ r"\??\UNC\soup-sentinel.invalid\share\x.bin",+ "/??/UNC/soup-sentinel.invalid/share/x.bin",+ r"\.\??\UNC\soup-sentinel.invalid\share\x.bin",+ r"\x\..\??\UNC\soup-sentinel.invalid\share\x.bin",+]++_KEY = {"llava": "image", "audio": "audio", "asr": "audio"}+_SETTING = {"llava": "image_dir", "audio": "audio_dir", "asr": "audio_dir"}+_FORMATS = ["llava", "audio", "asr"]+_PATH_KINDS = [+ "single_file",+ "eager_interleave",+ "streaming_interleave",+ "remote",+ "remote_streaming",+ "hub",+ "hub_streaming",+ "hub_interleave",+]+_REMOTE_KINDS = ["remote", "remote_streaming", "hub", "hub_streaming", "hub_interleave"]+_REMOTE_URI = "s3://soup-bucket/rows.jsonl"+_HUB_NAME = "org/media-set"+_TAG_KEY = "__soup_source_index__" # loader._SOURCE_INDEX_KEY, spelled out++[email protected](autouse=True)+def _guard_realpath(monkeypatch):+ real_realpath = os.path.realpath++ def guarded(path, *args, **kwargs):+ text = os.fsdecode(path)+ if "soup-sentinel" in text or "\x00" in text:+ raise AssertionError(f"os.path.realpath reached {text!r}")+ return real_realpath(path, *args, **kwargs)++ monkeypatch.setattr(os.path, "realpath", guarded)+++def loader_output(monkeypatch) -> io.StringIO:+ out = io.StringIO()+ monkeypatch.setattr(loader, "console", Console(file=out, width=400))+ return out+++# ---------------------------------------------------------------------------+# Rows, files and fakes+# ---------------------------------------------------------------------------+++def _row(fmt: str, media, tag: str) -> dict:+ """One row of ``fmt`` whose media value is ``media``; ``tag`` identifies it."""+ if fmt == "llava":+ return {+ "image": media,+ "conversations": [+ {"from": "human", "value": "<image>\nDescribe."},+ {"from": "gpt", "value": tag},+ ],+ }+ if fmt == "audio":+ return {+ "audio": media,+ "messages": [+ {"role": "user", "content": "Transcribe."},+ {"role": "assistant", "content": tag},+ ],+ }+ return {"audio": media, "text": tag}+++def _tag_of(row: dict) -> str:+ if "messages" in row:+ return row["messages"][-1]["content"]+ return row["text"]+++def _layout(tmp_path: Path) -> dict[str, Path]:+ """``data/`` (the data files), ``media_root/`` (a configured media dir) and+ ``outside/``, siblings under ``tmp_path``; both base dirs hold ``clips/ok.bin``."""+ dirs = {+ "data": tmp_path / "data",+ "media": tmp_path / "media_root",+ "outside": tmp_path / "outside",+ }+ for base in (dirs["data"], dirs["media"]):+ (base / "clips").mkdir(parents=True)+ (base / "clips" / "ok.bin").write_bytes(b"x")+ dirs["outside"].mkdir()+ (dirs["outside"] / "secret.bin").write_bytes(b"x")+ return dirs+++def _rows(fmt: str, base: Path, outside: Path) -> list[dict]:+ """Two rows that resolve under ``base`` and two that lie outside it (plus,+ for llava, one with an empty path; the audio converters drop that shape).++ Network and device spellings have tests of their own below, so the local+ load paths here behave exactly as they do on ``main`` and act as controls.+ """+ rows = [+ _row(fmt, "clips/ok.bin", "kept-relative"),+ _row(fmt, str(base / "clips" / "ok.bin"), "kept-absolute"),+ _row(fmt, "../outside/secret.bin", "outside-relative"),+ _row(fmt, str(outside / "secret.bin"), "outside-absolute"),+ ]+ if fmt == "llava":+ rows.append(_row(fmt, "", "empty"))+ return rows+++def _resolved(base: Path, relative: str = "clips/ok.bin") -> str:+ return str((base / relative).resolve())+++def _write_jsonl(path: Path, rows: list[dict]) -> Path:+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text("".join(json.dumps(row) + "\n" for row in rows), encoding="utf-8")+ return path+++def _read_jsonl(path: Path) -> list[dict]:+ text = path.read_text(encoding="utf-8")+ return [json.loads(line) for line in text.splitlines() if line.strip()]+++class _FakeStream:+ """Stand-in for an HF ``IterableDataset``: rows, ``map``, ``shuffle``, no features."""++ features = None++ def __init__(self, rows, calls: list[str]):+ self._rows = [dict(row) for row in rows]+ self._calls = calls++ def shuffle(self, buffer_size=None):+ return self++ def map(self, function, features=None):+ self._calls.append("map")+ return _FakeStream([{**row, **function(row)} for row in self._rows], self._calls)++ def __iter__(self):+ return iter([dict(row) for row in self._rows])+++def _install_fake_datasets(monkeypatch, *, files=None, hub=None) -> list[str]:+ """Install a fake ``datasets`` module; returns the list it records calls in.++ ``files`` maps a ``data_files`` value to rows (a local path not listed is+ read from disk); ``hub`` maps a dataset name to ``{split: rows}``.+ """+ files = dict(files or {})+ hub = dict(hub or {})+ calls: list[str] = []++ def load_dataset(path, data_files=None, split=None, streaming=False):+ if data_files is not None:+ assert split == "train" and streaming is True+ rows = files.get(data_files)+ if rows is None:+ rows = _read_jsonl(Path(data_files))+ return _FakeStream(rows, calls)+ splits = hub[path]+ if streaming:+ return {name: _FakeStream(rows, calls) for name, rows in splits.items()}+ return {name: [dict(row) for row in rows] for name, rows in splits.items()}++ def concatenate_datasets(streams):+ return _FakeStream([row for stream in streams for row in stream], calls)++ def interleave_datasets(streams, probabilities=None, stopping_strategy="first_exhausted"):+ pools = [list(stream) for stream in streams]+ if stopping_strategy == "all_exhausted":+ rounds = max(len(pool) for pool in pools)+ else:+ rounds = min(len(pool) for pool in pools)+ mixed = [pool[turn % len(pool)] for turn in range(rounds) for pool in pools]+ return _FakeStream(mixed, calls)++ module = types.ModuleType("datasets")+ module.load_dataset = load_dataset+ module.concatenate_datasets = concatenate_datasets+ module.interleave_datasets = interleave_datasets+ monkeypatch.setitem(sys.modules, "datasets", module)+ return calls+++def _install_fake_fsspec(monkeypatch, objects: dict[str, list[dict]]) -> None:+ class _Handle:+ def __init__(self, lines):+ self._lines = lines++ def __enter__(self):+ return iter(self._lines)++ def __exit__(self, *exc_info):+ return False++ def fake_open(uri, mode="rt", encoding=None):+ return _Handle([json.dumps(row) + "\n" for row in objects[uri]])++ module = types.ModuleType("fsspec")+ module.open = fake_open+ monkeypatch.setitem(sys.modules, "fsspec", module)+++def _load(kind, fmt, rows, extra_rows, tmp_path, monkeypatch, **data_overrides) -> dict:+ """Load ``rows`` through load path ``kind``. Interleave kinds add a second+ source holding ``extra_rows``, combined with ``concat``; the local ones keep+ both files in ``data/``."""+ data_dir = tmp_path / "data"+ common = {"format": fmt, "val_split": 0.0, **data_overrides}+ if kind in ("single_file", "eager_interleave", "streaming_interleave"):+ first = _write_jsonl(data_dir / "rows.jsonl", rows)+ if kind == "single_file":+ return load_dataset(DataConfig(train=str(first), **common))+ second = _write_jsonl(data_dir / "more.jsonl", extra_rows)+ streaming = kind == "streaming_interleave"+ if streaming:+ _install_fake_datasets(monkeypatch)+ return load_dataset(+ DataConfig(+ train=[str(first), str(second)],+ interleave="concat",+ streaming=streaming,+ **common,+ )+ )+ if kind in ("remote", "remote_streaming"):+ _install_fake_fsspec(monkeypatch, {_REMOTE_URI: rows})+ _install_fake_datasets(monkeypatch, files={_REMOTE_URI: rows})+ return load_dataset(+ DataConfig(train=_REMOTE_URI, streaming=kind == "remote_streaming", **common)+ )+ if kind in ("hub", "hub_streaming"):+ _install_fake_datasets(monkeypatch, hub={_HUB_NAME: {"train": rows}})+ return load_dataset(+ DataConfig(train=_HUB_NAME, streaming=kind == "hub_streaming", **common)+ )+ assert kind == "hub_interleave"+ _install_fake_datasets(+ monkeypatch,+ hub={_HUB_NAME: {"train": rows}, "org/more": {"train": extra_rows}},+ )+ return load_dataset(+ DataConfig(train=[_HUB_NAME, "org/more"], interleave="concat", **common)+ )+++def _skip_lines(key: str, count: int, base: Path | str) -> str:+ """The "outside" warning the loader prints for ``count`` rows of ``key``."""+ if key == "image":+ return f"Warning: {count} rows skipped (image path outside {base})"+ return f"Warning: {count} rows skipped (audio path traversal blocked)"+++def _assert_resolved_like_local(result: dict, fmt: str, base: Path, output: str) -> None:+ """The outcome every load path must share for ``_rows(fmt, base, ...)``."""+ kept = [row for row in result["train"] if _tag_of(row) != "second-source"]+ assert [_tag_of(row) for row in kept] == ["kept-relative", "kept-absolute"]+ assert [row[_KEY[fmt]] for row in kept] == [_resolved(base)] * 2++ plain = _plain(output)+ if fmt == "llava":+ assert plain.count("Warning: 1 rows skipped (missing image path)") == 1, plain+ assert plain.count(_skip_lines(_KEY[fmt], 2, base)) == 1, plain+++# ---------------------------------------------------------------------------+# Parity across load paths+# ---------------------------------------------------------------------------++[email protected]("fmt", _FORMATS)[email protected]("kind", _PATH_KINDS)+def test_every_load_path_resolves_against_the_configured_media_dir(+ kind, fmt, tmp_path, monkeypatch, loader_output+):+ dirs = _layout(tmp_path)+ media_root = dirs["media"]+ result = _load(+ kind,+ fmt,+ _rows(fmt, media_root, dirs["outside"]),+ [_row(fmt, "clips/ok.bin", "second-source")],+ tmp_path,+ monkeypatch,+ **{_SETTING[fmt]: str(media_root)},+ )++ _assert_resolved_like_local(result, fmt, media_root, loader_output.getvalue())+ if "interleave" in kind:+ assert _tag_of(result["train"][-1]) == "second-source"+ assert result["train"][-1][_KEY[fmt]] == _resolved(media_root)++[email protected]("fmt", _FORMATS)[email protected]("kind", ["single_file", "eager_interleave", "streaming_interleave"])+def test_local_paths_default_to_the_data_files_directory(+ kind, fmt, tmp_path, monkeypatch, loader_output+):+ dirs = _layout(tmp_path)+ result = _load(+ kind,+ fmt,+ _rows(fmt, dirs["data"], dirs["outside"]),+ [_row(fmt, "clips/ok.bin", "second-source")],+ tmp_path,+ monkeypatch,+ )++ _assert_resolved_like_local(result, fmt, dirs["data"], loader_output.getvalue())++[email protected]("fmt", _FORMATS)[email protected]("kind", ["streaming_interleave", *_REMOTE_KINDS])+def test_format_auto_resolves_like_an_explicit_format(+ kind, fmt, tmp_path, monkeypatch, loader_output+):+ # format: auto is the default. The media pass must use the detected format,+ # not the configured "auto", on every path that detects after loading.+ dirs = _layout(tmp_path)+ result = _load(+ kind,+ "auto",+ _rows(fmt, dirs["media"], dirs["outside"]),+ [_row(fmt, "clips/ok.bin", "second-source")],+ tmp_path,+ monkeypatch,+ **{_SETTING[fmt]: str(dirs["media"])},+ )++ _assert_resolved_like_local(result, fmt, dirs["media"], loader_output.getvalue())+++# ---------------------------------------------------------------------------+# Streaming interleave: each row against its own entry+# ---------------------------------------------------------------------------+++def _two_entry_dirs(tmp_path: Path, *, shared: bool = False) -> tuple[Path, Path]:+ first_dir = tmp_path / "first"+ second_dir = first_dir if shared else tmp_path / "second"+ for base in {first_dir, second_dir}:+ (base / "clips").mkdir(parents=True)+ (base / "clips" / "ok.bin").write_bytes(b"x")+ return first_dir, second_dir+++def _streaming_config(train, interleave="concat", **overrides) -> DataConfig:+ common = {"format": "llava", "val_split": 0.0, **overrides}+ return DataConfig(train=[str(path) for path in train], interleave=interleave,+ streaming=True, **common)++[email protected]("fmt", ["llava", "asr", "auto"])+def test_streamed_rows_resolve_against_their_own_entry(+ fmt, tmp_path, monkeypatch, loader_output+):+ shape = "asr" if fmt == "asr" else "llava"+ first_dir, second_dir = _two_entry_dirs(tmp_path)+ # The first row converts to nothing, so formatted rows sit one place+ # before their raw rows; each must still find its own entry.+ dropped = {"image": "clips/ok.bin"} if shape == "llava" else {"audio": "clips/ok.bin"}+ first = _write_jsonl(+ first_dir / "rows.jsonl", [dropped, _row(shape, "clips/ok.bin", "from-first")]+ )+ second = _write_jsonl(+ second_dir / "rows.jsonl",+ [+ _row(shape, "clips/ok.bin", "from-second"),+ _row(shape, "../first/clips/ok.bin", "leaves-second"),+ ],+ )+ calls = _install_fake_datasets(monkeypatch)++ result = load_dataset(_streaming_config([first, second], format=fmt))++ assert {_tag_of(row): row[_KEY[shape]] for row in result["train"]} == {+ "from-first": _resolved(first_dir),+ "from-second": _resolved(second_dir),+ }+ assert calls.count("map") == 2+ assert _plain(loader_output.getvalue()).count(+ _skip_lines(_KEY[shape], 1, second_dir)+ ) == 1+++ "first_rows",+ [["note", "from-first"], ["note"]],+ ids=["first-row-has-no-format", "first-entry-has-no-media"],+)+def test_format_auto_tags_when_any_first_row_carries_the_media_key(+ first_rows, tmp_path, monkeypatch+):+ # A row that matches no format is skipped by detection and dropped by the+ # converter, so the detected format comes from the rows after it, in any+ # entry: the check must read past it, and look at every entry.+ first_dir, second_dir = _two_entry_dirs(tmp_path)+ rows = {+ "note": {"note": "no format"},+ "from-first": _row("llava", "clips/ok.bin", "from-first"),+ }+ first = _write_jsonl(first_dir / "rows.jsonl", [rows[name] for name in first_rows])+ second = _write_jsonl(+ second_dir / "rows.jsonl",+ [{"note": "no format"}, _row("llava", "clips/ok.bin", "from-second")],+ )+ _install_fake_datasets(monkeypatch)++ result = load_dataset(_streaming_config([first, second], format="auto"))++ expected = {"from-first": _resolved(first_dir), "from-second": _resolved(second_dir)}+ assert {_tag_of(row): row["image"] for row in result["train"]} == {+ name: expected[name] for name in [*first_rows, "from-second"] if name != "note"+ }++[email protected]("fmt", ["llava", "asr", "auto"])+def test_streamed_entries_sharing_a_directory_are_not_tagged(+ fmt, tmp_path, monkeypatch, loader_output+):+ shape = "asr" if fmt == "asr" else "llava"+ first_dir, _ = _two_entry_dirs(tmp_path, shared=True)+ first = _write_jsonl(first_dir / "a.jsonl", [_row(shape, "clips/ok.bin", "a")])+ second = _write_jsonl(+ first_dir / "b.jsonl",+ [_row(shape, "clips/ok.bin", "b"), _row(shape, "../x.bin", "b-outside")],+ )+ calls = _install_fake_datasets(monkeypatch)++ result = load_dataset(_streaming_config([first, second], format=fmt))++ assert [(_tag_of(row), row[_KEY[shape]]) for row in result["train"]] == [+ ("a", _resolved(first_dir)),+ ("b", _resolved(first_dir)),+ ]+ assert "map" not in calls+ assert _plain(loader_output.getvalue()).count(+ _skip_lines(_KEY[shape], 1, first_dir)+ ) == 1++[email protected]("layout", ["one_directory", "two_directories"])+ "interleave", ["concat", "under", "over", {"strategy": "probs", "probs": [0.5, 0.5]}]+)+def test_every_streaming_strategy_resolves_each_row_against_its_entry(+ interleave, layout, tmp_path, monkeypatch, loader_output+):+ first_dir, second_dir = _two_entry_dirs(tmp_path, shared=layout == "one_directory")+ first = _write_jsonl(+ first_dir / "a.jsonl",+ [_row("llava", "clips/ok.bin", "a-kept"), _row("llava", "../x.bin", "a-outside")],+ )+ second = _write_jsonl(+ second_dir / "b.jsonl",+ [_row("llava", "clips/ok.bin", "b-kept"), _row("llava", "../x.bin", "b-outside")],+ )+ calls = _install_fake_datasets(monkeypatch)++ result = load_dataset(_streaming_config([first, second], interleave=interleave))++ assert sorted((_tag_of(row), row["image"]) for row in result["train"]) == [+ ("a-kept", _resolved(first_dir)),+ ("b-kept", _resolved(second_dir)),+ ]+ plain = _plain(loader_output.getvalue())+ if layout == "one_directory":+ assert plain.count(_skip_lines("image", 2, first_dir)) == 1, plain+ assert "map" not in calls+ else:+ assert plain.count(_skip_lines("image", 1, first_dir)) == 1, plain+ assert plain.count(_skip_lines("image", 1, second_dir)) == 1, plain+ assert calls.count("map") == 2+++def test_streaming_over_with_a_validation_split_resolves_both_sides(tmp_path, monkeypatch):+ first_dir, second_dir = _two_entry_dirs(tmp_path)+ first = _write_jsonl(+ first_dir / "a.jsonl",+ [_row("llava", "clips/ok.bin", f"a{index}") for index in range(3)],+ )+ second = _write_jsonl(second_dir / "b.jsonl", [_row("llava", "clips/ok.bin", "b0")])+ _install_fake_datasets(monkeypatch)++ result = load_dataset(_streaming_config([first, second], interleave="over", val_split=0.5))++ expected = {"a": _resolved(first_dir), "b": _resolved(second_dir)}+ assert result["val"], result+ for row in [*result["train"], *result["val"]]:+ assert row["image"] == expected[_tag_of(row)[0]], row+++def test_streaming_auto_format_does_not_leak_the_source_tag(tmp_path, monkeypatch):+ first_dir, second_dir = _two_entry_dirs(tmp_path)+ first = _write_jsonl(first_dir / "a.jsonl", [_row("llava", "clips/ok.bin", "a")])+ second = _write_jsonl(second_dir / "b.jsonl", [_row("llava", "clips/ok.bin", "b")])+ calls = _install_fake_datasets(monkeypatch)++ result = load_dataset(+ _streaming_config([first, second], format="auto"), preserve_source_columns=True+ )++ assert [(_tag_of(row), row["image"]) for row in result["train"]] == [+ ("a", _resolved(first_dir)),+ ("b", _resolved(second_dir)),+ ]+ assert calls.count("map") == 2+ assert all(_TAG_KEY not in row for row in result["train"])+++def test_a_row_cannot_name_its_own_entry(tmp_path, monkeypatch):+ first_dir, second_dir = _two_entry_dirs(tmp_path)+ first = _write_jsonl(+ first_dir / "a.jsonl",+ [{**_row("llava", "clips/ok.bin", "claims-second"), _TAG_KEY: 1}],+ )+ second = _write_jsonl(second_dir / "b.jsonl", [_row("llava", "clips/ok.bin", "b")])+ _install_fake_datasets(monkeypatch)++ result = load_dataset(_streaming_config([first, second]))++ assert {_tag_of(row): row["image"] for row in result["train"]} == {+ "claims-second": _resolved(first_dir),+ "b": _resolved(second_dir),+ }++[email protected]("fmt", ["plaintext", "auto"])+def test_streaming_text_entries_are_not_tagged(fmt, tmp_path, monkeypatch):+ first_dir, second_dir = _two_entry_dirs(tmp_path)+ first = _write_jsonl(first_dir / "a.jsonl", [{"text": "alpha"}])+ second = _write_jsonl(second_dir / "b.jsonl", [{"text": "beta"}])+ calls = _install_fake_datasets(monkeypatch)++ result = load_dataset(_streaming_config([first, second], format=fmt))++ assert len(result["train"]) == 2+ assert "map" not in calls+++def test_streaming_remote_entry_needs_the_media_dir(tmp_path, monkeypatch):+ local = _write_jsonl(tmp_path / "data" / "rows.jsonl", [_row("llava", "a.png", "local")])+ remote = "s3://soup-bucket/more.jsonl"+ _install_fake_datasets(monkeypatch, files={remote: [_row("llava", "b.png", "remote")]})++ with pytest.raises(ValueError) as excinfo:+ load_dataset(_streaming_config([local, remote]))++ message = str(excinfo.value)+ assert f"data.train[1] {remote!r} is not a local file" in message+ assert "Set data.image_dir to the local directory that holds the image files" in message+++def test_streaming_remote_entries_without_a_media_dir_name_every_entry(monkeypatch):+ first = "s3://soup-bucket/a.jsonl"+ second = "s3://soup-bucket/b.jsonl"+ calls = _install_fake_datasets(+ monkeypatch,+ files={first: [_row("llava", "a.png", "a")], second: [_row("llava", "b.png", "b")]},+ )++ with pytest.raises(ValueError) as excinfo:+ load_dataset(_streaming_config([first, second]))++ assert str(excinfo.value) == (+ f"data.train entries {first!r}, {second!r} are not local files, so their "+ "'image' paths have no directory to resolve against. Set data.image_dir to "+ "the local directory that holds the image files: relative paths resolve under "+ "it, and rows whose image is outside it are skipped."+ )+ assert "map" not in calls+++def test_streaming_remote_entries_resolve_against_the_media_dir(+ tmp_path, monkeypatch, loader_output+):+ dirs = _layout(tmp_path)+ first = "s3://soup-bucket/a.jsonl"+ second = "s3://soup-bucket/b.jsonl"+ calls = _install_fake_datasets(+ monkeypatch,+ files={+ first: [_row("llava", "clips/ok.bin", "a")],+ second: [_row("llava", "../outside/secret.bin", "b")],+ },+ )++ result = load_dataset(_streaming_config([first, second], image_dir=str(dirs["media"])))++ assert [(_tag_of(row), row["image"]) for row in result["train"]] == [+ ("a", _resolved(dirs["media"]))+ ]+ assert "map" not in calls+ assert _skip_lines("image", 1, dirs["media"]) in _plain(loader_output.getvalue())+++# ---------------------------------------------------------------------------+# Streaming interleave with the real ``datasets`` library (local files only)+# ---------------------------------------------------------------------------+++def _png_bytes() -> bytes:+ pil_image = pytest.importorskip("PIL.Image")+ buffer = io.BytesIO()+ pil_image.new("RGB", (2, 2), "red").save(buffer, format="PNG")+ return buffer.getvalue()+++def _write_parquet(path: Path, rows: list[dict], image_columns=()) -> Path:+ datasets = pytest.importorskip("datasets")+ table = datasets.Dataset.from_list(rows)+ for column in image_columns:+ table = table.cast_column(column, datasets.Image())+ path.parent.mkdir(parents=True, exist_ok=True)+ table.to_parquet(str(path))+ return path+++class TestRealDatasetsStreaming:+ @pytest.fixture(autouse=True)+ def _real_datasets(self):+ pytest.importorskip("datasets")+ pytest.importorskip("pyarrow")+ pytest.importorskip("PIL")++ @pytest.fixture+ def no_map(self, monkeypatch):+ import datasets++ def refuse(self, *args, **kwargs):+ raise AssertionError("IterableDataset.map was called")++ monkeypatch.setattr(datasets.IterableDataset, "map", refuse)++ def test_a_jsonl_and_an_image_parquet_in_different_directories(self, tmp_path):+ first_dir, second_dir = _two_entry_dirs(tmp_path)+ first = _write_jsonl(+ first_dir / "rows.jsonl",+ [_row("llava", "clips/ok.bin", "a0"), _row("llava", "clips/ok.bin", "a1")],+ )+ thumb = {"bytes": _png_bytes(), "path": None}+ second = _write_parquet(+ second_dir / "rows.parquet",+ [+ {**_row("llava", "clips/ok.bin", "b0"), "thumb": thumb},+ {**_row("llava", "../x.bin", "b-outside"), "thumb": thumb},+ ],+ image_columns=["thumb"],+ )++ result = load_dataset(+ _streaming_config([first, second], format="auto"), preserve_source_columns=True+ )++ rows = result["train"]+ assert [(_tag_of(row), row["image"]) for row in rows] == [+ ("a0", _resolved(first_dir)),+ ("a1", _resolved(first_dir)),+ ("b0", _resolved(second_dir)),+ ]+ assert all(_TAG_KEY not in row for row in rows)+ # The JSONL rows carry the parquet's extra column as None, as they do+ # when the two streams are combined without a tag.+ assert [("thumb" in row, row.get("thumb") is None) for row in rows] == [+ (True, True),+ (True, True),+ (True, False),+ ]++ def test_entries_sharing_a_directory_are_not_tagged(self, tmp_path, no_map):+ first_dir, _ = _two_entry_dirs(tmp_path, shared=True)+ first = _write_jsonl(first_dir / "a.jsonl", [_row("llava", "clips/ok.bin", "a")])+ thumb = {"bytes": _png_bytes(), "path": None}+ second = _write_parquet(+ first_dir / "b.parquet",+ [{**_row("llava", "clips/ok.bin", "b"), "thumb": thumb}],+ image_columns=["thumb"],+ )++ result = load_dataset(_streaming_config([first, second], format="auto"))++ assert [(_tag_of(row), row["image"]) for row in result["train"]] == [+ ("a", _resolved(first_dir)),+ ("b", _resolved(first_dir)),+ ]++ def test_text_entries_in_different_directories_are_not_tagged(self, tmp_path, no_map):+ first = _write_parquet(tmp_path / "a" / "rows.parquet", [{"text": "alpha"}])+ second = _write_parquet(tmp_path / "b" / "rows.parquet", [{"text": "beta"}])++ result = load_dataset(_streaming_config([first, second], format="auto"))++ assert [row["text"] for row in result["train"]] == ["alpha", "beta"]++ def test_decoded_images_from_two_directories_pass_through(self, tmp_path):+ pil_image = pytest.importorskip("PIL.Image")+ image = {"bytes": _png_bytes(), "path": None}+ first = _write_parquet(+ tmp_path / "a" / "rows.parquet", [_row("llava", image, "a")], image_columns=["image"]+ )+ second = _write_parquet(+ tmp_path / "b" / "rows.parquet", [_row("llava", image, "b")], image_columns=["image"]+ )++ result = load_dataset(_streaming_config([first, second]))++ assert [_tag_of(row) for row in result["train"]] == ["a", "b"]+ assert all(isinstance(row["image"], pil_image.Image) for row in result["train"])+++# ---------------------------------------------------------------------------+# Remote URI and Hub dataset: no data directory of their own+# ---------------------------------------------------------------------------++[email protected]("absolute", [False, True])+ ("fmt", "setting"),+ [("llava", "data.image_dir"), ("audio", "data.audio_dir"), ("asr", "data.audio_dir")],+)[email protected]("kind", _REMOTE_KINDS)+def test_remote_and_hub_paths_need_the_media_dir(+ kind, fmt, setting, absolute, tmp_path, monkeypatch+):+ media = str(tmp_path / "clips" / "ok.bin") if absolute else "clips/ok.bin"++ with pytest.raises(ValueError) as excinfo:+ _load(+ kind,+ fmt,+ [_row(fmt, media, "path-row")],+ [_row(fmt, media, "second-source")],+ tmp_path,+ monkeypatch,+ )++ message = str(excinfo.value)+ assert f"Set {setting} to the local directory that holds the" in message+ source = _REMOTE_URI if kind.startswith("remote") else _HUB_NAME+ assert f"{source!r} is not a local file" in message+++def test_the_media_dir_message_names_the_source_and_the_setting(tmp_path, monkeypatch):+ with pytest.raises(ValueError) as excinfo:+ _load("hub", "llava", [_row("llava", "clips/ok.bin", "row")], [], tmp_path, monkeypatch)++ assert str(excinfo.value) == (+ "Hub dataset 'org/media-set' is not a local file, so its 'image' paths have no "+ "directory to resolve against. Set data.image_dir to the local directory that "+ "holds the image files: relative paths resolve under it, and rows whose image "+ "is outside it are skipped."+ )+++_DRY_RUN_CONFIG = (+ "base: hf-internal-testing/tiny-random-LlamaForCausalLM\ntask: sft\nmodality: vision\n"+ "data:\n train: org/media-set\n format: llava\n val_split: 0.0\n{extra}output: ./out\n"+)+++def test_dry_run_stops_on_a_hub_dataset_without_the_media_dir(tmp_path, monkeypatch):+ from soup_cli.cli import app+ from soup_cli.utils import errors++ monkeypatch.chdir(tmp_path)+ _layout(tmp_path)+ _install_fake_datasets(+ monkeypatch, hub={_HUB_NAME: {"train": [_row("llava", "clips/ok.bin", "row")]}}+ )+ Path("soup.yaml").write_text(_DRY_RUN_CONFIG.format(extra=""), encoding="utf-8")++ result = CliRunner().invoke(app, ["train", "--config", "soup.yaml", "--dry-run"])++ assert result.exit_code == 1, (result.output, repr(result.exception))+ assert "Data OK" not in _plain(result.output)+ assert isinstance(result.exception, ValueError), repr(result.exception)+ rendered = io.StringIO()+ monkeypatch.setattr(errors, "console", Console(file=rendered, width=400))+ errors.format_friendly_error(result.exception)+ assert (+ "Error: ValueError: Hub dataset 'org/media-set' is not a local file, so its "+ "'image' paths have no directory to resolve against. Set data.image_dir to the "+ "local directory that holds the image files"+ ) in _plain(rendered.getvalue())++ Path("soup.yaml").write_text(+ _DRY_RUN_CONFIG.format(extra=" image_dir: media_root\n"), encoding="utf-8"+ )+ result = CliRunner().invoke(app, ["train", "--config", "soup.yaml", "--dry-run"])++ assert result.exit_code == 0, (result.output, repr(result.exception))+ assert "Data OK: 1 train samples" in _plain(result.output)+++def test_hub_decoded_images_pass_through_without_a_media_dir(monkeypatch):+ decoded = object() # stands in for a PIL image decoded from an Image() feature+ rows = [{"image": decoded, "conversations": [{"from": "human", "value": "Hi"}]}]+ _install_fake_datasets(monkeypatch, hub={"org/decoded": {"train": rows}})++ result = load_dataset(DataConfig(train="org/decoded", format="llava", val_split=0.0))++ assert result["train"][0]["image"] is decoded+++def test_hub_validation_split_is_resolved_too(tmp_path, monkeypatch, loader_output):+ dirs = _layout(tmp_path)+ _install_fake_datasets(+ monkeypatch,+ hub={+ _HUB_NAME: {+ "train": [_row("llava", "clips/ok.bin", "train")],+ "validation": [+ _row("llava", "clips/ok.bin", "val"),+ _row("llava", "../outside/secret.bin", "val-outside"),+ ],+ }+ },+ )++ result = load_dataset(+ DataConfig(+ train=_HUB_NAME, format="llava", val_split=0.0, image_dir=str(dirs["media"])+ )+ )++ assert [(_tag_of(row), row["image"]) for row in result["val"]] == [+ ("val", _resolved(dirs["media"]))+ ]+ assert _skip_lines("image", 1, dirs["media"]) in _plain(loader_output.getvalue())++[email protected]("kind", ["remote", "hub"])+def test_image_dir_dot_resolves_under_the_working_directory(+ kind, tmp_path, monkeypatch, loader_output+):+ monkeypatch.chdir(tmp_path)+ _layout(tmp_path)+ rows = [+ _row("llava", "media_root/clips/ok.bin", "kept"),+ _row("llava", str(tmp_path.parent / "elsewhere.bin"), "outside-cwd"),+ ]++ result = _load(kind, "llava", rows, [], tmp_path, monkeypatch, image_dir=".")++ assert [(_tag_of(row), row["image"]) for row in result["train"]] == [+ ("kept", _resolved(tmp_path / "media_root"))+ ]+ assert _skip_lines("image", 1, ".") in _plain(loader_output.getvalue())+++# ---------------------------------------------------------------------------+# Values refused before any filesystem call+# ---------------------------------------------------------------------------++[email protected]("layout", ["absolute_dir", "relative_dir", "relative_media_dir"])[email protected]("fmt", _FORMATS)+def test_network_device_and_nul_values_are_skipped_before_realpath(+ fmt, layout, tmp_path, monkeypatch, loader_output+):+ dirs = _layout(tmp_path)+ refused = [*NETWORK_FORMS, "clips/ok\x00.bin"]+ rows = [_row(fmt, "clips/ok.bin", "kept")] + [_row(fmt, value, "refused") for value in refused]+ if layout == "absolute_dir":+ result = _load("single_file", fmt, rows, [], tmp_path, monkeypatch)+ base: Path | str = dirs["data"]+ else:+ # A relative directory keeps a rooted value rooted when the two are+ # joined, so only the pre-check stands between it and realpath.+ monkeypatch.chdir(tmp_path)+ _write_jsonl(Path("data") / "rows.jsonl", rows)+ overrides = {_SETTING[fmt]: "media_root"} if layout == "relative_media_dir" else {}+ result = load_dataset(+ DataConfig(train="data/rows.jsonl", format=fmt, val_split=0.0, **overrides)+ )+ base = "media_root" if overrides else "data"++ assert [(_tag_of(row), row[_KEY[fmt]]) for row in result["train"]] == [+ ("kept", _resolved(tmp_path / base))+ ]+ assert _skip_lines(_KEY[fmt], len(refused), base) in _plain(loader_output.getvalue())++[email protected]("key", ["image", "audio"])+ "value",+ [b"clips/ok.bin", Path("clips/ok.bin"), os.fsencode(NETWORK_FORMS[0])],+ ids=["bytes", "path-object", "bytes-network"],+)+def test_a_bytes_or_path_object_value_is_skipped_not_passed_on(+ key, value, tmp_path, loader_output+):+ dirs = _layout(tmp_path)+ validate = loader._validate_vision_images if key == "image" else loader._validate_audio_files++ rows = validate([{"messages": [], key: value}], dirs["data"])++ assert rows == []+ assert _skip_lines(key, 1, dirs["data"]) in _plain(loader_output.getvalue())+++def test_a_hub_bytes_value_is_skipped_like_a_path_outside(tmp_path, monkeypatch, loader_output):+ dirs = _layout(tmp_path)+ rows = [_row("llava", "clips/ok.bin", "kept"), _row("llava", b"clips/ok.bin", "bytes")]+ _install_fake_datasets(monkeypatch, hub={_HUB_NAME: {"train": rows}})++ result = load_dataset(+ DataConfig(train=_HUB_NAME, format="llava", val_split=0.0, image_dir=str(dirs["media"]))+ )++ assert [(_tag_of(row), row["image"]) for row in result["train"]] == [+ ("kept", _resolved(dirs["media"]))+ ]+ assert _skip_lines("image", 1, dirs["media"]) in _plain(loader_output.getvalue())+++def test_a_hub_bytes_value_without_a_media_dir_is_skipped_not_refused(+ monkeypatch, loader_output+):+ decoded = object()+ rows = [_row("llava", b"clips/ok.bin", "bytes"), _row("llava", decoded, "decoded")]+ _install_fake_datasets(monkeypatch, hub={_HUB_NAME: {"train": rows}})++ result = load_dataset(DataConfig(train=_HUB_NAME, format="llava", val_split=0.0))++ assert [row["image"] for row in result["train"]] == [decoded]+ assert "Warning: 1 rows skipped (image value is not a path string)" in _plain(+ loader_output.getvalue()+ )+++def test_a_non_string_image_value_is_kept_as_is():+ decoded = object()++ rows = loader._validate_vision_images([{"messages": [], "image": decoded}], Path("unused"))++ assert rows[0]["image"] is decoded+++_DOS_DEVICE_VALUES = ["nul", "clips/CON.png", "com1.wav", "LPT9", "aux.tar.gz", "conin$"]++[email protected](os.name != "nt", reason="DOS device names are a Windows rule")[email protected]("fmt", _FORMATS)+def test_dos_device_names_are_skipped_on_windows(fmt, tmp_path, monkeypatch, loader_output):+ dirs = _layout(tmp_path)+ looked_up: list[str] = []+ guarded = os.path.realpath++ def spy(path, *args, **kwargs):+ looked_up.append(os.path.normcase(os.fsdecode(path)))+ return guarded(path, *args, **kwargs)++ monkeypatch.setattr(os.path, "realpath", spy)+ rows = [_row(fmt, "clips/ok.bin", "kept")] + [+ _row(fmt, value, "device") for value in _DOS_DEVICE_VALUES+ ]++ result = _load("single_file", fmt, rows, [], tmp_path, monkeypatch)++ assert [_tag_of(row) for row in result["train"]] == ["kept"]+ candidates = {os.path.normcase(str(dirs["data"] / value)) for value in _DOS_DEVICE_VALUES}+ assert candidates.isdisjoint(looked_up)+ plain = _plain(loader_output.getvalue())+ assert _skip_lines(_KEY[fmt], len(_DOS_DEVICE_VALUES), dirs["data"]) in plain++[email protected](os.name == "nt", reason="on Windows these name devices")+def test_dos_device_names_are_ordinary_file_names_elsewhere(tmp_path, monkeypatch):+ dirs = _layout(tmp_path)+ rows = [_row("llava", value, value) for value in _DOS_DEVICE_VALUES]++ result = _load("single_file", "llava", rows, [], tmp_path, monkeypatch)++ assert [row["image"] for row in result["train"]] == [+ _resolved(dirs["data"], value) for value in _DOS_DEVICE_VALUES+ ]+++# ---------------------------------------------------------------------------+# The string tests behind the checks+# ---------------------------------------------------------------------------+++ ("value", "expected"),+ [+ (r"\\host\share\x.png", True),+ ("//host/share/x.png", True),+ (r"\/host/share/x.png", True),+ (r"/\host\share\x.png", True),+ (r"\\?\C:\x.png", True), # a local extended-length path is refused too+ (r"\\?\UNC\host\share\x.png", True),+ (r"\\.\pipe\name", True),+ (r"\??\C:\x.png", True),+ ("/??/C:/x.png", True),+ (r"\.\??\UNC\h\s\x.png", True),+ ("/./??/UNC/h/s/x.png", True),+ (r"\x\..\??\UNC\h\s\x.png", True),+ # The prefix as written, in any separator, when ".." collapses it away.+ ("/??/../x.png", True),+ (r"\??/../x.png", True),+ (r"\??\..\x.png", True),+ ("\\\\", True),+ ("//", True),+ ("///x", True),+ ("//tmp/data/x.png", True), # POSIX reads this as /tmp/data/x.png+ (r"C:\data\x.png", False),+ ("C:/data/x.png", False),+ ("imgs/x.png", False),+ ("/srv/data/x.png", False),+ (r"\x.png", False),+ (r"\x\..\y.png", False),+ (r"a\??x", False),+ ("\\??", False),+ ("/?", False),+ ("", False),+ ],+)+def test_network_or_device_spellings(value, expected):+ assert is_network_or_device_path(value, dos_device_names=False) is expected+ assert is_network_or_device_path(value, dos_device_names=True) is expected+++ ("value", "expected"),+ [+ ("nul", True),+ ("NUL", True),+ ("Nul.png", True),+ ("clips/con", True),+ (r"clips\aux.wav", True),+ ("com1", True),+ ("COM9.txt", True),+ ("LPT1", True),+ ("com" + chr(0xB9), True),+ ("nul.", True),+ ("nul .png", True),+ ("con:stream", True),+ ("CONIN$", True),+ ("conout$.txt", True),+ ("clips/nul/x.png", True),+ ("null.png", False),+ ("console.png", False),+ ("com10", False),+ ("com0", False),+ ("acon.png", False),+ ("com.png", False),+ ("clips/nulls/x.png", False),+ (" nul", False),+ ],+)+def test_dos_device_names_are_a_parameter_of_the_check(value, expected):+ assert is_network_or_device_path(value, dos_device_names=True) is expected+ assert is_network_or_device_path(value, dos_device_names=False) is False+++ ("value", "expected"),+ [+ *[(value, True) for value in DEVICE_NAMESPACE_FORMS],+ (r"\\.\NUL", True),+ ("/??/../x.png", True),+ (r"\??\..\x.png", True),+ (r"\\host\share\x.png", False),+ ("//host/share/x.png", False),+ (r"\\?\C:\x.png", False),+ (r"\\?\UNC\host\share\x.png", False),+ (r"C:\x.png", False),+ ("/srv/x.png", False),+ ("nul", False),+ ],+)+def test_device_namespace_spellings(value, expected):+ assert is_device_namespace_path(value) is expected+++# ---------------------------------------------------------------------------+# Trainer side: only a regular file is opened+# ---------------------------------------------------------------------------+++def _regular_stat() -> os.stat_result:+ return os.stat_result((stat.S_IFREG | 0o644, 0, 0, 1, 0, 0, 1, 0, 0, 0))+++def _spy_lookups(monkeypatch, *, result=None) -> list[str]:+ """Record ``os.stat`` / ``os.lstat`` / ``os.path.exists`` calls on sentinel paths.++ A recorded call raises FileNotFoundError, or returns ``result`` when given.+ """+ seen: list[str] = []+ real = {"stat": os.stat, "lstat": os.lstat, "exists": os.path.exists}++ def spy(name):+ def lookup(path, *args, **kwargs):+ if isinstance(path, (str, bytes, os.PathLike)):+ text = os.fsdecode(path)+ if "soup-sentinel" in text:+ seen.append(text)+ if name == "exists":+ return result is not None+ if result is not None:+ return result+ raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), text)+ return real[name](path, *args, **kwargs)++ return lookup++ monkeypatch.setattr(os, "stat", spy("stat"))+ monkeypatch.setattr(os, "lstat", spy("lstat"))+ monkeypatch.setattr(os.path, "exists", spy("exists"))+ return seen+++class TestRequireRegularFile:+ def test_an_absolute_regular_file_is_returned(self, tmp_path):+ target = tmp_path / "ok.bin"+ target.write_bytes(b"x")++ assert require_regular_file(str(target)) == str(target)++ def test_a_relative_path_is_refused(self):+ with pytest.raises(OSError, match="not an absolute local file path"):+ require_regular_file("ok.bin")++ def test_a_nul_byte_is_an_oserror_not_a_valueerror(self, tmp_path):+ with pytest.raises(OSError, match="not an absolute local file path"):+ require_regular_file(str(tmp_path / "ok\x00.bin"))++ def test_a_directory_is_refused(self, tmp_path):+ with pytest.raises(OSError, match="not a regular file"):+ require_regular_file(str(tmp_path))++ def test_a_missing_file_is_file_not_found(self, tmp_path):+ with pytest.raises(FileNotFoundError):+ require_regular_file(str(tmp_path / "missing.bin"))++ @pytest.mark.skipif(not hasattr(os, "mkfifo"), reason="needs os.mkfifo")+ def test_a_fifo_is_refused_without_blocking(self, tmp_path):+ fifo = tmp_path / "pipe.bin"+ os.mkfifo(fifo)++ with pytest.raises(OSError, match="not a regular file"):+ require_regular_file(str(fifo))++ @pytest.mark.skipif(not os.path.exists("/dev/null"), reason="needs /dev/null")+ def test_a_device_is_refused(self):+ with pytest.raises(OSError, match="not a regular file"):+ require_regular_file("/dev/null")++ @pytest.mark.skipif(os.name != "nt", reason="DOS device names")+ def test_a_dos_device_name_is_refused(self, tmp_path):+ with pytest.raises(OSError, match="not a regular file"):+ require_regular_file(str(tmp_path / "nul"))++ @pytest.mark.parametrize("value", DEVICE_NAMESPACE_FORMS)+ def test_device_namespace_forms_are_refused_before_stat(self, value, monkeypatch):+ looked_up = _spy_lookups(monkeypatch)++ with pytest.raises(OSError, match="not an absolute local file path"):+ require_regular_file(value)+ assert looked_up == []++ def test_a_unc_path_is_not_refused_by_its_spelling(self, monkeypatch):+ # The loader resolves a media dir on a mapped drive to its UNC form; a+ # regular file there must stay readable.+ unc = "//soup-sentinel.invalid/share/x.bin"+ looked_up = _spy_lookups(monkeypatch, result=_regular_stat())++ assert require_regular_file(unc) == unc+ assert looked_up == [unc]++ @pytest.mark.skipif(os.name != "nt", reason="extended-length paths are Windows paths")+ def test_an_extended_length_local_path_is_not_refused(self, tmp_path):+ target = tmp_path / "ok.bin"+ target.write_bytes(b"x")+ extended = "\\\\?\\" + str(target)++ assert require_regular_file(extended) == extended+++class TestLoadAudioMonoReadsOnlyRegularFiles:+ @pytest.fixture(autouse=True)+ def _soundfile_must_not_be_reached(self, monkeypatch):+ def refuse(*args, **kwargs):+ raise AssertionError("soundfile reached a non-regular file")++ fake = types.ModuleType("soundfile")+ fake.info = refuse+ fake.read = refuse+ monkeypatch.setitem(sys.modules, "soundfile", fake)++ def _load_audio_mono(self, path):+ from soup_cli.utils.tts_codec import load_audio_mono++ return load_audio_mono(path)++ def test_a_directory_is_refused(self, tmp_path):+ with pytest.raises(ValueError, match="audio path must be a regular file"):+ self._load_audio_mono(str(tmp_path))++ @pytest.mark.skipif(not hasattr(os, "mkfifo"), reason="needs os.mkfifo")+ def test_a_fifo_is_refused_without_blocking(self, tmp_path):+ fifo = tmp_path / "pipe.wav"+ os.mkfifo(fifo)++ with pytest.raises(ValueError, match="audio path must be a regular file"):+ self._load_audio_mono(str(fifo))++ @pytest.mark.skipif(not os.path.exists("/dev/null"), reason="needs /dev/null")+ def test_a_character_device_is_refused(self):+ with pytest.raises(ValueError, match="audio path must be a regular file"):+ self._load_audio_mono("/dev/null")++ @pytest.mark.skipif(os.name != "nt", reason="DOS device names")+ def test_a_dos_device_name_is_refused(self, tmp_path):+ with pytest.raises(ValueError, match="audio path must be a regular file"):+ self._load_audio_mono(str(tmp_path / "nul"))++ @pytest.mark.parametrize("value", DEVICE_NAMESPACE_FORMS)+ def test_a_device_namespace_path_is_refused_before_any_lookup(self, value, monkeypatch):+ looked_up = _spy_lookups(monkeypatch)++ with pytest.raises(ValueError, match="audio path must not be a device path"):+ self._load_audio_mono(value)+ assert looked_up == []+++def _non_regular_paths(tmp_path: Path) -> list[str]:+ """A directory and a relative path, plus a FIFO and a device where the OS has them."""+ folder = tmp_path / "folder"+ folder.mkdir()+ paths = [str(folder), "ok.bin"]+ if hasattr(os, "mkfifo"):+ fifo = tmp_path / "pipe.bin"+ os.mkfifo(fifo)+ paths.append(str(fifo))+ if os.path.exists("/dev/null"):+ paths.append("/dev/null")+ if os.name == "nt":+ paths.append(str(tmp_path / "nul"))+ return paths+++def _vision_wrapper(monkeypatch):+ pytest.importorskip("datasets")+ from soup_cli.trainer import sft+ from soup_cli.trainer.sft import SFTTrainerWrapper++ out = io.StringIO()+ monkeypatch.setattr(sft, "console", Console(file=out, width=400))+ return object.__new__(SFTTrainerWrapper), out+++def _open_spy(pil_image, opened: list):+ real_open = pil_image.open++ def spy_open(fp, *args, **kwargs):+ if isinstance(fp, pil_image.Image):+ # A decoded value: hand it back, as a reader that accepts one would.+ opened.append(fp)+ return fp+ if isinstance(fp, (str, bytes, os.PathLike)):+ opened.append(os.fsdecode(fp))+ if not os.path.isfile(fp): # never block on a FIFO, whatever the code does+ raise OSError("spy: not a regular file")+ return real_open(fp, *args, **kwargs)++ return spy_open+++_VISION_MESSAGES = [{"role": "user", "content": "<image>\nDescribe."}]+++def test_vision_trainer_opens_only_regular_files(tmp_path, monkeypatch):+ pil_image = pytest.importorskip("PIL.Image")+ wrapper, out = _vision_wrapper(monkeypatch)+ image_path = tmp_path / "ok.png"+ pil_image.new("RGB", (4, 4), "red").save(image_path)+ refused = _non_regular_paths(tmp_path)+ rows = [{"messages": _VISION_MESSAGES, "image": str(image_path)}] + [+ {"messages": _VISION_MESSAGES, "image": path} for path in refused+ ]+ opened: list = []++ # Scoped to the call: reading the result back decodes the stored PNG+ # through PIL.Image.open(BytesIO), which must use the real function.+ with monkeypatch.context() as patched:+ patched.setattr(pil_image, "open", _open_spy(pil_image, opened))+ train_ds, _ = wrapper._prepare_vision_dataset({"train": rows})++ assert opened == [str(image_path)]+ assert [len(images) for images in train_ds["images"]] == [1] + [0] * len(refused)+ assert _plain(out.getvalue()).count("Warning: cannot open image:") == len(refused)+++def test_vision_trainer_checks_a_bytes_path_too(tmp_path, monkeypatch):+ pil_image = pytest.importorskip("PIL.Image")+ wrapper, out = _vision_wrapper(monkeypatch)+ refused = [os.fsencode(path) for path in _non_regular_paths(tmp_path)]+ rows = [{"messages": _VISION_MESSAGES, "image": path} for path in refused]+ opened: list = []++ with monkeypatch.context() as patched:+ patched.setattr(pil_image, "open", _open_spy(pil_image, opened))+ wrapper._prepare_vision_dataset({"train": rows})++ assert opened == []+ assert _plain(out.getvalue()).count("Warning: cannot open image:") == len(refused)+++def test_vision_trainer_hands_a_decoded_image_to_the_reader(tmp_path, monkeypatch):+ pil_image = pytest.importorskip("PIL.Image")+ wrapper, _ = _vision_wrapper(monkeypatch)+ rows = [{"messages": _VISION_MESSAGES, "image": pil_image.new("RGB", (4, 4), "blue")}]+ opened: list = []++ with monkeypatch.context() as patched:+ patched.setattr(pil_image, "open", _open_spy(pil_image, opened))+ train_ds, _ = wrapper._prepare_vision_dataset({"train": rows})++ assert [isinstance(value, pil_image.Image) for value in opened] == [True]+ assert [len(images) for images in train_ds["images"]] == [1]+++_AUDIO_MESSAGES = [+ {"role": "user", "content": "Transcribe."},+ {"role": "assistant", "content": "hello"},+]+++def _audio_wrapper(monkeypatch):+ pytest.importorskip("datasets")+ from soup_cli.trainer import sft+ from soup_cli.trainer.sft import SFTTrainerWrapper++ out = io.StringIO()+ monkeypatch.setattr(sft, "console", Console(file=out, width=400))+ wrapper = object.__new__(SFTTrainerWrapper)+ wrapper.processor = types.SimpleNamespace() # no chat template: turns are joined+ return wrapper, out+++def _fake_librosa(loaded: list):+ numpy = pytest.importorskip("numpy")++ def load(path, sr=None, mono=True):+ loaded.append(os.fsdecode(path) if isinstance(path, (str, bytes)) else path)+ return numpy.zeros(8, dtype=numpy.float32), 16000++ return types.SimpleNamespace(load=load)+++def test_audio_trainer_hands_a_value_that_is_no_file_name_to_the_reader(monkeypatch):+ wrapper, _ = _audio_wrapper(monkeypatch)+ clip = {"array": [0.0, 0.0], "sampling_rate": 16000}+ loaded: list = []++ with monkeypatch.context() as patched:+ patched.setitem(sys.modules, "librosa", _fake_librosa(loaded))+ wrapper._prepare_audio_dataset({"train": [{"messages": _AUDIO_MESSAGES, "audio": clip}]})++ assert loaded == [clip]+++def test_audio_trainer_reads_only_regular_files(tmp_path, monkeypatch):+ wrapper, out = _audio_wrapper(monkeypatch)+ messages = _AUDIO_MESSAGES+ loaded: list = []+ paths = _non_regular_paths(tmp_path)+ refused = [{"messages": messages, "audio": path} for path in paths]+ # A bytes value is a file name to the reader too; Arrow keeps it in a+ # column of its own, so it goes in a call of its own.+ refused_bytes = [{"messages": messages, "audio": os.fsencode(path)} for path in paths]+ clip = tmp_path / "ok.wav"+ clip.write_bytes(b"RIFF")++ # Only non-readable rows go in the first calls: mixing read and unread rows+ # in one Dataset.map hits a column mismatch that predates this change.+ with monkeypatch.context() as patched:+ patched.setitem(sys.modules, "librosa", _fake_librosa(loaded))+ wrapper._prepare_audio_dataset({"train": refused})+ wrapper._prepare_audio_dataset({"train": refused_bytes})+ assert loaded == []+ wrapper._prepare_audio_dataset({"train": [{"messages": messages, "audio": str(clip)}]})++ assert loaded == [str(clip)]+ assert _plain(out.getvalue()).count("Warning: cannot open audio:") == 2 * len(paths)+++# ---------------------------------------------------------------------------+# soup infer --task asr and soup data inspect use the same check+# ---------------------------------------------------------------------------++[email protected]("value", NETWORK_FORMS)+def test_infer_asr_refuses_every_network_and_device_spelling(value):+ from soup_cli.commands.infer import _resolve_asr_audio++ with pytest.raises(ValueError, match="UNC"):+ _resolve_asr_audio(value, Path("audio"))+++def test_soup_infer_asr_skips_network_and_device_rows(tmp_path, monkeypatch):+ import soup_cli.commands.infer as infer+ from soup_cli.cli import app++ monkeypatch.chdir(tmp_path)+ (tmp_path / "audio").mkdir()+ monkeypatch.setattr(infer, "_ASR_TRANSCRIBER_OVERRIDE", lambda audio_path: "hi")+ refused = [+ r"\??\UNC\soup-sentinel.invalid\share\x.wav",+ r"\/soup-sentinel.invalid/share/x.wav",+ r"\.\??\UNC\soup-sentinel.invalid\share\x.wav",+ ]+ _write_jsonl(+ tmp_path / "in.jsonl",+ [{"audio": value, "text": "x"} for value in refused] + [{"audio": "ok.wav", "text": "hi"}],+ )++ result = CliRunner().invoke(+ app,+ ["infer", "--task", "asr", "--model", "m", "--input", "in.jsonl",+ "--output", "out.jsonl", "--audio-dir", "audio"],+ )++ assert result.exit_code == 0, (result.output, repr(result.exception))+ written = _read_jsonl(tmp_path / "out.jsonl")+ assert [row["audio"] for row in written] == ["ok.wav"]+ plain = _plain(result.output)+ assert plain.count("audio path must not be a UNC / network / device path") == len(refused)+++def _inspect_rows(tmp_path: Path, rows: list[dict]):+ from soup_cli.commands.data import app as data_app++ _write_jsonl(tmp_path / "rows.jsonl", rows)+ result = CliRunner().invoke(data_app, ["inspect", "rows.jsonl", "--rows", "0"])+ assert result.exit_code == 0, (result.output, repr(result.exception))+ found = re.search(r"Images found on disk\W+(\d+)", _plain(result.output))+ assert found, _plain(result.output)+ return int(found.group(1))+++def test_data_inspect_never_looks_up_network_or_device_values(tmp_path, monkeypatch):+ monkeypatch.chdir(tmp_path)+ (tmp_path / "ok.png").write_bytes(b"x")+ looked_up = _spy_lookups(monkeypatch)+ rows = [{"image": "ok.png", "conversations": []}] + [+ {"image": value, "conversations": []} for value in [*NETWORK_FORMS, "ok\x00.png"]+ ]++ found = _inspect_rows(tmp_path, rows)++ assert found == 1+ assert looked_up == []++[email protected](os.name != "nt", reason="DOS device names")+def test_data_inspect_does_not_count_a_dos_device_as_an_image(tmp_path, monkeypatch):+ monkeypatch.chdir(tmp_path)++ assert _inspect_rows(tmp_path, [{"image": "nul", "conversations": []}]) == 0+++def test_data_inspect_skips_a_value_that_is_not_a_string(monkeypatch):+ from soup_cli.commands import data++ out = io.StringIO()+ monkeypatch.setattr(data, "console", Console(file=out, width=400))+ looked_up = _spy_lookups(monkeypatch)++ data._show_vision_stats(+ [{"image": os.fsencode(NETWORK_FORMS[0]), "conversations": []}, {"image": {"bytes": b""}}]+ )++ assert looked_up == []+ assert re.search(r"Images found on disk\W+0", _plain(out.getvalue()))