|
| 1 | +import logging |
| 2 | +from pathlib import Path |
| 3 | +import typer |
| 4 | +from datetime import datetime |
| 5 | +import json |
| 6 | +from rich.logging import RichHandler |
| 7 | +from rich.console import Console |
| 8 | +from rich.progress import ( |
| 9 | + Progress, |
| 10 | + SpinnerColumn, |
| 11 | + BarColumn, |
| 12 | + TaskProgressColumn, |
| 13 | + TimeElapsedColumn, |
| 14 | +) |
| 15 | +from services import SpotifyService, ElasticsearchService |
| 16 | +from models import SpotifyTrack |
| 17 | + |
| 18 | +logger = None |
| 19 | + |
| 20 | + |
| 21 | +def try_parsing_date(text): |
| 22 | + """Attempt to parse a date""" |
| 23 | + for fmt in ("%Y-%m-%dT%H:%M:%SZ", "%Y-%m-%dT%H:%M:%S.%fZ"): |
| 24 | + try: |
| 25 | + return datetime.strptime(text, fmt) |
| 26 | + except ValueError: |
| 27 | + logger.error(f"Error parsing date: {text}") |
| 28 | + pass |
| 29 | + |
| 30 | + |
| 31 | +def process_history_file( |
| 32 | + file_path: str, |
| 33 | + spotify_svc: SpotifyService, |
| 34 | + es_svc: ElasticsearchService, |
| 35 | + user_name: str, |
| 36 | +): |
| 37 | + """Main processing function""" |
| 38 | + # Set up rich logging |
| 39 | + logging.basicConfig( |
| 40 | + level=logging.INFO, |
| 41 | + format="%(message)s", |
| 42 | + handlers=[RichHandler(rich_tracebacks=True)], |
| 43 | + ) |
| 44 | + logger = logging.getLogger(__name__) |
| 45 | + console = Console() |
| 46 | + |
| 47 | + with open(file_path) as f: |
| 48 | + history = json.load(f) |
| 49 | + |
| 50 | + console.print(f"[green]Processing {file_path}") |
| 51 | + |
| 52 | + documents = [] |
| 53 | + with Progress( |
| 54 | + SpinnerColumn(), |
| 55 | + "[progress.description]{task.description}", |
| 56 | + BarColumn(), |
| 57 | + TaskProgressColumn(), |
| 58 | + TimeElapsedColumn(), |
| 59 | + ) as progress: |
| 60 | + task = progress.add_task("[cyan]Processing tracks...", total=len(history)) |
| 61 | + |
| 62 | + total_entries = len(history) |
| 63 | + batch_size = 50 |
| 64 | + for i in range(0, total_entries, batch_size): |
| 65 | + entries_batch = history[i : i + batch_size] |
| 66 | + metadata_batch = spotify_svc.get_tracks_metadata(entries_batch) |
| 67 | + for entry in entries_batch: |
| 68 | + try: |
| 69 | + # let's make sure to only look at songs |
| 70 | + # we do not support videos, podcats or |
| 71 | + # anything else yet. |
| 72 | + if entry["spotify_track_uri"] is not None and entry[ |
| 73 | + "spotify_track_uri" |
| 74 | + ].startswith("spotify:track:"): |
| 75 | + track_id = entry["spotify_track_uri"].replace( |
| 76 | + "spotify:track:", "" |
| 77 | + ) |
| 78 | + metadata = metadata_batch.get(track_id, None) |
| 79 | + played_at = try_parsing_date(entry["ts"]) |
| 80 | + if metadata is not None: |
| 81 | + documents.append( |
| 82 | + SpotifyTrack( |
| 83 | + id=str( |
| 84 | + int( |
| 85 | + ( |
| 86 | + played_at - datetime(1970, 1, 1) |
| 87 | + ).total_seconds() |
| 88 | + ) |
| 89 | + ) |
| 90 | + + "_" |
| 91 | + + entry["master_metadata_album_artist_name"], |
| 92 | + artist=[ |
| 93 | + artist["name"] for artist in metadata["artists"] |
| 94 | + ], |
| 95 | + album=metadata["album"]["name"], |
| 96 | + country=entry["conn_country"], |
| 97 | + duration=metadata["duration_ms"], |
| 98 | + explicit=metadata["explicit"], |
| 99 | + listened_to_pct=( |
| 100 | + entry["ms_played"] / metadata["duration_ms"] |
| 101 | + if metadata["duration_ms"] > 0 |
| 102 | + else None |
| 103 | + ), |
| 104 | + listened_to_ms=entry["ms_played"], |
| 105 | + ip=entry["ip_addr"], |
| 106 | + reason_start=entry["reason_start"], |
| 107 | + reason_end=entry["reason_end"], |
| 108 | + shuffle=entry["shuffle"], |
| 109 | + skipped=entry["skipped"], |
| 110 | + offline=entry["offline"], |
| 111 | + title=metadata["name"], |
| 112 | + platform=entry["platform"], |
| 113 | + played_at=played_at, |
| 114 | + spotify_metadata=metadata, |
| 115 | + hourOfDay=played_at.hour, |
| 116 | + dayOfWeek=played_at.strftime("%A"), |
| 117 | + url=metadata["external_urls"]["spotify"], |
| 118 | + user=user_name, |
| 119 | + ) |
| 120 | + ) |
| 121 | + else: |
| 122 | + console.print(f"[red]Metadata not found for track: {entry}") |
| 123 | + if len(documents) >= 500: |
| 124 | + console.print( |
| 125 | + f"[green]Indexing batch of tracks... {len(documents)}" |
| 126 | + ) |
| 127 | + es_svc.bulk_index(documents) |
| 128 | + documents = [] |
| 129 | + progress.advance(task) |
| 130 | + |
| 131 | + except Exception as e: |
| 132 | + logger.error(f"Error processing track: {e}") |
| 133 | + spotify_svc.metadata_cache.save_cache() |
| 134 | + raise |
| 135 | + |
| 136 | + if documents: |
| 137 | + console.print(f"[green]Indexing final batch of tracks... {len(documents)}") |
| 138 | + es_svc.bulk_index(documents) |
| 139 | + console.print(f"[green]Done! {file_path} processed!") |
| 140 | + |
| 141 | + spotify_svc.metadata_cache.save_cache() |
| 142 | + |
| 143 | + |
| 144 | +app = typer.Typer() |
| 145 | + |
| 146 | + |
| 147 | +@app.command() |
| 148 | +def process_history( |
| 149 | + es_url: str = typer.Option(..., help="Elasticsearch URL"), |
| 150 | + es_api_key: str = typer.Option(..., help="Elasticsearch API Key"), |
| 151 | + spotify_client_id: str = typer.Option(None, help="Spotify Client ID"), |
| 152 | + spotify_client_secret: str = typer.Option(None, help="Spotify Client Secret"), |
| 153 | + user_name: str = typer.Option(None, help="User name"), |
| 154 | +): |
| 155 | + """Setup the services""" |
| 156 | + if spotify_client_id and spotify_client_secret: |
| 157 | + spotify_svc = SpotifyService( |
| 158 | + client_id=spotify_client_id, |
| 159 | + client_secret=spotify_client_secret, |
| 160 | + redirect_uri="http://localhost:9100", |
| 161 | + ) |
| 162 | + es_svc = ElasticsearchService(es_url=es_url, api_key=es_api_key) |
| 163 | + # Ensure index exists |
| 164 | + es_svc.check_index() |
| 165 | + es_svc.check_pipeline() |
| 166 | + |
| 167 | + files = list(Path("to_read").glob("*Audio*.json")) |
| 168 | + if not files: |
| 169 | + raise ValueError( |
| 170 | + "No JSON files found in 'to_read' directory, expected them to be named *Audio*.json, like Streaming_History_Audio_2023_8.json" |
| 171 | + ) |
| 172 | + else: |
| 173 | + for file_path in files: |
| 174 | + process_history_file(file_path, spotify_svc, es_svc, user_name) |
| 175 | + move_file(file_path) |
| 176 | + |
| 177 | + |
| 178 | +def move_file(file_path: Path): |
| 179 | + """Move the file to the 'processed' directory""" |
| 180 | + processed_dir = Path("processed") |
| 181 | + processed_dir.mkdir(exist_ok=True) |
| 182 | + new_path = Path("processed") / file_path.name |
| 183 | + file_path.rename(new_path) |
| 184 | + |
| 185 | + |
| 186 | +if __name__ == "__main__": |
| 187 | + app() |
0 commit comments