feat: 历史记录100条上限 + 后台文件管理升级收口

- 所有功能历史最多显示100条:relay img-history vis[:150]→[:100]、mcp-usage 流水 LIMIT 300→100
- 前端三处兜底:loadImgHist/ai-gen/poster slice(0,100)
- 上轮遗留收口:后台文件管理全量视图/50条分页/100x100缩略图/下载/三类删除、图片历史铁规则 ImgHist 共享层接入7工具
- Home NEW_FEATURES 与 README 同步
This commit is contained in:
jinghui committed 2026-11-14 18:58:48 +08:00
1 parent 225aa5ed68
commit 3c126277eb
16 files changed
+1030 -93

No files matched your search

+19
View File
@@ -89,6 +89,25 @@
- AI 配图复用 `/relay/ai/gen-image` 与每日免费生图额度,按图框宽高比自动匹配上游尺寸档位。
- 完成后一键导出 1080×1440 PNG(旋转图层同步导出)。授权应用,支持每日免费试用。
### 历史记录 100 条上限(2026.11 新增)
所有功能里的历史记录最多显示 100 条(按时间倒序取最新 100 条):
- 服务端 `GET /relay/ai/img-history` 与 `GET /admin/mcp-usage` 调用流水统一截断前 100 条(只影响展示条数,后台总记录数/总调用量统计不受影响);
- 前端图片历史共享层(`loadImgHist`)、AI 生图与海报生成的自建历史均带 100 条本地兜底;
- 已有上限低于 100 的(生成记录 50 条、网速测速 20 条等)保持原值。
### 后台文件管理(2026.11 新增)
管理后台「文件管理」页全面升级:
- **默认全量视图**:进入即显示**所有用户**上传的文件 + AI 生成图片(换脸/生图/海报/编辑)+ MCP 产出文件的聚合列表,无需先选用户;下拉仍可按「仅 AI 生成 / 仅某用户」过滤。
- **50 条/页自动分页**:超过 50 条自动分页,页头页尾都有翻页控件,**显示总记录数与总大小**(如「共 81 条记录 · 合计 31.5 MB」)。
- **图片 100×100 缩略图**:图片类型文件在「预览」列显示 100×100 缩略图,点击看原图;**其他文件显示文件类型徽标**(PDF/PNG/MP4…)。
- **单独下载**:每一行都有「下载」链接(`Content-Disposition: attachment` 带原文件名),与「删除」并列;删除按来源分流(用户文件走 files 表、AI 生成图同步删 index、MCP 文件防路径穿越)。
- **安全**:缩略图与下载走统一 `/relay/admin/file?path=…&token=…` 路由(`<img>`/`<a>` 无法携带 header,鉴权走 query token,与 header 双通道校验);路径白名单限定 `users/`、`gen_images/`、`mcp_files/` 三棵子树 + realpath 校验,防目录穿越;无 token 请求 403。
- 服务端按 mtime 全局排序后切片分页,每项附带 `source`(user/gen/mcp)、`file_type`、`is_image`、相对 `path` 字段。
## 优势
- **一次激活,全站通用**:输入一次卡密,全部授权功能解锁,无需逐个购买
+1
View File
@@ -130,6 +130,7 @@ declare module '@vue/runtime-core' {
IconMdiVideo: typeof import('~icons/mdi/video')['default']
ImageOcr: typeof import('./src/tools/image-ocr/image-ocr.vue')['default']
ImageTools: typeof import('./src/tools/image-tools/image-tools.vue')['default']
ImgHist: typeof import('./src/tools/img-hist/ImgHist.vue')['default']
InputCopyable: typeof import('./src/components/InputCopyable.vue')['default']
IntegerBaseConverter: typeof import('./src/tools/integer-base-converter/integer-base-converter.vue')['default']
Ipv4AddressConverter: typeof import('./src/tools/ipv4-address-converter/ipv4-address-converter.vue')['default']
+2 -1
View File
@@ -76,7 +76,8 @@ def mcp_usage_query(days: int = 7) -> dict:
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()
# 铁规则:所有功能历史最多显示 100 条
"WHERE at>? ORDER BY at DESC LIMIT 100", (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()
+385 -26
View File
@@ -21,6 +21,7 @@ Trial state persisted to /app/data/trials.json (mounted volume).
import cgi
import io
import json
import mimetypes
import os
import re
import shutil
@@ -716,6 +717,7 @@ _FACE_LOCK = threading.Lock()
_FACE_APP = None
_FACE_SWAP = None
_FACE_MODELS_DIR = os.environ.get("FACE_MODELS_DIR", "/app/face-models")
_GFPGAN_SESS = None
def _face_engine():
@@ -737,6 +739,67 @@ def _largest_face(faces):
return max(faces, key=lambda f: float((f.bbox[2] - f.bbox[0]) * (f.bbox[3] - f.bbox[1])))
def _gfpgan_session():
global _GFPGAN_SESS
if _GFPGAN_SESS is None:
import onnxruntime as _ort
path = os.path.join(_FACE_MODELS_DIR, "gfpgan_1.4.onnx")
if not os.path.exists(path):
return None
_GFPGAN_SESS = _ort.InferenceSession(path, providers=["CPUExecutionProvider"])
return _GFPGAN_SESS
def _gfpgan_enhance(img):
"""用 GFPGAN 对图中最大人脸做修复增强,返回增强后的整图(失败则原样返回)。"""
try:
import cv2 as _cv2
import numpy as _np
sess = _gfpgan_session()
if sess is None:
return img
app, _ = _face_engine()
faces = app.get(img)
if not faces:
return img
f = _largest_face(faces)
x1, y1, x2, y2 = [int(v) for v in f.bbox]
h, w = img.shape[:2]
# 扩展 bbox
pad = int(0.25 * max(x2 - x1, y2 - y1))
x1 = max(0, x1 - pad); y1 = max(0, y1 - pad)
x2 = min(w, x2 + pad); y2 = min(h, y2 + pad)
crop = img[y1:y2, x1:x2]
if crop.size == 0:
return img
inp = _cv2.resize(crop, (512, 512))
inp = _cv2.cvtColor(inp, _cv2.COLOR_BGR2RGB).astype("float32") / 255.0
inp = (inp - 0.5) / 0.5
inp = _np.transpose(inp, (2, 0, 1))[None, ...].astype("float32")
out = sess.run(None, {sess.get_inputs()[0].name: inp})[0]
out = out[0].transpose(1, 2, 0)
out = (out * 0.5 + 0.5) * 255.0
out = _np.clip(out, 0, 255).astype("uint8")
out = _cv2.cvtColor(out, _cv2.COLOR_RGB2BGR)
out = _cv2.resize(out, (x2 - x1, y2 - y1))
# 羽化混合
mask = _np.zeros((y2 - y1, x2 - x1), dtype="float32")
cx, cy = (x2 - x1) // 2, (y2 - y1) // 2
# 简单中心渐变蒙版
Y, X = _np.ogrid[:y2-y1, :x2-x1]
dist = _np.sqrt((X - cx) ** 2 + (Y - cy) ** 2)
r = min(cx, cy)
mask = _np.clip(1 - dist / max(r, 1), 0, 1)
mask = mask[..., None]
blended = (out.astype("float32") * mask + crop.astype("float32") * (1 - mask)).astype("uint8")
res = img.copy()
res[y1:y2, x1:x2] = blended
return res
except Exception as e:
print(f"[gfpgan] enhance failed: {e}", flush=True)
return img
def _face_swap_run(src_img, dst_img):
"""源人脸 -> 目标照片。返回 (jpg字节|None, 错误信息, 耗时ms)。加锁串行避免并发吃满 CPU。"""
import cv2 as _cv2
@@ -750,6 +813,9 @@ def _face_swap_run(src_img, dst_img):
if not dst_faces:
return None, "目标图中未检测到人脸,请换一张含人物的照片", 0
out = swap.get(dst_img, _largest_face(dst_faces), _largest_face(src_faces), paste_back=True)
# GFPGAN 修复增强(可选)
if os.environ.get("FACE_SWAP_GFPGAN", "1") != "0":
out = _gfpgan_enhance(out)
ok, buf = _cv2.imencode(".jpg", out, [int(_cv2.IMWRITE_JPEG_QUALITY), 92])
if not ok:
return None, "结果编码失败", 0
@@ -1211,6 +1277,21 @@ def _admin_auth(handler) -> bool:
tok = handler.headers.get("X-Admin-Token", "")
if ADMIN_TOKEN and tok and tok == ADMIN_TOKEN:
return True
# query token fallback: <img src> / <a download> 无法携带 header,缩略图与下载走 ?token=
if not tok:
try:
tok = (parse.parse_qs(parse.urlparse(handler.path).query).get("token") or [""])[0]
except Exception:
tok = ""
if ADMIN_TOKEN and tok and tok == ADMIN_TOKEN:
return True
if tok:
acc = _parse_token(tok)
if acc:
role, disabled = _user_attr(acc)
if role == "admin" and not disabled:
return True
tok = ""
# channel 2: logged-in admin account
auth = handler.headers.get("Authorization", "")
if auth.lower().startswith("bearer "):
@@ -1278,26 +1359,157 @@ def admin_api(method: str, sub: str, payload: dict, handler):
"totals": {"users": len(out_users), "files": total_files, "size": total_size},
}}
# ---- 统一文件下载/缩略图:path 相对 DATA_DIR(users/、gen_images/、mcp_files/ 白名单)----
# 鉴权走 _admin_auth(支持 header 或 ?token=,因 <img src>/<a download> 无法带 header)
if method == "GET" and sub == "/file":
qs = parse.parse_qs(parse.urlparse(handler.path).query)
rel = (qs.get("path") or [""])[0]
as_dl = (qs.get("dl") or [""])[0] == "1"
disp_q = (qs.get("name") or [""])[0]
if not rel or rel.startswith("/") or ".." in rel.split("/"):
return 400, {"code": 400, "message": "参数错误"}
if rel.split("/")[0] not in ("users", "gen_images", "mcp_files"):
return 404, {"code": 404, "message": "文件不存在"}
root = os.path.realpath(DATA_DIR)
fp = os.path.realpath(os.path.join(root, rel))
if not fp.startswith(root + os.sep) or not os.path.isfile(fp):
return 404, {"code": 404, "message": "文件不存在"}
try:
with open(fp, "rb") as fh:
data = fh.read()
except OSError:
return 404, {"code": 404, "message": "文件不存在"}
disp = os.path.basename(disp_q.replace(chr(92), "/")) if disp_q else os.path.basename(fp)
disp = re.sub(r'[\r\n"]+', '', disp)[:180] or os.path.basename(fp)
ctype = mimetypes.guess_type(fp)[0] or "application/octet-stream"
handler.send_response(200)
handler.send_header("Content-Type", ctype)
handler.send_header("Content-Length", str(len(data)))
if as_dl:
handler.send_header("Content-Disposition", "attachment; filename*=UTF-8''" + parse.quote(disp))
handler.end_headers()
handler.wfile.write(data)
return None, None
# ---- 文件管理:默认全量聚合(所有用户文件 + AI 生成图片 + MCP 产出),50/页分页 ----
if method == "GET" and sub.startswith("/files"):
qs = parse.parse_qs(parse.urlparse(handler.path).query)
username = (qs.get("username") or [""])[0]
if not username or "/" in username or ".." in username:
scope = (qs.get("scope") or [""])[0]
try:
page = max(1, int((qs.get("page") or ["1"])[0]))
except Exception:
page = 1
try:
page_size = min(200, max(1, int((qs.get("page_size") or ["50"])[0])))
except Exception:
page_size = 50
if username and ("/" in username or ".." in username):
return 400, {"code": 400, "message": "参数错误"}
fdir = os.path.join(_user_dir(username), "files")
files = []
total = 0
for root, _d, fs in os.walk(fdir):
kind = os.path.basename(root) if root != fdir else ""
for f in fs:
fp = os.path.join(root, f)
IMG_EXT = {"png", "jpg", "jpeg", "gif", "webp", "bmp", "svg", "avif", "ico"}
items = []
want_user = scope not in ("gen", "mcp")
want_gen = scope in ("", "gen")
want_mcp = scope in ("", "mcp")
if username: # 指定用户时只看该用户文件(兼容旧下拉语义)
want_user, want_gen, want_mcp = True, False, False
# 1) 用户上传文件(磁盘是 uuid 名 -> DB 取真实文件名/mime)
if want_user:
db_meta = {}
try:
conn = _db()
for fid, un, nm, mi in conn.execute("SELECT id, username, name, mime FROM files").fetchall():
db_meta[(un, fid)] = (nm or fid, mi or "")
conn.close()
except Exception:
db_meta = {}
uroots = [username] if username else (
sorted(os.listdir(USERS_ROOT)) if os.path.isdir(USERS_ROOT) else [])
for u in uroots:
fdir = os.path.join(USERS_ROOT, u, "files")
if not os.path.isdir(fdir):
continue
for root, _d, fs in os.walk(fdir):
kind = os.path.basename(root) if root != fdir else ""
for f in fs:
fp = os.path.join(root, f)
try:
st = os.stat(fp)
except OSError:
continue
nm, mi = db_meta.get((u, f), (f, ""))
ext = os.path.splitext(nm)[1].lower().lstrip(".")
items.append({
"id": f, "name": nm, "kind": kind, "size": st.st_size,
"mtime": int(st.st_mtime), "source": "user", "username": u,
"mime": mi, "is_image": mi.startswith("image/") or ext in IMG_EXT,
"file_type": (ext or (mi.split("/")[-1] if mi else "file") or "file").upper(),
"path": os.path.relpath(fp, DATA_DIR),
})
# 2) AI 生成图片(换脸/生图/海报/编辑,跨所有机器聚合 gen_images/*/)
if want_gen:
groot = os.path.join(DATA_DIR, "gen_images")
for m in (sorted(os.listdir(groot)) if os.path.isdir(groot) else []):
gdir = os.path.join(groot, m)
if not os.path.isdir(gdir):
continue
idx = {}
try:
idxp = os.path.join(gdir, "index.json")
for it in (json.load(open(idxp, encoding="utf-8")) if os.path.exists(idxp) else []):
if isinstance(it, dict):
idx[str(it.get("id"))] = it
except Exception:
idx = {}
for f in os.listdir(gdir):
if f == "index.json":
continue
fp = os.path.join(gdir, f)
try:
st = os.stat(fp)
except OSError:
continue
iid = os.path.splitext(f)[0]
meta = idx.get(iid, {})
ext = os.path.splitext(f)[1].lower().lstrip(".")
items.append({
"id": iid, "name": f, "kind": str(meta.get("kind") or "gen"),
"size": st.st_size, "mtime": int(st.st_mtime), "machine": m,
"prompt": str(meta.get("prompt") or ""), "url": f"/relay/ai/img/{m}/{iid}",
"source": "gen", "username": "", "mime": f"image/{ext}",
"is_image": ext in IMG_EXT, "file_type": (ext or "img").upper(),
"path": os.path.relpath(fp, DATA_DIR),
})
# 3) MCP 产出文件(data/mcp_files/)
if want_mcp:
mroot = os.path.join(DATA_DIR, "mcp_files")
for f in (sorted(os.listdir(mroot)) if os.path.isdir(mroot) else []):
fp = os.path.join(mroot, f)
if not os.path.isfile(fp):
continue
try:
st = os.stat(fp)
except OSError:
continue
total += st.st_size
files.append({"id": f, "name": f, "kind": kind, "size": st.st_size, "mtime": int(st.st_mtime)})
files.sort(key=lambda x: -x["mtime"])
return 200, {"code": 200, "message": "ok", "data": {"files": files, "total_size": total, "count": len(files)}}
ext = os.path.splitext(f)[1].lower().lstrip(".")
items.append({
"id": f, "name": f, "kind": "mcp", "size": st.st_size,
"mtime": int(st.st_mtime), "source": "mcp", "username": "",
"mime": "", "is_image": ext in IMG_EXT,
"file_type": (ext or "file").upper(),
"path": os.path.relpath(fp, DATA_DIR),
})
items.sort(key=lambda x: -x["mtime"])
total = len(items)
total_size = sum(x["size"] for x in items)
pages = max(1, (total + page_size - 1) // page_size)
page = min(page, pages)
start = (page - 1) * page_size
page_items = items[start:start + page_size]
return 200, {"code": 200, "message": "ok", "data": {
"files": page_items, "total": total, "total_size": total_size,
"page": page, "page_size": page_size, "pages": pages, "count": len(page_items),
}}
if method == "POST" and sub == "/cleanup":
before = int(payload.get("before") or 0)
@@ -1340,8 +1552,45 @@ def admin_api(method: str, sub: str, payload: dict, handler):
if method == "POST" and sub == "/delete-file":
file_id = str(payload.get("id") or "")
username = str(payload.get("username") or "")
# MCP 文件删除:username 特殊标记 __mcp__,id=文件名(可含扩展名)
if username == "__mcp__":
if not file_id or file_id != os.path.basename(file_id) or file_id in (".", ".."):
return 400, {"code": 400, "message": "参数错误"}
mroot = os.path.realpath(os.path.join(DATA_DIR, "mcp_files"))
fp2 = os.path.realpath(os.path.join(mroot, file_id))
if not fp2.startswith(mroot + os.sep) or not os.path.isfile(fp2):
return 404, {"code": 404, "message": "文件不存在"}
size2 = os.path.getsize(fp2)
os.remove(fp2)
return 200, {"code": 200, "message": "ok", "data": {"freed": size2}}
if not re.match(r"^[A-Za-z0-9_-]{8,64}$", file_id) or not username:
return 400, {"code": 400, "message": "参数错误"}
# AI 生成图片删除:username 为特殊标记 __gen__,带 machine 定位 gen_images/<machine>/
if username == "__gen__":
machine = str(payload.get("machine") or "")
if not re.fullmatch(r"\d{10,16}", machine):
return 400, {"code": 400, "message": "参数错误"}
gdir = os.path.join(DATA_DIR, "gen_images", machine)
target = None
if os.path.isdir(gdir):
for fn in os.listdir(gdir):
if fn.startswith(file_id + ".") and os.path.isfile(os.path.join(gdir, fn)):
target = os.path.join(gdir, fn)
break
if not target:
return 404, {"code": 404, "message": "文件不存在"}
size = os.path.getsize(target)
os.remove(target)
idxp = os.path.join(gdir, "index.json")
with GEN_IMG_LOCK:
try:
idx = json.load(open(idxp, encoding="utf-8")) if os.path.exists(idxp) else []
idx = [it for it in idx if str((it or {}).get("id")) != file_id]
with open(idxp, "w", encoding="utf-8") as f:
json.dump(idx, f, ensure_ascii=False)
except Exception:
pass
return 200, {"code": 200, "message": "ok", "data": {"freed": size}}
base = os.path.join(_user_dir(username), "files")
target = os.path.join(base, file_id)
if not os.path.exists(target):
@@ -1490,6 +1739,8 @@ def admin_api(method: str, sub: str, payload: dict, handler):
if method == "GET" and sub == "/storage":
total = _dir_size(USERS_ROOT) if os.path.isdir(USERS_ROOT) else 0
if os.path.isdir(os.path.join(DATA_DIR, "gen_images")):
total += _dir_size(os.path.join(DATA_DIR, "gen_images"))
for extra in ("users.db", "usage.db", "trials.json"):
fp = os.path.join(DATA_DIR, extra)
if os.path.exists(fp):
@@ -1531,10 +1782,10 @@ def admin_api(method: str, sub: str, payload: dict, handler):
os.remove(probe)
except Exception as e:
return 400, {"code": 400, "message": f"目标路径不可写: {e}"}
# migrate existing data (users dir + db files)
# migrate existing data (users dir + AI 生成图片 + db files)
moved = []
old_root = DATA_DIR
for item in ("users",):
for item in ("users", "gen_images"):
src = os.path.join(old_root, item)
dst = os.path.join(new_root, item)
if os.path.isdir(src) and not os.path.isdir(dst):
@@ -2089,6 +2340,8 @@ class Handler(BaseHTTPRequestHandler):
self._reply(400, json.dumps({"code": 400, "message": "无效请求体"}, ensure_ascii=False).encode(), "application/json")
return
status, body = admin_api(method, sub, payload, self)
if status is None:
return # 二进制下载分支已自行写出响应
self._reply(status, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json")
# ---------- 网速测试(用户浏览器 <-> 本站服务器) ----------
@@ -3166,6 +3419,9 @@ class Handler(BaseHTTPRequestHandler):
if parsed.path == "/ai/gen-image":
self._handle_gen_image()
return
if parsed.path == "/ai/img-save":
self._handle_img_save()
return
if parsed.path == "/ai/edit-image":
self._handle_edit_image()
return
@@ -3395,11 +3651,18 @@ class Handler(BaseHTTPRequestHandler):
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"):
def _hist_owner(self, machine):
"""历史归属:登录账号优先,未登录回落机器码(铁规则:只看本人历史)。"""
u = _auth_user(self)
return u if u else machine
def _persist_gen_image(self, machine, d, model, prompt, w, h, kind="gen", owner=None):
"""把生成结果落盘并写入该机器的历史索引;返回站内图片 URL(任何失败返回空串)。"""
try:
if not self._gen_machine_ok(machine):
return ""
if owner is None:
owner = self._hist_owner(machine)
items = (d or {}).get("data") or []
if not items:
return ""
@@ -3451,6 +3714,7 @@ class Handler(BaseHTTPRequestHandler):
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],
"owner": str(owner)[:64],
"w": w, "h": h})
while len(idx) > 100:
old = idx.pop() or {}
@@ -3541,26 +3805,103 @@ class Handler(BaseHTTPRequestHandler):
return
self._reply(200, json.dumps({"code": 200, "message": "ok", "data": ids[:200]}, ensure_ascii=False).encode("utf-8"), "application/json")
def _handle_img_save(self):
"""导出海报/成片落盘:客户端把 PNG base64 POST 上来,写入该机器的图片历史。"""
payload = self._read_payload()
machine = str(payload.get("machine") or "")
tool = str(payload.get("tool") or "poster-maker")[:40]
if tool in PROTECTED_TOOLS:
if check(machine, tool) != 200:
self._reply(403, json.dumps({"code": 403, "message": "需要授权或今日免费试用已用完"}, ensure_ascii=False).encode("utf-8"), "application/json")
return
elif not MACHINE_RE.match(machine or ""):
# 免费工具历史落盘:仅要求合法机器码,不走授权门禁
self._reply(400, json.dumps({"code": 400, "message": "bad machine"}, ensure_ascii=False).encode("utf-8"), "application/json")
return
b64 = str(payload.get("b64") or "")
if "," in b64[:100]:
b64 = b64.split(",", 1)[1]
if not b64:
self._reply(400, json.dumps({"code": 400, "message": "缺少图片数据"}, ensure_ascii=False).encode("utf-8"), "application/json")
return
if len(b64) > 40 * 1024 * 1024:
self._reply(413, json.dumps({"code": 413, "message": "图片超过 30MB 限制"}, ensure_ascii=False).encode("utf-8"), "application/json")
return
prompt = str(payload.get("prompt") or "海报导出")[:500]
model = str(payload.get("model") or "AI海报")[:60]
d = {"data": [{"b64_json": b64}]}
img_url = self._persist_gen_image(machine, d, model, prompt, 0, 0, kind=str(payload.get("kind") or "poster")[:20])
if not img_url:
self._reply(500, json.dumps({"code": 500, "message": "保存失败"}, ensure_ascii=False).encode("utf-8"), "application/json")
return
log_usage(machine, tool)
self._reply(200, json.dumps({"code": 200, "message": "ok", "data": {"img_url": img_url}}, 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 "")
fkind = str((qs.get("kind") 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):
# 铁规则:只看本人历史。登录=账号本人条目(跨设备)+ 本机匿名条目;
# 未登录=仅本机匿名条目(owner 为空或等于机器码,含迁移前旧记录)。
me = _auth_user(self)
root = os.path.join(DATA_DIR, "gen_images")
pairs = []
if me:
try:
items = json.load(open(idx_path, encoding="utf-8"))
if not isinstance(items, list):
items = []
for name in sorted(os.listdir(root)):
ip = os.path.join(root, name, "index.json")
if not os.path.isfile(ip):
continue
try:
its = json.load(open(ip, encoding="utf-8"))
except Exception:
continue
if isinstance(its, list):
pairs.append((name, its))
except Exception:
items = []
pairs = []
else:
its = []
ip = os.path.join(root, machine, "index.json")
if os.path.exists(ip):
try:
its = json.load(open(ip, encoding="utf-8"))
except Exception:
its = []
if not isinstance(its, list):
its = []
pairs.append((machine, its))
items = []
for name, its in pairs:
for it in its:
if isinstance(it, dict):
it["_dir"] = name
items.append(it)
if fkind:
# kind 过滤:逗号分隔多值;旧记录无 kind 字段视为 "gen"
want = {k for k in fkind.split(",") if k}
items = [it for it in items if str(it.get("kind") or "gen") in want]
vis = []
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")
o = str(it.get("owner") or "")
d = str(it.get("_dir") or machine)
if me:
ok = (o == me) or (d == machine and (not o or o == machine))
else:
ok = (d == machine) and (not o or o == machine)
if ok:
it["img_url"] = f"/relay/ai/img/{d}/{it.get('id', '')}"
vis.append(it)
vis.sort(key=lambda x: int(x.get("at") or 0), reverse=True)
# 铁规则:所有功能历史最多显示 100 条(按时间倒序取前 100)
vis = vis[:100]
for it in vis:
it.pop("_dir", None)
self._reply(200, json.dumps({"code": 200, "message": "ok", "data": vis}, 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)
@@ -3640,7 +3981,11 @@ class Handler(BaseHTTPRequestHandler):
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) # 历史存用户原文
try:
kind = str(payload.get("kind") or "gen")[:20]
except Exception:
kind = "gen"
img_url = self._persist_gen_image(machine, d, model, prompt, w, h, kind=kind) # 历史存用户原文
if isinstance(d, dict) and img_url:
d["img_url"] = img_url
if translated and isinstance(d, dict):
@@ -3676,6 +4021,10 @@ class Handler(BaseHTTPRequestHandler):
daily_consume(machine, model) # 内置渠道成功才扣次(机器计数 + CF 共享池)
if translated and isinstance(d, dict):
d["prompt_en"] = gen_prompt
# 铁规则:生成即保存到后台存储目录(失败静默,不阻断响应)
img_url = self._persist_gen_image(machine, d, model, prompt, 0, 0, kind="edit")
if img_url and isinstance(d, dict):
d["img_url"] = img_url
self._img_reply_ok(d)
except Exception as e: # noqa: BLE001
print(f"[img] edit failed: {e}", flush=True)
@@ -3997,6 +4346,8 @@ class Handler(BaseHTTPRequestHandler):
idx = []
idx.insert(0, {"id": iid, "file": iid + ".jpg", "at": int(time.time()),
"model": "AI换脸", "prompt": "face-swap",
"kind": "face-swap",
"owner": str(self._hist_owner(machine))[:64],
"w": int(dst_img.shape[1]), "h": int(dst_img.shape[0])})
while len(idx) > 100:
old = idx.pop() or {}
@@ -4112,6 +4463,14 @@ class Handler(BaseHTTPRequestHandler):
self._reply(502, json.dumps({"code": 502, "message": f"重绘失败:{e}"}, ensure_ascii=False).encode("utf-8"), "application/json")
return
# 落盘到该机器图片历史(铁规则:生成即保存,失败不阻断响应)
try:
for im in images:
self._persist_gen_image(machine, {"data": [{"b64_json": im["b64"]}]},
"无痕改字", prompt, base_im.size[0], base_im.size[1],
kind="seamless")
except Exception as _pe: # noqa: BLE001
print(f"[se] persist failed: {_pe}", flush=True)
pub = [{"old": r["old"], "new": r["new"] or "(仅删除)", "style": r["style"]} for r in results]
self._reply(200, json.dumps({"code": 200, "message": "ok", "data": {"images": images, "edits": pub, "note": note}}, ensure_ascii=False).encode("utf-8"), "application/json")
+1 -1
View File
@@ -40,7 +40,7 @@ useHead(head);
const { t } = useI18n();
// 宽屏工具:不受 600px 限宽,占满可用宽度(画布/多栏类工具)
const WIDE_TOOLS = new Set(['/label-designer', '/json-prettify', '/pdf-tools', '/image-tools', '/doc-convert', '/video-tools', '/seal-maker', '/signature-pad', '/ai-image-lab', '/ai-chat', '/copywriting', '/ai-gen', '/code-reader', '/my-ip', '/mcp-connect', '/poster-maker']);
const WIDE_TOOLS = new Set(['/label-designer', '/json-prettify', '/pdf-tools', '/image-tools', '/doc-convert', '/video-tools', '/seal-maker', '/signature-pad', '/ai-image-lab', '/ai-chat', '/copywriting', '/ai-gen', '/code-reader', '/my-ip', '/mcp-connect', '/poster-maker', '/ai-text-edit', '/ai-retouch']);
const isWide = computed(() => WIDE_TOOLS.has(route.path));
const i18nKey = computed<string>(() => route.path.trim().replace('/', ''));
+178 -31
View File
@@ -107,25 +107,66 @@ async function loadOverview() {
overview.value = b.data;
}
// ============ 文件管理 ============
const fileUser = ref('');
// ============ 文件管理(默认全量聚合,50 条/页自动分页)============
const fileUser = ref(''); // ''=全部, '__gen__'=AI生成, 其他=指定用户
const fileList = ref<any[]>([]);
const fileTotal = ref(0);
const fileTotal = ref(0); // 合计字节数
const fileCount = ref(0); // 总记录数
const filePage = ref(1);
const filePages = ref(1);
const FILE_PAGE_SIZE = 50;
const cleanupDays = ref(7);
const cleanupUser = ref('');
const cleanupResult = ref('');
async function loadFiles() {
if (!fileUser.value) {
return;
}
const b = await api(`/admin/files?username=${encodeURIComponent(fileUser.value)}`);
const q = new URLSearchParams();
if (fileUser.value === '__gen__') q.set('scope', 'gen');
else if (fileUser.value) q.set('username', fileUser.value);
q.set('page', String(filePage.value));
q.set('page_size', String(FILE_PAGE_SIZE));
const b = await api(`/admin/files?${q}`);
fileList.value = b.data?.files ?? [];
fileTotal.value = b.data?.total_size ?? 0;
fileCount.value = b.data?.total ?? 0;
filePages.value = b.data?.pages ?? 1;
filePage.value = b.data?.page ?? 1;
}
async function delFile(id: string) {
const b = await api('/admin/delete-file', { method: 'POST', body: JSON.stringify({ id, username: fileUser.value }) });
function gotoFilePage(p: number) {
filePage.value = Math.min(Math.max(1, p), filePages.value);
loadFiles();
}
// 文件直链:缩略图 <img> 与下载 <a> 无法携带 header,鉴权走 ?token=
function fileUrl(f: any, dl = false) {
const q = new URLSearchParams();
q.set('path', f.path || '');
if (f.name) q.set('name', f.name);
if (dl) q.set('dl', '1');
if (token.value) q.set('token', token.value);
return `/relay/admin/file?${q}`;
}
function windowOpen(url: string) {
window.open(url, '_blank', 'noopener');
}
function fileOwner(f: any) {
if (f.source === 'gen') return f.machine || 'AI';
if (f.source === 'mcp') return 'MCP';
return f.username || f.source || '-';
}
async function delFile(f: any) {
const body: any = { id: f.id };
if (f.source === 'gen') {
body.username = '__gen__';
body.machine = f.machine;
} else if (f.source === 'mcp') {
body.username = '__mcp__';
} else {
body.username = f.username || fileUser.value;
}
const b = await api('/admin/delete-file', { method: 'POST', body: JSON.stringify(body) });
if (b.code === 200) {
await loadFiles();
loadOverview();
@@ -144,9 +185,8 @@ async function cleanup() {
if (b.code === 200) {
cleanupResult.value = `已删除 ${b.data.removed} 个文件,释放 ${fmtSize(b.data.freed)}`;
loadOverview();
if (fileUser.value) {
loadFiles();
}
filePage.value = 1;
loadFiles();
}
}
@@ -154,6 +194,7 @@ function pickUser(u: string) {
fileUser.value = u;
cleanupUser.value = u;
tab.value = 'files';
filePage.value = 1;
loadFiles();
}
@@ -495,6 +536,9 @@ function switchTab(id: 'overview' | 'files' | 'usage' | 'mcp' | 'storage' | 'rec
if (id === 'feedback') {
loadFeedback();
}
if (id === 'files') {
loadFiles();
}
}
</script>
@@ -592,11 +636,17 @@ function switchTab(id: 'overview' | 'files' | 'usage' | 'mcp' | 'storage' | 'rec
<!-- files -->
<template v-if="tab === 'files'">
<div class="adm-toolbar">
<select v-model="fileUser" class="adm-select" @change="loadFiles">
<option value="">选择用户…</option>
<option v-for="u in users" :key="u.username" :value="u.username">{{ u.username }}</option>
<select v-model="fileUser" class="adm-select" @change="filePage = 1; loadFiles()">
<option value="">全部(所有用户 + AI 生成 + MCP)</option>
<option value="__gen__">仅 AI 生成图片(换脸/生图/海报)</option>
<option v-for="u in users" :key="u.username" :value="u.username">仅 {{ u.username }}</option>
</select>
<span v-if="fileList.length" class="adm-sub">{{ fileList.length }} 个文件 · 合计 {{ fmtSize(fileTotal) }}</span>
<span class="adm-sub">共 {{ fileCount }} 条记录 · 合计 {{ fmtSize(fileTotal) }}</span>
<span v-if="filePages > 1" class="adm-pager">
<button class="adm-btn adm-btn-sm" :disabled="filePage <= 1" @click="gotoFilePage(filePage - 1)">‹ 上一页</button>
<span class="adm-pageinfo">第 {{ filePage }} / {{ filePages }} 页</span>
<button class="adm-btn adm-btn-sm" :disabled="filePage >= filePages" @click="gotoFilePage(filePage + 1)">下一页 ›</button>
</span>
</div>
<div class="adm-cleanup">
@@ -617,21 +667,36 @@ function switchTab(id: 'overview' | 'files' | 'usage' | 'mcp' | 'storage' | 'rec
<span v-if="cleanupResult" class="adm-ok">{{ cleanupResult }}</span>
</div>
<table class="adm-table">
<thead>
<tr><th>文件</th><th>类型</th><th>大小</th><th>时间</th><th></th></tr>
</thead>
<tbody>
<tr v-for="f in fileList" :key="f.id">
<td class="adm-fname">{{ f.name }}</td>
<td>{{ f.kind || '-' }}</td>
<td>{{ fmtSize(f.size) }}</td>
<td>{{ fmtTime(f.mtime) }}</td>
<td><a href="javascript:;" class="adm-del" @click="delFile(f.id)">删除</a></td>
</tr>
<tr v-if="!fileList.length"><td colspan="5" class="adm-none">{{ fileUser ? '该用户暂无文件' : '请先选择用户' }}</td></tr>
</tbody>
</table>
<div class="adm-fscroll">
<table class="adm-table">
<thead>
<tr><th class="adm-thumbcol">预览</th><th>文件</th><th>来源</th><th>类型</th><th>大小</th><th>时间</th><th></th></tr>
</thead>
<tbody>
<tr v-for="f in fileList" :key="(f.source || '') + ':' + (f.machine || '') + ':' + f.id">
<td class="adm-thumbcell">
<img v-if="f.is_image" class="adm-thumb" :src="fileUrl(f)" alt="" @click="windowOpen(fileUrl(f))">
<span v-else class="adm-ftype">{{ f.file_type || '文件' }}</span>
</td>
<td class="adm-fname" :title="f.prompt || f.name">{{ f.name }}</td>
<td>{{ fileOwner(f) }}</td>
<td>{{ f.kind || '-' }}</td>
<td>{{ fmtSize(f.size) }}</td>
<td>{{ fmtTime(f.mtime) }}</td>
<td class="adm-ops">
<a :href="fileUrl(f, true)" class="adm-dl" download>下载</a>
<a href="javascript:;" class="adm-del" @click="delFile(f)">删除</a>
</td>
</tr>
<tr v-if="!fileList.length"><td colspan="7" class="adm-none">暂无文件</td></tr>
</tbody>
</table>
</div>
<div v-if="filePages > 1" class="adm-pager adm-pager-b">
<button class="adm-btn adm-btn-sm" :disabled="filePage <= 1" @click="gotoFilePage(filePage - 1)">‹ 上一页</button>
<span class="adm-pageinfo">第 {{ filePage }} / {{ filePages }} 页 · 共 {{ fileCount }} 条</span>
<button class="adm-btn adm-btn-sm" :disabled="filePage >= filePages" @click="gotoFilePage(filePage + 1)">下一页 ›</button>
</div>
</template>
<!-- storage -->
@@ -1248,6 +1313,88 @@ function switchTab(id: 'overview' | 'files' | 'usage' | 'mcp' | 'storage' | 'rec
}
}
/* ===== 文件管理:缩略图/类型徽标/分页 ===== */
.adm-fscroll {
overflow-x: auto;
-webkit-overflow-scrolling: touch;
.adm-table {
min-width: 860px;
th {
white-space: nowrap;
}
}
}
.adm-thumbcol,
.adm-thumbcell {
width: 116px;
padding-top: 8px !important;
padding-bottom: 8px !important;
}
.adm-thumb {
width: 100px;
height: 100px;
object-fit: cover;
border-radius: 8px;
border: 1px solid rgba(128, 128, 128, 0.22);
background: rgba(128, 128, 128, 0.06);
display: block;
cursor: zoom-in;
}
.adm-ftype {
display: flex;
align-items: center;
justify-content: center;
width: 100px;
height: 64px;
border-radius: 8px;
background: rgba(128, 128, 128, 0.1);
font-weight: 700;
font-size: 13px;
letter-spacing: 0.5px;
color: rgba(128, 128, 128, 0.95);
text-transform: uppercase;
}
.adm-ops {
white-space: nowrap;
a + a {
margin-left: 10px;
}
}
.adm-dl {
color: #18a058;
text-decoration: none;
&:hover {
text-decoration: underline;
}
}
.adm-pager {
display: inline-flex;
align-items: center;
gap: 8px;
}
.adm-pager-b {
display: flex;
justify-content: center;
margin-top: 14px;
}
.adm-pageinfo {
font-size: 12.5px;
opacity: 0.75;
white-space: nowrap;
}
.adm-userbar {
display: flex;
align-items: center;
+2
View File
@@ -11,6 +11,8 @@ import { useRecentTools } from '@/composable/recent-tools';
// 近期新功能亮点(手动维护,新工具上线时加一条)
// ★铁规则:每完成一批新功能/新工具,必须在这里最前面加条目(新→旧),否则首页看不到
const NEW_FEATURES = [
{ path: '/admin', icon: '📁', name: '后台文件管理', desc: '默认聚合所有用户文件与AI生成图片,每页50条自动分页显示总记录数,图片100×100缩略图、其他文件显示类型,全部支持单独下载' },
{ path: '/ai-gen', icon: '🗂️', name: '图片历史铁规则', desc: '所有生图功能右侧 50×50 缩略图历史竖排、点击看大图,按登录账号/机器码只看本人的,生成即保存到后台指定目录,全部功能历史最多显示100条' },
{ path: '/face-swap', icon: '🎭', name: 'AI 换脸', desc: '上传源人脸与目标照片,本地 AI 一键换脸(insightface 人脸检测+inswapper),授权功能支持免费试用' },
{ path: '/poster-maker', icon: '🖼️', name: 'AI 海报生成', desc: '42套模板10分类(含校园师生款)、文字图片可旋转、整页自适应不滚动,改文字换图片AI生成配图,一键导出 PNG' },
{ path: '/ai-gen', icon: '🎨', name: 'AI 生图', desc: '10款内置模型一键出图,四组86个现成提示词(通用/自媒体/电商/软件类),中文自动转英文发送' },
+5 -3
View File
@@ -1,5 +1,6 @@
<script setup lang="ts">
import { getMachineId, licenseHeaders } from '@/tools/license/license';
import { authHdr } from '@/tools/img-hist/img-hist';
const models = ref<{ id: string; i2i: boolean; custom?: boolean }[]>([]);
const model = ref(''); // 打开页面默认选中列表第一个模型
@@ -101,9 +102,10 @@ function mergeModels() {
const history = ref<{ id: string; at: number; model: string; prompt: string; img_url: string }[]>([]);
async function loadHistory() {
try {
const res = await fetch(`/relay/ai/img-history?machine=${encodeURIComponent(getMachineId())}`);
const res = await fetch(`/relay/ai/img-history?machine=${encodeURIComponent(getMachineId())}&kind=gen`, { headers: authHdr() });
const j = await res.json();
if (j.code === 200 && Array.isArray(j.data)) history.value = j.data;
// 铁规则:所有功能历史最多显示 100 条
if (j.code === 200 && Array.isArray(j.data)) history.value = j.data.slice(0, 100);
} catch { /* ignore */ }
}
function openHist(it: any) {
@@ -337,7 +339,7 @@ async function generate() {
}
const res = await fetch('/relay/ai/gen-image', {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...licenseHeaders('ai-gen') },
headers: { 'Content-Type': 'application/json', ...licenseHeaders('ai-gen'), ...authHdr() },
body: JSON.stringify(body),
});
const j = await res.json().catch(() => ({}));
+19 -8
View File
@@ -2,11 +2,22 @@
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';
import ImgHist from '@/tools/img-hist/ImgHist.vue';
import { blobToB64, dataUrlToB64, saveImgHist } from '@/tools/img-hist/img-hist';
useHead({ title: 'AI 图片实验室 - IT-TOOLS-PRO' });
const genHist = useGenHistory('ai-image-lab');
const histRef = ref<InstanceType<typeof ImgHist> | null>(null);
/** 处理结果保存到服务器历史(失败静默,不影响下载) */
async function saveLab(model: string, prompt: string, src: Blob | string) {
try {
const b64 = typeof src === 'string' ? dataUrlToB64(src) : await blobToB64(src);
if (!b64) return;
const ok = await saveImgHist({ kind: 'ai-image-lab', tool: 'ai-image-tools', b64, model, prompt });
if (ok) histRef.value?.reload();
}
catch { /* 静默 */ }
}
type TabKey = 'matting' | 'upscale' | 'idphoto';
const tab = ref<TabKey>('matting');
@@ -83,7 +94,7 @@ async function doMatting() {
}
outUrl.value = URL.createObjectURL(blob);
outBlob.value = blob;
genHist.add({ title: `AI 抠图: ${curFile.value.name}`, detail: `${(blob.size / 1024).toFixed(0)}KB` });
saveLab('AI抠图', curFile.value?.name || '', blob);
}
catch (e: any) {
error.value = String(e?.message || e);
@@ -156,7 +167,7 @@ async function doUpscale() {
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` });
saveLab(`AI放大${upScale.value}x`, curFile.value?.name || '', blob);
}
catch (e: any) {
error.value = String(e?.message || e);
@@ -211,7 +222,7 @@ async function makeIdPhoto() {
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}` });
saveLab('证件照', `${spec.name} ${idBg.value === 'white' ? '白底' : idBg.value === 'red' ? '红底' : '蓝底'}`, idResult.value || '');
}
function downloadUrl(url: string, name: string) {
@@ -319,7 +330,7 @@ onMounted(() => {});
<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-if="tab === 'idphoto' && idResult" class="al-dl" @click="saveLab('证件照', '证件照下载', idResult); 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">
@@ -328,8 +339,8 @@ onMounted(() => {});
<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>
<ImgHist ref="histRef" kind="ai-image-lab" />
</div>
</div>
</template>
+17 -10
View File
@@ -1,10 +1,21 @@
<script setup lang="ts">
import { useUserAuth } from '@/composable/user-auth';
import { licenseHeaders } from '../license/license';
import GenHistory from '@/tools/gen-history/GenHistory.vue';
import { useGenHistory } from '@/tools/gen-history/gen-history';
import ImgHist from '@/tools/img-hist/ImgHist.vue';
import { blobToB64, saveImgHist } from '@/tools/img-hist/img-hist';
const genHist = useGenHistory('ai-retouch');
const histRef = ref<InstanceType<typeof ImgHist> | null>(null);
/** 修图结果保存到服务器历史(失败静默,不影响下载) */
async function saveRetouch(blob: Blob) {
try {
const b64 = await blobToB64(blob);
if (!b64) return;
const ok = await saveImgHist({ kind: 'ai-retouch', tool: 'ai-retouch', b64, model: tab.value.label, prompt: fileName.value || '' });
if (ok) histRef.value?.reload();
}
catch { /* 静默 */ }
}
interface TabDef {
key: string;
@@ -211,6 +222,7 @@ async function submit() {
}
const blob = await res.blob();
resultUrl.value = URL.createObjectURL(blob);
saveRetouch(blob);
if (tab.value.key === 'inpaint') clearMask();
}
catch (e: any) {
@@ -219,12 +231,7 @@ async function submit() {
finally {
elapsed.value = Math.round(performance.now() - start);
processing.value = false;
if (resultUrl.value) {
genHist.add({
title: tab.value.label,
detail: `原图 ${imgNatural.value.w}×${imgNatural.value.h} · 耗时 ${elapsed.value}ms`,
});
}
}
}
@@ -411,6 +418,7 @@ onUnmounted(() => {
</div>
</n-spin>
</div>
<ImgHist ref="histRef" kind="ai-retouch" />
</div>
<!-- bottom bar -->
@@ -432,7 +440,6 @@ onUnmounted(() => {
</c-button>
</div>
<GenHistory tool="ai-retouch" position="right" label="修图记录" />
</div>
</template>
+7 -2
View File
@@ -1,5 +1,7 @@
<script setup lang="ts">
import { getMachineId, licenseHeaders } from '@/tools/license/license';
import ImgHist from '@/tools/img-hist/ImgHist.vue';
import { authHdr } from '@/tools/img-hist/img-hist';
// ---------- 状态 ----------
const file = ref<File | null>(null);
@@ -51,6 +53,7 @@ onMounted(async () => {
// ---------- 最近任务(localStorage 缩略图) ----------
interface SETask { id: string; time: number; prompt: string; before: string; after: string; count: number }
const tasks = ref<SETask[]>([]);
const histRef = ref<InstanceType<typeof ImgHist> | null>(null);
const LS_KEY = 'it-ai-text-edit:tasks';
function loadTasks() {
@@ -145,7 +148,7 @@ async function submit() {
}
const res = await fetch('/relay/ai/seamless-edit', {
method: 'POST',
headers: licenseHeaders('ai-text-edit'),
headers: { ...licenseHeaders('ai-text-edit'), ...authHdr() },
body: fd,
});
const j = await res.json().catch(() => ({}));
@@ -167,6 +170,7 @@ async function submit() {
tasks.value = tasks.value.slice(0, 12);
saveTasks();
}
histRef.value?.reload();
else if (!note.value) {
note.value = '未产生结果,请调整描述后重试';
}
@@ -339,6 +343,7 @@ function clearAll() {
</div>
</div>
</div>
<ImgHist ref="histRef" kind="seamless" />
</div>
</div>
</template>
@@ -349,7 +354,7 @@ function clearAll() {
.se-title { font-size: 30px; font-weight: 800; letter-spacing: 2px; }
.se-sub { margin-top: 6px; font-size: 13px; opacity: 0.6; }
.se-grid { display: grid; grid-template-columns: 380px 1fr; gap: 16px; align-items: start; }
.se-grid { display: grid; grid-template-columns: 380px 1fr 76px; gap: 16px; align-items: start; }
@media (max-width: 900px) { .se-grid { grid-template-columns: 1fr; } }
.se-ctrl { background: #fff; border: 1px solid rgba(128,128,128,0.18); border-radius: 12px; padding: 16px; display: flex; flex-direction: column; gap: 14px; box-shadow: 0 1px 4px rgba(0,0,0,0.04); }
+20 -2
View File
@@ -2,6 +2,8 @@
import { onUnmounted, ref } from 'vue';
import { useHead } from '@vueuse/head';
import { licenseHeaders } from '@/tools/license/license';
import ImgHist from '@/tools/img-hist/ImgHist.vue';
import { authHdr } from '@/tools/img-hist/img-hist';
useHead({ title: 'AI 换脸 - IT-TOOLS-PRO' });
@@ -10,6 +12,7 @@ const dstUrl = ref('');
const srcFile = ref<File | null>(null);
const dstFile = ref<File | null>(null);
const consent = ref(false);
const histRef = ref<InstanceType<typeof ImgHist> | null>(null);
const busy = ref(false);
const error = ref('');
const resultUrl = ref('');
@@ -71,7 +74,7 @@ async function doSwap() {
try {
const res = await fetch('/relay/ai/face-swap', {
method: 'POST',
headers: licenseHeaders('face-swap'),
headers: { ...licenseHeaders('face-swap'), ...authHdr() },
body: fd,
signal: ctrl.signal,
});
@@ -84,6 +87,7 @@ async function doSwap() {
if (!resultUrl.value) {
throw new Error('服务端未返回结果图片');
}
histRef.value?.reload();
}
catch (e: any) {
error.value = e?.name === 'AbortError' ? '处理超时,请稍后重试' : String(e?.message || e);
@@ -118,6 +122,7 @@ onUnmounted(() => {
<template>
<div class="fs-root">
<div class="fs-main">
<div class="fs-head">
<h1>🎭 AI 换脸</h1>
<span class="fs-note">insightface 人脸检测 + inswapper 本地 CPU 推理 · 照片不离开服务器</span>
@@ -184,15 +189,28 @@ onUnmounted(() => {
<p class="fs-tips">
提示:两张图都需包含清晰人脸;源脸与目标脸角度、光线越接近效果越好。图片仅在服务器本地处理,不对外分享。
</p>
</div>
<ImgHist ref="histRef" kind="face-swap" />
</div>
</template>
<style scoped>
.fs-root {
display: flex;
flex-direction: row;
gap: 12px;
padding: 8px 4px;
align-items: flex-start;
}
.fs-main {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 16px;
padding: 8px 4px;
}
@media (max-width: 760px) {
.fs-root { flex-direction: column; }
}
.fs-head {
display: flex;
+171
View File
@@ -0,0 +1,171 @@
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { loadImgHist, type HistItem } from './img-hist';
/**
* 图片历史右栏(铁规则统一实现):
* 50×50 缩略图右侧竖排、点击查看大图、按本人隔离(登录=账号/未登录=机器码)。
* 父级把本组件放在布局最右侧即可;生成成功后调用父组件暴露的 reload()。
*/
const props = withDefaults(defineProps<{ kind: string; label?: string }>(), {
label: '历史',
});
const items = ref<HistItem[]>([]);
const viewUrl = ref('');
async function reload() {
items.value = await loadImgHist(props.kind);
}
defineExpose({ reload });
onMounted(reload);
</script>
<template>
<aside class="ih">
<div class="ih-t">
{{ label }}<em v-if="items.length">{{ items.length }}</em>
</div>
<div v-if="items.length" class="ih-list">
<img
v-for="it in items"
:key="it.id"
:src="it.img_url"
:title="it.prompt || '点击查看大图'"
class="ih-thumb"
@click="viewUrl = it.img_url"
>
</div>
<div v-else class="ih-empty">
还没有<br>生成记录
</div>
</aside>
<div v-if="viewUrl" class="ih-view" @click="viewUrl = ''">
<img :src="viewUrl" alt="历史图片">
<span class="ih-view-tip">点击任意处关闭</span>
</div>
</template>
<style scoped lang="less">
.ih {
flex: 0 0 76px;
width: 76px;
border: 1px solid rgba(128, 128, 128, 0.25);
border-radius: 12px;
background: rgba(128, 128, 128, 0.04);
display: flex;
flex-direction: column;
overflow: hidden;
align-self: flex-start;
max-height: calc(100vh - 230px);
.ih-t {
font-size: 11.5px;
font-weight: 700;
text-align: center;
padding: 9px 4px 7px;
border-bottom: 1px solid rgba(128, 128, 128, 0.18);
opacity: 0.75;
flex-shrink: 0;
em {
font-style: normal;
color: #0ea5a0;
margin-left: 4px;
}
}
.ih-list {
flex: 1;
overflow-y: auto;
overflow-x: hidden;
padding: 9px 13px 12px;
display: flex;
flex-direction: column;
align-items: center;
gap: 8px;
}
.ih-thumb {
width: 50px;
height: 50px;
object-fit: cover;
border-radius: 7px;
border: 2px solid transparent;
cursor: zoom-in;
background: #fff;
box-shadow: 0 1px 5px rgba(0, 0, 0, 0.1);
transition: all 0.15s;
display: block;
flex-shrink: 0;
&:hover {
border-color: #0ea5a0;
transform: translateY(-1px);
}
}
.ih-empty {
font-size: 11px;
text-align: center;
opacity: 0.45;
padding: 16px 4px;
line-height: 1.6;
}
}
.ih-view {
position: fixed;
inset: 0;
z-index: 9999;
background: rgba(0, 0, 0, 0.86);
display: flex;
align-items: center;
justify-content: center;
cursor: zoom-out;
img {
max-width: 92vw;
max-height: 88vh;
object-fit: contain;
border-radius: 8px;
box-shadow: 0 8px 40px rgba(0, 0, 0, 0.5);
}
.ih-view-tip {
position: absolute;
bottom: 26px;
left: 0;
right: 0;
text-align: center;
color: rgba(255, 255, 255, 0.65);
font-size: 12px;
}
}
@media (max-width: 900px) {
.ih {
flex: none;
width: 100%;
flex-direction: row;
align-items: center;
max-height: none;
.ih-t {
border-bottom: none;
border-right: 1px solid rgba(128, 128, 128, 0.18);
padding: 8px 10px;
flex-shrink: 0;
}
.ih-list {
flex-direction: row;
overflow-x: auto;
overflow-y: hidden;
padding: 8px;
}
}
}
</style>
+102
View File
@@ -0,0 +1,102 @@
import { getMachineId } from '@/tools/license/license';
/**
* 图片历史共享层(铁规则):
* - 历史右栏 50×50 缩略图竖排 + 点击查看大图(ImgHist.vue)
* - 按本人隔离:登录带 Authorization(服务端按账号归属过滤),未登录按机器码
* - 生成结果保存到服务器后台「存储设置」目录(/relay/ai/img-save → DATA_DIR/gen_images)
* 历史拉取/保存失败一律静默,不阻断生成与下载。
*/
/** 登录态 Authorization(无登录返回空对象) */
export function authHdr(): Record<string, string> {
try {
const a = JSON.parse(localStorage.getItem('it-tools-auth') ?? 'null');
if (a && typeof a.token === 'string' && a.token) {
const h: Record<string, string> = {};
h['Authorization'] = 'Bearer ' + a.token;
return h;
}
}
catch { /* ignore */ }
return {};
}
export interface HistItem {
id: string;
at: number;
model?: string;
prompt?: string;
kind?: string;
img_url: string;
w?: number;
h?: number;
}
/** 拉取本人某 kind 的图片历史(静默失败返回 []) */
export async function loadImgHist(kind: string): Promise<HistItem[]> {
try {
const url = `/relay/ai/img-history?machine=${encodeURIComponent(getMachineId())}&kind=${encodeURIComponent(kind)}`;
const res = await fetch(url, { headers: authHdr() });
const j = await res.json();
// 铁规则:所有功能历史最多显示 100 条(服务端已截断,此处兜底)
if (j.code === 200 && Array.isArray(j.data)) return j.data.slice(0, 100);
}
catch { /* 静默 */ }
return [];
}
export interface SaveImgOpts {
kind: string;
tool: string;
b64: string;
model?: string;
prompt?: string;
}
/** 保存生成结果到服务器(后台 storage_root/gen_images),静默失败返回 false */
export async function saveImgHist(o: SaveImgOpts): Promise<boolean> {
try {
const h = authHdr();
h['Content-Type'] = 'application/json';
const res = await fetch('/relay/ai/img-save', {
method: 'POST',
headers: h,
body: JSON.stringify({
machine: getMachineId(),
b64: o.b64,
kind: o.kind,
tool: o.tool,
model: o.model || '',
prompt: o.prompt || '',
}),
});
const j = await res.json().catch(() => ({}));
return j.code === 200;
}
catch { /* 静默,不阻断下载 */ }
return false;
}
/** Blob → 纯 base64(不含 data: 前缀) */
export function blobToB64(blob: Blob): Promise<string> {
return new Promise((resolve) => {
try {
const fr = new FileReader();
fr.onload = () => {
const s = String(fr.result || '');
resolve(s.includes(',') ? s.split(',', 2)[1] : s);
};
fr.onerror = () => resolve('');
fr.readAsDataURL(blob);
}
catch {
resolve('');
}
});
}
/** dataURL → 纯 base64 */
export function dataUrlToB64(u: string): string {
return u.includes(',') ? u.split(',', 2)[1] : u;
}
+70 -2
View File
@@ -1,6 +1,7 @@
<script setup lang="ts">
import { ref, computed, onMounted, onBeforeUnmount } from 'vue';
import { getMachineId, licenseHeaders } from '@/tools/license/license';
import { authHdr } from '@/tools/img-hist/img-hist';
import {
POSTER_TEMPLATES, POSTER_CATS, BG_PRESETS, POSTER_W, POSTER_H,
type PosterTemplate, type PosterBg, type PosterImageLayer,
@@ -28,6 +29,21 @@ const model = ref('');
const genBusy = ref(false);
const bgPrompt = ref('');
const exporting = ref(false);
// ---------- 生成历史(服务端落盘,右侧 50×50 缩略图竖排) ----------
const hist = ref<{ id: string; img_url: string; prompt?: string; kind?: string; at?: number }[]>([]);
const histBusy = ref(false);
const histView = ref(''); // 大图查看(点击缩略图打开,点空白关闭)
async function loadHist() {
histBusy.value = true;
try {
const res = await fetch(`/relay/ai/img-history?machine=${encodeURIComponent(getMachineId())}&kind=poster`, {
headers: { ...licenseHeaders('poster-maker'), ...authHdr() },
});
const j = await res.json().catch(() => ({}) as any);
// 铁规则:所有功能历史最多显示 100 条
if (res.ok && j.code === 200 && Array.isArray(j.data)) hist.value = j.data.slice(0, 100);
} catch { /* 历史拉取失败静默,不影响编辑 */ } finally { histBusy.value = false; }
}
let uid = 0;
let ro: ResizeObserver | null = null;
let scRO: ResizeObserver | null = null;
@@ -203,14 +219,15 @@ async function genFor(l: PosterImageLayer) {
else if (ar < 0.8) { width = 1024; height = 1792; }
const res = await fetch('/relay/ai/gen-image', {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...licenseHeaders('poster-maker') },
body: JSON.stringify({ machine: getMachineId(), prompt, model: model.value, width, height }),
headers: { 'Content-Type': 'application/json', ...licenseHeaders('poster-maker'), ...authHdr() },
body: JSON.stringify({ machine: getMachineId(), prompt, model: model.value, width, height, kind: 'poster' }),
});
const j = await res.json().catch(() => ({}) as any);
if (!res.ok || j.code !== 200) throw new Error(j.message || `HTTP ${res.status}`);
const url = j.data?.img_url || (j.data?.b64 ? b64DataUrl(j.data.b64) : '') || j.data?.url || '';
if (!url) throw new Error('未返回图片');
l.src = url;
loadHist(); // 服务端已落盘,刷新右侧历史
} catch (err: any) {
pmError.value = 'AI 生成失败:' + (err?.message || String(err));
} finally {
@@ -369,6 +386,21 @@ async function exportPng() {
a.download = `${cur.value?.name || '海报'}.png`;
a.click();
setTimeout(() => URL.revokeObjectURL(a.href), 8000);
// 同步保存到服务器后台存储目录(后台「存储设置」的 gen_images),失败不阻断下载
try {
const b64 = await new Promise<string>((res, rej) => {
const fr = new FileReader();
fr.onload = () => res(String(fr.result || ''));
fr.onerror = () => rej(new Error('读取失败'));
fr.readAsDataURL(blob);
});
await fetch('/relay/ai/img-save', {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...licenseHeaders('poster-maker'), ...authHdr() },
body: JSON.stringify({ machine: getMachineId(), b64, kind: 'poster', model: 'AI海报', prompt: cur.value?.name || '海报导出' }),
});
loadHist();
} catch { /* 保存失败不影响本地下载 */ }
} catch (err: any) {
pmError.value = '导出失败:' + (err?.message || String(err));
} finally {
@@ -378,6 +410,7 @@ async function exportPng() {
onMounted(async () => {
selectTemplate(POSTER_TEMPLATES[0]);
loadHist();
measure();
fit();
ro = new ResizeObserver(fit);
@@ -610,6 +643,26 @@ onBeforeUnmount(() => {
</div>
<div v-else class="pm-tip">点击画布中的元素进行编辑,拖动可移动位置;右侧图层可排序、删除。</div>
</aside>
<!-- 最右:生成历史(50×50 缩略图竖排,点击查看大图) -->
<aside class="pm-hist">
<div class="pm-hist-t">历史<em v-if="hist.length">{{ hist.length }}</em></div>
<div v-if="hist.length" class="pm-hist-list">
<img
v-for="it in hist" :key="it.id"
class="pm-hist-thumb"
:src="it.img_url"
:title="it.prompt || '点击查看大图'"
@click="histView = it.img_url"
/>
</div>
<div v-else class="pm-hist-empty">还没有<br />生成记录</div>
</aside>
</div>
<!-- 大图查看 -->
<div v-if="histView" class="pm-hist-view" @click="histView = ''">
<img :src="histView" alt="生成图片大图" />
</div>
</div>
</template>
@@ -654,6 +707,17 @@ onBeforeUnmount(() => {
/* 面板 */
.pm-panel { width: 316px; flex-shrink: 0; min-height: 0; overflow-y: auto; display: flex; flex-direction: column; gap: 14px; }
/* 生成历史(右栏 76px,50×50 缩略图竖排) */
.pm-hist { width: 76px; flex-shrink: 0; min-height: 0; display: flex; flex-direction: column; gap: 6px; }
.pm-hist-t { font-size: 12px; font-weight: 700; opacity: .75; text-align: center; }
.pm-hist-t em { font-style: normal; color: #3b82f6; margin-left: 3px; }
.pm-hist-list { flex: 1; min-height: 0; overflow-y: auto; display: flex; flex-direction: column; align-items: center; gap: 6px; padding-bottom: 8px; }
.pm-hist-thumb { width: 50px; height: 50px; object-fit: cover; border-radius: 8px; cursor: zoom-in; border: 2px solid transparent; background: rgba(127,127,127,.12); flex-shrink: 0; transition: border-color .15s; }
.pm-hist-thumb:hover { border-color: #3b82f6; }
.pm-hist-empty { font-size: 11px; opacity: .55; text-align: center; line-height: 1.6; padding-top: 10px; }
.pm-hist-view { position: fixed; inset: 0; z-index: 9999; background: rgba(0,0,0,.78); display: flex; align-items: center; justify-content: center; cursor: zoom-out; padding: 24px; }
.pm-hist-view img { max-width: 92vw; max-height: 92vh; object-fit: contain; border-radius: 8px; background: #fff; box-shadow: 0 10px 40px rgba(0,0,0,.4); }
.pm-sec { padding: 10px 12px; border: 1px solid var(--n-border-color, #e5e5e5); border-radius: 10px; background: rgba(127,127,127,.04); }
.pm-bgs { display: grid; grid-template-columns: repeat(8, 1fr); gap: 6px; }
.pm-bg-sw { height: 26px; border-radius: 6px; border: 1px solid rgba(127,127,127,.35); cursor: pointer; }
@@ -682,5 +746,9 @@ onBeforeUnmount(() => {
.pm-tpls, .pm-panel { width: 100%; max-height: none; overflow: visible; }
.pm-stage { flex: none; height: 56vh; }
.pm-tpl-grid { grid-template-columns: repeat(4, 1fr); }
/* 窄屏:历史栏改为横排(缩略图仍 50×50) */
.pm-hist { width: 100%; flex-direction: row; align-items: center; gap: 8px; }
.pm-hist-t { flex-shrink: 0; }
.pm-hist-list { flex-direction: row; overflow-x: auto; overflow-y: hidden; padding-bottom: 0; }
}
</style>
+31 -7
View File
@@ -1,12 +1,21 @@
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { useHead } from '@vueuse/head';
import GenHistory from '@/tools/gen-history/GenHistory.vue';
import { useGenHistory } from '@/tools/gen-history/gen-history';
import ImgHist from '@/tools/img-hist/ImgHist.vue';
import { blobToB64, saveImgHist } from '@/tools/img-hist/img-hist';
useHead({ title: '文字生成图片 - IT-TOOLS-PRO' });
const genHist = useGenHistory('text-to-image');
const histRef = ref<InstanceType<typeof ImgHist> | null>(null);
/** 生成结果保存到服务器历史(失败静默,不影响本地下载) */
async function persist(b64: string) {
try {
const ok = await saveImgHist({ kind: 'text-to-image', tool: 'text-to-image', b64, model: '文字生成图片', prompt: (text.value || '').slice(0, 100) });
if (ok) histRef.value?.reload();
}
catch { /* 静默 */ }
}
const text = ref('在线免费文字生成图片工具\nIT-TOOLS-PRO 让你更高效地工作\n如果你觉得这个工具好用,可以分享给你的小伙伴们');
const format = ref<'png' | 'jpg'>('png');
@@ -36,7 +45,7 @@ const generated = ref(false);
const resultUrl = ref('');
const resultSize = ref(0);
function render(toBlob = false) {
function render(toBlob = false, save = false) {
const c = canvas.value;
if (!c) {
return;
@@ -66,13 +75,15 @@ function render(toBlob = false) {
}
resultUrl.value = URL.createObjectURL(blob);
resultSize.value = blob.size;
if (save) {
blobToB64(blob).then((b64) => { if (b64) persist(b64); });
}
}, mime, 0.92);
}
}
function download() {
render(true);
genHist.add({ title: `文字生成图片: ${text.value.slice(0, 20)}`, detail: `${width.value}×${height.value} ${format.value.toUpperCase()} · ${fontSize.value}px` });
setTimeout(() => {
const a = document.createElement('a');
a.href = resultUrl.value;
@@ -105,6 +116,7 @@ onMounted(() => {
<template>
<div class="ti-root">
<div class="ti-main">
<div class="ti-panel">
<div class="ti-panel-title">📝 文本内容</div>
<textarea v-model="text" class="ti-textarea" rows="6" placeholder="输入要生成图片的文字,支持多行…" @input="render()" />
@@ -175,7 +187,7 @@ onMounted(() => {
</div>
<div class="ti-btns">
<button class="ti-btn" @click="render(true)">
<button class="ti-btn" @click="render(true, true)">
🚀 生成
</button>
<button class="ti-btn ti-btn-ghost" :disabled="!resultUrl" @click="download">
@@ -197,13 +209,25 @@ onMounted(() => {
</div>
</div>
<GenHistory tool="text-to-image" label="生成记录" class="mt-10px" />
</div>
<ImgHist ref="histRef" kind="text-to-image" />
</div>
</template>
<style lang="less" scoped>
.ti-root {
padding-bottom: 40px;
display: flex;
flex-direction: row;
gap: 12px;
align-items: flex-start;
}
.ti-main {
flex: 1;
min-width: 0;
}
@media (max-width: 760px) {
.ti-root { flex-direction: column; }
}
.ti-panel {