Skip to content
Merged
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -53,20 +53,8 @@ def _build_labels(self) -> list[str]:
labels.append(f"{note}m") # Minor
return labels

def recognize(self, y: np.ndarray, sr: int = 22050) -> list[TrackedChord]:
"""
Recognize chords in an audio array using chromagrams.

Args:
y: Audio time series.
sr: Sampling rate.

Returns:
List of dictionaries containing start_time, end_time, and chord string.
"""
if len(y) == 0:
return []

def _extract_chromagram(self, y: np.ndarray, sr: int) -> np.ndarray | None:
"""Extract chromagram from audio."""
# Compute harmonic harmonic-percussive separation (optional but helps)
try:
y_harmonic, _ = librosa.effects.hpss(y)
Expand All @@ -86,37 +74,47 @@ def recognize(self, y: np.ndarray, sr: int = 22050) -> list[TrackedChord]:
else:
chromagram = librosa.feature.chroma_cqt(y=y_harmonic, sr=sr)
except Exception:
return []
return None

if chromagram.size == 0:
return []
return None

# Optional: apply temporal smoothing to chromagram to reduce noise
chromagram = librosa.decompose.nn_filter(chromagram, aggregate=np.median, metric="cosine")
return librosa.decompose.nn_filter(chromagram, aggregate=np.median, metric="cosine")

# Calculate RMS energy to detect silence/noise
def _calculate_rms(self, y: np.ndarray, n_frames: int) -> np.ndarray:
"""Calculate RMS energy to detect silence/noise."""
try:
rms = librosa.feature.rms(y=y, frame_length=2048, hop_length=512)[0]
# Match RMS length to chromagram length
if len(rms) < chromagram.shape[1]:
rms = np.pad(rms, (0, chromagram.shape[1] - len(rms)), mode="edge")
if len(rms) < n_frames:
rms = np.pad(rms, (0, n_frames - len(rms)), mode="edge")
else:
rms = rms[: chromagram.shape[1]]
rms = rms[:n_frames]
except Exception:
rms = np.ones(chromagram.shape[1])
rms = np.ones(n_frames)
return np.asarray(rms)

def _match_templates(self, chromagram: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
"""Match chromagram to templates and return similarities and best match indices."""
# Compare chromagram frames to templates using dot product
# chromagram shape: (12, n_frames)
# templates shape: (24, 12)
# similarity shape: (24, n_frames)
similarity = np.dot(self.templates, chromagram)

# Find the best matching chord template for each frame
best_matches = np.argmax(similarity, axis=0)

# Convert frames to time segments
return similarity, best_matches

def _create_chord_segments(
self,
chromagram: np.ndarray,
similarity: np.ndarray,
best_matches: np.ndarray,
rms: np.ndarray,
sr: int,
) -> list[TrackedChord]:
"""Convert frame-level chord predictions into time segments."""
frames = librosa.frames_to_time(np.arange(chromagram.shape[1] + 1), sr=sr)

chords: list[TrackedChord] = []
current_chord = None
start_frame = 0
Expand All @@ -131,8 +129,6 @@ def recognize(self, y: np.ndarray, sr: int = 22050) -> list[TrackedChord]:
# For noise, the max similarity is usually lower, but to be robust
# we should check if the chromagram is too flat (e.g. low variance)
# or if the RMS energy is really low.
# However, since dot product normalization makes noise match *something*,
# we can look at the variance of the chromagram frame.
chroma_var = np.var(chromagram[:, i])
if max_sim < 0.3 or rms_val < 0.01 or chroma_var < 0.02:
chord_label = "N"
Expand Down Expand Up @@ -163,3 +159,26 @@ def recognize(self, y: np.ndarray, sr: int = 22050) -> list[TrackedChord]:
)

return chords

def recognize(self, y: np.ndarray, sr: int = 22050) -> list[TrackedChord]:
"""
Recognize chords in an audio array using chromagrams.

Args:
y: Audio time series.
sr: Sampling rate.

Returns:
List of dictionaries containing start_time, end_time, and chord string.
"""
if len(y) == 0:
return []

chromagram = self._extract_chromagram(y, sr)
if chromagram is None:
return []

rms = self._calculate_rms(y, chromagram.shape[1])
similarity, best_matches = self._match_templates(chromagram)

return self._create_chord_segments(chromagram, similarity, best_matches, rms, sr)
Loading