2022-02-12 23:47:23 +08:00
|
|
|
from __future__ import annotations
|
|
|
|
|
2018-04-29 10:52:48 -07:00
|
|
|
import os
|
2024-11-25 09:31:15 -07:00
|
|
|
from pathlib import Path
|
|
|
|
import hashlib
|
2022-02-12 23:47:23 +08:00
|
|
|
|
2019-01-10 17:06:22 -08:00
|
|
|
import numpy as np
|
2021-01-06 10:39:34 -08:00
|
|
|
import validators
|
2024-12-05 16:51:14 -06:00
|
|
|
import urllib.request
|
|
|
|
|
|
|
|
import manimlib.utils.directories
|
|
|
|
from manimlib.utils.simple_functions import hash_string
|
2021-01-06 10:39:34 -08:00
|
|
|
|
2022-04-12 19:19:59 +08:00
|
|
|
from typing import TYPE_CHECKING
|
|
|
|
|
|
|
|
if TYPE_CHECKING:
|
|
|
|
from typing import Iterable
|
|
|
|
|
2018-04-29 10:52:48 -07:00
|
|
|
|
2024-12-12 10:39:54 -06:00
|
|
|
def guarantee_existence(path: str | Path) -> Path:
|
|
|
|
path = Path(path)
|
|
|
|
path.mkdir(parents=True, exist_ok=True)
|
|
|
|
return path.absolute()
|
2018-05-01 01:53:59 -07:00
|
|
|
|
|
|
|
|
2022-02-12 23:47:23 +08:00
|
|
|
def find_file(
|
|
|
|
file_name: str,
|
|
|
|
directories: Iterable[str] | None = None,
|
|
|
|
extensions: Iterable[str] | None = None
|
2024-12-12 10:39:54 -06:00
|
|
|
) -> Path:
|
2021-01-06 10:39:34 -08:00
|
|
|
# Check if this is a file online first, and if so, download
|
|
|
|
# it to a temporary directory
|
|
|
|
if validators.url(file_name):
|
2024-11-25 09:31:15 -07:00
|
|
|
suffix = Path(file_name).suffix
|
2024-12-05 16:51:14 -06:00
|
|
|
file_hash = hash_string(file_name)
|
|
|
|
folder = manimlib.utils.directories.get_downloads_dir()
|
2024-11-25 09:31:15 -07:00
|
|
|
|
|
|
|
path = Path(folder, file_hash).with_suffix(suffix)
|
2021-01-06 10:39:34 -08:00
|
|
|
urllib.request.urlretrieve(file_name, path)
|
|
|
|
return path
|
|
|
|
|
|
|
|
# Check if what was passed in is already a valid path to a file
|
|
|
|
if os.path.exists(file_name):
|
2024-12-12 10:39:54 -06:00
|
|
|
return Path(file_name)
|
2021-01-06 10:39:34 -08:00
|
|
|
|
|
|
|
# Otherwise look in local file system
|
|
|
|
directories = directories or [""]
|
|
|
|
extensions = extensions or [""]
|
|
|
|
possible_paths = (
|
2024-12-12 10:39:54 -06:00
|
|
|
Path(directory, file_name + extension)
|
2021-01-05 23:14:16 -08:00
|
|
|
for directory in directories
|
2021-01-06 10:39:34 -08:00
|
|
|
for extension in extensions
|
|
|
|
)
|
2019-01-24 22:24:01 -08:00
|
|
|
for path in possible_paths:
|
2024-12-12 10:39:54 -06:00
|
|
|
if path.exists():
|
2019-01-24 22:24:01 -08:00
|
|
|
return path
|
2021-01-06 10:39:34 -08:00
|
|
|
raise IOError(f"{file_name} not Found")
|