Spaces:
Running

yaoqifa commited on
Commit
f80cfbe
·
verified ·
1 Parent(s): b7437fe

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +35 -24
app.py CHANGED
@@ -211,9 +211,11 @@ async def core_generate(req: GenerateRequest):
211
  target_w, target_h = RESOLUTION_MAP[ratio_key]["1k"]
212
  api_size_str = f"{target_w}x{target_h}"
213
 
214
- # 2. Prompt 处理
 
215
  final_prompt = req.prompt
216
- if "gemini" in req.model.lower():
 
217
  quality_prompt = "standard quality"
218
  if req.scale == "4k": quality_prompt = "Extreme High Quality, 4K Resolution"
219
  elif req.scale == "2k": quality_prompt = "High Quality, 2K Resolution"
@@ -226,45 +228,57 @@ async def core_generate(req: GenerateRequest):
226
  print("🧹 正在预处理参考图...")
227
  clean_init_image = sanitize_input_image(req.init_image)
228
 
229
- # 4. 初始化 OpenAI 客户端
230
  client = AsyncOpenAI(api_key=req.api_key, base_url=f"{app_base_url}/v1", max_retries=0, timeout=360.0)
231
  img_b = None
232
 
233
- # --- 分支 A: Gemini 模型 (使用 Chat Completion 多模态) ---
234
- if "gemini" in req.model.lower():
235
- print(f"🟣 Gemini: {req.model}")
236
  content_parts = [{"type": "text", "text": final_prompt}]
 
 
237
  if clean_init_image:
238
  content_parts.append({
239
  "type": "image_url",
240
  "image_url": {"url": f"data:image/jpeg;base64,{clean_init_image}"}
241
  })
242
 
 
 
 
 
 
 
243
  res = await client.chat.completions.create(
244
  model=req.model,
245
  messages=[{"role":"user","content": content_parts}],
246
- extra_body={"modalities":["image","text"]},
247
  timeout=360.0
248
  )
 
 
249
  c = res.choices[0].message.content
 
250
  u = re.search(r"!\[.*?\]\((https?://[^\)]+)\)", c) or re.search(r"(https?://\S+\.(?:png|jpg|jpeg|webp))", c)
251
- if u: img_b = await download_image_as_bytes(u.group(1))
252
- elif "base64," in c: img_b = base64.b64decode(c.split("base64,")[1].split(")")[0].strip())
253
- else: raise Exception("Gemini 返回中未找到图片数据")
254
-
255
- # --- 分支 B: 非 Gemini 模型 (Nano Banana 等) ---
 
 
 
 
 
256
  else:
257
- # B1: 如果有参考图,采用 edit 接口进行图生图
258
  if clean_init_image:
259
  print(f"🔵 [Edit 接口] 图生图模式: {req.model}")
260
-
261
- # 将清洗后的 Base64 转回二进制流
262
  image_data = base64.b64decode(clean_init_image)
263
  image_file = BytesIO(image_data)
264
- image_file.name = "init_image.jpg" # 必须提供文件名,部分 SDK 内部校验需要
265
 
266
  try:
267
- # 调用 edit 接口
268
  res = await client.images.edit(
269
  model=req.model,
270
  image=image_file,
@@ -272,11 +286,10 @@ async def core_generate(req: GenerateRequest):
272
  n=1,
273
  size=api_size_str,
274
  response_format="b64_json",
275
- extra_body={"strength": 0.75} # 图生图通常需要重绘强度参数
276
  )
277
  except Exception as e:
278
- # 如果 edit 接口报 404 或不支持,尝试回退到普通的 generate 强行传递
279
- print(f"⚠️ Edit 接口调用失败 ({e}),尝试使用 Generations 兼容模式...")
280
  res = await client.images.generate(
281
  model=req.model,
282
  prompt=final_prompt,
@@ -284,8 +297,6 @@ async def core_generate(req: GenerateRequest):
284
  response_format="b64_json",
285
  extra_body={"image": clean_init_image, "strength": 0.75}
286
  )
287
-
288
- # B2: 如果没有参考图,采用普���的 generate 接口进行文生图
289
  else:
290
  print(f"🔵 [Generate 接口] 文生图模式: {req.model}")
291
  res = await client.images.generate(
@@ -296,7 +307,7 @@ async def core_generate(req: GenerateRequest):
296
  response_format="b64_json"
297
  )
298
 
299
- # 处理返回的 Image 对象
300
  d = res.data[0]
301
  if getattr(d, 'b64_json', None):
302
  img_b = base64.b64decode(d.b64_json)
@@ -305,7 +316,7 @@ async def core_generate(req: GenerateRequest):
305
  else:
306
  raise Exception("API 未返回有效的图片数据")
307
 
308
- # 5. 最后进行图片后处理(缩放、格式转换等)
309
  return process_image_in_memory(img_b, req.format, target_size=(target_w, target_h))
310
 
311
  # ==========================================
 
211
  target_w, target_h = RESOLUTION_MAP[ratio_key]["1k"]
212
  api_size_str = f"{target_w}x{target_h}"
213
 
214
+ # 2. Prompt 处理 (针对 Gemini 和 Grok 增加格式描述)
215
+ is_chat_model = "gemini" in req.model.lower() or "grok" in req.model.lower()
216
  final_prompt = req.prompt
217
+
218
+ if is_chat_model:
219
  quality_prompt = "standard quality"
220
  if req.scale == "4k": quality_prompt = "Extreme High Quality, 4K Resolution"
221
  elif req.scale == "2k": quality_prompt = "High Quality, 2K Resolution"
 
228
  print("🧹 正在预处理参考图...")
229
  clean_init_image = sanitize_input_image(req.init_image)
230
 
231
+ # 4. 初始化客户端
232
  client = AsyncOpenAI(api_key=req.api_key, base_url=f"{app_base_url}/v1", max_retries=0, timeout=360.0)
233
  img_b = None
234
 
235
+ # --- 分支 A: Gemini & Grok 模型 (使用 Chat Completion 多模态) ---
236
+ if is_chat_model:
237
+ print(f"🟣 对话模型生图: {req.model}")
238
  content_parts = [{"type": "text", "text": final_prompt}]
239
+
240
+ # 如果有参考图,以多模态方式发送
241
  if clean_init_image:
242
  content_parts.append({
243
  "type": "image_url",
244
  "image_url": {"url": f"data:image/jpeg;base64,{clean_init_image}"}
245
  })
246
 
247
+ # 构造请求体参数
248
+ extra_payload = {"modalities": ["image", "text"]}
249
+ # 如果是 grok,部分 NewAPI 渠道可能需要 render 标志
250
+ if "grok" in req.model.lower():
251
+ extra_payload["render"] = True
252
+
253
  res = await client.chat.completions.create(
254
  model=req.model,
255
  messages=[{"role":"user","content": content_parts}],
256
+ extra_body=extra_payload,
257
  timeout=360.0
258
  )
259
+
260
+ # 提取回复内容
261
  c = res.choices[0].message.content
262
+ # 正则匹配:支持 Markdown 链接、纯 URL 或 Base64
263
  u = re.search(r"!\[.*?\]\((https?://[^\)]+)\)", c) or re.search(r"(https?://\S+\.(?:png|jpg|jpeg|webp))", c)
264
+
265
+ if u:
266
+ img_b = await download_image_as_bytes(u.group(1))
267
+ elif "base64," in c:
268
+ img_b = base64.b64decode(c.split("base64,")[1].split(")")[0].strip())
269
+ else:
270
+ print(f"❌ 模型回复内容: {c}")
271
+ raise Exception(f"{req.model} 返回中未找到图片链接或数据")
272
+
273
+ # --- 分支 B: 非对话类模型 (Nano Banana 等) ---
274
  else:
 
275
  if clean_init_image:
276
  print(f"🔵 [Edit 接口] 图生图模式: {req.model}")
 
 
277
  image_data = base64.b64decode(clean_init_image)
278
  image_file = BytesIO(image_data)
279
+ image_file.name = "init_image.jpg"
280
 
281
  try:
 
282
  res = await client.images.edit(
283
  model=req.model,
284
  image=image_file,
 
286
  n=1,
287
  size=api_size_str,
288
  response_format="b64_json",
289
+ extra_body={"strength": 0.75}
290
  )
291
  except Exception as e:
292
+ print(f"⚠️ Edit 失败,回退至 Generations 模式: {e}")
 
293
  res = await client.images.generate(
294
  model=req.model,
295
  prompt=final_prompt,
 
297
  response_format="b64_json",
298
  extra_body={"image": clean_init_image, "strength": 0.75}
299
  )
 
 
300
  else:
301
  print(f"🔵 [Generate 接口] 文生图模式: {req.model}")
302
  res = await client.images.generate(
 
307
  response_format="b64_json"
308
  )
309
 
310
+ # 处理 Standard 接口返回
311
  d = res.data[0]
312
  if getattr(d, 'b64_json', None):
313
  img_b = base64.b64decode(d.b64_json)
 
316
  else:
317
  raise Exception("API 未返回有效的图片数据")
318
 
319
+ # 5. 后处理
320
  return process_image_in_memory(img_b, req.format, target_size=(target_w, target_h))
321
 
322
  # ==========================================