Skip to content

armgit / Soup

Public Imported from GitHub
0

Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.

fix(data): scan all supported row formats in quality commands (#2037)

Nurkhan Esenbekd8b0c89a2fc5
diff --git a/changelog.d/0.76.0/2037.fixed.md b/changelog.d/0.76.0/2037.fixed.md
new file mode 100644
index 00000000..2eb638c4
--- /dev/null
+++ b/changelog.d/0.76.0/2037.fixed.md
@@ -0,0 +1 @@
+- Quality scans share the multi-format expectations extractor, see Alpaca/preference/ShareGPT text and prompt benchmark rows, and report unscanned rows instead of silently reporting them clean (#1427 by @kok-o in #2037; following @abdulbasit-ogunrinu's agreed plan).
diff --git a/docs/data.md b/docs/data.md
index 2178528c..24669ca6 100644
--- a/docs/data.md
+++ b/docs/data.md
@@ -1173,12 +1173,23 @@ the same comparison corpus, so omitting labels or changing one valid label to
another does not change the removal count. The file's JSONL is bounded and
cwd-contained by the shared loader, with strict
parsing: malformed/non-object rows, empty files and rows without usable 8-gram
-text are refused before the scorecard is printed. Text comes from `text`,
-`content`, or `messages[].content`, via the shared extractor. The fixed 8-gram
+text are refused before the scorecard is printed. Text comes from the shared
+expectations extractor: plain text/content, Alpaca instruction/input/output,
+prompt/chosen/rejected/completion, ShareGPT/ChatML conversations, embedding fields
+and textual tool-call arguments. The fixed 8-gram
heuristic uses `--threshold`; a resulting zero describes only those supplied
texts, not absence of contamination against every public benchmark. The other
input/standalone loader paths keep their previous tolerant behavior.
+All six quality commands (`score`, `pii`, `toxicity`, `langdetect`, `educational`
+and `decontaminate`) warn with a count when some input rows have no extractable
+text. They fail before reporting metrics or writing output when no row has text.
+Inputs with no rows, including empty files or files containing only blank or
+non-object/non-JSON lines, are refused too.
+Standalone decontamination applies the same rule to its benchmark file; the
+scorecard benchmark file retains the stricter per-row 8-gram validation above.
+The PII and abuse-keyword detectors themselves are unchanged.
+
The scorecard reports PII matches, abuse-keyword matches, language distribution, mean heuristic educational value, and decontamination removals. PII detection uses a narrow ReDoS-hardened regex set (email / phone / SSN / credit-card) with a 50 KB pre-cap on every input. Language detection is a stopword heuristic across six languages. `soup data toxicity` is retained as a compatible command name, but its output is explicitly an abuse-keyword heuristic, not a toxicity classifier. Ambiguous technical and medical terms such as process `kill`, thread `die`, and heart `attack` are not treated as standalone safety signals. This trades one known failure mode for explicit limitations: in maintainer review, 9 of 10 held-out abusive examples scored zero and 10 of 12 benign technical or editorial examples were flagged at the default threshold. Use it only for keyword triage, never as a safety decision. The default Magpie quality filter therefore applies only non-empty and educational heuristics; provide an explicit model-backed policy outside Soup when safety classification is required. The `[data-pro]` extra currently adds `langdetect` and Presidio only; it does not install Llama Guard or FineWeb-Edu. Decontamination uses n-gram containment against caller-supplied texts: `--benchmarks mmlu,gsm8k` selects allowlisted labels only; use `--benchmark-file custom_benchmark.jsonl` for actual comparison data.
diff --git a/src/soup_cli/commands/data_score.py b/src/soup_cli/commands/data_score.py
index 4a98c19a..5ecdee14 100644
--- a/src/soup_cli/commands/data_score.py
+++ b/src/soup_cli/commands/data_score.py
@@ -24,11 +24,26 @@ def _exit(msg: str, code: int = 1) -> None:
raise typer.Exit(code)
+def _check_text_rows(rows: List[Mapping[str, Any]], label: str) -> None:
+ """Report unscanned rows before printing clean metrics or writing output."""
+ from soup_cli.utils.data_score import extract_row_text
+
+ missing = sum(not extract_row_text(row).strip() for row in rows)
+ if not rows or missing == len(rows):
+ _exit(f"no extractable text in {len(rows)} {label} rows")
+ if missing:
+ console.print(
+ f"[yellow]Warning:[/] {missing} of {len(rows)} {label} rows have no extractable text"
+ )
+
+
def _read_rows(path: str) -> List[Mapping[str, Any]]:
from soup_cli.utils.data_score import load_jsonl_rows
try:
- return load_jsonl_rows(path)
+ rows = load_jsonl_rows(path)
+ _check_text_rows(rows, "input")
+ return rows
except (TypeError, ValueError, FileNotFoundError) as exc:
_exit(str(exc))
raise # unreachable; satisfies type checker
@@ -148,7 +163,7 @@ def decontaminate(
None, "--benchmark-file",
help=(
"v0.53.7: operator-supplied benchmark JSONL (under cwd). Each "
- "row's ``text``/``prompt``/``content`` field contributes to the "
+ "row's text, prompt, Alpaca, preference or conversation fields contribute to the "
"n-gram contamination set. Compatible with --benchmarks (extends)."
),
),
@@ -200,6 +215,7 @@ def decontaminate(
bench_rows = load_jsonl_rows(benchmark_file)
except (TypeError, ValueError, FileNotFoundError) as exc:
_exit(f"--benchmark-file: {exc}")
+ _check_text_rows(bench_rows, "benchmark")
for row in bench_rows:
try:
text = extract_row_text(row)
diff --git a/src/soup_cli/utils/data_score.py b/src/soup_cli/utils/data_score.py
index 0444197b..ae6d214d 100644
--- a/src/soup_cli/utils/data_score.py
+++ b/src/soup_cli/utils/data_score.py
@@ -139,22 +139,11 @@ def ngram_overlap_ratio(a: Any, b: Any, *, n: int = 8) -> float:
def _extract_row_text(row: Any) -> str:
+ from soup_cli.utils.row_text import extract_row_text
+
if not isinstance(row, Mapping):
return ""
- val = row.get("text") or row.get("content")
- if isinstance(val, str):
- return val
- # Fall back to joining messages if present (tolerant of various shapes)
- msgs = row.get("messages")
- if isinstance(msgs, list):
- parts: List[str] = []
- for m in msgs:
- if isinstance(m, Mapping):
- c = m.get("content")
- if isinstance(c, str):
- parts.append(c)
- return "\n".join(parts)
- return ""
+ return extract_row_text(row)
def decontaminate_rows(
diff --git a/src/soup_cli/utils/expectations.py b/src/soup_cli/utils/expectations.py
index 9884ed9f..96f85a7a 100644
--- a/src/soup_cli/utils/expectations.py
+++ b/src/soup_cli/utils/expectations.py
@@ -20,6 +20,16 @@ import os
from dataclasses import dataclass
from typing import Any, Callable, List, Mapping, Optional, Sequence, Tuple
+from soup_cli.utils.row_text import (
+ extract_assistant_text as _extract_assistant_text,
+)
+from soup_cli.utils.row_text import (
+ extract_row_parts as _extract_row_parts,
+)
+from soup_cli.utils.row_text import (
+ extract_row_text as _extract_row_text,
+)
+
# DoS caps + bounds for validators.
_MAX_NAME_LEN = 128
_MAX_DETAILS_PER_RESULT = 32
@@ -222,7 +232,6 @@ def _check_token_bounds(min_tokens: object, max_tokens: object) -> Tuple[int, in
# Row helpers & Format Extraction Rules
# -----------------------------------------------------------------------------
-_ASSISTANT_ROLES = frozenset({"assistant", "gpt", "chatgpt", "bot", "model"})
FORMAT_EXTRACTION_RULES: Mapping[str, Mapping[str, Tuple[str, ...]]] = {
"alpaca": {
@@ -288,268 +297,6 @@ FORMAT_EXTRACTION_RULES: Mapping[str, Mapping[str, Tuple[str, ...]]] = {
}
-def _extract_content_parts(content: Any) -> List[str]:
- """Extract strings from string or multimodal content parts list."""
- import json
-
- parts: List[str] = []
- if isinstance(content, str):
- if content:
- parts.append(content)
- elif isinstance(content, list):
- for part in content:
- if isinstance(part, str):
- if part:
- parts.append(part)
- elif isinstance(part, Mapping):
- val = part.get("text")
- if isinstance(val, str) and val:
- parts.append(val)
- args = part.get("arguments") or part.get("input")
- if isinstance(args, str) and args:
- parts.append(args)
- elif isinstance(args, (dict, list)):
- parts.append(json.dumps(args))
- return parts
-
-
-def _extract_tool_calls_text(tool_calls: Any) -> List[str]:
- """Extract function call arguments and names from tool_calls list."""
- import json
-
- parts: List[str] = []
- if isinstance(tool_calls, list):
- for call in tool_calls:
- if isinstance(call, Mapping):
- func = call.get("function")
- if isinstance(func, Mapping):
- args = func.get("arguments")
- if isinstance(args, str) and args:
- parts.append(args)
- elif isinstance(args, (dict, list)):
- parts.append(json.dumps(args))
- args = call.get("arguments")
- if isinstance(args, str) and args:
- parts.append(args)
- elif isinstance(args, (dict, list)):
- parts.append(json.dumps(args))
- return parts
-
-
-def _extract_messages_text(messages: Any, *, assistant_only: bool = False) -> List[str]:
- """Extract text from a messages list (chatml, audio, tool-calling, multimodal)."""
- parts: List[str] = []
- if not isinstance(messages, list):
- return parts
- for msg in messages:
- if not isinstance(msg, Mapping):
- continue
- role = msg.get("role")
- if assistant_only and role not in _ASSISTANT_ROLES:
- continue
- content = msg.get("content")
- parts.extend(_extract_content_parts(content))
- if "tool_calls" in msg:
- parts.extend(_extract_tool_calls_text(msg.get("tool_calls")))
- return parts
-
-
-def _extract_conversations_text(
- conversations: Any, *, assistant_only: bool = False
-) -> List[str]:
- """Extract text from a conversations list (sharegpt, llava, sharegpt4v)."""
- parts: List[str] = []
- if not isinstance(conversations, list):
- return parts
- for turn in conversations:
- if not isinstance(turn, Mapping):
- continue
- speaker = turn.get("from")
- if assistant_only and speaker not in _ASSISTANT_ROLES:
- continue
- val = turn.get("value")
- parts.extend(_extract_content_parts(val))
- return parts
-
-
-def _extract_field_text_or_messages(
- val: Any, *, assistant_only: bool = False
-) -> List[str]:
- """Extract text from a field that may be str or list of messages/strings."""
- if isinstance(val, str):
- return [val] if val else []
- if isinstance(val, list):
- msg_parts = _extract_messages_text(val, assistant_only=assistant_only)
- if msg_parts:
- return msg_parts
- str_parts: List[str] = []
- for item in val:
- if isinstance(item, str) and item:
- str_parts.append(item)
- elif isinstance(item, Mapping):
- if assistant_only:
- role = item.get("role") or item.get("from")
- if role is not None and role not in _ASSISTANT_ROLES:
- continue
- for k in ("content", "text", "value"):
- v = item.get(k)
- if isinstance(v, str) and v:
- str_parts.append(v)
- return str_parts
- return []
-
-
-def _extract_row_parts(row: Mapping[str, Any]) -> List[str]:
- """Extract all text parts across all format fields (PII / length scans)."""
- parts: List[str] = []
-
- for key in (
- "instruction",
- "input",
- "output",
- "system",
- "response",
- "anchor",
- "positive",
- "negative",
- "text",
- "content",
- "query",
- "golden_doc",
- "answer",
- ):
- val = row.get(key)
- if isinstance(val, str) and val:
- parts.append(val)
- elif isinstance(val, list) and key in ("anchor", "positive", "negative"):
- for s in val:
- if isinstance(s, str) and s:
- parts.append(s)
-
- for key in ("prompt", "chosen", "rejected", "completion"):
- val = row.get(key)
- if val is not None:
- parts.extend(_extract_field_text_or_messages(val, assistant_only=False))
-
- completions = row.get("completions")
- if isinstance(completions, list):
- for c in completions:
- if isinstance(c, str) and c:
- parts.append(c)
-
- distractors = row.get("distractor_docs")
- if isinstance(distractors, list):
- for d in distractors:
- if isinstance(d, str) and d:
- parts.append(d)
-
- segments = row.get("segments")
- if isinstance(segments, list):
- for seg in segments:
- if isinstance(seg, Mapping):
- t = seg.get("text")
- if isinstance(t, str) and t:
- parts.append(t)
-
- if "conversations" in row:
- parts.extend(_extract_conversations_text(row.get("conversations"), assistant_only=False))
-
- if "messages" in row:
- parts.extend(_extract_messages_text(row.get("messages"), assistant_only=False))
-
- if "tool_calls" in row:
- parts.extend(_extract_tool_calls_text(row.get("tool_calls")))
-
- tools = row.get("tools")
- if isinstance(tools, list):
- for tool in tools:
- if isinstance(tool, Mapping):
- func = tool.get("function")
- if isinstance(func, Mapping):
- desc = func.get("description")
- if isinstance(desc, str) and desc:
- parts.append(desc)
-
- return parts
-
-
-def _extract_row_text(row: Mapping[str, Any]) -> str:
- """Extract all text across all format fields as a single string."""
- return "\n".join(_extract_row_parts(row))
-
-
-def _extract_assistant_parts(row: Mapping[str, Any]) -> List[str]:
- """Extract assistant-side text parts (for refusal scans)."""
- parts: List[str] = []
-
- for key in ("output", "response", "answer"):
- val = row.get(key)
- if isinstance(val, str) and val:
- parts.append(val)
-
- if "conversations" in row:
- parts.extend(_extract_conversations_text(row.get("conversations"), assistant_only=True))
-
- if "messages" in row:
- parts.extend(_extract_messages_text(row.get("messages"), assistant_only=True))
-
- if "tool_calls" in row:
- parts.extend(_extract_tool_calls_text(row.get("tool_calls")))
-
- if "chosen" in row:
- val = row.get("chosen")
- if val is not None:
- parts.extend(_extract_field_text_or_messages(val, assistant_only=True))
-
- if "completion" in row:
- val = row.get("completion")
- if val is not None:
- parts.extend(_extract_field_text_or_messages(val, assistant_only=True))
-
- completions = row.get("completions")
- if isinstance(completions, list):
- for c in completions:
- if isinstance(c, str) and c:
- parts.append(c)
-
- segments = row.get("segments")
- if isinstance(segments, list):
- for seg in segments:
- if isinstance(seg, Mapping) and seg.get("label", True):
- t = seg.get("text")
- if isinstance(t, str) and t:
- parts.append(t)
-
- if not parts and ("text" in row or "content" in row):
- is_chat_or_pref = any(
- k in row
- for k in (
- "conversations",
- "messages",
- "instruction",
- "output",
- "prompt",
- "chosen",
- "completion",
- "query",
- "answer",
- "segments",
- "completions",
- )
- )
- if not is_chat_or_pref:
- val = row.get("text") or row.get("content")
- if isinstance(val, str) and val:
- parts.append(val)
-
- return parts
-
-
-def _extract_assistant_text(row: Mapping[str, Any]) -> str:
- """Extract assistant-side text as a single string."""
- return "\n".join(_extract_assistant_parts(row))
-
-
def _check_rows(rows: object) -> Sequence[Mapping[str, Any]]:
if isinstance(rows, str) or isinstance(rows, bytes):
raise TypeError("rows must be a list of mappings, not a string")
diff --git a/src/soup_cli/utils/row_text.py b/src/soup_cli/utils/row_text.py
new file mode 100644
index 00000000..a790553b
--- /dev/null
+++ b/src/soup_cli/utils/row_text.py
@@ -0,0 +1,269 @@
+"""Shared multi-format text extraction for expectations and quality scans."""
+
+from __future__ import annotations
+
+from typing import Any, List, Mapping
+
+_ASSISTANT_ROLES = frozenset({"assistant", "gpt", "chatgpt", "bot", "model"})
+
+
+def _extract_content_parts(content: Any) -> List[str]:
+ """Extract strings from string or multimodal content parts list."""
+ import json
+
+ parts: List[str] = []
+ if isinstance(content, str):
+ if content:
+ parts.append(content)
+ elif isinstance(content, list):
+ for part in content:
+ if isinstance(part, str):
+ if part:
+ parts.append(part)
+ elif isinstance(part, Mapping):
+ val = part.get("text")
+ if isinstance(val, str) and val:
+ parts.append(val)
+ args = part.get("arguments") or part.get("input")
+ if isinstance(args, str) and args:
+ parts.append(args)
+ elif isinstance(args, (dict, list)):
+ parts.append(json.dumps(args))
+ return parts
+
+
+def _extract_tool_calls_text(tool_calls: Any) -> List[str]:
+ """Extract function call arguments and names from tool_calls list."""
+ import json
+
+ parts: List[str] = []
+ if isinstance(tool_calls, list):
+ for call in tool_calls:
+ if isinstance(call, Mapping):
+ func = call.get("function")
+ if isinstance(func, Mapping):
+ args = func.get("arguments")
+ if isinstance(args, str) and args:
+ parts.append(args)
+ elif isinstance(args, (dict, list)):
+ parts.append(json.dumps(args))
+ args = call.get("arguments")
+ if isinstance(args, str) and args:
+ parts.append(args)
+ elif isinstance(args, (dict, list)):
+ parts.append(json.dumps(args))
+ return parts
+
+
+def _extract_messages_text(messages: Any, *, assistant_only: bool = False) -> List[str]:
+ """Extract text from a messages list (chatml, audio, tool-calling, multimodal)."""
+ parts: List[str] = []
+ if not isinstance(messages, list):
+ return parts
+ for msg in messages:
+ if not isinstance(msg, Mapping):
+ continue
+ role = msg.get("role")
+ if assistant_only and role not in _ASSISTANT_ROLES:
+ continue
+ content = msg.get("content")
+ parts.extend(_extract_content_parts(content))
+ if "tool_calls" in msg:
+ parts.extend(_extract_tool_calls_text(msg.get("tool_calls")))
+ return parts
+
+
+def _extract_conversations_text(
+ conversations: Any, *, assistant_only: bool = False
+) -> List[str]:
+ """Extract text from a conversations list (sharegpt, llava, sharegpt4v)."""
+ parts: List[str] = []
+ if not isinstance(conversations, list):
+ return parts
+ for turn in conversations:
+ if not isinstance(turn, Mapping):
+ continue
+ speaker = turn.get("from")
+ if assistant_only and speaker not in _ASSISTANT_ROLES:
+ continue
+ val = turn.get("value")
+ parts.extend(_extract_content_parts(val))
+ return parts
+
+
+def _extract_field_text_or_messages(
+ val: Any, *, assistant_only: bool = False
+) -> List[str]:
+ """Extract text from a field that may be str or list of messages/strings."""
+ if isinstance(val, str):
+ return [val] if val else []
+ if isinstance(val, list):
+ msg_parts = _extract_messages_text(val, assistant_only=assistant_only)
+ if msg_parts:
+ return msg_parts
+ str_parts: List[str] = []
+ for item in val:
+ if isinstance(item, str) and item:
+ str_parts.append(item)
+ elif isinstance(item, Mapping):
+ if assistant_only:
+ role = item.get("role") or item.get("from")
+ if role is not None and role not in _ASSISTANT_ROLES:
+ continue
+ for k in ("content", "text", "value"):
+ v = item.get(k)
+ if isinstance(v, str) and v:
+ str_parts.append(v)
+ return str_parts
+ return []
+
+
+def extract_row_parts(row: Mapping[str, Any]) -> List[str]:
+ """Extract all text parts across all format fields (PII / length scans)."""
+ parts: List[str] = []
+
+ for key in (
+ "instruction",
+ "input",
+ "output",
+ "system",
+ "response",
+ "anchor",
+ "positive",
+ "negative",
+ "text",
+ "content",
+ "query",
+ "golden_doc",
+ "answer",
+ ):
+ val = row.get(key)
+ if isinstance(val, str) and val:
+ parts.append(val)
+ elif isinstance(val, list) and key in ("anchor", "positive", "negative"):
+ for s in val:
+ if isinstance(s, str) and s:
+ parts.append(s)
+
+ for key in ("prompt", "chosen", "rejected", "completion"):
+ val = row.get(key)
+ if val is not None:
+ parts.extend(_extract_field_text_or_messages(val, assistant_only=False))
+
+ completions = row.get("completions")
+ if isinstance(completions, list):
+ for c in completions:
+ if isinstance(c, str) and c:
+ parts.append(c)
+
+ distractors = row.get("distractor_docs")
+ if isinstance(distractors, list):
+ for d in distractors:
+ if isinstance(d, str) and d:
+ parts.append(d)
+
+ segments = row.get("segments")
+ if isinstance(segments, list):
+ for seg in segments:
+ if isinstance(seg, Mapping):
+ t = seg.get("text")
+ if isinstance(t, str) and t:
+ parts.append(t)
+
+ if "conversations" in row:
+ parts.extend(_extract_conversations_text(row.get("conversations"), assistant_only=False))
+
+ if "messages" in row:
+ parts.extend(_extract_messages_text(row.get("messages"), assistant_only=False))
+
+ if "tool_calls" in row:
+ parts.extend(_extract_tool_calls_text(row.get("tool_calls")))
+
+ tools = row.get("tools")
+ if isinstance(tools, list):
+ for tool in tools:
+ if isinstance(tool, Mapping):
+ func = tool.get("function")
+ if isinstance(func, Mapping):
+ desc = func.get("description")
+ if isinstance(desc, str) and desc:
+ parts.append(desc)
+
+ return parts
+
+
+def extract_row_text(row: Mapping[str, Any]) -> str:
+ """Extract all text across all format fields as a single string."""
+ return "\n".join(extract_row_parts(row))
+
+
+def extract_assistant_parts(row: Mapping[str, Any]) -> List[str]:
+ """Extract assistant-side text parts (for refusal scans)."""
+ parts: List[str] = []
+
+ for key in ("output", "response", "answer"):
+ val = row.get(key)
+ if isinstance(val, str) and val:
+ parts.append(val)
+
+ if "conversations" in row:
+ parts.extend(_extract_conversations_text(row.get("conversations"), assistant_only=True))
+
+ if "messages" in row:
+ parts.extend(_extract_messages_text(row.get("messages"), assistant_only=True))
+
+ if "tool_calls" in row:
+ parts.extend(_extract_tool_calls_text(row.get("tool_calls")))
+
+ if "chosen" in row:
+ val = row.get("chosen")
+ if val is not None:
+ parts.extend(_extract_field_text_or_messages(val, assistant_only=True))
+
+ if "completion" in row:
+ val = row.get("completion")
+ if val is not None:
+ parts.extend(_extract_field_text_or_messages(val, assistant_only=True))
+
+ completions = row.get("completions")
+ if isinstance(completions, list):
+ for c in completions:
+ if isinstance(c, str) and c:
+ parts.append(c)
+
+ segments = row.get("segments")
+ if isinstance(segments, list):
+ for seg in segments:
+ if isinstance(seg, Mapping) and seg.get("label", True):
+ t = seg.get("text")
+ if isinstance(t, str) and t:
+ parts.append(t)
+
+ if not parts and ("text" in row or "content" in row):
+ is_chat_or_pref = any(
+ k in row
+ for k in (
+ "conversations",
+ "messages",
+ "instruction",
+ "output",
+ "prompt",
+ "chosen",
+ "completion",
+ "query",
+ "answer",
+ "segments",
+ "completions",
+ )
+ )
+ if not is_chat_or_pref:
+ val = row.get("text") or row.get("content")
+ if isinstance(val, str) and val:
+ parts.append(val)
+
+ return parts
+
+
+def extract_assistant_text(row: Mapping[str, Any]) -> str:
+ """Extract assistant-side text as a single string."""
+ return "\n".join(extract_assistant_parts(row))
diff --git a/tests/test_issue1427_shared_row_text.py b/tests/test_issue1427_shared_row_text.py
new file mode 100644
index 00000000..feb8a647
--- /dev/null
+++ b/tests/test_issue1427_shared_row_text.py
@@ -0,0 +1,149 @@
+"""Quality scans must see every supported row shape and report missing text."""
+
+import json
+import re
+
+import pytest
+from typer.testing import CliRunner
+
+from soup_cli.cli import app
+from soup_cli.utils import data_score
+from tests.conftest import strip_ansi
+
+PAYLOAD = "idiot [email protected]"
+CORPUS = "alpha beta gamma delta epsilon zeta eta theta iota kappa"
+SHAPES = ["text", "chat", "alpaca", "dpo", "kto", "sharegpt"]
+
+
+def _row(shape, text):
+ return {
+ "text": {"text": text},
+ "chat": {"messages": [{"role": "assistant", "content": text}]},
+ "alpaca": {"instruction": "", "input": "", "output": text},
+ "dpo": {"prompt": "", "chosen": "", "rejected": text},
+ "kto": {"prompt": "", "completion": [{"role": "assistant", "content": text}],
+ "label": True},
+ "sharegpt": {"conversations": [{"from": "gpt", "value": text}]},
+ }[shape]
+
+
+def _file(path, rows):
+ path.write_text("".join(json.dumps(row) + "\n" for row in rows), encoding="utf-8")
+ return path
+
+
+def _run(command, *extra):
+ return CliRunner().invoke(app, ["data", command, "--input", "rows.jsonl", *extra])
+
+
+def _plain(result):
+ return " ".join(strip_ansi(result.output).replace("│", " ").split())
+
+
[email protected](autouse=True)
+def local_inputs(tmp_path, monkeypatch):
+ monkeypatch.chdir(tmp_path)
+ # Exercise Soup's unchanged regex detector, without optional Presidio models.
+ monkeypatch.setattr(data_score, "_presidio_pii", lambda text: None)
+
+
[email protected]("shape", SHAPES)
[email protected]("command", ["pii", "toxicity", "score"])
+def test_quality_commands_scan_all_formats(tmp_path, shape, command):
+ row = _row(shape, PAYLOAD)
+ _file(tmp_path / "rows.jsonl", [row])
+ result = _run(command)
+ assert result.exit_code == 0, (result.output, result.exception)
+ if command == "score":
+ assert re.search(r"PII flagged\s+1", _plain(result))
+ assert re.search(r"Abuse-keyword flagged\s+1", _plain(result))
+ else:
+ assert re.search(r"Flagged:\s*1", _plain(result))
+ output = json.loads((tmp_path / f"{command}.jsonl").read_text(encoding="utf-8"))
+ assert all(output[key] == value for key, value in row.items())
+ if command == "toxicity":
+ assert output["_abuse_keyword_score"] == data_score.score_abuse_keywords(PAYLOAD)
+ else:
+ assert output["_pii_hits"] == data_score.detect_pii(PAYLOAD)
+
+
[email protected]("command", ["score", "decontaminate"])
[email protected]("shape", SHAPES + ["prompt"])
+def test_benchmark_formats_are_used(tmp_path, command, shape):
+ _file(tmp_path / "rows.jsonl", [{"text": CORPUS}, {"text": "unrelated content"}])
+ row = {"prompt": CORPUS} if shape == "prompt" else _row(shape, CORPUS)
+ _file(tmp_path / "benchmark.jsonl", [row])
+ result = _run(command, "--benchmark-file", "benchmark.jsonl")
+ assert result.exit_code == 0, (result.output, result.exception)
+ assert "Loaded 1 operator-supplied benchmark texts" in _plain(result)
+ if command == "score":
+ assert re.search(r"Decontaminated\s+1", _plain(result))
+ else:
+ assert re.search(r"Removed:\s*1", _plain(result))
+
+
+ "command", ["pii", "toxicity", "score", "decontaminate", "langdetect", "educational"],
+)
[email protected]("mixed", [False, True])
+def test_missing_text_is_reported_before_clean_results(tmp_path, command, mixed):
+ rows = [{"unknown": "unscanned"}, {"text": " "}]
+ if mixed:
+ rows.append({"text": PAYLOAD})
+ _file(tmp_path / "rows.jsonl", rows)
+ _file(tmp_path / "benchmark.jsonl", [{"text": CORPUS}])
+ extra = ["--benchmark-file", "benchmark.jsonl"] if command == "decontaminate" else []
+ result = _run(command, *extra)
+ output = _plain(result)
+ assert "no extractable text" in output
+ if mixed:
+ assert result.exit_code == 0, (result.output, result.exception)
+ assert "2 of 3 input rows" in output and "Warning:" in output
+ else:
+ assert result.exit_code == 1
+ assert "2 input rows" in output
+ assert "Flagged:" not in output and "Data Scorecard" not in output
+ assert not list(tmp_path.glob("pii.jsonl"))
+
+
[email protected]("mixed", [False, True])
+def test_decontamination_reports_missing_benchmark_text(tmp_path, mixed):
+ _file(tmp_path / "rows.jsonl", [{"text": CORPUS}])
+ rows = [{"unknown": "unscanned"}]
+ if mixed:
+ rows.append({"prompt": CORPUS})
+ _file(tmp_path / "benchmark.jsonl", rows)
+ result = _run("decontaminate", "--benchmark-file", "benchmark.jsonl")
+ assert "no extractable text" in _plain(result)
+ assert result.exit_code == (0 if mixed else 1)
+ if mixed:
+ assert "1 of 2 benchmark rows" in _plain(result)
+ assert re.search(r"Removed:\s*1", _plain(result))
+
+
[email protected]("content", ["", "\n\n", "not json\n[1, 2]\n"])
+ "command", ["pii", "toxicity", "score", "langdetect", "educational", "decontaminate"],
+)
+def test_input_without_rows_is_refused(tmp_path, command, content):
+ (tmp_path / "rows.jsonl").write_text(content, encoding="utf-8")
+ _file(tmp_path / "benchmark.jsonl", [{"text": CORPUS}])
+ extra = ["--benchmark-file", "benchmark.jsonl"] if command == "decontaminate" else []
+ result = _run(command, *extra)
+ assert result.exit_code == 1, (result.output, repr(result.exception))
+ assert "no extractable text in 0 input rows" in _plain(result)
+
+
+def test_shared_extraction_retains_all_fields_and_expectations_alias():
+ from soup_cli.utils import expectations, row_text
+
+ row = {"instruction": "instruction", "input": "input", "output": "output",
+ "prompt": "prompt", "chosen": "chosen", "rejected": "rejected",
+ "anchor": "anchor", "positive": ["positive"], "negative": "negative",
+ "tool_calls": [{"function": {"arguments": '{"email":"[email protected]"}'}}]}
+ text = row_text.extract_row_text(row)
+ assert expectations._extract_row_text is row_text.extract_row_text
+ assert data_score.extract_row_text(row) == text
+ for word in ("instruction", "input", "output", "prompt", "chosen", "rejected",
+ "anchor", "positive", "negative", "[email protected]"):
+ assert word in text