• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

popstas / talks-reducer / 18619239937

18 Oct 2025 06:15PM UTC coverage: 70.865% (-0.3%) from 71.158%
18619239937

push

github

web-flow
feat: Add 480p small preset option (#121)

* Add 480p small preset option

* Add 480p preset toggle to graphical interfaces

22 of 46 new or added lines in 8 files covered. (47.83%)

413 existing lines in 9 files now uncovered.

4996 of 7050 relevant lines covered (70.87%)

0.71 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

83.5
/talks_reducer/cli.py
1
"""Command line interface for the talks reducer package."""
2

3
from __future__ import annotations
1✔
4

5
import argparse
1✔
6
import os
1✔
7
import shutil
1✔
8
import subprocess
1✔
9
import sys
1✔
10
import time
1✔
11
from importlib import import_module
1✔
12
from pathlib import Path
1✔
13
from typing import Callable, Dict, List, Optional, Sequence, Tuple
1✔
14

15
from . import audio
1✔
16
from .ffmpeg import FFmpegNotFoundError
1✔
17
from .models import ProcessingOptions, default_temp_folder
1✔
18
from .pipeline import speed_up_video
1✔
19
from .progress import TqdmProgressReporter
1✔
20
from .version_utils import resolve_version
1✔
21

22

23
def _build_parser() -> argparse.ArgumentParser:
1✔
24
    """Create the argument parser used by the command line interface."""
25

26
    parser = argparse.ArgumentParser(
1✔
27
        description="Modifies a video file to play at different speeds when there is sound vs. silence.",
28
    )
29

30
    # Add version argument
31
    pkg_version = resolve_version()
1✔
32

33
    parser.add_argument(
1✔
34
        "--version",
35
        action="version",
36
        version=f"talks-reducer {pkg_version}",
37
    )
38

39
    parser.add_argument(
1✔
40
        "input_file",
41
        type=str,
42
        nargs="+",
43
        help="The video file(s) you want modified. Can be one or more directories and / or single files.",
44
    )
45
    parser.add_argument(
1✔
46
        "-o",
47
        "--output_file",
48
        type=str,
49
        dest="output_file",
50
        help="The output file. Only usable if a single file is given. If not included, it'll append _ALTERED to the name.",
51
    )
52
    parser.add_argument(
1✔
53
        "--temp_folder",
54
        type=str,
55
        default=str(default_temp_folder()),
56
        help="The file path of the temporary working folder.",
57
    )
58
    parser.add_argument(
1✔
59
        "-t",
60
        "--silent_threshold",
61
        type=float,
62
        dest="silent_threshold",
63
        help="The volume amount that frames' audio needs to surpass to be considered sounded. Defaults to 0.05.",
64
    )
65
    parser.add_argument(
1✔
66
        "-S",
67
        "--sounded_speed",
68
        type=float,
69
        dest="sounded_speed",
70
        help="The speed that sounded (spoken) frames should be played at. Defaults to 1.",
71
    )
72
    parser.add_argument(
1✔
73
        "-s",
74
        "--silent_speed",
75
        type=float,
76
        dest="silent_speed",
77
        help="The speed that silent frames should be played at. Defaults to 4.",
78
    )
79
    parser.add_argument(
1✔
80
        "-fm",
81
        "--frame_margin",
82
        type=float,
83
        dest="frame_spreadage",
84
        help="Some silent frames adjacent to sounded frames are included to provide context. Defaults to 2.",
85
    )
86
    parser.add_argument(
1✔
87
        "-sr",
88
        "--sample_rate",
89
        type=float,
90
        dest="sample_rate",
91
        help="Sample rate of the input and output videos. Usually extracted automatically by FFmpeg.",
92
    )
93
    parser.add_argument(
1✔
94
        "--small",
95
        action="store_true",
96
        help="Apply small file optimizations: resize video to 720p (or 480p with --480), audio to 128k bitrate, best compression (uses CUDA if available).",
97
    )
98
    parser.add_argument(
1✔
99
        "--480",
100
        dest="small_480",
101
        action="store_true",
102
        help="Use with --small to scale video to 480p instead of 720p.",
103
    )
104
    parser.add_argument(
1✔
105
        "--url",
106
        dest="server_url",
107
        default=None,
108
        help="Process videos via a Talks Reducer server at the provided base URL (for example, http://localhost:9005).",
109
    )
110
    parser.add_argument(
1✔
111
        "--host",
112
        dest="host",
113
        default=None,
114
        help="Shortcut for --url when targeting a Talks Reducer server on port 9005 (for example, localhost).",
115
    )
116
    parser.add_argument(
1✔
117
        "--server-stream",
118
        action="store_true",
119
        help="Stream remote progress updates when using --url.",
120
    )
121
    return parser
1✔
122

123

124
def gather_input_files(paths: List[str]) -> List[str]:
1✔
125
    """Expand provided paths into a flat list of files that contain audio streams."""
126

127
    files: List[str] = []
1✔
128
    for input_path in paths:
1✔
129
        if os.path.isfile(input_path) and audio.is_valid_input_file(input_path):
1✔
130
            files.append(os.path.abspath(input_path))
1✔
131
        elif os.path.isdir(input_path):
1✔
132
            for file in os.listdir(input_path):
1✔
133
                candidate = os.path.join(input_path, file)
1✔
134
                if audio.is_valid_input_file(candidate):
1✔
135
                    files.append(candidate)
1✔
136
    return files
1✔
137

138

139
def _print_total_time(start_time: float) -> None:
1✔
140
    """Print the elapsed processing time since *start_time*."""
141

142
    end_time = time.time()
1✔
143
    total_time = end_time - start_time
1✔
144
    hours, remainder = divmod(total_time, 3600)
1✔
145
    minutes, seconds = divmod(remainder, 60)
1✔
146
    print(f"\nTime: {int(hours)}h {int(minutes)}m {seconds:.2f}s")
1✔
147

148

149
class CliApplication:
1✔
150
    """Coordinator for CLI processing with dependency injection support."""
151

152
    def __init__(
1✔
153
        self,
154
        *,
155
        gather_files: Callable[[List[str]], List[str]],
156
        send_video: Optional[Callable[..., Tuple[Path, str, str]]],
157
        speed_up: Callable[[ProcessingOptions, object], object],
158
        reporter_factory: Callable[[], object],
159
        remote_error_message: Optional[str] = None,
160
    ) -> None:
161
        self._gather_files = gather_files
1✔
162
        self._send_video = send_video
1✔
163
        self._speed_up = speed_up
1✔
164
        self._reporter_factory = reporter_factory
1✔
165
        self._remote_error_message = remote_error_message
1✔
166

167
    def run(self, parsed_args: argparse.Namespace) -> Tuple[int, List[str]]:
1✔
168
        """Execute the CLI pipeline for *parsed_args*."""
169

170
        start_time = time.time()
1✔
171
        files = self._gather_files(parsed_args.input_file)
1✔
172

173
        args: Dict[str, object] = {
1✔
174
            key: value for key, value in vars(parsed_args).items() if value is not None
175
        }
176
        del args["input_file"]
1✔
177

178
        if "host" in args:
1✔
179
            del args["host"]
×
180

181
        if len(files) > 1 and "output_file" in args:
1✔
182
            del args["output_file"]
×
183

184
        if getattr(parsed_args, "small_480", False) and not getattr(
1✔
185
            parsed_args, "small", False
186
        ):
NEW
187
            print(
×
188
                "Warning: --480 has no effect unless --small is also provided.",
189
                file=sys.stderr,
190
            )
191

192
        error_messages: List[str] = []
1✔
193
        reporter_logs: List[str] = []
1✔
194

195
        if getattr(parsed_args, "server_url", None):
1✔
196
            remote_success, remote_errors, fallback_logs = self._process_via_server(
1✔
197
                files, parsed_args, start_time
198
            )
199
            error_messages.extend(remote_errors)
1✔
200
            reporter_logs.extend(fallback_logs)
1✔
201
            if remote_success:
1✔
202
                return 0, error_messages
1✔
203

204
        reporter = self._reporter_factory()
1✔
205
        for message in reporter_logs:
1✔
206
            reporter.log(message)
1✔
207

208
        for index, file in enumerate(files):
1✔
209
            print(
1✔
210
                f"Processing file {index + 1}/{len(files)} '{os.path.basename(file)}'"
211
            )
212
            local_options = dict(args)
1✔
213

214
            option_kwargs: Dict[str, object] = {"input_file": Path(file)}
1✔
215

216
            if "output_file" in local_options:
1✔
217
                option_kwargs["output_file"] = Path(local_options["output_file"])
1✔
218
            if "temp_folder" in local_options:
1✔
219
                option_kwargs["temp_folder"] = Path(local_options["temp_folder"])
1✔
220
            if "silent_threshold" in local_options:
1✔
221
                option_kwargs["silent_threshold"] = float(
1✔
222
                    local_options["silent_threshold"]
223
                )
224
            if "silent_speed" in local_options:
1✔
225
                option_kwargs["silent_speed"] = float(local_options["silent_speed"])
1✔
226
            if "sounded_speed" in local_options:
1✔
227
                option_kwargs["sounded_speed"] = float(local_options["sounded_speed"])
1✔
228
            if "frame_spreadage" in local_options:
1✔
229
                option_kwargs["frame_spreadage"] = int(local_options["frame_spreadage"])
1✔
230
            if "sample_rate" in local_options:
1✔
231
                option_kwargs["sample_rate"] = int(local_options["sample_rate"])
1✔
232
            if "small" in local_options:
1✔
233
                option_kwargs["small"] = bool(local_options["small"])
1✔
234
            if local_options.get("small_480"):
1✔
NEW
235
                option_kwargs["small_target_height"] = 480
×
236
            options = ProcessingOptions(**option_kwargs)
1✔
237

238
            try:
1✔
239
                result = self._speed_up(options, reporter=reporter)
1✔
240
            except FFmpegNotFoundError as exc:
×
241
                message = str(exc)
×
242
                return 1, [*error_messages, message]
×
243

244
            reporter.log(f"Completed: {result.output_file}")
1✔
245
            summary_parts: List[str] = []
1✔
246
            time_ratio = getattr(result, "time_ratio", None)
1✔
247
            size_ratio = getattr(result, "size_ratio", None)
1✔
248
            if time_ratio is not None:
1✔
249
                summary_parts.append(f"{time_ratio * 100:.0f}% time")
1✔
250
            if size_ratio is not None:
1✔
251
                summary_parts.append(f"{size_ratio * 100:.0f}% size")
1✔
252
            if summary_parts:
1✔
253
                reporter.log("Result: " + ", ".join(summary_parts))
1✔
254

255
        _print_total_time(start_time)
1✔
256
        return 0, error_messages
1✔
257

258
    def _process_via_server(
1✔
259
        self,
260
        files: Sequence[str],
261
        parsed_args: argparse.Namespace,
262
        start_time: float,
263
    ) -> Tuple[bool, List[str], List[str]]:
264
        """Upload *files* to the configured server and download the results."""
265

266
        if not self._send_video:
1✔
267
            message = self._remote_error_message or "Server processing is unavailable."
1✔
268
            fallback_notice = "Falling back to local processing pipeline."
1✔
269
            return False, [message, fallback_notice], [message, fallback_notice]
1✔
270

271
        server_url = parsed_args.server_url
1✔
272
        if not server_url:
1✔
273
            message = "Server URL was not provided."
×
274
            fallback_notice = "Falling back to local processing pipeline."
×
275
            return False, [message, fallback_notice], [message, fallback_notice]
×
276

277
        output_override: Optional[Path] = None
1✔
278
        if parsed_args.output_file and len(files) == 1:
1✔
279
            output_override = Path(parsed_args.output_file).expanduser()
×
280
        elif parsed_args.output_file and len(files) > 1:
1✔
281
            print(
1✔
282
                "Warning: --output is ignored when processing multiple files via the server.",
283
                file=sys.stderr,
284
            )
285

286
        remote_option_values: Dict[str, object] = {}
1✔
287
        if parsed_args.silent_threshold is not None:
1✔
288
            remote_option_values["silent_threshold"] = float(
1✔
289
                parsed_args.silent_threshold
290
            )
291
        if parsed_args.silent_speed is not None:
1✔
292
            remote_option_values["silent_speed"] = float(parsed_args.silent_speed)
1✔
293
        if parsed_args.sounded_speed is not None:
1✔
294
            remote_option_values["sounded_speed"] = float(parsed_args.sounded_speed)
1✔
295

296
        unsupported_options: List[str] = []
1✔
297
        for name in ("frame_spreadage", "sample_rate", "temp_folder"):
1✔
298
            if getattr(parsed_args, name) is not None:
1✔
299
                unsupported_options.append(f"--{name.replace('_', '-')}")
1✔
300

301
        if unsupported_options:
1✔
302
            print(
1✔
303
                "Warning: the following options are ignored when using --url: "
304
                + ", ".join(sorted(unsupported_options)),
305
                file=sys.stderr,
306
            )
307

308
        small_480_mode = bool(getattr(parsed_args, "small_480", False)) and bool(
1✔
309
            getattr(parsed_args, "small", False)
310
        )
311
        if small_480_mode:
1✔
NEW
312
            remote_option_values["small_480"] = True
×
313

314
        for index, file in enumerate(files, start=1):
1✔
315
            basename = os.path.basename(file)
1✔
316
            print(
1✔
317
                f"Processing file {index}/{len(files)} '{basename}' via server {server_url}"
318
            )
319
            printed_log_header = False
1✔
320
            progress_state: dict[str, tuple[Optional[int], Optional[int], str]] = {}
1✔
321
            stream_updates = bool(getattr(parsed_args, "server_stream", False))
1✔
322

323
            def _stream_server_log(line: str) -> None:
1✔
324
                nonlocal printed_log_header
325
                if not printed_log_header:
1✔
326
                    print("\nServer log:", flush=True)
1✔
327
                    printed_log_header = True
1✔
328
                print(line, flush=True)
1✔
329

330
            def _stream_progress(
1✔
331
                desc: str, current: Optional[int], total: Optional[int], unit: str
332
            ) -> None:
333
                key = desc or "Processing"
1✔
334
                state = (current, total, unit)
1✔
335
                if progress_state.get(key) == state:
1✔
336
                    return
1✔
337
                progress_state[key] = state
1✔
338

339
                parts: List[str] = []
1✔
340
                if current is not None and total and total > 0:
1✔
341
                    percent = (current / total) * 100
1✔
342
                    parts.append(f"{current}/{total}")
1✔
343
                    parts.append(f"{percent:.1f}%")
1✔
344
                elif current is not None:
1✔
345
                    parts.append(str(current))
×
346
                if unit:
1✔
347
                    parts.append(unit)
1✔
348
                message = " ".join(parts).strip()
1✔
349
                print(f"{key}: {message or 'update'}", flush=True)
1✔
350

351
            try:
1✔
352
                destination, summary, log_text = self._send_video(
1✔
353
                    input_path=Path(file),
354
                    output_path=output_override,
355
                    server_url=server_url,
356
                    small=bool(parsed_args.small),
357
                    small_480=small_480_mode,
358
                    **remote_option_values,
359
                    log_callback=_stream_server_log,
360
                    stream_updates=stream_updates,
361
                    progress_callback=_stream_progress if stream_updates else None,
362
                )
363
            except Exception as exc:  # pragma: no cover - network failure safeguard
364
                message = f"Failed to process {basename} via server: {exc}"
365
                fallback_notice = "Falling back to local processing pipeline."
366
                return False, [message, fallback_notice], [message, fallback_notice]
367

368
            print(summary)
1✔
369
            print(f"Saved processed video to {destination}")
1✔
370
            if log_text.strip() and not printed_log_header:
1✔
371
                print("\nServer log:\n" + log_text)
1✔
372

373
        _print_total_time(start_time)
1✔
374
        return True, [], []
1✔
375

376

377
def _launch_gui(argv: Sequence[str]) -> bool:
1✔
378
    """Attempt to launch the GUI with the provided arguments."""
379

380
    try:
×
381
        gui_module = import_module(".gui", __package__)
×
382
    except ImportError:
×
383
        return False
×
384

385
    gui_main = getattr(gui_module, "main", None)
×
386
    if gui_main is None:
×
387
        return False
×
388

389
    return bool(gui_main(list(argv)))
×
390

391

392
def _launch_server(argv: Sequence[str]) -> bool:
1✔
393
    """Attempt to launch the Gradio server with the provided arguments."""
394

395
    try:
×
396
        server_module = import_module(".server", __package__)
×
397
    except ImportError:
×
398
        return False
×
399

400
    server_main = getattr(server_module, "main", None)
×
401
    if server_main is None:
×
402
        return False
×
403

404
    server_main(list(argv))
×
405
    return True
×
406

407

408
def _find_server_tray_binary() -> Optional[Path]:
1✔
409
    """Return the best available path to the server tray executable."""
410

411
    binary_name = "talks-reducer-server-tray"
1✔
412
    candidates: List[Path] = []
1✔
413

414
    which_path = shutil.which(binary_name)
1✔
415
    if which_path:
1✔
416
        candidates.append(Path(which_path))
1✔
417

418
    try:
1✔
419
        launcher_dir = Path(sys.argv[0]).resolve().parent
1✔
420
    except Exception:
×
421
        launcher_dir = None
×
422

423
    potential_names = [binary_name]
1✔
424
    if sys.platform == "win32":
1✔
425
        potential_names = [f"{binary_name}.exe", binary_name]
×
426

427
    if launcher_dir is not None:
1✔
428
        for name in potential_names:
1✔
429
            candidates.append(launcher_dir / name)
1✔
430

431
    for candidate in candidates:
1✔
432
        if candidate and candidate.exists() and os.access(candidate, os.X_OK):
1✔
433
            return candidate
1✔
434

435
    return None
×
436

437

438
def _should_hide_subprocess_console() -> bool:
1✔
439
    """Return ``True` ` when a detached Windows launch should hide the console."""
440

441
    if sys.platform != "win32":
1✔
442
        return False
1✔
443

444
    try:
1✔
445
        import ctypes
1✔
446
    except Exception:  # pragma: no cover - optional runtime dependency
447
        return False
448

449
    try:
1✔
450
        get_console_window = ctypes.windll.kernel32.GetConsoleWindow  # type: ignore[attr-defined]
1✔
451
    except Exception:  # pragma: no cover - platform specific guard
452
        return False
453

454
    try:
1✔
455
        handle = get_console_window()
1✔
456
    except Exception:  # pragma: no cover - defensive fallback
457
        return False
458

459
    return handle == 0
1✔
460

461

462
def _launch_server_tray_binary(argv: Sequence[str]) -> bool:
1✔
463
    """Launch the packaged server tray executable when available."""
464

465
    command = _find_server_tray_binary()
1✔
466
    if command is None:
1✔
467
        return False
1✔
468

469
    tray_args = [str(command), *list(argv)]
1✔
470

471
    run_kwargs: Dict[str, object] = {"check": False}
1✔
472

473
    if sys.platform == "win32":
1✔
474
        no_window_flag = getattr(subprocess, "CREATE_NO_WINDOW", 0)
1✔
475
        if no_window_flag and _should_hide_subprocess_console():
1✔
476
            run_kwargs["creationflags"] = no_window_flag
1✔
477

478
    try:
1✔
479
        result = subprocess.run(tray_args, **run_kwargs)
1✔
480
    except OSError:
×
481
        return False
×
482

483
    return result.returncode == 0
1✔
484

485

486
def _launch_server_tray(argv: Sequence[str]) -> bool:
1✔
487
    """Attempt to launch the server tray helper with the provided arguments."""
488

489
    if _launch_server_tray_binary(argv):
1✔
490
        return True
×
491

492
    try:
1✔
493
        tray_module = import_module(".server_tray", __package__)
1✔
494
    except ImportError:
×
495
        return False
×
496

497
    tray_main = getattr(tray_module, "main", None)
1✔
498
    if tray_main is None:
1✔
499
        return False
×
500

501
    tray_main(list(argv))
1✔
502
    return True
1✔
503

504

505
def main(argv: Optional[Sequence[str]] = None) -> None:
1✔
506
    """Entry point for the command line interface.
507

508
    Launch the GUI when run without arguments, otherwise defer to the CLI.
509
    """
510

511
    if argv is None:
1✔
512
        argv_list = sys.argv[1:]
×
513
    else:
514
        argv_list = list(argv)
1✔
515

516
    if "--server" in argv_list:
1✔
517
        index = argv_list.index("--server")
1✔
518
        tray_args = argv_list[index + 1 :]
1✔
519
        if not _launch_server_tray(tray_args):
1✔
520
            print("Server tray mode is unavailable.", file=sys.stderr)
1✔
521
            sys.exit(1)
1✔
522
        return
1✔
523

524
    if argv_list and argv_list[0] in {"server", "serve"}:
1✔
525
        if not _launch_server(argv_list[1:]):
1✔
526
            print("Gradio server mode is unavailable.", file=sys.stderr)
1✔
527
            sys.exit(1)
1✔
528
        return
1✔
529

530
    if not argv_list:
1✔
531
        if _launch_gui(argv_list):
1✔
532
            return
1✔
533

534
        parser = _build_parser()
×
535
        parser.print_help()
×
536
        return
×
537

538
    parser = _build_parser()
1✔
539
    parsed_args = parser.parse_args(argv_list)
1✔
540

541
    host_value = getattr(parsed_args, "host", None)
1✔
542
    if host_value:
1✔
543
        parsed_args.server_url = f"http://{host_value}:9005"
×
544

545
    send_video = None
1✔
546
    remote_error_message: Optional[str] = None
1✔
547
    try:  # pragma: no cover - optional dependency guard
548
        from . import service_client
549
    except ImportError as exc:
×
550
        remote_error_message = (
×
551
            "Server mode requires the gradio_client dependency. " f"({exc})"
552
        )
553
    else:
554
        send_video = service_client.send_video
1✔
555

556
    application = CliApplication(
1✔
557
        gather_files=gather_input_files,
558
        send_video=send_video,
559
        speed_up=speed_up_video,
560
        reporter_factory=TqdmProgressReporter,
561
        remote_error_message=remote_error_message,
562
    )
563

564
    exit_code, error_messages = application.run(parsed_args)
1✔
565
    for message in error_messages:
1✔
566
        print(message, file=sys.stderr)
×
567
    if exit_code:
1✔
568
        sys.exit(exit_code)
×
569

570

571
if __name__ == "__main__":
1✔
572
    main()
×
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc