File size: 32,689 Bytes
f440f03 | 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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 | """Tests HuggingFace datasets ielādēm."""
from __future__ import annotations
import json
import os
import subprocess
import sys
import types
from pathlib import Path
import pytest
import maris_core.data.datasets as datasets_module
from maris_core.data.datasets import HFDatasetError, _find_snapshot_data_files, load_hf_dataset
from maris_core.data.preprocessing import record_to_training_text
from maris_core.data.validator import DatasetValidationError, validate_dataset_dir
from maris_core.training.train import train
REPO_ID = "MarisUK/maris-ai-memory"
REPO_ROOT = Path(__file__).resolve().parents[2]
class FakeGeneratedDataset(list):
@classmethod
def from_generator(cls, generator):
return cls(list(generator()))
class FakeDatasetDict(dict):
pass
@pytest.mark.parametrize(
"error_message",
[
"The directory doesn't contain any data files",
f"No (supported) data files found in {REPO_ID}",
],
)
def test_load_hf_dataset_falls_back_to_snapshot_for_nested_jsonl_files(
monkeypatch,
tmp_path: Path,
error_message: str,
) -> None:
repo_id = REPO_ID
snapshot_dir = tmp_path / "snapshot"
data_file = snapshot_dir / "data" / "conversation" / "sample.jsonl"
data_file.parent.mkdir(parents=True)
data_file.write_text(
json.dumps({"user": "Sveiki", "assistant": "Sveiks!"}, ensure_ascii=False) + "\n",
encoding="utf-8",
)
calls: list[tuple[object, object, object]] = []
class EmptyDatasetError(Exception):
pass
def fake_load_dataset(path, *args, **kwargs):
calls.append((path, args, kwargs))
if path == repo_id:
raise EmptyDatasetError(error_message)
if path == "json":
return {"train": [str(data_file)]}
raise AssertionError(f"Unexpected load_dataset call: {path!r}")
def fake_snapshot_download(**kwargs):
assert kwargs["repo_id"] == repo_id
assert kwargs["repo_type"] == "dataset"
return str(snapshot_dir)
monkeypatch.setitem(
sys.modules,
"datasets",
types.SimpleNamespace(
Dataset=FakeGeneratedDataset,
DatasetDict=FakeDatasetDict,
load_dataset=fake_load_dataset,
),
)
monkeypatch.setitem(
sys.modules,
"huggingface_hub",
types.SimpleNamespace(snapshot_download=fake_snapshot_download),
)
monkeypatch.delenv("HF_TOKEN", raising=False)
dataset = load_hf_dataset(repo_id)
assert list(dataset["train"]) == [
{"text": record_to_training_text({"user": "Sveiki", "assistant": "Sveiks!"})}
]
assert calls == [(repo_id, (), {"token": None})]
def test_load_hf_dataset_falls_back_for_wrapped_dataset_generation_error(
monkeypatch,
tmp_path: Path,
) -> None:
repo_id = REPO_ID
snapshot_dir = tmp_path / "snapshot"
data_file = snapshot_dir / "data" / "conversation" / "sample.jsonl"
data_file.parent.mkdir(parents=True)
data_file.write_text(
json.dumps({"user": "Sveiki", "assistant": "Sveiks!"}, ensure_ascii=False) + "\n",
encoding="utf-8",
)
calls: list[tuple[object, object, object]] = []
class EmptyDatasetError(Exception):
pass
class DatasetGenerationError(Exception):
pass
def fake_load_dataset(path, *args, **kwargs):
calls.append((path, args, kwargs))
if path == repo_id:
try:
raise EmptyDatasetError(f"No (supported) data files found in {repo_id}")
except EmptyDatasetError as source_exc:
raise DatasetGenerationError(
"An error occurred while generating the dataset"
) from source_exc
if path == "json":
return {"train": [str(data_file)]}
raise AssertionError(f"Unexpected load_dataset call: {path!r}")
def fake_snapshot_download(**kwargs):
assert kwargs["repo_id"] == repo_id
assert kwargs["repo_type"] == "dataset"
return str(snapshot_dir)
monkeypatch.setitem(
sys.modules,
"datasets",
types.SimpleNamespace(
Dataset=FakeGeneratedDataset,
DatasetDict=FakeDatasetDict,
load_dataset=fake_load_dataset,
),
)
monkeypatch.setitem(
sys.modules,
"huggingface_hub",
types.SimpleNamespace(snapshot_download=fake_snapshot_download),
)
monkeypatch.delenv("HF_TOKEN", raising=False)
dataset = load_hf_dataset(repo_id)
assert list(dataset["train"]) == [
{"text": record_to_training_text({"user": "Sveiki", "assistant": "Sveiks!"})}
]
assert calls == [(repo_id, (), {"token": None})]
@pytest.mark.parametrize(
"error_message",
[
"An error occurred while generating the dataset",
"Dataset generation failed in a different way",
],
)
def test_load_hf_dataset_falls_back_for_generic_dataset_generation_error(
monkeypatch,
tmp_path: Path,
error_message: str,
) -> None:
repo_id = REPO_ID
snapshot_dir = tmp_path / "snapshot"
data_file = snapshot_dir / "data" / "conversation" / "sample.jsonl"
data_file.parent.mkdir(parents=True)
data_file.write_text(
json.dumps({"user": "Sveiki", "assistant": "Sveiks!"}, ensure_ascii=False) + "\n",
encoding="utf-8",
)
calls: list[tuple[object, object, object]] = []
class DatasetGenerationError(Exception):
pass
def fake_load_dataset(path, *args, **kwargs):
calls.append((path, args, kwargs))
if path == repo_id:
raise DatasetGenerationError(error_message)
raise AssertionError(f"Unexpected load_dataset call: {path!r}")
def fake_snapshot_download(**kwargs):
assert kwargs["repo_id"] == repo_id
assert kwargs["repo_type"] == "dataset"
return str(snapshot_dir)
monkeypatch.setitem(
sys.modules,
"datasets",
types.SimpleNamespace(
Dataset=FakeGeneratedDataset,
DatasetDict=FakeDatasetDict,
load_dataset=fake_load_dataset,
),
)
monkeypatch.setitem(
sys.modules,
"huggingface_hub",
types.SimpleNamespace(snapshot_download=fake_snapshot_download),
)
monkeypatch.delenv("HF_TOKEN", raising=False)
dataset = load_hf_dataset(repo_id)
assert list(dataset["train"]) == [
{"text": record_to_training_text({"user": "Sveiki", "assistant": "Sveiks!"})}
]
assert calls == [(repo_id, (), {"token": None})]
def test_load_hf_dataset_falls_back_for_schema_cast_error(monkeypatch, tmp_path: Path) -> None:
repo_id = REPO_ID
snapshot_dir = tmp_path / "snapshot"
first_file = snapshot_dir / "data" / "image" / "sample-1.jsonl"
second_file = snapshot_dir / "data" / "image" / "sample-2.jsonl"
first_file.parent.mkdir(parents=True)
first_file.write_text(
json.dumps(
{
"timestamp": "2026-03-30T12:05:00Z",
"prompt": "A",
"metadata": {"style": "cinematic"},
},
ensure_ascii=False,
)
+ "\n",
encoding="utf-8",
)
second_file.write_text(
json.dumps(
{
"timestamp": "2026-03-30T12:06:00Z",
"prompt": "B",
"metadata": {"image_b64": "..."},
},
ensure_ascii=False,
)
+ "\n",
encoding="utf-8",
)
calls: list[tuple[object, object, object]] = []
class DatasetGenerationError(Exception):
pass
def fake_load_dataset(path, *args, **kwargs):
calls.append((path, args, kwargs))
if path == repo_id:
try:
raise TypeError(
"Couldn't cast array of type\nstruct<image_b64: string>\nto\n{'style': Value('string')}"
)
except TypeError as source_exc:
raise DatasetGenerationError(
"An error occurred while generating the dataset"
) from source_exc
raise AssertionError(f"Unexpected load_dataset call: {path!r}")
def fake_snapshot_download(**kwargs):
assert kwargs["repo_id"] == repo_id
assert kwargs["repo_type"] == "dataset"
return str(snapshot_dir)
monkeypatch.setitem(
sys.modules,
"datasets",
types.SimpleNamespace(
Dataset=FakeGeneratedDataset,
DatasetDict=FakeDatasetDict,
load_dataset=fake_load_dataset,
),
)
monkeypatch.setitem(
sys.modules,
"huggingface_hub",
types.SimpleNamespace(snapshot_download=fake_snapshot_download),
)
monkeypatch.delenv("HF_TOKEN", raising=False)
dataset = load_hf_dataset(repo_id)
assert list(dataset["train"]) == [
{
"text": record_to_training_text(
{
"timestamp": "2026-03-30T12:05:00Z",
"prompt": "A",
"metadata": {"style": "cinematic"},
}
)
},
{
"text": record_to_training_text(
{
"timestamp": "2026-03-30T12:06:00Z",
"prompt": "B",
"metadata": {"image_b64": "..."},
}
)
},
]
assert calls == [(repo_id, (), {"token": None})]
def test_load_hf_dataset_downloads_repo_data_files_when_snapshot_cache_is_incomplete(
monkeypatch,
tmp_path: Path,
) -> None:
repo_id = REPO_ID
snapshot_dir = tmp_path / "snapshot"
snapshot_dir.mkdir()
(snapshot_dir / "README.md").write_text("metadata only", encoding="utf-8")
data_file = snapshot_dir / "data" / "conversation" / "sample.jsonl"
calls: list[tuple[object, object, object]] = []
snapshot_calls: list[dict[str, object]] = []
class EmptyDatasetError(Exception):
pass
class FakeHfApi:
def __init__(self, *, token):
self.token = token
def list_repo_files(self, *, repo_id, repo_type):
assert repo_id == REPO_ID
assert repo_type == "dataset"
return ["README.md", "data/conversation/sample.jsonl"]
def fake_load_dataset(path, *args, **kwargs):
calls.append((path, args, kwargs))
if path == repo_id:
raise EmptyDatasetError("The directory doesn't contain any data files")
if path == "json":
return {"train": [str(data_file)]}
raise AssertionError(f"Unexpected load_dataset call: {path!r}")
def fake_snapshot_download(**kwargs):
snapshot_calls.append(kwargs)
if kwargs.get("allow_patterns"):
data_file.parent.mkdir(parents=True, exist_ok=True)
data_file.write_text(
json.dumps({"user": "Sveiki", "assistant": "Sveiks!"}, ensure_ascii=False) + "\n",
encoding="utf-8",
)
return str(snapshot_dir)
monkeypatch.setitem(
sys.modules,
"datasets",
types.SimpleNamespace(
Dataset=FakeGeneratedDataset,
DatasetDict=FakeDatasetDict,
load_dataset=fake_load_dataset,
),
)
monkeypatch.setitem(
sys.modules,
"huggingface_hub",
types.SimpleNamespace(
HfApi=FakeHfApi,
snapshot_download=fake_snapshot_download,
),
)
monkeypatch.delenv("HF_TOKEN", raising=False)
dataset = load_hf_dataset(repo_id)
assert list(dataset["train"]) == [
{"text": record_to_training_text({"user": "Sveiki", "assistant": "Sveiks!"})}
]
assert calls == [(repo_id, (), {"token": None})]
assert snapshot_calls == [
{"repo_id": repo_id, "repo_type": "dataset", "token": None},
{
"repo_id": repo_id,
"repo_type": "dataset",
"token": None,
"allow_patterns": ["data/conversation/sample.jsonl"],
},
]
def test_load_hf_dataset_raises_when_snapshot_contains_no_supported_files(
monkeypatch,
tmp_path: Path,
) -> None:
repo_id = REPO_ID
snapshot_dir = tmp_path / "snapshot"
snapshot_dir.mkdir()
(snapshot_dir / ".gitattributes").write_text("*.jsonl filter=lfs", encoding="utf-8")
class EmptyDatasetError(Exception):
pass
class FakeHfApi:
def __init__(self, *, token):
self.token = token
def list_repo_files(self, *, repo_id, repo_type):
assert repo_id == REPO_ID
assert repo_type == "dataset"
return [".gitattributes"]
def fake_load_dataset(path, *args, **kwargs):
if path == repo_id:
raise EmptyDatasetError("The directory doesn't contain any data files")
raise AssertionError(f"Unexpected load_dataset call: {path!r}")
def fake_snapshot_download(**kwargs):
return str(snapshot_dir)
monkeypatch.setitem(
sys.modules,
"datasets",
types.SimpleNamespace(load_dataset=fake_load_dataset),
)
monkeypatch.setitem(
sys.modules,
"huggingface_hub",
types.SimpleNamespace(HfApi=FakeHfApi, snapshot_download=fake_snapshot_download),
)
try:
load_hf_dataset(repo_id)
except HFDatasetError as exc:
assert "nesatur nevienu atbalstītu datu failu" in str(exc)
assert "data/conversation/bootstrap.jsonl" in str(exc)
assert ".gitattributes" in str(exc)
assert "Git LFS" in str(exc)
else:
raise AssertionError("load_hf_dataset() should fail when snapshot has no supported files")
def test_load_hf_dataset_raises_when_repo_lists_data_files_but_snapshot_stays_empty(
monkeypatch,
tmp_path: Path,
) -> None:
repo_id = REPO_ID
snapshot_dir = tmp_path / "snapshot"
snapshot_dir.mkdir()
(snapshot_dir / ".gitattributes").write_text("*.jsonl filter=lfs", encoding="utf-8")
class EmptyDatasetError(Exception):
pass
class FakeHfApi:
def __init__(self, *, token):
self.token = token
def list_repo_files(self, *, repo_id, repo_type):
assert repo_id == REPO_ID
assert repo_type == "dataset"
return ["data/conversation/sample.jsonl"]
def fake_load_dataset(path, *args, **kwargs):
if path == repo_id:
raise EmptyDatasetError("The directory doesn't contain any data files")
raise AssertionError(f"Unexpected load_dataset call: {path!r}")
def fake_snapshot_download(**kwargs):
return str(snapshot_dir)
monkeypatch.setitem(
sys.modules,
"datasets",
types.SimpleNamespace(load_dataset=fake_load_dataset),
)
monkeypatch.setitem(
sys.modules,
"huggingface_hub",
types.SimpleNamespace(HfApi=FakeHfApi, snapshot_download=fake_snapshot_download),
)
with pytest.raises(HFDatasetError) as excinfo:
load_hf_dataset(repo_id)
message = str(excinfo.value)
assert "satur atbalstītus datu failus" in message
assert "data/conversation/sample.jsonl" in message
assert ".gitattributes" in message
def test_load_hf_dataset_retries_direct_load_with_fallback_cache_dir(
monkeypatch,
tmp_path: Path,
) -> None:
repo_id = REPO_ID
fallback_cache_dir = tmp_path / "hf-cache"
calls: list[tuple[object, object, object]] = []
class CacheLockError(OSError):
pass
def fake_load_dataset(path, *args, **kwargs):
calls.append((path, args, kwargs))
if path != repo_id:
raise AssertionError(f"Unexpected load_dataset call: {path!r}")
if "cache_dir" not in kwargs:
raise CacheLockError(
5,
"Input/output error",
"/data/.cache/huggingface/hub/.locks/datasets--MarisUK--maris-ai-memory/test.lock",
)
return FakeDatasetDict({"train": [{"text": "ok"}]})
monkeypatch.setitem(
sys.modules,
"datasets",
types.SimpleNamespace(
Dataset=FakeGeneratedDataset,
DatasetDict=FakeDatasetDict,
load_dataset=fake_load_dataset,
),
)
monkeypatch.setenv("MARIS_HF_FALLBACK_CACHE_DIR", str(fallback_cache_dir))
monkeypatch.delenv("HF_TOKEN", raising=False)
dataset = load_hf_dataset(repo_id)
assert list(dataset["train"]) == [{"text": "ok"}]
assert calls == [
(repo_id, (), {"token": None}),
(repo_id, (), {"token": None, "cache_dir": str(fallback_cache_dir)}),
]
assert fallback_cache_dir.is_dir()
def test_load_hf_dataset_retries_snapshot_download_with_fallback_cache_dir(
monkeypatch,
tmp_path: Path,
) -> None:
repo_id = REPO_ID
fallback_cache_dir = tmp_path / "hf-cache"
snapshot_dir = tmp_path / "snapshot"
data_file = snapshot_dir / "data" / "conversation" / "sample.csv"
data_file.parent.mkdir(parents=True)
data_file.write_text("user,assistant\nSveiki,Sveiks!\n", encoding="utf-8")
load_calls: list[tuple[object, object, object]] = []
snapshot_calls: list[dict[str, object]] = []
class EmptyDatasetError(Exception):
pass
class CacheLockError(OSError):
pass
def fake_load_dataset(path, *args, **kwargs):
load_calls.append((path, args, kwargs))
if path == repo_id:
raise EmptyDatasetError("The directory doesn't contain any data files")
if path == "csv":
assert kwargs["cache_dir"] == str(fallback_cache_dir)
return FakeDatasetDict({"train": [{"text": "ok"}]})
raise AssertionError(f"Unexpected load_dataset call: {path!r}")
def fake_snapshot_download(**kwargs):
snapshot_calls.append(kwargs)
if "cache_dir" not in kwargs:
raise CacheLockError(
5,
"Input/output error",
"/data/.cache/huggingface/hub/.locks/datasets--MarisUK--maris-ai-memory/test.lock",
)
return str(snapshot_dir)
monkeypatch.setitem(
sys.modules,
"datasets",
types.SimpleNamespace(
Dataset=FakeGeneratedDataset,
DatasetDict=FakeDatasetDict,
load_dataset=fake_load_dataset,
),
)
monkeypatch.setitem(
sys.modules,
"huggingface_hub",
types.SimpleNamespace(snapshot_download=fake_snapshot_download),
)
monkeypatch.setenv("MARIS_HF_FALLBACK_CACHE_DIR", str(fallback_cache_dir))
monkeypatch.delenv("HF_TOKEN", raising=False)
dataset = load_hf_dataset(repo_id)
assert list(dataset["train"]) == [{"text": "ok"}]
assert load_calls == [
(repo_id, (), {"token": None}),
(
"csv",
(),
{"data_files": {"train": [str(data_file)]}, "cache_dir": str(fallback_cache_dir)},
),
]
assert snapshot_calls == [
{"repo_id": repo_id, "repo_type": "dataset", "token": None},
{
"repo_id": repo_id,
"repo_type": "dataset",
"token": None,
"cache_dir": str(fallback_cache_dir),
},
]
assert fallback_cache_dir.is_dir()
def test_find_snapshot_data_files_skips_walk_os_errors(
monkeypatch,
tmp_path: Path,
) -> None:
snapshot_dir = tmp_path / "snapshot"
data_file = snapshot_dir / "data" / "conversation" / "sample.jsonl"
data_file.parent.mkdir(parents=True)
data_file.write_text(
json.dumps({"user": "Sveiki", "assistant": "Sveiks!"}, ensure_ascii=False) + "\n",
encoding="utf-8",
)
def fake_walk(
path: str | os.PathLike[str],
*,
topdown: bool = True,
onerror: object | None = None,
followlinks: bool = False,
):
assert Path(path) == snapshot_dir / "data"
assert topdown is True
assert followlinks is False
walk_error = OSError(22, "Invalid argument")
walk_error.filename = "/proc/19/task/19/net"
if onerror is not None:
onerror(walk_error)
yield (os.fspath(data_file.parent), [], [data_file.name])
monkeypatch.setattr(datasets_module.os, "walk", fake_walk)
dataset_format, data_files = _find_snapshot_data_files(snapshot_dir)
assert dataset_format == "json"
assert data_files == [str(data_file)]
def test_load_hf_dataset_rejects_filesystem_root_snapshot(monkeypatch) -> None:
repo_id = REPO_ID
class EmptyDatasetError(Exception):
pass
def fake_load_dataset(path: str, *args: object, **kwargs: object):
del args, kwargs
if path == repo_id:
raise EmptyDatasetError("The directory doesn't contain any data files")
raise AssertionError(f"Unexpected load_dataset call: {path!r}")
def fake_snapshot_download(**kwargs: object) -> str:
assert kwargs["repo_id"] == repo_id
assert kwargs["repo_type"] == "dataset"
return "/"
monkeypatch.setitem(
sys.modules,
"datasets",
types.SimpleNamespace(load_dataset=fake_load_dataset),
)
monkeypatch.setitem(
sys.modules,
"huggingface_hub",
types.SimpleNamespace(snapshot_download=fake_snapshot_download),
)
with pytest.raises(HFDatasetError, match="nav droša rekursīvai skenēšanai"):
load_hf_dataset(repo_id)
def test_load_hf_dataset_merges_named_splits_into_train(monkeypatch) -> None:
repo_id = REPO_ID
calls: list[tuple[object, object, object]] = []
def fake_load_dataset(path, *args, **kwargs):
calls.append((path, args, kwargs))
if path == repo_id:
return {
"conversation": [{"user": "Sveiki", "assistant": "Labdien"}],
"image": [{"prompt": "Uzzīmē kaķi", "metadata": {"style": "anime"}}],
}
raise AssertionError(f"Unexpected load_dataset call: {path!r}")
monkeypatch.setitem(
sys.modules,
"datasets",
types.SimpleNamespace(
Dataset=FakeGeneratedDataset,
DatasetDict=FakeDatasetDict,
load_dataset=fake_load_dataset,
),
)
monkeypatch.delenv("HF_TOKEN", raising=False)
dataset = load_hf_dataset(repo_id)
assert list(dataset["train"]) == [
{"text": record_to_training_text({"user": "Sveiki", "assistant": "Labdien"})},
{
"text": record_to_training_text(
{"prompt": "Uzzīmē kaķi", "metadata": {"style": "anime"}}
)
},
]
assert calls == [(repo_id, (), {"token": None})]
def test_load_hf_dataset_fallback_normalizes_mixed_top_level_keys_to_text(
monkeypatch,
tmp_path: Path,
) -> None:
repo_id = REPO_ID
snapshot_dir = tmp_path / "snapshot"
first_file = snapshot_dir / "data" / "autonomous" / "sample-1.jsonl"
second_file = snapshot_dir / "data" / "autonomous" / "sample-2.jsonl"
first_file.parent.mkdir(parents=True)
first_file.write_text(
json.dumps(
{
"timestamp": "2026-03-30T12:05:00Z",
"prompt": "Izveido plānu",
"metadata": {"priority": "high"},
},
ensure_ascii=False,
)
+ "\n",
encoding="utf-8",
)
second_file.write_text(
json.dumps(
{
"timestamp": "2026-03-30T12:06:00Z",
"workflow": {"name": "planner", "step": 2},
"metadata": {"status": "running"},
},
ensure_ascii=False,
)
+ "\n",
encoding="utf-8",
)
class DatasetGenerationError(Exception):
pass
class EmptyDatasetError(Exception):
pass
class SchemaCheckingDataset(list):
@classmethod
def from_generator(cls, generator):
rows = list(generator())
if any(set(row) != {"text"} for row in rows):
raise DatasetGenerationError("generator output schema is not stable")
return cls(rows)
def fake_load_dataset(path, *args, **kwargs):
if path == repo_id:
try:
raise TypeError(
"Couldn't cast\n"
"timestamp: timestamp[s]\n"
"prompt: string\n"
"metadata: struct\n"
"| 'workflow'"
)
except TypeError as source_exc:
raise DatasetGenerationError(
"An error occurred while generating the dataset"
) from source_exc
raise AssertionError(f"Unexpected load_dataset call: {path!r}")
def fake_snapshot_download(**kwargs):
assert kwargs["repo_id"] == repo_id
assert kwargs["repo_type"] == "dataset"
return str(snapshot_dir)
monkeypatch.setitem(
sys.modules,
"datasets",
types.SimpleNamespace(
Dataset=SchemaCheckingDataset,
DatasetDict=FakeDatasetDict,
load_dataset=fake_load_dataset,
),
)
monkeypatch.setitem(
sys.modules,
"huggingface_hub",
types.SimpleNamespace(snapshot_download=fake_snapshot_download),
)
monkeypatch.delenv("HF_TOKEN", raising=False)
dataset = load_hf_dataset(repo_id)
assert list(dataset["train"]) == [
{
"text": record_to_training_text(
{
"timestamp": "2026-03-30T12:05:00Z",
"prompt": "Izveido plānu",
"metadata": {"priority": "high"},
}
)
},
{
"text": record_to_training_text(
{
"timestamp": "2026-03-30T12:06:00Z",
"workflow": {"name": "planner", "step": 2},
"metadata": {"status": "running"},
}
)
},
]
def test_load_hf_dataset_raises_actionable_error_for_invalid_snapshot_jsonl(
monkeypatch,
tmp_path: Path,
) -> None:
repo_id = REPO_ID
snapshot_dir = tmp_path / "snapshot"
data_file = snapshot_dir / "data" / "conversation" / "broken.jsonl"
data_file.parent.mkdir(parents=True)
data_file.write_text('{"user":"Sveiki"}\n{"assistant":\n', encoding="utf-8")
class DatasetGenerationError(Exception):
pass
class FakeGeneratedDatasetWithWrapper(list):
@classmethod
def from_generator(cls, generator):
try:
return cls(list(generator()))
except Exception as source_exc: # noqa: BLE001
raise DatasetGenerationError(
"An error occurred while generating the dataset"
) from source_exc
class FakeDatasetDict(dict):
pass
class EmptyDatasetError(Exception):
pass
def fake_load_dataset(path, *args, **kwargs):
if path == repo_id:
raise EmptyDatasetError("The directory doesn't contain any data files")
raise AssertionError(f"Unexpected load_dataset call: {path!r}")
def fake_snapshot_download(**kwargs):
assert kwargs["repo_id"] == repo_id
assert kwargs["repo_type"] == "dataset"
return str(snapshot_dir)
monkeypatch.setitem(
sys.modules,
"datasets",
types.SimpleNamespace(
Dataset=FakeGeneratedDatasetWithWrapper,
DatasetDict=FakeDatasetDict,
load_dataset=fake_load_dataset,
),
)
monkeypatch.setitem(
sys.modules,
"huggingface_hub",
types.SimpleNamespace(snapshot_download=fake_snapshot_download),
)
monkeypatch.delenv("HF_TOKEN", raising=False)
with pytest.raises(HFDatasetError) as excinfo:
load_hf_dataset(repo_id)
message = str(excinfo.value)
assert "datu failus neizdevās nolasīt apmācībai" in message
assert "data/conversation/broken.jsonl" in message
assert "An error occurred while generating the dataset" in message
def test_load_hf_dataset_raises_actionable_error_for_invalid_snapshot_csv(
monkeypatch,
tmp_path: Path,
) -> None:
repo_id = REPO_ID
snapshot_dir = tmp_path / "snapshot"
data_file = snapshot_dir / "data" / "conversation" / "broken.csv"
data_file.parent.mkdir(parents=True)
data_file.write_text("user,assistant\nSveiki,Labdien\n", encoding="utf-8")
class DatasetGenerationError(Exception):
pass
class EmptyDatasetError(Exception):
pass
def fake_load_dataset(path, *args, **kwargs):
if path == repo_id:
raise EmptyDatasetError("The directory doesn't contain any data files")
if path == "csv":
raise DatasetGenerationError("An error occurred while generating the dataset")
raise AssertionError(f"Unexpected load_dataset call: {path!r}")
def fake_snapshot_download(**kwargs):
assert kwargs["repo_id"] == repo_id
assert kwargs["repo_type"] == "dataset"
return str(snapshot_dir)
monkeypatch.setitem(
sys.modules,
"datasets",
types.SimpleNamespace(load_dataset=fake_load_dataset),
)
monkeypatch.setitem(
sys.modules,
"huggingface_hub",
types.SimpleNamespace(snapshot_download=fake_snapshot_download),
)
monkeypatch.delenv("HF_TOKEN", raising=False)
with pytest.raises(HFDatasetError) as excinfo:
load_hf_dataset(repo_id)
message = str(excinfo.value)
assert "datu failus neizdevās nolasīt apmācībai" in message
assert "data/conversation/broken.csv" in message
assert "An error occurred while generating the dataset" in message
def test_train_exits_with_actionable_message_when_dataset_repo_is_empty(monkeypatch) -> None:
message = (
"HF dataset repo MarisUK/maris-ai-memory pašlaik nesatur nevienu atbalstītu datu failu "
"(.jsonl, .json, .csv, .parquet)."
)
monkeypatch.setattr(
"maris_core.training.train.load_hf_dataset",
lambda repo_id: (_ for _ in ()).throw(HFDatasetError(message)),
)
with pytest.raises(SystemExit) as excinfo:
train()
assert str(excinfo.value) == message
def test_validate_dataset_dir_accepts_repo_bootstrap_dataset() -> None:
summary = validate_dataset_dir(REPO_ROOT / "data")
assert summary.files_checked == 6
assert summary.total_records == 121
assert summary.duplicate_count == 0
assert summary.counts_by_category == {
"conversation": 28,
"code": 45,
"image": 12,
"music": 12,
"video": 12,
"autonomous": 12,
}
def test_validate_dataset_dir_rejects_invalid_records_and_duplicates(tmp_path: Path) -> None:
dataset_dir = tmp_path / "data"
code_dir = dataset_dir / "code"
code_dir.mkdir(parents=True)
(code_dir / "sample.jsonl").write_text(
"\n".join(
[
json.dumps(
{
"timestamp": "2026-04-06T01:00:00Z",
"type": "code",
"prompt": "Write a validator",
"metadata": {"language": "python"},
"source": "test-bootstrap",
}
),
json.dumps(
{
"timestamp": "not-a-date",
"type": "video",
"prompt": "Write a validator",
"metadata": {},
}
),
]
)
+ "\n",
encoding="utf-8",
)
with pytest.raises(DatasetValidationError) as exc_info:
validate_dataset_dir(dataset_dir)
issues = exc_info.value.issues
assert any("timestamp" in issue for issue in issues)
assert any("lauks 'type' ir 'video'" in issue for issue in issues)
assert any("lauka 'source'" in issue for issue in issues)
assert any("laukā 'metadata'" in issue for issue in issues)
assert any("dublikāts" in issue for issue in issues)
def test_validate_datasets_cli_validates_repo_bootstrap_dataset() -> None:
script_path = REPO_ROOT / "core-python" / "scripts" / "validate_datasets.py"
assert REPO_ROOT.is_dir()
assert script_path.is_file()
result = subprocess.run( # noqa: S603
[
sys.executable,
str(script_path),
str(REPO_ROOT / "data"),
],
check=False,
capture_output=True,
text=True,
)
assert result.returncode == 0
assert "Dataset validācija veiksmīga" in result.stdout
|