#!/usr/bin/env python3
import json
import sys


def main():
    if len(sys.argv) != 2:
        print(json.dumps({"error": "Expected one audio file path."}))
        return 2

    try:
        import essentia.standard as es

        audio = es.MonoLoader(filename=sys.argv[1], sampleRate=44100)()
        key, scale, strength = es.KeyExtractor(profileType="bgate")(audio)
        bpm, _, _, _, _ = es.RhythmExtractor2013(method="multifeature")(audio)
        print(json.dumps({
            "key": key,
            "scale": scale,
            "keyConfidence": float(strength),
            "bpm": float(bpm),
        }))
        return 0
    except Exception as error:
        print(json.dumps({"error": str(error)}))
        return 1


if __name__ == "__main__":
    raise SystemExit(main())
