<commit_before># This file is part of beets.
# Copyright 2013, <NAME>.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.

"""Adds Beatport release and track search support to the autotagger
"""
import logging
import re
from datetime import datetime, timedelta

import requests

from beets import config
from beets.autotag.hooks import AlbumInfo, TrackInfo
from beets.plugins import BeetsPlugin

log = logging.getLogger('beets')


class BeatportAPIError(Exception):
    pass


class BeatportObject(object):
    beatport_id = None
    name = None
    release_date = None
    artists = []
    genres = []
    url = None

    def __init__(self, data):
        self.beatport_id = data['id']
        self.name = unicode(data['name'])
        if 'releaseDate' in data:
            self.release_date = datetime.strptime(data['releaseDate'],
                                                  '%Y-%m-%d')
        if 'artists' in data:
            self.artists = [(x['id'], unicode(x['name']))
                            for x in data['artists']]
        if 'genres' in data:
            self.genres = [unicode(x['name'])
                           for x in data['genres']]


class BeatportAPI(object):
    API_BASE = 'http://api.beatport.com/'

    @classmethod
    def get(cls, endpoint, **kwargs):
        try:
            response = requests.get(cls.API_BASE + endpoint, params=kwargs)
        except Exception as e:
            raise BeatportAPIError("Error connection to Beatport API: {}"
                                   .format(e.message))
        if not response:
            raise BeatportAPIError(
                "Error {0.status_code} for '{0.request.path_url}"
                .format(response))
        return response.json()['results']


class BeatportSearch(object):
    query = None
    release_type = None

    def __unicode__(self):
        return u"<BeatportSearch for {} \"{}\" with {} results>".format(
            self.release_type, self.query, len(self.results))

    def __init__(self, query, release_type='release', details=True):
        self.results = []
        self.query = query
        self.release_type = release_type
        response = BeatportAPI.get('catalog/3/search', query=query,
                                   facets=['fieldType:{}'
                                           .format(release_type)],
                                   perPage=5)
        for item in response:
            if release_type == 'release':
                release = BeatportRelease(item)
                if details:
                    release.get_tracks()
                self.results.append(release)
            elif release_type == 'track':
                self.results.append(BeatportTrack(item))


class BeatportRelease(BeatportObject):
    API_ENDPOINT = 'catalog/3/beatport/release'
    catalog_number = None
    label_name = None
    category = None

    def __unicode__(self):
        if len(self.artists) < 4:
            artist_str = ", ".join(x[1] for x in self.artists)
        else:
            artist_str = "Various Artists"
        return u"<BeatportRelease: {} - {} ({})>".format(artist_str, self.name,
                                                         self.catalog_number)

    def __init__(self, data):
        BeatportObject.__init__(self, data)
        if 'catalogNumber' in data:
            self.catalog_number = data['catalogNumber']
        if 'label' in data:
            self.label_name = data['label']['name']
        if 'category' in data:
            self.category = data['category']
        if 'slug' in data:
            self.url = "http://beatport.com/release/{}/{}".format(
                data['slug'], data['id'])

    @classmethod
    def from_id(cls, beatport_id):
        response = BeatportAPI.get(cls.API_ENDPOINT, id=beatport_id)
        release = BeatportRelease(response['release'])
        release.tracks = [BeatportTrack(x) for x in response['tracks']]
        return release

    def get_tracks(self):
        response = BeatportAPI.get(self.API_ENDPOINT, id=self.beatport_id)
        self.tracks = [BeatportTrack(x) for x in response['tracks']]


class BeatportTrack(BeatportObject):
    API_ENDPOINT = 'catalog/3/beatport/release'
    title = None
    mix_name = None
    length = None

    def __unicode__(self):
        artist_str = ", ".join(x[1] for x in self.artists)
        return u"<BeatportTrack: {} - {} ({})>".format(artist_str, self.name,
                                                       self.mix_name)

    def __init__(self, data):
        BeatportObject.__init__(self, data)
        if 'title' in data:
            self.title = unicode(data['title'])
        if 'mixName' in data:
            self.mix_name = data['mixName']
        if 'length' in data:<commit_msg>Bugfixes in Beatport plugin<commit_after># This file is part of beets.
# Copyright 2013, <NAME>.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.

"""Adds Beatport release and track search support to the autotagger
"""
import logging
import re
from datetime import datetime, timedelta

import requests

from beets import config
from beets.autotag.hooks import AlbumInfo, TrackInfo
from beets.plugins import BeetsPlugin

log = logging.getLogger('beets')


class BeatportAPIError(Exception):
    pass


class BeatportObject(object):
    def __init__(self, data):
        self.beatport_id = data['id']
        self.name = unicode(data['name'])
        if 'releaseDate' in data:
            self.release_date = datetime.strptime(data['releaseDate'],
                                                  '%Y-%m-%d')
        if 'artists' in data:
            self.artists = [(x['id'], unicode(x['name']))
                            for x in data['artists']]
        if 'genres' in data:
            self.genres = [unicode(x['name'])
                           for x in data['genres']]


class BeatportAPI(object):
    API_BASE = 'http://api.beatport.com/'

    @classmethod
    def get(cls, endpoint, **kwargs):
        try:
            response = requests.get(cls.API_BASE + endpoint, params=kwargs)
        except Exception as e:
            raise BeatportAPIError("Error connection to Beatport API: {}"
                                   .format(e.message))
        if not response:
            raise BeatportAPIError(
                "Error {0.status_code} for '{0.request.path_url}"
                .format(response))
        return response.json()['results']


class BeatportSearch(object):
    query = None
    release_type = None

    def __unicode__(self):
        return u"<BeatportSearch for {} \"{}\" with {} results>".format(
            self.release_type, self.query, len(self.results))

    def __init__(self, query, release_type='release', details=True):
        self.results = []
        self.query = query
        self.release_type = release_type
        response = BeatportAPI.get('catalog/3/search', query=query,
                                   facets=['fieldType:{}'
                                           .format(release_type)],
                                   perPage=5)
        for item in response:
            if release_type == 'release':
                release = BeatportRelease(item)
                if details:
                    release.get_tracks()
                self.results.append(release)
            elif release_type == 'track':
                self.results.append(BeatportTrack(item))


class BeatportRelease(BeatportObject):
    API_ENDPOINT = 'catalog/3/beatport/release'

    def __unicode__(self):
        if len(self.artists) < 4:
            artist_str = ", ".join(x[1] for x in self.artists)
        else:
            artist_str = "Various Artists"
        return u"<BeatportRelease: {} - {} ({})>".format(artist_str, self.name,
                                                         self.catalog_number)

    def __init__(self, data):
        BeatportObject.__init__(self, data)
        if 'catalogNumber' in data:
            self.catalog_number = data['catalogNumber']
        if 'label' in data:
            self.label_name = data['label']['name']
        if 'category' in data:
            self.category = data['category']
        if 'slug' in data:
            self.url = "http://beatport.com/release/{}/{}".format(
                data['slug'], data['id'])

    @classmethod
    def from_id(cls, beatport_id):
        response = BeatportAPI.get(cls.API_ENDPOINT, id=beatport_id)
        release = BeatportRelease(response['release'])
        release.tracks = [BeatportTrack(x) for x in response['tracks']]
        return release

    def get_tracks(self):
        response = BeatportAPI.get(self.API_ENDPOINT, id=self.beatport_id)
        self.tracks = [BeatportTrack(x) for x in response['tracks']]


class BeatportTrack(BeatportObject):
    API_ENDPOINT = 'catalog/3/beatport/track'

    def __unicode__(self):
        artist_str = ", ".join(x[1] for x in self.artists)
        return u"<BeatportTrack: {} - {} ({})>".format(artist_str, self.name,
                                                       self.mix_name)

    def __init__(self, data):
        BeatportObject.__init__(self, data)
        if 'title' in data:
            self.title = unicode(data['title'])
        if 'mixName' in data:
            self.mix_name = data['mixName']
        if 'length' in data:
{'fraction_non_alphanumeric': 0.1085465958474167, 'fraction_numerical': 0.002510864316755191, 'mean_word_length': 2.137231142078158, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 22, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2809405', 'n_tokens_mistral': 2887, 'n_tokens_neox': 2777, 'n_words': 782}