|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import importlib |
| 4 | +import os |
| 5 | +from functools import lru_cache |
| 6 | +from urllib.parse import parse_qs, unquote, urlparse |
| 7 | + |
| 8 | + |
| 9 | +def _normalize_local_artifact_path(uri: str) -> str: |
| 10 | + parsed = urlparse(uri) |
| 11 | + if parsed.scheme == "file": |
| 12 | + if parsed.netloc not in {"", "localhost"}: |
| 13 | + raise ValueError(f"Unsupported artifact URI host: {uri}") |
| 14 | + path = unquote(parsed.path) |
| 15 | + if path == "": |
| 16 | + raise ValueError(f"Invalid artifact URI (empty path): {uri}") |
| 17 | + return path |
| 18 | + if parsed.scheme == "": |
| 19 | + return uri |
| 20 | + raise ValueError( |
| 21 | + f"Unsupported artifact URI scheme '{parsed.scheme}'. Use local paths, file://, or hf:// URIs." |
| 22 | + ) |
| 23 | + |
| 24 | + |
| 25 | +def _parse_hf_uri( |
| 26 | + uri: str, |
| 27 | + *, |
| 28 | + default_repo_id: str | None = None, |
| 29 | + default_revision: str | None = None, |
| 30 | +) -> tuple[str, str, str | None]: |
| 31 | + parsed = urlparse(uri) |
| 32 | + if parsed.scheme != "hf": |
| 33 | + raise ValueError(f"Invalid HF URI: {uri}") |
| 34 | + |
| 35 | + # Expected format: hf://<owner>/<repo>/<path/to/file>[?revision=<rev>] |
| 36 | + payload = f"{parsed.netloc}{parsed.path}".lstrip("/") |
| 37 | + segments = [seg for seg in payload.split("/") if seg] |
| 38 | + if len(segments) >= 3: |
| 39 | + repo_id = f"{segments[0]}/{segments[1]}" |
| 40 | + filename = "/".join(segments[2:]) |
| 41 | + elif len(segments) >= 1 and default_repo_id: |
| 42 | + repo_id = default_repo_id |
| 43 | + filename = "/".join(segments) |
| 44 | + else: |
| 45 | + raise ValueError( |
| 46 | + f"Invalid HF URI '{uri}'. Expected hf://<owner>/<repo>/<artifact_path>." |
| 47 | + ) |
| 48 | + |
| 49 | + if filename == "": |
| 50 | + raise ValueError(f"Invalid HF URI '{uri}': missing artifact path.") |
| 51 | + |
| 52 | + query = parse_qs(parsed.query) |
| 53 | + revision = query.get("revision", [None])[0] or default_revision |
| 54 | + return repo_id, filename, revision |
| 55 | + |
| 56 | + |
| 57 | +@lru_cache(maxsize=128) |
| 58 | +def _download_hf_artifact( |
| 59 | + *, |
| 60 | + repo_id: str, |
| 61 | + filename: str, |
| 62 | + revision: str | None, |
| 63 | +) -> str: |
| 64 | + try: |
| 65 | + hf_module = importlib.import_module("huggingface_hub") |
| 66 | + except ModuleNotFoundError as exc: |
| 67 | + raise ValueError( |
| 68 | + "huggingface-hub is required for hf:// artifacts. " |
| 69 | + "Install it in the API runtime dependencies." |
| 70 | + ) from exc |
| 71 | + |
| 72 | + hf_hub_download = getattr(hf_module, "hf_hub_download", None) |
| 73 | + if hf_hub_download is None: |
| 74 | + raise ValueError("huggingface_hub.hf_hub_download is unavailable in this runtime.") |
| 75 | + |
| 76 | + token = os.getenv("HF_TOKEN") |
| 77 | + return str( |
| 78 | + hf_hub_download( |
| 79 | + repo_id=repo_id, |
| 80 | + filename=filename, |
| 81 | + revision=revision, |
| 82 | + token=token if token else None, |
| 83 | + ) |
| 84 | + ) |
| 85 | + |
| 86 | + |
| 87 | +def resolve_artifact_uri( |
| 88 | + uri: str | None, |
| 89 | + *, |
| 90 | + default_repo_id: str | None = None, |
| 91 | + default_revision: str | None = None, |
| 92 | +) -> str | None: |
| 93 | + if uri is None: |
| 94 | + return None |
| 95 | + cleaned = uri.strip() |
| 96 | + if cleaned == "": |
| 97 | + return None |
| 98 | + |
| 99 | + parsed = urlparse(cleaned) |
| 100 | + if parsed.scheme in {"", "file"}: |
| 101 | + return _normalize_local_artifact_path(cleaned) |
| 102 | + if parsed.scheme == "hf": |
| 103 | + repo_id, filename, revision = _parse_hf_uri( |
| 104 | + cleaned, |
| 105 | + default_repo_id=default_repo_id, |
| 106 | + default_revision=default_revision, |
| 107 | + ) |
| 108 | + return _download_hf_artifact( |
| 109 | + repo_id=repo_id, |
| 110 | + filename=filename, |
| 111 | + revision=revision, |
| 112 | + ) |
| 113 | + raise ValueError( |
| 114 | + f"Unsupported artifact URI scheme '{parsed.scheme}'. Use local paths, file://, or hf:// URIs." |
| 115 | + ) |
0 commit comments