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 })