colab-hf-chat 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,67 @@
1
- # Temporary Holding Version
1
+ # Colab Hugging Face Chat CLI
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 安装 Node.js 18 或更新版本。从下载的 npm 压缩包安装:
4
+
5
+ ```bash
6
+ npm install -g ./colab-hf-chat-0.1.0.tgz
7
+ colab-hf-chat
8
+ ```
9
+
10
+ macOS 和 Linux 直接运行。Windows 原生 Node.js 可以安装同一个 npm 包,运行时需要已经初始化的 WSL 2 Linux 发行版。Ubuntu 或 WSL 中缺少系统工具时,运行 `sudo apt install openssh-client curl`。本地 API 使用回环地址。Windows 访问 WSL 服务依赖 localhost 转发。
11
+
12
+ 工具会安装 Colab CLI、引导 Google OAuth、显示剩余 CU,并询问 Hugging Face 模型 ID、GPU 和本地端口。等待 **API 已就绪** 后,在 OpenAI 兼容客户端填入显示的 Base URL 和模型 ID。如果客户端要求 API Key,填 `local`。退出前按 **Ctrl+C** 释放本次 GPU 会话。仅查询额度可运行 `colab-hf-chat usage`。
13
+
14
+ ## Hugging Face 模型试跑与公网 API
15
+
16
+ 默认模型为量化的 DistilBERT 英文情感分类模型,使用 CPU。Colab 用于试跑和查询账户额度,Hugging Face Docker Space 托管公网推理 API。
17
+
18
+ ## Colab 查询和试跑
19
+
20
+ ```bash
21
+ uv tool install google-colab-cli
22
+ ./deploy.sh usage
23
+ ./deploy.sh colab
24
+ ```
25
+
26
+ 首次查询时按终端提示使用 Google AI Pro 所在账号完成 OAuth,并把授权码填回终端。额度查询显示账户剩余 CU、每小时消耗和活跃分配数。试跑临时创建 CPU 会话,加载模型、打印样例预测并在退出时释放会话。
27
+
28
+ ## 发布公网 API
29
+
30
+ ```bash
31
+ hf auth login
32
+ ./deploy.sh publish YOUR_HF_USERNAME/hf-text-api
33
+ ```
34
+
35
+ 使用有目标仓库写权限的 Hugging Face Token。脚本创建公开的 CPU Basic Docker Space。重复运行会更新同名 Space 中的应用文件,请选专用于此服务的 Space。脚本等待构建完成,从 Space 获取公网域名,并无凭证调用 `/health` 和 `/predict` 验证。要重新验证已发布的 Space,可运行 `./deploy.sh verify YOUR_HF_USERNAME/hf-text-api`。访问 `/docs` 可直接试用,`/health` 确认模型已加载。
36
+
37
+ ```bash
38
+ curl -fsS "https://YOUR-SPACE.hf.space/predict" \
39
+ -H 'Content-Type: application/json' \
40
+ -d '{"text":"I really loved this movie."}'
41
+ ```
42
+
43
+ 此 API 公开访问。Colab 查询命令在本机执行,账号余额不会进入公开 API。CPU Basic Space 空闲后可能休眠。
44
+
45
+ ## 更换模型
46
+
47
+ 支持带 `tokenizer.json`、具有 `id2label` 的 `config.json` 和匹配的 ONNX 文件的单文本分类模型。ONNX 输入需兼容 `input_ids`、`attention_mask` 或 `token_type_ids`,首个输出应为分类 logits。设置 `MODEL_ID`、可选的 `MODEL_REVISION` 和 `MODEL_FILE`。Colab 从本地命令环境接收上述配置,公网 API 从 Space Settings 的 Variables 接收配置。生成、图像或语音模型需要更换推理代码和请求格式。
48
+
49
+ ## Colab GPU 与 OpenAI 兼容聊天 API
50
+
51
+ ```bash
52
+ ./deploy.sh usage
53
+ ./gpu-chat.sh L4 Qwen/Qwen2.5-0.5B-Instruct 8000
54
+ ```
55
+
56
+ 脚本申请 Colab GPU,安装 vLLM,并通过 Colab CLI 的 SSH 转发把 API 接到本机。默认模型为可公开下载的 Qwen 聊天模型。看到 **API 已就绪** 后,在另一个终端验证:
57
+
58
+ ```bash
59
+ curl -fsS http://127.0.0.1:8000/v1/models
60
+ curl -fsS http://127.0.0.1:8000/v1/chat/completions \
61
+ -H 'Content-Type: application/json' \
62
+ -d '{"model":"Qwen/Qwen2.5-0.5B-Instruct","messages":[{"role":"user","content":"用一句话介绍你自己"}],"max_tokens":64}'
63
+ ```
64
+
65
+ OpenAI SDK 的 `base_url` 填 `http://127.0.0.1:8000/v1`。脚本监听本机回环地址,供当前电脑交互式测试。退出脚本会释放 GPU 会话。L4 和 SSH 能否使用取决于账号权益、CU 余额和当时的运行时供应。
66
+
67
+ Colab 托管运行时限制与交互式计算无关的 Web 服务。需要公网 OpenAI 兼容接口时,在可用于对外服务的 GPU 主机上运行同款 vLLM,并用 HTTPS 和 API key 提供访问。上面的 CPU Space 示例是文本分类接口。
package/cli.cjs ADDED
@@ -0,0 +1,51 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const { spawn, spawnSync } = require('node:child_process');
5
+ const { join } = require('node:path');
6
+
7
+ const args = process.argv.slice(2);
8
+ if (args.includes('--help') || args.includes('-h')) {
9
+ console.log('colab-hf-chat [usage]\n\n交互启动 Colab GPU 模型,或用 usage 查询剩余 CU。');
10
+ process.exit(0);
11
+ }
12
+ if (args.length > 1 || (args.length === 1 && args[0] !== 'usage')) {
13
+ console.error('用法: colab-hf-chat [usage]');
14
+ process.exit(2);
15
+ }
16
+
17
+ const windows = process.platform === 'win32';
18
+ if (!windows && !['linux', 'darwin'].includes(process.platform)) {
19
+ console.error('支持 Linux、macOS,以及安装了 WSL 的 Windows。');
20
+ process.exit(1);
21
+ }
22
+ let script = join(__dirname, 'wizard.sh');
23
+ if (windows) {
24
+ const result = spawnSync('wsl.exe', ['--exec', 'wslpath', '-a', script], {
25
+ encoding: 'utf8',
26
+ windowsHide: true,
27
+ });
28
+ if (result.error || result.status !== 0 || !result.stdout.trim().startsWith('/')) {
29
+ console.error('请先运行 wsl --install,并打开 Linux 发行版完成初始化。');
30
+ if (result.stderr) console.error(result.stderr.trim());
31
+ process.exit(1);
32
+ }
33
+ script = result.stdout.trim();
34
+ }
35
+ const child = windows
36
+ ? spawn('wsl.exe', ['--exec', 'bash', script, ...args], { stdio: 'inherit' })
37
+ : spawn('bash', [script, ...args], { stdio: 'inherit' });
38
+
39
+ for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) {
40
+ process.once(signal, () => {
41
+ if (!windows) child.kill(signal);
42
+ });
43
+ }
44
+ child.once('error', (error) => {
45
+ console.error(error.message);
46
+ process.exitCode = 1;
47
+ });
48
+ child.once('exit', (code, signal) => {
49
+ const signalExit = { SIGINT: 130, SIGTERM: 143, SIGHUP: 129 };
50
+ process.exitCode = code ?? signalExit[signal] ?? 1;
51
+ });
package/deploy.sh ADDED
@@ -0,0 +1,85 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
4
+ COLAB="${COLAB_BIN:-colab}"
5
+ verify_space() {
6
+ local repo="$1" base_url health prediction
7
+ hf spaces wait "$repo" --timeout 10m >&2
8
+ base_url="$(hf spaces info "$repo" --json | python3 -c '
9
+ import json
10
+ import re
11
+ import sys
12
+
13
+ info = json.load(sys.stdin)
14
+ host = info.get("host") or ""
15
+ if info.get("private") is not False or not re.fullmatch(r"https://[a-z0-9-]+[.]hf[.]space/?", host):
16
+ sys.exit("Space metadata does not contain a public hf.space URL")
17
+ print(host.rstrip("/"))
18
+ ')"
19
+ health="$(curl -fsS --retry 4 --max-time 20 "$base_url/health")"
20
+ prediction="$(curl -fsS --max-time 30 "$base_url/predict" \
21
+ -H 'Content-Type: application/json' \
22
+ -d '{"text":"I really loved this movie."}')"
23
+ python3 - "$health" "$prediction" <<'PYVERIFY'
24
+ import json
25
+ import sys
26
+
27
+ health, prediction = map(json.loads, sys.argv[1:])
28
+ if (
29
+ health.get("status") != "ready"
30
+ or not health.get("model")
31
+ or health["model"] != prediction.get("model")
32
+ or not prediction.get("label")
33
+ or not isinstance(prediction.get("score"), (float, int))
34
+ or not 0 <= prediction["score"] <= 1
35
+ ):
36
+ sys.exit("Unexpected response from the public model API")
37
+ print(json.dumps(prediction))
38
+ PYVERIFY
39
+ printf '公网 API %s/predict\n在线试用 %s/docs\n' "$base_url" "$base_url"
40
+ }
41
+
42
+ case "${1:-}" in
43
+ usage)
44
+ exec "$COLAB" usage
45
+ ;;
46
+ colab)
47
+ session="${2:-hf-model-check-$(date +%s)-$$}"
48
+ "$COLAB" new -s "$session"
49
+ trap '"$COLAB" stop -s "$session" || echo "请手动停止 Colab 会话 $session" >&2' EXIT
50
+ trap 'exit 130' INT
51
+ trap 'exit 143' TERM
52
+ "$COLAB" install -s "$session" -r "$ROOT/space/requirements.txt"
53
+ "$COLAB" upload -s "$session" "$ROOT/space/model.py" /content/hf_deploy_model.py
54
+ model_env=()
55
+ for name in MODEL_ID MODEL_REVISION MODEL_FILE; do
56
+ if [[ -n "${!name:-}" ]]; then
57
+ model_env+=(--env "$name=${!name}")
58
+ fi
59
+ done
60
+ "$COLAB" exec -s "$session" --timeout 300 ${model_env[@]+"${model_env[@]}"} <<'PY'
61
+ import json
62
+ import sys
63
+ sys.path.insert(0, "/content")
64
+ from hf_deploy_model import Classifier
65
+ model = Classifier()
66
+ print(json.dumps(model.predict("I really loved this movie.")))
67
+ PY
68
+ ;;
69
+ publish)
70
+ repo="${2:?请提供 Hugging Face 目标 Space,格式为 owner/space-name}"
71
+ hf auth whoami >/dev/null
72
+ hf repos create --repo-type space --space-sdk docker --public --flavor cpu-basic --exist-ok "$repo"
73
+ hf upload --repo-type space --exclude "__pycache__/*" "$repo" "$ROOT/space" .
74
+ printf '\nSpace 页面 https://huggingface.co/spaces/%s\n' "$repo"
75
+ verify_space "$repo"
76
+ ;;
77
+ verify)
78
+ repo="${2:?请提供 Hugging Face 目标 Space,格式为 owner/space-name}"
79
+ verify_space "$repo"
80
+ ;;
81
+ *)
82
+ echo "用法: $0 {usage|colab [session-name]|publish owner/space-name|verify owner/space-name}" >&2
83
+ exit 2
84
+ ;;
85
+ esac
package/gpu-chat.sh ADDED
@@ -0,0 +1,88 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ gpu="${1:-L4}"
5
+ model="${2:-Qwen/Qwen2.5-0.5B-Instruct}"
6
+ port="${3:-8000}"
7
+ if [[ ! "$model" =~ ^[[:alnum:]_.-]+/[[:alnum:]_.-]+$ ||
8
+ ! "$port" =~ ^[1-9][0-9]{0,4}$ ]] ||
9
+ (( port > 65535 )); then
10
+ echo "用法: $0 [GPU] [owner/model] [local-port]" >&2
11
+ exit 2
12
+ fi
13
+
14
+ if command -v lsof >/dev/null &&
15
+ lsof -nP -iTCP:"$port" -sTCP:LISTEN >/dev/null 2>&1; then
16
+ echo "本地端口 $port 已被占用,请换一个端口。" >&2
17
+ exit 1
18
+ fi
19
+
20
+ colab="$(command -v "${COLAB_BIN:-colab}")"
21
+ if [[ "${COLAB_USAGE_CHECKED:-}" != 1 ]]; then
22
+ "$colab" usage
23
+ fi
24
+ session="hf-chat-$(date +%s)-$$"
25
+ scratch="$(mktemp -d)"
26
+ created=0
27
+ ssh_pid=""
28
+ cleanup() {
29
+ if [[ -n "$ssh_pid" ]]; then
30
+ kill "$ssh_pid" 2>/dev/null || true
31
+ wait "$ssh_pid" 2>/dev/null || true
32
+ fi
33
+ rm -rf -- "$scratch"
34
+ if [[ "$created" == 1 ]]; then
35
+ "$colab" stop -s "$session" || echo "请手动停止 Colab 会话 $session" >&2
36
+ fi
37
+ }
38
+ trap cleanup EXIT
39
+ trap 'exit 130' INT
40
+ trap 'exit 143' TERM
41
+ trap 'exit 129' HUP
42
+
43
+ ssh-keygen -q -t ed25519 -N '' -f "$scratch/key"
44
+ "$colab" new -s "$session" --gpu "$gpu"
45
+ created=1
46
+
47
+ # Each argument is shell-escaped before embedding it in the OpenSSH proxy command.
48
+ proxy="$(printf '%q ' "$colab" ssh --proxy-mode -s "$session" -i "$scratch/key")"
49
+ printf 'Colab 会话 %s,模型 %s。正在启动 vLLM,等待本地端口 %s 就绪。\n' \
50
+ "$session" "$model" "$port"
51
+ ssh -F /dev/null -T -i "$scratch/key" \
52
+ -o IdentitiesOnly=yes \
53
+ -o "ProxyCommand=$proxy" \
54
+ -o "UserKnownHostsFile=$scratch/known_hosts" \
55
+ -o StrictHostKeyChecking=accept-new \
56
+ -o ExitOnForwardFailure=yes \
57
+ -o ServerAliveInterval=30 -o ServerAliveCountMax=3 \
58
+ -L "127.0.0.1:$port:127.0.0.1:8000" \
59
+ root@colab-runtime bash -s -- "$model" <<'REMOTE' &
60
+ set -euo pipefail
61
+ nvidia-smi
62
+ python -m pip install --quiet uv
63
+ python -m uv venv /tmp/hf-chat
64
+ python -m uv pip install --python /tmp/hf-chat/bin/python --torch-backend auto vllm
65
+ exec /tmp/hf-chat/bin/vllm serve "$1" \
66
+ --host 127.0.0.1 --port 8000 --dtype half \
67
+ --max-model-len 4096 --served-model-name "$1"
68
+ REMOTE
69
+
70
+ ssh_pid=$!
71
+ base_url="http://127.0.0.1:$port/v1"
72
+ deadline=$((SECONDS + 600))
73
+ while kill -0 "$ssh_pid" 2>/dev/null; do
74
+ if models="$(curl --noproxy '*' -fs --max-time 3 "$base_url/models")" &&
75
+ printf '%s' "$models" | grep -Fq "\"$model\""; then
76
+ printf '\nAPI 已就绪\nBase URL %s\n模型 %s\nAPI Key 客户端必填时填 local\n按 Ctrl+C 停止并释放 GPU。\n\n' "$base_url" "$model"
77
+ wait "$ssh_pid"
78
+ exit
79
+ fi
80
+ if (( SECONDS >= deadline )); then
81
+ echo "等待 API 就绪超过 10 分钟,即将释放 GPU。" >&2
82
+ exit 1
83
+ fi
84
+ sleep 3
85
+ done
86
+ wait "$ssh_pid"
87
+ echo "SSH 已结束,API 未就绪。" >&2
88
+ exit 1
package/package.json CHANGED
@@ -1,6 +1,18 @@
1
1
  {
2
2
  "name": "colab-hf-chat",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Launch a Hugging Face chat model on Google Colab with a local OpenAI-compatible API",
5
+ "bin": {
6
+ "colab-hf-chat": "cli.cjs"
7
+ },
8
+ "engines": {
9
+ "node": ">=18"
10
+ },
11
+ "files": [
12
+ "cli.cjs",
13
+ "wizard.sh",
14
+ "gpu-chat.sh",
15
+ "deploy.sh",
16
+ "space/"
17
+ ]
18
+ }
@@ -0,0 +1,9 @@
1
+ FROM python:3.12-slim
2
+ RUN useradd --create-home --uid 1000 user
3
+ WORKDIR /home/user/app
4
+ COPY requirements.txt .
5
+ RUN pip install --no-cache-dir -r requirements.txt
6
+ USER user
7
+ COPY --chown=user:user app.py model.py ./
8
+ EXPOSE 7860
9
+ CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
@@ -0,0 +1,7 @@
1
+ ---
2
+ title: HF Text Classification API
3
+ sdk: docker
4
+ app_port: 7860
5
+ ---
6
+
7
+ Use `/docs` to try the API or send `POST /predict` with a JSON body containing `text`.
package/space/app.py ADDED
@@ -0,0 +1,29 @@
1
+ from contextlib import asynccontextmanager
2
+
3
+ from fastapi import FastAPI
4
+ from pydantic import BaseModel, Field
5
+
6
+ from model import Classifier
7
+
8
+
9
+ @asynccontextmanager
10
+ async def lifespan(app):
11
+ app.state.model = Classifier()
12
+ yield
13
+
14
+
15
+ app = FastAPI(title="Hugging Face Text Classification", lifespan=lifespan)
16
+
17
+
18
+ class PredictionRequest(BaseModel):
19
+ text: str = Field(min_length=1, max_length=4096)
20
+
21
+
22
+ @app.get("/health")
23
+ def health():
24
+ return {"status": "ready", "model": app.state.model.model_id}
25
+
26
+
27
+ @app.post("/predict")
28
+ def predict(request: PredictionRequest):
29
+ return app.state.model.predict(request.text)
package/space/model.py ADDED
@@ -0,0 +1,48 @@
1
+ import json
2
+ import os
3
+
4
+ import numpy as np
5
+ import onnxruntime as ort
6
+ from huggingface_hub import hf_hub_download
7
+ from tokenizers import Tokenizer
8
+
9
+ DEFAULT_MODEL = "Xenova/distilbert-base-uncased-finetuned-sst-2-english"
10
+ DEFAULT_REVISION = "0b6928efcb76139cae2c6881d49cda67fe119f42"
11
+
12
+
13
+ class Classifier:
14
+ def __init__(self):
15
+ self.model_id = os.getenv("MODEL_ID", DEFAULT_MODEL)
16
+ revision = os.getenv("MODEL_REVISION") or (
17
+ DEFAULT_REVISION if self.model_id == DEFAULT_MODEL else None
18
+ )
19
+ model_file = os.getenv("MODEL_FILE", "onnx/model_quantized.onnx")
20
+ tokenizer_path = hf_hub_download(self.model_id, "tokenizer.json", revision=revision)
21
+ config_path = hf_hub_download(self.model_id, "config.json", revision=revision)
22
+ with open(config_path, encoding="utf-8") as config:
23
+ self.labels = json.load(config)["id2label"]
24
+ self.tokenizer = Tokenizer.from_file(tokenizer_path)
25
+ self.tokenizer.enable_truncation(max_length=256)
26
+ options = ort.SessionOptions()
27
+ options.intra_op_num_threads = 2
28
+ self.session = ort.InferenceSession(
29
+ hf_hub_download(self.model_id, model_file, revision=revision),
30
+ sess_options=options,
31
+ providers=["CPUExecutionProvider"],
32
+ )
33
+
34
+ def predict(self, text):
35
+ encoded = self.tokenizer.encode(text)
36
+ inputs = {
37
+ "input_ids": encoded.ids,
38
+ "attention_mask": encoded.attention_mask,
39
+ "token_type_ids": encoded.type_ids,
40
+ }
41
+ logits = self.session.run(None, {
42
+ item.name: np.asarray([inputs[item.name]], dtype=np.int64)
43
+ for item in self.session.get_inputs()
44
+ })[0][0]
45
+ scores = np.exp(logits - logits.max())
46
+ scores /= scores.sum()
47
+ index = int(scores.argmax())
48
+ return {"model": self.model_id, "label": self.labels[str(index)], "score": float(scores[index])}
@@ -0,0 +1,5 @@
1
+ huggingface_hub>=0.34,<3
2
+ tokenizers>=0.21,<1
3
+ onnxruntime>=1.22,<2
4
+ fastapi>=0.116,<1
5
+ uvicorn>=0.35,<1
package/wizard.sh ADDED
@@ -0,0 +1,44 @@
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+ cd "$(dirname "$0")"
4
+ export PATH="$PATH:$HOME/.local/bin:/opt/homebrew/bin:/usr/local/bin"
5
+
6
+ if ! command -v colab >/dev/null; then
7
+ if ! command -v uv >/dev/null; then
8
+ printf '首次运行需要 uv 来安装 Google Colab CLI。\n'
9
+ read -r -p '从 Astral 官方站点下载并安装 uv?[y/N] ' answer
10
+ case "$answer" in
11
+ y|Y) curl -fsSL https://astral.sh/uv/install.sh | env UV_NO_MODIFY_PATH=1 UV_INSTALL_DIR="$HOME/.local/bin" sh ;;
12
+ *) exit 0 ;;
13
+ esac
14
+ fi
15
+ echo '正在安装 Google Colab CLI…'
16
+ uv tool install google-colab-cli
17
+ export PATH="$(uv tool dir --bin):$PATH"
18
+ fi
19
+
20
+ printf '\n首次使用时,打开 CLI 打印的 Google 链接,用 Google AI Pro 账号授权,再把授权码粘贴回此处。\n'
21
+ colab usage
22
+ if [[ "${1:-}" == usage ]]; then
23
+ exit 0
24
+ fi
25
+ for tool in ssh ssh-keygen curl; do
26
+ if ! command -v "$tool" >/dev/null; then
27
+ echo "请先在当前系统安装 $tool。Ubuntu/WSL 可运行 sudo apt install openssh-client curl。" >&2
28
+ exit 1
29
+ fi
30
+ done
31
+ printf '\n请输入公开的 Hugging Face 聊天模型 ID。\n'
32
+ while true; do
33
+ read -r -p '模型 ID [Qwen/Qwen2.5-0.5B-Instruct]: ' model
34
+ model="${model:-Qwen/Qwen2.5-0.5B-Instruct}"
35
+ if [[ "$model" =~ ^[[:alnum:]_.-]+/[[:alnum:]_.-]+$ ]]; then
36
+ break
37
+ fi
38
+ echo '请输入 owner/model 格式的模型 ID。'
39
+ done
40
+
41
+ read -r -p 'GPU [L4,可填 T4/G4/A100/H100]: ' gpu
42
+ read -r -p '本地端口 [8000]: ' port
43
+ export COLAB_USAGE_CHECKED=1
44
+ exec ./gpu-chat.sh "${gpu:-L4}" "$model" "${port:-8000}"