Add src/generate_images.py

This commit is contained in:
augustin64 2024-07-05 20:53:26 +02:00
parent 2d8cd7fd79
commit 14d8616c29

77
src/generate_images.py Normal file
View File

@ -0,0 +1,77 @@
from xml.etree import ElementTree
import subprocess
import tempfile
import zipfile
import shutil
import sys
import os
def create_pagebreaks(data):
"""
Replaces all manual linebreaks by pagebreaks in a .mscx file (xml)
"""
def get_elements(root, attribute):
return [i for i in root if i.tag == attribute]
def get_element(root, attribute):
elems = get_elements(root, attribute)
if len(elems) > 1:
print(f"More than one '{attribute}' found")
if len(elems) == 0:
raise IndexError(f"No '{attribute}' found !")
return elems[0]
root = ElementTree.fromstring(data)
score = get_element(root, "Score")
parts = get_elements(score, "Part")
staffs = get_elements(score, "Staff")
for part in parts:
staffs += get_elements(part, "Staff")
changes = 0
for staff in staffs:
measures = get_elements(staff, "Measure")
for measure in measures:
layoutbreaks = get_elements(measure, "LayoutBreak")
for layoutbreak in layoutbreaks:
subtype = get_element(layoutbreak, "subtype")
if subtype.text == "line":
subtype.text = "page"
changes += 1
return ElementTree.tostring(root), changes
def create_pagebreaks_mscz(source, dest):
shutil.copy(source, dest)
with zipfile.ZipFile(source) as inzip, zipfile.ZipFile(dest, "w") as outzip:
for inzipinfo in inzip.infolist():
with inzip.open(inzipinfo) as infile:
if inzipinfo.filename.endswith(".mscx"):
new_data, changes = create_pagebreaks(infile.read())
outzip.writestr(inzipinfo.filename, new_data)
print(f"Modified {inzipinfo.filename} : {changes} elements")
else:
outzip.writestr(inzipinfo.filename, infile.read())
print(f"Copied {inzipinfo.filename}")
def generate_images(mscz_file, base_dest):
with tempfile.TemporaryDirectory() as tmpdirname:
tmp_mscz = os.path.join(tmpdirname, "score.mscz")
create_pagebreaks_mscz(mscz_file, tmp_mscz)
subprocess.call(["mscore", tmp_mscz, "-o", base_dest+".png"])
subprocess.call(["mscore", mscz_file, "-o", base_dest+"-short.png"])
print("Images created")
if __name__ == "__main__":
if len(sys.argv) < 3:
print(f"Usage: {sys.argv[0]} <score.mscz> <out_basename>", file=sys.stderr)
sys.exit(1)
generate_images(sys.argv[1], sys.argv[2])