webp-tui 2.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3 @@
1
+ """Batch image-to-WebP converter with CLI and Textual TUI."""
2
+
3
+ __version__ = "2.0.1"
webp_converter/cli.py ADDED
@@ -0,0 +1,197 @@
1
+ """Command-line interface for webp-converter."""
2
+
3
+ import argparse
4
+ import logging
5
+ import os
6
+ from typing import Any, Dict, List, Optional
7
+
8
+ from rich.progress import BarColumn, MofNCompleteColumn, Progress, SpinnerColumn, TextColumn, TimeElapsedColumn
9
+
10
+ from .config import (
11
+ DEFAULT_CONFIG_FILE,
12
+ Settings,
13
+ load_config,
14
+ normalise_formats,
15
+ settings_from_config,
16
+ )
17
+ from .core import BatchEvent, plan_conversions, run_batch, scan_folder, validate_folder_path
18
+
19
+ EXIT_OK = 0
20
+ EXIT_PARTIAL_FAILURE = 1
21
+ EXIT_FATAL = 2
22
+
23
+
24
+ def setup_logging(log_file: Optional[str] = None, verbose: bool = False) -> None:
25
+ """Configure console and optional file logging."""
26
+ for handler in logging.root.handlers[:]:
27
+ logging.root.removeHandler(handler)
28
+
29
+ level = logging.DEBUG if verbose else logging.INFO
30
+ console_handler = logging.StreamHandler()
31
+ console_handler.setFormatter(logging.Formatter("%(levelname)s - %(message)s"))
32
+ console_handler.setLevel(level)
33
+ logging.getLogger().addHandler(console_handler)
34
+ logging.getLogger().setLevel(logging.DEBUG if log_file else level)
35
+
36
+ if log_file:
37
+ file_handler = logging.FileHandler(log_file, mode="a", encoding="utf-8")
38
+ file_handler.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(message)s"))
39
+ file_handler.setLevel(logging.DEBUG)
40
+ logging.getLogger().addHandler(file_handler)
41
+
42
+
43
+ def quality_type(value: str) -> int:
44
+ try:
45
+ q = int(float(value))
46
+ except ValueError:
47
+ raise argparse.ArgumentTypeError(f"quality must be a number, got {value!r}")
48
+ if not 0 <= q <= 100:
49
+ raise argparse.ArgumentTypeError("quality must be between 0 and 100")
50
+ return q
51
+
52
+
53
+ def method_type(value: str) -> int:
54
+ try:
55
+ m = int(value)
56
+ except ValueError:
57
+ raise argparse.ArgumentTypeError(f"method must be an integer, got {value!r}")
58
+ if not 0 <= m <= 6:
59
+ raise argparse.ArgumentTypeError("method must be between 0 and 6")
60
+ return m
61
+
62
+
63
+ def positive_int(value: str) -> int:
64
+ try:
65
+ n = int(value)
66
+ except ValueError:
67
+ raise argparse.ArgumentTypeError(f"expected an integer, got {value!r}")
68
+ if n < 1:
69
+ raise argparse.ArgumentTypeError("must be at least 1")
70
+ return n
71
+
72
+
73
+ def build_parser() -> argparse.ArgumentParser:
74
+ parser = argparse.ArgumentParser(
75
+ prog="webp-converter",
76
+ description="Convert images to WebP. Launches the interactive TUI by default; pass --cli for command-line mode.",
77
+ )
78
+ parser.add_argument("folder_path", nargs="?", help="Folder path to open in TUI, or convert in --cli mode")
79
+ parser.add_argument("--cli", action="store_true", help="Run in headless command-line mode instead of opening the TUI")
80
+ parser.add_argument("--tui", action="store_true", help="Force the interactive terminal UI (default)")
81
+ parser.add_argument("--quality", "-q", type=quality_type, default=None, help="WebP quality 0-100 (default: 90)")
82
+ parser.add_argument("--lossless", action="store_true", default=None, help="Use lossless WebP encoding")
83
+ parser.add_argument("--lossy", action="store_false", dest="lossless", help="Use lossy encoding (overrides config)")
84
+ parser.add_argument("--method", "-m", type=method_type, default=None, help="Compression effort 0-6 (default: 4)")
85
+ parser.add_argument("--keep-originals", action="store_false", dest="delete_originals", default=None, help="Keep original files (default)")
86
+ parser.add_argument("--delete-originals", action="store_true", dest="delete_originals", help="Delete original files after successful conversion")
87
+ parser.add_argument("--overwrite", action="store_true", default=None, help="Overwrite existing .webp files")
88
+ parser.add_argument("--recursive", action="store_true", default=None, help="Scan subfolders recursively (default)")
89
+ parser.add_argument("--no-recursive", action="store_false", dest="recursive", help="Only scan the top-level folder")
90
+ parser.add_argument("--workers", "-w", type=positive_int, default=None, help="Number of worker threads")
91
+ parser.add_argument("--dry-run", action="store_true", help="Preview what would be converted without making changes")
92
+ parser.add_argument("--formats", nargs="+", default=None, help="Supported image formats (e.g. .jpg .png)")
93
+ parser.add_argument("--log-file", type=str, help="Write detailed logs to a file")
94
+ parser.add_argument("--verbose", "-v", action="store_true", help="Enable verbose logging")
95
+ parser.add_argument("--config", type=str, default=DEFAULT_CONFIG_FILE, help="Configuration JSON path")
96
+ return parser
97
+
98
+
99
+ def build_settings(args: argparse.Namespace, config: Dict[str, Any]) -> Settings:
100
+ """Merge config.json values with CLI overrides (CLI wins)."""
101
+ base = settings_from_config(config)
102
+ return Settings(
103
+ quality=args.quality if args.quality is not None else base.quality,
104
+ lossless=args.lossless if args.lossless is not None else base.lossless,
105
+ method=args.method if args.method is not None else base.method,
106
+ delete_originals=args.delete_originals if args.delete_originals is not None else base.delete_originals,
107
+ overwrite=args.overwrite if args.overwrite is not None else base.overwrite,
108
+ recursive=args.recursive if args.recursive is not None else base.recursive,
109
+ max_workers=args.workers if args.workers is not None else base.max_workers,
110
+ supported_formats=normalise_formats(args.formats) if args.formats is not None else base.supported_formats,
111
+ )
112
+
113
+
114
+ def format_bytes(num_bytes: int) -> str:
115
+ size = float(abs(num_bytes))
116
+ for unit in ("B", "KB", "MB", "GB"):
117
+ if size < 1024 or unit == "GB":
118
+ return f"{size:.1f} {unit}" if unit != "B" else f"{int(size)} B"
119
+ size /= 1024
120
+ return f"{size:.1f} GB"
121
+
122
+
123
+ def run_cli(argv: Optional[List[str]] = None) -> int:
124
+ args = build_parser().parse_args(argv)
125
+ setup_logging(log_file=args.log_file, verbose=args.verbose)
126
+
127
+ config = load_config(args.config)
128
+ try:
129
+ settings = build_settings(args, config)
130
+ except ValueError as e:
131
+ logging.error(f"Invalid configuration value: {e}")
132
+ return EXIT_FATAL
133
+
134
+ mode = "lossless" if settings.lossless else f"quality={settings.quality}"
135
+ logging.info(
136
+ f"Starting WebP conversion ({mode}, method={settings.method}, workers={settings.max_workers})"
137
+ )
138
+ if settings.delete_originals:
139
+ logging.info("Original files will be deleted after a successful conversion")
140
+ else:
141
+ logging.info("Original files will be kept after conversion")
142
+
143
+ folder_input = args.folder_path if args.folder_path else input("Enter the folder path containing images: ")
144
+ folder_path = validate_folder_path(folder_input)
145
+ if not folder_path:
146
+ return EXIT_FATAL
147
+
148
+ if args.dry_run:
149
+ logging.info("DRY RUN MODE: No files will be modified.")
150
+
151
+ try:
152
+ image_files = scan_folder(folder_path, settings.supported_formats, recursive=settings.recursive)
153
+ except PermissionError:
154
+ logging.error(f"Permission denied while accessing folder: {folder_path}")
155
+ return EXIT_FATAL
156
+ except Exception as e:
157
+ logging.error(f"Error while scanning folder: {e}")
158
+ return EXIT_FATAL
159
+
160
+ if not image_files:
161
+ logging.info("No supported image files found in the specified folder.")
162
+ return EXIT_OK
163
+
164
+ plan, skipped = plan_conversions(image_files, overwrite=settings.overwrite)
165
+ logging.info(f"Found {len(image_files)} image files, {len(plan)} to process, {len(skipped)} skipped.")
166
+
167
+ if args.dry_run:
168
+ logging.info("Files to be processed:")
169
+ for src, dst in plan:
170
+ logging.info(f" {src} -> {os.path.basename(dst)}")
171
+ logging.info("Dry run completed. No files were modified.")
172
+ return EXIT_OK
173
+
174
+ with Progress(
175
+ SpinnerColumn(),
176
+ TextColumn("[progress.description]{task.description}"),
177
+ BarColumn(),
178
+ MofNCompleteColumn(),
179
+ TimeElapsedColumn(),
180
+ transient=True,
181
+ ) as progress:
182
+ task_id = progress.add_task("Converting images", total=len(plan))
183
+
184
+ def on_event(ev: BatchEvent) -> None:
185
+ if ev.kind in ("file_completed", "file_failed"):
186
+ progress.advance(task_id, 1)
187
+
188
+ summary = run_batch(settings, plan, skipped=skipped, on_event=on_event)
189
+
190
+ saved = summary.saved_bytes
191
+ pct = (100.0 * saved / summary.bytes_before) if summary.bytes_before else 0.0
192
+ direction = "saved" if saved >= 0 else "larger"
193
+ logging.info(
194
+ f"Done: {summary.succeeded} succeeded, {summary.failed} failed, {summary.skipped} skipped "
195
+ f"({format_bytes(abs(saved))} {direction}, {abs(pct):.1f}%)."
196
+ )
197
+ return EXIT_PARTIAL_FAILURE if (summary.failed or summary.skipped) else EXIT_OK
@@ -0,0 +1,160 @@
1
+ """Configuration loading, saving, and validation."""
2
+
3
+ from dataclasses import dataclass, field
4
+ import json
5
+ import logging
6
+ import os
7
+ from typing import Any, Dict, Optional, Set
8
+
9
+ DEFAULT_CONFIG_FILE = "config.json"
10
+ DEFAULT_WEBP_QUALITY = 90
11
+ DEFAULT_LOSSLESS = False
12
+ DEFAULT_METHOD = 4
13
+ DEFAULT_DELETE_ORIGINALS = False
14
+ DEFAULT_OVERWRITE = False
15
+ DEFAULT_RECURSIVE = True
16
+ DEFAULT_SUPPORTED_FORMATS = [".jpg", ".jpeg", ".png", ".tif", ".tiff", ".bmp", ".gif"]
17
+ DEFAULT_MAX_WORKERS = os.cpu_count() or 4
18
+
19
+ _PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
20
+
21
+
22
+ @dataclass
23
+ class Settings:
24
+ """Runtime conversion settings resolved from config.json and CLI/TUI options."""
25
+
26
+ quality: int = DEFAULT_WEBP_QUALITY
27
+ lossless: bool = DEFAULT_LOSSLESS
28
+ method: int = DEFAULT_METHOD
29
+ delete_originals: bool = DEFAULT_DELETE_ORIGINALS
30
+ overwrite: bool = DEFAULT_OVERWRITE
31
+ recursive: bool = DEFAULT_RECURSIVE
32
+ max_workers: int = DEFAULT_MAX_WORKERS
33
+ supported_formats: Set[str] = field(default_factory=lambda: set(DEFAULT_SUPPORTED_FORMATS))
34
+
35
+
36
+ def user_config_path() -> str:
37
+ """Return the per-user configuration file path on Windows (or XDG fallback)."""
38
+ appdata = os.environ.get("APPDATA")
39
+ if appdata:
40
+ return os.path.join(appdata, "webp-converter", DEFAULT_CONFIG_FILE)
41
+ return os.path.join(os.path.expanduser("~"), ".config", "webp-converter", DEFAULT_CONFIG_FILE)
42
+
43
+
44
+ def resolve_config_path(config_file: str = DEFAULT_CONFIG_FILE) -> str:
45
+ """
46
+ Resolve which config file to read.
47
+
48
+ Explicit paths or a local config.json in the CWD or repo root take precedence;
49
+ otherwise fall back to the per-user config directory.
50
+ """
51
+ if os.path.isabs(config_file):
52
+ return config_file
53
+ if config_file != DEFAULT_CONFIG_FILE:
54
+ return os.path.abspath(config_file)
55
+ if os.path.exists(config_file):
56
+ return os.path.abspath(config_file)
57
+ repo_cfg = os.path.join(_PROJECT_ROOT, config_file)
58
+ if os.path.exists(repo_cfg):
59
+ return repo_cfg
60
+ return user_config_path()
61
+
62
+
63
+ def _default_config_dict() -> Dict[str, Any]:
64
+ return {
65
+ "webp_quality": DEFAULT_WEBP_QUALITY,
66
+ "lossless": DEFAULT_LOSSLESS,
67
+ "method": DEFAULT_METHOD,
68
+ "delete_originals": DEFAULT_DELETE_ORIGINALS,
69
+ "overwrite": DEFAULT_OVERWRITE,
70
+ "recursive": DEFAULT_RECURSIVE,
71
+ "supported_formats": DEFAULT_SUPPORTED_FORMATS,
72
+ "max_workers": DEFAULT_MAX_WORKERS,
73
+ }
74
+
75
+
76
+ def load_config(config_file: str = DEFAULT_CONFIG_FILE) -> Dict[str, Any]:
77
+ """Load configuration from JSON, returning {} (and creating defaults when needed) on miss."""
78
+ config_path = resolve_config_path(config_file)
79
+ if os.path.exists(config_path):
80
+ try:
81
+ with open(config_path, "r", encoding="utf-8") as f:
82
+ data = json.load(f)
83
+ if isinstance(data, dict):
84
+ logging.info(f"Configuration loaded from {config_path}")
85
+ return data
86
+ logging.error(f"Configuration in {config_path} must be a JSON object")
87
+ return {}
88
+ except (json.JSONDecodeError, OSError) as e:
89
+ logging.error(f"Error reading config file {config_path}: {e}")
90
+ return {}
91
+
92
+ if config_file != DEFAULT_CONFIG_FILE:
93
+ logging.warning(f"Config file not found: {config_path} (using defaults)")
94
+ return {}
95
+
96
+ defaults = _default_config_dict()
97
+ try:
98
+ os.makedirs(os.path.dirname(config_path), exist_ok=True)
99
+ with open(config_path, "w", encoding="utf-8") as f:
100
+ json.dump(defaults, f, indent=4)
101
+ logging.info(f"Default configuration file created: {config_path}")
102
+ except OSError as e:
103
+ logging.debug(f"Could not create default config file: {e}")
104
+ return defaults
105
+
106
+
107
+ def save_config(settings: Settings, config_file: str = DEFAULT_CONFIG_FILE) -> Optional[str]:
108
+ """Persist Settings to config.json and return the path written, or None on error."""
109
+ config_path = resolve_config_path(config_file)
110
+ payload = {
111
+ "webp_quality": settings.quality,
112
+ "lossless": settings.lossless,
113
+ "method": settings.method,
114
+ "delete_originals": settings.delete_originals,
115
+ "overwrite": settings.overwrite,
116
+ "recursive": settings.recursive,
117
+ "supported_formats": sorted(settings.supported_formats),
118
+ "max_workers": settings.max_workers,
119
+ }
120
+ try:
121
+ os.makedirs(os.path.dirname(config_path), exist_ok=True)
122
+ with open(config_path, "w", encoding="utf-8") as f:
123
+ json.dump(payload, f, indent=4)
124
+ return config_path
125
+ except OSError as e:
126
+ logging.error(f"Could not save config file {config_path}: {e}")
127
+ return None
128
+
129
+
130
+ def normalise_formats(formats: Any) -> Set[str]:
131
+ return {(str(f) if str(f).startswith(".") else f".{f}").lower() for f in formats}
132
+
133
+
134
+ def settings_from_config(config: Dict[str, Any]) -> Settings:
135
+ """Build validated Settings from a config dictionary."""
136
+ quality = int(float(config.get("webp_quality", DEFAULT_WEBP_QUALITY)))
137
+ if not 0 <= quality <= 100:
138
+ raise ValueError("quality must be between 0 and 100")
139
+
140
+ method = int(config.get("method", DEFAULT_METHOD))
141
+ if not 0 <= method <= 6:
142
+ raise ValueError("method must be between 0 and 6")
143
+
144
+ max_workers = int(config.get("max_workers", DEFAULT_MAX_WORKERS))
145
+ if max_workers < 1:
146
+ raise ValueError("max_workers must be at least 1")
147
+
148
+ raw_formats = config.get("supported_formats", DEFAULT_SUPPORTED_FORMATS)
149
+ formats = normalise_formats(raw_formats) if raw_formats else set(DEFAULT_SUPPORTED_FORMATS)
150
+
151
+ return Settings(
152
+ quality=quality,
153
+ lossless=bool(config.get("lossless", DEFAULT_LOSSLESS)),
154
+ method=method,
155
+ delete_originals=bool(config.get("delete_originals", DEFAULT_DELETE_ORIGINALS)),
156
+ overwrite=bool(config.get("overwrite", DEFAULT_OVERWRITE)),
157
+ recursive=bool(config.get("recursive", DEFAULT_RECURSIVE)),
158
+ max_workers=max_workers,
159
+ supported_formats=formats,
160
+ )