Example #1
0
def test_colorize():
    print(terminal.colorize('bold', 'bold'))
    print(terminal.colorize('red', 'red'))
    print(terminal.colorize('red', '#ff0000'))
    print(terminal.colorize('red', 'ff0000'))
    print(terminal.colorize('red', 'f00'))
    print(terminal.colorize('red', (255, 0, 0)))
    print(terminal.colorize('gray', (80, 80, 80)))
    print(terminal.colorize('red', 'f00', True))
Example #2
0
def namefix(albumdir, options):
    """
    Prettifies filenames, see doc in the namefix module.
    """
    from namefix import namefix
    from terminal import colorize
    filelist = getFilelist(albumdir)

    renamesign = "->"
    if options.dryrun:
        renamesign = "-dry->"

    for filepath in filelist:
        tofile = albumdir + namefix(filepath.getName())
        print filepath
        print "\t", colorize(renamesign), tofile
        if not options.dryrun:
            os.rename(str(filepath), str(tofile))

    todir = namefix(albumdir.getName())
    print "\n", albumdir.getName()
    print "\t", colorize(renamesign), todir
    if not options.dryrun:
        os.rename(str(albumdir), str(FilePath(albumdir.getParent(), todir)))
Example #3
0
def namefix(albumdir, options):
    """
    Prettifies filenames, see doc in the namefix module.
    """
    from namefix import namefix
    from terminal import colorize
    filelist = getFilelist(albumdir)
    
    renamesign = "->"
    if options.dryrun:
        renamesign = "-dry->" 
    
    for filepath in filelist:
        tofile = albumdir + namefix(filepath.getName())
        print filepath
        print "\t", colorize(renamesign), tofile
        if not options.dryrun:
            os.rename(str(filepath), str(tofile))

    todir = namefix(albumdir.getName())
    print "\n", albumdir.getName()
    print "\t", colorize(renamesign), todir
    if not options.dryrun:
        os.rename(str(albumdir), str(FilePath(albumdir.getParent(), todir)))
Example #4
0
 def update(self, message="", current=None):
     # Calculate position, make bar
     if current is None:
         self.current += 1
     else:
         self.current = current
     rat = self.current / self.max
     nchars = int(round(self.width * rat))
     bar = "%s%s" % (nchars*self.block, (self.width-nchars)*self.track)
     bar = terminal.colorize(bar, self.color)
     
     # Save current cursor position
     terminal.cursor.save(self.stream)
     terminal.cursor.place(1, self.line, self.stream)
     terminal.screen.clearline(part='all', stream=self.stream)
     print >>self.stream, " %d%% [ %s ] %s" % (int(100*rat), bar, message)
     terminal.cursor.unsave(self.stream)
Example #5
0
def print_success(message, stream=stderr):
    terminal.screen.clearline(stream=stream)
    print >>stream, terminal.colorize(message, 'white', 'green')
Example #6
0
def print_info(message, stream=stderr):
    terminal.screen.clearline(stream=stream)
    print >>stream, terminal.colorize(message, 'cyan')
Example #7
0
def print_good(message, stream=stderr):
    terminal.screen.clearline(stream=stream)
    print >>stream, terminal.colorize(message, 'green')
Example #8
0
def print_header(message, stream=stderr):
    terminal.screen.clearline(stream=stream)
    print >>stream, terminal.colorize(message, 'white', 'blue', effect='bold')
Example #9
0
def print_comment(message, stream=stderr):
    terminal.screen.clearline(stream=stream)
    print >>stream, terminal.colorize(message, 'yellow')
Example #10
0
def tagfiles(albumdir, album, options):
    '''Rename and tag files using freedb information for
       the specified album.'''

    # XXX: doesn't really belong here
    missing = album.validate()
    if len(missing) > 0:
        if options.strict:
            amiss = ",".join(missing)
            raise TagIncompleteWarning(amiss)
        else:
            for miss in missing:
                print TagIncompleteWarning(miss)
            print
    album.ignoreMissing(True)

    localalbum = LocalAlbumInfo(albumdir)
    filelist = localalbum.getfilelist(options.sysencoding)
    
    a = len(album.tracks)
    b = len(filelist)
    if a != b:
        raise NamingMuseError('there are %d files, but %d metainfo tracks' % (b,a))

    namebinder = get_namebinder(options, filelist)
    
    tracks = namebinder(filelist, album, options.sysencoding)
    if not sortedcmp(tracks, album.tracks):
        options.dryrun = True
        print NamingMuseError("binding was not exact, forcing dry run")

    print "Tagging album: %s, %s - %s, %s.\n" % \
          (album.year, album.artist, album.title, album.genre)

    # Process files
    renamealbum = True

    renameTempDir = FilePath(albumdir, 'rename-tmp')

    if renameTempDir.exists():
        raise NamingMuseError('%s exists!' % renameTempDir)

    renameTempDir.mkdir()

    # a list of tuples (from, to)
    # we use temporary renames to avoid filename collision on filename swaps
    # this holds the list of final renames to be executed
    finalrenames = []

    # a list of tuples (from, to)
    # used to rollback renames in case of error
    rollback = []

    renamesign = "->"
    rollbacksign = '<-'
    if options.tagonly:
        renamesign = "-tag->"
    if options.dryrun:
        renamesign = "-dry->" 

    try:
        for i in range(0, len(filelist)):
            fpath = filelist[i]
            # XXX: move bug check to freedbalbuminfo parser

            #if album.isVarious:
            #    if not "/" in title and "-" in title:
            #        # workaround: this is a bug in the freedb entry
            #        # (according to submission guidelines)
            #        trackartist, title = title.split("-")
            #        print NamingMuseWarning("bugged database entry with - instead of /")
            #    else:
            #        trackartist, title = title.split("/")
            #    trackartist, title = trackartist.strip(), title.strip()
            #else:
            #    trackartist = albumartist
            track = tracks[i]

            tofile = policy.genfilename(filelist[i], album, track)
            tofile = tofile.encode(options.sysencoding)
            totmpfile = FilePath(renameTempDir, tofile, encoding=options.sysencoding)
            tofinalfile = FilePath(albumdir, tofile, encoding=options.sysencoding)
        
            # Tag and rename file
            print fpath.getName()
            print "\t", colorize(renamesign), tofinalfile.getName()

            if not options.dryrun:

                # Tag file

                #preserve stat
                fd = tempfile.NamedTemporaryFile()
                tmpfilename = fd.name
                shutil.copystat(str(fpath), tmpfilename)
                
                # tag the file
                tagfile(fpath, album, track, options)

                # restore filestat
                shutil.copystat(tmpfilename, str(fpath))

                # deletes tempfile
                fd.close()

                # Rename file to temporary name
                
                if not options.tagonly:
                    if totmpfile.exists():
                        raise NamingMuseError('tried to rename file over existing: %s' % str(totmpfile))
                    if fpath != totmpfile:
                        fpath.rename(totmpfile)
                        rollback.append((fpath, totmpfile))
                        finalrenames.append((totmpfile, tofinalfile))

    except Exception, e:
        print
        print colorize('Error: an error occurred. rolling back %d renames.' % len(rollback))
        for frompath, topath in reversed(rollback):
            print frompath.getName()
            print "\t", colorize(rollbacksign), topath.getName()
            topath.rename(frompath)
        renameTempDir.rmdir()
        raise
Example #11
0
def raw_input(prompt, stream=stderr, color='reset', bg='reset'):
    # override default raw_input, prompt goes to stderr
    stream.flush()
    terminal.screen.clearline('all', stream=stream)
    stream.write('\r%s'%terminal.colorize(prompt, color, bg))
    return stdin.readline().strip()
Example #12
0
def tagfiles(albumdir, album, options):
    '''Rename and tag files using freedb information for
       the specified album.'''

    # XXX: doesn't really belong here
    missing = album.validate()
    if len(missing) > 0:
        if options.strict:
            amiss = ",".join(missing)
            raise TagIncompleteWarning(amiss)
        else:
            for miss in missing:
                print TagIncompleteWarning(miss)
            print
    album.ignoreMissing(True)

    localalbum = LocalAlbumInfo(albumdir)
    filelist = localalbum.getfilelist(options.sysencoding)

    a = len(album.tracks)
    b = len(filelist)
    if a != b:
        raise NamingMuseError('there are %d files, but %d metainfo tracks' %
                              (b, a))

    namebinder = get_namebinder(options, filelist)

    tracks = namebinder(filelist, album, options.sysencoding)
    if not sortedcmp(tracks, album.tracks):
        options.dryrun = True
        print NamingMuseError("binding was not exact, forcing dry run")

    print "Tagging album: %s, %s - %s, %s.\n" % \
          (album.year, album.artist, album.title, album.genre)

    # Process files
    renamealbum = True

    renameTempDir = FilePath(albumdir, 'rename-tmp')

    if renameTempDir.exists():
        raise NamingMuseError('%s exists!' % renameTempDir)

    renameTempDir.mkdir()

    # a list of tuples (from, to)
    # we use temporary renames to avoid filename collision on filename swaps
    # this holds the list of final renames to be executed
    finalrenames = []

    # a list of tuples (from, to)
    # used to rollback renames in case of error
    rollback = []

    renamesign = "->"
    rollbacksign = '<-'
    if options.tagonly:
        renamesign = "-tag->"
    if options.dryrun:
        renamesign = "-dry->"

    try:
        for i in range(0, len(filelist)):
            fpath = filelist[i]
            # XXX: move bug check to freedbalbuminfo parser

            #if album.isVarious:
            #    if not "/" in title and "-" in title:
            #        # workaround: this is a bug in the freedb entry
            #        # (according to submission guidelines)
            #        trackartist, title = title.split("-")
            #        print NamingMuseWarning("bugged database entry with - instead of /")
            #    else:
            #        trackartist, title = title.split("/")
            #    trackartist, title = trackartist.strip(), title.strip()
            #else:
            #    trackartist = albumartist
            track = tracks[i]

            tofile = policy.genfilename(filelist[i], album, track)
            tofile = tofile.encode(options.sysencoding)
            totmpfile = FilePath(renameTempDir,
                                 tofile,
                                 encoding=options.sysencoding)
            tofinalfile = FilePath(albumdir,
                                   tofile,
                                   encoding=options.sysencoding)

            # Tag and rename file
            print fpath.getName()
            print "\t", colorize(renamesign), tofinalfile.getName()

            if not options.dryrun:

                # Tag file

                #preserve stat
                fd = tempfile.NamedTemporaryFile()
                tmpfilename = fd.name
                shutil.copystat(str(fpath), tmpfilename)

                # tag the file
                tagfile(fpath, album, track, options)

                # restore filestat
                shutil.copystat(tmpfilename, str(fpath))

                # deletes tempfile
                fd.close()

                # Rename file to temporary name

                if not options.tagonly:
                    if totmpfile.exists():
                        raise NamingMuseError(
                            'tried to rename file over existing: %s' %
                            str(totmpfile))
                    if fpath != totmpfile:
                        fpath.rename(totmpfile)
                        rollback.append((fpath, totmpfile))
                        finalrenames.append((totmpfile, tofinalfile))

    except Exception, e:
        print
        print colorize('Error: an error occurred. rolling back %d renames.' %
                       len(rollback))
        for frompath, topath in reversed(rollback):
            print frompath.getName()
            print "\t", colorize(rollbacksign), topath.getName()
            topath.rename(frompath)
        renameTempDir.rmdir()
        raise
Example #13
0
    renamesign = "->"
    if options.dryrun or options.tagonly:
        renamesign = "-dry->"
    if not (options.dryrun or options.tagonly) and renamealbum \
        and str(albumdir) != str(newalbumdir):
        if newalbumdir.exists():
            raise NamingMuseWarning("Directory already exists (dup album?): " +
                                    str(newalbumdir))
        try:
            albumdir.rename(newalbumdir)
        except OSError, err:
            raise NamingMuseWarning(str(err))

    # Print rename message
    print "\n", albumdir.getName()
    print "\t", colorize(renamesign),
    if needartistdirmove:
        print FilePath(album.artist.encode(options.sysencoding),
                       newalbumdir.getName())
    else:
        print newalbumdir.getName()


def tagfile(fpath, album, track, options):
    """ Tag the file with metadata """

    if not hasattr(tagpy.FileRef, 'create'):
        print 'warning: using generic tagging. upgrade to tagpy 0.94.5 or later.'
        fileref = tagpy.FileRef(str(fpath))
        tag = fileref.tag()
        tag.year = album.year
Example #14
0
from datetime import datetime
from collections import defaultdict
import logging
import hashlib
import json
from string import Template

import numpy as np
import scipy as sp

from builtins import input
basestring = (str, bytes)

try:
    from terminal import colorize
    colored = lambda *x: str(colorize(x[0], x[1]))
except ImportError:
    lgg = logging.getLogger('root')
    lgg.debug("needs `terminal' module for colors printing")
    colored = lambda *x: x[0]


class PmkTemplate(Template):
    delimiter = '$$'
    #idpattern = r'[a-z][_a-z0-9]*'


#from itertools import cycle
class Cycle(object):
    def __init__(self, seq):
        self.seq = seq
Example #15
0
def test_raise_colorize():
    print(terminal.colorize('text', {'foo': 'bar'}))
Example #16
0
def print_error(message, stream=stderr):
    terminal.screen.clearline(stream=stream)
    print >>stream, terminal.colorize(message, 'red', 'white')
Example #17
0
    renamesign = "->"
    if options.dryrun or options.tagonly:
        renamesign = "-dry->"
    if not (options.dryrun or options.tagonly) and renamealbum \
        and str(albumdir) != str(newalbumdir):
        if newalbumdir.exists():
            raise NamingMuseWarning("Directory already exists (dup album?): " +
                  str(newalbumdir))
        try:
            albumdir.rename(newalbumdir)
        except OSError, err:
            raise NamingMuseWarning(str(err))

    # Print rename message
    print "\n", albumdir.getName()
    print "\t", colorize(renamesign),
    if needartistdirmove:
        print FilePath(album.artist.encode(options.sysencoding), newalbumdir.getName())
    else:
        print newalbumdir.getName()

def tagfile(fpath, album, track, options):
    """ Tag the file with metadata """

    if not hasattr(tagpy.FileRef, 'create'):
        print 'warning: using generic tagging. upgrade to tagpy 0.94.5 or later.'
        fileref = tagpy.FileRef(str(fpath))
        tag = fileref.tag()
        tag.year = album.year
        tag.genre = album.genre
        tag.artist = track.artist
Example #18
0
def print_warning(message, stream=stderr):
    terminal.screen.clearline(stream=stream)
    print >>stream, terminal.colorize(message, 'red')
 def __str__(self):
     return colorize(self.value)
Example #20
0
 def __str__(self):
     return colorize(self.value)