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

popstas / talks-reducer / 18619607454

18 Oct 2025 06:49PM UTC coverage: 69.249% (-1.9%) from 71.158%
18619607454

Pull #119

github

web-flow
Merge 941c5e173 into 0674fd1c8
Pull Request #119: Add Windows taskbar progress integration

78 of 193 new or added lines in 8 files covered. (40.41%)

950 existing lines in 18 files now uncovered.

5148 of 7434 relevant lines covered (69.25%)

0.69 hits per line

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

83.61
/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 .logging_config import configure_logging_from_env
1✔
18
from .models import ProcessingOptions, default_temp_folder
1✔
19
from .pipeline import speed_up_video
1✔
20
from .progress import TqdmProgressReporter
1✔
21
from .version_utils import resolve_version
1✔
22

23

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

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

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

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

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

124

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

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

139

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

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

149

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

377

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

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

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

UNCOV
390
    return bool(gui_main(list(argv)))
×
391

392

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

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

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

UNCOV
405
    server_main(list(argv))
×
UNCOV
406
    return True
×
407

408

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

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

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

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

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

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

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

UNCOV
436
    return None
×
437

438

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

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

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

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

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

460
    return handle == 0
1✔
461

462

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

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

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

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

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

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

484
    return result.returncode == 0
1✔
485

486

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

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

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

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

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

505

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

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

512
    configure_logging_from_env()
1✔
513

514
    if argv is None:
1✔
515
        argv_list = sys.argv[1:]
×
516
    else:
517
        argv_list = list(argv)
1✔
518

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

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

533
    if not argv_list:
1✔
534
        if _launch_gui(argv_list):
1✔
535
            return
1✔
536

UNCOV
537
        parser = _build_parser()
×
UNCOV
538
        parser.print_help()
×
UNCOV
539
        return
×
540

541
    parser = _build_parser()
1✔
542
    parsed_args = parser.parse_args(argv_list)
1✔
543

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

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

559
    application = CliApplication(
1✔
560
        gather_files=gather_input_files,
561
        send_video=send_video,
562
        speed_up=speed_up_video,
563
        reporter_factory=TqdmProgressReporter,
564
        remote_error_message=remote_error_message,
565
    )
566

567
    exit_code, error_messages = application.run(parsed_args)
1✔
568
    for message in error_messages:
1✔
UNCOV
569
        print(message, file=sys.stderr)
×
570
    if exit_code:
1✔
UNCOV
571
        sys.exit(exit_code)
×
572

573

574
if __name__ == "__main__":
1✔
UNCOV
575
    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