"""Download WebBrain-LingLoop-8B-A1.3B-Q6_K.gguf, tokenizer/metadata, and verify 638 GGUF tensors.""" from __future__ import annotations import os os.environ.setdefault("HF_HUB_DISABLE_XET", "1") import json import struct import sys import time import urllib.request from collections import Counter from pathlib import Path from typing import Optional if hasattr(sys.stdout, "reconfigure"): sys.stdout.reconfigure(encoding="utf-8", line_buffering=True) ROOT = Path(r"C:\Users\jhjwi\.gemini\antigravity\scratch\webbrain-lingloop-8b-wsp") UPSTREAM = ROOT / "upstream" META_DIR = UPSTREAM / "hf_meta" GGUF_PATH = UPSTREAM / "WebBrain-LingLoop-8B-A1.3B-Q6_K.gguf" GGUF_URL = "https://huggingface.co/webbrain-one/WebBrain-LingLoop-8B-A1.3B-GGUF/resolve/main/WebBrain-LingLoop-8B-A1.3B-Q6_K.gguf" META_BASE = "https://huggingface.co/webbrain-one/WebBrain-LingLoop-8B-A1.3B/resolve/main" META_FILES = [ "tokenizer.json", "tokenizer_config.json", "special_tokens_map.json", "chat_template.jinja", "config.json", "generation_config.json", "README.md", "TEST_CARD.md", ] MIT_LICENSE_URL = "https://huggingface.co/inclusionAI/Ling-3.0-tiny/resolve/main/LICENSE" def load_hf_token() -> Optional[str]: for p in (Path(r"C:\Users\jhjwi\.env"), Path.home() / ".env"): if p.exists(): raw = p.read_bytes().replace(b"\x00", b"").decode("utf-8", errors="ignore") for ln in raw.splitlines(): ln = ln.strip().lstrip("\ufeff") if "HF_TOKEN=" in ln: val = ln.split("HF_TOKEN=", 1)[1].strip().strip('"').strip("'") if val: return val return os.environ.get("HF_TOKEN") or None def download_resumable(url: str, dst: Path, token: Optional[str]) -> None: dst.parent.mkdir(parents=True, exist_ok=True) headers = {"User-Agent": "lingloop-wsp-dl/1.0"} if token: headers["Authorization"] = f"Bearer {token}" # Probe exact remote size via HEAD head_req = urllib.request.Request(url, headers=headers, method="HEAD") with urllib.request.urlopen(head_req, timeout=30) as resp: total_size = int(resp.headers.get("Content-Length") or 0) if dst.exists() and total_size > 0 and dst.stat().st_size == total_size: print(f"[DL] Already complete: {dst.name} ({total_size / 1024**3:.3f} GiB)", flush=True) return tmp = dst.with_suffix(dst.suffix + ".part") existing = tmp.stat().st_size if tmp.exists() else 0 if existing > 0 and total_size > 0 and existing < total_size: headers["Range"] = f"bytes={existing}-" mode = "ab" else: existing = 0 mode = "wb" req = urllib.request.Request(url, headers=headers) t0 = time.perf_counter() last_log = t0 downloaded = existing with urllib.request.urlopen(req, timeout=60) as resp, open(tmp, mode) as fp: if total_size == 0: total_size = int(resp.headers.get("Content-Length") or 0) + existing while True: chunk = resp.read(4 * 1024 * 1024) if not chunk: break fp.write(chunk) downloaded += len(chunk) now = time.perf_counter() if now - last_log >= 5.0: el = now - t0 rate = (downloaded - existing) / max(el, 1e-6) eta = (total_size - downloaded) / max(rate, 1.0) if total_size > 0 else 0.0 pct = 100.0 * downloaded / max(total_size, 1) print( f"[DL] {dst.name}: {downloaded / 1024**3:.2f}/{total_size / 1024**3:.2f} GiB " f"({pct:.1f}%) | {rate / 1024**2:.1f} MiB/s | elapsed={el:.0f}s | ETA={eta:.0f}s", flush=True, ) last_log = now tmp.replace(dst) print(f"[DL] Completed {dst.name} in {time.perf_counter() - t0:.1f}s ({dst.stat().st_size / 1024**3:.3f} GiB)", flush=True) def verify_gguf_header(gguf_path: Path) -> None: with open(gguf_path, "rb") as f: hdr = f.read(16 * 1024 * 1024) off = 0 magic, ver, nt, nkv = struct.unpack_from("<4sIQQ", hdr, off) off += 24 assert magic == b"GGUF", f"Bad GGUF magic: {magic}" def rstr() -> str: nonlocal off (n,) = struct.unpack_from(" None: for d in (UPSTREAM, META_DIR, ROOT / "lingloop_cuda", ROOT / "wsp_adapters", ROOT / "results", ROOT / "gguf"): d.mkdir(parents=True, exist_ok=True) token = load_hf_token() download_resumable(GGUF_URL, GGUF_PATH, token) for fn in META_FILES: download_resumable(f"{META_BASE}/{fn}", META_DIR / fn, token) # Fetch MIT LICENSE cleanly (or fallback standard MIT if inclusionAI repo lacks a LICENSE file) lic_dst = META_DIR / "LICENSE" try: download_resumable(MIT_LICENSE_URL, lic_dst, token) except Exception: lic_dst.write_text( "MIT License\n\nCopyright (c) InclusionAI & WebBrain\n\n" "Permission is hereby granted, free of charge, to any person obtaining a copy\n" "of this software and associated documentation files (the \"Software\"), to deal\n" "in the Software without restriction, including without limitation the rights\n" "to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n" "copies of the Software, and to permit persons to whom the Software is\n" "furnished to do so, subject to the following conditions:\n\n" "The above copyright notice and this permission notice shall be included in all\n" "copies or substantial portions of the Software.\n\n" "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n" "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n" "FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n" "AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n" "LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n" "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n" "SOFTWARE.\n", encoding="utf-8", ) print("[DL] Wrote MIT LICENSE file.", flush=True) verify_gguf_header(GGUF_PATH) if __name__ == "__main__": main()