File size: 2,994 Bytes
15c46ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Publish only reviewed project sources; never upload local environments or tokens."""
import argparse
import json
from pathlib import Path

from huggingface_hub import HfApi, CommitOperationAdd
from huggingface_hub.utils import RepositoryNotFoundError

ROOT = Path(__file__).resolve().parents[1]
ROOT_FILES = ["README.md", "Dockerfile", ".dockerignore", ".gitignore", ".gitattributes", "requirements.txt",
              "app.py", "engine.py", "settings.py", "LICENSE.upstream.md", "NOTICE.md",
              "vendor-patches.diff", "provenance.json", "start-preview.cmd"]
SOURCE_DIRS = ["vendor", "scripts", "tests", "examples", "docs"]


def source_files():
    files = [ROOT / name for name in ROOT_FILES]
    for name in SOURCE_DIRS:
        files.extend(p for p in (ROOT / name).rglob("*") if p.is_file()
                     and "__pycache__" not in p.parts and p.suffix not in (".pyc", ".log"))
    for file in files:
        if not file.is_file():
            raise FileNotFoundError(file)
        if file.suffix in (".pt", ".pth", ".bin", ".safetensors"):
            raise ValueError("Refusing to publish model weights: " + str(file))
    return sorted(files)


def publish(repo_id):
    api = HfApi()
    owner = api.whoami()["name"]
    if repo_id.split("/")[0] != owner:
        raise ValueError("Publish only into the authenticated personal account.")
    try:
        api.repo_info(repo_id, repo_type="space")
    except RepositoryNotFoundError:
        # Explicit CPU Basic. This script never requests paid GPU hardware.
        api.create_repo(repo_id, repo_type="space", space_sdk="docker", private=False,
                        space_hardware="cpu-basic")
    else:
        # Do not overwrite another existing project with a colliding name.
        from huggingface_hub import hf_hub_download
        provenance = json.loads(Path(hf_hub_download(repo_id, "provenance.json", repo_type="space")).read_text())
        if provenance.get("project") != "nextgpt-chapter6-reproduction":
            raise ValueError("Existing Space is a different project; choose another name.")
    files = source_files()
    commit = api.create_commit(repo_id, repo_type="space", commit_message="Add reproducible NExT-GPT inference and Docker deployment",
                               operations=[CommitOperationAdd(path_in_repo=p.relative_to(ROOT).as_posix(),
                                                              path_or_fileobj=str(p)) for p in files])
    return {"space": f"https://huggingface.co/spaces/{repo_id}",
            "source": f"https://huggingface.co/spaces/{repo_id}/tree/main", "commit": commit.oid}


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("repo_id")
    parser.add_argument("--list-only", action="store_true")
    args = parser.parse_args()
    if args.list_only:
        print("\n".join(p.relative_to(ROOT).as_posix() for p in source_files()))
    else:
        print(json.dumps(publish(args.repo_id), indent=2))