File size: 5,206 Bytes
8d75c41
 
0881b1b
 
 
 
8d75c41
 
 
0881b1b
 
 
 
 
fb6a074
47e4e25
8d75c41
 
0881b1b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d75c41
0881b1b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d75c41
 
 
 
 
0881b1b
 
8d75c41
0881b1b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
from fastapi import FastAPI, UploadFile, File
from fastapi.responses import JSONResponse
import tempfile
import os
import numpy as np
import librosa

app = FastAPI()

NOTE_NAMES = [
    "C", "C#", "D", "D#", "E", "F",
    "F#", "G", "G#", "A", "A#", "B"
]


@app.api_route("/ping", methods=["GET", "HEAD"])
async def ping():
    """
    Health check for uptime monitors and the app.
    """
    return {"status": "alive", "backend": "librosa-analyzer"}


def freq_to_pc(freq: float):
    """Convert freq (Hz) to pitch class 0..11 (C..B)."""
    if freq <= 0:
        return None
    midi = 69 + 12 * np.log2(freq / 440.0)
    mround = int(np.round(midi))
    # A0..C8 (piano range)
    if mround < 21 or mround > 108:
        return None
    return mround % 12


def interval_to_nashville(interval: int, quality: str) -> str:
    if interval == 0:
        return "i" if quality == "minor" else "I"
    elif interval == 2:
        return "ii" if quality == "minor" else "II"
    elif interval == 4:
        return "iii" if quality == "minor" else "III"
    elif interval == 5:
        return "iv" if quality == "minor" else "IV"
    elif interval == 7:
        return "v" if quality == "minor" else "V"
    elif interval == 9:
        return "vi" if quality == "minor" else "VI"
    elif interval == 11:
        return "vii°" if quality == "minor" else "VII°"
    else:
        return "?"


def detect_chord_and_key_from_pcs(pitch_classes):
    """
    Given list of pitch classes (0..11), guess chord (major/minor) and key.
    """
    if len(pitch_classes) == 0:
        return None, None, None, None

    # Histogram of pitch classes
    hist = np.zeros(12, dtype=int)
    for pc in pitch_classes:
        hist[pc % 12] += 1

    # Simple major-key profile: I, ii, iii, IV, V, vi, vii°
    major_degrees = np.array([0, 2, 4, 5, 7, 9, 11])
    best_key = -1
    best_score = -1
    for root in range(12):
        score = hist[(root + major_degrees) % 12].sum()
        if score > best_score:
            best_score = score
            best_key = root

    if best_score <= 0:
        # Fallback: just use last pitch class
        best_key = pitch_classes[-1]

    key_pc = best_key % 12
    key_name = NOTE_NAMES[key_pc]

    # Chord detection
    unique_pcs = sorted(list(set(pitch_classes)))
    if len(unique_pcs) < 2:
        root_pc = unique_pcs[-1]
        return root_pc, "major", "I", key_name

    chosen_root = None
    chosen_quality = None
    for root in unique_pcs:
        intervals = sorted([(pc - root) % 12 for pc in unique_pcs])
        is_major = (4 in intervals) and (7 in intervals)
        is_minor = (3 in intervals) and (7 in intervals)
        if is_major:
            chosen_root = root
            chosen_quality = "major"
            break
        if is_minor:
            chosen_root = root
            chosen_quality = "minor"
            break

    if chosen_root is None:
        # fallback: treat as major on last PC
        chosen_root = unique_pcs[-1]
        chosen_quality = "major"

    interval = (chosen_root - key_pc) % 12
    nashville = interval_to_nashville(interval, chosen_quality)

    return chosen_root, chosen_quality, nashville, key_name


@app.post("/analyze_piano")
async def analyze_piano(audio: UploadFile = File(...)):
    """
    Accepts a short audio snippet (0.5–2s), estimates pitches using librosa,
    and returns a rough chord + key guess.
    """
    # Save uploaded file to a temp WAV
    with tempfile.TemporaryDirectory() as tmpdir:
        in_path = os.path.join(tmpdir, "input.wav")

        with open(in_path, "wb") as f:
            f.write(await audio.read())

        # Load audio, mono, 16k
        try:
            y, sr = librosa.load(in_path, sr=16000, mono=True)
        except Exception as e:
            return JSONResponse({
                "has_piano": False,
                "reason": f"Error loading audio: {e}"
            })

        # If too short, bail
        if len(y) < 1600:
            return JSONResponse({
                "has_piano": False,
                "reason": "Audio too short"
            })

        # Limit to ~2 seconds for speed
        max_len = sr * 2
        if len(y) > max_len:
            y = y[:max_len]

        # Pitch estimation using librosa.yin
        f0 = librosa.yin(
            y,
            fmin=60.0,
            fmax=1000.0,
            sr=sr,
            frame_length=1024,
            hop_length=256
        )

        pcs = []
        for freq in f0:
            if np.isnan(freq) or freq <= 0:
                continue
            pc = freq_to_pc(float(freq))
            if pc is not None:
                pcs.append(pc)

        if len(pcs) == 0:
            return JSONResponse({
                "has_piano": False,
                "reason": "No stable pitches found"
            })

        root_pc, quality, nashville, key_name = detect_chord_and_key_from_pcs(pcs)
        chord_root_name = NOTE_NAMES[root_pc] if root_pc is not None else None

        return JSONResponse({
            "has_piano": True,
            "chord_root": chord_root_name,
            "chord_quality": quality,
            "nashville": nashville,
            "key": key_name
        })