Cotton code
143 lines · 5.3 KB · PythonRaw
#!/usr/bin/env python3"""Fetch a model in sherpa-onnx's format and lay it out as `pnpm voice:measure` reads it.    pnpm voice:fetch <model-id>... [--out DIR] [--copy]   (--list for every id)Every id is an entry in scripts/voice/candidates.json: where its files come from(a sherpa-onnx release archive, a Hugging Face repo, or a conversion script underscripts/voice/), its kind, which file plays which part, its options and licence.The model lands in <out>/<id>/ (default $VOICE_MODELS, ~/.cache/cotton-voice/models)with model.json and SHA256SUMS; --copy copies the files instead of linking them(for a folder that is to be uploaded). Archives are kept under $VOICE_DOWNLOADS(default ~/.cache/cotton-voice/downloads) so a second fetch reads no network."""from __future__ import annotationsimport argparseimport hashlibimport jsonimport osimport shutilimport subprocessimport sysimport tarfileimport urllib.requestfrom pathlib import PathHERE = Path(__file__).resolve().parentHOME = Path.home() / ".cache" / "cotton-voice"MODELS = Path(os.environ.get("VOICE_MODELS", HOME / "models"))DOWNLOADS = Path(os.environ.get("VOICE_DOWNLOADS", HOME / "downloads"))RELEASE = "https://github.com/k2-fsa/sherpa-onnx/releases/download"def download(url: str, dest: Path) -> Path:    if dest.exists():        return dest    dest.parent.mkdir(parents=True, exist_ok=True)    part = dest.with_suffix(dest.suffix + ".part")    print(f"[voice] {url}", file=sys.stderr)    headers = {}    if "huggingface.co" in url and os.environ.get("HF_TOKEN"):        headers["Authorization"] = f"Bearer {os.environ['HF_TOKEN']}"    with urllib.request.urlopen(urllib.request.Request(url, headers=headers)) as r, open(part, "wb") as fh:        shutil.copyfileobj(r, fh, 1 << 20)    part.rename(dest)    return destdef source_dir(mid: str, entry: dict) -> Path:    src = entry["source"]    if "release" in src:        name = src["archive"]        folder = DOWNLOADS / name        if not folder.exists():            archive = download(f"{RELEASE}/{src['release']}/{name}.tar.bz2", DOWNLOADS / f"{name}.tar.bz2")            with tarfile.open(archive) as t:                t.extractall(DOWNLOADS, filter="data")            archive.unlink()        return folder    if "release_file" in src:        folder = DOWNLOADS / mid        download(f"{RELEASE}/{src['release_file']}", folder / Path(src["release_file"]).name)        return folder    if "hf" in src:        folder = DOWNLOADS / mid        for f in src["files"]:            download(f"https://huggingface.co/{src['hf']}/resolve/{src.get('revision', 'main')}/{f}", folder / f)        return folder    if "convert" in src:        folder = DOWNLOADS / mid        if not (folder / ".done").exists():            cmd = [sys.executable, str(HERE / src["convert"]), str(folder)] + src.get("args", [])            subprocess.run(cmd, check=True)            (folder / ".done").write_text("")        return folder    raise SystemExit(f"{mid}: no source")def sha256(path: Path) -> str:    h = hashlib.sha256()    with open(path, "rb") as fh:        for block in iter(lambda: fh.read(1 << 20), b""):            h.update(block)    return h.hexdigest()def fetch(mid: str, entry: dict, out: Path, copy: bool) -> Path:    src = source_dir(mid, entry)    dest = out / mid    dest.mkdir(parents=True, exist_ok=True)    files = {}    sums = []    for part, rel in entry["files"].items():        s = src / rel        if not s.exists():            raise SystemExit(f"{mid}: {rel} is not in {src}")        name = Path(rel).name        d = dest / name        if d.is_symlink() or d.is_file():            d.unlink()        elif d.is_dir():            shutil.rmtree(d)        if copy and s.is_dir():            shutil.copytree(s, d)        elif copy:            shutil.copy2(s, d)        else:            os.symlink(s.resolve(), d)        files[part] = name        if s.is_dir():            for f in sorted(x for x in s.rglob("*") if x.is_file()):                sums.append((sha256(f), f"{name}/{f.relative_to(s)}", f.stat().st_size))        else:            sums.append((sha256(s), name, s.stat().st_size))    spec = {k: v for k, v in entry.items() if k not in ("source", "files")}    spec.update(id=mid, files=files,                file_list=[{"name": n, "bytes": b, "sha256": h} for h, n, b in sums])    (dest / "model.json").write_text(json.dumps(spec, indent=2, ensure_ascii=False) + "\n")    (dest / "SHA256SUMS").write_text("".join(f"{h}  {n}\n" for h, n, _ in sums))    print(f"{mid}: {dest} ({sum(b for _, _, b in sums) / 1e6:.0f} MB)")    return destdef main() -> None:    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)    ap.add_argument("ids", nargs="*")    ap.add_argument("--out", type=Path, default=MODELS)    ap.add_argument("--copy", action="store_true")    ap.add_argument("--list", action="store_true")    a = ap.parse_args()    reg = json.loads((HERE / "candidates.json").read_text())["models"]    if a.list or not a.ids:        for mid, e in reg.items():            print(f"{mid:<52} {e['kind']:<24} {e['licence']['id']}")        return    for mid in a.ids:        if mid not in reg:            raise SystemExit(f"no candidate {mid} (pnpm voice:fetch --list)")        fetch(mid, reg[mid], a.out, a.copy)if __name__ == "__main__":    main()