fffiloni commited on
Commit
e941edc
·
verified ·
1 Parent(s): 4ac8803

Upload 9 files

Browse files
Files changed (4) hide show
  1. app.py +28 -1
  2. notation.py +87 -18
  3. requirements.txt +1 -1
  4. studio_component.py +2 -0
app.py CHANGED
@@ -1365,6 +1365,8 @@ def _viewer_payload(
1365
  state: str,
1366
  status: str,
1367
  progress: float,
 
 
1368
  audio_name: str,
1369
  elapsed: float,
1370
  duration: float,
@@ -1373,6 +1375,21 @@ def _viewer_payload(
1373
  original_audio: str = "",
1374
  available_until: float | None = None,
1375
  ) -> dict[str, Any]:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1376
  live_end = (
1377
  duration
1378
  if available_until is None and state in {"complete", "ready"}
@@ -1384,6 +1401,8 @@ def _viewer_payload(
1384
  "state": state,
1385
  "status": status,
1386
  "progress": round(max(0.0, min(1.0, progress)), 4),
 
 
1387
  "audio_name": audio_name,
1388
  "export_stem": safe_filename_stem(Path(audio_name).stem, "muscriptor-transcription"),
1389
  "elapsed": round(elapsed, 2),
@@ -1564,6 +1583,7 @@ def transcribe_audio(
1564
  events: list[Any] = []
1565
  started = time.perf_counter()
1566
  last_completed = -1
 
1567
 
1568
  try:
1569
  transcribe_options: dict[str, Any] = {
@@ -1584,6 +1604,7 @@ def transcribe_audio(
1584
  if event.completed == last_completed:
1585
  continue
1586
  last_completed = event.completed
 
1587
  notes = _notes_from_events(events)
1588
  tracks = _track_payloads(notes, requested)
1589
  fraction = event.completed / max(1, event.total)
@@ -1607,6 +1628,8 @@ def transcribe_audio(
1607
  state="transcribing",
1608
  status=status,
1609
  progress=fraction,
 
 
1610
  audio_name=audio_name,
1611
  elapsed=time.perf_counter() - started,
1612
  duration=duration,
@@ -1640,6 +1663,8 @@ def transcribe_audio(
1640
  state="complete",
1641
  status=f"Transcription complete in {elapsed:.1f}s · score available on demand",
1642
  progress=1,
 
 
1643
  audio_name=audio_name,
1644
  elapsed=elapsed,
1645
  duration=duration,
@@ -1693,7 +1718,9 @@ def transcribe_audio(
1693
  viewer = _viewer_payload(
1694
  state="error",
1695
  status=message,
1696
- progress=0,
 
 
1697
  audio_name=audio_name,
1698
  elapsed=elapsed,
1699
  duration=duration,
 
1365
  state: str,
1366
  status: str,
1367
  progress: float,
1368
+ completed_windows: int | None = None,
1369
+ total_windows: int | None = None,
1370
  audio_name: str,
1371
  elapsed: float,
1372
  duration: float,
 
1375
  original_audio: str = "",
1376
  available_until: float | None = None,
1377
  ) -> dict[str, Any]:
1378
+ inferred_total_windows = math.ceil(duration / 5.0) if duration > 0 else 0
1379
+ window_total = max(
1380
+ 0,
1381
+ int(total_windows if total_windows is not None else inferred_total_windows),
1382
+ )
1383
+ if completed_windows is None:
1384
+ if state in {"complete", "ready", "generating_score"}:
1385
+ window_completed = window_total
1386
+ elif available_until is not None:
1387
+ window_completed = math.floor(max(0.0, float(available_until)) / 5.0 + 1e-9)
1388
+ else:
1389
+ window_completed = math.floor(max(0.0, float(progress)) * window_total + 1e-9)
1390
+ else:
1391
+ window_completed = int(completed_windows)
1392
+ window_completed = max(0, min(window_total, window_completed))
1393
  live_end = (
1394
  duration
1395
  if available_until is None and state in {"complete", "ready"}
 
1401
  "state": state,
1402
  "status": status,
1403
  "progress": round(max(0.0, min(1.0, progress)), 4),
1404
+ "completed_windows": window_completed,
1405
+ "total_windows": window_total,
1406
  "audio_name": audio_name,
1407
  "export_stem": safe_filename_stem(Path(audio_name).stem, "muscriptor-transcription"),
1408
  "elapsed": round(elapsed, 2),
 
1583
  events: list[Any] = []
1584
  started = time.perf_counter()
1585
  last_completed = -1
1586
+ last_total = math.ceil(duration / 5.0)
1587
 
1588
  try:
1589
  transcribe_options: dict[str, Any] = {
 
1604
  if event.completed == last_completed:
1605
  continue
1606
  last_completed = event.completed
1607
+ last_total = max(1, int(event.total))
1608
  notes = _notes_from_events(events)
1609
  tracks = _track_payloads(notes, requested)
1610
  fraction = event.completed / max(1, event.total)
 
1628
  state="transcribing",
1629
  status=status,
1630
  progress=fraction,
1631
+ completed_windows=event.completed,
1632
+ total_windows=event.total,
1633
  audio_name=audio_name,
1634
  elapsed=time.perf_counter() - started,
1635
  duration=duration,
 
1663
  state="complete",
1664
  status=f"Transcription complete in {elapsed:.1f}s · score available on demand",
1665
  progress=1,
1666
+ completed_windows=last_total,
1667
+ total_windows=last_total,
1668
  audio_name=audio_name,
1669
  elapsed=elapsed,
1670
  duration=duration,
 
1718
  viewer = _viewer_payload(
1719
  state="error",
1720
  status=message,
1721
+ progress=max(0, last_completed) / max(1, last_total),
1722
+ completed_windows=max(0, last_completed),
1723
+ total_windows=last_total,
1724
  audio_name=audio_name,
1725
  elapsed=elapsed,
1726
  duration=duration,
notation.py CHANGED
@@ -444,6 +444,7 @@ def estimate_score_settings(tracks: list[dict[str, Any]]) -> dict[str, Any]:
444
 
445
 
446
  _INVALID_XML_CHARACTERS = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f]")
 
447
 
448
 
449
  def _clean_display_text(value: Any, fallback: str) -> str:
@@ -1143,6 +1144,18 @@ def _write_musicxml(score: Any, output_path: Path) -> Path:
1143
  score.write("musicxml", fp=str(output_path))
1144
  xml_text = output_path.read_text(encoding="utf-8-sig")
1145
  cleaned = _INVALID_XML_CHARACTERS.sub("", xml_text)
 
 
 
 
 
 
 
 
 
 
 
 
1146
  if cleaned != xml_text:
1147
  output_path.write_text(cleaned, encoding="utf-8")
1148
  try:
@@ -1154,6 +1167,79 @@ def _write_musicxml(score: Any, output_path: Path) -> Path:
1154
  return output_path
1155
 
1156
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1157
  def _render_svg_pages(
1158
  musicxml: Path,
1159
  output_dir: Path,
@@ -1165,29 +1251,12 @@ def _render_svg_pages(
1165
  except ImportError as exc: # pragma: no cover - deployment configuration
1166
  raise RuntimeError("La dépendance verovio est nécessaire pour afficher la partition.") from exc
1167
 
1168
- toolkit = verovio.toolkit()
1169
- toolkit.setOptions(
1170
- {
1171
- "adjustPageHeight": True,
1172
- "breaks": "auto",
1173
- "footer": "none",
1174
- "header": "none",
1175
- "pageHeight": 2100,
1176
- "pageWidth": 2970,
1177
- "scale": 38,
1178
- "spacingStaff": 8,
1179
- "spacingSystem": 12,
1180
- }
1181
- )
1182
  xml_text = _INVALID_XML_CHARACTERS.sub("", musicxml.read_text(encoding="utf-8-sig"))
1183
  try:
1184
  ElementTree.fromstring(xml_text.encode("utf-8"))
1185
  except ElementTree.ParseError as exc:
1186
  raise RuntimeError(f"Invalid MusicXML in {musicxml.name}: {exc}") from exc
1187
- if not toolkit.loadData(xml_text):
1188
- log_lines = [line.strip() for line in str(toolkit.getLog() or "").splitlines() if line.strip()]
1189
- diagnostic = " · ".join(log_lines[-3:])[-600:] if log_lines else "no parser details"
1190
- raise RuntimeError(f"Verovio could not read {musicxml.name}: {diagnostic}")
1191
 
1192
  pages: list[Path] = []
1193
  preview = ""
 
444
 
445
 
446
  _INVALID_XML_CHARACTERS = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f]")
447
+ _MUSICXML_NUMERIC_VOICE = re.compile(r"(<voice>)(\d+)(</voice>)")
448
 
449
 
450
  def _clean_display_text(value: Any, fallback: str) -> str:
 
1144
  score.write("musicxml", fp=str(output_path))
1145
  xml_text = output_path.read_text(encoding="utf-8-sig")
1146
  cleaned = _INVALID_XML_CHARACTERS.sub("", xml_text)
1147
+ # music21 numbers Voice objects from zero in some polyphonic exports.
1148
+ # MusicXML technically accepts a token here, but Verovio maps numeric
1149
+ # voices to one-based MEI layers and reports every <voice>0</voice> as a
1150
+ # missing layer. If a zero-based voice is present, shift the complete
1151
+ # numeric voice set together so voices remain distinct and portable.
1152
+ if "<voice>0</voice>" in cleaned:
1153
+ cleaned = _MUSICXML_NUMERIC_VOICE.sub(
1154
+ lambda match: (
1155
+ f"{match.group(1)}{int(match.group(2)) + 1}{match.group(3)}"
1156
+ ),
1157
+ cleaned,
1158
+ )
1159
  if cleaned != xml_text:
1160
  output_path.write_text(cleaned, encoding="utf-8")
1161
  try:
 
1167
  return output_path
1168
 
1169
 
1170
+ _VEROVIO_OPTIONS = {
1171
+ "adjustPageHeight": True,
1172
+ "breaks": "auto",
1173
+ "footer": "none",
1174
+ "header": "none",
1175
+ "pageHeight": 2100,
1176
+ "pageWidth": 2970,
1177
+ "scale": 38,
1178
+ "spacingStaff": 8,
1179
+ "spacingSystem": 12,
1180
+ }
1181
+
1182
+
1183
+ def _verovio_toolkit(verovio_module: Any) -> Any:
1184
+ """Create a toolkit with an explicit wheel resource path when available."""
1185
+
1186
+ module_file = getattr(verovio_module, "__file__", "")
1187
+ resource_path = Path(module_file).resolve().parent / "data" if module_file else None
1188
+ toolkit = None
1189
+ if resource_path and resource_path.is_dir():
1190
+ try:
1191
+ toolkit = verovio_module.toolkit(False)
1192
+ if not toolkit.setResourcePath(str(resource_path)):
1193
+ toolkit = None
1194
+ except (AttributeError, TypeError):
1195
+ toolkit = None
1196
+ if toolkit is None:
1197
+ toolkit = verovio_module.toolkit()
1198
+ toolkit.setOptions(_VEROVIO_OPTIONS)
1199
+ return toolkit
1200
+
1201
+
1202
+ def _verovio_log(toolkit: Any) -> str:
1203
+ try:
1204
+ raw_log = toolkit.getLog()
1205
+ except Exception:
1206
+ raw_log = ""
1207
+ lines = [line.strip() for line in str(raw_log or "").splitlines() if line.strip()]
1208
+ return " · ".join(lines[-3:])[-600:] if lines else "no parser details"
1209
+
1210
+
1211
+ def _load_verovio_musicxml(verovio_module: Any, musicxml: Path, xml_text: str) -> Any:
1212
+ """Load MusicXML through both native Python routes before giving up.
1213
+
1214
+ `loadFile` is Verovio's documented Python path and avoids copying a large
1215
+ score through the binding. `loadData` remains a useful independent retry
1216
+ for unusual temporary-file or filesystem behaviour on hosted Spaces.
1217
+ """
1218
+
1219
+ diagnostics: list[str] = []
1220
+ for method in ("file", "data"):
1221
+ toolkit = _verovio_toolkit(verovio_module)
1222
+ try:
1223
+ loaded = (
1224
+ toolkit.loadFile(str(musicxml.resolve()))
1225
+ if method == "file"
1226
+ else toolkit.loadData(xml_text)
1227
+ )
1228
+ except Exception as exc:
1229
+ diagnostics.append(f"{method} loader: {type(exc).__name__}: {exc}")
1230
+ continue
1231
+ if loaded:
1232
+ return toolkit
1233
+ diagnostics.append(f"{method} loader: {_verovio_log(toolkit)}")
1234
+
1235
+ root_name = ElementTree.fromstring(xml_text.encode("utf-8")).tag
1236
+ detail = " · ".join(diagnostics)[-1200:]
1237
+ raise RuntimeError(
1238
+ f"Verovio could not read {musicxml.name} after file and data loading "
1239
+ f"({root_name}, {len(xml_text.encode('utf-8'))} bytes): {detail}"
1240
+ )
1241
+
1242
+
1243
  def _render_svg_pages(
1244
  musicxml: Path,
1245
  output_dir: Path,
 
1251
  except ImportError as exc: # pragma: no cover - deployment configuration
1252
  raise RuntimeError("La dépendance verovio est nécessaire pour afficher la partition.") from exc
1253
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1254
  xml_text = _INVALID_XML_CHARACTERS.sub("", musicxml.read_text(encoding="utf-8-sig"))
1255
  try:
1256
  ElementTree.fromstring(xml_text.encode("utf-8"))
1257
  except ElementTree.ParseError as exc:
1258
  raise RuntimeError(f"Invalid MusicXML in {musicxml.name}: {exc}") from exc
1259
+ toolkit = _load_verovio_musicxml(verovio, musicxml, xml_text)
 
 
 
1260
 
1261
  pages: list[Path] = []
1262
  preview = ""
requirements.txt CHANGED
@@ -10,6 +10,6 @@ soundfile==0.14.0
10
  safetensors==0.8.0
11
  huggingface_hub==1.21.0
12
  music21==9.9.1
13
- verovio==5.7.0
14
  CairoSVG==2.8.2
15
  pypdf==6.6.0
 
10
  safetensors==0.8.0
11
  huggingface_hub==1.21.0
12
  music21==9.9.1
13
+ verovio==6.2.1
14
  CairoSVG==2.8.2
15
  pypdf==6.6.0
studio_component.py CHANGED
@@ -20,6 +20,8 @@ def initial_studio_value() -> dict[str, Any]:
20
  "state": "idle",
21
  "status": "Upload a recording to begin.",
22
  "progress": 0,
 
 
23
  "audio_name": "",
24
  "export_stem": "muscriptor",
25
  "elapsed": 0,
 
20
  "state": "idle",
21
  "status": "Upload a recording to begin.",
22
  "progress": 0,
23
+ "completed_windows": 0,
24
+ "total_windows": 0,
25
  "audio_name": "",
26
  "export_stem": "muscriptor",
27
  "elapsed": 0,