feat: 第一梯队AI功能落地 — AI图片实验室(rembg抠图+waifu2x无损放大+证件照换底裁剪) & AI问答(NewAPI qwen3.8-flash多轮对话), 受控授权+试用, relay三接口/remove-bg /upscale /ai/chat, u2net模型预下载+CPU推理

This commit is contained in:
personal82555 committed 2026-10-12 23:09:50 +08:00
1 parent 76494cc474
commit 94e624e840
10 files changed
+1060 -3

No files matched your search

+114 -1
View File
@@ -44,7 +44,7 @@ AUTH_PASS = os.environ.get("AUTH_PASS", "")
PROJECT_NAME = os.environ.get("PROJECT_NAME", "IT-Tools")
TRIAL_FILE = os.environ.get("TRIAL_FILE", "/app/data/trials.json")
TRIAL_MS = int(os.environ.get("TRIAL_MS_MIN", "30")) * 60 * 1000
PROTECTED_TOOLS = {"translator", "image-ocr", "pdf-ocr", "ai-retouch", "label-designer", "doc-convert", "image-tools", "pdf-tools", "video-tools", "audio-tools", "text-to-image"}
PROTECTED_TOOLS = {"translator", "image-ocr", "pdf-ocr", "ai-retouch", "label-designer", "doc-convert", "image-tools", "pdf-tools", "video-tools", "audio-tools", "text-to-image", "ai-image-tools", "ai-chat"}
MACHINE_RE = re.compile(r"^\d{10,16}$")
# verify() messages that unconditionally block activation
@@ -1456,6 +1456,110 @@ class Handler(BaseHTTPRequestHandler):
except Exception: # noqa: BLE001
return {}
# ---------- AI 图片:抠图 / 放大 ----------
_bg_session = None
def _handle_removebg(self):
machine = self.headers.get("X-Machine-Id", "")
if check(machine, "ai-image-tools") != 200:
self._reply(403, json.dumps({"code": 403, "message": "需要授权或免费试用已结束"}, ensure_ascii=False).encode("utf-8"), "application/json")
return
try:
length = int(self.headers.get("Content-Length") or 0)
if length > 30 * 1024 * 1024:
self._reply(413, json.dumps({"code": 413, "message": "图片超过 30MB 限制"}, ensure_ascii=False).encode(), "application/json")
return
raw = self.rfile.read(length) if length else b""
if not raw:
self._reply(400, json.dumps({"code": 400, "message": "未收到图片数据"}, ensure_ascii=False).encode(), "application/json")
return
from rembg import new_session, remove as _bgremove
cls = type(self)
if cls._bg_session is None:
cls._bg_session = new_session("u2net")
out = _bgremove(raw, session=cls._bg_session)
log_usage(machine, "ai-image-tools")
self._reply(200, out, "image/png")
except Exception as e: # noqa: BLE001
self._reply(500, json.dumps({"code": 500, "message": f"抠图失败: {e}"}, ensure_ascii=False).encode(), "application/json")
def _handle_upscale(self):
machine = self.headers.get("X-Machine-Id", "")
if check(machine, "ai-image-tools") != 200:
self._reply(403, json.dumps({"code": 403, "message": "需要授权或免费试用已结束"}, ensure_ascii=False).encode("utf-8"), "application/json")
return
try:
q = parse.parse_qs(parse.urlparse(self.path).query)
scale = (q.get("scale") or ["2"])[0]
noise = (q.get("noise") or ["1"])[0]
if scale not in ("2", "4"):
scale = "2"
if noise not in ("-1", "0", "1", "2", "3"):
noise = "1"
length = int(self.headers.get("Content-Length") or 0)
if length > 30 * 1024 * 1024:
self._reply(413, json.dumps({"code": 413, "message": "图片超过 30MB 限制"}, ensure_ascii=False).encode(), "application/json")
return
raw = self.rfile.read(length) if length else b""
if not raw:
self._reply(400, json.dumps({"code": 400, "message": "未收到图片数据"}, ensure_ascii=False).encode(), "application/json")
return
ctype = (self.headers.get("Content-Type") or "").split(";")[0].strip()
ext = {"image/png": "png", "image/webp": "webp"}.get(ctype, "jpg")
wd = "/tmp/up-" + uuid.uuid4().hex[:12]
os.makedirs(wd, exist_ok=True)
fin = os.path.join(wd, f"in.{ext}")
fout = os.path.join(wd, f"out.{ext}")
with open(fin, "wb") as f:
f.write(raw)
import subprocess as _sp
r = _sp.run(
["/app/waifu2x/waifu2x-ncnn-vulkan", "-i", fin, "-o", fout, "-s", scale, "-n", noise, "-g", "-1", "-t", "128"],
capture_output=True, text=True, timeout=180,
)
if r.returncode != 0 or not os.path.exists(fout):
raise RuntimeError((r.stderr or r.stdout or "waifu2x failed")[-300:])
with open(fout, "rb") as f:
out = f.read()
shutil.rmtree(wd, ignore_errors=True)
log_usage(machine, "ai-image-tools")
self._reply(200, out, ctype or "image/jpeg")
except Exception as e: # noqa: BLE001
self._reply(500, json.dumps({"code": 500, "message": f"放大失败: {e}"}, ensure_ascii=False).encode(), "application/json")
# ---------- AI 问答 ----------
def _handle_aichat(self):
payload = self._read_payload()
machine = str(payload.get("machine") or "")
if check(machine, "ai-chat") != 200:
self._reply(403, json.dumps({"code": 403, "message": "需要授权或免费试用已结束"}, ensure_ascii=False).encode("utf-8"), "application/json")
return
prompt = str(payload.get("prompt") or "").strip()[:4000]
if not prompt:
self._reply(400, json.dumps({"code": 400, "message": "请输入问题"}, ensure_ascii=False).encode(), "application/json")
return
history = payload.get("history") or []
if not isinstance(history, list):
history = []
history = [m for m in history[-8:] if isinstance(m, dict) and m.get("role") in ("user", "assistant") and isinstance(m.get("content"), str)]
messages = [{"role": "system", "content": "你是 IT-TOOLS-PRO 工具站的 AI 助手,用简体中文简洁、直接地回答,代码用代码块包裹。"}] + history + [{"role": "user", "content": prompt}]
key = os.environ.get("NEWAPI_KEY", "")
upstream = os.environ.get("NEWAPI_URL", "http://192.168.68.19:3099/v1/chat/completions")
model = os.environ.get("NEWAPI_MODEL", "big-pickle")
if not key:
self._reply(500, json.dumps({"code": 500, "message": "AI 服务未配置"}, ensure_ascii=False).encode(), "application/json")
return
try:
body = json.dumps({"model": model, "messages": messages, "temperature": 0.7, "max_tokens": 2048}).encode()
req = request.Request(upstream, data=body, headers={"Content-Type": "application/json", "Authorization": "Bearer " + key})
resp = request.urlopen(req, timeout=180)
data = json.loads(resp.read())
text = data["choices"][0]["message"]["content"]
log_usage(machine, "ai-chat")
self._reply(200, json.dumps({"code": 200, "message": "ok", "data": {"reply": text}}, ensure_ascii=False).encode("utf-8"), "application/json")
except Exception as e: # noqa: BLE001
self._reply(502, json.dumps({"code": 502, "message": f"AI 服务异常: {e}"}, ensure_ascii=False).encode(), "application/json")
def _handle_video(self):
import uuid as _uuid
import video_ops
@@ -1713,6 +1817,15 @@ class Handler(BaseHTTPRequestHandler):
if parsed.path == "/video":
self._handle_video()
return
if parsed.path == "/remove-bg":
self._handle_removebg()
return
if parsed.path.startswith("/upscale"):
self._handle_upscale()
return
if parsed.path == "/ai/chat":
self._handle_aichat()
return
if parsed.path == "/convert":
self._handle_convert()
return