CLI Module¶
Command-line interface implementation using Typer and Rich.
Module Documentation¶
cli
¶
Command-line interface for the loups package.
Classes¶
Functions¶
get_default_template
¶
Get path to the default bundled template image.
Returns:
| Type | Description |
|---|---|
Path
|
Path to the bundled template_solid.png file. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the default template cannot be located. |
Source code in loups/cli.py
get_default_thumbnail_template
¶
Get path to the default bundled thumbnail template image.
Returns:
| Type | Description |
|---|---|
Path
|
Path to the bundled thumbnail_template.png file. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the default thumbnail template cannot be located. |
Source code in loups/cli.py
setup_logging
¶
Configure logging with file rotation and error output.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
log_path
|
Optional[Path]
|
Optional path for log file. If None, file logging is disabled. |
None
|
quiet
|
bool
|
If True, suppress non-error console output. |
False
|
debug
|
bool
|
If True, set file log level to DEBUG instead of INFO. |
False
|
Note
File logs rotate at 10MB with 3 backup files. Errors always go to stderr regardless of quiet mode.
Source code in loups/cli.py
format_elapsed_time
¶
Format elapsed time as HH:MM:SS or MM:SS.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seconds
|
float
|
Elapsed time in seconds. |
required |
Returns:
| Type | Description |
|---|---|
str
|
Formatted time string (MM:SS if < 1 hour, otherwise HH:MM:SS). |
Examples:
Source code in loups/cli.py
create_progress_display
¶
create_progress_display(
elapsed: float,
batter_count: int,
spinner_state: int,
percent: Optional[float] = None,
last_batter: Optional[str] = None,
) -> Text
Create animated progress display with softball animation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
elapsed
|
float
|
Elapsed time in seconds. |
required |
batter_count
|
int
|
Number of batters found so far. |
required |
spinner_state
|
int
|
Current animation frame number. |
required |
percent
|
Optional[float]
|
Optional scan completion percentage. |
None
|
last_batter
|
Optional[str]
|
Optional name of most recently found batter. |
None
|
Returns:
| Type | Description |
|---|---|
Text
|
Rich Text object with animated progress display. |
Source code in loups/cli.py
create_thumbnail_progress_display
¶
Create animated progress display for thumbnail extraction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spinner_state
|
int
|
Current animation frame number. |
required |
Returns:
| Type | Description |
|---|---|
Text
|
Rich Text object with animated progress display. |
Source code in loups/cli.py
thumbnail
¶
thumbnail(
ctx: Context,
thumbnail_template: Optional[Path] = Option(
None,
"--thumbnail-template",
help="Path to thumbnail template image (defaults to bundled template)",
),
thumbnail_output: Optional[Path] = Option(
None,
"--thumbnail-output",
help="Output path for thumbnail (default: <video>-thumbnail.jpg in cwd)",
),
thumbnail_scan_duration: int = Option(
120,
"--thumbnail-scan-duration",
help="Maximum seconds to scan from video start",
),
thumbnail_threshold: float = Option(
0.35,
"--thumbnail-threshold",
min=0.0,
max=1.0,
help="Minimum SSIM score to accept (0.0-1.0)",
),
thumbnail_frames_per_second: int = Option(
3,
"--thumbnail-frames-per-second",
min=1,
help="Frame sampling rate (frames to check per second)",
),
quiet: bool = Option(
False,
"--quiet",
"-q",
help="Suppress progress display and output",
),
log: Optional[str] = Option(
None,
"--log",
"-l",
is_flag=False,
flag_value="loups.log",
help="Enable logging. Use without argument for default 'loups.log', or provide a path for custom location. Logs rotate at 10MB, keeps 3 backups.",
),
debug: bool = Option(
False,
"--debug",
"-d",
help="Enable DEBUG level logging to file (default is INFO)",
),
) -> None
Extract thumbnail from video using SSIM-based template matching.
Scan video frames from the beginning to find a frame matching the template. Uses Structural Similarity Index (SSIM) for accurate frame matching. Stops at first match above threshold for efficiency.
Examples:
Extract with default template:
Custom template and output:
Source code in loups/cli.py
396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 | |
callback
¶
callback(
ctx: Context,
video: Path = Argument(
..., help="Path to the video file to scan"
),
template: Optional[Path] = Option(
None,
"--template",
"-t",
help="Path to template image (defaults to bundled template)",
),
log: Optional[str] = Option(
None,
"--log",
"-l",
is_flag=False,
flag_value="loups.log",
help="Enable logging. Use without argument for default 'loups.log', or provide a path for custom location. Logs rotate at 10MB, keeps 3 backups.",
),
output: Optional[Path] = Option(
None,
"--output",
"-o",
help="Save results to file (YouTube chapter format)",
),
quiet: bool = Option(
False,
"--quiet",
"-q",
help="Suppress progress display and output (errors still go to stderr)",
),
debug: bool = Option(
False,
"--debug",
"-d",
help="Enable DEBUG level logging to file (default is INFO)",
),
extract_thumbnail: bool = Option(
False,
"--extract-thumbnail",
help="Extract thumbnail during chapter scan",
),
thumbnail_template: Optional[Path] = Option(
None,
"--thumbnail-template",
help="Path to thumbnail template (defaults to bundled template)",
),
thumbnail_output: Optional[Path] = Option(
None,
"--thumbnail-output",
help="Output path for thumbnail (default: <video>-thumbnail.jpg in cwd)",
),
thumbnail_threshold: float = Option(
0.35,
"--thumbnail-threshold",
min=0.0,
max=1.0,
help="Minimum SSIM score for thumbnail (0.0-1.0)",
),
thumbnail_scan_duration: int = Option(
120,
"--thumbnail-scan-duration",
help="Maximum seconds to scan for thumbnail",
),
thumbnail_frames_per_second: int = Option(
3,
"--thumbnail-frames-per-second",
min=1,
help="Frame sampling rate for thumbnail extraction",
),
) -> None
Scan video to extract batter information and generate YouTube chapters.
Main command for processing Lights Out HB fastpitch game videos (or any video with consistent identifying frames). Detects batters using template matching and extracts names via OCR. Outputs YouTube-compatible chapter timestamps.
Examples:
Basic scan with default template:
Save chapters to file:
Extract thumbnail and scan for batters:
Use 'thumbnail' subcommand for standalone thumbnail extraction:
Source code in loups/cli.py
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 | |
CLI Architecture¶
The Loups CLI is built with:
- Typer - Modern CLI framework
- Rich - Beautiful terminal output
- Subcommands - Main command + thumbnail extraction
graph TD
A[loups CLI] --> B[Main Command]
A --> C[Thumbnail Subcommand]
B --> B1[Parse Arguments]
B1 --> B2[Initialize Loups]
B2 --> B3[Scan Video]
B3 --> B4[Display/Save Results]
C --> C1[Parse Arguments]
C1 --> C2[Extract Thumbnail]
C2 --> C3[Save JPEG]
style A fill:#00ffff,stroke:#000,color:#000
style B fill:#00b8d4,stroke:#000,color:#fff
style C fill:#00b8d4,stroke:#000,color:#fff
style B4 fill:#00ffff,stroke:#000,color:#000
style C3 fill:#00ffff,stroke:#000,color:#000
Customizing the CLI¶
Extending Commands¶
You can build on top of the Loups CLI:
from loups.cli import app
import typer
@app.command()
def batch(
directory: str = typer.Argument(..., help="Directory with videos"),
template: str = typer.Option(None, "-t", "--template")
):
"""Process all videos in a directory."""
from pathlib import Path
from loups import Loups
video_dir = Path(directory)
for video in video_dir.glob("*.mp4"):
print(f"Processing {video.name}...")
loups = Loups(
video_path=str(video),
template_path=template
)
chapters = loups.scan()
# Save output
output = video.with_suffix(".txt")
with open(output, "w") as f:
for ch in chapters:
f.write(f"{ch.timestamp} {ch.title}\n")
if __name__ == "__main__":
app()
Custom Progress Display¶
Replace the default progress bar:
from loups import Loups
from rich.progress import Progress, SpinnerColumn, TextColumn
class CustomLoups(Loups):
def scan(self):
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
transient=True
) as progress:
task = progress.add_task("Scanning...", total=None)
# Your custom processing
results = super().scan()
progress.update(task, completed=True)
return results
Output Formatting¶
Custom Chapter Format¶
from loups import Loups
loups = Loups("video.mp4", "template.png")
chapters = loups.scan()
# Custom format
for i, ch in enumerate(chapters, 1):
print(f"{i}. [{ch.timestamp}] {ch.title}")
# JSON format
import json
output = json.dumps([
{"time": ch.timestamp, "title": ch.title}
for ch in chapters
], indent=2)
print(output)
# Markdown format
print("## Chapters\n")
for ch in chapters:
print(f"- **{ch.timestamp}** - {ch.title}")
Automation Examples¶
Shell Script Integration¶
#!/bin/bash
# process_videos.sh
for video in videos/*.mp4; do
echo "Processing: $video"
# Run Loups
loups -q -o "${video%.mp4}.txt" "$video"
# Check exit code
if [ $? -eq 0 ]; then
echo "✅ Success: $video"
else
echo "❌ Failed: $video"
fi
done
Python Automation¶
import subprocess
from pathlib import Path
videos = Path("videos").glob("*.mp4")
for video in videos:
output = video.with_suffix(".txt")
# Run Loups CLI
result = subprocess.run([
"loups",
"-q",
"-o", str(output),
str(video)
], capture_output=True, text=True)
if result.returncode == 0:
print(f"✅ {video.name}")
else:
print(f"❌ {video.name}: {result.stderr}")
CLI Development¶
Running from Source¶
Testing CLI Commands¶
from typer.testing import CliRunner
from loups.cli import app
runner = CliRunner()
def test_main_command():
result = runner.invoke(app, ["--help"])
assert result.exit_code == 0
assert "video" in result.stdout.lower()
def test_thumbnail_command():
result = runner.invoke(app, [
"test.mp4",
"thumbnail",
"--thumbnail-output", "thumb.jpg"
])
assert result.exit_code == 0
Command Reference¶
For complete CLI usage documentation, see:
- CLI Reference - All command options
- Quick Start - Usage examples
Related¶
- Loups Class - Core Python API
- Thumbnail Extraction - Thumbnail API
- CLI Reference Guide - User documentation