<commit_before>#!/usr/bin/env python

"""Plays a pseudo-random sequence of songs.

Author: <NAME>
Name: random_music.py
License: BSD License

"""

from __future__ import with_statement
import os
import sys
import glob
from stat import ST_MTIME
from socket import gethostname
from random import randint
import subprocess
import datetime
import time
from ConfigParser import (ConfigParser, NoOptionError, NoSectionError,
                         MissingSectionHeaderError, RawConfigParser)
from optparse import OptionParser

__author__ = "<NAME>"
__copyright__ = "Copyright (c) 2011 <NAME>."
__version__ = "2.1.3"
__license__ = "BSD License"


class _Error(Exception):
    pass

class DirectoryNotFoundError(_Error):
    """The specified directory could not be found."""
    def __init__(self, dirname):
        self.dirname = dirname
        self.value = "The '%s' directory could not be found" % dirname
        Exception.__init__()
    def __str__(self):
        return repr(self.value)

class MissingConfigFileError(_Error):
    """Config file could not be found."""
    def __init__(self, config_file):
        self.config_file = config_file
        self.value = "The config file '%s' could not be found" % config_file
    def __str__(self):
        return repr(self.value)


def main():
    """Generate a playlist and start playing the songs."""
    try:
        rmp = RandomMusicPlaylist()
        rmp.play_music()
    except MissingConfigFileError:
        create_config_file(RandomMusicPlaylist._get_config_file(), 
                           RandomMusicPlaylist._get_home_dir())
        rmp = RandomMusicPlaylist()
        rmp.play_music()

def which(name):
    """
    Equivalent of unix which command - return full path to a binary if it
    exists.
    """
    for path in os.environ["PATH"].split(os.pathsep):
        potential_path = os.path.join(path, name)
        if os.path.exists(potential_path):
            break
        else:
            potential_path = None
    return potential_path

def create_config_file(config_file, random_music_home):
    """Create a configuration file."""
    print "You do not appear to have a config file, lets create one!"
    config = RawConfigParser()
    config.add_section('config')
    config.set('config', 'loop_songs', 'true')
    config.set('config', 'randomise', 'true')
    config.set('config', 'index_dir', os.path.join(random_music_home, 
                                                   "indicies"))
    music_client = "mplayer"
    while not which(music_client):
        music_client = raw_input("The music player '%s' could not be found "
                                   "on your path. Please input a different "
                                   "music player:" % music_client)   
    
    config.set('config', 'music_client', music_client) 

    user_music_dirs = ""
    while not all([os.path.isdir(d) for d in user_music_dirs.split(",")]):
        user_music_dirs = raw_input("Input a csv list of full paths to "
                                   "your music dirs:")
    config.set('config', 'music_dirs', user_music_dirs)
            
    with open(config_file, 'wb') as fh:
        config.write(fh)

  
def check_is_dir(path):
    """Check if a directory exists."""
    if not os.path.isdir(path):
        raise DirectoryNotFoundError(path)

PATHNAME, SCRIPTNAME = os.path.split(sys.argv[0])
PATHNAME = os.path.abspath(PATHNAME)        

class RandomMusicPlaylist:
    """Generate and play random music playlists."""
    def __init__(self):
        self.load_config()
        self.process_flags()
        self.index_file = self.get_index_file()
        self.generate_list()

    @staticmethod
    def _get_home_dir():
        return os.path.join(os.path.expanduser("~"), ".random_music")

    @staticmethod    
    def _get_config_file():
        return os.path.join(os.path.expanduser("~"), ".random_music", "config.txt")


    def load_config(self):
        """Load configuration variables."""
        self.random_music_home = self._get_home_dir()
        if not os.path.isdir(self.random_music_home):
            os.makedirs(self.random_music_home)
            
        self.config_file = self._get_config_file()
        if not os.path.exists(self.config_file):
            raise MissingConfigFileError(self.config_file)
            
        config = ConfigParser()
        config.read(self.config_file)
        try:
            self.loop_songs = config.getboolean("config", "loop_songs")
            self.randomise = config.getboolean("config", "randomise")
            self.index_dir = config.get("config", "index_dir")
            self.music_client = config.get("config", "music_client")
            # music_dirs may be separated by commas. Unfortunately the
            # create_config_file() does not take account of this at the
            # moment. TODO: implement this
            self.music_dirs = config.get("config", "music_dirs").split(",") 
        except NoOptionError:
            print "No such option in config file"
            sys.exit(1)
        except NoSectionError:
            print "No such section in config file"
            sys.exit(1)
        except MissingSectionHeaderError:
            print "Failed to parse config file"
            sys.exit(1)<commit_msg>Allowing config_file to be specified as an arg for RandomMusicPlaylist()<commit_after>#!/usr/bin/env python

"""Plays a pseudo-random sequence of songs.

Author: <NAME>
Name: random_music.py
License: BSD License

"""

from __future__ import with_statement
import os
import sys
import glob
from stat import ST_MTIME
from socket import gethostname
from random import randint
import subprocess
import datetime
import time
from ConfigParser import (ConfigParser, NoOptionError, NoSectionError,
                         MissingSectionHeaderError, RawConfigParser)
from optparse import OptionParser

__author__ = "<NAME>"
__copyright__ = "Copyright (c) 2011 <NAME>."
__version__ = "2.1.4"
__license__ = "BSD License"


class _Error(Exception):
    pass

class DirectoryNotFoundError(_Error):
    """The specified directory could not be found."""
    def __init__(self, dirname):
        self.dirname = dirname
        self.value = "The '%s' directory could not be found" % dirname
        Exception.__init__()
    def __str__(self):
        return repr(self.value)

class MissingConfigFileError(_Error):
    """Config file could not be found."""
    def __init__(self, config_file):
        self.config_file = config_file
        self.value = "The config file '%s' could not be found" % config_file
    def __str__(self):
        return repr(self.value)


def main():
    """Generate a playlist and start playing the songs."""
    try:
        rmp = RandomMusicPlaylist()
        rmp.play_music()
    except MissingConfigFileError:
        create_config_file(RandomMusicPlaylist._get_config_file(), 
                           RandomMusicPlaylist._get_home_dir())
        rmp = RandomMusicPlaylist()
        rmp.play_music()

def which(name):
    """
    Equivalent of unix which command - return full path to a binary if it
    exists.
    """
    for path in os.environ["PATH"].split(os.pathsep):
        potential_path = os.path.join(path, name)
        if os.path.exists(potential_path):
            break
        else:
            potential_path = None
    return potential_path

def create_config_file(config_file, random_music_home):
    """Create a configuration file."""
    print "You do not appear to have a config file, lets create one!"
    config = RawConfigParser()
    config.add_section('config')
    config.set('config', 'loop_songs', 'true')
    config.set('config', 'randomise', 'true')
    config.set('config', 'index_dir', os.path.join(random_music_home, 
                                                   "indicies"))
    music_client = "mplayer"
    while not which(music_client):
        music_client = raw_input("The music player '%s' could not be found "
                                   "on your path. Please input a different "
                                   "music player:" % music_client)   
    
    config.set('config', 'music_client', music_client) 

    user_music_dirs = ""
    while not all([os.path.isdir(d) for d in user_music_dirs.split(",")]):
        user_music_dirs = raw_input("Input a csv list of full paths to "
                                   "your music dirs:")
    config.set('config', 'music_dirs', user_music_dirs)
            
    with open(config_file, 'wb') as fh:
        config.write(fh)

  
def check_is_dir(path):
    """Check if a directory exists."""
    if not os.path.isdir(path):
        raise DirectoryNotFoundError(path)

PATHNAME, SCRIPTNAME = os.path.split(sys.argv[0])
PATHNAME = os.path.abspath(PATHNAME)        

class RandomMusicPlaylist:
    """Generate and play random music playlists."""
    def __init__(self, config_file=None):
        self.random_music_home = self._get_home_dir()
        if not os.path.isdir(self.random_music_home):
            os.makedirs(self.random_music_home)
            
        if config_file and os.path.exists(config_file):
            self.config_file = config_file
        else:
            self.config_file = self._get_config_file()
        self.load_config()
        self.process_flags()
        self.index_file = self.get_index_file()
        self.generate_list()

    @staticmethod
    def _get_home_dir():
        return os.path.join(os.path.expanduser("~"), ".random_music")

    @staticmethod    
    def _get_config_file():
        return os.path.join(os.path.expanduser("~"), ".random_music", "config.txt")


    def load_config(self):
        """Load configuration variables."""
        if not os.path.exists(self.config_file):
            raise MissingConfigFileError(self.config_file)
            
        config = ConfigParser()
        config.read(self.config_file)
        try:
            self.loop_songs = config.getboolean("config", "loop_songs")
            self.randomise = config.getboolean("config", "randomise")
            self.index_dir = config.get("config", "index_dir")
            self.music_client = config.get("config", "music_client")
            # music_dirs may be separated by commas. Unfortunately the
            # create_config_file() does not take account of this at the
            # moment. TODO: implement this
            self.music_dirs = config.get("config", "music_dirs").split(",") 
        except NoOptionError:
            print "No such option in config file"
            sys.exit(1)
        except NoSectionError:
            print "No such section in config file"
            sys.exit(1)
        except MissingSectionHeaderError:
            print "Failed to parse config file"
            sys.exit(1)
{'fraction_non_alphanumeric': 0.10247810694987888, 'fraction_numerical': 0.0020495621389975778, 'mean_word_length': 2.521981627296588, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 12, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1656676', 'n_tokens_mistral': 3135, 'n_tokens_neox': 3027, 'n_words': 812}