Spaces:
Sleeping
Sleeping
| import os | |
| from pathlib import Path | |
| import tempfile | |
| from PIL import Image | |
| def create_folder(folder_path: str) -> str: | |
| """ | |
| Create a folder if it doesn't exist. | |
| Args: | |
| folder_path (str): Path to the folder to create. | |
| Returns: | |
| str: Absolute path to the created or existing folder. | |
| """ | |
| path = Path(folder_path).expanduser().resolve() | |
| path.mkdir(parents=True, exist_ok=True) | |
| return str(path) | |
| def validate_path(p: str) -> Path: | |
| path = Path(os.path.expanduser(p)).resolve() | |
| if not path.exists(): | |
| raise FileNotFoundError(f"Path does not exist: {path}") | |
| return path | |
| def temp_output(suffix=".png"): | |
| return tempfile.NamedTemporaryFile(delete=False, suffix=suffix).name | |
| def ensure_path_from_img(img) -> Path: | |
| """ | |
| Ensures that the input is converted to a valid image file path. | |
| If `img` is a PIL.Image object, it saves it to a temporary file and returns the path. | |
| If `img` is already a path (string or Path), it wraps and returns it as a Path. | |
| Args: | |
| img: A PIL.Image or a path string | |
| Returns: | |
| Path to the image file | |
| """ | |
| if isinstance(img, Image.Image): | |
| temp_input = temp_output() | |
| img.save(temp_input) | |
| return Path(temp_input) | |
| return validate_path(img) |