File size: 2,486 Bytes
04c5ce0 | 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 | """Publish the sentiment classifier as a Hugging Face Static Space."""
import argparse
import json
import time
from pathlib import Path
from huggingface_hub import HfApi, get_token
from huggingface_hub.errors import RepositoryNotFoundError
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--name", default="nlp-bert-tiny-sentiment")
parser.add_argument("--wait-seconds", type=int, default=600)
args = parser.parse_args()
space = Path(__file__).resolve().parent / "space_static"
if not (space / "model" / "onnx" / "model.onnx").exists():
raise SystemExit("缺少 ONNX 权重,请先完成 train.py 和 export_onnx.py。")
if not get_token():
raise SystemExit("请先运行 hf auth login 登录 Hugging Face。")
api = HfApi()
username = api.whoami()["name"]
repo_id = f"{username}/{args.name}"
# Static Spaces run in the browser, have no paid compute, and require no paid plan.
try:
existing = api.space_info(repo_id)
except RepositoryNotFoundError:
pass
else:
if existing.sdk != "static":
raise SystemExit("同名 Space 已使用其他 SDK。请换 --name,避免修改现有 Space。")
api.create_repo(repo_id=repo_id, repo_type="space", space_sdk="static", exist_ok=True)
api.upload_folder(repo_id=repo_id, repo_type="space", folder_path=space,
ignore_patterns=["__pycache__/**"], commit_message="Deploy verified SST-2 fine-tuned BERT Tiny demo")
started = time.monotonic()
result = {"repo_id": repo_id, "space_url": f"https://huggingface.co/spaces/{repo_id}",
"source_url": f"https://huggingface.co/spaces/{repo_id}/tree/main", "sdk": "static", "paid_compute": False}
while time.monotonic() - started < args.wait_seconds:
runtime = api.get_space_runtime(repo_id)
stage = getattr(runtime.stage, "value", str(runtime.stage))
print(stage, flush=True)
result["stage"] = stage
if "RUNNING" in stage and "BUILDING" not in stage:
break
if any(x in stage for x in ["ERROR", "FAILED", "PAUSED"]):
break
time.sleep(15)
output = Path(__file__).resolve().parent / "results" / "deployment.json"
output.parent.mkdir(exist_ok=True)
output.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
print(json.dumps(result, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
|