Arguments parser CLI, with all existing tests passed.

This commit is contained in:
Saleem Ansari 2014-11-28 05:20:29 +05:30
parent 406187bd1a
commit 2972dce6eb
5 changed files with 94 additions and 95 deletions

131
dejavu.py
View file

@ -3,96 +3,89 @@
import sys import sys
import json import json
import warnings import warnings
import argparse
from dejavu import Dejavu from dejavu import Dejavu
from dejavu.recognize import FileRecognizer from dejavu.recognize import FileRecognizer
from dejavu.recognize import MicrophoneRecognizer from dejavu.recognize import MicrophoneRecognizer
from dejavu.recognize import FileRecognizer from argparse import RawTextHelpFormatter
warnings.filterwarnings("ignore") warnings.filterwarnings("ignore")
def init(): DEFAULT_CONFIG_FILE = "dejavu.cnf"
# load config from a JSON file (or anything outputting a python dictionary)
with open("dejavu.cnf") as f:
def init(config_file):
""" Load config from a JSON file
or anything outputting a python dictionary
"""
try:
with open(config_file) as f:
config = json.load(f) config = json.load(f)
except IOError as err:
print("Cannot open configuration: %s. Exiting" % (str(err)))
sys.exit(1)
# create a Dejavu instance # create a Dejavu instance
return Dejavu(config) return Dejavu(config)
def showHelp():
print ""
print "------------------------------------------------"
print "DejaVu audio fingerprinting and recognition tool"
print "------------------------------------------------"
print ""
print "Usage: dejavu.py [command] [arguments]"
print ""
print "Available commands:"
print ""
print " Fingerprint a file"
print " dejavu.py fingerprint /path/to/file.extension"
print ""
print " Fingerprint all files in a directory"
print " dejavu.py fingerprint /path/to/directory extension"
print ""
print " Recognize what is playing through the microphone"
print " dejavu.py recognize mic number_of_seconds"
print ""
print " Recognize a file by listening to it"
print " dejavu.py recognize file /path/to/file"
print ""
print " Display this help screen"
print " dejavu.py help"
print ""
exit
if len(sys.argv) > 1: if __name__ == '__main__':
command = sys.argv[1] """ If running from terminal.
else: """
showHelp() parser = argparse.ArgumentParser(
description="Audio Fingerprinting library",
formatter_class=RawTextHelpFormatter)
parser.add_argument('-c', '--config', nargs='?',
help='Path to configuration file\n'
'Usages: \n'
'--config /path/to/congfile\n')
parser.add_argument('-f', '--fingerprint', nargs='*',
help='Fingerprint files in a directory\n'
'Usages: \n'
'--fingerprint /path/to/directory extension\n'
'--fingerprint /path/to/directory')
parser.add_argument('-r', '--recognize', nargs=2,
help='Recognize what is '
'playing through the microphone\n'
'Usage: \n'
'--recognize mic number_of_seconds \n'
'--recognize file path/to/file \n')
args = parser.parse_args()
if command == 'fingerprint': # Fingerprint all files in a directory if not args.fingerprint and not args.recognize:
print("No arguments")
sys.exit(0)
djv = init() config_file = args.config
if config_file is None:
config_file = DEFAULT_CONFIG_FILE
if len(sys.argv) == 4: # print "Using default config file: %s" % (config_file)
directory = sys.argv[2]
extension = sys.argv[3]
print "Fingerprinting all .%s files in the %s directory" % (extension, directory)
djv = init(config_file)
if args.fingerprint:
# Fingerprint all files in a directory
if 2 == len(args.fingerprint):
directory = args.fingerprint[0]
extension = args.fingerprint[1]
print("Fingerprinting all .%s files in the %s directory"
% (extension, directory))
djv.fingerprint_directory(directory, ["." + extension], 4) djv.fingerprint_directory(directory, ["." + extension], 4)
else: elif 1 == len(args.fingerprint):
filepath = args.fingerprint[0]
filepath = sys.argv[2]
djv.fingerprint_file(filepath) djv.fingerprint_file(filepath)
elif command == 'recognize': # Recognize audio elif args.recognize:
# Recognize audio source
source = sys.argv[2]
song = None song = None
source = args.recognize[0]
opt_arg = args.recognize[1]
if source in ['mic', 'microphone']: if source in ('mic', 'microphone'):
song = djv.recognize(MicrophoneRecognizer, seconds=opt_arg)
seconds = int(sys.argv[3])
djv = init()
song = djv.recognize(MicrophoneRecognizer, seconds=seconds)
elif source == 'file': elif source == 'file':
song = djv.recognize(FileRecognizer, opt_arg)
print(song)
djv = init() sys.exit(0)
sourceFile = sys.argv[3]
song = djv.recognize(FileRecognizer, sourceFile)
else:
showHelp()
print song
else:
showHelp()

View file

@ -207,10 +207,16 @@ class DejavuTest(object):
log_msg('file: %s' % f) log_msg('file: %s' % f)
# get column # get column
col = self.get_column_id(re.findall("[0-9]*sec",f)[0]) col = self.get_column_id(re.findall("[0-9]*sec", f)[0])
song = path_to_songname(f).split("_")[0] # format: XXXX_offset_length.mp3 # format: XXXX_offset_length.mp3
line = self.get_line_id (song) song = path_to_songname(f).split("_")[0]
result = subprocess.check_output(["python", "dejavu.py", 'recognize', 'file', self.test_folder + "/" + f]) line = self.get_line_id(song)
result = subprocess.check_output([
"python",
"dejavu.py",
'-r',
'file',
self.test_folder + "/" + f])
if result.strip() == "None": if result.strip() == "None":
log_msg('No match') log_msg('No match')

View file

@ -62,7 +62,7 @@ except:
os.mkdir(options.results_folder) os.mkdir(options.results_folder)
# set logging # set logging
if options.log == True: if options.log:
logging.basicConfig(filename=options.log_file, level=logging.DEBUG) logging.basicConfig(filename=options.log_file, level=logging.DEBUG)
# set test seconds # set test seconds

View file

@ -15,7 +15,7 @@ def parse_requirements(requirements):
return reqs return reqs
PACKAGE_NAME = "PyDejavu" PACKAGE_NAME = "PyDejavu"
PACKAGE_VERSION = "0.1" PACKAGE_VERSION = "0.1.1"
SUMMARY = 'Dejavu Audio Fingerprinting' SUMMARY = 'Dejavu Audio Fingerprinting'
DESCRIPTION = """Dejavu Audio Fingerprinting""" DESCRIPTION = """Dejavu Audio Fingerprinting"""
REQUIREMENTS = parse_requirements("requirements.txt") REQUIREMENTS = parse_requirements("requirements.txt")

View file

@ -8,7 +8,7 @@ rm -rf ./results ./temp_audio
########### ###########
# Fingerprint files of extension mp3 in the ./mp3 folder # Fingerprint files of extension mp3 in the ./mp3 folder
python dejavu.py fingerprint ./mp3/ mp3 python dejavu.py -f ./mp3/ mp3
########## ##########
# Run a test suite on the ./mp3 folder by extracting 1, 2, 3, 4, and 5 # Run a test suite on the ./mp3 folder by extracting 1, 2, 3, 4, and 5