|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +Guitar Pro YouTube Sync - Interactive CLI |
| 4 | +
|
| 5 | +Generates Guitar Pro (.gp) files from Songsterr tabs, |
| 6 | +optionally synced with YouTube audio. |
| 7 | +""" |
| 8 | + |
| 9 | +import sys |
| 10 | +from pathlib import Path |
| 11 | + |
| 12 | +import gen_gp |
| 13 | +from sync import ( |
| 14 | + fetch_song_meta, |
| 15 | + fetch_video_points, |
| 16 | + select_video_entry, |
| 17 | + download_youtube_audio, |
| 18 | + sync_gp_file, |
| 19 | + print_summary, |
| 20 | +) |
| 21 | +from utils import load_config, save_config |
| 22 | + |
| 23 | + |
| 24 | +BROWSERS = ["chrome", "firefox", "edge", "brave", "safari", "opera"] |
| 25 | + |
| 26 | + |
| 27 | +def prompt_yes_no(question: str, default: bool = True) -> bool: |
| 28 | + """Prompt user for yes/no answer.""" |
| 29 | + suffix = "[Y/n]" if default else "[y/N]" |
| 30 | + while True: |
| 31 | + answer = input(f"{question} {suffix}: ").strip().lower() |
| 32 | + if answer == "": |
| 33 | + return default |
| 34 | + if answer in ("y", "yes"): |
| 35 | + return True |
| 36 | + if answer in ("n", "no"): |
| 37 | + return False |
| 38 | + print(" Please enter 'y' or 'n'") |
| 39 | + |
| 40 | + |
| 41 | +def prompt_browser_choice() -> str | None: |
| 42 | + """Prompt user to select a browser for cookie extraction.""" |
| 43 | + print("\n YouTube may require authentication for this video.") |
| 44 | + print(" Select a browser to use cookies from (must be logged into YouTube):") |
| 45 | + for i, browser in enumerate(BROWSERS, 1): |
| 46 | + print(f" {i}. {browser}") |
| 47 | + skip_num = len(BROWSERS) + 1 |
| 48 | + print(f" {skip_num}. Skip audio") |
| 49 | + |
| 50 | + while True: |
| 51 | + try: |
| 52 | + choice = input(f"\n Choice [{skip_num}]: ").strip() |
| 53 | + if choice == "": |
| 54 | + return None |
| 55 | + idx = int(choice) |
| 56 | + if 1 <= idx <= len(BROWSERS): |
| 57 | + return BROWSERS[idx - 1] |
| 58 | + if idx == skip_num: |
| 59 | + return None |
| 60 | + print(f" Please enter a number between 1 and {skip_num}") |
| 61 | + except ValueError: |
| 62 | + print(" Please enter a number") |
| 63 | + |
| 64 | + |
| 65 | +def try_download_audio(video_id: str, audio_path: Path, trim_start: float, config: dict) -> bool: |
| 66 | + """Attempt to download audio, with automatic retry using saved browser and manual prompt. |
| 67 | +
|
| 68 | + Returns True if audio was downloaded successfully. |
| 69 | + """ |
| 70 | + # First attempt: no cookies |
| 71 | + try: |
| 72 | + download_youtube_audio(video_id, audio_path, trim_start=trim_start) |
| 73 | + return True |
| 74 | + except Exception as e: |
| 75 | + print(f"\n Audio download failed: {e}") |
| 76 | + |
| 77 | + # Second attempt: auto-retry with saved browser |
| 78 | + saved_browser = config.get("cookie_browser") |
| 79 | + if saved_browser: |
| 80 | + print(f"\n Retrying with saved browser ({saved_browser})...") |
| 81 | + try: |
| 82 | + download_youtube_audio(video_id, audio_path, trim_start=trim_start, cookies_browser=saved_browser) |
| 83 | + return True |
| 84 | + except Exception as e: |
| 85 | + print(f" Still failed: {e}") |
| 86 | + |
| 87 | + # Third attempt: ask user to pick a browser |
| 88 | + browser = prompt_browser_choice() |
| 89 | + if not browser: |
| 90 | + print(" Skipping audio.") |
| 91 | + return False |
| 92 | + |
| 93 | + print(f"\n Retrying with {browser} cookies...") |
| 94 | + try: |
| 95 | + download_youtube_audio(video_id, audio_path, trim_start=trim_start, cookies_browser=browser) |
| 96 | + # Save successful browser for next time |
| 97 | + config["cookie_browser"] = browser |
| 98 | + save_config(config) |
| 99 | + print(f" (Saved {browser} as default browser for next time)") |
| 100 | + return True |
| 101 | + except Exception as e: |
| 102 | + print(f"\n Download failed again: {e}") |
| 103 | + print(" Skipping audio.") |
| 104 | + return False |
| 105 | + |
| 106 | + |
| 107 | +def process_song(config: dict) -> None: |
| 108 | + """Process a single song (generate GP + optional audio sync).""" |
| 109 | + # Get song input |
| 110 | + while True: |
| 111 | + user_input = input("\nEnter Songsterr URL or song ID (or 'q' to quit): ").strip() |
| 112 | + if user_input.lower() in ("q", "quit", "exit"): |
| 113 | + raise SystemExit(0) |
| 114 | + if not user_input: |
| 115 | + continue |
| 116 | + try: |
| 117 | + song_id = gen_gp.parse_song_id(user_input) |
| 118 | + break |
| 119 | + except ValueError as e: |
| 120 | + print(f"\n Error: {e}") |
| 121 | + print(" Examples: https://www.songsterr.com/a/wsa/metallica-master-of-puppets-tab-s84 or 84") |
| 122 | + |
| 123 | + # Fetch metadata |
| 124 | + print("\nFetching song info...") |
| 125 | + try: |
| 126 | + meta = fetch_song_meta(song_id) |
| 127 | + except Exception as e: |
| 128 | + print(f"\n Error fetching song data: {e}") |
| 129 | + return |
| 130 | + |
| 131 | + artist = meta.get("artist", "Unknown") |
| 132 | + title = meta.get("title", "Unknown") |
| 133 | + num_tracks = len(meta.get("tracks", [])) |
| 134 | + print(f" Found: {artist} - {title} ({num_tracks} tracks)") |
| 135 | + |
| 136 | + include_audio = prompt_yes_no("\nInclude YouTube audio?", default=True) |
| 137 | + |
| 138 | + safe_name = "".join(c if c.isalnum() or c in " -_" else "" for c in f"{artist} - {title}").strip() |
| 139 | + total_steps = 3 if include_audio else 1 |
| 140 | + |
| 141 | + # Step 1: Generate GP file |
| 142 | + print(f"\n[1/{total_steps}] Generating Guitar Pro file...") |
| 143 | + try: |
| 144 | + gp_meta, tracks = gen_gp.fetch_all_tracks(song_id) |
| 145 | + gp_file = Path(f"{safe_name or 'output'}.gp").resolve() |
| 146 | + gen_gp.generate_gp(tracks, gp_file, gp_meta) |
| 147 | + except Exception as e: |
| 148 | + print(f"\n Error generating GP file: {e}") |
| 149 | + return |
| 150 | + |
| 151 | + if not include_audio: |
| 152 | + print(f"\nDone! File saved to: {gp_file}") |
| 153 | + return |
| 154 | + |
| 155 | + # Step 2: Download audio |
| 156 | + print(f"\n[2/{total_steps}] Downloading YouTube audio...") |
| 157 | + revision_id = meta["revisionId"] |
| 158 | + try: |
| 159 | + entries = fetch_video_points(song_id, revision_id) |
| 160 | + entry = select_video_entry(entries) |
| 161 | + except Exception as e: |
| 162 | + print(f"\n Error fetching video data: {e}") |
| 163 | + print(" Continuing without audio...") |
| 164 | + print(f"\nDone! File saved to: {gp_file}") |
| 165 | + return |
| 166 | + |
| 167 | + points = entry["points"] |
| 168 | + video_id = entry["videoId"] |
| 169 | + trim_start = points[0] if points else 0.0 |
| 170 | + audio_path = gp_file.parent / ".tmp_audio.mp3" |
| 171 | + |
| 172 | + audio_ok = try_download_audio(video_id, audio_path, trim_start, config) |
| 173 | + |
| 174 | + # Step 3: Sync |
| 175 | + print(f"\n[3/{total_steps}] Syncing audio with tab...") |
| 176 | + synced_path = gp_file.parent / f"{gp_file.stem}_synced{gp_file.suffix}" |
| 177 | + mp3_path = audio_path if audio_ok else None |
| 178 | + bpms = sync_gp_file(gp_file, points, synced_path, mp3_path=mp3_path) |
| 179 | + |
| 180 | + if audio_path.exists(): |
| 181 | + audio_path.unlink() |
| 182 | + |
| 183 | + print_summary(bpms, points) |
| 184 | + print(f"\nDone! File saved to: {synced_path}") |
| 185 | + |
| 186 | + |
| 187 | +def main(): |
| 188 | + print("=== Guitar Pro YouTube Sync ===") |
| 189 | + |
| 190 | + config = load_config() |
| 191 | + |
| 192 | + while True: |
| 193 | + try: |
| 194 | + process_song(config) |
| 195 | + print("\n" + "-" * 40) |
| 196 | + except SystemExit: |
| 197 | + print("\nGoodbye!") |
| 198 | + break |
| 199 | + except KeyboardInterrupt: |
| 200 | + print("\n\nGoodbye!") |
| 201 | + break |
| 202 | + except Exception as e: |
| 203 | + print(f"\nUnexpected error: {e}") |
| 204 | + print("You can try another song.\n") |
| 205 | + |
| 206 | + |
| 207 | +if __name__ == "__main__": |
| 208 | + main() |
0 commit comments