@@ -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 " ) )
@@ -56,9 +58,17 @@ PROJECT_ALIASES = {
} or { PROJECT_NAME }
TRIAL_FILE = os . environ . get ( " TRIAL_FILE " , " /app/data/trials.json " )
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 " }
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 " , " face-swap " , " poster-maker " }
MACHINE_RE = re . compile ( r " ^ \ d { 10,16}$ " )
# verify() messages that unconditionally block activation
@@ -189,6 +199,143 @@ def trial_allowed(machine: str, tool: str) -> bool:
return ( now_ms - start ) < TRIAL_MS
# ---------- AI 生图页:每日免费次数(未授权;北京时间 0 点重置,自带 KEY 不计次) ----------
_DAILY_LOCK = threading . Lock ( )
def _load_daily ( ) - > dict :
try :
with open ( DAILY_FILE , encoding = " utf-8 " ) as f :
d = json . load ( f )
return d if isinstance ( d , dict ) else { }
except Exception :
return { }
def _save_daily ( d : dict ) - > None :
try :
with open ( DAILY_FILE , " w " , encoding = " utf-8 " ) as f :
json . dump ( d , f , ensure_ascii = False )
except Exception :
pass
def _day_key ( ) - > int :
return _today_start ( int ( time . time ( ) * 1000 ) )
def daily_used ( machine : str ) - > int :
""" 该机器今日已用内置免费生图次数(跨天自动归零)。 """
rec = _load_daily ( ) . get ( machine )
if isinstance ( rec , dict ) and rec . get ( " day " ) == _day_key ( ) :
try :
return int ( rec . get ( " n " , 0 ) )
except Exception :
return 0
return 0
def daily_consume ( machine : str , model : str = " " ) - > None :
""" 内置渠道生成成功后扣次:未授权机器计数照记;走 Cloudflare 的模型同时消耗全站共享池。 """
with _DAILY_LOCK :
d = _load_daily ( )
rec = d . get ( machine )
if not ( isinstance ( rec , dict ) and rec . get ( " day " ) == _day_key ( ) ) :
rec = { " day " : _day_key ( ) , " n " : 0 }
try :
rec [ " n " ] = int ( rec . get ( " n " , 0 ) ) + 1
except Exception :
rec [ " n " ] = 1
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 ) )
# ---------- 全站共享上游: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 " bad_machine "
if own_provider :
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 ] :
""" Revoke authorization for this machine.
@@ -564,6 +711,51 @@ def check(machine: str, tool: str) -> int:
return 200 if trial_allowed ( machine , tool ) else 403
# ---- AI 换脸引擎:insightface buffalo_l 人脸检测 + inswapper_128 换脸(本机 CPU 推理) ----
_FACE_LOCK = threading . Lock ( )
_FACE_APP = None
_FACE_SWAP = None
_FACE_MODELS_DIR = os . environ . get ( " FACE_MODELS_DIR " , " /app/face-models " )
def _face_engine ( ) :
""" 懒加载换脸引擎(线程安全;首次调用约 1~2s,之后常驻内存复用)。 """
global _FACE_APP , _FACE_SWAP
if _FACE_APP is None :
from insightface . app import FaceAnalysis
from insightface import model_zoo
app = FaceAnalysis ( name = " buffalo_l " , root = _FACE_MODELS_DIR , providers = [ " CPUExecutionProvider " ] )
app . prepare ( ctx_id = 0 , det_size = ( 640 , 640 ) )
swap = model_zoo . get_model ( os . path . join ( _FACE_MODELS_DIR , " inswapper_128.onnx " ) ,
providers = [ " CPUExecutionProvider " ] )
_FACE_APP , _FACE_SWAP = app , swap
return _FACE_APP , _FACE_SWAP
def _largest_face ( faces ) :
""" 多张脸时取面积最大的一张(换脸默认作用于最显眼的人脸)。 """
return max ( faces , key = lambda f : float ( ( f . bbox [ 2 ] - f . bbox [ 0 ] ) * ( f . bbox [ 3 ] - f . bbox [ 1 ] ) ) )
def _face_swap_run ( src_img , dst_img ) :
""" 源人脸 -> 目标照片。返回 (jpg字节|None, 错误信息, 耗时ms)。加锁串行避免并发吃满 CPU。 """
import cv2 as _cv2
t0 = time . time ( )
with _FACE_LOCK :
app , swap = _face_engine ( )
src_faces = app . get ( src_img )
dst_faces = app . get ( dst_img )
if not src_faces :
return None , " 源图中未检测到人脸,请换一张清晰的正脸照片 " , 0
if not dst_faces :
return None , " 目标图中未检测到人脸,请换一张含人物的照片 " , 0
out = swap . get ( dst_img , _largest_face ( dst_faces ) , _largest_face ( src_faces ) , paste_back = True )
ok , buf = _cv2 . imencode ( " .jpg " , out , [ int ( _cv2 . IMWRITE_JPEG_QUALITY ) , 92 ] )
if not ok :
return None , " 结果编码失败 " , 0
return buf . tobytes ( ) , None , int ( ( time . time ( ) - t0 ) * 1000 )
def _account_license_ok ( machine : str ) - > bool :
""" True when this device logged into an authorized account.
@@ -756,6 +948,7 @@ def _db():
" ALTER TABLE users ADD COLUMN bound_machines TEXT DEFAULT ' [] ' " ,
" ALTER TABLE users ADD COLUMN role TEXT DEFAULT ' user ' " ,
" ALTER TABLE users ADD COLUMN disabled INTEGER DEFAULT 0 " ,
" ALTER TABLE users ADD COLUMN last_login REAL DEFAULT 0 " ,
) :
try :
conn . execute ( stmt )
@@ -1036,12 +1229,12 @@ def admin_api(method: str, sub: str, payload: dict, handler):
if method == " GET " and sub == " /overview " :
conn = _db ( )
users = conn . execute ( " SELECT username, created, card_key, bound_machines, role, disabled FROM users " ) . fetchall ( )
users = conn . execute ( " SELECT username, created, card_key, bound_machines, role, disabled, last_login FROM users " ) . fetchall ( )
conn . close ( )
out_users = [ ]
total_files = 0
total_size = 0
for username , created , card_key , bm , role , disabled in users :
for username , created , card_key , bm , role , disabled , last_login in users :
udir = os . path . join ( USERS_ROOT , username )
fdir = os . path . join ( udir , " files " )
fcount = 0
@@ -1069,6 +1262,7 @@ def admin_api(method: str, sub: str, payload: dict, handler):
out_users . append ( {
" username " : username ,
" created " : int ( created or 0 ) ,
" last_login " : int ( last_login or 0 ) ,
" files " : fcount ,
" file_size " : fsize ,
" data_size " : dsize ,
@@ -1686,7 +1880,7 @@ def user_api(method, sub, payload, handler):
conn = _db ( )
try :
salt = secrets . token_hex ( 16 )
conn . execute ( " INSERT INTO users VALUES (?,?,?,?) " , ( username , salt , _hash_pw ( password , salt ) , time . time ( ) ) )
conn . execute ( " INSERT INTO users (username, salt, pw_hash, created, last_login) VALUES (?,?,?,?,? ) " , ( username , salt , _hash_pw ( password , salt ) , time . time ( ) , time . time ( ) ) )
conn . commit ( )
except sqlite3 . IntegrityError :
return 409 , { " code " : 409 , " message " : " 用户名已被注册 " }
@@ -1710,6 +1904,13 @@ def user_api(method, sub, payload, handler):
return 401 , { " code " : 401 , " message " : " 用户名或密码错误 " }
_user_dir ( username )
_bind_machine ( username , _req_machine ( handler ) )
try :
_conn2 = _db ( )
_conn2 . execute ( " UPDATE users SET last_login=? WHERE username=? " , ( time . time ( ) , username ) )
_conn2 . commit ( )
_conn2 . close ( )
except Exception :
pass
role , disabled = _user_attr ( username )
if disabled :
return 403 , { " code " : 403 , " message " : " 账号已被禁用,请联系管理员 " }
@@ -1947,6 +2148,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,12 +3157,21 @@ class Handler(BaseHTTPRequestHandler):
if parsed . path == " /ai/models " :
self . _handle_ai_models ( )
return
if parsed . path == " /ai/quota " :
self . _handle_ai_quota ( )
return
if parsed . path == " /ai/custom-models " :
self . _handle_custom_models ( )
return
if parsed . path == " /ai/gen-image " :
self . _handle_gen_image ( )
return
if parsed . path == " /ai/edit-image " :
self . _handle_edit_image ( )
return
if parsed . path == " /ai/face-swap " :
self . _handle_face_swap ( )
return
if parsed . path == " /ai/seamless-edit " :
self . _handle_seamless_edit ( )
return
@@ -3036,6 +3252,51 @@ class Handler(BaseHTTPRequestHandler):
self . _reply ( 404 , b " not found " )
# ---------- 中文提示词自动转英文(Flux/SDXL 系对英文理解最好) ----------
_ZH_RE = re . compile ( r " [ \ u4e00- \ u9fff] " )
_trans_cache : dict = { }
def _translate_prompt ( self , prompt : str ) :
""" 含中文才翻;成功 (英文, True);失败/未配置回退 (原文, False),绝不阻断生图。 """
if not prompt or not self . _ZH_RE . search ( prompt ) :
return prompt , False
cached = self . _trans_cache . get ( prompt )
if cached :
return cached , True
key = os . environ . get ( " NEWAPI_KEY " , " " )
if not key :
return prompt , False
try :
body = json . dumps ( {
" model " : os . environ . get ( " IMG_PROMPT_MODEL " , " mimo-v2.6-flash " ) ,
" messages " : [
{ " role " : " system " , " content " : (
" You are an expert prompt engineer for text-to-image models (Flux / SDXL / DALL-E). "
" Translate the user ' s Chinese image prompt into ONE high-quality English image-generation prompt. "
" Preserve every style, composition, aspect-ratio, lighting and detail keyword; you may expand "
" slightly for natural flow. Output ONLY the English prompt itself - no quotes, no explanations, "
" no Chinese characters, no markdown. " ) } ,
{ " role " : " user " , " content " : prompt } ,
] ,
" temperature " : 0.3 , " max_tokens " : 500 ,
} ) . encode ( )
req = request . Request (
os . environ . get ( " NEWAPI_URL " , " http://192.168.68.19:3099/v1/chat/completions " ) ,
data = body , headers = { " Content-Type " : " application/json " , " Authorization " : " Bearer " + key } )
data = json . loads ( request . urlopen ( req , timeout = 30 ) . read ( ) )
en = str ( data . get ( " choices " , [ { } ] ) [ 0 ] . get ( " message " , { } ) . get ( " content " ) or " " ) . strip ( )
en = en . strip ( " ` \" ' \u201c \u201d " ) . strip ( )
if not en or self . _ZH_RE . search ( en [ : 120 ] ) :
return prompt , False
if len ( self . _trans_cache ) > = 300 :
self . _trans_cache . clear ( )
self . _trans_cache [ prompt ] = en
print ( f " [img] prompt translated: { prompt [ : 40 ] } -> { en [ : 70 ] } " , flush = True )
return en , True
except Exception as e : # noqa: BLE001
print ( f " [img] translate failed, use original: { e } " , flush = True )
return prompt , False
# ---------- AI 生图 (NEWAPI) ----------
def _nm_base ( self ) :
return os . environ . get ( " NEWAPI_URL " , " http://192.168.68.19:3099/v1/chat/completions " ) . replace ( " /chat/completions " , " " )
@@ -3088,7 +3349,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 " " , " prompt_en " : ( d . get ( " prompt_en " ) or " " ) if isinstance ( d , dict ) else " " } } , ensure_ascii = False ) . encode ( " utf-8 " ) , " application/json " )
def _handle_image_models ( self ) :
try :
@@ -3098,17 +3359,267 @@ 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 , kind = " gen " ) :
""" 把生成结果落盘并写入该机器的历史索引;返回站内图片 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 not ( w and h ) :
try :
from PIL import Image as _PIL
import io as _io
_im = _PIL . open ( _io . BytesIO ( raw ) )
w , h = _im . size
except Exception :
w , h = 0 , 0
if raw [ : 8 ] == b " \x89 PNG \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 ] ,
" kind " : str ( kind or " gen " ) [ : 20 ] ,
" 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_ai_quota ( self ) :
""" 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 ) )
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 ) :
""" 测试用户的 OpenAI 兼容提供商并拉取模型列表(KEY 只进本次请求头,不落盘)。 """
payload = self . _read_payload ( )
machine = str ( payload . get ( " machine " ) or " " )
if check_gen ( machine , True ) != 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 " " )
if check ( machine , " ai-gen " ) != 200 :
self . _reply ( 403 , json . dumps ( { " code " : 403 , " message " : " 需要授权或今日免费试用已用完 " } , ensure_ascii = False ) . encode ( " utf-8 " ) , " application/json " )
# 先解析自带提供商与模型:自带 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 ( ) )
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 )
@@ -3116,18 +3627,28 @@ class Handler(BaseHTTPRequestHandler):
w , h = 1024 , 1024
w = max ( 16 , min ( 2048 , w ) )
h = max ( 16 , min ( 2048 , h ) )
# 中文提示词自动转英文再发上游(Flux/SDXL 英文效果最好;翻译失败回退原文)
gen_prompt , translated = self . _translate_prompt ( prompt )
try :
d = self . _nm_images_gen ( model , prompt , f " { w } x { h } " )
self . _img_reply_ok ( d )
if own_provider :
d = self . _provider_images_gen ( provider , model , gen_prompt , f " { w } x { h } " )
else :
d = self . _nm_images_gen ( model , gen_prompt , f " { w } x { h } " )
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 " )
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
if translated and isinstance ( d , dict ) :
d [ " prompt_en " ] = gen_prompt # 实际发给上游的英文提示词(供前端提示)
self . _img_reply_ok ( d )
def _handle_edit_image ( self ) :
machine = self . headers . get ( " X-Machine-Id " , " " )
if check ( machine , " ai-gen " ) != 200 :
self . _reply ( 403 , json . dumps ( { " code " : 403 , " message " : " 需要授权或今日免费试用已用完 " } , 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 " )
@@ -3135,6 +3656,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
@@ -3145,7 +3671,11 @@ class Handler(BaseHTTPRequestHandler):
return
try :
img = up . file . read ( )
d = self . _nm_images_edit ( model , prompt , img , up . filename )
gen_prompt , translated = self . _translate_prompt ( prompt )
d = self . _nm_images_edit ( model , gen_prompt , img , up . filename )
daily_consume ( machine , model ) # 内置渠道成功才扣次(机器计数 + CF 共享池)
if translated and isinstance ( d , dict ) :
d [ " prompt_en " ] = gen_prompt
self . _img_reply_ok ( d )
except Exception as e : # noqa: BLE001
print ( f " [img] edit failed: { e } " , flush = True )
@@ -3399,6 +3929,94 @@ class Handler(BaseHTTPRequestHandler):
canvas . paste ( im2 , ( ( tw - im2 . width ) / / 2 , ( th - im2 . height ) / / 2 ) )
return canvas
def _handle_face_swap ( self ) :
""" AI换脸(授权功能):源人脸照片 -> 目标照片,本机 CPU 推理,结果走 /ai/img 站内图链路。 """
machine = self . headers . get ( " X-Machine-Id " , " " )
code = check ( machine , " face-swap " )
if code != 200 :
self . _reply ( 403 , json . dumps ( { " code " : 403 , " message " : " AI换脸是授权功能:试用期内可免费体验,正式使用请先激活卡密 " } ,
ensure_ascii = False ) . encode ( " utf-8 " ) , " application/json " )
return
log_usage ( machine , " face-swap " )
ctype = self . headers . get ( " Content-Type " ) or " "
if " multipart/form-data " not in ctype :
self . _reply ( 400 , json . dumps ( { " code " : 400 , " message " : " 需要 multipart/form-data " } , ensure_ascii = False ) . encode ( " utf-8 " ) , " application/json " )
return
try :
form = cgi . FieldStorage ( fp = self . rfile , headers = self . headers ,
environ = { " REQUEST_METHOD " : " POST " , " CONTENT_TYPE " : ctype } )
except Exception as e : # noqa: BLE001
self . _reply ( 400 , json . dumps ( { " code " : 400 , " message " : f " 表单解析失败: { e } " } , ensure_ascii = False ) . encode ( " utf-8 " ) , " application/json " )
return
if str ( form . getvalue ( " consent " ) or " " ) != " 1 " :
self . _reply ( 400 , json . dumps ( { " code " : 400 , " message " : " 请先勾选「我承诺仅使用已获本人授权的照片进行换脸」 " } ,
ensure_ascii = False ) . encode ( " utf-8 " ) , " application/json " )
return
try :
src_raw = form [ " source " ] . file . read ( ) if " source " in form else b " "
dst_raw = form [ " target " ] . file . read ( ) if " target " in form else b " "
except Exception :
src_raw , dst_raw = b " " , b " "
if not src_raw or not dst_raw :
self . _reply ( 400 , json . dumps ( { " code " : 400 , " message " : " 请同时上传源人脸照片与目标照片 " } , ensure_ascii = False ) . encode ( " utf-8 " ) , " application/json " )
return
if len ( src_raw ) > 15 * 1024 * 1024 or len ( dst_raw ) > 15 * 1024 * 1024 :
self . _reply ( 400 , json . dumps ( { " code " : 400 , " message " : " 单张图片不能超过 15MB " } , ensure_ascii = False ) . encode ( " utf-8 " ) , " application/json " )
return
import cv2 as _cv2
import numpy as _np
src_img = _cv2 . imdecode ( _np . frombuffer ( src_raw , _np . uint8 ) , _cv2 . IMREAD_COLOR )
dst_img = _cv2 . imdecode ( _np . frombuffer ( dst_raw , _np . uint8 ) , _cv2 . IMREAD_COLOR )
if src_img is None or dst_img is None :
self . _reply ( 400 , json . dumps ( { " code " : 400 , " message " : " 图片解码失败,请上传 JPG/PNG 等常见格式 " } , ensure_ascii = False ) . encode ( " utf-8 " ) , " application/json " )
return
try :
out_jpg , msg , ms = _face_swap_run ( src_img , dst_img )
except Exception as e : # noqa: BLE001
print ( f " [face-swap] failed: { e } " , flush = True )
self . _reply ( 500 , json . dumps ( { " code " : 500 , " message " : f " 换脸失败: { e } " } , ensure_ascii = False ) . encode ( " utf-8 " ) , " application/json " )
return
if out_jpg is None :
self . _reply ( 400 , json . dumps ( { " code " : 400 , " message " : msg } , ensure_ascii = False ) . encode ( " utf-8 " ) , " application/json " )
return
try :
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 ] } "
with open ( os . path . join ( gen_dir , iid + " .jpg " ) , " wb " ) as f :
f . write ( out_jpg )
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 " : iid + " .jpg " , " at " : int ( time . time ( ) ) ,
" model " : " AI换脸 " , " prompt " : " face-swap " ,
" w " : int ( dst_img . shape [ 1 ] ) , " h " : int ( dst_img . shape [ 0 ] ) } )
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 )
except Exception as e : # noqa: BLE001
print ( f " [face-swap] persist failed: { e } " , flush = True )
self . _reply ( 500 , json . dumps ( { " code " : 500 , " message " : " 结果保存失败 " } , ensure_ascii = False ) . encode ( " utf-8 " ) , " application/json " )
return
body = json . dumps ( { " code " : 200 , " message " : " ok " ,
" data " : { " url " : f " /relay/ai/img/ { machine } / { iid } " , " elapsed_ms " : ms } } ,
ensure_ascii = False ) . encode ( " utf-8 " )
self . _reply ( 200 , body , " application/json " )
def _handle_seamless_edit ( self ) :
machine = self . headers . get ( " X-Machine-Id " , " " )
if check ( machine , " ai-text-edit " ) != 200 :