# -*- coding: utf-8 -*-
"""从 hf-mirror 直链下载 faster-whisper CT2 模型（断点续传）
用法: python fetch_model.py small|medium|large-v3-turbo
"""
import os, sys, time, requests

REPOS = {
    "small": "Systran/faster-whisper-small",
    "medium": "Systran/faster-whisper-medium",
    "base": "Systran/faster-whisper-base",
    "large-v3": "Systran/faster-whisper-large-v3",
    "large-v3-turbo": "deepdml/faster-whisper-large-v3-turbo-ct2",
}
FILES = ["config.json", "tokenizer.json", "vocabulary.txt", "preprocessor_config.json", "model.bin"]

name = sys.argv[1] if len(sys.argv) > 1 else "small"
repo = REPOS[name]
dst = os.path.join(r"D:\Deepseek\douyin_fengdaquan\models", "faster-whisper-" + name)
os.makedirs(dst, exist_ok=True)
BASE = "https://hf-mirror.com"


def fetch(fn):
    fp = os.path.join(dst, fn)
    url = BASE + "/" + repo + "/resolve/main/" + fn
    for attempt in range(4):
        have = os.path.getsize(fp) if os.path.exists(fp) else 0
        head = {}
        if have:
            head["Range"] = "bytes=%d-" % have
        try:
            with requests.get(url, headers=head, stream=True, timeout=60) as r:
                if r.status_code == 404:
                    print("  %s: not found, skip" % fn, flush=True)
                    return True
                if have and r.status_code == 200:
                    have = 0
                total = int(r.headers.get("Content-Length") or 0) + have
                with open(fp, "ab" if have else "wb") as f:
                    for c in r.iter_content(1 << 18):
                        f.write(c)
            got = os.path.getsize(fp)
            if total and got < total:
                raise RuntimeError("incomplete %d/%d" % (got, total))
            print("  %s: %.1fMB done" % (fn, got / 1e6), flush=True)
            return True
        except Exception as e:
            print("  %s attempt %d failed: %s" % (fn, attempt + 1, e), flush=True)
            time.sleep(2)
    return False


t0 = time.time()
print("download %s <- %s -> %s" % (name, repo, dst), flush=True)
ok = all(fetch(f) for f in FILES)
print(("OK" if ok else "PARTIAL") + " in %.0fs" % (time.time() - t0), flush=True)
