|
"""Anomalib Path Utils.""" |
|
|
|
|
|
|
|
|
|
import re |
|
from pathlib import Path |
|
|
|
|
|
def create_versioned_dir(root_dir: str | Path) -> Path: |
|
"""Create a new version directory and update the ``latest`` symbolic link. |
|
|
|
Args: |
|
root_dir (Path): The root directory where the version directories are stored. |
|
|
|
Returns: |
|
latest_link_path (Path): The path to the ``latest`` symbolic link. |
|
|
|
Examples: |
|
>>> version_dir = create_version_dir(Path('path/to/experiments/')) |
|
PosixPath('/path/to/experiments/latest') |
|
|
|
>>> version_dir.resolve().name |
|
v1 |
|
|
|
Calling the function again will create a new version directory and |
|
update the ``latest`` symbolic link: |
|
|
|
>>> version_dir = create_version_dir('path/to/experiments/') |
|
PosixPath('/path/to/experiments/latest') |
|
|
|
>>> version_dir.resolve().name |
|
v2 |
|
|
|
""" |
|
|
|
version_pattern = re.compile(r"^v(\d+)$") |
|
|
|
|
|
root_dir = Path(root_dir).resolve() |
|
root_dir.mkdir(parents=True, exist_ok=True) |
|
|
|
|
|
highest_version = -1 |
|
for version_dir in root_dir.iterdir(): |
|
if version_dir.is_dir(): |
|
match = version_pattern.match(version_dir.name) |
|
if match: |
|
version_number = int(match.group(1)) |
|
highest_version = max(highest_version, version_number) |
|
|
|
|
|
new_version_number = highest_version + 1 |
|
new_version_dir = root_dir / f"v{new_version_number}" |
|
|
|
|
|
new_version_dir.mkdir() |
|
|
|
|
|
latest_link_path = root_dir / "latest" |
|
if latest_link_path.is_symlink() or latest_link_path.exists(): |
|
latest_link_path.unlink() |
|
latest_link_path.symlink_to(new_version_dir, target_is_directory=True) |
|
|
|
return latest_link_path |
|
|
|
|
|
def convert_to_snake_case(s: str) -> str: |
|
"""Converts a string to snake case. |
|
|
|
Args: |
|
s (str): The input string to be converted. |
|
|
|
Returns: |
|
str: The converted string in snake case. |
|
|
|
Examples: |
|
>>> convert_to_snake_case("Snake Case") |
|
'snake_case' |
|
|
|
>>> convert_to_snake_case("snakeCase") |
|
'snake_case' |
|
|
|
>>> convert_to_snake_case("snake_case") |
|
'snake_case' |
|
""" |
|
|
|
s = re.sub(r"\s+|[-.\']", "_", s) |
|
|
|
|
|
s = re.sub(r"(?<!^)(?=[A-Z])", "_", s).lower() |
|
|
|
|
|
s = re.sub(r"^_+|_+$", "", s) |
|
|
|
|
|
return re.sub(r"__+", "_", s) |
|
|