71 行
1.6 KiB
Python
71 行
1.6 KiB
Python
|
|
from __future__ import annotations
|
||
|
|
|
||
|
|
import re
|
||
|
|
from pathlib import Path
|
||
|
|
|
||
|
|
|
||
|
|
IMAGE_SUFFIXES = {".jpg", ".jpeg", ".png", ".webp"}
|
||
|
|
WINDOWS_RESERVED_NAMES = {
|
||
|
|
"CON",
|
||
|
|
"PRN",
|
||
|
|
"AUX",
|
||
|
|
"NUL",
|
||
|
|
"COM1",
|
||
|
|
"COM2",
|
||
|
|
"COM3",
|
||
|
|
"COM4",
|
||
|
|
"COM5",
|
||
|
|
"COM6",
|
||
|
|
"COM7",
|
||
|
|
"COM8",
|
||
|
|
"COM9",
|
||
|
|
"LPT1",
|
||
|
|
"LPT2",
|
||
|
|
"LPT3",
|
||
|
|
"LPT4",
|
||
|
|
"LPT5",
|
||
|
|
"LPT6",
|
||
|
|
"LPT7",
|
||
|
|
"LPT8",
|
||
|
|
"LPT9",
|
||
|
|
}
|
||
|
|
|
||
|
|
|
||
|
|
def natural_key(value: Path | str) -> list[int | str]:
|
||
|
|
return [
|
||
|
|
int(part) if part.isdigit() else part.lower()
|
||
|
|
for part in re.split(r"(\d+)", str(value))
|
||
|
|
]
|
||
|
|
|
||
|
|
|
||
|
|
def collect_image_files(root: Path) -> list[Path]:
|
||
|
|
files = [
|
||
|
|
path
|
||
|
|
for path in root.rglob("*")
|
||
|
|
if path.is_file() and path.suffix.lower() in IMAGE_SUFFIXES
|
||
|
|
]
|
||
|
|
return sorted(files, key=natural_key)
|
||
|
|
|
||
|
|
|
||
|
|
def safe_filename(value: str, fallback: str = "untitled") -> str:
|
||
|
|
cleaned = "".join(
|
||
|
|
"_" if char in '<>:"/\\|?*' or ord(char) < 32 else char
|
||
|
|
for char in value.strip()
|
||
|
|
)
|
||
|
|
cleaned = re.sub(r"\s+", " ", cleaned).strip(" .")
|
||
|
|
if not cleaned:
|
||
|
|
cleaned = fallback
|
||
|
|
if cleaned.upper() in WINDOWS_RESERVED_NAMES:
|
||
|
|
cleaned = f"_{cleaned}"
|
||
|
|
return cleaned[:180]
|
||
|
|
|
||
|
|
|
||
|
|
def infer_album_title(download_dir: Path, comic_id: str) -> str:
|
||
|
|
candidates = []
|
||
|
|
for child in sorted(download_dir.iterdir(), key=lambda path: natural_key(path.name)):
|
||
|
|
if child.is_dir() and collect_image_files(child):
|
||
|
|
candidates.append(child.name)
|
||
|
|
if len(candidates) == 1:
|
||
|
|
return candidates[0]
|
||
|
|
return f"JM {comic_id}"
|