feat(ai-gen): 自定义提供商转发 + 生成图落盘历史端点
- POST /ai/custom-models: 测试 OpenAI 兼容提供商并拉取模型(KEY仅请求透传不落盘) - POST /ai/gen-image: 可选 provider 字段 → _provider_images_gen 用用户 base_url+KEY 直连上游 - 生成成功落盘 DATA_DIR/gen_images/<machine>/ + index.json(每机100张超限清旧, thread lock) - GET /ai/img-history?machine= 历史列表; GET /ai/img/<m>/<id>[?dl=1] 图片文件/附件下载 - 图片文件端点从尾部解析路径段(兼容 nginx 剥 /relay 前缀与直连两条链路)
This commit is contained in:
1 parent
b30ffda52e
commit
cf4e57cf79
1 file changed
+227
-3
@@ -34,6 +34,8 @@ from urllib import parse, request
|
||||
|
||||
import mcp_ops
|
||||
|
||||
GEN_IMG_LOCK = threading.Lock()
|
||||
|
||||
UPSTREAM = "https://translate.googleapis.com/translate_a/single"
|
||||
PROXY = os.environ.get("HTTPS_PROXY") or os.environ.get("https_proxy") or ""
|
||||
TIMEOUT = float(os.environ.get("RELAY_TIMEOUT", "25"))
|
||||
@@ -1947,6 +1949,12 @@ class Handler(BaseHTTPRequestHandler):
|
||||
if parsed.path == "/ai/image-models":
|
||||
self._handle_image_models()
|
||||
return
|
||||
if parsed.path == "/ai/img-history":
|
||||
self._handle_img_history()
|
||||
return
|
||||
if parsed.path.startswith("/ai/img/"):
|
||||
self._handle_img_file(parsed)
|
||||
return
|
||||
if parsed.path == "/ai/models":
|
||||
self._handle_ai_models()
|
||||
return
|
||||
@@ -2950,6 +2958,9 @@ class Handler(BaseHTTPRequestHandler):
|
||||
if parsed.path == "/ai/models":
|
||||
self._handle_ai_models()
|
||||
return
|
||||
if parsed.path == "/ai/custom-models":
|
||||
self._handle_custom_models()
|
||||
return
|
||||
if parsed.path == "/ai/gen-image":
|
||||
self._handle_gen_image()
|
||||
return
|
||||
@@ -3088,7 +3099,7 @@ class Handler(BaseHTTPRequestHandler):
|
||||
b64 = item.get("b64_json") or ""
|
||||
if not url and not b64:
|
||||
raise RuntimeError("上游未返回图片")
|
||||
self._reply(200, json.dumps({"code": 200, "message": "ok", "data": {"url": url, "b64": b64}}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
self._reply(200, json.dumps({"code": 200, "message": "ok", "data": {"url": url, "b64": b64, "img_url": (d.get("img_url") or "") if isinstance(d, dict) else ""}}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
|
||||
def _handle_image_models(self):
|
||||
try:
|
||||
@@ -3098,6 +3109,210 @@ class Handler(BaseHTTPRequestHandler):
|
||||
models = []
|
||||
self._reply(200, json.dumps({"code": 200, "message": "ok", "data": models}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
|
||||
# ---------- AI 生图:自定义提供商 + 历史落盘 ----------
|
||||
@staticmethod
|
||||
def _gen_machine_ok(machine):
|
||||
return bool(re.fullmatch(r"[A-Za-z0-9_-]{4,64}", machine or ""))
|
||||
|
||||
def _provider_images_gen(self, provider, model, prompt, size):
|
||||
"""用用户自己的 base_url + API KEY 走 OpenAI 兼容 images 接口(KEY 仅请求透传,不落盘)。"""
|
||||
base = str(provider.get("base_url") or "").strip().rstrip("/")
|
||||
if not base.startswith(("http://", "https://")):
|
||||
raise RuntimeError("接口地址必须以 http(s):// 开头")
|
||||
if base.endswith("/v1"):
|
||||
url = base + "/images/generations"
|
||||
elif base.endswith("/images/generations"):
|
||||
url = base
|
||||
else:
|
||||
url = base + "/v1/images/generations"
|
||||
body = json.dumps({"model": model, "prompt": prompt, "n": 1, "size": size}).encode("utf-8")
|
||||
key = str(provider.get("api_key") or "").strip()
|
||||
req = request.Request(url, data=body, headers={
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": "Bearer " + key,
|
||||
"User-Agent": "Mozilla/5.0",
|
||||
})
|
||||
with request.urlopen(req, timeout=120) as resp:
|
||||
d = json.loads(resp.read().decode("utf-8", "replace"))
|
||||
if isinstance(d, dict) and d.get("data"):
|
||||
return d
|
||||
msg = ""
|
||||
if isinstance(d, dict):
|
||||
err = d.get("error")
|
||||
if isinstance(err, dict):
|
||||
msg = str(err.get("message") or "")
|
||||
else:
|
||||
msg = str(err or d.get("message") or "")
|
||||
raise RuntimeError(msg[:300] or "上游未返回图片")
|
||||
|
||||
def _persist_gen_image(self, machine, d, model, prompt, w, h):
|
||||
"""把生成结果落盘并写入该机器的历史索引;返回站内图片 URL(任何失败返回空串)。"""
|
||||
try:
|
||||
if not self._gen_machine_ok(machine):
|
||||
return ""
|
||||
items = (d or {}).get("data") or []
|
||||
if not items:
|
||||
return ""
|
||||
item = items[0] if isinstance(items[0], dict) else {}
|
||||
raw = None
|
||||
if item.get("b64_json"):
|
||||
import base64 as _b64
|
||||
raw = _b64.b64decode(item["b64_json"])
|
||||
elif item.get("url"):
|
||||
ureq = request.Request(item["url"], headers={"User-Agent": "Mozilla/5.0"})
|
||||
with request.urlopen(ureq, timeout=60) as rr:
|
||||
raw = rr.read()
|
||||
if not raw or len(raw) < 200:
|
||||
return ""
|
||||
if raw[:8] == b"\x89PNG\r\n\x1a\n":
|
||||
ext = ".png"
|
||||
elif raw[:2] == b"\xff\xd8":
|
||||
ext = ".jpg"
|
||||
elif raw[:6] in (b"GIF87a", b"GIF89a"):
|
||||
ext = ".gif"
|
||||
elif len(raw) > 12 and raw[8:12] == b"WEBP":
|
||||
ext = ".webp"
|
||||
else:
|
||||
ext = ".png"
|
||||
gen_dir = os.path.join(DATA_DIR, "gen_images", machine)
|
||||
os.makedirs(gen_dir, exist_ok=True)
|
||||
iid = f"{int(time.time())}_{uuid.uuid4().hex[:8]}"
|
||||
fname = iid + ext
|
||||
with open(os.path.join(gen_dir, fname), "wb") as f:
|
||||
f.write(raw)
|
||||
idx_path = os.path.join(gen_dir, "index.json")
|
||||
with GEN_IMG_LOCK:
|
||||
idx = []
|
||||
if os.path.exists(idx_path):
|
||||
try:
|
||||
idx = json.load(open(idx_path, encoding="utf-8"))
|
||||
if not isinstance(idx, list):
|
||||
idx = []
|
||||
except Exception:
|
||||
idx = []
|
||||
idx.insert(0, {"id": iid, "file": fname, "at": int(time.time()),
|
||||
"model": str(model)[:60], "prompt": str(prompt)[:500],
|
||||
"w": w, "h": h})
|
||||
while len(idx) > 100:
|
||||
old = idx.pop() or {}
|
||||
fn = str(old.get("file") or "")
|
||||
if fn and "/" not in fn and "\\" not in fn:
|
||||
try:
|
||||
os.remove(os.path.join(gen_dir, fn))
|
||||
except Exception:
|
||||
pass
|
||||
with open(idx_path, "w", encoding="utf-8") as f:
|
||||
json.dump(idx, f, ensure_ascii=False)
|
||||
return f"/relay/ai/img/{machine}/{iid}"
|
||||
except Exception as e: # noqa: BLE001
|
||||
print(f"[ai-gen] persist failed: {e}", flush=True)
|
||||
return ""
|
||||
|
||||
def _handle_custom_models(self):
|
||||
"""测试用户的 OpenAI 兼容提供商并拉取模型列表(KEY 只进本次请求头,不落盘)。"""
|
||||
payload = self._read_payload()
|
||||
machine = str(payload.get("machine") or "")
|
||||
if check(machine, "ai-gen") != 200:
|
||||
self._reply(403, json.dumps({"code": 403, "message": "需要授权或今日免费试用已用完"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
base = str(payload.get("base_url") or "").strip().rstrip("/")
|
||||
key = str(payload.get("api_key") or "").strip()
|
||||
if not base.startswith(("http://", "https://")):
|
||||
self._reply(400, json.dumps({"code": 400, "message": "接口地址必须以 http(s):// 开头"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
if not key:
|
||||
self._reply(400, json.dumps({"code": 400, "message": "请填写 API KEY"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
if base.endswith("/v1"):
|
||||
url = base + "/models"
|
||||
elif base.endswith("/models"):
|
||||
url = base
|
||||
else:
|
||||
url = base + "/v1/models"
|
||||
req = request.Request(url, headers={"Authorization": "Bearer " + key, "User-Agent": "Mozilla/5.0"})
|
||||
try:
|
||||
with request.urlopen(req, timeout=20) as resp:
|
||||
d = json.loads(resp.read().decode("utf-8", "replace"))
|
||||
except Exception as e: # noqa: BLE001
|
||||
msg = str(e)
|
||||
if isinstance(e, request.HTTPError):
|
||||
try:
|
||||
msg = e.read().decode("utf-8", "replace")[:300]
|
||||
except Exception:
|
||||
pass
|
||||
self._reply(502, json.dumps({"code": 502, "message": f"连接失败:{msg}"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
items = d.get("data") if isinstance(d, dict) else None
|
||||
ids = [str(m.get("id")) for m in (items or []) if isinstance(m, dict) and m.get("id")]
|
||||
if not ids:
|
||||
self._reply(502, json.dumps({"code": 502, "message": "上游未返回模型列表(请确认接口地址为 OpenAI 兼容格式)"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
self._reply(200, json.dumps({"code": 200, "message": "ok", "data": ids[:200]}, 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 "")
|
||||
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):
|
||||
try:
|
||||
items = json.load(open(idx_path, encoding="utf-8"))
|
||||
if not isinstance(items, list):
|
||||
items = []
|
||||
except Exception:
|
||||
items = []
|
||||
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")
|
||||
|
||||
def _handle_img_file(self, parsed):
|
||||
# 兼容两条链路:直连 relay(/relay/ai/img/m/id)与经 nginx(/ai/img/m/id)
|
||||
parts = parsed.path.split("/")
|
||||
if len(parts) < 5 or parts[-3] != "img":
|
||||
self._reply(404, b"not found")
|
||||
return
|
||||
machine, iid = parts[-2], parts[-1]
|
||||
if not self._gen_machine_ok(machine) or not re.fullmatch(r"[A-Za-z0-9_\-]{4,64}", iid or ""):
|
||||
self._reply(404, b"not found")
|
||||
return
|
||||
gen_dir = os.path.join(DATA_DIR, "gen_images", machine)
|
||||
found = None
|
||||
if os.path.isdir(gen_dir):
|
||||
for fn in os.listdir(gen_dir):
|
||||
if fn.startswith(iid + ".") and os.path.isfile(os.path.join(gen_dir, fn)):
|
||||
found = os.path.join(gen_dir, fn)
|
||||
break
|
||||
if not found:
|
||||
self._reply(404, b"not found")
|
||||
return
|
||||
ext = os.path.splitext(found)[1].lower()
|
||||
ctype = {".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg",
|
||||
".gif": "image/gif", ".webp": "image/webp"}.get(ext, "image/png")
|
||||
try:
|
||||
with open(found, "rb") as f:
|
||||
raw = f.read()
|
||||
except Exception:
|
||||
self._reply(404, b"not found")
|
||||
return
|
||||
qs = parse.parse_qs(parsed.query)
|
||||
dl = str((qs.get("dl") or [""])[0] or "")
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", ctype)
|
||||
self.send_header("Content-Length", str(len(raw)))
|
||||
self.send_header("Cache-Control", "private, max-age=86400")
|
||||
if dl == "1":
|
||||
self.send_header("Content-Disposition", f'attachment; filename="{iid}{ext}"')
|
||||
self.end_headers()
|
||||
try:
|
||||
self.wfile.write(raw)
|
||||
except (BrokenPipeError, ConnectionResetError):
|
||||
pass
|
||||
|
||||
def _handle_gen_image(self):
|
||||
payload = self._read_payload()
|
||||
machine = str(payload.get("machine") or "")
|
||||
@@ -3116,12 +3331,21 @@ class Handler(BaseHTTPRequestHandler):
|
||||
w, h = 1024, 1024
|
||||
w = max(16, min(2048, w))
|
||||
h = max(16, min(2048, h))
|
||||
provider = payload.get("provider") if isinstance(payload.get("provider"), dict) else None
|
||||
try:
|
||||
d = self._nm_images_gen(model, prompt, f"{w}x{h}")
|
||||
self._img_reply_ok(d)
|
||||
if provider and str(provider.get("base_url") or "").strip() and str(provider.get("api_key") or "").strip():
|
||||
d = self._provider_images_gen(provider, model, prompt, f"{w}x{h}")
|
||||
else:
|
||||
d = self._nm_images_gen(model, prompt, f"{w}x{h}")
|
||||
except Exception as e: # noqa: BLE001
|
||||
print(f"[img] gen failed: {e}", flush=True)
|
||||
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)
|
||||
if isinstance(d, dict) and img_url:
|
||||
d["img_url"] = img_url
|
||||
self._img_reply_ok(d)
|
||||
|
||||
def _handle_edit_image(self):
|
||||
machine = self.headers.get("X-Machine-Id", "")
|
||||
|
||||
Reference in new issue
Block a user