Skip to content

Bulk asynchronous downloader for multiple file hosts

fix: sorting format options (#1160)

NTFSvolumed7293df91af6
diff --git a/cyberdrop_dl/config/config_model.py b/cyberdrop_dl/config/config_model.py
index c50b1f696..1fcbd9b10 100755
--- a/cyberdrop_dl/config/config_model.py
+++ b/cyberdrop_dl/config/config_model.py
@@ -28,7 +28,16 @@ from cyberdrop_dl.utils.utilities import purge_dir_tree
from ._common import ConfigModel, Field, PathAliasModel
ALL_SUPPORTED_SITES = ["<<ALL_SUPPORTED_SITES>>"]
-SORTING_COMMON_KEYS = {"sort_dir", "base_dir", "parent_dir", "filename", "ext"}
+_SORTING_COMMON_FIELDS = {
+ "base_dir",
+ "ext",
+ "file_date",
+ "file_date_iso",
+ "file_date_us",
+ "filename",
+ "parent_dir",
+ "sort_dir",
+}
class DownloadOptions(BaseModel):
@@ -196,11 +205,19 @@ class Sorting(BaseModel):
sorted_other: NonEmptyStrOrNone = "{sort_dir}/{base_dir}/Other/{filename}{ext}"
sorted_video: NonEmptyStrOrNone = "{sort_dir}/{base_dir}/Videos/{filename}{ext}"
+ @field_validator("sort_incrementer_format", mode="after")
+ @classmethod
+ def valid_sort_incrementer_format(cls, value: str | None) -> str | None:
+ if value is not None:
+ valid_keys = {"i"}
+ validate_format_string(value, valid_keys)
+ return value
+
@field_validator("sorted_audio", mode="after")
@classmethod
def valid_sorted_audio(cls, value: str | None) -> str | None:
if value is not None:
- valid_keys = SORTING_COMMON_KEYS.union("bitrate", "duration", "length", "sample_rate")
+ valid_keys = _SORTING_COMMON_FIELDS | {"bitrate", "duration", "length", "sample_rate"}
validate_format_string(value, valid_keys)
return value
@@ -208,7 +225,7 @@ class Sorting(BaseModel):
@classmethod
def valid_sorted_image(cls, value: str | None) -> str | None:
if value is not None:
- valid_keys = SORTING_COMMON_KEYS.union("height", "width", "resolution")
+ valid_keys = _SORTING_COMMON_FIELDS | {"height", "resolution", "width"}
validate_format_string(value, valid_keys)
return value
@@ -216,7 +233,7 @@ class Sorting(BaseModel):
@classmethod
def valid_sorted_other(cls, value: str | None) -> str | None:
if value is not None:
- valid_keys = SORTING_COMMON_KEYS.union("bitrate", "duration", "length", "sample_rate")
+ valid_keys = _SORTING_COMMON_FIELDS | {"bitrate", "duration", "length", "sample_rate"}
validate_format_string(value, valid_keys)
return value
@@ -224,9 +241,15 @@ class Sorting(BaseModel):
@classmethod
def valid_sorted_video(cls, value: str | None) -> str | None:
if value is not None:
- valid_keys = SORTING_COMMON_KEYS.union(
- "codec", "duration", "fps", "length", "height", "width", "resolution"
- )
+ valid_keys = _SORTING_COMMON_FIELDS | {
+ "codec",
+ "duration",
+ "fps",
+ "height",
+ "length",
+ "resolution",
+ "width",
+ }
validate_format_string(value, valid_keys)
return value
diff --git a/cyberdrop_dl/utils/sorting.py b/cyberdrop_dl/utils/sorting.py
index 6213d60d5..e590bb96d 100644
--- a/cyberdrop_dl/utils/sorting.py
+++ b/cyberdrop_dl/utils/sorting.py
@@ -14,6 +14,7 @@ from PIL import Image
from videoprops import get_audio_properties, get_video_properties
from cyberdrop_dl.constants import FILE_FORMATS
+from cyberdrop_dl.utils import strings
from cyberdrop_dl.utils.logger import log_with_color
from cyberdrop_dl.utils.utilities import purge_dir_tree
@@ -164,7 +165,12 @@ class Sorter:
resolution = f"{width}x{height}"
if await self._process_file_move(
- file, base_name, self.image_format, resolution=resolution, width=width, height=height
+ file,
+ base_name,
+ self.image_format,
+ height=height,
+ resolution=resolution,
+ width=width,
):
self.manager.progress_manager.sort_progress.increment_image()
@@ -182,15 +188,16 @@ class Sorter:
if width and height:
resolution = f"{width}x{height}"
- codec = props.get("codec_name")
+ codec: str = props.get("codec_name")
duration = int(float(props.get("duration", 0))) or None
fps = (
float(Fraction(props.get("avg_frame_rate", 0)))
if str(props.get("avg_frame_rate", 0)) not in {"0/0", "0"}
else None
)
- if fps:
- fps = int(fps) if fps.is_integer() else f"{fps:.2f}"
+
+ if fps is not None:
+ fps = str(int(fps)) if fps.is_integer() else f"{fps:.2f}"
if await self._process_file_move(
file,
@@ -199,9 +206,9 @@ class Sorter:
codec=codec,
duration=duration,
fps=fps,
+ height=height,
resolution=resolution,
width=width,
- height=height,
):
self.manager.progress_manager.sort_progress.increment_video()
@@ -217,20 +224,22 @@ class Sorter:
file_date_us = file_date.strftime("%Y-%d-%m")
file_date_iso = file_date.strftime("%Y-%m-%d")
- for name, value in kwargs.items():
- if value is None:
- kwargs[name] = "Unknown"
-
- new_file = Path(
- format_str.format(
- base_dir=base_name,
- ext=file.suffix,
- file_date_iso=file_date_iso,
- file_date_us=file_date_us,
- filename=file.stem,
- parent_dir=file.parent.name,
- sort_dir=self.sorted_folder,
- **kwargs,
- ),
+ duration = kwargs.get("duration") or kwargs.get("length")
+ if duration is not None:
+ kwargs["duration"] = kwargs["length"] = duration
+
+ file_path, _ = strings.safe_format(
+ format_str,
+ base_dir=base_name,
+ ext=file.suffix,
+ file_date=file_date,
+ file_date_iso=file_date_iso,
+ file_date_us=file_date_us,
+ filename=file.stem,
+ parent_dir=file.parent.name,
+ sort_dir=self.sorted_folder,
+ **kwargs,
)
+
+ new_file = Path(file_path)
return self._move_file(file, new_file)
diff --git a/cyberdrop_dl/utils/strings.py b/cyberdrop_dl/utils/strings.py
index 1fee7bab9..813cd37ec 100644
--- a/cyberdrop_dl/utils/strings.py
+++ b/cyberdrop_dl/utils/strings.py
@@ -60,7 +60,7 @@ def safe_format(format_string: str, **fields: Any) -> tuple[str, set[str]]:
# To use with pydantic
def validate_format_string(format_string: str, valid_keys: set[str]) -> None:
- msg = "Invalid format string. "
+ msg = "invalid format string. "
for _, field_name, _, _ in _FORMATER.parse(format_string):
if field_name is not None:
if field_name.isdigit() or field_name == "":
@@ -71,7 +71,13 @@ def validate_format_string(format_string: str, valid_keys: set[str]) -> None:
raise ValueError(msg)
if unknown_field_names := get_unknown_field_names(format_string, valid_keys):
- msg += f"{sorted(unknown_field_names)} are not valid keys for this option. Valid keys: {sorted(valid_keys)}"
+ msg += " ".join(
+ (
+ f"{tuple(sorted(unknown_field_names))}",
+ f"{'is not a valid field' if len(unknown_field_names) == 1 else 'are not valid fields'}",
+ f"for this option. \n\n Valid fields: {sorted(valid_keys)}",
+ )
+ )
raise ValueError(msg)
diff --git a/docs/reference/configuration-options/settings/sorting.md b/docs/reference/configuration-options/settings/sorting.md
index 51758dfd7..ea2c0d19e 100644
--- a/docs/reference/configuration-options/settings/sorting.md
+++ b/docs/reference/configuration-options/settings/sorting.md
@@ -7,15 +7,21 @@ However, `filename` and `ext` must always be used.
Common fields for sorting format options (supported for `audio`, `videos`, `images` and `other`):
-> `sort_dir`: This represent the same path as `sort_folder` from the download options
+> `base_dir`: the name of highest level folder inside `scan_folder`. This normally is the model name or the thread name
>
-> `base_dir`: the name of highest level folder inside `scan_folder` ex: (model name / thread name)
+> `ext`: the file extension (suffix)
+>
+> `file_date`: the file date. This is a datetime object, which means it accepts a custom format spec ex: `{file_date:%Y-%m}`
+>
+> `file_date_iso`: the file date as an iso 8601 string (`%Y-%m-%d`)
>
-> `parent_dir`: the name of the folder where the file is located at. Ex: (album name)
+> `file_date_us`: the file date in the US format (`%Y-%d-%m`)
>
> `filename`: the file's name (stem)
>
-> `ext`: the file extension (suffix)
+> `parent_dir`: the name of the folder where the file is located at (its parent folder). This is normally the album name for photos or the post name for forums/reddit if `separate_post` is enabled
+>
+> `sort_dir`: the same path as `sort_folder` from the download options
## `scan_folder`
@@ -71,13 +77,13 @@ This is the format for the directory structure and naming scheme for audio files
In addition to the common sorting format fields, this option supports:
-> `bitrate`: file bit rate
+> `bitrate`: file bit rate. This is an `int`
>
-> `duration`: audio total runtime
+> `duration`: audio total runtime in seconds. This is an `int`
>
> `length`: same as `duration`
>
-> `sample_rate`: audio sample rate
+> `sample_rate`: audio sample rate. This is an `int`
## `sorted_image`
@@ -89,11 +95,11 @@ This is the format for the directory structure and naming scheme for image files
In addition to the common sorting format fields, this option supports:
-> `height`: vertical pixel count
+> `height`: vertical pixel count. This is an `int`
>
-> `width`: horizontal pixel count
+> `width`: horizontal pixel count. This is an `int`
>
-> `resolution`: `width`x`height` ex. 1080x1920
+> `resolution`: `width`x`height` ex. 1080x1920. This is a `str`
## `sorted_video`
@@ -105,19 +111,19 @@ This is the format for the directory structure and naming scheme for video files
In addition to the common sorting format fields, this option supports:
-> `codec`: ex. h264
+> `codec`: ex. h264. This is a `str`. It could potencially be `None` for some files
>
-> `duration`: video total runtime
+> `duration`: video total runtime in seconds. This is an `int`
>
-> `fps`: ex. 24
+> `fps`: ex. `24`. This represents a number but is a `str`. It could potencially be `None` for some files
>
> `length`: same as `duration`
>
-> `height`: vertical pixel count
+> `height`: vertical pixel count. This is an `int`
>
-> `width`: horizontal pixel count
+> `width`: horizontal pixel count.This is an `int`
>
-> `resolution`: `width`x`height` ex. 1080x1920
+> `resolution`: `width`x`height` ex. 1080x1920. This is a `str`
## `sorted_other`