Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from transformers import AutoModelForImageSegmentation
|
| 3 |
+
import torch
|
| 4 |
+
from torchvision import transforms
|
| 5 |
+
from PIL import Image
|
| 6 |
+
import io
|
| 7 |
+
|
| 8 |
+
# --- 1. 初始化模型 (只會在啟動時執行一次) ---
|
| 9 |
+
model_id = "briaai/RMBG-2.0"
|
| 10 |
+
print(f"正在載入模型: {model_id} ...")
|
| 11 |
+
|
| 12 |
+
try:
|
| 13 |
+
# 載入模型到 CPU (Hugging Face Free Tier 只有 CPU)
|
| 14 |
+
model = AutoModelForImageSegmentation.from_pretrained(model_id, trust_remote_code=True)
|
| 15 |
+
device = torch.device("cpu") # 強制使用 CPU
|
| 16 |
+
model.to(device)
|
| 17 |
+
model.eval() # 設定為評估模式
|
| 18 |
+
print("模型載入成功!")
|
| 19 |
+
except Exception as e:
|
| 20 |
+
print(f"模型載入失敗: {e}")
|
| 21 |
+
|
| 22 |
+
# --- 2. 定義圖像處理邏輯 ---
|
| 23 |
+
def process_image(input_image):
|
| 24 |
+
if input_image is None:
|
| 25 |
+
return None
|
| 26 |
+
|
| 27 |
+
# 紀錄原始尺寸
|
| 28 |
+
orig_w, orig_h = input_image.size
|
| 29 |
+
|
| 30 |
+
# 準備輸入 (RMBG 2.0 建議尺寸為 1024x1024)
|
| 31 |
+
transform_image = transforms.Compose([
|
| 32 |
+
transforms.Resize((1024, 1024)),
|
| 33 |
+
transforms.ToTensor(),
|
| 34 |
+
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
|
| 35 |
+
])
|
| 36 |
+
|
| 37 |
+
input_tensor = transform_image(input_image).unsqueeze(0).to(device)
|
| 38 |
+
|
| 39 |
+
# 推理 (Inference)
|
| 40 |
+
with torch.no_grad():
|
| 41 |
+
preds = model(input_tensor)[0][0]
|
| 42 |
+
# 還原到原始尺寸
|
| 43 |
+
preds = torch.nn.functional.interpolate(preds, size=(orig_h, orig_w), mode='bilinear', align_corners=False)
|
| 44 |
+
preds = torch.sigmoid(preds)
|
| 45 |
+
|
| 46 |
+
# 處理遮罩
|
| 47 |
+
mask = preds.squeeze().cpu().numpy()
|
| 48 |
+
|
| 49 |
+
# 轉回 PIL Image
|
| 50 |
+
mask_img = Image.fromarray((mask * 255).astype('uint8'), mode='L')
|
| 51 |
+
|
| 52 |
+
# 合成去背圖
|
| 53 |
+
output_img = input_image.convert("RGBA")
|
| 54 |
+
output_img.putalpha(mask_img)
|
| 55 |
+
|
| 56 |
+
return output_img
|
| 57 |
+
|
| 58 |
+
# --- 3. 設定 PWA 與手機優化 HTML ---
|
| 59 |
+
# 這些標籤會讓網頁在「加入主畫面」後變成全螢幕 APP
|
| 60 |
+
pwa_header = """
|
| 61 |
+
<head>
|
| 62 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
|
| 63 |
+
<meta name="apple-mobile-web-app-capable" content="yes">
|
| 64 |
+
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
|
| 65 |
+
<meta name="theme-color" content="#0b0f19">
|
| 66 |
+
<title>AI 去背神器</title>
|
| 67 |
+
<style>
|
| 68 |
+
/* 隱藏 Gradio 預設的頁尾,讓畫面更乾淨 */
|
| 69 |
+
footer {display: none !important;}
|
| 70 |
+
.gradio-container {min-height: 100vh !important;}
|
| 71 |
+
</style>
|
| 72 |
+
</head>
|
| 73 |
+
"""
|
| 74 |
+
|
| 75 |
+
# --- 4. 建立 Gradio 介面 ---
|
| 76 |
+
with gr.Blocks(head=pwa_header, theme=gr.themes.Soft()) as app:
|
| 77 |
+
|
| 78 |
+
gr.Markdown(
|
| 79 |
+
"""
|
| 80 |
+
# ✂️ AI 自動去背 (RMBG 2.0)
|
| 81 |
+
上傳照片,自動去除背景。
|
| 82 |
+
"""
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
with gr.Row():
|
| 86 |
+
# 手機上通常是直向排列,Gradio 會自動響應
|
| 87 |
+
with gr.Column():
|
| 88 |
+
input_img = gr.Image(type="pil", label="點擊上傳或拍照", sources=["upload", "clipboard"])
|
| 89 |
+
btn = gr.Button("開始去背", variant="primary", size="lg")
|
| 90 |
+
|
| 91 |
+
with gr.Column():
|
| 92 |
+
output_img = gr.Image(type="pil", label="去背結果 (長按儲存)", format="png", show_download_button=True)
|
| 93 |
+
|
| 94 |
+
# 按鈕事件
|
| 95 |
+
btn.click(fn=process_image, inputs=input_img, outputs=output_img)
|
| 96 |
+
|
| 97 |
+
# 啟動應用
|
| 98 |
+
if __name__ == "__main__":
|
| 99 |
+
app.launch()
|