Upload 3 files
Browse files- Dockerfile +9 -14
- app.py +129 -200
- requirements.txt +1 -2
Dockerfile
CHANGED
|
@@ -1,32 +1,27 @@
|
|
| 1 |
# 1. 基础镜像
|
| 2 |
FROM python:3.10-slim
|
| 3 |
|
| 4 |
-
# 2. 创建用户
|
| 5 |
RUN useradd -m -u 1000 user
|
|
|
|
|
|
|
| 6 |
USER user
|
|
|
|
|
|
|
| 7 |
ENV HOME=/home/user \
|
| 8 |
PATH=/home/user/.local/bin:$PATH \
|
| 9 |
PYTHONUNBUFFERED=1
|
| 10 |
|
| 11 |
-
#
|
| 12 |
WORKDIR $HOME/app
|
| 13 |
|
| 14 |
-
#
|
|
|
|
| 15 |
COPY --chown=user requirements.txt .
|
| 16 |
RUN pip install --no-cache-dir -r requirements.txt
|
| 17 |
|
| 18 |
-
#
|
| 19 |
COPY --chown=user . .
|
| 20 |
|
| 21 |
-
# 6. 【关键修复】切换回 root 给予权限,但路径要用变量或者点
|
| 22 |
-
USER root
|
| 23 |
-
# 修正路径:使用 . (当前工作目录) 或者 /home/user/app
|
| 24 |
-
RUN chmod -R 777 .
|
| 25 |
-
# 权限给完后,切回普通用户启动
|
| 26 |
-
USER user
|
| 27 |
-
|
| 28 |
-
# 7. 暴露端口
|
| 29 |
-
EXPOSE 7860
|
| 30 |
-
|
| 31 |
# 8. 启动
|
| 32 |
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
|
|
|
|
| 1 |
# 1. 基础镜像
|
| 2 |
FROM python:3.10-slim
|
| 3 |
|
| 4 |
+
# 2. 创建用户 (HF 要求 ID 1000)
|
| 5 |
RUN useradd -m -u 1000 user
|
| 6 |
+
|
| 7 |
+
# 3. 切换用户 (后续所有操作都以 user 身份进行)
|
| 8 |
USER user
|
| 9 |
+
|
| 10 |
+
# 4. 设置环境变量 (关键!)
|
| 11 |
ENV HOME=/home/user \
|
| 12 |
PATH=/home/user/.local/bin:$PATH \
|
| 13 |
PYTHONUNBUFFERED=1
|
| 14 |
|
| 15 |
+
# 5. 设置工作目录
|
| 16 |
WORKDIR $HOME/app
|
| 17 |
|
| 18 |
+
# 6. 复制并安装依赖
|
| 19 |
+
# 注意:使用 --chown=user,这样复制进去的文件直接归 user 所有,不需要 chmod
|
| 20 |
COPY --chown=user requirements.txt .
|
| 21 |
RUN pip install --no-cache-dir -r requirements.txt
|
| 22 |
|
| 23 |
+
# 7. 复制所有代码
|
| 24 |
COPY --chown=user . .
|
| 25 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
# 8. 启动
|
| 27 |
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
|
app.py
CHANGED
|
@@ -6,6 +6,7 @@ import asyncio
|
|
| 6 |
import time
|
| 7 |
import gc
|
| 8 |
from datetime import datetime
|
|
|
|
| 9 |
from PIL import Image
|
| 10 |
from io import BytesIO
|
| 11 |
from openai import AsyncOpenAI
|
|
@@ -18,21 +19,19 @@ import uvicorn
|
|
| 18 |
# ==========================================
|
| 19 |
# 1. 配置区域
|
| 20 |
# ==========================================
|
|
|
|
| 21 |
|
| 22 |
-
# ---
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
# --- 启动检查日志 ---
|
| 27 |
-
if BAIDU_API_KEY and BAIDU_SECRET_KEY:
|
| 28 |
-
print(f"✅ [System] 检测到百度 API Key: {BAIDU_API_KEY[:4]}****")
|
| 29 |
-
else:
|
| 30 |
-
print(f"⚠️ [System] 未检测到百度 API Key 或 SECRET KEY,审核功能将关闭!")
|
| 31 |
|
| 32 |
-
#
|
| 33 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
|
| 35 |
-
# --- 基础配置 ---
|
| 36 |
AR_BASES = {
|
| 37 |
"1:1 (SDXL标准 1024)": (1024, 1024),
|
| 38 |
"16:9 (SDXL标准 768p)": (1344, 768),
|
|
@@ -41,42 +40,67 @@ AR_BASES = {
|
|
| 41 |
"4:3 (标准)": (1152, 896),
|
| 42 |
"21:9 (宽屏)": (1536, 640)
|
| 43 |
}
|
|
|
|
| 44 |
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
}
|
| 48 |
|
| 49 |
-
#
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
# ==========================================
|
| 57 |
-
#
|
| 58 |
# ==========================================
|
| 59 |
|
| 60 |
-
# 全局缓存 Access Token
|
| 61 |
_BAIDU_TOKEN_CACHE = {"token": None, "expires_at": 0}
|
| 62 |
|
| 63 |
async def get_baidu_access_token():
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
if not
|
| 67 |
-
return None
|
| 68 |
-
|
| 69 |
now = time.time()
|
| 70 |
if _BAIDU_TOKEN_CACHE["token"] and now < _BAIDU_TOKEN_CACHE["expires_at"]:
|
| 71 |
return _BAIDU_TOKEN_CACHE["token"]
|
| 72 |
-
|
| 73 |
-
url = "https://aip.baidubce.com/oauth/2.0/token"
|
| 74 |
-
params = {
|
| 75 |
-
"grant_type": "client_credentials",
|
| 76 |
-
"client_id": BAIDU_API_KEY,
|
| 77 |
-
"client_secret": BAIDU_SECRET_KEY
|
| 78 |
-
}
|
| 79 |
|
|
|
|
|
|
|
| 80 |
try:
|
| 81 |
async with httpx.AsyncClient(timeout=10) as client:
|
| 82 |
resp = await client.post(url, params=params)
|
|
@@ -84,55 +108,36 @@ async def get_baidu_access_token():
|
|
| 84 |
token = data.get("access_token")
|
| 85 |
if token:
|
| 86 |
_BAIDU_TOKEN_CACHE["token"] = token
|
| 87 |
-
_BAIDU_TOKEN_CACHE["expires_at"] = now +
|
| 88 |
return token
|
| 89 |
-
|
| 90 |
-
print(f"⚠️ 百度 Token 获取失败: {data}")
|
| 91 |
-
return None
|
| 92 |
-
except Exception as e:
|
| 93 |
-
print(f"⚠️ 百度 Token 网络错误: {e}")
|
| 94 |
-
return None
|
| 95 |
|
| 96 |
async def check_baidu_text_censor(text):
|
| 97 |
-
"""调用百度 API 检查文本"""
|
| 98 |
token = await get_baidu_access_token()
|
| 99 |
-
if not token:
|
| 100 |
-
# 如果获取不到 token (未配置环境变量或接口挂了),默认放行
|
| 101 |
-
return False, None
|
| 102 |
|
| 103 |
url = f"https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined?access_token={token}"
|
|
|
|
| 104 |
data = {'text': text}
|
| 105 |
|
| 106 |
try:
|
| 107 |
async with httpx.AsyncClient(timeout=10) as client:
|
| 108 |
-
resp = await client.post(url, data=data)
|
| 109 |
result = resp.json()
|
| 110 |
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
if
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
return True, reason
|
| 121 |
-
elif
|
| 122 |
-
return True, "内容疑似违规"
|
| 123 |
-
|
| 124 |
return False, None
|
| 125 |
-
|
| 126 |
-
except Exception as e:
|
| 127 |
-
print(f"⚠️ 百度审核接口异常: {e}")
|
| 128 |
-
return False, None
|
| 129 |
-
|
| 130 |
-
def contains_local_sensitive_words(text: str):
|
| 131 |
-
text_lower = text.lower()
|
| 132 |
-
for word in SENSITIVE_WORDS:
|
| 133 |
-
if word.lower() in text_lower:
|
| 134 |
-
return True, word
|
| 135 |
-
return False, None
|
| 136 |
|
| 137 |
class GenerateRequest(BaseModel):
|
| 138 |
api_key: str
|
|
@@ -146,168 +151,92 @@ class GenerateRequest(BaseModel):
|
|
| 146 |
def process_image_in_memory(image_bytes: bytes, target_format: str) -> str:
|
| 147 |
try:
|
| 148 |
with Image.open(BytesIO(image_bytes)) as img:
|
| 149 |
-
|
| 150 |
-
if target_format == "jpg"
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
except Exception as e:
|
| 157 |
-
raise Exception(f"格式转换失败: {str(e)}")
|
| 158 |
-
finally:
|
| 159 |
-
gc.collect()
|
| 160 |
|
| 161 |
async def download_image_as_bytes(url):
|
| 162 |
-
print(f"📥
|
| 163 |
async with httpx.AsyncClient(timeout=60) as client:
|
| 164 |
-
|
| 165 |
-
if
|
| 166 |
-
|
| 167 |
-
else:
|
| 168 |
-
raise Exception(f"下载失败 HTTP {response.status_code}")
|
| 169 |
-
|
| 170 |
-
# ==========================================
|
| 171 |
-
# 3. 核心生成逻辑
|
| 172 |
-
# ==========================================
|
| 173 |
|
| 174 |
async def core_generate(req: GenerateRequest):
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
if req.ratio == "custom":
|
| 178 |
-
final_size = req.custom_size.strip()
|
| 179 |
else:
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
final_prompt = req.prompt
|
| 186 |
if "gemini" in req.model.lower():
|
| 187 |
-
if req.ratio
|
| 188 |
-
|
| 189 |
-
else:
|
| 190 |
-
final_prompt = f"{req.prompt} --ar {ratio_str} --resolution {final_size}"
|
| 191 |
|
| 192 |
-
client = AsyncOpenAI(
|
| 193 |
-
api_key=req.api_key,
|
| 194 |
-
base_url="https://api.cloudapp.ink/v1",
|
| 195 |
-
max_retries=0,
|
| 196 |
-
timeout=60.0
|
| 197 |
-
)
|
| 198 |
-
|
| 199 |
-
image_bytes = None
|
| 200 |
|
|
|
|
| 201 |
if "gemini" in req.model.lower():
|
| 202 |
-
print(f"🟣
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
)
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
url_match = re.search(r"!\[.*?\]\((https?://[^\)]+)\)", content)
|
| 211 |
-
if not url_match:
|
| 212 |
-
url_match = re.search(r"(https?://\S+\.(?:png|jpg|jpeg|webp))", content)
|
| 213 |
-
|
| 214 |
-
if url_match:
|
| 215 |
-
image_bytes = await download_image_as_bytes(url_match.group(1))
|
| 216 |
-
elif "base64," in content:
|
| 217 |
-
print(f"🟣 [Chat模式] 检测到 Base64 流")
|
| 218 |
-
b64_str = content.split("base64,")[1].split(")")[0].strip()
|
| 219 |
-
image_bytes = base64.b64decode(b64_str)
|
| 220 |
-
else:
|
| 221 |
-
raise Exception("未能识别图片内容")
|
| 222 |
-
|
| 223 |
else:
|
| 224 |
-
print(f"🔵
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
response_format="b64_json"
|
| 231 |
-
)
|
| 232 |
-
print(f"🔵 [绘图模式] 请求成功")
|
| 233 |
|
| 234 |
-
|
| 235 |
-
if getattr(data, 'b64_json', None):
|
| 236 |
-
image_bytes = base64.b64decode(data.b64_json)
|
| 237 |
-
elif hasattr(data, 'url'):
|
| 238 |
-
image_bytes = await download_image_as_bytes(data.url)
|
| 239 |
-
else:
|
| 240 |
-
raise Exception("API 未返回有效图片数据")
|
| 241 |
-
|
| 242 |
-
return process_image_in_memory(image_bytes, req.format)
|
| 243 |
|
| 244 |
# ==========================================
|
| 245 |
# 4. FastAPI App
|
| 246 |
# ==========================================
|
| 247 |
app = FastAPI()
|
| 248 |
-
|
| 249 |
app.mount("/static", StaticFiles(directory="static"), name="static")
|
| 250 |
|
| 251 |
@app.get("/")
|
| 252 |
-
async def read_index():
|
| 253 |
-
return FileResponse('static/index.html')
|
| 254 |
|
| 255 |
@app.get("/health")
|
| 256 |
-
def health():
|
| 257 |
-
return {"status": "ok"}
|
| 258 |
|
| 259 |
@app.post("/api/generate")
|
| 260 |
async def generate_api(req: GenerateRequest, request: Request):
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
print("\n" + "="*60)
|
| 265 |
-
print(f"🚀 [Request] {timestamp} | IP: {client_host}")
|
| 266 |
-
print(f"📌 Model: {req.model}")
|
| 267 |
-
print(f"💡 Prompt: {req.prompt}")
|
| 268 |
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
if is_local_sensitive:
|
| 272 |
-
print(f"🚫 [Blocked-Local] 命中本地词库: {word}")
|
| 273 |
-
return JSONResponse(
|
| 274 |
-
content={
|
| 275 |
-
"status": "error",
|
| 276 |
-
"message": f"提示词包含违禁词汇 ({word}),请求被拒绝。"
|
| 277 |
-
},
|
| 278 |
-
status_code=200
|
| 279 |
-
)
|
| 280 |
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
return JSONResponse(
|
| 286 |
-
content={
|
| 287 |
-
"status": "error",
|
| 288 |
-
"message": f"提示词未通过智能安全审核: {reason}"
|
| 289 |
-
},
|
| 290 |
-
status_code=200
|
| 291 |
-
)
|
| 292 |
|
| 293 |
-
|
|
|
|
|
|
|
|
|
|
| 294 |
|
| 295 |
-
# 3. 正常生成
|
| 296 |
async with CONCURRENCY_LIMITER:
|
| 297 |
try:
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
duration = time.time() - start_time
|
| 302 |
-
print(f"✅ [Success] 耗时: {duration:.2f}s")
|
| 303 |
-
return {"status": "success", "image_base64": base64_img}
|
| 304 |
-
|
| 305 |
except Exception as e:
|
| 306 |
-
print(f"❌
|
| 307 |
-
return JSONResponse(
|
| 308 |
-
content={"status": "error", "message": str(e)},
|
| 309 |
-
status_code=200
|
| 310 |
-
)
|
| 311 |
finally:
|
| 312 |
gc.collect()
|
| 313 |
|
|
|
|
| 6 |
import time
|
| 7 |
import gc
|
| 8 |
from datetime import datetime
|
| 9 |
+
from collections import deque # 引入双端队列
|
| 10 |
from PIL import Image
|
| 11 |
from io import BytesIO
|
| 12 |
from openai import AsyncOpenAI
|
|
|
|
| 19 |
# ==========================================
|
| 20 |
# 1. 配置区域
|
| 21 |
# ==========================================
|
| 22 |
+
CONCURRENCY_LIMITER = asyncio.Semaphore(3)
|
| 23 |
|
| 24 |
+
# --- 🚀 动态违禁词缓存 (核心修改) ---
|
| 25 |
+
# maxlen=200: 自动保持最新的200个,旧的自动丢弃
|
| 26 |
+
DYNAMIC_BLOCK_CACHE = deque(maxlen=200)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
+
# 硬编码的基础高危词 (保留最基本的底线,防止API挂了时裸奔)
|
| 29 |
+
SENSITIVE_WORDS = [
|
| 30 |
+
"nsfw", "nude", "naked", "sex", "porn", "hentai",
|
| 31 |
+
"裸", "色情", "全裸", "blood", "kill", "murder",
|
| 32 |
+
"血腥", "尸体", "毒品", "杀"
|
| 33 |
+
]
|
| 34 |
|
|
|
|
| 35 |
AR_BASES = {
|
| 36 |
"1:1 (SDXL标准 1024)": (1024, 1024),
|
| 37 |
"16:9 (SDXL标准 768p)": (1344, 768),
|
|
|
|
| 40 |
"4:3 (标准)": (1152, 896),
|
| 41 |
"21:9 (宽屏)": (1536, 640)
|
| 42 |
}
|
| 43 |
+
SCALE_MULTIPLIERS = {"1k": 1.0, "2k": 1.5, "4k": 2.0}
|
| 44 |
|
| 45 |
+
# IP 限流记录
|
| 46 |
+
IP_REQUEST_HISTORY = {}
|
|
|
|
| 47 |
|
| 48 |
+
# ==========================================
|
| 49 |
+
# 2. 辅助功能
|
| 50 |
+
# ==========================================
|
| 51 |
+
|
| 52 |
+
def get_real_ip(request: Request):
|
| 53 |
+
forwarded = request.headers.get("X-Forwarded-For")
|
| 54 |
+
if forwarded:
|
| 55 |
+
return forwarded.split(",")[0].strip()
|
| 56 |
+
return request.client.host
|
| 57 |
+
|
| 58 |
+
def check_ip_rate_limit(ip: str, limit: int = 5, window: int = 60):
|
| 59 |
+
now = time.time()
|
| 60 |
+
history = IP_REQUEST_HISTORY.get(ip, [])
|
| 61 |
+
valid_history = [t for t in history if now - t < window]
|
| 62 |
+
if len(valid_history) >= limit:
|
| 63 |
+
IP_REQUEST_HISTORY[ip] = valid_history
|
| 64 |
+
return True
|
| 65 |
+
valid_history.append(now)
|
| 66 |
+
IP_REQUEST_HISTORY[ip] = valid_history
|
| 67 |
+
if len(IP_REQUEST_HISTORY) > 5000: IP_REQUEST_HISTORY.clear()
|
| 68 |
+
return False
|
| 69 |
+
|
| 70 |
+
def contains_local_sensitive_words(text: str):
|
| 71 |
+
"""
|
| 72 |
+
检查本地缓存
|
| 73 |
+
1. 检查最近被百度封杀的200个Prompt (精确匹配)
|
| 74 |
+
2. 检查硬编码的关键词 (模糊匹配)
|
| 75 |
+
"""
|
| 76 |
+
# 1. 检查动态缓存 (O(n) 遍历,但n最大200,极快)
|
| 77 |
+
if text in DYNAMIC_BLOCK_CACHE:
|
| 78 |
+
return True, "最近违规记录 (已缓存)"
|
| 79 |
+
|
| 80 |
+
# 2. 检查静态关键词
|
| 81 |
+
text_lower = text.lower()
|
| 82 |
+
for word in SENSITIVE_WORDS:
|
| 83 |
+
if word and word.lower() in text_lower:
|
| 84 |
+
return True, word
|
| 85 |
+
|
| 86 |
+
return False, None
|
| 87 |
|
| 88 |
# ==========================================
|
| 89 |
+
# 3. 百度审核 & 生成
|
| 90 |
# ==========================================
|
| 91 |
|
|
|
|
| 92 |
_BAIDU_TOKEN_CACHE = {"token": None, "expires_at": 0}
|
| 93 |
|
| 94 |
async def get_baidu_access_token():
|
| 95 |
+
ak = os.getenv("BAIDU_API_KEY", "").strip()
|
| 96 |
+
sk = os.getenv("BAIDU_SECRET_KEY", "").strip()
|
| 97 |
+
if not ak or not sk: return None
|
|
|
|
|
|
|
| 98 |
now = time.time()
|
| 99 |
if _BAIDU_TOKEN_CACHE["token"] and now < _BAIDU_TOKEN_CACHE["expires_at"]:
|
| 100 |
return _BAIDU_TOKEN_CACHE["token"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
|
| 102 |
+
url = "https://aip.baidubce.com/oauth/2.0/token"
|
| 103 |
+
params = {"grant_type": "client_credentials", "client_id": ak, "client_secret": sk}
|
| 104 |
try:
|
| 105 |
async with httpx.AsyncClient(timeout=10) as client:
|
| 106 |
resp = await client.post(url, params=params)
|
|
|
|
| 108 |
token = data.get("access_token")
|
| 109 |
if token:
|
| 110 |
_BAIDU_TOKEN_CACHE["token"] = token
|
| 111 |
+
_BAIDU_TOKEN_CACHE["expires_at"] = now + 1728000
|
| 112 |
return token
|
| 113 |
+
except: return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
|
| 115 |
async def check_baidu_text_censor(text):
|
|
|
|
| 116 |
token = await get_baidu_access_token()
|
| 117 |
+
if not token: return False, None
|
|
|
|
|
|
|
| 118 |
|
| 119 |
url = f"https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined?access_token={token}"
|
| 120 |
+
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
|
| 121 |
data = {'text': text}
|
| 122 |
|
| 123 |
try:
|
| 124 |
async with httpx.AsyncClient(timeout=10) as client:
|
| 125 |
+
resp = await client.post(url, data=data, headers=headers)
|
| 126 |
result = resp.json()
|
| 127 |
|
| 128 |
+
if result.get('conclusionType') == 2:
|
| 129 |
+
msg = [i.get('msg') for i in result.get('data', [])]
|
| 130 |
+
reason = ",".join(msg) if msg else "违规"
|
| 131 |
+
|
| 132 |
+
# 🚀 发现新词:存入内存队列
|
| 133 |
+
if text not in DYNAMIC_BLOCK_CACHE:
|
| 134 |
+
DYNAMIC_BLOCK_CACHE.append(text)
|
| 135 |
+
print(f"🔒 [Cache] 缓存违规Prompt ({len(DYNAMIC_BLOCK_CACHE)}/200): {text[:15]}...")
|
| 136 |
+
|
| 137 |
return True, reason
|
| 138 |
+
elif result.get('conclusionType') == 3: return True, "疑似违规"
|
|
|
|
|
|
|
| 139 |
return False, None
|
| 140 |
+
except: return False, None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
|
| 142 |
class GenerateRequest(BaseModel):
|
| 143 |
api_key: str
|
|
|
|
| 151 |
def process_image_in_memory(image_bytes: bytes, target_format: str) -> str:
|
| 152 |
try:
|
| 153 |
with Image.open(BytesIO(image_bytes)) as img:
|
| 154 |
+
out = BytesIO()
|
| 155 |
+
fmt = "JPEG" if target_format == "jpg" else "PNG"
|
| 156 |
+
img = img.convert("RGB") if target_format == "jpg" else img
|
| 157 |
+
img.save(out, format=fmt, quality=95)
|
| 158 |
+
return base64.b64encode(out.getvalue()).decode('utf-8')
|
| 159 |
+
except Exception as e: raise Exception(f"IMG Error: {e}")
|
| 160 |
+
finally: gc.collect()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 161 |
|
| 162 |
async def download_image_as_bytes(url):
|
| 163 |
+
print(f"📥 下载: {url}")
|
| 164 |
async with httpx.AsyncClient(timeout=60) as client:
|
| 165 |
+
r = await client.get(url)
|
| 166 |
+
if r.status_code == 200: return r.content
|
| 167 |
+
raise Exception(f"HTTP {r.status_code}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
|
| 169 |
async def core_generate(req: GenerateRequest):
|
| 170 |
+
fs = "1024x1024"
|
| 171 |
+
if req.ratio == "custom": fs = req.custom_size.strip()
|
|
|
|
|
|
|
| 172 |
else:
|
| 173 |
+
w, h = AR_BASES.get(req.ratio, (1024, 1024))
|
| 174 |
+
m = SCALE_MULTIPLIERS.get(req.scale, 1.0)
|
| 175 |
+
fs = f"{int(w*m)}x{int(h*m)}"
|
| 176 |
+
|
| 177 |
+
fp = req.prompt
|
|
|
|
| 178 |
if "gemini" in req.model.lower():
|
| 179 |
+
suffix = f"--resolution {fs}" if req.ratio=="custom" else f"--ar {req.ratio.split()[0]} --resolution {fs}"
|
| 180 |
+
fp = f"{req.prompt} {suffix}"
|
|
|
|
|
|
|
| 181 |
|
| 182 |
+
client = AsyncOpenAI(api_key=req.api_key, base_url="https://api.cloudapp.ink/v1", max_retries=0, timeout=60.0)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 183 |
|
| 184 |
+
img_b = None
|
| 185 |
if "gemini" in req.model.lower():
|
| 186 |
+
print(f"🟣 Gemini: {req.model}")
|
| 187 |
+
res = await client.chat.completions.create(model=req.model, messages=[{"role":"user","content":fp}], extra_body={"modalities":["image","text"]})
|
| 188 |
+
c = res.choices[0].message.content
|
| 189 |
+
u = re.search(r"!\[.*?\]\((https?://[^\)]+)\)", c) or re.search(r"(https?://\S+\.(?:png|jpg|jpeg|webp))", c)
|
| 190 |
+
if u: img_b = await download_image_as_bytes(u.group(1))
|
| 191 |
+
elif "base64," in c: img_b = base64.b64decode(c.split("base64,")[1].split(")")[0].strip())
|
| 192 |
+
else: raise Exception("No Image")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 193 |
else:
|
| 194 |
+
print(f"🔵 Standard: {req.model}")
|
| 195 |
+
res = await client.images.generate(model=req.model, prompt=fp, n=1, size=fs, response_format="b64_json")
|
| 196 |
+
d = res.data[0]
|
| 197 |
+
if getattr(d,'b64_json',None): img_b = base64.b64decode(d.b64_json)
|
| 198 |
+
elif hasattr(d,'url'): img_b = await download_image_as_bytes(d.url)
|
| 199 |
+
else: raise Exception("No Data")
|
|
|
|
|
|
|
|
|
|
| 200 |
|
| 201 |
+
return process_image_in_memory(img_b, req.format)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 202 |
|
| 203 |
# ==========================================
|
| 204 |
# 4. FastAPI App
|
| 205 |
# ==========================================
|
| 206 |
app = FastAPI()
|
|
|
|
| 207 |
app.mount("/static", StaticFiles(directory="static"), name="static")
|
| 208 |
|
| 209 |
@app.get("/")
|
| 210 |
+
async def read_index(): return FileResponse('static/index.html')
|
|
|
|
| 211 |
|
| 212 |
@app.get("/health")
|
| 213 |
+
def health(): return {"status": "ok"}
|
|
|
|
| 214 |
|
| 215 |
@app.post("/api/generate")
|
| 216 |
async def generate_api(req: GenerateRequest, request: Request):
|
| 217 |
+
ip = get_real_ip(request)
|
| 218 |
+
print(f"\n🚀 [{datetime.now().strftime('%H:%M:%S')}] IP: {ip} | Prompt: {req.prompt[:20]}...")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 219 |
|
| 220 |
+
if check_ip_rate_limit(ip, 5, 60):
|
| 221 |
+
return JSONResponse({"status": "error", "message": "请求过快"}, 429)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 222 |
|
| 223 |
+
is_loc, word = contains_local_sensitive_words(req.prompt)
|
| 224 |
+
if is_loc:
|
| 225 |
+
print(f"🚫 [Local] 拦截: {word}")
|
| 226 |
+
return JSONResponse({"status": "error", "message": f"违规内容: {word}"}, 200)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 227 |
|
| 228 |
+
is_bd, reason = await check_baidu_text_censor(req.prompt)
|
| 229 |
+
if is_bd:
|
| 230 |
+
print(f"🚫 [Baidu] 拦截: {reason}")
|
| 231 |
+
return JSONResponse({"status": "error", "message": f"审核未通过: {reason}"}, 200)
|
| 232 |
|
|
|
|
| 233 |
async with CONCURRENCY_LIMITER:
|
| 234 |
try:
|
| 235 |
+
b64 = await core_generate(req)
|
| 236 |
+
return {"status": "success", "image_base64": b64}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 237 |
except Exception as e:
|
| 238 |
+
print(f"❌ Error: {e}")
|
| 239 |
+
return JSONResponse({"status": "error", "message": str(e)}, 200)
|
|
|
|
|
|
|
|
|
|
| 240 |
finally:
|
| 241 |
gc.collect()
|
| 242 |
|
requirements.txt
CHANGED
|
@@ -3,5 +3,4 @@ uvicorn
|
|
| 3 |
httpx
|
| 4 |
openai>=1.0.0
|
| 5 |
pillow
|
| 6 |
-
python-multipart
|
| 7 |
-
aiofiles
|
|
|
|
| 3 |
httpx
|
| 4 |
openai>=1.0.0
|
| 5 |
pillow
|
| 6 |
+
python-multipart
|
|
|