Spaces:
Sleeping
Sleeping
Upload 4 files
Browse files- README.md +12 -14
- app.py +4 -4
- chat_backend.py +20 -11
README.md
CHANGED
|
@@ -14,13 +14,7 @@ pinned: false
|
|
| 14 |
|
| 15 |
一个可部署到 **Hugging Face Spaces** 的中文图文对话界面,支持文字、单张或多张图片,用于调用 vLLM 的 OpenAI 兼容接口。Space 只运行网页和 HTTP 转发逻辑,模型继续运行在你已有的 vLLM 服务上,因此前端 Space 不需要 GPU。
|
| 16 |
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
```text
|
| 20 |
-
https://jo8bpbok8b8kcca5jahhqmdcpbd9cchm.openapi-inspire.inf.tech
|
| 21 |
-
```
|
| 22 |
-
|
| 23 |
-
程序自动使用 `/v1/models` 获取模型列表,向 `/v1/chat/completions` 发送对话请求。API Key 只从服务端环境变量读取。图片在 Space 服务端读取并转换为 OpenAI `image_url` 数据块,再发送给你的模型接口。
|
| 24 |
|
| 25 |
## 1. 部署到 Hugging Face Spaces
|
| 26 |
|
|
@@ -36,12 +30,13 @@ https://jo8bpbok8b8kcca5jahhqmdcpbd9cchm.openapi-inspire.inf.tech
|
|
| 36 |
|
| 37 |
| 名称 | 值 |
|
| 38 |
| --- | --- |
|
|
|
|
| 39 |
| `INF_API_KEY` | 你的实际 API Key,不包含 `Bearer ` 前缀 |
|
| 40 |
|
| 41 |
4. 按下面的环境变量表配置需要的选项。保存配置并等待 Space 完成构建、重启。
|
| 42 |
-
5. 打开应用,
|
| 43 |
|
| 44 |
-
**`INF_API_KEY` 应创建为 Secret。** Hugging Face 的普通 Variables 适合非敏感配置;它们可以在 Space 设置中公开查看。Secrets 和 Variables 都能在 Gradio 服务端通过环境变量读取,但可见性不同。
|
| 45 |
|
| 46 |
如果你希望只有自己使用,创建 **Private Space**;也可以配置下面的 `APP_USERNAME`、`APP_PASSWORD` 启用应用登录。公开且未配置登录的 Space,其访问者可以通过这个界面使用你的服务端 Key 调用模型。
|
| 47 |
|
|
@@ -66,8 +61,8 @@ https://jo8bpbok8b8kcca5jahhqmdcpbd9cchm.openapi-inspire.inf.tech
|
|
| 66 |
| 名称 | 设置位置 | 默认值 | 作用 |
|
| 67 |
| --- | --- | --- | --- |
|
| 68 |
| `INF_API_KEY` | **Secret** | 无,必填 | 请求头中的 API Key。只填写 Key 本身。 |
|
| 69 |
-
| `INF_BASE_URL` |
|
| 70 |
-
| `INF_MODEL` | Variable |
|
| 71 |
| `INF_VERIFY_SSL` | Variable | `true` | 是否验证 HTTPS 证书。设为 `false` 时对应你原来 `curl -k` 的行为。 |
|
| 72 |
| `INF_TIMEOUT` | Variable | `600` | HTTP 请求超时配置,单位为秒。 |
|
| 73 |
| `MAX_CONCURRENT_REQUESTS` | Variable | `8` | 应用允许的并发生成请求数,按后端承载能力调整。 |
|
|
@@ -241,9 +236,12 @@ source .venv/bin/activate
|
|
| 241 |
pip install -r requirements.txt
|
| 242 |
```
|
| 243 |
|
| 244 |
-
在终端
|
| 245 |
|
| 246 |
```bash
|
|
|
|
|
|
|
|
|
|
| 247 |
read -rsp 'API Key: ' INF_API_KEY
|
| 248 |
export INF_API_KEY
|
| 249 |
printf '\n'
|
|
@@ -256,11 +254,11 @@ python app.py
|
|
| 256 |
export INF_VERIFY_SSL=false
|
| 257 |
```
|
| 258 |
|
| 259 |
-
|
| 260 |
|
| 261 |
```bash
|
| 262 |
export INF_BASE_URL='https://your-api.example.com/v1'
|
| 263 |
-
export INF_MODEL='
|
| 264 |
python app.py
|
| 265 |
```
|
| 266 |
|
|
|
|
| 14 |
|
| 15 |
一个可部署到 **Hugging Face Spaces** 的中文图文对话界面,支持文字、单张或多张图片,用于调用 vLLM 的 OpenAI 兼容接口。Space 只运行网页和 HTTP 转发逻辑,模型继续运行在你已有的 vLLM 服务上,因此前端 Space 不需要 GPU。
|
| 16 |
|
| 17 |
+
接口地址和 API Key 仅从服务端私有环境变量读取,代码中没有默认接口地址。默认模型 ID 为 `test-model`。程序使用 `/v1/models` 获取模型列表,向 `/v1/chat/completions` 发送对话请求。图片在 Space 服务端读取并转换为 OpenAI `image_url` 数据块,再发送给模型接口。
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
## 1. 部署到 Hugging Face Spaces
|
| 20 |
|
|
|
|
| 30 |
|
| 31 |
| 名称 | 值 |
|
| 32 |
| --- | --- |
|
| 33 |
+
| `INF_BASE_URL` | 你的接口根地址或 `/v1` 地址;设置为 **Secret**,不要使用公开 Variable |
|
| 34 |
| `INF_API_KEY` | 你的实际 API Key,不包含 `Bearer ` 前缀 |
|
| 35 |
|
| 36 |
4. 按下面的环境变量表配置需要的选项。保存配置并等待 Space 完成构建、重启。
|
| 37 |
+
5. 打开应用,模型默认选择 `test-model`,可以直接发送消息。如果网关没有开放 `/v1/models`,不影响使用已填写的模型 ID 发送聊天请求。需要使用其他模型时可手动输入,或设置 `INF_MODEL`。
|
| 38 |
|
| 39 |
+
**`INF_BASE_URL` 和 `INF_API_KEY` 都应创建为 Secret。** Hugging Face 的普通 Variables 适合非敏感配置;它们可以在 Space 设置中公开查看。Secrets 和 Variables 都能在 Gradio 服务端通过环境变量读取,但可见性不同。接口地址和域名不会放进前端配置或请求预览;显示到网页的错误信息也会隐藏已配置的接口地址、域名和 Key。旧 Git 提交中已有的内容不会因这次更新自动删除。
|
| 40 |
|
| 41 |
如果你希望只有自己使用,创建 **Private Space**;也可以配置下面的 `APP_USERNAME`、`APP_PASSWORD` 启用应用登录。公开且未配置登录的 Space,其访问者可以通过这个界面使用你的服务端 Key 调用模型。
|
| 42 |
|
|
|
|
| 61 |
| 名称 | 设置位置 | 默认值 | 作用 |
|
| 62 |
| --- | --- | --- | --- |
|
| 63 |
| `INF_API_KEY` | **Secret** | 无,必填 | 请求头中的 API Key。只填写 Key 本身。 |
|
| 64 |
+
| `INF_BASE_URL` | **Secret** | 无,必填 | 支持填写服务根地址或带 `/v1` 的地址;程序会规范化接口路径。 |
|
| 65 |
+
| `INF_MODEL` | Variable 或 Secret | `test-model` | 默认模型 ID。适合 `/v1/models` 不可用或需要固定模型的网关。 |
|
| 66 |
| `INF_VERIFY_SSL` | Variable | `true` | 是否验证 HTTPS 证书。设为 `false` 时对应你原来 `curl -k` 的行为。 |
|
| 67 |
| `INF_TIMEOUT` | Variable | `600` | HTTP 请求超时配置,单位为秒。 |
|
| 68 |
| `MAX_CONCURRENT_REQUESTS` | Variable | `8` | 应用允许的并发生成请求数,按后端承载能力调整。 |
|
|
|
|
| 236 |
pip install -r requirements.txt
|
| 237 |
```
|
| 238 |
|
| 239 |
+
在终端输入私有接口地址和 API Key,再启动(不要把真实值写入仓库文件):
|
| 240 |
|
| 241 |
```bash
|
| 242 |
+
read -rsp 'API base URL: ' INF_BASE_URL
|
| 243 |
+
export INF_BASE_URL
|
| 244 |
+
printf '\n'
|
| 245 |
read -rsp 'API Key: ' INF_API_KEY
|
| 246 |
export INF_API_KEY
|
| 247 |
printf '\n'
|
|
|
|
| 254 |
export INF_VERIFY_SSL=false
|
| 255 |
```
|
| 256 |
|
| 257 |
+
接口地址没有内置默认值。下面仅为占位示例,不包含真实私有配置:
|
| 258 |
|
| 259 |
```bash
|
| 260 |
export INF_BASE_URL='https://your-api.example.com/v1'
|
| 261 |
+
export INF_MODEL='test-model'
|
| 262 |
python app.py
|
| 263 |
```
|
| 264 |
|
app.py
CHANGED
|
@@ -390,13 +390,13 @@ def create_app(config=None, backend=None):
|
|
| 390 |
model = gr.Dropdown(
|
| 391 |
choices=[config.default_model] if config.default_model else [],
|
| 392 |
value=config.default_model or None, allow_custom_value=True,
|
| 393 |
-
label="模型 ID", info="
|
| 394 |
interactive=True,
|
| 395 |
)
|
| 396 |
refresh = gr.Button("刷新模型 / 测试连接", size="sm")
|
| 397 |
connection = gr.Markdown(
|
| 398 |
-
"已读取
|
| 399 |
-
else "等待配置 · 请在 Space Settings → Secrets 中添加 INF_API_KEY。",
|
| 400 |
elem_id="connection",
|
| 401 |
)
|
| 402 |
system = gr.Textbox(
|
|
@@ -519,7 +519,7 @@ def create_app(config=None, backend=None):
|
|
| 519 |
queue=False, api_visibility="private")
|
| 520 |
refresh.click(fn=refresh_models, inputs=[model], outputs=[model, connection],
|
| 521 |
concurrency_limit=4, show_progress="hidden", api_visibility="private")
|
| 522 |
-
if config.api_key:
|
| 523 |
demo.load(fn=refresh_models, inputs=[model], outputs=[model, connection],
|
| 524 |
concurrency_limit=4, show_progress="hidden", api_visibility="private")
|
| 525 |
sampling = [temperature, top_p, top_k, min_p, repetition, presence, frequency]
|
|
|
|
| 390 |
model = gr.Dropdown(
|
| 391 |
choices=[config.default_model] if config.default_model else [],
|
| 392 |
value=config.default_model or None, allow_custom_value=True,
|
| 393 |
+
label="模型 ID", info="默认 test-model;可手动刷新或填写 served-model-name。",
|
| 394 |
interactive=True,
|
| 395 |
)
|
| 396 |
refresh = gr.Button("刷新模型 / 测试连接", size="sm")
|
| 397 |
connection = gr.Markdown(
|
| 398 |
+
"已读取私有接口配置 · 可直接发送消息。" if config.base_url and config.api_key
|
| 399 |
+
else "等待配置 · 请在 Space Settings → Secrets 中添加 INF_BASE_URL 和 INF_API_KEY。",
|
| 400 |
elem_id="connection",
|
| 401 |
)
|
| 402 |
system = gr.Textbox(
|
|
|
|
| 519 |
queue=False, api_visibility="private")
|
| 520 |
refresh.click(fn=refresh_models, inputs=[model], outputs=[model, connection],
|
| 521 |
concurrency_limit=4, show_progress="hidden", api_visibility="private")
|
| 522 |
+
if config.base_url and config.api_key and not config.default_model:
|
| 523 |
demo.load(fn=refresh_models, inputs=[model], outputs=[model, connection],
|
| 524 |
concurrency_limit=4, show_progress="hidden", api_visibility="private")
|
| 525 |
sampling = [temperature, top_p, top_k, min_p, repetition, presence, frequency]
|
chat_backend.py
CHANGED
|
@@ -29,7 +29,7 @@ import httpx
|
|
| 29 |
from PIL import Image, ImageOps, UnidentifiedImageError
|
| 30 |
|
| 31 |
|
| 32 |
-
|
| 33 |
|
| 34 |
|
| 35 |
class ChatAPIError(Exception):
|
|
@@ -75,14 +75,14 @@ def _env_bool(name: str, default: bool) -> bool:
|
|
| 75 |
|
| 76 |
@dataclass(frozen=True, slots=True)
|
| 77 |
class Config:
|
| 78 |
-
base_url: str =
|
| 79 |
api_key: str = field(default="", repr=False)
|
| 80 |
verify_ssl: bool = True
|
| 81 |
timeout: float = 600.0
|
| 82 |
-
default_model: str =
|
| 83 |
|
| 84 |
def __post_init__(self) -> None:
|
| 85 |
-
object.__setattr__(self, "base_url", normalize_base_url(self.base_url))
|
| 86 |
if not isinstance(self.api_key, str) or any(c in self.api_key for c in "\r\n"):
|
| 87 |
raise ChatAPIError("INF_API_KEY 格式无效,请重新检查 Space Secret。")
|
| 88 |
object.__setattr__(self, "api_key", self.api_key.strip())
|
|
@@ -105,11 +105,11 @@ class Config:
|
|
| 105 |
except ValueError:
|
| 106 |
raise ChatAPIError("INF_TIMEOUT 必须是大于 0 的有限秒数。") from None
|
| 107 |
return cls(
|
| 108 |
-
base_url=os.environ.get("INF_BASE_URL", "").strip()
|
| 109 |
api_key=os.environ.get("INF_API_KEY", ""),
|
| 110 |
verify_ssl=_env_bool("INF_VERIFY_SSL", True),
|
| 111 |
timeout=timeout,
|
| 112 |
-
default_model=os.environ.get("INF_MODEL", ""),
|
| 113 |
)
|
| 114 |
|
| 115 |
|
|
@@ -125,15 +125,22 @@ def _redact_image_text(text: str) -> str:
|
|
| 125 |
return _IMAGE_ECHO_RE.sub("[已隐藏图片 Base64 数据]", text)
|
| 126 |
|
| 127 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
def _clean_text(value: Any, config: Config, limit: int = 700) -> str:
|
| 129 |
text = _redact_image_text(str(value or ""))
|
| 130 |
# Redact before truncation, so a shortened secret can never survive.
|
| 131 |
-
|
| 132 |
-
text = text.replace(config.api_key, "[已隐藏密钥]")
|
| 133 |
-
text = re.sub(r"(?i)\bBearer\s+[^\s\"'<>]+", "Bearer [已隐藏密钥]", text)
|
| 134 |
text = _redact_image_text(html.unescape(text))
|
| 135 |
-
|
| 136 |
-
text = text.replace(config.api_key, "[已隐藏密钥]")
|
| 137 |
text = re.sub(r"<[^>]*>", " ", text)
|
| 138 |
text = re.sub(r"[\x00-\x08\x0b\x0c\x0e-\x1f]", "", text)
|
| 139 |
text = " ".join(text.split())
|
|
@@ -711,6 +718,8 @@ class ChatBackend:
|
|
| 711 |
self.transport = transport
|
| 712 |
|
| 713 |
def _client(self) -> httpx.AsyncClient:
|
|
|
|
|
|
|
| 714 |
if not self.config.api_key:
|
| 715 |
raise ChatAPIError("尚未配置 INF_API_KEY,请在 Space Settings → Secrets 中添加 API Key。")
|
| 716 |
return httpx.AsyncClient(
|
|
|
|
| 29 |
from PIL import Image, ImageOps, UnidentifiedImageError
|
| 30 |
|
| 31 |
|
| 32 |
+
DEFAULT_MODEL = "test-model"
|
| 33 |
|
| 34 |
|
| 35 |
class ChatAPIError(Exception):
|
|
|
|
| 75 |
|
| 76 |
@dataclass(frozen=True, slots=True)
|
| 77 |
class Config:
|
| 78 |
+
base_url: str = field(default="", repr=False)
|
| 79 |
api_key: str = field(default="", repr=False)
|
| 80 |
verify_ssl: bool = True
|
| 81 |
timeout: float = 600.0
|
| 82 |
+
default_model: str = DEFAULT_MODEL
|
| 83 |
|
| 84 |
def __post_init__(self) -> None:
|
| 85 |
+
object.__setattr__(self, "base_url", normalize_base_url(self.base_url) if self.base_url.strip() else "")
|
| 86 |
if not isinstance(self.api_key, str) or any(c in self.api_key for c in "\r\n"):
|
| 87 |
raise ChatAPIError("INF_API_KEY 格式无效,请重新检查 Space Secret。")
|
| 88 |
object.__setattr__(self, "api_key", self.api_key.strip())
|
|
|
|
| 105 |
except ValueError:
|
| 106 |
raise ChatAPIError("INF_TIMEOUT 必须是大于 0 的有限秒数。") from None
|
| 107 |
return cls(
|
| 108 |
+
base_url=os.environ.get("INF_BASE_URL", "").strip(),
|
| 109 |
api_key=os.environ.get("INF_API_KEY", ""),
|
| 110 |
verify_ssl=_env_bool("INF_VERIFY_SSL", True),
|
| 111 |
timeout=timeout,
|
| 112 |
+
default_model=os.environ.get("INF_MODEL", "").strip() or DEFAULT_MODEL,
|
| 113 |
)
|
| 114 |
|
| 115 |
|
|
|
|
| 125 |
return _IMAGE_ECHO_RE.sub("[已隐藏图片 Base64 数据]", text)
|
| 126 |
|
| 127 |
|
| 128 |
+
def _redact_private_text(text: str, config: Config) -> str:
|
| 129 |
+
if config.api_key:
|
| 130 |
+
text = text.replace(config.api_key, "[已隐藏密钥]")
|
| 131 |
+
parts = urlsplit(config.base_url)
|
| 132 |
+
for value in (config.base_url, parts.netloc, parts.hostname):
|
| 133 |
+
if value:
|
| 134 |
+
text = re.sub(re.escape(value), "[已隐藏接口]", text, flags=re.IGNORECASE)
|
| 135 |
+
return re.sub(r"(?i)\bBearer\s+[^\s\"'<>]+", "Bearer [已隐藏密钥]", text)
|
| 136 |
+
|
| 137 |
+
|
| 138 |
def _clean_text(value: Any, config: Config, limit: int = 700) -> str:
|
| 139 |
text = _redact_image_text(str(value or ""))
|
| 140 |
# Redact before truncation, so a shortened secret can never survive.
|
| 141 |
+
text = _redact_private_text(text, config)
|
|
|
|
|
|
|
| 142 |
text = _redact_image_text(html.unescape(text))
|
| 143 |
+
text = _redact_private_text(text, config)
|
|
|
|
| 144 |
text = re.sub(r"<[^>]*>", " ", text)
|
| 145 |
text = re.sub(r"[\x00-\x08\x0b\x0c\x0e-\x1f]", "", text)
|
| 146 |
text = " ".join(text.split())
|
|
|
|
| 718 |
self.transport = transport
|
| 719 |
|
| 720 |
def _client(self) -> httpx.AsyncClient:
|
| 721 |
+
if not self.config.base_url:
|
| 722 |
+
raise ChatAPIError("尚未配置 INF_BASE_URL,请在 Space Settings → Secrets 中添加接口地址。")
|
| 723 |
if not self.config.api_key:
|
| 724 |
raise ChatAPIError("尚未配置 INF_API_KEY,请在 Space Settings → Secrets 中添加 API Key。")
|
| 725 |
return httpx.AsyncClient(
|