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 json
import warnings
import argparse
from dejavu import Dejavu
from dejavu.recognize import FileRecognizer
from dejavu.recognize import MicrophoneRecognizer
from dejavu.recognize import FileRecognizer
from argparse import RawTextHelpFormatter
warnings.filterwarnings("ignore")
def init():
# load config from a JSON file (or anything outputting a python dictionary)
with open("dejavu.cnf") as f:
DEFAULT_CONFIG_FILE = "dejavu.cnf"
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
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:
command = sys.argv[1]
else:
showHelp()
if __name__ == '__main__':
""" If running from terminal.
"""
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()
if len(sys.argv) == 4:
directory = sys.argv[2]
extension = sys.argv[3]
print "Fingerprinting all .%s files in the %s directory" % (extension, directory)
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)
else:
filepath = sys.argv[2]
elif 1 == len(args.fingerprint):
filepath = args.fingerprint[0]
djv.fingerprint_file(filepath)
elif command == 'recognize': # Recognize audio
source = sys.argv[2]
elif args.recognize:
# Recognize audio source
song = None
source = args.recognize[0]
opt_arg = args.recognize[1]
if source in ['mic', 'microphone']:
seconds = int(sys.argv[3])
djv = init()
song = djv.recognize(MicrophoneRecognizer, seconds=seconds)
if source in ('mic', 'microphone'):
song = djv.recognize(MicrophoneRecognizer, seconds=opt_arg)
elif source == 'file':
song = djv.recognize(FileRecognizer, opt_arg)
print(song)
djv = init()
sourceFile = sys.argv[3]
song = djv.recognize(FileRecognizer, sourceFile)
else:
showHelp()
print song
else:
showHelp()
sys.exit(0)

View file

@ -208,9 +208,15 @@ class DejavuTest(object):
# get column
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
song = path_to_songname(f).split("_")[0]
line = self.get_line_id(song)
result = subprocess.check_output(["python", "dejavu.py", 'recognize', 'file', self.test_folder + "/" + f])
result = subprocess.check_output([
"python",
"dejavu.py",
'-r',
'file',
self.test_folder + "/" + f])
if result.strip() == "None":
log_msg('No match')

View file

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

View file

@ -15,7 +15,7 @@ def parse_requirements(requirements):
return reqs
PACKAGE_NAME = "PyDejavu"
PACKAGE_VERSION = "0.1"
PACKAGE_VERSION = "0.1.1"
SUMMARY = 'Dejavu Audio Fingerprinting'
DESCRIPTION = """Dejavu Audio Fingerprinting"""
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
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