Datasets:
Download scripts/make_real_sheets.py from gregology/sheet-music-scanner-eval: direct link, hf CLI and curl.
- Browser
- Download file 8.25 kB
-
https://huggingface.co/datasets/gregology/sheet-music-scanner-eval/resolve/main/scripts/make_real_sheets.py
- Command line
-
hf download hf://datasets/gregology/sheet-music-scanner-eval/scripts/make_real_sheets.py
-
curl -L -o make_real_sheets.py https://huggingface.co/datasets/gregology/sheet-music-scanner-eval/resolve/main/scripts/make_real_sheets.py
8.25 kB
| # /// script | |
| # requires-python = ">=3.12" | |
| # dependencies = ["pypdf==6.1.1"] | |
| # /// | |
| """Writes the experiment's sheets of real music: page one of a string part from OpenScore's string quartets, as | |
| MuseScore engraves it, and the notes on that page as MusicXML. | |
| Usage: uv run scripts/make_real_sheets.py [--musescore <MuseScore's AppRun>] [--cache <folder>] | |
| The scores are CC0. MuseScore is GPL-3.0: it runs here to draw the pages, and nothing of it goes into the app. How to | |
| install it: README.md, "My photos". | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import os | |
| import subprocess | |
| import urllib.parse | |
| import urllib.request | |
| import xml.etree.ElementTree as ET | |
| from pathlib import Path | |
| from pypdf import PdfReader, PdfWriter | |
| SHEETS = Path(__file__).parent / "sheets" | |
| OPENSCORE = "https://raw.githubusercontent.com/OpenScore/StringQuartets" | |
| COMMIT = "2614b0b2958dd1ce3f52e172a43e5f4d0e29570f" | |
| ENGRAVER, VERSION = 2, "4.7.6" | |
| LETTER = (8.5, 11.0) # inches, as MuseScore's page style gives them | |
| # Sheet letter, OpenScore's number for the score, the score's folder in OpenScore's repository, and the part. | |
| PARTS = [ | |
| ("i", 9396439, "Beethoven,_Ludwig_van/String_Quartet_No.5,_Op.18_No.5", "Violin 1"), | |
| ("j", 9396439, "Beethoven,_Ludwig_van/String_Quartet_No.5,_Op.18_No.5", "Violoncello"), | |
| ("k", 7108150, "Brahms,_Johannes/String_Quartet_No.1,_Op.51_No.1", "Violin 1"), | |
| ("l", 7108150, "Brahms,_Johannes/String_Quartet_No.1,_Op.51_No.1", "Violoncello"), | |
| ("m", 7302602, "Brahms,_Johannes/String_Quartet_No.2,_Op.51_No.2", "Viola"), | |
| ("n", 8461409, "Haydn,_Joseph/String_Quartet_in_B-flat_major_(“La_Chasse”),_Hob._III1,_Op.1_No.1", "Violin 1"), | |
| ("o", 9137469, "Dvořák,_Antonín/String_Quartet_No.10,_Op.51", "Viola"), | |
| ("p", 8907120, "Beethoven,_Ludwig_van/String_Quartet_No.3,_Op.18_No.3", "Viola"), | |
| ("q", 9137469, "Dvořák,_Antonín/String_Quartet_No.10,_Op.51", "Violin 1"), | |
| ("r", 10675759, "Borodin,_Alexander/String_Quartet_No.2", "Violin 1"), | |
| ] | |
| def download(cache: Path, number: int, folder: str) -> Path: | |
| path = cache / "mscx" / f"{number}.mscx" | |
| if not path.exists(): | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| url = f"{OPENSCORE}/{COMMIT}/" + urllib.parse.quote(f"scores/{folder}/sq{number}.mscx") | |
| with urllib.request.urlopen(url) as response: | |
| path.write_bytes(response.read()) | |
| return path | |
| def extract(score: Path, part: str, label: str, out: Path) -> None: | |
| """The part, as a score of its own on a Letter page, with the sheet's label before its title. OpenScore's files | |
| keep each part inside the score, with the part's own layout and style.""" | |
| tree = ET.parse(score) | |
| root = tree.getroot() | |
| whole = root.find("Score") | |
| parts = {excerpt.findtext("name"): excerpt for excerpt in whole.findall("Score")} | |
| if part not in parts: | |
| raise SystemExit(f"{score.name} has no part {part!r}; it has {sorted(parts)}") | |
| excerpt = parts[part] | |
| excerpt.remove(excerpt.find("name")) | |
| style = excerpt.find("Style") | |
| margin = float(style.findtext("pageOddLeftMargin") or style.findtext("pageEvenLeftMargin") or 15 / 25.4) | |
| for key, value in (("pageWidth", LETTER[0]), ("pageHeight", LETTER[1]), ("pagePrintableWidth", LETTER[0] - 2 * margin)): | |
| setting = style.find(key) | |
| (setting if setting is not None else ET.SubElement(style, key)).text = f"{value:g}" | |
| titles = [text.find("text") for text in excerpt.iter("Text") if text.findtext("style") == "Title"] | |
| if len(titles) != 1: | |
| raise SystemExit(f"{score.name}, {part}: {len(titles)} titles; the label goes before one") | |
| titles[0].text = f"{label} · {titles[0].text or ''}" | |
| root[list(root).index(whole)] = excerpt | |
| out.parent.mkdir(parents=True, exist_ok=True) | |
| tree.write(out, encoding="UTF-8", xml_declaration=True) | |
| def engrave(musescore: Path, jobs: list[dict], cache: Path) -> None: | |
| """Runs MuseScore without a screen; it takes its Qt platform from a variable of its own.""" | |
| environment = os.environ | {"MU_QT_QPA_PLATFORM": "offscreen", "QT_QPA_PLATFORM": "offscreen"} | |
| version = subprocess.run([musescore, "--version"], env=environment, capture_output=True, text=True).stdout | |
| if VERSION not in version: | |
| raise SystemExit(f"engraver {ENGRAVER} is MuseScore {VERSION}; {musescore} says {version.strip()!r}") | |
| job = cache / "job.json" | |
| job.write_text(json.dumps(jobs, indent=1)) | |
| done = subprocess.run([musescore, "-j", job], env=environment, capture_output=True, text=True) | |
| if done.returncode: | |
| raise SystemExit(f"MuseScore stopped with {done.returncode}:\n{done.stdout}{done.stderr}") | |
| def first_page(pdf: Path, out: Path) -> int: | |
| reader = PdfReader(pdf) | |
| writer = PdfWriter() | |
| writer.add_page(reader.pages[0]) | |
| with open(out, "wb") as file: | |
| writer.write(file) | |
| return len(reader.pages) | |
| def cut(musicxml: Path, out: Path) -> list[str]: | |
| """The notes on page one: the measures before the first page break MuseScore marks in its MusicXML. A page ends | |
| at a barline, so no measure is split. What the page does not print is left out: OpenScore's files have rests | |
| hidden in an empty second voice and staccato marks kept only for playback.""" | |
| tree = ET.parse(musicxml) | |
| root = tree.getroot() | |
| (part,) = root.findall("part") | |
| measures = part.findall("measure") | |
| end = next((n for n, measure in enumerate(measures) if n and measure.find("print[@new-page='yes']") is not None), len(measures)) | |
| for measure in measures[end:]: | |
| part.remove(measure) | |
| for measure in measures[:end]: | |
| drop_hidden(measure) | |
| for credit in root.findall("credit"): | |
| if credit.get("page", "1") != "1": | |
| root.remove(credit) | |
| tree.write(out, encoding="UTF-8", xml_declaration=True) | |
| return [measure.get("number") for measure in measures[:end]] | |
| def drop_hidden(measure: ET.Element) -> None: | |
| """Removes everything in the measure marked as not printed. A hidden note or rest becomes a `forward` of its | |
| length, so the notes after it keep their place in the measure.""" | |
| parents = {child: parent for parent in measure.iter() for child in parent} | |
| for element in [e for e in measure.iter() if e.get("print-object") == "no"]: | |
| parent = parents[element] | |
| if element.tag == "note" and element.find("chord") is None and element.find("grace") is None: | |
| following = list(parent)[list(parent).index(element) + 1:] | |
| if following and following[0].tag == "note" and following[0].find("chord") is not None: | |
| raise SystemExit(f"measure {measure.get('number')}: a hidden note with printed notes in its chord") | |
| forward = ET.Element("forward") | |
| ET.SubElement(forward, "duration").text = element.findtext("duration") | |
| if element.find("voice") is not None: | |
| ET.SubElement(forward, "voice").text = element.findtext("voice") | |
| parent.insert(list(parent).index(element), forward) | |
| parent.remove(element) | |
| def main() -> None: | |
| parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) | |
| parser.add_argument("--musescore", type=Path, default=Path.home() / ".local/opt/musescore/squashfs-root/AppRun") | |
| parser.add_argument("--cache", type=Path, default=Path.home() / ".cache/sheet-music-scanner/openscore") | |
| arguments = parser.parse_args() | |
| work = arguments.cache / "parts" | |
| jobs = [] | |
| for letter, number, folder, part in PARTS: | |
| label = f"{letter}{ENGRAVER}" | |
| extract(download(arguments.cache, number, folder), part, label, work / f"{label}.mscx") | |
| jobs.append({"in": str(work / f"{label}.mscx"), "out": [str(work / f"{label}-all.pdf"), str(work / f"{label}.musicxml")]}) | |
| engrave(arguments.musescore, jobs, arguments.cache) | |
| for letter, number, folder, part in PARTS: | |
| label = f"{letter}{ENGRAVER}" | |
| pages = first_page(work / f"{label}-all.pdf", SHEETS / f"{label}.pdf") | |
| bars = cut(work / f"{label}.musicxml", SHEETS / f"{letter}.musicxml") | |
| print(f"{label}: {folder.split('/')[1].replace('_', ' ')}, {part}: bars {bars[0]} to {bars[-1]} of {pages} pages") | |
| if __name__ == "__main__": | |
| main() | |