Delete app.py
Browse files
app.py
DELETED
|
@@ -1,850 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Melodimodell 67M – Hugging Face Space
|
| 3 |
-
|
| 4 |
-
Modellen arbetar på byte-nivå: varje token är en byte i UTF-8-texten, precis som när
|
| 5 |
-
du skickar "prompt": list(text.encode()) till llama-server. Här körs samma GGUF-fil
|
| 6 |
-
direkt i Space:t med llama-cpp-python, så ingen separat server behövs.
|
| 7 |
-
|
| 8 |
-
Notformat: [oktav][notnamn][volym][notlängd][tidstämpel], t.ex. 4G5d21
|
| 9 |
-
• varje rad = 1 sekund, tidstämpel 0–59 i steg om 1/60 s
|
| 10 |
-
• notnamn C I D J E F K G L A H B = C C# D D# E F F# G G# A A# B
|
| 11 |
-
• volym 0–10, notlängd a–i = 1, 2, 4 … 256 × 33 ms
|
| 12 |
-
• "*" skiljer låtar åt, så "*\n" betyder att en ny låt börjar
|
| 13 |
-
|
| 14 |
-
Miljövariabler (Settings → Variables and secrets i Space:t):
|
| 15 |
-
MODEL_REPO, MODEL_FILE vilken GGUF-fil som laddas ner
|
| 16 |
-
MODEL_PATH lokal GGUF-fil i stället för nedladdning
|
| 17 |
-
N_CTX kontextlängd (standard 8192, som -c 8192)
|
| 18 |
-
MAX_SECONDS tak för reglaget "Sekunder ny musik"
|
| 19 |
-
N_THREADS antal CPU-trådar (annars läses Space:ts CPU-kvot)
|
| 20 |
-
SOUNDFONT sökväg till en .sf2-fil för FluidSynth
|
| 21 |
-
"""
|
| 22 |
-
|
| 23 |
-
import codecs
|
| 24 |
-
import glob
|
| 25 |
-
import inspect
|
| 26 |
-
import os
|
| 27 |
-
import queue
|
| 28 |
-
import random
|
| 29 |
-
import re
|
| 30 |
-
import shutil
|
| 31 |
-
import subprocess
|
| 32 |
-
import tempfile
|
| 33 |
-
import threading
|
| 34 |
-
import time
|
| 35 |
-
import traceback
|
| 36 |
-
import wave
|
| 37 |
-
from collections import defaultdict
|
| 38 |
-
from functools import lru_cache
|
| 39 |
-
from pathlib import Path
|
| 40 |
-
from statistics import median
|
| 41 |
-
|
| 42 |
-
import gradio as gr
|
| 43 |
-
import mido
|
| 44 |
-
import numpy as np
|
| 45 |
-
from matplotlib.collections import PolyCollection
|
| 46 |
-
from matplotlib.figure import Figure
|
| 47 |
-
from matplotlib.patches import Patch
|
| 48 |
-
|
| 49 |
-
# ------------------------------------------------------------
|
| 50 |
-
# Modell och körning
|
| 51 |
-
# ------------------------------------------------------------
|
| 52 |
-
MODEL_REPO = os.environ.get("MODEL_REPO", "qwrt/Melodimodell-67M")
|
| 53 |
-
MODEL_FILE = os.environ.get("MODEL_FILE", "midi-67m-f16.gguf")
|
| 54 |
-
MODEL_PATH = os.environ.get("MODEL_PATH", "")
|
| 55 |
-
N_CTX = int(os.environ.get("N_CTX", "8192"))
|
| 56 |
-
MAX_SECONDS = int(os.environ.get("MAX_SECONDS", "120"))
|
| 57 |
-
KEEP_FRACTION = 0.5 # andel av kontexten som behålls när den blir full
|
| 58 |
-
|
| 59 |
-
# ------------------------------------------------------------
|
| 60 |
-
# Notformatet (samma konstanter som i dina konverteringsskript)
|
| 61 |
-
# ------------------------------------------------------------
|
| 62 |
-
STAMP_SPAN_MS = 1_000
|
| 63 |
-
TAKTER_PER_STAMP = 60
|
| 64 |
-
TACKT_MS = STAMP_SPAN_MS / TAKTER_PER_STAMP
|
| 65 |
-
BASE_DUR_MS = 33
|
| 66 |
-
VELOCITY_SCALE = 12.8
|
| 67 |
-
TEMPO_US_PER_BEAT = 500_000
|
| 68 |
-
TICKS_PER_BEAT = 480
|
| 69 |
-
|
| 70 |
-
NOTE_MAP = {
|
| 71 |
-
"C": 0, "I": 1, "D": 2, "J": 3, "E": 4, "F": 5,
|
| 72 |
-
"K": 6, "G": 7, "L": 8, "A": 9, "H": 10, "B": 11,
|
| 73 |
-
}
|
| 74 |
-
MIDI_TO_NOTE = {v: k for k, v in NOTE_MAP.items()}
|
| 75 |
-
DURATION_MAP = {"a": 1, "b": 2, "c": 4, "d": 8, "e": 16, "f": 32, "g": 64, "h": 128, "i": 256}
|
| 76 |
-
TOKEN_RE = re.compile(r"(\d+)([A-L])(\d+)([a-i])(\d+)")
|
| 77 |
-
|
| 78 |
-
# MIDI -> text, samma val som i convert_midi_to_custom_string.py
|
| 79 |
-
FILTER_DRUMS = True
|
| 80 |
-
FILTER_NON_PIANO = False
|
| 81 |
-
MAX_CHORD_NOTES = 10
|
| 82 |
-
MIN_VOLUME = 0
|
| 83 |
-
MAX_OCTAVE = 6
|
| 84 |
-
|
| 85 |
-
EXAMPLE_PROMPT = """*
|
| 86 |
-
4D4d0 4D4c18 4D4d27 4D4c45 4D4d54
|
| 87 |
-
4D4c12 4D4c21 4D4c30 4D4c39 4D4d48
|
| 88 |
-
4D4c6 4D4d15 4D4c33 4D4d42 4D4c59
|
| 89 |
-
4D4c9 4D4c18 4D4c27 4D4d36 2D4f36 1D4f36 4D4c54
|
| 90 |
-
4D4d3 4D4c21 4D4d30 4H4d30 2D4d30 1D4d30 4D4c48 4D4c57 4A4d57 2D4d57 1D4d57
|
| 91 |
-
3A4c6 4A4d10 4C4c15 4D4d24 3A4d24 3F4d24 3D4d24 2D4d24 4D4d42 3A4d42 3F4d42 3D4c42 2D4c42 3D4d51 2D4d51 4D4c59 3A4c59 3F4c59
|
| 92 |
-
4E4c9 4C4c9 3A4c9 3C4c9 2C4c9 4F4d18 4D4d18 3H4d18 2H4d18 1H4d18 4F4d36 4D4d36 3H4d36 2H4c36 1H4c36 2H4d45 1H4d45 4F4c54 4D4c54 3H4c54
|
| 93 |
-
4G4c3 4D4c3 2H4c3 1H4c3 4E4d12 4C4d12 3A4d12 2A4d12 1A4d12 4E4d30 4C4d30 3A4d30 2A4c30 1A4c30 2A4d39 1A4d39 4D4c48 3A4c48 4C4c57 3G4c57 2A4c57 1A4c57
|
| 94 |
-
4C4c6 3A4c6 3D4d6 2D4d6 4D4d15 3A4d15 3D4c24 2D4c24 3D4d33 2D4d33 3A4c42 4C4c51 3D4c51 2D4c51
|
| 95 |
-
4D4d0 3H4d0 3F4d0 2H4d0 1H4d0 4D4d18 3H4d18 3F4d18 2H4c18 1H4c18 2H4d27 1H4d27 4D4c36 3H4c36 4E4c45 3H4c45 2H4c45 1H4c45 4F4d54 4C4d54 3A4d54 2H4d54 1H4d54
|
| 96 |
-
4F4d12 4C4d12 3A4d12 2H4c12 1H4c12 2H4d21 1H4d21 4F4c30 4C4c30 4G4c39 4C4c39 2H4c39 1H4c39 4E4d48 4C4d48 3A4d48 2A4d48 1A4d48
|
| 97 |
-
4E4d6 4C4d6 3A4d6 2A4c6 1A4c6 2A4d15 1A4d15 4D4c24 3A4c24 4C4c33 3G4c33 2A4c33 1A4c33 4D4d42 3A4d42 3F4d42 3D4d42 2D4d42 3D4c59 2D4c59
|
| 98 |
-
3D4d9 2D4d9 3A4c18 4C4c27 3D4c27 2D4c27 4D4d36 3A4d36 3F4d36 3D4d36 2D4d36 4D4d54 3A4d54 3F4d54 3D4c54 2D4c54
|
| 99 |
-
3D4d3 2D4d3 4D4c12 3A4c12 4F4c21 3A4c21 3D4c21 2D4c21 4G4d30 4D4d30 3H4d30 2H4d30 1H4d30 4G4d48 4D4d48 3H4d48 2H4c48 1H4c48 2H4d57 1H4d57
|
| 100 |
-
4G4c6 4D4c6 4A4c15 4D4c15 2H4c15 1H4c15 4H4d24 4G4d24 4D4d24 2G4d24 1G4d24 4H4d42 4G4d42 4D4d42 2G4c42 1G4c42 2G4d51 1G4d51 4A4c59 4F4c59
|
| 101 |
-
4G4c9 4E4c9 2G4c9 1G4c9 4A4c18 4F4c18 3D4d18 2D4d18 4D4d27 3D4c36 2D4c36 3D4d45 2D4d45 4D4c54"""
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
# ------------------------------------------------------------
|
| 105 |
-
# Text -> noter -> MIDI
|
| 106 |
-
# ------------------------------------------------------------
|
| 107 |
-
def normalize_prompt(text):
|
| 108 |
-
"""Enhetliga radbrytningar, bara ASCII och ett mellanslag mellan tokens."""
|
| 109 |
-
text = (text or "").replace("\r\n", "\n").replace("\r", "\n")
|
| 110 |
-
text = text.encode("ascii", "ignore").decode("ascii")
|
| 111 |
-
text = "\n".join(" ".join(line.split()) for line in text.split("\n")).lstrip("\n")
|
| 112 |
-
return text if text.strip() else "*\n"
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
def parse_notes(text, prompt_len=0):
|
| 116 |
-
"""Tolkar texten som parse_custom gör, men hoppar över trasiga tokens i stället för att krascha.
|
| 117 |
-
|
| 118 |
-
Returnerar ([(start_ms, pitch, velocity, duration_ms, från_prompten)], antal_ogiltiga).
|
| 119 |
-
"""
|
| 120 |
-
text = text.replace("*", " ") # samma längd, så teckenpositionerna stämmer
|
| 121 |
-
pos = len(text) - len(text.lstrip()) # som .strip(): inledande tomrader räknas inte
|
| 122 |
-
events, invalid = [], 0
|
| 123 |
-
for stamp, line in enumerate(text[pos:].split("\n")):
|
| 124 |
-
for m in re.finditer(r"\S+", line):
|
| 125 |
-
tok = TOKEN_RE.fullmatch(m.group())
|
| 126 |
-
if not tok:
|
| 127 |
-
invalid += 1
|
| 128 |
-
continue
|
| 129 |
-
octave, letter, vol, dur, takt = tok.groups()
|
| 130 |
-
pitch = NOTE_MAP[letter] + (int(octave) + 1) * 12
|
| 131 |
-
velocity = min(127, int(round(int(vol) * VELOCITY_SCALE)))
|
| 132 |
-
if pitch > 127:
|
| 133 |
-
invalid += 1
|
| 134 |
-
continue
|
| 135 |
-
if velocity == 0: # volym 0 hörs inte
|
| 136 |
-
continue
|
| 137 |
-
start_ms = stamp * STAMP_SPAN_MS + int(takt) * TACKT_MS
|
| 138 |
-
events.append((start_ms, pitch, velocity, DURATION_MAP[dur] * BASE_DUR_MS,
|
| 139 |
-
pos + m.start() < prompt_len))
|
| 140 |
-
pos += len(line) + 1
|
| 141 |
-
return events, invalid
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
def build_midi(events, out_path):
|
| 145 |
-
"""Ett spår med piano. Överlappande noter på samma tangent kapas, så att en
|
| 146 |
-
note_off aldrig stänger av en senare not, och note_off kommer före note_on."""
|
| 147 |
-
per_pitch = defaultdict(list)
|
| 148 |
-
for start, pitch, velocity, duration, *_ in events:
|
| 149 |
-
per_pitch[pitch].append((start, start + duration, velocity))
|
| 150 |
-
|
| 151 |
-
messages = []
|
| 152 |
-
for pitch, notes in per_pitch.items():
|
| 153 |
-
notes.sort()
|
| 154 |
-
for i, (start, end, velocity) in enumerate(notes):
|
| 155 |
-
if i + 1 < len(notes):
|
| 156 |
-
end = min(end, notes[i + 1][0])
|
| 157 |
-
if end - start < 1: # samma tangent två gånger på samma tid
|
| 158 |
-
continue
|
| 159 |
-
messages.append((start, 1, pitch, velocity))
|
| 160 |
-
messages.append((end, 0, pitch, 0))
|
| 161 |
-
messages.sort(key=lambda m: (m[0], m[1]))
|
| 162 |
-
|
| 163 |
-
mid = mido.MidiFile(ticks_per_beat=TICKS_PER_BEAT)
|
| 164 |
-
track = mido.MidiTrack()
|
| 165 |
-
mid.tracks.append(track)
|
| 166 |
-
track.append(mido.MetaMessage("set_tempo", tempo=TEMPO_US_PER_BEAT, time=0))
|
| 167 |
-
track.append(mido.Message("program_change", program=0, time=0))
|
| 168 |
-
last_tick = 0
|
| 169 |
-
for ms, is_on, pitch, velocity in messages:
|
| 170 |
-
tick = int(round(mido.second2tick(ms / 1000, TICKS_PER_BEAT, TEMPO_US_PER_BEAT)))
|
| 171 |
-
track.append(mido.Message("note_on" if is_on else "note_off", note=pitch,
|
| 172 |
-
velocity=velocity, time=max(0, tick - last_tick)))
|
| 173 |
-
last_tick = max(last_tick, tick)
|
| 174 |
-
mid.save(str(out_path))
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
# ------------------------------------------------------------
|
| 178 |
-
# MIDI -> text (din convert_midi_to_custom_string, något förenklad)
|
| 179 |
-
# ------------------------------------------------------------
|
| 180 |
-
def midi_to_events(path):
|
| 181 |
-
"""MIDI -> [(start_ms, pitch, velocity, duration_ms)]. mido räknar om ticks till
|
| 182 |
-
sekunder och tar hänsyn till alla tempobyten."""
|
| 183 |
-
mid = mido.MidiFile(path, clip=True)
|
| 184 |
-
programs, active, events, now = {}, {}, [], 0.0
|
| 185 |
-
for msg in mid: # alla spår sammanslagna, msg.time = sekunder sedan förra meddelandet
|
| 186 |
-
now += msg.time
|
| 187 |
-
if msg.type == "program_change":
|
| 188 |
-
programs[msg.channel] = msg.program
|
| 189 |
-
continue
|
| 190 |
-
if msg.type not in ("note_on", "note_off"):
|
| 191 |
-
continue
|
| 192 |
-
if FILTER_DRUMS and msg.channel == 9:
|
| 193 |
-
continue
|
| 194 |
-
if FILTER_NON_PIANO and programs.get(msg.channel, 0) > 7:
|
| 195 |
-
continue
|
| 196 |
-
key = (msg.note, msg.channel)
|
| 197 |
-
if key in active: # note_off, eller ett nytt anslag på en tangent som redan låter
|
| 198 |
-
start, velocity = active.pop(key)
|
| 199 |
-
events.append((round(start * 1000, 3), msg.note, velocity, (now - start) * 1000))
|
| 200 |
-
if msg.type == "note_on" and msg.velocity > 0:
|
| 201 |
-
active[key] = (now, msg.velocity)
|
| 202 |
-
for (note, _), (start, velocity) in active.items():
|
| 203 |
-
events.append((round(start * 1000, 3), note, velocity, (now - start) * 1000))
|
| 204 |
-
# Avrundningen tar bort flyttalsbrus från summeringen ovan, annars kan en not
|
| 205 |
-
# på exakt 9000 ms hamna på 8999.9999 ms, alltså sista takten på raden innan.
|
| 206 |
-
return sorted(events, key=lambda e: e[0])
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
def remove_duplicate_notes(events):
|
| 210 |
-
best = {}
|
| 211 |
-
for ev in events:
|
| 212 |
-
key = (round(ev[0], 1), ev[1])
|
| 213 |
-
if key not in best or ev[2] > best[key][2]:
|
| 214 |
-
best[key] = ev
|
| 215 |
-
return sorted(best.values(), key=lambda e: e[0])
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
def filter_large_chords(events, max_simultaneous):
|
| 219 |
-
groups = defaultdict(list)
|
| 220 |
-
for ev in events:
|
| 221 |
-
groups[round(ev[0], 1)].append(ev)
|
| 222 |
-
kept = []
|
| 223 |
-
for group in groups.values():
|
| 224 |
-
if len(group) > max_simultaneous:
|
| 225 |
-
middle = median(e[1] for e in group)
|
| 226 |
-
group = sorted(group, key=lambda e: abs(e[1] - middle))[:max_simultaneous]
|
| 227 |
-
kept.extend(group)
|
| 228 |
-
return sorted(kept, key=lambda e: e[0])
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
def duration_to_letter(duration_ms):
|
| 232 |
-
units = duration_ms / BASE_DUR_MS
|
| 233 |
-
return min(DURATION_MAP, key=lambda letter: abs(units - DURATION_MAP[letter]))
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
def events_to_text(events):
|
| 237 |
-
stamps = defaultdict(list)
|
| 238 |
-
for start_ms, pitch, velocity, duration_ms in events:
|
| 239 |
-
octave = pitch // 12 - 1
|
| 240 |
-
volume = max(0, min(10, int(round(velocity / VELOCITY_SCALE))))
|
| 241 |
-
if octave < 0 or octave > MAX_OCTAVE or volume <= MIN_VOLUME:
|
| 242 |
-
continue
|
| 243 |
-
stamp = int(start_ms // STAMP_SPAN_MS)
|
| 244 |
-
takt = max(0, min(59, int(round((start_ms - stamp * STAMP_SPAN_MS) / TACKT_MS))))
|
| 245 |
-
token = f"{octave}{MIDI_TO_NOTE[pitch % 12]}{volume}{duration_to_letter(duration_ms)}{takt}"
|
| 246 |
-
if token not in stamps[stamp]:
|
| 247 |
-
stamps[stamp].append(token)
|
| 248 |
-
if not stamps:
|
| 249 |
-
return ""
|
| 250 |
-
return "\n".join(" ".join(stamps.get(i, [])) for i in range(max(stamps) + 1))
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
def midi_to_text(path):
|
| 254 |
-
events = remove_duplicate_notes(midi_to_events(path))
|
| 255 |
-
events = [e for e in events if e[1] >= 12] # negativ oktav bort
|
| 256 |
-
if MAX_CHORD_NOTES > 0:
|
| 257 |
-
events = filter_large_chords(events, MAX_CHORD_NOTES)
|
| 258 |
-
return events_to_text(events)
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
# ------------------------------------------------------------
|
| 262 |
-
# Ljud: FluidSynth om det finns (packages.txt), annars en enkel syntes
|
| 263 |
-
# ------------------------------------------------------------
|
| 264 |
-
AUDIO_SR = 22050
|
| 265 |
-
FLUIDSYNTH = shutil.which("fluidsynth")
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
def _find_soundfont():
|
| 269 |
-
candidates = [
|
| 270 |
-
os.environ.get("SOUNDFONT", ""),
|
| 271 |
-
"/usr/share/sounds/sf2/FluidR3_GM.sf2",
|
| 272 |
-
"/usr/share/soundfonts/FluidR3_GM.sf2",
|
| 273 |
-
"/usr/share/sounds/sf2/default-GM.sf2",
|
| 274 |
-
"/usr/share/soundfonts/default.sf2",
|
| 275 |
-
]
|
| 276 |
-
candidates += sorted(glob.glob("/usr/share/sounds/sf2/*.sf2"))
|
| 277 |
-
candidates += sorted(glob.glob("/usr/share/soundfonts/*.sf2"))
|
| 278 |
-
return next((p for p in candidates if p and os.path.isfile(p)), None)
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
SOUNDFONT = _find_soundfont()
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
def _render_fluidsynth(midi_path):
|
| 285 |
-
raw_path = Path(midi_path).with_suffix(".f32")
|
| 286 |
-
cmd = [FLUIDSYNTH, "-ni", "-g", "0.6", "-r", str(AUDIO_SR), "-T", "raw", "-O", "float",
|
| 287 |
-
"-F", str(raw_path), SOUNDFONT, str(midi_path)]
|
| 288 |
-
subprocess.run(cmd, check=True, timeout=300,
|
| 289 |
-
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
| 290 |
-
samples = np.fromfile(raw_path, dtype="<f4")
|
| 291 |
-
raw_path.unlink(missing_ok=True)
|
| 292 |
-
if samples.size < 2:
|
| 293 |
-
raise RuntimeError("FluidSynth gav inget ljud")
|
| 294 |
-
return samples[: samples.size // 2 * 2].reshape(-1, 2) # stereo
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
@lru_cache(maxsize=256)
|
| 298 |
-
def _piano_tone(pitch, duration_ms):
|
| 299 |
-
"""En enkel pianolik ton: några övertoner som klingar av, mjuk attack och släpp."""
|
| 300 |
-
f0 = 440.0 * 2 ** ((pitch - 69) / 12)
|
| 301 |
-
hold = duration_ms / 1000
|
| 302 |
-
n = int((hold + 0.3) * AUDIO_SR)
|
| 303 |
-
t = np.arange(n, dtype=np.float32) / AUDIO_SR
|
| 304 |
-
tau = float(np.clip(1.4 * (261.6 / f0) ** 0.5, 0.25, 3.0)) # mörka toner klingar längre
|
| 305 |
-
tone = np.zeros(n, dtype=np.float32)
|
| 306 |
-
for k, amp in enumerate((1.0, 0.5, 0.28, 0.14, 0.07), start=1):
|
| 307 |
-
if k * f0 >= AUDIO_SR / 2:
|
| 308 |
-
break
|
| 309 |
-
tone += amp * np.sin(2 * np.pi * k * f0 * t) * np.exp(-t * k / tau)
|
| 310 |
-
envelope = np.minimum(1.0, t / 0.005)
|
| 311 |
-
released = t > hold
|
| 312 |
-
envelope[released] *= np.exp(-(t[released] - hold) / 0.08)
|
| 313 |
-
return (tone * envelope).astype(np.float32)
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
def _render_simple(events):
|
| 317 |
-
end_s = max(e[0] + e[3] for e in events) / 1000 + 0.5
|
| 318 |
-
buf = np.zeros(int(end_s * AUDIO_SR) + 1, dtype=np.float32)
|
| 319 |
-
for start, pitch, velocity, duration, *_ in events:
|
| 320 |
-
tone = _piano_tone(pitch, int(duration))
|
| 321 |
-
i = int(start / 1000 * AUDIO_SR)
|
| 322 |
-
j = min(len(buf), i + len(tone))
|
| 323 |
-
buf[i:j] += tone[: j - i] * (velocity / 127)
|
| 324 |
-
return buf
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
def _write_wav(path, samples):
|
| 328 |
-
peak = float(np.max(np.abs(samples))) if samples.size else 0.0
|
| 329 |
-
if peak > 0:
|
| 330 |
-
samples = samples * (0.89 / peak)
|
| 331 |
-
pcm = (samples * 32767).astype("<i2")
|
| 332 |
-
with wave.open(str(path), "wb") as w:
|
| 333 |
-
w.setnchannels(1 if pcm.ndim == 1 else pcm.shape[1])
|
| 334 |
-
w.setsampwidth(2)
|
| 335 |
-
w.setframerate(AUDIO_SR)
|
| 336 |
-
w.writeframes(np.ascontiguousarray(pcm).tobytes())
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
def render_audio(midi_path, events, wav_path):
|
| 340 |
-
samples = None
|
| 341 |
-
if FLUIDSYNTH and SOUNDFONT:
|
| 342 |
-
try:
|
| 343 |
-
samples = _render_fluidsynth(midi_path)
|
| 344 |
-
except Exception:
|
| 345 |
-
traceback.print_exc()
|
| 346 |
-
if samples is None:
|
| 347 |
-
samples = _render_simple(events)
|
| 348 |
-
_write_wav(wav_path, samples)
|
| 349 |
-
return str(wav_path)
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
# ------------------------------------------------------------
|
| 353 |
-
# Pianorulle
|
| 354 |
-
# ------------------------------------------------------------
|
| 355 |
-
PROMPT_RGB = (0.55, 0.61, 0.71) # filtgrå: det du gav modellen
|
| 356 |
-
NEW_RGB = (0.91, 0.64, 0.24) # mässing: det modellen skrev
|
| 357 |
-
MUTED = "#8a8f98"
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
def piano_roll(events):
|
| 361 |
-
fig = Figure(figsize=(10, 3.8), dpi=110)
|
| 362 |
-
fig.patch.set_alpha(0)
|
| 363 |
-
ax = fig.add_subplot(111)
|
| 364 |
-
ax.set_facecolor((0, 0, 0, 0))
|
| 365 |
-
if not events:
|
| 366 |
-
ax.text(0.5, 0.5, "Inga noter att visa", ha="center", va="center",
|
| 367 |
-
color=MUTED, transform=ax.transAxes)
|
| 368 |
-
ax.set_axis_off()
|
| 369 |
-
return fig
|
| 370 |
-
|
| 371 |
-
verts, colors = [], []
|
| 372 |
-
for start, pitch, velocity, duration, from_prompt in events:
|
| 373 |
-
x0, x1 = start / 1000, (start + duration) / 1000
|
| 374 |
-
verts.append(((x0, pitch - 0.42), (x1, pitch - 0.42), (x1, pitch + 0.42), (x0, pitch + 0.42)))
|
| 375 |
-
colors.append((*(PROMPT_RGB if from_prompt else NEW_RGB), 0.35 + 0.65 * velocity / 127))
|
| 376 |
-
ax.add_collection(PolyCollection(verts, facecolors=colors, edgecolors="none"))
|
| 377 |
-
|
| 378 |
-
low = min(e[1] for e in events) - 2
|
| 379 |
-
high = max(e[1] for e in events) + 2
|
| 380 |
-
ax.set_xlim(0, max(1.0, max(e[0] + e[3] for e in events) / 1000))
|
| 381 |
-
ax.set_ylim(low, high)
|
| 382 |
-
c_notes = [p for p in range(low, high + 1) if p % 12 == 0]
|
| 383 |
-
ax.set_yticks(c_notes)
|
| 384 |
-
ax.set_yticklabels([f"{p // 12 - 1}C" for p in c_notes]) # samma skrivsätt som formatet
|
| 385 |
-
ax.set_xlabel("Sekunder", color=MUTED)
|
| 386 |
-
ax.tick_params(colors=MUTED, labelsize=8)
|
| 387 |
-
for side, spine in ax.spines.items():
|
| 388 |
-
spine.set_visible(side == "bottom")
|
| 389 |
-
spine.set_color(MUTED)
|
| 390 |
-
ax.grid(axis="y", color=MUTED, alpha=0.15, linewidth=0.6)
|
| 391 |
-
|
| 392 |
-
new_starts = [e[0] for e in events if not e[4]]
|
| 393 |
-
handles = []
|
| 394 |
-
if len(new_starts) < len(events):
|
| 395 |
-
handles.append(Patch(color=PROMPT_RGB, label="Prompt"))
|
| 396 |
-
if new_starts:
|
| 397 |
-
handles.append(Patch(color=NEW_RGB, label="Ny musik"))
|
| 398 |
-
if len(new_starts) < len(events):
|
| 399 |
-
ax.axvline(min(new_starts) / 1000, color=MUTED, linewidth=1, linestyle=(0, (3, 3)))
|
| 400 |
-
ax.legend(handles=handles, loc="upper right", frameon=False, fontsize=8, labelcolor=MUTED)
|
| 401 |
-
fig.subplots_adjust(left=0.06, right=0.99, top=0.96, bottom=0.14)
|
| 402 |
-
return fig
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
# ------------------------------------------------------------
|
| 406 |
-
# Modellen
|
| 407 |
-
# ------------------------------------------------------------
|
| 408 |
-
def _cpu_count():
|
| 409 |
-
"""Antal kärnor Space:t faktiskt får (os.cpu_count() visar hela värddatorn)."""
|
| 410 |
-
if os.environ.get("N_THREADS"):
|
| 411 |
-
return max(1, int(os.environ["N_THREADS"]))
|
| 412 |
-
try: # cgroup v2
|
| 413 |
-
quota, period = Path("/sys/fs/cgroup/cpu.max").read_text().split()[:2]
|
| 414 |
-
if quota != "max":
|
| 415 |
-
return max(1, round(int(quota) / int(period)))
|
| 416 |
-
except (OSError, ValueError):
|
| 417 |
-
pass
|
| 418 |
-
try: # cgroup v1
|
| 419 |
-
quota = int(Path("/sys/fs/cgroup/cpu/cpu.cfs_quota_us").read_text())
|
| 420 |
-
period = int(Path("/sys/fs/cgroup/cpu/cpu.cfs_period_us").read_text())
|
| 421 |
-
if quota > 0 and period > 0:
|
| 422 |
-
return max(1, round(quota / period))
|
| 423 |
-
except (OSError, ValueError):
|
| 424 |
-
pass
|
| 425 |
-
try:
|
| 426 |
-
return max(1, len(os.sched_getaffinity(0)))
|
| 427 |
-
except AttributeError:
|
| 428 |
-
return max(1, os.cpu_count() or 1)
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
def load_model():
|
| 432 |
-
from llama_cpp import Llama
|
| 433 |
-
|
| 434 |
-
path = MODEL_PATH
|
| 435 |
-
if not path:
|
| 436 |
-
from huggingface_hub import hf_hub_download
|
| 437 |
-
|
| 438 |
-
path = hf_hub_download(repo_id=MODEL_REPO, filename=MODEL_FILE)
|
| 439 |
-
threads = _cpu_count()
|
| 440 |
-
print(f"Laddar {path} med n_ctx={N_CTX} och {threads} trådar", flush=True)
|
| 441 |
-
return Llama(model_path=path, n_ctx=N_CTX, n_batch=512, n_threads=threads,
|
| 442 |
-
n_threads_batch=threads, verbose=os.environ.get("LLAMA_VERBOSE") == "1")
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
LLM, LOAD_ERROR = None, ""
|
| 446 |
-
try:
|
| 447 |
-
LLM = load_model()
|
| 448 |
-
except Exception as exc: # visa felet i gränssnittet i stället för att krascha
|
| 449 |
-
LOAD_ERROR = f"{type(exc).__name__}: {exc}"
|
| 450 |
-
traceback.print_exc()
|
| 451 |
-
CTX_LIMIT = LLM.n_ctx() if LLM is not None else N_CTX
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
# ------------------------------------------------------------
|
| 455 |
-
# Generering. All kontakt med modellen sker i en och samma tråd; Gradio-
|
| 456 |
-
# funktionen läser bara tokens från en kö och uppdaterar gränssnittet.
|
| 457 |
-
# ------------------------------------------------------------
|
| 458 |
-
JOBS = queue.Queue()
|
| 459 |
-
_SESSION_STOPS = {} # session -> stop-event för Stoppa-knappen
|
| 460 |
-
_LATEST = {"stop": None} # stop-event för det senast startade jobbet
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
def _slide(ctx):
|
| 464 |
-
"""Behåll slutet av kontexten och börja helst vid en ny rad (= hel sekund)."""
|
| 465 |
-
keep = max(1, int(CTX_LIMIT * KEEP_FRACTION))
|
| 466 |
-
if len(ctx) <= keep:
|
| 467 |
-
return ctx
|
| 468 |
-
tail = ctx[-keep:]
|
| 469 |
-
for sep in (10, 32): # "\n", annars " "
|
| 470 |
-
if sep in tail:
|
| 471 |
-
return tail[tail.index(sep) + 1:]
|
| 472 |
-
return tail
|
| 473 |
-
|
| 474 |
-
|
| 475 |
-
def _run_job(prompt, opts, out_q, stop_ev):
|
| 476 |
-
reason = "eos"
|
| 477 |
-
try:
|
| 478 |
-
if stop_ev.is_set():
|
| 479 |
-
reason = "stopped"
|
| 480 |
-
return
|
| 481 |
-
out_q.put(("started", None))
|
| 482 |
-
ctx = list(prompt.encode("utf-8")) # samma som "prompt": list(text.encode())
|
| 483 |
-
if len(ctx) > CTX_LIMIT - 256:
|
| 484 |
-
ctx = _slide(ctx)
|
| 485 |
-
# Slutar prompten mitt på en rad avslutar det första "\n" bara den raden.
|
| 486 |
-
newlines_left = opts["seconds"] + (0 if prompt.endswith("\n") else 1)
|
| 487 |
-
eos = LLM.token_eos()
|
| 488 |
-
window = 0
|
| 489 |
-
while True:
|
| 490 |
-
LLM.set_seed((opts["seed"] + window) % 0xFFFFFFFF)
|
| 491 |
-
window += 1
|
| 492 |
-
stream = LLM.generate(
|
| 493 |
-
list(ctx), # kopia: ctx byggs på nedan medan generatorn körs
|
| 494 |
-
temp=opts["temperature"],
|
| 495 |
-
top_k=opts["top_k"],
|
| 496 |
-
top_p=opts["top_p"],
|
| 497 |
-
min_p=opts["min_p"],
|
| 498 |
-
repeat_penalty=opts["repeat_penalty"],
|
| 499 |
-
)
|
| 500 |
-
context_full = False
|
| 501 |
-
try:
|
| 502 |
-
for tok in stream:
|
| 503 |
-
if stop_ev.is_set():
|
| 504 |
-
reason = "stopped"
|
| 505 |
-
return
|
| 506 |
-
if tok == eos or not 0 <= tok < 256:
|
| 507 |
-
reason = "eos"
|
| 508 |
-
return
|
| 509 |
-
if tok == 42 and opts["stop_at_star"]: # "*": nästa låt börjar
|
| 510 |
-
reason = "star"
|
| 511 |
-
return
|
| 512 |
-
ctx.append(tok)
|
| 513 |
-
out_q.put(("tok", tok))
|
| 514 |
-
if tok == 10:
|
| 515 |
-
newlines_left -= 1
|
| 516 |
-
if newlines_left <= 0:
|
| 517 |
-
reason = "done"
|
| 518 |
-
return
|
| 519 |
-
if len(ctx) >= CTX_LIMIT:
|
| 520 |
-
context_full = True
|
| 521 |
-
break
|
| 522 |
-
finally:
|
| 523 |
-
stream.close()
|
| 524 |
-
if not context_full:
|
| 525 |
-
return
|
| 526 |
-
# Kontexten är full: modellen får se slutet och skriver vidare.
|
| 527 |
-
# Hela texten finns ändå kvar hos Gradio-funktionen.
|
| 528 |
-
ctx = _slide(ctx)
|
| 529 |
-
out_q.put(("slide", None))
|
| 530 |
-
except Exception as exc:
|
| 531 |
-
traceback.print_exc()
|
| 532 |
-
reason = "error"
|
| 533 |
-
out_q.put(("error", f"{type(exc).__name__}: {exc}"))
|
| 534 |
-
finally:
|
| 535 |
-
out_q.put(("done", reason))
|
| 536 |
-
|
| 537 |
-
|
| 538 |
-
def _model_loop():
|
| 539 |
-
while True:
|
| 540 |
-
_run_job(*JOBS.get())
|
| 541 |
-
|
| 542 |
-
|
| 543 |
-
threading.Thread(target=_model_loop, name="llm", daemon=True).start()
|
| 544 |
-
|
| 545 |
-
OUT_ROOT = Path(tempfile.gettempdir()) / "melodimodell"
|
| 546 |
-
|
| 547 |
-
|
| 548 |
-
def _new_output_dir():
|
| 549 |
-
OUT_ROOT.mkdir(parents=True, exist_ok=True)
|
| 550 |
-
now = time.time()
|
| 551 |
-
for old in OUT_ROOT.iterdir(): # städa bort resultat äldre än en timme
|
| 552 |
-
try:
|
| 553 |
-
if now - old.stat().st_mtime > 3600:
|
| 554 |
-
shutil.rmtree(old, ignore_errors=True)
|
| 555 |
-
except OSError:
|
| 556 |
-
pass
|
| 557 |
-
return Path(tempfile.mkdtemp(dir=OUT_ROOT))
|
| 558 |
-
|
| 559 |
-
|
| 560 |
-
def _session_key(request):
|
| 561 |
-
return getattr(request, "session_hash", None) or "anon"
|
| 562 |
-
|
| 563 |
-
|
| 564 |
-
def _new_seconds(gen_text, prompt):
|
| 565 |
-
return max(0, gen_text.count("\n") - (0 if prompt.endswith("\n") else 1))
|
| 566 |
-
|
| 567 |
-
|
| 568 |
-
def _drop_partial_token(text):
|
| 569 |
-
"""Tar bort en ev. halvskriven not i slutet."""
|
| 570 |
-
if not text or text[-1] in " \n":
|
| 571 |
-
return text
|
| 572 |
-
return text[: max(text.rfind(" "), text.rfind("\n")) + 1]
|
| 573 |
-
|
| 574 |
-
|
| 575 |
-
FINAL_TEXT = {
|
| 576 |
-
"done": "Klart.",
|
| 577 |
-
"star": "Klart. Modellen avslutade låten.",
|
| 578 |
-
"eos": "Klart. Modellen slutade skriva.",
|
| 579 |
-
"stopped": "Stoppad.",
|
| 580 |
-
}
|
| 581 |
-
|
| 582 |
-
|
| 583 |
-
def generate_music(prompt, seconds, temperature, top_k, top_p, min_p,
|
| 584 |
-
repeat_penalty, seed, stop_at_star, request: gr.Request = None):
|
| 585 |
-
if LLM is None:
|
| 586 |
-
yield (prompt, f"Modellen kunde inte laddas ({LOAD_ERROR}). Läs loggen under Logs.",
|
| 587 |
-
None, None, None)
|
| 588 |
-
return
|
| 589 |
-
|
| 590 |
-
prompt = normalize_prompt(prompt)
|
| 591 |
-
try:
|
| 592 |
-
seed = int(seed)
|
| 593 |
-
except (TypeError, ValueError):
|
| 594 |
-
seed = -1
|
| 595 |
-
if seed < 0:
|
| 596 |
-
seed = random.randint(0, 2**31 - 1)
|
| 597 |
-
opts = {
|
| 598 |
-
"seconds": int(seconds),
|
| 599 |
-
"temperature": float(temperature),
|
| 600 |
-
"top_k": int(top_k),
|
| 601 |
-
"top_p": float(top_p),
|
| 602 |
-
"min_p": float(min_p),
|
| 603 |
-
"repeat_penalty": float(repeat_penalty),
|
| 604 |
-
"seed": seed,
|
| 605 |
-
"stop_at_star": bool(stop_at_star),
|
| 606 |
-
}
|
| 607 |
-
|
| 608 |
-
# Gradio kör bara en generering åt gången (concurrency_limit=1). Hänger ett
|
| 609 |
-
# gammalt jobb kvar, t.ex. från en flik som stängdes mitt i, avbryts det här.
|
| 610 |
-
if _LATEST["stop"] is not None:
|
| 611 |
-
_LATEST["stop"].set()
|
| 612 |
-
stop_ev = threading.Event()
|
| 613 |
-
_LATEST["stop"] = stop_ev
|
| 614 |
-
key = _session_key(request)
|
| 615 |
-
_SESSION_STOPS[key] = stop_ev
|
| 616 |
-
|
| 617 |
-
out_q = queue.Queue()
|
| 618 |
-
JOBS.put((prompt, opts, out_q, stop_ev))
|
| 619 |
-
|
| 620 |
-
decoder = codecs.getincrementaldecoder("utf-8")(errors="replace")
|
| 621 |
-
pieces, reason, error, slides = [], None, "", 0
|
| 622 |
-
t_start, last_ui = None, 0.0
|
| 623 |
-
try:
|
| 624 |
-
yield prompt, "Väntar på modellen …", None, None, None
|
| 625 |
-
while reason is None:
|
| 626 |
-
items = []
|
| 627 |
-
try:
|
| 628 |
-
items.append(out_q.get(timeout=0.25))
|
| 629 |
-
while True:
|
| 630 |
-
items.append(out_q.get_nowait())
|
| 631 |
-
except queue.Empty:
|
| 632 |
-
pass
|
| 633 |
-
for kind, value in items:
|
| 634 |
-
if kind == "tok":
|
| 635 |
-
pieces.append(decoder.decode(bytes([value])))
|
| 636 |
-
elif kind == "started":
|
| 637 |
-
t_start = time.time()
|
| 638 |
-
elif kind == "slide":
|
| 639 |
-
slides += 1
|
| 640 |
-
elif kind == "error":
|
| 641 |
-
error = value
|
| 642 |
-
elif kind == "done":
|
| 643 |
-
reason = value
|
| 644 |
-
if reason is None and t_start is not None and time.time() - last_ui > 0.3:
|
| 645 |
-
last_ui = time.time()
|
| 646 |
-
gen_text = "".join(pieces)
|
| 647 |
-
rate = len(gen_text) / max(1e-6, last_ui - t_start)
|
| 648 |
-
yield (prompt + gen_text,
|
| 649 |
-
f"Genererar … {_new_seconds(gen_text, prompt)} av {opts['seconds']} s "
|
| 650 |
-
f"ny musik ({rate:.0f} tecken per sekund).",
|
| 651 |
-
None, None, None)
|
| 652 |
-
finally:
|
| 653 |
-
stop_ev.set()
|
| 654 |
-
if _SESSION_STOPS.get(key) is stop_ev:
|
| 655 |
-
del _SESSION_STOPS[key]
|
| 656 |
-
|
| 657 |
-
elapsed = time.time() - (t_start or time.time())
|
| 658 |
-
gen_text = "".join(pieces)
|
| 659 |
-
if reason != "done":
|
| 660 |
-
gen_text = _drop_partial_token(gen_text)
|
| 661 |
-
full_text = prompt + gen_text
|
| 662 |
-
print(f"[generering] seed={seed} orsak={reason} nya_tecken={len(gen_text)} "
|
| 663 |
-
f"tid={elapsed:.1f}s fönsterflytt={slides}", flush=True)
|
| 664 |
-
|
| 665 |
-
head = f"Fel under genereringen: {error}." if reason == "error" else FINAL_TEXT.get(reason, "Klart.")
|
| 666 |
-
try:
|
| 667 |
-
events, invalid = parse_notes(full_text, prompt_len=len(prompt))
|
| 668 |
-
out_dir = _new_output_dir()
|
| 669 |
-
stem = f"melodi-seed{seed}"
|
| 670 |
-
txt_path = out_dir / f"{stem}.txt"
|
| 671 |
-
txt_path.write_text(full_text, encoding="utf-8")
|
| 672 |
-
files, audio_path = [str(txt_path)], None
|
| 673 |
-
if events:
|
| 674 |
-
midi_path = out_dir / f"{stem}.mid"
|
| 675 |
-
build_midi(events, midi_path)
|
| 676 |
-
files.insert(0, str(midi_path))
|
| 677 |
-
try:
|
| 678 |
-
audio_path = render_audio(midi_path, events, out_dir / f"{stem}.wav")
|
| 679 |
-
except Exception:
|
| 680 |
-
traceback.print_exc()
|
| 681 |
-
total_s = max((e[0] + e[3] for e in events), default=0) / 1000
|
| 682 |
-
parts = [head, f"{_new_seconds(gen_text, prompt)} s ny musik på {elapsed:.0f} s. "
|
| 683 |
-
f"Hela låten är {total_s:.0f} s lång med {len(events)} noter. Seed {seed}."]
|
| 684 |
-
if slides:
|
| 685 |
-
parts.append(f"Kontexten blev full och flyttades fram {slides} "
|
| 686 |
-
f"{'gång' if slides == 1 else 'gånger'}.")
|
| 687 |
-
if invalid:
|
| 688 |
-
parts.append(f"{invalid} ogiltiga tokens hoppades över.")
|
| 689 |
-
yield full_text, " ".join(parts), audio_path, piano_roll(events), files
|
| 690 |
-
except Exception as exc:
|
| 691 |
-
traceback.print_exc()
|
| 692 |
-
yield full_text, f"{head} Kunde inte skapa MIDI eller ljud: {type(exc).__name__}: {exc}", None, None, None
|
| 693 |
-
|
| 694 |
-
|
| 695 |
-
def stop_generation(request: gr.Request = None):
|
| 696 |
-
stop_ev = _SESSION_STOPS.get(_session_key(request))
|
| 697 |
-
if stop_ev is not None:
|
| 698 |
-
stop_ev.set()
|
| 699 |
-
|
| 700 |
-
|
| 701 |
-
def use_result_as_prompt(result, prompt):
|
| 702 |
-
return result if (result or "").strip() else prompt
|
| 703 |
-
|
| 704 |
-
|
| 705 |
-
def midi_to_prompt(midi_file, seconds, prompt, status):
|
| 706 |
-
path = midi_file if isinstance(midi_file, str) else getattr(midi_file, "name", None)
|
| 707 |
-
if not path:
|
| 708 |
-
return prompt, status
|
| 709 |
-
try:
|
| 710 |
-
text = midi_to_text(path)
|
| 711 |
-
except Exception as exc:
|
| 712 |
-
raise gr.Error(f"Kunde inte läsa MIDI-filen ({type(exc).__name__}: {exc}). Prova en annan fil.")
|
| 713 |
-
lines = text.split("\n")
|
| 714 |
-
first = next((i for i, line in enumerate(lines) if line.strip()), None)
|
| 715 |
-
if first is None:
|
| 716 |
-
raise gr.Error("Hittade inga noter att använda. Trummor och toner över oktav 6 tas bort.")
|
| 717 |
-
chunk = lines[first:first + int(seconds)]
|
| 718 |
-
new_prompt = "*\n" + "\n".join(chunk) + "\n"
|
| 719 |
-
notes = sum(len(line.split()) for line in chunk)
|
| 720 |
-
message = (f"Prompten är de första {len(chunk)} sekunderna av {Path(path).name}: "
|
| 721 |
-
f"{notes} noter, {len(new_prompt)} tecken.")
|
| 722 |
-
if len(new_prompt) > CTX_LIMIT - 256:
|
| 723 |
-
message += " Den är längre än modellens kontext, så modellen ser bara slutet av den."
|
| 724 |
-
return new_prompt, message
|
| 725 |
-
|
| 726 |
-
|
| 727 |
-
# ------------------------------------------------------------
|
| 728 |
-
# Gränssnitt
|
| 729 |
-
# ------------------------------------------------------------
|
| 730 |
-
HEADER_MD = """
|
| 731 |
-
# Melodimodell 67M
|
| 732 |
-
En liten språkmodell som skriver musik som text, ett tecken i taget. Ge den en början och lyssna
|
| 733 |
-
på hur den fortsätter. Du kan skriva själv, ladda upp en MIDI-fil eller börja från noll.
|
| 734 |
-
"""
|
| 735 |
-
|
| 736 |
-
FORMAT_MD = """
|
| 737 |
-
Varje rad är en sekund. En not skrivs som `[oktav][not][volym][längd][tid]`, till exempel `4G5d21`:
|
| 738 |
-
|
| 739 |
-
| Del | Värden | I `4G5d21` |
|
| 740 |
-
|---|---|---|
|
| 741 |
-
| Oktav | 0–6, där `4C` är mittens C | `4` |
|
| 742 |
-
| Not | `C I D J E F K G L A H B` = C, C♯, D, D♯, E, F, F♯, G, G♯, A, A♯, B | `G` |
|
| 743 |
-
| Volym | 1–10 | `5` |
|
| 744 |
-
| Längd | `a`–`i` = 1, 2, 4 … 256 × 33 ms | `d` = 264 ms |
|
| 745 |
-
| Tid | 0–59, var i sekunden noten börjar, i steg om 1/60 s | `21` = 350 ms |
|
| 746 |
-
|
| 747 |
-
En rad med bara `*` betyder att en ny låt börjar. Därför börjar prompten med `*`.
|
| 748 |
-
"""
|
| 749 |
-
|
| 750 |
-
THEME = gr.themes.Soft(
|
| 751 |
-
primary_hue=gr.themes.colors.amber,
|
| 752 |
-
neutral_hue=gr.themes.colors.slate,
|
| 753 |
-
font=[gr.themes.GoogleFont("Instrument Sans"), "ui-sans-serif", "system-ui", "sans-serif"],
|
| 754 |
-
font_mono=[gr.themes.GoogleFont("JetBrains Mono"), "ui-monospace", "monospace"],
|
| 755 |
-
)
|
| 756 |
-
|
| 757 |
-
CSS = """
|
| 758 |
-
#prompt textarea, #result textarea {
|
| 759 |
-
font-family: var(--font-mono);
|
| 760 |
-
font-size: 13px;
|
| 761 |
-
line-height: 1.6;
|
| 762 |
-
}
|
| 763 |
-
"""
|
| 764 |
-
|
| 765 |
-
|
| 766 |
-
def _split_style_kwargs(**style):
|
| 767 |
-
"""Beroende på Gradio-version tas title/theme/css emot av gr.Blocks() eller av launch()."""
|
| 768 |
-
blocks_params = inspect.signature(gr.Blocks.__init__).parameters
|
| 769 |
-
launch_params = inspect.signature(gr.Blocks.launch).parameters
|
| 770 |
-
blocks_kw = {k: v for k, v in style.items() if k in blocks_params}
|
| 771 |
-
launch_kw = {k: v for k, v in style.items() if k not in blocks_kw and k in launch_params}
|
| 772 |
-
return blocks_kw, launch_kw
|
| 773 |
-
|
| 774 |
-
|
| 775 |
-
BLOCKS_KW, LAUNCH_KW = _split_style_kwargs(title="Melodimodell 67M", theme=THEME, css=CSS)
|
| 776 |
-
|
| 777 |
-
with gr.Blocks(**BLOCKS_KW) as demo:
|
| 778 |
-
gr.Markdown(HEADER_MD)
|
| 779 |
-
if LOAD_ERROR:
|
| 780 |
-
gr.Markdown(f"**Modellen kunde inte laddas:** `{LOAD_ERROR}`. "
|
| 781 |
-
"Kontrollera MODEL_REPO och MODEL_FILE och läs loggen under Logs.")
|
| 782 |
-
|
| 783 |
-
with gr.Row(equal_height=False):
|
| 784 |
-
with gr.Column(scale=5):
|
| 785 |
-
prompt_box = gr.Textbox(
|
| 786 |
-
label="Början på låten",
|
| 787 |
-
info="Modellen fortsätter där texten slutar. En rad är en sekund.",
|
| 788 |
-
value=EXAMPLE_PROMPT, lines=12, max_lines=12, elem_id="prompt",
|
| 789 |
-
)
|
| 790 |
-
with gr.Row():
|
| 791 |
-
example_btn = gr.Button("Ladda exemplet", size="sm")
|
| 792 |
-
scratch_btn = gr.Button("Börja från noll", size="sm")
|
| 793 |
-
with gr.Accordion("Börja från en MIDI-fil", open=False):
|
| 794 |
-
midi_in = gr.File(label="MIDI-fil", file_types=[".mid", ".midi"], type="filepath")
|
| 795 |
-
midi_secs = gr.Slider(minimum=1, maximum=60, value=10, step=1,
|
| 796 |
-
label="Sekunder från filen")
|
| 797 |
-
seconds_in = gr.Slider(minimum=5, maximum=MAX_SECONDS, value=30, step=5,
|
| 798 |
-
label="Sekunder ny musik")
|
| 799 |
-
with gr.Accordion("Sampling", open=False):
|
| 800 |
-
temperature_in = gr.Slider(minimum=0.1, maximum=1.5, value=0.9, step=0.05,
|
| 801 |
-
label="Temperatur")
|
| 802 |
-
with gr.Row():
|
| 803 |
-
top_k_in = gr.Slider(minimum=0, maximum=64, value=0, step=1,
|
| 804 |
-
label="top_k", info="0 = av")
|
| 805 |
-
top_p_in = gr.Slider(minimum=0.1, maximum=1.0, value=1.0, step=0.01,
|
| 806 |
-
label="top_p")
|
| 807 |
-
with gr.Row():
|
| 808 |
-
min_p_in = gr.Slider(minimum=0.0, maximum=0.5, value=0.0, step=0.01,
|
| 809 |
-
label="min_p")
|
| 810 |
-
repeat_in = gr.Slider(minimum=1.0, maximum=1.3, value=1.0, step=0.01,
|
| 811 |
-
label="repeat_penalty")
|
| 812 |
-
with gr.Row():
|
| 813 |
-
seed_in = gr.Number(value=-1, precision=0, label="Seed",
|
| 814 |
-
info="-1 ger en ny slumpad seed varje gång")
|
| 815 |
-
star_in = gr.Checkbox(value=True, label="Sluta när låten tar slut (*)")
|
| 816 |
-
with gr.Row():
|
| 817 |
-
gen_btn = gr.Button("Generera musik", variant="primary")
|
| 818 |
-
stop_btn = gr.Button("Stoppa", variant="stop")
|
| 819 |
-
|
| 820 |
-
with gr.Column(scale=6):
|
| 821 |
-
status_box = gr.Textbox(label="Status", interactive=False, lines=2, max_lines=4)
|
| 822 |
-
audio_out = gr.Audio(label="Ljud", type="filepath", interactive=False)
|
| 823 |
-
roll_out = gr.Plot(label="Pianorulle")
|
| 824 |
-
files_out = gr.File(label="MIDI och text", file_count="multiple", interactive=False)
|
| 825 |
-
result_box = gr.Textbox(label="Resultat", lines=12, max_lines=12,
|
| 826 |
-
interactive=False, elem_id="result")
|
| 827 |
-
continue_btn = gr.Button("Fortsätt från resultatet")
|
| 828 |
-
|
| 829 |
-
with gr.Accordion("Om notformatet", open=False):
|
| 830 |
-
gr.Markdown(FORMAT_MD)
|
| 831 |
-
|
| 832 |
-
gen_inputs = [prompt_box, seconds_in, temperature_in, top_k_in, top_p_in,
|
| 833 |
-
min_p_in, repeat_in, seed_in, star_in]
|
| 834 |
-
gen_outputs = [result_box, status_box, audio_out, roll_out, files_out]
|
| 835 |
-
|
| 836 |
-
gen_btn.click(generate_music, gen_inputs, gen_outputs,
|
| 837 |
-
concurrency_limit=1, concurrency_id="model")
|
| 838 |
-
continue_btn.click(use_result_as_prompt, [result_box, prompt_box], prompt_box).then(
|
| 839 |
-
generate_music, gen_inputs, gen_outputs, concurrency_limit=1, concurrency_id="model")
|
| 840 |
-
stop_btn.click(stop_generation, None, None)
|
| 841 |
-
example_btn.click(lambda: EXAMPLE_PROMPT, None, prompt_box)
|
| 842 |
-
scratch_btn.click(lambda: "*\n", None, prompt_box)
|
| 843 |
-
midi_inputs = [midi_in, midi_secs, prompt_box, status_box]
|
| 844 |
-
midi_in.change(midi_to_prompt, midi_inputs, [prompt_box, status_box])
|
| 845 |
-
midi_secs.change(midi_to_prompt, midi_inputs, [prompt_box, status_box])
|
| 846 |
-
|
| 847 |
-
demo.queue(max_size=20)
|
| 848 |
-
|
| 849 |
-
if __name__ == "__main__":
|
| 850 |
-
demo.launch(**LAUNCH_KW)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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