#!/usr/bin/env python3 """Prepare an API request from two uncompressed or compressed MusicXML files.""" import argparse import json from pathlib import Path import re import sys import xml.etree.ElementTree as ET from zipfile import BadZipFile, ZipFile SCORE_BYTES = 400_000 CONTAINER_BYTES = 32_768 ARCHIVE_BYTES = 32 * 1024 * 1024 MUSICXML_MEDIA = "application/vnd.recordare.musicxml+xml" def limited_read(file, limit): data = file.read(limit + 1) if len(data) > limit: raise ValueError(f"Input exceeds the {limit:,}-byte reader limit.") return data def zip_member(archive, name, limit): parts = name.split("/") if "\\" in name or ":" in name or any(part in ("", ".", "..") for part in parts): raise ValueError("The score must use a relative archive path.") matches = [entry for entry in archive.infolist() if entry.filename == name] if len(matches) != 1 or matches[0].is_dir(): raise ValueError(f"Expected one ZIP member named {name}.") entry = matches[0] if entry.file_size > limit or entry.flag_bits & 1: raise ValueError(f"ZIP member {name} is too large or encrypted.") with archive.open(entry) as file: return limited_read(file, limit) def xml_text(data): if data.startswith((b"\xff\xfe", b"\xfe\xff")): return data.decode("utf-16") return data.decode("utf-8-sig") def read_score(path): if path.suffix.lower() == ".mxl": if path.stat().st_size > ARCHIVE_BYTES: raise ValueError("The MXL archive exceeds 32 MiB.") with ZipFile(path) as archive: container = xml_text(zip_member(archive, "META-INF/container.xml", CONTAINER_BYTES)) if re.search(r" 100_000: raise ValueError("The API accepts at most 100,000 UTF-16 code units per score.") return score def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("before", type=Path) parser.add_argument("after", type=Path) args = parser.parse_args() try: body = json.dumps({"before_xml": read_score(args.before), "after_xml": read_score(args.after)}, separators=(",", ":"), ensure_ascii=False).encode("utf-8") if len(body) > 262_144: raise ValueError("The JSON request exceeds the API's 262,144-byte limit.") sys.stdout.buffer.write(body + b"\n") except (OSError, ValueError, ET.ParseError, BadZipFile, RuntimeError, NotImplementedError) as exc: parser.exit(2, f"error: {exc}\n") if __name__ == "__main__": main()