Upload 3 files
Browse files- Dockerfile +21 -0
- app.py +326 -0
- requirements.txt +6 -0
Dockerfile
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.10-slim
|
| 2 |
+
|
| 3 |
+
WORKDIR /app
|
| 4 |
+
|
| 5 |
+
# 复制依赖并安装
|
| 6 |
+
COPY requirements.txt .
|
| 7 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 8 |
+
|
| 9 |
+
# 复制代码
|
| 10 |
+
COPY . .
|
| 11 |
+
|
| 12 |
+
# 关键:赋予权限,解决 OpenPermissionError
|
| 13 |
+
RUN chmod -R 777 /app
|
| 14 |
+
|
| 15 |
+
# 环境变量
|
| 16 |
+
ENV GRADIO_SERVER_NAME="0.0.0.0" \
|
| 17 |
+
GRADIO_SERVER_PORT="7860"
|
| 18 |
+
|
| 19 |
+
EXPOSE 7860
|
| 20 |
+
|
| 21 |
+
CMD ["python", "app.py"]
|
app.py
ADDED
|
@@ -0,0 +1,326 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import httpx # 替换 requests 实现异步
|
| 3 |
+
import re
|
| 4 |
+
import base64
|
| 5 |
+
import os
|
| 6 |
+
import asyncio
|
| 7 |
+
from PIL import Image
|
| 8 |
+
from openai import AsyncOpenAI # 使用异步客户端
|
| 9 |
+
from fastapi import FastAPI
|
| 10 |
+
import uvicorn
|
| 11 |
+
|
| 12 |
+
# ==========================================
|
| 13 |
+
# 全局配置
|
| 14 |
+
# ==========================================
|
| 15 |
+
|
| 16 |
+
# 1. 基础分辨率
|
| 17 |
+
AR_BASES = {
|
| 18 |
+
"1:1 (SDXL标准 1024)": (1024, 1024),
|
| 19 |
+
"16:9 (SDXL标准 768p)": (1344, 768),
|
| 20 |
+
"16:9 (1080p Full HD)": (1920, 1080),
|
| 21 |
+
"9:16 (手机竖屏)": (768, 1344),
|
| 22 |
+
"4:3 (标准)": (1152, 896),
|
| 23 |
+
"21:9 (宽屏)": (1536, 640)
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
# 2. 倍率 (Scale)
|
| 27 |
+
SCALE_MULTIPLIERS = {
|
| 28 |
+
"1k": 1.0,
|
| 29 |
+
"2k": 1.5,
|
| 30 |
+
"4k": 2.0
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
# ==========================================
|
| 34 |
+
# 工具函数
|
| 35 |
+
# ==========================================
|
| 36 |
+
|
| 37 |
+
def process_image_format(image_path, target_format):
|
| 38 |
+
"""
|
| 39 |
+
CPU 密集型任务,保持同步即可,影响不大
|
| 40 |
+
"""
|
| 41 |
+
try:
|
| 42 |
+
print(f"⚙️ [System] 正在转换格式: {target_format.upper()}...")
|
| 43 |
+
img = Image.open(image_path)
|
| 44 |
+
base_name = os.path.splitext(image_path)[0]
|
| 45 |
+
output_filename = f"{base_name}_final.{target_format}"
|
| 46 |
+
|
| 47 |
+
if target_format == "jpg":
|
| 48 |
+
img = img.convert("RGB")
|
| 49 |
+
img.save(output_filename, format="JPEG", quality=95)
|
| 50 |
+
else:
|
| 51 |
+
img.save(output_filename, format="PNG")
|
| 52 |
+
|
| 53 |
+
print(f"✅ [System] 转换完成: {output_filename}")
|
| 54 |
+
return output_filename
|
| 55 |
+
except Exception as e:
|
| 56 |
+
print(f"⚠️ [System] 格式转换失败: {e},将返回原图")
|
| 57 |
+
return image_path
|
| 58 |
+
|
| 59 |
+
async def download_image_async(url, mode_prefix):
|
| 60 |
+
"""
|
| 61 |
+
异步下载图片,非阻塞
|
| 62 |
+
"""
|
| 63 |
+
filename = f"temp_{mode_prefix.lower().strip('[]')}.png"
|
| 64 |
+
print(f"{mode_prefix} 检测到 URL,开始异步下载: {url}")
|
| 65 |
+
|
| 66 |
+
try:
|
| 67 |
+
async with httpx.AsyncClient(timeout=30) as client:
|
| 68 |
+
response = await client.get(url)
|
| 69 |
+
|
| 70 |
+
if response.status_code == 200:
|
| 71 |
+
# 写入文件操作通常很快,直接同步写入即可,或者用 aiofiles (这里保持简单)
|
| 72 |
+
with open(filename, "wb") as f:
|
| 73 |
+
f.write(response.content)
|
| 74 |
+
print(f"{mode_prefix} ✅ 图片下载并保存成功")
|
| 75 |
+
return filename
|
| 76 |
+
else:
|
| 77 |
+
raise Exception(f"HTTP {response.status_code}")
|
| 78 |
+
except Exception as e:
|
| 79 |
+
raise Exception(f"下载失败: {e}")
|
| 80 |
+
|
| 81 |
+
# ==========================================
|
| 82 |
+
# 核心逻辑 (异步)
|
| 83 |
+
# ==========================================
|
| 84 |
+
|
| 85 |
+
# 分支 1: Standard Logic (Nano Banana)
|
| 86 |
+
async def generate_and_save_image_logic(client: AsyncOpenAI, model, prompt, size_str):
|
| 87 |
+
PREFIX = "🔵 [Standard]"
|
| 88 |
+
print(f"{PREFIX} 1. 开始请求 | 模型: {model} | 分辨率: {size_str}")
|
| 89 |
+
|
| 90 |
+
try:
|
| 91 |
+
# 异步调用 API
|
| 92 |
+
response = await client.images.generate(
|
| 93 |
+
model=model,
|
| 94 |
+
prompt=prompt,
|
| 95 |
+
n=1,
|
| 96 |
+
size=size_str,
|
| 97 |
+
response_format="b64_json"
|
| 98 |
+
)
|
| 99 |
+
print(f"{PREFIX} 2. 收到响应 | 状态: Success")
|
| 100 |
+
|
| 101 |
+
first_data = response.data[0]
|
| 102 |
+
image_b64 = getattr(first_data, 'b64_json', None)
|
| 103 |
+
|
| 104 |
+
# URL 兼容
|
| 105 |
+
if not image_b64 and hasattr(first_data, 'url'):
|
| 106 |
+
print(f"{PREFIX} 3. 转为 URL 下载")
|
| 107 |
+
return await download_image_async(first_data.url, PREFIX)
|
| 108 |
+
|
| 109 |
+
if image_b64:
|
| 110 |
+
print(f"{PREFIX} 3. 解码 Base64...")
|
| 111 |
+
image_data = base64.b64decode(image_b64)
|
| 112 |
+
filename = "temp_standard.png"
|
| 113 |
+
with open(filename, "wb") as f:
|
| 114 |
+
f.write(image_data)
|
| 115 |
+
print(f"{PREFIX} ✅ 4. 保存成功: {filename}")
|
| 116 |
+
return filename
|
| 117 |
+
|
| 118 |
+
raise Exception("未找到图片数据")
|
| 119 |
+
|
| 120 |
+
except Exception as e:
|
| 121 |
+
print(f"{PREFIX} ❌ 错误: {e}")
|
| 122 |
+
raise e
|
| 123 |
+
|
| 124 |
+
# 分支 2: Chat Logic (Gemini)
|
| 125 |
+
async def handle_gemini_output_logic(client: AsyncOpenAI, model, prompt):
|
| 126 |
+
PREFIX = "🟣 [Chat]"
|
| 127 |
+
print(f"{PREFIX} 1. 开始请求 | 模型: {model}")
|
| 128 |
+
print(f"{PREFIX} Prompt片段: {prompt[:60]}...")
|
| 129 |
+
|
| 130 |
+
try:
|
| 131 |
+
# 异步调用 API
|
| 132 |
+
response = await client.chat.completions.create(
|
| 133 |
+
model=model,
|
| 134 |
+
messages=[{"role": "user", "content": prompt}],
|
| 135 |
+
extra_body={"modalities": ["image", "text"]}
|
| 136 |
+
)
|
| 137 |
+
print(f"{PREFIX} 2. 收到响应 | 状态: Success")
|
| 138 |
+
|
| 139 |
+
content = response.choices[0].message.content
|
| 140 |
+
filename = "temp_chat.png"
|
| 141 |
+
|
| 142 |
+
# 正则提取
|
| 143 |
+
url_pattern = r"!\[.*?\]\((https?://[^\)]+)\)"
|
| 144 |
+
url_match = re.search(url_pattern, content)
|
| 145 |
+
if url_match:
|
| 146 |
+
return await download_image_async(url_match.group(1), PREFIX)
|
| 147 |
+
|
| 148 |
+
raw_url_pattern = r"(https?://\S+\.(?:png|jpg|jpeg|webp))"
|
| 149 |
+
raw_url_match = re.search(raw_url_pattern, content)
|
| 150 |
+
if raw_url_match:
|
| 151 |
+
return await download_image_async(raw_url_match.group(1), PREFIX)
|
| 152 |
+
|
| 153 |
+
if "base64," in content:
|
| 154 |
+
base64_data = content.split("base64,")[1].split(")")[0].strip()
|
| 155 |
+
with open(filename, "wb") as f:
|
| 156 |
+
f.write(base64.b64decode(base64_data))
|
| 157 |
+
print(f"{PREFIX} ✅ 4. Base64 保存成功")
|
| 158 |
+
return filename
|
| 159 |
+
|
| 160 |
+
print(f"{PREFIX} ❌ 未能识别图片内容: {content[:100]}")
|
| 161 |
+
raise Exception("未能从对话中提取出图片")
|
| 162 |
+
|
| 163 |
+
except Exception as e:
|
| 164 |
+
print(f"{PREFIX} ❌ 错误: {e}")
|
| 165 |
+
raise e
|
| 166 |
+
|
| 167 |
+
# 主调度入口 (Async)
|
| 168 |
+
async def main_generate(api_key, model_name, prompt, ratio_selection, scale_selection, custom_size_input, format_selection):
|
| 169 |
+
if not api_key:
|
| 170 |
+
raise gr.Error("请输入 API Key")
|
| 171 |
+
|
| 172 |
+
# 分辨率计算
|
| 173 |
+
final_size = "1024x1024"
|
| 174 |
+
ratio_str = "1:1"
|
| 175 |
+
|
| 176 |
+
if ratio_selection == "自定义 (Custom)":
|
| 177 |
+
final_size = custom_size_input.strip()
|
| 178 |
+
else:
|
| 179 |
+
base_w, base_h = AR_BASES.get(ratio_selection, (1024, 1024))
|
| 180 |
+
multiplier = SCALE_MULTIPLIERS.get(scale_selection, 1.0)
|
| 181 |
+
final_w = int(base_w * multiplier)
|
| 182 |
+
final_h = int(base_h * multiplier)
|
| 183 |
+
final_size = f"{final_w}x{final_h}"
|
| 184 |
+
ratio_str = ratio_selection.split(" ")[0]
|
| 185 |
+
|
| 186 |
+
# Prompt 处理
|
| 187 |
+
final_prompt = prompt
|
| 188 |
+
if "gemini" in model_name.lower():
|
| 189 |
+
if ratio_selection == "自定义 (Custom)":
|
| 190 |
+
final_prompt = f"{prompt} --resolution {final_size}"
|
| 191 |
+
else:
|
| 192 |
+
final_prompt = f"{prompt} --ar {ratio_str} --resolution {final_size}"
|
| 193 |
+
|
| 194 |
+
# 初始化异步客户端
|
| 195 |
+
client = AsyncOpenAI(
|
| 196 |
+
api_key=api_key,
|
| 197 |
+
base_url="https://api.cloudapp.ink/v1"
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
try:
|
| 201 |
+
if "gemini" in model_name.lower():
|
| 202 |
+
temp_path = await handle_gemini_output_logic(client, model_name, final_prompt)
|
| 203 |
+
else:
|
| 204 |
+
temp_path = await generate_and_save_image_logic(client, model_name, final_prompt, final_size)
|
| 205 |
+
|
| 206 |
+
final_path = process_image_format(temp_path, format_selection)
|
| 207 |
+
return final_path
|
| 208 |
+
|
| 209 |
+
except Exception as e:
|
| 210 |
+
error_str = str(e)
|
| 211 |
+
if "500" in error_str:
|
| 212 |
+
gr.Warning("服务端返回 500。4k 分辨率可能过高,建议尝试 1k 或 2k。")
|
| 213 |
+
raise gr.Error(f"生成失败 (500): {error_str}")
|
| 214 |
+
else:
|
| 215 |
+
raise gr.Error(f"生成失败: {error_str}")
|
| 216 |
+
|
| 217 |
+
# ==========================================
|
| 218 |
+
# UI 构建
|
| 219 |
+
# ==========================================
|
| 220 |
+
|
| 221 |
+
# CSS: 彻底隐藏 Footer
|
| 222 |
+
css = """
|
| 223 |
+
#col-container {max-width: 900px; margin-left: auto; margin-right: auto;}
|
| 224 |
+
footer { display: none !important; }
|
| 225 |
+
.gradio-container footer { display: none !important; }
|
| 226 |
+
"""
|
| 227 |
+
|
| 228 |
+
# JS: 页面加载时强制移除 Footer 元素
|
| 229 |
+
js_remove_footer = """
|
| 230 |
+
function() {
|
| 231 |
+
const footer = document.querySelector("footer");
|
| 232 |
+
if (footer) { footer.remove(); }
|
| 233 |
+
const footerDiv = document.querySelector(".footer");
|
| 234 |
+
if (footerDiv) { footerDiv.remove(); }
|
| 235 |
+
}
|
| 236 |
+
"""
|
| 237 |
+
|
| 238 |
+
with gr.Blocks(css=css, js=js_remove_footer, title="Nano Banana Generator") as demo:
|
| 239 |
+
with gr.Column(elem_id="col-container"):
|
| 240 |
+
gr.Markdown(f"# Nano Banana & Gemini 图片生成")
|
| 241 |
+
gr.Markdown("支持 Nano Banana Pro 4k 及 Gemini 3 Pro 系列模型。")
|
| 242 |
+
|
| 243 |
+
with gr.Row():
|
| 244 |
+
with gr.Column(scale=1):
|
| 245 |
+
api_key_input = gr.Textbox(
|
| 246 |
+
label="API Key",
|
| 247 |
+
type="password",
|
| 248 |
+
placeholder="sk-..."
|
| 249 |
+
)
|
| 250 |
+
|
| 251 |
+
# 模型列表
|
| 252 |
+
model_input = gr.Dropdown(
|
| 253 |
+
label="模型名称",
|
| 254 |
+
choices=[
|
| 255 |
+
"nano-banana",
|
| 256 |
+
"nano-banana-pro",
|
| 257 |
+
"nano-banana-pro-4k",
|
| 258 |
+
"gemini-2.5-flash-image",
|
| 259 |
+
"gemini-3-pro-image",
|
| 260 |
+
"gemini-3-pro-image-preview"
|
| 261 |
+
],
|
| 262 |
+
value="nano-banana",
|
| 263 |
+
allow_custom_value=True
|
| 264 |
+
)
|
| 265 |
+
|
| 266 |
+
with gr.Row():
|
| 267 |
+
ratio_input = gr.Dropdown(
|
| 268 |
+
label="1. 基础比例",
|
| 269 |
+
choices=list(AR_BASES.keys()) + ["自定义 (Custom)"],
|
| 270 |
+
value="16:9 (1080p Full HD)"
|
| 271 |
+
)
|
| 272 |
+
scale_input = gr.Dropdown(
|
| 273 |
+
label="2. 清晰度",
|
| 274 |
+
choices=list(SCALE_MULTIPLIERS.keys()),
|
| 275 |
+
value="1k"
|
| 276 |
+
)
|
| 277 |
+
|
| 278 |
+
custom_size_input = gr.Textbox(
|
| 279 |
+
label="手动分辨率 (WxH)",
|
| 280 |
+
value="1920x1080",
|
| 281 |
+
visible=False
|
| 282 |
+
)
|
| 283 |
+
|
| 284 |
+
format_input = gr.Radio(
|
| 285 |
+
label="输出格式",
|
| 286 |
+
choices=["png", "jpg"],
|
| 287 |
+
value="png"
|
| 288 |
+
)
|
| 289 |
+
|
| 290 |
+
run_btn = gr.Button("🚀 生成图片", variant="primary")
|
| 291 |
+
|
| 292 |
+
with gr.Column(scale=2):
|
| 293 |
+
prompt_input = gr.Textbox(
|
| 294 |
+
label="提示词",
|
| 295 |
+
placeholder="请输入提示词...",
|
| 296 |
+
lines=4
|
| 297 |
+
)
|
| 298 |
+
|
| 299 |
+
result_output = gr.Image(
|
| 300 |
+
label="生成结果",
|
| 301 |
+
type="filepath",
|
| 302 |
+
interactive=False
|
| 303 |
+
)
|
| 304 |
+
|
| 305 |
+
def toggle_custom_box(ratio_val):
|
| 306 |
+
return gr.update(visible=(ratio_val == "自定义 (Custom)"))
|
| 307 |
+
|
| 308 |
+
ratio_input.change(fn=toggle_custom_box, inputs=ratio_input, outputs=custom_size_input)
|
| 309 |
+
|
| 310 |
+
run_btn.click(
|
| 311 |
+
fn=main_generate,
|
| 312 |
+
inputs=[api_key_input, model_input, prompt_input, ratio_input, scale_input, custom_size_input, format_input],
|
| 313 |
+
outputs=[result_output]
|
| 314 |
+
)
|
| 315 |
+
|
| 316 |
+
# ==========================================
|
| 317 |
+
# FastAPI & Health Check
|
| 318 |
+
# ==========================================
|
| 319 |
+
app = FastAPI()
|
| 320 |
+
|
| 321 |
+
@app.get("/health")
|
| 322 |
+
def health_check():
|
| 323 |
+
return {"status": "ok", "message": "Service is healthy"}
|
| 324 |
+
|
| 325 |
+
# 挂载 Gradio 到根路径
|
| 326 |
+
app = gr.mount_gradio_app(app, demo, path="/")
|
requirements.txt
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio
|
| 2 |
+
httpx
|
| 3 |
+
pillow
|
| 4 |
+
openai>=1.0.0
|
| 5 |
+
fastapi
|
| 6 |
+
uvicorn
|