def write_expanded_mei_data(mei, fname, expansion): vrv = verovio.toolkit() if bool(expansion): vrv.setOptions(json.dumps({'expand': expansion})) vrv.loadData(mei) print("writing mei to: ", fname) vrv.saveFile(fname)
class Rendering: tk = verovio.toolkit() def pae_to_mei(self, clef, keysig, timesig, score): data = "@clef:" + clef + "\n" + "@keysig:" + keysig + "\n" + "@timesig:" + timesig + "\n" + "@data:" + score self.tk.loadData(data) return self.tk.getMEI() pass
def load_mei_tk(mensural=True): tk = verovio.toolkit(False) # The path for my resource folder - probably will change on server tk.setResourcePath(r"C:\Users\misin\OneDrive\Documents\GitHub\verovio\data") # Suggested by developer on github for mensural MEI files if mensural: tk.setNoLayout(True) #tk.setPageHeight(800) #tk.setPageWidth(2) tk.setFormat("mei") return tk
def close(): fKern.close() fAgnostic.close() tk = verovio.toolkit() tk.loadFile(pathKern) tk.getPageCount() tk.renderToSVGFile("page.svg", 1) with Image(filename='page.svg') as image: image.save(filename=pathImageJPG) os.remove("page.svg")
def produce_annnot_svg(mei_file, annotations, out_path="annotated_score.svg"): """Highlight different notes in the svg score based on the annotations. Only highlith notes, not other elements. For example, if a tie is deleted, it highlight the note attached to that tie. Because of this, an element could be highlighted multiple time. Therefore we use only one color. Args: mei_file (str|Path): the path of the MEI file annotations (list): the list of annotations to display out_path (str|Path, optional): Path to save the annotated svg score. Defaults to "annotated_score.svg". Raises: TypeError: if a certain annotation is not supported """ # produce the svg string with Verovio tk = verovio.toolkit() # tk.setOption("pageHeight", "500") # tk.setOption("scale", "90") # tk.setOption("ignoreLayout", "1") global RESOURCES_PATH if RESOURCES_PATH != None: tk.setResourcePath( str(RESOURCES_PATH)) # set the correct folder of resourches tk.loadFile(str(mei_file)) if isinstance(mei_file, Path) else tk.loadFile(mei_file) # TODO: display of multiple pages stringSVG = ( tk.renderToSVG() ) # this will produce just the first page. To update for longer scores svg_tree = ET.ElementTree(ET.fromstring(stringSVG)) # build the parent map parent_map = {c: p for p in svg_tree.iter() for c in p} # display the annotations for ann in annotations: if isinstance(ann["id"], list): # if there are multiple elements to highlight for e_id in ann["id"]: element = svg_tree.find(".//{}[@id='{}']".format( el_dict["g"], e_id)) element.set("fill", SUB_COLOR) else: # only one note element = svg_tree.find(".//{}[@id='{}']".format( el_dict["g"], ann["id"])) element.set("fill", SUB_COLOR) with open(out_path, "wb") as svg_file: svg_tree.write(svg_file) return True
def produce_annnot_svg_old(mei_file, annotations, out_path="annotated_score.svg"): """Old version of svg generator that highlight different elements in the score (e.g. points, ties, etc.) Args: mei_file (str|Path): the path of the MEI file annotations (list): the list of annotations to display out_path (str|Path, optional): Path to save the annotated svg score. Defaults to "annotated_score.svg". Raises: TypeError: if a certain annotation is not supported """ tk = verovio.toolkit() # tk.setOption("pageHeight", "500") # tk.setOption("scale", "90") # tk.setOption("ignoreLayout", "1") global RESOURCES_PATH if RESOURCES_PATH != None: tk.setResourcePath( str(RESOURCES_PATH)) # set the correct folder of resourches tk.loadFile(str(mei_file)) if isinstance(mei_file, Path) else tk.loadFile(mei_file) # TODO: display of multiple pages stringSVG = ( tk.renderToSVG() ) # this will produce just the first page. To update for longer scores svg_tree = ET.ElementTree(ET.fromstring(stringSVG)) # build the parent map parent_map = {c: p for p in svg_tree.iter() for c in p} # display the annotations for ann in annotations: if ann["target"] == "bar": # find the lower common element lce = find_lce(ann["id"], svg_tree, parent_map) # color the common element lce.set("fill", ann["color"]) elif ann["target"] == "note": # print(ann) element = svg_tree.find(".//{}[@id='{}']".format( el_dict["g"], ann["id"])) element.set("fill", ann["color"]) elif ann["target"] == "notehead": # try to extract the notehead (or noteheads) notehead_list = find_notehead(ann["id"], svg_tree, ann["head_id"]) # color the notehead for notehead in notehead_list: notehead.set("fill", ann["color"]) elif ann["target"] == "beam": stem = find_stem(ann["id"], svg_tree) # color the stem stem.set("fill", ann["color"]) elif ann["target"] == "tuplet": # TODO: to implement print("tuplet not visualized") elif ann["target"] == "accidental": # find accident accident = find_accident(ann["id"], svg_tree, ann["head_id"]) # color the corresponding accidental accident.set("fill", ann["color"]) elif ann["target"] == "dot": # find dots dots = find_dots(ann["id"], svg_tree) # color the corresponding dot dots.set("fill", ann["color"]) elif ann["target"] == "tie": # find dots tie, tie_line = find_tie(ann["id"], svg_tree, ann["head_id"], parent_map) # color the corresponding tie tie.set("fill", ann["color"]) tie_line.set("stroke", ann["color"]) else: raise TypeError("Unsupported annotation target: {}".format( ann["target"])) with open(out_path, "wb") as svg_file: svg_tree.write(svg_file)
from flask import Flask, jsonify, request import verovio import sys; sys.path.insert(0, "/usr/local/lib/python3.7/site-packages") print(sys.path) app = Flask(__name__) @app.route("/") def index(): return jsonify({"status": "service started"}) tk = verovio.toolkit() class Rendering: tk = verovio.toolkit() def pae_to_mei(self, clef, keysig, timesig, score): data = "@clef:" + clef + "\n" + "@keysig:" + keysig + "\n" + "@timesig:" + timesig + "\n" + "@data:" + score self.tk.loadData(data) return self.tk.getMEI() pass @app.route("/test", methods=['POST']) def send_mei(): req_data = request.get_json() clef = req_data['clef']
def mei_to_midi(mei, fname, expansion): vrv = verovio.toolkit() if bool(expansion): vrv.setOption('expand', expansion) vrv.loadData(mei) vrv.renderToMIDIFile(fname)
'breaks': 'auto', 'pageHeight': 2970, 'pageWidth': 2100, 'header': 'none', 'footer': 'none', 'scale': 40, 'spacingStaff': 4 } if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("test_suite_dir") parser.add_argument("output_dir") args = parser.parse_args() tk = verovio.toolkit(False) # version of the toolkit print(tk.getVersion()) # keep all the options to be able to reset them for each test defaultOptions = json.loads(tk.getOptions(True)) tk.setResourcePath('../../data') path1 = args.test_suite_dir.replace("\ ", " ") path2 = args.output_dir.replace("\ ", " ") dir1 = sorted(os.listdir(path1)) for item1 in dir1: if not (os.path.isdir(os.path.join(path1, item1))): continue
def neueAufgabeApp(): result = {} modDict = { "Loewe III": MODULS_FOLDER + "loewe-3", "Loewe II": MODULS_FOLDER + "loewe-2", "Loewe I": MODULS_FOLDER + "loewe-1", "Loewe IV": MODULS_FOLDER + "loewe-4", "Loewe V": MODULS_FOLDER + "loewe-5", "Loewe VI": MODULS_FOLDER + "loewe-6", "Loewe VII": MODULS_FOLDER + "loewe-7", "Loewe VIII": MODULS_FOLDER + "loewe-8", "Loewe IX": MODULS_FOLDER + "loewe-9", "Loewe X": MODULS_FOLDER + "loewe-10", "Loewe XI": MODULS_FOLDER + "loewe-11", "Teufelsmühle I": MODULS_FOLDER + "teufelsmuehle-1", } modTypeUsed = "" requestedMod = request.form.get('modType') fdata = request.form.get('modType') #print(fdata) #See what was requested. Website und App send Lists (as json) or Strings. try: requestedMod = json.loads(requestedMod) modTypeUsed = random.choice(requestedMod) except: return make_response("Wrong Request") #modTypeUsed = requestedMod #isAppRequest = False thePath = modDict[modTypeUsed] tInts = [ "A-4", "P-4", "M-3", "m-3", "M-2", "M-2", "m-2", "P1", "P1", "m2", "M2", "M2", "m3", "M3", "P4", "A4" ] tI = random.choice(tInts) s = converter.parse(thePath + ".musicxml") exS = s.transpose(tI) exerciceXML = musicxml.m21ToXml.GeneralObjectExporter().parse(exS) s = converter.parse(thePath + "-lsg.musicxml") lsgS = s.transpose(tI) lsgXML = musicxml.m21ToXml.GeneralObjectExporter().parse(lsgS) #render exercice vtk = verovio.toolkit() vtk.loadData(exerciceXML.decode('utf-8')) vtk.setOption("pageHeight", "600") vtk.setOption("pageWidth", "1500") vtk.setScale(45) vtk.setOption("header", "none") vtk.setOption("footer", "none") vtk.setOption("adjustPageHeight", "true") vtk.redoLayout() pageArray = [] for each in range(vtk.getPageCount()): strSVG = vtk.renderToSVG(each + 1) pageArray.append(strSVG) result['pngInk'] = bytes.decode(b64encode(renderPNG(pageArray[0])[0])) #render solution vtk.loadData(lsgXML.decode('utf-8')) vtk.setOption("pageHeight", "600") vtk.setOption("pageWidth", "1650") vtk.setScale(45) vtk.setOption("adjustPageHeight", "true") vtk.redoLayout() pageArrayLsg = [] for each in range(vtk.getPageCount()): strSVG = vtk.renderToSVG(each + 1) pageArrayLsg.append(strSVG) result['pngInkLsg'] = bytes.decode(b64encode( renderPNG(pageArrayLsg[0])[0])) #get hint if there are some. result["hint"] = collectHintsForFigures(modTypeUsed) #check if something is rendered if result["pngInk"]: result["done"] = True #headers = { "Access-Control-Request-Headers": "X-Requested-With, accept, content-type", # 'Access-Control-Allow-Methods': 'GET, POST', # 'Access-Control-Allow-Origin': '*'}, headers resp = make_response((result)) return resp
def neueAufgabe(): #init a dict to be returned in the end result = {} modDict = { "Loewe III": MODULS_FOLDER + "loewe-3", "Loewe II": MODULS_FOLDER + "loewe-2", "Loewe I": MODULS_FOLDER + "loewe-1", "Loewe IV": MODULS_FOLDER + "loewe-4", "Loewe V": MODULS_FOLDER + "loewe-5", "Loewe VI": MODULS_FOLDER + "loewe-6", "Loewe VII": MODULS_FOLDER + "loewe-7", "Loewe VIII": MODULS_FOLDER + "loewe-8", "Loewe IX": MODULS_FOLDER + "loewe-9", "Loewe X": MODULS_FOLDER + "loewe-10", "Loewe XI": MODULS_FOLDER + "loewe-11", "Teufelsmühle I": MODULS_FOLDER + "teufelsmuehle-1", } modTypeUsed = "" requestedMod = request.form.get("modType") isAppRequest = True print(requestedMod) #See what was requested. Website und App send Lists (as json) or Strings. try: requestDataType = request.form.get("dataType") requestedMod = json.loads(requestedMod) modTypeUsed = random.choice(requestedMod) except: modTypeUsed = requestedMod #isAppRequest = False #find the xml paths of the example. thePath = modDict[modTypeUsed] tInts = [ "A-4", "P-4", "M-3", "m-3", "M-2", "M-2", "m-2", "P1", "P1", "m2", "M2", "M2", "m3", "M3", "P4", "A4" ] tI = random.choice(tInts) s = converter.parse(thePath + ".musicxml") exS = s.transpose(tI) exerciceXML = musicxml.m21ToXml.GeneralObjectExporter().parse(exS) s = converter.parse(thePath + "-lsg.musicxml") lsgS = s.transpose(tI) lsgXML = musicxml.m21ToXml.GeneralObjectExporter().parse(lsgS) #render exercice vtk = verovio.toolkit() vtk.loadData(exerciceXML.decode('utf-8')) #vtk.setOption("pageHeight", "600") vtk.setOption("pageWidth", "980") vtk.setScale(40) vtk.setOption("header", "none") vtk.setOption("footer", "none") vtk.setOption("adjustPageHeight", "true") #vtk.setBorder(0) vtk.redoLayout() pageArray = [] for each in range(vtk.getPageCount()): strSVG = vtk.renderToSVG(each + 1) pageArray.append(strSVG) result["svg"] = pageArray #pngImg = b64encode(svg2png(pageArray[0], output_height=200, scale=1.5)) #result["png"] = bytes.decode(pngImg) svgFile = io.StringIO(pageArray[0]) img = svg2rlg(svgFile) #print(pageArray[0]) #strSvg = img.asString("png") if requestDataType == 'png': result['png'] = bytes.decode(b64encode(img.asString('png'))) result['pngInk'] = bytes.decode(b64encode(renderPNG(pageArray[0])[0])) #print(strSvg, result['png'], pageArray[0]) #strSvg #render solution vtk.loadData(lsgXML.decode('utf-8')) vtk.setOption("pageHeight", "600") vtk.setOption("pageWidth", "980") vtk.setScale(40) vtk.setOption("adjustPageHeight", "true") #vtk.setBorder(0) vtk.redoLayout() pageArrayLsg = [] for each in range(vtk.getPageCount()): strSVG = vtk.renderToSVG(each + 1) pageArrayLsg.append(strSVG) #get hints if necessary result["hint"] = collectHintsForFigures(modTypeUsed) #deliver svg as a jsonified result result["lsg"] = pageArrayLsg if requestDataType == 'png': result['pngInkLsg'] = bytes.decode( b64encode(renderPNG(pageArrayLsg[0])[0])) #check if something is rendered if result["svg"] != []: result["done"] = True #headers = { "Access-Control-Request-Headers": "X-Requested-With, accept, content-type", # 'Access-Control-Allow-Methods': 'GET, POST', # 'Access-Control-Allow-Origin': '*'} #{}, headers resp = make_response((result)) return resp