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
| 4 |
+
import os
|
| 5 |
+
import gradio as gr
|
| 6 |
+
import gc
|
| 7 |
+
import zipfile
|
| 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"
|
| 16 |
+
ZIP_PATH = "output/results.zip"
|
| 17 |
+
TARGET_WIDTH, TARGET_HEIGHT = 2133, 1200
|
| 18 |
+
POS1 = (1032, 0)
|
| 19 |
+
POS2 = (4666, 0)
|
| 20 |
+
|
| 21 |
+
# 初始化資料夾與權限檢查
|
| 22 |
+
def check_write_permission(path):
|
| 23 |
+
if not os.path.exists(path):
|
| 24 |
+
try:
|
| 25 |
+
os.makedirs(path)
|
| 26 |
+
except Exception as e:
|
| 27 |
+
raise RuntimeError(f"❌ 無法建立目錄 '{path}':{e}")
|
| 28 |
+
elif not os.access(path, os.W_OK):
|
| 29 |
+
raise RuntimeError(f"❌ 目錄 '{path}' 存在,但沒有寫入權限!")
|
| 30 |
+
|
| 31 |
+
check_write_permission(FG_DIR)
|
| 32 |
+
check_write_permission(OUTPUT_DIR)
|
| 33 |
+
|
| 34 |
+
# PDF轉圖片(使用 PyMuPDF)
|
| 35 |
+
def pdf_to_images(pdf_file):
|
| 36 |
+
try:
|
| 37 |
+
image_paths = []
|
| 38 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp_pdf:
|
| 39 |
+
tmp_pdf.write(pdf_file.read())
|
| 40 |
+
tmp_pdf.flush()
|
| 41 |
+
doc = fitz.open(tmp_pdf.name)
|
| 42 |
+
|
| 43 |
+
for i, page in enumerate(doc, start=1):
|
| 44 |
+
pix = page.get_pixmap(matrix=fitz.Matrix(2, 2)) # 高解析度
|
| 45 |
+
img_path = os.path.join(FG_DIR, f"page_{i:03d}.jpg")
|
| 46 |
+
pix.save(img_path)
|
| 47 |
+
image_paths.append(img_path)
|
| 48 |
+
|
| 49 |
+
return image_paths
|
| 50 |
+
except Exception as e:
|
| 51 |
+
raise gr.Error(f"PDF轉換失敗: {str(e)}")
|
| 52 |
+
|
| 53 |
+
# 合成圖片
|
| 54 |
+
def overlay_image(bg, fg, x, y):
|
| 55 |
+
h, w = fg.shape[:2]
|
| 56 |
+
bh, bw = bg.shape[:2]
|
| 57 |
+
if x + w > bw or y + h > bh:
|
| 58 |
+
raise ValueError(f"前景圖超出背景邊界:({x},{y},{w},{h}) > 背景({bw},{bh})")
|
| 59 |
+
|
| 60 |
+
if fg.shape[2] == 4:
|
| 61 |
+
alpha = fg[:, :, 3:] / 255.0
|
| 62 |
+
bg[y:y+h, x:x+w] = alpha * fg[:, :, :3] + (1 - alpha) * bg[y:y+h, x:x+w]
|
| 63 |
+
else:
|
| 64 |
+
bg[y:y+h, x:x+w] = fg[:, :, :3]
|
| 65 |
+
return bg
|
| 66 |
+
|
| 67 |
+
# 壓縮成 zip
|
| 68 |
+
def zip_output_files():
|
| 69 |
+
with zipfile.ZipFile(ZIP_PATH, "w", zipfile.ZIP_DEFLATED) as zipf:
|
| 70 |
+
for file in sorted(os.listdir(OUTPUT_DIR)):
|
| 71 |
+
if file.endswith(".jpg"):
|
| 72 |
+
zipf.write(os.path.join(OUTPUT_DIR, file), arcname=file)
|
| 73 |
+
return ZIP_PATH
|
| 74 |
+
|
| 75 |
+
# 主流程
|
| 76 |
+
def process_pdf(pdf_file):
|
| 77 |
+
try:
|
| 78 |
+
progress = gr.Progress()
|
| 79 |
+
progress(0, desc="準備中...")
|
| 80 |
+
|
| 81 |
+
# 轉換PDF為圖片
|
| 82 |
+
progress(0.1, "正在轉換PDF頁面為圖片...")
|
| 83 |
+
image_paths = pdf_to_images(pdf_file)
|
| 84 |
+
|
| 85 |
+
if len(image_paths) == 0:
|
| 86 |
+
return [], None, "PDF轉換失敗,未產生任何圖片"
|
| 87 |
+
if len(image_paths) > MAX_PAGES:
|
| 88 |
+
raise gr.Error(f"PDF頁數過多,最多支援 {MAX_PAGES} 頁")
|
| 89 |
+
|
| 90 |
+
# 讀取背景圖
|
| 91 |
+
bg = cv2.imread(BG_PATH)
|
| 92 |
+
if bg is None:
|
| 93 |
+
raise gr.Error("無法讀取背景圖(請確認 background.jpg 是否存在)")
|
| 94 |
+
|
| 95 |
+
# 清除舊結果
|
| 96 |
+
for f in os.listdir(OUTPUT_DIR):
|
| 97 |
+
if f.endswith(".jpg"):
|
| 98 |
+
os.remove(os.path.join(OUTPUT_DIR, f))
|
| 99 |
+
|
| 100 |
+
results = []
|
| 101 |
+
for i, img_path in enumerate(image_paths, 1):
|
| 102 |
+
progress(i / len(image_paths), f"合成第 {i} 頁...")
|
| 103 |
+
|
| 104 |
+
try:
|
| 105 |
+
fg = cv2.imread(img_path, cv2.IMREAD_UNCHANGED)
|
| 106 |
+
if fg is None:
|
| 107 |
+
continue
|
| 108 |
+
|
| 109 |
+
fg = cv2.resize(fg, (TARGET_WIDTH, TARGET_HEIGHT), interpolation=cv2.INTER_AREA)
|
| 110 |
+
result = overlay_image(bg.copy(), fg, *POS1)
|
| 111 |
+
result = overlay_image(result, fg, *POS2)
|
| 112 |
+
|
| 113 |
+
output_path = f"{OUTPUT_DIR}/result_{i:03d}.jpg"
|
| 114 |
+
cv2.imwrite(output_path, result)
|
| 115 |
+
results.append((output_path, f"Page {i:03d}"))
|
| 116 |
+
|
| 117 |
+
if i % 10 == 0:
|
| 118 |
+
gc.collect()
|
| 119 |
+
|
| 120 |
+
except Exception as e:
|
| 121 |
+
print(f"處理第 {i} 頁失敗: {str(e)}")
|
| 122 |
+
continue
|
| 123 |
+
|
| 124 |
+
progress(1, "完成!")
|
| 125 |
+
zip_file = zip_output_files()
|
| 126 |
+
return results, zip_file, f"成功處理 {len(results)}/{len(image_paths)} 頁,已打包為 ZIP 可下載"
|
| 127 |
+
|
| 128 |
+
except Exception as e:
|
| 129 |
+
raise gr.Error(f"處理出錯:{str(e)}")
|
| 130 |
+
|
| 131 |
+
# Gradio 介面
|
| 132 |
+
with gr.Blocks() as demo:
|
| 133 |
+
gr.Markdown("## 📄 PDF頁面合成工具(背景固定為 7872x1200)")
|
| 134 |
+
|
| 135 |
+
pdf_upload = gr.File(label="上傳PDF文件", file_types=[".pdf"])
|
| 136 |
+
btn_run = gr.Button("開始合成", variant="primary")
|
| 137 |
+
|
| 138 |
+
with gr.Row():
|
| 139 |
+
gallery = gr.Gallery(label="合成結果預覽", columns=3, preview=True)
|
| 140 |
+
zip_download = gr.File(label="下載結果 ZIP 檔")
|
| 141 |
+
log_output = gr.Textbox(label="日誌", interactive=False)
|
| 142 |
+
|
| 143 |
+
btn_run.click(
|
| 144 |
+
fn=process_pdf,
|
| 145 |
+
inputs=pdf_upload,
|
| 146 |
+
outputs=[gallery, zip_download, log_output],
|
| 147 |
+
concurrency_limit=4
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
if __name__ == "__main__":
|
| 151 |
+
demo.launch()
|