An open API service indexing awesome lists of open source software.

https://github.com/computingvictor/spotify_playlists_to_youtube_music

A Python tool to seamlessly transfer your playlists from Spotify to YouTube Music using official APIs with OAuth2 authentication.
https://github.com/computingvictor/spotify_playlists_to_youtube_music

api-integration automation cli-tool data-migration music-converter music-tools open-source playlist-migration python spotify spotipy youtube-music ytmusicapi

Last synced: about 2 months ago
JSON representation

A Python tool to seamlessly transfer your playlists from Spotify to YouTube Music using official APIs with OAuth2 authentication.

Awesome Lists containing this project

README

          

# Spotify to YouTube Music Playlist Migrator

[![Python 3.13+](https://img.shields.io/badge/python-3.13+-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![GitHub issues](https://img.shields.io/github/issues/ComputingVictor/Spotify_Playlists_to_Youtube_Music)](https://github.com/ComputingVictor/Spotify_Playlists_to_Youtube_Music/issues)
[![GitHub stars](https://img.shields.io/github/stars/ComputingVictor/Spotify_Playlists_to_Youtube_Music)](https://github.com/ComputingVictor/Spotify_Playlists_to_Youtube_Music/stargazers)
[![GitHub forks](https://img.shields.io/github/forks/ComputingVictor/Spotify_Playlists_to_Youtube_Music)](https://github.com/ComputingVictor/Spotify_Playlists_to_Youtube_Music/network)

A comprehensive Python tool to easily migrate your playlists from Spotify to YouTube Music with OAuth2 authentication.

![image](https://github.com/user-attachments/assets/e161f8cc-8589-4c95-9049-b3d8d1a3fb54)

## Overview

This tool allows you to:
- Connect to your Spotify account
- List all your Spotify playlists
- Select which playlists to migrate
- Search for each song on YouTube Music
- Create new playlists on YouTube Music
- Migrate songs while preserving playlist names and descriptions

## Project Structure

```
SPOTIFY_PLAYLISTS_TO_YOUTUBE_MUSIC/
├── .venv/ # Virtual environment directory (created by uv venv)
├── .env # Environment file with Spotify credentials (created manually)
├── .gitignore # Git ignore file (excludes sensitive files)
├── .python-version # Python version specification
├── requirements.txt # List of Python dependencies
├── pyproject.toml # Project metadata and dependencies
├── README.md # Project documentation
├── src/ # Source code directory
│ └── main.py # Main migration script
├── uv.lock # Lock file generated by uv (dependency versions)

# Files generated during setup/execution:
├── oauth.json # Created by running "ytmusicapi oauth"
│ # Contains OAuth tokens with expiration details
└── ytmusic_headers.json # Generated automatically during first run
# Contains HTTP headers for YouTube Music API
```

## Requirements

- Python 3.13 or higher
- Spotify Developer Account
- Google Cloud Project with YouTube Data API enabled

## Installation

### Using uv (recommended)

```bash
uv venv
uv pip install -r requirements.txt
```

### Using pip

```bash
pip install -r requirements.txt
```

### Development installation

```bash
uv venv
uv pip install -e .
```

## Configuration

### 1. Spotify API Setup

1. Go to the [Spotify Developer Dashboard](https://developer.spotify.com/dashboard/applications)
2. Create a new application
3. Obtain your **Client ID** and **Client Secret**
4. Add `http://localhost:8888/callback` as a **Redirect URI** in the app settings
5. Save these credentials for later use

### 2. YouTube Music API Setup

As of November 2024, YouTube Music requires OAuth authentication using the YouTube Data API:

1. Go to the [Google Cloud Console](https://console.cloud.google.com/)
2. Create a new project or select an existing one
3. Enable the **YouTube Data API v3**
4. Go to **APIs & Services > OAuth consent screen**:
- Select "External" user type
- Fill in the required app information
- **IMPORTANT**: Add your YouTube Music account email as a test user
- You'll need to add any Google account that will use this tool as a test user
5. Go to **APIs & Services > Credentials**:
- Click "Create Credentials"
- Select **OAuth client ID**
- Choose **TVs and Limited Input devices**
- Download the credentials file (optional, but good to have)

6. Run the OAuth setup utility:
```bash
ytmusicapi oauth
```

7. Follow the instructions:
- A URL and code will be displayed
- Open the URL in your browser
- Sign in with your Google account
- Enter the displayed code
- Confirm the requested permissions

8. This will create an `oauth.json` file in the current directory with this format:
```json
{
"scope": "https://www.googleapis.com/auth/youtube",
"token_type": "Bearer",
"access_token": "ya29.a0AZYkNZiK...",
"refresh_token": "1//03OJYQHLNGghG...",
"expires_at": 1744620393,
"expires_in": 3599
}
```

### 3. Environment File (Optional)

Create a `.env` file in the project root to store your Spotify credentials:

```
SPOTIFY_CLIENT_ID=your_client_id_here
SPOTIFY_CLIENT_SECRET=your_client_secret_here
SPOTIFY_REDIRECT_URI=http://localhost:8888/callback
```

## Usage

1. Make sure the `oauth.json` file is in the same directory as the script

2. Run the migrator:
```bash
python src/main.py
```

3. If you haven't set up the `.env` file, you'll be prompted to enter your Spotify credentials

4. The script will:
- Connect to both Spotify and YouTube Music
- List all your Spotify playlists
- Ask which ones you want to migrate

5. Enter playlist numbers separated by commas (e.g., "1,3,5") or "all" to migrate everything

6. The migration process will begin:
- Each playlist will be created on YouTube Music
- Each song will be searched on YouTube Music
- Matching songs will be added to the new playlist
- A summary will be displayed at the end

## Advanced Features

### Token Refreshing

OAuth tokens expire after approximately 1 hour (3599 seconds as specified in the `expires_in` field). If you get authentication errors:

1. Run `ytmusicapi oauth` again to generate a new token
2. Replace the existing `oauth.json` file
3. Delete the `ytmusic_headers.json` file if it exists
4. Run the script again

### Playlist Privacy

By default, all migrated playlists are set to PRIVATE. You can modify this in the code if needed.

## Troubleshooting

### Spotify Authentication Issues

- Verify your Client ID and Client Secret
- Ensure your Redirect URI is configured correctly in the Spotify Developer Dashboard
- Check if your `.env` file has the correct format

### YouTube Music Authentication Errors

- "invalid_grant" error: Your OAuth token has expired. Generate a new one with `ytmusicapi oauth`
- Permission errors: Make sure your email is added as a test user in the OAuth consent screen
- If you receive a 401 or 403 error, check that:
- The YouTube Data API is enabled in your Google Cloud project
- Your OAuth consent screen is properly configured

### Migration Errors

- Rate limiting: If you get API rate limit errors, the script will pause, but you might need to wait longer
- Songs not found: Some songs may not be available on YouTube Music or might have different titles
- Long playlists: YouTube Music has a limit of 5,000 songs per playlist

## Performance and Limitations

### API Rate Limits
- **Spotify API**: Generally allows up to 100 requests per second
- **YouTube Music API**: Has more restrictive rate limits (approximately 1-2 requests per second recommended)
- The tool includes automatic delays (0.5s between requests) to respect rate limits

### Known Limitations
- YouTube Music playlists are limited to 5,000 songs maximum
- Some songs may not be available on YouTube Music due to licensing
- Song matching is based on title and artist name, which may not always be accurate
- OAuth tokens expire after 1 hour and need to be refreshed

### Performance Tips
- For large playlists (>500 songs), expect migration to take 5-10 minutes per playlist
- Close other applications using YouTube Music API during migration
- If you encounter rate limit errors, wait a few minutes before retrying

## Error Handling

### Common Errors and Solutions

| Error | Cause | Solution |
|-------|-------|----------|
| `invalid_grant` | OAuth token expired | Run `ytmusicapi oauth` again |
| `401 Unauthorized` | Invalid credentials | Check Spotify Client ID/Secret |
| `403 Forbidden` | YouTube API not enabled | Enable YouTube Data API in Google Cloud Console |
| `Rate limit exceeded` | Too many API requests | Wait 5-10 minutes and try again |
| `Playlist creation failed` | YouTube Music API error | Check if you're signed into the correct Google account |

### Debugging Mode

To enable verbose logging, set the environment variable:
```bash
export SPOTIFY_YTMUSIC_DEBUG=1
python src/main.py
```

## Security Considerations

- **Never share your `oauth.json` file** - it contains your Google account tokens
- **Keep your `.env` file private** - it contains your Spotify credentials
- The tool only requests read access to Spotify and write access to YouTube Music
- All playlist creation is done with PRIVATE visibility by default
- No personal data is stored beyond the current session

## API Documentation

### Spotify Web API
- Documentation: https://developer.spotify.com/documentation/web-api
- Scopes used: `user-library-read`, `playlist-read-private`

### YouTube Music API (via ytmusicapi)
- Documentation: https://ytmusicapi.readthedocs.io/
- Permissions: YouTube Data API v3 access

## Dependencies

### Core Dependencies
- `spotipy>=2.25.1`: Spotify API client library
- `ytmusicapi>=1.10.3`: YouTube Music API client library
- `python-dotenv>=1.1.0`: Environment variable management
- `requests>=2.32.3`: HTTP request library

### Authentication Dependencies
- `google-api-python-client>=2.166.0`: Google API client library
- `google-auth-oauthlib>=1.2.1`: OAuth2 authentication for Google services
- `google-auth-httplib2>=0.2.0`: HTTP transport for Google Auth

### Optional Dependencies
- `browser-cookie3>=0.20.1`: Browser cookie extraction (fallback authentication)
- `Pillow>=10.2.0`: Image processing (for potential future features)

## Changelog

### v0.1.0 (Current)
- Initial release
- Basic playlist migration functionality
- OAuth2 authentication support for YouTube Music
- Support for Spotify API authentication via Client ID/Secret
- Batch processing of songs (50 songs per API call)
- Private playlist creation by default

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## Contributing

Contributions are welcome! Here's how you can help:

### Getting Started
1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Make your changes
4. Add tests if applicable
5. Ensure code follows the existing style
6. Commit your changes (`git commit -m 'Add amazing feature'`)
7. Push to the branch (`git push origin feature/amazing-feature`)
8. Open a Pull Request

### Development Setup
```bash
# Clone your fork
git clone https://github.com/yourusername/spotify-playlists-to-youtube-music.git
cd spotify-playlists-to-youtube-music

# Create virtual environment
uv venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate

# Install dependencies
uv pip install -e .
```

### Code Style Guidelines
- Follow PEP 8 for Python code style
- Use type hints for function parameters and return values
- Add docstrings for all public functions and classes
- Keep functions focused and under 50 lines when possible

### Bug Reports
Please include:
- Python version
- Operating system
- Complete error message
- Steps to reproduce
- Expected vs actual behavior

### Feature Requests
Please describe:
- The problem you're trying to solve
- Your proposed solution
- Any alternative solutions considered
- How this would benefit other users