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

+2
View File
@@ -12,6 +12,8 @@ declare module '@vue/runtime-core' {
'404.page': typeof import('./src/pages/404.page.vue')['default']
About: typeof import('./src/pages/About.vue')['default']
'Admin.page': typeof import('./src/pages/Admin.page.vue')['default']
AiChat: typeof import('./src/tools/ai-chat/ai-chat.vue')['default']
AiImageLab: typeof import('./src/tools/ai-image-lab/ai-image-lab.vue')['default']
AiRetouch: typeof import('./src/tools/ai-retouch/ai-retouch.vue')['default']
App: typeof import('./src/App.vue')['default']
AsciiTextDrawer: typeof import('./src/tools/ascii-text-drawer/ascii-text-drawer.vue')['default']
+12 -2
View File
@@ -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"]
+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
+2
View File
@@ -18,6 +18,8 @@ const NEW_FEATURES = [
{ path: '/video-tools', icon: '🎥', name: '视频工具箱', desc: '13 个 ffmpeg 工具:转码/压缩/水印/去水印/GIF' },
{ path: '/audio-tools', icon: '🎙️', name: '音频工具', desc: '文字转音频、语音识别、声音克隆(部署中)' },
{ path: '/user-center', icon: '👤', name: '用户中心', desc: '收藏/记录云端同步,换电脑登录即恢复,授权跟随账号' },
{ path: '/ai-image-lab', icon: '🪄', name: 'AI 图片实验室', desc: '智能抠图去背景、AI 无损放大变清晰、一键证件照' },
{ path: '/ai-chat', icon: '🤖', name: 'AI 问答', desc: '报错解读、文案写作、代码问题随口问,支持多轮对话' },
];
import { config } from '@/config';
+343
View File
@@ -0,0 +1,343 @@
<script setup lang="ts">
import { nextTick, ref } from 'vue';
import { useHead } from '@vueuse/head';
import { getMachineId, licenseHeaders } from '@/tools/license/license';
import { useGenHistory } from '@/tools/gen-history/gen-history';
useHead({ title: 'AI 问答 - IT-TOOLS-PRO' });
const genHist = useGenHistory('ai-chat');
interface Msg {
role: 'user' | 'assistant';
content: string;
}
const messages = ref<Msg[]>([]);
const input = ref('');
const busy = ref(false);
const error = ref('');
const listEl = ref<HTMLElement>();
const suggestions = ['帮我写一个 Python 批量重命名脚本', '这段报错是什么意思?', '用一句话解释什么是 Docker', '写一封请假邮件'];
async function scrollBottom() {
await nextTick();
listEl.value?.scrollTo({ top: listEl.value.scrollHeight, behavior: 'smooth' });
}
async function send(text?: string) {
const content = (text ?? input.value).trim();
if (!content || busy.value) {
return;
}
input.value = '';
messages.value.push({ role: 'user', content });
busy.value = true;
error.value = '';
scrollBottom();
try {
const res = await fetch('/relay/ai/chat', {
method: 'POST',
headers: { ...licenseHeaders('ai-chat'), 'Content-Type': 'application/json' },
body: JSON.stringify({
machine: getMachineId(),
prompt: content,
history: messages.value.slice(0, -1).slice(-8),
}),
});
const j = await res.json().catch(() => ({}));
if (!res.ok || j.code !== 200) {
throw new Error(j.message || `HTTP ${res.status}`);
}
messages.value.push({ role: 'assistant', content: j.data.reply });
genHist.add({ title: `AI 问答: ${content.slice(0, 24)}`, detail: `回复 ${j.data.reply.length} 字` });
}
catch (e: any) {
error.value = String(e?.message || e);
}
finally {
busy.value = false;
scrollBottom();
}
}
function clearChat() {
messages.value = [];
error.value = '';
}
</script>
<template>
<div class="ac-root">
<div class="ac-head">
<div>
<div class="ac-title">🤖 AI 问答</div>
<div class="ac-sub">报错信息、英文邮件、生活问题、代码片段——直接问。支持多轮上下文。</div>
</div>
<button v-if="messages.length" class="ac-clear" @click="clearChat">🗑 清空对话</button>
</div>
<div ref="listEl" class="ac-list">
<div v-if="!messages.length" class="ac-welcome">
<div class="ac-wave">👋</div>
<div class="ac-tip">试试这些问题:</div>
<div class="ac-sugg">
<button v-for="s in suggestions" :key="s" class="ac-sugg-item" @click="input = s; send(s)">
{{ s }}
</button>
</div>
</div>
<div v-for="(m, i) in messages" :key="i" class="ac-msg" :class="m.role">
<div class="ac-avatar">{{ m.role === 'user' ? '我' : 'AI' }}</div>
<div class="ac-bubble">
<pre class="ac-text">{{ m.content }}</pre>
</div>
</div>
<div v-if="busy" class="ac-msg assistant">
<div class="ac-avatar">AI</div>
<div class="ac-bubble ac-thinking">
<span class="ac-dot" /><span class="ac-dot" /><span class="ac-dot" />
思考中…
</div>
</div>
<div v-if="error" class="ac-error">⚠️ {{ error }}</div>
</div>
<div class="ac-inputbar">
<textarea
v-model="input"
class="ac-input"
rows="2"
placeholder="输入你的问题,Enter 发送,Shift+Enter 换行"
@keydown.enter.exact.prevent="input.trim() && send()"
/>
<button class="ac-send" :disabled="busy || !input.trim()" @click="send()">
{{ busy ? '…' : '发送' }}
</button>
</div>
</div>
</template>
<style lang="less" scoped>
.ac-root {
display: flex;
flex-direction: column;
height: calc(100vh - 200px);
min-height: 480px;
border: 1px solid rgba(128, 128, 128, 0.2);
border-radius: 14px;
overflow: hidden;
background: #fff;
}
.ac-head {
display: flex;
justify-content: space-between;
align-items: center;
padding: 14px 18px;
border-bottom: 1px solid rgba(128, 128, 128, 0.15);
.ac-title {
font-size: 16.5px;
font-weight: 800;
}
.ac-sub {
font-size: 12px;
opacity: 0.5;
margin-top: 2px;
}
.ac-clear {
border: 1px solid rgba(128, 128, 128, 0.3);
background: #fff;
border-radius: 8px;
padding: 6px 13px;
font-size: 12.5px;
cursor: pointer;
&:hover {
border-color: #d03050;
color: #d03050;
}
}
}
.ac-list {
flex: 1;
overflow-y: auto;
padding: 18px;
}
.ac-welcome {
text-align: center;
padding: 40px 0;
.ac-wave {
font-size: 42px;
}
.ac-tip {
font-size: 13.5px;
opacity: 0.6;
margin: 14px 0 12px;
}
}
.ac-sugg {
display: flex;
flex-wrap: wrap;
gap: 9px;
justify-content: center;
}
.ac-sugg-item {
border: 1px solid rgba(37, 99, 235, 0.35);
background: rgba(37, 99, 235, 0.05);
color: #2563eb;
border-radius: 999px;
padding: 8px 16px;
font-size: 13px;
cursor: pointer;
transition: all 0.13s;
&:hover {
background: #2563eb;
color: #fff;
}
}
.ac-msg {
display: flex;
gap: 10px;
margin-bottom: 14px;
&.user {
flex-direction: row-reverse;
.ac-bubble {
background: #2563eb;
color: #fff;
}
}
.ac-avatar {
width: 32px;
height: 32px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
font-size: 12.5px;
font-weight: 800;
flex-shrink: 0;
color: #fff;
background: linear-gradient(135deg, #2563eb, #18a058);
}
&.user .ac-avatar {
background: linear-gradient(135deg, #f59e0b, #e60012);
}
.ac-bubble {
max-width: 78%;
background: rgba(128, 128, 128, 0.08);
border-radius: 12px;
padding: 10px 14px;
}
.ac-text {
margin: 0;
white-space: pre-wrap;
word-break: break-word;
font-family: inherit;
font-size: 13.5px;
line-height: 1.75;
}
}
.ac-thinking {
display: flex;
align-items: center;
gap: 5px;
font-size: 12.5px;
opacity: 0.7;
.ac-dot {
width: 6px;
height: 6px;
border-radius: 50%;
background: #2563eb;
animation: ac-blink 1.2s infinite;
&:nth-child(2) {
animation-delay: 0.2s;
}
&:nth-child(3) {
animation-delay: 0.4s;
}
}
}
@keyframes ac-blink {
0%,
60%,
100% {
opacity: 0.25;
}
30% {
opacity: 1;
}
}
.ac-error {
color: #d03050;
font-size: 12.5px;
padding: 8px 4px;
}
.ac-inputbar {
display: flex;
gap: 10px;
padding: 13px 16px;
border-top: 1px solid rgba(128, 128, 128, 0.15);
background: rgba(128, 128, 128, 0.03);
.ac-input {
flex: 1;
resize: none;
border: 1px solid rgba(128, 128, 128, 0.35);
border-radius: 10px;
padding: 10px 13px;
font-size: 13.5px;
font-family: inherit;
outline: none;
&:focus {
border-color: #2563eb;
}
}
.ac-send {
align-self: stretch;
border: none;
background: #2563eb;
color: #fff;
border-radius: 10px;
padding: 0 24px;
font-size: 14px;
font-weight: 700;
cursor: pointer;
&:disabled {
opacity: 0.5;
cursor: not-allowed;
}
&:hover:not(:disabled) {
background: #1d4ed8;
}
}
}
</style>
+11
View File
@@ -0,0 +1,11 @@
import { Robot } from '@vicons/tabler';
import { defineTool } from '../tool';
export const tool = defineTool({
name: 'AI 问答',
path: '/ai-chat',
description: '智能 AI 对话助手:报错解读、文案写作、代码问题随口问',
keywords: ['ai', 'chat', 'gpt', 'assistant', 'llm', '问答', '对话', '助手', 'AI'],
component: () => import('./ai-chat.vue'),
icon: Robot,
});
+559
View File
@@ -0,0 +1,559 @@
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { useHead } from '@vueuse/head';
import { licenseHeaders } from '@/tools/license/license';
import GenHistory from '@/tools/gen-history/GenHistory.vue';
import { useGenHistory } from '@/tools/gen-history/gen-history';
useHead({ title: 'AI 图片实验室 - IT-TOOLS-PRO' });
const genHist = useGenHistory('ai-image-lab');
type TabKey = 'matting' | 'upscale' | 'idphoto';
const tab = ref<TabKey>('matting');
// ============ 公共 ============
const srcUrl = ref('');
const outUrl = ref('');
const busy = ref(false);
const error = ref('');
const fileInput = ref<HTMLInputElement>();
const curFile = ref<File | null>(null);
function pickFile() {
fileInput.value?.click();
}
function onInput(e: Event) {
const input = e.target as HTMLInputElement;
setFile(input.files?.[0] ?? null);
input.value = '';
}
function onDrop(e: DragEvent) {
setFile(e.dataTransfer?.files?.[0] ?? null);
}
function setFile(f: File | null) {
if (srcUrl.value) {
URL.revokeObjectURL(srcUrl.value);
}
if (outUrl.value) {
URL.revokeObjectURL(outUrl.value);
}
curFile.value = f;
srcUrl.value = f ? URL.createObjectURL(f) : '';
outUrl.value = '';
error.value = '';
}
async function fetchWithTimeout(url: string, opts: RequestInit, ms: number): Promise<Response> {
const ctrl = new AbortController();
const t = setTimeout(() => ctrl.abort(), ms);
try {
return await fetch(url, { ...opts, signal: ctrl.signal });
}
finally {
clearTimeout(t);
}
}
// ============ 抠图 ============
const bgMode = ref<'transparent' | 'white' | 'red' | 'blue' | 'green'>('transparent');
async function doMatting() {
if (!curFile.value) {
error.value = '请先上传图片';
return;
}
busy.value = true;
error.value = '';
try {
const res = await fetchWithTimeout('/relay/remove-bg', {
method: 'POST',
body: curFile.value,
headers: { ...licenseHeaders('ai-image-tools'), 'Content-Type': curFile.value.type || 'image/jpeg' },
}, 120000);
if (!res.ok) {
const j = await res.json().catch(() => ({}));
throw new Error(j.message || `HTTP ${res.status}`);
}
const blob = await res.blob();
if (outUrl.value) {
URL.revokeObjectURL(outUrl.value);
}
outUrl.value = URL.createObjectURL(blob);
outBlob.value = blob;
genHist.add({ title: `AI 抠图: ${curFile.value.name}`, detail: `${(blob.size / 1024).toFixed(0)}KB` });
}
catch (e: any) {
error.value = String(e?.message || e);
}
finally {
busy.value = false;
}
}
const outBlob = ref<Blob | null>(null);
// 抠图结果叠加底色预览(证件照换底也用)
const compositeUrl = ref('');
async function applyBg(mode: string) {
bgMode.value = mode as any;
if (!outBlob.value) {
return;
}
const img = new Image();
const url = URL.createObjectURL(outBlob.value);
await new Promise<void>((r) => {
img.onload = () => r();
img.src = url;
});
const c = document.createElement('canvas');
c.width = img.naturalWidth;
c.height = img.naturalHeight;
const ctx = c.getContext('2d')!;
if (mode !== 'transparent') {
const colors: Record<string, string> = { white: '#ffffff', red: '#e60012', blue: '#438edb', green: '#07a05c' };
ctx.fillStyle = colors[mode] || '#ffffff';
ctx.fillRect(0, 0, c.width, c.height);
}
ctx.drawImage(img, 0, 0);
URL.revokeObjectURL(url);
if (compositeUrl.value) {
URL.revokeObjectURL(compositeUrl.value);
}
compositeUrl.value = c.toDataURL('image/png');
}
// ============ 无损放大 ============
const upScale = ref(2);
const upNoise = ref(1);
async function doUpscale() {
if (!curFile.value) {
error.value = '请先上传图片';
return;
}
busy.value = true;
error.value = '';
try {
const res = await fetchWithTimeout(`/relay/upscale?scale=${upScale.value}&noise=${upNoise.value}`, {
method: 'POST',
body: curFile.value,
headers: { ...licenseHeaders('ai-image-tools'), 'Content-Type': curFile.value.type || 'image/jpeg' },
}, 200000);
if (!res.ok) {
const j = await res.json().catch(() => ({}));
throw new Error(j.message || `HTTP ${res.status}`);
}
const blob = await res.blob();
if (outUrl.value) {
URL.revokeObjectURL(outUrl.value);
}
outUrl.value = URL.createObjectURL(blob);
const img = new Image();
img.src = outUrl.value;
await new Promise<void>((r) => {
img.onload = () => r();
});
genHist.add({ title: `AI 放大 ${upScale.value}x: ${curFile.value.name}`, detail: `${img.naturalWidth}×${img.naturalHeight} · ${(blob.size / 1024).toFixed(0)}KB` });
}
catch (e: any) {
error.value = String(e?.message || e);
}
finally {
busy.value = false;
}
}
// ============ 证件照 ============
const idSizes = [
{ key: 'one', name: '一寸', w: 295, h: 413 },
{ key: 'two', name: '二寸', w: 413, h: 579 },
{ key: 'passport', name: '护照', w: 390, h: 567 },
{ key: 'sq', name: '方形头像', w: 400, h: 400 },
];
const idSize = ref('one');
const idBg = ref<'white' | 'red' | 'blue'>('white');
const headScale = ref(100);
const headY = ref(0);
const idResult = ref('');
async function makeIdPhoto() {
if (!outBlob.value) {
error.value = '请先完成抠图(切换到「抠图」生成透明底图)';
return;
}
error.value = '';
const spec = idSizes.find(s => s.key === idSize.value)!;
const img = new Image();
const url = URL.createObjectURL(outBlob.value);
await new Promise<void>((r) => {
img.onload = () => r();
img.src = url;
});
const c = document.createElement('canvas');
c.width = spec.w;
c.height = spec.h;
const ctx = c.getContext('2d')!;
const colors: Record<string, string> = { white: '#ffffff', red: '#e60012', blue: '#438edb' };
ctx.fillStyle = colors[idBg.value];
ctx.fillRect(0, 0, c.width, c.height);
// 人物居中:按证件照标准(头部占约 60-70% 高)
const base = (c.height * 0.92) / img.naturalHeight;
const s = base * (headScale.value / 100);
const dw = img.naturalWidth * s;
const dh = img.naturalHeight * s;
const dx = (c.width - dw) / 2;
const dy = (c.height - dh) / 2 + (headY.value / 100) * c.height * 0.25;
ctx.drawImage(img, dx, dy, dw, dh);
if (idResult.value) {
URL.revokeObjectURL(idResult.value);
}
idResult.value = c.toDataURL('image/png');
genHist.add({ title: `证件照: ${spec.name} ${idBg.value === 'white' ? '白底' : idBg.value === 'red' ? '红底' : '蓝底'}`, detail: `${spec.w}×${spec.h}` });
}
function downloadUrl(url: string, name: string) {
const a = document.createElement('a');
a.href = url;
a.download = name;
a.click();
}
function switchTab(k: TabKey) {
tab.value = k;
error.value = '';
}
onMounted(() => {});
</script>
<template>
<div class="al-root">
<div class="al-tabs">
<button class="al-tab" :class="{ on: tab === 'matting' }" @click="switchTab('matting')">
✂️ 智能抠图
</button>
<button class="al-tab" :class="{ on: tab === 'upscale' }" @click="switchTab('upscale')">
🔍 无损放大
</button>
<button class="al-tab" :class="{ on: tab === 'idphoto' }" @click="switchTab('idphoto')">
🪪 证件照制作
</button>
<span class="al-note">本地 AI 处理,图片不离开服务器</span>
</div>
<div class="al-cols">
<!-- 左:参数 -->
<div class="al-left">
<input ref="fileInput" type="file" hidden accept="image/*" @change="onInput">
<div class="al-drop" @click="pickFile" @dragover.prevent @drop.prevent="onDrop">
<template v-if="!curFile">
<div class="al-drop-hint">📁 点击或拖入图片<br><span>JPG / PNG / WebP · ≤30MB</span></div>
</template>
<div v-else class="al-file">
🖼️ {{ curFile.name }}
<span class="al-file-size">({{ (curFile.size / 1024 / 1024).toFixed(1) }} MB)</span>
<a href="javascript:;" class="al-clear" @click.stop="setFile(null)">✕</a>
</div>
</div>
<!-- 抠图参数 -->
<template v-if="tab === 'matting'">
<div class="al-sec">抠图后背景</div>
<div class="al-chips">
<button class="al-chip" :class="{ on: bgMode === 'transparent' }" @click="applyBg('transparent')">透明</button>
<button class="al-chip" :class="{ on: bgMode === 'white' }" @click="applyBg('white')">白色</button>
<button class="al-chip" :class="{ on: bgMode === 'red' }" @click="applyBg('red')">红色</button>
<button class="al-chip" :class="{ on: bgMode === 'blue' }" @click="applyBg('blue')">蓝色</button>
<button class="al-chip" :class="{ on: bgMode === 'green' }" @click="applyBg('green')">绿色</button>
</div>
<div class="al-hint">一键去除背景,保留主体;可直接切换证件照底色。</div>
</template>
<!-- 放大参数 -->
<template v-if="tab === 'upscale'">
<div class="al-sec">放大倍数</div>
<div class="al-chips">
<button class="al-chip" :class="{ on: upScale === 2 }" @click="upScale = 2">2 倍</button>
<button class="al-chip" :class="{ on: upScale === 4 }" @click="upScale = 4">4 倍</button>
</div>
<div class="al-sec">降噪强度</div>
<div class="al-chips">
<button v-for="n in [-1, 0, 1, 2, 3]" :key="n" class="al-chip" :class="{ on: upNoise === n }" @click="upNoise = n">
{{ n === -1 ? '无' : `LV${n}` }}
</button>
</div>
<div class="al-hint">waifu2x 深度学习超分:模糊/低清图片放大后补细节,截图和照片都适用。</div>
</template>
<!-- 证件照参数 -->
<template v-if="tab === 'idphoto'">
<div class="al-sec">证件照规格</div>
<div class="al-chips">
<button v-for="s in idSizes" :key="s.key" class="al-chip" :class="{ on: idSize === s.key }" @click="idSize = s.key; makeIdPhoto()">
{{ s.name }}
</button>
</div>
<div class="al-sec">背景颜色</div>
<div class="al-chips">
<button class="al-chip" :class="{ on: idBg === 'white' }" @click="idBg = 'white'; makeIdPhoto()">白底</button>
<button class="al-chip" :class="{ on: idBg === 'red' }" @click="idBg = 'red'; makeIdPhoto()">红底</button>
<button class="al-chip" :class="{ on: idBg === 'blue' }" @click="idBg = 'blue'; makeIdPhoto()">蓝底</button>
</div>
<div class="al-sec">人物大小 {{ headScale }}%</div>
<input v-model.number="headScale" type="range" min="70" max="140" step="1" class="al-range" @change="makeIdPhoto()">
<div class="al-sec">上下位置 {{ headY > 0 ? '+' : '' }}{{ headY }}</div>
<input v-model.number="headY" type="range" min="-30" max="30" step="1" class="al-range" @change="makeIdPhoto()">
<div class="al-hint">流程:先在「抠图」去掉背景 → 回到本页选规格底色 → 微调人物大小位置。</div>
</template>
<button class="al-go" :disabled="busy || !curFile" @click="tab === 'matting' ? doMatting() : tab === 'upscale' ? doUpscale() : makeIdPhoto()">
{{ busy ? '⏳ AI 处理中…' : tab === 'matting' ? '✂️ 开始抠图' : tab === 'upscale' ? `🔍 放大 ${upScale}x` : '🪪 生成证件照' }}
</button>
<div v-if="error" class="al-error">{{ error }}</div>
</div>
<!-- 右:预览 -->
<div class="al-right">
<div class="al-sec">
{{ tab === 'idphoto' ? '证件照预览' : outUrl ? '处理结果' : '原图预览' }}
<button v-if="tab === 'idphoto' && idResult" class="al-dl" @click="downloadUrl(idResult, '证件照.png')">⬇ 下载证件照</button>
<button v-else-if="outUrl && tab !== 'idphoto'" class="al-dl" @click="downloadUrl(outUrl, tab === 'matting' ? '抠图.png' : `放大${upScale}x.${(curFile?.name || '').split('.').pop() || 'jpg'}`)">⬇ 下载结果</button>
</div>
<div class="al-preview">
<img v-if="tab === 'idphoto' && idResult" :src="idResult" class="al-img al-img-id" alt="id photo">
<img v-else-if="outUrl" :src="bgMode !== 'transparent' && compositeUrl && tab === 'matting' ? compositeUrl : outUrl" class="al-img al-img-checker" alt="result">
<img v-else-if="srcUrl" :src="srcUrl" class="al-img" alt="source">
<div v-else class="al-empty">上传图片后在这里预览</div>
</div>
<GenHistory tool="ai-image-lab" label="AI 图片记录" class="mt-10px" />
</div>
</div>
</div>
</template>
<style lang="less" scoped>
.al-root {
padding-bottom: 16px;
}
.al-tabs {
display: flex;
gap: 8px;
align-items: center;
margin-bottom: 14px;
flex-wrap: wrap;
}
.al-tab {
border: 1px solid rgba(128, 128, 128, 0.3);
background: #fff;
border-radius: 999px;
padding: 8px 18px;
font-size: 13.5px;
cursor: pointer;
transition: all 0.15s;
&.on {
background: #2563eb;
border-color: #2563eb;
color: #fff;
font-weight: 700;
}
}
.al-note {
margin-left: auto;
font-size: 11.5px;
opacity: 0.5;
}
.al-cols {
display: flex;
gap: 14px;
align-items: flex-start;
}
.al-left {
width: 340px;
flex-shrink: 0;
border: 1px solid rgba(128, 128, 128, 0.2);
border-radius: 12px;
padding: 14px;
}
.al-right {
flex: 1;
min-width: 0;
border: 1px solid rgba(128, 128, 128, 0.2);
border-radius: 12px;
padding: 14px;
}
.al-drop {
border: 1.5px dashed rgba(128, 128, 128, 0.4);
border-radius: 10px;
padding: 18px 12px;
text-align: center;
cursor: pointer;
margin-bottom: 12px;
transition: border-color 0.15s;
&:hover {
border-color: #2563eb;
}
.al-drop-hint {
font-size: 13.5px;
font-weight: 600;
line-height: 1.7;
span {
font-size: 11.5px;
font-weight: 400;
opacity: 0.5;
}
}
.al-file {
font-size: 12.5px;
font-weight: 600;
word-break: break-all;
.al-file-size {
font-weight: 400;
opacity: 0.55;
}
.al-clear {
color: #d03050;
margin-left: 8px;
text-decoration: none;
}
}
}
.al-sec {
font-size: 12.5px;
font-weight: 700;
opacity: 0.75;
margin: 10px 0 7px;
display: flex;
justify-content: space-between;
align-items: center;
}
.al-chips {
display: flex;
gap: 7px;
flex-wrap: wrap;
}
.al-chip {
border: 1px solid rgba(128, 128, 128, 0.3);
background: #fff;
border-radius: 999px;
padding: 5px 13px;
font-size: 12.5px;
cursor: pointer;
transition: all 0.13s;
&:hover {
border-color: #2563eb;
}
&.on {
background: rgba(37, 99, 235, 0.1);
border-color: #2563eb;
color: #2563eb;
font-weight: 700;
}
}
.al-range {
width: 100%;
}
.al-hint {
font-size: 11.5px;
opacity: 0.5;
line-height: 1.7;
margin-top: 10px;
}
.al-go {
width: 100%;
margin-top: 14px;
border: none;
background: #2563eb;
color: #fff;
border-radius: 9px;
padding: 11px;
font-size: 14px;
font-weight: 700;
cursor: pointer;
&:disabled {
opacity: 0.5;
cursor: not-allowed;
}
&:hover:not(:disabled) {
background: #1d4ed8;
}
}
.al-error {
color: #d03050;
font-size: 12.5px;
margin-top: 9px;
line-height: 1.6;
}
.al-dl {
border: 1px solid rgba(128, 128, 128, 0.3);
background: #fff;
border-radius: 7px;
padding: 4px 12px;
font-size: 12px;
cursor: pointer;
&:hover {
border-color: #18a058;
color: #18a058;
}
}
.al-preview {
min-height: 380px;
display: flex;
align-items: center;
justify-content: center;
background: rgba(128, 128, 128, 0.05);
border-radius: 10px;
padding: 16px;
.al-img {
max-width: 100%;
max-height: 520px;
border-radius: 8px;
}
.al-img-checker {
background:
repeating-conic-gradient(rgba(128, 128, 128, 0.12) 0% 25%, transparent 0% 50%) 0 0 / 20px 20px;
}
.al-img-id {
max-height: 460px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.18);
}
.al-empty {
font-size: 13px;
opacity: 0.45;
}
}
</style>
+11
View File
@@ -0,0 +1,11 @@
import { Wand } from '@vicons/tabler';
import { defineTool } from '../tool';
export const tool = defineTool({
name: 'AI 图片实验室',
path: '/ai-image-lab',
description: '智能抠图、AI 无损放大、证件照制作——本地 AI 处理',
keywords: ['ai', 'matting', 'upscale', 'idphoto', 'background', 'cutout', '抠图', '去背景', '放大', '变清晰', '证件照', 'AI'],
component: () => import('./ai-image-lab.vue'),
icon: Wand,
});
+4
View File
@@ -88,6 +88,8 @@ import { tool as signaturePad } from './signature-pad';
import { tool as textToImage } from './text-to-image';
import { tool as zhConvert } from './zh-convert';
import { tool as pinyinConverter } from './pinyin-converter';
import { tool as aiImageLab } from './ai-image-lab';
import { tool as aiChat } from './ai-chat';
import { tool as docConvert } from './doc-convert';
import { tool as aiRetouch } from './ai-retouch';
import { tool as wifiQrCodeGenerator } from './wifi-qr-code-generator';
@@ -205,6 +207,8 @@ export const toolsByCategory: ToolCategory[] = [
translator,
zhConvert,
pinyinConverter,
aiImageLab,
aiChat,
],
},
{
+2
View File
@@ -17,6 +17,8 @@ export const PROTECTED_TOOLS: Record<string, string> = {
'/video-tools': '视频工具',
'/audio-tools': '音频工具',
'/text-to-image': '文字生成图片',
'/ai-image-lab': 'AI图片实验室',
'/ai-chat': 'AI问答',
};
export const TRIAL_MS = 30 * 60 * 1000; // 每个功能免费 30 分钟