Spaces:
Sleeping
Sleeping
Upload 3 files
Browse files- Dockerfile +40 -0
- app.py +492 -0
- requirements.txt +9 -0
Dockerfile
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.9-slim
|
| 2 |
+
|
| 3 |
+
# Install system dependencies
|
| 4 |
+
RUN apt-get update && apt-get install -y \
|
| 5 |
+
fluidsynth \
|
| 6 |
+
libsndfile1 \
|
| 7 |
+
wget \
|
| 8 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 9 |
+
|
| 10 |
+
# Create app directory
|
| 11 |
+
WORKDIR /app
|
| 12 |
+
|
| 13 |
+
# Copy requirements first to leverage Docker cache
|
| 14 |
+
COPY requirements.txt .
|
| 15 |
+
|
| 16 |
+
# Install Python dependencies
|
| 17 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 18 |
+
|
| 19 |
+
# Copy the rest of the application
|
| 20 |
+
COPY . .
|
| 21 |
+
|
| 22 |
+
# Download soundfonts
|
| 23 |
+
RUN mkdir -p /app/soundfonts && \
|
| 24 |
+
wget -O /app/soundfonts/Trumpet.sf2 https://github.com/FluidSynth/fluidsynth/raw/master/sf2/Trumpet.sf2 && \
|
| 25 |
+
wget -O /app/soundfonts/Piano.sf2 https://musical-artifacts.com/artifacts/2719/GeneralUser_GS_1.471.sf2 && \
|
| 26 |
+
wget -O /app/soundfonts/Violin.sf2 https://musical-artifacts.com/artifacts/2744/SalC5Light.sf2 && \
|
| 27 |
+
wget -O /app/soundfonts/Clarinet.sf2 https://musical-artifacts.com/artifacts/2744/SalC5Light.sf2 && \
|
| 28 |
+
wget -O /app/soundfonts/Flute.sf2 https://musical-artifacts.com/artifacts/2744/SalC5Light.sf2
|
| 29 |
+
|
| 30 |
+
# Create static directory for audio files
|
| 31 |
+
RUN mkdir -p /app/static
|
| 32 |
+
|
| 33 |
+
# Set environment variables
|
| 34 |
+
ENV PYTHONUNBUFFERED=1
|
| 35 |
+
|
| 36 |
+
# Expose port
|
| 37 |
+
EXPOSE 7860
|
| 38 |
+
|
| 39 |
+
# Run the application
|
| 40 |
+
CMD ["python", "app.py"]
|
app.py
ADDED
|
@@ -0,0 +1,492 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Adaptive Music Exercise Generator (Strict Duration Enforcement)
|
| 3 |
+
==============================================================
|
| 4 |
+
|
| 5 |
+
Generates custom musical exercises with LLM, perfectly fit to user-specified number of measures
|
| 6 |
+
AND time signature, guaranteeing exact durations in MIDI and in the UI!
|
| 7 |
+
|
| 8 |
+
Major updates:
|
| 9 |
+
- Added duration sum display in Exercise Data tab
|
| 10 |
+
- Shows total duration units (16th notes) for verification
|
| 11 |
+
- Fixed difficulty level implementation
|
| 12 |
+
- Maintained all original functionality
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
# -----------------------------------------------------------------------------
|
| 16 |
+
# 1. Runtime-time package installation (for fresh containers/Colab/etc)
|
| 17 |
+
# -----------------------------------------------------------------------------
|
| 18 |
+
import sys
|
| 19 |
+
import subprocess
|
| 20 |
+
from typing import Dict, Optional, Tuple, List
|
| 21 |
+
|
| 22 |
+
def install(packages: List[str]):
|
| 23 |
+
for package in packages:
|
| 24 |
+
try:
|
| 25 |
+
__import__(package)
|
| 26 |
+
except ImportError:
|
| 27 |
+
print(f"Installing missing package: {package}")
|
| 28 |
+
subprocess.check_call([sys.executable, "-m", "pip", "install", package])
|
| 29 |
+
|
| 30 |
+
install([
|
| 31 |
+
"mido", "midi2audio", "pydub", "gradio",
|
| 32 |
+
"requests", "numpy", "matplotlib", "librosa", "scipy",
|
| 33 |
+
])
|
| 34 |
+
|
| 35 |
+
# -----------------------------------------------------------------------------
|
| 36 |
+
# 2. Static imports
|
| 37 |
+
# -----------------------------------------------------------------------------
|
| 38 |
+
import random
|
| 39 |
+
import requests
|
| 40 |
+
import json
|
| 41 |
+
import tempfile
|
| 42 |
+
import mido
|
| 43 |
+
from mido import Message, MidiFile, MidiTrack, MetaMessage
|
| 44 |
+
import re
|
| 45 |
+
from io import BytesIO
|
| 46 |
+
from midi2audio import FluidSynth
|
| 47 |
+
from pydub import AudioSegment
|
| 48 |
+
import gradio as gr
|
| 49 |
+
import numpy as np
|
| 50 |
+
import matplotlib.pyplot as plt
|
| 51 |
+
import librosa
|
| 52 |
+
from scipy.io import wavfile
|
| 53 |
+
import os
|
| 54 |
+
import subprocess as sp
|
| 55 |
+
import base64
|
| 56 |
+
import shutil
|
| 57 |
+
|
| 58 |
+
# -----------------------------------------------------------------------------
|
| 59 |
+
# 3. Configuration & constants
|
| 60 |
+
# -----------------------------------------------------------------------------
|
| 61 |
+
MISTRAL_API_URL = "https://api.mistral.ai/v1/chat/completions"
|
| 62 |
+
MISTRAL_API_KEY = "yQdfM8MLbX9uhInQ7id4iUTwN4h4pDLX" # ← Replace with your key!
|
| 63 |
+
|
| 64 |
+
SOUNDFONT_URLS = {
|
| 65 |
+
"Trumpet": "https://github.com/FluidSynth/fluidsynth/raw/master/sf2/Trumpet.sf2",
|
| 66 |
+
"Piano": "https://musical-artifacts.com/artifacts/2719/GeneralUser_GS_1.471.sf2",
|
| 67 |
+
"Violin": "https://musical-artifacts.com/artifacts/2744/SalC5Light.sf2",
|
| 68 |
+
"Clarinet": "https://musical-artifacts.com/artifacts/2744/SalC5Light.sf2",
|
| 69 |
+
"Flute": "https://musical-artifacts.com/artifacts/2744/SalC5Light.sf2",
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
SAMPLE_RATE = 44100 # Hz
|
| 73 |
+
TICKS_PER_BEAT = 480 # Standard MIDI resolution
|
| 74 |
+
TICKS_PER_16TH = TICKS_PER_BEAT // 4 # 120 ticks per 16th note
|
| 75 |
+
|
| 76 |
+
if not os.path.exists('/usr/bin/fluidsynth'):
|
| 77 |
+
try:
|
| 78 |
+
os.system('apt-get update && apt-get install -y fluidsynth')
|
| 79 |
+
except Exception:
|
| 80 |
+
print("Could not install FluidSynth automatically. Please install it manually.")
|
| 81 |
+
|
| 82 |
+
os.makedirs("static", exist_ok=True)
|
| 83 |
+
|
| 84 |
+
# -----------------------------------------------------------------------------
|
| 85 |
+
# 4. Music theory helpers (note names ↔︎ MIDI numbers)
|
| 86 |
+
# -----------------------------------------------------------------------------
|
| 87 |
+
NOTE_MAP: Dict[str, int] = {
|
| 88 |
+
"C": 0, "C#": 1, "DB": 1,
|
| 89 |
+
"D": 2, "D#": 3, "EB": 3,
|
| 90 |
+
"E": 4, "F": 5, "F#": 6, "GB": 6,
|
| 91 |
+
"G": 7, "G#": 8, "AB": 8,
|
| 92 |
+
"A": 9, "A#": 10, "BB": 10,
|
| 93 |
+
"B": 11,
|
| 94 |
+
}
|
| 95 |
+
|
| 96 |
+
INSTRUMENT_PROGRAMS: Dict[str, int] = {
|
| 97 |
+
"Piano": 0, "Trumpet": 56, "Violin": 40,
|
| 98 |
+
"Clarinet": 71, "Flute": 73,
|
| 99 |
+
}
|
| 100 |
+
|
| 101 |
+
def note_name_to_midi(note: str) -> int:
|
| 102 |
+
match = re.match(r"([A-Ga-g][#b]?)(\d)", note)
|
| 103 |
+
if not match:
|
| 104 |
+
raise ValueError(f"Invalid note: {note}")
|
| 105 |
+
pitch, octave = match.groups()
|
| 106 |
+
pitch = pitch.upper().replace('b', 'B')
|
| 107 |
+
if pitch not in NOTE_MAP:
|
| 108 |
+
raise ValueError(f"Invalid pitch: {pitch}")
|
| 109 |
+
return NOTE_MAP[pitch] + (int(octave) + 1) * 12
|
| 110 |
+
|
| 111 |
+
def midi_to_note_name(midi_num: int) -> str:
|
| 112 |
+
notes = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]
|
| 113 |
+
octave = (midi_num // 12) - 1
|
| 114 |
+
return f"{notes[midi_num % 12]}{octave}"
|
| 115 |
+
|
| 116 |
+
# -----------------------------------------------------------------------------
|
| 117 |
+
# 5. Duration scaling: guarantee the output sums to requested total (using integers)
|
| 118 |
+
# -----------------------------------------------------------------------------
|
| 119 |
+
def scale_json_durations(json_data, target_units: int) -> list:
|
| 120 |
+
"""Scales durations so that their sum is exactly target_units (16th notes)."""
|
| 121 |
+
durations = [int(d) for _, d in json_data]
|
| 122 |
+
total = sum(durations)
|
| 123 |
+
if total == 0:
|
| 124 |
+
return json_data
|
| 125 |
+
|
| 126 |
+
# Calculate proportional scaling with integer arithmetic
|
| 127 |
+
scaled = []
|
| 128 |
+
remainder = target_units
|
| 129 |
+
for i, (note, d) in enumerate(json_data):
|
| 130 |
+
if i < len(json_data) - 1:
|
| 131 |
+
# Proportional allocation
|
| 132 |
+
portion = max(1, round(d * target_units / total))
|
| 133 |
+
scaled.append([note, portion])
|
| 134 |
+
remainder -= portion
|
| 135 |
+
else:
|
| 136 |
+
# Last note gets all remaining units
|
| 137 |
+
scaled.append([note, max(1, remainder)])
|
| 138 |
+
|
| 139 |
+
return scaled
|
| 140 |
+
|
| 141 |
+
# -----------------------------------------------------------------------------
|
| 142 |
+
# 6. MIDI from scaled JSON (using integer durations)
|
| 143 |
+
# -----------------------------------------------------------------------------
|
| 144 |
+
def json_to_midi(json_data: list, instrument: str, tempo: int, time_signature: str, measures: int) -> MidiFile:
|
| 145 |
+
mid = MidiFile(ticks_per_beat=TICKS_PER_BEAT)
|
| 146 |
+
track = MidiTrack(); mid.tracks.append(track)
|
| 147 |
+
program = INSTRUMENT_PROGRAMS.get(instrument, 56)
|
| 148 |
+
numerator, denominator = map(int, time_signature.split('/'))
|
| 149 |
+
|
| 150 |
+
track.append(MetaMessage('time_signature', numerator=numerator,
|
| 151 |
+
denominator=denominator, time=0))
|
| 152 |
+
track.append(MetaMessage('set_tempo', tempo=mido.bpm2tempo(tempo), time=0))
|
| 153 |
+
track.append(Message('program_change', program=program, time=0))
|
| 154 |
+
|
| 155 |
+
for note_name, duration_units in json_data:
|
| 156 |
+
try:
|
| 157 |
+
note_num = note_name_to_midi(note_name)
|
| 158 |
+
ticks = int(duration_units * TICKS_PER_16TH)
|
| 159 |
+
ticks = max(ticks, 1)
|
| 160 |
+
velocity = random.randint(60, 100)
|
| 161 |
+
track.append(Message('note_on', note=note_num, velocity=velocity, time=0))
|
| 162 |
+
track.append(Message('note_off', note=note_num, velocity=velocity, time=ticks))
|
| 163 |
+
except Exception as e:
|
| 164 |
+
print(f"Error parsing note {note_name}: {e}")
|
| 165 |
+
return mid
|
| 166 |
+
|
| 167 |
+
# -----------------------------------------------------------------------------
|
| 168 |
+
# 7. MIDI → Audio (MP3) helpers
|
| 169 |
+
# -----------------------------------------------------------------------------
|
| 170 |
+
def get_soundfont(instrument: str) -> str:
|
| 171 |
+
os.makedirs("soundfonts", exist_ok=True)
|
| 172 |
+
sf2_path = f"soundfonts/{instrument}.sf2"
|
| 173 |
+
if not os.path.exists(sf2_path):
|
| 174 |
+
url = SOUNDFONT_URLS.get(instrument, SOUNDFONT_URLS["Trumpet"])
|
| 175 |
+
print(f"Downloading SoundFont for {instrument}…")
|
| 176 |
+
response = requests.get(url)
|
| 177 |
+
with open(sf2_path, "wb") as f:
|
| 178 |
+
f.write(response.content)
|
| 179 |
+
return sf2_path
|
| 180 |
+
|
| 181 |
+
def midi_to_mp3(midi_obj: MidiFile, instrument: str = "Trumpet") -> Tuple[str, float]:
|
| 182 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".mid") as mid_file:
|
| 183 |
+
midi_obj.save(mid_file.name)
|
| 184 |
+
wav_path = mid_file.name.replace(".mid", ".wav")
|
| 185 |
+
mp3_path = mid_file.name.replace(".mid", ".mp3")
|
| 186 |
+
sf2_path = get_soundfont(instrument)
|
| 187 |
+
try:
|
| 188 |
+
sp.run([
|
| 189 |
+
'fluidsynth', '-ni', sf2_path, mid_file.name,
|
| 190 |
+
'-F', wav_path, '-r', '44100', '-g', '1.0'
|
| 191 |
+
], check=True, capture_output=True)
|
| 192 |
+
except Exception:
|
| 193 |
+
fs = FluidSynth(sf2_path, sample_rate=44100, gain=1.0)
|
| 194 |
+
fs.midi_to_audio(mid_file.name, wav_path)
|
| 195 |
+
try:
|
| 196 |
+
sound = AudioSegment.from_wav(wav_path)
|
| 197 |
+
if instrument == "Trumpet":
|
| 198 |
+
sound = sound.high_pass_filter(200)
|
| 199 |
+
elif instrument == "Violin":
|
| 200 |
+
sound = sound.low_pass_filter(5000)
|
| 201 |
+
sound.export(mp3_path, format="mp3")
|
| 202 |
+
static_mp3_path = os.path.join('static', os.path.basename(mp3_path))
|
| 203 |
+
shutil.move(mp3_path, static_mp3_path)
|
| 204 |
+
return static_mp3_path, sound.duration_seconds
|
| 205 |
+
finally:
|
| 206 |
+
for f in [mid_file.name, wav_path]:
|
| 207 |
+
try:
|
| 208 |
+
os.remove(f)
|
| 209 |
+
except FileNotFoundError:
|
| 210 |
+
pass
|
| 211 |
+
|
| 212 |
+
# -----------------------------------------------------------------------------
|
| 213 |
+
# 8. Prompt engineering for variety (using integer durations)
|
| 214 |
+
# -----------------------------------------------------------------------------
|
| 215 |
+
def get_fallback_exercise(instrument: str, level: str, key: str,
|
| 216 |
+
time_sig: str, measures: int) -> str:
|
| 217 |
+
instrument_patterns = {
|
| 218 |
+
"Trumpet": ["C4", "D4", "E4", "G4", "E4", "C4"],
|
| 219 |
+
"Piano": ["C4", "E4", "G4", "C5", "G4", "E4"],
|
| 220 |
+
"Violin": ["G4", "A4", "B4", "D5", "B4", "G4"],
|
| 221 |
+
"Clarinet": ["E4", "F4", "G4", "Bb4", "G4", "E4"],
|
| 222 |
+
"Flute": ["A4", "B4", "C5", "E5", "C5", "A4"],
|
| 223 |
+
}
|
| 224 |
+
pattern = instrument_patterns.get(instrument, instrument_patterns["Trumpet"])
|
| 225 |
+
numerator, denominator = map(int, time_sig.split('/'))
|
| 226 |
+
units_per_measure = numerator * (16 // denominator)
|
| 227 |
+
target_units = measures * units_per_measure
|
| 228 |
+
notes, durs = [], []
|
| 229 |
+
i = 0
|
| 230 |
+
|
| 231 |
+
# Use quarter notes (4 units) as base duration
|
| 232 |
+
while len(notes) * 4 < target_units:
|
| 233 |
+
notes.append(pattern[i % len(pattern)])
|
| 234 |
+
durs.append(4)
|
| 235 |
+
i += 1
|
| 236 |
+
|
| 237 |
+
# Adjust last duration to match total exactly
|
| 238 |
+
total_units = len(durs) * 4
|
| 239 |
+
if total_units > target_units:
|
| 240 |
+
durs[-1] = 4 - (total_units - target_units)
|
| 241 |
+
|
| 242 |
+
return json.dumps([[n, d] for n, d in zip(notes, durs)])
|
| 243 |
+
|
| 244 |
+
def get_style_based_on_level(level: str) -> str:
|
| 245 |
+
styles = {
|
| 246 |
+
"Beginner": ["simple", "legato", "stepwise"],
|
| 247 |
+
"Intermediate": ["jazzy", "bluesy", "march-like", "syncopated"],
|
| 248 |
+
"Advanced": ["technical", "chromatic", "fast arpeggios", "wide intervals"],
|
| 249 |
+
}
|
| 250 |
+
return random.choice(styles.get(level, ["technical"]))
|
| 251 |
+
|
| 252 |
+
def get_technique_based_on_level(level: str) -> str:
|
| 253 |
+
techniques = {
|
| 254 |
+
"Beginner": ["with long tones", "with simple rhythms", "focusing on tone"],
|
| 255 |
+
"Intermediate": ["with slurs", "with accents", "using triplets"],
|
| 256 |
+
"Advanced": ["with double tonguing", "with extreme registers", "complex rhythms"],
|
| 257 |
+
}
|
| 258 |
+
return random.choice(techniques.get(level, ["with slurs"]))
|
| 259 |
+
|
| 260 |
+
# -----------------------------------------------------------------------------
|
| 261 |
+
# 9. Mistral API: query, fallback on errors (using integer durations)
|
| 262 |
+
# -----------------------------------------------------------------------------
|
| 263 |
+
def query_mistral(prompt: str, instrument: str, level: str, key: str,
|
| 264 |
+
time_sig: str, measures: int) -> str:
|
| 265 |
+
headers = {
|
| 266 |
+
"Authorization": f"Bearer {MISTRAL_API_KEY}",
|
| 267 |
+
"Content-Type": "application/json",
|
| 268 |
+
}
|
| 269 |
+
numerator, denominator = map(int, time_sig.split('/'))
|
| 270 |
+
units_per_measure = numerator * (16 // denominator)
|
| 271 |
+
required_total = measures * units_per_measure
|
| 272 |
+
|
| 273 |
+
duration_constraint = (
|
| 274 |
+
f"Sum of all durations MUST BE EXACTLY {required_total} units (16th notes). "
|
| 275 |
+
f"Each integer duration represents a 16th note (1=16th, 2=8th, 4=quarter, 8=half, 16=whole). "
|
| 276 |
+
f"If it doesn't match, the exercise is invalid."
|
| 277 |
+
)
|
| 278 |
+
system_prompt = (
|
| 279 |
+
f"You are an expert music teacher specializing in {instrument.lower()}. "
|
| 280 |
+
"Create customized exercises using INTEGER durations representing 16th notes."
|
| 281 |
+
)
|
| 282 |
+
|
| 283 |
+
if prompt.strip():
|
| 284 |
+
user_prompt = (
|
| 285 |
+
f"{prompt} {duration_constraint} Output ONLY a JSON array of [note, duration] pairs."
|
| 286 |
+
)
|
| 287 |
+
else:
|
| 288 |
+
style = get_style_based_on_level(level)
|
| 289 |
+
technique = get_technique_based_on_level(level)
|
| 290 |
+
user_prompt = (
|
| 291 |
+
f"Create a {style} {instrument.lower()} exercise in {key} with {time_sig} time signature "
|
| 292 |
+
f"{technique} for a {level.lower()} player. {duration_constraint} "
|
| 293 |
+
"Output ONLY a JSON array of [note, duration] pairs following these rules: "
|
| 294 |
+
"Use standard note names (e.g., \"Bb4\", \"F#5\"). Monophonic only. "
|
| 295 |
+
"Durations: 1=16th, 2=8th, 4=quarter, 8=half, 16=whole. "
|
| 296 |
+
"Sum must be exactly as specified. ONLY output the JSON array. No prose."
|
| 297 |
+
)
|
| 298 |
+
|
| 299 |
+
payload = {
|
| 300 |
+
"model": "mistral-medium",
|
| 301 |
+
"messages": [
|
| 302 |
+
{"role": "system", "content": system_prompt},
|
| 303 |
+
{"role": "user", "content": user_prompt},
|
| 304 |
+
],
|
| 305 |
+
"temperature": 0.7 if level == "Advanced" else 0.5,
|
| 306 |
+
"max_tokens": 1000,
|
| 307 |
+
"top_p": 0.95,
|
| 308 |
+
"frequency_penalty": 0.2,
|
| 309 |
+
"presence_penalty": 0.2,
|
| 310 |
+
}
|
| 311 |
+
|
| 312 |
+
try:
|
| 313 |
+
response = requests.post(MISTRAL_API_URL, headers=headers, json=payload)
|
| 314 |
+
response.raise_for_status()
|
| 315 |
+
content = response.json()["choices"][0]["message"]["content"]
|
| 316 |
+
return content.replace("```json","").replace("```","").strip()
|
| 317 |
+
except Exception as e:
|
| 318 |
+
print(f"Error querying Mistral API: {e}")
|
| 319 |
+
return get_fallback_exercise(instrument, level, key, time_sig, measures)
|
| 320 |
+
|
| 321 |
+
# -----------------------------------------------------------------------------
|
| 322 |
+
# 10. Robust JSON parsing for LLM outputs
|
| 323 |
+
# -----------------------------------------------------------------------------
|
| 324 |
+
def safe_parse_json(text: str) -> Optional[list]:
|
| 325 |
+
try:
|
| 326 |
+
text = text.replace("'", '"')
|
| 327 |
+
match = re.search(r"\[(\s*\[.*?\]\s*,?)*\]", text, re.DOTALL)
|
| 328 |
+
if match:
|
| 329 |
+
return json.loads(match.group(0))
|
| 330 |
+
return json.loads(text)
|
| 331 |
+
except Exception as e:
|
| 332 |
+
print(f"JSON parsing error: {e}\nRaw text: {text}")
|
| 333 |
+
return None
|
| 334 |
+
|
| 335 |
+
# -----------------------------------------------------------------------------
|
| 336 |
+
# 11. Main orchestration: talk to API, *scale durations*, build MIDI, UI values
|
| 337 |
+
# -----------------------------------------------------------------------------
|
| 338 |
+
def generate_exercise(instrument: str, level: str, key: str, tempo: int, time_signature: str,
|
| 339 |
+
measures: int, custom_prompt: str, mode: str) -> Tuple[str, Optional[str], str, MidiFile, str, str, int]:
|
| 340 |
+
try:
|
| 341 |
+
prompt_to_use = custom_prompt if mode == "Exercise Prompt" else ""
|
| 342 |
+
output = query_mistral(prompt_to_use, instrument, level, key, time_signature, measures)
|
| 343 |
+
parsed = safe_parse_json(output)
|
| 344 |
+
if not parsed:
|
| 345 |
+
return "Invalid JSON format", None, str(tempo), None, "0", time_signature, 0
|
| 346 |
+
|
| 347 |
+
# Calculate total required 16th notes
|
| 348 |
+
numerator, denominator = map(int, time_signature.split('/'))
|
| 349 |
+
units_per_measure = numerator * (16 // denominator)
|
| 350 |
+
total_units = measures * units_per_measure
|
| 351 |
+
|
| 352 |
+
# Strict scaling
|
| 353 |
+
parsed_scaled = scale_json_durations(parsed, total_units)
|
| 354 |
+
|
| 355 |
+
# Calculate total duration units
|
| 356 |
+
total_duration = sum(d for _, d in parsed_scaled)
|
| 357 |
+
|
| 358 |
+
# Generate MIDI and audio
|
| 359 |
+
midi = json_to_midi(parsed_scaled, instrument, tempo, time_signature, measures)
|
| 360 |
+
mp3_path, real_duration = midi_to_mp3(midi, instrument)
|
| 361 |
+
output_json_str = json.dumps(parsed_scaled, indent=2)
|
| 362 |
+
return output_json_str, mp3_path, str(tempo), midi, f"{real_duration:.2f} seconds", time_signature, total_duration
|
| 363 |
+
except Exception as e:
|
| 364 |
+
return f"Error: {str(e)}", None, str(tempo), None, "0", time_signature, 0
|
| 365 |
+
|
| 366 |
+
# -----------------------------------------------------------------------------
|
| 367 |
+
# 12. Simple AI chat assistant (optional, shares LLM)
|
| 368 |
+
# -----------------------------------------------------------------------------
|
| 369 |
+
def handle_chat(message: str, history: List, instrument: str, level: str):
|
| 370 |
+
if not message.strip():
|
| 371 |
+
return "", history
|
| 372 |
+
messages = [{"role": "system", "content": f"You are a {instrument} teacher for {level} students."}]
|
| 373 |
+
for user_msg, assistant_msg in history:
|
| 374 |
+
messages.append({"role": "user", "content": user_msg})
|
| 375 |
+
messages.append({"role": "assistant", "content": assistant_msg})
|
| 376 |
+
messages.append({"role": "user", "content": message})
|
| 377 |
+
headers = {"Authorization": f"Bearer {MISTRAL_API_KEY}", "Content-Type": "application/json"}
|
| 378 |
+
payload = {"model": "mistral-medium", "messages": messages, "temperature": 0.7, "max_tokens": 500}
|
| 379 |
+
try:
|
| 380 |
+
response = requests.post(MISTRAL_API_URL, headers=headers, json=payload)
|
| 381 |
+
response.raise_for_status()
|
| 382 |
+
content = response.json()["choices"][0]["message"]["content"]
|
| 383 |
+
history.append((message, content))
|
| 384 |
+
return "", history
|
| 385 |
+
except Exception as e:
|
| 386 |
+
history.append((message, f"Error: {str(e)}"))
|
| 387 |
+
return "", history
|
| 388 |
+
|
| 389 |
+
# -----------------------------------------------------------------------------
|
| 390 |
+
# 13. Gradio user interface definition (for humans!)
|
| 391 |
+
# -----------------------------------------------------------------------------
|
| 392 |
+
def create_ui() -> gr.Blocks:
|
| 393 |
+
with gr.Blocks(title="Adaptive Music Exercise Generator", theme="soft") as demo:
|
| 394 |
+
gr.Markdown("# 🎼 Adaptive Music Exercise Generator")
|
| 395 |
+
current_midi = gr.State(None)
|
| 396 |
+
current_exercise = gr.State("")
|
| 397 |
+
|
| 398 |
+
mode = gr.Radio(["Exercise Parameters","Exercise Prompt"], value="Exercise Parameters", label="Generation Mode")
|
| 399 |
+
with gr.Row():
|
| 400 |
+
with gr.Column(scale=1):
|
| 401 |
+
with gr.Group(visible=True) as params_group:
|
| 402 |
+
gr.Markdown("### Exercise Parameters")
|
| 403 |
+
instrument = gr.Dropdown([
|
| 404 |
+
"Trumpet", "Piano", "Violin", "Clarinet", "Flute",
|
| 405 |
+
], value="Trumpet", label="Instrument")
|
| 406 |
+
level = gr.Radio([
|
| 407 |
+
"Beginner", "Intermediate", "Advanced",
|
| 408 |
+
], value="Intermediate", label="Difficulty Level")
|
| 409 |
+
key = gr.Dropdown([
|
| 410 |
+
"C Major", "G Major", "D Major", "F Major", "Bb Major", "A Minor", "E Minor",
|
| 411 |
+
], value="C Major", label="Key Signature")
|
| 412 |
+
time_signature = gr.Dropdown(["3/4", "4/4"], value="4/4", label="Time Signature")
|
| 413 |
+
measures = gr.Radio([4, 8], value=4, label="Length (measures)")
|
| 414 |
+
with gr.Group(visible=False) as prompt_group:
|
| 415 |
+
gr.Markdown("### Exercise Prompt")
|
| 416 |
+
custom_prompt = gr.Textbox("", label="Enter your custom prompt", lines=3)
|
| 417 |
+
measures_prompt = gr.Radio([4, 8], value=4, label="Length (measures)")
|
| 418 |
+
generate_btn = gr.Button("Generate Exercise", variant="primary")
|
| 419 |
+
with gr.Column(scale=2):
|
| 420 |
+
with gr.Tabs():
|
| 421 |
+
with gr.TabItem("Exercise Player"):
|
| 422 |
+
audio_output = gr.Audio(label="Generated Exercise", autoplay=True, type="filepath")
|
| 423 |
+
bpm_display = gr.Textbox(label="Tempo (BPM)")
|
| 424 |
+
time_sig_display = gr.Textbox(label="Time Signature")
|
| 425 |
+
duration_display = gr.Textbox(label="Audio Duration", interactive=False)
|
| 426 |
+
with gr.TabItem("Exercise Data"):
|
| 427 |
+
json_output = gr.Code(label="JSON Representation", language="json")
|
| 428 |
+
# NEW: Duration sum display
|
| 429 |
+
duration_sum = gr.Number(
|
| 430 |
+
label="Total Duration Units (16th notes)",
|
| 431 |
+
interactive=False,
|
| 432 |
+
precision=0
|
| 433 |
+
)
|
| 434 |
+
with gr.TabItem("MIDI Export"):
|
| 435 |
+
midi_output = gr.File(label="MIDI File")
|
| 436 |
+
download_midi = gr.Button("Generate MIDI File")
|
| 437 |
+
with gr.TabItem("AI Chat"):
|
| 438 |
+
chat_history = gr.Chatbot(label="Practice Assistant", height=400)
|
| 439 |
+
chat_message = gr.Textbox(label="Ask the AI anything about your practice")
|
| 440 |
+
send_chat_btn = gr.Button("Send")
|
| 441 |
+
# Toggle UI groups
|
| 442 |
+
mode.change(
|
| 443 |
+
fn=lambda m: {
|
| 444 |
+
params_group: gr.update(visible=(m == "Exercise Parameters")),
|
| 445 |
+
prompt_group: gr.update(visible=(m == "Exercise Prompt")),
|
| 446 |
+
},
|
| 447 |
+
inputs=[mode], outputs=[params_group, prompt_group]
|
| 448 |
+
)
|
| 449 |
+
def generate_caller(mode_val, instrument_val, level_val, key_val,
|
| 450 |
+
time_sig_val, measures_val, prompt_val, measures_prompt_val):
|
| 451 |
+
real_measures = measures_prompt_val if mode_val == "Exercise Prompt" else measures_val
|
| 452 |
+
fixed_tempo = 60
|
| 453 |
+
return generate_exercise(
|
| 454 |
+
instrument_val, level_val, key_val, fixed_tempo, time_sig_val,
|
| 455 |
+
real_measures, prompt_val, mode_val
|
| 456 |
+
)
|
| 457 |
+
generate_btn.click(
|
| 458 |
+
fn=generate_caller,
|
| 459 |
+
inputs=[mode, instrument, level, key, time_signature,measures, custom_prompt, measures_prompt],
|
| 460 |
+
outputs=[json_output, audio_output, bpm_display, current_midi, duration_display, time_sig_display, duration_sum]
|
| 461 |
+
)
|
| 462 |
+
def save_midi(json_data, instr, time_sig):
|
| 463 |
+
parsed = safe_parse_json(json_data)
|
| 464 |
+
if not parsed:
|
| 465 |
+
return None
|
| 466 |
+
numerator, denominator = map(int, time_sig.split('/'))
|
| 467 |
+
units_per_measure = numerator * (16 // denominator)
|
| 468 |
+
total_units = sum(int(d[1]) for d in parsed)
|
| 469 |
+
measures_est = max(1, round(total_units / units_per_measure))
|
| 470 |
+
scaled = scale_json_durations(parsed, measures_est * units_per_measure)
|
| 471 |
+
midi_obj = json_to_midi(scaled, instr, 60, time_sig, measures_est)
|
| 472 |
+
midi_path = os.path.join("static", "exercise.mid")
|
| 473 |
+
midi_obj.save(midi_path)
|
| 474 |
+
return midi_path
|
| 475 |
+
download_midi.click(
|
| 476 |
+
fn=save_midi,
|
| 477 |
+
inputs=[json_output, instrument, time_signature],
|
| 478 |
+
outputs=[midi_output],
|
| 479 |
+
)
|
| 480 |
+
send_chat_btn.click(
|
| 481 |
+
fn=handle_chat,
|
| 482 |
+
inputs=[chat_message, chat_history, instrument, level],
|
| 483 |
+
outputs=[chat_message, chat_history],
|
| 484 |
+
)
|
| 485 |
+
return demo
|
| 486 |
+
|
| 487 |
+
# -----------------------------------------------------------------------------
|
| 488 |
+
# 14. Entry point
|
| 489 |
+
# -----------------------------------------------------------------------------
|
| 490 |
+
if __name__ == "__main__":
|
| 491 |
+
demo = create_ui()
|
| 492 |
+
demo.launch()
|
requirements.txt
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio==4.22.0
|
| 2 |
+
requests==2.31.0
|
| 3 |
+
mido==1.2.10
|
| 4 |
+
midi2audio==0.1.1
|
| 5 |
+
pydub==0.25.1
|
| 6 |
+
numpy==1.26.4
|
| 7 |
+
librosa==0.10.1
|
| 8 |
+
sounddevice==0.4.6
|
| 9 |
+
pyFluidSynth==1.3.2 # Alternative to fluidsynth
|