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

141
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:
config = json.load(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)
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
# print "Using default config file: %s" % (config_file)
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)
if len(sys.argv) == 4: elif 1 == len(args.fingerprint):
filepath = args.fingerprint[0]
djv.fingerprint_file(filepath)
directory = sys.argv[2] elif args.recognize:
extension = sys.argv[3] # Recognize audio source
print "Fingerprinting all .%s files in the %s directory" % (extension, directory) song = None
source = args.recognize[0]
opt_arg = args.recognize[1]
djv.fingerprint_directory(directory, ["." + extension], 4) if source in ('mic', 'microphone'):
song = djv.recognize(MicrophoneRecognizer, seconds=opt_arg)
else: elif source == 'file':
song = djv.recognize(FileRecognizer, opt_arg)
filepath = sys.argv[2] print(song)
djv.fingerprint_file(filepath)
elif command == 'recognize': # Recognize audio
source = sys.argv[2]
song = None
if source in ['mic', 'microphone']:
seconds = int(sys.argv[3])
djv = init()
song = djv.recognize(MicrophoneRecognizer, seconds=seconds)
elif source == 'file':
djv = init()
sourceFile = sys.argv[3]
song = djv.recognize(FileRecognizer, sourceFile)
else:
showHelp()
print song
else:
showHelp()
sys.exit(0)

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

@ -8,28 +8,28 @@ import shutil
usage = "usage: %prog [options] TESTING_AUDIOFOLDER" usage = "usage: %prog [options] TESTING_AUDIOFOLDER"
parser = OptionParser(usage=usage, version="%prog 1.1") parser = OptionParser(usage=usage, version="%prog 1.1")
parser.add_option("--secs", parser.add_option("--secs",
action="store", action="store",
dest="secs", dest="secs",
default=5, default=5,
type=int, type=int,
help='Number of seconds starting from zero to test') help='Number of seconds starting from zero to test')
parser.add_option("--results", parser.add_option("--results",
action="store", action="store",
dest="results_folder", dest="results_folder",
default="./dejavu_test_results", default="./dejavu_test_results",
help='Sets the path where the results are saved') help='Sets the path where the results are saved')
parser.add_option("--temp", parser.add_option("--temp",
action="store", action="store",
dest="temp_folder", dest="temp_folder",
default="./dejavu_temp_testing_files", default="./dejavu_temp_testing_files",
help='Sets the path where the temp files are saved') help='Sets the path where the temp files are saved')
parser.add_option("--log", parser.add_option("--log",
action="store_true", action="store_true",
dest="log", dest="log",
default=True, default=True,
help='Enables logging') help='Enables logging')
parser.add_option("--silent", parser.add_option("--silent",
action="store_false", action="store_false",
dest="silent", dest="silent",
default=False, default=False,
help='Disables printing') help='Disables printing')
@ -38,13 +38,13 @@ parser.add_option("--log-file",
default="results-compare.log", default="results-compare.log",
help='Set the path and filename of the log file') help='Set the path and filename of the log file')
parser.add_option("--padding", parser.add_option("--padding",
action="store", action="store",
dest="padding", dest="padding",
default=10, default=10,
type=int, type=int,
help='Number of seconds to pad choice of place to test from') help='Number of seconds to pad choice of place to test from')
parser.add_option("--seed", parser.add_option("--seed",
action="store", action="store",
dest="seed", dest="seed",
default=None, default=None,
type=int, type=int,
@ -62,27 +62,27 @@ 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
test_seconds = ['%dsec' % i for i in range(1, options.secs + 1, 1)] test_seconds = ['%dsec' % i for i in range(1, options.secs + 1, 1)]
# generate testing files # generate testing files
for i in range(1, options.secs + 1, 1): for i in range(1, options.secs + 1, 1):
generate_test_files(test_folder, options.temp_folder, generate_test_files(test_folder, options.temp_folder,
i, padding=options.padding) i, padding=options.padding)
# scan files # scan files
log_msg("Running Dejavu fingerprinter on files in %s..." % test_folder, log_msg("Running Dejavu fingerprinter on files in %s..." % test_folder,
log=options.log, silent=options.silent) log=options.log, silent=options.silent)
tm = time.time() tm = time.time()
djv = DejavuTest(options.temp_folder, test_seconds) djv = DejavuTest(options.temp_folder, test_seconds)
log_msg("finished obtaining results from dejavu in %s" % (time.time() - tm), log_msg("finished obtaining results from dejavu in %s" % (time.time() - tm),
log=options.log, silent=options.silent) log=options.log, silent=options.silent)
tests = 1 # djv tests = 1 # djv
n_secs = len(test_seconds) n_secs = len(test_seconds)
# set result variables -> 4d variables # set result variables -> 4d variables

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