File size: 55,675 Bytes
71923bb | 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 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 | {
"cells": [
{
"cell_type": "markdown",
"source": [
"# Chapter 4 - Training Data and Preprocessing for VLMs"
],
"metadata": {
"id": "_Q1EXjtG0LEs"
}
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "wa4KqZMLaSY2",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "9e52e684-f7a3-4068-ee5a-b8f8b5cdf851"
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Requirement already satisfied: datasets in /usr/local/lib/python3.12/dist-packages (4.0.0)\n",
"Requirement already satisfied: pillow in /usr/local/lib/python3.12/dist-packages (11.3.0)\n",
"Requirement already satisfied: huggingface_hub in /usr/local/lib/python3.12/dist-packages (1.5.0)\n",
"Requirement already satisfied: requests in /usr/local/lib/python3.12/dist-packages (2.32.4)\n",
"Requirement already satisfied: filelock in /usr/local/lib/python3.12/dist-packages (from datasets) (3.24.3)\n",
"Requirement already satisfied: numpy>=1.17 in /usr/local/lib/python3.12/dist-packages (from datasets) (2.0.2)\n",
"Requirement already satisfied: pyarrow>=15.0.0 in /usr/local/lib/python3.12/dist-packages (from datasets) (18.1.0)\n",
"Requirement already satisfied: dill<0.3.9,>=0.3.0 in /usr/local/lib/python3.12/dist-packages (from datasets) (0.3.8)\n",
"Requirement already satisfied: pandas in /usr/local/lib/python3.12/dist-packages (from datasets) (2.2.2)\n",
"Requirement already satisfied: tqdm>=4.66.3 in /usr/local/lib/python3.12/dist-packages (from datasets) (4.67.3)\n",
"Requirement already satisfied: xxhash in /usr/local/lib/python3.12/dist-packages (from datasets) (3.6.0)\n",
"Requirement already satisfied: multiprocess<0.70.17 in /usr/local/lib/python3.12/dist-packages (from datasets) (0.70.16)\n",
"Requirement already satisfied: fsspec<=2025.3.0,>=2023.1.0 in /usr/local/lib/python3.12/dist-packages (from fsspec[http]<=2025.3.0,>=2023.1.0->datasets) (2025.3.0)\n",
"Requirement already satisfied: packaging in /usr/local/lib/python3.12/dist-packages (from datasets) (26.0)\n",
"Requirement already satisfied: pyyaml>=5.1 in /usr/local/lib/python3.12/dist-packages (from datasets) (6.0.3)\n",
"Requirement already satisfied: hf-xet<2.0.0,>=1.2.0 in /usr/local/lib/python3.12/dist-packages (from huggingface_hub) (1.3.1)\n",
"Requirement already satisfied: httpx<1,>=0.23.0 in /usr/local/lib/python3.12/dist-packages (from huggingface_hub) (0.28.1)\n",
"Requirement already satisfied: typer in /usr/local/lib/python3.12/dist-packages (from huggingface_hub) (0.24.1)\n",
"Requirement already satisfied: typing-extensions>=4.1.0 in /usr/local/lib/python3.12/dist-packages (from huggingface_hub) (4.15.0)\n",
"Requirement already satisfied: charset_normalizer<4,>=2 in /usr/local/lib/python3.12/dist-packages (from requests) (3.4.4)\n",
"Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.12/dist-packages (from requests) (3.11)\n",
"Requirement already satisfied: urllib3<3,>=1.21.1 in /usr/local/lib/python3.12/dist-packages (from requests) (2.5.0)\n",
"Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.12/dist-packages (from requests) (2026.2.25)\n",
"Requirement already satisfied: aiohttp!=4.0.0a0,!=4.0.0a1 in /usr/local/lib/python3.12/dist-packages (from fsspec[http]<=2025.3.0,>=2023.1.0->datasets) (3.13.3)\n",
"Requirement already satisfied: anyio in /usr/local/lib/python3.12/dist-packages (from httpx<1,>=0.23.0->huggingface_hub) (4.12.1)\n",
"Requirement already satisfied: httpcore==1.* in /usr/local/lib/python3.12/dist-packages (from httpx<1,>=0.23.0->huggingface_hub) (1.0.9)\n",
"Requirement already satisfied: h11>=0.16 in /usr/local/lib/python3.12/dist-packages (from httpcore==1.*->httpx<1,>=0.23.0->huggingface_hub) (0.16.0)\n",
"Requirement already satisfied: python-dateutil>=2.8.2 in /usr/local/lib/python3.12/dist-packages (from pandas->datasets) (2.9.0.post0)\n",
"Requirement already satisfied: pytz>=2020.1 in /usr/local/lib/python3.12/dist-packages (from pandas->datasets) (2025.2)\n",
"Requirement already satisfied: tzdata>=2022.7 in /usr/local/lib/python3.12/dist-packages (from pandas->datasets) (2025.3)\n",
"Requirement already satisfied: click>=8.2.1 in /usr/local/lib/python3.12/dist-packages (from typer->huggingface_hub) (8.3.1)\n",
"Requirement already satisfied: shellingham>=1.3.0 in /usr/local/lib/python3.12/dist-packages (from typer->huggingface_hub) (1.5.4)\n",
"Requirement already satisfied: rich>=12.3.0 in /usr/local/lib/python3.12/dist-packages (from typer->huggingface_hub) (13.9.4)\n",
"Requirement already satisfied: annotated-doc>=0.0.2 in /usr/local/lib/python3.12/dist-packages (from typer->huggingface_hub) (0.0.4)\n",
"Requirement already satisfied: aiohappyeyeballs>=2.5.0 in /usr/local/lib/python3.12/dist-packages (from aiohttp!=4.0.0a0,!=4.0.0a1->fsspec[http]<=2025.3.0,>=2023.1.0->datasets) (2.6.1)\n",
"Requirement already satisfied: aiosignal>=1.4.0 in /usr/local/lib/python3.12/dist-packages (from aiohttp!=4.0.0a0,!=4.0.0a1->fsspec[http]<=2025.3.0,>=2023.1.0->datasets) (1.4.0)\n",
"Requirement already satisfied: attrs>=17.3.0 in /usr/local/lib/python3.12/dist-packages (from aiohttp!=4.0.0a0,!=4.0.0a1->fsspec[http]<=2025.3.0,>=2023.1.0->datasets) (25.4.0)\n",
"Requirement already satisfied: frozenlist>=1.1.1 in /usr/local/lib/python3.12/dist-packages (from aiohttp!=4.0.0a0,!=4.0.0a1->fsspec[http]<=2025.3.0,>=2023.1.0->datasets) (1.8.0)\n",
"Requirement already satisfied: multidict<7.0,>=4.5 in /usr/local/lib/python3.12/dist-packages (from aiohttp!=4.0.0a0,!=4.0.0a1->fsspec[http]<=2025.3.0,>=2023.1.0->datasets) (6.7.1)\n",
"Requirement already satisfied: propcache>=0.2.0 in /usr/local/lib/python3.12/dist-packages (from aiohttp!=4.0.0a0,!=4.0.0a1->fsspec[http]<=2025.3.0,>=2023.1.0->datasets) (0.4.1)\n",
"Requirement already satisfied: yarl<2.0,>=1.17.0 in /usr/local/lib/python3.12/dist-packages (from aiohttp!=4.0.0a0,!=4.0.0a1->fsspec[http]<=2025.3.0,>=2023.1.0->datasets) (1.22.0)\n",
"Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.12/dist-packages (from python-dateutil>=2.8.2->pandas->datasets) (1.17.0)\n",
"Requirement already satisfied: markdown-it-py>=2.2.0 in /usr/local/lib/python3.12/dist-packages (from rich>=12.3.0->typer->huggingface_hub) (4.0.0)\n",
"Requirement already satisfied: pygments<3.0.0,>=2.13.0 in /usr/local/lib/python3.12/dist-packages (from rich>=12.3.0->typer->huggingface_hub) (2.19.2)\n",
"Requirement already satisfied: mdurl~=0.1 in /usr/local/lib/python3.12/dist-packages (from markdown-it-py>=2.2.0->rich>=12.3.0->typer->huggingface_hub) (0.1.2)\n",
"Collecting transformers==5.2.0\n",
" Downloading transformers-5.2.0-py3-none-any.whl.metadata (32 kB)\n",
"Requirement already satisfied: huggingface-hub<2.0,>=1.3.0 in /usr/local/lib/python3.12/dist-packages (from transformers==5.2.0) (1.5.0)\n",
"Requirement already satisfied: numpy>=1.17 in /usr/local/lib/python3.12/dist-packages (from transformers==5.2.0) (2.0.2)\n",
"Requirement already satisfied: packaging>=20.0 in /usr/local/lib/python3.12/dist-packages (from transformers==5.2.0) (26.0)\n",
"Requirement already satisfied: pyyaml>=5.1 in /usr/local/lib/python3.12/dist-packages (from transformers==5.2.0) (6.0.3)\n",
"Requirement already satisfied: regex!=2019.12.17 in /usr/local/lib/python3.12/dist-packages (from transformers==5.2.0) (2025.11.3)\n",
"Requirement already satisfied: tokenizers<=0.23.0,>=0.22.0 in /usr/local/lib/python3.12/dist-packages (from transformers==5.2.0) (0.22.2)\n",
"Requirement already satisfied: typer-slim in /usr/local/lib/python3.12/dist-packages (from transformers==5.2.0) (0.24.0)\n",
"Requirement already satisfied: safetensors>=0.4.3 in /usr/local/lib/python3.12/dist-packages (from transformers==5.2.0) (0.7.0)\n",
"Requirement already satisfied: tqdm>=4.27 in /usr/local/lib/python3.12/dist-packages (from transformers==5.2.0) (4.67.3)\n",
"Requirement already satisfied: filelock>=3.10.0 in /usr/local/lib/python3.12/dist-packages (from huggingface-hub<2.0,>=1.3.0->transformers==5.2.0) (3.24.3)\n",
"Requirement already satisfied: fsspec>=2023.5.0 in /usr/local/lib/python3.12/dist-packages (from huggingface-hub<2.0,>=1.3.0->transformers==5.2.0) (2025.3.0)\n",
"Requirement already satisfied: hf-xet<2.0.0,>=1.2.0 in /usr/local/lib/python3.12/dist-packages (from huggingface-hub<2.0,>=1.3.0->transformers==5.2.0) (1.3.1)\n",
"Requirement already satisfied: httpx<1,>=0.23.0 in /usr/local/lib/python3.12/dist-packages (from huggingface-hub<2.0,>=1.3.0->transformers==5.2.0) (0.28.1)\n",
"Requirement already satisfied: typer in /usr/local/lib/python3.12/dist-packages (from huggingface-hub<2.0,>=1.3.0->transformers==5.2.0) (0.24.1)\n",
"Requirement already satisfied: typing-extensions>=4.1.0 in /usr/local/lib/python3.12/dist-packages (from huggingface-hub<2.0,>=1.3.0->transformers==5.2.0) (4.15.0)\n",
"Requirement already satisfied: anyio in /usr/local/lib/python3.12/dist-packages (from httpx<1,>=0.23.0->huggingface-hub<2.0,>=1.3.0->transformers==5.2.0) (4.12.1)\n",
"Requirement already satisfied: certifi in /usr/local/lib/python3.12/dist-packages (from httpx<1,>=0.23.0->huggingface-hub<2.0,>=1.3.0->transformers==5.2.0) (2026.2.25)\n",
"Requirement already satisfied: httpcore==1.* in /usr/local/lib/python3.12/dist-packages (from httpx<1,>=0.23.0->huggingface-hub<2.0,>=1.3.0->transformers==5.2.0) (1.0.9)\n",
"Requirement already satisfied: idna in /usr/local/lib/python3.12/dist-packages (from httpx<1,>=0.23.0->huggingface-hub<2.0,>=1.3.0->transformers==5.2.0) (3.11)\n",
"Requirement already satisfied: h11>=0.16 in /usr/local/lib/python3.12/dist-packages (from httpcore==1.*->httpx<1,>=0.23.0->huggingface-hub<2.0,>=1.3.0->transformers==5.2.0) (0.16.0)\n",
"Requirement already satisfied: click>=8.2.1 in /usr/local/lib/python3.12/dist-packages (from typer->huggingface-hub<2.0,>=1.3.0->transformers==5.2.0) (8.3.1)\n",
"Requirement already satisfied: shellingham>=1.3.0 in /usr/local/lib/python3.12/dist-packages (from typer->huggingface-hub<2.0,>=1.3.0->transformers==5.2.0) (1.5.4)\n",
"Requirement already satisfied: rich>=12.3.0 in /usr/local/lib/python3.12/dist-packages (from typer->huggingface-hub<2.0,>=1.3.0->transformers==5.2.0) (13.9.4)\n",
"Requirement already satisfied: annotated-doc>=0.0.2 in /usr/local/lib/python3.12/dist-packages (from typer->huggingface-hub<2.0,>=1.3.0->transformers==5.2.0) (0.0.4)\n",
"Requirement already satisfied: markdown-it-py>=2.2.0 in /usr/local/lib/python3.12/dist-packages (from rich>=12.3.0->typer->huggingface-hub<2.0,>=1.3.0->transformers==5.2.0) (4.0.0)\n",
"Requirement already satisfied: pygments<3.0.0,>=2.13.0 in /usr/local/lib/python3.12/dist-packages (from rich>=12.3.0->typer->huggingface-hub<2.0,>=1.3.0->transformers==5.2.0) (2.19.2)\n",
"Requirement already satisfied: mdurl~=0.1 in /usr/local/lib/python3.12/dist-packages (from markdown-it-py>=2.2.0->rich>=12.3.0->typer->huggingface-hub<2.0,>=1.3.0->transformers==5.2.0) (0.1.2)\n",
"Downloading transformers-5.2.0-py3-none-any.whl (10.4 MB)\n",
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m10.4/10.4 MB\u001b[0m \u001b[31m38.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
"\u001b[?25hInstalling collected packages: transformers\n",
" Attempting uninstall: transformers\n",
" Found existing installation: transformers 5.0.0\n",
" Uninstalling transformers-5.0.0:\n",
" Successfully uninstalled transformers-5.0.0\n",
"Successfully installed transformers-5.2.0\n",
"Get:1 https://cloud.r-project.org/bin/linux/ubuntu jammy-cran40/ InRelease [3,632 B]\n",
"Get:2 https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2204/x86_64 InRelease [1,581 B]\n",
"Get:3 https://cli.github.com/packages stable InRelease [3,917 B]\n",
"Get:4 https://cloud.r-project.org/bin/linux/ubuntu jammy-cran40/ Packages [85.2 kB]\n",
"Get:5 https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2204/x86_64 Packages [2,388 kB]\n",
"Get:6 https://r2u.stat.illinois.edu/ubuntu jammy InRelease [6,555 B]\n",
"Hit:7 http://archive.ubuntu.com/ubuntu jammy InRelease\n",
"Get:8 http://security.ubuntu.com/ubuntu jammy-security InRelease [129 kB]\n",
"Get:9 https://cli.github.com/packages stable/main amd64 Packages [357 B]\n",
"Get:10 http://archive.ubuntu.com/ubuntu jammy-updates InRelease [128 kB]\n",
"Get:11 https://r2u.stat.illinois.edu/ubuntu jammy/main all Packages [9,802 kB]\n",
"Get:12 https://ppa.launchpadcontent.net/deadsnakes/ppa/ubuntu jammy InRelease [18.1 kB]\n",
"Hit:13 https://ppa.launchpadcontent.net/graphics-drivers/ppa/ubuntu jammy InRelease\n",
"Hit:14 https://ppa.launchpadcontent.net/ubuntugis/ppa/ubuntu jammy InRelease\n",
"Get:15 http://security.ubuntu.com/ubuntu jammy-security/universe amd64 Packages [1,301 kB]\n",
"Get:16 http://archive.ubuntu.com/ubuntu jammy-backports InRelease [127 kB]\n",
"Get:17 https://ppa.launchpadcontent.net/deadsnakes/ppa/ubuntu jammy/main amd64 Packages [39.2 kB]\n",
"Get:18 https://r2u.stat.illinois.edu/ubuntu jammy/main amd64 Packages [2,919 kB]\n",
"Get:19 http://archive.ubuntu.com/ubuntu jammy-updates/universe amd64 Packages [1,613 kB]\n",
"Get:20 http://security.ubuntu.com/ubuntu jammy-security/restricted amd64 Packages [6,662 kB]\n",
"Get:21 http://archive.ubuntu.com/ubuntu jammy-updates/restricted amd64 Packages [6,887 kB]\n",
"Get:22 http://archive.ubuntu.com/ubuntu jammy-updates/main amd64 Packages [4,122 kB]\n",
"Get:23 http://security.ubuntu.com/ubuntu jammy-security/main amd64 Packages [3,782 kB]\n",
"Fetched 40.0 MB in 4s (11.0 MB/s)\n",
"Reading package lists... Done\n",
"Building dependency tree... Done\n",
"Reading state information... Done\n",
"88 packages can be upgraded. Run 'apt list --upgradable' to see them.\n",
"\u001b[1;33mW: \u001b[0mSkipping acquire of configured file 'main/source/Sources' as repository 'https://r2u.stat.illinois.edu/ubuntu jammy InRelease' does not seem to provide it (sources.list entry misspelt?)\u001b[0m\n",
"Reading package lists... Done\n",
"Building dependency tree... Done\n",
"Reading state information... Done\n",
"ffmpeg is already the newest version (7:4.4.2-0ubuntu0.22.04.1).\n",
"0 upgraded, 0 newly installed, 0 to remove and 88 not upgraded.\n"
]
}
],
"source": [
"# Here some installs that we will be using in multiple parts of the chapter\n",
"!pip install datasets pillow huggingface_hub requests\n",
"!pip install transformers==5.2.0\n",
"!apt update && apt install -y ffmpeg"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "WDv1_NAkEFlr"
},
"outputs": [],
"source": [
"# Very important to be logged in!\n",
"from huggingface_hub import login\n",
"login()\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0oWU8mV_Emo5"
},
"source": [
"## 4.1 Looking at the data\n",
"### 4.1.1 Image-Text Datasets\n",
"\n",
"*Looking at LAION dataset*\n",
"\n",
"Remember: some datasets are gated, this means that you first have to go to the dataset page and accept the terms and conditions and then you will be able to browse it.\n",
"\n",
"\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 205,
"referenced_widgets": [
"6fb4c46f20c341cea17b28f01ac3875c",
"01cc8005bcbd490a87fbfbb80aa14c5f",
"7ff3c9983e3d485dafcbf61ddaf7dff5",
"d9230e48433241a885b378eec94dc1e0",
"f9bbe2539c894dbda093d123e7e6c6cf",
"931d5409dfa842d59ea3d5e12f13991b",
"95a6409bf61e4ecaa1b3f705eb6483e6",
"7f2aee6daa8642a1a22100cd5adbe2a2",
"e03116fd32e0467687c479bdcf9ef6c2",
"47e4ace1c6be41e0b6bf6bf42e8919a0",
"7531a9c6fec842ffa8b73425d4b25569"
]
},
"id": "06n46XuGERPe",
"outputId": "371f3e84-b8d6-4da7-8f6b-403347f18b1a"
},
"outputs": [
{
"output_type": "display_data",
"data": {
"text/plain": [
"Resolving data files: 0%| | 0/128 [00:00<?, ?it/s]"
],
"application/vnd.jupyter.widget-view+json": {
"version_major": 2,
"version_minor": 0,
"model_id": "6fb4c46f20c341cea17b28f01ac3875c"
}
},
"metadata": {}
},
{
"output_type": "stream",
"name": "stdout",
"text": [
"Caption: \"\"\"Brent Payne \"\"\"\"Brent Payne\"\"\"\" 1999 Self Released Country Nm/Nm Out Of Print Cd\"\"\"\n",
"Image URL: https://www.picclickimg.com/d/l400/pict/333262346250_/Brent-Payne-Brent-Payne-1999-Self-Released-Country.jpg\n",
"---\n",
"Caption: Universal Orlando 2012 The Ultimate Guide to the Ultimate Theme Park Adventure\n",
"Image URL: https://nationalbookswap.com/pbs/m/42/0942/9781887140942.jpg\n",
"---\n",
"Caption: Unique 14k Gold Yellow and Blue Diamond Engagement Ring 2.64ct.\n",
"Image URL: https://d1251d0o0760fi.cloudfront.net/catalog/product/1/4/14k-gold-diamond-engagement-ring-264-ct-p-64.jpg\n",
"---\n"
]
}
],
"source": [
"# Stream LAION dataset without downloading terabytes using the streaming functionality\n",
"from datasets import load_dataset\n",
"\n",
"dataset = load_dataset(\"laion/relaion2B-en-research-safe\", streaming=True)\n",
"\n",
"for example in dataset['train'].take(3):\n",
" print(f\"Caption: {example['caption']}\")\n",
" print(f\"Image URL: {example['url']}\")\n",
" print(\"---\")\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "w-x35KMLaFRI"
},
"source": [
"## 4.2 Building a dataset\n",
"### 4.2.2 Data Filtering at Scale\n",
"\n",
"Complementing the snippet in section 4.2.2, here is the full code to read videos from a HF Dataset and push back to another repo the videos that are not static"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "lZBIVXVIag1f"
},
"outputs": [],
"source": [
"import os\n",
"import math\n",
"import subprocess\n",
"import tempfile\n",
"import requests\n",
"from datasets import Dataset, DatasetDict\n",
"from huggingface_hub import HfApi\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "tCeVkb5Iax1a"
},
"outputs": [],
"source": [
"# CONFIG, set here your input dataset with videos and your output dataset where you want to push the results\n",
"INPUT_DATASET_REPO = \"vlmbook/videos\"\n",
"OUTPUT_DATASET_REPO = \"<yourUsername>/filtered-videos\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "XTq0f4LbaOii"
},
"outputs": [],
"source": [
"\n",
"# A couple of auxiliar functions to explore the input dataset, find MP4 files and download those to analyze them\n",
"def get_mp4_files_in_repo():\n",
" \"\"\"Check which MP4 files are available in the repository root.\"\"\"\n",
" api = HfApi()\n",
"\n",
" try:\n",
" repo_files = api.list_repo_files(INPUT_DATASET_REPO, repo_type=\"dataset\")\n",
" # Filter for MP4 files in root only\n",
" mp4_files = [f for f in repo_files if f.endswith('.mp4') and '/' not in f]\n",
"\n",
" print(f\"Found {len(mp4_files)} MP4 files:\")\n",
" for mp4_file in mp4_files:\n",
" print(f\" - {mp4_file}\")\n",
"\n",
" return mp4_files\n",
"\n",
" except Exception as e:\n",
" print(f\"Error accessing repository: {e}\")\n",
" return []\n",
"\n",
"\n",
"def download_video_from_hf(video_filename):\n",
" \"\"\"Download a specific MP4 file from the HF repository.\"\"\"\n",
" url = f\"https://huggingface.co/datasets/{INPUT_DATASET_REPO}/resolve/main/{video_filename}\"\n",
"\n",
" try:\n",
" response = requests.get(url, stream=True)\n",
" response.raise_for_status()\n",
"\n",
" # Create temporary file\n",
" temp_file = tempfile.NamedTemporaryFile(suffix=\".mp4\", delete=False)\n",
"\n",
" # Download video data\n",
" for chunk in response.iter_content(chunk_size=8192):\n",
" temp_file.write(chunk)\n",
"\n",
" temp_file.close()\n",
" print(f\"Downloaded {video_filename}\")\n",
" return temp_file.name\n",
"\n",
" except Exception as e:\n",
" print(f\"Error downloading {video_filename}: {e}\")\n",
" return None\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "n05DQOWldhbu"
},
"outputs": [],
"source": [
"\n",
"\n",
"# The magic of the script - how we use ffmpeg and its plugin freezedetect to discard videos quickly\n",
"\n",
"def is_video_static(video_file, threshold=0.4):\n",
" \"\"\"Check if video has static content using ffmpeg freezedetect.\"\"\"\n",
"\n",
" # Get video duration\n",
" result = subprocess.run([\n",
" \"ffprobe\", \"-v\", \"quiet\", \"-show_entries\", \"format=duration\",\n",
" \"-of\", \"csv=p=0\", video_file\n",
" ], capture_output=True, text=True)\n",
"\n",
" duration = float(result.stdout.strip())\n",
" segments = math.ceil(duration / 60) # 60-second segments\n",
" freeze_count = 0\n",
"\n",
" # Check each segment for freezes\n",
" for start in range(0, int(duration), 60):\n",
" result = subprocess.run([\n",
" \"ffmpeg\", \"-ss\", str(start), \"-i\", video_file, \"-t\", \"60\",\n",
" \"-vf\", \"freezedetect=n=0.05:d=50\", \"-f\", \"null\", \"-\"\n",
" ], capture_output=True, text=True)\n",
"\n",
" if \"freezedetect\" in result.stderr:\n",
" freeze_count += 1\n",
"\n",
" freeze_percentage = freeze_count / segments\n",
" print(f\" Freeze percentage: {freeze_percentage:.1%}\")\n",
"\n",
" return freeze_percentage >= threshold\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "rrQlzPILdqbF",
"outputId": "14668220-d37a-4833-f9fc-b744a23f9625"
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Checking for MP4 files in repository...\n",
"Found 4 MP4 files:\n",
" - 09KmKSz4r_Y.mp4\n",
" - MewNUHRGOm0.mp4\n",
" - StKxb6z-MHk.mp4\n",
" - solid_rgb_3min_640x480.mp4\n",
"\n",
"Processing 09KmKSz4r_Y.mp4...\n",
"Downloaded 09KmKSz4r_Y.mp4\n",
" Freeze percentage: 0.0%\n",
"09KmKSz4r_Y passed filter\n",
"\n",
"Processing MewNUHRGOm0.mp4...\n",
"Downloaded MewNUHRGOm0.mp4\n",
" Freeze percentage: 0.0%\n",
"MewNUHRGOm0 passed filter\n",
"\n",
"Processing StKxb6z-MHk.mp4...\n",
"Downloaded StKxb6z-MHk.mp4\n",
" Freeze percentage: 0.0%\n",
"StKxb6z-MHk passed filter\n",
"\n",
"Processing solid_rgb_3min_640x480.mp4...\n",
"Downloaded solid_rgb_3min_640x480.mp4\n",
" Freeze percentage: 100.0%\n",
"solid_rgb_3min_640x480 filtered out\n"
]
}
],
"source": [
"\n",
"# Discover MP4 files in the repository\n",
"print(\"Checking for MP4 files in repository...\")\n",
"mp4_files = get_mp4_files_in_repo()\n",
"\n",
"\n",
"# Process each MP4 file\n",
"filtered_videos = []\n",
"\n",
"\n",
"for mp4_file in mp4_files:\n",
" print(f\"\\nProcessing {mp4_file}...\")\n",
"\n",
" # Extract video ID from filename\n",
" video_id = mp4_file.replace('.mp4', '')\n",
"\n",
" # Download video from HF repo\n",
" temp_video_path = download_video_from_hf(mp4_file)\n",
" if not temp_video_path:\n",
" continue\n",
"\n",
" # Analyze video for static content\n",
" try:\n",
" if not is_video_static(temp_video_path):\n",
" # Video passes filter - read file data\n",
" with open(temp_video_path, 'rb') as f:\n",
" video_bytes = f.read()\n",
"\n",
" filtered_videos.append({\n",
" 'video_id': video_id,\n",
" 'filename': mp4_file,\n",
" 'video_data': video_bytes\n",
" })\n",
" print(f\"{video_id} passed filter\")\n",
" else:\n",
" print(f\"{video_id} filtered out\")\n",
"\n",
" except Exception as e:\n",
" print(f\"Error analyzing {video_id}: {e}\")\n",
"\n",
" finally:\n",
" # Clean up temporary file\n",
" if os.path.exists(temp_video_path):\n",
" os.unlink(temp_video_path)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 331,
"referenced_widgets": [
"d043aca0454e41aeafa0314eb52e3de1",
"5df17c962fea448f9ab65840d5348191",
"71105a58216543dd97f89b21d3c52e46",
"7ae0acc5a455476e92660d66ed0aa654",
"8231960b067a44838bb511c0683b356e",
"7a94bbecb5ef45ca848e303e4260072a",
"b1d72d695d24457cb0c38ddf41142d45",
"af877034a8fe4ed5a1f04b15b793a85d",
"935fd711ec3445ee93552b836d8db66b",
"8e8c3aa012b343918a1b63d94d6a05d5",
"9136a68daf2849c38845db321bb6a92f",
"e9f7a808209b4f1097938619a2da36be",
"27207ee74d08460490fb53904e67136e",
"77e2a74dbd8149da9c283629c31bff54",
"2ca8a18ca66d4bc0b7e4a4876554ad8a",
"2e12213a8e20463f8d1fcbb371000f91",
"17eebc11f7474c18a97b85bc21a01fb1",
"e916b950fabe45f3904cfdf5b489ccec",
"d54396afdac541bc9e39a01e990934e8",
"be26502380d145e3be399a772b64ce61",
"1e09a0ec58c94ce7b7d513523f4502e6",
"9617edbffb0e4c7da3bca89c8d174ed1",
"d6ae988b5b254549a11265d5f614f097",
"891505d1669840eaa653258f32e0c68f",
"6fb8d978614f496da180b49db99d6e16",
"fe1dbafda42c4f4199ff16ed4b771d6e",
"ebb3dbe62b28422e95d6156a500efffa",
"bab64793b7774f34a7f595ba9d959f57",
"0393f0d884984c25b592c1e522c322ce",
"3558cf3c25604c7fb1e6534b9e7f79ea",
"05fd4ba3ab0349aab985be2af838955f",
"85ae0cf070234107aea7c5054c2309eb",
"d8f1ae4b0cb743f4be8a714910a303e3",
"3d7142c20d9f404db34aace5f02f9217",
"47ad1f400e804c9a974d499733c4ea3f",
"92e36f6cea7d440d9146b1f82fcb340c",
"e055d11e35374fe28ec11f22c0e84856",
"53d3fc6165ef496b8ea5313251196183",
"5c720b1e69cd4e51bbda86fe07b6c69f",
"48e762b5761e42af9303f1164b735a52",
"23648c140cc34acd864b28bd174c3728",
"f58de732c3b041acb241212138f25a57",
"a82fdc777f1a4137a52766d02294f909",
"b4d74937b3214e1b9719e939a5ad53e1",
"057374af98334017aafd3b09920fc73a",
"4e11cd0e2804402ab2b728818fe98d73",
"393ee0d241ee40a292335a31b6eecfdc",
"19bb9cd225f744fd9acdbe5fba4c9542",
"bac5fb32e8df4ecab39f2257ebfdbbf2",
"a7e02099e0724f69b780800dd8da5e50",
"f30c317ba4714e5ba52214d64f7e2130",
"dc872bfe82bb4c148f4ace719fd11def",
"06ac820a1bf7419a8a84728b360baf2f",
"a44429bb16c54d76b4cc0711d077ffc6",
"8027761326584bb99a492f8c4c7b6179",
"67e2fc1789cc4578b2774b569a22b5b1",
"3ac1ef8db8594dd39bb17e50e4a34a9a",
"125b5880409a423b990fc0fa0c3a1191",
"7fcad37186c14deeb5995c1b90b6de06",
"27e1492f25a74ed39bbfae072a797cd4",
"3dd571ff3dd44c2997307b38772ccf5c",
"010f292ede174e049bb68cfd2250b1f7",
"fdfe81254b414ec4b2639a7095f1732c",
"8503e41b70b047e3aee82fcabac20e16",
"b42a5c02ffe947a48a58aaed080fd528",
"e0240d1a25934d26811f01c448da2eec"
]
},
"id": "VxNtFeLcdv7V",
"outputId": "460c297e-3ed1-4984-a488-d5bd3b23ac53"
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"\n",
"Saving 3 filtered videos...\n"
]
},
{
"output_type": "display_data",
"data": {
"text/plain": [
"Uploading the dataset shards: 0%| | 0/1 [00:00<?, ? shards/s]"
],
"application/vnd.jupyter.widget-view+json": {
"version_major": 2,
"version_minor": 0,
"model_id": "d043aca0454e41aeafa0314eb52e3de1"
}
},
"metadata": {}
},
{
"output_type": "display_data",
"data": {
"text/plain": [
"Creating parquet from Arrow format: 0%| | 0/1 [00:00<?, ?ba/s]"
],
"application/vnd.jupyter.widget-view+json": {
"version_major": 2,
"version_minor": 0,
"model_id": "e9f7a808209b4f1097938619a2da36be"
}
},
"metadata": {}
},
{
"output_type": "display_data",
"data": {
"text/plain": [
"Processing Files (0 / 0) : | | 0.00B / 0.00B "
],
"application/vnd.jupyter.widget-view+json": {
"version_major": 2,
"version_minor": 0,
"model_id": "d6ae988b5b254549a11265d5f614f097"
}
},
"metadata": {}
},
{
"output_type": "display_data",
"data": {
"text/plain": [
"New Data Upload : | | 0.00B / 0.00B "
],
"application/vnd.jupyter.widget-view+json": {
"version_major": 2,
"version_minor": 0,
"model_id": "3d7142c20d9f404db34aace5f02f9217"
}
},
"metadata": {}
},
{
"output_type": "display_data",
"data": {
"text/plain": [
" : 100%|##########| 10.6MB / 10.6MB "
],
"application/vnd.jupyter.widget-view+json": {
"version_major": 2,
"version_minor": 0,
"model_id": "057374af98334017aafd3b09920fc73a"
}
},
"metadata": {}
},
{
"output_type": "display_data",
"data": {
"text/plain": [
"README.md: 0%| | 0.00/354 [00:00<?, ?B/s]"
],
"application/vnd.jupyter.widget-view+json": {
"version_major": 2,
"version_minor": 0,
"model_id": "67e2fc1789cc4578b2774b569a22b5b1"
}
},
"metadata": {}
},
{
"output_type": "stream",
"name": "stderr",
"text": [
"No files have been modified since last commit. Skipping to prevent empty commit.\n",
"WARNING:huggingface_hub.hf_api:No files have been modified since last commit. Skipping to prevent empty commit.\n"
]
},
{
"output_type": "stream",
"name": "stdout",
"text": [
"\n",
"Filtered dataset available at: mfarre/testing\n",
"Filtered videos saved successfully!\n"
]
}
],
"source": [
"\n",
"\n",
"# Save filtered results\n",
"if filtered_videos:\n",
" print(f\"\\nSaving {len(filtered_videos)} filtered videos...\")\n",
"\n",
" # Create dataset from filtered videos\n",
" filtered_dataset = Dataset.from_list(filtered_videos)\n",
"\n",
" # Push filtered videos to new repository\n",
" if OUTPUT_DATASET_REPO is not None:\n",
" filtered_dataset.push_to_hub(f\"{OUTPUT_DATASET_REPO}\")\n",
"\n",
" print(f\"\\nFiltered dataset available at: {OUTPUT_DATASET_REPO}\")\n",
"\n",
" print(\"Filtered videos saved successfully!\")\n",
"\n",
"else:\n",
"\n",
" print(\"No videos passed the filter.\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "BCx7QFDee8qx"
},
"source": [
"### 4.2.4 Build your own synthesis pipeline\n",
"Below the full code to synthesize Q&A using Apple's FastVLM. Note that we use the 1.5B model to make it easier to run in a colab but expect better Q&A pairs with the 7B."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "8ag3ZUh7EGu7"
},
"outputs": [],
"source": [
"# Import libraries\n",
"import torch\n",
"import json\n",
"from PIL import Image\n",
"from transformers import AutoTokenizer, AutoModelForCausalLM\n",
"from datasets import load_dataset, Dataset\n",
"from huggingface_hub import login\n",
"import requests\n",
"from io import BytesIO"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 104,
"referenced_widgets": [
"1e57069ccfca419c9766848e1e483f36",
"dc40b9401c204aaca7e189afe0fbf44b",
"9508c6fcbbec456fa9254c959bca94e8",
"4ca6b0d38f8e45dda8a3559c927c5343",
"ef16ac573a6548f8ab352d068939a328",
"9d16aae28af94083999e587d2253e298",
"74ebf8a676c3433989a066a04d31e595",
"7e76adfb940c4abeb4ce0a4299fd5aab",
"29156ef77e604895ad5764e0e8d68e22",
"7ff7f19358324d1bb0a1543525ad63d9",
"2920d545b6dd43929ad1d542512bde4a"
]
},
"id": "8xLhei0afKpV",
"outputId": "9e0a86d9-3572-4809-d7fd-78cbd1c0461b"
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Loading FastVLM model...\n"
]
},
{
"output_type": "display_data",
"data": {
"text/plain": [
"Loading weights: 0%| | 0/972 [00:00<?, ?it/s]"
],
"application/vnd.jupyter.widget-view+json": {
"version_major": 2,
"version_minor": 0,
"model_id": "1e57069ccfca419c9766848e1e483f36"
}
},
"metadata": {}
},
{
"output_type": "stream",
"name": "stderr",
"text": [
"The tied weights mapping and config for this model specifies to tie model.embed_tokens.weight to lm_head.weight, but both are present in the checkpoints, so we will NOT tie them. You should update the config with `tie_word_embeddings=False` to silence this warning\n"
]
}
],
"source": [
"# Load the model from the hub\n",
"# Note: we are loading the 1.5B because it fits in a free Google Colab but for\n",
"# better quality Q&A you can use the 7B\n",
"\n",
"model_id = \"apple/FastVLM-1.5B\"\n",
"#model_id = \"apple/FastVLM-7B\"\n",
"\n",
"IMAGE_TOKEN_INDEX = -200\n",
"\n",
"print(\"Loading FastVLM model...\")\n",
"tok = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)\n",
"model = AutoModelForCausalLM.from_pretrained(\n",
" model_id,\n",
" dtype=torch.bfloat16,\n",
" device_map=\"auto\",\n",
" trust_remote_code=True\n",
")\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "7YqzQdjgEiyh"
},
"outputs": [],
"source": [
"\n",
"# Given an image, FastVLM returns us three Q&As for our dataset\n",
"\n",
"def generate_qa_pairs(image_url):\n",
" try:\n",
" # Download image\n",
" response = requests.get(image_url, timeout=10)\n",
" img = Image.open(BytesIO(response.content)).convert(\"RGB\")\n",
"\n",
" # Build chat template for Q&A generation\n",
" messages = [\n",
" {\"role\": \"user\", \"content\": \"<image>\\nGenerate 3 question-answer pairs about this image. Format as JSON: [{\\\"question\\\": \\\"...\\\", \\\"answer\\\": \\\"...\\\"}]\"}\n",
" ]\n",
" rendered = tok.apply_chat_template(\n",
" messages, add_generation_prompt=True, tokenize=False\n",
" )\n",
" pre, post = rendered.split(\"<image>\", 1)\n",
"\n",
" # Tokenize around image token\n",
" pre_ids = tok(pre, return_tensors=\"pt\", add_special_tokens=False).input_ids\n",
" post_ids = tok(post, return_tensors=\"pt\", add_special_tokens=False).input_ids\n",
" img_tok = torch.tensor([[IMAGE_TOKEN_INDEX]], dtype=pre_ids.dtype)\n",
" input_ids = torch.cat([pre_ids, img_tok, post_ids], dim=1).to(model.device)\n",
" attention_mask = torch.ones_like(input_ids, device=model.device)\n",
"\n",
" # Process image\n",
" px = model.get_vision_tower().image_processor(images=img, return_tensors=\"pt\")[\"pixel_values\"]\n",
" px = px.to(model.device, dtype=model.dtype)\n",
"\n",
" # Generate Q&A pairs\n",
" out = model.generate(\n",
" inputs=input_ids,\n",
" attention_mask=attention_mask,\n",
" images=px,\n",
" max_new_tokens=256,\n",
" )\n",
"\n",
" result = tok.decode(out[0], skip_special_tokens=True)\n",
" # Extract JSON part after the prompt\n",
" qa_text = result.split(\"Format as JSON:\")[-1].strip()\n",
" return qa_text\n",
"\n",
" except Exception as e:\n",
" return f\"Error: {str(e)}\"\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "jkZID9yIEuJc",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 885,
"referenced_widgets": [
"888fda19ae204839b1914490290efc36",
"75c03a2b90634cb18e02beb0345d4d5d",
"406b705a7c43405b9a0d1f8f01620db1",
"80899375b61c46559fc69641e8fc0be5",
"faf1003fc2c94c9fbbb842cfa64997ba",
"a3f5aaabc7e148d2a40255352bafd5e4",
"7fcc8215550c458fa902d54dd1d8e266",
"e7728dddd387461a98fc23b0755de6ba",
"45503561975246199b7d2e6eef94d8bb",
"2afefd33049844cba03b9cd159be5240",
"f026fad6c7d04a7e89ccc536e9549e7b"
]
},
"outputId": "f0463fea-db0f-4cae-f68e-ab363fd58b4c"
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Streaming LAION dataset...\n"
]
},
{
"output_type": "display_data",
"data": {
"text/plain": [
"Resolving data files: 0%| | 0/128 [00:00<?, ?it/s]"
],
"application/vnd.jupyter.widget-view+json": {
"version_major": 2,
"version_minor": 0,
"model_id": "888fda19ae204839b1914490290efc36"
}
},
"metadata": {}
},
{
"output_type": "stream",
"name": "stdout",
"text": [
"\n",
"Example 1:\n",
"Original caption: \"\"\"Brent Payne \"\"\"\"Brent Payne\"\"\"\" 1999 Self Released Country Nm/Nm Out Of Print Cd\"\"\"\n",
"Image URL: https://www.picclickimg.com/d/l400/pict/333262346250_/Brent-Payne-Brent-Payne-1999-Self-Released-Country.jpg\n",
"Generated Q&A: Error: cannot identify image file <_io.BytesIO object at 0x790e8e165b70>\n",
"---\n",
"\n",
"Example 2:\n",
"Original caption: Universal Orlando 2012 The Ultimate Guide to the Ultimate Theme Park Adventure\n",
"Image URL: https://nationalbookswap.com/pbs/m/42/0942/9781887140942.jpg\n",
"Generated Q&A: Error: HTTPSConnectionPool(host='nationalbookswap.com', port=443): Max retries exceeded with url: /pbs/m/42/0942/9781887140942.jpg (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1010)')))\n",
"---\n",
"\n",
"Example 3:\n",
"Original caption: Unique 14k Gold Yellow and Blue Diamond Engagement Ring 2.64ct.\n",
"Image URL: https://d1251d0o0760fi.cloudfront.net/catalog/product/1/4/14k-gold-diamond-engagement-ring-264-ct-p-64.jpg\n",
"Generated Q&A: Error: cannot identify image file <_io.BytesIO object at 0x790e94133420>\n",
"---\n",
"\n",
"Example 4:\n",
"Original caption: Herd of cows on alpine pasture among mountains in Alps, northern Italy. Stock Photo\n",
"Image URL: https://c8.alamy.com/comp/C84HAM/herd-of-cows-on-alpine-pasture-among-mountains-in-alps-northern-italy-C84HAM.jpg\n",
"Generated Q&A: There are several potential questions and answers that could be derived from this image:\n",
"\n",
"1. **Question:** What type of animals are seen grazing in the image?\n",
" **Answer:** The animals in the image appear to be cows, identifiable by their size, color, and the typical udder visible on some of the herd.\n",
"\n",
"2. **Question:** Describe the terrain where these cows are grazing.\n",
" **Answer:** The cows are grazing on a grassy field that appears to be at the base of a mountainous region. The field has patches of brown grass, typical of late spring or early summer, and the surrounding terrain includes sloping hills covered with more green vegetation.\n",
"\n",
"3. **Question:** What kind of environment is depicted in the background of the image?\n",
" **Answer:** The background showcases a deep valley flanked by steep, forest-covered mountains. The forest appears dense, with coniferous trees covering much of the mountain slopes, indicative of a high-altitude or alpine environment.\n",
"\n",
"4. **Question:** What could the cows be utilizing in terms of food sources within this image?\n",
" **Answer:** The cows are grazing on the grass and other vegetation present in the field, which is a common food source for cattle. The mixture of green grass and patches of\n",
"---\n",
"\n",
"Example 5:\n",
"Original caption: Farmaderbe - Max color vegetal 24 Castano moka\n",
"Image URL: https://ss-pics.s3.eu-west-1.amazonaws.com/files/1619887/page-V.987024.jpg?1600681301\n",
"Generated Q&A: {\"question\": \"What company produces the MAXCOLORE vegetable coloring product?\", \"answer\": \"The product is produced by Castando Moka,\" which is indicated in the branding at the top right of the box. This is supported by the brand name and the company logo on the packaging.\"}\n",
"{\"question\": \"What are the main ingredients in the MAXCOLORE vegetable coloring product as stated on the packaging?\", \"answer\": \"The main ingredients are 'Tricologie' combined with 'Stimtex AS,' 'Argan,' 'Marine Oil,' 'Litchi Chinesis,' 'Chloride,' 'Calcium,' 'Sodium Phosphate,' 'Maltodextrin,' 'Potassium Chloride,' 'BHT,' and 'Sodium Benzoate' according to the ingredients list. These ingredients are listed for their specific functions and properties related to hair coloring and preservation.\"}\n",
"{\"question\": \"Does the MAXCOLORE vegetable coloring product contain any metal components?\", \"answer\": \"No, the product specifies that it is devoid of metal components, indicated by 'ZERO METAL CONT Laurent' in the description.\"}\n",
"This question-answer format is designed to address potential customer inquiries about the product, providing\n",
"---\n",
"[{'original_caption': '\"\"\"Brent Payne \"\"\"\"Brent Payne\"\"\"\" 1999 Self Released Country Nm/Nm Out Of Print Cd\"\"\"', 'image_url': 'https://www.picclickimg.com/d/l400/pict/333262346250_/Brent-Payne-Brent-Payne-1999-Self-Released-Country.jpg', 'generated_qa': 'Error: cannot identify image file <_io.BytesIO object at 0x790e8e165b70>'}, {'original_caption': 'Universal Orlando 2012 The Ultimate Guide to the Ultimate Theme Park Adventure', 'image_url': 'https://nationalbookswap.com/pbs/m/42/0942/9781887140942.jpg', 'generated_qa': \"Error: HTTPSConnectionPool(host='nationalbookswap.com', port=443): Max retries exceeded with url: /pbs/m/42/0942/9781887140942.jpg (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1010)')))\"}, {'original_caption': 'Unique 14k Gold Yellow and Blue Diamond Engagement Ring 2.64ct.', 'image_url': 'https://d1251d0o0760fi.cloudfront.net/catalog/product/1/4/14k-gold-diamond-engagement-ring-264-ct-p-64.jpg', 'generated_qa': 'Error: cannot identify image file <_io.BytesIO object at 0x790e94133420>'}, {'original_caption': 'Herd of cows on alpine pasture among mountains in Alps, northern Italy. Stock Photo', 'image_url': 'https://c8.alamy.com/comp/C84HAM/herd-of-cows-on-alpine-pasture-among-mountains-in-alps-northern-italy-C84HAM.jpg', 'generated_qa': 'There are several potential questions and answers that could be derived from this image:\\n\\n1. **Question:** What type of animals are seen grazing in the image?\\n **Answer:** The animals in the image appear to be cows, identifiable by their size, color, and the typical udder visible on some of the herd.\\n\\n2. **Question:** Describe the terrain where these cows are grazing.\\n **Answer:** The cows are grazing on a grassy field that appears to be at the base of a mountainous region. The field has patches of brown grass, typical of late spring or early summer, and the surrounding terrain includes sloping hills covered with more green vegetation.\\n\\n3. **Question:** What kind of environment is depicted in the background of the image?\\n **Answer:** The background showcases a deep valley flanked by steep, forest-covered mountains. The forest appears dense, with coniferous trees covering much of the mountain slopes, indicative of a high-altitude or alpine environment.\\n\\n4. **Question:** What could the cows be utilizing in terms of food sources within this image?\\n **Answer:** The cows are grazing on the grass and other vegetation present in the field, which is a common food source for cattle. The mixture of green grass and patches of'}, {'original_caption': 'Farmaderbe - Max color vegetal 24 Castano moka', 'image_url': 'https://ss-pics.s3.eu-west-1.amazonaws.com/files/1619887/page-V.987024.jpg?1600681301', 'generated_qa': '{\"question\": \"What company produces the MAXCOLORE vegetable coloring product?\", \"answer\": \"The product is produced by Castando Moka,\" which is indicated in the branding at the top right of the box. This is supported by the brand name and the company logo on the packaging.\"}\\n{\"question\": \"What are the main ingredients in the MAXCOLORE vegetable coloring product as stated on the packaging?\", \"answer\": \"The main ingredients are \\'Tricologie\\' combined with \\'Stimtex AS,\\' \\'Argan,\\' \\'Marine Oil,\\' \\'Litchi Chinesis,\\' \\'Chloride,\\' \\'Calcium,\\' \\'Sodium Phosphate,\\' \\'Maltodextrin,\\' \\'Potassium Chloride,\\' \\'BHT,\\' and \\'Sodium Benzoate\\' according to the ingredients list. These ingredients are listed for their specific functions and properties related to hair coloring and preservation.\"}\\n{\"question\": \"Does the MAXCOLORE vegetable coloring product contain any metal components?\", \"answer\": \"No, the product specifies that it is devoid of metal components, indicated by \\'ZERO METAL CONT Laurent\\' in the description.\"}\\nThis question-answer format is designed to address potential customer inquiries about the product, providing'}]\n"
]
}
],
"source": [
"# Here you do three things:\n",
"# 1- Stream the LAION dataset (limited to 5 samples in this example)\n",
"# 2- Get Q&A pairs from Fast VLM\n",
"# 3- Push the results to your own repo\n",
"\n",
"#OUTPUT_REPO = \"<yourUsername>/laion-vlm-analysis\" # If set to None, it skips the push\n",
"OUTPUT_REPO = None\n",
"print(\"Streaming LAION dataset...\")\n",
"dataset = load_dataset(\"laion/relaion2B-en-research-safe\", streaming=True)\n",
"\n",
"analyzed_examples = []\n",
"\n",
"for i, example in enumerate(dataset['train'].take(5)):\n",
" print(f\"\\nExample {i+1}:\")\n",
" print(f\"Original caption: {example['caption']}\")\n",
" print(f\"Image URL: {example['url']}\")\n",
"\n",
" # Generate Q&A pairs with VLM\n",
" qa_pairs = generate_qa_pairs(example['url'])\n",
" print(f\"Generated Q&A: {qa_pairs}\")\n",
"\n",
" analyzed_examples.append({\n",
" 'original_caption': example['caption'],\n",
" 'image_url': example['url'],\n",
" 'generated_qa': qa_pairs,\n",
" })\n",
" print(\"---\")\n",
"\n",
"# Create and push dataset\n",
"analyzed_dataset = Dataset.from_list(analyzed_examples)\n",
"print(analyzed_examples)\n",
"if OUTPUT_REPO is not None:\n",
" analyzed_dataset.push_to_hub(OUTPUT_REPO)\n",
" print(f\"Dataset available at: {OUTPUT_REPO}\")"
]
},
{
"cell_type": "markdown",
"source": [
"### 4.2.5 Preparing the dataset for consumption\n",
"Getting data from a webdataset sample. Here you can see how we stream data from inside a tar file from a webdataset\n"
],
"metadata": {
"id": "hMQKJo-2Bm_l"
}
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "gvzSv7ADFk_-",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "789ee25c-4329-44f5-84e3-874eedc83f34"
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Sample PMC4991227_00003\n",
"Annotations: {'annotations': [{'area': 11114.139543321944, 'bbox': [313.74, 51.71, 235.78, 50.59], 'category_id': 1, 'category_name': 'text', 'id': 1690135, 'image_id': 174179, 'iscrowd': 0, 'segmentation': [[313.74, 51.71, 549.51, 51.71, 549.51, 64.75, 549.52, 64.75, 549.52, 76.34, 549.45, 76.34, 549.45, 89.32, 486.89, 89.32, 486.89, 102.3, 313.74, 102.3, 313.74, 90.7, 313.74, 77.73, 313.74, 64.75, 313.74, 51.71]]}, {'area': 36452.22784148902, 'bbox': [59.98, 363.82, 235.83, 154.6], 'category_id': 1, 'category_name': 'text', 'id': 1690136, 'image_id': 174179, 'iscrowd': 0, 'segmentation': [[59.98, 363.82, 295.8, 363.82, 295.8, 375.41, 295.74, 375.41, 295.74, 389.67, 295.75, 389.67, 295.75, 401.43, 295.75, 401.43, 295.75, 415.86, 295.75, 415.86, 295.75, 428.84, 295.81, 428.84, 295.81, 440.43, 295.75, 440.43, 295.75, 454.86, 295.77, 454.86, 295.77, 466.45, 295.74, 466.45, 295.74, 480.81, 295.78, 480.81, 295.78, 492.41, 295.77, 492.41, 295.77, 505.38, 295.75, 505.38, 295.75, 518.42, 59.98, 518.42, 59.98, 506.83, 59.98, 493.79, 59.98, 480.81, 59.98, 467.84, 59.98, 454.86, 59.98, 441.82, 59.98, 428.84, 59.98, 415.86, 59.98, 402.82, 59.98, 389.67, 59.98, 376.86, 59.98, 363.82]]}, {'area': 20601.87269781693, 'bbox': [313.74, 103.68, 235.76, 89.59], 'category_id': 1, 'category_name': 'text', 'id': 1690137, 'image_id': 174179, 'iscrowd': 0, 'segmentation': [[325.7, 103.68, 549.48, 103.68, 549.48, 116.72, 549.49, 116.72, 549.49, 128.31, 549.46, 128.31, 549.46, 142.68, 549.47, 142.68, 549.47, 154.27, 549.44, 154.27, 549.44, 168.7, 549.5, 168.7, 549.5, 180.29, 521.66, 180.29, 521.66, 193.27, 313.74, 193.27, 313.74, 181.68, 313.74, 168.7, 313.74, 155.72, 313.74, 142.68, 313.74, 129.7, 313.74, 116.72, 325.7, 116.72, 325.7, 103.68]]}, {'area': 24022.353919701418, 'bbox': [313.74, 194.72, 235.76, 102.56], 'category_id': 1, 'category_name': 'text', 'id': 1690138, 'image_id': 174179, 'iscrowd': 0, 'segmentation': [[325.7, 194.72, 549.48, 194.72, 549.48, 206.31, 549.47, 206.31, 549.47, 220.67, 549.47, 220.67, 549.47, 233.71, 549.49, 233.71, 549.49, 246.69, 549.5, 246.69, 549.5, 258.28, 549.44, 258.28, 549.44, 271.26, 549.43, 271.26, 549.43, 285.35, 549.47, 285.35, 549.47, 297.28, 313.74, 297.28, 313.74, 285.35, 313.74, 272.26, 313.74, 259.67, 313.74, 246.69, 313.74, 233.71, 313.74, 220.67, 313.74, 207.7, 325.7, 207.7, 325.7, 194.72]]}, {'area': 51573.07954365853, 'bbox': [313.74, 298.67, 235.78, 219.56], 'category_id': 1, 'category_name': 'text', 'id': 1690139, 'image_id': 174179, 'iscrowd': 0, 'segmentation': [[325.7, 298.67, 549.49, 298.67, 549.49, 310.26, 549.45, 310.26, 549.45, 323.24, 549.43, 323.24, 549.43, 337.67, 549.47, 337.67, 549.47, 349.26, 547.37, 349.26, 547.37, 363.14, 549.43, 363.14, 549.43, 376.66, 549.47, 376.66, 549.47, 389.64, 549.52, 389.64, 549.52, 401.23, 549.51, 401.23, 549.51, 414.21, 549.5, 414.21, 549.5, 428.64, 549.51, 428.64, 549.51, 440.23, 549.43, 440.23, 549.43, 454.66, 549.49, 454.66, 549.49, 467.64, 549.5, 467.64, 549.5, 479.23, 549.43, 479.23, 549.43, 493.66, 549.45, 493.66, 549.45, 506.63, 549.51, 506.63, 549.51, 518.23, 313.74, 518.23, 313.74, 506.63, 313.74, 493.66, 313.74, 480.23, 313.74, 467.64, 313.74, 454.66, 313.74, 441.22, 313.74, 428.64, 313.74, 415.66, 313.74, 402.62, 313.74, 389.64, 313.74, 376.66, 313.74, 363.14, 313.74, 350.26, 313.74, 337.67, 313.74, 324.3, 313.74, 311.65, 325.7, 311.65, 325.7, 298.67]]}, {'area': 3647.5442417136946, 'bbox': [60.04, 50.43, 235.74, 22.63], 'category_id': 1, 'category_name': 'text', 'id': 1690140, 'image_id': 174179, 'iscrowd': 0, 'segmentation': [[60.04, 50.43, 295.77, 50.43, 295.77, 62.07, 142.33, 62.07, 142.33, 73.07, 60.04, 73.07, 60.04, 62.07, 60.04, 62.07, 60.04, 50.43]]}, {'area': 6928.976886857068, 'bbox': [59.98, 544.21, 489.43, 22.32], 'category_id': 1, 'category_name': 'text', 'id': 1690141, 'image_id': 174179, 'iscrowd': 0, 'segmentation': [[59.98, 544.21, 549.41, 544.21, 549.41, 555.52, 186.4, 555.52, 186.4, 566.52, 59.98, 566.52, 59.98, 555.84, 59.98, 555.84, 59.98, 544.21]]}, {'area': 2128.087193914893, 'bbox': [60.04, 331.74, 230.57, 9.23], 'category_id': 1, 'category_name': 'text', 'id': 1690142, 'image_id': 174179, 'iscrowd': 0, 'segmentation': [[60.04, 331.74, 290.6, 331.74, 290.6, 340.97, 60.04, 340.97, 60.04, 331.74]]}, {'area': 60529.66627771362, 'bbox': [60.03, 74.11, 235.79, 256.7], 'category_id': 4, 'category_name': 'table', 'id': 1690143, 'image_id': 174179, 'iscrowd': 0, 'segmentation': [[60.03, 74.11, 295.83, 74.11, 295.83, 330.82, 60.03, 330.82, 60.03, 74.11]]}, {'area': 81781.74340952508, 'bbox': [59.98, 567.57, 489.49, 167.08], 'category_id': 4, 'category_name': 'table', 'id': 1690144, 'image_id': 174179, 'iscrowd': 0, 'segmentation': [[59.98, 567.57, 549.47, 567.57, 549.47, 734.64, 59.98, 734.64, 59.98, 567.57]]}], 'file_name': 'PMC4991227_00003.jpg', 'height': 794, 'id': 174179, 'width': 610}\n"
]
}
],
"source": [
"\n",
"\n",
"base_url = \"https://huggingface.co/datasets/vlmbook/small-publaynet-wds/resolve/main/publaynet-train-{i:06d}.tar\"\n",
"urls = [base_url.format(i=i) for i in range(4)]\n",
"dataset = load_dataset(\"webdataset\", data_files={\"train\": urls}, split=\"train\", streaming=True)\n",
"# From here, use like any HF dataset\n",
"for sample in dataset:\n",
" print(f\"Sample {sample['__key__']}\")\n",
" img_value = sample['png']\n",
" print(f\"Annotations: {sample['json']}\")\n",
" break\n"
]
}
],
"metadata": {
"colab": {
"provenance": [],
"gpuType": "T4"
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
},
"language_info": {
"name": "python"
},
"accelerator": "GPU"
},
"nbformat": 4,
"nbformat_minor": 0
}
|