feat: AI生图额度按上游真实配额展示——下拉标注CF 173张/日与Pollinations按Key余额、文案双上游联动、已授权显示共享池剩余、tooltip官方出处

This commit is contained in:
jinghui committed 2026-11-13 09:43:31 +08:00
1 parent b4e5d6ac6d
commit eefdc07786
3 files changed
+159 -38

No files matched your search

+8 -2
View File
@@ -58,12 +58,18 @@
### AI 生图:自定义提供商 + 生成历史(2026.11 新增)
- **模型来源与免费说明**:站内 10 个生图模型全部经自建 NewAPI 网关聚合——5 个 `pollinations-*` 走 Pollinations.ai(完全免费、无需 KEY),4 个 `flux*` + `dall-e-3` 走 Cloudflare Workers AI(站主账号承担免费额度),**对使用者全部免费**;模型列表由后端从网关实时拉取。
- **模型来源与免费说明**:站内 10 个生图模型全部经自建 NewAPI 网关聚合——5 个 `pollinations-*` 走 Pollinations.ai(站主 API Key 预算制、对使用者免费),4 个 `flux*` + `dall-e-3` 走 Cloudflare Workers AI(站主账号免费额度,官方 10,000 Neurons/天 ≈ **173 张/天**),**对使用者全部免费但共享池有限**;模型列表由后端从网关实时拉取,下拉标注各上游配额。
- **我的提供商**:左侧「或使用自己的提供商 / API KEY」展开,填写 OpenAI 兼容接口地址 + KEY,点「连接并拉取模型」自动拉取上游模型列表;与站内模型合并展示(下拉分组「站内免费模型 / 我的模型」,自定义模型胶囊为紫色虚线框)。支持手动输入模型名回车添加、单个移除、一键清除。
- **KEY 只存本地**:接口地址与 KEY 仅保存在浏览器 localStorage(`it-tools-ai-provider`),生成时临时发给后端转发,**不入库、不落盘**(已 grep 宿主与容器数据目录验证零残留)。
- **生成历史**:每次生成成功自动落盘服务端(按机器隔离,每机上限 100 张、超限自动清理最旧),页面右侧新增 50×50 缩略图竖排历史列;点击任意缩略图回看大图,「下载图片」带 `?dl=1` 触发附件下载,「新窗口打开」直连原图,刷新后历史仍在。
- **新增端点**:`POST /relay/ai/custom-models`(测试连接并拉取模型)、`POST /relay/ai/gen-image` 扩展可选 `provider` 字段(自定义提供商转发)、`GET /relay/ai/img-history?machine=`(历史列表)、`GET /relay/ai/img/<machine>/<id>[?dl=1]`(图片文件/下载)。
- **内置免费每日次数**(2026.11 新增):「模型」区右侧实时显示额度说明——未授权用户每日 **10 次**(`DAILY_FREE_LIMIT` 环境变量可调,北京时间 0 点重置),**生成成功才扣次**;卡密已授权不限次;**自带提供商/KEY 生成不计次**。次数用完点「或使用自己的提供商 / API KEY」用自己的 KEY 继续生成,403 提示文案同步引导。额度查询端点 `POST /relay/ai/quota`(返回 `authorized/limit/used/remaining`,`remaining=-1` 表示不限)。
- **内置免费每日次数 + 上游真实免费配额**(2026.11 新增;2026.11.13 按上游官方/实测补真实数字):「模型」区右侧实时显示、模型下拉每个选项标注上游配额、鼠标悬停显示出处——
- **机器限额**:未授权每日 **10 次**(`DAILY_FREE_LIMIT` 环境变量可调,北京时间 0 点重置,**生成成功才扣次**;自带提供商/KEY 生成不计次)。
- **上游免费池(全站共享,已授权同样受保护)**——内置模型上游是站主账号的免费额度,不存在「无限次」:
- `flux*` / `dall-e-3`(5 个)→ Cloudflare Workers AI:**官方免费 10,000 Neurons/天**,proxy 固定 1024×1024/4 步 = 57.6 Neurons/张 → **约 173 张/天**(`CF_DAILY_LIMIT` 默认 173,北京时间约 08:00 重置,账号级共享,超出 Free plan 直接报错);服务端按 `daily_gen_cf.json` 全站计数保护,池尽返回 403 并提示。
- `pollinations-*`(5 个)→ Pollinations.ai:站主 **API Key 预算制(pollen 余额)**,无固定每日张数(官方匿名档才是 45 秒/张按 IP);上游错误透传。
- **界面文案**(按所选模型联动):未授权 `免费10次·剩N · CF池剩X/173张` / `… · Pollinations按Key余额`;已授权 `已授权 · CF池剩X/173张`;CF 池尽红色 `CF免费池已用完 · 08:00重置`。
- 额度查询端点 `POST /relay/ai/quota`(带 `model` 返回 `authorized/limit/used/remaining` + `upstream/upstream_daily/upstream_used/upstream_remaining/upstream_note/cf_daily`;`remaining=-1` 表示机器维度不限,仍受共享池约束)。次数用完点「或使用自己的提供商 / API KEY」用自己的 KEY 继续生成,403 提示文案同步引导。
## 优势
+120 -27
View File
@@ -61,6 +61,11 @@ TRIAL_MS = int(os.environ.get("TRIAL_MS_MIN", "30")) * 60 * 1000
# AI 生图页内置免费:未授权用户每日次数(北京时间 0 点重置);自带 KEY 不计次
DAILY_FREE_LIMIT = int(os.environ.get("DAILY_FREE_LIMIT", "10"))
DAILY_FILE = os.environ.get("DAILY_FILE", "/app/data/daily_gen.json")
# Cloudflare Workers AI 免费池(flux/flux-*/dall-e-3 等内置模型的上游):
# 官方免费 10,000 Neurons/天,proxy 固定 1024x1024/4 步 = 57.6 Neurons/张 → 10000/57.6 ≈ 173 张/天
# (北京时间约 08:00 重置;账号级共享,超了 Free plan 直接报错)
CF_DAILY_LIMIT = int(os.environ.get("CF_DAILY_LIMIT", "173"))
CF_DAILY_FILE = os.environ.get("CF_DAILY_FILE", "/app/data/daily_gen_cf.json")
DAY_MS = 24 * 60 * 60 * 1000
TZ_OFFSET_MS = 8 * 60 * 60 * 1000 # 北京时间 UTC+8 —— 重置对齐自然日 0 点
PROTECTED_TOOLS = {"translator", "image-ocr", "pdf-ocr", "ai-retouch", "doc-convert", "image-tools", "pdf-tools", "video-tools", "audio-tools", "text-to-image", "ai-image-tools", "copywriting", "screenshot-qa", "video-subtitle", "ai-gen", "ai-text-edit"}
@@ -230,8 +235,8 @@ def daily_used(machine: str) -> int:
return 0
def daily_consume(machine: str) -> None:
"""内置渠道生成成功后扣一次当日免费额度。"""
def daily_consume(machine: str, model: str = "") -> None:
"""内置渠道生成成功后扣次:未授权机器计数照记;走 Cloudflare 的模型同时消耗全站共享池。"""
with _DAILY_LOCK:
d = _load_daily()
rec = d.get(machine)
@@ -244,24 +249,91 @@ def daily_consume(machine: str) -> None:
rec["day"] = _day_key()
d[machine] = rec
_save_daily(d)
if _upstream_of(model) == "cloudflare":
cf_consume()
def daily_remaining(machine: str) -> int:
return max(0, DAILY_FREE_LIMIT - daily_used(machine))
def check_gen(machine: str, own_provider: bool = False) -> int:
"""AI 生图页门禁:已授权不限次;未授权用内置渠道每日 DAILY_FREE_LIMIT 次;
own_provider=True(用户自带提供商/KEY)不消耗平台免费额度,只需机器码格式合法。"""
# ---------- 全站共享上游:Cloudflare 免费池(flux/flux-*/dall-e-3,官方 173 张/天) ----------
def _upstream_of(model: str) -> str:
"""内置模型 → 上游通道:pollinations-* 走 Pollinations(key 预算制);其余 flux/dall-e* 走 Cloudflare。"""
if (model or "").lower().startswith("pollinations"):
return "pollinations"
return "cloudflare"
def _cf_load() -> dict:
try:
with open(CF_DAILY_FILE, encoding="utf-8") as f:
d = json.load(f)
return d if isinstance(d, dict) else {}
except Exception:
return {}
def cf_used_today() -> int:
"""全站今日已消耗的 Cloudflare 免费池张数(北京时间 0 点归零;与官方 08:00 重置略有差异,取更早者保护)。"""
d = _cf_load()
if d.get("day") == _day_key():
try:
return int(d.get("n", 0))
except Exception:
return 0
return 0
def cf_consume() -> None:
with _DAILY_LOCK:
d = _cf_load()
if d.get("day") != _day_key():
d = {"day": _day_key(), "n": 0}
try:
d["n"] = int(d.get("n", 0)) + 1
except Exception:
d["n"] = 1
try:
with open(CF_DAILY_FILE, "w", encoding="utf-8") as f:
json.dump(d, f, ensure_ascii=False)
except Exception:
pass
def cf_remaining() -> int:
return max(0, CF_DAILY_LIMIT - cf_used_today())
def gen_block_reason(machine: str, own_provider: bool = False, model: str = "") -> str | None:
"""AI 生图门禁:返回 None=放行;否则返回拒绝原因码。
- own_provider=True(自带提供商/KEY):不耗平台额度,直接放行
- 未授权:每机每日 DAILY_FREE_LIMIT 次
- 内置走 Cloudflare 的模型:全站共享池 CF_DAILY_LIMIT 张/天(**已授权也保护**,上游是账号级免费池)
"""
if not machine or not MACHINE_RE.match(machine):
return 403
return "bad_machine"
if own_provider:
return 200
if machine in _load_revoked():
pass # 已吊销:按未授权计次
elif query_authorized(machine) or _account_license_ok(machine):
return 200
return 200 if daily_remaining(machine) > 0 else 403
return None
authed = machine not in _load_revoked() and (query_authorized(machine) or _account_license_ok(machine))
if not authed and daily_remaining(machine) <= 0:
return "machine_quota"
if _upstream_of(model) == "cloudflare" and cf_remaining() <= 0:
return "cf_pool"
return None
def check_gen(machine: str, own_provider: bool = False, model: str = "") -> int:
return 200 if gen_block_reason(machine, own_provider, model) is None else 403
def gen_block_message(reason: str | None) -> str:
if reason == "machine_quota":
return f"需要授权,或今日内置免费生图次数({DAILY_FREE_LIMIT} 次/天)已用完——可配置自己的 API KEY 继续生成"
if reason == "cf_pool":
return (f"今日免费生图池已用完:Cloudflare 官方免费 10,000 Neurons/天 ≈ {CF_DAILY_LIMIT} 张"
f"(北京时间约 08:00 重置,全站共享)——可配置自己的 API KEY 继续生成")
return "需要授权或今日免费试用已用完"
def deactivate_card(machine_id: str) -> tuple[int, dict]:
@@ -3294,18 +3366,36 @@ class Handler(BaseHTTPRequestHandler):
return ""
def _handle_ai_quota(self):
"""AI 生图页额度查询:授权状态 + 今日内置免费剩余次数(前端「模型」区展示)。"""
"""AI 生图页额度查询:授权状态 + 机器今日剩余 + 当前模型上游的真实免费配额。"""
payload = self._read_payload()
machine = str(payload.get("machine") or "")
model = str(payload.get("model") or "")[:60]
if not machine or not MACHINE_RE.match(machine):
self._reply(400, json.dumps({"code": 400, "message": "bad machine"}, ensure_ascii=False).encode("utf-8"), "application/json")
return
authed = machine not in _load_revoked() and (query_authorized(machine) or _account_license_ok(machine))
if authed:
data = {"authorized": True, "limit": DAILY_FREE_LIMIT, "used": 0, "remaining": -1}
else:
used = daily_used(machine)
data = {"authorized": False, "limit": DAILY_FREE_LIMIT, "used": used, "remaining": max(0, DAILY_FREE_LIMIT - used)}
used = daily_used(machine)
data = {
"authorized": authed,
"limit": DAILY_FREE_LIMIT,
"used": used if not authed else 0,
"remaining": -1 if authed else max(0, DAILY_FREE_LIMIT - used),
"cf_daily": CF_DAILY_LIMIT, # CF 免费池官方换算张数(前端模型下拉后缀用)
}
# 上游真实免费配额(按当前所选模型的通道返回,前端「模型」区如实展示)
up = _upstream_of(model) if model else ""
data["upstream"] = up
if up == "cloudflare":
data["upstream_daily"] = CF_DAILY_LIMIT
data["upstream_used"] = cf_used_today()
data["upstream_remaining"] = cf_remaining()
data["upstream_note"] = (f"Cloudflare Workers AI 官方免费 10,000 Neurons/天"
f"≈ {CF_DAILY_LIMIT} 张(1024×1024/4 步),北京时间约 08:00 重置,账号级共享")
elif up == "pollinations":
data["upstream_daily"] = None
data["upstream_used"] = None
data["upstream_remaining"] = None
data["upstream_note"] = "Pollinations 按 API Key 预算(pollen 余额)计费,无固定每日张数"
self._reply(200, json.dumps({"code": 200, "message": "ok", "data": data}, ensure_ascii=False).encode("utf-8"), "application/json")
def _handle_custom_models(self):
@@ -3416,17 +3506,18 @@ class Handler(BaseHTTPRequestHandler):
def _handle_gen_image(self):
payload = self._read_payload()
machine = str(payload.get("machine") or "")
# 先解析自带提供商:自带 KEY 不消耗平台每日免费次数
# 先解析自带提供商与模型:自带 KEY 不消耗平台额度;模型决定上游共享池判定
provider = payload.get("provider") if isinstance(payload.get("provider"), dict) else None
own_provider = bool(provider and str(provider.get("base_url") or "").strip() and str(provider.get("api_key") or "").strip())
if check_gen(machine, own_provider) != 200:
self._reply(403, json.dumps({"code": 403, "message": f"需要授权,或今日内置免费生图次数({DAILY_FREE_LIMIT} 次/天)已用完——可配置自己的 API KEY 继续生成"}, ensure_ascii=False).encode("utf-8"), "application/json")
model = str(payload.get("model") or "pollinations-flux")[:60]
reason = gen_block_reason(machine, own_provider, model)
if reason is not None:
self._reply(403, json.dumps({"code": 403, "message": gen_block_message(reason)}, ensure_ascii=False).encode("utf-8"), "application/json")
return
prompt = str(payload.get("prompt") or "").strip()[:2000]
if not prompt:
self._reply(400, json.dumps({"code": 400, "message": "请输入提示词"}, ensure_ascii=False).encode("utf-8"), "application/json")
return
model = str(payload.get("model") or "pollinations-flux")[:60]
try:
w = int(payload.get("width") or 1024)
h = int(payload.get("height") or 1024)
@@ -3439,7 +3530,7 @@ class Handler(BaseHTTPRequestHandler):
d = self._provider_images_gen(provider, model, prompt, f"{w}x{h}")
else:
d = self._nm_images_gen(model, prompt, f"{w}x{h}")
daily_consume(machine) # 内置渠道成功才扣当日免费次数
daily_consume(machine, model) # 内置渠道成功才扣次(机器计数 + CF 共享池)
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")
@@ -3452,9 +3543,6 @@ class Handler(BaseHTTPRequestHandler):
def _handle_edit_image(self):
machine = self.headers.get("X-Machine-Id", "")
if check_gen(machine, False) != 200:
self._reply(403, json.dumps({"code": 403, "message": f"需要授权,或今日内置免费生图次数({DAILY_FREE_LIMIT} 次/天)已用完——可配置自己的 API KEY 继续生成"}, ensure_ascii=False).encode("utf-8"), "application/json")
return
ctype = self.headers.get("Content-Type", "")
if "multipart/form-data" not in ctype:
self._reply(400, json.dumps({"code": 400, "message": "需要 multipart 上传"}, ensure_ascii=False).encode("utf-8"), "application/json")
@@ -3462,6 +3550,11 @@ class Handler(BaseHTTPRequestHandler):
form = cgi.FieldStorage(fp=self.rfile, headers=self.headers, environ={"REQUEST_METHOD": "POST", "CONTENT_TYPE": ctype})
prompt = str(form.getvalue("prompt") or "").strip()[:2000]
model = str(form.getvalue("model") or "dall-e-3")[:60]
# 门禁放模型解析之后:模型决定上游(Cloudflare 共享池已授权也保护)
reason = gen_block_reason(machine, False, model)
if reason is not None:
self._reply(403, json.dumps({"code": 403, "message": gen_block_message(reason)}, ensure_ascii=False).encode("utf-8"), "application/json")
return
if not prompt:
self._reply(400, json.dumps({"code": 400, "message": "请输入提示词"}, ensure_ascii=False).encode("utf-8"), "application/json")
return
@@ -3473,7 +3566,7 @@ class Handler(BaseHTTPRequestHandler):
try:
img = up.file.read()
d = self._nm_images_edit(model, prompt, img, up.filename)
daily_consume(machine) # 内置渠道成功才扣当日免费次数
daily_consume(machine, model) # 内置渠道成功才扣次(机器计数 + CF 共享池)
self._img_reply_ok(d)
except Exception as e: # noqa: BLE001
print(f"[img] edit failed: {e}", flush=True)
+31 -9
View File
@@ -138,27 +138,49 @@ const EXAMPLES = [
const canGen = computed(() => !!prompt.value.trim());
// ---------- 内置免费额度(每日次数,服务端统计;北京时间 0 点重置) ----------
const quota = ref<{ authorized: boolean; limit: number; used: number; remaining: number } | null>(null);
// ---------- 内置免费额度(机器每日次数 + 上游真实免费池;北京时间 0 点重置) ----------
const quota = ref<{
authorized: boolean; limit: number; used: number; remaining: number;
upstream?: string; upstream_daily?: number | null; upstream_used?: number | null;
upstream_remaining?: number | null; upstream_note?: string; cf_daily?: number;
} | null>(null);
const quotaText = computed(() => {
const q = quota.value;
if (!q) return '内置免费 · 有每日次数限制';
if (q.authorized) return '已授权 · 不限次数';
if (q.remaining <= 0) return `内置免费 · 每日${q.limit}次 · 今日已用完`;
return `内置免费 · 每日${q.limit}次 · 今日剩${q.remaining}次`;
if (!q.authorized && q.remaining <= 0) return `内置免费 · 每日${q.limit}次 · 今日已用完`;
const me = q.authorized ? '已授权' : `免费${q.limit}次·剩${q.remaining}`;
if (q.upstream === 'pollinations') return `${me} · Pollinations按Key余额`;
if (q.upstream === 'cloudflare') {
if ((q.upstream_remaining ?? 1) <= 0) return 'CF免费池已用完 · 08:00重置';
return `${me} · CF池剩${q.upstream_remaining}/${q.upstream_daily}张`;
}
return q.authorized ? '已授权' : `内置免费 · 每日${q.limit}次 · 今日剩${q.remaining}次`;
});
const quotaOut = computed(() => !!quota.value && !quota.value.authorized && quota.value.remaining <= 0);
const quotaOut = computed(() => {
const q = quota.value;
if (!q) return false;
if (q.upstream === 'cloudflare' && (q.upstream_remaining ?? 1) <= 0) return true;
return !q.authorized && q.remaining <= 0;
});
const quotaTip = computed(() => quota.value?.upstream_note || '内置免费额度说明');
// 模型下拉后缀:把各上游的真实免费配额实际写出来
function upSuffix(id: string) {
if (id.startsWith('pollinations')) return '(按Key余额)';
return `(CF ${quota.value?.cf_daily ?? 173}张/日)`;
}
async function loadQuota() {
try {
const res = await fetch('/relay/ai/quota', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ machine: getMachineId() }),
body: JSON.stringify({ machine: getMachineId(), model: model.value }),
});
const j = await res.json();
if (j.code === 200 && j.data) quota.value = j.data;
} catch { /* ignore */ }
}
// 切换模型 → 上游不同,额度说明跟着换
watch(model, () => loadQuota());
onMounted(async () => {
loadProvider();
@@ -243,10 +265,10 @@ async function generate() {
<div class="gen-ctrl">
<!-- 模型 -->
<div class="gen-sec">
<div class="gen-h">模型 <span class="gen-quota" :class="{ out: quotaOut }">{{ quotaText }}</span></div>
<div class="gen-h" :title="quotaTip">模型 <span class="gen-quota" :class="{ out: quotaOut }">{{ quotaText }}</span></div>
<select v-model="model" class="gen-model-sel">
<optgroup label="站内免费模型">
<option v-for="m in models.filter(x => !x.custom)" :key="m.id" :value="m.id">{{ m.id }}</option>
<option v-for="m in models.filter(x => !x.custom)" :key="m.id" :value="m.id">{{ m.id }}{{ upSuffix(m.id) }}</option>
</optgroup>
<optgroup v-if="models.some(x => x.custom)" label="我的模型">
<option v-for="m in models.filter(x => x.custom)" :key="m.id" :value="m.id">{{ m.id }}(我的)</option>