|
| 1 | +"""Executable tutorial contracts, not pretrained speech-quality tests.""" |
| 2 | +import copy |
| 3 | +import hashlib |
| 4 | +import json |
| 5 | +from pathlib import Path |
| 6 | +import sys |
| 7 | +import types |
| 8 | +import wave |
| 9 | + |
| 10 | +from bs4 import BeautifulSoup |
| 11 | +import pytest |
| 12 | + |
| 13 | +SITE = Path(__file__).resolve().parents[1] |
| 14 | +sys.path.insert(0, str(SITE)) |
| 15 | +from build import build |
| 16 | + |
| 17 | +SLUG = "speech-to-text-python-transcribe-audio" |
| 18 | +MODEL = "iic/speech_seaco_paraformer_large_asr_nat-zh-cn-16k-common-vocab8404-pytorch" |
| 19 | +TITLES = ("用 Python 把第一段录音转成文字", "Transcribe your first recording with Python") |
| 20 | + |
| 21 | + |
| 22 | +@pytest.fixture(scope="module", params=["source", "built"]) |
| 23 | +def root(request, tmp_path_factory): |
| 24 | + if request.param == "source": |
| 25 | + return SITE / "legacy" |
| 26 | + dest = tmp_path_factory.mktemp("first-transcript-build") |
| 27 | + build(dest) |
| 28 | + return dest |
| 29 | + |
| 30 | + |
| 31 | +@pytest.fixture(params=["", "en/"]) |
| 32 | +def article(root, request): |
| 33 | + prefix = request.param |
| 34 | + return prefix, BeautifulSoup((root / prefix / "blog" / (SLUG + ".html")).read_text(), "html.parser") |
| 35 | + |
| 36 | + |
| 37 | +def test_catalogue(): |
| 38 | + data = json.loads((SITE / "data/blog.json").read_text()) |
| 39 | + row = next(x for x in data["articles"] if x["slug"] == SLUG) |
| 40 | + assert row["reviewed"] is True |
| 41 | + assert row["category"] == "applications" |
| 42 | + assert (row["zh"]["title"], row["en"]["title"]) == TITLES |
| 43 | + assert SLUG in [data["lead"], *data["selected"]] |
| 44 | + |
| 45 | + |
| 46 | +def test_reader_and_agent_contract(article): |
| 47 | + prefix, soup = article |
| 48 | + assert soup.h1.get_text() == TITLES[bool(prefix)] |
| 49 | + metadata = json.loads(soup.select_one('script[type="application/ld+json"]').get_text()) |
| 50 | + assert metadata["datePublished"] == "2026-06-18" |
| 51 | + assert metadata["dateModified"] == "2026-11-17" |
| 52 | + assert metadata["headline"] == soup.h1.get_text() |
| 53 | + assert soup.select_one('link[rel="canonical"]')["href"] == f"https://www.funasr.com/{prefix}blog/{SLUG}.html" |
| 54 | + for section in ("ecosystem", "requirements", "installation", "audio", "transcribe", "result", "troubleshooting", "agent-contract", "verification"): |
| 55 | + assert soup.select_one(f"article #{section}"), section |
| 56 | + text = soup.select_one("article").get_text() |
| 57 | + for claim in ("代码全部实测", "每段代码都已实测", "换模型只改", "CPU 也能实时", "All code tested", "just change model="): |
| 58 | + assert claim not in text |
| 59 | + assert "1.4.26" in text and "30" in text and "16000" in text |
| 60 | + assert soup.select_one('article [data-editorial="next-step"] a[href]') |
| 61 | + assert not soup.select("article .post-list") |
| 62 | + assert "pretrained" in soup.select_one("#verification").parent.get_text().lower() if prefix else "预训练" in soup.select_one("#verification").parent.get_text() |
| 63 | + |
| 64 | + |
| 65 | +@pytest.fixture |
| 66 | +def recipe(article): |
| 67 | + _, soup = article |
| 68 | + node = soup.select_one('code[data-example="transcribe-first"]') |
| 69 | + assert node is not None |
| 70 | + ns = {"__name__": "tutorial_example"} |
| 71 | + exec(compile(node.get_text(), "article/transcribe_first.py", "exec"), ns) |
| 72 | + return ns["main"] |
| 73 | + |
| 74 | + |
| 75 | +def wav_file(tmp_path, rate=16000, channels=1, seconds=1, width=2): |
| 76 | + p = tmp_path / "sample.wav" |
| 77 | + with wave.open(str(p), "wb") as audio: |
| 78 | + audio.setnchannels(channels) |
| 79 | + audio.setsampwidth(width) |
| 80 | + audio.setframerate(rate) |
| 81 | + audio.writeframes(b"\x00" * int(rate * seconds) * channels * width) |
| 82 | + return p |
| 83 | + |
| 84 | + |
| 85 | +@pytest.fixture |
| 86 | +def fake_model(monkeypatch): |
| 87 | + calls = [] |
| 88 | + result = [{"text": "测试结果"}] |
| 89 | + class Model: |
| 90 | + model_path = "/reviewed/model" |
| 91 | + def __init__(self, **kwargs): |
| 92 | + calls.append(("construct", kwargs)) |
| 93 | + def generate(self, **kwargs): |
| 94 | + calls.append(("generate", kwargs)) |
| 95 | + return copy.deepcopy(result) |
| 96 | + module = types.ModuleType("funasr") |
| 97 | + module.AutoModel = Model |
| 98 | + module.__version__ = "1.4.26" |
| 99 | + monkeypatch.setitem(sys.modules, "funasr", module) |
| 100 | + return calls, result |
| 101 | + |
| 102 | + |
| 103 | +def args_for(tmp_path, audio): |
| 104 | + model = tmp_path / "model" |
| 105 | + model.mkdir(exist_ok=True) |
| 106 | + return ["--audio", str(audio), "--model-dir", str(model), "--output", str(tmp_path / "transcript.json")] |
| 107 | + |
| 108 | + |
| 109 | +def test_local_model_output_and_immutable_input(recipe, tmp_path, fake_model): |
| 110 | + audio = wav_file(tmp_path) |
| 111 | + before = hashlib.sha256(audio.read_bytes()).hexdigest() |
| 112 | + args = args_for(tmp_path, audio) |
| 113 | + recipe(args) |
| 114 | + calls, _ = fake_model |
| 115 | + assert calls == [ |
| 116 | + ("construct", dict(model=str(tmp_path / "model"), hub="ms", device="cpu", ncpu=4, disable_update=True, trust_remote_code=False)), |
| 117 | + ("generate", dict(input=str(audio), batch_size=1)), |
| 118 | + ] |
| 119 | + out = json.loads((tmp_path / "transcript.json").read_text()) |
| 120 | + assert out["text"] == "测试结果" and out["funasr_version"] == "1.4.26" |
| 121 | + assert out["audio"] == str(audio) and out["model_dir"] == "/reviewed/model" |
| 122 | + assert out["duration_seconds"] == 1.0 |
| 123 | + assert hashlib.sha256(audio.read_bytes()).hexdigest() == before |
| 124 | + |
| 125 | + |
| 126 | +def test_download_requires_explicit_opt_in(recipe, tmp_path, fake_model): |
| 127 | + audio = wav_file(tmp_path) |
| 128 | + with pytest.raises(SystemExit) as e: |
| 129 | + recipe(["--audio", str(audio), "--output", str(tmp_path / "out.json")]) |
| 130 | + assert e.value.code == 2 and fake_model[0] == [] |
| 131 | + recipe(["--audio", str(audio), "--allow-download", "--output", str(tmp_path / "out.json")]) |
| 132 | + assert fake_model[0][0][1]["model"] == MODEL |
| 133 | + |
| 134 | + |
| 135 | +@pytest.mark.parametrize("case", ["missing", "not-wav", "stereo", "rate", "empty", "long", "width", "truncated", "model-missing", "output-exists", "output-parent"]) |
| 136 | +def test_invalid_inputs_stop_before_model_load(recipe, tmp_path, fake_model, case): |
| 137 | + options = {"stereo": {"channels": 2}, "rate": {"rate": 8000}, "empty": {"seconds": 0}, "long": {"seconds": 31}, "width": {"width": 1}} |
| 138 | + audio = wav_file(tmp_path, **options.get(case, {})) |
| 139 | + args = args_for(tmp_path, audio) |
| 140 | + if case == "missing": |
| 141 | + audio.unlink() |
| 142 | + elif case == "not-wav": |
| 143 | + audio.write_bytes(b"not a wav") |
| 144 | + elif case == "truncated": |
| 145 | + audio.write_bytes(audio.read_bytes()[:-4]) |
| 146 | + elif case == "model-missing": |
| 147 | + (tmp_path / "model").rmdir() |
| 148 | + elif case == "output-exists": |
| 149 | + (tmp_path / "transcript.json").write_text("KEEP") |
| 150 | + elif case == "output-parent": |
| 151 | + args[-1] = str(tmp_path / "absent" / "out.json") |
| 152 | + with pytest.raises((SystemExit, OSError, ValueError, EOFError, wave.Error)): |
| 153 | + recipe(args) |
| 154 | + assert fake_model[0] == [] |
| 155 | + if case == "output-exists": |
| 156 | + assert (tmp_path / "transcript.json").read_text() == "KEEP" |
| 157 | + else: |
| 158 | + assert not (tmp_path / "transcript.json").exists() |
| 159 | + |
| 160 | + |
| 161 | +@pytest.mark.parametrize("response", [[], [{}], [{"text": ""}], [{"text": 12}], [{"text": " "}], [{"text": "one"}, {"text": "two"}]]) |
| 162 | +def test_invalid_results_do_not_create_success_file(recipe, tmp_path, fake_model, response): |
| 163 | + audio = wav_file(tmp_path) |
| 164 | + fake_model[1][:] = response |
| 165 | + with pytest.raises((SystemExit, ValueError, RuntimeError)): |
| 166 | + recipe(args_for(tmp_path, audio)) |
| 167 | + assert not (tmp_path / "transcript.json").exists() |
| 168 | + |
| 169 | + |
| 170 | +def test_bilingual_code_is_identical(root): |
| 171 | + codes = [] |
| 172 | + for prefix in ("", "en/"): |
| 173 | + soup = BeautifulSoup((root / prefix / "blog" / (SLUG + ".html")).read_text(), "html.parser") |
| 174 | + codes.append(soup.select_one('code[data-example="transcribe-first"]').get_text()) |
| 175 | + assert codes[0] == codes[1] |
0 commit comments