Files
2026-07-09 10:58:09 +09:00

311 lines
10 KiB
Python

from __future__ import annotations
import logging
import threading
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
from uuid import uuid4
import pretty_midi
from .. import job_manager as jm
log = logging.getLogger(__name__)
_SESSIONS_LOCK = threading.Lock()
_SESSIONS: dict[str, dict[str, Any]] = {}
def _now_iso() -> str:
return datetime.now(timezone.utc).isoformat()
def _clamp(value: float, lo: float, hi: float) -> float:
return max(lo, min(hi, value))
def _resolve_midi_path(job_id: str, filename: str | None) -> Path:
job = jm.get_job(job_id)
if not job:
raise ValueError("job not found")
files = [f for f in (job.get("files") or []) if str(f.get("name", "")).lower().endswith(".mid")]
if not files:
raise ValueError("no midi file found on job")
chosen = None
if filename:
for item in files:
if item.get("name") == filename:
chosen = item
break
if not chosen:
raise ValueError("midi filename not found on job")
else:
chosen = files[0]
path = Path(str(chosen.get("path", "")))
if not path.exists() or not path.is_file():
raise ValueError("midi file is missing from disk")
return path
def create_session(job_id: str, filename: str | None = None) -> dict[str, Any]:
source_path = _resolve_midi_path(job_id, filename)
midi = pretty_midi.PrettyMIDI(str(source_path))
tracks: list[dict[str, Any]] = []
for idx, instrument in enumerate(midi.instruments):
notes = [
{
"id": uuid4().hex[:10],
"pitch": int(note.pitch),
"start": float(note.start),
"duration": float(max(0.001, note.end - note.start)),
"velocity": int(note.velocity),
}
for note in instrument.notes
]
bends = [
{
"id": uuid4().hex[:10],
"time": float(bend.time),
"value": int(bend.pitch),
}
for bend in instrument.pitch_bends
]
tracks.append(
{
"index": idx,
"name": instrument.name or f"Track {idx + 1}",
"program": int(instrument.program),
"is_drum": bool(instrument.is_drum),
"notes": notes,
"bends": bends,
}
)
session_id = uuid4().hex
payload = {
"id": session_id,
"created_at": _now_iso(),
"source_job_id": job_id,
"source_filename": source_path.name,
"source_path": str(source_path),
"tracks": tracks,
"editor_version": "stemengine-midi-editor-v1",
}
with _SESSIONS_LOCK:
_SESSIONS[session_id] = payload
return payload
def get_session(session_id: str) -> dict[str, Any]:
with _SESSIONS_LOCK:
session = _SESSIONS.get(session_id)
if not session:
raise ValueError("session not found")
return session
def discard_session(session_id: str) -> dict[str, Any]:
with _SESSIONS_LOCK:
existed = _SESSIONS.pop(session_id, None) is not None
if not existed:
raise ValueError("session not found")
return {"discarded": True}
def apply_ops(session_id: str, ops: list[dict[str, Any]]) -> dict[str, Any]:
with _SESSIONS_LOCK:
session = _SESSIONS.get(session_id)
if not session:
raise ValueError("session not found")
for op in ops:
_apply_single_op(session, op)
return session
def _get_track(session: dict[str, Any], track_index: int) -> dict[str, Any]:
tracks: list[dict[str, Any]] = session["tracks"]
if track_index < 0 or track_index >= len(tracks):
raise ValueError("track_index out of range")
return tracks[track_index]
def _apply_single_op(session: dict[str, Any], op: dict[str, Any]) -> None:
op_name = str(op.get("op", "")).strip()
if not op_name:
raise ValueError("op is required")
track_index = int(op.get("track_index", 0))
track = _get_track(session, track_index)
if op_name == "add_note":
start = float(op.get("start", 0.0))
duration = float(op.get("duration", 0.5))
note = {
"id": uuid4().hex[:10],
"pitch": int(_clamp(float(op.get("pitch", 60)), 0, 127)),
"start": _clamp(start, 0.0, 86400.0),
"duration": _clamp(duration, 0.001, 60.0),
"velocity": int(_clamp(float(op.get("velocity", 100)), 1, 127)),
}
track["notes"].append(note)
track["notes"].sort(key=lambda x: (x["start"], x["pitch"]))
return
if op_name == "update_note":
note_id = str(op.get("note_id", ""))
note = next((n for n in track["notes"] if n["id"] == note_id), None)
if not note:
raise ValueError("note not found")
if "pitch" in op:
note["pitch"] = int(_clamp(float(op["pitch"]), 0, 127))
if "start" in op:
note["start"] = _clamp(float(op["start"]), 0.0, 86400.0)
if "duration" in op:
note["duration"] = _clamp(float(op["duration"]), 0.001, 60.0)
if "velocity" in op:
note["velocity"] = int(_clamp(float(op["velocity"]), 1, 127))
track["notes"].sort(key=lambda x: (x["start"], x["pitch"]))
return
if op_name == "delete_note":
note_id = str(op.get("note_id", ""))
track["notes"] = [n for n in track["notes"] if n["id"] != note_id]
return
if op_name == "quantize_notes":
step = float(op.get("step", 0.25))
if step <= 0:
raise ValueError("quantize step must be > 0")
for note in track["notes"]:
note["start"] = round(note["start"] / step) * step
note["duration"] = max(step, round(note["duration"] / step) * step)
track["notes"].sort(key=lambda x: (x["start"], x["pitch"]))
return
if op_name == "add_bend":
bend = {
"id": uuid4().hex[:10],
"time": _clamp(float(op.get("time", 0.0)), 0.0, 86400.0),
"value": int(_clamp(float(op.get("value", 0)), -8192, 8191)),
}
track["bends"].append(bend)
track["bends"].sort(key=lambda x: x["time"])
return
if op_name == "update_bend":
bend_id = str(op.get("bend_id", ""))
bend = next((b for b in track["bends"] if b["id"] == bend_id), None)
if not bend:
raise ValueError("bend not found")
if "time" in op:
bend["time"] = _clamp(float(op["time"]), 0.0, 86400.0)
if "value" in op:
bend["value"] = int(_clamp(float(op["value"]), -8192, 8191))
track["bends"].sort(key=lambda x: x["time"])
return
if op_name == "delete_bend":
bend_id = str(op.get("bend_id", ""))
track["bends"] = [b for b in track["bends"] if b["id"] != bend_id]
return
raise ValueError(f"unsupported op: {op_name}")
def save_session(session_id: str) -> dict[str, Any]:
with _SESSIONS_LOCK:
session = _SESSIONS.get(session_id)
if not session:
raise ValueError("session not found")
source_path = Path(session["source_path"])
if not source_path.exists() or not source_path.is_file():
raise ValueError("source midi file is missing")
midi = pretty_midi.PrettyMIDI(str(source_path))
tracks: list[dict[str, Any]] = session["tracks"]
while len(midi.instruments) < len(tracks):
midi.instruments.append(pretty_midi.Instrument(program=0, is_drum=False, name="New Track"))
for idx, track in enumerate(tracks):
instrument = midi.instruments[idx]
instrument.program = int(track.get("program", 0))
instrument.is_drum = bool(track.get("is_drum", False))
instrument.name = str(track.get("name", instrument.name or f"Track {idx + 1}"))
notes = []
for item in track.get("notes", []):
start = float(item["start"])
duration = float(item["duration"])
notes.append(
pretty_midi.Note(
velocity=int(item["velocity"]),
pitch=int(item["pitch"]),
start=max(0.0, start),
end=max(0.001, start + duration),
)
)
notes.sort(key=lambda x: (x.start, x.pitch))
bends = []
for item in track.get("bends", []):
bends.append(
pretty_midi.PitchBend(
pitch=int(item["value"]),
time=max(0.0, float(item["time"])),
)
)
bends.sort(key=lambda x: x.time)
instrument.notes = notes
instrument.pitch_bends = bends
edited_name = f"{source_path.stem}.edited.mid"
edited_path = source_path.with_name(edited_name)
suffix = 2
while edited_path.exists():
edited_path = source_path.with_name(f"{source_path.stem}.edited.{suffix}.mid")
suffix += 1
midi.write(str(edited_path))
summary = {
"track_count": len(tracks),
"note_count": sum(len(t.get("notes", [])) for t in tracks),
"bend_count": sum(len(t.get("bends", [])) for t in tracks),
}
save_job_id = jm.create_job("midi-edit-save")
jm.update_job(
save_job_id,
status=jm.JobStatus.DONE,
progress="MIDI edits saved.",
files=[{"name": edited_path.name, "path": str(edited_path), "type": "midi"}],
result={
"source_midi_path": str(source_path),
"edited_midi_path": str(edited_path),
"midi_edit_summary": summary,
"midi_editor_version": session.get("editor_version", "stemengine-midi-editor-v1"),
"saved_at": _now_iso(),
},
)
session["last_saved_path"] = str(edited_path)
session["last_saved_job_id"] = save_job_id
return {
"job_id": save_job_id,
"filename": edited_path.name,
"path": str(edited_path),
"summary": summary,
}