hoyoMusic / convert.py
Monan Zhou
Upload 5 files
6c48757 verified
raw
history blame
2.66 kB
import os
import sys
import fitz
import subprocess
from PIL import Image
from music21 import converter
from utils import download
if sys.platform.startswith("linux"):
apkname = "MuseScore.AppImage"
extra_dir = "squashfs-root"
download(
filename=apkname,
url="https://master.dl.sourceforge.net/project/musescore.mirror/v4.2.0/MuseScore-4.2.0.233521125-x86_64.AppImage?viasf=1",
)
if not os.path.exists(extra_dir):
subprocess.run(["chmod", "+x", f"./{apkname}"])
subprocess.run([f"./{apkname}", "--appimage-extract"])
MSCORE = f"./{extra_dir}/AppRun"
os.environ["QT_QPA_PLATFORM"] = "offscreen"
else:
MSCORE = "D:/Program Files/MuseScore 3/bin/MuseScore3.exe"
def abc_to_midi(abc_content, output_midi_path):
score = converter.parse(abc_content, format="abc")
score.write("midi", fp=output_midi_path)
return output_midi_path
def abc_to_musicxml(abc_content, output_xml_path):
score = converter.parse(abc_content, format="abc")
score.write("musicxml", fp=output_xml_path)
return output_xml_path
def musicxml_to_mxl(xml_path):
mxl_file = xml_path.replace(".musicxml", ".mxl")
command = [MSCORE, "-o", mxl_file, xml_path]
result = subprocess.run(command)
print(result)
return mxl_file
def midi2wav(mid_file: str):
wav_file = mid_file.replace(".mid", ".wav")
command = [MSCORE, "-o", wav_file, mid_file]
result = subprocess.run(command)
print(result)
return wav_file
def pdf2img(pdf_path: str):
output_path = pdf_path.replace(".pdf", ".jpg")
doc = fitz.open(pdf_path)
# 创建一个图像列表
images = []
for page_number in range(doc.page_count):
page = doc[page_number]
# 将页面渲染为图像
image = page.get_pixmap()
# 将图像添加到列表
images.append(
Image.frombytes("RGB", [image.width, image.height], image.samples)
)
# 竖向合并图像
merged_image = Image.new(
"RGB", (images[0].width, sum(image.height for image in images))
)
y_offset = 0
for image in images:
merged_image.paste(image, (0, y_offset))
y_offset += image.height
# 保存合并后的图像为JPG
merged_image.save(output_path, "JPEG")
# 关闭PDF文档
doc.close()
return output_path
def mxl2jpg(mxl_file: str):
pdf_score = mxl_file.replace(".mxl", ".pdf")
command = [MSCORE, "-o", pdf_score, mxl_file]
result = subprocess.run(command)
print(result)
return pdf_score, pdf2img(pdf_score)