Demo entry 3548913

foo

   

Submitted by anonymous on Jan 20, 2016 at 07:17
Language: Python. Code size: 4.7 kB.

#!/usr/bin/env python
# -*- coding: latin-1 -*-   

import os
import sys
import re
from math import log
import sqlite3 as lite
import eyeD3
import getopt

from sets import Set


def hsize_of_file(num):
    """Human friendly file size -  thanks to joctee at SO"""

    unit_list = zip([ 'bytes', 'kB', 'MB', 'GB', 'TB', 'PB', ], [ 0, 0, 1, 2, 2, 2, ])
    if num > 1:
        exponent = min(int(log(num, 1024)), len(unit_list) - 1)
        quotient = float(num) / 1024 ** exponent
        (unit, num_decimals) = unit_list[exponent]
        format_string = '{:.%sf} {}' % num_decimals
        return format_string.format(quotient, unit)
    if num == 0:
        return '0 bytes'
    if num == 1:
        return '1 byte'


def get_track_info(f, path):
    size = os.stat(path).st_size
    fsize = hsize_of_file(size)
    tag = eyeD3.Tag()
    tag.link(path)

    artist = tag.getArtist()
    artist = re.sub(r'The\s+', '', artist.encode('utf-8'))
    album = tag.getAlbum()
    album.encode('utf-8')
    title = tag.getTitle()
    title.encode('utf-8')
    genre = tag.getGenre()
    genre = re.sub(r'\(.*\)', '', str(genre))

    # print "file: %s\tsize: %s\n\tArtist: %s\n\tAlbum: %s\n\tTitle: %s\n\tGenre: %s\n" %\
            # (mp3, fsize, tag.getArtist(), tag.getAlbum(), tag.getTitle(), genre)

    return((
        f,
        path,
        size,
        fsize,
        artist,
        album,
        title,
        genre,
        ))




def load_track_info(topdir):
    tracks = []
    for (root, dirs, files) in os.walk(topdir, topdown=True):
        exclude = Set(["irc_mp3",])
        dirs[:] = [d for d in dirs if d not in exclude]
        for f in files:
            if f.endswith('.mp3'):
        #        print "file: %s\n" % f
                tracks.append(get_track_info(f, os.path.join(root, f)))
    return tracks


def create_db(db, topdir = '/mnt/TB1-1/music_stor'):
    con = lite.connect(db)
    con.text_factory =  lambda x: unicode(x, "utf-8", "ignore") # why - not sure this is working!
    with con:
        cur = con.cursor()
        cur.execute('DROP TABLE IF EXISTS Tracks')
        cur.execute('CREATE TABLE Tracks(File TEXT, Path TEXT, Size INT, FSize INT, Artist TEXT, Album TEXT, Title TEXT, Genre TEXT)')

        for track in load_track_info(topdir):
            cur.execute('INSERT INTO Tracks VALUES(?, ?, ?, ?, ?, ?, ?, ?)', track)


def artist_prompt(db):
    artist_dict = {}
    con = lite.connect(db)
    with con:
        cur = con.cursor()
        cur.execute('SELECT Artist FROM Tracks')
        rows = cur.fetchall()

        for r in rows:
            artist_dict[r[0]] = ''

    artist_list = []
    for k in sorted(artist_dict):
        artist_list.append(k)

    for (offset, artist) in enumerate(artist_list):
        print(offset, "...", artist)

    while True:
        try:
            choice = int(raw_input("choose artist by index number: "))
        except ValueError, e:
            print "oops: ", e
            continue

        if choice < 1 or choice > len(artist_list):
            print "try again"
            continue
        else:
            break

    return artist_list[choice]

def album_prompt(db, artist):
    con = lite.connect(db)
    with con:
        cur = con.cursor()
        comstr = "SELECT Album FROM Tracks WHERE Artist GLOB '*%s*'" % artist
        print comstr
        cur.execute(comstr)
        rows = cur.fetchall()

    for r in rows:
        print r





def main():

    '''
    Goals: 
            -c -> create new database
            -d -> optional database file name
            -p -> optional path for database creation
    have program prompt for Artist choice to simulate  choice 
    from gui drop-down list
    Test paths:
    '''
    tp1 = '/mnt/TB1-1/music_stor/CD_RIPS_mine/pazzandjop/Grateful Dead-Reckoning/'
    tp2 = u'/mnt/TB1-1/music_stor/CD_RIPS_mine/classical/Ludwig_Van_Beethoven-The_Five_Cello_Sonatas_(du_Pré,Barenboim)_(Disc_1_of_2)'

    import argparse

    parser = argparse.ArgumentParser(description='testing, testing...')
    parser.add_argument('-c', action='store_true',
            dest='boolean_create_db',
            default=False,
            help='create new database')
    parser.add_argument('-d', action='store',
            dest='db_file',
            help='specify database file to use' )
    parser.add_argument('-p', action='store',
            dest='path',
            help='specify path to music library')

    args = parser.parse_args()
    vdb = args.db_file
    path = args.path

    if args.boolean_create_db:
        create_db(vdb, path)

    artist_choice = artist_prompt(vdb) 
    album_prompt(vdb, artist_choice)

if __name__ == "__main__":

    main()

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).