muscriptor2sky-skill 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- m2s_skill/__init__.py +32 -0
- m2s_skill/__main__.py +5 -0
- m2s_skill/cli.py +108 -0
- m2s_skill/doctor.py +118 -0
- m2s_skill/fetch.py +244 -0
- m2s_skill/ffmpeg.py +174 -0
- m2s_skill/pipeline.py +215 -0
- m2s_skill/transcribe.py +250 -0
- muscriptor2sky_skill-1.0.0.dist-info/METADATA +254 -0
- muscriptor2sky_skill-1.0.0.dist-info/RECORD +14 -0
- muscriptor2sky_skill-1.0.0.dist-info/WHEEL +5 -0
- muscriptor2sky_skill-1.0.0.dist-info/entry_points.txt +2 -0
- muscriptor2sky_skill-1.0.0.dist-info/licenses/LICENSE +21 -0
- muscriptor2sky_skill-1.0.0.dist-info/top_level.txt +1 -0
m2s_skill/pipeline.py
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""
|
|
3
|
+
一条龙编排:链接/音频 -> 音频 -> MIDI -> 光遇琴谱
|
|
4
|
+
================================================
|
|
5
|
+
|
|
6
|
+
四个阶段:
|
|
7
|
+
|
|
8
|
+
1. 取音频 链接 -> yt-dlp(优先纯音频流,不需要 ffmpeg)
|
|
9
|
+
2. 转谱 音频 -> muscriptor API -> MIDI
|
|
10
|
+
3. 转琴谱 MIDI -> muscriptor2sky -> SkyStudio .txt(默认 C 调)
|
|
11
|
+
4. 报告 整理成用户能看懂的一段话
|
|
12
|
+
|
|
13
|
+
关于 ffmpeg
|
|
14
|
+
-----------
|
|
15
|
+
不是所有平台都需要它:
|
|
16
|
+
|
|
17
|
+
· B站/YouTube 有纯音频流 -> 直接下 m4a,全程不碰 ffmpeg
|
|
18
|
+
· 小红书/抖音 只有视频流 -> 必须 ffmpeg 抽音轨
|
|
19
|
+
|
|
20
|
+
所以这里不把 ffmpeg 当硬性前置条件,而是在真正需要时才要求。
|
|
21
|
+
"""
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import os
|
|
25
|
+
import sys
|
|
26
|
+
import tempfile
|
|
27
|
+
import time
|
|
28
|
+
|
|
29
|
+
from . import fetch as F
|
|
30
|
+
from . import ffmpeg as FF
|
|
31
|
+
from . import transcribe as T
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _find_muscriptor2sky():
|
|
35
|
+
"""定位 muscriptor2sky 包。优先已安装,其次找兄弟仓库。"""
|
|
36
|
+
try:
|
|
37
|
+
import muscriptor2sky # noqa: F401
|
|
38
|
+
return True
|
|
39
|
+
except Exception:
|
|
40
|
+
pass
|
|
41
|
+
|
|
42
|
+
here = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
43
|
+
for cand in (
|
|
44
|
+
os.path.join(os.path.dirname(here), 'muscriptor2sky-github'),
|
|
45
|
+
os.path.join(os.path.dirname(here), 'muscriptor2sky'),
|
|
46
|
+
):
|
|
47
|
+
if os.path.isdir(os.path.join(cand, 'muscriptor2sky')):
|
|
48
|
+
sys.path.insert(0, cand)
|
|
49
|
+
return True
|
|
50
|
+
return False
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def midi_to_sheet(midi_path, out_txt, name=None, author=None, transcribed=None,
|
|
54
|
+
pitch_level=0, max_poly=0, grid=0.25):
|
|
55
|
+
"""MIDI -> SkyStudio 琴谱。默认 C 调(pitchLevel=0)。"""
|
|
56
|
+
if not _find_muscriptor2sky():
|
|
57
|
+
raise RuntimeError(
|
|
58
|
+
"没有找到 muscriptor2sky。\n"
|
|
59
|
+
"装一下:pip install muscriptor2sky\n"
|
|
60
|
+
"或者把 muscriptor2sky 仓库放在同级目录。"
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
import types
|
|
64
|
+
from muscriptor2sky.core import (
|
|
65
|
+
read_midi, midi_to_sky, write_sky, preview, skyr_parse,
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
args = types.SimpleNamespace(
|
|
69
|
+
input=midi_path, out=out_txt,
|
|
70
|
+
name=name or os.path.splitext(os.path.basename(midi_path))[0],
|
|
71
|
+
author=author or '',
|
|
72
|
+
arranged=None,
|
|
73
|
+
transcribed=transcribed,
|
|
74
|
+
bpm=None,
|
|
75
|
+
bits_per_page=16,
|
|
76
|
+
pitch_level=int(pitch_level or 0),
|
|
77
|
+
virtual_notes=False,
|
|
78
|
+
encoding='utf-16',
|
|
79
|
+
root=60,
|
|
80
|
+
transpose='auto',
|
|
81
|
+
grid=grid,
|
|
82
|
+
max_poly=max_poly,
|
|
83
|
+
verify=True,
|
|
84
|
+
ppq=480,
|
|
85
|
+
note_len=0.25,
|
|
86
|
+
no_preview=True,
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
m = read_midi(midi_path)
|
|
90
|
+
notes, info = midi_to_sky(m, args)
|
|
91
|
+
if not notes:
|
|
92
|
+
raise RuntimeError("转出来没有任何音符(" + str(info.get("error", "")) + ")")
|
|
93
|
+
write_sky(out_txt, notes, args, info)
|
|
94
|
+
|
|
95
|
+
verify = None
|
|
96
|
+
try:
|
|
97
|
+
verify = skyr_parse(out_txt)
|
|
98
|
+
except Exception:
|
|
99
|
+
pass
|
|
100
|
+
|
|
101
|
+
return {
|
|
102
|
+
'notes': notes,
|
|
103
|
+
'info': info,
|
|
104
|
+
'verify': verify,
|
|
105
|
+
'preview': preview(notes),
|
|
106
|
+
'out': out_txt,
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def run(source, out_dir=None, name=None, author=None, transcribed=None,
|
|
111
|
+
pitch_level=0, max_poly=0, grid=0.25, instruments=None,
|
|
112
|
+
work_dir=None, on_step=None, on_progress=None, on_log=None):
|
|
113
|
+
"""跑完整流程。
|
|
114
|
+
|
|
115
|
+
参数
|
|
116
|
+
----
|
|
117
|
+
source : str 视频链接 / 音频文件 / 视频文件 / MIDI 文件
|
|
118
|
+
out_dir: str 输出目录(默认当前目录)
|
|
119
|
+
instruments : list 只保留这些乐器,如 ['acoustic_piano']
|
|
120
|
+
"""
|
|
121
|
+
t0 = time.time()
|
|
122
|
+
out_dir = os.path.abspath(out_dir or os.getcwd())
|
|
123
|
+
os.makedirs(out_dir, exist_ok=True)
|
|
124
|
+
tmp = work_dir or tempfile.mkdtemp(prefix='m2s-skill-')
|
|
125
|
+
os.makedirs(tmp, exist_ok=True)
|
|
126
|
+
|
|
127
|
+
def step(msg):
|
|
128
|
+
if on_step:
|
|
129
|
+
on_step(msg)
|
|
130
|
+
|
|
131
|
+
result = {'steps': [], 'work_dir': tmp}
|
|
132
|
+
|
|
133
|
+
src = (source or '').strip()
|
|
134
|
+
if not src:
|
|
135
|
+
raise RuntimeError("没有给我任何链接或文件")
|
|
136
|
+
|
|
137
|
+
ext = os.path.splitext(src)[1].lower()
|
|
138
|
+
is_midi_input = ext in ('.mid', '.midi') and os.path.isfile(src)
|
|
139
|
+
|
|
140
|
+
if is_midi_input:
|
|
141
|
+
step("输入已经是 MIDI,跳过下载和转谱")
|
|
142
|
+
midi_path = src
|
|
143
|
+
result['steps'].append(('输入', 'MIDI 文件,直接转琴谱'))
|
|
144
|
+
else:
|
|
145
|
+
# ---------- 阶段 1:拿到可上传的音频 ----------
|
|
146
|
+
if F.looks_like_url(src):
|
|
147
|
+
step("正在下载视频…")
|
|
148
|
+
audio = F.prepare_audio(
|
|
149
|
+
src, tmp, on_log=on_log,
|
|
150
|
+
on_note=lambda m: step(m),
|
|
151
|
+
)
|
|
152
|
+
result['audio'] = audio
|
|
153
|
+
result['steps'].append(('音频', os.path.basename(audio)))
|
|
154
|
+
|
|
155
|
+
# ---------- 阶段 2:音频 -> MIDI ----------
|
|
156
|
+
step("正在转谱(音频 -> MIDI),这一步最慢…")
|
|
157
|
+
midi_bytes, meta = T.transcribe(
|
|
158
|
+
audio, instruments=instruments, on_progress=on_progress,
|
|
159
|
+
)
|
|
160
|
+
base = name or os.path.splitext(os.path.basename(audio))[0]
|
|
161
|
+
midi_path = os.path.join(tmp, base + '.mid')
|
|
162
|
+
with open(midi_path, 'wb') as f:
|
|
163
|
+
f.write(midi_bytes)
|
|
164
|
+
result['midi'] = midi_path
|
|
165
|
+
result['transcribe_meta'] = meta
|
|
166
|
+
result['steps'].append(('转谱', '%d 字节 MIDI' % len(midi_bytes)))
|
|
167
|
+
|
|
168
|
+
# ---------- 阶段 3:MIDI -> 琴谱 ----------
|
|
169
|
+
step("正在转换成光遇 15 键琴谱…")
|
|
170
|
+
if not name:
|
|
171
|
+
name = os.path.splitext(os.path.basename(midi_path))[0]
|
|
172
|
+
out_txt = os.path.join(out_dir, name + '.txt')
|
|
173
|
+
sheet = midi_to_sheet(
|
|
174
|
+
midi_path, out_txt, name=name, author=author, transcribed=transcribed,
|
|
175
|
+
pitch_level=pitch_level, max_poly=max_poly, grid=grid,
|
|
176
|
+
)
|
|
177
|
+
result.update(sheet)
|
|
178
|
+
result['midi'] = midi_path
|
|
179
|
+
result['elapsed_s'] = round(time.time() - t0, 1)
|
|
180
|
+
result['steps'].append(('琴谱', os.path.basename(out_txt)))
|
|
181
|
+
|
|
182
|
+
step("完成")
|
|
183
|
+
return result
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def format_report(r):
|
|
187
|
+
"""把结果整理成给用户看的一段中文报告。"""
|
|
188
|
+
info = r.get('info') or {}
|
|
189
|
+
st = info.get('stat') or {}
|
|
190
|
+
mel = info.get('melody') or {}
|
|
191
|
+
lines = []
|
|
192
|
+
|
|
193
|
+
lines.append('已生成光遇琴谱:' + r['out'])
|
|
194
|
+
lines.append('')
|
|
195
|
+
lines.append('源音符 %d → 输出音符 %d' % (info.get('src', 0), len(r.get('notes') or [])))
|
|
196
|
+
lines.append('移调 %+d 半音 bpm %.1f' % (info.get('transpose', 0), info.get('bpm', 0)))
|
|
197
|
+
lines.append('映射:精确 %d / 八度折叠 %d / 半音吸附 %d / 同键合并 %d / 超复音丢弃 %d' % (
|
|
198
|
+
st.get('exact', 0), st.get('octave', 0), st.get('snapped', 0),
|
|
199
|
+
st.get('merged', 0), st.get('dropped', 0)))
|
|
200
|
+
if mel:
|
|
201
|
+
lines.append('主旋律保留 %d/%d(%.1f%%)' % (
|
|
202
|
+
mel.get('kept', 0), mel.get('total', 0), mel.get('rate', 0)))
|
|
203
|
+
pl = info.get('pitch_level', 0)
|
|
204
|
+
if pl:
|
|
205
|
+
lines.append('定调 pitchLevel = %d(游戏内需把乐器调到该调)' % pl)
|
|
206
|
+
else:
|
|
207
|
+
lines.append('定调 pitchLevel = 0(C 调,游戏默认,直接能弹)')
|
|
208
|
+
v = r.get('verify')
|
|
209
|
+
if v:
|
|
210
|
+
lines.append('格式自检:%s | 音符 %d | 最大复音 %d | 时长 %.1fs' % (
|
|
211
|
+
v.get('encoding', ''), v.get('noteCount', 0),
|
|
212
|
+
v.get('polyphony', 0), v.get('durationMs', 0) / 1000.0))
|
|
213
|
+
if r.get('elapsed_s'):
|
|
214
|
+
lines.append('总耗时 %.1f 秒' % r['elapsed_s'])
|
|
215
|
+
return '\n'.join(lines)
|
m2s_skill/transcribe.py
ADDED
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""
|
|
3
|
+
muscriptor API 客户端
|
|
4
|
+
=====================
|
|
5
|
+
|
|
6
|
+
直接调用 muscriptor.kyutai.org 的 /transcribe 接口,把音频转成 MIDI。
|
|
7
|
+
|
|
8
|
+
为什么不用浏览器自动化
|
|
9
|
+
----------------------
|
|
10
|
+
实测确认 muscriptor 是「浏览器 + 服务端」架构:前端只负责解码音频、
|
|
11
|
+
上传文件、渲染结果,真正的转谱推理在服务端。浏览器里唯一的上传动作是:
|
|
12
|
+
|
|
13
|
+
POST /transcribe multipart/form-data (file, 可选 instruments)
|
|
14
|
+
-> text/event-stream,逐条 SSE
|
|
15
|
+
|
|
16
|
+
所以只要按同样的方式发请求,就能拿到同样的结果,不需要开浏览器。
|
|
17
|
+
这样 skill 才能做到「一条命令跑完」,也才能在无图形界面的环境里工作。
|
|
18
|
+
|
|
19
|
+
服务端返回的事件流(每条一行 data: {json}):
|
|
20
|
+
|
|
21
|
+
{"type": "progress", "completed": n, "total": m}
|
|
22
|
+
{"type": "start", "pitch": 60, "start_time": 0.5, "index": 0, "instrument": "acoustic_piano"}
|
|
23
|
+
{"type": "end", "end_time": 1.2, "start_event_index": 0}
|
|
24
|
+
{"type": "transcription_complete", "data": "<base64 MIDI>", "beat_grid": {...} | null}
|
|
25
|
+
|
|
26
|
+
其中 data 就是标准 MIDI 文件的 base64,可以直接交给 muscriptor2sky。
|
|
27
|
+
|
|
28
|
+
注意:这是第三方公共服务,接口没有公开文档,随时可能变。
|
|
29
|
+
本模块把「协议细节」全部收在这里,万一接口变了只改这一个文件。
|
|
30
|
+
"""
|
|
31
|
+
from __future__ import annotations
|
|
32
|
+
|
|
33
|
+
import base64
|
|
34
|
+
import json
|
|
35
|
+
import mimetypes
|
|
36
|
+
import os
|
|
37
|
+
import time
|
|
38
|
+
import urllib.error
|
|
39
|
+
import urllib.request
|
|
40
|
+
import uuid
|
|
41
|
+
|
|
42
|
+
DEFAULT_ENDPOINT = "https://muscriptor.kyutai.org"
|
|
43
|
+
TRANSCRIBE_PATH = "/transcribe"
|
|
44
|
+
HEALTH_PATH = "/health"
|
|
45
|
+
INSTRUMENTS_PATH = "/instruments"
|
|
46
|
+
|
|
47
|
+
# 用户代理:保持和浏览器一致,避免被当作脚本拒绝
|
|
48
|
+
_UA = (
|
|
49
|
+
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
|
50
|
+
"(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class TranscribeError(RuntimeError):
|
|
55
|
+
"""转谱失败。message 是给最终用户看的中文说明。"""
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class _ServerBusy(Exception):
|
|
59
|
+
"""服务端忙(429/503),可重试。"""
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _build_multipart(file_path, file_name, fields):
|
|
63
|
+
"""手工拼 multipart/form-data。
|
|
64
|
+
|
|
65
|
+
不用 requests 是因为本项目坚持零第三方依赖 ——
|
|
66
|
+
用户可能是被 Agent 临时调用,不该先要求他装一堆包。
|
|
67
|
+
"""
|
|
68
|
+
boundary = "----m2sskill" + uuid.uuid4().hex
|
|
69
|
+
out = []
|
|
70
|
+
for k, v in (fields or {}).items():
|
|
71
|
+
if isinstance(v, (list, tuple)):
|
|
72
|
+
for item in v:
|
|
73
|
+
out.append(
|
|
74
|
+
("--%s\r\n" % boundary).encode()
|
|
75
|
+
+ ('Content-Disposition: form-data; name="%s"\r\n\r\n' % k).encode()
|
|
76
|
+
+ ("%s\r\n" % item).encode()
|
|
77
|
+
)
|
|
78
|
+
else:
|
|
79
|
+
out.append(
|
|
80
|
+
("--%s\r\n" % boundary).encode()
|
|
81
|
+
+ ('Content-Disposition: form-data; name="%s"\r\n\r\n' % k).encode()
|
|
82
|
+
+ ("%s\r\n" % v).encode()
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
ctype = mimetypes.guess_type(file_name)[0] or "application/octet-stream"
|
|
86
|
+
with open(file_path, "rb") as f:
|
|
87
|
+
payload = f.read()
|
|
88
|
+
out.append(
|
|
89
|
+
("--%s\r\n" % boundary).encode()
|
|
90
|
+
+ (
|
|
91
|
+
'Content-Disposition: form-data; name="file"; filename="%s"\r\n'
|
|
92
|
+
% file_name
|
|
93
|
+
).encode()
|
|
94
|
+
+ ("Content-Type: %s\r\n\r\n" % ctype).encode()
|
|
95
|
+
+ payload
|
|
96
|
+
+ b"\r\n"
|
|
97
|
+
)
|
|
98
|
+
out.append(("--%s--\r\n" % boundary).encode())
|
|
99
|
+
return b"".join(out), boundary
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def check_server(endpoint=DEFAULT_ENDPOINT, timeout=15):
|
|
103
|
+
"""检查服务是否在线。返回 True/False,不抛异常。"""
|
|
104
|
+
url = endpoint.rstrip("/") + HEALTH_PATH
|
|
105
|
+
req = urllib.request.Request(url, headers={"User-Agent": _UA})
|
|
106
|
+
try:
|
|
107
|
+
with urllib.request.urlopen(req, timeout=timeout) as r:
|
|
108
|
+
return r.status == 200
|
|
109
|
+
except Exception:
|
|
110
|
+
return False
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def list_instruments(endpoint=DEFAULT_ENDPOINT, timeout=20):
|
|
114
|
+
"""取服务端支持的乐器列表(用于只保留钢琴轨)。"""
|
|
115
|
+
url = endpoint.rstrip("/") + INSTRUMENTS_PATH
|
|
116
|
+
req = urllib.request.Request(url, headers={"User-Agent": _UA})
|
|
117
|
+
with urllib.request.urlopen(req, timeout=timeout) as r:
|
|
118
|
+
data = json.loads(r.read().decode("utf-8"))
|
|
119
|
+
return data.get("instruments", [])
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def transcribe(audio_path, endpoint=DEFAULT_ENDPOINT, instruments=None,
|
|
123
|
+
timeout=900, on_progress=None, retries=2):
|
|
124
|
+
"""把音频文件转成 MIDI 字节。
|
|
125
|
+
|
|
126
|
+
参数
|
|
127
|
+
----
|
|
128
|
+
audio_path : str 音频文件路径(mp3/wav/flac/m4a 等)
|
|
129
|
+
instruments: list 只要这些乐器(例如 ["acoustic_piano"])。
|
|
130
|
+
传 None 表示全部保留。
|
|
131
|
+
on_progress: callable 进度回调,签名 (completed, total, message)
|
|
132
|
+
retries : int 服务忙(429/503)时自动重试次数
|
|
133
|
+
|
|
134
|
+
返回
|
|
135
|
+
----
|
|
136
|
+
(midi_bytes, meta) meta 含 bpm / beats_per_bar / note_count
|
|
137
|
+
"""
|
|
138
|
+
if not os.path.isfile(audio_path):
|
|
139
|
+
raise TranscribeError("找不到音频文件:%s" % audio_path)
|
|
140
|
+
|
|
141
|
+
fields = {}
|
|
142
|
+
if instruments:
|
|
143
|
+
fields["instruments"] = list(instruments)
|
|
144
|
+
|
|
145
|
+
last_err = None
|
|
146
|
+
for attempt in range(retries + 1):
|
|
147
|
+
try:
|
|
148
|
+
return _transcribe_once(
|
|
149
|
+
audio_path, endpoint, fields, timeout, on_progress
|
|
150
|
+
)
|
|
151
|
+
except _ServerBusy as e:
|
|
152
|
+
last_err = e
|
|
153
|
+
if attempt < retries:
|
|
154
|
+
wait = min(60, 5 * (attempt + 1))
|
|
155
|
+
if on_progress:
|
|
156
|
+
on_progress(0, 1, "服务繁忙,%d 秒后重试(第 %d 次)" % (wait, attempt + 1))
|
|
157
|
+
time.sleep(wait)
|
|
158
|
+
continue
|
|
159
|
+
raise TranscribeError(
|
|
160
|
+
"转谱服务当前繁忙,请稍后再试。\n"
|
|
161
|
+
"如果一直失败,可以改用网页版手动转:https://muscriptor.kyutai.org/"
|
|
162
|
+
) from e
|
|
163
|
+
raise TranscribeError(str(last_err))
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _transcribe_once(audio_path, endpoint, fields, timeout, on_progress):
|
|
167
|
+
body, boundary = _build_multipart(
|
|
168
|
+
audio_path, os.path.basename(audio_path), fields
|
|
169
|
+
)
|
|
170
|
+
url = endpoint.rstrip("/") + TRANSCRIBE_PATH
|
|
171
|
+
req = urllib.request.Request(
|
|
172
|
+
url,
|
|
173
|
+
data=body,
|
|
174
|
+
method="POST",
|
|
175
|
+
headers={
|
|
176
|
+
"Content-Type": "multipart/form-data; boundary=%s" % boundary,
|
|
177
|
+
"Content-Length": str(len(body)),
|
|
178
|
+
"User-Agent": _UA,
|
|
179
|
+
"Origin": endpoint.rstrip("/"),
|
|
180
|
+
"Referer": endpoint.rstrip("/") + "/",
|
|
181
|
+
"X-Client-Id": "m2s-skill-" + uuid.uuid4().hex[:12],
|
|
182
|
+
},
|
|
183
|
+
)
|
|
184
|
+
|
|
185
|
+
try:
|
|
186
|
+
resp = urllib.request.urlopen(req, timeout=timeout)
|
|
187
|
+
except urllib.error.HTTPError as e:
|
|
188
|
+
if e.code in (429, 503, 502):
|
|
189
|
+
raise _ServerBusy("HTTP %d" % e.code)
|
|
190
|
+
detail = ""
|
|
191
|
+
try:
|
|
192
|
+
payload = json.loads(e.read().decode("utf-8", "replace"))
|
|
193
|
+
detail = payload.get("detail", "")
|
|
194
|
+
except Exception:
|
|
195
|
+
pass
|
|
196
|
+
raise TranscribeError(
|
|
197
|
+
"转谱服务返回错误 HTTP %d%s" % (e.code, (":" + detail) if detail else "")
|
|
198
|
+
)
|
|
199
|
+
except urllib.error.URLError as e:
|
|
200
|
+
raise TranscribeError(
|
|
201
|
+
"连不上转谱服务(%s)。\n请检查网络,或改用网页版:https://muscriptor.kyutai.org/"
|
|
202
|
+
% e.reason
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
midi_bytes = None
|
|
206
|
+
meta = {}
|
|
207
|
+
started = time.time()
|
|
208
|
+
|
|
209
|
+
with resp:
|
|
210
|
+
for raw_line in resp:
|
|
211
|
+
line = raw_line.decode("utf-8", "replace").strip()
|
|
212
|
+
if not line.startswith("data:"):
|
|
213
|
+
continue
|
|
214
|
+
payload = line[5:].strip()
|
|
215
|
+
if not payload:
|
|
216
|
+
continue
|
|
217
|
+
try:
|
|
218
|
+
ev = json.loads(payload)
|
|
219
|
+
except json.JSONDecodeError:
|
|
220
|
+
continue
|
|
221
|
+
|
|
222
|
+
etype = ev.get("type")
|
|
223
|
+
if etype == "progress":
|
|
224
|
+
if on_progress:
|
|
225
|
+
on_progress(
|
|
226
|
+
ev.get("completed", 0), ev.get("total", 1),
|
|
227
|
+
"转谱中 %s/%s" % (ev.get("completed", 0), ev.get("total", 1)),
|
|
228
|
+
)
|
|
229
|
+
elif etype == "transcription_complete":
|
|
230
|
+
data = ev.get("data")
|
|
231
|
+
if not data:
|
|
232
|
+
raise TranscribeError("服务端返回成功但没带 MIDI 数据")
|
|
233
|
+
midi_bytes = base64.b64decode(data)
|
|
234
|
+
grid = ev.get("beat_grid") or {}
|
|
235
|
+
meta = {
|
|
236
|
+
"bpm": grid.get("bpm"),
|
|
237
|
+
"beats_per_bar": grid.get("beats_per_bar"),
|
|
238
|
+
"onset_delay": grid.get("onset_delay", 0),
|
|
239
|
+
"has_beat_grid": bool(grid),
|
|
240
|
+
"elapsed_s": round(time.time() - started, 1),
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
if midi_bytes is None:
|
|
244
|
+
raise TranscribeError(
|
|
245
|
+
"转谱没有完成(服务端没有返回 MIDI)。\n"
|
|
246
|
+
"可能是音频太长或格式不支持,试试换个文件,或用网页版。"
|
|
247
|
+
)
|
|
248
|
+
if midi_bytes[:4] != b"MThd":
|
|
249
|
+
raise TranscribeError("服务端返回的数据不是标准 MIDI")
|
|
250
|
+
return midi_bytes, meta
|