Metadata-Version: 2.4
Name: pitchperfect
Version: 0.1.0
Summary: Chord recognition for audio files, in plain NumPy and SciPy.
Project-URL: Homepage, https://github.com/Jonjlim/Pitchperfect
Project-URL: Repository, https://github.com/Jonjlim/Pitchperfect
Project-URL: Issues, https://github.com/Jonjlim/Pitchperfect/issues
Author-email: Jonathon Lim <limjonathon321@gmail.com>
License: MIT License
        
        Copyright (c) 2026 Jonathon Lim
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
License-File: LICENSE
Keywords: audio,chord-recognition,chords,dsp,mir,music
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Multimedia :: Sound/Audio :: Analysis
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: numpy>=1.24
Requires-Dist: scipy>=1.10
Requires-Dist: soundfile>=0.12
Provides-Extra: viz
Requires-Dist: matplotlib>=3.7; extra == 'viz'
Description-Content-Type: text/markdown

# Pitchperfect

[![CI](https://github.com/Jonjlim/Pitchperfect/actions/workflows/ci.yml/badge.svg)](https://github.com/Jonjlim/Pitchperfect/actions/workflows/ci.yml)
[![Python](https://img.shields.io/badge/python-3.10%2B-blue)](https://www.python.org/)
[![License: MIT](https://img.shields.io/badge/license-MIT-green)](LICENSE)

Chord recognition for audio files, written from scratch in NumPy and SciPy.

Point it at a recording and it tells you which chords are played and when. No
machine-learning model, no pre-trained weights, and no heavy audio framework —
just a short-time Fourier transform, a chromagram, and template matching.

```python
from pitchperfect import analyze

sheet = analyze("song.mp3")

for segment in sheet.without_rests():
    print(f"{segment.start:6.2f}s  {segment.label}")
```

```
  0.83s  C
  4.12s  G
  7.45s  Am
 10.90s  F
```

## Install

```bash
pip install pitchperfect
```

Optional plotting helpers:

```bash
pip install "pitchperfect[viz]"
```

Requires Python 3.10+. Audio decoding is handled by
[libsndfile](https://libsndfile.github.io/libsndfile/) via `soundfile`, which
supports WAV, FLAC, OGG and MP3 out of the box — no `ffmpeg` needed.

## Command line

```bash
pitchperfect song.mp3               # human-readable table
pitchperfect song.mp3 --json        # machine-readable
pitchperfect song.mp3 --no-rests    # skip silent stretches
```

```
   START       END  CHORD
    0.83      8.00  C
```

## Library reference

### `analyze(path, config=None, title=None) -> ChordSheet`

Analyze an audio file. `title` defaults to the file name.

### `analyze_samples(audio, sample_rate, config=None, title=None) -> ChordSheet`

Same, for a mono NumPy array you already have in memory.

### `ChordSheet`

| Attribute / method | Description                                        |
| ------------------ | -------------------------------------------------- |
| `segments`         | `list[ChordSegment]` in chronological order.       |
| `labels`           | Chord labels in order, including rests.            |
| `duration`         | Length of the source audio in seconds.             |
| `sample_rate`      | Sample rate of the source audio.                   |
| `title`            | File name, or whatever you passed in.              |
| `chord_at(t)`      | The segment sounding at time `t`, or `None`.       |
| `without_rests()`  | Segments excluding silence.                        |
| `to_dict()`        | JSON-serializable `{"title", "duration", "chords"}`. |

It is iterable and sized, so `for segment in sheet` and `len(sheet)` work.

### `ChordSegment`

A frozen dataclass of `start`, `end` and `label` (plus `duration` and
`is_rest`). Labels are `"C"`, `"Cm"`, `"F#"`, … or `"rest"` for silence.

### `AnalysisConfig`

Every knob has a default; override only what you need.

| Field               | Default | Meaning                                            |
| ------------------- | ------- | -------------------------------------------------- |
| `chroma_resolution` | `5`     | Chroma sub-bins per semitone.                      |
| `smoothing_kernel`  | `9`     | Median-filter width in frames.                     |
| `window_size`       | `None`  | FFT window in samples; derived from the rate.      |
| `hop_length`        | `None`  | Hop in samples; defaults to half the window.       |
| `window_divisor`    | `3`     | Window is `sample_rate / window_divisor`.          |
| `silence_threshold` | `0.02`  | Energy fraction below which a frame is a rest.     |

```python
from pitchperfect import AnalysisConfig, analyze

# Shorter windows react faster to chord changes but are noisier.
sheet = analyze("song.mp3", AnalysisConfig(window_size=4096, smoothing_kernel=5))
```

## How it works

```
audio ─► STFT ─► chromagram ─► template match ─► median filter ─► segments
```

1. **`audio.py`** frames the signal, applies a Hann window and takes an
   `rfft`, giving a magnitude spectrogram.
2. **`chroma.py`** folds every FFT bin onto a 12-semitone circle
   (`12·log₂(f / 440) mod 12`), so all octaves of a pitch collapse together.
   The fold is a one-hot matrix multiply, so the whole spectrogram is projected
   in a single operation.
3. **`recognition.py`** compares each frame against unit-norm templates for all
   24 major and minor triads by cosine similarity, and marks low-energy frames
   as rests.
4. A median filter removes single-frame flickers, and runs of identical labels
   collapse into `ChordSegment`s.

### Limitations

- Only major and minor triads are recognized — no sevenths, suspensions or
  inversions. Extending `CHORD_QUALITIES` in `recognition.py` adds more.
- Chord-level resolution: the default window is a third of a second, so very
  fast changes get smoothed away.
- No key estimation, beat tracking or lyric alignment.

## Development

The project uses [Pixi](https://pixi.sh) for reproducible dev environments.
Packaging metadata lives in the same `pyproject.toml`, so the library stays a
normal `pip install` for everyone else.

```bash
pixi install -e dev      # create the environment
pixi run -e dev test     # run the test suite
pixi run -e dev cov      # tests with coverage
pixi run -e dev lint     # ruff
pixi run -e dev example  # analyze the bundled sample
```

Prefer plain pip:

```bash
pip install -e ".[viz]" pytest && pytest
```

The tests synthesize their own audio from sine waves, so the suite is fast,
deterministic, and does not depend on any checked-in recordings.

## Project layout

```
pitchperfect/
├── src/pitchperfect/
│   ├── audio.py        # loading and STFT
│   ├── chroma.py       # spectrogram → chromagram
│   ├── recognition.py  # templates, matching, smoothing, segmentation
│   ├── pipeline.py     # analyze() / analyze_samples()
│   ├── models.py       # ChordSheet and ChordSegment
│   ├── config.py       # AnalysisConfig and musical constants
│   ├── viz.py          # optional matplotlib plots
│   └── cli.py          # the pitchperfect command
├── examples/           # runnable scripts
├── tests/              # pytest suite
└── resources/samples/  # small audio clips for manual testing
```

## Demo

A web front end for this library lives in
[Pitchperfect-Website](https://github.com/Jonjlim/Pitchperfect-website): a
FastAPI service wrapping the package, plus a React UI that plays audio and
scrolls the chords in time with it.

## License

MIT — see [LICENSE](LICENSE).
