yaoqifa commited on
Commit
bdd5980
·
verified ·
1 Parent(s): ea0d3fc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +282 -282
app.py CHANGED
@@ -1,283 +1,283 @@
1
- import httpx
2
- import re
3
- import base64
4
- import os
5
- import asyncio
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
13
- from fastapi import FastAPI, HTTPException, Request
14
- from fastapi.staticfiles import StaticFiles
15
- from fastapi.responses import FileResponse, JSONResponse
16
- from pydantic import BaseModel
17
- import uvicorn
18
-
19
- # ==========================================
20
- # 1. 配置区域
21
- # ==========================================
22
- CONCURRENCY_LIMITER = asyncio.Semaphore(3)
23
-
24
- DYNAMIC_BLOCK_CACHE = deque(maxlen=200)
25
-
26
- SENSITIVE_WORDS = [
27
- "nsfw", "nude", "naked", "sex", "porn", "hentai",
28
- "裸", "色情", "全裸", "blood", "kill", "murder",
29
- "血腥", "尸体", "毒品", "杀"
30
- ]
31
-
32
- # 精确的枚举表
33
- RESOLUTION_MAP = {
34
- "1:1": {"1k": (1024, 1024), "2k": (2048, 2048), "4k": (4096, 4096)},
35
- "16:9": {"1k": (1280, 720), "2k": (2560, 1440), "4k": (3840, 2160)},
36
- "9:16": {"1k": (720, 1280), "2k": (1440, 2560), "4k": (2160, 3840)},
37
- "4:3": {"1k": (1152, 864), "2k": (2048, 1536), "4k": (2880, 2160)},
38
- "3:4": {"1k": (864, 1152), "2k": (1536, 2048), "4k": (2160, 2880)},
39
- "21:9": {"1k": (1680, 720), "2k": (3360, 1440), "4k": (5040, 2160)},
40
- "2:3": {"1k": (852, 1280), "2k": (1704, 2560), "4k": (2440, 3660)}
41
- }
42
-
43
- IP_REQUEST_HISTORY = {}
44
-
45
- # ==========================================
46
- # 2. 辅助功能
47
- # ==========================================
48
-
49
- def get_real_ip(request: Request):
50
- forwarded = request.headers.get("X-Forwarded-For")
51
- if forwarded:
52
- return forwarded.split(",")[0].strip()
53
- return request.client.host
54
-
55
- def check_ip_rate_limit(ip: str, limit: int = 5, window: int = 60):
56
- now = time.time()
57
- history = IP_REQUEST_HISTORY.get(ip, [])
58
- valid_history = [t for t in history if now - t < window]
59
- if len(valid_history) >= limit:
60
- IP_REQUEST_HISTORY[ip] = valid_history
61
- return True
62
- valid_history.append(now)
63
- IP_REQUEST_HISTORY[ip] = valid_history
64
- if len(IP_REQUEST_HISTORY) > 5000: IP_REQUEST_HISTORY.clear()
65
- return False
66
-
67
- def contains_local_sensitive_words(text: str):
68
- if text in DYNAMIC_BLOCK_CACHE: return True, text
69
- text_lower = text.lower()
70
- for word in SENSITIVE_WORDS:
71
- if word and word.lower() in text_lower: return True, word
72
- return False, None
73
-
74
- # ==========================================
75
- # 3. 百度审核 & 生成逻辑
76
- # ==========================================
77
-
78
- _BAIDU_TOKEN_CACHE = {"token": None, "expires_at": 0}
79
-
80
- async def get_baidu_access_token():
81
- ak = os.getenv("BAIDU_API_KEY", "").strip()
82
- sk = os.getenv("BAIDU_SECRET_KEY", "").strip()
83
- if not ak or not sk: return None
84
- now = time.time()
85
- if _BAIDU_TOKEN_CACHE["token"] and now < _BAIDU_TOKEN_CACHE["expires_at"]:
86
- return _BAIDU_TOKEN_CACHE["token"]
87
-
88
- url = "https://aip.baidubce.com/oauth/2.0/token"
89
- params = {"grant_type": "client_credentials", "client_id": ak, "client_secret": sk}
90
- try:
91
- async with httpx.AsyncClient(timeout=10) as client:
92
- resp = await client.post(url, params=params)
93
- token = resp.json().get("access_token")
94
- if token:
95
- _BAIDU_TOKEN_CACHE["token"] = token
96
- _BAIDU_TOKEN_CACHE["expires_at"] = now + 1728000
97
- return token
98
- except: return None
99
-
100
- async def check_baidu_text_censor(text):
101
- token = await get_baidu_access_token()
102
- if not token: return False, None
103
-
104
- url = f"https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined?access_token={token}"
105
- headers = {'Content-Type': 'application/x-www-form-urlencoded'}
106
- data = {'text': text}
107
-
108
- try:
109
- async with httpx.AsyncClient(timeout=10) as client:
110
- resp = await client.post(url, data=data, headers=headers)
111
- result = resp.json()
112
- if result.get('conclusionType') == 2:
113
- msg = [i.get('msg') for i in result.get('data', [])]
114
- reason = ",".join(msg) if msg else "违规"
115
- if text not in DYNAMIC_BLOCK_CACHE:
116
- DYNAMIC_BLOCK_CACHE.append(text)
117
- print(f"🔒 [Cache] 新增违规: {text[:10]}...")
118
- return True, reason
119
- elif result.get('conclusionType') == 3: return True, "疑似违规"
120
- return False, None
121
- except: return False, None
122
-
123
- class GenerateRequest(BaseModel):
124
- api_key: str
125
- model: str
126
- prompt: str
127
- ratio: str
128
- scale: str
129
- format: str
130
- # ⚠️ custom_size 已移除
131
-
132
- def process_image_in_memory(image_bytes: bytes, target_format: str, target_size: tuple = None) -> str:
133
- try:
134
- with Image.open(BytesIO(image_bytes)) as img:
135
- out = BytesIO()
136
- final_img = img
137
- status_msg = f"[原图直出] 尺寸: {img.size}"
138
-
139
- if target_size:
140
- w_diff = abs(img.size[0] - target_size[0])
141
- h_diff = abs(img.size[1] - target_size[1])
142
- if w_diff > 50 or h_diff > 50:
143
- print(f"⚠️ [Resize] {img.size} -> {target_size}")
144
- final_img = img.resize(target_size, Image.Resampling.LANCZOS)
145
- status_msg = f"[触发放大] -> {target_size}"
146
- else:
147
- status_msg = f"[原图直出] 符合预期"
148
- print(f"✅ {status_msg}")
149
-
150
- fmt = "JPEG" if target_format == "jpg" else "PNG"
151
- final_img = final_img.convert("RGB") if target_format == "jpg" else final_img
152
- final_img.save(out, format=fmt, quality=95)
153
- return base64.b64encode(out.getvalue()).decode('utf-8')
154
- except Exception as e:
155
- raise Exception(f"Image Error: {e}")
156
- finally:
157
- gc.collect()
158
-
159
- async def download_image_as_bytes(url):
160
- print(f"📥 下载: {url}")
161
- async with httpx.AsyncClient(timeout=180) as client:
162
- r = await client.get(url)
163
- if r.status_code == 200: return r.content
164
- raise Exception(f"HTTP {r.status_code}")
165
-
166
- async def core_generate(req: GenerateRequest):
167
- # 1. 纯查表逻辑 (不再处理 custom)
168
- ratio_key = req.ratio.split(' ')[0] # 提取 "16:9"
169
-
170
- # 默认兜底
171
- target_w, target_h = 1024, 1024
172
-
173
- if ratio_key in RESOLUTION_MAP:
174
- if req.scale in RESOLUTION_MAP[ratio_key]:
175
- target_w, target_h = RESOLUTION_MAP[ratio_key][req.scale]
176
- else:
177
- # 如果 scale 不在表里,默认 1k
178
- target_w, target_h = RESOLUTION_MAP[ratio_key]["1k"]
179
-
180
- api_size_str = f"{target_w}x{target_h}"
181
-
182
- # 2. Prompt 处理
183
- final_prompt = req.prompt
184
- if "gemini" in req.model.lower():
185
- quality_prompt = "standard quality"
186
- if req.scale == "4k": quality_prompt = "Extreme High Quality, 4K Resolution"
187
- elif req.scale == "2k": quality_prompt = "High Quality, 2K Resolution"
188
-
189
- suffix = f". (Settings: Aspect Ratio {ratio_key}, Quality {quality_prompt}, Target Size {api_size_str})"
190
- final_prompt = f"{req.prompt} {suffix}"
191
-
192
- # 3. API 请求
193
- client = AsyncOpenAI(api_key=req.api_key, base_url="https://api.cloudapp.ink/v1", max_retries=0, timeout=60.0)
194
- img_b = None
195
-
196
- if "gemini" in req.model.lower():
197
- print(f"🟣 Gemini: {req.model}")
198
- res = await client.chat.completions.create(
199
- model=req.model,
200
- messages=[{"role":"user","content":final_prompt}],
201
- extra_body={"modalities":["image","text"]}
202
- )
203
- c = res.choices[0].message.content
204
- u = re.search(r"!\[.*?\]\((https?://[^\)]+)\)", c) or re.search(r"(https?://\S+\.(?:png|jpg|jpeg|webp))", c)
205
- if u: img_b = await download_image_as_bytes(u.group(1))
206
- elif "base64," in c: img_b = base64.b64decode(c.split("base64,")[1].split(")")[0].strip())
207
- else: raise Exception("No Image Found")
208
- else:
209
- print(f"🔵 Standard: {req.model} | 请求 {api_size_str}")
210
- res = await client.images.generate(
211
- model=req.model, prompt=final_prompt, n=1, size=api_size_str, response_format="b64_json"
212
- )
213
- d = res.data[0]
214
- if getattr(d,'b64_json',None): img_b = base64.b64decode(d.b64_json)
215
- elif hasattr(d,'url'): img_b = await download_image_as_bytes(d.url)
216
- else: raise Exception("No Data")
217
-
218
- return process_image_in_memory(img_b, req.format, target_size=(target_w, target_h))
219
-
220
- # ==========================================
221
- # 4. FastAPI App
222
- # ==========================================
223
- app = FastAPI()
224
- app.mount("/static", StaticFiles(directory="static"), name="static")
225
-
226
- @app.get("/")
227
- async def read_index(): return FileResponse('static/index.html')
228
-
229
- @app.get("/health")
230
- def health(): return {"status": "ok"}
231
-
232
- @app.post("/api/generate")
233
- async def generate_api(req: GenerateRequest, request: Request):
234
- ip = get_real_ip(request)
235
-
236
- # --- 🔒 API Key 脱敏处理 ---
237
- # 如果 Key 长度不足 8 位,显示全部;否则只显示后 8 位,前面用 * 代替
238
- key_suffix = req.api_key[-8:] if len(req.api_key) >= 8 else req.api_key
239
- masked_key = f"******{key_suffix}"
240
-
241
- # --- 📝 增强日志记录 ---
242
- timestamp = datetime.now().strftime('%H:%M:%S')
243
- print("\n" + "="*60)
244
- print(f"🚀 [Req] {timestamp} | IP: {ip}")
245
- print(f"🔑 Key: {masked_key}") # 显示后8位
246
- print(f"📌 Model: {req.model} | Scale: {req.scale} | Ratio: {req.ratio}")
247
- print("-" * 60)
248
- print(f"💡 Prompt (Full):") # 记录完整提示词
249
- print(req.prompt)
250
- print("="*60 + "\n")
251
-
252
- # 1. IP 限流
253
- if check_ip_rate_limit(ip, 5, 60):
254
- print(f"⛔ [Rate-Limit] IP {ip} 请求过快")
255
- return JSONResponse({"status": "error", "message": "请求过快"}, 429)
256
-
257
- # 2. 本地敏感词拦截
258
- is_loc, word = contains_local_sensitive_words(req.prompt)
259
- if is_loc:
260
- print(f"🚫 [Local] 拦截: {word}")
261
- return JSONResponse({"status": "error", "message": f"违规内容: {word}"}, 200)
262
-
263
- # 3. 百度 API 检查
264
- is_bd, reason = await check_baidu_text_censor(req.prompt)
265
- if is_bd:
266
- print(f"🚫 [Baidu] 拦截: {reason}")
267
- return JSONResponse({"status": "error", "message": f"审核未通过: {reason}"}, 200)
268
-
269
- # 4. 执行生成
270
- async with CONCURRENCY_LIMITER:
271
- try:
272
- start_time = time.time()
273
- b64 = await core_generate(req)
274
- print(f"✅ [Success] 耗时: {time.time()-start_time:.2f}s")
275
- return {"status": "success", "image_base64": b64}
276
- except Exception as e:
277
- print(f"❌ [Error] {e}")
278
- return JSONResponse({"status": "error", "message": str(e)}, 200)
279
- finally:
280
- gc.collect()
281
-
282
- if __name__ == "__main__":
283
  uvicorn.run(app, host="0.0.0.0", port=7860)
 
1
+ import httpx
2
+ import re
3
+ import base64
4
+ import os
5
+ import asyncio
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
13
+ from fastapi import FastAPI, HTTPException, Request
14
+ from fastapi.staticfiles import StaticFiles
15
+ from fastapi.responses import FileResponse, JSONResponse
16
+ from pydantic import BaseModel
17
+ import uvicorn
18
+
19
+ # ==========================================
20
+ # 1. 配置区域
21
+ # ==========================================
22
+ CONCURRENCY_LIMITER = asyncio.Semaphore(5)
23
+
24
+ DYNAMIC_BLOCK_CACHE = deque(maxlen=200)
25
+
26
+ SENSITIVE_WORDS = [
27
+ "nsfw", "nude", "naked", "sex", "porn", "hentai",
28
+ "裸", "色情", "全裸", "blood", "kill", "murder",
29
+ "血腥", "尸体", "毒品", "杀"
30
+ ]
31
+
32
+ # 精确的枚举表
33
+ RESOLUTION_MAP = {
34
+ "1:1": {"1k": (1024, 1024), "2k": (2048, 2048), "4k": (4096, 4096)},
35
+ "16:9": {"1k": (1280, 720), "2k": (2560, 1440), "4k": (3840, 2160)},
36
+ "9:16": {"1k": (720, 1280), "2k": (1440, 2560), "4k": (2160, 3840)},
37
+ "4:3": {"1k": (1152, 864), "2k": (2048, 1536), "4k": (2880, 2160)},
38
+ "3:4": {"1k": (864, 1152), "2k": (1536, 2048), "4k": (2160, 2880)},
39
+ "21:9": {"1k": (1680, 720), "2k": (3360, 1440), "4k": (5040, 2160)},
40
+ "2:3": {"1k": (852, 1280), "2k": (1704, 2560), "4k": (2440, 3660)}
41
+ }
42
+
43
+ IP_REQUEST_HISTORY = {}
44
+
45
+ # ==========================================
46
+ # 2. 辅助功能
47
+ # ==========================================
48
+
49
+ def get_real_ip(request: Request):
50
+ forwarded = request.headers.get("X-Forwarded-For")
51
+ if forwarded:
52
+ return forwarded.split(",")[0].strip()
53
+ return request.client.host
54
+
55
+ def check_ip_rate_limit(ip: str, limit: int = 5, window: int = 60):
56
+ now = time.time()
57
+ history = IP_REQUEST_HISTORY.get(ip, [])
58
+ valid_history = [t for t in history if now - t < window]
59
+ if len(valid_history) >= limit:
60
+ IP_REQUEST_HISTORY[ip] = valid_history
61
+ return True
62
+ valid_history.append(now)
63
+ IP_REQUEST_HISTORY[ip] = valid_history
64
+ if len(IP_REQUEST_HISTORY) > 5000: IP_REQUEST_HISTORY.clear()
65
+ return False
66
+
67
+ def contains_local_sensitive_words(text: str):
68
+ if text in DYNAMIC_BLOCK_CACHE: return True, text
69
+ text_lower = text.lower()
70
+ for word in SENSITIVE_WORDS:
71
+ if word and word.lower() in text_lower: return True, word
72
+ return False, None
73
+
74
+ # ==========================================
75
+ # 3. 百度审核 & 生成逻辑
76
+ # ==========================================
77
+
78
+ _BAIDU_TOKEN_CACHE = {"token": None, "expires_at": 0}
79
+
80
+ async def get_baidu_access_token():
81
+ ak = os.getenv("BAIDU_API_KEY", "").strip()
82
+ sk = os.getenv("BAIDU_SECRET_KEY", "").strip()
83
+ if not ak or not sk: return None
84
+ now = time.time()
85
+ if _BAIDU_TOKEN_CACHE["token"] and now < _BAIDU_TOKEN_CACHE["expires_at"]:
86
+ return _BAIDU_TOKEN_CACHE["token"]
87
+
88
+ url = "https://aip.baidubce.com/oauth/2.0/token"
89
+ params = {"grant_type": "client_credentials", "client_id": ak, "client_secret": sk}
90
+ try:
91
+ async with httpx.AsyncClient(timeout=10) as client:
92
+ resp = await client.post(url, params=params)
93
+ token = resp.json().get("access_token")
94
+ if token:
95
+ _BAIDU_TOKEN_CACHE["token"] = token
96
+ _BAIDU_TOKEN_CACHE["expires_at"] = now + 1728000
97
+ return token
98
+ except: return None
99
+
100
+ async def check_baidu_text_censor(text):
101
+ token = await get_baidu_access_token()
102
+ if not token: return False, None
103
+
104
+ url = f"https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined?access_token={token}"
105
+ headers = {'Content-Type': 'application/x-www-form-urlencoded'}
106
+ data = {'text': text}
107
+
108
+ try:
109
+ async with httpx.AsyncClient(timeout=20) as client:
110
+ resp = await client.post(url, data=data, headers=headers)
111
+ result = resp.json()
112
+ if result.get('conclusionType') == 2:
113
+ msg = [i.get('msg') for i in result.get('data', [])]
114
+ reason = ",".join(msg) if msg else "违规"
115
+ if text not in DYNAMIC_BLOCK_CACHE:
116
+ DYNAMIC_BLOCK_CACHE.append(text)
117
+ print(f"🔒 [Cache] 新增违规: {text[:10]}...")
118
+ return True, reason
119
+ elif result.get('conclusionType') == 3: return True, "疑似违规"
120
+ return False, None
121
+ except: return False, None
122
+
123
+ class GenerateRequest(BaseModel):
124
+ api_key: str
125
+ model: str
126
+ prompt: str
127
+ ratio: str
128
+ scale: str
129
+ format: str
130
+ # ⚠️ custom_size 已移除
131
+
132
+ def process_image_in_memory(image_bytes: bytes, target_format: str, target_size: tuple = None) -> str:
133
+ try:
134
+ with Image.open(BytesIO(image_bytes)) as img:
135
+ out = BytesIO()
136
+ final_img = img
137
+ status_msg = f"[原图直出] 尺寸: {img.size}"
138
+
139
+ if target_size:
140
+ w_diff = abs(img.size[0] - target_size[0])
141
+ h_diff = abs(img.size[1] - target_size[1])
142
+ if w_diff > 50 or h_diff > 50:
143
+ print(f"⚠️ [Resize] {img.size} -> {target_size}")
144
+ final_img = img.resize(target_size, Image.Resampling.LANCZOS)
145
+ status_msg = f"[触发放大] -> {target_size}"
146
+ else:
147
+ status_msg = f"[原图直出] 符合预期"
148
+ print(f"✅ {status_msg}")
149
+
150
+ fmt = "JPEG" if target_format == "jpg" else "PNG"
151
+ final_img = final_img.convert("RGB") if target_format == "jpg" else final_img
152
+ final_img.save(out, format=fmt, quality=95)
153
+ return base64.b64encode(out.getvalue()).decode('utf-8')
154
+ except Exception as e:
155
+ raise Exception(f"Image Error: {e}")
156
+ finally:
157
+ gc.collect()
158
+
159
+ async def download_image_as_bytes(url):
160
+ print(f"📥 下载: {url}")
161
+ async with httpx.AsyncClient(timeout=360) as client:
162
+ r = await client.get(url)
163
+ if r.status_code == 200: return r.content
164
+ raise Exception(f"HTTP {r.status_code}")
165
+
166
+ async def core_generate(req: GenerateRequest):
167
+ # 1. 纯查表逻辑 (不再处理 custom)
168
+ ratio_key = req.ratio.split(' ')[0] # 提取 "16:9"
169
+
170
+ # 默认兜底
171
+ target_w, target_h = 1024, 1024
172
+
173
+ if ratio_key in RESOLUTION_MAP:
174
+ if req.scale in RESOLUTION_MAP[ratio_key]:
175
+ target_w, target_h = RESOLUTION_MAP[ratio_key][req.scale]
176
+ else:
177
+ # 如果 scale 不在表里,默认 1k
178
+ target_w, target_h = RESOLUTION_MAP[ratio_key]["1k"]
179
+
180
+ api_size_str = f"{target_w}x{target_h}"
181
+
182
+ # 2. Prompt 处理
183
+ final_prompt = req.prompt
184
+ if "gemini" in req.model.lower():
185
+ quality_prompt = "standard quality"
186
+ if req.scale == "4k": quality_prompt = "Extreme High Quality, 4K Resolution"
187
+ elif req.scale == "2k": quality_prompt = "High Quality, 2K Resolution"
188
+
189
+ suffix = f". (Settings: Aspect Ratio {ratio_key}, Quality {quality_prompt}, Target Size {api_size_str})"
190
+ final_prompt = f"{req.prompt} {suffix}"
191
+
192
+ # 3. API 请求
193
+ client = AsyncOpenAI(api_key=req.api_key, base_url="https://api.cloudapp.ink/v1", max_retries=0, timeout=60.0)
194
+ img_b = None
195
+
196
+ if "gemini" in req.model.lower():
197
+ print(f"🟣 Gemini: {req.model}")
198
+ res = await client.chat.completions.create(
199
+ model=req.model,
200
+ messages=[{"role":"user","content":final_prompt}],
201
+ extra_body={"modalities":["image","text"]}
202
+ )
203
+ c = res.choices[0].message.content
204
+ u = re.search(r"!\[.*?\]\((https?://[^\)]+)\)", c) or re.search(r"(https?://\S+\.(?:png|jpg|jpeg|webp))", c)
205
+ if u: img_b = await download_image_as_bytes(u.group(1))
206
+ elif "base64," in c: img_b = base64.b64decode(c.split("base64,")[1].split(")")[0].strip())
207
+ else: raise Exception("No Image Found")
208
+ else:
209
+ print(f"🔵 Standard: {req.model} | 请求 {api_size_str}")
210
+ res = await client.images.generate(
211
+ model=req.model, prompt=final_prompt, n=1, size=api_size_str, response_format="b64_json"
212
+ )
213
+ d = res.data[0]
214
+ if getattr(d,'b64_json',None): img_b = base64.b64decode(d.b64_json)
215
+ elif hasattr(d,'url'): img_b = await download_image_as_bytes(d.url)
216
+ else: raise Exception("No Data")
217
+
218
+ return process_image_in_memory(img_b, req.format, target_size=(target_w, target_h))
219
+
220
+ # ==========================================
221
+ # 4. FastAPI App
222
+ # ==========================================
223
+ app = FastAPI()
224
+ app.mount("/static", StaticFiles(directory="static"), name="static")
225
+
226
+ @app.get("/")
227
+ async def read_index(): return FileResponse('static/index.html')
228
+
229
+ @app.get("/health")
230
+ def health(): return {"status": "ok"}
231
+
232
+ @app.post("/api/generate")
233
+ async def generate_api(req: GenerateRequest, request: Request):
234
+ ip = get_real_ip(request)
235
+
236
+ # --- 🔒 API Key 脱敏处理 ---
237
+ # 如果 Key 长度不足 8 位,显示全部;否则只显示后 8 位,前面用 * 代替
238
+ key_suffix = req.api_key[-8:] if len(req.api_key) >= 8 else req.api_key
239
+ masked_key = f"******{key_suffix}"
240
+
241
+ # --- 📝 增强日志记录 ---
242
+ timestamp = datetime.now().strftime('%H:%M:%S')
243
+ print("\n" + "="*60)
244
+ print(f"🚀 [Req] {timestamp} | IP: {ip}")
245
+ print(f"🔑 Key: {masked_key}") # 显示后8位
246
+ print(f"📌 Model: {req.model} | Scale: {req.scale} | Ratio: {req.ratio}")
247
+ print("-" * 60)
248
+ print(f"💡 Prompt (Full):") # 记录完整提示词
249
+ print(req.prompt)
250
+ print("="*60 + "\n")
251
+
252
+ # 1. IP 限流
253
+ if check_ip_rate_limit(ip, 3, 60):
254
+ print(f"⛔ [Rate-Limit] IP {ip} 请求过快")
255
+ return JSONResponse({"status": "error", "message": "请求过快"}, 429)
256
+
257
+ # 2. 本地敏感词拦截
258
+ is_loc, word = contains_local_sensitive_words(req.prompt)
259
+ if is_loc:
260
+ print(f"🚫 [Local] 拦截: {word}")
261
+ return JSONResponse({"status": "error", "message": f"违规内容: {word}"}, 200)
262
+
263
+ # 3. 百度 API 检查
264
+ is_bd, reason = await check_baidu_text_censor(req.prompt)
265
+ if is_bd:
266
+ print(f"🚫 [Baidu] 拦截: {reason}")
267
+ return JSONResponse({"status": "error", "message": f"审核未通过: {reason}"}, 200)
268
+
269
+ # 4. 执行生成
270
+ async with CONCURRENCY_LIMITER:
271
+ try:
272
+ start_time = time.time()
273
+ b64 = await core_generate(req)
274
+ print(f"✅ [Success] 耗时: {time.time()-start_time:.2f}s")
275
+ return {"status": "success", "image_base64": b64}
276
+ except Exception as e:
277
+ print(f"❌ [Error] {e}")
278
+ return JSONResponse({"status": "error", "message": str(e)}, 200)
279
+ finally:
280
+ gc.collect()
281
+
282
+ if __name__ == "__main__":
283
  uvicorn.run(app, host="0.0.0.0", port=7860)