Skip to content
プロジェクト

rohan-prasen/audioreconstruction

GitHubで見る

概要

An adversarial neural network that restores the high fidelity audio lost during lossy compression

デザイン・メディア

この数値の測り方

計測したスター増加

24時間
0
7日間
+1
15日間
+1
1か月
履歴を収集中

期間ごとの純増数です。期間は重複しており、日別の値ではありません。未計測の値は空欄です。スター数は注目度の指標であり、品質の保証ではありません。

audioreconstruction

Publish audioreconstructor to PyPi PyPI Version GitHub stars Hugging Face License Python

Give your old MP3s a second listen.

Pick a track you haven’t played in years. audioreconstruction uses a trained model to estimate detail lost during MP3 compression and saves the result as FLAC, ready to compare with the copy you know.

Try it for free in your browser or run it locally from the command line.

Try in your browser · Run locally with the CLI

Input: MP3 (128 / 256 / 320 kbps)  |  Output: FLAC (~800+ kbps effective bitrate)  |  Audio: stereo, 44.1 kHz

Reconstruction quality

The model reconstructed MP3 encodes of a lossless FLAC at three bitrates. Each reconstruction was scored against the original with packages/benchmarks/eval_flac.py.

Results from one 30-second demo track

Source MP3 SNR vs. original Spectrogram similarity
128 kbps 16.78 dB 99.56 %
256 kbps 22.62 dB 99.96 %
320 kbps 20.46 dB 99.98 %

Full-track comparison on “Thriller” (128 kbps)

Metric vs. the original FLAC MP3 input Reconstructed FLAC
SNR 17.53 dB 12.01 dB
Wideband PESQ 4.58 4.58

SNR changed by −5.52 dB across the aligned recording, with no gain adjustment. Wideband PESQ is a speech-quality metric shown here as a supplementary score on 16 kHz mono audio.

Reproduce the FLAC comparison: transcode any lossless FLAC to MP3, reconstruct it, then run uv run python -m benchmarks.eval_flac original.flac reconstructed.flac.

Hear it (before / after)

Three excerpts from Michael Jackson’s “Bad,” each comparing the 128 kbps MP3 input with the reconstructed FLAC.

Excerpt MP3 input Reconstructed FLAC
1:00–1:12 MP3 FLAC
1:50–2:02 MP3 FLAC
3:10–3:22 MP3 FLAC

Browse all six files in media/samples/clips/.


Contents


Pick your path

There are three independent ways to use this project. Choose by how much you want to run yourself:

Try it now, no install → open the hosted web app at audioreconstruction.vercel.app, drop in an MP3, download the FLAC (Path 2 below).

Path For whom What you run Needs a GPU?
1. CLI (pip) Anyone who just wants better audio pip install audioreconstructor → runs an ONNX model on CPU No
2. Hosted web app Non-technical users Open the site, drop an MP3, download the FLAC No (runs on our GPU)
3. Self-host / develop Contributors & tinkerers Clone the repo, run the FastAPI server + React frontend, or train the model Training: yes. Inference: optional
  • Path 1 ships a standalone audioreconstructor PyPI package — no PyTorch, no repo clone, no GPU. See Quick Start.
  • Path 2 is the React frontend deployed to Vercel (https://audioreconstruction.vercel.app), backed by the production server on Modal.com.
  • Path 3 is the full repository. See Getting Started.

Quick Start (CLI)

The fastest way to reconstruct audio — no training, no GPU, no repo clone. The audioreconstructor package ships an ONNX build of the trained model that runs on CPU:

pip install audioreconstructor
audioreconstructor setup                                       # downloads + verifies model
audioreconstructor enhance --input song.mp3 --output song.flac # single file
audioreconstructor enhance --folder ./songs                    # whole folder (recursive)
audioreconstructor doctor                                      # diagnose environment / cache

CLI demo showing an MP3 reconstructed as FLAC

Reconstructing an MP3 as FLAC from the terminal.

On first run, setup downloads the native executable, model.onnx, and config.json from the matching GitHub Release, verifies each against a SHA-256 manifest, and caches them per-version. Supports 64-bit Linux and Windows, plus macOS Apple Silicon and Intel. See packages/cli/README.md for execution providers and cache locations.

How It Works

A GAN (Generative Adversarial Network) learns to reverse compression artifacts:

  1. Generator — a 1D U-Net (~28M params) that predicts high-resolution spectral content from the compressed waveform. It uses a residual connection (output = generator(input) + input), so it learns the difference between lossy and lossless rather than regenerating the whole signal.

  2. Discriminator — a multi-scale network (~25M params) that enforces perceptual realism by distinguishing real from reconstructed audio.

  3. Training objective — a weighted sum of three losses:

    Loss Weight What it does
    LSGAN adversarial 1.0 Pushes output toward the "real audio" manifold
    Multi-scale spectral (STFT @ 512 / 1024 / 2048) 100.0 L1 on magnitude + log-magnitude; the main fidelity signal
    Feature matching 10.0 L1 on the discriminator's intermediate features; stabilizes training

Inference processes audio in segment_length chunks (131072 samples ≈ 3 s). Training uses mixed precision (torch.amp) and gradient checkpointing on CUDA.

Use cases

  • Music remastering from low-bitrate sources
  • Streaming audio quality enhancement
  • Archival recovery of degraded recordings

Repository Map

audioreconstruction/
├── apps/web/              # React 19, Vite 8 and Tailwind CSS 4
├── packages/
│   ├── api/               # Production FastAPI app, Azure uploads and Modal image
│   ├── backend/           # Local multipart inference server
│   ├── benchmarks/        # PESQ, SNR, LSD, SI-SDR and Mel-SSIM evaluation
│   ├── cli/               # Published audioreconstructor CLI (Click and Rich)
│   ├── packages/model/             # PyTorch model, data prep, training and checkpoint export
│   └── onnx/              # ONNX export, torch-free inference and PyInstaller spec
├── crates/                # Rust CLI, core, TUI and PyO3 bindings
├── docs/                  # Contributing, security and agent routing
├── design/                # UI briefs and mockups
├── openspec/              # Change proposals
├── media/                 # Demo GIFs, sample audio and screenshots
├── AGENTS.md              # Agent guide, linked from CLAUDE.md and GEMINI.md
├── PRODUCT.md             # Product intent and target user
├── DESIGN.md              # Design system
└── uv.lock, pnpm-lock.yaml, Cargo.lock

Two inference servers — why both?

  • packages/backend/ is a simple dev server: imports packages/model/ directly, one request at a time, permissive CORS. Checkpoint path from CHECKPOINT_DIR (default packages/model/checkpoints/best/). Not deployed.
  • packages/api/ is the production server on Modal.com. It keeps its own copy of the inference-only model code (packages/api/model/) because Modal packages packages/api/ as an isolated container image. It adds dynamic batching, rate limiting, strict CORS, structured logging, and a pre-signed-upload flow.

When changing inference behavior for production, edit packages/api/.

Pre-signed uploads (production only)

Audio never passes through the GPU container. The browser uploads straight to Azure Blob Storage:

  1. POST /upload-url → {uploadUrl, blobName} — a write-only SAS scoped to one blob, 15 min.
  2. Browser PUTs the MP3 directly to Azure (header x-ms-blob-type: BlockBlob).
  3. POST /model-serve with {blobName, filename} → {downloadUrl, filename, size} — a read-only SAS, 1 hour, that saves as <stem>_reconstructed.flac.

blobName is server-generated and re-validated on arrival (it's used as a temp-file path). The input blob is deleted after processing.

Getting Started (Developers)

Prerequisites

  • Python 3.12 (pinned in .python-version; the published CLI supports Python 3.10–3.13)
  • Node.js (pinned in .nvmrc)
  • uv — Python package manager
  • pnpm (pinned in package.json)
  • Git LFS — required for checkpoint and ONNX weights
  • FFmpeg — required only for training-data preparation

Setup

git clone [email protected]:rohan-prasen/audioreconstruction.git
cd audioreconstruction
git lfs pull

# Python dependencies
uv sync --locked

# Frontend dependencies
pnpm install --frozen-lockfile

Model weights are hosted on HuggingFace — download here. Place generator.safetensors under ./packages/model/checkpoints/best/. (Training produces checkpoints there; inference loads the generator only.)

Run locally

# Terminal 1 — API used by the web app
uv run uvicorn api.app:app --reload       # http://localhost:8000

# Terminal 2 — frontend (proxies /api/* to the backend in dev)
pnpm dev                          # http://localhost:5173

Set the Azure variables below before testing uploads. To use the multipart API independently, run uv run uvicorn backend.main:app --reload.

See apps/web/CLAUDE.md for the frontend state model, retry/back-off logic, and styling.

Training Your Own Model

The packages/model/ pipeline runs as python -m model.<module>. CUDA is required for training.

# 1. Place source FLACs in data/lossless/, then transcode to MP3 (needs FFmpeg)
uv run python -m model.prepare_data            # → data/lossy/{128,256,320}/*.mp3

# 2. Train (defaults: 200 epochs, batch 4, lr 1e-4; saves best by val spectral loss)
uv run python -m model.train
uv run python -m model.train --resume packages/model/checkpoints/epoch_50

# 3. Export generator-only weights (strips discriminator) for distribution
uv run python -m model.export --checkpoint packages/model/checkpoints/best

Data layout:

data/
├── lossless/          # source FLAC files (you provide these)
└── lossy/
    ├── 128/           # auto-generated MP3
    ├── 256/
    └── 320/

Files are paired by stem name. Each checkpoint directory holds generator.safetensors, discriminator.safetensors, training_state.pt (epoch + optimizer state), and config.json. Weights use safetensors exclusively (never .pt for model weights).

Evaluation & Audio Metrics

# Reconstruct and (optionally) score against reference FLACs — single file or directory
uv run python -m model.evaluate --checkpoint packages/model/checkpoints/best --input song.mp3 --output output/
uv run python -m model.evaluate --checkpoint packages/model/checkpoints/best \
  --input data/lossy/128/ --output output/ --reference data/lossless/

evaluate computes PESQ and SNR when references are supplied. The packages/benchmarks/ directory holds standalone similarity CLIs (not a pytest suite) for comparing file pairs:

uv run python -m benchmarks.eval_flac "original.flac" "reconstructed.flac"
uv run python -m benchmarks.eval_mp3  "reference.flac" "compressed.mp3"

Lower-level metric modules live alongside them: snr.py, pesq.py, lsd.py, mel_ssim.py, si_sdr.py. See packages/benchmarks/README.md.

Deployment

Production server → Modal.com

uv run modal deploy packages/api/modal_app.py          # requires `modal` CLI auth

Runs on a T4 GPU (min_containers=0, max_containers=2, scales to zero when idle). Rate-limited via slowapi, CORS locked to the frontend origin.

Frontend → Vercel

Set the Vercel project root to apps/web and retain VITE_BACKEND_URL for the Modal API.

Azure Blob Storage

The production server needs these environment variables (supplied on Modal via the azure-blob secret): AZURE_STORAGE_ACCOUNT, AZURE_STORAGE_KEY, AZURE_UPLOAD_CONTAINER, AZURE_OUTPUT_CONTAINER (and AZURE_BLOB_ENDPOINT to point at Azurite locally).

The storage account must have a CORS rule allowing PUT/GET from the frontend origin, or the browser's direct upload is blocked.

ONNX CLI release flow

Build the native binary with PyInstaller → generate the SHA-256 manifest.json → upload the binary + model.onnx + config.json + manifest.json to a GitHub Release tagged audioreconstructor-v<version> → bump packages/cli/pyproject.toml to match. The package version and release tag must stay in lockstep. See packages/cli/README.md.

Development Commands

# Root Python project
uv run ruff check .                 # lint
uv run pytest                       # CLI and ONNX metadata tests

# Published CLI package (packages/cli/)
uv run pytest packages/cli/tests        # unittest-based tests
uv run ruff check packages/cli  # lint

# Frontend
pnpm lint             # ESLint
pnpm build        # production build

# Rust workspace and optional Python bindings
cargo test --workspace --locked
uv sync --locked --group native

Tech Stack

Layer Technology
Model PyTorch, torchaudio, safetensors
Backend FastAPI, uvicorn, SlowAPI
Deployment Modal.com (serverless GPU — T4), Azure Blob
Frontend React 19, Vite 8, Tailwind CSS 4, Framer Motion
CLI ONNX Runtime, Click, Rich, PyInstaller
Metrics PESQ, SNR, LSD, SI-SDR, Mel-SSIM
Tooling uv (Python), pnpm (JS), Ruff (lint)

Key Constraints

  • Python 3.12 pinned (.python-version); root project requires >=3.10, the CLI package supports 3.10–3.13
  • CUDA required for training (mixed precision assumes CUDA); inference falls back to CPU but is slow
  • FFmpeg required for data preparation
  • Audio is always stereo (in_channels=2), 44.1 kHz
  • Model weights use safetensors exclusively (not .pt)
  • Upload limit on both inference servers: 25 MB / 6 minutes

Project Docs

Doc What's in it
CLAUDE.md / AGENTS.md Full architecture guide for agents (mirrors of each other)
PRODUCT.md Product purpose and target user
DESIGN.md Design system — color tokens, typography
apps/web/CLAUDE.md Frontend state model, retry logic, styling
packages/cli/README.md CLI usage, execution providers, cache locations
packages/benchmarks/README.md Audio-similarity evaluation scripts
openspec/changes/ Planned / in-flight change proposals

Contributing

See CONTRIBUTING.md for guidelines and CODE_OF_CONDUCT.md.

Security

To report a vulnerability, see SECURITY.md.

License

MIT — Rohan Prasen Kedari


Found this useful? A ⭐ on the repo helps other people find it — and nudges me to keep improving the model.

関連プロジェクトを探す

読み込み中…