這篇在做什麼 BlackBear-Flash-ASR 是 4,764 萬參數的臺灣國語語音辨識模型,一般電腦的 CPU 就能跑。這篇從安裝開始,依序做出逐字稿、字幕檔、即時字幕和瀏覽器版,最後用自己的錄音微調,讓它更懂你的場景。每一步的程式都實際跑過。完整的參數與評測請看模型說明頁。
0. 你需要什麼
- 一台 Linux 或 macOS 電腦,Python 3.10 以上。辨識只需要 CPU。
- 微調需要 GPU:全模型約 7 GB 顯示卡記憶體,只調輸出層約 2.4 GB。
- 一個 Hugging Face 帳號,用來申請下載權重。
1. 安裝與申請權重
git clone https://github.com/OpenFormosa/blackbear-flash-asr && cd blackbear-flash-asr
pip install -e .
huggingface-cli login
到 Hugging Face 模型頁填寫申請表,送出後自動核准。第一次載入模型會下載約 191 MB 的權重。
2. 第一份逐字稿
from blackbear_flash import BlackBearFlash
asr = BlackBearFlash.from_pretrained("OpenFormosa/blackbear-flash-asr")
print(asr.transcribe("audio.wav"))
輸出沒有標點,例如「每天帶小女兒走路上學」。錄音是臺語的話,加上 language="nan",輸出會是中文。
很多檔案一起跑時用 transcribe_batch,程式會依長度排序、併成一批,比一個一個跑快很多:
import glob
files = sorted(glob.glob("recordings/*.wav"))
for f, text in zip(files, asr.transcribe_batch(files)):
print(f, text)
3. 幫影片做字幕檔
先用 ffmpeg 把影片的聲音抽出來,再用 segments() 切段。它在模型超過 0.6 秒沒出字的地方切開,回傳每段的開始、結束時間和文字:
ffmpeg -i lecture.mp4 -vn -ac 1 -ar 16000 lecture.wav
def ts(t):
h, m = divmod(int(t), 3600); m, s = divmod(m, 60)
return f"{h:02d}:{m:02d}:{s:02d},{int(t % 1 * 1000):03d}"
with open("lecture.srt", "w", encoding="utf-8") as f:
for i, (start, end, text) in enumerate(asr.segments("lecture.wav"), 1):
f.write(f"{i}\n{ts(start)} --> {ts(end)}\n{text}\n\n")
把 lecture.srt 和影片放在一起,大部分播放器和剪輯軟體都能讀。兩個小提醒:
- 模型不偷看未來的聲音,所以時間會比實際說話晚零點幾秒。需要的話,可以在剪輯軟體裡把整份字幕往前移。
- 字幕段落太碎時,把
pause=調大,例如asr.segments("lecture.wav", pause=1.0)。
4. 即時字幕
stream() 每 0.64 秒出一次字,已經寫出的字不會再改。先用錄音檔試:
for event in asr.stream("lecture.wav"):
print(event["new"], end="", flush=True)
接麥克風時,把 16 kHz、int16 的聲音區塊交給 chunks=。下面用 sounddevice(pip install sounddevice):
import sounddevice as sd
def mic():
with sd.InputStream(samplerate=16000, channels=1, dtype="int16", blocksize=10240) as s:
while True:
data, _ = s.read(10240) # 0.64 秒
yield data[:, 0]
for event in asr.stream(chunks=mic()):
print(event["new"], end="", flush=True)
程式只保留模型看得到的最近約 16 秒聲音,所以講一小時也不會越跑越慢。桌機 CPU 上,每 0.64 秒的聲音約花 0.18 秒處理。
5. 放進瀏覽器
想讓別人不用安裝任何東西就能用,可以匯出成 ONNX,再用 onnxruntime-web 在瀏覽器裡跑。錄音不會離開使用者的電腦。
pip install onnx onnxruntime onnxscript
python scripts/export_onnx.py --model OpenFormosa/blackbear-flash-asr --out onnx/ --quantize int8 --check-audio audio.wav
int8 版只有 51.5 MB,Common Voice 錯誤率 17.34%,和 fp32 的 17.31% 幾乎一樣。網頁範例在 GitHub 的 web/,我們的試用頁就是這樣做的。
- 一定要加
--check-audio,用真實錄音比對 ONNX 和 PyTorch 的輸出。 - 匯出腳本會讓聲音前端(Mel 濾波器)保持 fp32。如果你自己量化,別把這一層也量化,錯誤率會壞到 83%。
- 靜態網站通常限制單一檔案大小。可以用
split -b 20m把模型切成小檔,在網頁裡依序下載再接起來。 - 在 GitHub Pages 上,瀏覽器只能用單執行緒,10 秒錄音約 0.9 秒辨識完。
6. 先量你的資料
微調前,先知道模型在你的錄音上表現如何。準備一份 jsonl,每行一段錄音和正確的逐字稿:
{"audio": "clips/0001.wav", "text": "今天我們來講梯度下降", "language": "zh"}
如果你的資料是一個資料夾,每個 xxx.wav 旁邊有同名的 xxx.txt 逐字稿,可以這樣產生:
import json, pathlib
def make_manifest(folder, out):
folder = pathlib.Path(folder)
with open(out, "w", encoding="utf-8") as f:
for wav in sorted(folder.glob("*.wav")):
text = wav.with_suffix(".txt").read_text(encoding="utf-8").strip()
f.write(json.dumps({"audio": str(wav.relative_to(pathlib.Path(out).parent)), "text": text, "language": "zh"}, ensure_ascii=False) + "\n")
make_manifest("data/clips_train", "data/train.jsonl")
make_manifest("data/clips_dev", "data/dev.jsonl")
然後量分數:
pip install -e ".[eval]"
python scripts/evaluate.py --model OpenFormosa/blackbear-flash-asr --manifest data/dev.jsonl --out before.jsonl
before.jsonl 裡有每句的模型輸出,可以看看錯的多半是哪些詞。
7. 用自己的錄音微調
準備資料的四個原則
- 每段 2 到 30 秒。 超過 30 秒的會被略過。長錄音先依字幕時間切段。
- dev 和 train 分開。 dev 用不同講者、不同天或不同影片的錄音,不然分數會太樂觀。
- 混入一般錄音。 只用場景資料,一般辨識會退步。我們建議場景資料和一般朗讀資料約 2:1,寫進同一個
train.jsonl。一般資料可以用 Common Voice 的臺灣國語。 - 逐字稿照實寫。 說了什麼就寫什麼,標點會自動拿掉。
開始訓練
python scripts/finetune.py --model OpenFormosa/blackbear-flash-asr \
--train data/train.jsonl --dev data/dev.jsonl --out runs/my-flash --train-part all
程式每 250 步量一次 dev 錯誤率,只保留最好的版本。常用參數:
| 參數 | 預設 | 什麼時候改 |
|---|---|---|
--train-part |
all |
只是多了新詞、錄音環境沒變時,改用 head(只調輸出層,約 2.4 GB 記憶體) |
--lr |
3e-5 | 通常不用改。調高很容易變差 |
--steps |
1500 | 資料只有幾小時時,最好的版本常出現在前幾百步 |
--batch-seconds |
240 | 顯示卡記憶體不夠時調低 |
用微調後的模型
asr = BlackBearFlash.from_pretrained("runs/my-flash")
用法和原本一模一樣,也可以照第 5 步匯出成 ONNX 放進瀏覽器。
確認有變好,也沒變差
python scripts/evaluate.py --model runs/my-flash --manifest data/dev.jsonl --out after.jsonl
python scripts/evaluate.py --model runs/my-flash --manifest data/general_test.jsonl
第二行用一般國語的測試集,確認一般辨識沒有退步。
8. 我們自己的實測
我們用 14 小時的單一講者課堂錄音試過。依影片切分,測試用的 3 部影片完全沒有參與訓練。
| 做法 | 沒看過的講次 | 一般國語(Common Voice 1,000 句) |
|---|---|---|
| 微調前 | 12.32 | 17.26 |
| 只用課堂錄音,600 步 | 10.02 | 20.12 |
| 課堂錄音與一般朗讀錄音約 2:1 混合,900 步 | 10.28 | 16.82 |
- 混合版在講次上進步 2 個百分點,一般國語沒有退步。只用課堂錄音雖然講次分數更好,一般國語卻退步了約 3 個百分點。
- 改對的多半是課程術語:Pper → paper、sequonc → sequence、AI ag → AI agent。
- 900 步在資料中心 GPU 上約 1.5 分鐘。
我們也試過拿 2.5 小時的 Common Voice 朗讀資料微調,1,000 句測試從 17.30 降到 16.58,但統計上不顯著。原因是這類資料和模型原本的訓練資料很像。和原本差異大的場景才值得微調,例如特定的麥克風、教室收音、口音,或大量專有名詞。
常見問題
可以加標點嗎? Flash 沒有標點。需要標點、改稿或回答錄音內容的問題,請用完整版 BlackBear-ASR。
可以給它一份專有名詞清單嗎? 不行,Flash 不支援熱詞。可以把含這些詞的錄音拿來微調,用 --train-part head 就夠了。
臺語可以用嗎? 可以,用 language="nan",輸出是中文。目前還沒有臺語公開測試集的分數,正式使用前請先用自己的資料量一次。
Windows 可以嗎? 還沒測試過。遇到問題歡迎到 GitHub 回報。
有問題或想分享你的微調結果,歡迎到 Discord 聊。
What this covers BlackBear-Flash-ASR is a 47.6M-parameter Taiwan Mandarin speech recognizer that runs on a laptop CPU. This guide goes from install to transcripts, subtitles, live captions and a browser build, then fine-tunes it on your own recordings. Every snippet was run. For all numbers, see the model page.
1. Install
Python 3.10+ on Linux or macOS. Transcription needs only a CPU; fine-tuning needs a GPU (about 7 GB for the full model, 2.4 GB for the output layer only).
git clone https://github.com/OpenFormosa/blackbear-flash-asr && cd blackbear-flash-asr
pip install -e .
huggingface-cli login
Fill in the access form on the model page (approval is automatic).
2. Transcribe
from blackbear_flash import BlackBearFlash
asr = BlackBearFlash.from_pretrained("OpenFormosa/blackbear-flash-asr")
print(asr.transcribe("audio.wav")) # no punctuation; language="nan" for Taigi
texts = asr.transcribe_batch(["a.wav", "b.wav"]) # batched by length, much faster
3. Subtitles
ffmpeg -i lecture.mp4 -vn -ac 1 -ar 16000 lecture.wav
def ts(t):
h, m = divmod(int(t), 3600); m, s = divmod(m, 60)
return f"{h:02d}:{m:02d}:{s:02d},{int(t % 1 * 1000):03d}"
with open("lecture.srt", "w", encoding="utf-8") as f:
for i, (start, end, text) in enumerate(asr.segments("lecture.wav"), 1):
f.write(f"{i}\n{ts(start)} --> {ts(end)}\n{text}\n\n")
Times lag speech by a few tenths of a second (no look-ahead). Raise pause= for fewer, longer cues.
4. Live captions
import sounddevice as sd # pip install sounddevice
def mic():
with sd.InputStream(samplerate=16000, channels=1, dtype="int16", blocksize=10240) as s:
while True:
data, _ = s.read(10240) # 0.64 s
yield data[:, 0]
for event in asr.stream(chunks=mic()): # or asr.stream("file.wav")
print(event["new"], end="", flush=True)
Text arrives every 0.64 s and is never revised. Only the last ~16 s of audio is kept, so an hour-long talk does not slow down: about 0.18 s of CPU per 0.64 s chunk on a desktop.
5. In the browser
pip install onnx onnxruntime onnxscript
python scripts/export_onnx.py --model OpenFormosa/blackbear-flash-asr --out onnx/ --quantize int8 --check-audio audio.wav
int8 is 51.5 MB with a 17.34% error rate (fp32: 17.31%). See web/ and our try page. Keep the Mel-filter layer in fp32 if you quantize yourself (otherwise 83% error); split the file with split -b 20m for static hosts. On GitHub Pages the browser runs single-threaded: about 0.9 s per 10 s clip.
6. Measure on your data
One JSON line per clip: {"audio": "clips/0001.wav", "text": "...", "language": "zh"}. Then:
pip install -e ".[eval]"
python scripts/evaluate.py --model OpenFormosa/blackbear-flash-asr --manifest data/dev.jsonl --out before.jsonl
7. Fine-tune
Clips of 2–30 s; dev from a different speaker, day or video; mix scene data with general read speech about 2:1 (for example Common Voice Taiwan Mandarin) in one train.jsonl; write what was said.
python scripts/finetune.py --model OpenFormosa/blackbear-flash-asr \
--train data/train.jsonl --dev data/dev.jsonl --out runs/my-flash --train-part all
It evaluates dev every 250 steps and keeps the best checkpoint. Use --train-part head for new words only; keep --lr 3e-5; lower --batch-seconds on small GPUs. Load with BlackBearFlash.from_pretrained("runs/my-flash"), then evaluate both your dev set and a general Mandarin test set.
8. Our results
On 14 h of single-speaker lectures (test videos unseen): before 12.32 / general 17.26; lectures only 10.02 / 20.12; lectures + read speech ~2:1, 900 steps (~1.5 min) 10.28 / 16.82. Fixed terms include Pper → paper and AI ag → AI agent. Fine-tuning on 2.5 h of Common Voice gave 17.30 → 16.58, not significant: fine-tune for scenes that differ from the training data (microphones, rooms, accents, terminology).
FAQ. No punctuation or hotwords in Flash; use the full BlackBear-ASR for those, or fine-tune for new words. Taigi works with language="nan" (written as Chinese), without a public score yet. Windows is untested. Questions and results are welcome on Discord.