Skip to content

About

AI-powered music generation system that uses LSTM deep learning networks to learn musical patterns from MIDI datasets and generate original music sequences. Built with Python, TensorFlow, and Music21.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

Β 

History

12 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Live demo: Open in Google Colab Open In Colab

🎡 CodeAlpha Internship Project 3: Music Generation with AI

Python 3.10+ TensorFlow 2.15+ Music21 Google Colab License: MIT Internship: CodeAlpha

An end-to-end Deep Learning system that composes novel, coherent polyphonic music using Long Short-Term Memory (LSTM) neural networks and Music21. Compatible with both local Windows environments and free Google Colab (T4 GPU).


πŸ“‘ Table of Contents

  1. Project Overview
  2. System Architecture & Pipeline
  3. Curated Public-Domain Dataset
  4. Deep Learning Model Architecture
  5. Temperature-Based Probabilistic Sampling
  6. Project Structure
  7. Getting Started on Google Colab (Recommended)
  8. Getting Started Locally on Windows
  9. Automated Test Suite & Verification
  10. Sample Generated Outputs
  11. Author & Acknowledgments

🎼 Project Overview

Music composition possesses both temporal structure (rhythm and melody over time) and spatial structure (harmony and polyphonic chords). This project constructs a deep sequential recurrent model capable of:

  • Extracting symbolic musical elements (notes, chords, quantized durations, and rests) from Standard MIDI Files (SMF).
  • Learning sequential harmonic transitions using stacked LSTM layers with Embedding, Dropout, and Batch Normalization.
  • Generating novel musical sequences using temperature-scaled stochastic sampling.
  • Synthesizing generated tokens back into standard .mid files and playable .wav audio.

πŸ”„ System Architecture & Pipeline

+-----------------------+
|  Raw MIDI Dataset     | (Public Domain: Bach, Beethoven, Chopin, Mozart, Pachelbel)
+-----------+-----------+
            |
            v
+-----------------------+
|  Music21 Preprocessor | -> Quantizes durations, extracts notes/chords/rests
+-----------+-----------+    Encodes into tokens (e.g. 'C4_0.5', 'C4.E4.G4_1.0')
            |
            v
+-----------------------+
|  Sliding Window (X,y) | -> Window length = 32, Token-to-Index vocabulary
+-----------+-----------+
            |
            v
+-----------------------+
|  Stacked LSTM Model   | -> Embedding(128) -> LSTM(256) -> Dropout(0.3) ->
+-----------+-----------+    BatchNorm -> LSTM(256) -> Dense(256) -> Softmax
            |
            v
+-----------------------+
| Temperature Sampler   | -> P(i) = exp(z_i / T) / sum(exp(z_j / T))
+-----------+-----------+    Controlled creativity (T in [0.2, 1.2])
            |
            +---------------------------+
            |                           |
            v                           v
+-----------------------+   +-----------------------+
|   Standard MIDI (.mid)|   | Playable Audio (.wav) |
+-----------------------+   +-----------------------+

πŸ“š Curated Public-Domain Dataset

To guarantee legal, copyright-free usage, the repository includes curated classical compositions located in data/raw_midi/:

  • J.S. Bach: Two-Part Invention No. 1 in C Major (BWV 772)
  • FrΓ©dΓ©ric Chopin: Prelude in E Minor (Op. 28 No. 4)
  • Ludwig van Beethoven: Symphony No. 9 "Ode to Joy" Piano Theme
  • W.A. Mozart: 12 Variations on "Ah vous dirai-je, Maman" (KV 265)
  • Johann Pachelbel: Canon in D Major Piano Progression

All pieces are strictly in the public domain under CC0 / Open Access music archives.


🧠 Deep Learning Model Architecture

Layer Type Specifications Function
1 Input (batch_size, 32) Receives integer token sequence
2 Embedding input_dim=Vocab, output_dim=128 Maps discrete musical tokens into dense continuous harmonic space
3 LSTM 1 256 units, return_sequences=True Extracts high-level melodic contour
4 Dropout 1 rate=0.3 Regularization against overfitting
5 BatchNormalization 1 Channels axis Stabilizes activations across training
6 LSTM 2 256 units, return_sequences=False Encodes long-term sequence dependencies
7 Dropout 2 rate=0.3 Regularization
8 BatchNormalization 2 Channels axis Stabilizes activations
9 Dense Hidden 256 units, activation='relu' Non-linear feature combination
10 Dropout 3 rate=0.3 Regularization
11 Output Dense units=Vocab, activation='softmax' Categorical probability distribution for next token

πŸŽ›οΈ Temperature-Based Probabilistic Sampling

Rather than simply choosing the most likely token (greedy argmax, which causes repetitive loops), the generator applies temperature scaling:

$$\text{scaled_logits}_i = \frac{\ln(p_i + \epsilon)}{T}, \quad P(i) = \frac{\exp(\text{scaled_logits}_i)}{\sum_j \exp(\text{scaled_logits}_j)}$$

  • $T = 0.3$ (Conservative): Sharpens probability peaks. Highly predictable, tightly follows motif patterns.
  • $T = 0.8$ (Recommended / Sweet Spot): Balanced creativity and harmonic coherence.
  • $T = 1.2$ (Adventurous): Broadens probability distribution. More unexpected, jazz-like or experimental transitions.

πŸ“ Project Structure

CodeAlpha_MusicGenerationAI/
β”œβ”€β”€ data/
β”‚   β”œβ”€β”€ raw_midi/                # 5 curated public-domain classical pieces (.mid)
β”‚   └── processed/               # Vocabulary mapping and preprocessed token sequences
β”œβ”€β”€ models/
β”‚   └── lstm_music_model_best.keras # Checkpoint weights (saved during training)
β”œβ”€β”€ output/
β”‚   β”œβ”€β”€ generated_music.mid      # Synthesized AI MIDI file
β”‚   β”œβ”€β”€ generated_music.wav      # Playable WAV audio file
β”‚   └── training_loss_curve.png  # Training loss/accuracy convergence plot
β”œβ”€β”€ notebooks/
β”‚   └── Music_Generation_AI_Colab.ipynb # Complete, beginner-friendly Colab notebook
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ config.py                # Hyperparameters, sequence length, and paths
β”‚   β”œβ”€β”€ midi_dataset.py          # Dataset discovery and download utilities
β”‚   β”œβ”€β”€ preprocess.py            # Music21 tokenizer & sequence builder
β”‚   β”œβ”€β”€ model.py                 # Keras stacked LSTM architecture
β”‚   β”œβ”€β”€ train.py                 # Training pipeline with callbacks & resume support
β”‚   β”œβ”€β”€ generate.py              # Temperature-based generation engine
β”‚   β”œβ”€β”€ postprocess.py           # MIDI writer & acoustic WAV synthesizer
β”‚   └── utils.py                 # Diagnostics, audio display, and helpers
β”œβ”€β”€ tests/
β”‚   β”œβ”€β”€ test_midi_io.py          # Unit tests for MIDI parsing & writing
β”‚   β”œβ”€β”€ test_preprocessing.py    # Unit tests for vocabulary and windowing
β”‚   β”œβ”€β”€ test_generation.py       # Unit tests for temperature sampling
β”‚   └── run_all_tests.py         # Complete automated test runner
β”œβ”€β”€ requirements.txt             # Dependency specifications
β”œβ”€β”€ .gitignore                   # Git exclusion rules
└── README.md                    # Project documentation

πŸš€ Getting Started on Google Colab (Recommended)

Google Colab allows you to train the deep learning model on a free cloud GPU (NVIDIA T4) with zero local installation:

  1. Open Google Colab.
  2. Click Upload and upload notebooks/Music_Generation_AI_Colab.ipynb.
  3. Enable GPU acceleration:

    Runtime βž” Change runtime type βž” Hardware accelerator βž” T4 GPU βž” Save.

  4. Click Runtime βž” Run all (or run each cell sequentially).
  5. The notebook will automatically:
    • Install music21 and fluidsynth.
    • Extract notes and train the LSTM model.
    • Generate an original song with temperature sampling.
    • Provide an instant Download Button for the .mid file and an interactive audio player for the .wav audio.

πŸ’» Getting Started Locally on Windows

1. Prerequisites

  • Python 3.10 to 3.12 installed on your machine.
  • Standard Command Prompt or PowerShell.

2. Install Dependencies

pip install -r requirements.txt

3. Step-by-Step CLI Execution

Step A: Preprocess the MIDI dataset

python -m src.preprocess

Step B: Train the LSTM Model

python -m src.train --epochs 35 --batch-size 32

Tip: If you interrupt training, running python -m src.train will automatically resume from the latest saved checkpoint.

Step C: Generate Original Music

python -m src.generate --temperature 0.8 --length 150

Outputs are written to:

  • output/generated_music.mid
  • output/generated_music.wav

πŸ§ͺ Automated Test Suite & Verification

The project includes a comprehensive automated unit test suite covering:

  • MIDI header format integrity (SMF MThd and MTrk chunks).
  • Music21 tokenization and quantized duration preservation.
  • Invertibility of vocabulary mappings ($t = \text{idx_to_token}[\text{token_to_idx}[t]]$).
  • Sliding window dimensions and target label alignment.
  • Mathematical correctness of temperature sampling across temperature regimes.
  • End-to-end generation of valid .mid and .wav files.

To run the test suite:

python -m tests.run_all_tests

Result:

=================================================================
Running Test Suite: CodeAlpha MusicGenerationAI
=================================================================
test_end_to_end_generation_flow ... ok
test_low_temperature_peaks_highest_probability ... ok
test_temperature_sampling_bounds ... ok
test_midi_header_validity ... ok
test_midi_parsing_and_token_extraction ... ok
test_raw_midi_files_exist ... ok
test_token_to_midi_creation ... ok
test_wav_synthesis ... ok
test_quantize_duration ... ok
test_sequence_preparation_dimensions ... ok
test_vocabulary_mapping_invertibility ... ok
----------------------------------------------------------------------
Ran 11 tests in 5.915s
OK
>> ALL UNIT TESTS PASSED SUCCESSFULLY! <<

🎧 Sample Generated Outputs

Sample generated outputs from the model are stored in the output/ directory:


πŸ‘€ Author & Acknowledgments

  • Intern: CodeAlpha AI Intern
  • Organization: CodeAlpha
  • Project: Internship Project 3 β€” Music Generation with AI
  • Tools Used: Python, TensorFlow, Keras, Music21, PrettyMIDI, FluidSynth, Google Colab, Google Antigravity.

About

AI-powered music generation system that uses LSTM deep learning networks to learn musical patterns from MIDI datasets and generate original music sequences. Built with Python, TensorFlow, and Music21.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages