Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,14 +2,13 @@ import cv2
|
|
| 2 |
import numpy as np
|
| 3 |
import os
|
| 4 |
import gradio as gr
|
| 5 |
-
import gc
|
| 6 |
import zipfile
|
|
|
|
|
|
|
| 7 |
from pdf2image import convert_from_path
|
| 8 |
from PIL import Image
|
| 9 |
-
import tempfile
|
| 10 |
|
| 11 |
-
#
|
| 12 |
-
MAX_PAGES = 250
|
| 13 |
BG_PATH = "background.jpg"
|
| 14 |
FG_DIR = "foregrounds"
|
| 15 |
OUTPUT_DIR = "output"
|
|
@@ -18,27 +17,36 @@ TARGET_WIDTH, TARGET_HEIGHT = 2133, 1200
|
|
| 18 |
POS1 = (1032, 0)
|
| 19 |
POS2 = (4666, 0)
|
| 20 |
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
def overlay_image(bg, fg, x, y):
|
| 43 |
h, w = fg.shape[:2]
|
| 44 |
if fg.shape[2] == 4:
|
|
@@ -48,81 +56,82 @@ def overlay_image(bg, fg, x, y):
|
|
| 48 |
bg[y:y+h, x:x+w] = fg[:, :, :3]
|
| 49 |
return bg
|
| 50 |
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
with zipfile.ZipFile(
|
| 54 |
-
for
|
| 55 |
-
if
|
| 56 |
-
|
| 57 |
-
return
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
|
|
|
|
|
|
| 67 |
os.remove(os.path.join(OUTPUT_DIR, f))
|
| 68 |
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
results
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
# Gradio UI (相容���版)
|
| 109 |
with gr.Blocks() as demo:
|
| 110 |
-
gr.Markdown("##
|
| 111 |
-
gr.Markdown("背景圖為固定的 `background.jpg`,前景可為 PDF 或圖片。")
|
| 112 |
-
|
| 113 |
-
files_input = gr.Files(label="📂 上傳 PDF 或圖片", file_types=[".pdf", ".jpg", ".png", ".jpeg"])
|
| 114 |
-
prefix_input = gr.Textbox(label="📎 自訂輸出檔案前綴", placeholder="例如 myproject_")
|
| 115 |
|
| 116 |
-
|
|
|
|
|
|
|
| 117 |
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
|
|
|
|
|
|
| 121 |
|
| 122 |
run_btn.click(
|
| 123 |
fn=process_inputs,
|
| 124 |
-
inputs=[
|
| 125 |
-
outputs=[gallery, zip_file,
|
|
|
|
| 126 |
)
|
| 127 |
|
| 128 |
if __name__ == "__main__":
|
|
|
|
| 2 |
import numpy as np
|
| 3 |
import os
|
| 4 |
import gradio as gr
|
|
|
|
| 5 |
import zipfile
|
| 6 |
+
import tempfile
|
| 7 |
+
import gc
|
| 8 |
from pdf2image import convert_from_path
|
| 9 |
from PIL import Image
|
|
|
|
| 10 |
|
| 11 |
+
# 設定常數與目錄
|
|
|
|
| 12 |
BG_PATH = "background.jpg"
|
| 13 |
FG_DIR = "foregrounds"
|
| 14 |
OUTPUT_DIR = "output"
|
|
|
|
| 17 |
POS1 = (1032, 0)
|
| 18 |
POS2 = (4666, 0)
|
| 19 |
|
| 20 |
+
# 確保目錄存在
|
| 21 |
+
for d in [FG_DIR, OUTPUT_DIR]:
|
| 22 |
+
os.makedirs(d, exist_ok=True)
|
| 23 |
+
|
| 24 |
+
# PDF 轉圖片
|
| 25 |
+
def pdf_to_images(pdf_file_path, prefix):
|
| 26 |
+
with open(pdf_file_path, "rb") as f:
|
| 27 |
+
with tempfile.NamedTemporaryFile(suffix=".pdf", delete=False) as tmp_pdf:
|
| 28 |
+
tmp_pdf.write(f.read())
|
| 29 |
+
tmp_pdf.flush()
|
| 30 |
+
images = convert_from_path(tmp_pdf.name, fmt='jpg')
|
| 31 |
+
|
| 32 |
+
paths = []
|
| 33 |
+
for i, img in enumerate(images, 1):
|
| 34 |
+
path = os.path.join(FG_DIR, f"{prefix}page_{i:03d}.jpg")
|
| 35 |
+
img.save(path, 'JPEG')
|
| 36 |
+
paths.append(path)
|
| 37 |
+
return paths
|
| 38 |
+
|
| 39 |
+
# 儲存上傳圖片
|
| 40 |
+
def save_uploaded_images(files, prefix):
|
| 41 |
+
paths = []
|
| 42 |
+
for i, file in enumerate(files, 1):
|
| 43 |
+
img = Image.open(file.name).convert("RGB")
|
| 44 |
+
path = os.path.join(FG_DIR, f"{prefix}img_{i:03d}.jpg")
|
| 45 |
+
img.save(path, "JPEG")
|
| 46 |
+
paths.append(path)
|
| 47 |
+
return paths
|
| 48 |
+
|
| 49 |
+
# 合成圖層
|
| 50 |
def overlay_image(bg, fg, x, y):
|
| 51 |
h, w = fg.shape[:2]
|
| 52 |
if fg.shape[2] == 4:
|
|
|
|
| 56 |
bg[y:y+h, x:x+w] = fg[:, :, :3]
|
| 57 |
return bg
|
| 58 |
|
| 59 |
+
# 壓縮輸出成 ZIP
|
| 60 |
+
def zip_output_files():
|
| 61 |
+
with zipfile.ZipFile(ZIP_PATH, "w", zipfile.ZIP_DEFLATED) as zipf:
|
| 62 |
+
for file in sorted(os.listdir(OUTPUT_DIR)):
|
| 63 |
+
if file.endswith(".jpg"):
|
| 64 |
+
zipf.write(os.path.join(OUTPUT_DIR, file), arcname=file)
|
| 65 |
+
return ZIP_PATH
|
| 66 |
+
|
| 67 |
+
# 主處理邏輯
|
| 68 |
+
def process_inputs(pdf_file, image_files, prefix):
|
| 69 |
+
try:
|
| 70 |
+
progress = gr.Progress()
|
| 71 |
+
fg_images = []
|
| 72 |
+
|
| 73 |
+
# 清除舊資料
|
| 74 |
+
for f in os.listdir(FG_DIR):
|
| 75 |
+
os.remove(os.path.join(FG_DIR, f))
|
| 76 |
+
for f in os.listdir(OUTPUT_DIR):
|
| 77 |
os.remove(os.path.join(OUTPUT_DIR, f))
|
| 78 |
|
| 79 |
+
# PDF
|
| 80 |
+
if pdf_file is not None:
|
| 81 |
+
progress(0.1, "轉換 PDF 為圖片...")
|
| 82 |
+
fg_images = pdf_to_images(pdf_file, prefix)
|
| 83 |
+
|
| 84 |
+
# 圖片
|
| 85 |
+
elif image_files is not None:
|
| 86 |
+
progress(0.1, "儲存上傳圖片...")
|
| 87 |
+
fg_images = save_uploaded_images(image_files, prefix)
|
| 88 |
+
|
| 89 |
+
else:
|
| 90 |
+
raise gr.Error("請上傳 PDF 或圖片!")
|
| 91 |
+
|
| 92 |
+
# 背景圖
|
| 93 |
+
bg = cv2.imread(BG_PATH)
|
| 94 |
+
if bg is None:
|
| 95 |
+
raise gr.Error("找不到背景圖 background.jpg")
|
| 96 |
+
|
| 97 |
+
results = []
|
| 98 |
+
for i, img_path in enumerate(fg_images, 1):
|
| 99 |
+
progress(0.2 + 0.7 * i / len(fg_images), f"合成第 {i} 張圖片...")
|
| 100 |
+
fg = cv2.imread(img_path, cv2.IMREAD_UNCHANGED)
|
| 101 |
+
fg = cv2.resize(fg, (TARGET_WIDTH, TARGET_HEIGHT))
|
| 102 |
+
result = overlay_image(bg.copy(), fg, *POS1)
|
| 103 |
+
result = overlay_image(result, fg, *POS2)
|
| 104 |
+
out_path = os.path.join(OUTPUT_DIR, f"{prefix}result_{i:03d}.jpg")
|
| 105 |
+
cv2.imwrite(out_path, result)
|
| 106 |
+
results.append((out_path, f"{prefix}{i:03d}"))
|
| 107 |
+
if i % 10 == 0:
|
| 108 |
+
gc.collect()
|
| 109 |
+
|
| 110 |
+
zip_file = zip_output_files()
|
| 111 |
+
return results, zip_file, f"✅ 成功處理 {len(results)} 張圖片,ZIP 可下載"
|
| 112 |
+
|
| 113 |
+
except Exception as e:
|
| 114 |
+
raise gr.Error(f"處理出錯:{str(e)}")
|
| 115 |
+
|
| 116 |
+
# Gradio UI
|
|
|
|
|
|
|
| 117 |
with gr.Blocks() as demo:
|
| 118 |
+
gr.Markdown("## 📄 PDF 或圖片合成工具(固定背景圖)")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
|
| 120 |
+
with gr.Row():
|
| 121 |
+
pdf_file = gr.File(label="上傳 PDF(選一)", file_types=[".pdf"])
|
| 122 |
+
image_files = gr.Files(label="或上傳圖片(JPG/PNG 多張)", file_types=[".jpg", ".png"])
|
| 123 |
|
| 124 |
+
prefix_input = gr.Textbox(label="自定義檔名前綴", value="results_")
|
| 125 |
+
run_btn = gr.Button("開始合成")
|
| 126 |
+
gallery = gr.Gallery(label="預覽", columns=3)
|
| 127 |
+
zip_file = gr.File(label="下載 ZIP")
|
| 128 |
+
log = gr.Textbox(label="處理日誌", interactive=False)
|
| 129 |
|
| 130 |
run_btn.click(
|
| 131 |
fn=process_inputs,
|
| 132 |
+
inputs=[pdf_file, image_files, prefix_input],
|
| 133 |
+
outputs=[gallery, zip_file, log],
|
| 134 |
+
concurrency_limit=2
|
| 135 |
)
|
| 136 |
|
| 137 |
if __name__ == "__main__":
|