Spaces:
Sleeping
Sleeping
File size: 7,030 Bytes
4f9adc4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 | #!/usr/bin/env python3
"""
Test script for the source_finding module.
This script demonstrates and validates the functionality of:
1. Searching for games by team name(s)
2. Generating download commands
3. Extracting direct video URLs (if yt-dlp is available)
Usage:
# Activate virtual environment first
source .venv/bin/activate
# Run with default test (Ohio State vs Oregon)
python scripts/test_source_finding.py
# Search for a specific team
python scripts/test_source_finding.py --team-a "Tennessee"
# Search for a specific matchup
python scripts/test_source_finding.py --team-a "Ohio State" --team-b "Oregon"
# Search more pages (default is 3)
python scripts/test_source_finding.py --team-a "Michigan" --max-pages 10
# Test URL extraction on a specific result
python scripts/test_source_finding.py --team-a "Ohio State" --test-download
"""
import argparse
import logging
import sys
from pathlib import Path
# Add src to path for imports
sys.path.insert(0, str(Path(__file__).parent.parent / "src"))
from source_finding import search_games, get_download_command, extract_direct_video_url, get_suggested_filename
from source_finding.downloader import is_ytdlp_available, get_video_info
def setup_logging(verbose: bool = False) -> None:
"""Configure logging for the test script."""
level = logging.DEBUG if verbose else logging.INFO
logging.basicConfig(
level=level,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
datefmt="%H:%M:%S",
)
def print_separator(title: str = "") -> None:
"""Print a visual separator with optional title."""
width = 70
if title:
print(f"\n{'=' * width}")
print(f" {title}")
print(f"{'=' * width}")
else:
print(f"\n{'-' * width}")
def test_search(team_a: str, team_b: str | None, max_pages: int) -> None:
"""Test game search functionality."""
print_separator(f"Searching for: {team_a}" + (f" vs {team_b}" if team_b else ""))
print(f"\nParameters:")
print(f" team_a: {team_a}")
print(f" team_b: {team_b or '(any)'}")
print(f" max_pages: {max_pages}")
# Perform the search
results = search_games(team_a=team_a, team_b=team_b, max_pages=max_pages)
print(f"\nSearch Results:")
print(f" Pages searched: {results.pages_searched}")
print(f" Total games scanned: {results.total_games_scanned}")
print(f" Matching games found: {len(results.games)}")
if not results.games:
print("\n No matching games found!")
return results
print_separator("Found Games")
for i, game in enumerate(results.games, 1):
print(f"\n[{i}] {game.title}")
print(f" Teams: {game.team_a} vs {game.team_b}")
if game.event:
print(f" Event: {game.event}")
if game.year:
print(f" Year: {game.year}")
if game.date_str:
print(f" Date: {game.date_str}")
print(f" URL: {game.url}")
if game.thumbnail_url:
print(f" Thumbnail: {game.thumbnail_url[:60]}...")
return results
def test_download_command(game) -> None:
"""Test download command generation."""
print_separator("Download Command Generation")
# Generate download command
cmd = get_download_command(game, output_dir="~/Downloads")
filename = get_suggested_filename(game)
print(f"\nGame: {game}")
print(f"Suggested filename: {filename}")
print(f"\nDownload command:")
print(f" {cmd}")
def test_url_extraction(game) -> None:
"""Test direct URL extraction (requires yt-dlp)."""
print_separator("Direct URL Extraction")
if not is_ytdlp_available():
print("\n yt-dlp is not available. Install with: pip install yt-dlp")
print(" Skipping URL extraction test.")
return
print(f"\nExtracting direct URL for: {game.title}")
print(" (This may take 10-30 seconds...)")
url = extract_direct_video_url(game, timeout_seconds=60)
if url:
print(f"\n SUCCESS! Direct URL extracted:")
# Truncate URL for display if very long
if len(url) > 100:
print(f" {url[:100]}...")
else:
print(f" {url}")
print("\n This URL can be used for browser-direct download.")
print(" NOTE: URL may expire after a few minutes!")
else:
print("\n FAILED to extract direct URL.")
print(" The video may use a hosting service not supported by yt-dlp,")
print(" or there may be extraction issues.")
def test_video_info(game) -> None:
"""Test video info extraction (requires yt-dlp)."""
print_separator("Video Info Extraction")
if not is_ytdlp_available():
print("\n yt-dlp is not available. Skipping.")
return
print(f"\nGetting video info for: {game.title}")
print(" (This may take a few seconds...)")
info = get_video_info(game, timeout_seconds=30)
if info:
print("\n Video metadata:")
print(f" Title: {info.get('title', 'N/A')}")
print(f" Duration: {info.get('duration', 'N/A')} seconds")
filesize = info.get("filesize") or info.get("filesize_approx")
if filesize:
print(f" File size: {filesize / (1024*1024*1024):.2f} GB")
print(f" Format: {info.get('format', 'N/A')}")
print(f" Resolution: {info.get('resolution', 'N/A')}")
else:
print("\n FAILED to get video info.")
def main():
parser = argparse.ArgumentParser(description="Test the source_finding module")
parser.add_argument("--team-a", default="Ohio State", help="Primary team to search for")
parser.add_argument("--team-b", default=None, help="Optional second team for specific matchup")
parser.add_argument("--max-pages", type=int, default=3, help="Maximum pages to search")
parser.add_argument("--test-download", action="store_true", help="Test URL extraction on first result")
parser.add_argument("--verbose", "-v", action="store_true", help="Enable verbose logging")
args = parser.parse_args()
setup_logging(args.verbose)
print("\n" + "=" * 70)
print(" SOURCE FINDING MODULE TEST")
print("=" * 70)
# Check yt-dlp availability
print(f"\nyt-dlp available: {is_ytdlp_available()}")
# Run search test
results = test_search(args.team_a, args.team_b, args.max_pages)
if results and results.games:
# Test with the first result
first_game = results.games[0]
# Always test download command generation
test_download_command(first_game)
# Optionally test URL extraction
if args.test_download:
test_url_extraction(first_game)
test_video_info(first_game)
print_separator("Test Complete")
print("\nTo test URL extraction, run with --test-download flag:")
print(f' python scripts/test_source_finding.py --team-a "{args.team_a}" --test-download')
if __name__ == "__main__":
main()
|