Skip to content

Commit

Permalink
Use logging and not print
Browse files Browse the repository at this point in the history
  • Loading branch information
mayhem committed Feb 9, 2024
1 parent 0bd5ee4 commit ed77548
Show file tree
Hide file tree
Showing 26 changed files with 276 additions and 203 deletions.
75 changes: 49 additions & 26 deletions troi/__init__.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
from abc import ABC, abstractmethod
import logging
import random
from typing import Dict

from troi.logging import info, debug
from troi.utils import recursively_update_dict

DEVELOPMENT_SERVER_URL = "https://datasets.listenbrainz.org"
Expand All @@ -18,7 +18,6 @@ class Element(ABC):

def __init__(self, patch=None):
self.sources = []
self.logger = logging.getLogger(type(self).__name__)
self.patch = patch

def set_patch_object(self, patch):
Expand All @@ -38,13 +37,6 @@ def local_storage(self):

return self.patch.local_storage


def log(self, msg):
'''
Log a message with the info log level, which is the default for troi.
'''
self.logger.info(msg)

def set_sources(self, sources):
"""
Set the source elements for this element.
Expand All @@ -53,7 +45,7 @@ def set_sources(self, sources):
"""

if not isinstance(sources, list):
sources = [ sources ]
sources = [sources]

self.sources = sources

Expand All @@ -67,9 +59,7 @@ def set_sources(self, sources):
break

if not matched:
raise RuntimeError("Element %s cannot accept any of %s as input." %
(type(self).__name__, self.inputs()))

raise RuntimeError("Element %s cannot accept any of %s as input." % (type(self).__name__, self.inputs()))

def check(self):
"""
Expand All @@ -83,7 +73,6 @@ def check(self):
for source in self.sources:
source.check()


def generate(self, quiet):
"""
Generate output from the pipeline. This should be called on
Expand All @@ -102,7 +91,7 @@ def generate(self, quiet):
if len(self.inputs()) > 0 and \
len(result) > 0 and type(result[0]) not in self.inputs() and \
len(source.outputs()) > 0:
raise RuntimeError("Element %s was expected to output %s, but actually output %s" %
raise RuntimeError("Element %s was expected to output %s, but actually output %s" %
(type(source).__name__, source.outputs()[0], type(result[0])))

source_lists.append(result)
Expand All @@ -113,9 +102,9 @@ def generate(self, quiet):

if not quiet:
if len(items) > 0 and type(items[0]) == Playlist:
print(" %-50s %d items" % (type(self).__name__[:49], len(items[0].recordings or [])))
info(" %-50s %d items" % (type(self).__name__[:49], len(items[0].recordings or [])))
else:
print(" %-50s %d items" % (type(self).__name__[:49], len(items or [])))
info(" %-50s %d items" % (type(self).__name__[:49], len(items or [])))

return items

Expand Down Expand Up @@ -174,6 +163,7 @@ class Entity(ABC):
of an artist or the listenbrainz dict might contain the BPM for a track.
How exactly these dicts will be organized is TDB.
"""

def __init__(self, ranking=None, musicbrainz=None, listenbrainz=None, acousticbrainz=None):
self.name = None
self.mbid = None
Expand Down Expand Up @@ -209,6 +199,7 @@ class Area(Entity):
"""
The class that represents an area.
"""

def __init__(self, id=id, name=None):
Entity.__init__(self)
self.name = name
Expand All @@ -222,8 +213,15 @@ class Artist(Entity):
"""
The class that represents an artist.
"""
def __init__(self, name=None, mbids=None, artist_credit_id=None, ranking=None,
musicbrainz=None, listenbrainz=None, acousticbrainz=None):

def __init__(self,
name=None,
mbids=None,
artist_credit_id=None,
ranking=None,
musicbrainz=None,
listenbrainz=None,
acousticbrainz=None):
Entity.__init__(self, ranking=ranking, musicbrainz=musicbrainz, listenbrainz=listenbrainz, acousticbrainz=acousticbrainz)
self.name = name
self.artist_credit_id = artist_credit_id
Expand All @@ -242,8 +240,8 @@ class Release(Entity):
"""
The class that represents a release.
"""
def __init__(self, name=None, mbid=None, artist=None, ranking=None,
musicbrainz=None, listenbrainz=None, acousticbrainz=None):

def __init__(self, name=None, mbid=None, artist=None, ranking=None, musicbrainz=None, listenbrainz=None, acousticbrainz=None):
Entity.__init__(self, ranking=ranking, musicbrainz=musicbrainz, listenbrainz=listenbrainz, acousticbrainz=acousticbrainz)
self.artist = artist
self.name = name
Expand All @@ -257,10 +255,22 @@ class Recording(Entity):
"""
The class that represents a recording.
"""
def __init__(self, name=None, mbid=None, msid=None, duration=None, artist=None, release=None,
ranking=None, year=None, spotify_id=None, musicbrainz=None, listenbrainz=None, acousticbrainz=None):

def __init__(self,
name=None,
mbid=None,
msid=None,
duration=None,
artist=None,
release=None,
ranking=None,
year=None,
spotify_id=None,
musicbrainz=None,
listenbrainz=None,
acousticbrainz=None):
Entity.__init__(self, ranking=ranking, musicbrainz=musicbrainz, listenbrainz=listenbrainz, acousticbrainz=acousticbrainz)
self.duration = duration # track duration in ms
self.duration = duration # track duration in ms
self.artist = artist
self.release = release
self.name = name
Expand All @@ -283,8 +293,20 @@ class Playlist(Entity):
and that filename is the suggested filename that this playlist should be saved as, if the user asked to
do that and didn't provide a different filename.
"""
def __init__(self, name=None, mbid=None, filename=None, recordings=None, description=None, ranking=None,
year=None, musicbrainz=None, listenbrainz=None, acousticbrainz=None, patch_slug=None, user_name=None,

def __init__(self,
name=None,
mbid=None,
filename=None,
recordings=None,
description=None,
ranking=None,
year=None,
musicbrainz=None,
listenbrainz=None,
acousticbrainz=None,
patch_slug=None,
user_name=None,
additional_metadata=None):
Entity.__init__(self, ranking=ranking, musicbrainz=musicbrainz, listenbrainz=listenbrainz, acousticbrainz=acousticbrainz)
self.name = name
Expand Down Expand Up @@ -317,6 +339,7 @@ class User(Entity):
"""
The class that represents a ListenBrainz user.
"""

def __init__(self, user_name=None, user_id=None):
Entity.__init__(self)
self.user_name = user_name
Expand Down
27 changes: 17 additions & 10 deletions troi/cli.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
#!/usr/bin/env python3

import logging
import sys

import click

from troi.logging import set_log_level, info
from troi.utils import discover_patches
from troi.core import list_patches, patch_info, convert_patch_to_command
from troi.content_resolver.cli import cli as resolver_cli, db_file_check, output_playlist
Expand All @@ -17,7 +20,6 @@
except ImportError as err:
config = None


@click.group()
def cli():
pass
Expand Down Expand Up @@ -63,10 +65,12 @@ def playlist(patch, quiet, save, token, upload, args, created_for, name, desc, m
"""
Generate a global MBID based playlist using a patch
"""

set_log_level(quiet)
patchname = patch
patches = discover_patches()
if patchname not in patches:
print("Cannot load patch '%s'. Use the list command to get a list of available patches." % patchname, file=sys.stderr)
info("Cannot load patch '%s'. Use the list command to get a list of available patches." % patchname, file=sys.stderr)
return None

patch_args = {
Expand Down Expand Up @@ -101,10 +105,10 @@ def playlist(patch, quiet, save, token, upload, args, created_for, name, desc, m

user_feedback = patch.user_feedback()
if len(user_feedback) > 0:
print("User feedback:")
info("User feedback:")
for feedback in user_feedback:
print(f" * {feedback}")
print()
info(f" * {feedback}")
info()

sys.exit(0 if ret else -1)

Expand Down Expand Up @@ -135,13 +139,14 @@ def info(patch):
@click.argument('jspf_playlist')
def resolve(db_file, threshold, upload_to_subsonic, save_to_m3u, save_to_jspf, dont_ask, quiet, jspf_playlist):
""" Resolve a global JSPF playlist with MusicBrainz MBIDs to files in the local collection"""
set_log_level(quiet)
db_file = db_file_check(db_file)
db = SubsonicDatabase(db_file, config, quiet)
db.open()
lbrl = ListenBrainzRadioLocal(quiet)
playlist = read_jspf_playlist(jspf_playlist)
lbrl.resolve_playlist(threshold, playlist)
output_playlist(db, playlist, upload_to_subsonic, save_to_m3u, save_to_jspf, dont_ask, quiet)
output_playlist(db, playlist, upload_to_subsonic, save_to_m3u, save_to_jspf, dont_ask)


@cli.command(name="lb-radio", context_settings=dict(ignore_unknown_options=True, ))
Expand All @@ -156,18 +161,19 @@ def resolve(db_file, threshold, upload_to_subsonic, save_to_m3u, save_to_jspf, d
@click.argument('prompt')
def lb_radio(db_file, threshold, upload_to_subsonic, save_to_m3u, save_to_jspf, dont_ask, quiet, mode, prompt):
"""Use LB Radio to create a playlist from a prompt, using a local music collection"""
set_log_level(quiet)
db_file = db_file_check(db_file)
db = SubsonicDatabase(db_file, config, quiet)
db.open()
r = ListenBrainzRadioLocal()
playlist = r.generate(mode, prompt, threshold, quiet)
r = ListenBrainzRadioLocal(quiet)
playlist = r.generate(mode, prompt, threshold)
try:
_ = playlist.playlists[0].recordings[0]
except (KeyError, IndexError, AttributeError):
db.metadata_sanity_check(include_subsonic=upload_to_subsonic)
return

output_playlist(db, playlist, upload_to_subsonic, save_to_m3u, save_to_jspf, dont_ask, quiet)
output_playlist(db, playlist, upload_to_subsonic, save_to_m3u, save_to_jspf, dont_ask)


@cli.command("weekly-jams", context_settings=dict(ignore_unknown_options=True, ))
Expand All @@ -181,6 +187,7 @@ def lb_radio(db_file, threshold, upload_to_subsonic, save_to_m3u, save_to_jspf,
@click.argument('user_name')
def periodic_jams(db_file, threshold, upload_to_subsonic, save_to_m3u, save_to_jspf, dont_ask, quiet, user_name):
"Generate a weekly jams playlist for your local collection"
set_log_level(quiet)
db_file = db_file_check(db_file)
db = SubsonicDatabase(db_file, config, quiet)
db.open()
Expand All @@ -193,7 +200,7 @@ def periodic_jams(db_file, threshold, upload_to_subsonic, save_to_m3u, save_to_j
db.metadata_sanity_check(include_subsonic=upload_to_subsonic)
return

output_playlist(db, playlist, upload_to_subsonic, save_to_m3u, save_to_jspf, dont_ask, quiet)
output_playlist(db, playlist, upload_to_subsonic, save_to_m3u, save_to_jspf, dont_ask)


@cli.command(context_settings=dict(ignore_unknown_options=True, ))
Expand Down
Loading

0 comments on commit ed77548

Please sign in to comment.