File size: 3,808 Bytes
688378c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Сборка весов Audit (Whisper base, CTranslate2) из PyPI-пакетов.

Веса опубликованы на PyPI в двух частях (wheel):
  - gympulse-whisper-base-part1: config.json, tokenizer.json,
    vocabulary.txt, model.bin.part1
  - gympulse-whisper-base-part2: model.bin.part2

Сборка: cat model.bin.part1 model.bin.part2 > model.bin
Проверка: magic-bytes «WhisperSpeech» + SHA-256.

Использование:
    python scripts/build_model.py [--output model] [--sha256 d01c...]
"""

from __future__ import annotations

import argparse
import hashlib
import subprocess
import sys
import tempfile
import zipfile
from pathlib import Path

PART1 = "gympulse-whisper-base-part1"
PART2 = "gympulse-whisper-base-part2"
EXPECTED_SHA256 = "d01c3014881c9c6f3133c182f3d2887eb6ca1c789a7538c5c007196857a0a6a9"
# Header: uint32 version (6) + string "WhisperSpec" (uint16 len+1, bytes, 0)
EXPECTED_HEADER = b"\x06\x00\x00\x00\x0c\x00WhisperSpec\x00"

ROOT = Path(__file__).resolve().parent.parent


def pip_download(pkg: str, dest: Path) -> Path:
    subprocess.run(
        [sys.executable, "-m", "pip", "download", pkg, "-d", str(dest), "--no-deps", "-q"],
        check=True,
    )
    wheels = list(dest.glob(f"*{pkg.replace('-', '_')}*.whl"))
    if not wheels:
        raise RuntimeError(f"wheel не найден для {pkg}")
    return wheels[0]


def extract_data(wheel: Path, out: Path) -> None:
    with zipfile.ZipFile(wheel) as zf:
        for name in zf.namelist():
            if "/data/" in name and not name.endswith("/"):
                zf.extract(name, out)


def sha256_file(path: Path) -> str:
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for chunk in iter(lambda: f.read(1 << 20), b""):
            h.update(chunk)
    return h.hexdigest()


def main(argv=None) -> int:
    ap = argparse.ArgumentParser(description="Сборка весов Audit")
    ap.add_argument("--output", default=str(ROOT / "model"))
    ap.add_argument(
        "--sha256",
        default=EXPECTED_SHA256,
        help="ожидаемый sha256 model.bin (пустой — проверку пропустить)",
    )
    args = ap.parse_args(argv)

    out = Path(args.output)
    out.mkdir(parents=True, exist_ok=True)

    with tempfile.TemporaryDirectory() as td:
        td = Path(td)
        wheel1 = pip_download(PART1, td)
        wheel2 = pip_download(PART2, td)

        ext1 = td / "p1"
        ext2 = td / "p2"
        extract_data(wheel1, ext1)
        extract_data(wheel2, ext2)

        p1 = next(ext1.rglob("model.bin.part1"))
        p2 = next(ext2.rglob("model.bin.part2"))

        model_bin = out / "model.bin"
        with open(p1, "rb") as f1, open(p2, "rb") as f2, open(model_bin, "wb") as out_f:
            for chunk in iter(lambda: f1.read(1 << 20), b""):
                out_f.write(chunk)
            for chunk in iter(lambda: f2.read(1 << 20), b""):
                out_f.write(chunk)

        for aux in ("config.json", "tokenizer.json", "vocabulary.txt"):
            src = next(ext1.rglob(aux))
            (out / aux).write_bytes(src.read_bytes())

    with open(model_bin, "rb") as f:
        header = f.read(len(EXPECTED_HEADER))
    if header != EXPECTED_HEADER:
        raise RuntimeError(f"Неверный заголовок model.bin: {header!r}")

    digest = sha256_file(model_bin)
    print(f"model.bin: {model_bin} ({model_bin.stat().st_size / 1e6:.1f} МБ)")
    print(f"sha256: {digest}")
    if args.sha256 and digest != args.sha256:
        raise RuntimeError(f"SHA-256 не совпадает с оригиналом: {digest}")
    print("Сборка успешна. Запуск: python -m audio_audit.cli examples/jfk.wav")
    return 0


if __name__ == "__main__":
    sys.exit(main())