File size: 819 Bytes
78d69b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b3f44b9
 
78d69b1
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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}