feat: 历史记录100条上限 — img-history vis[:100](原150)、mcp-usage 流水 LIMIT 100(原300);含 admin/files 全量聚合分页收口
This commit is contained in:
1 parent
b33b149555
commit
2141d6fd82
2 files changed
+387
-27
No files matched your search
+2
-1
@@ -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()
|
||||
|
||||
@@ -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")
|
||||
|
||||
|
||||
Reference in new issue
Block a user