Update app.py
Browse files
app.py
CHANGED
|
@@ -1,99 +1,84 @@
|
|
|
|
|
| 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 |
-
#
|
| 14 |
-
model = AutoModelForImageSegmentation.from_pretrained(
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 29 |
|
| 30 |
-
#
|
| 31 |
transform_image = transforms.Compose([
|
| 32 |
-
transforms.Resize(
|
| 33 |
transforms.ToTensor(),
|
| 34 |
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
|
| 35 |
])
|
| 36 |
|
| 37 |
-
|
|
|
|
| 38 |
|
| 39 |
-
#
|
| 40 |
with torch.no_grad():
|
| 41 |
-
preds = model(
|
| 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 |
-
|
| 48 |
|
| 49 |
-
# 轉回 PIL
|
| 50 |
-
|
|
|
|
|
|
|
|
|
|
| 51 |
|
| 52 |
# 合成去背圖
|
| 53 |
-
|
| 54 |
-
|
| 55 |
|
| 56 |
-
return
|
| 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 |
-
# ---
|
| 76 |
-
with gr.Blocks(
|
| 77 |
|
| 78 |
-
gr.Markdown(
|
| 79 |
-
|
| 80 |
-
# ✂️ AI 自動去背 (RMBG 2.0)
|
| 81 |
-
上傳照片,自動去除背景。
|
| 82 |
-
"""
|
| 83 |
-
)
|
| 84 |
|
| 85 |
-
with gr.
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 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()
|
|
|
|
| 1 |
+
import os
|
| 2 |
import gradio as gr
|
| 3 |
from transformers import AutoModelForImageSegmentation
|
| 4 |
import torch
|
| 5 |
from torchvision import transforms
|
| 6 |
from PIL import Image
|
|
|
|
| 7 |
|
| 8 |
+
# --- 1. 初始化模型 ---
|
| 9 |
model_id = "briaai/RMBG-2.0"
|
| 10 |
print(f"正在載入模型: {model_id} ...")
|
| 11 |
|
| 12 |
+
hf_token = os.getenv("HF_TOKEN")
|
| 13 |
+
|
| 14 |
+
# 檢查 Token
|
| 15 |
+
if not hf_token:
|
| 16 |
+
print("⚠️ 警告: 未偵測到 HF_TOKEN,請檢查 Settings 中的 Secret。")
|
| 17 |
+
|
| 18 |
try:
|
| 19 |
+
# 載入模型
|
| 20 |
+
model = AutoModelForImageSegmentation.from_pretrained(
|
| 21 |
+
model_id,
|
| 22 |
+
trust_remote_code=True,
|
| 23 |
+
token=hf_token
|
| 24 |
+
)
|
| 25 |
+
# 強制使用 CPU (避免免費空間報錯)
|
| 26 |
+
device = torch.device("cpu")
|
| 27 |
model.to(device)
|
| 28 |
+
model.eval()
|
| 29 |
+
print("✅ 模型載入成功!")
|
| 30 |
except Exception as e:
|
| 31 |
+
print(f"❌ 模型載入失敗: {e}")
|
| 32 |
|
| 33 |
+
# --- 2. 定義圖像處理邏輯 (官方邏輯) ---
|
| 34 |
def process_image(input_image):
|
| 35 |
if input_image is None:
|
| 36 |
return None
|
| 37 |
|
| 38 |
+
# 準備圖像尺寸
|
| 39 |
+
image_size = (1024, 1024)
|
| 40 |
|
| 41 |
+
# 定義轉換
|
| 42 |
transform_image = transforms.Compose([
|
| 43 |
+
transforms.Resize(image_size),
|
| 44 |
transforms.ToTensor(),
|
| 45 |
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
|
| 46 |
])
|
| 47 |
|
| 48 |
+
# 轉換並增加維度
|
| 49 |
+
input_images = transform_image(input_image).unsqueeze(0).to(device)
|
| 50 |
|
| 51 |
+
# 開始預測
|
| 52 |
with torch.no_grad():
|
| 53 |
+
preds = model(input_images)[-1].sigmoid().cpu()
|
|
|
|
|
|
|
|
|
|
| 54 |
|
| 55 |
+
# 處理預測結果
|
| 56 |
+
pred = preds[0].squeeze()
|
| 57 |
|
| 58 |
+
# 轉回 PIL 圖片
|
| 59 |
+
pred_pil = transforms.ToPILImage()(pred)
|
| 60 |
+
|
| 61 |
+
# 調整回原始圖片的大小
|
| 62 |
+
mask = pred_pil.resize(input_image.size)
|
| 63 |
|
| 64 |
# 合成去背圖
|
| 65 |
+
image = input_image.convert("RGBA")
|
| 66 |
+
image.putalpha(mask)
|
| 67 |
|
| 68 |
+
return image
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
|
| 70 |
+
# --- 3. 建立介面 (移除導致錯誤的 head 參數) ---
|
| 71 |
+
with gr.Blocks(theme=gr.themes.Soft()) as app:
|
| 72 |
|
| 73 |
+
gr.Markdown("## ✂️ AI 自動去背 (RMBG 2.0)")
|
| 74 |
+
gr.Markdown("由於版本相容性,目前以標準網頁模式運行。")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
|
| 76 |
+
with gr.Column():
|
| 77 |
+
input_img = gr.Image(type="pil", label="上傳圖片", sources=["upload", "clipboard", "webcam"])
|
| 78 |
+
btn = gr.Button("✨ 開始去背", variant="primary", size="lg")
|
| 79 |
+
output_img = gr.Image(type="pil", label="去背結果", format="png", show_download_button=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
|
|
|
|
| 81 |
btn.click(fn=process_image, inputs=input_img, outputs=output_img)
|
| 82 |
|
|
|
|
| 83 |
if __name__ == "__main__":
|
| 84 |
app.launch()
|