Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 6 additions & 7 deletions .github/workflows/ci-cd.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ name: CI/CD

on:
push:
branches: [master]
branches: ['*']
pull_request:
branches: [master]
branches: ['*']

env:
REGISTRY: ghcr.io
Expand All @@ -19,7 +19,7 @@ jobs:
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: "3.13"
python-version: '3.13'

- name: Install dependencies
run: make dev-requirements
Expand All @@ -30,8 +30,6 @@ jobs:
build-and-push:
needs: test
runs-on: ubuntu-latest
# Only run this job on master branch pushes, not on PRs
if: github.event_name == 'push' && github.ref == 'refs/heads/master'
permissions:
contents: read
packages: write
Expand All @@ -46,7 +44,7 @@ jobs:
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}

- name: Extract metadata for Docker
- name: Set up Docker tags
id: meta
uses: docker/metadata-action@v5
with:
Expand All @@ -57,7 +55,8 @@ jobs:
type=ref,event=pr
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
type=raw,value=latest
# Only add latest tag for master branch
type=raw,value=latest,enable=${{ github.ref == 'refs/heads/master' }}

- name: Build and push Docker image
uses: docker/build-push-action@v5
Expand Down
59 changes: 54 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,14 @@ Welcome to **Plexmuse**! This project leverages the power of AI to generate pers
### Installation

1. **Clone the repository**:

```sh
git clone git@github.com:LubergAlexander/plexmuse.git
cd plexmuse
```

2. **Setup**:

```sh
make all
```
Expand All @@ -48,26 +50,74 @@ You can run the application using the Makefile or directly with Docker.
#### Using the Makefile

1. **Set up and run the application**:

```sh
make run
```
2. **Start**:
```sh
make start
```

#### Using Docker

1. **Build the Docker image**:

```sh
docker compose build
```

2. **Start the Docker container**:

```sh
docker compose up
```

#### Using the Published Docker Image

You can also use the pre-built Docker image from GitHub Container Registry, which is automatically built and published on each push to the master branch:

1. **Pull the Docker image**:

```sh
docker pull ghcr.io/lubergalexander/plexmuse:latest
```

2. **Run the Docker container**:

```sh
docker run -p 8000:8000 \
-e PLEX_BASE_URL=your_plex_url \
-e PLEX_TOKEN=your_plex_token \
-e OPENAI_API_KEY=your_openai_key \
ghcr.io/lubergalexander/plexmuse:latest
```

3. **Using Docker Compose**:

Create a `docker-compose.yml` file:

```yaml
version: '3'
services:
plexmuse:
image: ghcr.io/lubergalexander/plexmuse:latest
ports:
- "8000:8000"
environment:
- PLEX_BASE_URL=your_plex_url
- PLEX_TOKEN=your_plex_token
- OPENAI_API_KEY=your_openai_key
# Add other environment variables as needed
restart: unless-stopped
```

Then run:

```sh
docker compose up -d
```

4. **Available Tags**:

- `latest`: The most recent build from the master branch
- SHA tags: Each image is also tagged with the Git commit SHA

## Usage 📖

Expand All @@ -76,7 +126,6 @@ You can run the application using the Makefile or directly with Docker.
Access the user interface at the root route `/`. This UI allows you to interact with the API, select playlist length, and is mobile-friendly.
![UI Screenshot](plexmuse-ui.png)


### API

Send a POST request to `/recommendations` with the following JSON body:
Expand Down
67 changes: 49 additions & 18 deletions app/services/plex_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ def __init__(self, base_url: str, token: str):
self.token = token
self._server: Optional[PlexServer] = None
self.machine_identifier: Optional[str] = None
self._music_library = None
self._music_libraries = []

# Only cache artists
self._artists_cache: Dict[str, Artist] = {} # key: artist_id -> Artist
Expand All @@ -86,17 +86,33 @@ def initialize(self):
self._server = PlexServer(self.base_url, self.token)
self.machine_identifier = self._server.machineIdentifier

self._music_library = self._server.library.section("Music")

# Load all artists
artists = self._music_library.search(libtype="artist")
for artist in artists:
artist_id = str(artist.ratingKey)
self._artists_cache[artist_id] = Artist(
id=artist_id, name=artist.title, genres=[genre.tag for genre in getattr(artist, "genres", [])]
)

logger.info("Cached %d artists", len(self._artists_cache))
# Find all music libraries instead of assuming one called "Music"
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

probably drop the comment or rephrase, PR resolves the assumption

self._music_libraries = []
for section in self._server.library.sections():
if section.type == "artist":
self._music_libraries.append(section)
logger.info(f"Found music library: {section.title}")

if not self._music_libraries:
logger.warning("No music libraries found on the Plex server")
return

# Load all artists from all music libraries
for library in self._music_libraries:
artists = library.search(libtype="artist")
for artist in artists:
artist_id = str(artist.ratingKey)
# Only add if not already in cache (avoid duplicates across libraries)
if artist_id not in self._artists_cache:
self._artists_cache[artist_id] = Artist(
id=artist_id,
name=artist.title,
genres=[genre.tag for genre in getattr(artist, "genres", [])],
)

logger.info(
"Cached %d artists from %d music libraries", len(self._artists_cache), len(self._music_libraries)
)

except Exception as e:
logger.error("Failed to initialize Plex cache: %s", str(e))
Expand All @@ -120,9 +136,13 @@ def get_artists_albums_bulk(self, artist_names: List[str]) -> dict:
for artist in self._artists_cache.values():
if artist.name.lower() == artist_name.lower():
# Found in cache, now get the Plex object
matches = self._music_library.search(artist.name, libtype="artist")
if matches:
artist_found = matches[0]
# Search across all music libraries
for library in self._music_libraries:
matches = library.search(artist.name, libtype="artist")
if matches:
artist_found = matches[0]
break
if artist_found:
break

if artist_found:
Expand Down Expand Up @@ -154,7 +174,14 @@ def create_curated_playlist(

# Process each artist's tracks in bulk
for artist_name, track_titles in artist_tracks.items():
artists = self._music_library.search(artist_name, libtype="artist")
# Search for artist across all music libraries
artists = []
for library in self._music_libraries:
found_artists = library.search(artist_name, libtype="artist")
if found_artists:
artists.append(found_artists[0])
break # Found in one library, no need to check others

if not artists:
logger.warning("Artist not found: %s", artist_name)
continue
Expand All @@ -172,8 +199,12 @@ def create_curated_playlist(
logger.debug("Matched '%s' to '%s' (score: %.2f)", title, track.title, score)
matched_tracks.append(track)
else:
# If no match found for artist, try global search
global_tracks = self._music_library.search(title, libtype="track")
# If no match found for artist, try global search across all music libraries
global_tracks = []
for library in self._music_libraries:
found_tracks = library.search(title, libtype="track")
global_tracks.extend(found_tracks)

if global_tracks:
track, score = find_best_track_match(global_tracks, title, threshold=0.75)
if track and track.artist().title.lower() == artist_name.lower():
Expand Down
37 changes: 30 additions & 7 deletions tests/test_plex_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,13 @@ def mock_plex_server():

# Create mock library section
mock_library = Mock()
mock_server.return_value.library.section.return_value = mock_library

# Mock library sections for multiple music libraries
mock_section = Mock(type="artist", title="Mock Music Library")
mock_server.return_value.library.sections.return_value = [mock_section]

# Make the mock_section searchable
mock_section.search = mock_library.search

yield mock_server, mock_library

Expand All @@ -70,7 +76,7 @@ def plex_service(mock_plex_server): # pylint: disable=unused-argument

def test_plex_service_initialization(plex_service, mock_plex_server): # pylint: disable=unused-argument
"""Test PlexService initialization."""
_, mock_library = mock_plex_server
mock_server, mock_library = mock_plex_server

# Mock artists for initialization
artist1 = Mock(ratingKey="1", title="Artist1")
Expand All @@ -84,6 +90,7 @@ def test_plex_service_initialization(plex_service, mock_plex_server): # pylint:
mock_genre3 = Mock(tag="Pop")
artist2.genres.append(mock_genre3)

# Set up the mock library section to return artists
mock_library.search.return_value = [artist1, artist2]

# Initialize service
Expand Down Expand Up @@ -124,9 +131,13 @@ def test_get_artists_albums_bulk(plex_service, mock_plex_server):
# Setup mock search results
mock_library.search.return_value = [artist1]

# Initialize plex service
# Initialize plex service with mock music libraries
plex_service.initialize()
plex_service._music_library = mock_library

# Create a mock music library and add it to the service
mock_music_library = Mock()
mock_music_library.search = mock_library.search
plex_service._music_libraries = [mock_music_library]
plex_service._server = mock_server.return_value

# Add artist to cache
Expand Down Expand Up @@ -177,7 +188,11 @@ def mock_search(*args, **kwargs): # pylint: disable=unused-argument

# Initialize plex service
plex_service.initialize()
plex_service._music_library = mock_library

# Create a mock music library and add it to the service
mock_music_library = Mock()
mock_music_library.search = mock_library.search
plex_service._music_libraries = [mock_music_library]
plex_service._server = mock_server.return_value

# Test playlist creation
Expand All @@ -198,7 +213,11 @@ def test_create_curated_playlist_no_matches(plex_service, mock_plex_server):

# Initialize plex service
plex_service.initialize()
plex_service._music_library = mock_library

# Create a mock music library and add it to the service
mock_music_library = Mock()
mock_music_library.search = mock_library.search
plex_service._music_libraries = [mock_music_library]
plex_service._server = mock_server.return_value

# Test playlist creation with no matches
Expand Down Expand Up @@ -242,7 +261,11 @@ def mock_search(*args, **kwargs): # pylint: disable=unused-argument

# Initialize plex service
plex_service.initialize()
plex_service._music_library = mock_library

# Create a mock music library and add it to the service
mock_music_library = Mock()
mock_music_library.search = mock_library.search
plex_service._music_libraries = [mock_music_library]
plex_service._server = mock_server.return_value

# Test playlist creation with fuzzy matching
Expand Down