Advertisement
Guest User

Full Circle Magazine - Python Part 9 - mp3

a guest
Mar 12th, 2010
1,767
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.10 KB | None | 0 0
  1. # MCat.py
  2.  
  3. # An MP3 audio file cataloging program
  4.  
  5. # Written by G.D. Walters
  6.  
  7. # For Full Circle Magazine
  8.  
  9.  
  10.  
  11. from mutagen.mp3 import MP3
  12.  
  13. import os
  14.  
  15. from os.path import join,getsize,exists
  16.  
  17. import sys
  18.  
  19. import apsw
  20.  
  21.  
  22.  
  23. def MakeDataBase():
  24.  
  25.     # IF the table does not exist, this will create the table.
  26.  
  27.     # Otherwise, this will be ignored due to the 'IF NOT EXISTS' clause
  28.  
  29.     sql = 'CREATE TABLE IF NOT EXISTS mp3 (pkID INTEGER PRIMARY KEY, title TEXT, artist TEXT, album TEXT, bitrate TEXT, '
  30.  
  31.     sql = sql + 'genre TEXT, playtime TEXT, track INTEGER, year TEXT, filesize TEXT, path TEXT, filename TEXT);'
  32.  
  33.     cursor.execute(sql)
  34.  
  35.  
  36.  
  37. def S2HMS(t):
  38.  
  39.     # Converts seconds to a string formatted H:mm:ss
  40.  
  41.     if t > 3600:
  42.  
  43.         h = int(t/3600)
  44.  
  45.         r = t-(h*3600)
  46.  
  47.         m = int(r / 60)
  48.  
  49.         s = int(r-(m*60))
  50.  
  51.         return '{0}:{1:02n}:{2:02n}'.format(h,m,s)
  52.  
  53.     else:
  54.  
  55.         m = int(t / 60)
  56.  
  57.         s = int(t-(m*60))
  58.  
  59.         return '{0}:{1:02n}'.format(m,s)
  60.  
  61.  
  62.  
  63. def WalkThePath(musicpath):
  64.  
  65.     ecntr = 0  # Error Counter
  66.  
  67.     rcntr = 0  # Folder Counter
  68.  
  69.     fcntr = 0  # File Counter
  70.  
  71.     # Open the error log file
  72.  
  73.     efile = open('errors.log',"w")
  74.  
  75.     for root, dirs, files in os.walk(musicpath):
  76.  
  77.         rcntr += 1  # This is the number of folders we have walked
  78.  
  79.         for file in [f for f in files if f.endswith(".mp3")]:
  80.  
  81.             fcntr += 1  # This is the number of mp3 files we found
  82.  
  83.             # Clear the holding variables each pass
  84.  
  85.             _title=''
  86.  
  87.             _artist=''
  88.  
  89.             _album=''
  90.  
  91.             _genre=''
  92.  
  93.             _year = ''
  94.  
  95.             _bitrate=''
  96.  
  97.             _length=''
  98.  
  99.             _fsize=''
  100.  
  101.             _track = 0
  102.  
  103.             # Combine path and filename to create a single variable.
  104.  
  105.             fn = join(root,file)  
  106.  
  107.             try:
  108.  
  109.                 audio = MP3(fn)
  110.  
  111.                 keys = audio.keys()
  112.  
  113.                 for key in keys:
  114.  
  115.                     if key == 'TDRC':           # Year
  116.  
  117.                         _year = audio.get(key)
  118.  
  119.                     elif key == 'TALB':         # Album
  120.  
  121.                         _album = audio.get(key)
  122.  
  123.                     elif key == 'TRCK':         # Track
  124.  
  125.                         try:
  126.  
  127.                             _trk = audio.get(key)
  128.  
  129.                             if _trk[0].find("/"):
  130.  
  131.                                 _trk1 = _trk[0]
  132.  
  133.                                 _track=_trk1[_trk1.find("/")+1]
  134.  
  135.                             elif len(trk[0]) == 0:
  136.  
  137.                                 _track = 0
  138.  
  139.                             else:
  140.  
  141.                                 _track = _trk[0]
  142.  
  143.                         except:
  144.  
  145.                             track = 0
  146.  
  147.                     elif key == "TPE1":         # Artist
  148.  
  149.                         _artist = audio.get(key)
  150.  
  151.                     elif key == "TIT2":         # Song Title
  152.  
  153.                         _title = audio.get(key)
  154.  
  155.                     elif key == "TCON":         # Genre
  156.  
  157.                         _genre = audio.get(key)
  158.  
  159.                 _bitrate = audio.info.bitrate   # Bitrate
  160.  
  161.                 _length = S2HMS(audio.info.length)    # Audio Length
  162.  
  163.                 _fsize = getsize(fn)            # File Size
  164.  
  165.                 # Now write the database
  166.  
  167.                 # This is a different way of doing it from last time.  Works much better.
  168.  
  169.                 sql = 'INSERT INTO mp3 (title,artist,album,genre,year,track,bitrate,playtime,filesize,path,filename) VALUES (?,?,?,?,?,?,?,?,?,?,?)'
  170.  
  171.                 cursor.execute(sql,(str(_title),str(_artist),str(_album),str(_genre),str(_year),int(_track),str(_bitrate),str(_length),str(_fsize),root,file))
  172.  
  173.             except ValueError:
  174.  
  175.                 ecntr += 1
  176.  
  177.                 efile.writelines('===========================================\n')
  178.  
  179.                 efile.writelines('VALUE ERROR - Filename: %s\n' % fn)
  180.  
  181.                 efile.writelines('Title: %s - Artist: %s - Album: %s\n' %(_title,_artist,_album))
  182.  
  183.                 efile.writelines('Genre: %s - Year: %s - Track: %s\n' % (_genre,_year,_track))
  184.  
  185.                 efile.writelines('bitrate: {0} - length: {1} \n'.format(_bitrate,_length))              
  186.  
  187.                 efile.writelines('===========================================\n')
  188.  
  189.             except TypeError:
  190.  
  191.                 ecntr += 1
  192.  
  193.                 efile.writelines('===========================================\n')
  194.  
  195.                 efile.writelines('TYPE ERROR - Filename: {0}\n'.format(fn))
  196.  
  197.                 efile.writelines('Title: {0} - Artist: {1} - Album: {2}\n'.format(_title,_artist,_album))
  198.  
  199.                 efile.writelines('Genre: {0} - Year: {1} - Track: {2}\n'.format(_genre,_year,_track))
  200.  
  201.                 efile.writelines('bitrate: {0} - length: {1} \n'.format(_bitrate,_length))
  202.  
  203.                 efile.writelines('===========================================\n')
  204.  
  205.             except:
  206.  
  207.                 ecntr += 1
  208.  
  209.                 efile.writelines('TYPE ERROR - Filename: {0}\n'.format(fn))
  210.  
  211.             print fcntr
  212.  
  213.         # Close the log file
  214.  
  215.         efile.close
  216.  
  217.     # Finish Up
  218.  
  219.     print ("\n")
  220.  
  221.     print ("Number of errors: {0}").format(ecntr)
  222.  
  223.     print ("Number of files processed: {0}").format(fcntr)
  224.  
  225.     print ("Number of folders processed: {0}").format(rcntr)
  226.  
  227.     # End of WalkThePath
  228.  
  229.  
  230.  
  231. def error(message):
  232.  
  233.     print >> sys.stderr, str(message)
  234.  
  235.  
  236.  
  237. def main():
  238.  
  239.     global connection
  240.  
  241.     global cursor
  242.  
  243.     #-----------------------------------------------------------------------------
  244.  
  245.     if len(sys.argv) != 2:
  246.  
  247.         usage()
  248.  
  249.     else:
  250.  
  251.         StartFolder = sys.argv[1]
  252.  
  253.         if not exists(StartFolder): # From os.path
  254.  
  255.             print('Path {0} does not seem to exist...Exiting app.').format(StartFolder)
  256.  
  257.             sys.exit(1)
  258.  
  259.         else:
  260.  
  261.             print('About to work {0} folder(s):').format(StartFolder)            
  262.  
  263.         # Create the connection and cursor.
  264.  
  265.         connection=apsw.Connection("mCat.db3")
  266.  
  267.         cursor=connection.cursor()
  268.  
  269.         # Make the database if it doesn't exist...
  270.  
  271.         MakeDataBase()
  272.  
  273.         # Do the actual work...
  274.  
  275.         WalkThePath(StartFolder)
  276.  
  277.         # Close the cursor and connection...
  278.  
  279.         cursor.close()
  280.  
  281.         connection.close()
  282.  
  283.         # Let us know we are finished...
  284.  
  285.         print("FINISHED!")
  286.  
  287.  
  288.  
  289. def usage():
  290.  
  291.     message = (
  292.  
  293.        '=======================================================================\n'
  294.  
  295.        'mCat - Finds all *.mp3 files in a given folder (and sub-folders),\n'
  296.  
  297.        '\tread the id3 tags, and write that information to a SQLite database.\n\n'
  298.  
  299.        'Usage:\n'
  300.  
  301.        '\t{0} <foldername>\n'
  302.  
  303.        '\t WHERE <foldername> is the path to your MP3 files.\n\n'
  304.  
  305.        'Author: Greg Walters\n'
  306.  
  307.        'For Full Circle Magazine\n'
  308.  
  309.        '=======================================================================\n'
  310.  
  311.        ).format(sys.argv[0])
  312.  
  313.     error(message)
  314.  
  315.     sys.exit(1)
  316.  
  317.  
  318.  
  319. if __name__ == '__main__':
  320.  
  321.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement