Spaces:
Sleeping
Sleeping
| """ | |
| 一键部署到 Hugging Face Spaces(永久免费在线) | |
| 使用方法: | |
| 1. 注册 Hugging Face: https://huggingface.co/join | |
| 2. 创建 Access Token: https://huggingface.co/settings/tokens | |
| 3. 运行: python deploy.py | |
| 前提条件: | |
| - Git 已安装 | |
| - huggingface_hub 已安装(已预装) | |
| - 一个 Hugging Face 账号 | |
| """ | |
| import os | |
| import sys | |
| import subprocess | |
| import json | |
| from pathlib import Path | |
| BASE_DIR = Path(__file__).parent | |
| def run_cmd(cmd, cwd=None, capture=True): | |
| """运行命令并返回结果""" | |
| try: | |
| r = subprocess.run( | |
| cmd, shell=True, cwd=cwd or BASE_DIR, | |
| capture_output=capture, text=True, timeout=120 | |
| ) | |
| return r.returncode, r.stdout.strip() if capture else "", r.stderr.strip() if capture else "" | |
| except subprocess.TimeoutExpired: | |
| return -1, "", "超时" | |
| except Exception as e: | |
| return -1, "", str(e) | |
| def check_prerequisites(): | |
| """检查前置条件""" | |
| print("=" * 50) | |
| print(" 检查前置条件...") | |
| print("=" * 50) | |
| # 检查 Git | |
| code, out, _ = run_cmd("git --version") | |
| if code != 0 or not out: | |
| print(" ❌ Git 未安装!请先安装 Git: https://git-scm.com/") | |
| return False | |
| print(f" ✅ Git: {out}") | |
| # 检查 huggingface_hub | |
| try: | |
| import huggingface_hub | |
| print(f" ✅ huggingface_hub: {huggingface_hub.__version__}") | |
| except ImportError: | |
| print(" ❌ huggingface_hub 未安装!") | |
| return False | |
| # 检查 Git LFS(用于大文件,非必需) | |
| code, out, _ = run_cmd("git lfs version") | |
| if code == 0: | |
| print(f" ✅ Git LFS: {out.split()[2] if out else '已安装'}") | |
| else: | |
| print(" ℹ️ Git LFS 未安装(非必需,已忽略)") | |
| return True | |
| def get_hf_token(): | |
| """获取 Hugging Face Token""" | |
| token = os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACE_TOKEN") | |
| if token: | |
| return token | |
| print() | |
| print("=" * 50) | |
| print(" Hugging Face Token 设置") | |
| print("=" * 50) | |
| print() | |
| print(" 请前往 https://huggingface.co/settings/tokens") | |
| print(" 创建一个 Access Token(选 write 权限)") | |
| print() | |
| token = input(" 输入你的 HF Token: ").strip() | |
| return token if token else None | |
| def deploy_to_hf_spaces(token, space_name="garbage-classifier"): | |
| """部署到 Hugging Face Spaces""" | |
| username = None | |
| try: | |
| from huggingface_hub import HfApi, login, create_repo, get_full_repo_name | |
| api = HfApi(token=token) | |
| # 获取用户名 | |
| user_info = api.whoami() | |
| username = user_info["name"] | |
| repo_id = f"{username}/{space_name}" | |
| full_url = f"https://huggingface.co/spaces/{repo_id}" | |
| print() | |
| print("=" * 50) | |
| print(f" 部署到 Hugging Face Spaces") | |
| print("=" * 50) | |
| print(f" 用户名: {username}") | |
| print(f" Space: {space_name}") | |
| print(f" 地址: {full_url}") | |
| print() | |
| # 登录 | |
| login(token=token, add_to_git_credential=True) | |
| # 创建 Space(如果不存在) | |
| print(" 创建 Space...") | |
| try: | |
| create_repo( | |
| repo_id=repo_id, | |
| repo_type="space", | |
| space_sdk="docker", | |
| token=token, | |
| exist_ok=True, | |
| ) | |
| print(" ✅ Space 创建/确认成功") | |
| except Exception as e: | |
| print(f" ⚠️ 创建 Space 时遇到问题: {e}") | |
| print(f" 请手动创建 Space: https://huggingface.co/new-space") | |
| print(f" Space Name: {space_name}") | |
| print(f" SDK: Docker") | |
| return False | |
| # 初始化 Git 仓库并推送 | |
| print() | |
| print(" 初始化 Git 并推送代码...") | |
| print(" (首次推送会安装依赖,约需 10-15 分钟)") | |
| print() | |
| # 初始化 git | |
| run_cmd("git init", capture=False) | |
| run_cmd("git checkout -b main", capture=False) | |
| # 配置 git | |
| run_cmd(f'git config user.name "{username}"', capture=False) | |
| run_cmd(f'git config user.email "{username}@users.noreply.huggingface.co"', capture=False) | |
| # 添加文件 | |
| run_cmd("git add -A", capture=False) | |
| # 提交 | |
| code, out, err = run_cmd('git commit -m "Initial deploy: garbage classifier"') | |
| if code != 0: | |
| if "nothing to commit" in err.lower() or "nothing to commit" in out.lower(): | |
| print(" ℹ️ 没有新文件需要提交") | |
| else: | |
| print(f" ⚠️ Commit 警告: {err[:100] if err else out[:100]}") | |
| # 设置 remote | |
| space_url = f"https://huggingface.co/spaces/{repo_id}" | |
| run_cmd(f"git remote add space {space_url}", capture=False) | |
| # 推送 | |
| print(" 正在推送代码到 Hugging Face Spaces...") | |
| print(" (这可能需要几分钟)...") | |
| code, out, err = run_cmd( | |
| f"git push --force space main", | |
| capture=False | |
| ) | |
| if code == 0: | |
| print() | |
| print("=" * 50) | |
| print(f" ✅ 部署成功!".center(50)) | |
| print("=" * 50) | |
| print() | |
| print(f" 🌐 访问地址:") | |
| print(f" https://huggingface.co/spaces/{repo_id}") | |
| print() | |
| print(f" ⏳ 首次启动需要 5-10 分钟安装依赖") | |
| print(f" 页面显示 Building 属于正常现象") | |
| print() | |
| print(f" 🚀 构建完成后直接打开即可使用!") | |
| print() | |
| return True | |
| else: | |
| print(f" ❌ 推送失败") | |
| print(f" {err[:200] if err else out[:200]}") | |
| return False | |
| except Exception as e: | |
| print(f" ❌ 部署失败: {e}") | |
| return False | |
| def main(): | |
| print() | |
| print(" 🌱 智能垃圾分类系统 - 一键部署") | |
| print(" ====================================") | |
| print() | |
| if not check_prerequisites(): | |
| sys.exit(1) | |
| token = get_hf_token() | |
| if not token: | |
| print("❌ 未提供 Token,部署取消") | |
| sys.exit(1) | |
| # 可选自定义 Space 名称 | |
| name = input(f" Space 名称 (回车默认: garbage-classifier): ").strip() | |
| if not name: | |
| name = "garbage-classifier" | |
| success = deploy_to_hf_spaces(token, name) | |
| if not success: | |
| print() | |
| print(" 💡 你也可以手动部署:") | |
| print(" 1. 打开 https://huggingface.co/new-space") | |
| print(" 2. Space Name: garbage-classifier") | |
| print(" 3. SDK: Docker") | |
| print(" 4. 创建后,将项目代码 push 上去即可") | |
| sys.exit(1) | |
| if __name__ == "__main__": | |
| main() | |