Skip to content

Commit 9d699b1

Browse files
authored
perf: use hashing to determine the format in infer/lib/audio.py (#26)
1 parent 70b43e8 commit 9d699b1

File tree

1 file changed

+21
-14
lines changed

1 file changed

+21
-14
lines changed

infer/lib/audio.py

Lines changed: 21 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,24 @@
1-
import platform
1+
from io import BufferedWriter, BytesIO
2+
from pathlib import Path
3+
from typing import Dict
24
import ffmpeg
35
import numpy as np
46
import av
57

8+
video_format_dict: Dict[str, str] = {
9+
"m4a": "mp4",
10+
}
611

7-
def wav2(i, o, format):
12+
audio_format_dict: Dict[str, str] = {
13+
"ogg": "libvorbis",
14+
"mp4": "aac",
15+
}
16+
17+
def wav2(i: BytesIO, o: BufferedWriter, format: str):
818
inp = av.open(i, "r")
9-
if format == "m4a":
10-
format = "mp4"
19+
format = video_format_dict.get(format, format)
1120
out = av.open(o, "w", format=format)
12-
if format == "ogg":
13-
format = "libvorbis"
14-
if format == "mp4":
15-
format = "aac"
21+
format = audio_format_dict.get(format, format)
1622

1723
ostream = out.add_stream(format)
1824

@@ -27,12 +33,15 @@ def wav2(i, o, format):
2733
inp.close()
2834

2935

30-
def load_audio(file, sr):
36+
def load_audio(file: str, sr: int) -> np.ndarray:
37+
if not Path(file).exists():
38+
raise FileNotFoundError(f"File not found: {file}")
39+
3140
try:
3241
# https://github.com/openai/whisper/blob/main/whisper/audio.py#L26
3342
# This launches a subprocess to decode audio while down-mixing and resampling as necessary.
3443
# Requires the ffmpeg CLI and `ffmpeg-python` package to be installed.
35-
file = clean_path(file) # 防止小白拷路径头尾带了空格和"和回车
44+
file = str(clean_path(file)) # 防止小白拷路径头尾带了空格和"和回车
3645
out, _ = (
3746
ffmpeg.input(file, threads=0)
3847
.output("-", format="f32le", acodec="pcm_f32le", ac=1, ar=sr)
@@ -44,7 +53,5 @@ def load_audio(file, sr):
4453
return np.frombuffer(out, np.float32).flatten()
4554

4655

47-
def clean_path(path_str):
48-
if platform.system() == "Windows":
49-
path_str = path_str.replace("/", "\\")
50-
return path_str.strip(" ").strip('"').strip("\n").strip('"').strip(" ")
56+
def clean_path(path: str) -> Path:
57+
return Path(path.strip(' "\n')).resolve()

0 commit comments

Comments
 (0)