File size: 1,295 Bytes
c3182bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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)