Compare commits
13
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5d79d653ac | ||
|
|
0cec894ba8 | ||
|
|
dcf7e9006e | ||
|
|
049fb73231 | ||
|
|
77f91fad99 | ||
|
|
cf4e57cf79 | ||
|
|
b30ffda52e | ||
|
|
0bc283dc49 | ||
|
|
a17ac893c2 | ||
|
|
5bea806f07 | ||
|
|
853d9d3c8c | ||
|
|
6cae4e9cf9 | ||
|
|
66966f6990 |
No files matched your search
@@ -6,5 +6,6 @@ hf-cache/
|
||||
piper-models/
|
||||
ai-models/
|
||||
waifu2x/
|
||||
face-models/
|
||||
*.log
|
||||
.venv-hf/
|
||||
+4
-1
@@ -7,13 +7,16 @@ RUN apt-get update \
|
||||
# models are pre-downloaded on the host (build env has no internet)
|
||||
RUN pip install --no-cache-dir piper-tts faster-whisper
|
||||
RUN pip install --no-cache-dir -i https://pypi.tuna.tsinghua.edu.cn/simple "rembg[cpu]"
|
||||
# AI 换脸: insightface(纯Python wheel 免编译) + buffalo_l人脸检测 + inswapper_128换脸模型(宿主已预置)
|
||||
RUN pip install --no-cache-dir -i https://pypi.tuna.tsinghua.edu.cn/simple insightface
|
||||
COPY hf-cache /root/.cache/huggingface
|
||||
COPY face-models /app/face-models
|
||||
COPY piper-models /app/piper-models
|
||||
# AI 图片: u2net 抠图模型(预下载) + waifu2x-ncnn-vulkan 无损放大(CPU)
|
||||
COPY ai-models/u2net.onnx /root/.u2net/u2net.onnx
|
||||
COPY waifu2x/waifu2x-ncnn-vulkan-20220728-ubuntu /app/waifu2x
|
||||
WORKDIR /app
|
||||
COPY server.py video_ops.py audio_ops.py .
|
||||
COPY server.py video_ops.py audio_ops.py mcp_ops.py .
|
||||
ENV HF_HOME=/root/.cache/huggingface
|
||||
EXPOSE 8091
|
||||
CMD ["python", "server.py"]
|
||||
@@ -4,6 +4,10 @@ IT-Tools 的自建后端中继服务(Python 标准库 `http.server`,**监听
|
||||
|
||||
- **翻译代理** `GET /translate` —— 转发 Google Translate(走 `HTTPS_PROXY` 出网,解决国内不通)
|
||||
- **授权校验** `GET /check` —— 供 nginx `auth_request` 调用,卡密授权 / 试用窗口判定(网络故障 fail-open,不锁死付费用户)
|
||||
- **AI 生图额度** `POST /ai/quota`(前端经 `/relay/ai/quota`,带 `model` 返回上游真实配额 `upstream/upstream_daily/upstream_remaining/upstream_note`)—— **两级真实限额**:
|
||||
- 机器级:未授权用内置渠道每日 `DAILY_FREE_LIMIT` 次(默认 10,北京时间 0 点重置,`daily_gen.json` 落盘),**生成成功才扣次**,**自带提供商/KEY 生成不计次**;
|
||||
- 上游共享池(**已授权同样受保护**——内置模型上游是站主免费额度,不存在无限次):`flux*`/`dall-e-3` 走 Cloudflare Workers AI,**官方 10,000 Neurons/天 ÷ 57.6 Neurons/张(1024×1024/4 步)≈ 173 张/天**(`CF_DAILY_LIMIT` 默认 173,北京时间约 08:00 重置,`daily_gen_cf.json` 全站计数);`pollinations-*` 走 Pollinations(API Key 预算制,无固定日限,上游错误透传);
|
||||
- 额度用尽生图返回 403(含官方配额出处文案)并引导配置自己的 KEY
|
||||
- **卡密激活** `POST /activate` —— 代理 CardAuth 验卡,`CARD_AUTH_KEY` 只留在容器内
|
||||
- **授权中心 hub** `GET /hub/announcements`(拉项目公告,服务端双保险过滤 `project_id`)+ `POST /hub/report`(安装登记 + 心跳在线统计,`X-Api-Key`/`X-Project-Id=6` 只存在服务端;**先心跳后 check-update**——实测 CardAuth heartbeat 会清空 `client_version/device_info`,check-update 放最后保证版本号落库)
|
||||
- 另有大量 AI 对话/生图、TTS/ASR、视频、格式转换、网速测速、IP 查询等接口(`server.py`,约 3700 行)
|
||||
@@ -39,6 +43,11 @@ NEWAPI_URL=https://your-newapi-host/v1/chat/completions
|
||||
NEWAPI_KEY=sk-xxx
|
||||
NEWAPI_MODEL=qwen3.8-flash
|
||||
|
||||
# AI 生图内置免费额度(可选)
|
||||
DAILY_FREE_LIMIT=10 # 未授权机器每日次数(北京 0 点重置)
|
||||
CF_DAILY_LIMIT=173 # Cloudflare 共享池张数/天(官方 10,000 Neurons ÷ 57.6/张)
|
||||
CF_DAILY_FILE=/app/data/daily_gen_cf.json
|
||||
|
||||
# 出网代理(翻译等走 Google 的接口用,可选)
|
||||
HTTPS_PROXY=http://host.docker.internal:7890
|
||||
RELAY_TIMEOUT=25
|
||||
@@ -53,14 +62,27 @@ EOF
|
||||
```bash
|
||||
docker build -t it-tools-relay .
|
||||
docker run -d --name it-tools-relay --restart always \
|
||||
-p 8091:8091 --env-file .env \
|
||||
-v relay-data:/app/data \
|
||||
--network ittools-net -p 8091:8091 --env-file .env \
|
||||
-e DEFAULT_HOST_ROOT=/vol3/1000/HD3/docker/it-tools-relay/data \
|
||||
-e HTTPS_PROXY=http://host.docker.internal:7890 \
|
||||
-e HTTP_PROXY=http://host.docker.internal:7890 \
|
||||
-e NO_PROXY=localhost,127.0.0.1,192.168.68.19 \
|
||||
--add-host host.docker.internal:host-gateway \
|
||||
--cap-add NET_ADMIN \
|
||||
-v /:/hostfs \
|
||||
-v /vol3/1000/HD3/docker/it-tools-relay/data:/app/data \
|
||||
-v /vol3/1000/HD3/docker/it-tools-relay/data/config.json:/vol3/1000/HD3/docker/it-tools-relay/data/config.json \
|
||||
it-tools-relay
|
||||
```
|
||||
|
||||
已有镜像时可省去构建:`docker run ... 192.168.68.19:3200/jinghui/it-tools-relay:latest`。
|
||||
|
||||
数据(试用记录、用量库、用户库)持久化在卷 `relay-data:/app/data`。要被 IT-Tools 的 nginx 按容器名反代,需加 `--network ittools-net`(`docker network create ittools-net`)。
|
||||
数据(试用记录、用量库、用户库、news.json)持久化在目录 `data/`。要被 IT-Tools 的 nginx 按容器名反代,需加 `--network ittools-net`(`docker network create ittools-net`)。
|
||||
|
||||
注意事项(缺一不可):
|
||||
- `--add-host host.docker.internal:host-gateway` 必须有,代理与宿主服务访问依赖该解析,缺失时境外 RSS 抓取报 `Network unreachable`;
|
||||
- `HTTPS_PROXY/HTTP_PROXY` 指向宿主 Mihomo(BBC 等境外源直连不可达),`NO_PROXY` 必须包含内网地址(NewAPI/OCR/授权中心),否则内网请求被绕进代理;
|
||||
- 国际新闻走代理抓取,改动代理配置后删除 `data/news.json` 再访问一次 `/news` 即可强制重抓。
|
||||
|
||||
## 方式二:Docker Compose 部署
|
||||
|
||||
@@ -69,7 +91,6 @@ docker run -d --name it-tools-relay --restart always \
|
||||
```yaml
|
||||
services:
|
||||
it-tools-relay:
|
||||
build: .
|
||||
image: 192.168.68.19:3200/jinghui/it-tools-relay:latest
|
||||
container_name: it-tools-relay
|
||||
restart: always
|
||||
@@ -78,27 +99,33 @@ services:
|
||||
env_file:
|
||||
- .env
|
||||
environment:
|
||||
# 常用项也可直接写在这里,优先级高于 .env
|
||||
- RELAY_TIMEOUT=25
|
||||
- MAX_UPLOAD_MB=50
|
||||
- HF_HOME=/root/.cache/huggingface
|
||||
# 宿主数据目录(/hostfs、宿主路径访问类接口用)
|
||||
- DEFAULT_HOST_ROOT=/vol3/1000/HD3/docker/it-tools-relay/data
|
||||
# 容器出网走宿主 Mihomo 代理(BBC RSS 等境外源直连不可达)
|
||||
- HTTPS_PROXY=http://host.docker.internal:7890
|
||||
- HTTP_PROXY=http://host.docker.internal:7890
|
||||
# 内网服务(NewAPI/OCR/授权中心)直连,不走代理
|
||||
- NO_PROXY=localhost,127.0.0.1,192.168.68.19
|
||||
volumes:
|
||||
# 试用记录 / 用量库 / 用户库 持久化
|
||||
- relay-data:/app/data
|
||||
# 可选:代理宿主机目录,供 /hostfs、文件转换类接口使用
|
||||
# - ./data:/app/data
|
||||
# 数据持久化:试用记录 / 用量库 / 用户库 / news.json
|
||||
- ./data:/app/data
|
||||
# 宿主全路径(run 段同款):缺失则 DATA_DIR 漂移到容器易失层,重建后用户库/密钥全丢
|
||||
- /:/hostfs
|
||||
# 存储根配置必须持久:不挂载则落在容器易失层,重建容器后 storage_root 丢失
|
||||
# → DATA_DIR 漂移到易失目录 → 用户库/密钥/上传全丢
|
||||
- ./data/config.json:/vol3/1000/HD3/docker/it-tools-relay/data/config.json
|
||||
cap_add:
|
||||
- NET_ADMIN
|
||||
extra_hosts:
|
||||
# 容器内访问宿机代理 / 服务时用 host.docker.internal
|
||||
# 缺失会导致境外 RSS 抓取 Network unreachable
|
||||
- "host.docker.internal:host-gateway"
|
||||
networks:
|
||||
- ittools-net
|
||||
|
||||
volumes:
|
||||
relay-data:
|
||||
|
||||
networks:
|
||||
# 接入既有 ittools-net 供 it-tools nginx 反代;external=true 防止重建同名网络
|
||||
ittools-net:
|
||||
driver: bridge
|
||||
external: true
|
||||
```
|
||||
|
||||
```bash
|
||||
@@ -112,6 +139,10 @@ curl -s http://127.0.0.1:8091/auth-status # 返回 JSON 即服务正常
|
||||
|
||||
只重建代码(模型目录已缓存):`docker compose up -d --build it-tools-relay`。
|
||||
|
||||
## 中文提示词自动转英文(2026-11-13)
|
||||
|
||||
`_handle_gen_image` / `_handle_edit_image` 发起生成前经 `_translate_prompt()`:提示词含中文时用 `IMG_PROMPT_MODEL`(默认 `mimo-v2.6-flash`,走 NEWAPI_URL + NEWAPI_KEY)转成高质量英文生图提示词再发上游(Flux/SDXL 系对英文理解最好);进程内缓存 300 条;翻译失败/超时/结果仍含中文一律回退原文,**绝不阻断生图**;纯英文提示词原样透传。实际发送的英文随响应 `prompt_en` 字段返回(前端结果图操作行显示「🌐 已自动转英文发送(悬停查看)」);生成历史仍存用户原文。
|
||||
|
||||
## 其他镜像变体
|
||||
|
||||
| 文件 | 用途 |
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
services:
|
||||
it-tools-relay:
|
||||
image: 192.168.68.19:3200/jinghui/it-tools-relay:latest
|
||||
container_name: it-tools-relay
|
||||
restart: always
|
||||
ports:
|
||||
- "8091:8091"
|
||||
env_file:
|
||||
- .env
|
||||
environment:
|
||||
# 宿主数据目录(/hostfs、宿主路径访问类接口用)
|
||||
- DEFAULT_HOST_ROOT=/vol3/1000/HD3/docker/it-tools-relay/data
|
||||
# 容器出网走宿主 Mihomo 代理(BBC RSS 等境外源直连不可达,必须走代理)
|
||||
- HTTPS_PROXY=http://host.docker.internal:7890
|
||||
- HTTP_PROXY=http://host.docker.internal:7890
|
||||
# 内网服务(NewAPI/OCR/授权中心)直连,不走代理
|
||||
- NO_PROXY=localhost,127.0.0.1,192.168.68.19
|
||||
volumes:
|
||||
# 数据持久化:试用记录 / 用量库 / 用户库 / news.json
|
||||
- ./data:/app/data
|
||||
# 宿主全路径(canonical run line 同款):_load_storage_root 经 /hostfs 解析 config.json,
|
||||
# 缺失则 DATA_DIR 漂移到容器易失 /vol3/... 层 → 重建容器后用户库/密钥全丢
|
||||
- /:/hostfs
|
||||
# 存储根配置必须持久:不挂载则落在容器易失层,重建容器后 storage_root 丢失
|
||||
# → DATA_DIR 漂移到易失目录 → 用户库/密钥/上传全丢
|
||||
- ./data/config.json:/vol3/1000/HD3/docker/it-tools-relay/data/config.json
|
||||
cap_add:
|
||||
- NET_ADMIN
|
||||
extra_hosts:
|
||||
# 代理/宿主服务访问依赖此解析(缺失会导致出网 Network unreachable)
|
||||
- "host.docker.internal:host-gateway"
|
||||
networks:
|
||||
- ittools-net
|
||||
|
||||
networks:
|
||||
# 必须接入既有 ittools-net,供 it-tools 的 nginx 按容器名反代;
|
||||
# 已存在则必须 external=true,否则 compose 会重建同名网络导致孤立
|
||||
ittools-net:
|
||||
external: true
|
||||
+744
@@ -0,0 +1,744 @@
|
||||
"""MCP (Model Context Protocol) 接入模块 — IT-TOOLS-PRO 授权应用的 AI 调用入口。
|
||||
|
||||
设计(与 video_ops/audio_ops 同为 server.py 伴星模块):
|
||||
- 令牌:MCP 令牌存 DATA_DIR/mcp_tokens.json,与本机机器码绑定;生成与每次调用都复验
|
||||
query_authorized / 账号授权,卡密过期令牌即失效("购买卡密才能调用")。
|
||||
- 协议端点:POST /mcp —— MCP Streamable HTTP(JSON-RPC 2.0,无会话状态)。
|
||||
initialize / tools/list 免鉴权(让客户端先发现工具),tools/call 必须 Bearer 令牌。
|
||||
- 13 个工具经本机 loopback http://127.0.0.1:8091 直调 relay 自身端点(完整走
|
||||
check() 授权 + log_usage() 统计),OCR 直打宿主 rapidocr:5000。
|
||||
- 文件类结果落 DATA_DIR/mcp_files/,响应里返回可下载 URL(GET /mcp/file/<name>,同令牌鉴权)。
|
||||
- 每次 tools/call 记 mcp_usage 表(令牌尾号/机器/工具/耗时/成败),供后台「MCP 调用」页查询。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import sqlite3
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
# ---- 由 server.py 启动时注入(避免循环 import) ----
|
||||
_CTX = {
|
||||
"data_dir": "/app/data",
|
||||
"usage_db": "/app/data/usage.db",
|
||||
"query_authorized": lambda machine: False,
|
||||
"account_ok": lambda machine: False,
|
||||
"machine_ok": lambda m: bool(re.match(r"^\d{13,20}$", m)),
|
||||
"public_base": "", # 空则按请求 Host 推断
|
||||
}
|
||||
|
||||
|
||||
def setup(**kw):
|
||||
_CTX.update({k: v for k, v in kw.items() if v is not None})
|
||||
_ensure_table()
|
||||
|
||||
|
||||
def _tokens_file():
|
||||
return os.path.join(_CTX["data_dir"], "mcp_tokens.json")
|
||||
|
||||
|
||||
def _files_dir():
|
||||
d = os.path.join(_CTX["data_dir"], "mcp_files")
|
||||
os.makedirs(d, exist_ok=True)
|
||||
return d
|
||||
|
||||
|
||||
def _ensure_table():
|
||||
try:
|
||||
conn = sqlite3.connect(_CTX["usage_db"])
|
||||
conn.execute("CREATE TABLE IF NOT EXISTS mcp_usage ("
|
||||
"id INTEGER PRIMARY KEY AUTOINCREMENT, token_tail TEXT, machine TEXT, "
|
||||
"tool TEXT, ok INTEGER, err TEXT, dur_ms INTEGER, at REAL)")
|
||||
conn.commit()
|
||||
conn.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def log_mcp(token_tail: str, machine: str, tool: str, ok: bool, err: str, dur_ms: int):
|
||||
try:
|
||||
conn = sqlite3.connect(_CTX["usage_db"])
|
||||
conn.execute("INSERT INTO mcp_usage (token_tail, machine, tool, ok, err, dur_ms, at) "
|
||||
"VALUES (?,?,?,?,?,?,?)",
|
||||
(token_tail, machine, tool, 1 if ok else 0, (err or "")[:400], int(dur_ms), time.time()))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def mcp_usage_query(days: int = 7) -> dict:
|
||||
since = time.time() - days * 86400
|
||||
conn = sqlite3.connect(_CTX["usage_db"])
|
||||
rows = conn.execute(
|
||||
"SELECT token_tail, machine, tool, ok, err, dur_ms, at FROM mcp_usage "
|
||||
"WHERE at>? ORDER BY at DESC LIMIT 300", (since,)).fetchall()
|
||||
by_tool = conn.execute(
|
||||
"SELECT tool, COUNT(*), SUM(ok) FROM mcp_usage WHERE at>? GROUP BY tool ORDER BY COUNT(*) DESC",
|
||||
(since,)).fetchall()
|
||||
total = conn.execute("SELECT COUNT(*), SUM(ok) FROM mcp_usage WHERE at>?", (since,)).fetchone()
|
||||
conn.close()
|
||||
return {
|
||||
"days": days,
|
||||
"total": int(total[0] or 0),
|
||||
"ok_total": int(total[1] or 0),
|
||||
"by_tool": [{"tool": t, "count": int(c), "ok": int(o or 0)} for t, c, o in by_tool],
|
||||
"rows": [{"token_tail": r[0], "machine": r[1], "tool": r[2], "ok": bool(r[3]),
|
||||
"err": r[4] or "", "dur_ms": int(r[5] or 0), "at": int(r[6] or 0)} for r in rows],
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 令牌管理
|
||||
|
||||
def _load_tokens() -> list:
|
||||
try:
|
||||
with open(_tokens_file(), "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
return data if isinstance(data, list) else []
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
|
||||
def _save_tokens(items: list):
|
||||
tmp = _tokens_file() + ".tmp"
|
||||
with open(tmp, "w", encoding="utf-8") as f:
|
||||
json.dump(items, f, ensure_ascii=False, indent=1)
|
||||
os.replace(tmp, _tokens_file())
|
||||
|
||||
|
||||
def _authorized(machine: str) -> bool:
|
||||
if not machine or not _CTX["machine_ok"](machine):
|
||||
return False
|
||||
try:
|
||||
return bool(_CTX["query_authorized"](machine)) or bool(_CTX["account_ok"](machine))
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _bearer(handler) -> str:
|
||||
auth = handler.headers.get("Authorization", "") or ""
|
||||
if auth.lower().startswith("bearer "):
|
||||
return auth[7:].strip()
|
||||
return (handler.headers.get("X-MCP-Token", "") or "").strip()
|
||||
|
||||
|
||||
def _find_token(tok: str):
|
||||
if not tok:
|
||||
return None
|
||||
for it in _load_tokens():
|
||||
if it.get("token") == tok:
|
||||
return it
|
||||
return None
|
||||
|
||||
|
||||
def tokens_api(method: str, payload: dict, qs: dict) -> tuple[int, dict]:
|
||||
"""令牌管理:GET /mcp/tokens、POST /mcp/tokens(生成)、POST /mcp/tokens/delete。"""
|
||||
machine = (payload.get("machine_id") or payload.get("machine")
|
||||
or (qs.get("machine_id") or qs.get("machine") or [""])[0] or "").strip()
|
||||
if not _authorized(machine):
|
||||
return 403, {"code": 403, "message": "本设备尚未授权:购买卡密并激活后才能生成 MCP 令牌"}
|
||||
|
||||
items = _load_tokens()
|
||||
if method == "GET":
|
||||
mine = [it for it in items if it.get("machine") == machine]
|
||||
return 200, {"code": 200, "message": "ok",
|
||||
"data": {"tokens": mine, "count": len(mine), "authorized": True}}
|
||||
|
||||
if method == "POST" and payload.get("action") == "delete":
|
||||
tok = payload.get("token") or ""
|
||||
kept = [it for it in items if not (it.get("token") == tok and it.get("machine") == machine)]
|
||||
if len(kept) != len(items):
|
||||
_save_tokens(kept)
|
||||
return 200, {"code": 200, "message": "已删除", "data": {"tokens": [i for i in kept if i.get("machine") == machine]}}
|
||||
return 404, {"code": 404, "message": "令牌不存在"}
|
||||
|
||||
# 生成
|
||||
mine = [it for it in items if it.get("machine") == machine]
|
||||
if len(mine) >= 10:
|
||||
return 400, {"code": 400, "message": "每台设备最多 10 个 MCP 令牌,请先删除不用的"}
|
||||
note = (payload.get("note") or "").strip()[:40]
|
||||
rec = {
|
||||
"token": "mcpt_" + secrets.token_hex(24),
|
||||
"machine": machine,
|
||||
"note": note or "MCP 客户端",
|
||||
"created": int(time.time()),
|
||||
"last_used": 0,
|
||||
"calls": 0,
|
||||
}
|
||||
items.append(rec)
|
||||
_save_tokens(items)
|
||||
return 200, {"code": 200, "message": "ok", "data": {"token": rec["token"], "record": rec}}
|
||||
|
||||
|
||||
def _touch_token(tok: str):
|
||||
items = _load_tokens()
|
||||
changed = False
|
||||
for it in items:
|
||||
if it.get("token") == tok:
|
||||
it["last_used"] = int(time.time())
|
||||
it["calls"] = int(it.get("calls") or 0) + 1
|
||||
changed = True
|
||||
break
|
||||
if changed:
|
||||
try:
|
||||
_save_tokens(items)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- http 内调
|
||||
|
||||
_LOOPBACK = "http://127.0.0.1:8091"
|
||||
_OCR_URL = "http://host.docker.internal:5000/ocr"
|
||||
|
||||
|
||||
def _req(base: str, method: str, path: str, headers: dict, body=None, timeout: int = 600):
|
||||
h = {"User-Agent": "ittools-mcp/1.0"}
|
||||
if headers:
|
||||
h.update(headers)
|
||||
url = base + path
|
||||
req = urllib.request.Request(url, data=body, headers=h, method=method)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
return r.status, dict(r.headers), r.read()
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code, dict(e.headers), e.read()
|
||||
|
||||
|
||||
def _hdr(machine: str, tool: str, ct: str = "") -> dict:
|
||||
h = {"X-Machine-Id": machine, "X-Tool": tool}
|
||||
if ct:
|
||||
h["Content-Type"] = ct
|
||||
return h
|
||||
|
||||
|
||||
def _check(status, raw):
|
||||
if status == 403:
|
||||
raise RuntimeError("授权校验未通过(403):设备授权缺失或已过期")
|
||||
if status >= 400:
|
||||
raise RuntimeError(f"HTTP {status}: {raw.decode('utf-8', 'ignore')[:300]}")
|
||||
return raw
|
||||
|
||||
|
||||
def _json_api(status, raw):
|
||||
_check(status, raw)
|
||||
try:
|
||||
j = json.loads(raw.decode("utf-8"))
|
||||
except Exception:
|
||||
return raw.decode("utf-8", "ignore")[:5000]
|
||||
if isinstance(j, dict) and j.get("code") not in (None, 200, 0):
|
||||
raise RuntimeError(j.get("message") or f"接口返回 code={j.get('code')}")
|
||||
return j
|
||||
|
||||
|
||||
def _multipart(fields, files):
|
||||
boundary = uuid.uuid4().hex
|
||||
out = bytearray()
|
||||
for k, v in fields.items():
|
||||
out += f"--{boundary}\r\nContent-Disposition: form-data; name=\"{k}\"\r\n\r\n{v}\r\n".encode()
|
||||
for field, fname, data, ct in files:
|
||||
out += (f"--{boundary}\r\nContent-Disposition: form-data; name=\"{field}\"; "
|
||||
f"filename=\"{fname}\"\r\nContent-Type: {ct}\r\n\r\n").encode()
|
||||
out += data + b"\r\n"
|
||||
out += f"--{boundary}--\r\n".encode()
|
||||
return bytes(out), f"multipart/form-data; boundary={boundary}"
|
||||
|
||||
|
||||
def _mime(path: str) -> str:
|
||||
ext = os.path.splitext(path)[1].lower()
|
||||
return {
|
||||
".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp",
|
||||
".gif": "image/gif", ".pdf": "application/pdf", ".mp3": "audio/mpeg", ".wav": "audio/wav",
|
||||
".m4a": "audio/mp4", ".mp4": "video/mp4", ".mov": "video/quicktime", ".mkv": "video/x-matroska",
|
||||
".avi": "video/x-msvideo", ".webm": "video/webm",
|
||||
".doc": "application/msword",
|
||||
".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||
".xls": "application/vnd.ms-excel",
|
||||
".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
".ppt": "application/vnd.ms-powerpoint",
|
||||
".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
|
||||
".txt": "text/plain", ".srt": "application/x-subrip", ".json": "application/json",
|
||||
}.get(ext, "application/octet-stream")
|
||||
|
||||
|
||||
def _save_file(data: bytes, name_hint: str, headers=None) -> dict:
|
||||
name = name_hint
|
||||
cd = (headers or {}).get("Content-Disposition") or ""
|
||||
m = re.search(r"filename\*=UTF-8''([^;]+)", cd) or re.search(r'filename="([^"]+)"', cd)
|
||||
if m:
|
||||
name = urllib.parse.unquote(m.group(1))
|
||||
safe = re.sub(r"[^\w.\-]+", "_", name)[-80:] or "result.bin"
|
||||
if "." not in safe:
|
||||
safe += ".bin"
|
||||
fname = f"{time.strftime('%Y%m%d-%H%M%S')}-{uuid.uuid4().hex[:6]}-{safe}"
|
||||
with open(os.path.join(_files_dir(), fname), "wb") as f:
|
||||
f.write(data)
|
||||
return {"file": fname, "name": safe, "bytes": len(data), "url": f"/mcp/file/{fname}"}
|
||||
|
||||
|
||||
def _host_path(path: str) -> str:
|
||||
"""AI 客户端(与宿主同机)传宿主绝对路径(/vol1/…),relay 容器内经 /:/hostfs 挂载可达。"""
|
||||
if not path or not str(path).startswith("/"):
|
||||
return path
|
||||
if os.path.isfile(path):
|
||||
return path
|
||||
alt = "/hostfs" + path
|
||||
if os.path.isfile(alt):
|
||||
return alt
|
||||
return path
|
||||
|
||||
|
||||
def _read_file(path: str) -> bytes:
|
||||
path = _host_path(path)
|
||||
if not path or not os.path.isfile(path):
|
||||
raise RuntimeError(f"文件不存在: {path}")
|
||||
with open(path, "rb") as f:
|
||||
return f.read()
|
||||
|
||||
|
||||
def _ok(data):
|
||||
return json.dumps({"ok": True, "data": data}, ensure_ascii=False, default=str)
|
||||
|
||||
|
||||
def _err(e):
|
||||
return json.dumps({"ok": False, "error": str(e)[:1500]}, ensure_ascii=False)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 13 个工具
|
||||
|
||||
def tool_translate_text(machine, text, source="auto", target="zh-CN"):
|
||||
q = urllib.parse.urlencode({"client": "gtx", "sl": source, "tl": target, "dt": "t", "q": text})
|
||||
status, _, raw = _req(_LOOPBACK, "GET", "/translate?" + q, _hdr(machine, "translator"), timeout=60)
|
||||
j = json.loads(_check(status, raw).decode("utf-8"))
|
||||
segs = j[0] if isinstance(j, list) and j else []
|
||||
return _ok({"text": "".join(s[0] for s in segs if isinstance(s, list) and s and s[0])})
|
||||
|
||||
|
||||
def tool_ocr(machine, path):
|
||||
path = _host_path(path)
|
||||
if path.lower().endswith(".pdf"):
|
||||
pages = _pdf_pages(path)
|
||||
result = []
|
||||
for fn, data in pages:
|
||||
body, ct = _multipart({}, [("image_file", fn, data, "image/jpeg")])
|
||||
status, _, raw = _req("http://host.docker.internal:5000", "POST", "/ocr",
|
||||
_hdr(machine, "pdf-ocr", ct), body, timeout=120)
|
||||
j = json.loads(_check(status, raw).decode("utf-8"))
|
||||
lines = [{"text": j[k].get("rec_txt", ""), "score": j[k].get("score", 0)}
|
||||
for k in sorted(j, key=lambda x: int(x)) if j[k].get("rec_txt")]
|
||||
result.append({"page": fn, "lines": lines})
|
||||
return _ok({"pages": len(result), "detail": result,
|
||||
"text": "\n".join(l["text"] for p in result for l in p["lines"])})
|
||||
data = _read_file(path)
|
||||
body, ct = _multipart({}, [("image_file", os.path.basename(path), data, _mime(path))])
|
||||
status, _, raw = _req("http://host.docker.internal:5000", "POST", "/ocr",
|
||||
_hdr(machine, "image-ocr", ct), body, timeout=120)
|
||||
j = json.loads(_check(status, raw).decode("utf-8"))
|
||||
lines = [{"text": j[k].get("rec_txt", ""), "score": j[k].get("score", 0)}
|
||||
for k in sorted(j, key=lambda x: int(x)) if j[k].get("rec_txt")]
|
||||
return _ok({"lines": lines, "text": "\n".join(l["text"] for l in lines)})
|
||||
|
||||
|
||||
def _pdf_pages(path, dpi=150):
|
||||
try:
|
||||
import subprocess
|
||||
tmp = os.path.join(_files_dir(), f".pdf-{uuid.uuid4().hex[:8]}")
|
||||
os.makedirs(tmp, exist_ok=True)
|
||||
proc = subprocess.run(["pdftoppm", "-jpeg", "-r", str(dpi), path, os.path.join(tmp, "p")],
|
||||
capture_output=True, timeout=120)
|
||||
if proc.returncode == 0:
|
||||
pages = []
|
||||
for fn in sorted(os.listdir(tmp)):
|
||||
if fn.endswith(".jpg"):
|
||||
with open(os.path.join(tmp, fn), "rb") as f:
|
||||
pages.append((fn, f.read()))
|
||||
if pages:
|
||||
return pages
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
import fitz
|
||||
except ImportError:
|
||||
raise RuntimeError("PDF 渲染组件缺失(需 pdftoppm 或 pymupdf)")
|
||||
with open(path, "rb") as f:
|
||||
data = f.read()
|
||||
doc = fitz.open(stream=data, filetype="pdf")
|
||||
return [(f"page-{i + 1}.jpg", p.get_pixmap(dpi=dpi).tobytes("jpg")) for i, p in enumerate(doc)]
|
||||
|
||||
|
||||
def tool_translate_doc(machine, path, to="en"):
|
||||
data = _read_file(path)
|
||||
body, ct = _multipart({"to": to}, [("file", os.path.basename(path), data, _mime(path))])
|
||||
status, _, raw = _req(_LOOPBACK, "POST", "/translate-doc", _hdr(machine, "translator", ct),
|
||||
body, timeout=480)
|
||||
j = _json_api(status, raw)
|
||||
d = j.get("data") or {}
|
||||
return _ok({"text": d.get("text"), "chars": d.get("chars"), "target": to})
|
||||
|
||||
|
||||
def tool_tts(machine, text, voice="", rate="", pitch=""):
|
||||
body = json.dumps({"text": text, "voice": voice, "rate": rate, "pitch": pitch}).encode()
|
||||
status, hdrs, raw = _req(_LOOPBACK, "POST", "/tts", _hdr(machine, "audio-tools", "application/json"),
|
||||
body, timeout=180)
|
||||
_check(status, raw)
|
||||
if raw[:1] in (b"{", b"["):
|
||||
raise RuntimeError(json.loads(raw.decode("utf-8")).get("message") or "TTS 失败")
|
||||
return _ok(_save_file(raw, "tts.mp3", hdrs))
|
||||
|
||||
|
||||
def tool_speech_to_text(machine, path, language="auto"):
|
||||
data = _read_file(path)
|
||||
body, ct = _multipart({"language": language}, [("file", os.path.basename(path), data, _mime(path))])
|
||||
status, _, raw = _req(_LOOPBACK, "POST", "/asr", _hdr(machine, "audio-tools", ct), body, timeout=300)
|
||||
j = _json_api(status, raw)
|
||||
d = j.get("data") or {}
|
||||
return _ok({"text": d.get("text"), "language": d.get("language"), "segments": d.get("segments")})
|
||||
|
||||
|
||||
def tool_extract_subtitle(machine, path, lang=""):
|
||||
data = _read_file(path)
|
||||
body, ct = _multipart({}, [("file", os.path.basename(path), data, _mime(path))])
|
||||
status, _, raw = _req(_LOOPBACK, "POST", "/subtitle?lang=" + urllib.parse.quote(lang),
|
||||
_hdr(machine, "video-tools", ct), body, timeout=600)
|
||||
j = _json_api(status, raw)
|
||||
d = j.get("data") or {}
|
||||
return _ok({"segments": d.get("segments"), "language": d.get("language")})
|
||||
|
||||
|
||||
_VIDEO_OPS = ("convert", "gif", "gif2video", "compress", "trim", "rotate", "flip",
|
||||
"speed", "mute", "watermark", "unwatermark", "audio", "screenshot")
|
||||
|
||||
|
||||
def tool_video_process(machine, path, op, options=None):
|
||||
if op == "subtitle":
|
||||
return tool_extract_subtitle(machine, path)
|
||||
if op not in _VIDEO_OPS:
|
||||
raise RuntimeError(f"op 须为 {'/'.join(_VIDEO_OPS)} 或 subtitle")
|
||||
data = _read_file(path)
|
||||
fields = {"op": op}
|
||||
for k, v in (options or {}).items():
|
||||
fields[k] = str(v)
|
||||
body, ct = _multipart(fields, [("file", os.path.basename(path), data, _mime(path))])
|
||||
status, hdrs, raw = _req(_LOOPBACK, "POST", "/video", _hdr(machine, "video-tools", ct), body, timeout=600)
|
||||
_check(status, raw)
|
||||
if raw[:1] in (b"{", b"["):
|
||||
raise RuntimeError(json.loads(raw.decode("utf-8")).get("message") or "视频处理失败")
|
||||
return _ok(_save_file(raw, f"{op}-out.bin", hdrs))
|
||||
|
||||
|
||||
def tool_gen_image(machine, prompt, model="pollinations-flux", width=1024, height=1024):
|
||||
body = json.dumps({"machine": machine, "prompt": prompt, "model": model,
|
||||
"width": int(width), "height": int(height)}).encode()
|
||||
status, _, raw = _req(_LOOPBACK, "POST", "/ai/gen-image",
|
||||
_hdr(machine, "ai-gen", "application/json"), body, timeout=300)
|
||||
j = _json_api(status, raw)
|
||||
d = (j.get("data") or {}) if isinstance(j, dict) else {}
|
||||
if d.get("b64"):
|
||||
import base64
|
||||
b64 = d["b64"].split(",", 1)[-1]
|
||||
return _ok(_save_file(base64.b64decode(b64), "ai-gen.png"))
|
||||
if d.get("url"):
|
||||
req = urllib.request.Request(d["url"], headers={"User-Agent": "ittools-mcp/1.0"})
|
||||
with urllib.request.urlopen(req, timeout=120) as r:
|
||||
return _ok(_save_file(r.read(), "ai-gen.png", dict(r.headers)))
|
||||
raise RuntimeError("接口未返回图片数据")
|
||||
|
||||
|
||||
def tool_convert_doc(machine, path, format):
|
||||
data = _read_file(path)
|
||||
body, ct = _multipart({"format": format}, [("files", os.path.basename(path), data, _mime(path))])
|
||||
status, hdrs, raw = _req(_LOOPBACK, "POST", "/convert", _hdr(machine, "doc-convert", ct),
|
||||
body, timeout=300)
|
||||
_check(status, raw)
|
||||
if raw[:1] in (b"{", b"["):
|
||||
raise RuntimeError(json.loads(raw.decode("utf-8")).get("message") or "格式转换失败")
|
||||
return _ok(_save_file(raw, os.path.basename(path) + f".{format.lstrip('.')}", hdrs))
|
||||
|
||||
|
||||
def _raw_image_op(machine, path, api_path, ct_override=None, timeout=300):
|
||||
data = _read_file(path)
|
||||
status, hdrs, raw = _req(_LOOPBACK, "POST", api_path,
|
||||
_hdr(machine, "image-tools", ct_override or _mime(path)),
|
||||
data, timeout=timeout)
|
||||
_check(status, raw)
|
||||
if raw[:1] in (b"{", b"["):
|
||||
raise RuntimeError(json.loads(raw.decode("utf-8")).get("message") or "图片处理失败")
|
||||
ext = ".png" if raw[:8] == b"\x89PNG\r\n\x1a\n" else (".jpg" if raw[:2] == b"\xff\xd8" else ".webp")
|
||||
return _ok(_save_file(raw, "out" + ext, hdrs))
|
||||
|
||||
|
||||
def tool_remove_bg(machine, path):
|
||||
return _raw_image_op(machine, path, "/remove-bg", timeout=300)
|
||||
|
||||
|
||||
def tool_upscale_image(machine, path, scale=2, noise=1):
|
||||
if int(scale) not in (2, 4):
|
||||
raise RuntimeError("scale 仅支持 2 或 4")
|
||||
return _raw_image_op(machine, path, f"/upscale?scale={int(scale)}&noise={int(noise)}", timeout=400)
|
||||
|
||||
|
||||
_COPY_SCENES = ("rewrite", "deaigc", "titles", "xhs", "moments")
|
||||
|
||||
|
||||
def tool_copywriting(machine, text, scene="rewrite", model="mimo-v2.6-flash"):
|
||||
if scene not in _COPY_SCENES:
|
||||
raise RuntimeError(f"scene 须为 {'/'.join(_COPY_SCENES)}")
|
||||
body = json.dumps({"machine": machine, "scene": scene, "text": text, "model": model}).encode()
|
||||
status, _, raw = _req(_LOOPBACK, "POST", "/ai/copy", _hdr(machine, "", "application/json"),
|
||||
body, timeout=180)
|
||||
j = _json_api(status, raw)
|
||||
d = j.get("data") if isinstance(j, dict) else j
|
||||
if isinstance(d, dict) and (d.get("text") or d.get("reply")):
|
||||
return _ok({"text": d.get("text") or d.get("reply")})
|
||||
if isinstance(d, str):
|
||||
return _ok({"text": d})
|
||||
return _ok({"result": d})
|
||||
|
||||
|
||||
def tool_vision_qa(machine, image_path, question="描述这张图片的内容"):
|
||||
import base64
|
||||
data = _read_file(image_path)
|
||||
body = json.dumps({"machine": machine, "image": base64.b64encode(data).decode(),
|
||||
"question": question}).encode()
|
||||
status, _, raw = _req(_LOOPBACK, "POST", "/ai/vision", _hdr(machine, "image-tools", "application/json"),
|
||||
body, timeout=180)
|
||||
j = _json_api(status, raw)
|
||||
d = j.get("data") if isinstance(j, dict) else j
|
||||
if isinstance(d, dict) and (d.get("text") or d.get("answer") or d.get("reply")):
|
||||
return _ok({"answer": d.get("text") or d.get("answer") or d.get("reply")})
|
||||
if isinstance(d, str):
|
||||
return _ok({"answer": d})
|
||||
return _ok({"result": d})
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 工具注册表
|
||||
|
||||
_S = {"type": "object"}
|
||||
TOOLS = [
|
||||
{"name": "translate_text", "fn": tool_translate_text,
|
||||
"description": "翻译一段文本(谷歌引擎,多语言互译)。",
|
||||
"inputSchema": {"type": "object", "properties": {
|
||||
"text": {"type": "string"}, "source": {"type": "string", "default": "auto"},
|
||||
"target": {"type": "string", "default": "zh-CN"}}, "required": ["text"]}},
|
||||
{"name": "ocr", "fn": tool_ocr,
|
||||
"description": "识别图片/PDF 中的文字,返回逐行文本与置信度(PDF 自动逐页)。",
|
||||
"inputSchema": {"type": "object", "properties": {"path": {"type": "string", "description": "服务器可访问的文件路径或已上传文件名"}},
|
||||
"required": ["path"]}},
|
||||
{"name": "translate_doc", "fn": tool_translate_doc,
|
||||
"description": "整篇文档翻译(docx/pdf 等 → 译文全文),耗时可达数分钟。",
|
||||
"inputSchema": {"type": "object", "properties": {"path": {"type": "string"},
|
||||
"to": {"type": "string", "default": "en"}},
|
||||
"required": ["path"]}},
|
||||
{"name": "tts", "fn": tool_tts,
|
||||
"description": "文字合成语音,返回 mp3 下载 URL。",
|
||||
"inputSchema": {"type": "object", "properties": {"text": {"type": "string"},
|
||||
"voice": {"type": "string"}, "rate": {"type": "string"},
|
||||
"pitch": {"type": "string"}}, "required": ["text"]}},
|
||||
{"name": "speech_to_text", "fn": tool_speech_to_text,
|
||||
"description": "音频转文字(ASR),返回识别文本与时间分段。",
|
||||
"inputSchema": {"type": "object", "properties": {"path": {"type": "string"},
|
||||
"language": {"type": "string", "default": "auto"}},
|
||||
"required": ["path"]}},
|
||||
{"name": "extract_subtitle", "fn": tool_extract_subtitle,
|
||||
"description": "视频/音频 AI 字幕生成:输出带时间轴的识别分段。",
|
||||
"inputSchema": {"type": "object", "properties": {"path": {"type": "string"}, "lang": {"type": "string"}},
|
||||
"required": ["path"]}},
|
||||
{"name": "video_process", "fn": tool_video_process,
|
||||
"description": "视频批处理:转码/压缩/裁剪/旋转/翻转/调速/消音/加去水印/提取音频/截图/GIF 等。",
|
||||
"inputSchema": {"type": "object", "properties": {
|
||||
"path": {"type": "string"}, "op": {"type": "string", "enum": list(_VIDEO_OPS) + ["subtitle"]},
|
||||
"options": {"type": "object", "description": "按 op 传参:trim={start,end}; speed={speed}; rotate={angle}; flip={dir}; watermark={text}; unwatermark={x,y,w,h}; convert={format}; gif={fps,w,h}"}},
|
||||
"required": ["path", "op"]}},
|
||||
{"name": "gen_image", "fn": tool_gen_image,
|
||||
"description": "AI 文生图,返回图片下载 URL。",
|
||||
"inputSchema": {"type": "object", "properties": {"prompt": {"type": "string"},
|
||||
"model": {"type": "string", "default": "pollinations-flux"},
|
||||
"width": {"type": "integer", "default": 1024},
|
||||
"height": {"type": "integer", "default": 1024}},
|
||||
"required": ["prompt"]}},
|
||||
{"name": "convert_doc", "fn": tool_convert_doc,
|
||||
"description": "文档格式转换(pdf/docx/xlsx/pptx 互转等),返回结果下载 URL。",
|
||||
"inputSchema": {"type": "object", "properties": {"path": {"type": "string"},
|
||||
"format": {"type": "string"}}, "required": ["path", "format"]}},
|
||||
{"name": "remove_bg", "fn": tool_remove_bg,
|
||||
"description": "图片抠图去背景,输出透明底 PNG 下载 URL。",
|
||||
"inputSchema": {"type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"]}},
|
||||
{"name": "upscale_image", "fn": tool_upscale_image,
|
||||
"description": "图片超分辨率放大(2x/4x)并降噪。",
|
||||
"inputSchema": {"type": "object", "properties": {"path": {"type": "string"},
|
||||
"scale": {"type": "integer", "default": 2},
|
||||
"noise": {"type": "integer", "default": 1}},
|
||||
"required": ["path"]}},
|
||||
{"name": "copywriting", "fn": tool_copywriting,
|
||||
"description": "文案工具箱:改写/降AIGC率/爆款标题/小红书笔记/朋友圈文案。",
|
||||
"inputSchema": {"type": "object", "properties": {
|
||||
"text": {"type": "string"}, "scene": {"type": "string", "enum": list(_COPY_SCENES)},
|
||||
"model": {"type": "string", "default": "mimo-v2.6-flash"}}, "required": ["text", "scene"]}},
|
||||
{"name": "vision_qa", "fn": tool_vision_qa,
|
||||
"description": "看图问答:描述图片内容/提取图中信息/判断图片状态。",
|
||||
"inputSchema": {"type": "object", "properties": {"image_path": {"type": "string"},
|
||||
"question": {"type": "string"}},
|
||||
"required": ["image_path"]}},
|
||||
]
|
||||
TOOLS_MAP = {t["name"]: t for t in TOOLS}
|
||||
|
||||
|
||||
def tools_schema() -> list:
|
||||
return [{k: t[k] for k in ("name", "description", "inputSchema")} for t in TOOLS]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- JSON-RPC
|
||||
|
||||
def _public_base(handler) -> str:
|
||||
if _CTX.get("public_base"):
|
||||
return _CTX["public_base"].rstrip("/")
|
||||
host = handler.headers.get("Host", "") or "it.88531.cn"
|
||||
# 带端口的内网访问走 http,否则公网 https
|
||||
scheme = "http" if ":" in host else "https"
|
||||
return f"{scheme}://{host}"
|
||||
|
||||
|
||||
def _rpc_result(rid, result):
|
||||
return {"jsonrpc": "2.0", "id": rid, "result": result}
|
||||
|
||||
|
||||
def _rpc_error(rid, code, message):
|
||||
return {"jsonrpc": "2.0", "id": rid, "error": {"code": code, "message": message}}
|
||||
|
||||
|
||||
def _handle_rpc(req: dict, token_rec: dict | None, handler) -> dict | None:
|
||||
"""处理单个 JSON-RPC 请求;notification 返回 None。"""
|
||||
method = req.get("method")
|
||||
rid = req.get("id")
|
||||
params = req.get("params") or {}
|
||||
|
||||
if method in ("notifications/initialized", "notifications/cancelled", "notifications/roots/list_changed"):
|
||||
return None
|
||||
if rid is None and method and method.startswith("notifications/"):
|
||||
return None
|
||||
if method == "ping":
|
||||
return _rpc_result(rid, {})
|
||||
if method == "initialize":
|
||||
return _rpc_result(rid, {
|
||||
"protocolVersion": params.get("protocolVersion", "2025-06-18"),
|
||||
"capabilities": {"tools": {}},
|
||||
"serverInfo": {"name": "it-tools-pro", "version": "1.0.0",
|
||||
"title": "IT-TOOLS-PRO 授权应用 MCP"},
|
||||
"instructions": "本站 13 个授权工具的 MCP 入口。文件类入参传服务器可见的文件路径;"
|
||||
"结果中的 url 字段为可下载地址(需同款 Bearer 令牌)。",
|
||||
})
|
||||
if method == "tools/list":
|
||||
return _rpc_result(rid, {"tools": tools_schema()})
|
||||
if method == "tools/call":
|
||||
if not token_rec:
|
||||
return _rpc_error(rid, -32001, "未授权:请在请求头携带 Authorization: Bearer <MCP令牌>(站内「MCP 接入」页购买卡密后生成)")
|
||||
machine = token_rec.get("machine") or ""
|
||||
if not _authorized(machine):
|
||||
return _rpc_error(rid, -32001, "授权已失效:卡密过期或设备授权撤销,请重新激活")
|
||||
name = params.get("name")
|
||||
args = params.get("arguments") or {}
|
||||
tool = TOOLS_MAP.get(name)
|
||||
if not tool:
|
||||
return _rpc_error(rid, -32602, f"unknown tool: {name}")
|
||||
if name in ("ocr", "translate_doc", "tts", "speech_to_text", "extract_subtitle",
|
||||
"video_process", "convert_doc", "remove_bg", "upscale_image", "vision_qa"):
|
||||
# 文件类入参:允许直接传文件名(mcp_files 内已上传文件)或绝对路径
|
||||
for key in ("path", "image_path"):
|
||||
if key in args and args[key] and not os.path.isabs(str(args[key])):
|
||||
cand = os.path.join(_files_dir(), os.path.basename(str(args[key])))
|
||||
if os.path.isfile(cand):
|
||||
args[key] = cand
|
||||
t0 = time.time()
|
||||
ok, err = True, ""
|
||||
try:
|
||||
text = tool["fn"](machine, **args)
|
||||
except Exception as e: # noqa: BLE001
|
||||
text, ok, err = _err(e), False, str(e)
|
||||
dur = int((time.time() - t0) * 1000)
|
||||
log_mcp((token_rec.get("token") or "")[-6:], machine, name, ok, err, dur)
|
||||
_touch_token(token_rec.get("token") or "")
|
||||
# 下载 URL 补全域前缀
|
||||
try:
|
||||
obj = json.loads(text)
|
||||
base = _public_base(handler)
|
||||
|
||||
def _abs(o):
|
||||
if isinstance(o, dict):
|
||||
return {k: (base + v if k == "url" and isinstance(v, str) and v.startswith("/mcp/") else _abs(v))
|
||||
for k, v in o.items()}
|
||||
if isinstance(o, list):
|
||||
return [_abs(x) for x in o]
|
||||
return o
|
||||
text = json.dumps(_abs(obj), ensure_ascii=False)
|
||||
except Exception:
|
||||
pass
|
||||
return _rpc_result(rid, {"content": [{"type": "text", "text": text}], "isError": not ok})
|
||||
return _rpc_error(rid, -32601, f"method not found: {method}")
|
||||
|
||||
|
||||
def handle_post(handler) -> tuple[int, bytes, str]:
|
||||
"""POST /mcp —— 返回 (status, body, content_type)。"""
|
||||
try:
|
||||
length = int(handler.headers.get("Content-Length") or 0)
|
||||
except ValueError:
|
||||
length = 0
|
||||
raw = handler.rfile.read(length) if length else b"{}"
|
||||
try:
|
||||
payload = json.loads(raw.decode("utf-8") or "{}")
|
||||
except Exception:
|
||||
return 400, json.dumps({"jsonrpc": "2.0", "id": None,
|
||||
"error": {"code": -32700, "message": "parse error"}},
|
||||
ensure_ascii=False).encode(), "application/json"
|
||||
|
||||
tok = _bearer(handler)
|
||||
token_rec = _find_token(tok)
|
||||
# initialize/tools/list 免鉴权(发现能力),tools/call 必须有效令牌
|
||||
requests = payload if isinstance(payload, list) else [payload]
|
||||
needs_auth = any(isinstance(r, dict) and r.get("method") == "tools/call" for r in requests)
|
||||
if needs_auth and not token_rec:
|
||||
return 401, json.dumps({"error": "unauthorized",
|
||||
"message": "缺少或无效的 MCP 令牌(Authorization: Bearer mcpt_…)"},
|
||||
ensure_ascii=False).encode(), "application/json"
|
||||
|
||||
out = []
|
||||
for r in requests:
|
||||
if not isinstance(r, dict):
|
||||
continue
|
||||
resp = _handle_rpc(r, token_rec, handler)
|
||||
if resp is not None:
|
||||
out.append(resp)
|
||||
if not out:
|
||||
return 202, b"", "application/json"
|
||||
body = out[0] if len(out) == 1 else out
|
||||
return 200, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json"
|
||||
|
||||
|
||||
def handle_get_file(handler, fname: str):
|
||||
"""GET /mcp/file/<name> —— 令牌鉴权后提供结果文件下载。"""
|
||||
tok = _bearer(handler)
|
||||
if not _find_token(tok):
|
||||
handler.send_response(401)
|
||||
handler.send_header("Content-Type", "application/json")
|
||||
handler.end_headers()
|
||||
handler.wfile.write(b'{"error":"unauthorized"}')
|
||||
return
|
||||
safe = os.path.basename(fname)
|
||||
path = os.path.join(_files_dir(), safe)
|
||||
if not os.path.isfile(path):
|
||||
handler.send_response(404)
|
||||
handler.end_headers()
|
||||
handler.wfile.write(b'{"error":"not found"}')
|
||||
return
|
||||
with open(path, "rb") as f:
|
||||
data = f.read()
|
||||
handler.send_response(200)
|
||||
handler.send_header("Content-Type", "application/octet-stream")
|
||||
handler.send_header("Content-Length", str(len(data)))
|
||||
handler.send_header("Content-Disposition",
|
||||
f'attachment; filename="{safe}"; filename*=UTF-8\'\'{urllib.parse.quote(safe)}')
|
||||
handler.end_headers()
|
||||
handler.wfile.write(data)
|
||||
@@ -32,6 +32,10 @@ import zipfile
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from urllib import parse, request
|
||||
|
||||
import mcp_ops
|
||||
|
||||
GEN_IMG_LOCK = threading.Lock()
|
||||
|
||||
UPSTREAM = "https://translate.googleapis.com/translate_a/single"
|
||||
PROXY = os.environ.get("HTTPS_PROXY") or os.environ.get("https_proxy") or ""
|
||||
TIMEOUT = float(os.environ.get("RELAY_TIMEOUT", "25"))
|
||||
@@ -54,9 +58,17 @@ PROJECT_ALIASES = {
|
||||
} or {PROJECT_NAME}
|
||||
TRIAL_FILE = os.environ.get("TRIAL_FILE", "/app/data/trials.json")
|
||||
TRIAL_MS = int(os.environ.get("TRIAL_MS_MIN", "30")) * 60 * 1000
|
||||
# AI 生图页内置免费:未授权用户每日次数(北京时间 0 点重置);自带 KEY 不计次
|
||||
DAILY_FREE_LIMIT = int(os.environ.get("DAILY_FREE_LIMIT", "10"))
|
||||
DAILY_FILE = os.environ.get("DAILY_FILE", "/app/data/daily_gen.json")
|
||||
# Cloudflare Workers AI 免费池(flux/flux-*/dall-e-3 等内置模型的上游):
|
||||
# 官方免费 10,000 Neurons/天,proxy 固定 1024x1024/4 步 = 57.6 Neurons/张 → 10000/57.6 ≈ 173 张/天
|
||||
# (北京时间约 08:00 重置;账号级共享,超了 Free plan 直接报错)
|
||||
CF_DAILY_LIMIT = int(os.environ.get("CF_DAILY_LIMIT", "173"))
|
||||
CF_DAILY_FILE = os.environ.get("CF_DAILY_FILE", "/app/data/daily_gen_cf.json")
|
||||
DAY_MS = 24 * 60 * 60 * 1000
|
||||
TZ_OFFSET_MS = 8 * 60 * 60 * 1000 # 北京时间 UTC+8 —— 重置对齐自然日 0 点
|
||||
PROTECTED_TOOLS = {"translator", "image-ocr", "pdf-ocr", "ai-retouch", "doc-convert", "image-tools", "pdf-tools", "video-tools", "audio-tools", "text-to-image", "ai-image-tools", "copywriting", "screenshot-qa", "video-subtitle", "ai-gen", "ai-text-edit"}
|
||||
PROTECTED_TOOLS = {"translator", "image-ocr", "pdf-ocr", "ai-retouch", "doc-convert", "image-tools", "pdf-tools", "video-tools", "audio-tools", "text-to-image", "ai-image-tools", "copywriting", "screenshot-qa", "video-subtitle", "ai-gen", "ai-text-edit", "face-swap", "poster-maker"}
|
||||
MACHINE_RE = re.compile(r"^\d{10,16}$")
|
||||
|
||||
# verify() messages that unconditionally block activation
|
||||
@@ -187,6 +199,143 @@ def trial_allowed(machine: str, tool: str) -> bool:
|
||||
return (now_ms - start) < TRIAL_MS
|
||||
|
||||
|
||||
# ---------- AI 生图页:每日免费次数(未授权;北京时间 0 点重置,自带 KEY 不计次) ----------
|
||||
_DAILY_LOCK = threading.Lock()
|
||||
|
||||
|
||||
def _load_daily() -> dict:
|
||||
try:
|
||||
with open(DAILY_FILE, encoding="utf-8") as f:
|
||||
d = json.load(f)
|
||||
return d if isinstance(d, dict) else {}
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
def _save_daily(d: dict) -> None:
|
||||
try:
|
||||
with open(DAILY_FILE, "w", encoding="utf-8") as f:
|
||||
json.dump(d, f, ensure_ascii=False)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _day_key() -> int:
|
||||
return _today_start(int(time.time() * 1000))
|
||||
|
||||
|
||||
def daily_used(machine: str) -> int:
|
||||
"""该机器今日已用内置免费生图次数(跨天自动归零)。"""
|
||||
rec = _load_daily().get(machine)
|
||||
if isinstance(rec, dict) and rec.get("day") == _day_key():
|
||||
try:
|
||||
return int(rec.get("n", 0))
|
||||
except Exception:
|
||||
return 0
|
||||
return 0
|
||||
|
||||
|
||||
def daily_consume(machine: str, model: str = "") -> None:
|
||||
"""内置渠道生成成功后扣次:未授权机器计数照记;走 Cloudflare 的模型同时消耗全站共享池。"""
|
||||
with _DAILY_LOCK:
|
||||
d = _load_daily()
|
||||
rec = d.get(machine)
|
||||
if not (isinstance(rec, dict) and rec.get("day") == _day_key()):
|
||||
rec = {"day": _day_key(), "n": 0}
|
||||
try:
|
||||
rec["n"] = int(rec.get("n", 0)) + 1
|
||||
except Exception:
|
||||
rec["n"] = 1
|
||||
rec["day"] = _day_key()
|
||||
d[machine] = rec
|
||||
_save_daily(d)
|
||||
if _upstream_of(model) == "cloudflare":
|
||||
cf_consume()
|
||||
|
||||
|
||||
def daily_remaining(machine: str) -> int:
|
||||
return max(0, DAILY_FREE_LIMIT - daily_used(machine))
|
||||
|
||||
|
||||
# ---------- 全站共享上游:Cloudflare 免费池(flux/flux-*/dall-e-3,官方 173 张/天) ----------
|
||||
def _upstream_of(model: str) -> str:
|
||||
"""内置模型 → 上游通道:pollinations-* 走 Pollinations(key 预算制);其余 flux/dall-e* 走 Cloudflare。"""
|
||||
if (model or "").lower().startswith("pollinations"):
|
||||
return "pollinations"
|
||||
return "cloudflare"
|
||||
|
||||
|
||||
def _cf_load() -> dict:
|
||||
try:
|
||||
with open(CF_DAILY_FILE, encoding="utf-8") as f:
|
||||
d = json.load(f)
|
||||
return d if isinstance(d, dict) else {}
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
def cf_used_today() -> int:
|
||||
"""全站今日已消耗的 Cloudflare 免费池张数(北京时间 0 点归零;与官方 08:00 重置略有差异,取更早者保护)。"""
|
||||
d = _cf_load()
|
||||
if d.get("day") == _day_key():
|
||||
try:
|
||||
return int(d.get("n", 0))
|
||||
except Exception:
|
||||
return 0
|
||||
return 0
|
||||
|
||||
|
||||
def cf_consume() -> None:
|
||||
with _DAILY_LOCK:
|
||||
d = _cf_load()
|
||||
if d.get("day") != _day_key():
|
||||
d = {"day": _day_key(), "n": 0}
|
||||
try:
|
||||
d["n"] = int(d.get("n", 0)) + 1
|
||||
except Exception:
|
||||
d["n"] = 1
|
||||
try:
|
||||
with open(CF_DAILY_FILE, "w", encoding="utf-8") as f:
|
||||
json.dump(d, f, ensure_ascii=False)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def cf_remaining() -> int:
|
||||
return max(0, CF_DAILY_LIMIT - cf_used_today())
|
||||
|
||||
|
||||
def gen_block_reason(machine: str, own_provider: bool = False, model: str = "") -> str | None:
|
||||
"""AI 生图门禁:返回 None=放行;否则返回拒绝原因码。
|
||||
- own_provider=True(自带提供商/KEY):不耗平台额度,直接放行
|
||||
- 未授权:每机每日 DAILY_FREE_LIMIT 次
|
||||
- 内置走 Cloudflare 的模型:全站共享池 CF_DAILY_LIMIT 张/天(**已授权也保护**,上游是账号级免费池)
|
||||
"""
|
||||
if not machine or not MACHINE_RE.match(machine):
|
||||
return "bad_machine"
|
||||
if own_provider:
|
||||
return None
|
||||
authed = machine not in _load_revoked() and (query_authorized(machine) or _account_license_ok(machine))
|
||||
if not authed and daily_remaining(machine) <= 0:
|
||||
return "machine_quota"
|
||||
if _upstream_of(model) == "cloudflare" and cf_remaining() <= 0:
|
||||
return "cf_pool"
|
||||
return None
|
||||
|
||||
|
||||
def check_gen(machine: str, own_provider: bool = False, model: str = "") -> int:
|
||||
return 200 if gen_block_reason(machine, own_provider, model) is None else 403
|
||||
|
||||
|
||||
def gen_block_message(reason: str | None) -> str:
|
||||
if reason == "machine_quota":
|
||||
return f"需要授权,或今日内置免费生图次数({DAILY_FREE_LIMIT} 次/天)已用完——可配置自己的 API KEY 继续生成"
|
||||
if reason == "cf_pool":
|
||||
return (f"今日免费生图池已用完:Cloudflare 官方免费 10,000 Neurons/天 ≈ {CF_DAILY_LIMIT} 张"
|
||||
f"(北京时间约 08:00 重置,全站共享)——可配置自己的 API KEY 继续生成")
|
||||
return "需要授权或今日免费试用已用完"
|
||||
|
||||
|
||||
def deactivate_card(machine_id: str) -> tuple[int, dict]:
|
||||
"""Revoke authorization for this machine.
|
||||
|
||||
@@ -562,6 +711,51 @@ def check(machine: str, tool: str) -> int:
|
||||
return 200 if trial_allowed(machine, tool) else 403
|
||||
|
||||
|
||||
# ---- AI 换脸引擎:insightface buffalo_l 人脸检测 + inswapper_128 换脸(本机 CPU 推理) ----
|
||||
_FACE_LOCK = threading.Lock()
|
||||
_FACE_APP = None
|
||||
_FACE_SWAP = None
|
||||
_FACE_MODELS_DIR = os.environ.get("FACE_MODELS_DIR", "/app/face-models")
|
||||
|
||||
|
||||
def _face_engine():
|
||||
"""懒加载换脸引擎(线程安全;首次调用约 1~2s,之后常驻内存复用)。"""
|
||||
global _FACE_APP, _FACE_SWAP
|
||||
if _FACE_APP is None:
|
||||
from insightface.app import FaceAnalysis
|
||||
from insightface import model_zoo
|
||||
app = FaceAnalysis(name="buffalo_l", root=_FACE_MODELS_DIR, providers=["CPUExecutionProvider"])
|
||||
app.prepare(ctx_id=0, det_size=(640, 640))
|
||||
swap = model_zoo.get_model(os.path.join(_FACE_MODELS_DIR, "inswapper_128.onnx"),
|
||||
providers=["CPUExecutionProvider"])
|
||||
_FACE_APP, _FACE_SWAP = app, swap
|
||||
return _FACE_APP, _FACE_SWAP
|
||||
|
||||
|
||||
def _largest_face(faces):
|
||||
"""多张脸时取面积最大的一张(换脸默认作用于最显眼的人脸)。"""
|
||||
return max(faces, key=lambda f: float((f.bbox[2] - f.bbox[0]) * (f.bbox[3] - f.bbox[1])))
|
||||
|
||||
|
||||
def _face_swap_run(src_img, dst_img):
|
||||
"""源人脸 -> 目标照片。返回 (jpg字节|None, 错误信息, 耗时ms)。加锁串行避免并发吃满 CPU。"""
|
||||
import cv2 as _cv2
|
||||
t0 = time.time()
|
||||
with _FACE_LOCK:
|
||||
app, swap = _face_engine()
|
||||
src_faces = app.get(src_img)
|
||||
dst_faces = app.get(dst_img)
|
||||
if not src_faces:
|
||||
return None, "源图中未检测到人脸,请换一张清晰的正脸照片", 0
|
||||
if not dst_faces:
|
||||
return None, "目标图中未检测到人脸,请换一张含人物的照片", 0
|
||||
out = swap.get(dst_img, _largest_face(dst_faces), _largest_face(src_faces), paste_back=True)
|
||||
ok, buf = _cv2.imencode(".jpg", out, [int(_cv2.IMWRITE_JPEG_QUALITY), 92])
|
||||
if not ok:
|
||||
return None, "结果编码失败", 0
|
||||
return buf.tobytes(), None, int((time.time() - t0) * 1000)
|
||||
|
||||
|
||||
def _account_license_ok(machine: str) -> bool:
|
||||
"""True when this device logged into an authorized account.
|
||||
|
||||
@@ -754,6 +948,7 @@ def _db():
|
||||
"ALTER TABLE users ADD COLUMN bound_machines TEXT DEFAULT '[]'",
|
||||
"ALTER TABLE users ADD COLUMN role TEXT DEFAULT 'user'",
|
||||
"ALTER TABLE users ADD COLUMN disabled INTEGER DEFAULT 0",
|
||||
"ALTER TABLE users ADD COLUMN last_login REAL DEFAULT 0",
|
||||
):
|
||||
try:
|
||||
conn.execute(stmt)
|
||||
@@ -907,6 +1102,80 @@ def log_usage(machine: str, tool: str):
|
||||
pass
|
||||
|
||||
|
||||
# ---- 前端工具使用上报(未登录访客也统计):10 分钟同机同工具去重 + 每 IP 限流防刷 ----
|
||||
_USE_SEEN: dict = {} # "<machine|ip>|<tool>" -> last report ts
|
||||
_USE_IP: dict = {} # ip -> [recent ts...]
|
||||
_USE_LOCK = threading.Lock()
|
||||
|
||||
|
||||
def usage_track(payload: dict, handler) -> tuple:
|
||||
"""POST /usage:任意访客(含未登录)上报工具使用,落 usage.db。
|
||||
10 分钟内同一机器+同一工具只计一次(防刷新刷量);每 IP 10 分钟上限 300 条。"""
|
||||
tool = str(payload.get("tool") or "").strip()
|
||||
if not tool or len(tool) > 64 or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9\-_.]*", tool):
|
||||
return 400, {"code": 400, "message": "无效 tool"}
|
||||
machine = str(payload.get("machine_id") or "").strip()
|
||||
if machine and not MACHINE_RE.match(machine):
|
||||
machine = ""
|
||||
try:
|
||||
ip = (handler.headers.get("X-Real-IP") or "").strip() or handler.client_address[0]
|
||||
except Exception:
|
||||
ip = ""
|
||||
now = time.time()
|
||||
key = f"{machine or ip}|{tool}"
|
||||
with _USE_LOCK:
|
||||
if len(_USE_SEEN) > 20000: # 修剪过期键,防内存膨胀
|
||||
for k in [k for k, t in _USE_SEEN.items() if now - t >= 600]:
|
||||
_USE_SEEN.pop(k, None)
|
||||
last = _USE_SEEN.get(key)
|
||||
if last is not None and now - last < 600:
|
||||
return 200, {"code": 200, "message": "ok", "data": {"dup": 1}}
|
||||
recent = [t for t in _USE_IP.get(ip, []) if now - t < 600]
|
||||
if len(recent) >= 300:
|
||||
_USE_IP[ip] = recent
|
||||
return 200, {"code": 200, "message": "ok", "data": {"capped": 1}}
|
||||
recent.append(now)
|
||||
_USE_IP[ip] = recent
|
||||
_USE_SEEN[key] = now
|
||||
log_usage(machine, tool)
|
||||
return 200, {"code": 200, "message": "ok", "data": {"ok": 1}}
|
||||
|
||||
|
||||
# ---- 在线统计:仅未登录访客,前端停留满 1 分钟才开始心跳 ----
|
||||
ONLINE_WINDOW = 90.0 # 心跳每 30s 一次(后台标签被节流为 60s),超 90s 无心跳判离线
|
||||
_ONLINE: dict = {} # machine_id -> 最近心跳时间戳(进程内存)
|
||||
_ONLINE_LOCK = threading.Lock()
|
||||
|
||||
|
||||
def online_beat(payload: dict) -> tuple:
|
||||
"""POST /online:访客在线心跳。
|
||||
|
||||
- guest=true(未登录)→ 记为在线;guest=false(已登录)→ 移出统计。
|
||||
- 「停留超过 1 分钟才算在线」由前端控制:打开满 60s 才发首次心跳。
|
||||
"""
|
||||
machine = str(payload.get("machine_id") or "").strip()
|
||||
if not machine or not MACHINE_RE.match(machine):
|
||||
return 400, {"code": 400, "message": "无效 machine_id"}
|
||||
guest = bool(payload.get("guest"))
|
||||
now = time.time()
|
||||
with _ONLINE_LOCK:
|
||||
if guest:
|
||||
_ONLINE[machine] = now
|
||||
else:
|
||||
_ONLINE.pop(machine, None) # 登录用户不统计
|
||||
if len(_ONLINE) > 5000: # 防内存膨胀:修剪过期
|
||||
for k in [k for k, t in _ONLINE.items() if now - t > ONLINE_WINDOW]:
|
||||
_ONLINE.pop(k, None)
|
||||
count = sum(1 for t in _ONLINE.values() if now - t <= ONLINE_WINDOW)
|
||||
return 200, {"code": 200, "message": "ok", "data": {"online": count}}
|
||||
|
||||
|
||||
def online_count() -> int:
|
||||
now = time.time()
|
||||
with _ONLINE_LOCK:
|
||||
return sum(1 for t in _ONLINE.values() if now - t <= ONLINE_WINDOW)
|
||||
|
||||
|
||||
def _dir_size(path: str) -> int:
|
||||
total = 0
|
||||
for root, _dirs, files in os.walk(path):
|
||||
@@ -960,12 +1229,12 @@ def admin_api(method: str, sub: str, payload: dict, handler):
|
||||
|
||||
if method == "GET" and sub == "/overview":
|
||||
conn = _db()
|
||||
users = conn.execute("SELECT username, created, card_key, bound_machines, role, disabled FROM users").fetchall()
|
||||
users = conn.execute("SELECT username, created, card_key, bound_machines, role, disabled, last_login FROM users").fetchall()
|
||||
conn.close()
|
||||
out_users = []
|
||||
total_files = 0
|
||||
total_size = 0
|
||||
for username, created, card_key, bm, role, disabled in users:
|
||||
for username, created, card_key, bm, role, disabled, last_login in users:
|
||||
udir = os.path.join(USERS_ROOT, username)
|
||||
fdir = os.path.join(udir, "files")
|
||||
fcount = 0
|
||||
@@ -993,6 +1262,7 @@ def admin_api(method: str, sub: str, payload: dict, handler):
|
||||
out_users.append({
|
||||
"username": username,
|
||||
"created": int(created or 0),
|
||||
"last_login": int(last_login or 0),
|
||||
"files": fcount,
|
||||
"file_size": fsize,
|
||||
"data_size": dsize,
|
||||
@@ -1301,14 +1571,23 @@ def admin_api(method: str, sub: str, payload: dict, handler):
|
||||
by_tool = conn.execute("SELECT tool, COUNT(*) c FROM usage WHERE at>? GROUP BY tool ORDER BY c DESC LIMIT 30", (since,)).fetchall()
|
||||
by_user = conn.execute("SELECT username, COUNT(*) c, MAX(at) last FROM usage WHERE at>? AND username!='' GROUP BY username ORDER BY c DESC LIMIT 50", (since,)).fetchall()
|
||||
total = conn.execute("SELECT COUNT(*) FROM usage WHERE at>?", (since,)).fetchone()[0]
|
||||
# 未登录访客(username 为空)聚合:访客的功能使用也统计并展示
|
||||
g = conn.execute("SELECT COUNT(*) c, MAX(at) last FROM usage WHERE at>? AND username=''", (since,)).fetchone()
|
||||
conn.close()
|
||||
return 200, {"code": 200, "message": "ok", "data": {
|
||||
"days": days,
|
||||
"total": total,
|
||||
"by_tool": [{"tool": t, "count": c} for t, c in by_tool],
|
||||
"by_user": [{"username": u, "count": c, "last": int(l or 0)} for u, c, l in by_user],
|
||||
"guest": {"count": int(g[0] or 0), "last": int(g[1] or 0)},
|
||||
"online": online_count(),
|
||||
}}
|
||||
|
||||
if method == "GET" and sub == "/mcp-usage":
|
||||
qs = parse.parse_qs(parse.urlparse(handler.path).query)
|
||||
days = _int_str((qs.get("days") or ["7"])[0], 1, 365, 7)
|
||||
return 200, {"code": 200, "message": "ok", "data": mcp_ops.mcp_usage_query(days)}
|
||||
|
||||
return 404, {"code": 404, "message": "unknown admin api"}
|
||||
|
||||
|
||||
@@ -1601,7 +1880,7 @@ def user_api(method, sub, payload, handler):
|
||||
conn = _db()
|
||||
try:
|
||||
salt = secrets.token_hex(16)
|
||||
conn.execute("INSERT INTO users VALUES (?,?,?,?)", (username, salt, _hash_pw(password, salt), time.time()))
|
||||
conn.execute("INSERT INTO users (username, salt, pw_hash, created, last_login) VALUES (?,?,?,?,?)", (username, salt, _hash_pw(password, salt), time.time(), time.time()))
|
||||
conn.commit()
|
||||
except sqlite3.IntegrityError:
|
||||
return 409, {"code": 409, "message": "用户名已被注册"}
|
||||
@@ -1625,6 +1904,13 @@ def user_api(method, sub, payload, handler):
|
||||
return 401, {"code": 401, "message": "用户名或密码错误"}
|
||||
_user_dir(username)
|
||||
_bind_machine(username, _req_machine(handler))
|
||||
try:
|
||||
_conn2 = _db()
|
||||
_conn2.execute("UPDATE users SET last_login=? WHERE username=?", (time.time(), username))
|
||||
_conn2.commit()
|
||||
_conn2.close()
|
||||
except Exception:
|
||||
pass
|
||||
role, disabled = _user_attr(username)
|
||||
if disabled:
|
||||
return 403, {"code": 403, "message": "账号已被禁用,请联系管理员"}
|
||||
@@ -1862,9 +2148,32 @@ class Handler(BaseHTTPRequestHandler):
|
||||
if parsed.path == "/ai/image-models":
|
||||
self._handle_image_models()
|
||||
return
|
||||
if parsed.path == "/ai/img-history":
|
||||
self._handle_img_history()
|
||||
return
|
||||
if parsed.path.startswith("/ai/img/"):
|
||||
self._handle_img_file(parsed)
|
||||
return
|
||||
if parsed.path == "/ai/models":
|
||||
self._handle_ai_models()
|
||||
return
|
||||
if parsed.path == "/mcp":
|
||||
info = {"code": 200,
|
||||
"message": "IT-TOOLS-PRO MCP endpoint (Streamable HTTP / JSON-RPC 2.0)",
|
||||
"protocol": "mcp",
|
||||
"endpoint": "/mcp",
|
||||
"auth": "Authorization: Bearer <MCP令牌>(站内「MCP 接入」页购买卡密后生成)",
|
||||
"tools": [t["name"] for t in mcp_ops.TOOLS]}
|
||||
self._reply(200, json.dumps(info, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
if parsed.path == "/mcp/tokens":
|
||||
qs = parse.parse_qs(parsed.query)
|
||||
status, body = mcp_ops.tokens_api("GET", {}, qs)
|
||||
self._reply(status, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
if parsed.path.startswith("/mcp/file/"):
|
||||
mcp_ops.handle_get_file(self, parsed.path[len("/mcp/file/"):])
|
||||
return
|
||||
if parsed.path.startswith("/admin"):
|
||||
self._handle_admin("GET")
|
||||
return
|
||||
@@ -2793,6 +3102,25 @@ class Handler(BaseHTTPRequestHandler):
|
||||
status, body = hub_report(payload)
|
||||
self._reply(status, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
if parsed.path == "/usage":
|
||||
payload = self._read_payload() or {}
|
||||
status, body = usage_track(payload, self)
|
||||
self._reply(status, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
if parsed.path == "/online":
|
||||
payload = self._read_payload() or {}
|
||||
status, body = online_beat(payload)
|
||||
self._reply(status, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
if parsed.path == "/mcp":
|
||||
status, body, ctype = mcp_ops.handle_post(self)
|
||||
self._reply(status, body, ctype)
|
||||
return
|
||||
if parsed.path == "/mcp/tokens":
|
||||
payload = self._read_payload() or {}
|
||||
status, body = mcp_ops.tokens_api("POST", payload, {})
|
||||
self._reply(status, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
if parsed.path.startswith("/admin"):
|
||||
self._handle_admin("POST")
|
||||
return
|
||||
@@ -2829,12 +3157,21 @@ class Handler(BaseHTTPRequestHandler):
|
||||
if parsed.path == "/ai/models":
|
||||
self._handle_ai_models()
|
||||
return
|
||||
if parsed.path == "/ai/quota":
|
||||
self._handle_ai_quota()
|
||||
return
|
||||
if parsed.path == "/ai/custom-models":
|
||||
self._handle_custom_models()
|
||||
return
|
||||
if parsed.path == "/ai/gen-image":
|
||||
self._handle_gen_image()
|
||||
return
|
||||
if parsed.path == "/ai/edit-image":
|
||||
self._handle_edit_image()
|
||||
return
|
||||
if parsed.path == "/ai/face-swap":
|
||||
self._handle_face_swap()
|
||||
return
|
||||
if parsed.path == "/ai/seamless-edit":
|
||||
self._handle_seamless_edit()
|
||||
return
|
||||
@@ -2915,6 +3252,51 @@ class Handler(BaseHTTPRequestHandler):
|
||||
|
||||
self._reply(404, b"not found")
|
||||
|
||||
# ---------- 中文提示词自动转英文(Flux/SDXL 系对英文理解最好) ----------
|
||||
_ZH_RE = re.compile(r"[\u4e00-\u9fff]")
|
||||
_trans_cache: dict = {}
|
||||
|
||||
def _translate_prompt(self, prompt: str):
|
||||
"""含中文才翻;成功 (英文, True);失败/未配置回退 (原文, False),绝不阻断生图。"""
|
||||
if not prompt or not self._ZH_RE.search(prompt):
|
||||
return prompt, False
|
||||
cached = self._trans_cache.get(prompt)
|
||||
if cached:
|
||||
return cached, True
|
||||
key = os.environ.get("NEWAPI_KEY", "")
|
||||
if not key:
|
||||
return prompt, False
|
||||
try:
|
||||
body = json.dumps({
|
||||
"model": os.environ.get("IMG_PROMPT_MODEL", "mimo-v2.6-flash"),
|
||||
"messages": [
|
||||
{"role": "system", "content": (
|
||||
"You are an expert prompt engineer for text-to-image models (Flux / SDXL / DALL-E). "
|
||||
"Translate the user's Chinese image prompt into ONE high-quality English image-generation prompt. "
|
||||
"Preserve every style, composition, aspect-ratio, lighting and detail keyword; you may expand "
|
||||
"slightly for natural flow. Output ONLY the English prompt itself - no quotes, no explanations, "
|
||||
"no Chinese characters, no markdown.")},
|
||||
{"role": "user", "content": prompt},
|
||||
],
|
||||
"temperature": 0.3, "max_tokens": 500,
|
||||
}).encode()
|
||||
req = request.Request(
|
||||
os.environ.get("NEWAPI_URL", "http://192.168.68.19:3099/v1/chat/completions"),
|
||||
data=body, headers={"Content-Type": "application/json", "Authorization": "Bearer " + key})
|
||||
data = json.loads(request.urlopen(req, timeout=30).read())
|
||||
en = str(data.get("choices", [{}])[0].get("message", {}).get("content") or "").strip()
|
||||
en = en.strip("`\"'\u201c\u201d ").strip()
|
||||
if not en or self._ZH_RE.search(en[:120]):
|
||||
return prompt, False
|
||||
if len(self._trans_cache) >= 300:
|
||||
self._trans_cache.clear()
|
||||
self._trans_cache[prompt] = en
|
||||
print(f"[img] prompt translated: {prompt[:40]} -> {en[:70]}", flush=True)
|
||||
return en, True
|
||||
except Exception as e: # noqa: BLE001
|
||||
print(f"[img] translate failed, use original: {e}", flush=True)
|
||||
return prompt, False
|
||||
|
||||
# ---------- AI 生图 (NEWAPI) ----------
|
||||
def _nm_base(self):
|
||||
return os.environ.get("NEWAPI_URL", "http://192.168.68.19:3099/v1/chat/completions").replace("/chat/completions", "")
|
||||
@@ -2967,7 +3349,7 @@ class Handler(BaseHTTPRequestHandler):
|
||||
b64 = item.get("b64_json") or ""
|
||||
if not url and not b64:
|
||||
raise RuntimeError("上游未返回图片")
|
||||
self._reply(200, json.dumps({"code": 200, "message": "ok", "data": {"url": url, "b64": b64}}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
self._reply(200, json.dumps({"code": 200, "message": "ok", "data": {"url": url, "b64": b64, "img_url": (d.get("img_url") or "") if isinstance(d, dict) else "", "prompt_en": (d.get("prompt_en") or "") if isinstance(d, dict) else ""}}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
|
||||
def _handle_image_models(self):
|
||||
try:
|
||||
@@ -2977,17 +3359,267 @@ class Handler(BaseHTTPRequestHandler):
|
||||
models = []
|
||||
self._reply(200, json.dumps({"code": 200, "message": "ok", "data": models}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
|
||||
# ---------- AI 生图:自定义提供商 + 历史落盘 ----------
|
||||
@staticmethod
|
||||
def _gen_machine_ok(machine):
|
||||
return bool(re.fullmatch(r"[A-Za-z0-9_-]{4,64}", machine or ""))
|
||||
|
||||
def _provider_images_gen(self, provider, model, prompt, size):
|
||||
"""用用户自己的 base_url + API KEY 走 OpenAI 兼容 images 接口(KEY 仅请求透传,不落盘)。"""
|
||||
base = str(provider.get("base_url") or "").strip().rstrip("/")
|
||||
if not base.startswith(("http://", "https://")):
|
||||
raise RuntimeError("接口地址必须以 http(s):// 开头")
|
||||
if base.endswith("/v1"):
|
||||
url = base + "/images/generations"
|
||||
elif base.endswith("/images/generations"):
|
||||
url = base
|
||||
else:
|
||||
url = base + "/v1/images/generations"
|
||||
body = json.dumps({"model": model, "prompt": prompt, "n": 1, "size": size}).encode("utf-8")
|
||||
key = str(provider.get("api_key") or "").strip()
|
||||
req = request.Request(url, data=body, headers={
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": "Bearer " + key,
|
||||
"User-Agent": "Mozilla/5.0",
|
||||
})
|
||||
with request.urlopen(req, timeout=120) as resp:
|
||||
d = json.loads(resp.read().decode("utf-8", "replace"))
|
||||
if isinstance(d, dict) and d.get("data"):
|
||||
return d
|
||||
msg = ""
|
||||
if isinstance(d, dict):
|
||||
err = d.get("error")
|
||||
if isinstance(err, dict):
|
||||
msg = str(err.get("message") or "")
|
||||
else:
|
||||
msg = str(err or d.get("message") or "")
|
||||
raise RuntimeError(msg[:300] or "上游未返回图片")
|
||||
|
||||
def _persist_gen_image(self, machine, d, model, prompt, w, h, kind="gen"):
|
||||
"""把生成结果落盘并写入该机器的历史索引;返回站内图片 URL(任何失败返回空串)。"""
|
||||
try:
|
||||
if not self._gen_machine_ok(machine):
|
||||
return ""
|
||||
items = (d or {}).get("data") or []
|
||||
if not items:
|
||||
return ""
|
||||
item = items[0] if isinstance(items[0], dict) else {}
|
||||
raw = None
|
||||
if item.get("b64_json"):
|
||||
import base64 as _b64
|
||||
raw = _b64.b64decode(item["b64_json"])
|
||||
elif item.get("url"):
|
||||
ureq = request.Request(item["url"], headers={"User-Agent": "Mozilla/5.0"})
|
||||
with request.urlopen(ureq, timeout=60) as rr:
|
||||
raw = rr.read()
|
||||
if not raw or len(raw) < 200:
|
||||
return ""
|
||||
if not (w and h):
|
||||
try:
|
||||
from PIL import Image as _PIL
|
||||
import io as _io
|
||||
_im = _PIL.open(_io.BytesIO(raw))
|
||||
w, h = _im.size
|
||||
except Exception:
|
||||
w, h = 0, 0
|
||||
if raw[:8] == b"\x89PNG\r\n\x1a\n":
|
||||
ext = ".png"
|
||||
elif raw[:2] == b"\xff\xd8":
|
||||
ext = ".jpg"
|
||||
elif raw[:6] in (b"GIF87a", b"GIF89a"):
|
||||
ext = ".gif"
|
||||
elif len(raw) > 12 and raw[8:12] == b"WEBP":
|
||||
ext = ".webp"
|
||||
else:
|
||||
ext = ".png"
|
||||
gen_dir = os.path.join(DATA_DIR, "gen_images", machine)
|
||||
os.makedirs(gen_dir, exist_ok=True)
|
||||
iid = f"{int(time.time())}_{uuid.uuid4().hex[:8]}"
|
||||
fname = iid + ext
|
||||
with open(os.path.join(gen_dir, fname), "wb") as f:
|
||||
f.write(raw)
|
||||
idx_path = os.path.join(gen_dir, "index.json")
|
||||
with GEN_IMG_LOCK:
|
||||
idx = []
|
||||
if os.path.exists(idx_path):
|
||||
try:
|
||||
idx = json.load(open(idx_path, encoding="utf-8"))
|
||||
if not isinstance(idx, list):
|
||||
idx = []
|
||||
except Exception:
|
||||
idx = []
|
||||
idx.insert(0, {"id": iid, "file": fname, "at": int(time.time()),
|
||||
"model": str(model)[:60], "prompt": str(prompt)[:500],
|
||||
"kind": str(kind or "gen")[:20],
|
||||
"w": w, "h": h})
|
||||
while len(idx) > 100:
|
||||
old = idx.pop() or {}
|
||||
fn = str(old.get("file") or "")
|
||||
if fn and "/" not in fn and "\\" not in fn:
|
||||
try:
|
||||
os.remove(os.path.join(gen_dir, fn))
|
||||
except Exception:
|
||||
pass
|
||||
with open(idx_path, "w", encoding="utf-8") as f:
|
||||
json.dump(idx, f, ensure_ascii=False)
|
||||
return f"/relay/ai/img/{machine}/{iid}"
|
||||
except Exception as e: # noqa: BLE001
|
||||
print(f"[ai-gen] persist failed: {e}", flush=True)
|
||||
return ""
|
||||
|
||||
def _handle_ai_quota(self):
|
||||
"""AI 生图页额度查询:授权状态 + 机器今日剩余 + 当前模型上游的真实免费配额。"""
|
||||
payload = self._read_payload()
|
||||
machine = str(payload.get("machine") or "")
|
||||
model = str(payload.get("model") or "")[:60]
|
||||
if not machine or not MACHINE_RE.match(machine):
|
||||
self._reply(400, json.dumps({"code": 400, "message": "bad machine"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
authed = machine not in _load_revoked() and (query_authorized(machine) or _account_license_ok(machine))
|
||||
used = daily_used(machine)
|
||||
data = {
|
||||
"authorized": authed,
|
||||
"limit": DAILY_FREE_LIMIT,
|
||||
"used": used if not authed else 0,
|
||||
"remaining": -1 if authed else max(0, DAILY_FREE_LIMIT - used),
|
||||
"cf_daily": CF_DAILY_LIMIT, # CF 免费池官方换算张数(前端模型下拉后缀用)
|
||||
}
|
||||
# 上游真实免费配额(按当前所选模型的通道返回,前端「模型」区如实展示)
|
||||
up = _upstream_of(model) if model else ""
|
||||
data["upstream"] = up
|
||||
if up == "cloudflare":
|
||||
data["upstream_daily"] = CF_DAILY_LIMIT
|
||||
data["upstream_used"] = cf_used_today()
|
||||
data["upstream_remaining"] = cf_remaining()
|
||||
data["upstream_note"] = (f"Cloudflare Workers AI 官方免费 10,000 Neurons/天"
|
||||
f"≈ {CF_DAILY_LIMIT} 张(1024×1024/4 步),北京时间约 08:00 重置,账号级共享")
|
||||
elif up == "pollinations":
|
||||
data["upstream_daily"] = None
|
||||
data["upstream_used"] = None
|
||||
data["upstream_remaining"] = None
|
||||
data["upstream_note"] = "Pollinations 按 API Key 预算(pollen 余额)计费,无固定每日张数"
|
||||
self._reply(200, json.dumps({"code": 200, "message": "ok", "data": data}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
|
||||
def _handle_custom_models(self):
|
||||
"""测试用户的 OpenAI 兼容提供商并拉取模型列表(KEY 只进本次请求头,不落盘)。"""
|
||||
payload = self._read_payload()
|
||||
machine = str(payload.get("machine") or "")
|
||||
if check_gen(machine, True) != 200:
|
||||
self._reply(403, json.dumps({"code": 403, "message": "需要授权或今日免费试用已用完"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
base = str(payload.get("base_url") or "").strip().rstrip("/")
|
||||
key = str(payload.get("api_key") or "").strip()
|
||||
if not base.startswith(("http://", "https://")):
|
||||
self._reply(400, json.dumps({"code": 400, "message": "接口地址必须以 http(s):// 开头"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
if not key:
|
||||
self._reply(400, json.dumps({"code": 400, "message": "请填写 API KEY"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
if base.endswith("/v1"):
|
||||
url = base + "/models"
|
||||
elif base.endswith("/models"):
|
||||
url = base
|
||||
else:
|
||||
url = base + "/v1/models"
|
||||
req = request.Request(url, headers={"Authorization": "Bearer " + key, "User-Agent": "Mozilla/5.0"})
|
||||
try:
|
||||
with request.urlopen(req, timeout=20) as resp:
|
||||
d = json.loads(resp.read().decode("utf-8", "replace"))
|
||||
except Exception as e: # noqa: BLE001
|
||||
msg = str(e)
|
||||
if isinstance(e, request.HTTPError):
|
||||
try:
|
||||
msg = e.read().decode("utf-8", "replace")[:300]
|
||||
except Exception:
|
||||
pass
|
||||
self._reply(502, json.dumps({"code": 502, "message": f"连接失败:{msg}"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
items = d.get("data") if isinstance(d, dict) else None
|
||||
ids = [str(m.get("id")) for m in (items or []) if isinstance(m, dict) and m.get("id")]
|
||||
if not ids:
|
||||
self._reply(502, json.dumps({"code": 502, "message": "上游未返回模型列表(请确认接口地址为 OpenAI 兼容格式)"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
self._reply(200, json.dumps({"code": 200, "message": "ok", "data": ids[:200]}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
|
||||
def _handle_img_history(self):
|
||||
parsed = parse.urlparse(self.path)
|
||||
qs = parse.parse_qs(parsed.query)
|
||||
machine = str((qs.get("machine") or [""])[0] or "")
|
||||
if not self._gen_machine_ok(machine):
|
||||
self._reply(400, json.dumps({"code": 400, "message": "bad machine"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
idx_path = os.path.join(DATA_DIR, "gen_images", machine, "index.json")
|
||||
items = []
|
||||
if os.path.exists(idx_path):
|
||||
try:
|
||||
items = json.load(open(idx_path, encoding="utf-8"))
|
||||
if not isinstance(items, list):
|
||||
items = []
|
||||
except Exception:
|
||||
items = []
|
||||
for it in items:
|
||||
if isinstance(it, dict):
|
||||
it["img_url"] = f"/relay/ai/img/{machine}/{it.get('id', '')}"
|
||||
self._reply(200, json.dumps({"code": 200, "message": "ok", "data": items}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
|
||||
def _handle_img_file(self, parsed):
|
||||
# 兼容两条链路:直连 relay(/relay/ai/img/m/id)与经 nginx(/ai/img/m/id)
|
||||
parts = parsed.path.split("/")
|
||||
if len(parts) < 5 or parts[-3] != "img":
|
||||
self._reply(404, b"not found")
|
||||
return
|
||||
machine, iid = parts[-2], parts[-1]
|
||||
if not self._gen_machine_ok(machine) or not re.fullmatch(r"[A-Za-z0-9_\-]{4,64}", iid or ""):
|
||||
self._reply(404, b"not found")
|
||||
return
|
||||
gen_dir = os.path.join(DATA_DIR, "gen_images", machine)
|
||||
found = None
|
||||
if os.path.isdir(gen_dir):
|
||||
for fn in os.listdir(gen_dir):
|
||||
if fn.startswith(iid + ".") and os.path.isfile(os.path.join(gen_dir, fn)):
|
||||
found = os.path.join(gen_dir, fn)
|
||||
break
|
||||
if not found:
|
||||
self._reply(404, b"not found")
|
||||
return
|
||||
ext = os.path.splitext(found)[1].lower()
|
||||
ctype = {".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg",
|
||||
".gif": "image/gif", ".webp": "image/webp"}.get(ext, "image/png")
|
||||
try:
|
||||
with open(found, "rb") as f:
|
||||
raw = f.read()
|
||||
except Exception:
|
||||
self._reply(404, b"not found")
|
||||
return
|
||||
qs = parse.parse_qs(parsed.query)
|
||||
dl = str((qs.get("dl") or [""])[0] or "")
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", ctype)
|
||||
self.send_header("Content-Length", str(len(raw)))
|
||||
self.send_header("Cache-Control", "private, max-age=86400")
|
||||
if dl == "1":
|
||||
self.send_header("Content-Disposition", f'attachment; filename="{iid}{ext}"')
|
||||
self.end_headers()
|
||||
try:
|
||||
self.wfile.write(raw)
|
||||
except (BrokenPipeError, ConnectionResetError):
|
||||
pass
|
||||
|
||||
def _handle_gen_image(self):
|
||||
payload = self._read_payload()
|
||||
machine = str(payload.get("machine") or "")
|
||||
if check(machine, "ai-gen") != 200:
|
||||
self._reply(403, json.dumps({"code": 403, "message": "需要授权或今日免费试用已用完"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
# 先解析自带提供商与模型:自带 KEY 不消耗平台额度;模型决定上游共享池判定
|
||||
provider = payload.get("provider") if isinstance(payload.get("provider"), dict) else None
|
||||
own_provider = bool(provider and str(provider.get("base_url") or "").strip() and str(provider.get("api_key") or "").strip())
|
||||
model = str(payload.get("model") or "pollinations-flux")[:60]
|
||||
reason = gen_block_reason(machine, own_provider, model)
|
||||
if reason is not None:
|
||||
self._reply(403, json.dumps({"code": 403, "message": gen_block_message(reason)}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
prompt = str(payload.get("prompt") or "").strip()[:2000]
|
||||
if not prompt:
|
||||
self._reply(400, json.dumps({"code": 400, "message": "请输入提示词"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
model = str(payload.get("model") or "pollinations-flux")[:60]
|
||||
try:
|
||||
w = int(payload.get("width") or 1024)
|
||||
h = int(payload.get("height") or 1024)
|
||||
@@ -2995,18 +3627,28 @@ class Handler(BaseHTTPRequestHandler):
|
||||
w, h = 1024, 1024
|
||||
w = max(16, min(2048, w))
|
||||
h = max(16, min(2048, h))
|
||||
# 中文提示词自动转英文再发上游(Flux/SDXL 英文效果最好;翻译失败回退原文)
|
||||
gen_prompt, translated = self._translate_prompt(prompt)
|
||||
try:
|
||||
d = self._nm_images_gen(model, prompt, f"{w}x{h}")
|
||||
self._img_reply_ok(d)
|
||||
if own_provider:
|
||||
d = self._provider_images_gen(provider, model, gen_prompt, f"{w}x{h}")
|
||||
else:
|
||||
d = self._nm_images_gen(model, gen_prompt, f"{w}x{h}")
|
||||
daily_consume(machine, model) # 内置渠道成功才扣次(机器计数 + CF 共享池)
|
||||
except Exception as e: # noqa: BLE001
|
||||
print(f"[img] gen failed: {e}", flush=True)
|
||||
self._reply(502, json.dumps({"code": 502, "message": f"生图失败:{e}"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
# 落盘保存到该机器的历史(失败不阻断响应)
|
||||
img_url = self._persist_gen_image(machine, d, model, prompt, w, h) # 历史存用户原文
|
||||
if isinstance(d, dict) and img_url:
|
||||
d["img_url"] = img_url
|
||||
if translated and isinstance(d, dict):
|
||||
d["prompt_en"] = gen_prompt # 实际发给上游的英文提示词(供前端提示)
|
||||
self._img_reply_ok(d)
|
||||
|
||||
def _handle_edit_image(self):
|
||||
machine = self.headers.get("X-Machine-Id", "")
|
||||
if check(machine, "ai-gen") != 200:
|
||||
self._reply(403, json.dumps({"code": 403, "message": "需要授权或今日免费试用已用完"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
ctype = self.headers.get("Content-Type", "")
|
||||
if "multipart/form-data" not in ctype:
|
||||
self._reply(400, json.dumps({"code": 400, "message": "需要 multipart 上传"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
@@ -3014,6 +3656,11 @@ class Handler(BaseHTTPRequestHandler):
|
||||
form = cgi.FieldStorage(fp=self.rfile, headers=self.headers, environ={"REQUEST_METHOD": "POST", "CONTENT_TYPE": ctype})
|
||||
prompt = str(form.getvalue("prompt") or "").strip()[:2000]
|
||||
model = str(form.getvalue("model") or "dall-e-3")[:60]
|
||||
# 门禁放模型解析之后:模型决定上游(Cloudflare 共享池已授权也保护)
|
||||
reason = gen_block_reason(machine, False, model)
|
||||
if reason is not None:
|
||||
self._reply(403, json.dumps({"code": 403, "message": gen_block_message(reason)}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
if not prompt:
|
||||
self._reply(400, json.dumps({"code": 400, "message": "请输入提示词"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
@@ -3024,7 +3671,11 @@ class Handler(BaseHTTPRequestHandler):
|
||||
return
|
||||
try:
|
||||
img = up.file.read()
|
||||
d = self._nm_images_edit(model, prompt, img, up.filename)
|
||||
gen_prompt, translated = self._translate_prompt(prompt)
|
||||
d = self._nm_images_edit(model, gen_prompt, img, up.filename)
|
||||
daily_consume(machine, model) # 内置渠道成功才扣次(机器计数 + CF 共享池)
|
||||
if translated and isinstance(d, dict):
|
||||
d["prompt_en"] = gen_prompt
|
||||
self._img_reply_ok(d)
|
||||
except Exception as e: # noqa: BLE001
|
||||
print(f"[img] edit failed: {e}", flush=True)
|
||||
@@ -3278,6 +3929,94 @@ class Handler(BaseHTTPRequestHandler):
|
||||
canvas.paste(im2, ((tw - im2.width) // 2, (th - im2.height) // 2))
|
||||
return canvas
|
||||
|
||||
def _handle_face_swap(self):
|
||||
"""AI换脸(授权功能):源人脸照片 -> 目标照片,本机 CPU 推理,结果走 /ai/img 站内图链路。"""
|
||||
machine = self.headers.get("X-Machine-Id", "")
|
||||
code = check(machine, "face-swap")
|
||||
if code != 200:
|
||||
self._reply(403, json.dumps({"code": 403, "message": "AI换脸是授权功能:试用期内可免费体验,正式使用请先激活卡密"},
|
||||
ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
log_usage(machine, "face-swap")
|
||||
ctype = self.headers.get("Content-Type") or ""
|
||||
if "multipart/form-data" not in ctype:
|
||||
self._reply(400, json.dumps({"code": 400, "message": "需要 multipart/form-data"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
try:
|
||||
form = cgi.FieldStorage(fp=self.rfile, headers=self.headers,
|
||||
environ={"REQUEST_METHOD": "POST", "CONTENT_TYPE": ctype})
|
||||
except Exception as e: # noqa: BLE001
|
||||
self._reply(400, json.dumps({"code": 400, "message": f"表单解析失败: {e}"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
if str(form.getvalue("consent") or "") != "1":
|
||||
self._reply(400, json.dumps({"code": 400, "message": "请先勾选「我承诺仅使用已获本人授权的照片进行换脸」"},
|
||||
ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
try:
|
||||
src_raw = form["source"].file.read() if "source" in form else b""
|
||||
dst_raw = form["target"].file.read() if "target" in form else b""
|
||||
except Exception:
|
||||
src_raw, dst_raw = b"", b""
|
||||
if not src_raw or not dst_raw:
|
||||
self._reply(400, json.dumps({"code": 400, "message": "请同时上传源人脸照片与目标照片"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
if len(src_raw) > 15 * 1024 * 1024 or len(dst_raw) > 15 * 1024 * 1024:
|
||||
self._reply(400, json.dumps({"code": 400, "message": "单张图片不能超过 15MB"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
import cv2 as _cv2
|
||||
import numpy as _np
|
||||
src_img = _cv2.imdecode(_np.frombuffer(src_raw, _np.uint8), _cv2.IMREAD_COLOR)
|
||||
dst_img = _cv2.imdecode(_np.frombuffer(dst_raw, _np.uint8), _cv2.IMREAD_COLOR)
|
||||
if src_img is None or dst_img is None:
|
||||
self._reply(400, json.dumps({"code": 400, "message": "图片解码失败,请上传 JPG/PNG 等常见格式"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
try:
|
||||
out_jpg, msg, ms = _face_swap_run(src_img, dst_img)
|
||||
except Exception as e: # noqa: BLE001
|
||||
print(f"[face-swap] failed: {e}", flush=True)
|
||||
self._reply(500, json.dumps({"code": 500, "message": f"换脸失败: {e}"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
if out_jpg is None:
|
||||
self._reply(400, json.dumps({"code": 400, "message": msg}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
try:
|
||||
gen_dir = os.path.join(DATA_DIR, "gen_images", machine)
|
||||
os.makedirs(gen_dir, exist_ok=True)
|
||||
iid = f"{int(time.time())}_{uuid.uuid4().hex[:8]}"
|
||||
with open(os.path.join(gen_dir, iid + ".jpg"), "wb") as f:
|
||||
f.write(out_jpg)
|
||||
idx_path = os.path.join(gen_dir, "index.json")
|
||||
with GEN_IMG_LOCK:
|
||||
idx = []
|
||||
if os.path.exists(idx_path):
|
||||
try:
|
||||
idx = json.load(open(idx_path, encoding="utf-8"))
|
||||
if not isinstance(idx, list):
|
||||
idx = []
|
||||
except Exception:
|
||||
idx = []
|
||||
idx.insert(0, {"id": iid, "file": iid + ".jpg", "at": int(time.time()),
|
||||
"model": "AI换脸", "prompt": "face-swap",
|
||||
"w": int(dst_img.shape[1]), "h": int(dst_img.shape[0])})
|
||||
while len(idx) > 100:
|
||||
old = idx.pop() or {}
|
||||
fn = str(old.get("file") or "")
|
||||
if fn and "/" not in fn and "\\" not in fn:
|
||||
try:
|
||||
os.remove(os.path.join(gen_dir, fn))
|
||||
except Exception:
|
||||
pass
|
||||
with open(idx_path, "w", encoding="utf-8") as f:
|
||||
json.dump(idx, f, ensure_ascii=False)
|
||||
except Exception as e: # noqa: BLE001
|
||||
print(f"[face-swap] persist failed: {e}", flush=True)
|
||||
self._reply(500, json.dumps({"code": 500, "message": "结果保存失败"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
body = json.dumps({"code": 200, "message": "ok",
|
||||
"data": {"url": f"/relay/ai/img/{machine}/{iid}", "elapsed_ms": ms}},
|
||||
ensure_ascii=False).encode("utf-8")
|
||||
self._reply(200, body, "application/json")
|
||||
|
||||
def _handle_seamless_edit(self):
|
||||
machine = self.headers.get("X-Machine-Id", "")
|
||||
if check(machine, "ai-text-edit") != 200:
|
||||
@@ -4135,5 +4874,13 @@ def _news_loop():
|
||||
|
||||
if __name__ == "__main__":
|
||||
_ensure_admin()
|
||||
mcp_ops.setup(
|
||||
data_dir=DATA_DIR,
|
||||
usage_db=USAGE_DB,
|
||||
query_authorized=query_authorized,
|
||||
account_ok=_account_license_ok,
|
||||
machine_ok=lambda m: bool(MACHINE_RE.match(m)),
|
||||
public_base=os.environ.get("MCP_PUBLIC_BASE", ""),
|
||||
)
|
||||
threading.Thread(target=_news_loop, daemon=True).start()
|
||||
ThreadingHTTPServer(("0.0.0.0", 8091), Handler).serve_forever()
|
||||
Reference in new issue
Block a user