feat: 第一梯队AI功能落地 — AI图片实验室(rembg抠图+waifu2x无损放大+证件照换底裁剪) & AI问答(NewAPI qwen3.8-flash多轮对话), 受控授权+试用, relay三接口/remove-bg /upscale /ai/chat, u2net模型预下载+CPU推理
This commit is contained in:
1 parent
76494cc474
commit
94e624e840
10 files changed
+1060
-3
No files matched your search
@@ -1,9 +1,19 @@
|
||||
FROM python:3.10-slim-bookworm
|
||||
# calibre provides ebook-convert: docx/pdf/txt/rtf/odt/epub/mobi/azw3/html interop
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends calibre \
|
||||
&& apt-get install -y --no-install-recommends calibre ffmpeg fonts-wqy-zenhei \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
# audio tools: Piper (local neural TTS) + faster-whisper (local ASR)
|
||||
# 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]"
|
||||
COPY hf-cache /root/.cache/huggingface
|
||||
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 .
|
||||
COPY server.py video_ops.py audio_ops.py .
|
||||
ENV HF_HOME=/root/.cache/huggingface
|
||||
EXPOSE 8091
|
||||
CMD ["python", "server.py"]
|
||||
@@ -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
|
||||
|
||||
Reference in new issue
Block a user