gregology's picture
My photos with their metadata stripped, the survey of OpenScore's string quartet parts, and the synthetic test set t1, with evaluate.py
2935e65 verified
Raw History Blame Contribute Delete
6.11 kB
# /// script
# requires-python = ">=3.12"
# dependencies = ["pypdf==6.1.1"]
# ///
"""Writes the survey: a clean picture of page one of every string part in OpenScore's string quartets, as MuseScore
engraves it, and the notes on that page as MusicXML.
Usage: uv run scripts/make_survey.py [--musescore <MuseScore's AppRun>] [--cache <folder>] [--out <folder>]
The survey is for finding what a reader gets wrong on real notation, over hundreds of pages and with no camera. Its
pages are never printed and never trained on. The ten parts that are the experiment's sheets `i` to `r` are left out.
A part MuseScore or the true-score cut cannot handle is skipped, as is a score OpenScore keeps as `.mscz` alone, and
`index.tsv` says why. What the survey is for: README.md, "The survey".
"""
from __future__ import annotations
import argparse
import csv
import subprocess
import urllib.error
import urllib.request
import xml.etree.ElementTree as ET
from pathlib import Path
from make_real_sheets import COMMIT, OPENSCORE, PARTS, cut, download, engrave, extract
DPI = 300
def scores(cache: Path) -> list[tuple[int, str]]:
"""Every score in OpenScore's list: its number and its folder."""
path = cache / "scores.tsv"
if not path.exists():
cache.mkdir(parents=True, exist_ok=True)
with urllib.request.urlopen(f"{OPENSCORE}/{COMMIT}/scores.tsv") as response:
path.write_bytes(response.read())
with open(path, newline="") as file:
return [(int(row["id"]), row["path"]) for row in csv.DictReader(file, delimiter="\t")]
def part_names(score: Path) -> list[str]:
return [excerpt.findtext("name") for excerpt in ET.parse(score).getroot().find("Score").findall("Score")]
def measures(musicxml: Path) -> int:
return sum(1 for _ in ET.parse(musicxml).getroot().iter("measure"))
def voices(musicxml: Path) -> int:
"""How many voices the page prints notes in. The true score reads one line of music; a second voice on the staff
is music it puts in the wrong order."""
found = {note.findtext("voice") or "1" for note in ET.parse(musicxml).getroot().iter("note") if note.find("rest") is None}
return len(found)
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")
parser.add_argument("--out", type=Path, default=Path.home() / ".cache/sheet-music-scanner/survey")
arguments = parser.parse_args()
work = arguments.cache / "survey-parts"
arguments.out.mkdir(parents=True, exist_ok=True)
sheets = {(number, part) for _, number, _, part in PARTS}
rows = []
for number, folder in scores(arguments.cache):
try:
score = download(arguments.cache, number, folder)
names = part_names(score)
except urllib.error.HTTPError as failure:
# OpenScore keeps its later scores as `.mscz` alone, MuseScore 4's packed file with each part in a file
# of its own, which `extract` does not read.
rows.append((f"{number}", folder, "", "", "", "no .mscx in OpenScore's repository" if failure.code == 404 else f"not fetched: {failure}"))
continue
except Exception as failure: # a score that cannot be fetched or parsed is one row in the index, not the end
rows.append((f"{number}", folder, "", "", "", f"not read: {type(failure).__name__}: {failure}"))
continue
jobs, labels = [], []
for place, name in enumerate(names):
label = f"{number}-{place}"
if (number, name) in sheets:
rows.append((label, folder, name, "", "", "one of the experiment's sheets"))
continue
if (arguments.out / f"{label}.png").exists() and (arguments.out / f"{label}.musicxml").exists():
labels.append((label, name))
continue
try:
extract(score, name, label, work / f"{label}.mscx")
except SystemExit as failure:
rows.append((label, folder, name, "", "", f"not extracted: {failure}"))
continue
jobs.append({"in": str(work / f"{label}.mscx"), "out": [str(work / f"{label}-all.pdf"), str(work / f"{label}.musicxml")]})
labels.append((label, name))
if jobs:
try:
engrave(arguments.musescore, jobs, arguments.cache)
except SystemExit as failure:
rows.extend((label, folder, name, "", "", f"not engraved: {str(failure).splitlines()[0]}") for label, name in labels)
continue
for label, name in labels:
picture, truth = arguments.out / f"{label}.png", arguments.out / f"{label}.musicxml"
try:
if not picture.exists():
subprocess.run(["pdftoppm", "-r", str(DPI), "-png", "-singlefile", "-f", "1", "-l", "1", str(work / f"{label}-all.pdf"), str(picture.with_suffix(""))], check=True)
if not truth.exists():
cut(work / f"{label}.musicxml", truth)
except (SystemExit, Exception) as failure:
picture.unlink(missing_ok=True)
truth.unlink(missing_ok=True)
rows.append((label, folder, name, "", "", f"not cut: {type(failure).__name__}: {failure}"))
continue
rows.append((label, folder, name, measures(truth), voices(truth), ""))
print(f"{number}: {folder.split('/')[-1]}: {len(labels)} parts", flush=True)
with open(arguments.out / "index.tsv", "w", newline="") as file:
writer = csv.writer(file, delimiter="\t")
writer.writerow(("page", "score", "part", "measures", "voices", "left out"))
writer.writerows(rows)
made = sum(1 for row in rows if not row[5])
print(f"{made} pages in {arguments.out}; {len(rows) - made} left out")
if __name__ == "__main__":
main()