forked from MakazhanAlpamys/Soup
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata.py
More file actions
4009 lines (3545 loc) · 142 KB
/
Copy pathdata.py
File metadata and controls
4009 lines (3545 loc) · 142 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""soup data — dataset inspection and tools."""
from __future__ import annotations
import json
import ntpath
import os
import random
from pathlib import Path
from typing import Optional
import typer
from rich.console import Console
from rich.table import Table
from soup_cli.data.loader import load_raw_data
from soup_cli.data.validator import validate_and_stats
from soup_cli.utils.embed import DEFAULT_EMBED_MODEL, embed_texts
from soup_cli.utils.paths import is_under_cwd
from soup_cli.utils.semdedup import DedupReport, greedy_semdedup
console = Console()
app = typer.Typer(no_args_is_help=True)
@app.command()
def inspect(
path: str = typer.Argument(..., help="Path to dataset file (jsonl, csv, parquet)"),
rows: int = typer.Option(5, "--rows", "-r", help="Number of sample rows to show"),
):
"""Inspect a dataset: show stats and sample rows."""
file_path = Path(path)
if not file_path.exists():
console.print(f"[red]File not found: {file_path}[/]")
raise typer.Exit(1)
console.print(f"[dim]Inspecting {file_path}...[/]\n")
data = load_raw_data(file_path)
result = validate_and_stats(data)
# Print stats
stats_table = Table(title="Dataset Stats")
stats_table.add_column("Metric", style="bold")
stats_table.add_column("Value")
stats_table.add_row("Total samples", str(result["total"]))
stats_table.add_row("Columns", ", ".join(result["columns"]))
stats_table.add_row("Avg length (chars)", str(result["avg_length"]))
stats_table.add_row("Min length", str(result["min_length"]))
stats_table.add_row("Max length", str(result["max_length"]))
stats_table.add_row("Empty fields", str(result["empty_fields"]))
stats_table.add_row("Duplicates", str(result["duplicates"]))
console.print(stats_table)
# Vision stats (if dataset contains images)
_show_vision_stats(data)
# Print sample rows
if rows > 0 and len(data) > 0:
# Escape dataset-derived cell content + column names: a stray '[/]' in
# ordinary data crashes Rich with MarkupError; a crafted '[link=...]'
# renders a phishing hyperlink. Mirrors `soup data review`.
from rich.markup import escape as _escape
console.print(f"\n[bold]Sample rows ({min(rows, len(data))}):[/]")
sample_table = Table(show_lines=True)
for col in result["columns"][:5]: # max 5 columns
sample_table.add_column(_escape(str(col)), max_width=60)
for row in data[: min(rows, len(data))]:
values = [
_escape(str(row.get(col, ""))[:60])
for col in result["columns"][:5]
]
sample_table.add_row(*values)
console.print(sample_table)
@app.command()
def validate(
path: str = typer.Argument(..., help="Path to dataset file"),
fmt: str = typer.Option(
"auto", "--format", "-f",
help="Expected format: auto, alpaca, sharegpt, chatml, dpo, kto, plaintext",
),
):
"""Validate dataset format and report issues."""
file_path = Path(path)
if not file_path.exists():
console.print(f"[red]File not found: {file_path}[/]")
raise typer.Exit(1)
data = load_raw_data(file_path)
# Auto-detect format if not specified
if fmt == "auto":
from soup_cli.data.formats import detect_format
try:
fmt = detect_format(data)
console.print(f"[dim]Auto-detected format: {fmt}[/]")
except ValueError as exc:
console.print(f"[red]{exc}[/]")
raise typer.Exit(1)
result = validate_and_stats(data, expected_format=fmt)
if result["issues"]:
console.print("[yellow]Issues found:[/]")
for issue in result["issues"]:
console.print(f" [yellow]![/] {issue}")
else:
console.print("[bold green]Dataset is valid![/]")
valid = result["valid_rows"]
total = result["total"]
console.print(f"\n[green]{valid}/{total} rows valid for {fmt} format[/]")
@app.command()
def convert(
path: str = typer.Argument(..., help="Input dataset file"),
to: str = typer.Option(
..., "--to", "-t",
help="Target format: alpaca, sharegpt, chatml",
),
output: str = typer.Option(
None, "--output", "-o",
help="Output file path (default: <input>_<format>.jsonl)",
),
):
"""Convert a dataset between formats (alpaca, sharegpt, chatml)."""
from soup_cli.data.formats import (
CONVERTIBLE_FORMATS,
detect_format,
format_to_messages,
messages_to_format,
)
file_path = Path(path)
if not file_path.exists():
console.print(f"[red]File not found: {file_path}[/]")
raise typer.Exit(1)
if to not in CONVERTIBLE_FORMATS:
console.print(
f"[red]Invalid target format: {to}[/]\n"
f"Supported: {', '.join(CONVERTIBLE_FORMATS)}"
)
raise typer.Exit(1)
data = load_raw_data(file_path)
if not data:
console.print("[red]Dataset is empty.[/]")
raise typer.Exit(1)
src_fmt = detect_format(data)
console.print(f"[dim]Detected source format: {src_fmt}[/]")
if src_fmt == to:
console.print(f"[yellow]Source and target format are both '{to}'. Nothing to convert.[/]")
raise typer.Exit()
if src_fmt == "dpo":
console.print("[red]Cannot convert DPO format (preference pairs are not conversations).[/]")
raise typer.Exit(1)
# Convert: source -> messages -> target
converted = []
failed = 0
for row in data:
messages = format_to_messages(row, src_fmt)
if messages is None:
failed += 1
continue
result = messages_to_format(messages, to)
if result is None:
failed += 1
continue
converted.append(result)
if not converted:
console.print("[red]All rows failed to convert.[/]")
raise typer.Exit(1)
# Determine output path
if output is None:
output = str(file_path.stem) + f"_{to}.jsonl"
out_path = Path(output)
_write_jsonl(out_path, converted)
console.print(
f"[green]Converted {len(converted)} rows:[/] {src_fmt} -> {to}\n"
f"Output: [bold]{out_path}[/]"
)
if failed > 0:
console.print(f"[yellow]{failed} rows failed to convert.[/]")
@app.command()
def merge(
files: list[str] = typer.Argument(..., help="Paths to dataset files to merge"),
output: str = typer.Option(
"merged.jsonl", "--output", "-o",
help="Output file path",
),
shuffle: bool = typer.Option(False, "--shuffle", help="Shuffle after merging"),
):
"""Merge multiple datasets into a single file."""
all_data: list[dict] = []
for file_str in files:
file_path = Path(file_str)
if not file_path.exists():
console.print(f"[red]File not found: {file_path}[/]")
raise typer.Exit(1)
data = load_raw_data(file_path)
console.print(f"[dim]Loaded {len(data)} rows from {file_path}[/]")
all_data.extend(data)
if not all_data:
console.print("[red]No data loaded from any file.[/]")
raise typer.Exit(1)
if shuffle:
random.shuffle(all_data)
out_path = Path(output)
_write_jsonl(out_path, all_data)
console.print(
f"[green]Merged {len(all_data)} rows from {len(files)} files.[/]\n"
f"Output: [bold]{out_path}[/]"
)
def _row_embed_text(row: dict, field: Optional[str]) -> str:
"""What gets embedded for a row: one field, or all text values joined.
Mirrors the MinHash branch's text selection so ``--field`` means the
same thing for both backends. NOTE: ``soup data topics`` deliberately
picks row text differently — it prefers ``_eval_text.row_text``'s
assistant-turn extraction, because a topic map should cluster on what
the model is taught to SAY, whereas dedup must consider the whole row.
"""
if field:
return str(row.get(field, ""))
return " ".join(str(value) for value in row.values() if value)
def _semantic_dedup(
data: list[dict],
*,
threshold: float,
field: Optional[str],
embed_model: str,
device: str,
out_path: Path,
) -> DedupReport:
"""SemDeDup branch of ``soup data dedup --semantic``."""
texts = [_row_embed_text(row, field) for row in data]
try:
vectors = embed_texts(texts, model_id=embed_model, device=device)
except ImportError:
console.print(
"[red]Semantic dedup needs PyTorch + transformers.[/]\n"
# \[train] is escaped: Rich would otherwise eat the bracket as a
# markup tag and print `pip install "soup-cli"` -- a command that
# installs the package WITHOUT the extra the user is missing.
# Double quotes, not single: cmd.exe cannot strip `'` and pip then
# rejects the requirement outright.
"Install with: [bold]pip install \"soup-cli\\[train]\"[/]"
)
raise typer.Exit(1)
except (ValueError, TypeError) as exc:
from rich.markup import escape as _esc
console.print(f"[red]{_esc(str(exc))}[/]")
raise typer.Exit(1)
report = greedy_semdedup(vectors, threshold=threshold)
unique = [data[idx] for idx in report.kept]
_write_jsonl(out_path, unique)
console.print(
f"[green]Semantic dedup complete:[/] {len(data)} -> {len(unique)} rows "
f"([red]-{len(report.dropped)}[/] near-duplicates)\n"
f"Output: [bold]{out_path}[/]"
)
return report
@app.command()
def dedup(
path: str = typer.Argument(..., help="Path to dataset file"),
output: str = typer.Option(
None, "--output", "-o",
help="Output file path (default: <input>_deduped.jsonl)",
),
threshold: float = typer.Option(
0.8, "--threshold",
help="Similarity threshold (0.0-1.0): MinHash Jaccard by default, "
"embedding cosine under --semantic.",
),
field: str = typer.Option(
None, "--field", "-f",
help="Field to hash/embed (default: all text fields concatenated)",
),
semantic: bool = typer.Option(
False, "--semantic",
help="Use embedding cosine (SemDeDup) instead of MinHash. Catches "
"paraphrases MinHash misses. Requires soup-cli\\[train].",
),
embed_model: str = typer.Option(
DEFAULT_EMBED_MODEL, "--embed-model",
help="Embedding model used by --semantic.",
),
device: str = typer.Option(
"auto", "--device", help="Device for --semantic (auto/cpu/cuda)."
),
):
"""Remove near-duplicate rows: MinHash (default) or embeddings (--semantic).
``--threshold`` is backend-dependent: MinHash Jaccard similarity by
default, embedding cosine under ``--semantic``.
"""
file_path = Path(path)
if not file_path.exists():
console.print(f"[red]File not found: {file_path}[/]")
raise typer.Exit(1)
data = load_raw_data(file_path)
if not data:
console.print("[red]Dataset is empty.[/]")
raise typer.Exit(1)
# Output resolution + containment is shared by BOTH backends.
if output is None:
output = str(file_path.stem) + "_deduped.jsonl"
out_path = Path(output)
if not is_under_cwd(out_path):
console.print(
f"[red]Output path is outside the working directory: {out_path}[/]"
)
raise typer.Exit(1)
if semantic:
console.print(
f"[dim]Semantic dedup of {len(data)} rows "
f"(threshold={threshold}, model={embed_model})...[/]"
)
_semantic_dedup(
data, threshold=threshold, field=field,
embed_model=embed_model, device=device, out_path=out_path,
)
return
# MinHash branch. The import lives HERE, not at the top of the function:
# the semantic path must not require the [data] extra it never uses.
try:
from datasketch import MinHash, MinHashLSH
except ImportError:
console.print(
"[red]datasketch not installed.[/]\n"
"Install with: [bold]pip install \"soup-cli\\[data]\"[/]"
)
raise typer.Exit(1)
console.print(f"[dim]Deduplicating {len(data)} rows (threshold={threshold})...[/]")
# Build MinHash for each row
num_perm = 128
lsh = MinHashLSH(threshold=threshold, num_perm=num_perm)
minhashes = []
for idx, row in enumerate(data):
if field:
text = str(row.get(field, ""))
else:
text = " ".join(str(v) for v in row.values() if v)
words = text.lower().split()
shingles = set()
for i in range(max(1, len(words) - 2)):
shingles.add(" ".join(words[i: i + 3]))
mhash = MinHash(num_perm=num_perm)
for shingle in shingles:
mhash.update(shingle.encode("utf-8"))
minhashes.append(mhash)
try:
lsh.insert(str(idx), mhash)
except ValueError:
pass # duplicate key, already inserted by LSH
# Collect unique indices
seen: set[int] = set()
unique_indices = []
for idx in range(len(data)):
if idx in seen:
continue
unique_indices.append(idx)
results = lsh.query(minhashes[idx])
for dup_idx_str in results:
seen.add(int(dup_idx_str))
unique_data = [data[idx] for idx in unique_indices]
removed = len(data) - len(unique_data)
_write_jsonl(out_path, unique_data)
console.print(
f"[green]Dedup complete:[/] {len(data)} -> {len(unique_data)} rows "
f"([red]-{removed}[/] duplicates)\n"
f"Output: [bold]{out_path}[/]"
)
@app.command(name="filter")
def filter_data(
path: str = typer.Argument(..., help="Path to dataset file"),
output: str = typer.Option(
None, "--output", "-o",
help="Output file path (default: <input>_filtered.jsonl)",
),
perplexity: float = typer.Option(
None, "--perplexity", "--ppl",
help="Max perplexity threshold (rows above this are removed)",
),
coherence: float = typer.Option(
None, "--coherence", "--min-coherence",
help="Min coherence threshold 0.0-1.0 (rows below this are removed)",
),
perplexity_model: str = typer.Option(
"gpt2", "--ppl-model",
help="Model for perplexity scoring (default: gpt2)",
),
field: str = typer.Option(
None, "--field", "-f",
help="Field to score (default: all text fields concatenated)",
),
score_only: bool = typer.Option(
False, "--score-only",
help="Add scores to data without filtering (writes _scored.jsonl)",
),
):
"""Filter dataset by quality: perplexity and/or coherence scoring."""
file_path = Path(path)
if not file_path.exists():
console.print(f"[red]File not found: {file_path}[/]")
raise typer.Exit(1)
if perplexity is None and coherence is None and not score_only:
console.print(
"[red]Specify at least one filter: --perplexity, --coherence, or --score-only[/]"
)
raise typer.Exit(1)
data = load_raw_data(file_path)
if not data:
console.print("[red]Dataset is empty.[/]")
raise typer.Exit(1)
console.print(f"[dim]Scoring {len(data)} rows...[/]")
# Extract texts for scoring
texts = []
for row in data:
if field and field in row:
texts.append(str(row[field]))
else:
texts.append(" ".join(str(v) for v in row.values() if v))
# Compute coherence scores (lightweight, always computed)
from soup_cli.utils.quality import compute_coherence_score
coherence_scores = compute_coherence_score(texts)
# Compute perplexity scores (requires model, only if requested)
perplexity_scores = None
if perplexity is not None or score_only:
try:
from soup_cli.utils.quality import compute_perplexity_scores
console.print(f"[dim]Computing perplexity with {perplexity_model}...[/]")
perplexity_scores = compute_perplexity_scores(
texts, model_name=perplexity_model,
)
except ImportError:
console.print(
"[yellow]torch/transformers not available for perplexity scoring. "
"Skipping perplexity.[/]"
)
if score_only:
# Add scores to each row and write output
scored_data = []
for idx, row in enumerate(data):
scored_row = dict(row)
scored_row["_coherence_score"] = coherence_scores[idx]
if perplexity_scores is not None:
scored_row["_perplexity_score"] = round(perplexity_scores[idx], 2)
scored_data.append(scored_row)
if output is None:
output = str(file_path.stem) + "_scored.jsonl"
out_path = Path(output)
_write_jsonl(out_path, scored_data)
console.print(
f"[green]Scored {len(scored_data)} rows.[/]\n"
f"Output: [bold]{out_path}[/]"
)
return
# Filter
kept = []
removed = []
for idx, row in enumerate(data):
remove = False
if perplexity is not None and perplexity_scores is not None:
if perplexity_scores[idx] > perplexity:
remove = True
if coherence is not None and coherence_scores[idx] < coherence:
remove = True
if remove:
removed.append(row)
else:
kept.append(row)
if output is None:
output = str(file_path.stem) + "_filtered.jsonl"
out_path = Path(output)
_write_jsonl(out_path, kept)
console.print(
f"[green]Filter complete:[/] {len(data)} -> {len(kept)} rows "
f"([red]-{len(removed)}[/] removed)\n"
f"Output: [bold]{out_path}[/]"
)
if perplexity is not None and perplexity_scores is not None:
avg_ppl = sum(perplexity_scores) / len(perplexity_scores)
console.print(f"Avg perplexity: [bold]{avg_ppl:.1f}[/] (threshold: {perplexity})")
if coherence is not None:
avg_coh = sum(coherence_scores) / len(coherence_scores)
console.print(f"Avg coherence: [bold]{avg_coh:.3f}[/] (threshold: {coherence})")
@app.command()
def stats(
path: str = typer.Argument(..., help="Path to dataset file"),
):
"""Extended dataset statistics: length distribution, token counts, languages."""
from soup_cli.data.validator import extended_stats
file_path = Path(path)
if not file_path.exists():
console.print(f"[red]File not found: {file_path}[/]")
raise typer.Exit(1)
data = load_raw_data(file_path)
if not data:
console.print("[red]Dataset is empty.[/]")
raise typer.Exit(1)
ext_stats = extended_stats(data)
# Basic info table
info_table = Table(title=f"Extended Stats: {file_path.name}")
info_table.add_column("Metric", style="bold")
info_table.add_column("Value", justify="right")
info_table.add_row("Total samples", str(ext_stats["total"]))
info_table.add_row("", "")
info_table.add_row("[bold]Length (chars)[/]", "")
info_table.add_row(" p10", str(ext_stats["length_p10"]))
info_table.add_row(" p25", str(ext_stats["length_p25"]))
info_table.add_row(" p50 (median)", str(ext_stats["length_p50"]))
info_table.add_row(" p75", str(ext_stats["length_p75"]))
info_table.add_row(" p90", str(ext_stats["length_p90"]))
info_table.add_row("", "")
info_table.add_row("[bold]Tokens (approx)[/]", "")
info_table.add_row(" Average", str(ext_stats["avg_tokens"]))
info_table.add_row(" Min", str(ext_stats["min_tokens"]))
info_table.add_row(" Max", str(ext_stats["max_tokens"]))
if ext_stats["languages"]:
info_table.add_row("", "")
info_table.add_row("[bold]Languages (sample)[/]", "")
for lang, count in sorted(
ext_stats["languages"].items(), key=lambda x: -x[1]
):
info_table.add_row(f" {lang}", str(count))
console.print(info_table)
# Terminal histogram of lengths
try:
import io
import sys
import plotext as plt
lengths = ext_stats["lengths"]
if lengths:
# Force UTF-8 stdout on Windows to avoid UnicodeEncodeError
# plotext uses box-drawing chars (U+2500 etc.) that cp1251/cp1252 can't encode
original_stdout = sys.stdout
needs_redirect = (
sys.platform == "win32"
and hasattr(sys.stdout, "encoding")
and (sys.stdout.encoding or "").lower().replace("-", "") != "utf8"
)
if needs_redirect:
try:
sys.stdout = io.TextIOWrapper(
sys.stdout.buffer, encoding="utf-8", errors="replace",
)
except AttributeError:
pass # no .buffer (e.g. in tests), keep original
try:
from soup_cli.utils.plotext_compat import render_histogram
render_histogram(
plt,
lengths,
bins=30,
title="Text Length Distribution (chars)",
xlabel="Length",
ylabel="Count",
theme="dark",
)
finally:
sys.stdout = original_stdout
except UnicodeEncodeError:
console.print(
"\n[dim]Histogram skipped (encoding issue).[/] "
"Set PYTHONIOENCODING=utf-8 to enable."
)
except ImportError:
console.print(
"\n[dim]Install plotext for histograms:[/] [bold]pip install plotext[/]"
)
def _show_vision_stats(data: list[dict]) -> None:
"""Show image statistics if dataset contains image fields."""
if not data:
return
# Check if this is a vision dataset
sample = data[0]
if "image" not in sample:
return
total = len(data)
has_image = sum(1 for row in data if row.get("image"))
missing_image = total - has_image
# Collect image file info
extensions: dict[str, int] = {}
existing = 0
for row in data:
img_path = row.get("image", "")
if not img_path:
continue
ext = Path(img_path).suffix.lower()
extensions[ext] = extensions.get(ext, 0) + 1
if Path(img_path).exists():
existing += 1
vision_table = Table(title="Vision Stats")
vision_table.add_column("Metric", style="bold")
vision_table.add_column("Value")
vision_table.add_row("Images referenced", str(has_image))
vision_table.add_row("Missing image field", str(missing_image))
vision_table.add_row("Images found on disk", str(existing))
if extensions:
ext_str = ", ".join(f"{ext} ({count})" for ext, count in sorted(extensions.items()))
vision_table.add_row("Image formats", ext_str)
console.print(vision_table)
def _write_jsonl(path: Path, data: list[dict]) -> None:
"""Write a list of dicts as JSONL."""
with open(path, "w", encoding="utf-8") as f:
for row in data:
f.write(json.dumps(row, ensure_ascii=False) + "\n")
# --- Sampling strategies ---
def _sample_random(data: list[dict], num: int, seed: int | None = None) -> list[dict]:
"""Random sampling without replacement."""
rng = random.Random(seed)
num = min(num, len(data))
return rng.sample(data, num)
def _sample_diverse(
data: list[dict], num: int, seed: int | None = None
) -> list[dict]:
"""Cluster-based diverse sampling using TF-IDF + K-means.
Falls back to random sampling if sklearn is not available.
"""
num = min(num, len(data))
if num >= len(data):
return list(data)
# Extract text representations
texts = [
" ".join(str(val) for val in row.values() if val) for row in data
]
try:
from sklearn.cluster import MiniBatchKMeans
from sklearn.feature_extraction.text import TfidfVectorizer
vectorizer = TfidfVectorizer(max_features=1000, stop_words="english")
tfidf_matrix = vectorizer.fit_transform(texts)
num_clusters = min(num, len(data))
kmeans = MiniBatchKMeans(
n_clusters=num_clusters, random_state=seed or 0, n_init=3
)
labels = kmeans.fit_predict(tfidf_matrix)
# Sample one item from each cluster (index-based dedup)
chosen_indices: list[int] = []
rng = random.Random(seed)
for cluster_id in range(num_clusters):
cluster_indices = [
idx for idx, label in enumerate(labels) if label == cluster_id
]
if cluster_indices:
chosen_indices.append(rng.choice(cluster_indices))
sampled = [data[idx] for idx in chosen_indices]
# If we need more, fill randomly from remaining
if len(sampled) < num:
remaining_indices = list(set(range(len(data))) - set(chosen_indices))
extra_indices = rng.sample(
remaining_indices, min(num - len(sampled), len(remaining_indices))
)
sampled.extend(data[idx] for idx in extra_indices)
return sampled[:num]
except ImportError:
# Fallback: simple length-based diversity (bucket by text length)
rng = random.Random(seed)
indexed = [(idx, len(texts[idx])) for idx in range(len(data))]
indexed.sort(key=lambda pair: pair[1])
# Evenly spaced picks across sorted list
step = max(1, len(indexed) // num)
picked_indices = [
indexed[idx * step][0] for idx in range(min(num, len(indexed)))
]
picked = [data[idx] for idx in picked_indices]
# Fill remainder randomly
if len(picked) < num:
remaining_indices = list(set(range(len(data))) - set(picked_indices))
extra_indices = rng.sample(
remaining_indices, min(num - len(picked), len(remaining_indices))
)
picked.extend(data[idx] for idx in extra_indices)
return picked[:num]
def _sample_hard(data: list[dict], num: int) -> list[dict]:
"""Sample hardest examples by text length (proxy for complexity).
Longer texts tend to be more complex / challenging.
"""
num = min(num, len(data))
if num >= len(data):
return list(data)
# Score by total text length (proxy for difficulty)
scored = []
for row in data:
text_len = sum(len(str(val)) for val in row.values() if val)
scored.append((text_len, row))
# Sort by length descending, take top N
scored.sort(key=lambda pair: pair[0], reverse=True)
return [row for _, row in scored[:num]]
@app.command(name="sample")
def sample_data(
path: str = typer.Argument(..., help="Path to dataset file"),
output: str = typer.Option(
None, "--output", "-o",
help="Output file path (default: <input>_sampled.jsonl)",
),
num: int = typer.Option(
None, "--n", "-n",
help="Number of samples to select",
),
pct: float = typer.Option(
None, "--pct",
help="Percentage of dataset to sample (0-100)",
),
strategy: str = typer.Option(
"random", "--strategy", "-s",
help="Sampling strategy: random, diverse (TF-IDF + clusters), hard (by length)",
),
seed: int = typer.Option(
None, "--seed",
help="Random seed for reproducibility",
),
):
"""Sample a subset of a dataset using various strategies."""
file_path = Path(path)
if not file_path.exists():
console.print(f"[red]File not found: {file_path}[/]")
raise typer.Exit(1)
if num is None and pct is None:
console.print("[red]Specify either --n (count) or --pct (percentage).[/]")
raise typer.Exit(1)
if strategy not in ("random", "diverse", "hard"):
console.print(
f"[red]Unknown strategy: {strategy}[/]\n"
"Supported: [bold]random[/], [bold]diverse[/], [bold]hard[/]"
)
raise typer.Exit(1)
data = load_raw_data(file_path)
if not data:
console.print("[red]Dataset is empty.[/]")
raise typer.Exit(1)
# Compute sample count
if pct is not None:
sample_count = max(1, int(len(data) * pct / 100))
else:
sample_count = num
# Apply strategy
if strategy == "random":
sampled = _sample_random(data, sample_count, seed=seed)
elif strategy == "diverse":
sampled = _sample_diverse(data, sample_count, seed=seed)
elif strategy == "hard":
sampled = _sample_hard(data, sample_count)
else:
sampled = _sample_random(data, sample_count, seed=seed)
# Resolve output path (with path traversal protection on explicit --output)
# v0.40.1 Part E — include the strategy in the default filename so
# successive `random` / `diverse` / `hard` runs don't silently overwrite
# each other.
if output is None:
out_path = file_path.parent / f"{file_path.stem}_sampled_{strategy}.jsonl"
else:
from soup_cli.utils.paths import is_under_cwd
out_path = Path(output).resolve()
# realpath + commonpath (is_under_cwd) — Path.resolve()+relative_to()
# breaks on Windows 8.3 short names.
if not is_under_cwd(output):
console.print("[red]Output path must be under the current working directory.[/]")
raise typer.Exit(1)
_write_jsonl(out_path, sampled)
console.print(
f"[green]Sampled {len(sampled)} rows[/] from {len(data)} "
f"(strategy: {strategy})\n"
f"Output: [bold]{out_path}[/]"
)
@app.command(name="split")
def split_data(
path: str = typer.Argument(..., help="Path to dataset file"),
val: int = typer.Option(
None, "--val",
help="Validation split: percentage (default) or absolute count (with --absolute)",
),
test: int = typer.Option(
None, "--test",
help="Test split: percentage (default) or absolute count (with --absolute)",
),
train: int = typer.Option(
None, "--train",
help=(
"Train split (informational; the train remainder is implied by "
"--val + --test). Accepted for command parity."
),
),
absolute: bool = typer.Option(
False, "--absolute",
help="Treat --val/--test as absolute sample counts instead of percentages",
),
seed: int = typer.Option(
None, "--seed",
help="Random seed for reproducible splits",
),
stratify: str = typer.Option(
None, "--stratify",
help="Field name for stratified splitting (preserves category distribution)",
),
stratify_semantic: bool = typer.Option(
False, "--stratify-semantic",
help=(
"Use semantic clustering (TF-IDF + K-Means) to perform stratified "
"splitting without requiring a category field"
),
),
num_clusters: Optional[int] = typer.Option(
None, "--num-clusters",
help="Number of semantic clusters to use for semantic stratified splitting (default: 5)",
),
):
"""Split dataset into train/val/test files."""
file_path = Path(path)
if not file_path.exists():
console.print(f"[red]File not found: {file_path}[/]")
raise typer.Exit(1)
if val is None and test is None:
console.print("[red]Specify at least one of --val or --test.[/]")
raise typer.Exit(1)
# Reject negatives: a negative val/test slipped past the `>= total` check
# and produced a negative slice (e.g. --val -10 sent 90 rows to val, 10 to
# train — a silently inverted split).
if (val is not None and val < 0) or (test is not None and test < 0):
console.print("[red]--val and --test must be non-negative.[/]")
raise typer.Exit(1)
if stratify and stratify_semantic:
console.print("[red]Cannot use --stratify and --stratify-semantic together. Pick one.[/]")
raise typer.Exit(1)
if num_clusters is not None and num_clusters <= 0:
console.print("[red]--num-clusters must be a positive integer.[/]")
raise typer.Exit(1)
if not stratify_semantic and num_clusters is not None:
console.print(
"[yellow]Warning: --num-clusters was passed but --stratify-semantic is not enabled. "
"It will have no effect.[/]"
)
data = load_raw_data(file_path)
if not data:
console.print("[red]Dataset is empty.[/]")
raise typer.Exit(1)
total = len(data)
# Calculate split sizes
if absolute:
val_count = val or 0
test_count = test or 0
if val_count + test_count >= total:
console.print(
f"[red]val ({val_count}) + test ({test_count}) >= dataset size ({total}).[/]"
)
raise typer.Exit(1)
else:
val_count = int(total * val / 100) if val else 0
test_count = int(total * test / 100) if test else 0
if val_count + test_count >= total:
console.print(
f"[red]Split sizes ({val_count} + {test_count}) >= dataset size ({total}).[/]"
)
raise typer.Exit(1)
# Perform split
if stratify:
train_data, val_data, test_data = _stratified_split(
data, val_count, test_count, stratify, seed=seed,
)
elif stratify_semantic:
resolved_clusters = num_clusters or 5
labels = _get_semantic_labels(data, resolved_clusters, seed=seed)
train_data, val_data, test_data = _stratified_split(
data, val_count, test_count, labels, seed=seed,
)
else:
train_data, val_data, test_data = _random_split(
data, val_count, test_count, seed=seed,
)
# Write output files
stem = file_path.stem
parent = file_path.parent
train_path = parent / f"{stem}_train.jsonl"
_write_jsonl(train_path, train_data)