|
import glob |
|
import json |
|
import multiprocessing |
|
import os |
|
import platform |
|
import random |
|
import subprocess |
|
import tempfile |
|
import time |
|
import zipfile |
|
from functools import partial |
|
from typing import List, Literal, Optional, Union |
|
|
|
import fire |
|
import fsspec |
|
import GPUtil |
|
import pandas as pd |
|
from loguru import logger |
|
|
|
from objaverse_xl.github import download_github_objects |
|
from objaverse_xl.utils import get_uid_from_str |
|
|
|
|
|
def log_processed_object(object_id: str, sha256: str, csv_filename: str) -> None: |
|
"""Log when an object is done being used. |
|
|
|
Args: |
|
object_id (str): ID of the object. |
|
sha256 (str): SHA256 of the object. |
|
csv_filename (str): Name of the CSV file to save the logs to. |
|
|
|
Returns: |
|
None |
|
""" |
|
|
|
|
|
dirname = os.path.expanduser(f"~/.objaverse/github/logs/") |
|
os.makedirs(dirname, exist_ok=True) |
|
with open(os.path.join(dirname, csv_filename), "a", encoding="utf-8") as f: |
|
f.write(f"{time.time()},{object_id},{sha256}\n") |
|
|
|
|
|
def zipdir(path: str, ziph: zipfile.ZipFile) -> None: |
|
"""Zip up a directory with an arcname structure. |
|
|
|
Args: |
|
path (str): Path to the directory to zip. |
|
ziph (zipfile.ZipFile): ZipFile handler object to write to. |
|
|
|
Returns: |
|
None |
|
""" |
|
|
|
for root, dirs, files in os.walk(path): |
|
for file in files: |
|
|
|
arcname = os.path.join(os.path.basename(root), file) |
|
ziph.write(os.path.join(root, file), arcname=arcname) |
|
|
|
|
|
def handle_found_object( |
|
file: str, |
|
github_url: str, |
|
sha256: str, |
|
repo: str, |
|
organization: str, |
|
num_renders: int, |
|
render_dir: str, |
|
only_northern_hemisphere: bool, |
|
gpu_devices: Union[int, List[int]], |
|
render_timeout: int, |
|
successful_log_file: str = "handle-found-object-successful.csv", |
|
failed_log_file: str = "handle-found-object-failed.csv", |
|
) -> None: |
|
"""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 None, 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. |
|
num_renders (int): Number of renders to save of the object. |
|
render_dir (str): Directory where the objects will be rendered. |
|
only_northern_hemisphere (bool): Only render the northern hemisphere of the |
|
object. |
|
gpu_devices (Union[int, List[int]]): GPU device(s) to use for rendering. If |
|
an int, the GPU device will be randomly selected from 0 to gpu_devices - 1. |
|
If a list, the GPU device will be randomly selected from the list. |
|
If 0, the CPU will be used for rendering. |
|
render_timeout (int): Number of seconds to wait for the rendering job to |
|
complete. |
|
successful_log_file (str): Name of the log file to save successful renders to. |
|
failed_log_file (str): Name of the log file to save failed renders to. |
|
|
|
Returns: |
|
None |
|
""" |
|
save_uid = get_uid_from_str(github_url) |
|
args = f"--object_path '{file}' --num_renders {num_renders}" |
|
|
|
|
|
using_gpu: bool = True |
|
gpu_i = 0 |
|
if isinstance(gpu_devices, int) and gpu_devices > 0: |
|
num_gpus = gpu_devices |
|
gpu_i = random.randint(0, num_gpus - 1) |
|
elif isinstance(gpu_devices, list): |
|
gpu_i = random.choice(gpu_devices) |
|
elif isinstance(gpu_devices, int) and gpu_devices == 0: |
|
using_gpu = False |
|
else: |
|
raise ValueError( |
|
f"gpu_devices must be an int > 0, 0, or a list of ints. Got {gpu_devices}." |
|
) |
|
|
|
with tempfile.TemporaryDirectory() as temp_dir: |
|
|
|
target_directory = os.path.join(temp_dir, save_uid) |
|
os.makedirs(target_directory, exist_ok=True) |
|
args += f" --output_dir {target_directory}" |
|
|
|
|
|
if platform.system() == "Linux" and using_gpu: |
|
args += " --engine BLENDER_EEVEE" |
|
elif platform.system() == "Darwin" or ( |
|
platform.system() == "Linux" and not using_gpu |
|
): |
|
|
|
|
|
|
|
args += " --engine CYCLES" |
|
else: |
|
raise NotImplementedError(f"Platform {platform.system()} is not supported.") |
|
|
|
|
|
if only_northern_hemisphere: |
|
args += " --only_northern_hemisphere" |
|
|
|
|
|
command = f"blender-3.2.2-linux-x64/blender --background --python blender_script.py -- {args}" |
|
if using_gpu: |
|
command = f"export DISPLAY=:0.{gpu_i} && {command}" |
|
|
|
|
|
subprocess.run(["bash", "-c", command], timeout=render_timeout, check=False) |
|
|
|
|
|
png_files = glob.glob(os.path.join(target_directory, "*.png")) |
|
metadata_files = glob.glob(os.path.join(target_directory, "*.json")) |
|
npy_files = glob.glob(os.path.join(target_directory, "*.npy")) |
|
if ( |
|
(len(png_files) != num_renders) |
|
or (len(npy_files) != num_renders) |
|
or (len(metadata_files) != 1) |
|
): |
|
logger.error(f"Found object {github_url} was not rendered successfully!") |
|
log_processed_object(github_url, sha256, failed_log_file) |
|
return |
|
|
|
|
|
with open(f"{target_directory}/metadata.json", "r", encoding="utf-8") as f: |
|
metadata = json.load(f) |
|
metadata["sha256"] = sha256 |
|
metadata["file_identifier"] = github_url |
|
metadata["save_uid"] = save_uid |
|
with open(f"{target_directory}/metadata.json", "w", encoding="utf-8") as f: |
|
json.dump(metadata, f, sort_keys=True, indent=2) |
|
|
|
|
|
|
|
with zipfile.ZipFile( |
|
f"{target_directory}.zip", "w", zipfile.ZIP_DEFLATED |
|
) as zipf: |
|
zipdir(target_directory, zipf) |
|
|
|
|
|
fs, path = fsspec.core.url_to_fs(render_dir) |
|
|
|
|
|
fs.makedirs(os.path.join(path, "github", "renders"), exist_ok=True) |
|
fs.put( |
|
os.path.join(f"{target_directory}.zip"), |
|
os.path.join(path, "github", "renders", f"{save_uid}.zip"), |
|
) |
|
|
|
|
|
log_processed_object(github_url, sha256, successful_log_file) |
|
|
|
|
|
def handle_new_object( |
|
file: str, |
|
github_url: str, |
|
sha256: str, |
|
repo: str, |
|
organization: str, |
|
log_file: str = "handle-new-object.csv", |
|
) -> None: |
|
"""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 None, 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. |
|
log_file (str): Name of the log file to save the handle_new_object logs to. |
|
|
|
Returns: |
|
None |
|
""" |
|
|
|
log_processed_object(github_url, sha256, log_file) |
|
|
|
|
|
def handle_modified_object( |
|
file: str, |
|
github_url: str, |
|
sha256: str, |
|
repo: str, |
|
organization: str, |
|
num_renders: int, |
|
render_dir: str, |
|
only_northern_hemisphere: bool, |
|
gpu_devices: Union[int, List[int]], |
|
render_timeout: int, |
|
) -> None: |
|
"""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 None, 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. |
|
num_renders (int): Number of renders to save of the object. |
|
render_dir (str): Directory where the objects will be rendered. |
|
only_northern_hemisphere (bool): Only render the northern hemisphere of the |
|
object. |
|
gpu_devices (Union[int, List[int]]): GPU device(s) to use for rendering. If |
|
an int, the GPU device will be randomly selected from 0 to gpu_devices - 1. |
|
If a list, the GPU device will be randomly selected from the list. |
|
If 0, the CPU will be used for rendering. |
|
render_timeout (int): Number of seconds to wait for the rendering job to |
|
complete. |
|
|
|
Returns: |
|
None |
|
""" |
|
handle_found_object( |
|
file=file, |
|
github_url=github_url, |
|
sha256=sha256, |
|
repo=repo, |
|
organization=organization, |
|
num_renders=num_renders, |
|
render_dir=render_dir, |
|
only_northern_hemisphere=only_northern_hemisphere, |
|
gpu_devices=gpu_devices, |
|
render_timeout=render_timeout, |
|
successful_log_file="handle-modified-object-successful.csv", |
|
failed_log_file="handle-modified-object-failed.csv", |
|
) |
|
|
|
|
|
def handle_missing_object( |
|
github_url: str, |
|
sha256: str, |
|
repo: str, |
|
organization: str, |
|
log_file: str = "handle-missing-object.csv", |
|
) -> None: |
|
"""Called when an object that is in Objaverse-XL is not found. |
|
|
|
Here, it is likely that the repository was deleted or renamed. If None, nothing |
|
will be done with the missing object. |
|
|
|
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. |
|
log_file (str): Name of the log file to save missing renders to. |
|
|
|
Returns: |
|
None |
|
""" |
|
|
|
log_processed_object(github_url, sha256, log_file) |
|
|
|
|
|
def get_example_objects() -> pd.DataFrame: |
|
"""Returns a DataFrame of example objects to use for debugging.""" |
|
return 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", |
|
}, |
|
] |
|
) |
|
|
|
|
|
def render_github_objects( |
|
render_dir: str = "~/.objaverse", |
|
num_renders: int = 12, |
|
processes: Optional[int] = None, |
|
save_repo_format: Optional[Literal["zip", "tar", "tar.gz"]] = None, |
|
only_northern_hemisphere: bool = False, |
|
render_timeout: int = 300, |
|
gpu_devices: Optional[Union[int, List[int]]] = None, |
|
) -> None: |
|
"""Renders all GitHub objects in the Objaverse-XL dataset. |
|
|
|
Args: |
|
render_dir (str): Directory where the objects will be rendered. |
|
num_renders (int): Number of renders to save of the object. |
|
processes (Optional[int]): Number of processes to use for downloading the |
|
objects. If None, defaults to multiprocessing.cpu_count() * 3. |
|
save_repo_format (Optional[Literal["zip", "tar", "tar.gz"]]): If not None, |
|
the GitHub repo will be deleted after rendering each object from it. |
|
only_northern_hemisphere (bool): Only render the northern hemisphere of the |
|
object. Useful for rendering objects that are obtained from photogrammetry, |
|
since the southern hemisphere is often has holes. |
|
render_timeout (int): Number of seconds to wait for the rendering job to |
|
complete. |
|
gpu_devices (Optional[Union[int, List[int]]]): GPU device(s) to use for |
|
rendering. If an int, the GPU device will be randomly selected from 0 to |
|
gpu_devices - 1. If a list, the GPU device will be randomly selected from |
|
the list. If 0, the CPU will be used for rendering. If None, defaults to |
|
use all available GPUs. |
|
|
|
Returns: |
|
None |
|
""" |
|
if platform.system() not in ["Linux", "Darwin"]: |
|
raise NotImplementedError( |
|
f"Platform {platform.system()} is not supported. Use Linux or MacOS." |
|
) |
|
|
|
|
|
parsed_gpu_devices: Union[int, List[int]] = 0 |
|
if gpu_devices is None: |
|
parsed_gpu_devices = len(GPUtil.getGPUs()) |
|
|
|
if processes is None: |
|
processes = multiprocessing.cpu_count() * 3 |
|
|
|
objects = get_example_objects() |
|
download_github_objects( |
|
objects=objects, |
|
processes=processes, |
|
save_repo_format=save_repo_format, |
|
download_dir=render_dir, |
|
handle_found_object=partial( |
|
handle_found_object, |
|
render_dir=render_dir, |
|
num_renders=num_renders, |
|
only_northern_hemisphere=only_northern_hemisphere, |
|
gpu_devices=parsed_gpu_devices, |
|
render_timeout=render_timeout, |
|
), |
|
handle_new_object=handle_new_object, |
|
handle_modified_object=partial( |
|
handle_modified_object, |
|
render_dir=render_dir, |
|
num_renders=num_renders, |
|
gpu_devices=parsed_gpu_devices, |
|
only_northern_hemisphere=only_northern_hemisphere, |
|
), |
|
handle_missing_object=handle_missing_object, |
|
) |
|
|
|
|
|
if __name__ == "__main__": |
|
fire.Fire(render_github_objects) |
|
|