-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchromaprint_utils.py
More file actions
240 lines (225 loc) · 7.35 KB
/
chromaprint_utils.py
File metadata and controls
240 lines (225 loc) · 7.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
import subprocess
import tempfile
import os
import json
import shutil
import time
import logging
from config import FP_SUBPROCESS_TIMEOUT_SEC, load_config
from utils.path_helpers import ensure_long_path, strip_ext_prefix
verbose: bool = True
_logger = logging.getLogger(__name__)
def _dlog(label: str, msg: str) -> None:
if not verbose:
return
_logger.debug(f"{time.strftime('%H:%M:%S')} [{label}] {msg}")
# Backwards compatibility -------------------------------------------------
strip_long_path_prefix = strip_ext_prefix
class FingerprintError(Exception):
"""Raised when fingerprint computation fails."""
def _tail_stderr(stderr_text: str, max_lines: int = 10) -> str:
if not stderr_text:
return ""
lines = stderr_text.strip().splitlines()
if len(lines) > max_lines:
lines = lines[-max_lines:]
return "\n".join(lines).strip()
def ensure_tool(name: str) -> None:
"""Raise RuntimeError if external tool is missing."""
if shutil.which(name) is None:
raise FingerprintError(f"Required tool '{name}' not found")
def trim_silence(
input_path: str,
*,
threshold_db: float = -50.0,
min_silence_duration: float = 0.5,
sample_rate: int = 44100,
channels: int = 1,
) -> str:
"""Use FFmpeg to trim leading and trailing silence."""
if not os.path.exists(input_path):
raise FingerprintError(f"file missing: {input_path}")
ensure_tool("ffmpeg")
tmp = tempfile.NamedTemporaryFile(suffix=".wav", delete=False)
tmp.close()
output_path = tmp.name
ffmpeg_filter = (
f"silenceremove=start_periods=1:start_threshold={threshold_db}dB:start_duration={min_silence_duration},"
"areverse,"
f"silenceremove=start_periods=1:start_threshold={threshold_db}dB:start_duration={min_silence_duration},"
"areverse"
)
cmd = [
"ffmpeg",
"-y",
"-i",
ensure_long_path(input_path),
"-af",
ffmpeg_filter,
"-ar",
str(sample_rate),
"-ac",
str(channels),
output_path,
]
start = time.perf_counter()
_logger.info("Trim silence ffmpeg start: path=%s cmd=%s", input_path, cmd)
proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
elapsed = time.perf_counter() - start
_logger.info(
"Trim silence ffmpeg end: path=%s returncode=%s elapsed=%.2fs",
input_path,
proc.returncode,
elapsed,
)
if proc.returncode != 0:
os.remove(output_path)
msg = _tail_stderr(proc.stderr.decode(errors="ignore"))
_logger.error(
"Trim silence ffmpeg failed: path=%s returncode=%s stderr_tail=%s",
input_path,
proc.returncode,
msg,
)
raise FingerprintError(f"FFmpeg error: {msg}")
return output_path
def fingerprint_fpcalc(
path: str,
*,
trim: bool = True,
start_sec: float = 0.0,
duration_sec: float = 120.0,
threshold_db: float = -50.0,
min_silence_duration: float = 0.5,
) -> str | None:
"""Return fingerprint string computed via fpcalc."""
if not os.path.exists(path):
raise FingerprintError(f"file missing: {path}")
ensure_tool("fpcalc")
ensure_tool("ffmpeg")
tmp1 = None
tmp2 = None
to_process = path
try:
cfg = load_config()
timeout_sec = float(cfg.get("fingerprint_subprocess_timeout_sec", FP_SUBPROCESS_TIMEOUT_SEC))
if trim:
tmp1 = trim_silence(
path,
threshold_db=threshold_db,
min_silence_duration=min_silence_duration,
)
else:
tmp1 = path
tmp2 = tempfile.NamedTemporaryFile(suffix=".wav", delete=False)
tmp2.close()
ffmpeg_cmd = [
"ffmpeg",
"-y",
"-ss",
str(start_sec),
"-t",
str(duration_sec),
"-i",
ensure_long_path(tmp1),
"-ar",
str(44100),
"-ac",
str(1),
tmp2.name,
]
try:
start = time.perf_counter()
_logger.info(
"Fingerprint ffmpeg start: path=%s cmd=%s timeout=%.2fs",
path,
ffmpeg_cmd,
timeout_sec,
)
subprocess.run(
ffmpeg_cmd,
check=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
timeout=timeout_sec,
)
elapsed = time.perf_counter() - start
_logger.info(
"Fingerprint ffmpeg end: path=%s elapsed=%.2fs output=%s",
path,
elapsed,
tmp2.name,
)
except subprocess.TimeoutExpired as exc:
_logger.error(
"Fingerprint ffmpeg timeout: path=%s timeout=%.2fs",
path,
timeout_sec,
)
raise FingerprintError("Fingerprint timeout") from exc
except subprocess.CalledProcessError as exc:
msg = _tail_stderr((exc.stderr or b"").decode(errors="ignore"))
_logger.error(
"Fingerprint ffmpeg failed: path=%s returncode=%s stderr_tail=%s",
path,
exc.returncode,
msg,
)
raise FingerprintError(f"FFmpeg error: {msg}") from exc
to_process = tmp2.name
safe_path = strip_ext_prefix(to_process)
cmd = ["fpcalc", "-json", safe_path]
_logger.info(
"Fingerprint fpcalc start: path=%s cmd=%s timeout=%.2fs",
path,
cmd,
timeout_sec,
)
_dlog("FPCLI", f"cmd={cmd}")
try:
start = time.perf_counter()
proc = subprocess.run(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
timeout=timeout_sec,
)
except subprocess.TimeoutExpired as exc:
_logger.error(
"Fingerprint fpcalc timeout: path=%s timeout=%.2fs",
path,
timeout_sec,
)
raise FingerprintError("Fingerprint timeout") from exc
elapsed = time.perf_counter() - start
_logger.info(
"Fingerprint fpcalc end: path=%s returncode=%s elapsed=%.2fs",
path,
proc.returncode,
elapsed,
)
_dlog("FPCLI", f"stdout={proc.stdout.strip()}")
_dlog("FPCLI", f"stderr={_tail_stderr(proc.stderr)}")
if proc.returncode != 0:
_logger.error(
"Fingerprint fpcalc failed: path=%s returncode=%s stderr_tail=%s",
path,
proc.returncode,
_tail_stderr(proc.stderr),
)
raise FingerprintError(_tail_stderr(proc.stderr))
data = json.loads(proc.stdout)
fp = data.get("fingerprint")
if not fp:
return None
fp_str = " ".join(fp.split(","))
_dlog("FP", f"prefix={fp_str[:16]} len={len(fp_str)}")
return fp_str
finally:
for t in (tmp1 if trim else None, tmp2.name if tmp2 else None):
if t and os.path.exists(t) and t != path:
try:
os.remove(t)
except OSError:
pass