chord_classifier / inference.py
kshahnathwani's picture
Update inference.py
9328223 verified
import joblib
import numpy as np
import re
import os
NAME_TO_PC = {
"C":0,"C#":1,"Db":1,"D":2,"D#":3,"Eb":3,"E":4,"F":5,"F#":6,"Gb":6,
"G":7,"G#":8,"Ab":8,"A":9,"A#":10,"Bb":10,"B":11
}
NOTE_TOKEN_RE = re.compile(r"[A-Ga-g](?:#|b)?")
MODEL_PATH = os.path.join(os.path.dirname(__file__), "chord_classifier.pkl")
clf = joblib.load(MODEL_PATH)
def notes_to_vector(notes_str: str):
tokens = NOTE_TOKEN_RE.findall(notes_str)
pcs = [NAME_TO_PC.get(t.upper(), None) for t in tokens]
pcs = [p for p in pcs if p is not None]
vec = np.zeros(12)
for p in pcs:
vec[p] = 1
return vec
def predict(inputs: str):
vec = notes_to_vector(inputs)
if np.sum(vec) < 2:
return {"label": "Invalid input (need 2+ notes)"}
label = clf.predict([vec])[0]
return {"label": label}