vicompres 0.1.0__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.
vicompres/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """Vicompres - Efficiently compress video files using ffmpeg."""
vicompres/main.py ADDED
@@ -0,0 +1,276 @@
1
+ #!/usr/bin/env python3
2
+ """Vicompres - Efficiently compress video files using ffmpeg."""
3
+
4
+ import argparse
5
+ import signal
6
+ import subprocess
7
+ import sys
8
+ from pathlib import Path
9
+
10
+ SUPPORTED_EXTENSIONS = {".mp4", ".mkv", ".avi", ".mov"}
11
+
12
+ # Compression presets mapped by level (1-10).
13
+ # Each level defines: (preset, crf, audio_bitrate)
14
+ COMPRESSION_PROFILES = {
15
+ 1: ("ultrafast", 28, "192k"),
16
+ 2: ("superfast", 27, "176k"),
17
+ 3: ("veryfast", 26, "160k"),
18
+ 4: ("faster", 25, "144k"),
19
+ 5: ("medium", 23, "128k"),
20
+ 6: ("medium", 21, "128k"),
21
+ 7: ("slow", 19, "112k"),
22
+ 8: ("slower", 17, "96k"),
23
+ 9: ("veryslow", 15, "96k"),
24
+ 10: ("veryslow", 13, "80k"),
25
+ }
26
+
27
+ # Per-extension codec and container settings
28
+ EXTENSION_SETTINGS = {
29
+ ".mp4": {"vcodec": "libx264", "acodec": "aac"},
30
+ ".mkv": {"vcodec": "libx264", "acodec": "aac"},
31
+ ".avi": {"vcodec": "libxvid", "acodec": "libmp3lame"},
32
+ ".mov": {"vcodec": "libx264", "acodec": "aac"},
33
+ }
34
+
35
+ # Graceful shutdown flag
36
+ _shutdown_requested = False
37
+
38
+
39
+ def _handle_sigint(signum: int, frame) -> None:
40
+ """Set shutdown flag on first Ctrl+C; force-exit on second."""
41
+ global _shutdown_requested
42
+ if _shutdown_requested:
43
+ # Second interrupt – abort immediately
44
+ print("\nForced shutdown.", file=sys.stderr)
45
+ sys.exit(1)
46
+ _shutdown_requested = True
47
+ print("\nShutdown requested – finishing current file, then stopping…")
48
+
49
+
50
+ def parse_args() -> argparse.Namespace:
51
+ parser = argparse.ArgumentParser(
52
+ prog="vicompres",
53
+ description="Efficiently compress video files using ffmpeg.",
54
+ )
55
+ parser.add_argument(
56
+ "-d",
57
+ "--directory",
58
+ type=str,
59
+ default=".",
60
+ help="Directory containing video files to compress (default: current directory).",
61
+ )
62
+ parser.add_argument(
63
+ "-c",
64
+ "--compression",
65
+ type=int,
66
+ default=5,
67
+ choices=range(1, 11),
68
+ metavar="1-10",
69
+ help="Compression level 1-10. Higher = better compression, slower (default: 5).",
70
+ )
71
+ parser.add_argument(
72
+ "-p",
73
+ "--prefix",
74
+ type=str,
75
+ default="",
76
+ help="Only process files whose name starts with this prefix (default: all files).",
77
+ )
78
+ parser.add_argument(
79
+ "-o",
80
+ "--output",
81
+ type=str,
82
+ default=None,
83
+ help="Output directory for compressed files (default: same as input).",
84
+ )
85
+ parser.add_argument(
86
+ "-s",
87
+ "--suffix",
88
+ type=str,
89
+ default="compressed",
90
+ help="Suffix appended to output file names (default: 'compressed').",
91
+ )
92
+ parser.add_argument(
93
+ "-r",
94
+ "--remove-original",
95
+ action="store_true",
96
+ default=False,
97
+ help="Delete original files after successful compression (default: keep originals).",
98
+ )
99
+ return parser.parse_args()
100
+
101
+
102
+ def check_ffmpeg() -> None:
103
+ """Verify that ffmpeg is available on the system."""
104
+ try:
105
+ subprocess.run(
106
+ ["ffmpeg", "-version"],
107
+ stdout=subprocess.DEVNULL,
108
+ stderr=subprocess.DEVNULL,
109
+ check=True,
110
+ )
111
+ except (FileNotFoundError, subprocess.CalledProcessError):
112
+ print("Error: ffmpeg is not installed or not found in PATH.", file=sys.stderr)
113
+ sys.exit(1)
114
+
115
+
116
+ def collect_files(directory: str, prefix: str) -> list[Path]:
117
+ """Return a sorted list of supported video files in *directory*."""
118
+ dir_path = Path(directory).resolve()
119
+ if not dir_path.is_dir():
120
+ print(f"Error: '{directory}' is not a valid directory.", file=sys.stderr)
121
+ sys.exit(1)
122
+
123
+ files: list[Path] = []
124
+ for entry in sorted(dir_path.iterdir()):
125
+ if not entry.is_file():
126
+ continue
127
+ if entry.suffix.lower() not in SUPPORTED_EXTENSIONS:
128
+ continue
129
+ if prefix and not entry.name.startswith(prefix):
130
+ continue
131
+ files.append(entry)
132
+ return files
133
+
134
+
135
+ def build_output_path(input_file: Path, output_dir: Path, suffix: str) -> Path:
136
+ """Construct the output file path with the given suffix."""
137
+ stem = input_file.stem
138
+ ext = input_file.suffix
139
+ out_name = f"{stem}_{suffix}{ext}"
140
+ return output_dir / out_name
141
+
142
+
143
+ def build_ffmpeg_cmd(
144
+ input_file: Path,
145
+ output_file: Path,
146
+ compression: int,
147
+ ) -> list[str]:
148
+ """Build the ffmpeg command list for compressing a single file."""
149
+ ext = input_file.suffix.lower()
150
+ preset, crf, audio_br = COMPRESSION_PROFILES[compression]
151
+ settings = EXTENSION_SETTINGS[ext]
152
+
153
+ cmd = [
154
+ "ffmpeg",
155
+ "-i", str(input_file),
156
+ "-preset", preset,
157
+ "-crf", str(crf),
158
+ "-vcodec", settings["vcodec"],
159
+ "-acodec", settings["acodec"],
160
+ "-b:a", audio_br,
161
+ "-y",
162
+ str(output_file),
163
+ ]
164
+ return cmd
165
+
166
+
167
+ def compress_file(
168
+ input_file: Path,
169
+ output_file: Path,
170
+ compression: int,
171
+ ) -> bool:
172
+ """Compress a single video file. Returns True on success."""
173
+ cmd = build_ffmpeg_cmd(input_file, output_file, compression)
174
+ print(f" Compressing: {input_file.name} -> {output_file.name}")
175
+ try:
176
+ subprocess.run(
177
+ cmd, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE
178
+ )
179
+ return True
180
+ except subprocess.CalledProcessError as exc:
181
+ print(
182
+ f" Error compressing {input_file.name}: {exc.stderr.decode().strip()}",
183
+ file=sys.stderr,
184
+ )
185
+ return False
186
+
187
+
188
+ def format_size(size_bytes: int) -> str:
189
+ """Return a human-readable file size string."""
190
+ for unit in ("B", "KB", "MB", "GB"):
191
+ if abs(size_bytes) < 1024:
192
+ return f"{size_bytes:.1f} {unit}"
193
+ size_bytes /= 1024 # type: ignore[assignment]
194
+ return f"{size_bytes:.1f} TB"
195
+
196
+
197
+ def main() -> None:
198
+ signal.signal(signal.SIGINT, _handle_sigint)
199
+
200
+ args = parse_args()
201
+ check_ffmpeg()
202
+
203
+ directory = args.directory
204
+ compression = args.compression
205
+ prefix = args.prefix
206
+ suffix = args.suffix
207
+ output_dir_arg = args.output
208
+ remove_original = args.remove_original
209
+
210
+ files = collect_files(directory, prefix)
211
+ if not files:
212
+ print("No supported video files found.")
213
+ return
214
+
215
+ # Resolve output directory
216
+ if output_dir_arg:
217
+ output_dir = Path(output_dir_arg).resolve()
218
+ output_dir.mkdir(parents=True, exist_ok=True)
219
+ else:
220
+ output_dir = files[0].parent
221
+
222
+ print(f"Vicompres — compression level {compression}")
223
+ print(f" Input: {Path(directory).resolve()}")
224
+ print(f" Output: {output_dir}")
225
+ print(f" Files: {len(files)}")
226
+ print()
227
+
228
+ success = 0
229
+ failed = 0
230
+ removed = 0
231
+ total_saved: int = 0
232
+
233
+ for f in files:
234
+ if _shutdown_requested:
235
+ print("\n Stopping – shutdown was requested.")
236
+ break
237
+
238
+ out_path = build_output_path(f, output_dir, suffix)
239
+
240
+ # Skip files that already have the suffix (avoid re-compressing)
241
+ if f.stem.endswith(f"_{suffix}"):
242
+ print(f" Skipping (already compressed): {f.name}")
243
+ continue
244
+
245
+ if compress_file(f, out_path, compression):
246
+ original_size = f.stat().st_size
247
+ compressed_size = out_path.stat().st_size
248
+ saved = original_size - compressed_size
249
+ total_saved += saved
250
+ pct = (saved / original_size * 100) if original_size else 0
251
+ print(
252
+ f" {format_size(original_size)} -> {format_size(compressed_size)} ({pct:.1f}% saved)"
253
+ )
254
+ success += 1
255
+ if remove_original:
256
+ try:
257
+ f.unlink()
258
+ print(f" Removed original: {f.name}")
259
+ removed += 1
260
+ except OSError as exc:
261
+ print(f" Failed to remove {f.name}: {exc}", file=sys.stderr)
262
+ else:
263
+ failed += 1
264
+
265
+ print()
266
+ print(f"Done. {success} succeeded, {failed} failed.")
267
+ if removed:
268
+ print(f"Removed {removed} original file(s).")
269
+ if total_saved > 0:
270
+ print(f"Total space saved: {format_size(total_saved)}")
271
+ elif total_saved < 0:
272
+ print(f"Total size increased by: {format_size(abs(total_saved))}")
273
+
274
+
275
+ if __name__ == "__main__":
276
+ main()
@@ -0,0 +1,69 @@
1
+ Metadata-Version: 2.4
2
+ Name: vicompres
3
+ Version: 0.1.0
4
+ Summary: Efficiently compress video files using ffmpeg
5
+ Author-email: Kirill Pechenkin <pechkirill@mail.ru>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/pechenkin-ka/vicompres
8
+ Project-URL: Repository, https://github.com/pechenkin-ka/vicompres
9
+ Project-URL: Issues, https://github.com/pechenkin-ka/vicompres/issues
10
+ Keywords: video,compression,ffmpeg,cli
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: End Users/Desktop
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Multimedia :: Video :: Conversion
21
+ Requires-Python: >=3.10
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Dynamic: license-file
25
+
26
+ # Vicompres
27
+
28
+ Vicompres is a CLI tool to efficiently compress video files using ffmpeg. It provides a simple interface for batch-compressing videos with configurable quality levels.
29
+
30
+ ## Installation
31
+
32
+ ```bash
33
+ pip install vicompres
34
+ ```
35
+
36
+ **Prerequisite:** [ffmpeg](https://ffmpeg.org/) must be installed and available in your PATH.
37
+
38
+ ## Usage
39
+
40
+ ```bash
41
+ vicompres -d /path/to/videos -c 5
42
+ ```
43
+
44
+ ## Features
45
+
46
+ Arguments:
47
+
48
+ - `-d` or `--directory`: Specify the directory containing the video files to be compressed. By default, it uses the current directory.
49
+ - `-c` or `--compression`: Set the compression level (1-10). Higher values result in better compression but may take more time. The default value is 5.
50
+ - compression level is ephemeral — it maps to a specific ffmpeg preset, CRF, and bitrate based on the file extension.
51
+ - `-p` or `--prefix`: Define a prefix for the input files to be compressed. Only files that start with the specified prefix will be processed. By default, it processes all files in the directory.
52
+ - `-o` or `--output`: Specify the output directory where the compressed files will be saved. If not provided, the compressed files will be saved in the same directory as the input files.
53
+ - `-s` or `--suffix`: Add a specific suffix to the output file names. This can help differentiate compressed files from the original ones. By default, `compressed` suffix is added.
54
+ - `-r` or `--remove-original`: If this flag is set, the original files will be deleted after successful compression. By default, original files are retained.
55
+
56
+ Supported file extensions:
57
+
58
+ - `.mp4`
59
+ - `.mkv`
60
+ - `.avi`
61
+ - `.mov`
62
+
63
+ Graceful shutdown:
64
+
65
+ The tool can be gracefully shut down using a keyboard interrupt (Ctrl+C). It will stop processing new files and complete the current compression before exiting.
66
+
67
+ ## License
68
+
69
+ MIT
@@ -0,0 +1,8 @@
1
+ vicompres/__init__.py,sha256=MEEDjJFW5lD8AwyUxQh1iRBGVho--_Cj45vk3R7pTZk,65
2
+ vicompres/main.py,sha256=2EHcr_Tw3AE4D0uKVwI33TbLXoKJjJC30_n-eGCnzEQ,8297
3
+ vicompres-0.1.0.dist-info/licenses/LICENSE,sha256=c5X73c5hzD0Gqlvmvz1VJeZT9IIJUP1Ve53cE3hKGaw,1073
4
+ vicompres-0.1.0.dist-info/METADATA,sha256=cpjSXq0BL3iTK_aCGv6jADRjuCdnDD13IgE_QcpQGmw,2823
5
+ vicompres-0.1.0.dist-info/WHEEL,sha256=YCfwYGOYMi5Jhw2fU4yNgwErybb2IX5PEwBKV4ZbdBo,91
6
+ vicompres-0.1.0.dist-info/entry_points.txt,sha256=3cWRPAZYhK_U-AsgigpnKi22d3s-DWfIYJu3HAoLJew,50
7
+ vicompres-0.1.0.dist-info/top_level.txt,sha256=daHAeR7IPX_0Cmh8oPdy65OLd1Z1tdTTgbWsHUi3TT4,10
8
+ vicompres-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ vicompres = vicompres.main:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kirill Pechenkin
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ vicompres