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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""

- handle_found_object: Called when an object is successfully found and downloaded. Here,
    the object has the same sha256 as the one that was downloaded with Objaverse-XL. If
    not specified, the object will be downloaded, but nothing will be done with it.

    Args:
        file (str): Local path to the downloaded 3D object.
        github_url (str): GitHub URL of the 3D object.
        sha256 (str): SHA256 of the contents of the 3D object.
        repo (str): Name of the GitHub repo where the 3D object comes from.
        organization (str): Name of the GitHub organization where the 3D object comes from.
    Returns: Any

- handle_new_object: Called when a new object is found. Here, the object is not used in
    Objaverse-XL, but is still downloaded with the repository. The object may have not
    been used because it does not successfully import into Blender. If not specified,
    the object will be downloaded, but nothing will be done with it.

    Args:
        file (str): Local path to the downloaded 3D object.
        github_url (str): GitHub URL of the 3D object.
        sha256 (str): SHA256 of the contents of the 3D object.
        repo (str): Name of the GitHub repo where the 3D object comes from.
        organization (str): Name of the GitHub organization where the 3D object comes from.
    Returns: Any

- handle_modified_object: Called when a modified object is found and downloaded. Here,
    the object is successfully downloaded, but it has a different sha256 than the one
    that was downloaded with Objaverse-XL. This is not expected to happen very often,
    because the same commit hash is used for each repo. If not specified, the object
    will be downloaded, but nothing will be done with it.

    Args:
        file (str): Local path to the downloaded 3D object.
        github_url (str): GitHub URL of the 3D object.
        sha256 (str): SHA256 of the contents of the 3D object.
        repo (str): Name of the GitHub repo where the 3D object comes from.
        organization (str): Name of the GitHub organization where the 3D object comes from.
    Returns: Any

- handle_missing_object: Called when an object that is in Objaverse-XL is not found.
    Here, it is likely that the repository was deleted or renamed. If not specified, the
    object will be downloaded, but nothing will be done with it.

    Args:
        github_url (str): GitHub URL of the 3D object.
        sha256 (str): SHA256 of the contents of the original 3D object.
        repo (str): Name of the GitHub repo where the 3D object comes from.
        organization (str): Name of the GitHub organization where the 3D object comes from.
    Returns: Any


Note: You'll likely find more objects by 

"""

# %%
import shutil
import json
import pandas as pd
from typing import Dict, List, Optional, Literal, Callable
from tqdm import tqdm
import os
import tarfile
import fsspec
import requests
import tempfile
import subprocess
from loguru import logger
import hashlib
from multiprocessing import Pool
import multiprocessing

FILE_EXTENSIONS = [
    ".obj",
    ".glb",
    ".gltf",
    ".usdz",
    ".usd",
    ".fbx",
    ".stl",
    ".usda",
    ".dae",
    ".ply",
    ".abc",
    ".blend",
]


def load_github_metadata(download_dir: str = "~/.objaverse") -> pd.DataFrame:
    """Loads the GitHub 3D object metadata as a Pandas DataFrame.

    Args:
        download_dir (str, optional): Directory to download the parquet metadata file.
            Supports all file systems supported by fsspec. Defaults to "~/.objaverse".

    Returns:
        pd.DataFrame: GitHub 3D object metadata as a Pandas DataFrame with columns for
            the object "githubUrl", "license", and "sha256".
    """
    filename = os.path.join(download_dir, "github", "github-urls.parquet")
    fs, path = fsspec.core.url_to_fs(filename)
    fs.makedirs(os.path.dirname(path), exist_ok=True)

    # download the parquet file if it doesn't exist
    if not fs.exists(path):
        url = "https://huggingface.co/datasets/allenai/objaverse-xl/resolve/main/github/github-urls.parquet"

        response = requests.get(url)
        response.raise_for_status()
        with fs.open(path, "wb") as file:
            file.write(response.content)

    # load the parquet file with fsspec
    with fs.open(path) as f:
        df = pd.read_parquet(f)

    return df


def _get_repo_id_with_hash(item: pd.Series) -> str:
    org, repo = item["githubUrl"].split("/")[3:5]
    commit_hash = item["githubUrl"].split("/")[6]
    return f"{org}/{repo}/{commit_hash}"


def _git_shallow_clone(repo_url: str, target_directory: str) -> bool:
    return _run_command_with_check(
        ["git", "clone", "--depth", "1", repo_url, target_directory],
    )


def _run_command_with_check(command: List[str], cwd: Optional[str] = None) -> bool:
    try:
        subprocess.run(
            command,
            cwd=cwd,
            check=True,
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL,
        )
        return True
    except subprocess.CalledProcessError as e:
        logger.error("Error:", e)
        logger.error(e.stdout)
        logger.error(e.stderr)
        return False


def get_file_hash(file_path: str) -> str:
    # Check if the path is a symbolic link
    if os.path.islink(file_path):
        # Resolve the symbolic link
        resolved_path = os.readlink(file_path)
        # Check if the resolved path exists
        if not os.path.exists(resolved_path):
            raise FileNotFoundError(
                f"The symbolic link points to a file that doesn't exist: {resolved_path}"
            )
    sha256 = hashlib.sha256()
    # Read the file from the path
    with open(file_path, "rb") as f:
        # Loop till the end of the file
        for byte_block in iter(lambda: f.read(4096), b""):
            sha256.update(byte_block)
    return sha256.hexdigest()


def _process_repo(
    repo_id: str,
    fs: fsspec.AbstractFileSystem,
    base_dir: str,
    save_repo_format: Optional[Literal["zip", "tar", "tar.gz", "files"]],
    expected_objects: Dict[str, str],
    handle_found_object: Optional[Callable],
    handle_modified_object: Optional[Callable],
    handle_missing_object: Optional[Callable],
    handle_new_object: Optional[Callable],
    commit_hash: Optional[str],
) -> List[Dict[str, str]]:
    """

    Args:
        expected_objects (Dict[str, str]): Dictionary of objects that one expects to
            find in the repo. Keys are the GitHub URLs and values are the sha256 of the
            objects.
    """
    # NOTE: assuming that the user has already checked that the repo doesn't exist,
    org, repo = repo_id.split("/")

    with tempfile.TemporaryDirectory() as temp_dir:
        # clone the repo to a temp directory
        target_directory = os.path.join(temp_dir, repo)
        successful_clone = _git_shallow_clone(
            f"https://github.com/{org}/{repo}.git", target_directory
        )
        if not successful_clone:
            logger.error(f"Could not clone {repo_id}")
            if handle_missing_object is not None:
                for github_url, sha256 in expected_objects.items():
                    handle_missing_object(
                        github_url=github_url,
                        sha256=sha256,
                        repo=repo,
                        organization=org,
                    )
            return []

        # use the commit hash if specified
        repo_commit_hash = _get_commit_hash_from_local_git_dir(target_directory)
        if commit_hash is not None:
            keep_going = True
            if repo_commit_hash != commit_hash:
                # run git reset --hard && git checkout 37f4d8d287e201ce52c048bf74d46d6a09d26b2c
                if not _run_command_with_check(
                    ["git", "fetch", "origin", commit_hash], target_directory
                ):
                    logger.error(
                        f"Error in git fetch! Sticking with {repo_commit_hash=} instead of {commit_hash=}"
                    )
                    keep_going = False

                if keep_going and not _run_command_with_check(
                    ["git", "reset", "--hard"], target_directory
                ):
                    logger.error(
                        f"Error in git reset! Sticking with {repo_commit_hash=} instead of {commit_hash=}"
                    )
                    keep_going = False

                if keep_going:
                    if _run_command_with_check(
                        ["git", "checkout", commit_hash], target_directory
                    ):
                        repo_commit_hash = commit_hash
                    else:
                        logger.error(
                            f"Error in git checkout! Sticking with {repo_commit_hash=} instead of {commit_hash=}"
                        )

        # pull the lfs files
        _pull_lfs_files(target_directory)

        # get all the files in the repo
        files = _list_files(target_directory)
        files_with_3d_extension = [
            file
            for file in files
            if any(file.lower().endswith(ext) for ext in FILE_EXTENSIONS)
        ]

        # get the sha256 for each file
        file_hashes = []
        for file in files_with_3d_extension:
            file_hash = get_file_hash(file)
            # remove the temp_dir from the file path
            github_url = file.replace(
                target_directory,
                f"https://github.com/{org}/{repo}/blob/{repo_commit_hash}",
            )
            file_hashes.append(dict(sha256=file_hash, githubUrl=github_url))

            # handle the object under different conditions
            if github_url in expected_objects:
                if expected_objects[github_url] == file_hash:
                    if handle_found_object is not None:
                        handle_found_object(
                            file=file,
                            github_url=github_url,
                            sha256=file_hash,
                            repo=repo,
                            organization=org,
                        )
                else:
                    if handle_modified_object is not None:
                        handle_modified_object(
                            file=file,
                            github_url=github_url,
                            sha256=file_hash,
                            repo=repo,
                            organization=org,
                        )
            elif handle_new_object is not None:
                handle_new_object(
                    file=file,
                    github_url=github_url,
                    sha256=file_hash,
                    repo=repo,
                    organization=org,
                )

        # save the file hashes to a json file
        with open(
            os.path.join(target_directory, ".objaverse-file-hashes.json"), "w"
        ) as f:
            json.dump(file_hashes, f, indent=2)

        # remove the .git directory
        shutil.rmtree(os.path.join(target_directory, ".git"))

        if save_repo_format is not None:
            logger.debug(f"Saving as {save_repo_format}")
            # save the repo to a zip file
            if save_repo_format == "zip":
                shutil.make_archive(target_directory, "zip", target_directory)
            elif save_repo_format == "tar":
                with tarfile.open(os.path.join(temp_dir, f"{repo}.tar"), "w") as tar:
                    tar.add(target_directory, arcname=repo)
            elif save_repo_format == "tar.gz":
                with tarfile.open(
                    os.path.join(temp_dir, f"{repo}.tar.gz"), "w:gz"
                ) as tar:
                    tar.add(target_directory, arcname=repo)
            elif save_repo_format == "files":
                pass
            else:
                raise ValueError(
                    f"save_repo_format must be one of zip, tar, tar.gz, files. Got {save_repo_format}"
                )

            dirname = os.path.join(base_dir, "repos", org)
            fs.makedirs(dirname, exist_ok=True)
            if save_repo_format != "files":
                # move the repo to the correct location (with put)
                fs.put(
                    os.path.join(temp_dir, f"{repo}.{save_repo_format}"),
                    os.path.join(dirname, f"{repo}.{save_repo_format}"),
                )
            else:
                # move the repo to the correct location (with put)
                fs.put(target_directory, dirname, recursive=True)

    # get each object that was missing from the expected objects
    if handle_missing_object is not None:
        obtained_urls = {x["githubUrl"] for x in file_hashes}
        for github_url, sha256 in expected_objects.items():
            if github_url not in obtained_urls:
                handle_missing_object(
                    github_url=github_url,
                    sha256=sha256,
                    repo=repo,
                    organization=org,
                )

    return file_hashes


def _list_files(root_dir: str) -> List[str]:
    return [
        os.path.join(root, f) for root, dirs, files in os.walk(root_dir) for f in files
    ]


def _pull_lfs_files(repo_dir: str) -> None:
    if _has_lfs_files(repo_dir):
        subprocess.run(["git", "lfs", "pull"], cwd=repo_dir)


def _has_lfs_files(repo_dir: str) -> bool:
    gitattributes_path = os.path.join(repo_dir, ".gitattributes")
    if not os.path.exists(gitattributes_path):
        return False
    with open(gitattributes_path, "r") as f:
        for line in f:
            if "filter=lfs" in line:
                return True
    return False


def _get_commit_hash_from_local_git_dir(local_git_dir: str) -> str:
    # get the git hash of the repo
    result = subprocess.run(
        ["git", "rev-parse", "HEAD"], cwd=local_git_dir, capture_output=True
    )
    commit_hash = result.stdout.strip().decode("utf-8")
    return commit_hash


def _parallel_process_repo(args) -> List[Dict[str, str]]:
    (
        repo_id_hash,
        fs,
        base_dir,
        save_repo_format,
        expected_objects,
        handle_found_object,
        handle_modified_object,
        handle_missing_object,
        handle_new_object,
    ) = args
    repo_id = "/".join(repo_id_hash.split("/")[:2])
    commit_hash = repo_id_hash.split("/")[2]
    return _process_repo(
        repo_id=repo_id,
        fs=fs,
        base_dir=base_dir,
        save_repo_format=save_repo_format,
        expected_objects=expected_objects,
        handle_found_object=handle_found_object,
        handle_modified_object=handle_modified_object,
        handle_missing_object=handle_missing_object,
        handle_new_object=handle_new_object,
        commit_hash=commit_hash,
    )


def _process_group(group):
    key, group_df = group
    return key, group_df.set_index("githubUrl")["sha256"].to_dict()


# %%


def download_github_objects(
    objects: pd.DataFrame,
    processes: Optional[int] = None,
    download_dir: str = "~/.objaverse",
    save_repo_format: Optional[Literal["zip", "tar", "tar.gz", "files"]] = None,
    handle_found_object: Optional[Callable] = None,
    handle_modified_object: Optional[Callable] = None,
    handle_missing_object: Optional[Callable] = None,
    handle_new_object: Optional[Callable] = None,
) -> List[Dict[str, str]]:
    """Download the specified GitHub objects.

    Args:
        objects (pd.DataFrmae): GitHub objects to download. Must have columns for the
            object "githubUrl" and "sha256". Use the load_github_metadata function to
            get the metadata.
        processes (Optional[int], optional): Number of processes to use for downloading.
            If None, will use the number of CPUs on the machine. Defaults to None.
        download_dir (str, optional): Directory to download the GitHub objects to.
            Supports all file systems supported by fsspec. Defaults to "~/.objaverse".

    Returns:
        List[Dict[str, str]]: List of dictionaries with the keys "githubUrl" and
            "sha256" for each downloaded object.
    """
    if processes is None:
        processes = multiprocessing.cpu_count()

    base_download_dir = os.path.join(download_dir, "github")
    fs, path = fsspec.core.url_to_fs(base_download_dir)
    fs.makedirs(path, exist_ok=True)

    # Getting immediate subdirectories of root_path
    if save_repo_format == "files":
        downloaded_repo_dirs = fs.glob(base_download_dir + "/repos/*/*/")
        downloaded_repo_ids = set(
            ["/".join(x.split("/")[-2:]) for x in downloaded_repo_dirs]
        )
    else:
        downloaded_repo_dirs = fs.glob(
            base_download_dir + f"/repos/*/*.{save_repo_format}"
        )
        downloaded_repo_ids = set()
        for x in downloaded_repo_dirs:
            org, repo = x.split("/")[-2:]
            repo = repo[: -len(f".{save_repo_format}")]
            repo_id = f"{org}/{repo}"
            downloaded_repo_ids.add(repo_id)

    # make copy of objects
    objects = objects.copy()

    # get the unique repoIds
    objects["repoIdHash"] = objects.apply(_get_repo_id_with_hash, axis=1)
    repo_id_hashes = set(objects["repoIdHash"].unique().tolist())
    repo_ids = set(
        ["/".join(repo_id_hash.split("/")[:2]) for repo_id_hash in repo_id_hashes]
    )
    assert len(repo_id_hashes) == len(repo_ids), (
        f"More than 1 commit hash per repoId!"
        f" {len(repo_id_hashes)=}, {len(repo_ids)=}"
    )

    logger.info(
        f"Provided {len(repo_ids)} repoIds with {len(objects)} objects to process."
    )

    # remove repoIds that have already been downloaded
    repo_ids_to_download = repo_ids - downloaded_repo_ids
    repo_id_hashes_to_download = [
        repo_id_hash
        for repo_id_hash in repo_id_hashes
        if "/".join(repo_id_hash.split("/")[:2]) in repo_ids_to_download
    ]

    logger.info(
        f"Found {len(repo_ids_to_download)} not yet downloaded. Downloading now..."
    )

    # get the objects to download
    groups = list(objects.groupby("repoIdHash"))
    with Pool(processes=processes) as pool:
        out_list = list(
            tqdm(
                pool.imap_unordered(_process_group, groups),
                total=len(groups),
                desc="Grouping objects by repository",
            )
        )
    objects_per_repo_id_hash = dict(out_list)

    all_args = [
        (
            repo_id_hash,
            fs,
            path,
            save_repo_format,
            objects_per_repo_id_hash[repo_id_hash],
            handle_found_object,
            handle_missing_object,
            handle_modified_object,
            handle_new_object,
        )
        for repo_id_hash in repo_id_hashes_to_download
    ]

    with Pool(processes=processes) as pool:
        # use tqdm to show progress
        out = list(
            tqdm(
                pool.imap_unordered(_parallel_process_repo, all_args),
                total=len(all_args),
            )
        )
    out_list = [item for sublist in out for item in sublist]
    return out_list


def test_process_repo():
    download_dir = "~/.objaverse-tests"
    base_download_dir = os.path.join(download_dir, "github")
    fs, path = fsspec.core.url_to_fs(base_download_dir)
    fs.makedirs(path, exist_ok=True)

    for save_repo_format in ["tar", "tar.gz", "zip", "files"]:
        # shutil.rmtree(os.path.join(path, "repos"), ignore_errors=True)
        out = _process_repo(
            repo_id="mattdeitke/objaverse-xl-test-files",
            fs=fs,
            base_dir=path,
            save_repo_format=save_repo_format,  # type: ignore
            expected_objects=dict(),
            handle_found_object=None,
            handle_modified_object=None,
            handle_missing_object=None,
            handle_new_object=None,
            commit_hash="6928b08a2501aa7a4a4aabac1f888b66e7782056",
        )

        # test that the sha256's are correct
        assert len(out) == 3
        sha256s = [x["sha256"] for x in out]
        for sha256 in [
            "d2b9a5d7c47dc93526082c9b630157ab6bce4fd8669610d942176f4a36444e71",
            "04e6377317d6818e32c5cbd1951e76deb3641bbf4f6db6933046221d5fbf1c5c",
            "7037575f47816118e5a34e7c0da9927e1be7be3f5b4adfac337710822eb50fa9",
        ]:
            assert sha256 in sha256s, f"{sha256=} not in {sha256s=}"
        github_urls = [x["githubUrl"] for x in out]
        for github_url in [
            "https://github.com/mattdeitke/objaverse-xl-test-files/blob/6928b08a2501aa7a4a4aabac1f888b66e7782056/example.fbx",
            "https://github.com/mattdeitke/objaverse-xl-test-files/blob/6928b08a2501aa7a4a4aabac1f888b66e7782056/example.glb",
            "https://github.com/mattdeitke/objaverse-xl-test-files/blob/6928b08a2501aa7a4a4aabac1f888b66e7782056/example.obj",
        ]:
            assert github_url in github_urls, f"{github_url=} not in {github_urls=}"

        # test that the files are correct
        if save_repo_format != "files":
            assert fs.exists(
                os.path.join(
                    path,
                    "repos",
                    "mattdeitke",
                    f"objaverse-xl-test-files.{save_repo_format}",
                )
            )
        else:
            assert fs.exists(
                os.path.join(
                    base_download_dir, "repos", "mattdeitke", "objaverse-xl-test-files"
                )
            )


def test_handle_new_object():
    found_objects = []
    handle_found_object = (
        lambda file, github_url, sha256, repo, organization: found_objects.append(
            dict(
                file=file,
                github_url=github_url,
                sha256=sha256,
                repo=repo,
                organization=organization,
            )
        )
    )

    missing_objects = []
    handle_missing_object = (
        lambda github_url, sha256, repo, organization: missing_objects.append(
            dict(
                github_url=github_url,
                sha256=sha256,
                repo=repo,
                organization=organization,
            )
        )
    )

    new_objects = []
    handle_new_object = (
        lambda file, github_url, sha256, repo, organization: new_objects.append(
            dict(
                file=file,
                github_url=github_url,
                sha256=sha256,
                repo=repo,
                organization=organization,
            )
        )
    )

    modified_objects = []
    handle_modified_object = (
        lambda file, github_url, sha256, repo, organization: modified_objects.append(
            dict(
                file=file,
                github_url=github_url,
                sha256=sha256,
                repo=repo,
                organization=organization,
            )
        )
    )

    download_dir = "~/.objaverse-tests"
    base_download_dir = os.path.join(download_dir, "github")
    fs, path = fsspec.core.url_to_fs(base_download_dir)
    fs.makedirs(path, exist_ok=True)

    shutil.rmtree(os.path.join(path, "repos"), ignore_errors=True)
    out = _process_repo(
        repo_id="mattdeitke/objaverse-xl-test-files",
        fs=fs,
        base_dir=path,
        save_repo_format=None,
        expected_objects=dict(),
        handle_found_object=handle_found_object,
        handle_modified_object=handle_modified_object,
        handle_missing_object=handle_missing_object,
        handle_new_object=handle_new_object,
        commit_hash="6928b08a2501aa7a4a4aabac1f888b66e7782056",
    )

    assert len(out) == 3
    assert len(new_objects) == 3
    assert len(found_objects) == 0
    assert len(modified_objects) == 0
    assert len(missing_objects) == 0


def test_handle_found_object():
    found_objects = []
    handle_found_object = (
        lambda file, github_url, sha256, repo, organization: found_objects.append(
            dict(
                file=file,
                github_url=github_url,
                sha256=sha256,
                repo=repo,
                organization=organization,
            )
        )
    )

    missing_objects = []
    handle_missing_object = (
        lambda github_url, sha256, repo, organization: missing_objects.append(
            dict(
                github_url=github_url,
                sha256=sha256,
                repo=repo,
                organization=organization,
            )
        )
    )

    new_objects = []
    handle_new_object = (
        lambda file, github_url, sha256, repo, organization: new_objects.append(
            dict(
                file=file,
                github_url=github_url,
                sha256=sha256,
                repo=repo,
                organization=organization,
            )
        )
    )

    modified_objects = []
    handle_modified_object = (
        lambda file, github_url, sha256, repo, organization: modified_objects.append(
            dict(
                file=file,
                github_url=github_url,
                sha256=sha256,
                repo=repo,
                organization=organization,
            )
        )
    )

    download_dir = "~/.objaverse-tests"
    base_download_dir = os.path.join(download_dir, "github")
    fs, path = fsspec.core.url_to_fs(base_download_dir)
    fs.makedirs(path, exist_ok=True)

    shutil.rmtree(os.path.join(path, "repos"), ignore_errors=True)
    out = _process_repo(
        repo_id="mattdeitke/objaverse-xl-test-files",
        fs=fs,
        base_dir=path,
        save_repo_format=None,
        expected_objects={
            "https://github.com/mattdeitke/objaverse-xl-test-files/blob/6928b08a2501aa7a4a4aabac1f888b66e7782056/example.fbx": "7037575f47816118e5a34e7c0da9927e1be7be3f5b4adfac337710822eb50fa9",
            "https://github.com/mattdeitke/objaverse-xl-test-files/blob/6928b08a2501aa7a4a4aabac1f888b66e7782056/example.glb": "04e6377317d6818e32c5cbd1951e76deb3641bbf4f6db6933046221d5fbf1c5c",
            "https://github.com/mattdeitke/objaverse-xl-test-files/blob/6928b08a2501aa7a4a4aabac1f888b66e7782056/example.obj": "d2b9a5d7c47dc93526082c9b630157ab6bce4fd8669610d942176f4a36444e71",
        },
        handle_found_object=handle_found_object,
        handle_modified_object=handle_modified_object,
        handle_missing_object=handle_missing_object,
        handle_new_object=handle_new_object,
        commit_hash="6928b08a2501aa7a4a4aabac1f888b66e7782056",
    )

    assert len(out) == 3
    assert len(found_objects) == 3
    assert len(missing_objects) == 0
    assert len(new_objects) == 0
    assert len(modified_objects) == 0


def test_handle_modified_object():
    found_objects = []
    handle_found_object = (
        lambda file, github_url, sha256, repo, organization: found_objects.append(
            dict(
                file=file,
                github_url=github_url,
                sha256=sha256,
                repo=repo,
                organization=organization,
            )
        )
    )

    missing_objects = []
    handle_missing_object = (
        lambda github_url, sha256, repo, organization: missing_objects.append(
            dict(
                github_url=github_url,
                sha256=sha256,
                repo=repo,
                organization=organization,
            )
        )
    )

    new_objects = []
    handle_new_object = (
        lambda file, github_url, sha256, repo, organization: new_objects.append(
            dict(
                file=file,
                github_url=github_url,
                sha256=sha256,
                repo=repo,
                organization=organization,
            )
        )
    )

    modified_objects = []
    handle_modified_object = (
        lambda file, github_url, sha256, repo, organization: modified_objects.append(
            dict(
                file=file,
                github_url=github_url,
                sha256=sha256,
                repo=repo,
                organization=organization,
            )
        )
    )

    download_dir = "~/.objaverse-tests"
    base_download_dir = os.path.join(download_dir, "github")
    fs, path = fsspec.core.url_to_fs(base_download_dir)
    fs.makedirs(path, exist_ok=True)

    shutil.rmtree(os.path.join(path, "repos"), ignore_errors=True)
    out = _process_repo(
        repo_id="mattdeitke/objaverse-xl-test-files",
        fs=fs,
        base_dir=path,
        save_repo_format=None,
        expected_objects={
            "https://github.com/mattdeitke/objaverse-xl-test-files/blob/6928b08a2501aa7a4a4aabac1f888b66e7782056/example.fbx": "7037575f47816118e5a34e7c0da9927e1be7be3f5b4adfac337710822eb50fa9<modified>",
            "https://github.com/mattdeitke/objaverse-xl-test-files/blob/6928b08a2501aa7a4a4aabac1f888b66e7782056/example.glb": "04e6377317d6818e32c5cbd1951e76deb3641bbf4f6db6933046221d5fbf1c5c",
            "https://github.com/mattdeitke/objaverse-xl-test-files/blob/6928b08a2501aa7a4a4aabac1f888b66e7782056/example.obj": "d2b9a5d7c47dc93526082c9b630157ab6bce4fd8669610d942176f4a36444e71",
        },
        handle_found_object=handle_found_object,
        handle_modified_object=handle_modified_object,
        handle_missing_object=handle_missing_object,
        handle_new_object=handle_new_object,
        commit_hash="6928b08a2501aa7a4a4aabac1f888b66e7782056",
    )

    assert len(out) == 3
    assert len(found_objects) == 2
    assert len(missing_objects) == 0
    assert len(new_objects) == 0
    assert len(modified_objects) == 1


def test_handle_missing_object():
    found_objects = []
    handle_found_object = (
        lambda file, github_url, sha256, repo, organization: found_objects.append(
            dict(
                file=file,
                github_url=github_url,
                sha256=sha256,
                repo=repo,
                organization=organization,
            )
        )
    )

    missing_objects = []
    handle_missing_object = (
        lambda github_url, sha256, repo, organization: missing_objects.append(
            dict(
                github_url=github_url,
                sha256=sha256,
                repo=repo,
                organization=organization,
            )
        )
    )

    new_objects = []
    handle_new_object = (
        lambda file, github_url, sha256, repo, organization: new_objects.append(
            dict(
                file=file,
                github_url=github_url,
                sha256=sha256,
                repo=repo,
                organization=organization,
            )
        )
    )

    modified_objects = []
    handle_modified_object = (
        lambda file, github_url, sha256, repo, organization: modified_objects.append(
            dict(
                file=file,
                github_url=github_url,
                sha256=sha256,
                repo=repo,
                organization=organization,
            )
        )
    )

    download_dir = "~/.objaverse-tests"
    base_download_dir = os.path.join(download_dir, "github")
    fs, path = fsspec.core.url_to_fs(base_download_dir)
    fs.makedirs(path, exist_ok=True)

    shutil.rmtree(os.path.join(path, "repos"), ignore_errors=True)
    out = _process_repo(
        repo_id="mattdeitke/objaverse-xl-test-files",
        fs=fs,
        base_dir=path,
        save_repo_format=None,
        expected_objects={
            "https://github.com/mattdeitke/objaverse-xl-test-files/blob/6928b08a2501aa7a4a4aabac1f888b66e7782056/example.fbx": "7037575f47816118e5a34e7c0da9927e1be7be3f5b4adfac337710822eb50fa9",
            "https://github.com/mattdeitke/objaverse-xl-test-files/blob/6928b08a2501aa7a4a4aabac1f888b66e7782056/example-2.fbx": "<fake-missing-object>",
            "https://github.com/mattdeitke/objaverse-xl-test-files/blob/6928b08a2501aa7a4a4aabac1f888b66e7782056/example.glb": "04e6377317d6818e32c5cbd1951e76deb3641bbf4f6db6933046221d5fbf1c5c",
            "https://github.com/mattdeitke/objaverse-xl-test-files/blob/6928b08a2501aa7a4a4aabac1f888b66e7782056/example.obj": "d2b9a5d7c47dc93526082c9b630157ab6bce4fd8669610d942176f4a36444e71",
        },
        handle_found_object=handle_found_object,
        handle_modified_object=handle_modified_object,
        handle_missing_object=handle_missing_object,
        handle_new_object=handle_new_object,
        commit_hash="6928b08a2501aa7a4a4aabac1f888b66e7782056",
    )

    assert len(out) == 3
    assert len(found_objects) == 3
    assert len(missing_objects) == 1
    assert len(new_objects) == 0
    assert len(modified_objects) == 0


def test_handle_missing_object_2():
    found_objects = []
    handle_found_object = (
        lambda file, github_url, sha256, repo, organization: found_objects.append(
            dict(
                file=file,
                github_url=github_url,
                sha256=sha256,
                repo=repo,
                organization=organization,
            )
        )
    )

    missing_objects = []
    handle_missing_object = (
        lambda github_url, sha256, repo, organization: missing_objects.append(
            dict(
                github_url=github_url,
                sha256=sha256,
                repo=repo,
                organization=organization,
            )
        )
    )

    new_objects = []
    handle_new_object = (
        lambda file, github_url, sha256, repo, organization: new_objects.append(
            dict(
                file=file,
                github_url=github_url,
                sha256=sha256,
                repo=repo,
                organization=organization,
            )
        )
    )

    modified_objects = []
    handle_modified_object = (
        lambda file, github_url, sha256, repo, organization: modified_objects.append(
            dict(
                file=file,
                github_url=github_url,
                sha256=sha256,
                repo=repo,
                organization=organization,
            )
        )
    )

    download_dir = "~/.objaverse-tests"
    base_download_dir = os.path.join(download_dir, "github")
    fs, path = fsspec.core.url_to_fs(base_download_dir)
    fs.makedirs(path, exist_ok=True)

    shutil.rmtree(os.path.join(path, "repos"), ignore_errors=True)
    out = _process_repo(
        repo_id="mattdeitke/objaverse-xl-test-files-does-not-exist",
        fs=fs,
        base_dir=path,
        save_repo_format=None,
        expected_objects={
            "https://github.com/mattdeitke/objaverse-xl-test-files/blob/6928b08a2501aa7a4a4aabac1f888b66e7782056/example.fbx": "7037575f47816118e5a34e7c0da9927e1be7be3f5b4adfac337710822eb50fa9",
            "https://github.com/mattdeitke/objaverse-xl-test-files/blob/6928b08a2501aa7a4a4aabac1f888b66e7782056/example-2.fbx": "<fake-missing-object>",
            "https://github.com/mattdeitke/objaverse-xl-test-files/blob/6928b08a2501aa7a4a4aabac1f888b66e7782056/example.glb": "04e6377317d6818e32c5cbd1951e76deb3641bbf4f6db6933046221d5fbf1c5c",
            "https://github.com/mattdeitke/objaverse-xl-test-files/blob/6928b08a2501aa7a4a4aabac1f888b66e7782056/example.obj": "d2b9a5d7c47dc93526082c9b630157ab6bce4fd8669610d942176f4a36444e71",
        },
        handle_found_object=handle_found_object,
        handle_modified_object=handle_modified_object,
        handle_missing_object=handle_missing_object,
        handle_new_object=handle_new_object,
        commit_hash="6928b08a2501aa7a4a4aabac1f888b66e7782056",
    )

    assert len(out) == 0
    assert len(found_objects) == 0
    assert len(missing_objects) == 4
    assert len(new_objects) == 0
    assert len(modified_objects) == 0


def test_download_cache():
    objects = pd.DataFrame(
        [
            {
                "githubUrl": "https://github.com/mattdeitke/objaverse-xl-test-files/blob/6928b08a2501aa7a4a4aabac1f888b66e7782056/example.fbx",
                "license": None,
                "sha256": "7037575f47816118e5a34e7c0da9927e1be7be3f5b4adfac337710822eb50fa9",
            },
            {
                "githubUrl": "https://github.com/mattdeitke/objaverse-xl-test-files/blob/6928b08a2501aa7a4a4aabac1f888b66e7782056/example.glb",
                "license": None,
                "sha256": "04e6377317d6818e32c5cbd1951e76deb3641bbf4f6db6933046221d5fbf1c5c",
            },
            {
                "githubUrl": "https://github.com/mattdeitke/objaverse-xl-test-files/blob/6928b08a2501aa7a4a4aabac1f888b66e7782056/example.obj",
                "license": None,
                "sha256": "d2b9a5d7c47dc93526082c9b630157ab6bce4fd8669610d942176f4a36444e71",
            },
        ]
    )

    # remove the repos directory
    for save_repo_format in ["tar", "tar.gz", "zip", "files"]:
        repos_dir = "~/.objaverse-tests/github/repos"
        shutil.rmtree(os.path.expanduser(repos_dir), ignore_errors=True)

        out = download_github_objects(
            objects=objects,
            processes=1,
            download_dir="~/.objaverse-tests",
            save_repo_format=save_repo_format,  # type: ignore
        )
        assert len(out) == 3

        out = download_github_objects(
            objects=objects,
            processes=1,
            download_dir="~/.objaverse-tests",
            save_repo_format=save_repo_format,  # type: ignore
        )
        assert len(out) == 0